@montonio/montonio-js 1.0.26 → 1.0.27

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.
@@ -49,7 +49,7 @@ class l {
49
49
  try {
50
50
  const a = {
51
51
  Accept: "application/json",
52
- "X-Montonio-Js-Version": "1.0.26"
52
+ "X-Montonio-Js-Version": "1.0.27"
53
53
  };
54
54
  s && (a["Content-Type"] = "application/json");
55
55
  const r = {
@@ -1,2 +1,2 @@
1
- (function(o,u){typeof exports=="object"&&typeof module!="undefined"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(o=typeof globalThis!="undefined"?globalThis:o||self,u(o.Montonio={}))})(this,function(o){"use strict";o.MessageTypeEnum=void 0,function(i){i.CHECKOUT_PAYMENT_COMPONENT_READY="montonio:checkout.paymentComponentReady",i.CHECKOUT_CHANGE_LOCALE="montonio:checkout.changeLocale",i.CHECKOUT_SUBMIT_PAYMENT="montonio:checkout.submitPayment",i.CHECKOUT_START_PAYMENT_AUTH="montonio:checkout.startPaymentAuth",i.CHECKOUT_SEND_PAYMENT_AUTH_DATA="montonio:checkout.sendPaymentAuthData",i.CHECKOUT_PAYMENT_AUTH_COMPONENT_READY="montonio:checkout.paymentAuthComponentReady",i.CHECKOUT_PAYMENT_AUTH_COMPLETED="montonio:checkout.paymentAuthCompleted",i.CHECKOUT_PAYMENT_COMPLETED="montonio:checkout.paymentCompleted",i.CHECKOUT_PAYMENT_FAILED="montonio:checkout.paymentFailed",i.CHECKOUT_SEND_PAYMENT_FAILED_DATA="montonio:checkout.sendPaymentFailedData",i.CHECKOUT_HEIGHT_CHANGED="montonio:checkout.heightChanged"}(o.MessageTypeEnum||(o.MessageTypeEnum={}));class u{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 getInstance(){return u.instance||(u.instance=new u),u.instance}getConfig(t,e){return this.environmentVariables[t][e]}}class m{constructor(){this.timeout=1e4}static getInstance(){return m.instance||(m.instance=new m),m.instance}async get(t){return this.request(t,"GET")}async post(t,e){return this.request(t,"POST",e)}async patch(t,e){return this.request(t,"PATCH",e)}async request(t,e,n){const s=new AbortController,r=setTimeout(()=>s.abort(),this.timeout);try{const c={Accept:"application/json","X-Montonio-Js-Version":"1.0.26"};n&&(c["Content-Type"]="application/json");const a={method:e,headers:c,credentials:"include",mode:"cors",signal:s.signal};n&&(a.body=JSON.stringify(n));const l=await fetch(t,a);if(!l.ok)throw new Error(`HTTP error ${l.status}: ${l.statusText}`);return await l.json()}catch(c){throw c instanceof DOMException&&c.name==="AbortError"?new Error(`Request timeout after ${this.timeout}ms`):c}finally{clearTimeout(r)}}}class h{constructor(){this.subscriptions=new Map,this.globalListenerAttached=!1,this.subscriptionCounter=0,this.setupGlobalMessageListener()}static getInstance(){return h.instance||(h.instance=new h),h.instance}subscribe(t,e,n){const s=`sub_${++this.subscriptionCounter}`,r=this.extractWindowSources(n);return this.subscriptions.set(s,{id:s,messageType:t,handler:e,sources:r}),s}addSourceToSubscription(t,e){const n=this.subscriptions.get(t);if(!n)throw new Error(`Subscription with ID '${t}' not found`);return n.sources.includes(e)?!1:(n.sources.push(e),!0)}unsubscribe(t){this.subscriptions.delete(t)}waitForMessage(t,e,n=1e4){return new Promise((s,r)=>{const c=setTimeout(()=>{this.unsubscribe(a),r(new Error(`Message ${t} timeout after ${n}ms`))},n),a=this.subscribe(t,l=>{clearTimeout(c),this.unsubscribe(a),s(l)},e)})}postMessage(t,e,n="*"){if(!t)throw new Error("Target window is not available.");t.postMessage(e,n)}clearSubscriptionsForSource(t){const e=[];this.subscriptions.forEach(n=>{n.sources.includes(t)&&(n.sources=n.sources.filter(s=>s!==t),n.sources.length===0&&e.push(n.id))}),e.forEach(n=>{this.subscriptions.delete(n)})}clearAllSubscriptions(){this.subscriptions.clear()}setupGlobalMessageListener(){this.globalListenerAttached||(window.addEventListener("message",t=>{try{if(!t.data||typeof t.data!="object"||!t.data.name)return;const e=t.data;this.subscriptions.forEach(n=>{if(!(n.messageType!==e.name||!n.sources.some(r=>r===t.source)))try{n.handler(e)}catch(r){console.error("Error in message handler:",r)}})}catch(e){console.error("Error processing iframe message:",e)}}),this.globalListenerAttached=!0)}extractWindowSources(t){return t.map(e=>{if(e instanceof d){const n=e.getContentWindow();if(!n)throw new Error("Iframe contentWindow is not available. Make sure the iframe is mounted and loaded.");return n}return e}).filter(e=>e!==null)}}class d{constructor(t){var e;this.defaultStyles={width:"100%",height:"100%"},this.subscriptionIds=new Set,this.options=t,this.resizeOnHeightChange=(e=t.resizeOnHeightChange)!==null&&e!==void 0?e:!0,this.element=document.createElement("iframe"),this.messagingService=h.getInstance(),this.setupIframe()}setupIframe(){const{src:t,allow:e="payment",styles:n={}}=this.options;this.element.src=t,this.element.allow=e;const s={...this.defaultStyles,...n};Object.assign(this.element.style,s)}mount(){return this.options.mountElement.appendChild(this.element),this.resizeOnHeightChange&&this.startResizing(this.element),this.element}unmount(){this.clearSubscriptions(),this.element.contentWindow&&this.messagingService.clearSubscriptionsForSource(this.element.contentWindow),this.element.parentNode&&this.element.parentNode.removeChild(this.element)}clearSubscriptions(){this.subscriptionIds.forEach(t=>{this.messagingService.unsubscribe(t)}),this.subscriptionIds.clear()}getElement(){return 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}waitForLoad(t=1e4){return new Promise((e,n)=>{const s=setTimeout(()=>{n(new Error(`Iframe load timeout after ${t}ms`))},t);this.element.onload=()=>{clearTimeout(s),e()}})}waitForMessage(t,e=1e4){const n=this.element.contentWindow;if(!n)throw new Error("Iframe contentWindow is not available. Make sure the iframe is mounted and loaded.");return this.messagingService.waitForMessage(t,[n],e)}subscribe(t,e){const n=this.element.contentWindow;if(!n)throw new Error("Iframe contentWindow is not available. Make sure the iframe is mounted and loaded.");const s=this.messagingService.subscribe(t,e,[n]);this.subscriptionIds.add(s)}postMessage(t,e="*"){if(!this.element.contentWindow)throw new Error("Iframe is not available. Make sure the iframe is mounted and loaded.");this.messagingService.postMessage(this.element.contentWindow,t,e)}startResizing(t){this.subscribe(o.MessageTypeEnum.CHECKOUT_HEIGHT_CHANGED,e=>{t.style.height=e.payload.height+"px"})}}class p{constructor(){this.iframe=null,this.mountElement=null,this.loaded=!1,this.http=m.getInstance(),this.config=u.getInstance(),this.messaging=h.getInstance()}destroy(){this.cleanup()}getIframe(){if(!this.iframe)throw new Error("Iframe not initialized");return this.iframe}cleanup(){this.iframe&&(this.iframe.unmount(),this.iframe=null)}}class E extends p{constructor(t){super(),this.options=t,this.mountElement=t.mountElement||document.body}async initialize(){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");this.iframe=new d({src:this.options.paymentAuthData.embeddedUrl,mountElement:this.mountElement,styles:{width:"100vw",height:"100vh",position:"fixed",top:"0",left:"0",zIndex:"16777271"},resizeOnHeightChange:!1}),this.iframe.mount(),await this.iframe.waitForMessage(o.MessageTypeEnum.CHECKOUT_PAYMENT_AUTH_COMPONENT_READY),this.iframe.postMessage({name:o.MessageTypeEnum.CHECKOUT_SEND_PAYMENT_AUTH_DATA,payload:{paymentAuthData:this.options.paymentAuthData}})}async redirectViaPost(t){if(!t.redirectUrl)throw new Error("Redirect URL is not set in paymentAuthData");const e=document.createElement("form");if(e.method=t.redirectMethod||"get",e.action=t.redirectUrl,e.style.display="none",t.formData)for(const[n,s]of Object.entries(t.formData)){const r=document.createElement("input");r.type="hidden",r.name=n,r.value=s,e.appendChild(r)}throw document.body.appendChild(e),e.submit(),await new Promise(n=>setTimeout(n,1e4)),new Error("Redirect timeout: Expected redirect to occur within 10 seconds")}}function g(i){if(typeof i=="string"){const t=document.querySelector(i);if(!t||!(t instanceof HTMLElement))throw new Error(`Element not found: ${i}`);return t}return i}o.Environment=void 0,function(i){i.DEVELOPMENT="development",i.PRODUCTION="production",i.SANDBOX="sandbox",i.PRELIVE_SANDBOX="prelive-sandbox",i.PRELIVE_PRODUCTION="prelive-production"}(o.Environment||(o.Environment={}));class f extends Error{constructor(t="MontonioCheckout not initialized. Please call the .initialize() method of the MontonioCheckout class first."){super(t),this.name="MontonioCheckoutNotInitializedError"}}class b extends Error{constructor(t){super(`Payment failed: ${t.errorCode}`),this.name="PaymentFailedError",this.paymentFailedMessageData=t}}class y extends p{constructor(t){super(),this.paymentAuth=null,this.submitPaymentSubscriptions={completedId:"",failedId:"",authId:""},this.options=t,this.environment=t.environment||o.Environment.PRODUCTION}async initialize(t){try{this.mountElement=g(t);const e=await this.fetchSession();return console.log("SDK: sessionData from Stargate",e),this.iframe=new d({src:e.url,mountElement:this.mountElement,styles:{minHeight:"230px"}}),this.iframe.mount(),await this.iframe.waitForMessage(o.MessageTypeEnum.CHECKOUT_PAYMENT_COMPONENT_READY),this.loaded=!0,!0}catch(e){throw this.cleanup(),e}}updateOptions(t){if(!this.loaded)throw new f;t.locale!==void 0&&(this.options.locale=t.locale,this.getIframe().postMessage({name:o.MessageTypeEnum.CHECKOUT_CHANGE_LOCALE,payload:{locale:t.locale}}))}async validateOrReject(){return await console.log("Payment form validation not implemented yet")}async submitPayment(){if(!this.loaded)throw new f;return new Promise((t,e)=>{this.submitPaymentSubscriptions.completedId=this.messaging.subscribe(o.MessageTypeEnum.CHECKOUT_PAYMENT_COMPLETED,async n=>{console.log("CHECKOUT_PAYMENT_COMPLETED (from main iframe)",n);const s=await this.handlePaymentCompletedMessage(n);t(s),this.cleanupAfterPaymentSubmission()},[this.getIframe()]),this.submitPaymentSubscriptions.failedId=this.messaging.subscribe(o.MessageTypeEnum.CHECKOUT_PAYMENT_FAILED,n=>{console.error("CHECKOUT_PAYMENT_FAILED (from main iframe)",n),this.getIframe().postMessage({name:o.MessageTypeEnum.CHECKOUT_SEND_PAYMENT_FAILED_DATA,payload:n.payload}),e(new b(n.payload)),this.cleanupAfterPaymentSubmission()},[this.getIframe()]),this.submitPaymentSubscriptions.authId=this.messaging.subscribe(o.MessageTypeEnum.CHECKOUT_START_PAYMENT_AUTH,async n=>{try{console.log("PAYMENT AUTH STARTED",n),this.paymentAuth=new E({paymentAuthData:n.payload.paymentAuthData}),await this.paymentAuth.initialize();const s=this.paymentAuth.getIframe();this.messaging.addSourceToSubscription(this.submitPaymentSubscriptions.completedId,s.getContentWindow()),this.messaging.addSourceToSubscription(this.submitPaymentSubscriptions.failedId,s.getContentWindow())}catch(s){e(s)}},[this.getIframe()]),this.getIframe().postMessage({name:o.MessageTypeEnum.CHECKOUT_SUBMIT_PAYMENT})})}async fetchSession(){const e=`${this.config.getConfig("stargateUrl",this.environment)}/api/sessions/${this.options.sessionUuid}/gateway-url${this.options.locale?`?preferredLocale=${this.options.locale}`:""}`;return await this.http.get(e)}async handlePaymentCompletedMessage(t){const n=`${this.config.getConfig("stargateUrl",this.environment)}/api/payment-intents/${t.payload.paymentIntentUuid}/return-url`,s=10,r=1e3;let c=0;for(;c<s;){try{const a=await this.http.get(n);if(c++,a!=null&&a.merchantReturnUrl)return{returnUrl:a.merchantReturnUrl}}catch(a){console.error("Error fetching return URL:",a)}c<s&&await new Promise(a=>setTimeout(a,r))}throw new Error(`Failed to fetch the return url after ${c} attempts`)}cleanupAfterPaymentSubmission(){this.messaging.unsubscribe(this.submitPaymentSubscriptions.completedId),this.messaging.unsubscribe(this.submitPaymentSubscriptions.failedId),this.messaging.unsubscribe(this.submitPaymentSubscriptions.authId),this.cleanupPaymentAuth()}cleanup(){this.cleanupPaymentAuth(),super.cleanup()}cleanupPaymentAuth(){this.paymentAuth&&(this.paymentAuth.destroy(),this.paymentAuth=null)}}o.MontonioCheckout=y,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});
1
+ (function(o,u){typeof exports=="object"&&typeof module!="undefined"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(o=typeof globalThis!="undefined"?globalThis:o||self,u(o.Montonio={}))})(this,function(o){"use strict";o.MessageTypeEnum=void 0,function(i){i.CHECKOUT_PAYMENT_COMPONENT_READY="montonio:checkout.paymentComponentReady",i.CHECKOUT_CHANGE_LOCALE="montonio:checkout.changeLocale",i.CHECKOUT_SUBMIT_PAYMENT="montonio:checkout.submitPayment",i.CHECKOUT_START_PAYMENT_AUTH="montonio:checkout.startPaymentAuth",i.CHECKOUT_SEND_PAYMENT_AUTH_DATA="montonio:checkout.sendPaymentAuthData",i.CHECKOUT_PAYMENT_AUTH_COMPONENT_READY="montonio:checkout.paymentAuthComponentReady",i.CHECKOUT_PAYMENT_AUTH_COMPLETED="montonio:checkout.paymentAuthCompleted",i.CHECKOUT_PAYMENT_COMPLETED="montonio:checkout.paymentCompleted",i.CHECKOUT_PAYMENT_FAILED="montonio:checkout.paymentFailed",i.CHECKOUT_SEND_PAYMENT_FAILED_DATA="montonio:checkout.sendPaymentFailedData",i.CHECKOUT_HEIGHT_CHANGED="montonio:checkout.heightChanged"}(o.MessageTypeEnum||(o.MessageTypeEnum={}));class u{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 getInstance(){return u.instance||(u.instance=new u),u.instance}getConfig(t,e){return this.environmentVariables[t][e]}}class m{constructor(){this.timeout=1e4}static getInstance(){return m.instance||(m.instance=new m),m.instance}async get(t){return this.request(t,"GET")}async post(t,e){return this.request(t,"POST",e)}async patch(t,e){return this.request(t,"PATCH",e)}async request(t,e,n){const s=new AbortController,r=setTimeout(()=>s.abort(),this.timeout);try{const c={Accept:"application/json","X-Montonio-Js-Version":"1.0.27"};n&&(c["Content-Type"]="application/json");const a={method:e,headers:c,credentials:"include",mode:"cors",signal:s.signal};n&&(a.body=JSON.stringify(n));const l=await fetch(t,a);if(!l.ok)throw new Error(`HTTP error ${l.status}: ${l.statusText}`);return await l.json()}catch(c){throw c instanceof DOMException&&c.name==="AbortError"?new Error(`Request timeout after ${this.timeout}ms`):c}finally{clearTimeout(r)}}}class h{constructor(){this.subscriptions=new Map,this.globalListenerAttached=!1,this.subscriptionCounter=0,this.setupGlobalMessageListener()}static getInstance(){return h.instance||(h.instance=new h),h.instance}subscribe(t,e,n){const s=`sub_${++this.subscriptionCounter}`,r=this.extractWindowSources(n);return this.subscriptions.set(s,{id:s,messageType:t,handler:e,sources:r}),s}addSourceToSubscription(t,e){const n=this.subscriptions.get(t);if(!n)throw new Error(`Subscription with ID '${t}' not found`);return n.sources.includes(e)?!1:(n.sources.push(e),!0)}unsubscribe(t){this.subscriptions.delete(t)}waitForMessage(t,e,n=1e4){return new Promise((s,r)=>{const c=setTimeout(()=>{this.unsubscribe(a),r(new Error(`Message ${t} timeout after ${n}ms`))},n),a=this.subscribe(t,l=>{clearTimeout(c),this.unsubscribe(a),s(l)},e)})}postMessage(t,e,n="*"){if(!t)throw new Error("Target window is not available.");t.postMessage(e,n)}clearSubscriptionsForSource(t){const e=[];this.subscriptions.forEach(n=>{n.sources.includes(t)&&(n.sources=n.sources.filter(s=>s!==t),n.sources.length===0&&e.push(n.id))}),e.forEach(n=>{this.subscriptions.delete(n)})}clearAllSubscriptions(){this.subscriptions.clear()}setupGlobalMessageListener(){this.globalListenerAttached||(window.addEventListener("message",t=>{try{if(!t.data||typeof t.data!="object"||!t.data.name)return;const e=t.data;this.subscriptions.forEach(n=>{if(!(n.messageType!==e.name||!n.sources.some(r=>r===t.source)))try{n.handler(e)}catch(r){console.error("Error in message handler:",r)}})}catch(e){console.error("Error processing iframe message:",e)}}),this.globalListenerAttached=!0)}extractWindowSources(t){return t.map(e=>{if(e instanceof d){const n=e.getContentWindow();if(!n)throw new Error("Iframe contentWindow is not available. Make sure the iframe is mounted and loaded.");return n}return e}).filter(e=>e!==null)}}class d{constructor(t){var e;this.defaultStyles={width:"100%",height:"100%"},this.subscriptionIds=new Set,this.options=t,this.resizeOnHeightChange=(e=t.resizeOnHeightChange)!==null&&e!==void 0?e:!0,this.element=document.createElement("iframe"),this.messagingService=h.getInstance(),this.setupIframe()}setupIframe(){const{src:t,allow:e="payment",styles:n={}}=this.options;this.element.src=t,this.element.allow=e;const s={...this.defaultStyles,...n};Object.assign(this.element.style,s)}mount(){return this.options.mountElement.appendChild(this.element),this.resizeOnHeightChange&&this.startResizing(this.element),this.element}unmount(){this.clearSubscriptions(),this.element.contentWindow&&this.messagingService.clearSubscriptionsForSource(this.element.contentWindow),this.element.parentNode&&this.element.parentNode.removeChild(this.element)}clearSubscriptions(){this.subscriptionIds.forEach(t=>{this.messagingService.unsubscribe(t)}),this.subscriptionIds.clear()}getElement(){return 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}waitForLoad(t=1e4){return new Promise((e,n)=>{const s=setTimeout(()=>{n(new Error(`Iframe load timeout after ${t}ms`))},t);this.element.onload=()=>{clearTimeout(s),e()}})}waitForMessage(t,e=1e4){const n=this.element.contentWindow;if(!n)throw new Error("Iframe contentWindow is not available. Make sure the iframe is mounted and loaded.");return this.messagingService.waitForMessage(t,[n],e)}subscribe(t,e){const n=this.element.contentWindow;if(!n)throw new Error("Iframe contentWindow is not available. Make sure the iframe is mounted and loaded.");const s=this.messagingService.subscribe(t,e,[n]);this.subscriptionIds.add(s)}postMessage(t,e="*"){if(!this.element.contentWindow)throw new Error("Iframe is not available. Make sure the iframe is mounted and loaded.");this.messagingService.postMessage(this.element.contentWindow,t,e)}startResizing(t){this.subscribe(o.MessageTypeEnum.CHECKOUT_HEIGHT_CHANGED,e=>{t.style.height=e.payload.height+"px"})}}class p{constructor(){this.iframe=null,this.mountElement=null,this.loaded=!1,this.http=m.getInstance(),this.config=u.getInstance(),this.messaging=h.getInstance()}destroy(){this.cleanup()}getIframe(){if(!this.iframe)throw new Error("Iframe not initialized");return this.iframe}cleanup(){this.iframe&&(this.iframe.unmount(),this.iframe=null)}}class E extends p{constructor(t){super(),this.options=t,this.mountElement=t.mountElement||document.body}async initialize(){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");this.iframe=new d({src:this.options.paymentAuthData.embeddedUrl,mountElement:this.mountElement,styles:{width:"100vw",height:"100vh",position:"fixed",top:"0",left:"0",zIndex:"16777271"},resizeOnHeightChange:!1}),this.iframe.mount(),await this.iframe.waitForMessage(o.MessageTypeEnum.CHECKOUT_PAYMENT_AUTH_COMPONENT_READY),this.iframe.postMessage({name:o.MessageTypeEnum.CHECKOUT_SEND_PAYMENT_AUTH_DATA,payload:{paymentAuthData:this.options.paymentAuthData}})}async redirectViaPost(t){if(!t.redirectUrl)throw new Error("Redirect URL is not set in paymentAuthData");const e=document.createElement("form");if(e.method=t.redirectMethod||"get",e.action=t.redirectUrl,e.style.display="none",t.formData)for(const[n,s]of Object.entries(t.formData)){const r=document.createElement("input");r.type="hidden",r.name=n,r.value=s,e.appendChild(r)}throw document.body.appendChild(e),e.submit(),await new Promise(n=>setTimeout(n,1e4)),new Error("Redirect timeout: Expected redirect to occur within 10 seconds")}}function g(i){if(typeof i=="string"){const t=document.querySelector(i);if(!t||!(t instanceof HTMLElement))throw new Error(`Element not found: ${i}`);return t}return i}o.Environment=void 0,function(i){i.DEVELOPMENT="development",i.PRODUCTION="production",i.SANDBOX="sandbox",i.PRELIVE_SANDBOX="prelive-sandbox",i.PRELIVE_PRODUCTION="prelive-production"}(o.Environment||(o.Environment={}));class f extends Error{constructor(t="MontonioCheckout not initialized. Please call the .initialize() method of the MontonioCheckout class first."){super(t),this.name="MontonioCheckoutNotInitializedError"}}class b extends Error{constructor(t){super(`Payment failed: ${t.errorCode}`),this.name="PaymentFailedError",this.paymentFailedMessageData=t}}class y extends p{constructor(t){super(),this.paymentAuth=null,this.submitPaymentSubscriptions={completedId:"",failedId:"",authId:""},this.options=t,this.environment=t.environment||o.Environment.PRODUCTION}async initialize(t){try{this.mountElement=g(t);const e=await this.fetchSession();return console.log("SDK: sessionData from Stargate",e),this.iframe=new d({src:e.url,mountElement:this.mountElement,styles:{minHeight:"230px"}}),this.iframe.mount(),await this.iframe.waitForMessage(o.MessageTypeEnum.CHECKOUT_PAYMENT_COMPONENT_READY),this.loaded=!0,!0}catch(e){throw this.cleanup(),e}}updateOptions(t){if(!this.loaded)throw new f;t.locale!==void 0&&(this.options.locale=t.locale,this.getIframe().postMessage({name:o.MessageTypeEnum.CHECKOUT_CHANGE_LOCALE,payload:{locale:t.locale}}))}async validateOrReject(){return await console.log("Payment form validation not implemented yet")}async submitPayment(){if(!this.loaded)throw new f;return new Promise((t,e)=>{this.submitPaymentSubscriptions.completedId=this.messaging.subscribe(o.MessageTypeEnum.CHECKOUT_PAYMENT_COMPLETED,async n=>{console.log("CHECKOUT_PAYMENT_COMPLETED (from main iframe)",n);const s=await this.handlePaymentCompletedMessage(n);t(s),this.cleanupAfterPaymentSubmission()},[this.getIframe()]),this.submitPaymentSubscriptions.failedId=this.messaging.subscribe(o.MessageTypeEnum.CHECKOUT_PAYMENT_FAILED,n=>{console.error("CHECKOUT_PAYMENT_FAILED (from main iframe)",n),this.getIframe().postMessage({name:o.MessageTypeEnum.CHECKOUT_SEND_PAYMENT_FAILED_DATA,payload:n.payload}),e(new b(n.payload)),this.cleanupAfterPaymentSubmission()},[this.getIframe()]),this.submitPaymentSubscriptions.authId=this.messaging.subscribe(o.MessageTypeEnum.CHECKOUT_START_PAYMENT_AUTH,async n=>{try{console.log("PAYMENT AUTH STARTED",n),this.paymentAuth=new E({paymentAuthData:n.payload.paymentAuthData}),await this.paymentAuth.initialize();const s=this.paymentAuth.getIframe();this.messaging.addSourceToSubscription(this.submitPaymentSubscriptions.completedId,s.getContentWindow()),this.messaging.addSourceToSubscription(this.submitPaymentSubscriptions.failedId,s.getContentWindow())}catch(s){e(s)}},[this.getIframe()]),this.getIframe().postMessage({name:o.MessageTypeEnum.CHECKOUT_SUBMIT_PAYMENT})})}async fetchSession(){const e=`${this.config.getConfig("stargateUrl",this.environment)}/api/sessions/${this.options.sessionUuid}/gateway-url${this.options.locale?`?preferredLocale=${this.options.locale}`:""}`;return await this.http.get(e)}async handlePaymentCompletedMessage(t){const n=`${this.config.getConfig("stargateUrl",this.environment)}/api/payment-intents/${t.payload.paymentIntentUuid}/return-url`,s=10,r=1e3;let c=0;for(;c<s;){try{const a=await this.http.get(n);if(c++,a!=null&&a.merchantReturnUrl)return{returnUrl:a.merchantReturnUrl}}catch(a){console.error("Error fetching return URL:",a)}c<s&&await new Promise(a=>setTimeout(a,r))}throw new Error(`Failed to fetch the return url after ${c} attempts`)}cleanupAfterPaymentSubmission(){this.messaging.unsubscribe(this.submitPaymentSubscriptions.completedId),this.messaging.unsubscribe(this.submitPaymentSubscriptions.failedId),this.messaging.unsubscribe(this.submitPaymentSubscriptions.authId),this.cleanupPaymentAuth()}cleanup(){this.cleanupPaymentAuth(),super.cleanup()}cleanupPaymentAuth(){this.paymentAuth&&(this.paymentAuth.destroy(),this.paymentAuth=null)}}o.MontonioCheckout=y,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});
2
2
  //# 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.26",
3
+ "version": "1.0.27",
4
4
  "description": "Montonio JS SDK for front-end web applications",
5
5
  "type": "module",
6
6
  "publishConfig": {