@montonio/montonio-js 1.0.55 → 1.0.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -41,7 +41,7 @@ To integrate Montonio's embeddable payment methods into your checkout, you first
41
41
 
42
42
  ### 1. Initialize MontonioCheckout
43
43
 
44
- First, create a container element in your HTML where the Montonio Checkout will be rendered. You need to decide on the appropriate place in your checkout.
44
+ First, create a container element in your HTML where MontonioCheckout will be rendered. You need to decide on the appropriate place in your checkout page.
45
45
 
46
46
  ```html
47
47
  <div id="montonio-checkout-container"></div>
@@ -61,7 +61,7 @@ const montonioCheckout = new MontonioCheckout(checkoutOptions);
61
61
  await montonioCheckout.initialize('#montonio-checkout-container'); // The CSS selector string or HTMLElement of the container to mount the Montonio Checkout component
62
62
  ```
63
63
 
64
- The `MontonioCheckout.initialize()` method will render the Montonio Checkout iframe in the specified container. You can then interact with the checkout by calling methods on the `MontonioCheckout` instance.
64
+ The `MontonioCheckout.initialize()` method will render the MontonioCheckout component in the specified container. You can then interact with it by calling methods on the `MontonioCheckout` instance.
65
65
 
66
66
  ### 2. Validate the payment form
67
67
 
@@ -74,7 +74,7 @@ class l {
74
74
  try {
75
75
  const r = {
76
76
  Accept: "application/json",
77
- "X-Montonio-Js-Version": "1.0.55"
77
+ "X-Montonio-Js-Version": "1.0.56"
78
78
  };
79
79
  s && (r["Content-Type"] = "application/json");
80
80
  const a = {
@@ -1,3 +1,3 @@
1
1
  (function(s,h){typeof exports=="object"&&typeof module!="undefined"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(s=typeof globalThis!="undefined"?globalThis:s||self,h(s.Montonio={}))})(this,function(s){"use strict";s.ErrorEnum=void 0,function(t){t.MONTONIO_CHECKOUT_NOT_INITIALIZED="MONTONIO_CHECKOUT_NOT_INITIALIZED",t.VALIDATION_ERROR="VALIDATION_ERROR",t.PAYMENT_FAILED="PAYMENT_FAILED",t.FAILED_TO_FETCH_RETURN_URL="FAILED_TO_FETCH_RETURN_URL"}(s.ErrorEnum||(s.ErrorEnum={}));class h extends Error{constructor(e="MontonioCheckout not initialized. Please call the .initialize() method of the MontonioCheckout class first."){super(e),this.name=s.ErrorEnum.MONTONIO_CHECKOUT_NOT_INITIALIZED}}class E extends Error{constructor(e="Validation failed. Check payment details and try again."){super(e),this.displayedInPaymentComponent=!0,this.name=s.ErrorEnum.VALIDATION_ERROR}}class A extends Error{constructor(e){super(`Payment failed: ${e.errorCode}`),this.displayedInPaymentComponent=!0,this.name=s.ErrorEnum.PAYMENT_FAILED,this.paymentFailedMessageData=e}}class _ extends Error{constructor({attempts:e}){super(`Payment was successful but we failed to fetch the return-url from our servers after ${e} retries.
2
- The customer should not try again! We will inform you about the payment being paid via webhook.`),this.name=s.ErrorEnum.FAILED_TO_FETCH_RETURN_URL}}s.MessageTypeEnum=void 0,function(t){t.CHECKOUT_PAYMENT_COMPONENT_READY="montonio:checkout.paymentComponentReady",t.CHECKOUT_CHANGE_LOCALE="montonio:checkout.changeLocale",t.CHECKOUT_SUBMIT_PAYMENT="montonio:checkout.submitPayment",t.CHECKOUT_START_PAYMENT_AUTH="montonio:checkout.startPaymentAuth",t.CHECKOUT_SEND_PAYMENT_AUTH_DATA="montonio:checkout.sendPaymentAuthData",t.CHECKOUT_PAYMENT_AUTH_COMPONENT_READY="montonio:checkout.paymentAuthComponentReady",t.CHECKOUT_PAYMENT_AUTH_COMPLETED="montonio:checkout.paymentAuthCompleted",t.CHECKOUT_PAYMENT_COMPLETED="montonio:checkout.paymentCompleted",t.CHECKOUT_PAYMENT_FAILED="montonio:checkout.paymentFailed",t.CHECKOUT_SEND_PAYMENT_FAILED_DATA="montonio:checkout.sendPaymentFailedData",t.CHECKOUT_HEIGHT_CHANGED="montonio:checkout.heightChanged",t.CHECKOUT_VALIDATE_FIELDS="montonio:checkout.validateFields",t.CHECKOUT_VALIDATE_FIELDS_RESULT="montonio:checkout.validateFieldsResult",t.CHECKOUT_PAYMENT_FORM_CHANGED="montonio:checkout.paymentFormChanged"}(s.MessageTypeEnum||(s.MessageTypeEnum={}));class l{constructor(){this.environmentVariables={stargateUrl:{sandbox:"https://sandbox-stargate.montonio.com",production:"https://stargate.montonio.com","prelive-sandbox":"https://sandbox-stargate.prelive.montonio.com","prelive-production":"https://stargate.prelive.montonio.com",development:"https://api-stargate.montonio.dev"}}}static get instance(){return l._instance||(l._instance=new l),l._instance}getConfig(e,i){return this.environmentVariables[e][i]}}class u{constructor(){this.timeout=3e4}static get instance(){return u._instance||(u._instance=new u),u._instance}async get(e){return this.request(e,"GET")}async post(e,i){return this.request(e,"POST",i)}async patch(e,i){return this.request(e,"PATCH",i)}async request(e,i,n){const o=new AbortController,c=setTimeout(()=>o.abort(),this.timeout);try{const r={Accept:"application/json","X-Montonio-Js-Version":"1.0.55"};n&&(r["Content-Type"]="application/json");const a={method:i,headers:r,credentials:"include",mode:"cors",signal:o.signal};n&&(a.body=JSON.stringify(n));const m=await fetch(e,a);if(!m.ok)throw new Error(`HTTP error ${m.status}: ${m.statusText}`);return await m.json()}catch(r){throw r instanceof DOMException&&r.name==="AbortError"?new Error(`Request timeout after ${this.timeout}ms`):r}finally{clearTimeout(c)}}}class d{constructor(){this.subscriptions=new Map,this.setupMessageListener()}subscribe(e,i,n){if(this.subscriptions.has(e))throw new Error(`Subscription for '${e}' already exists`);const o=this.extractWindowFromIframe(n);this.subscriptions.set(e,{handler:i,sources:[o]})}addIframeToSubscription(e,i){const n=this.subscriptions.get(e);if(!n)throw new Error(`Subscription for '${e}' not found`);const o=this.extractWindowFromIframe(i);n.sources.includes(o)||n.sources.push(o)}waitForMessage(e,i,n=3e4){return new Promise((o,c)=>{const r=setTimeout(()=>{this.removeIframeFromSubscription(e,i),c(new Error(`Message ${e} timeout after ${n}ms`))},n);this.subscribe(e,a=>{clearTimeout(r),this.removeIframeFromSubscription(e,i),o(a)},i)})}postMessage(e,i,n="*"){this.extractWindowFromIframe(e).postMessage(i,n)}clearAllSubscriptions(){this.subscriptions.clear()}clearSubscriptionsExcept(e){for(const i of[...this.subscriptions.keys()])e.includes(i)||this.subscriptions.delete(i)}removeIframeFromSubscription(e,i){const n=this.subscriptions.get(e);if(!n)throw new Error(`Subscription for '${e}' not found`);const o=this.extractWindowFromIframe(i);n.sources=n.sources.filter(c=>c!==o),n.sources.length===0&&this.subscriptions.delete(e)}setupMessageListener(){window.addEventListener("message",e=>{try{if(!e.data||typeof e.data!="object"||!e.data.name)return;const i=e.data;this.subscriptions.forEach((n,o)=>{if(!(o!==i.name||!n.sources.some(r=>r===e.source)))try{n.handler(i)}catch(r){console.error("Error in message handler:",r)}})}catch(i){console.error("Error processing iframe message:",i)}})}extractWindowFromIframe(e){return e.getContentWindow()}}class f{constructor(e){var i;this.defaultStyles={border:"none",display:"block",width:"100%",height:"100%"},this.options=e,this.resizeOnHeightChange=(i=e.resizeOnHeightChange)!==null&&i!==void 0?i:!0,this.element=document.createElement("iframe"),this.messagingService=new d,this.setupIframe()}mount(){return this.options.mountElement.appendChild(this.element),this.resizeOnHeightChange&&this.startResizing(this.element),this.element}unmount(){this.element.contentWindow&&this.messagingService.clearAllSubscriptions(),this.element.parentNode&&this.element.parentNode.removeChild(this.element)}getContentWindow(){if(!this.element.contentWindow)throw new Error("Iframe contentWindow is not available. Make sure the iframe is mounted and loaded.");return this.element.contentWindow}startResizing(e){this.messagingService.subscribe(s.MessageTypeEnum.CHECKOUT_HEIGHT_CHANGED,i=>{e.style.height=i.payload.height+"px"},this)}setupIframe(){const{src:e,allow:i="payment",styles:n={}}=this.options;this.element.src=e,this.element.allow=i;const o={...this.defaultStyles,...n};Object.assign(this.element.style,o)}}class T{constructor(){this.loaded=!1,this.mountElement=null,this._iframe=null,this.messagingService=new d,this.httpService=u.instance,this.configService=l.instance}get iframe(){if(!this._iframe)throw new Error("Iframe not initialized");return this._iframe}set iframe(e){this._iframe=e}cleanup(){this.iframe&&(this.iframe.unmount(),this.iframe=null)}}function C(t){if(typeof t=="string"){const e=document.querySelector(t);if(!e||!(e instanceof HTMLElement))throw new Error(`Element not found: ${t}`);return e}return t}function g(){const t=document.body.style.overflow||null;return document.body.style.overflow="hidden",{originalOverflow:t}}function y(t){t?document.body.style.overflow=t:document.body.style.removeProperty("overflow")}class O extends T{constructor(e){super(),this.originalBodyOverflow=null,this.options=e,this.mountElement=e.mountElement||document.body}async initialize(){try{if(this.options.paymentAuthData.type==="redirect"){await this.redirectViaPost(this.options.paymentAuthData);return}if(!this.options.paymentAuthData.embeddedUrl)throw new Error("Embedded URL is not set in paymentAuthData");const{originalOverflow:e}=g();this.originalBodyOverflow=e,this.iframe=new f({src:this.options.paymentAuthData.embeddedUrl,mountElement:this.mountElement,styles:{width:"100dvw",height:"100dvh",position:"fixed",top:"0",left:"0",zIndex:"2147483647"},resizeOnHeightChange:!1}),this.iframe.mount(),await this.messagingService.waitForMessage(s.MessageTypeEnum.CHECKOUT_PAYMENT_AUTH_COMPONENT_READY,this.iframe),this.messagingService.postMessage(this.iframe,{name:s.MessageTypeEnum.CHECKOUT_SEND_PAYMENT_AUTH_DATA,payload:{paymentAuthData:this.options.paymentAuthData}}),this.loaded=!0}catch(e){throw this.cleanup(),e}}cleanup(){this.loaded&&y(this.originalBodyOverflow),super.cleanup()}async redirectViaPost(e){if(!e.redirectUrl)throw new Error("Redirect URL is not set in paymentAuthData");const i=document.createElement("form");if(i.method=e.redirectMethod||"get",i.action=e.redirectUrl,i.style.display="none",e.formData)for(const[n,o]of Object.entries(e.formData)){const c=document.createElement("input");c.type="hidden",c.name=n,c.value=o,i.appendChild(c)}throw document.body.appendChild(i),i.submit(),await new Promise(n=>setTimeout(n,3e4)),new Error("Redirect timeout: Expected redirect to occur within 30 seconds")}}s.Environment=void 0,function(t){t.DEVELOPMENT="development",t.PRODUCTION="production",t.SANDBOX="sandbox",t.PRELIVE_SANDBOX="prelive-sandbox",t.PRELIVE_PRODUCTION="prelive-production"}(s.Environment||(s.Environment={}));class w extends T{constructor(e){super(),this.isValid=!1,this.paymentAuth=null,this.options=e,this.environment=e.environment||s.Environment.PRODUCTION}async initialize(e){try{this.mountElement=C(e);const i=await this.fetchSession();return this.iframe=new f({src:i.url,mountElement:this.mountElement}),this.iframe.mount(),await this.messagingService.waitForMessage(s.MessageTypeEnum.CHECKOUT_PAYMENT_COMPONENT_READY,this.iframe),this.listenForPaymentFormChanges(),this.loaded=!0,!0}catch(i){throw console.error("Error initializing MontonioCheckout",i),this.cleanup(),i}}updateOptions(e){if(!this.loaded)throw new h;e.locale!==void 0&&(this.options.locale=e.locale,this.messagingService.postMessage(this.iframe,{name:s.MessageTypeEnum.CHECKOUT_CHANGE_LOCALE,payload:{locale:e.locale}}))}async validateOrReject(){return new Promise((e,i)=>{this.messagingService.waitForMessage(s.MessageTypeEnum.CHECKOUT_VALIDATE_FIELDS_RESULT,this.iframe).then(n=>{n.payload.isValid?e():i(new E)}).catch(()=>i(new E)),this.messagingService.postMessage(this.iframe,{name:s.MessageTypeEnum.CHECKOUT_VALIDATE_FIELDS})})}async submitPayment(){if(!this.loaded)throw new h;return new Promise((e,i)=>{this.messagingService.subscribe(s.MessageTypeEnum.CHECKOUT_PAYMENT_COMPLETED,async n=>{console.log("CHECKOUT_PAYMENT_COMPLETED (from main iframe)",n),this.cleanupPaymentAuth();try{const o=await this.getPaymentResult(n.payload.paymentIntentUuid);e(o)}catch(o){i(o)}this.cleanupAfterPaymentSubmission()},this.iframe),this.messagingService.subscribe(s.MessageTypeEnum.CHECKOUT_PAYMENT_FAILED,n=>{console.error("CHECKOUT_PAYMENT_FAILED (from main iframe)",n),this.cleanupPaymentAuth(),this.messagingService.postMessage(this.iframe,{name:s.MessageTypeEnum.CHECKOUT_SEND_PAYMENT_FAILED_DATA,payload:n.payload}),i(new A(n.payload)),this.cleanupAfterPaymentSubmission()},this.iframe),this.messagingService.subscribe(s.MessageTypeEnum.CHECKOUT_VALIDATE_FIELDS_RESULT,n=>{console.log("CHECKOUT_VALIDATE_FIELDS_RESULT",n),n.payload.isValid||i(new E)},this.iframe),this.messagingService.subscribe(s.MessageTypeEnum.CHECKOUT_START_PAYMENT_AUTH,async n=>{try{console.log("PAYMENT AUTH STARTED",n),this.paymentAuth=new O({paymentAuthData:n.payload.paymentAuthData}),await this.paymentAuth.initialize();const o=this.paymentAuth.iframe;this.messagingService.addIframeToSubscription(s.MessageTypeEnum.CHECKOUT_PAYMENT_COMPLETED,o),this.messagingService.addIframeToSubscription(s.MessageTypeEnum.CHECKOUT_PAYMENT_FAILED,o)}catch(o){i(o)}},this.iframe),this.messagingService.postMessage(this.iframe,{name:s.MessageTypeEnum.CHECKOUT_SUBMIT_PAYMENT})})}async fetchSession(){const i=`${this.configService.getConfig("stargateUrl",this.environment)}/api/sessions/${this.options.sessionUuid}/gateway-url${this.options.locale?`?preferredLocale=${this.options.locale}`:""}`;return await this.httpService.get(i)}listenForPaymentFormChanges(){this.messagingService.subscribe(s.MessageTypeEnum.CHECKOUT_PAYMENT_FORM_CHANGED,e=>{this.isValid=e.payload.isValid,console.log("CHECKOUT_PAYMENT_FORM_CHANGED",this.isValid)},this.iframe)}async getPaymentResult(e){const n=`${this.configService.getConfig("stargateUrl",this.environment)}/api/payment-intents/${e}/return-url`,o=10,c=1e3;let r=0;for(;r<o;){try{const a=await this.httpService.get(n);if(r++,a!=null&&a.merchantReturnUrl)return{returnUrl:a.merchantReturnUrl,orderToken:a.orderToken,paymentStatus:a.paymentStatus}}catch(a){console.error("Error fetching return URL:",a)}r<o&&await new Promise(a=>setTimeout(a,c))}throw new _({attempts:r})}cleanupAfterPaymentSubmission(){this.messagingService.clearSubscriptionsExcept([s.MessageTypeEnum.CHECKOUT_PAYMENT_FORM_CHANGED])}cleanupPaymentAuth(){this.paymentAuth&&(this.paymentAuth.cleanup(),this.paymentAuth=null)}}s.LocaleEnum=void 0,function(t){t.EN="en",t.ET="et",t.LT="lt",t.LV="lv",t.PL="pl",t.RU="ru",t.FI="fi"}(s.LocaleEnum||(s.LocaleEnum={}));var p;(function(t){t.PENDING="PENDING",t.AUTHORIZED="AUTHORIZED",t.PAID="PAID",t.PARTIALLY_REFUNDED="PARTIALLY_REFUNDED",t.REFUNDED="REFUNDED",t.VOIDED="VOIDED",t.ABANDONED="ABANDONED"})(p||(p={})),s.MontonioCheckout=w,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})});
2
+ The customer should not try again! We will inform you about the payment being paid via webhook.`),this.name=s.ErrorEnum.FAILED_TO_FETCH_RETURN_URL}}s.MessageTypeEnum=void 0,function(t){t.CHECKOUT_PAYMENT_COMPONENT_READY="montonio:checkout.paymentComponentReady",t.CHECKOUT_CHANGE_LOCALE="montonio:checkout.changeLocale",t.CHECKOUT_SUBMIT_PAYMENT="montonio:checkout.submitPayment",t.CHECKOUT_START_PAYMENT_AUTH="montonio:checkout.startPaymentAuth",t.CHECKOUT_SEND_PAYMENT_AUTH_DATA="montonio:checkout.sendPaymentAuthData",t.CHECKOUT_PAYMENT_AUTH_COMPONENT_READY="montonio:checkout.paymentAuthComponentReady",t.CHECKOUT_PAYMENT_AUTH_COMPLETED="montonio:checkout.paymentAuthCompleted",t.CHECKOUT_PAYMENT_COMPLETED="montonio:checkout.paymentCompleted",t.CHECKOUT_PAYMENT_FAILED="montonio:checkout.paymentFailed",t.CHECKOUT_SEND_PAYMENT_FAILED_DATA="montonio:checkout.sendPaymentFailedData",t.CHECKOUT_HEIGHT_CHANGED="montonio:checkout.heightChanged",t.CHECKOUT_VALIDATE_FIELDS="montonio:checkout.validateFields",t.CHECKOUT_VALIDATE_FIELDS_RESULT="montonio:checkout.validateFieldsResult",t.CHECKOUT_PAYMENT_FORM_CHANGED="montonio:checkout.paymentFormChanged"}(s.MessageTypeEnum||(s.MessageTypeEnum={}));class l{constructor(){this.environmentVariables={stargateUrl:{sandbox:"https://sandbox-stargate.montonio.com",production:"https://stargate.montonio.com","prelive-sandbox":"https://sandbox-stargate.prelive.montonio.com","prelive-production":"https://stargate.prelive.montonio.com",development:"https://api-stargate.montonio.dev"}}}static get instance(){return l._instance||(l._instance=new l),l._instance}getConfig(e,i){return this.environmentVariables[e][i]}}class u{constructor(){this.timeout=3e4}static get instance(){return u._instance||(u._instance=new u),u._instance}async get(e){return this.request(e,"GET")}async post(e,i){return this.request(e,"POST",i)}async patch(e,i){return this.request(e,"PATCH",i)}async request(e,i,n){const o=new AbortController,c=setTimeout(()=>o.abort(),this.timeout);try{const r={Accept:"application/json","X-Montonio-Js-Version":"1.0.56"};n&&(r["Content-Type"]="application/json");const a={method:i,headers:r,credentials:"include",mode:"cors",signal:o.signal};n&&(a.body=JSON.stringify(n));const m=await fetch(e,a);if(!m.ok)throw new Error(`HTTP error ${m.status}: ${m.statusText}`);return await m.json()}catch(r){throw r instanceof DOMException&&r.name==="AbortError"?new Error(`Request timeout after ${this.timeout}ms`):r}finally{clearTimeout(c)}}}class d{constructor(){this.subscriptions=new Map,this.setupMessageListener()}subscribe(e,i,n){if(this.subscriptions.has(e))throw new Error(`Subscription for '${e}' already exists`);const o=this.extractWindowFromIframe(n);this.subscriptions.set(e,{handler:i,sources:[o]})}addIframeToSubscription(e,i){const n=this.subscriptions.get(e);if(!n)throw new Error(`Subscription for '${e}' not found`);const o=this.extractWindowFromIframe(i);n.sources.includes(o)||n.sources.push(o)}waitForMessage(e,i,n=3e4){return new Promise((o,c)=>{const r=setTimeout(()=>{this.removeIframeFromSubscription(e,i),c(new Error(`Message ${e} timeout after ${n}ms`))},n);this.subscribe(e,a=>{clearTimeout(r),this.removeIframeFromSubscription(e,i),o(a)},i)})}postMessage(e,i,n="*"){this.extractWindowFromIframe(e).postMessage(i,n)}clearAllSubscriptions(){this.subscriptions.clear()}clearSubscriptionsExcept(e){for(const i of[...this.subscriptions.keys()])e.includes(i)||this.subscriptions.delete(i)}removeIframeFromSubscription(e,i){const n=this.subscriptions.get(e);if(!n)throw new Error(`Subscription for '${e}' not found`);const o=this.extractWindowFromIframe(i);n.sources=n.sources.filter(c=>c!==o),n.sources.length===0&&this.subscriptions.delete(e)}setupMessageListener(){window.addEventListener("message",e=>{try{if(!e.data||typeof e.data!="object"||!e.data.name)return;const i=e.data;this.subscriptions.forEach((n,o)=>{if(!(o!==i.name||!n.sources.some(r=>r===e.source)))try{n.handler(i)}catch(r){console.error("Error in message handler:",r)}})}catch(i){console.error("Error processing iframe message:",i)}})}extractWindowFromIframe(e){return e.getContentWindow()}}class f{constructor(e){var i;this.defaultStyles={border:"none",display:"block",width:"100%",height:"100%"},this.options=e,this.resizeOnHeightChange=(i=e.resizeOnHeightChange)!==null&&i!==void 0?i:!0,this.element=document.createElement("iframe"),this.messagingService=new d,this.setupIframe()}mount(){return this.options.mountElement.appendChild(this.element),this.resizeOnHeightChange&&this.startResizing(this.element),this.element}unmount(){this.element.contentWindow&&this.messagingService.clearAllSubscriptions(),this.element.parentNode&&this.element.parentNode.removeChild(this.element)}getContentWindow(){if(!this.element.contentWindow)throw new Error("Iframe contentWindow is not available. Make sure the iframe is mounted and loaded.");return this.element.contentWindow}startResizing(e){this.messagingService.subscribe(s.MessageTypeEnum.CHECKOUT_HEIGHT_CHANGED,i=>{e.style.height=i.payload.height+"px"},this)}setupIframe(){const{src:e,allow:i="payment",styles:n={}}=this.options;this.element.src=e,this.element.allow=i;const o={...this.defaultStyles,...n};Object.assign(this.element.style,o)}}class T{constructor(){this.loaded=!1,this.mountElement=null,this._iframe=null,this.messagingService=new d,this.httpService=u.instance,this.configService=l.instance}get iframe(){if(!this._iframe)throw new Error("Iframe not initialized");return this._iframe}set iframe(e){this._iframe=e}cleanup(){this.iframe&&(this.iframe.unmount(),this.iframe=null)}}function C(t){if(typeof t=="string"){const e=document.querySelector(t);if(!e||!(e instanceof HTMLElement))throw new Error(`Element not found: ${t}`);return e}return t}function g(){const t=document.body.style.overflow||null;return document.body.style.overflow="hidden",{originalOverflow:t}}function y(t){t?document.body.style.overflow=t:document.body.style.removeProperty("overflow")}class O extends T{constructor(e){super(),this.originalBodyOverflow=null,this.options=e,this.mountElement=e.mountElement||document.body}async initialize(){try{if(this.options.paymentAuthData.type==="redirect"){await this.redirectViaPost(this.options.paymentAuthData);return}if(!this.options.paymentAuthData.embeddedUrl)throw new Error("Embedded URL is not set in paymentAuthData");const{originalOverflow:e}=g();this.originalBodyOverflow=e,this.iframe=new f({src:this.options.paymentAuthData.embeddedUrl,mountElement:this.mountElement,styles:{width:"100dvw",height:"100dvh",position:"fixed",top:"0",left:"0",zIndex:"2147483647"},resizeOnHeightChange:!1}),this.iframe.mount(),await this.messagingService.waitForMessage(s.MessageTypeEnum.CHECKOUT_PAYMENT_AUTH_COMPONENT_READY,this.iframe),this.messagingService.postMessage(this.iframe,{name:s.MessageTypeEnum.CHECKOUT_SEND_PAYMENT_AUTH_DATA,payload:{paymentAuthData:this.options.paymentAuthData}}),this.loaded=!0}catch(e){throw this.cleanup(),e}}cleanup(){this.loaded&&y(this.originalBodyOverflow),super.cleanup()}async redirectViaPost(e){if(!e.redirectUrl)throw new Error("Redirect URL is not set in paymentAuthData");const i=document.createElement("form");if(i.method=e.redirectMethod||"get",i.action=e.redirectUrl,i.style.display="none",e.formData)for(const[n,o]of Object.entries(e.formData)){const c=document.createElement("input");c.type="hidden",c.name=n,c.value=o,i.appendChild(c)}throw document.body.appendChild(i),i.submit(),await new Promise(n=>setTimeout(n,3e4)),new Error("Redirect timeout: Expected redirect to occur within 30 seconds")}}s.Environment=void 0,function(t){t.DEVELOPMENT="development",t.PRODUCTION="production",t.SANDBOX="sandbox",t.PRELIVE_SANDBOX="prelive-sandbox",t.PRELIVE_PRODUCTION="prelive-production"}(s.Environment||(s.Environment={}));class w extends T{constructor(e){super(),this.isValid=!1,this.paymentAuth=null,this.options=e,this.environment=e.environment||s.Environment.PRODUCTION}async initialize(e){try{this.mountElement=C(e);const i=await this.fetchSession();return this.iframe=new f({src:i.url,mountElement:this.mountElement}),this.iframe.mount(),await this.messagingService.waitForMessage(s.MessageTypeEnum.CHECKOUT_PAYMENT_COMPONENT_READY,this.iframe),this.listenForPaymentFormChanges(),this.loaded=!0,!0}catch(i){throw console.error("Error initializing MontonioCheckout",i),this.cleanup(),i}}updateOptions(e){if(!this.loaded)throw new h;e.locale!==void 0&&(this.options.locale=e.locale,this.messagingService.postMessage(this.iframe,{name:s.MessageTypeEnum.CHECKOUT_CHANGE_LOCALE,payload:{locale:e.locale}}))}async validateOrReject(){return new Promise((e,i)=>{this.messagingService.waitForMessage(s.MessageTypeEnum.CHECKOUT_VALIDATE_FIELDS_RESULT,this.iframe).then(n=>{n.payload.isValid?e():i(new E)}).catch(()=>i(new E)),this.messagingService.postMessage(this.iframe,{name:s.MessageTypeEnum.CHECKOUT_VALIDATE_FIELDS})})}async submitPayment(){if(!this.loaded)throw new h;return new Promise((e,i)=>{this.messagingService.subscribe(s.MessageTypeEnum.CHECKOUT_PAYMENT_COMPLETED,async n=>{console.log("CHECKOUT_PAYMENT_COMPLETED (from main iframe)",n),this.cleanupPaymentAuth();try{const o=await this.getPaymentResult(n.payload.paymentIntentUuid);e(o)}catch(o){i(o)}this.cleanupAfterPaymentSubmission()},this.iframe),this.messagingService.subscribe(s.MessageTypeEnum.CHECKOUT_PAYMENT_FAILED,n=>{console.error("CHECKOUT_PAYMENT_FAILED (from main iframe)",n),this.cleanupPaymentAuth(),this.messagingService.postMessage(this.iframe,{name:s.MessageTypeEnum.CHECKOUT_SEND_PAYMENT_FAILED_DATA,payload:n.payload}),i(new A(n.payload)),this.cleanupAfterPaymentSubmission()},this.iframe),this.messagingService.subscribe(s.MessageTypeEnum.CHECKOUT_VALIDATE_FIELDS_RESULT,n=>{console.log("CHECKOUT_VALIDATE_FIELDS_RESULT",n),n.payload.isValid||i(new E)},this.iframe),this.messagingService.subscribe(s.MessageTypeEnum.CHECKOUT_START_PAYMENT_AUTH,async n=>{try{console.log("PAYMENT AUTH STARTED",n),this.paymentAuth=new O({paymentAuthData:n.payload.paymentAuthData}),await this.paymentAuth.initialize();const o=this.paymentAuth.iframe;this.messagingService.addIframeToSubscription(s.MessageTypeEnum.CHECKOUT_PAYMENT_COMPLETED,o),this.messagingService.addIframeToSubscription(s.MessageTypeEnum.CHECKOUT_PAYMENT_FAILED,o)}catch(o){i(o)}},this.iframe),this.messagingService.postMessage(this.iframe,{name:s.MessageTypeEnum.CHECKOUT_SUBMIT_PAYMENT})})}async fetchSession(){const i=`${this.configService.getConfig("stargateUrl",this.environment)}/api/sessions/${this.options.sessionUuid}/gateway-url${this.options.locale?`?preferredLocale=${this.options.locale}`:""}`;return await this.httpService.get(i)}listenForPaymentFormChanges(){this.messagingService.subscribe(s.MessageTypeEnum.CHECKOUT_PAYMENT_FORM_CHANGED,e=>{this.isValid=e.payload.isValid,console.log("CHECKOUT_PAYMENT_FORM_CHANGED",this.isValid)},this.iframe)}async getPaymentResult(e){const n=`${this.configService.getConfig("stargateUrl",this.environment)}/api/payment-intents/${e}/return-url`,o=10,c=1e3;let r=0;for(;r<o;){try{const a=await this.httpService.get(n);if(r++,a!=null&&a.merchantReturnUrl)return{returnUrl:a.merchantReturnUrl,orderToken:a.orderToken,paymentStatus:a.paymentStatus}}catch(a){console.error("Error fetching return URL:",a)}r<o&&await new Promise(a=>setTimeout(a,c))}throw new _({attempts:r})}cleanupAfterPaymentSubmission(){this.messagingService.clearSubscriptionsExcept([s.MessageTypeEnum.CHECKOUT_PAYMENT_FORM_CHANGED])}cleanupPaymentAuth(){this.paymentAuth&&(this.paymentAuth.cleanup(),this.paymentAuth=null)}}s.LocaleEnum=void 0,function(t){t.EN="en",t.ET="et",t.LT="lt",t.LV="lv",t.PL="pl",t.RU="ru",t.FI="fi"}(s.LocaleEnum||(s.LocaleEnum={}));var p;(function(t){t.PENDING="PENDING",t.AUTHORIZED="AUTHORIZED",t.PAID="PAID",t.PARTIALLY_REFUNDED="PARTIALLY_REFUNDED",t.REFUNDED="REFUNDED",t.VOIDED="VOIDED",t.ABANDONED="ABANDONED"})(p||(p={})),s.MontonioCheckout=w,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})});
3
3
  //# sourceMappingURL=montonio.umd.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@montonio/montonio-js",
3
- "version": "1.0.55",
3
+ "version": "1.0.56",
4
4
  "description": "Montonio JS SDK for front-end web applications",
5
5
  "type": "module",
6
6
  "publishConfig": {