@bigcommerce/checkout-sdk 1.817.0 → 1.818.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import{flatMap as e,map as t,noop as r,pick as i,values as n,without as s}from"lodash";import{fromEvent as o}from"rxjs";import{filter as a,map as d,switchMap as c,take as h}from"rxjs/operators";class u{constructor(e){const t=new Promise((e,t)=>{this.cancel=t});this.promise=Promise.race([e,t])}}class l extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}class p extends l{constructor(e){super(e||"Unable to proceed because the required element is unexpectedly detached from the page."),this.name="UnexpectedDetachmentError",this.type="unexpected_detachment"}}class m{constructor(e){this._mutationObserver=e}ensurePresence(e,t){return r=this,i=void 0,s=function*(){const r=new u(t),i=this._mutationObserver.create(t=>{t.forEach(t=>{0!==Array.from(t.removedNodes).filter(t=>e.some(e=>t===e||t.contains(e))).length&&r.cancel(new p)})});i.observe(document.body,{childList:!0,subtree:!0});try{const e=yield r.promise;return i.disconnect(),e}catch(e){throw i.disconnect(),e}},new((n=void 0)||(n=Promise))(function(e,t){function o(e){try{d(s.next(e))}catch(e){t(e)}}function a(e){try{d(s.throw(e))}catch(e){t(e)}}function d(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(e){e(r)})).then(o,a)}d((s=s.apply(r,i||[])).next())});var r,i,n,s}}class f{constructor(e=window){this._window=e}create(e){return new this._window.MutationObserver(e)}}class _ extends l{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}function y(e){if(!/^(https?:)?\/\//.test(e))throw new _("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const r=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}${r?`:${r}`:""}`,pathname:t.pathname,port:r,protocol:t.protocol,search:t.search}}function v(e,t){return e.type===t}class E{constructor(e,t,r){this._targetWindow=t,this._context=r,this._targetOrigin="*"===e?"*":y(e).origin}post(e,t){const r=this._targetWindow;if(window===r)return;if(!r)throw new Error("Unable to post message because target window is not set.");const i=t&&o(window,"message").pipe(a(e=>e.origin===this._targetOrigin&&v(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)),d(e=>{if(t.errorType===e.data.type)throw e.data;return e.data}),h(1)).toPromise();return r.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),i}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}function b(e,t,r){if("function"!=typeof r.value)return r;let i=r.value;return{get(){const e=i.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},r),{value:e})),e},set(e){i=e}}}class g{constructor(e){var t;this._sourceOrigins=[y(e).origin,(t=y(e),y(0===t.hostname.indexOf("www")?t.href:t.href.replace(t.hostname,`www.${t.hostname}`))).origin],this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))}addListener(e,t){let r=this._listeners[e];r||(this._listeners[e]=r=[]),-1===r.indexOf(t)&&r.push(t)}removeListener(e,t){const r=this._listeners[e];if(!r)return;const i=r.indexOf(t);i>=0&&r.splice(i,1)}trigger(e,t){const r=this._listeners[e.type];r&&r.forEach(r=>t?r(e,t):r(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!v(e.data,e.data.type))return;const t=e.data,{context:r}=t,i=function(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r}(t,["context"]);this.trigger(i,r)}}!function(e,t,r,i){var n,s=arguments.length,o=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,r,o):n(t,r))||o);s>3&&o&&Object.defineProperty(t,r,o)}([function(e,t,r){return t&&r?b(0,t,r):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(r=>{const i=Object.getOwnPropertyDescriptor(e.prototype,r);i&&"constructor"!==r&&Object.defineProperty(t.prototype,r,b(e.prototype,r,i))}),t}(e)}],g.prototype,"_handleMessage",null);const w={body:{},headers:{},status:0};class O extends l{constructor(e,{message:t,errors:r}={}){const{body:i,headers:n,status:s}=e||w;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=i,this.headers=n,this.status=s,this.errors=r||[]}}function S(e){if(Array.isArray(e))return e.reduce((e,t)=>t&&t.message?[...e,t.message]:e,[]).join(" ")}class T extends l{constructor(e){super(e||"Unable to proceed due to invalid configuration provided for the hosted payment form."),this.name="InvalidHostedFormConfigError",this.type="invalid_hosted_form_config"}}class F extends l{constructor(e){super(e||"Unable to proceed due to an unknown error with the hosted payment form."),this.name="InvalidHostedFormError",this.type="invalid_hosted_form"}}class D extends l{constructor(r){super(["Unable to proceed due to invalid user input values",...e(n(r),e=>t(e,({message:e})=>e))].join(". ")),this.errors=r,this.name="InvalidHostedFormValueError",this.type="invalid_hosted_form_value"}}var I,P;!function(e){e.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",e.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",e.SubmitManualOrderRequested="HOSTED_FIELD:SUBMIT_MANUAL_ORDER_REQUESTED",e.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED",e.StoredCardRequested="HOSTED_FIELD:STORED_CARD_REQUESTED"}(I||(I={})),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.SubmitManualOrderSucceeded="HOSTED_INPUT:SUBMIT_MANUAL_ORDER_SUCCEEDED",e.SubmitManualOrderFailed="HOSTED_INPUT:SUBMIT_MANUAL_ORDER_FAILED",e.Validated="HOSTED_INPUT:VALIDATED",e.StoredCardSucceeded="HOSTED_INPUT:STORED_CARD_SUCCEEDED",e.StoredCardFailed="HOSTED_INPUT:STORED_CARD_FAILED"}(P||(P={}));var C=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{d(i.next(e))}catch(e){s(e)}}function a(e){try{d(i.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}d((i=i.apply(e,t||[])).next())})};class L{constructor(e,t,r,i,n,s,o,a,d){this._type=e,this._containerId=t,this._placeholder=r,this._accessibilityLabel=i,this._styles=n,this._eventPoster=s,this._eventListener=o,this._detachmentObserver=a,this._orderId=d,this._iframe=document.createElement("iframe"),this._iframe.src=this.getFrameSrc(this._orderId),this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}getFrameSrc(e){return void 0!==e?`/admin/payments/${this._orderId}/hosted-form-field?version=1.817.0`:"/account/stored-instruments/hosted-fields?version=1.817.0"}getType(){return this._type}attach(){return C(this,void 0,void 0,function*(){const e=document.getElementById(this._containerId);if(!e)throw new T("Unable to proceed because the provided container ID is not valid.");e.appendChild(this._iframe),this._eventListener.listen();const t=o(this._iframe,"load").pipe(c(({target:e})=>C(this,void 0,void 0,function*(){const t=e&&e.contentWindow;if(!t)throw new Error("The content window of the iframe cannot be accessed.");this._eventPoster.setTarget(t),yield this._eventPoster.post({type:I.AttachRequested,payload:{accessibilityLabel:this._accessibilityLabel,fontUrls:this._getFontUrls(),placeholder:this._placeholder,styles:this._styles,origin:document.location.origin,type:this._type}},{successType:P.AttachSucceeded,errorType:P.AttachFailed})})),h(1)).toPromise();yield this._detachmentObserver.ensurePresence([this._iframe],t)})}detach(){this._iframe.parentElement&&(this._iframe.parentElement.removeChild(this._iframe),this._eventListener.stopListen())}submitForm(e,t){return C(this,void 0,void 0,function*(){try{const r=this._eventPoster.post({type:I.SubmitRequested,payload:{fields:e,data:t}},{successType:P.SubmitSucceeded,errorType:P.SubmitFailed});return yield this._detachmentObserver.ensurePresence([this._iframe],r)}catch(e){if(this._isSubmitErrorEvent(e)){if("hosted_form_error"===e.payload.error.code)throw new F(e.payload.error.message);if(e.payload.response)throw function(e){const{body:t}=e,{errors:r=[]}=t;return new O(e,{message:S(r)||void 0,errors:r})}(e.payload.response);throw new Error(e.payload.error.message)}throw e}})}submitManualOrderForm(e){return C(this,void 0,void 0,function*(){try{const t=this._eventPoster.post({type:I.SubmitManualOrderRequested,payload:{data:e}},{successType:P.SubmitManualOrderSucceeded,errorType:P.SubmitManualOrderFailed});return yield this._detachmentObserver.ensurePresence([this._iframe],t)}catch(e){if(this._isSubmitManualOrderErrorEvent(e)){if("hosted_form_error"===e.payload.error.code)throw new F(e.payload.error.message);if(e.payload.error.message)throw new Error(e.payload.error.message);throw new Error(e.payload.error.code)}throw e}})}submitStoredCardForm(e,t){return C(this,void 0,void 0,function*(){const r=this._eventPoster.post({type:I.StoredCardRequested,payload:{fields:e,data:t}},{successType:P.StoredCardSucceeded,errorType:P.StoredCardFailed});return this._detachmentObserver.ensurePresence([this._iframe],r)})}validateForm(){return C(this,void 0,void 0,function*(){const e=this._eventPoster.post({type:I.ValidateRequested},{successType:P.Validated}),{payload:t}=yield this._detachmentObserver.ensurePresence([this._iframe],e);if(!t.isValid)throw new D(t.errors)})}_getFontUrls(){const e="fonts.googleapis.com",t=document.querySelectorAll(`link[href*='${e}'][rel='stylesheet']`);return Array.prototype.slice.call(t).filter(t=>y(t.href).hostname===e).filter(e=>n(this._styles).map(e=>e&&e.fontFamily).filter(e=>"string"==typeof e).some(t=>t.split(/,\s/).some(t=>-1!==e.href.indexOf(t.replace(" ","+"))))).map(e=>e.href)}_isSubmitManualOrderErrorEvent(e){return e instanceof Object&&null!==e&&"type"in e&&e.type===P.SubmitManualOrderFailed}_isSubmitErrorEvent(e){return e.type===P.SubmitFailed}}var U,x=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{d(i.next(e))}catch(e){s(e)}}function a(e){try{d(i.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}d((i=i.apply(e,t||[])).next())})};class N{constructor(e,t,i){this._fields=e,this._eventListener=t,this._eventCallbacks=i,this._handleEnter=({payload:e})=>x(this,void 0,void 0,function*(){try{yield this.validate()}catch(e){if(e instanceof Error&&"InvalidHostedFormValueError"!==e.name)throw e}const{onEnter:t=r}=this._eventCallbacks;t(e)});const{onBlur:n=r,onCardTypeChange:s=r,onFocus:o=r,onValidate:a=r}=this._eventCallbacks;this._eventListener.addListener(P.Blurred,({payload:e})=>n(e)),this._eventListener.addListener(P.CardTypeChanged,({payload:e})=>s(e)),this._eventListener.addListener(P.Focused,({payload:e})=>o(e)),this._eventListener.addListener(P.Validated,({payload:e})=>a(e)),this._eventListener.addListener(P.Entered,this._handleEnter),this._eventListener.addListener(P.CardTypeChanged,({payload:e})=>this._cardType=e.cardType),this._eventListener.addListener(P.BinChanged,({payload:e})=>this._bin=e.bin)}getBin(){return this._bin}getCardType(){return this._cardType}attach(){return x(this,void 0,void 0,function*(){this._eventListener.listen();const e=this._getFirstField(),t=s(this._fields,e);yield e.attach(),yield Promise.all(t.map(e=>e.attach()))})}detach(){this._eventListener.stopListen(),this._fields.forEach(e=>{e.detach()})}submitManualOrderPayment(e){return x(this,void 0,void 0,function*(){return this._getFirstField().submitManualOrderForm(e.data)})}submitStoredCard(e){return x(this,void 0,void 0,function*(){return this._getFirstField().submitStoredCardForm(e.fields,e.data)})}submit(e,t,r,i){return x(this,void 0,void 0,function*(){try{return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),r.transform(e,i))}catch(i){let n;if(!(i instanceof Error||"string"==typeof i))throw new Error("Unexpected error type");return n=yield t.handlePaymentHumanVerification(i),yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),r.transform(e,n))}})}validate(){return x(this,void 0,void 0,function*(){return this._getFirstField().validateForm()})}_getFirstField(){const e=this._fields[0];if(!e)throw new T("Unable to proceed because the payment form has no field defined.");return e}}class A{create(e,t){const r=Object.keys(t.fields).reduce((r,i)=>{const n=t.fields[i];return n?[...r,new L(i,n.containerId,n.placeholder||"",n.accessibilityLabel||"",t.styles||{},new E(e),new g(e),new m(new f),t.orderId)]:r},[]);return new N(r,new g(e),i(t,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"))}}!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"}(U||(U={}));class R extends l{constructor(e){super(function(e){switch(e){case U.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case U.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case U.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case U.SpamProtectionNotInitialized:return"Unable to proceed because the checkout spam protection has not been initialized.";default:return"Unable to proceed because the required component has not been initialized."}}(e)),this.subtype=e,this.name="NotInitializedError",this.type="not_initialized"}}class H{constructor(e,t){this._host=e,this._hostedFormFactory=t}initialize(e){const t=this._hostedFormFactory.create(this._host,e);return t.attach().then(()=>{this._hostedForm=t})}deinitialize(){this._hostedForm&&(this._hostedForm.detach(),this._hostedForm=void 0)}submitManualOrderPayment(e){return t=this,r=void 0,n=function*(){const t=this._hostedForm;if(!t)throw new R(U.PaymentNotInitialized);return yield t.validate(),t.submitManualOrderPayment({data:e})},new((i=void 0)||(i=Promise))(function(e,s){function o(e){try{d(n.next(e))}catch(e){s(e)}}function a(e){try{d(n.throw(e))}catch(e){s(e)}}function d(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i(function(e){e(r)})).then(o,a)}d((n=n.apply(t,r||[])).next())});var t,r,i,n}}function M(e){return new H(e,new A)}class z{constructor(e,t){this._host=e,this._hostedFormFactory=t}submitStoredCard(e,t){return r=this,i=void 0,s=function*(){const r=this._hostedForm;if(!r)throw new R(U.PaymentNotInitialized);yield r.validate().then(()=>r.submitStoredCard({fields:e,data:t}))},new((n=void 0)||(n=Promise))(function(e,t){function o(e){try{d(s.next(e))}catch(e){t(e)}}function a(e){try{d(s.throw(e))}catch(e){t(e)}}function d(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(e){e(r)})).then(o,a)}d((s=s.apply(r,i||[])).next())});var r,i,n,s}initialize(e){const t=this._hostedFormFactory.create(this._host,e);return t.attach().then(()=>{this._hostedForm=t})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}function j(e){return new z(e,new A)}export{M as createHostedFormService,j as createStoredCardHostedFormService};
1
+ import{flatMap as e,map as t,noop as r,pick as i,values as n,without as s}from"lodash";import{fromEvent as o}from"rxjs";import{filter as a,map as d,switchMap as c,take as h}from"rxjs/operators";class u{constructor(e){const t=new Promise((e,t)=>{this.cancel=t});this.promise=Promise.race([e,t])}}class l extends Error{constructor(e){var t;super(e||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",t=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}class p extends l{constructor(e){super(e||"Unable to proceed because the required element is unexpectedly detached from the page."),this.name="UnexpectedDetachmentError",this.type="unexpected_detachment"}}class m{constructor(e){this._mutationObserver=e}ensurePresence(e,t){return r=this,i=void 0,s=function*(){const r=new u(t),i=this._mutationObserver.create(t=>{t.forEach(t=>{0!==Array.from(t.removedNodes).filter(t=>e.some(e=>t===e||t.contains(e))).length&&r.cancel(new p)})});i.observe(document.body,{childList:!0,subtree:!0});try{const e=yield r.promise;return i.disconnect(),e}catch(e){throw i.disconnect(),e}},new((n=void 0)||(n=Promise))(function(e,t){function o(e){try{d(s.next(e))}catch(e){t(e)}}function a(e){try{d(s.throw(e))}catch(e){t(e)}}function d(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(e){e(r)})).then(o,a)}d((s=s.apply(r,i||[])).next())});var r,i,n,s}}class f{constructor(e=window){this._window=e}create(e){return new this._window.MutationObserver(e)}}class _ extends l{constructor(e){super(e||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}function y(e){if(!/^(https?:)?\/\//.test(e))throw new _("The provided URL must be absolute.");const t=document.createElement("a");t.href=e;const r=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}${r?`:${r}`:""}`,pathname:t.pathname,port:r,protocol:t.protocol,search:t.search}}function v(e,t){return e.type===t}class E{constructor(e,t,r){this._targetWindow=t,this._context=r,this._targetOrigin="*"===e?"*":y(e).origin}post(e,t){const r=this._targetWindow;if(window===r)return;if(!r)throw new Error("Unable to post message because target window is not set.");const i=t&&o(window,"message").pipe(a(e=>e.origin===this._targetOrigin&&v(e.data,e.data.type)&&-1!==[t.successType,t.errorType].indexOf(e.data.type)),d(e=>{if(t.errorType===e.data.type)throw e.data;return e.data}),h(1)).toPromise();return r.postMessage(Object.assign(Object.assign({},e),{context:this._context}),this._targetOrigin),i}setTarget(e){this._targetWindow=e}setContext(e){this._context=e}}function b(e,t,r){if("function"!=typeof r.value)return r;let i=r.value;return{get(){const e=i.bind(this);return Object.defineProperty(this,t,Object.assign(Object.assign({},r),{value:e})),e},set(e){i=e}}}class g{constructor(e){var t;this._sourceOrigins=[y(e).origin,(t=y(e),y(0===t.hostname.indexOf("www")?t.href:t.href.replace(t.hostname,`www.${t.hostname}`))).origin],this._isListening=!1,this._listeners={}}listen(){this._isListening||(this._isListening=!0,window.addEventListener("message",this._handleMessage))}stopListen(){this._isListening&&(this._isListening=!1,window.removeEventListener("message",this._handleMessage))}addListener(e,t){let r=this._listeners[e];r||(this._listeners[e]=r=[]),-1===r.indexOf(t)&&r.push(t)}removeListener(e,t){const r=this._listeners[e];if(!r)return;const i=r.indexOf(t);i>=0&&r.splice(i,1)}trigger(e,t){const r=this._listeners[e.type];r&&r.forEach(r=>t?r(e,t):r(e))}_handleMessage(e){if(-1===this._sourceOrigins.indexOf(e.origin)||!v(e.data,e.data.type))return;const t=e.data,{context:r}=t,i=function(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(r[i[n]]=e[i[n]])}return r}(t,["context"]);this.trigger(i,r)}}!function(e,t,r,i){var n,s=arguments.length,o=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,r):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,r,i);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(o=(s<3?n(o):s>3?n(t,r,o):n(t,r))||o);s>3&&o&&Object.defineProperty(t,r,o)}([function(e,t,r){return t&&r?b(0,t,r):function(e){const t=class extends e{};return Object.getOwnPropertyNames(e.prototype).forEach(r=>{const i=Object.getOwnPropertyDescriptor(e.prototype,r);i&&"constructor"!==r&&Object.defineProperty(t.prototype,r,b(e.prototype,r,i))}),t}(e)}],g.prototype,"_handleMessage",null);const w={body:{},headers:{},status:0};class O extends l{constructor(e,{message:t,errors:r}={}){const{body:i,headers:n,status:s}=e||w;super(t||"An unexpected error has occurred."),this.name="RequestError",this.type="request",this.body=i,this.headers=n,this.status=s,this.errors=r||[]}}function S(e){if(Array.isArray(e))return e.reduce((e,t)=>t&&t.message?[...e,t.message]:e,[]).join(" ")}class T extends l{constructor(e){super(e||"Unable to proceed due to invalid configuration provided for the hosted payment form."),this.name="InvalidHostedFormConfigError",this.type="invalid_hosted_form_config"}}class F extends l{constructor(e){super(e||"Unable to proceed due to an unknown error with the hosted payment form."),this.name="InvalidHostedFormError",this.type="invalid_hosted_form"}}class D extends l{constructor(r){super(["Unable to proceed due to invalid user input values",...e(n(r),e=>t(e,({message:e})=>e))].join(". ")),this.errors=r,this.name="InvalidHostedFormValueError",this.type="invalid_hosted_form_value"}}var I,P;!function(e){e.AttachRequested="HOSTED_FIELD:ATTACH_REQUESTED",e.SubmitRequested="HOSTED_FIELD:SUBMITTED_REQUESTED",e.SubmitManualOrderRequested="HOSTED_FIELD:SUBMIT_MANUAL_ORDER_REQUESTED",e.ValidateRequested="HOSTED_FIELD:VALIDATE_REQUESTED",e.StoredCardRequested="HOSTED_FIELD:STORED_CARD_REQUESTED"}(I||(I={})),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.SubmitManualOrderSucceeded="HOSTED_INPUT:SUBMIT_MANUAL_ORDER_SUCCEEDED",e.SubmitManualOrderFailed="HOSTED_INPUT:SUBMIT_MANUAL_ORDER_FAILED",e.Validated="HOSTED_INPUT:VALIDATED",e.StoredCardSucceeded="HOSTED_INPUT:STORED_CARD_SUCCEEDED",e.StoredCardFailed="HOSTED_INPUT:STORED_CARD_FAILED"}(P||(P={}));var C=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{d(i.next(e))}catch(e){s(e)}}function a(e){try{d(i.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}d((i=i.apply(e,t||[])).next())})};class L{constructor(e,t,r,i,n,s,o,a,d){this._type=e,this._containerId=t,this._placeholder=r,this._accessibilityLabel=i,this._styles=n,this._eventPoster=s,this._eventListener=o,this._detachmentObserver=a,this._orderId=d,this._iframe=document.createElement("iframe"),this._iframe.src=this.getFrameSrc(this._orderId),this._iframe.style.border="none",this._iframe.style.height="100%",this._iframe.style.overflow="hidden",this._iframe.style.width="100%"}getFrameSrc(e){return void 0!==e?`/admin/payments/${this._orderId}/hosted-form-field?version=1.818.0`:"/account/stored-instruments/hosted-fields?version=1.818.0"}getType(){return this._type}attach(){return C(this,void 0,void 0,function*(){const e=document.getElementById(this._containerId);if(!e)throw new T("Unable to proceed because the provided container ID is not valid.");e.appendChild(this._iframe),this._eventListener.listen();const t=o(this._iframe,"load").pipe(c(({target:e})=>C(this,void 0,void 0,function*(){const t=e&&e.contentWindow;if(!t)throw new Error("The content window of the iframe cannot be accessed.");this._eventPoster.setTarget(t),yield this._eventPoster.post({type:I.AttachRequested,payload:{accessibilityLabel:this._accessibilityLabel,fontUrls:this._getFontUrls(),placeholder:this._placeholder,styles:this._styles,origin:document.location.origin,type:this._type}},{successType:P.AttachSucceeded,errorType:P.AttachFailed})})),h(1)).toPromise();yield this._detachmentObserver.ensurePresence([this._iframe],t)})}detach(){this._iframe.parentElement&&(this._iframe.parentElement.removeChild(this._iframe),this._eventListener.stopListen())}submitForm(e,t){return C(this,void 0,void 0,function*(){try{const r=this._eventPoster.post({type:I.SubmitRequested,payload:{fields:e,data:t}},{successType:P.SubmitSucceeded,errorType:P.SubmitFailed});return yield this._detachmentObserver.ensurePresence([this._iframe],r)}catch(e){if(this._isSubmitErrorEvent(e)){if("hosted_form_error"===e.payload.error.code)throw new F(e.payload.error.message);if(e.payload.response)throw function(e){const{body:t}=e,{errors:r=[]}=t;return new O(e,{message:S(r)||void 0,errors:r})}(e.payload.response);throw new Error(e.payload.error.message)}throw e}})}submitManualOrderForm(e){return C(this,void 0,void 0,function*(){try{const t=this._eventPoster.post({type:I.SubmitManualOrderRequested,payload:{data:e}},{successType:P.SubmitManualOrderSucceeded,errorType:P.SubmitManualOrderFailed});return yield this._detachmentObserver.ensurePresence([this._iframe],t)}catch(e){if(this._isSubmitManualOrderErrorEvent(e)){if("hosted_form_error"===e.payload.error.code)throw new F(e.payload.error.message);if(e.payload.error.message)throw new Error(e.payload.error.message);throw new Error(e.payload.error.code)}throw e}})}submitStoredCardForm(e,t){return C(this,void 0,void 0,function*(){const r=this._eventPoster.post({type:I.StoredCardRequested,payload:{fields:e,data:t}},{successType:P.StoredCardSucceeded,errorType:P.StoredCardFailed});return this._detachmentObserver.ensurePresence([this._iframe],r)})}validateForm(){return C(this,void 0,void 0,function*(){const e=this._eventPoster.post({type:I.ValidateRequested},{successType:P.Validated}),{payload:t}=yield this._detachmentObserver.ensurePresence([this._iframe],e);if(!t.isValid)throw new D(t.errors)})}_getFontUrls(){const e="fonts.googleapis.com",t=document.querySelectorAll(`link[href*='${e}'][rel='stylesheet']`);return Array.prototype.slice.call(t).filter(t=>y(t.href).hostname===e).filter(e=>n(this._styles).map(e=>e&&e.fontFamily).filter(e=>"string"==typeof e).some(t=>t.split(/,\s/).some(t=>-1!==e.href.indexOf(t.replace(" ","+"))))).map(e=>e.href)}_isSubmitManualOrderErrorEvent(e){return e instanceof Object&&null!==e&&"type"in e&&e.type===P.SubmitManualOrderFailed}_isSubmitErrorEvent(e){return e.type===P.SubmitFailed}}var U,x=function(e,t,r,i){return new(r||(r=Promise))(function(n,s){function o(e){try{d(i.next(e))}catch(e){s(e)}}function a(e){try{d(i.throw(e))}catch(e){s(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}d((i=i.apply(e,t||[])).next())})};class N{constructor(e,t,i){this._fields=e,this._eventListener=t,this._eventCallbacks=i,this._handleEnter=({payload:e})=>x(this,void 0,void 0,function*(){try{yield this.validate()}catch(e){if(e instanceof Error&&"InvalidHostedFormValueError"!==e.name)throw e}const{onEnter:t=r}=this._eventCallbacks;t(e)});const{onBlur:n=r,onCardTypeChange:s=r,onFocus:o=r,onValidate:a=r}=this._eventCallbacks;this._eventListener.addListener(P.Blurred,({payload:e})=>n(e)),this._eventListener.addListener(P.CardTypeChanged,({payload:e})=>s(e)),this._eventListener.addListener(P.Focused,({payload:e})=>o(e)),this._eventListener.addListener(P.Validated,({payload:e})=>a(e)),this._eventListener.addListener(P.Entered,this._handleEnter),this._eventListener.addListener(P.CardTypeChanged,({payload:e})=>this._cardType=e.cardType),this._eventListener.addListener(P.BinChanged,({payload:e})=>this._bin=e.bin)}getBin(){return this._bin}getCardType(){return this._cardType}attach(){return x(this,void 0,void 0,function*(){this._eventListener.listen();const e=this._getFirstField(),t=s(this._fields,e);yield e.attach(),yield Promise.all(t.map(e=>e.attach()))})}detach(){this._eventListener.stopListen(),this._fields.forEach(e=>{e.detach()})}submitManualOrderPayment(e){return x(this,void 0,void 0,function*(){return this._getFirstField().submitManualOrderForm(e.data)})}submitStoredCard(e){return x(this,void 0,void 0,function*(){return this._getFirstField().submitStoredCardForm(e.fields,e.data)})}submit(e,t,r,i){return x(this,void 0,void 0,function*(){try{return yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),r.transform(e,i))}catch(i){let n;if(!(i instanceof Error||"string"==typeof i))throw new Error("Unexpected error type");return n=yield t.handlePaymentHumanVerification(i),yield this._getFirstField().submitForm(this._fields.map(e=>e.getType()),r.transform(e,n))}})}validate(){return x(this,void 0,void 0,function*(){return this._getFirstField().validateForm()})}_getFirstField(){const e=this._fields[0];if(!e)throw new T("Unable to proceed because the payment form has no field defined.");return e}}class A{create(e,t){const r=Object.keys(t.fields).reduce((r,i)=>{const n=t.fields[i];return n?[...r,new L(i,n.containerId,n.placeholder||"",n.accessibilityLabel||"",t.styles||{},new E(e),new g(e),new m(new f),t.orderId)]:r},[]);return new N(r,new g(e),i(t,"onBlur","onEnter","onFocus","onCardTypeChange","onValidate"))}}!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"}(U||(U={}));class R extends l{constructor(e){super(function(e){switch(e){case U.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case U.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case U.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case U.SpamProtectionNotInitialized:return"Unable to proceed because the checkout spam protection has not been initialized.";default:return"Unable to proceed because the required component has not been initialized."}}(e)),this.subtype=e,this.name="NotInitializedError",this.type="not_initialized"}}class H{constructor(e,t){this._host=e,this._hostedFormFactory=t}initialize(e){const t=this._hostedFormFactory.create(this._host,e);return t.attach().then(()=>{this._hostedForm=t})}deinitialize(){this._hostedForm&&(this._hostedForm.detach(),this._hostedForm=void 0)}submitManualOrderPayment(e){return t=this,r=void 0,n=function*(){const t=this._hostedForm;if(!t)throw new R(U.PaymentNotInitialized);return yield t.validate(),t.submitManualOrderPayment({data:e})},new((i=void 0)||(i=Promise))(function(e,s){function o(e){try{d(n.next(e))}catch(e){s(e)}}function a(e){try{d(n.throw(e))}catch(e){s(e)}}function d(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i(function(e){e(r)})).then(o,a)}d((n=n.apply(t,r||[])).next())});var t,r,i,n}}function M(e){return new H(e,new A)}class z{constructor(e,t){this._host=e,this._hostedFormFactory=t}submitStoredCard(e,t){return r=this,i=void 0,s=function*(){const r=this._hostedForm;if(!r)throw new R(U.PaymentNotInitialized);yield r.validate().then(()=>r.submitStoredCard({fields:e,data:t}))},new((n=void 0)||(n=Promise))(function(e,t){function o(e){try{d(s.next(e))}catch(e){t(e)}}function a(e){try{d(s.throw(e))}catch(e){t(e)}}function d(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(e){e(r)})).then(o,a)}d((s=s.apply(r,i||[])).next())});var r,i,n,s}initialize(e){const t=this._hostedFormFactory.create(this._host,e);return t.attach().then(()=>{this._hostedForm=t})}deinitialize(){this._hostedForm&&this._hostedForm.detach()}}function j(e){return new z(e,new A)}export{M as createHostedFormService,j as createStoredCardHostedFormService};
2
2
  //# sourceMappingURL=hosted-form-v2-iframe-host.js.map
@@ -1,2 +1,2 @@
1
- import{getScriptLoader as t}from"@bigcommerce/script-loader";import{noop as e,reduce as n}from"lodash";import{createRequestSender as i}from"@bigcommerce/request-sender";var o,a;class r extends Error{constructor(t){var e;super(t||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",e=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,e):this.__proto__=e,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}!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"}(o||(o={}));class s extends r{constructor(t){super(function(t){switch(t){case o.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case o.MissingCart:return"Unable to proceed because cart data is unavailable.";case o.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case o.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case o.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case o.MissingCheckoutConfig:case o.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case o.MissingOrder:return"Unable to proceed because order data is unavailable.";case o.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case o.MissingPayment:return"Unable to proceed because payment data is unavailable.";case o.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case o.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case o.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(t)),this.subtype=t,this.name="MissingDataError",this.type="missing_data"}}function c(t){return e=t.lineItems.physicalItems.filter(t=>!t.addedByPromotion),n(e,(t,e)=>t+e.quantity,0);var e}function u(t,e){if(null==t)throw e?e():new Error("An unexpected error has occurred.");return t}!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"}(a||(a={}));class d extends r{constructor(t){super(function(t){switch(t){case a.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case a.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case a.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case a.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.subtype=t,this.name="NotInitializedError",this.type="not_initialized"}}const h={de:"eu",jp:"fe",uk:"eu",us:"na"};var l,y,m,p,g,P;!function(t){t.en_US="en_US",t.en_GB="en_GB",t.de_DE="de_DE",t.fr_FR="fr_FR",t.it_IT="it_IT",t.es_ES="es_ES",t.ja_JP="ja_JP"}(l||(l={})),function(t){t.Home="Home",t.Product="Product",t.Cart="Cart",t.Checkout="Checkout",t.Other="Other"}(y||(y={})),function(t){t.USD="USD",t.EUR="EUR",t.GBP="GBP",t.JPY="JPY"}(m||(m={})),function(t){t.PayAndShip="PayAndShip",t.PayOnly="PayOnly"}(p||(p={})),function(t){t.Gold="Gold",t.LightGray="LightGray",t.DarkGray="DarkGray"}(g||(g={})),function(t){t.C0001="C0001"}(P||(P={}));var f=function(t,e,n,i){return new(n||(n=Promise))(function(o,a){function r(t){try{c(i.next(t))}catch(t){a(t)}}function s(t){try{c(i.throw(t))}catch(t){a(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,s)}c((i=i.apply(t,e||[])).next())})};class b{constructor(t){this.amazonPayV2ScriptLoader=t}initialize(t){return f(this,void 0,void 0,function*(){this.amazonPayV2SDK=yield this.amazonPayV2ScriptLoader.load(t),this.buttonParentContainer=this.buttonParentContainer||this.createAmazonPayButtonParentContainer()})}deinitialize(){var t;return this.amazonPayV2Button=void 0,null===(t=this.buttonParentContainer)||void 0===t||t.remove(),this.buttonParentContainer=void 0,this.amazonPayV2SDK=void 0,Promise.resolve()}bindButton(t,e,n){this.getAmazonPayV2SDK().Pay.bindChangeAction(`#${t}`,{amazonCheckoutSessionId:e,changeAction:n})}createButton(t,e){this.amazonPayV2Button=this.getAmazonPayV2SDK().Pay.renderButton(`#${t}`,e)}prepareCheckout(t){const e=this.prepareRequestConfig(t);this.getAmazonPayV2Button().onClick(()=>{this.getAmazonPayV2Button().initCheckout(e)})}prepareCheckoutWithCreationRequestConfig(t){this.getAmazonPayV2Button().onClick(()=>f(this,void 0,void 0,function*(){const e=yield t();if(e){const t=this.prepareRequestConfig(e.createCheckoutSessionConfig,e.estimatedOrderAmount,e.productType);this.getAmazonPayV2Button().initCheckout(t)}}))}signout(){return f(this,void 0,void 0,function*(){return this.amazonPayV2SDK&&this.amazonPayV2SDK.Pay.signout(),Promise.resolve()})}renderAmazonPayButton({buttonColor:t,checkoutState:e,containerId:n,decoupleCheckoutInitiation:i=!1,methodId:o,options:a,placement:r,isButtonMicroTextDisabled:s=!1}){const c=document.querySelector(`#${n}`);if(!c)return;const{id:u}=c.appendChild(this.getButtonParentContainer());a&&s&&(a.design=P.C0001);const d=null!=a?a:this.getAmazonPayV2ButtonOptions(e,o,r,i,t);return this.createButton(u,d),this.getButtonParentContainer()}updateBuyNowFlowFlag(t){this.isBuyNowFlow=Boolean(t)}isPh4Enabled(t,e){const n=!!t["PROJECT-3483.amazon_pay_ph4"],i=!!t["INT-6885.amazon_pay_ph4_us_only"];return n&&i?"US"===e:n}prepareRequestConfig(t,e,n){const{publicKeyId:i}=t,o=function(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(t);o<i.length;o++)e.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(t,i[o])&&(n[i[o]]=t[i[o]])}return n}(t,["publicKeyId"]);return Object.assign(Object.assign({createCheckoutSessionConfig:this.isEnvironmentSpecific(i)?o:t},e&&{estimatedOrderAmount:e}),n&&{productType:n})}createAmazonPayButtonParentContainer(){const t=Math.random().toString(16).substr(-4),e=document.createElement("div");return e.id=`amazonpay_button_parent_container_${t}`,e}getAmazonPayV2ButtonOptions(t,e,n,i=!1,a=g.Gold){var r;const{getCart:u,getCheckout:d,getStoreConfigOrThrow:h,getPaymentMethodOrThrow:l}=this.getCheckoutState(t),{config:{merchantId:y,testMode:m},initializationData:f}=l(e);if(!f)throw new s(o.MissingPaymentMethod);const{checkoutLanguage:b,checkoutSessionMethod:v,createCheckoutSessionConfig:C,extractAmazonCheckoutSessionId:z,ledgerCurrency:w,publicKeyId:S="",isButtonMicroTextDisabled:I}=f;if(!y||!w)throw new s(o.MissingPaymentMethod);const _=Object.assign({merchantId:y,ledgerCurrency:w,checkoutLanguage:b,placement:n,buttonColor:a},I?{design:P.C0001}:{});if(this.isBuyNowFlow)return Object.assign(Object.assign({},_),{sandbox:!!m});const O=u();_.productType=O&&0===c(O)?p.PayOnly:p.PayAndShip;const{checkoutSettings:{features:k},storeProfile:{shopPath:M,storeCountryCode:B}}=h();if(this.isPh4Enabled(k,B)){if(!C)throw new s(o.MissingPaymentMethod);const t=null===(r=d())||void 0===r?void 0:r.outstandingBalance.toString(),e=null==O?void 0:O.currency.code,n=Object.assign({},_);let a;return this.isEnvironmentSpecific(S)?(n.publicKeyId=S,a=C):(n.sandbox=!!m,a=Object.assign(Object.assign({},C),{publicKeyId:S})),i||(n.createCheckoutSessionConfig=a),t&&e&&(n.estimatedOrderAmount={amount:t,currencyCode:e}),n}const A={method:v,url:`${M}/remote-checkout/${e}/payment-session`,extractAmazonCheckoutSessionId:z};return Object.assign(Object.assign({},_),{createCheckoutSession:A,sandbox:!!m})}isEnvironmentSpecific(t){return/^(SANDBOX|LIVE)/.test(t)}getAmazonPayV2SDK(){return this.getOrThrow(this.amazonPayV2SDK)}getButtonParentContainer(){return this.getOrThrow(this.buttonParentContainer)}getAmazonPayV2Button(){return this.getOrThrow(this.amazonPayV2Button)}getOrThrow(t){return u(t,()=>new d(a.PaymentNotInitialized))}getCheckoutState(t){return"object"==typeof(e=t)&&null!==e&&"cart"in e&&"checkout"in e&&"config"in e&&"paymentMethods"in e?{getCart:t.cart.getCart,getCheckout:t.checkout.getCheckout,getStoreConfigOrThrow:t.config.getStoreConfigOrThrow,getPaymentMethodOrThrow:e=>t.paymentMethods.getPaymentMethodOrThrow(e)}:t;var e}}class v extends r{constructor(t){super(t||"Unable to proceed because the client library of a payment method is not loaded or ready to be used."),this.name="PaymentMethodClientUnavailableError",this.type="payment_method_client_unavailable"}}class C{constructor(t,e=window){this.scriptLoader=t,this.windowWithAmazonPay=e}load(t){return e=this,n=void 0,o=function*(){const{initializationData:e}=t,n=(null==e?void 0:e.region)||"us",i=h[n];if(yield this.scriptLoader.loadScript(`https://static-${i}.payments-amazon.com/checkout.js`),!this.windowWithAmazonPay.amazon)throw new v;return this.windowWithAmazonPay.amazon},new((i=void 0)||(i=Promise))(function(t,a){function r(t){try{c(o.next(t))}catch(t){a(t)}}function s(t){try{c(o.throw(t))}catch(t){a(t)}}function c(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i(function(t){t(n)})).then(r,s)}c((o=o.apply(e,n||[])).next())});var e,n,i,o}}function z(){return new b(new C(t()))}function w(t,e){return Object.assign(t,{resolveIds:e})}class S extends r{constructor(t){super(t||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class I extends S{constructor(t){let e="Unable to submit payment for the order because the payload is invalid.";t&&(e=`${e} Make sure the following fields are provided correctly: ${t.join(", ")}.`),super(e),this.name="PaymentArgumentInvalidError"}}class _ extends r{constructor(t){super(t||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}class O extends r{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}var k=function(t,e,n,i){return new(n||(n=Promise))(function(o,a){function r(t){try{c(i.next(t))}catch(t){a(t)}}function s(t){try{c(i.throw(t))}catch(t){a(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,s)}c((i=i.apply(t,e||[])).next())})};class M{constructor(t,e){this.paymentIntegrationService=t,this.amazonPayV2PaymentProcessor=e}initialize(t){return k(this,void 0,void 0,function*(){const{methodId:e,amazonpay:n}=t;if(!e)throw new S('Unable to proceed because "methodId" argument is not provided.');const i=this.paymentIntegrationService.getState(),{features:o}=i.getStoreConfigOrThrow().checkoutSettings,a=i.getPaymentMethodOrThrow(e),r=a.initializationData||{},{paymentToken:s="",region:c="",isButtonMicroTextDisabled:u}=r;if(yield this.amazonPayV2PaymentProcessor.initialize(a),this._isReadyToPay(s))(null==n?void 0:n.editButtonId)&&this._bindEditButton(n.editButtonId,s,"changePayment",this._isModalFlow(c));else{const{id:t}=this._createContainer();if(this._amazonPayButton=this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:i,containerId:t,decoupleCheckoutInitiation:this._isOneTimeTransaction(o,c.toUpperCase()),methodId:e,placement:y.Checkout,isButtonMicroTextDisabled:u}),!this._amazonPayButton)throw new S("Unable to render the Amazon Pay button to an invalid HTML container element.")}})}execute(t,n){return k(this,void 0,void 0,function*(){const{payment:i}=t;if(!i)throw new I(["payment"]);const{methodId:o}=i,a=this.paymentIntegrationService.getState(),{features:r}=a.getStoreConfigOrThrow().checkoutSettings,s=a.getPaymentMethodOrThrow(o).initializationData||{},{paymentToken:c="",region:u=""}=s;if(this._isReadyToPay(c)||this._isOneTimeTransaction(r,u.toUpperCase())){const e={methodId:o,paymentData:{nonce:c||"apb"}};yield this.paymentIntegrationService.submitOrder(t,n);try{return void(yield this.paymentIntegrationService.submitPayment(e))}catch(t){if(!((t=>"object"==typeof t&&null!==t&&"body"in t)(t)&&(d=t.body,"object"==typeof d&&null!==d&&"status"in d&&"additional_action_required"in d&&"additional_action_required"===d.status&&"data"in d.additional_action_required&&"redirect_url"in d.additional_action_required.data&&"string"==typeof d.additional_action_required.data.redirect_url)))throw t;const{additional_action_required:e}=t.body,{redirect_url:n}=e.data;if(c)return new Promise(()=>window.location.assign(n));this.amazonPayV2PaymentProcessor.prepareCheckout(JSON.parse(n))}}var d;return this._getAmazonPayButton().click(),this._isModalFlow(u)?new Promise((t,e)=>{const n=()=>{window.removeEventListener("focus",n),e(new _("Shopper needs to login to Amazonpay to continue"))};window.addEventListener("focus",n)}):new Promise(e)})}finalize(){return Promise.reject(new O)}deinitialize(){return k(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize(),this._amazonPayButton=void 0})}_bindEditButton(t,e,n,i){const o=document.getElementById(t);if(o&&o.parentNode){if(!i){const t=o.cloneNode(!0);o.parentNode.replaceChild(t,o),t.addEventListener("click",()=>{this._showLoadingSpinner()})}this.amazonPayV2PaymentProcessor.bindButton(t,e,n)}}_isModalFlow(t){return"us"===t}_showLoadingSpinner(){return k(this,void 0,void 0,function*(){yield this.paymentIntegrationService.widgetInteraction(()=>new Promise(e))})}_createContainer(){let t=document.getElementById("AmazonPayButton");return t||(t=document.createElement("div"),t.id="AmazonPayButton",t.style.display="none",document.body.appendChild(t))}_getAmazonPayButton(){return u(this._amazonPayButton,()=>new d(a.PaymentNotInitialized))}_isOneTimeTransaction(t,e){return this.amazonPayV2PaymentProcessor.isPh4Enabled(t,e)&&t["INT-6399.amazon_pay_apb"]}_isReadyToPay(t){return!!t}}const B=w(t=>new M(t,z()),[{id:"amazonpay"}]);class A extends r{constructor(t){super(t||"Not implemented."),this.name="NotImplementedError",this.type="not_implemented"}}var T=function(t,e,n,i){return new(n||(n=Promise))(function(o,a){function r(t){try{c(i.next(t))}catch(t){a(t)}}function s(t){try{c(i.throw(t))}catch(t){a(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,s)}c((i=i.apply(t,e||[])).next())})};class V{constructor(t,e){this.paymentIntegrationService=t,this.amazonPayV2PaymentProcessor=e}initialize(t){return T(this,void 0,void 0,function*(){const{methodId:e,amazonpay:n}=t;if(!e||!(null==n?void 0:n.container))throw new S('Unable to proceed because "methodId" or "containerId" argument is not provided.');let i;try{i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e)}catch(t){yield this.paymentIntegrationService.loadPaymentMethod(e),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e)}yield this.amazonPayV2PaymentProcessor.initialize(i),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:n.container,methodId:e,placement:y.Checkout})})}deinitialize(){return T(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize()})}signIn(){throw new A('In order to sign in via Amazon, the shopper must click on "Amazon Pay" button.')}signOut(t){return T(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getPaymentId();e&&(yield this.amazonPayV2PaymentProcessor.signout(),yield this.paymentIntegrationService.remoteCheckoutSignOut(e.providerId,t))})}executePaymentMethodCheckout(t){var e;return null===(e=null==t?void 0:t.continueWithCheckoutCallback)||void 0===e||e.call(t),Promise.resolve()}}const N=w(t=>new V(t,z()),[{id:"amazonpay"}]);class x extends r{constructor(t){super(t||"An unexpected error has occurred during buy now cart creation process. Please try again later."),this.name="BuyNowCartCreationError",this.type="buy_now_cart_creation_error"}}class E extends r{constructor(t){super(t||"An unexpected error has occurred during config creation process. Please try again later."),this.name="AmazonPayV2ConfigCreationError",this.type="amazon_pay_v2_config_creation_error"}}function U(t){return t instanceof Object&&"buyNowInitializeOptions"in t}var j,D=function(t,e,n,i){return new(n||(n=Promise))(function(o,a){function r(t){try{c(i.next(t))}catch(t){a(t)}}function s(t){try{c(i.throw(t))}catch(t){a(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,s)}c((i=i.apply(t,e||[])).next())})};class q{constructor(t,e,n){this.paymentIntegrationService=t,this.amazonPayV2PaymentProcessor=e,this.amazonPayV2ConfigRequestSender=n}initialize(t){var e;return D(this,void 0,void 0,function*(){const{methodId:n,containerId:i,amazonpay:o}=t,{buttonColor:a}=o||{};if(!n||!i)throw new S('Unable to proceed because "methodId" or "containerId" argument is not provided.');const{getPaymentMethodOrThrow:r}=this.paymentIntegrationService.getState(),s=r(n),{initializationData:c}=s;yield this.amazonPayV2PaymentProcessor.initialize(s),o||(yield this.paymentIntegrationService.loadDefaultCheckout());const u=U(o)?void 0:o;U(o)&&"function"==typeof(null===(e=o.buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)&&(this._buyNowInitializeOptions=o.buyNowInitializeOptions,this.amazonPayV2PaymentProcessor.updateBuyNowFlowFlag(!0)),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:i,methodId:n,options:u,placement:y.Cart,buttonColor:a,isButtonMicroTextDisabled:null==c?void 0:c.isButtonMicroTextDisabled}),this._buyNowInitializeOptions&&this.amazonPayV2PaymentProcessor.prepareCheckoutWithCreationRequestConfig(this._getCheckoutCreationRequestConfig.bind(this))})}deinitialize(){return this.amazonPayV2PaymentProcessor.deinitialize()}_createBuyNowCartOrThrow(){var t,e;return D(this,void 0,void 0,function*(){const n=null===(e=null===(t=this._buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)||void 0===e?void 0:e.call(t);if(!n)throw new s(o.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(n)}catch(t){throw new x}})}_createCheckoutConfig(t){return D(this,void 0,void 0,function*(){try{const e=(yield this.amazonPayV2ConfigRequestSender.createCheckoutConfig(t)).body,{payload:n,public_key:i}=e,o=function(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(t);o<i.length;o++)e.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(t,i[o])&&(n[i[o]]=t[i[o]])}return n}(e,["payload","public_key"]);return Object.assign({payloadJSON:n,publicKeyId:i},o)}catch(t){throw new E}})}_getCheckoutCreationRequestConfig(){return D(this,void 0,void 0,function*(){const t=yield this._createBuyNowCartOrThrow(),e={amount:String(t.baseAmount),currencyCode:t.currency.code};return{createCheckoutSessionConfig:yield this._createCheckoutConfig(t.id),estimatedOrderAmount:e,productType:0===c(t)?p.PayOnly:p.PayAndShip}})}}!function(t){t.Json="application/json",t.JsonV1="application/vnd.bc.v1+json"}(j||(j={}));const R=j,L={"X-Checkout-SDK-Version":"1.817.0"};class K{constructor(t){this._requestSender=t}createCheckoutConfig(t){const e={cartId:t},n=Object.assign({"X-API-INTERNAL":"This API endpoint is for internal use only and may change in the future","Content-Type":R.Json},L);return this._requestSender.post("/api/storefront/payment/amazonpay",{headers:n,body:e})}}const F=w(t=>{const e=i(),n=new K(e),o=z();return new q(t,o,n)},[{id:"amazonpay"}]);export{F as createAmazonPayV2ButtonStrategy,N as createAmazonPayV2CustomerStrategy,B as createAmazonPayV2PaymentStrategy};
1
+ import{getScriptLoader as t}from"@bigcommerce/script-loader";import{noop as e,reduce as n}from"lodash";import{createRequestSender as i}from"@bigcommerce/request-sender";var o,a;class r extends Error{constructor(t){var e;super(t||"An unexpected error has occurred."),this.name="StandardError",this.type="standard",e=new.target.prototype,Object.setPrototypeOf?Object.setPrototypeOf(this,e):this.__proto__=e,"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,new.target):this.stack=new Error(this.message).stack}}!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"}(o||(o={}));class s extends r{constructor(t){super(function(t){switch(t){case o.MissingBillingAddress:return"Unable to proceed because billing address data is unavailable.";case o.MissingCart:return"Unable to proceed because cart data is unavailable.";case o.MissingConsignments:return"Unable to proceed because consignments data is unavailable.";case o.MissingCheckout:return"Unable to proceed because checkout data is unavailable.";case o.MissingCustomer:return"Unable to proceed because customer data is unavailable.";case o.MissingCheckoutConfig:case o.MissingOrderConfig:return"Unable to proceed because configuration data is unavailable.";case o.MissingOrder:return"Unable to proceed because order data is unavailable.";case o.MissingOrderId:return"Unable to proceed because order ID is unavailable or not generated yet.";case o.MissingPayment:return"Unable to proceed because payment data is unavailable.";case o.MissingPaymentToken:return"Unable to proceed because the token required to submit a payment is missing.";case o.MissingPaymentMethod:return"Unable to proceed because payment method data is unavailable or not properly configured.";case o.MissingShippingAddress:return"Unable to proceed because shipping address data is unavailable.";default:return"Unable to proceed because the required data is unavailable."}}(t)),this.subtype=t,this.name="MissingDataError",this.type="missing_data"}}function c(t){return e=t.lineItems.physicalItems.filter(t=>!t.addedByPromotion),n(e,(t,e)=>t+e.quantity,0);var e}function u(t,e){if(null==t)throw e?e():new Error("An unexpected error has occurred.");return t}!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"}(a||(a={}));class d extends r{constructor(t){super(function(t){switch(t){case a.CustomerNotInitialized:return"Unable to proceed because the customer step of checkout has not been initialized.";case a.PaymentNotInitialized:return"Unable to proceed because the payment step of checkout has not been initialized.";case a.ShippingNotInitialized:return"Unable to proceed because the shipping step of checkout has not been initialized.";case a.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.subtype=t,this.name="NotInitializedError",this.type="not_initialized"}}const h={de:"eu",jp:"fe",uk:"eu",us:"na"};var l,y,m,p,g,P;!function(t){t.en_US="en_US",t.en_GB="en_GB",t.de_DE="de_DE",t.fr_FR="fr_FR",t.it_IT="it_IT",t.es_ES="es_ES",t.ja_JP="ja_JP"}(l||(l={})),function(t){t.Home="Home",t.Product="Product",t.Cart="Cart",t.Checkout="Checkout",t.Other="Other"}(y||(y={})),function(t){t.USD="USD",t.EUR="EUR",t.GBP="GBP",t.JPY="JPY"}(m||(m={})),function(t){t.PayAndShip="PayAndShip",t.PayOnly="PayOnly"}(p||(p={})),function(t){t.Gold="Gold",t.LightGray="LightGray",t.DarkGray="DarkGray"}(g||(g={})),function(t){t.C0001="C0001"}(P||(P={}));var f=function(t,e,n,i){return new(n||(n=Promise))(function(o,a){function r(t){try{c(i.next(t))}catch(t){a(t)}}function s(t){try{c(i.throw(t))}catch(t){a(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,s)}c((i=i.apply(t,e||[])).next())})};class b{constructor(t){this.amazonPayV2ScriptLoader=t}initialize(t){return f(this,void 0,void 0,function*(){this.amazonPayV2SDK=yield this.amazonPayV2ScriptLoader.load(t),this.buttonParentContainer=this.buttonParentContainer||this.createAmazonPayButtonParentContainer()})}deinitialize(){var t;return this.amazonPayV2Button=void 0,null===(t=this.buttonParentContainer)||void 0===t||t.remove(),this.buttonParentContainer=void 0,this.amazonPayV2SDK=void 0,Promise.resolve()}bindButton(t,e,n){this.getAmazonPayV2SDK().Pay.bindChangeAction(`#${t}`,{amazonCheckoutSessionId:e,changeAction:n})}createButton(t,e){this.amazonPayV2Button=this.getAmazonPayV2SDK().Pay.renderButton(`#${t}`,e)}prepareCheckout(t){const e=this.prepareRequestConfig(t);this.getAmazonPayV2Button().onClick(()=>{this.getAmazonPayV2Button().initCheckout(e)})}prepareCheckoutWithCreationRequestConfig(t){this.getAmazonPayV2Button().onClick(()=>f(this,void 0,void 0,function*(){const e=yield t();if(e){const t=this.prepareRequestConfig(e.createCheckoutSessionConfig,e.estimatedOrderAmount,e.productType);this.getAmazonPayV2Button().initCheckout(t)}}))}signout(){return f(this,void 0,void 0,function*(){return this.amazonPayV2SDK&&this.amazonPayV2SDK.Pay.signout(),Promise.resolve()})}renderAmazonPayButton({buttonColor:t,checkoutState:e,containerId:n,decoupleCheckoutInitiation:i=!1,methodId:o,options:a,placement:r,isButtonMicroTextDisabled:s=!1}){const c=document.querySelector(`#${n}`);if(!c)return;const{id:u}=c.appendChild(this.getButtonParentContainer());a&&s&&(a.design=P.C0001);const d=null!=a?a:this.getAmazonPayV2ButtonOptions(e,o,r,i,t);return this.createButton(u,d),this.getButtonParentContainer()}updateBuyNowFlowFlag(t){this.isBuyNowFlow=Boolean(t)}isPh4Enabled(t,e){const n=!!t["PROJECT-3483.amazon_pay_ph4"],i=!!t["INT-6885.amazon_pay_ph4_us_only"];return n&&i?"US"===e:n}prepareRequestConfig(t,e,n){const{publicKeyId:i}=t,o=function(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(t);o<i.length;o++)e.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(t,i[o])&&(n[i[o]]=t[i[o]])}return n}(t,["publicKeyId"]);return Object.assign(Object.assign({createCheckoutSessionConfig:this.isEnvironmentSpecific(i)?o:t},e&&{estimatedOrderAmount:e}),n&&{productType:n})}createAmazonPayButtonParentContainer(){const t=Math.random().toString(16).substr(-4),e=document.createElement("div");return e.id=`amazonpay_button_parent_container_${t}`,e}getAmazonPayV2ButtonOptions(t,e,n,i=!1,a=g.Gold){var r;const{getCart:u,getCheckout:d,getStoreConfigOrThrow:h,getPaymentMethodOrThrow:l}=this.getCheckoutState(t),{config:{merchantId:y,testMode:m},initializationData:f}=l(e);if(!f)throw new s(o.MissingPaymentMethod);const{checkoutLanguage:b,checkoutSessionMethod:v,createCheckoutSessionConfig:C,extractAmazonCheckoutSessionId:z,ledgerCurrency:w,publicKeyId:S="",isButtonMicroTextDisabled:I}=f;if(!y||!w)throw new s(o.MissingPaymentMethod);const _=Object.assign({merchantId:y,ledgerCurrency:w,checkoutLanguage:b,placement:n,buttonColor:a},I?{design:P.C0001}:{});if(this.isBuyNowFlow)return Object.assign(Object.assign({},_),{sandbox:!!m});const O=u();_.productType=O&&0===c(O)?p.PayOnly:p.PayAndShip;const{checkoutSettings:{features:k},storeProfile:{shopPath:M,storeCountryCode:B}}=h();if(this.isPh4Enabled(k,B)){if(!C)throw new s(o.MissingPaymentMethod);const t=null===(r=d())||void 0===r?void 0:r.outstandingBalance.toString(),e=null==O?void 0:O.currency.code,n=Object.assign({},_);let a;return this.isEnvironmentSpecific(S)?(n.publicKeyId=S,a=C):(n.sandbox=!!m,a=Object.assign(Object.assign({},C),{publicKeyId:S})),i||(n.createCheckoutSessionConfig=a),t&&e&&(n.estimatedOrderAmount={amount:t,currencyCode:e}),n}const A={method:v,url:`${M}/remote-checkout/${e}/payment-session`,extractAmazonCheckoutSessionId:z};return Object.assign(Object.assign({},_),{createCheckoutSession:A,sandbox:!!m})}isEnvironmentSpecific(t){return/^(SANDBOX|LIVE)/.test(t)}getAmazonPayV2SDK(){return this.getOrThrow(this.amazonPayV2SDK)}getButtonParentContainer(){return this.getOrThrow(this.buttonParentContainer)}getAmazonPayV2Button(){return this.getOrThrow(this.amazonPayV2Button)}getOrThrow(t){return u(t,()=>new d(a.PaymentNotInitialized))}getCheckoutState(t){return"object"==typeof(e=t)&&null!==e&&"cart"in e&&"checkout"in e&&"config"in e&&"paymentMethods"in e?{getCart:t.cart.getCart,getCheckout:t.checkout.getCheckout,getStoreConfigOrThrow:t.config.getStoreConfigOrThrow,getPaymentMethodOrThrow:e=>t.paymentMethods.getPaymentMethodOrThrow(e)}:t;var e}}class v extends r{constructor(t){super(t||"Unable to proceed because the client library of a payment method is not loaded or ready to be used."),this.name="PaymentMethodClientUnavailableError",this.type="payment_method_client_unavailable"}}class C{constructor(t,e=window){this.scriptLoader=t,this.windowWithAmazonPay=e}load(t){return e=this,n=void 0,o=function*(){const{initializationData:e}=t,n=(null==e?void 0:e.region)||"us",i=h[n];if(yield this.scriptLoader.loadScript(`https://static-${i}.payments-amazon.com/checkout.js`),!this.windowWithAmazonPay.amazon)throw new v;return this.windowWithAmazonPay.amazon},new((i=void 0)||(i=Promise))(function(t,a){function r(t){try{c(o.next(t))}catch(t){a(t)}}function s(t){try{c(o.throw(t))}catch(t){a(t)}}function c(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i(function(t){t(n)})).then(r,s)}c((o=o.apply(e,n||[])).next())});var e,n,i,o}}function z(){return new b(new C(t()))}function w(t,e){return Object.assign(t,{resolveIds:e})}class S extends r{constructor(t){super(t||"Invalid arguments have been provided."),this.name="InvalidArgumentError",this.type="invalid_argument"}}class I extends S{constructor(t){let e="Unable to submit payment for the order because the payload is invalid.";t&&(e=`${e} Make sure the following fields are provided correctly: ${t.join(", ")}.`),super(e),this.name="PaymentArgumentInvalidError"}}class _ extends r{constructor(t){super(t||"Payment process was cancelled."),this.name="PaymentMethodCancelledError",this.type="payment_cancelled"}}class O extends r{constructor(){super("The current order does not need to be finalized at this stage."),this.name="OrderFinalizationNotRequiredError",this.type="order_finalization_not_required"}}var k=function(t,e,n,i){return new(n||(n=Promise))(function(o,a){function r(t){try{c(i.next(t))}catch(t){a(t)}}function s(t){try{c(i.throw(t))}catch(t){a(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,s)}c((i=i.apply(t,e||[])).next())})};class M{constructor(t,e){this.paymentIntegrationService=t,this.amazonPayV2PaymentProcessor=e}initialize(t){return k(this,void 0,void 0,function*(){const{methodId:e,amazonpay:n}=t;if(!e)throw new S('Unable to proceed because "methodId" argument is not provided.');const i=this.paymentIntegrationService.getState(),{features:o}=i.getStoreConfigOrThrow().checkoutSettings,a=i.getPaymentMethodOrThrow(e),r=a.initializationData||{},{paymentToken:s="",region:c="",isButtonMicroTextDisabled:u}=r;if(yield this.amazonPayV2PaymentProcessor.initialize(a),this._isReadyToPay(s))(null==n?void 0:n.editButtonId)&&this._bindEditButton(n.editButtonId,s,"changePayment",this._isModalFlow(c));else{const{id:t}=this._createContainer();if(this._amazonPayButton=this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:i,containerId:t,decoupleCheckoutInitiation:this._isOneTimeTransaction(o,c.toUpperCase()),methodId:e,placement:y.Checkout,isButtonMicroTextDisabled:u}),!this._amazonPayButton)throw new S("Unable to render the Amazon Pay button to an invalid HTML container element.")}})}execute(t,n){return k(this,void 0,void 0,function*(){const{payment:i}=t;if(!i)throw new I(["payment"]);const{methodId:o}=i,a=this.paymentIntegrationService.getState(),{features:r}=a.getStoreConfigOrThrow().checkoutSettings,s=a.getPaymentMethodOrThrow(o).initializationData||{},{paymentToken:c="",region:u=""}=s;if(this._isReadyToPay(c)||this._isOneTimeTransaction(r,u.toUpperCase())){const e={methodId:o,paymentData:{nonce:c||"apb"}};yield this.paymentIntegrationService.submitOrder(t,n);try{return void(yield this.paymentIntegrationService.submitPayment(e))}catch(t){if(!((t=>"object"==typeof t&&null!==t&&"body"in t)(t)&&(d=t.body,"object"==typeof d&&null!==d&&"status"in d&&"additional_action_required"in d&&"additional_action_required"===d.status&&"data"in d.additional_action_required&&"redirect_url"in d.additional_action_required.data&&"string"==typeof d.additional_action_required.data.redirect_url)))throw t;const{additional_action_required:e}=t.body,{redirect_url:n}=e.data;if(c)return new Promise(()=>window.location.assign(n));this.amazonPayV2PaymentProcessor.prepareCheckout(JSON.parse(n))}}var d;return this._getAmazonPayButton().click(),this._isModalFlow(u)?new Promise((t,e)=>{const n=()=>{window.removeEventListener("focus",n),e(new _("Shopper needs to login to Amazonpay to continue"))};window.addEventListener("focus",n)}):new Promise(e)})}finalize(){return Promise.reject(new O)}deinitialize(){return k(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize(),this._amazonPayButton=void 0})}_bindEditButton(t,e,n,i){const o=document.getElementById(t);if(o&&o.parentNode){if(!i){const t=o.cloneNode(!0);o.parentNode.replaceChild(t,o),t.addEventListener("click",()=>{this._showLoadingSpinner()})}this.amazonPayV2PaymentProcessor.bindButton(t,e,n)}}_isModalFlow(t){return"us"===t}_showLoadingSpinner(){return k(this,void 0,void 0,function*(){yield this.paymentIntegrationService.widgetInteraction(()=>new Promise(e))})}_createContainer(){let t=document.getElementById("AmazonPayButton");return t||(t=document.createElement("div"),t.id="AmazonPayButton",t.style.display="none",document.body.appendChild(t))}_getAmazonPayButton(){return u(this._amazonPayButton,()=>new d(a.PaymentNotInitialized))}_isOneTimeTransaction(t,e){return this.amazonPayV2PaymentProcessor.isPh4Enabled(t,e)&&t["INT-6399.amazon_pay_apb"]}_isReadyToPay(t){return!!t}}const B=w(t=>new M(t,z()),[{id:"amazonpay"}]);class A extends r{constructor(t){super(t||"Not implemented."),this.name="NotImplementedError",this.type="not_implemented"}}var T=function(t,e,n,i){return new(n||(n=Promise))(function(o,a){function r(t){try{c(i.next(t))}catch(t){a(t)}}function s(t){try{c(i.throw(t))}catch(t){a(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,s)}c((i=i.apply(t,e||[])).next())})};class V{constructor(t,e){this.paymentIntegrationService=t,this.amazonPayV2PaymentProcessor=e}initialize(t){return T(this,void 0,void 0,function*(){const{methodId:e,amazonpay:n}=t;if(!e||!(null==n?void 0:n.container))throw new S('Unable to proceed because "methodId" or "containerId" argument is not provided.');let i;try{i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e)}catch(t){yield this.paymentIntegrationService.loadPaymentMethod(e),i=this.paymentIntegrationService.getState().getPaymentMethodOrThrow(e)}yield this.amazonPayV2PaymentProcessor.initialize(i),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:n.container,methodId:e,placement:y.Checkout})})}deinitialize(){return T(this,void 0,void 0,function*(){yield this.amazonPayV2PaymentProcessor.deinitialize()})}signIn(){throw new A('In order to sign in via Amazon, the shopper must click on "Amazon Pay" button.')}signOut(t){return T(this,void 0,void 0,function*(){const e=this.paymentIntegrationService.getState().getPaymentId();e&&(yield this.amazonPayV2PaymentProcessor.signout(),yield this.paymentIntegrationService.remoteCheckoutSignOut(e.providerId,t))})}executePaymentMethodCheckout(t){var e;return null===(e=null==t?void 0:t.continueWithCheckoutCallback)||void 0===e||e.call(t),Promise.resolve()}}const N=w(t=>new V(t,z()),[{id:"amazonpay"}]);class x extends r{constructor(t){super(t||"An unexpected error has occurred during buy now cart creation process. Please try again later."),this.name="BuyNowCartCreationError",this.type="buy_now_cart_creation_error"}}class E extends r{constructor(t){super(t||"An unexpected error has occurred during config creation process. Please try again later."),this.name="AmazonPayV2ConfigCreationError",this.type="amazon_pay_v2_config_creation_error"}}function U(t){return t instanceof Object&&"buyNowInitializeOptions"in t}var j,D=function(t,e,n,i){return new(n||(n=Promise))(function(o,a){function r(t){try{c(i.next(t))}catch(t){a(t)}}function s(t){try{c(i.throw(t))}catch(t){a(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,s)}c((i=i.apply(t,e||[])).next())})};class q{constructor(t,e,n){this.paymentIntegrationService=t,this.amazonPayV2PaymentProcessor=e,this.amazonPayV2ConfigRequestSender=n}initialize(t){var e;return D(this,void 0,void 0,function*(){const{methodId:n,containerId:i,amazonpay:o}=t,{buttonColor:a}=o||{};if(!n||!i)throw new S('Unable to proceed because "methodId" or "containerId" argument is not provided.');const{getPaymentMethodOrThrow:r}=this.paymentIntegrationService.getState(),s=r(n),{initializationData:c}=s;yield this.amazonPayV2PaymentProcessor.initialize(s),o||(yield this.paymentIntegrationService.loadDefaultCheckout());const u=U(o)?void 0:o;U(o)&&"function"==typeof(null===(e=o.buyNowInitializeOptions)||void 0===e?void 0:e.getBuyNowCartRequestBody)&&(this._buyNowInitializeOptions=o.buyNowInitializeOptions,this.amazonPayV2PaymentProcessor.updateBuyNowFlowFlag(!0)),this.amazonPayV2PaymentProcessor.renderAmazonPayButton({checkoutState:this.paymentIntegrationService.getState(),containerId:i,methodId:n,options:u,placement:y.Cart,buttonColor:a,isButtonMicroTextDisabled:null==c?void 0:c.isButtonMicroTextDisabled}),this._buyNowInitializeOptions&&this.amazonPayV2PaymentProcessor.prepareCheckoutWithCreationRequestConfig(this._getCheckoutCreationRequestConfig.bind(this))})}deinitialize(){return this.amazonPayV2PaymentProcessor.deinitialize()}_createBuyNowCartOrThrow(){var t,e;return D(this,void 0,void 0,function*(){const n=null===(e=null===(t=this._buyNowInitializeOptions)||void 0===t?void 0:t.getBuyNowCartRequestBody)||void 0===e?void 0:e.call(t);if(!n)throw new s(o.MissingCart);try{return yield this.paymentIntegrationService.createBuyNowCart(n)}catch(t){throw new x}})}_createCheckoutConfig(t){return D(this,void 0,void 0,function*(){try{const e=(yield this.amazonPayV2ConfigRequestSender.createCheckoutConfig(t)).body,{payload:n,public_key:i}=e,o=function(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(t);o<i.length;o++)e.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(t,i[o])&&(n[i[o]]=t[i[o]])}return n}(e,["payload","public_key"]);return Object.assign({payloadJSON:n,publicKeyId:i},o)}catch(t){throw new E}})}_getCheckoutCreationRequestConfig(){return D(this,void 0,void 0,function*(){const t=yield this._createBuyNowCartOrThrow(),e={amount:String(t.baseAmount),currencyCode:t.currency.code};return{createCheckoutSessionConfig:yield this._createCheckoutConfig(t.id),estimatedOrderAmount:e,productType:0===c(t)?p.PayOnly:p.PayAndShip}})}}!function(t){t.Json="application/json",t.JsonV1="application/vnd.bc.v1+json"}(j||(j={}));const R=j,L={"X-Checkout-SDK-Version":"1.818.0"};class K{constructor(t){this._requestSender=t}createCheckoutConfig(t){const e={cartId:t},n=Object.assign({"X-API-INTERNAL":"This API endpoint is for internal use only and may change in the future","Content-Type":R.Json},L);return this._requestSender.post("/api/storefront/payment/amazonpay",{headers:n,body:e})}}const F=w(t=>{const e=i(),n=new K(e),o=z();return new q(t,o,n)},[{id:"amazonpay"}]);export{F as createAmazonPayV2ButtonStrategy,N as createAmazonPayV2CustomerStrategy,B as createAmazonPayV2PaymentStrategy};
2
2
  //# sourceMappingURL=amazon-pay.js.map