@payrails/web-sdk 2.7.6 → 2.7.7

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/index.js CHANGED
@@ -1,4 +1,4 @@
1
- !function(){"use strict";var t;let e;exports.ElementType=void 0,(t=exports.ElementType||(exports.ElementType={})).CARD_NUMBER="CARD_NUMBER",t.CARDHOLDER_NAME="CARDHOLDER_NAME",t.CVV="CVV",t.EXPIRATION_MONTH="EXPIRATION_MONTH",t.EXPIRATION_YEAR="EXPIRATION_YEAR";const n=new Uint8Array(16);function i(){if(!e&&(e="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!e))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return e(n)}const o=[];for(let t=0;t<256;++t)o.push((t+256).toString(16).slice(1));var s,a={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function r(t,e,n){if(a.randomUUID&&!e&&!t)return a.randomUUID();const s=(t=t||{}).random||(t.rng||i)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e){n=n||0;for(let t=0;t<16;++t)e[n+t]=s[t];return e}return function(t,e=0){return(o[t[e+0]]+o[t[e+1]]+o[t[e+2]]+o[t[e+3]]+"-"+o[t[e+4]]+o[t[e+5]]+"-"+o[t[e+6]]+o[t[e+7]]+"-"+o[t[e+8]]+o[t[e+9]]+"-"+o[t[e+10]]+o[t[e+11]]+o[t[e+12]]+o[t[e+13]]+o[t[e+14]]+o[t[e+15]]).toLowerCase()}(s)}!function(t){t.GET="GET",t.POST="POST"}(s||(s={}));const l=async({url:t,method:e=s.GET,token:n,body:i})=>{const o={method:e,headers:Object.assign(Object.assign(Object.assign({},h()),c(n)),v())};e===s.POST&&(o.body=JSON.stringify(i||{}));const a=await fetch(t,o),r=await a.json();if([401,403].includes(a.status))throw new d(t,e);if(!a.ok)throw new u(t,e,r);return{ok:a.ok,req:Object.assign({url:t},o),res:r}};class d extends Error{constructor(t,e){super(`[${e}] ${t} unauthorized`)}}class u extends Error{constructor(t,e,n){super(`[${e}] ${t} unsuccessful`),this.res=n}}const c=t=>({authorization:`Bearer ${t}`}),h=()=>({"x-idempotency-key":r()}),v=()=>({"x-client-version":"2.7.6","x-client-type":"web-sdk"});class p{constructor(t,e,n){this.sdkConfig=t,this.execution=e,this.returnLinks=n}async pay(t){const e=(await this.authorize(t)).res.links.execution;return await this.pollForAuthorizationResult(e)}async authorize(t){if(!this.execution.authorizeLink||!this.sdkConfig.amount)throw new Error("SDK was not initialized with workflow execution");const{success:e="https://payrails.io/success",error:n="https://payrails.io/error",cancel:i="https://payrails.io/cancel"}=this.returnLinks||{};return l({url:this.execution.authorizeLink,method:s.POST,token:this.sdkConfig.token,body:{amount:this.sdkConfig.amount,paymentComposition:t,returnInfo:{success:e,cancel:i,error:n}}})}async confirm(t,e={}){const n=await l({url:t,method:s.POST,token:this.sdkConfig.token,body:{data:e}}),i=await this.pollForAuthorizationResult(n.res.links.execution);if(i.finalState)return i;const o=i.response.status.slice().sort(((t,e)=>new Date(e.time).getTime()-new Date(t.time).getTime()))[0].time,{res:a}=await this.getExecution(n.res.links.execution,void 0,o);return{finalState:a.status.find((({code:t,time:e})=>["authorizeSuccessful","authorizeFailed"].includes(t)&&new Date(e)>new Date(o))),response:a}}async pollForAuthorizationResult(t,e=0){const n=(await this.getExecution(t)).res,i=n.status,o=["authorizePending","authorizeSuccessful","authorizeFailed"],s=i.find((({code:t})=>"authorizeRequested"===t));if(!s&&e<10)return await new Promise((t=>setTimeout(t,300))),this.pollForAuthorizationResult(t,e+1);if(!s)throw new Error("Authorization was not requested");const a=i.find((({code:t,time:e})=>"confirmRequested"===t&&new Date(e)>new Date(s.time))),r=a?a.time:s.time;let l=i.find((({code:t,time:e})=>o.includes(t)&&new Date(e)>new Date(r)));if(!l){const{res:e}=await this.getExecution(t,void 0,r);return l=e.status.find((({code:t,time:e})=>o.includes(t)&&new Date(e)>new Date(r))),{finalState:l,response:e}}return{finalState:l,response:n}}async getExecution(t,e,n){const i=new URLSearchParams;e&&e.length>0&&i.append("waitWhile[status]",`[${e.map((t=>`"${t}"`)).join(",")}]`),n&&i.append("waitWhile[lastStatusTime]",n);const o=`${t}${i.toString()?"?":""}${i.toString()}`;return l({url:o,token:this.sdkConfig.token})}async createApplePaySession(t){return l({url:t.requestUrl,method:s.POST,token:this.sdkConfig.token,body:{integrationType:"api",paymentMethodCode:"applePay",amount:this.sdkConfig.amount,meta:{sessionURL:t.sessionUrl,clientDomain:t.clientDomain||window.location.host}}})}}var m,y,g;!function(t){t.CARD="card",t.GOOGLE_PAY="googlePay",t.PAYPAL="payPal",t.APPLE_PAY="applePay"}(m||(m={})),function(t){t.ENABLED="enabled",t.CREATED="created"}(y||(y={}));class b{constructor(t){this.executionResponse=t}get lookup(){return this.executionResponse.initialResults.find((({body:{name:t}})=>"lookup"===t))}get holderReference(){return this.executionResponse.holderReference}get savedCreditCards(){return this.getStoredInstrumentForPaymentMethod(m.CARD)}get savedPaypalAccounts(){return this.getStoredInstrumentForPaymentMethod(m.PAYPAL)}get savedGooglePayAccounts(){return this.getStoredInstrumentForPaymentMethod(m.GOOGLE_PAY)}get savedApplePayAccounts(){return this.getStoredInstrumentForPaymentMethod(m.APPLE_PAY)}get paypalConfig(){const t=this.availablePaymentMethods.find((({paymentMethodCode:t})=>t===m.PAYPAL));if(!t)throw new Error("trying to initialize paypal without config");return t.config||{}}get googlePayConfig(){const t=this.availablePaymentMethods.find((({paymentMethodCode:t})=>t===m.GOOGLE_PAY));if(!t)throw new Error("trying to initialize google pay without config");return t?[t.config]:[]}get applePayConfig(){const t=this.availablePaymentMethods.find((({paymentMethodCode:t})=>t===m.APPLE_PAY));if(!t)throw new Error("apple pay config not found");return t.config.parameters}get url(){return this.response.links.self}get response(){return this.executionResponse}get meta(){return this.executionResponse.meta}get availablePaymentMethods(){var t;return(null===(t=this.lookup)||void 0===t?void 0:t.body.data.paymentCompositionOptions)||[]}get authorizeLink(){var t;return null===(t=this.lookup)||void 0===t?void 0:t.body.links.authorize.href}get createSessionLink(){return this.response.links.startPaymentSession.href}get storedPaymentInstruments(){return this.availablePaymentMethods.flatMap((t=>t.paymentInstruments||[]))}getStoredInstrumentForPaymentMethod(t){var e;return(null===(e=this.availablePaymentMethods.find((({paymentMethodCode:e})=>e===t)))||void 0===e?void 0:e.paymentInstruments)||[]}}class f{constructor(t,{id:e="",className:n=""}={}){this.subElements=[];const i=document.createElement(t);e&&(this.id=e,i.setAttribute("id",e)),n&&i.setAttribute("class",n),this.element=i}get parentElement(){return this.element.parentElement}get selector(){if(!this.id)throw new Error("Element id is not set");return`#${this.id}`}mount(t){const e=document.querySelector(t);if(!e)throw new Error(`Element with selector "${t}" not found in in the DOM`);e.appendChild(this.element),this.subElements.forEach((t=>{if(!this.id)throw new Error("Sub elements can not be rendered, please set id for the element");t.mount(this.selector)}))}unmount(){var t;this.subElements.forEach((t=>t.unmount())),null===(t=this.parentElement)||void 0===t||t.removeChild(this.element)}}class C extends f{get bin(){var t;return this.selectedInstrument?this.selectedInstrument.data.bin?this.selectedInstrument.data.bin:"":(null===(t=this.cardForm)||void 0===t?void 0:t.bin)||""}constructor(t,e,n,i){var o;super("button",{id:"payrails-card-payment-button"}),this.sdkConfig=t,this.execution=e,this.options=n,this.returnLinks=i,this.selectedInstrument=null,this.element.innerText=(null===(o=null==n?void 0:n.translations)||void 0===o?void 0:o.label)||"Pay",this.element.addEventListener("click",this.onPay.bind(this)),this.element.addEventListener("mouseenter",(()=>{var t;this.element.classList.contains("disabled")||(this.element.classList.add("hover"),this.setStyles((null===(t=this.options.styles)||void 0===t?void 0:t.hover)||{}))})),this.element.addEventListener("mouseleave",(()=>{var t;this.element.classList.contains("disabled")||(this.element.classList.remove("hover"),this.removeStyles((null===(t=this.options.styles)||void 0===t?void 0:t.hover)||{}))})),this.paymentExecutor=new p(this.sdkConfig,this.execution,this.returnLinks)}setDisabled(t){var e,n,i;this.element.disabled=t,t?(this.element.classList.add("disabled"),(null===(e=this.options.styles)||void 0===e?void 0:e.disabled)&&this.setStyles(this.options.styles.disabled)):(this.element.classList.remove("disabled"),this.removeStyles((null===(n=this.options.styles)||void 0===n?void 0:n.disabled)||{}),(null===(i=this.options.styles)||void 0===i?void 0:i.base)&&this.setStyles(this.options.styles.base))}setSavedCreditCard(t){console.warn("setSavedCreditCard is deprecated, please use setSavedInstrument"),this.setSavedInstrument(t)}setSavedInstrument(t){this.selectedInstrument=t,this.setDisabled(!1)}setStyles(t){var e;const n=Object.assign(Object.assign({},null===(e=this.options.styles)||void 0===e?void 0:e.base),t);Object.keys(n).forEach((t=>{this.element.style[t]=n[t]}))}removeStyles(t){var e;const n=Object.keys((null===(e=this.options.styles)||void 0===e?void 0:e.base)||{});Object.keys(t).forEach((t=>{var e,i;n.includes(t)?this.element.style[t]=null===(i=null===(e=this.options.styles)||void 0===e?void 0:e.base)||void 0===i?void 0:i[t]:this.element.style[t]=""}))}setLabel(t){this.element.innerText=t}setCardForm(t){this.cardForm=t}triggerLoading(t){var e,n,i,o;const s=this.element.offsetWidth;this.element.style.minWidth=`${s}px`,t?(this.element.innerHTML='<div class="dot-flashing"></div>',this.element.classList.add("loading"),(null===(e=this.options.styles)||void 0===e?void 0:e.loading)&&this.setStyles(this.options.styles.loading)):(this.element.innerText=(null===(i=null===(n=this.options)||void 0===n?void 0:n.translations)||void 0===i?void 0:i.label)||"Pay",this.element.classList.remove("loading"),this.removeStyles((null===(o=this.options.styles)||void 0===o?void 0:o.loading)||{}))}onAuthorizationFailed(t){var e,n;this.setDisabled(!1),this.triggerLoading(!1),(null===(e=this.options.events)||void 0===e?void 0:e.onAuthorizeFailed)&&(null===(n=this.options.events)||void 0===n||n.onAuthorizeFailed(t))}async onPay(){var t,e,n,i,o,s,a,r,l,u;if(this.setDisabled(!0),this.triggerLoading(!0),null===(t=this.options.events)||void 0===t?void 0:t.onPaymentButtonClicked)try{if(!1===await(null===(e=this.options.events)||void 0===e?void 0:e.onPaymentButtonClicked({bin:this.bin||""})))return void this.onAuthorizationFailed({code:exports.AuthorizationFailureReasons.VALIDATION_FAILED,message:"Callback passed to onPaymentButtonClicked resolved to false"})}catch(t){return void this.onAuthorizationFailed({code:exports.AuthorizationFailureReasons.VALIDATION_FAILED,message:"Callback passed to onPaymentButtonClicked threw an error"})}try{const t=[{paymentMethodCode:m.CARD,integrationType:"api",amount:this.sdkConfig.amount,storeInstrument:!1}];if(null===(n=this.selectedInstrument)||void 0===n?void 0:n.id)t[0].paymentInstrumentId=null===(i=this.selectedInstrument)||void 0===i?void 0:i.id,t[0].paymentMethodCode=null===(o=this.selectedInstrument)||void 0===o?void 0:o.paymentMethod;else{const{tokenizedCardData:e,storeInstrument:n,enrollInstrumentToNetworkOffers:i}=await this.collectCardFormValues();t[0].paymentInstrumentData={vaultToken:null==e?void 0:e.instrumentId,card:{numberToken:null==e?void 0:e.card_number,securityCodeToken:null==e?void 0:e.security_code}},t[0].storeInstrument=n,t[0].enrollInstrumentToNetworkOffers=i}const e=await this.paymentExecutor.pay(t);this.handleAuthorizationResult(e)}catch(t){t instanceof d||[401,403].includes(null===(s=null==t?void 0:t.error)||void 0===s?void 0:s.code)?(null===(r=null===(a=this.options.events)||void 0===a?void 0:a.onPaymentSessionExpired)||void 0===r||r.call(a),this.onAuthorizationFailed({code:exports.AuthorizationFailureReasons.AUTHENTICATION_ERROR,message:"API token is not valid or expired."})):t.toString().includes("Invalid token")?(null===(u=null===(l=this.options.events)||void 0===l?void 0:l.onPaymentSessionExpired)||void 0===u||u.call(l),this.onAuthorizationFailed({code:exports.AuthorizationFailureReasons.AUTHENTICATION_ERROR,message:"Vault token is not valid or expired."})):this.onAuthorizationFailed({code:exports.AuthorizationFailureReasons.UNKNOWN_ERROR,message:t.toString(),rawError:t})}}handleAuthorizationResult(t){var e,n,i;switch(null===(e=null==t?void 0:t.finalState)||void 0===e?void 0:e.code){case"authorizeSuccessful":this.triggerLoading(!1),(null===(n=this.options.events)||void 0===n?void 0:n.onAuthorizeSuccess)&&this.options.events.onAuthorizeSuccess();break;case"authorizePending":"3ds"===(null===(i=null==t?void 0:t.response)||void 0===i?void 0:i.actionRequired)&&this.handle3ds(t);break;default:this.onAuthorizationFailed({code:exports.AuthorizationFailureReasons.AUTHORIZATION_ERROR,message:"Authorization failed."})}}handle3ds(t){var e,n,i,o;try{null===(n=null===(e=this.options.events)||void 0===e?void 0:e.onThreeDSecureChallenge)||void 0===n||n.call(e)}catch(t){}const s=null===(i=null==t?void 0:t.response)||void 0===i?void 0:i.links["3ds"];if(s){const t=[[250,400],[390,400],[500,600],[600,400]],e=screen.width,n=t.reduce(((t,n)=>e>n[0]?n:t),[250,400]),i=document.createElement("iframe");i.setAttribute("id","payrails-3ds-frame"),i.setAttribute("src",s),i.setAttribute("width",n[0].toString()),i.setAttribute("height",n[1].toString());const a=document.createElement("div");a.setAttribute("id","payrails-3ds-challenge"),a.appendChild(i);const r=document.createElement("div");r.addEventListener("click",(async()=>{r.remove()})),r.setAttribute("id","payrails-3ds-popup-background"),r.appendChild(a);const l=async t=>{var e,n,i;if(t.data&&'{"type":"3DS-challenge-completed"}'===t.data){window.removeEventListener("message",l),r.remove();if(!(await this.paymentExecutor.getExecution(this.execution.url)).res.status.find((({code:t})=>"authorizeSuccessful"===t))&&(null===(e=this.options.events)||void 0===e?void 0:e.onAuthorizeFailed))return void this.onAuthorizationFailed({code:exports.AuthorizationFailureReasons.AUTHORIZATION_ERROR,message:"Authorization failed after 3DS challenge."});if(null===(n=this.options.events)||void 0===n?void 0:n.onAuthorizeSuccess)return void(null===(i=this.options.events)||void 0===i||i.onAuthorizeSuccess())}};null===(o=document.querySelector("body"))||void 0===o||o.appendChild(r),window.addEventListener("message",l),a.style.width=`${n[0]+4}px`,a.style.height=`${n[1]+4}px`}}async collectCardFormValues(){if(!this.cardForm)throw new Error("Trying to collect values from non-existent card form");return await this.cardForm.collectValues()}}exports.AuthorizationFailureReasons=void 0,(g=exports.AuthorizationFailureReasons||(exports.AuthorizationFailureReasons={})).VALIDATION_FAILED="VALIDATION_FAILED",g.AUTHORIZATION_ERROR="AUTHORIZATION_ERROR",g.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",g.UNKNOWN_ERROR="UNKNOWN_ERROR";class w{constructor(t){this.loadFunction=t,this.loadScript()}get loader(){return this.loadingPromise||(this.loadingPromise=this.loadScript()),this.loadingPromise}async loadScript(){return this.loadingPromise||(this.loadingPromise=new Promise(((t,e)=>{this.loadFunction().then((e=>{e&&t(e)}),(()=>{e()})).catch((()=>{}))}))),this.loadingPromise}}class A extends f{constructor(t){super("span",{id:t.id,className:"payrails-store-instrument"}),this.options=t,this.createHTML(),this.applyStyles(),this.addListeners()}get isChecked(){var t;return!!(null===(t=this.element.querySelector("input"))||void 0===t?void 0:t.checked)}createHTML(){var t,e,n,i,o,s,a,r,l;const d=(null===(n=null===(e=null===(t=this.options)||void 0===t?void 0:t.translations)||void 0===e?void 0:e.labels)||void 0===n?void 0:n.saveInstrument)||(null===(s=null===(o=null===(i=this.options)||void 0===i?void 0:i.translations)||void 0===o?void 0:o.labels)||void 0===s?void 0:s.storeInstrument)||"Save instrument for future payments",u=`${this.id}-checkbox`;(null===(l=null===(r=null===(a=this.options)||void 0===a?void 0:a.translations)||void 0===r?void 0:r.labels)||void 0===l?void 0:l.saveInstrument)&&console.warn("The saveInstrument label is deprecated, please use storeInstrument instead"),this.element.innerHTML=`<label for="${u}"><input type="checkbox" id="${u}" name="${u}" class="payrails-store-instrument-checkbox">${d}</label>`}applyStyles(){var t,e;Object.keys((null===(e=null===(t=this.options)||void 0===t?void 0:t.styles)||void 0===e?void 0:e.storeInstrumentCheckbox)||{}).forEach((t=>{var e,n,i;this.element.style[t]=null===(i=null===(n=null===(e=this.options)||void 0===e?void 0:e.styles)||void 0===n?void 0:n.storeInstrumentCheckbox)||void 0===i?void 0:i[t]}))}addListeners(){this.element.addEventListener("change",(t=>{var e,n,i,o;(null===(n=null===(e=this.options)||void 0===e?void 0:e.events)||void 0===n?void 0:n.onSaveInstrumentCheckboxChanged)&&(null===(o=null===(i=this.options)||void 0===i?void 0:i.events)||void 0===o||o.onSaveInstrumentCheckboxChanged({checked:this.isChecked})),t.stopPropagation(),t.stopImmediatePropagation()}))}}class k extends f{constructor(t,e){var n,i;super(t,e),this.options=e,this.storeInstrumentCheckbox=null,(null===(n=this.options)||void 0===n?void 0:n.showStoreInstrumentCheckbox)&&(this.storeInstrumentCheckbox=new A(Object.assign(Object.assign({},e),{id:`${null===(i=this.options)||void 0===i?void 0:i.id}-store-instrument-checkbox`,events:{onSaveInstrumentCheckboxChanged:async t=>{var n,i;null===(i=null===(n=null==e?void 0:e.events)||void 0===n?void 0:n.onSaveInstrumentCheckboxChanged)||void 0===i||i.call(n,t)}}})),this.subElements.push(this.storeInstrumentCheckbox))}get shouldStoreInstrument(){var t,e;return(null===(t=this.storeInstrumentCheckbox)||void 0===t?void 0:t.isChecked)||(null===(e=this.options)||void 0===e?void 0:e.alwaysStoreInstrument)||!1}}class E extends k{constructor(t,e,n){super("div",Object.assign(Object.assign({},n),{id:"payrails-apple-pay-button"})),this.sdkConfig=t,this.execution=e,this.options=n,this.appleButton=null,this.paymentExecutor=new p(t,e),this.loadScript=new w((async()=>{const t=document.createElement("script");return t.src="https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js",new Promise(((e,n)=>{t.onload=async()=>{var t,n,i;await this.isApplePayAvailable()?(null===(i=null===(n=null===(t=this.options)||void 0===t?void 0:t.events)||void 0===n?void 0:n.onApplePayAvailable)||void 0===i||i.call(n),e(!0)):e(!1)},t.onerror=()=>{n()},document.body.appendChild(t)}))}))}mount(t){super.mount(t),(async()=>{try{await this.loadScript.loader,await this.mountApplePayButton()}catch(t){}})()}unmount(){var t,e;null===(e=null===(t=this.appleButton)||void 0===t?void 0:t.parentElement)||void 0===e||e.removeChild(this.appleButton),super.unmount()}async isApplePayAvailable(){if(!(null===window||void 0===window?void 0:window.ApplePaySession))return!1;return await ApplePaySession.canMakePayments()}async mountApplePayButton(){var t,e,n;if(null===window||void 0===window?void 0:window.ApplePaySession)try{if(!this.isApplePayAvailable())return;null===(e=null===(t=this.options.events)||void 0===t?void 0:t.onApplePayAvailable)||void 0===e||e.call(t),this.element.innerHTML='<apple-pay-button buttonstyle="black" type="buy" locale="en-GB"></apple-pay-button>',null===(n=this.storeInstrumentCheckbox)||void 0===n||n.mount(this.selector);const i=this.element.querySelector("apple-pay-button");null==i||i.setAttribute("style","width: 100%;"),null==i||i.addEventListener("click",(()=>{this.createApplePaySession()}))}catch(t){}}createApplePaySession(){const t=this.execution.applePayConfig,{countryCode:e,supportedNetworks:n,merchantCapabilities:i}=t,{amount:o}=this.sdkConfig;try{const t={countryCode:e,currencyCode:o.currency,merchantCapabilities:i,supportedNetworks:n,total:{label:"",type:"final",amount:o.value}},s=new ApplePaySession(3,t);return s.onvalidatemerchant=async t=>{const{res:e}=await this.paymentExecutor.createApplePaySession({requestUrl:this.execution.createSessionLink,sessionUrl:t.validationURL,clientDomain:this.options.clientDomain}),n=e.data.data;s.completeMerchantValidation(n)},s.onpaymentauthorized=async t=>{var e,n,i,o,a,r,l,d,u,c,h,v;try{const c=await this.onApplePayAuthorized(t.payment.token);if("authorizeSuccessful"===(null===(e=null==c?void 0:c.finalState)||void 0===e?void 0:e.code))(null===(n=this.options.events)||void 0===n?void 0:n.onAuthorizeSuccess)&&this.options.events.onAuthorizeSuccess();else s.completePayment(ApplePaySession.STATUS_FAILURE),(null===(o=null===(i=this.options)||void 0===i?void 0:i.events)||void 0===o?void 0:o.onAuthorizeFailed)&&(null===(a=this.options)||void 0===a||a.events.onAuthorizeFailed());s.completePayment(ApplePaySession.STATUS_SUCCESS),(null===(l=null===(r=this.options)||void 0===r?void 0:r.events)||void 0===l?void 0:l.onAuthorizeSuccess)&&(null===(u=null===(d=this.options)||void 0===d?void 0:d.events)||void 0===u||u.onAuthorizeSuccess(c))}catch(t){s.completePayment(ApplePaySession.STATUS_FAILURE),(null===(h=null===(c=this.options)||void 0===c?void 0:c.events)||void 0===h?void 0:h.onAuthorizeFailed)&&(null===(v=this.options)||void 0===v||v.events.onAuthorizeFailed(t))}},s.begin(),s}catch(t){return null}}async onApplePayAuthorized(t){const e={paymentData:t.paymentData,transactionIdentifier:t.transactionIdentifier,paymentNetwork:t.paymentMethod.network,paymentInstrumentName:t.paymentMethod.displayName},n=[{paymentMethodCode:"applePay",integrationType:"api",paymentInstrumentData:{paymentToken:JSON.stringify(e)},amount:this.sdkConfig.amount,storeInstrument:this.shouldStoreInstrument}];return await this.paymentExecutor.pay(n)}}const{CARD_NUMBER:P,CVV:x,CARDHOLDER_NAME:I,EXPIRATION_MONTH:S,EXPIRATION_YEAR:O}=exports.ElementType,_={base:{border:"none",padding:"10px 16px",color:"#1d1d1d",backgroundColor:"#fff"},invalid:{backgroundColor:"#f9e1e1",borderColor:"#f25226",border:"1px solid"}},T=[{type:I,placeholder:"Card holder",styles:Object.assign(Object.assign({},_),{base:Object.assign(Object.assign({},_.base),{border:"1px solid #eae8ee",padding:"10px 16px",borderTopLeftRadius:"4px",borderTopRightRadius:"4px"})})},{type:P,placeholder:"1234 1234 1234 1234",styles:Object.assign(Object.assign({},_),{base:Object.assign(Object.assign({},_.base),{border:"1px solid #eae8ee",padding:"10px 16px",borderTopLeftRadius:"4px",borderTopRightRadius:"4px",textIndent:"0"}),cardIcon:{position:"absolute",right:"8px",height:"24px",bottom:"calc(50% - 12px)"}})},{type:S,placeholder:"MM",styles:Object.assign(Object.assign({},_),{base:Object.assign(Object.assign({},_.base),{borderBottom:"1px solid #eae8ee",borderLeft:"1px solid #eae8ee",borderRight:"1px solid #eae8ee",borderBottomLeftRadius:"4px"})})},{type:O,placeholder:"YY",format:"YY",styles:Object.assign(Object.assign({},_),{base:Object.assign(Object.assign({},_.base),{borderBottom:"1px solid #eae8ee",borderRight:"1px solid #eae8ee"})})},{type:x,placeholder:"CVC",styles:Object.assign(Object.assign({},_),{base:Object.assign(Object.assign({},_.base),{borderBottom:"1px solid #eae8ee",borderRight:"1px solid #eae8ee",borderBottomRightRadius:"4px"})})}];class R extends k{get bin(){return this.collectContainer.bin}constructor(t,e){var n,i,o,s,a;super("div",Object.assign(Object.assign({},e),{translations:Object.assign(Object.assign({},null==e?void 0:e.translations),{labels:Object.assign(Object.assign({},null===(n=null==e?void 0:e.translations)||void 0===n?void 0:n.labels),{saveInstrument:null===(o=null===(i=null==e?void 0:e.translations)||void 0===i?void 0:i.labels)||void 0===o?void 0:o.saveCreditCard})}),styles:Object.assign({storeInstrumentCheckbox:null===(s=null==e?void 0:e.styles)||void 0===s?void 0:s.storeCardCheckbox},null==e?void 0:e.styles),id:"payrails-card-form"})),this.collectContainer=t,this.options=e,this.formFields=[],(null===(a=null==e?void 0:e.styles)||void 0===a?void 0:a.storeCardCheckbox)&&console.warn("The `storeCardCheckbox` option for styles is deprecated. Please use `storeInstrumentCheckbox` instead."),T.forEach((({type:t,styles:n,format:i,placeholder:o})=>{var s,a,r,l,d,u,c;if(!(null===(s=this.options)||void 0===s?void 0:s.showCardHolderName)&&t===exports.ElementType.CARDHOLDER_NAME)return;const h=new L(this.collectContainer,{type:t,label:null===(r=null===(a=null==e?void 0:e.translations)||void 0===a?void 0:a.labels)||void 0===r?void 0:r[t],placeholder:(null===(d=null===(l=null==e?void 0:e.translations)||void 0===l?void 0:l.placeholders)||void 0===d?void 0:d[t])||o,labelStyles:this.prepareLabelStyles(t),inputStyles:this.prepareInputStyles(n,t),format:i,events:{onFocus:null===(c=null===(u=this.options)||void 0===u?void 0:u.events)||void 0===c?void 0:c.onFocus,onChange:this.onChange.bind(this)}});this.formFields.push(h)})),this.subElements.push(this.collectContainer),this.storeInstrumentCheckbox&&this.subElements.push(this.storeInstrumentCheckbox)}show(){this.element.style.display="flex"}hide(){this.element.style.display="none"}prepareLabelStyles(t){return["base"].reduce(((e,n)=>{var i,o,s,a,r,l,d,u;return e[n]=Object.assign(Object.assign(Object.assign({},null===(o=null===(i=this.options)||void 0===i?void 0:i.styles)||void 0===o?void 0:o.base),null===(r=null===(a=null===(s=this.options)||void 0===s?void 0:s.styles)||void 0===a?void 0:a.labels)||void 0===r?void 0:r.all),null===(u=null===(d=null===(l=this.options)||void 0===l?void 0:l.styles)||void 0===d?void 0:d.labels)||void 0===u?void 0:u[t]),e}),{})}prepareInputStyles(t,e){var n;let i=JSON.parse(JSON.stringify(t));return(null===(n=this.options)||void 0===n?void 0:n.showCardHolderName)&&e===exports.ElementType.CARD_NUMBER&&(this.element.setAttribute("class","with-card-holder"),i=Object.assign(Object.assign({},t),{base:Object.assign(Object.assign({},_.base),{border:"1px solid #eae8ee",borderTop:"none",padding:"10px 16px",textIndent:"0"})})),["base","complete","empty","focus","invalid","cardIcon","copyIcon"].forEach((t=>{var n,o,s,a,r,l,d,u;i[t]=Object.assign(Object.assign(Object.assign({},i[t]),null===(a=null===(s=null===(o=null===(n=this.options)||void 0===n?void 0:n.styles)||void 0===o?void 0:o.inputFields)||void 0===s?void 0:s.all)||void 0===a?void 0:a[t]),null===(u=null===(d=null===(l=null===(r=this.options)||void 0===r?void 0:r.styles)||void 0===l?void 0:l.inputFields)||void 0===d?void 0:d[e])||void 0===u?void 0:u[t])})),i}get isValid(){return this.formFields.reduce(((t,e)=>t&&e.isValid),!0)}get cardNetwork(){var t,e;return null!==(e=null===(t=this.formFields.find((t=>Boolean(t.cardNetwork))))||void 0===t?void 0:t.cardNetwork)&&void 0!==e?e:""}onChange(){var t,e,n,i;(null===(e=null===(t=this.options)||void 0===t?void 0:t.events)||void 0===e?void 0:e.onChange)&&(null===(i=null===(n=this.options)||void 0===n?void 0:n.events)||void 0===i||i.onChange({isValid:this.isValid,cardNetwork:this.cardNetwork,bin:this.bin}))}async collectValues(){var t;return{tokenizedCardData:await this.collectContainer.collect(),storeInstrument:this.shouldStoreInstrument,enrollInstrumentToNetworkOffers:Boolean(null===(t=this.options)||void 0===t?void 0:t.enrollInstrumentToNetworkOffers)}}}class L{constructor(t,e){this.isValid=!1,this.cardNetwork="";const{events:n}=e,i=t.createCollectElement(e);(null==n?void 0:n.onFocus)&&i.on("FOCUS",n.onFocus),i.on("CHANGE",(t=>{const{isEmpty:e,isValid:i,network:o}=t;this.isValid=!e&&i,this.cardNetwork=null!=o?o:"",(null==n?void 0:n.onChange)&&n.onChange(this)}))}}class B extends f{constructor(t,e){super("div",{id:"payrails-card-list"}),this.workflowExecution=t,this.listItems=[],this.workflowExecution.savedCreditCards.forEach((t=>{const n=new F((()=>{(null==e?void 0:e.onCardChange)&&e.onCardChange(t)}),t);this.listItems.push(n),this.subElements.push(n)}))}reset(){this.element.querySelectorAll("input").forEach((t=>t.checked=!1))}}class F extends f{constructor(t,e){super("div",{className:"payrails-card-list-item",id:`payrails-card-list-item-${e.id}`});const{id:n}=e,i=this.createCardLabel(e),o=document.createElement("label");o.setAttribute("for",n),o.addEventListener("click",t);const s=document.createElement("input");s.setAttribute("type","radio"),s.setAttribute("name","payment-option"),s.setAttribute("id",n),s.setAttribute("value",n),o.appendChild(s);const a=document.createElement("span");a.innerText=i,o.appendChild(a),this.element.appendChild(o)}createCardLabel({data:t={}}){return`****${null==t?void 0:t.suffix}`}}class j extends f{constructor(t="Authorization failed, please try again."){super("div",{id:"authorization-failed-message"}),this.element.innerText=t,this.element.innerHTML=`\n <div>\n <svg class="checkmark-cross" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">\n <circle class="checkmark-cross_circle" cx="26" cy="26" r="25" fill="none"/>\n <path class="checkmark-cross_check" fill="none" d="M14.1 14.1l23.8 23.8 m0,-23.8 l-23.8,23.8"/>\n </svg>\n </div>\n <div>${t}</div>`,this.element.addEventListener("click",(t=>{t.preventDefault(),t.stopImmediatePropagation(),t.stopPropagation(),this.unmount()}))}}class z extends f{constructor(t){var e;super("div",{id:"payrails-authorization-success-msg"}),this.element.innerHTML=`\n <div class="checkmark-wrapper">\n <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">\n <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none"/>\n <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/>\n </svg>\n </div>\n <div id="payrails-authorization-success">${(null===(e=null==t?void 0:t.translations)||void 0===e?void 0:e.label)||"Payment successful"}</div`}}class N extends f{constructor(t,e,n){super("div",{id:t,className:"payrails-dropin-item"}),this.events=n,this.isActive=!1;const i=`payrails-dropin-item-${t}`,o=document.createElement("label");o.setAttribute("for",i);const s=document.createElement("input");s.setAttribute("type","radio"),s.setAttribute("name","payment-option"),s.setAttribute("id",i),s.setAttribute("value",i),this.input=s,o.appendChild(s),this.label=o;const a=document.createElement("span");o.appendChild(a),a.innerText=e,this.element.appendChild(o)}get identifier(){return`payrails-dropin-item-${this.id}`}deactivate(){var t,e;this.isActive&&(this.isActive=!1,this.label.style.marginBottom="0",null===(t=this.component)||void 0===t||t.unmount(),(null===(e=this.events)||void 0===e?void 0:e.onDeactivate)&&this.events.onDeactivate())}activate(){var t,e;this.isActive||(null===(t=this.component)||void 0===t||t.mount(this.selector),this.label.style.marginBottom="8px",this.isActive=!0,(null===(e=this.events)||void 0===e?void 0:e.onActivate)&&this.events.onActivate())}}class D extends N{constructor(){super(...arguments),this.buttonShown=!1}activate(){if(!this.buttonShown)return super.activate(),void(this.buttonShown=!0);this.label.style.marginBottom="8px",this.isActive=!0,this.element.querySelector(this.component.selector).style.display="block"}deactivate(){this.isActive&&(this.isActive=!1,this.label.style.marginBottom="0",this.element.querySelector(this.component.selector).style.display="none")}mountAfterAvailable(){super.mount(`#${this.loadElementId}`)}mount(t){const e=document.querySelector(t);if(!e)throw new Error(`Element with selector "${t}" not found in in the DOM`);const n=document.createElement("div");n.setAttribute("id",this.loadElementId),n.setAttribute("style","width: 100%;"),e.appendChild(n)}unmount(){var t;super.unmount(),null===(t=document.querySelector(`#${this.loadElementId}`))||void 0===t||t.remove()}}class M extends D{constructor(t,e,n){var i,o;super("apple-pay-dropin",(null===(o=null===(i=n.translations)||void 0===i?void 0:i.labels)||void 0===o?void 0:o.label)||"Apple Pay"),this.loadElementId="apple-pay-dropin-load-element",this.component=new E(t,e,Object.assign(Object.assign({},n),{events:{onApplePayAvailable:()=>{this.mountAfterAvailable()}}}))}mount(t){const e=document.querySelector(t);if(!e)throw new Error(`Element with selector "${t}" not found in in the DOM`);const n=document.createElement("div");n.setAttribute("id",this.loadElementId),n.setAttribute("style","width: 100%;"),e.appendChild(n)}}class U extends N{constructor(t,e){super("payrails-credit-card-wrapper","Card"),this.cardForm=t,this.paymentButton=e,this.cardFormShown=!1,this.component=new $(t,e)}activate(){var t,e;this.label.style.marginBottom="8px",this.cardFormShown||(this.cardFormShown=!0,null===(t=this.component)||void 0===t||t.mount(this.selector)),this.isActive||(this.paymentButton.selectedInstrument=null,this.paymentButton.mount(this.selector),this.paymentButton.setDisabled(!this.cardForm.isValid),this.paymentButton.mount("#payrails-card-form"),this.input.checked=!0,this.cardForm.show(),this.isActive=!0,(null===(e=this.events)||void 0===e?void 0:e.onActivate)&&this.events.onActivate())}deactivate(){var t;this.isActive&&(this.label.style.marginBottom="0",this.paymentButton.unmount(),this.cardForm.hide(),this.isActive=!1,(null===(t=this.events)||void 0===t?void 0:t.onDeactivate)&&this.events.onDeactivate())}}class $ extends f{constructor(t,e){super("div",{id:"payrails-form-container"}),this.subElements.push(t,e)}}const V={apiVersion:2,apiVersionMinor:0};class H extends k{constructor(t,e,n){super("div",Object.assign(Object.assign({},n),{id:"payrails-google-pay-button"})),this.sdkConfig=t,this.execution=e,this.options=n,this.googleButton=null,this.paymentExecutor=new p(t,e),this.loadScript=new w((async()=>{const t=document.createElement("script");return t.src="https://pay.google.com/gp/p/js/pay.js",new Promise(((e,n)=>{t.onload=()=>{const t=new google.payments.api.PaymentsClient({environment:this.options.environment||"TEST"}),i=Object.assign(Object.assign({},V),{allowedPaymentMethods:this.execution.googlePayConfig});t.isReadyToPay(i).then((i=>{var o,s,a;i?(null===(a=null===(s=null===(o=this.options)||void 0===o?void 0:o.events)||void 0===s?void 0:s.onGooglePayAvailable)||void 0===a||a.call(s),e(t)):n()}),n)},t.onerror=()=>{n()},document.body.appendChild(t)}))}))}async sdkLoaded(t){var e,n,i,o,s,a,r,l;try{const d=(null===(n=null===(e=this.options)||void 0===e?void 0:e.styles)||void 0===n?void 0:n.buttonColor)||"black",u=(null===(o=null===(i=this.options)||void 0===i?void 0:i.styles)||void 0===o?void 0:o.buttonType)||"long",c=(null===(a=null===(s=this.options)||void 0===s?void 0:s.styles)||void 0===a?void 0:a.buttonSizeMode)||"fill",h=(null===(l=null===(r=this.options)||void 0===r?void 0:r.styles)||void 0===l?void 0:l.buttonLocale)||void 0;return this.googleButton=t.createButton({buttonColor:d,buttonType:u,buttonSizeMode:c,buttonLocale:h,onClick:async()=>{var t,e,n;if(null===(e=null===(t=this.options)||void 0===t?void 0:t.events)||void 0===e?void 0:e.onPaymentButtonClicked){if(!await(null===(n=this.options)||void 0===n?void 0:n.events.onPaymentButtonClicked()))return}await this.onPaymentButtonClicked()},allowedPaymentMethods:this.execution.googlePayConfig}),this.element.appendChild(this.googleButton),this.googleButton}catch(t){throw console.error("Google pay can not be initialized",t),new Error(t.message)}}async onLoadPaymentData(t){var e,n,i,o;const s=[{paymentMethodCode:"googlePay",integrationType:"api",paymentInstrumentData:{paymentToken:t.paymentMethodData.tokenizationData.token},amount:this.sdkConfig.amount,storeInstrument:this.shouldStoreInstrument}],a=await this.paymentExecutor.pay(s);(null===(n=null===(e=this.options)||void 0===e?void 0:e.events)||void 0===n?void 0:n.onAuthorizeSuccess)&&(null===(o=null===(i=this.options)||void 0===i?void 0:i.events)||void 0===o||o.onAuthorizeSuccess(a))}async onPaymentButtonClicked(){var t,e,n,i,o;const s=Object.assign({},V);s.allowedPaymentMethods=this.execution.googlePayConfig,s.transactionInfo={totalPriceStatus:"FINAL",totalPrice:null===(t=this.sdkConfig.amount)||void 0===t?void 0:t.value,currencyCode:null===(e=this.sdkConfig.amount)||void 0===e?void 0:e.currency,countryCode:null===(o=null===(i=null===(n=this.execution.meta)||void 0===n?void 0:n.customer)||void 0===i?void 0:i.country)||void 0===o?void 0:o.code};(await this.loadScript.loader).loadPaymentData(s).then((t=>{this.onLoadPaymentData(t)})).catch((t=>{var e,n,i;(null===(n=null===(e=this.options)||void 0===e?void 0:e.events)||void 0===n?void 0:n.onAuthorizeFailed)&&(null===(i=this.options)||void 0===i||i.events.onAuthorizeFailed(t))}))}mount(t){super.mount(t),(async()=>{var t;try{const e=await this.loadScript.loader,n=await this.sdkLoaded(e);this.element.appendChild(n),null===(t=this.storeInstrumentCheckbox)||void 0===t||t.mount(this.selector)}catch(t){}})()}unmount(){var t,e,n;null===(e=null===(t=this.googleButton)||void 0===t?void 0:t.parentElement)||void 0===e||e.removeChild(this.googleButton),null===(n=this.storeInstrumentCheckbox)||void 0===n||n.unmount(),super.unmount()}}class G extends D{constructor(t,e,n){var i,o;super("google-pay-dropin",(null===(o=null===(i=n.translations)||void 0===i?void 0:i.labels)||void 0===o?void 0:o.label)||"Google Pay"),this.loadElementId="google-pay-dropin-load-element",this.component=new H(t,e,Object.assign(Object.assign({},n),{events:Object.assign(Object.assign({},n.events),{onGooglePayAvailable:()=>{this.mountAfterAvailable()}})}))}mount(t){const e=document.querySelector(t);if(!e)throw new Error(`Element with selector "${t}" not found in in the DOM`);const n=document.createElement("div");n.setAttribute("id",this.loadElementId),n.setAttribute("style","width: 100%;"),e.appendChild(n)}}
1
+ !function(){"use strict";var t;let e;exports.ElementType=void 0,(t=exports.ElementType||(exports.ElementType={})).CARD_NUMBER="CARD_NUMBER",t.CARDHOLDER_NAME="CARDHOLDER_NAME",t.CVV="CVV",t.EXPIRATION_MONTH="EXPIRATION_MONTH",t.EXPIRATION_YEAR="EXPIRATION_YEAR";const n=new Uint8Array(16);function i(){if(!e&&(e="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!e))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return e(n)}const o=[];for(let t=0;t<256;++t)o.push((t+256).toString(16).slice(1));var s,a={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function r(t,e,n){if(a.randomUUID&&!e&&!t)return a.randomUUID();const s=(t=t||{}).random||(t.rng||i)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e){n=n||0;for(let t=0;t<16;++t)e[n+t]=s[t];return e}return function(t,e=0){return(o[t[e+0]]+o[t[e+1]]+o[t[e+2]]+o[t[e+3]]+"-"+o[t[e+4]]+o[t[e+5]]+"-"+o[t[e+6]]+o[t[e+7]]+"-"+o[t[e+8]]+o[t[e+9]]+"-"+o[t[e+10]]+o[t[e+11]]+o[t[e+12]]+o[t[e+13]]+o[t[e+14]]+o[t[e+15]]).toLowerCase()}(s)}!function(t){t.GET="GET",t.POST="POST"}(s||(s={}));const l=async({url:t,method:e=s.GET,token:n,body:i})=>{const o={method:e,headers:Object.assign(Object.assign(Object.assign({},h()),c(n)),v())};e===s.POST&&(o.body=JSON.stringify(i||{}));const a=await fetch(t,o),r=await a.json();if([401,403].includes(a.status))throw new d(t,e);if(!a.ok)throw new u(t,e,r);return{ok:a.ok,req:Object.assign({url:t},o),res:r}};class d extends Error{constructor(t,e){super(`[${e}] ${t} unauthorized`)}}class u extends Error{constructor(t,e,n){super(`[${e}] ${t} unsuccessful`),this.res=n}}const c=t=>({authorization:`Bearer ${t}`}),h=()=>({"x-idempotency-key":r()}),v=()=>({"x-client-version":"2.7.7","x-client-type":"web-sdk"});class p{constructor(t,e,n){this.sdkConfig=t,this.execution=e,this.returnLinks=n}async pay(t){const e=(await this.authorize(t)).res.links.execution;return await this.pollForAuthorizationResult(e)}async authorize(t){if(!this.execution.authorizeLink||!this.sdkConfig.amount)throw new Error("SDK was not initialized with workflow execution");const{success:e="https://payrails.io/success",error:n="https://payrails.io/error",cancel:i="https://payrails.io/cancel"}=this.returnLinks||{};return l({url:this.execution.authorizeLink,method:s.POST,token:this.sdkConfig.token,body:{amount:this.sdkConfig.amount,paymentComposition:t,returnInfo:{success:e,cancel:i,error:n}}})}async confirm(t,e={}){const n=await l({url:t,method:s.POST,token:this.sdkConfig.token,body:{data:e}}),i=await this.pollForAuthorizationResult(n.res.links.execution);if(i.finalState)return i;const o=i.response.status.slice().sort(((t,e)=>new Date(e.time).getTime()-new Date(t.time).getTime()))[0].time,{res:a}=await this.getExecution(n.res.links.execution,void 0,o);return{finalState:a.status.find((({code:t,time:e})=>["authorizeSuccessful","authorizeFailed"].includes(t)&&new Date(e)>new Date(o))),response:a}}async pollForAuthorizationResult(t,e=0){const n=(await this.getExecution(t)).res,i=n.status,o=["authorizePending","authorizeSuccessful","authorizeFailed"],s=i.find((({code:t})=>"authorizeRequested"===t));if(!s&&e<10)return await new Promise((t=>setTimeout(t,300))),this.pollForAuthorizationResult(t,e+1);if(!s)throw new Error("Authorization was not requested");const a=i.find((({code:t,time:e})=>"confirmRequested"===t&&new Date(e)>new Date(s.time))),r=a?a.time:s.time;let l=i.find((({code:t,time:e})=>o.includes(t)&&new Date(e)>new Date(r)));if(!l){const{res:e}=await this.getExecution(t,void 0,r);return l=e.status.find((({code:t,time:e})=>o.includes(t)&&new Date(e)>new Date(r))),{finalState:l,response:e}}return{finalState:l,response:n}}async getExecution(t,e,n){const i=new URLSearchParams;e&&e.length>0&&i.append("waitWhile[status]",`[${e.map((t=>`"${t}"`)).join(",")}]`),n&&i.append("waitWhile[lastStatusTime]",n);const o=`${t}${i.toString()?"?":""}${i.toString()}`;return l({url:o,token:this.sdkConfig.token})}async createApplePaySession(t){return l({url:t.requestUrl,method:s.POST,token:this.sdkConfig.token,body:{integrationType:"api",paymentMethodCode:"applePay",amount:this.sdkConfig.amount,meta:{sessionURL:t.sessionUrl,clientDomain:t.clientDomain||window.location.host}}})}}var m,y,g;!function(t){t.CARD="card",t.GOOGLE_PAY="googlePay",t.PAYPAL="payPal",t.APPLE_PAY="applePay"}(m||(m={})),function(t){t.ENABLED="enabled",t.CREATED="created"}(y||(y={}));class b{constructor(t){this.executionResponse=t}get lookup(){return this.executionResponse.initialResults.find((({body:{name:t}})=>"lookup"===t))}get holderReference(){return this.executionResponse.holderReference}get savedCreditCards(){return this.getStoredInstrumentForPaymentMethod(m.CARD)}get savedPaypalAccounts(){return this.getStoredInstrumentForPaymentMethod(m.PAYPAL)}get savedGooglePayAccounts(){return this.getStoredInstrumentForPaymentMethod(m.GOOGLE_PAY)}get savedApplePayAccounts(){return this.getStoredInstrumentForPaymentMethod(m.APPLE_PAY)}get paypalConfig(){const t=this.availablePaymentMethods.find((({paymentMethodCode:t})=>t===m.PAYPAL));if(!t)throw new Error("trying to initialize paypal without config");return t.config||{}}get googlePayConfig(){const t=this.availablePaymentMethods.find((({paymentMethodCode:t})=>t===m.GOOGLE_PAY));if(!t)throw new Error("trying to initialize google pay without config");return t?[t.config]:[]}get applePayConfig(){const t=this.availablePaymentMethods.find((({paymentMethodCode:t})=>t===m.APPLE_PAY));if(!t)throw new Error("apple pay config not found");return t.config.parameters}get url(){return this.response.links.self}get response(){return this.executionResponse}get meta(){return this.executionResponse.meta}get availablePaymentMethods(){var t;return(null===(t=this.lookup)||void 0===t?void 0:t.body.data.paymentCompositionOptions)||[]}get authorizeLink(){var t;return null===(t=this.lookup)||void 0===t?void 0:t.body.links.authorize.href}get createSessionLink(){return this.response.links.startPaymentSession.href}get storedPaymentInstruments(){return this.availablePaymentMethods.flatMap((t=>t.paymentInstruments||[]))}getStoredInstrumentForPaymentMethod(t){var e;return(null===(e=this.availablePaymentMethods.find((({paymentMethodCode:e})=>e===t)))||void 0===e?void 0:e.paymentInstruments)||[]}}class f{constructor(t,{id:e="",className:n=""}={}){this.subElements=[];const i=document.createElement(t);e&&(this.id=e,i.setAttribute("id",e)),n&&i.setAttribute("class",n),this.element=i}get parentElement(){return this.element.parentElement}get selector(){if(!this.id)throw new Error("Element id is not set");return`#${this.id}`}mount(t){const e=document.querySelector(t);if(!e)throw new Error(`Element with selector "${t}" not found in in the DOM`);e.appendChild(this.element),this.subElements.forEach((t=>{if(!this.id)throw new Error("Sub elements can not be rendered, please set id for the element");t.mount(this.selector)}))}unmount(){var t;this.subElements.forEach((t=>t.unmount())),null===(t=this.parentElement)||void 0===t||t.removeChild(this.element)}}class C extends f{get bin(){var t;return this.selectedInstrument?this.selectedInstrument.data.bin?this.selectedInstrument.data.bin:"":(null===(t=this.cardForm)||void 0===t?void 0:t.bin)||""}constructor(t,e,n,i){var o;super("button",{id:"payrails-card-payment-button"}),this.sdkConfig=t,this.execution=e,this.options=n,this.returnLinks=i,this.selectedInstrument=null,this.element.innerText=(null===(o=null==n?void 0:n.translations)||void 0===o?void 0:o.label)||"Pay",this.element.addEventListener("click",this.onPay.bind(this)),this.element.addEventListener("mouseenter",(()=>{var t;this.element.classList.contains("disabled")||(this.element.classList.add("hover"),this.setStyles((null===(t=this.options.styles)||void 0===t?void 0:t.hover)||{}))})),this.element.addEventListener("mouseleave",(()=>{var t;this.element.classList.contains("disabled")||(this.element.classList.remove("hover"),this.removeStyles((null===(t=this.options.styles)||void 0===t?void 0:t.hover)||{}))})),this.paymentExecutor=new p(this.sdkConfig,this.execution,this.returnLinks)}setDisabled(t){var e,n,i,o,s;this.element.classList.contains("disabled")!==t&&(null===(n=null===(e=this.options.events)||void 0===e?void 0:e.onStateChanged)||void 0===n||n.call(e,t?"disabled":"enabled")),this.element.disabled=t,t?(this.element.classList.add("disabled"),(null===(i=this.options.styles)||void 0===i?void 0:i.disabled)&&this.setStyles(this.options.styles.disabled)):(this.element.classList.remove("disabled"),this.removeStyles((null===(o=this.options.styles)||void 0===o?void 0:o.disabled)||{}),(null===(s=this.options.styles)||void 0===s?void 0:s.base)&&this.setStyles(this.options.styles.base))}setSavedCreditCard(t){console.warn("setSavedCreditCard is deprecated, please use setSavedInstrument"),this.setSavedInstrument(t)}setSavedInstrument(t){this.selectedInstrument=t,this.setDisabled(!1)}setStyles(t){var e;const n=Object.assign(Object.assign({},null===(e=this.options.styles)||void 0===e?void 0:e.base),t);Object.keys(n).forEach((t=>{this.element.style[t]=n[t]}))}removeStyles(t){var e;const n=Object.keys((null===(e=this.options.styles)||void 0===e?void 0:e.base)||{});Object.keys(t).forEach((t=>{var e,i;n.includes(t)?this.element.style[t]=null===(i=null===(e=this.options.styles)||void 0===e?void 0:e.base)||void 0===i?void 0:i[t]:this.element.style[t]=""}))}setLabel(t){this.element.innerText=t}setCardForm(t){this.cardForm=t}triggerLoading(t){var e,n,i,o;const s=this.element.offsetWidth;this.element.style.minWidth=`${s}px`,t?(this.element.innerHTML='<div class="dot-flashing"></div>',this.element.classList.add("loading"),(null===(e=this.options.styles)||void 0===e?void 0:e.loading)&&this.setStyles(this.options.styles.loading)):(this.element.innerText=(null===(i=null===(n=this.options)||void 0===n?void 0:n.translations)||void 0===i?void 0:i.label)||"Pay",this.element.classList.remove("loading"),this.removeStyles((null===(o=this.options.styles)||void 0===o?void 0:o.loading)||{}))}onAuthorizationFailed(t){var e,n;this.setDisabled(!1),this.triggerLoading(!1),(null===(e=this.options.events)||void 0===e?void 0:e.onAuthorizeFailed)&&(null===(n=this.options.events)||void 0===n||n.onAuthorizeFailed(t))}async onPay(){var t,e,n,i,o,s,a,r,l,u;if(this.setDisabled(!0),this.triggerLoading(!0),null===(t=this.options.events)||void 0===t?void 0:t.onPaymentButtonClicked)try{if(!1===await(null===(e=this.options.events)||void 0===e?void 0:e.onPaymentButtonClicked({bin:this.bin||""})))return void this.onAuthorizationFailed({code:exports.AuthorizationFailureReasons.VALIDATION_FAILED,message:"Callback passed to onPaymentButtonClicked resolved to false"})}catch(t){return void this.onAuthorizationFailed({code:exports.AuthorizationFailureReasons.VALIDATION_FAILED,message:"Callback passed to onPaymentButtonClicked threw an error"})}try{const t=[{paymentMethodCode:m.CARD,integrationType:"api",amount:this.sdkConfig.amount,storeInstrument:!1}];if(null===(n=this.selectedInstrument)||void 0===n?void 0:n.id)t[0].paymentInstrumentId=null===(i=this.selectedInstrument)||void 0===i?void 0:i.id,t[0].paymentMethodCode=null===(o=this.selectedInstrument)||void 0===o?void 0:o.paymentMethod;else{const{tokenizedCardData:e,storeInstrument:n,enrollInstrumentToNetworkOffers:i}=await this.collectCardFormValues();t[0].paymentInstrumentData={vaultToken:null==e?void 0:e.instrumentId,card:{numberToken:null==e?void 0:e.card_number,securityCodeToken:null==e?void 0:e.security_code}},t[0].storeInstrument=n,t[0].enrollInstrumentToNetworkOffers=i}const e=await this.paymentExecutor.pay(t);this.handleAuthorizationResult(e)}catch(t){t instanceof d||[401,403].includes(null===(s=null==t?void 0:t.error)||void 0===s?void 0:s.code)?(null===(r=null===(a=this.options.events)||void 0===a?void 0:a.onPaymentSessionExpired)||void 0===r||r.call(a),this.onAuthorizationFailed({code:exports.AuthorizationFailureReasons.AUTHENTICATION_ERROR,message:"API token is not valid or expired."})):t.toString().includes("Invalid token")?(null===(u=null===(l=this.options.events)||void 0===l?void 0:l.onPaymentSessionExpired)||void 0===u||u.call(l),this.onAuthorizationFailed({code:exports.AuthorizationFailureReasons.AUTHENTICATION_ERROR,message:"Vault token is not valid or expired."})):this.onAuthorizationFailed({code:exports.AuthorizationFailureReasons.UNKNOWN_ERROR,message:t.toString(),rawError:t})}}handleAuthorizationResult(t){var e,n,i;switch(null===(e=null==t?void 0:t.finalState)||void 0===e?void 0:e.code){case"authorizeSuccessful":this.triggerLoading(!1),(null===(n=this.options.events)||void 0===n?void 0:n.onAuthorizeSuccess)&&this.options.events.onAuthorizeSuccess();break;case"authorizePending":"3ds"===(null===(i=null==t?void 0:t.response)||void 0===i?void 0:i.actionRequired)&&this.handle3ds(t);break;default:this.onAuthorizationFailed({code:exports.AuthorizationFailureReasons.AUTHORIZATION_ERROR,message:"Authorization failed."})}}handle3ds(t){var e,n,i,o;try{null===(n=null===(e=this.options.events)||void 0===e?void 0:e.onThreeDSecureChallenge)||void 0===n||n.call(e)}catch(t){}const s=null===(i=null==t?void 0:t.response)||void 0===i?void 0:i.links["3ds"];if(s){const t=[[250,400],[390,400],[500,600],[600,400]],e=screen.width,n=t.reduce(((t,n)=>e>n[0]?n:t),[250,400]),i=document.createElement("iframe");i.setAttribute("id","payrails-3ds-frame"),i.setAttribute("src",s),i.setAttribute("width",n[0].toString()),i.setAttribute("height",n[1].toString());const a=document.createElement("div");a.setAttribute("id","payrails-3ds-challenge"),a.appendChild(i);const r=document.createElement("div");r.addEventListener("click",(async()=>{r.remove()})),r.setAttribute("id","payrails-3ds-popup-background"),r.appendChild(a);const l=async t=>{var e,n,i;if(t.data&&'{"type":"3DS-challenge-completed"}'===t.data){window.removeEventListener("message",l),r.remove();if(!(await this.paymentExecutor.getExecution(this.execution.url)).res.status.find((({code:t})=>"authorizeSuccessful"===t))&&(null===(e=this.options.events)||void 0===e?void 0:e.onAuthorizeFailed))return void this.onAuthorizationFailed({code:exports.AuthorizationFailureReasons.AUTHORIZATION_ERROR,message:"Authorization failed after 3DS challenge."});if(null===(n=this.options.events)||void 0===n?void 0:n.onAuthorizeSuccess)return void(null===(i=this.options.events)||void 0===i||i.onAuthorizeSuccess())}};null===(o=document.querySelector("body"))||void 0===o||o.appendChild(r),window.addEventListener("message",l),a.style.width=`${n[0]+4}px`,a.style.height=`${n[1]+4}px`}}async collectCardFormValues(){if(!this.cardForm)throw new Error("Trying to collect values from non-existent card form");return await this.cardForm.collectValues()}}exports.AuthorizationFailureReasons=void 0,(g=exports.AuthorizationFailureReasons||(exports.AuthorizationFailureReasons={})).VALIDATION_FAILED="VALIDATION_FAILED",g.AUTHORIZATION_ERROR="AUTHORIZATION_ERROR",g.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",g.UNKNOWN_ERROR="UNKNOWN_ERROR";class w{constructor(t){this.loadFunction=t,this.loadScript()}get loader(){return this.loadingPromise||(this.loadingPromise=this.loadScript()),this.loadingPromise}async loadScript(){return this.loadingPromise||(this.loadingPromise=new Promise(((t,e)=>{this.loadFunction().then((e=>{e&&t(e)}),(()=>{e()})).catch((()=>{}))}))),this.loadingPromise}}class A extends f{constructor(t){super("span",{id:t.id,className:"payrails-store-instrument"}),this.options=t,this.createHTML(),this.applyStyles(),this.addListeners()}get isChecked(){var t;return!!(null===(t=this.element.querySelector("input"))||void 0===t?void 0:t.checked)}createHTML(){var t,e,n,i,o,s,a,r,l;const d=(null===(n=null===(e=null===(t=this.options)||void 0===t?void 0:t.translations)||void 0===e?void 0:e.labels)||void 0===n?void 0:n.saveInstrument)||(null===(s=null===(o=null===(i=this.options)||void 0===i?void 0:i.translations)||void 0===o?void 0:o.labels)||void 0===s?void 0:s.storeInstrument)||"Save instrument for future payments",u=`${this.id}-checkbox`;(null===(l=null===(r=null===(a=this.options)||void 0===a?void 0:a.translations)||void 0===r?void 0:r.labels)||void 0===l?void 0:l.saveInstrument)&&console.warn("The saveInstrument label is deprecated, please use storeInstrument instead"),this.element.innerHTML=`<label for="${u}"><input type="checkbox" id="${u}" name="${u}" class="payrails-store-instrument-checkbox">${d}</label>`}applyStyles(){var t,e;Object.keys((null===(e=null===(t=this.options)||void 0===t?void 0:t.styles)||void 0===e?void 0:e.storeInstrumentCheckbox)||{}).forEach((t=>{var e,n,i;this.element.style[t]=null===(i=null===(n=null===(e=this.options)||void 0===e?void 0:e.styles)||void 0===n?void 0:n.storeInstrumentCheckbox)||void 0===i?void 0:i[t]}))}addListeners(){this.element.addEventListener("change",(t=>{var e,n,i,o;(null===(n=null===(e=this.options)||void 0===e?void 0:e.events)||void 0===n?void 0:n.onSaveInstrumentCheckboxChanged)&&(null===(o=null===(i=this.options)||void 0===i?void 0:i.events)||void 0===o||o.onSaveInstrumentCheckboxChanged({checked:this.isChecked})),t.stopPropagation(),t.stopImmediatePropagation()}))}}class k extends f{constructor(t,e){var n,i;super(t,e),this.options=e,this.storeInstrumentCheckbox=null,(null===(n=this.options)||void 0===n?void 0:n.showStoreInstrumentCheckbox)&&(this.storeInstrumentCheckbox=new A(Object.assign(Object.assign({},e),{id:`${null===(i=this.options)||void 0===i?void 0:i.id}-store-instrument-checkbox`,events:{onSaveInstrumentCheckboxChanged:async t=>{var n,i;null===(i=null===(n=null==e?void 0:e.events)||void 0===n?void 0:n.onSaveInstrumentCheckboxChanged)||void 0===i||i.call(n,t)}}})),this.subElements.push(this.storeInstrumentCheckbox))}get shouldStoreInstrument(){var t,e;return(null===(t=this.storeInstrumentCheckbox)||void 0===t?void 0:t.isChecked)||(null===(e=this.options)||void 0===e?void 0:e.alwaysStoreInstrument)||!1}}class E extends k{constructor(t,e,n){super("div",Object.assign(Object.assign({},n),{id:"payrails-apple-pay-button"})),this.sdkConfig=t,this.execution=e,this.options=n,this.appleButton=null,this.paymentExecutor=new p(t,e),this.loadScript=new w((async()=>{const t=document.createElement("script");return t.src="https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js",new Promise(((e,n)=>{t.onload=async()=>{var t,n,i;await this.isApplePayAvailable()?(null===(i=null===(n=null===(t=this.options)||void 0===t?void 0:t.events)||void 0===n?void 0:n.onApplePayAvailable)||void 0===i||i.call(n),e(!0)):e(!1)},t.onerror=()=>{n()},document.body.appendChild(t)}))}))}mount(t){super.mount(t),(async()=>{try{await this.loadScript.loader,await this.mountApplePayButton()}catch(t){}})()}unmount(){var t,e;null===(e=null===(t=this.appleButton)||void 0===t?void 0:t.parentElement)||void 0===e||e.removeChild(this.appleButton),super.unmount()}async isApplePayAvailable(){if(!(null===window||void 0===window?void 0:window.ApplePaySession))return!1;return await ApplePaySession.canMakePayments()}async mountApplePayButton(){var t,e,n;if(null===window||void 0===window?void 0:window.ApplePaySession)try{if(!this.isApplePayAvailable())return;null===(e=null===(t=this.options.events)||void 0===t?void 0:t.onApplePayAvailable)||void 0===e||e.call(t),this.element.innerHTML='<apple-pay-button buttonstyle="black" type="buy" locale="en-GB"></apple-pay-button>',null===(n=this.storeInstrumentCheckbox)||void 0===n||n.mount(this.selector);const i=this.element.querySelector("apple-pay-button");null==i||i.setAttribute("style","width: 100%;"),null==i||i.addEventListener("click",(()=>{this.createApplePaySession()}))}catch(t){}}createApplePaySession(){const t=this.execution.applePayConfig,{countryCode:e,supportedNetworks:n,merchantCapabilities:i}=t,{amount:o}=this.sdkConfig;try{const t={countryCode:e,currencyCode:o.currency,merchantCapabilities:i,supportedNetworks:n,total:{label:"",type:"final",amount:o.value}},s=new ApplePaySession(3,t);return s.onvalidatemerchant=async t=>{const{res:e}=await this.paymentExecutor.createApplePaySession({requestUrl:this.execution.createSessionLink,sessionUrl:t.validationURL,clientDomain:this.options.clientDomain}),n=e.data.data;s.completeMerchantValidation(n)},s.onpaymentauthorized=async t=>{var e,n,i,o,a,r,l,d,u,c,h,v;try{const c=await this.onApplePayAuthorized(t.payment.token);if("authorizeSuccessful"===(null===(e=null==c?void 0:c.finalState)||void 0===e?void 0:e.code))(null===(n=this.options.events)||void 0===n?void 0:n.onAuthorizeSuccess)&&this.options.events.onAuthorizeSuccess();else s.completePayment(ApplePaySession.STATUS_FAILURE),(null===(o=null===(i=this.options)||void 0===i?void 0:i.events)||void 0===o?void 0:o.onAuthorizeFailed)&&(null===(a=this.options)||void 0===a||a.events.onAuthorizeFailed());s.completePayment(ApplePaySession.STATUS_SUCCESS),(null===(l=null===(r=this.options)||void 0===r?void 0:r.events)||void 0===l?void 0:l.onAuthorizeSuccess)&&(null===(u=null===(d=this.options)||void 0===d?void 0:d.events)||void 0===u||u.onAuthorizeSuccess(c))}catch(t){s.completePayment(ApplePaySession.STATUS_FAILURE),(null===(h=null===(c=this.options)||void 0===c?void 0:c.events)||void 0===h?void 0:h.onAuthorizeFailed)&&(null===(v=this.options)||void 0===v||v.events.onAuthorizeFailed(t))}},s.begin(),s}catch(t){return null}}async onApplePayAuthorized(t){const e={paymentData:t.paymentData,transactionIdentifier:t.transactionIdentifier,paymentNetwork:t.paymentMethod.network,paymentInstrumentName:t.paymentMethod.displayName},n=[{paymentMethodCode:"applePay",integrationType:"api",paymentInstrumentData:{paymentToken:JSON.stringify(e)},amount:this.sdkConfig.amount,storeInstrument:this.shouldStoreInstrument}];return await this.paymentExecutor.pay(n)}}const{CARD_NUMBER:P,CVV:x,CARDHOLDER_NAME:I,EXPIRATION_MONTH:S,EXPIRATION_YEAR:O}=exports.ElementType,_={base:{border:"none",padding:"10px 16px",color:"#1d1d1d",backgroundColor:"#fff"},invalid:{backgroundColor:"#f9e1e1",borderColor:"#f25226",border:"1px solid"}},T=[{type:I,placeholder:"Card holder",styles:Object.assign(Object.assign({},_),{base:Object.assign(Object.assign({},_.base),{border:"1px solid #eae8ee",padding:"10px 16px",borderTopLeftRadius:"4px",borderTopRightRadius:"4px"})})},{type:P,placeholder:"1234 1234 1234 1234",styles:Object.assign(Object.assign({},_),{base:Object.assign(Object.assign({},_.base),{border:"1px solid #eae8ee",padding:"10px 16px",borderTopLeftRadius:"4px",borderTopRightRadius:"4px",textIndent:"0"}),cardIcon:{position:"absolute",right:"8px",height:"24px",bottom:"calc(50% - 12px)"}})},{type:S,placeholder:"MM",styles:Object.assign(Object.assign({},_),{base:Object.assign(Object.assign({},_.base),{borderBottom:"1px solid #eae8ee",borderLeft:"1px solid #eae8ee",borderRight:"1px solid #eae8ee",borderBottomLeftRadius:"4px"})})},{type:O,placeholder:"YY",format:"YY",styles:Object.assign(Object.assign({},_),{base:Object.assign(Object.assign({},_.base),{borderBottom:"1px solid #eae8ee",borderRight:"1px solid #eae8ee"})})},{type:x,placeholder:"CVC",styles:Object.assign(Object.assign({},_),{base:Object.assign(Object.assign({},_.base),{borderBottom:"1px solid #eae8ee",borderRight:"1px solid #eae8ee",borderBottomRightRadius:"4px"})})}];class R extends k{get bin(){return this.collectContainer.bin}constructor(t,e){var n,i,o,s,a;super("div",Object.assign(Object.assign({},e),{translations:Object.assign(Object.assign({},null==e?void 0:e.translations),{labels:Object.assign(Object.assign({},null===(n=null==e?void 0:e.translations)||void 0===n?void 0:n.labels),{saveInstrument:null===(o=null===(i=null==e?void 0:e.translations)||void 0===i?void 0:i.labels)||void 0===o?void 0:o.saveCreditCard})}),styles:Object.assign({storeInstrumentCheckbox:null===(s=null==e?void 0:e.styles)||void 0===s?void 0:s.storeCardCheckbox},null==e?void 0:e.styles),id:"payrails-card-form"})),this.collectContainer=t,this.options=e,this.formFields=[],(null===(a=null==e?void 0:e.styles)||void 0===a?void 0:a.storeCardCheckbox)&&console.warn("The `storeCardCheckbox` option for styles is deprecated. Please use `storeInstrumentCheckbox` instead."),T.forEach((({type:t,styles:n,format:i,placeholder:o})=>{var s,a,r,l,d,u,c;if(!(null===(s=this.options)||void 0===s?void 0:s.showCardHolderName)&&t===exports.ElementType.CARDHOLDER_NAME)return;const h=new L(this.collectContainer,{type:t,label:null===(r=null===(a=null==e?void 0:e.translations)||void 0===a?void 0:a.labels)||void 0===r?void 0:r[t],placeholder:(null===(d=null===(l=null==e?void 0:e.translations)||void 0===l?void 0:l.placeholders)||void 0===d?void 0:d[t])||o,labelStyles:this.prepareLabelStyles(t),inputStyles:this.prepareInputStyles(n,t),format:i,events:{onFocus:null===(c=null===(u=this.options)||void 0===u?void 0:u.events)||void 0===c?void 0:c.onFocus,onChange:this.onChange.bind(this),onReady:this.triggerOnReady.bind(this)}});this.formFields.push(h)})),this.subElements.push(this.collectContainer),this.storeInstrumentCheckbox&&this.subElements.push(this.storeInstrumentCheckbox)}show(){this.element.style.display="flex"}hide(){this.element.style.display="none"}triggerOnReady(){var t,e,n;this.formFields.reduce(((t,e)=>t&&e.isReady),!0)&&(null===(n=null===(e=null===(t=this.options)||void 0===t?void 0:t.events)||void 0===e?void 0:e.onReady)||void 0===n||n.call(e))}prepareLabelStyles(t){return["base"].reduce(((e,n)=>{var i,o,s,a,r,l,d,u;return e[n]=Object.assign(Object.assign(Object.assign({},null===(o=null===(i=this.options)||void 0===i?void 0:i.styles)||void 0===o?void 0:o.base),null===(r=null===(a=null===(s=this.options)||void 0===s?void 0:s.styles)||void 0===a?void 0:a.labels)||void 0===r?void 0:r.all),null===(u=null===(d=null===(l=this.options)||void 0===l?void 0:l.styles)||void 0===d?void 0:d.labels)||void 0===u?void 0:u[t]),e}),{})}prepareInputStyles(t,e){var n;let i=JSON.parse(JSON.stringify(t));return(null===(n=this.options)||void 0===n?void 0:n.showCardHolderName)&&e===exports.ElementType.CARD_NUMBER&&(this.element.setAttribute("class","with-card-holder"),i=Object.assign(Object.assign({},t),{base:Object.assign(Object.assign({},_.base),{border:"1px solid #eae8ee",borderTop:"none",padding:"10px 16px",textIndent:"0"})})),["base","complete","empty","focus","invalid","cardIcon","copyIcon"].forEach((t=>{var n,o,s,a,r,l,d,u;i[t]=Object.assign(Object.assign(Object.assign({},i[t]),null===(a=null===(s=null===(o=null===(n=this.options)||void 0===n?void 0:n.styles)||void 0===o?void 0:o.inputFields)||void 0===s?void 0:s.all)||void 0===a?void 0:a[t]),null===(u=null===(d=null===(l=null===(r=this.options)||void 0===r?void 0:r.styles)||void 0===l?void 0:l.inputFields)||void 0===d?void 0:d[e])||void 0===u?void 0:u[t])})),i}get isValid(){return this.formFields.reduce(((t,e)=>t&&e.isValid),!0)}get cardNetwork(){var t,e;return null!==(e=null===(t=this.formFields.find((t=>Boolean(t.cardNetwork))))||void 0===t?void 0:t.cardNetwork)&&void 0!==e?e:""}onChange(){var t,e,n,i;(null===(e=null===(t=this.options)||void 0===t?void 0:t.events)||void 0===e?void 0:e.onChange)&&(null===(i=null===(n=this.options)||void 0===n?void 0:n.events)||void 0===i||i.onChange({isValid:this.isValid,cardNetwork:this.cardNetwork,bin:this.bin}))}async collectValues(){var t;return{tokenizedCardData:await this.collectContainer.collect(),storeInstrument:this.shouldStoreInstrument,enrollInstrumentToNetworkOffers:Boolean(null===(t=this.options)||void 0===t?void 0:t.enrollInstrumentToNetworkOffers)}}}class L{constructor(t,e){this.isValid=!1,this.isReady=!1,this.cardNetwork="";const{events:n}=e,i=t.createCollectElement(e);(null==n?void 0:n.onFocus)&&i.on("FOCUS",n.onFocus),i.on("READY",(()=>{var t,n;this.isReady=!0,null===(n=null===(t=e.events)||void 0===t?void 0:t.onReady)||void 0===n||n.call(t)})),i.on("CHANGE",(t=>{const{isEmpty:e,isValid:i,network:o}=t;this.isValid=!e&&i,this.cardNetwork=null!=o?o:"",(null==n?void 0:n.onChange)&&n.onChange(this)}))}}class B extends f{constructor(t,e){super("div",{id:"payrails-card-list"}),this.workflowExecution=t,this.listItems=[],this.workflowExecution.savedCreditCards.forEach((t=>{const n=new F((()=>{(null==e?void 0:e.onCardChange)&&e.onCardChange(t)}),t);this.listItems.push(n),this.subElements.push(n)}))}reset(){this.element.querySelectorAll("input").forEach((t=>t.checked=!1))}}class F extends f{constructor(t,e){super("div",{className:"payrails-card-list-item",id:`payrails-card-list-item-${e.id}`});const{id:n}=e,i=this.createCardLabel(e),o=document.createElement("label");o.setAttribute("for",n),o.addEventListener("click",t);const s=document.createElement("input");s.setAttribute("type","radio"),s.setAttribute("name","payment-option"),s.setAttribute("id",n),s.setAttribute("value",n),o.appendChild(s);const a=document.createElement("span");a.innerText=i,o.appendChild(a),this.element.appendChild(o)}createCardLabel({data:t={}}){return`****${null==t?void 0:t.suffix}`}}class j extends f{constructor(t="Authorization failed, please try again."){super("div",{id:"authorization-failed-message"}),this.element.innerText=t,this.element.innerHTML=`\n <div>\n <svg class="checkmark-cross" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">\n <circle class="checkmark-cross_circle" cx="26" cy="26" r="25" fill="none"/>\n <path class="checkmark-cross_check" fill="none" d="M14.1 14.1l23.8 23.8 m0,-23.8 l-23.8,23.8"/>\n </svg>\n </div>\n <div>${t}</div>`,this.element.addEventListener("click",(t=>{t.preventDefault(),t.stopImmediatePropagation(),t.stopPropagation(),this.unmount()}))}}class z extends f{constructor(t){var e;super("div",{id:"payrails-authorization-success-msg"}),this.element.innerHTML=`\n <div class="checkmark-wrapper">\n <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">\n <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none"/>\n <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/>\n </svg>\n </div>\n <div id="payrails-authorization-success">${(null===(e=null==t?void 0:t.translations)||void 0===e?void 0:e.label)||"Payment successful"}</div`}}class N extends f{constructor(t,e,n){super("div",{id:t,className:"payrails-dropin-item"}),this.events=n,this.isActive=!1;const i=`payrails-dropin-item-${t}`,o=document.createElement("label");o.setAttribute("for",i);const s=document.createElement("input");s.setAttribute("type","radio"),s.setAttribute("name","payment-option"),s.setAttribute("id",i),s.setAttribute("value",i),this.input=s,o.appendChild(s),this.label=o;const a=document.createElement("span");o.appendChild(a),a.innerText=e,this.element.appendChild(o)}get identifier(){return`payrails-dropin-item-${this.id}`}deactivate(){var t,e;this.isActive&&(this.isActive=!1,this.label.style.marginBottom="0",null===(t=this.component)||void 0===t||t.unmount(),(null===(e=this.events)||void 0===e?void 0:e.onDeactivate)&&this.events.onDeactivate())}activate(){var t,e;this.isActive||(null===(t=this.component)||void 0===t||t.mount(this.selector),this.label.style.marginBottom="8px",this.isActive=!0,(null===(e=this.events)||void 0===e?void 0:e.onActivate)&&this.events.onActivate())}}class D extends N{constructor(){super(...arguments),this.buttonShown=!1}activate(){if(!this.buttonShown)return super.activate(),void(this.buttonShown=!0);this.label.style.marginBottom="8px",this.isActive=!0,this.element.querySelector(this.component.selector).style.display="block"}deactivate(){this.isActive&&(this.isActive=!1,this.label.style.marginBottom="0",this.element.querySelector(this.component.selector).style.display="none")}mountAfterAvailable(){super.mount(`#${this.loadElementId}`)}mount(t){const e=document.querySelector(t);if(!e)throw new Error(`Element with selector "${t}" not found in in the DOM`);const n=document.createElement("div");n.setAttribute("id",this.loadElementId),n.setAttribute("style","width: 100%;"),e.appendChild(n)}unmount(){var t;super.unmount(),null===(t=document.querySelector(`#${this.loadElementId}`))||void 0===t||t.remove()}}class M extends D{constructor(t,e,n){var i,o;super("apple-pay-dropin",(null===(o=null===(i=n.translations)||void 0===i?void 0:i.labels)||void 0===o?void 0:o.label)||"Apple Pay"),this.loadElementId="apple-pay-dropin-load-element",this.component=new E(t,e,Object.assign(Object.assign({},n),{events:{onApplePayAvailable:()=>{this.mountAfterAvailable()}}}))}mount(t){const e=document.querySelector(t);if(!e)throw new Error(`Element with selector "${t}" not found in in the DOM`);const n=document.createElement("div");n.setAttribute("id",this.loadElementId),n.setAttribute("style","width: 100%;"),e.appendChild(n)}}class U extends N{constructor(t,e){super("payrails-credit-card-wrapper","Card"),this.cardForm=t,this.paymentButton=e,this.cardFormShown=!1,this.component=new $(t,e)}activate(){var t,e;this.label.style.marginBottom="8px",this.cardFormShown||(this.cardFormShown=!0,null===(t=this.component)||void 0===t||t.mount(this.selector)),this.isActive||(this.paymentButton.selectedInstrument=null,this.paymentButton.mount(this.selector),this.paymentButton.setDisabled(!this.cardForm.isValid),this.paymentButton.mount("#payrails-card-form"),this.input.checked=!0,this.cardForm.show(),this.isActive=!0,(null===(e=this.events)||void 0===e?void 0:e.onActivate)&&this.events.onActivate())}deactivate(){var t;this.isActive&&(this.label.style.marginBottom="0",this.paymentButton.unmount(),this.cardForm.hide(),this.isActive=!1,(null===(t=this.events)||void 0===t?void 0:t.onDeactivate)&&this.events.onDeactivate())}}class $ extends f{constructor(t,e){super("div",{id:"payrails-form-container"}),this.subElements.push(t,e)}}const V={apiVersion:2,apiVersionMinor:0};class H extends k{constructor(t,e,n){super("div",Object.assign(Object.assign({},n),{id:"payrails-google-pay-button"})),this.sdkConfig=t,this.execution=e,this.options=n,this.googleButton=null,this.paymentExecutor=new p(t,e),this.loadScript=new w((async()=>{const t=document.createElement("script");return t.src="https://pay.google.com/gp/p/js/pay.js",new Promise(((e,n)=>{t.onload=()=>{const t=new google.payments.api.PaymentsClient({environment:this.options.environment||"TEST"}),i=Object.assign(Object.assign({},V),{allowedPaymentMethods:this.execution.googlePayConfig});t.isReadyToPay(i).then((i=>{var o,s,a;i?(null===(a=null===(s=null===(o=this.options)||void 0===o?void 0:o.events)||void 0===s?void 0:s.onGooglePayAvailable)||void 0===a||a.call(s),e(t)):n()}),n)},t.onerror=()=>{n()},document.body.appendChild(t)}))}))}async sdkLoaded(t){var e,n,i,o,s,a,r,l;try{const d=(null===(n=null===(e=this.options)||void 0===e?void 0:e.styles)||void 0===n?void 0:n.buttonColor)||"black",u=(null===(o=null===(i=this.options)||void 0===i?void 0:i.styles)||void 0===o?void 0:o.buttonType)||"long",c=(null===(a=null===(s=this.options)||void 0===s?void 0:s.styles)||void 0===a?void 0:a.buttonSizeMode)||"fill",h=(null===(l=null===(r=this.options)||void 0===r?void 0:r.styles)||void 0===l?void 0:l.buttonLocale)||void 0;return this.googleButton=t.createButton({buttonColor:d,buttonType:u,buttonSizeMode:c,buttonLocale:h,onClick:async()=>{var t,e,n;if(null===(e=null===(t=this.options)||void 0===t?void 0:t.events)||void 0===e?void 0:e.onPaymentButtonClicked){if(!await(null===(n=this.options)||void 0===n?void 0:n.events.onPaymentButtonClicked()))return}await this.onPaymentButtonClicked()},allowedPaymentMethods:this.execution.googlePayConfig}),this.element.appendChild(this.googleButton),this.googleButton}catch(t){throw console.error("Google pay can not be initialized",t),new Error(t.message)}}async onLoadPaymentData(t){var e,n,i,o;const s=[{paymentMethodCode:"googlePay",integrationType:"api",paymentInstrumentData:{paymentToken:t.paymentMethodData.tokenizationData.token},amount:this.sdkConfig.amount,storeInstrument:this.shouldStoreInstrument}],a=await this.paymentExecutor.pay(s);(null===(n=null===(e=this.options)||void 0===e?void 0:e.events)||void 0===n?void 0:n.onAuthorizeSuccess)&&(null===(o=null===(i=this.options)||void 0===i?void 0:i.events)||void 0===o||o.onAuthorizeSuccess(a))}async onPaymentButtonClicked(){var t,e,n,i,o;const s=Object.assign({},V);s.allowedPaymentMethods=this.execution.googlePayConfig,s.transactionInfo={totalPriceStatus:"FINAL",totalPrice:null===(t=this.sdkConfig.amount)||void 0===t?void 0:t.value,currencyCode:null===(e=this.sdkConfig.amount)||void 0===e?void 0:e.currency,countryCode:null===(o=null===(i=null===(n=this.execution.meta)||void 0===n?void 0:n.customer)||void 0===i?void 0:i.country)||void 0===o?void 0:o.code};(await this.loadScript.loader).loadPaymentData(s).then((t=>{this.onLoadPaymentData(t)})).catch((t=>{var e,n,i;(null===(n=null===(e=this.options)||void 0===e?void 0:e.events)||void 0===n?void 0:n.onAuthorizeFailed)&&(null===(i=this.options)||void 0===i||i.events.onAuthorizeFailed(t))}))}mount(t){super.mount(t),(async()=>{var t;try{const e=await this.loadScript.loader,n=await this.sdkLoaded(e);this.element.appendChild(n),null===(t=this.storeInstrumentCheckbox)||void 0===t||t.mount(this.selector)}catch(t){}})()}unmount(){var t,e,n;null===(e=null===(t=this.googleButton)||void 0===t?void 0:t.parentElement)||void 0===e||e.removeChild(this.googleButton),null===(n=this.storeInstrumentCheckbox)||void 0===n||n.unmount(),super.unmount()}}class G extends D{constructor(t,e,n){var i,o;super("google-pay-dropin",(null===(o=null===(i=n.translations)||void 0===i?void 0:i.labels)||void 0===o?void 0:o.label)||"Google Pay"),this.loadElementId="google-pay-dropin-load-element",this.component=new H(t,e,Object.assign(Object.assign({},n),{events:Object.assign(Object.assign({},n.events),{onGooglePayAvailable:()=>{this.mountAfterAvailable()}})}))}mount(t){const e=document.querySelector(t);if(!e)throw new Error(`Element with selector "${t}" not found in in the DOM`);const n=document.createElement("div");n.setAttribute("id",this.loadElementId),n.setAttribute("style","width: 100%;"),e.appendChild(n)}}
2
2
  /*!
3
3
  * paypal-js v5.1.4 (2022-11-29T23:08:21.847Z)
4
4
  * Copyright 2020-present, PayPal, Inc. All rights reserved.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payrails/web-sdk",
3
- "version": "2.7.6",
3
+ "version": "2.7.7",
4
4
  "description": "SDK providing tokenization options on the client for merchants",
5
5
  "main": "index.js",
6
6
  "types": "payrails.d.ts",
package/payrails.d.ts CHANGED
@@ -309,6 +309,7 @@ interface CardFormOptions extends StoreInstrumentElementOptions {
309
309
  onFocus?: () => void;
310
310
  onChange?: (e: OnChange) => void;
311
311
  onSaveInstrumentCheckboxChanged?: PayrailsSDKEvents['onSaveInstrumentCheckboxChanged'];
312
+ onReady?: () => void;
312
313
  };
313
314
  styles?: {
314
315
  base?: Partial<CSSStyleDeclaration>;
@@ -333,6 +334,7 @@ declare class CardForm extends PayrailsElementWithStoreInstrumentCheckbox {
333
334
  constructor(collectContainer: PayrailsCollectContainer, options?: CardFormOptions | undefined);
334
335
  show(): void;
335
336
  hide(): void;
337
+ private triggerOnReady;
336
338
  private prepareLabelStyles;
337
339
  private prepareInputStyles;
338
340
  get isValid(): boolean;
@@ -380,7 +382,9 @@ interface RedirectReturnLinks {
380
382
  }
381
383
 
382
384
  interface CardPaymentButtonOptions {
383
- events?: PayrailsSDKEvents;
385
+ events?: PayrailsSDKEvents & {
386
+ onStateChanged?: (state: 'enabled' | 'disabled') => void;
387
+ };
384
388
  translations?: {
385
389
  label: string;
386
390
  };