import { SerializedVis , Vis , VisSavedObject , VisualizeEmbeddableContract , VisualizeInput , } from 'src/plugins/visualizations/public' ; import { SearchSourceFields } from 'src/plugins/data/public' ; import { SavedObject } from 'src/plugins/saved_objects/public' ; import { cloneDeep } from 'lodash' ; import { ExpressionValueError } from 'src/plugins/expressions/public' ; import { createSavedSearchesLoader } from '../../../../discover/public' ; import { VisualizeServices } from '../types' ; const createVisualizeEmbeddableAndLinkSavedSearch = async ( vis , visualizeServices ) => { const { chrome , data , overlays , createVisEmbeddableFromObject , savedObjects } = visualizeServices ; const embeddableHandler = ( await createVisEmbeddableFromObject ( vis , { timeRange : data . query . timefilter . timefilter . getTime ( ) , filters : data . query . filterManager . getFilters ( ) , id : '' , } ) ) as VisualizeEmbeddableContract ; embeddableHandler . getOutput$ ( ) . subscribe ( ( output ) => { if ( output . error ) { data . search . showError ( ( ( output . error as unknown ) as ExpressionValueError [ 'error' ] ) . original || output . error ) ; } } ) ; let savedSearch ; if ( vis . data . savedSearchId ) { savedSearch = await createSavedSearchesLoader ( { savedObjectsClient : savedObjects . client , indexPatterns : data . indexPatterns , search : data . search , chrome , overlays , } ) . get ( vis . data . savedSearchId ) ; } return { savedSearch , embeddableHandler } ; } ; export const getVisualizationInstanceFromInput = async ( visualizeServices , input ) => { const { visualizations } = visualizeServices ; const visState = input . savedVis as SerializedVis ; let vis = await visualizations . createVis ( visState . type , cloneDeep ( visState ) ) ; if ( vis . type . setup ) { try { vis = await vis . type . setup ( vis ) ; } catch { } } const { embeddableHandler , savedSearch } = await createVisualizeEmbeddableAndLinkSavedSearch ( vis , visualizeServices ) ; return { vis , embeddableHandler , savedSearch , } ; } ; export const getVisualizationInstance = async ( visualizeServices , /**
 * opts can be either a saved visualization id passed as string,
 * or an object of new visualization params.
 * Both come from url search query
 */ opts ? ) => { const { visualizations , savedVisualizations } = visualizeServices ; const savedVis = await savedVisualizations . get ( opts ) ; if ( typeof opts !== 'string' ) { savedVis . searchSourceFields = { index : opts ?. indexPattern } as SearchSourceFields ; } const serializedVis = visualizations . convertToSerializedVis ( savedVis ) ; let vis = await visualizations . createVis ( serializedVis . type , serializedVis ) ; if ( vis . type . setup ) { try { vis = await vis . type . setup ( vis ) ; } catch { } } const { embeddableHandler , savedSearch } = await createVisualizeEmbeddableAndLinkSavedSearch ( vis , visualizeServices ) ; return { vis , embeddableHandler , savedSearch , savedVis , } ; } ;