@adyen/adyen-web
Version:
[](https://www.npmjs.com/package/@adyen/adyen-web)
3 lines (2 loc) • 8.79 kB
JavaScript
import{Language as t}from"../language/Language.js";import o from"./RiskModule/RiskModule.js";import e from"./ProcessResponse/PaymentMethods/PaymentMethods.js";import s from"./ProcessResponse/PaymentAction/PaymentAction.js";import i from"./Analytics/Analytics.js";import{processGlobalOptions as n,assertConfigurationPropertiesAreValid as a}from"./utils.js";import r from"./CheckoutSession/CheckoutSession.js";import{hasOwnProperty as c}from"../utils/hasOwnProperty.js";import{Resources as l}from"./Context/Resources.js";import{SRPanel as h}from"./Errors/SRPanel.js";import p from"./core.registry.js";import{sanitizeResponse as m,verifyPaymentDidNotFail as d,cleanupFinalResult as u}from"../components/internal/UIElement/utils.js";import y,{IMPLEMENTATION_ERROR as f}from"./Errors/AdyenCheckoutError.js";import{THREEDS2_FULL as g}from"../components/ThreeDS2/constants.js";import{DEFAULT_LOCALE as C}from"../language/constants.js";import A from"./Services/get-translations.js";import{defaultProps as v}from"./core.defaultProps.js";import{formatLocale as w,formatCustomTranslations as j}from"../language/utils.js";import{resolveEnvironments as b}from"./Environment/Environment.js";import{LIBRARY_BUNDLE_TYPE as E,LIBRARY_VERSION as P}from"./config.js";import{AnalyticsLogEvent as M,LogEventType as T}from"./Analytics/events/AnalyticsLogEvent.js";import R from"./Errors/CancelError.js";import{AnalyticsService as I}from"./Analytics/AnalyticsService.js";import{AnalyticsEventQueue as U}from"./Analytics/AnalyticsEventQueue.js";import{isAmountValid as x}from"../utils/amount-util.js";function k(t,o,e){return o in t?Object.defineProperty(t,o,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[o]=e,t}class D{static setBundleType(t){D.metadata.bundleType=t}static register(...t){p.add(...t)}register(...t){p.add(...t)}getComponent(t){return p.getComponent(t)}async initialize(){return await this.initializeCore(),this.validateCoreConfiguration(),await this.createCoreModules(),await this.requestAnalyticsAttemptId(),this}async initializeCore(){return this.session?this.session.setupSession(this.options).then(t=>{const{amount:o,shopperLocale:e,countryCode:s,paymentMethods:i,...n}=t;return this.setOptions({...n,amount:this.options.order?this.options.order.remainingAmount:o,locale:this.options.locale||e,countryCode:this.options.countryCode||s}),this.createPaymentMethodsList(i),this}).catch(t=>(this.options.onError&&this.options.onError(t),Promise.reject(t))):(this.createPaymentMethodsList(),Promise.resolve(this))}async fetchLocaleTranslations(){try{return await A(this.cdnTranslationsUrl,D.metadata.version,this.options.locale)}catch(t){t instanceof y?this.options.onError?.(t):this.options.onError?.(new y("ERROR","Failed to fetch translation",{cause:t}))}}validateCoreConfiguration(){if(this.options.paymentMethodsConfiguration&&console.warn('WARNING: "paymentMethodsConfiguration" is supported only by Drop-in.'),!this.options.countryCode)throw new y(f,"You must specify a countryCode when initializing checkout.");this.options.locale||this.setOptions({locale:C}),this.options.locale=w(this.options.locale),this.options.translations=j(this.options.translations)}submitDetails(t){let o=null;this.options.onAdditionalDetails&&(o=new Promise((o,e)=>{this.options.onAdditionalDetails({data:t},void 0,{resolve:o,reject:e})})),this.session&&(o=this.session.submitDetails(t).catch(t=>(this.options.onError?.(t),Promise.reject(t)))),o?o.then(m).then(d).then(this.afterAdditionalDetails).then(t=>{u(t),this.options.onPaymentCompleted?.(t)}).catch(t=>{t instanceof R||(u(t),this.options.onPaymentFailed?.(t))}):this.options.onError?.(new y("IMPLEMENTATION_ERROR",'It can not submit the details. The callback "onAdditionalDetails" or the Session is not setup correctly.'))}createFromAction(t,o={}){if(!t||!t.type){if(c(t,"action")&&c(t,"resultCode"))throw new Error('createFromAction::Invalid Action - the passed action object itself has an "action" property and a "resultCode": have you passed in the whole response object by mistake?');throw new Error('createFromAction::Invalid Action - the passed action object does not have a "type" property')}if(t.type){const e=t.type===g?`${t.type}${t.subtype}`:t.paymentMethodType,i=new M({type:T.action,subType:M.getSubtypeFromActionType(t.type),message:`${e} action was handled by the SDK`,component:e});this.modules.analytics.sendAnalytics(i);const n={...this.getCorePropsForComponent(),...o};return s(this,p,t,n)}return this.handleCreateError()}update(t={},{shouldReinitializeCheckout:o=!0}={}){if(o)return this.setOptions(t),this.initialize().then(()=>(this.components.forEach(o=>{const e={...t.order?.remainingAmount?{amount:t.order.remainingAmount}:{amount:this.options.amount},...this.session&&{session:this.session},...t};o.update(e)}),this));const{amount:e,secondaryAmount:s}=t;return(e||s)&&this.triggerAmountUpdate(e,s),Promise.resolve(this)}triggerAmountUpdate(t,o){x(t)?!o||x(o)?(this.setOptions({amount:t,...o&&{secondaryAmount:o}}),this.components.forEach(e=>{e.updateAmount(t,o)})):console.warn("Core update(): Update canceled. Invalid secondary amount object"):console.warn("Core update(): Update canceled. Invalid amount object")}getCorePropsForComponent(){return{...n(this.options),core:this,i18n:this.modules.i18n,modules:this.modules,session:this.session,loadingContext:this.loadingContext,cdnContext:this.cdnImagesUrl,createFromAction:this.createFromAction}}storeElementReference(t){t&&this.components.push(t)}handleCreateError(t){const o=t?`${t?.name??"The passed payment method"} is not a valid Checkout Component. What was passed as a txVariant was: ${JSON.stringify(t)}. Check if this payment method is configured in the Backoffice or if the txVariant is a valid one`:"No Payment Method component was passed";throw new Error(o)}createPaymentMethodsList(t){this.paymentMethodsResponse=new e(this.options.paymentMethodsResponse||t,this.options)}async createCoreModules(){if(this.modules)return;const e=await this.fetchLocaleTranslations();this.modules=Object.freeze({risk:new o(this,{...this.options,loadingContext:this.loadingContext}),analytics:new i({eventQueue:new U,service:new I({analyticsContext:this.analyticsContext,clientKey:this.options.clientKey}),enabled:this.options.analytics?.enabled,analyticsData:this.options.analytics?.analyticsData}),resources:new l(this.cdnImagesUrl),i18n:new t({locale:this.options.locale,translations:e,customTranslations:this.options.translations}),srPanel:new h(this,{...this.options.srConfig})})}async requestAnalyticsAttemptId(){await this.modules.analytics.setUp({locale:this.options.locale,...this.session?.id&&{sessionId:this.session.id}})}constructor(t){k(this,"session",void 0),k(this,"paymentMethodsResponse",void 0),k(this,"modules",void 0),k(this,"options",void 0),k(this,"analyticsContext",void 0),k(this,"loadingContext",void 0),k(this,"cdnImagesUrl",void 0),k(this,"cdnTranslationsUrl",void 0),k(this,"components",[]),k(this,"afterAdditionalDetails",t=>{if(this.options.afterAdditionalDetails&&t?.action){const o=this.createFromAction(t.action);return this.options.afterAdditionalDetails(o),Promise.reject(new R("Handled by afterAdditionalDetails"))}return Promise.resolve(t)}),k(this,"remove",t=>(this.components=this.components.filter(o=>o._id!==t._id),t.unmount(),this)),k(this,"setOptions",t=>{this.options={...this.options,...t,locale:t?.locale||this.options?.locale,environment:String.prototype.toLowerCase.apply(t?.environment||this.options?.environment)}}),a(t),this.createFromAction=this.createFromAction.bind(this),this.update=this.update.bind(this),this.setOptions({...v,...t});const{apiUrl:o,analyticsUrl:e,cdnImagesUrl:s,cdnTranslationsUrl:i}=b(this.options.environment,this.options._environmentUrls);this.loadingContext=o,this.analyticsContext=e,this.cdnImagesUrl=s,this.cdnTranslationsUrl=i,this.session=this.options.session&&new r(this.options.session,this.options.clientKey,this.loadingContext);const n=this.options.clientKey?.substring(0,4);if(("test"===n||"live"===n)&&!this.loadingContext.includes(n))throw new y("IMPLEMENTATION_ERROR",`Error: you are using a ${n} clientKey against the ${this.options._environmentUrls?.api||this.options.environment} environment`);"pub."===n&&console.debug(`The value you are passing as your "clientKey" looks like an originKey (${this.options.clientKey?.substring(0,12)}..). Although this is supported it is not the recommended way to integrate. To generate a clientKey, see the documentation (https://docs.adyen.com/development-resources/client-side-authentication/migrate-from-origin-key-to-client-key/) for more details.`),this.options.exposeLibraryMetadata&&(window.AdyenWebMetadata=D.metadata)}}k(D,"metadata",{version:P,bundleType:E}),k(D,"registry",p);export{D as default};
//# sourceMappingURL=core.js.map