import { cloneDeep } from 'lodash' ; import { Observable } from 'rxjs' ; import { take } from 'rxjs/operators' ; import { CapabilitiesSwitcher , CoreSetup , Logger } from 'src/core/server' ; import { ILicense } from '../../../../licensing/common/types' ; import { isFullLicense , isMinimumLicense , isMlEnabled } from '../../../common/license' ; import { MlCapabilities , basicLicenseMlCapabilities } from '../../../common/types/capabilities' ; export const setupCapabilitiesSwitcher = ( coreSetup , license$ , logger ) => { coreSetup . capabilities . registerSwitcher ( getSwitcher ( license$ , logger ) ) ; } ; function getSwitcher ( license$ , logger ) { return async ( request , capabilities ) => { const isAnonymousRequest = ! request . route . options . authRequired ; if ( isAnonymousRequest ) { return capabilities ; } try { const license = await license$ . pipe ( take ( 1 ) ) . toPromise ( ) ; const mlEnabled = isMlEnabled ( license ) ; if ( mlEnabled && isFullLicense ( license ) ) { return capabilities ; } const mlCaps = capabilities . ml as MlCapabilities ; const originalCapabilities = cloneDeep ( mlCaps ) ; Object . keys ( mlCaps ) . forEach ( ( k ) => { mlCaps [ k as keyof MlCapabilities ] = false ; } ) ; if ( mlEnabled && isMinimumLicense ( license ) ) { basicLicenseMlCapabilities . forEach ( ( c ) => ( mlCaps [ c ] = originalCapabilities [ c ] ) ) ; } return capabilities ; } catch ( e ) { logger . debug ( `Error updating capabilities for ML based on licensing: ${ e }` ) ; return capabilities ; } } ; }