UNPKG

@adyen/adyen-web

Version:

[![npm](https://img.shields.io/npm/v/@adyen/adyen-web.svg)](https://www.npmjs.com/package/@adyen/adyen-web)

3 lines (2 loc) 8.58 kB
import{Language as t}from"../language/Language.js";import e from"./RiskModule/RiskModule.js";import o from"./ProcessResponse/PaymentMethods/PaymentMethods.js";import s from"./ProcessResponse/PaymentAction/PaymentAction.js";import i from"./Analytics/Analytics.js";import{processGlobalOptions as n,assertConfigurationPropertiesAreValid as r}from"./utils.js";import a from"./CheckoutSession/CheckoutSession.js";import{hasOwnProperty as h}from"../utils/hasOwnProperty.js";import{Resources as c}from"./Context/Resources.js";import{SRPanel as l}from"./Errors/SRPanel.js";import m from"./core.registry.js";import{sanitizeResponse as d,verifyPaymentDidNotFail as p,cleanupFinalResult as u}from"../components/internal/UIElement/utils.js";import y,{IMPLEMENTATION_ERROR as g}from"./Errors/AdyenCheckoutError.js";import{THREEDS2_FULL as f}from"../components/ThreeDS2/constants.js";import{defaultProps as C}from"./core.defaultProps.js";import{resolveEnvironments as v}from"./Environment/Environment.js";import{LIBRARY_BUNDLE_TYPE as A,LIBRARY_VERSION as w}from"./config.js";import{AnalyticsLogEvent as j,LogEventType as b}from"./Analytics/events/AnalyticsLogEvent.js";import E from"./Errors/CancelError.js";import{AnalyticsService as P}from"./Analytics/AnalyticsService.js";import{AnalyticsEventQueue as T}from"./Analytics/AnalyticsEventQueue.js";import{isAmountValid as M}from"../utils/amount-util.js";import{LanguageService as U}from"../language/LanguageService.js";function I(t,e,o){return e in t?Object.defineProperty(t,e,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[e]=o,t}class k{static setBundleType(t){k.metadata.bundleType=t}static register(...t){m.add(...t)}register(...t){m.add(...t)}getComponent(t){return m.getComponent(t)}async initialize(){return await this.initializeCore(),this.validateCoreConfiguration(),this.createCoreModules(),this.assignLocaleToCore(),this.requestAnalyticsAttemptId(),await this.requestTranslations(),this}async initializeCore(){return this.session?this.session.setupSession(this.options).then(t=>{const{amount:e,shopperLocale:o,countryCode:s,paymentMethods:i,...n}=t;return this.setOptions({...n,amount:this.options.order?this.options.order.remainingAmount:e,locale:this.options.locale||o,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))}validateCoreConfiguration(){if(this.options.paymentMethodsConfiguration&&console.warn('WARNING: "paymentMethodsConfiguration" is supported only by Drop-in.'),!this.options.countryCode)throw new y(g,"You must specify a countryCode when initializing checkout.")}submitDetails(t){let e=null;this.options.onAdditionalDetails&&(e=new Promise((e,o)=>{this.options.onAdditionalDetails({data:t},void 0,{resolve:e,reject:o})})),this.session&&(e=this.session.submitDetails(t).catch(t=>(this.options.onError?.(t),Promise.reject(t)))),e?e.then(d).then(p).then(this.afterAdditionalDetails).then(t=>{u(t),this.options.onPaymentCompleted?.(t)}).catch(t=>{t instanceof E||(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,e={}){if(!t||!t.type){if(h(t,"action")&&h(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 o=t.type===f?`${t.type}${t.subtype}`:t.paymentMethodType,i=new j({type:b.action,subType:j.getSubtypeFromActionType(t.type),message:`${o} action was handled by the SDK`,component:o});this.modules.analytics.sendAnalytics(i);const n={...this.getCorePropsForComponent(),...e};return s(this,m,t,n)}return this.handleCreateError()}update(t={},{shouldReinitializeCheckout:e=!0}={}){if(e)return this.setOptions(t),this.initialize().then(()=>(this.components.forEach(e=>{const o={...t.order?.remainingAmount?{amount:t.order.remainingAmount}:{amount:this.options.amount},...this.session&&{session:this.session},...t};e.update(o)}),this));const{amount:o,secondaryAmount:s}=t;return(o||s)&&this.triggerAmountUpdate(o,s),Promise.resolve(this)}triggerAmountUpdate(t,e){M(t)?!e||M(e)?(this.setOptions({amount:t,...e&&{secondaryAmount:e}}),this.components.forEach(o=>{o.updateAmount(t,e)})):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 e=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(e)}createPaymentMethodsList(t){this.paymentMethodsResponse=new o(this.options.paymentMethodsResponse||t,this.options)}createCoreModules(){this.modules||(this.modules=Object.freeze({risk:new e(this,{...this.options,loadingContext:this.loadingContext}),analytics:new i({eventQueue:new T,service:new P({analyticsContext:this.analyticsContext,clientKey:this.options.clientKey}),enabled:this.options.analytics?.enabled,analyticsData:this.options.analytics?.analyticsData}),resources:new c(this.cdnImagesUrl),i18n:new t({locale:this.options.locale,customTranslations:this.options.translations,service:new U({cdnUrl:this.cdnTranslationsUrl,sdkVersion:k.metadata.version}),onError:this.options?.onError}),srPanel:new l(this,{...this.options.srConfig})}))}assignLocaleToCore(){this.options.locale=this.modules.i18n.locale}async requestTranslations(){try{await this.modules.i18n.requestTranslations()}catch(t){console.warn("Core - requestTranslations(): Something went wrong.",t)}}async requestAnalyticsAttemptId(){await this.modules.analytics.setUp({locale:this.options.locale,...this.session?.id&&{sessionId:this.session.id}})}constructor(t){I(this,"session",void 0),I(this,"paymentMethodsResponse",void 0),I(this,"modules",void 0),I(this,"options",void 0),I(this,"analyticsContext",void 0),I(this,"loadingContext",void 0),I(this,"cdnImagesUrl",void 0),I(this,"cdnTranslationsUrl",void 0),I(this,"components",[]),I(this,"afterAdditionalDetails",t=>{if(this.options.afterAdditionalDetails&&t?.action){const e=this.createFromAction(t.action);return this.options.afterAdditionalDetails(e),Promise.reject(new E("Handled by afterAdditionalDetails"))}return Promise.resolve(t)}),I(this,"remove",t=>(this.components=this.components.filter(e=>e._id!==t._id),t.unmount(),this)),I(this,"setOptions",t=>{this.options={...this.options,...t,locale:t?.locale||this.options?.locale,environment:String.prototype.toLowerCase.apply(t?.environment||this.options?.environment)}}),r(t),this.createFromAction=this.createFromAction.bind(this),this.update=this.update.bind(this),this.setOptions({...C,...t});const{apiUrl:e,analyticsUrl:o,cdnImagesUrl:s,cdnTranslationsUrl:i}=v(this.options.environment,this.options._environmentUrls);this.loadingContext=e,this.analyticsContext=o,this.cdnImagesUrl=s,this.cdnTranslationsUrl=i,this.session=this.options.session&&new a(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=k.metadata)}}I(k,"metadata",{version:w,bundleType:A}),I(k,"registry",m);export{k as default}; //# sourceMappingURL=core.js.map