import { SavedObject } from '../../../types' ; import { KibanaRequest } from '../../http' ; import { SavedObjectsExportError } from './errors' ; import { SavedObjectsExportTransform , SavedObjectsExportTransformContext } from './types' ; import { getObjKey , SavedObjectComparator } from './utils' ; interface ApplyExportTransformsOptions { objects : SavedObject [ ] ; request : KibanaRequest ; transforms : Map < string , SavedObjectsExportTransform > ; sortFunction ? : SavedObjectComparator ; } export const applyExportTransforms = async ( { objects , request , transforms , sortFunction , } ) : Promise < SavedObject [ ] > => { const context = createContext ( request ) ; const byType = splitByType ( objects ) ; let finalObjects = [ ] ; for ( const [ type , typeObjs ] of Object . entries ( byType ) ) { const typeTransformFn = transforms . get ( type ) ; if ( typeTransformFn ) { finalObjects = [ ... finalObjects , ... ( await applyTransform ( typeObjs , typeTransformFn , context ) ) , ] ; } else { finalObjects = [ ... finalObjects , ... typeObjs ] ; } } if ( sortFunction ) { finalObjects . sort ( sortFunction ) ; } return finalObjects ; } ; const applyTransform = async ( objs , transformFn , context ) => { const objKeys = objs . map ( getObjKey ) ; let transformedObjects ; try { transformedObjects = await transformFn ( context , objs ) ; } catch ( e ) { throw SavedObjectsExportError . objectTransformError ( objs , e ) ; } assertValidTransform ( transformedObjects , objKeys ) ; return transformedObjects ; } ; const createContext = ( request ) : SavedObjectsExportTransformContext => { return { request , } ; } ; const splitByType = ( objects ) : Record < string , SavedObject [ ] > => { return objects . reduce ( ( memo , obj ) => { memo [ obj . type ] = [ ... ( memo [ obj . type ] ?? [ ] ) , obj ] ; return memo ; } , { } as Record < string , SavedObject [ ] > ) ; } ; const assertValidTransform = ( transformedObjects , initialKeys ) => { const transformedKeys = transformedObjects . map ( getObjKey ) ; const missingKeys = [ ] ; initialKeys . forEach ( ( initialKey ) => { if ( ! transformedKeys . includes ( initialKey ) ) { missingKeys . push ( initialKey ) ; } } ) ; if ( missingKeys . length ) { throw SavedObjectsExportError . invalidTransformError ( missingKeys ) ; } } ;