diff --git a/Jenkinsfile b/Jenkinsfile index 33d8d47f06e8f5..08ccc879054bd7 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -17,6 +17,8 @@ stage("Kibana Pipeline") { // This stage is just here to help the BlueOcean UI a 'oss-ciGroup4': getOssCiGroupWorker(4), 'oss-ciGroup5': getOssCiGroupWorker(5), 'oss-ciGroup6': getOssCiGroupWorker(6), + ]), + 'kibana-oss-agent2': withWorkers('kibana-oss-tests2', { buildOss() }, [ 'oss-ciGroup7': getOssCiGroupWorker(7), 'oss-ciGroup8': getOssCiGroupWorker(8), 'oss-ciGroup9': getOssCiGroupWorker(9), @@ -32,6 +34,8 @@ stage("Kibana Pipeline") { // This stage is just here to help the BlueOcean UI a 'xpack-ciGroup3': getXpackCiGroupWorker(3), 'xpack-ciGroup4': getXpackCiGroupWorker(4), 'xpack-ciGroup5': getXpackCiGroupWorker(5), + ]), + 'kibana-xpack-agent2': withWorkers('kibana-xpack-tests2', { buildXpack() }, [ 'xpack-ciGroup6': getXpackCiGroupWorker(6), 'xpack-ciGroup7': getXpackCiGroupWorker(7), 'xpack-ciGroup8': getXpackCiGroupWorker(8), diff --git a/docs/development/core/public/kibana-plugin-public.applicationsetup.registermountcontext.md b/docs/development/core/public/kibana-plugin-public.applicationsetup.registermountcontext.md index 0b5bd8eeb36eca..f264ba500ed6ef 100644 --- a/docs/development/core/public/kibana-plugin-public.applicationsetup.registermountcontext.md +++ b/docs/development/core/public/kibana-plugin-public.applicationsetup.registermountcontext.md @@ -9,7 +9,7 @@ Register a context provider for application mounting. Will only be available to Signature: ```typescript -registerMountContext(contextName: T, provider: IContextProvider): void; +registerMountContext(contextName: T, provider: IContextProvider): void; ``` ## Parameters @@ -17,7 +17,7 @@ registerMountContext(contextName: T, provider: | Parameter | Type | Description | | --- | --- | --- | | contextName | T | The key of [AppMountContext](./kibana-plugin-public.appmountcontext.md) this provider's return value should be attached to. | -| provider | IContextProvider<AppMountContext, T> | A [IContextProvider](./kibana-plugin-public.icontextprovider.md) function | +| provider | IContextProvider<App['mount'], T> | A [IContextProvider](./kibana-plugin-public.icontextprovider.md) function | Returns: diff --git a/docs/development/core/public/kibana-plugin-public.applicationstart.registermountcontext.md b/docs/development/core/public/kibana-plugin-public.applicationstart.registermountcontext.md index fc86aaf658b681..62821fcbb92bad 100644 --- a/docs/development/core/public/kibana-plugin-public.applicationstart.registermountcontext.md +++ b/docs/development/core/public/kibana-plugin-public.applicationstart.registermountcontext.md @@ -9,7 +9,7 @@ Register a context provider for application mounting. Will only be available to Signature: ```typescript -registerMountContext(contextName: T, provider: IContextProvider): void; +registerMountContext(contextName: T, provider: IContextProvider): void; ``` ## Parameters @@ -17,7 +17,7 @@ registerMountContext(contextName: T, provider: | Parameter | Type | Description | | --- | --- | --- | | contextName | T | The key of [AppMountContext](./kibana-plugin-public.appmountcontext.md) this provider's return value should be attached to. | -| provider | IContextProvider<AppMountContext, T> | A [IContextProvider](./kibana-plugin-public.icontextprovider.md) function | +| provider | IContextProvider<App['mount'], T> | A [IContextProvider](./kibana-plugin-public.icontextprovider.md) function | Returns: diff --git a/docs/development/core/public/kibana-plugin-public.appmountcontext.core.md b/docs/development/core/public/kibana-plugin-public.appmountcontext.core.md index 63b3ead814f003..f4dee0f29af342 100644 --- a/docs/development/core/public/kibana-plugin-public.appmountcontext.core.md +++ b/docs/development/core/public/kibana-plugin-public.appmountcontext.core.md @@ -18,5 +18,8 @@ core: { notifications: NotificationsStart; overlays: OverlayStart; uiSettings: UiSettingsClientContract; + injectedMetadata: { + getInjectedVar: (name: string, defaultValue?: any) => unknown; + }; }; ``` diff --git a/docs/development/core/public/kibana-plugin-public.appmountcontext.md b/docs/development/core/public/kibana-plugin-public.appmountcontext.md index c6541e3eca392f..97d143d518f60b 100644 --- a/docs/development/core/public/kibana-plugin-public.appmountcontext.md +++ b/docs/development/core/public/kibana-plugin-public.appmountcontext.md @@ -16,5 +16,5 @@ export interface AppMountContext | Property | Type | Description | | --- | --- | --- | -| [core](./kibana-plugin-public.appmountcontext.core.md) | {
application: Pick<ApplicationStart, 'capabilities' | 'navigateToApp'>;
chrome: ChromeStart;
docLinks: DocLinksStart;
http: HttpStart;
i18n: I18nStart;
notifications: NotificationsStart;
overlays: OverlayStart;
uiSettings: UiSettingsClientContract;
} | Core service APIs available to mounted applications. | +| [core](./kibana-plugin-public.appmountcontext.core.md) | {
application: Pick<ApplicationStart, 'capabilities' | 'navigateToApp'>;
chrome: ChromeStart;
docLinks: DocLinksStart;
http: HttpStart;
i18n: I18nStart;
notifications: NotificationsStart;
overlays: OverlayStart;
uiSettings: UiSettingsClientContract;
injectedMetadata: {
getInjectedVar: (name: string, defaultValue?: any) => unknown;
};
} | Core service APIs available to mounted applications. | diff --git a/docs/development/core/public/kibana-plugin-public.contextsetup.createcontextcontainer.md b/docs/development/core/public/kibana-plugin-public.contextsetup.createcontextcontainer.md index 2644596354e383..5334eee8425779 100644 --- a/docs/development/core/public/kibana-plugin-public.contextsetup.createcontextcontainer.md +++ b/docs/development/core/public/kibana-plugin-public.contextsetup.createcontextcontainer.md @@ -9,9 +9,9 @@ Creates a new [IContextContainer](./kibana-plugin-public.icontextcontainer.md) f Signature: ```typescript -createContextContainer(): IContextContainer; +createContextContainer>(): IContextContainer; ``` Returns: -`IContextContainer` +`IContextContainer` diff --git a/docs/development/core/public/kibana-plugin-public.coresetup.injectedmetadata.md b/docs/development/core/public/kibana-plugin-public.coresetup.injectedmetadata.md new file mode 100644 index 00000000000000..f9c1a283e38089 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.coresetup.injectedmetadata.md @@ -0,0 +1,19 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [CoreSetup](./kibana-plugin-public.coresetup.md) > [injectedMetadata](./kibana-plugin-public.coresetup.injectedmetadata.md) + +## CoreSetup.injectedMetadata property + +> Warning: This API is now obsolete. +> +> + +exposed temporarily until https://github.com/elastic/kibana/issues/41990 done use \*only\* to retrieve config values. There is no way to set injected values in the new platform. Use the legacy platform API instead. + +Signature: + +```typescript +injectedMetadata: { + getInjectedVar: (name: string, defaultValue?: any) => unknown; + }; +``` diff --git a/docs/development/core/public/kibana-plugin-public.coresetup.md b/docs/development/core/public/kibana-plugin-public.coresetup.md index 9b94e2db528319..f9335425fed4ca 100644 --- a/docs/development/core/public/kibana-plugin-public.coresetup.md +++ b/docs/development/core/public/kibana-plugin-public.coresetup.md @@ -20,6 +20,7 @@ export interface CoreSetup | [context](./kibana-plugin-public.coresetup.context.md) | ContextSetup | [ContextSetup](./kibana-plugin-public.contextsetup.md) | | [fatalErrors](./kibana-plugin-public.coresetup.fatalerrors.md) | FatalErrorsSetup | [FatalErrorsSetup](./kibana-plugin-public.fatalerrorssetup.md) | | [http](./kibana-plugin-public.coresetup.http.md) | HttpSetup | [HttpSetup](./kibana-plugin-public.httpsetup.md) | +| [injectedMetadata](./kibana-plugin-public.coresetup.injectedmetadata.md) | {
getInjectedVar: (name: string, defaultValue?: any) => unknown;
} | exposed temporarily until https://github.com/elastic/kibana/issues/41990 done use \*only\* to retrieve config values. There is no way to set injected values in the new platform. Use the legacy platform API instead. | | [notifications](./kibana-plugin-public.coresetup.notifications.md) | NotificationsSetup | [NotificationsSetup](./kibana-plugin-public.notificationssetup.md) | | [uiSettings](./kibana-plugin-public.coresetup.uisettings.md) | UiSettingsClientContract | [UiSettingsClient](./kibana-plugin-public.uisettingsclient.md) | diff --git a/docs/development/core/public/kibana-plugin-public.corestart.injectedmetadata.md b/docs/development/core/public/kibana-plugin-public.corestart.injectedmetadata.md new file mode 100644 index 00000000000000..9224b97bc43004 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.corestart.injectedmetadata.md @@ -0,0 +1,19 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [CoreStart](./kibana-plugin-public.corestart.md) > [injectedMetadata](./kibana-plugin-public.corestart.injectedmetadata.md) + +## CoreStart.injectedMetadata property + +> Warning: This API is now obsolete. +> +> + +exposed temporarily until https://github.com/elastic/kibana/issues/41990 done use \*only\* to retrieve config values. There is no way to set injected values in the new platform. Use the legacy platform API instead. + +Signature: + +```typescript +injectedMetadata: { + getInjectedVar: (name: string, defaultValue?: any) => unknown; + }; +``` diff --git a/docs/development/core/public/kibana-plugin-public.corestart.md b/docs/development/core/public/kibana-plugin-public.corestart.md index 5c1626958c4df6..47eba78bf43e46 100644 --- a/docs/development/core/public/kibana-plugin-public.corestart.md +++ b/docs/development/core/public/kibana-plugin-public.corestart.md @@ -21,6 +21,7 @@ export interface CoreStart | [docLinks](./kibana-plugin-public.corestart.doclinks.md) | DocLinksStart | [DocLinksStart](./kibana-plugin-public.doclinksstart.md) | | [http](./kibana-plugin-public.corestart.http.md) | HttpStart | [HttpStart](./kibana-plugin-public.httpstart.md) | | [i18n](./kibana-plugin-public.corestart.i18n.md) | I18nStart | [I18nStart](./kibana-plugin-public.i18nstart.md) | +| [injectedMetadata](./kibana-plugin-public.corestart.injectedmetadata.md) | {
getInjectedVar: (name: string, defaultValue?: any) => unknown;
} | exposed temporarily until https://github.com/elastic/kibana/issues/41990 done use \*only\* to retrieve config values. There is no way to set injected values in the new platform. Use the legacy platform API instead. | | [notifications](./kibana-plugin-public.corestart.notifications.md) | NotificationsStart | [NotificationsStart](./kibana-plugin-public.notificationsstart.md) | | [overlays](./kibana-plugin-public.corestart.overlays.md) | OverlayStart | [OverlayStart](./kibana-plugin-public.overlaystart.md) | | [savedObjects](./kibana-plugin-public.corestart.savedobjects.md) | SavedObjectsStart | [SavedObjectsStart](./kibana-plugin-public.savedobjectsstart.md) | diff --git a/docs/development/core/public/kibana-plugin-public.handlercontexttype.md b/docs/development/core/public/kibana-plugin-public.handlercontexttype.md new file mode 100644 index 00000000000000..b083449d2b703f --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.handlercontexttype.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [HandlerContextType](./kibana-plugin-public.handlercontexttype.md) + +## HandlerContextType type + +Extracts the type of the first argument of a [HandlerFunction](./kibana-plugin-public.handlerfunction.md) to represent the type of the context. + +Signature: + +```typescript +export declare type HandlerContextType> = T extends HandlerFunction ? U : never; +``` diff --git a/docs/development/core/public/kibana-plugin-public.handlerfunction.md b/docs/development/core/public/kibana-plugin-public.handlerfunction.md new file mode 100644 index 00000000000000..98c342c17691d9 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.handlerfunction.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [HandlerFunction](./kibana-plugin-public.handlerfunction.md) + +## HandlerFunction type + +A function that accepts a context object and an optional number of additional arguments. Used for the generic types in [IContextContainer](./kibana-plugin-public.icontextcontainer.md) + +Signature: + +```typescript +export declare type HandlerFunction = (context: T, ...args: any[]) => any; +``` diff --git a/docs/development/core/public/kibana-plugin-public.handlerparameters.md b/docs/development/core/public/kibana-plugin-public.handlerparameters.md new file mode 100644 index 00000000000000..f46c4b649e9436 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.handlerparameters.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [HandlerParameters](./kibana-plugin-public.handlerparameters.md) + +## HandlerParameters type + +Extracts the types of the additional arguments of a [HandlerFunction](./kibana-plugin-public.handlerfunction.md), excluding the [HandlerContextType](./kibana-plugin-public.handlercontexttype.md). + +Signature: + +```typescript +export declare type HandlerParameters> = T extends (context: any, ...args: infer U) => any ? U : never; +``` diff --git a/docs/development/core/public/kibana-plugin-public.icontextcontainer.createhandler.md b/docs/development/core/public/kibana-plugin-public.icontextcontainer.createhandler.md index 2a995df45757f3..af3b5e3fc2eb65 100644 --- a/docs/development/core/public/kibana-plugin-public.icontextcontainer.createhandler.md +++ b/docs/development/core/public/kibana-plugin-public.icontextcontainer.createhandler.md @@ -9,7 +9,7 @@ Create a new handler function pre-wired to context for the plugin. Signature: ```typescript -createHandler(pluginOpaqueId: PluginOpaqueId, handler: IContextHandler): (...rest: THandlerParameters) => THandlerReturn extends Promise ? THandlerReturn : Promise; +createHandler(pluginOpaqueId: PluginOpaqueId, handler: THandler): (...rest: HandlerParameters) => ShallowPromise>; ``` ## Parameters @@ -17,11 +17,11 @@ createHandler(pluginOpaqueId: PluginOpaqueId, handler: IContextHandlerPluginOpaqueId | The plugin opaque ID for the plugin that registers this handler. | -| handler | IContextHandler<TContext, THandlerReturn, THandlerParameters> | Handler function to pass context object to. | +| handler | THandler | Handler function to pass context object to. | Returns: -`(...rest: THandlerParameters) => THandlerReturn extends Promise ? THandlerReturn : Promise` +`(...rest: HandlerParameters) => ShallowPromise>` A function that takes `THandlerParameters`, calls `handler` with a new context, and returns a Promise of the `handler` return value. diff --git a/docs/development/core/public/kibana-plugin-public.icontextcontainer.md b/docs/development/core/public/kibana-plugin-public.icontextcontainer.md index 0bc7c8f3808d16..f16c07b3d7906d 100644 --- a/docs/development/core/public/kibana-plugin-public.icontextcontainer.md +++ b/docs/development/core/public/kibana-plugin-public.icontextcontainer.md @@ -9,7 +9,7 @@ An object that handles registration of context providers and configuring handler Signature: ```typescript -export interface IContextContainer +export interface IContextContainer> ``` ## Methods diff --git a/docs/development/core/public/kibana-plugin-public.icontextcontainer.registercontext.md b/docs/development/core/public/kibana-plugin-public.icontextcontainer.registercontext.md index 2cf10a6ec841d6..775f95bd7affaa 100644 --- a/docs/development/core/public/kibana-plugin-public.icontextcontainer.registercontext.md +++ b/docs/development/core/public/kibana-plugin-public.icontextcontainer.registercontext.md @@ -9,7 +9,7 @@ Register a new context provider. Signature: ```typescript -registerContext(pluginOpaqueId: PluginOpaqueId, contextName: TContextName, provider: IContextProvider): this; +registerContext>(pluginOpaqueId: PluginOpaqueId, contextName: TContextName, provider: IContextProvider): this; ``` ## Parameters @@ -18,7 +18,7 @@ registerContext(pluginOpaqueId: PluginOpaqu | --- | --- | --- | | pluginOpaqueId | PluginOpaqueId | The plugin opaque ID for the plugin that registers this context. | | contextName | TContextName | The key of the TContext object this provider supplies the value for. | -| provider | IContextProvider<TContext, TContextName, THandlerParameters> | A [IContextProvider](./kibana-plugin-public.icontextprovider.md) to be called each time a new context is created. | +| provider | IContextProvider<THandler, TContextName> | A [IContextProvider](./kibana-plugin-public.icontextprovider.md) to be called each time a new context is created. | Returns: diff --git a/docs/development/core/public/kibana-plugin-public.icontexthandler.md b/docs/development/core/public/kibana-plugin-public.icontexthandler.md deleted file mode 100644 index 2251b1131c3138..00000000000000 --- a/docs/development/core/public/kibana-plugin-public.icontexthandler.md +++ /dev/null @@ -1,18 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [IContextHandler](./kibana-plugin-public.icontexthandler.md) - -## IContextHandler type - -A function registered by a plugin to perform some action. - -Signature: - -```typescript -export declare type IContextHandler = (context: TContext, ...rest: THandlerParameters) => TReturn; -``` - -## Remarks - -A new `TContext` will be built for each handler before invoking. - diff --git a/docs/development/core/public/kibana-plugin-public.icontextprovider.md b/docs/development/core/public/kibana-plugin-public.icontextprovider.md index a84917d6e14420..40f0ee3782f6da 100644 --- a/docs/development/core/public/kibana-plugin-public.icontextprovider.md +++ b/docs/development/core/public/kibana-plugin-public.icontextprovider.md @@ -9,7 +9,7 @@ A function that returns a context value for a specific key of given context type Signature: ```typescript -export declare type IContextProvider, TContextName extends keyof TContext, TProviderParameters extends any[] = []> = (context: Partial, ...rest: TProviderParameters) => Promise | TContext[TContextName]; +export declare type IContextProvider, TContextName extends keyof HandlerContextType> = (context: Partial>, ...rest: HandlerParameters) => Promise[TContextName]> | HandlerContextType[TContextName]; ``` ## Remarks diff --git a/docs/development/core/public/kibana-plugin-public.md b/docs/development/core/public/kibana-plugin-public.md index e2ef807a75018c..7531cf9a063336 100644 --- a/docs/development/core/public/kibana-plugin-public.md +++ b/docs/development/core/public/kibana-plugin-public.md @@ -91,11 +91,13 @@ The plugin integrates with the core system via lifecycle events: `setup` | [AppUnmount](./kibana-plugin-public.appunmount.md) | A function called when an application should be unmounted from the page. This function should be synchronous. | | [ChromeHelpExtension](./kibana-plugin-public.chromehelpextension.md) | | | [ChromeNavLinkUpdateableFields](./kibana-plugin-public.chromenavlinkupdateablefields.md) | | +| [HandlerContextType](./kibana-plugin-public.handlercontexttype.md) | Extracts the type of the first argument of a [HandlerFunction](./kibana-plugin-public.handlerfunction.md) to represent the type of the context. | +| [HandlerFunction](./kibana-plugin-public.handlerfunction.md) | A function that accepts a context object and an optional number of additional arguments. Used for the generic types in [IContextContainer](./kibana-plugin-public.icontextcontainer.md) | +| [HandlerParameters](./kibana-plugin-public.handlerparameters.md) | Extracts the types of the additional arguments of a [HandlerFunction](./kibana-plugin-public.handlerfunction.md), excluding the [HandlerContextType](./kibana-plugin-public.handlercontexttype.md). | | [HttpBody](./kibana-plugin-public.httpbody.md) | | | [HttpHandler](./kibana-plugin-public.httphandler.md) | | | [HttpSetup](./kibana-plugin-public.httpsetup.md) | | | [HttpStart](./kibana-plugin-public.httpstart.md) | | -| [IContextHandler](./kibana-plugin-public.icontexthandler.md) | A function registered by a plugin to perform some action. | | [IContextProvider](./kibana-plugin-public.icontextprovider.md) | A function that returns a context value for a specific key of given context type. | | [OverlayBannerMount](./kibana-plugin-public.overlaybannermount.md) | A function that will mount the banner inside the provided element. | | [OverlayBannerUnmount](./kibana-plugin-public.overlaybannerunmount.md) | A function that will unmount the banner from the element. | diff --git a/docs/development/core/server/kibana-plugin-server.basepath.get.md b/docs/development/core/server/kibana-plugin-server.basepath.get.md index 2b3b6c899e8ded..04feca7ccc5a87 100644 --- a/docs/development/core/server/kibana-plugin-server.basepath.get.md +++ b/docs/development/core/server/kibana-plugin-server.basepath.get.md @@ -9,5 +9,5 @@ returns `basePath` value, specific for an incoming request. Signature: ```typescript -get: (request: KibanaRequest | LegacyRequest) => string; +get: (request: LegacyRequest | KibanaRequest) => string; ``` diff --git a/docs/development/core/server/kibana-plugin-server.basepath.md b/docs/development/core/server/kibana-plugin-server.basepath.md index 45fb697b329f89..bfa1ea02aec178 100644 --- a/docs/development/core/server/kibana-plugin-server.basepath.md +++ b/docs/development/core/server/kibana-plugin-server.basepath.md @@ -16,11 +16,11 @@ export declare class BasePath | Property | Modifiers | Type | Description | | --- | --- | --- | --- | -| [get](./kibana-plugin-server.basepath.get.md) | | (request: KibanaRequest<unknown, unknown, unknown> | LegacyRequest) => string | returns basePath value, specific for an incoming request. | +| [get](./kibana-plugin-server.basepath.get.md) | | (request: LegacyRequest | KibanaRequest<unknown, unknown, unknown>) => string | returns basePath value, specific for an incoming request. | | [prepend](./kibana-plugin-server.basepath.prepend.md) | | (path: string) => string | returns a new basePath value, prefixed with passed url. | | [remove](./kibana-plugin-server.basepath.remove.md) | | (path: string) => string | returns a new basePath value, cleaned up from passed url. | | [serverBasePath](./kibana-plugin-server.basepath.serverbasepath.md) | | string | returns the server's basePathSee [BasePath.get](./kibana-plugin-server.basepath.get.md) for getting the basePath value for a specific request | -| [set](./kibana-plugin-server.basepath.set.md) | | (request: KibanaRequest<unknown, unknown, unknown> | LegacyRequest, requestSpecificBasePath: string) => void | sets basePath value, specific for an incoming request. | +| [set](./kibana-plugin-server.basepath.set.md) | | (request: LegacyRequest | KibanaRequest<unknown, unknown, unknown>, requestSpecificBasePath: string) => void | sets basePath value, specific for an incoming request. | ## Remarks diff --git a/docs/development/core/server/kibana-plugin-server.basepath.set.md b/docs/development/core/server/kibana-plugin-server.basepath.set.md index 1272a134ef5c44..cec70ee853bfa4 100644 --- a/docs/development/core/server/kibana-plugin-server.basepath.set.md +++ b/docs/development/core/server/kibana-plugin-server.basepath.set.md @@ -9,5 +9,5 @@ sets `basePath` value, specific for an incoming request. Signature: ```typescript -set: (request: KibanaRequest | LegacyRequest, requestSpecificBasePath: string) => void; +set: (request: LegacyRequest | KibanaRequest, requestSpecificBasePath: string) => void; ``` diff --git a/docs/development/core/server/kibana-plugin-server.contextsetup.createcontextcontainer.md b/docs/development/core/server/kibana-plugin-server.contextsetup.createcontextcontainer.md index f44e6a3d7640b7..7096bfc43a520b 100644 --- a/docs/development/core/server/kibana-plugin-server.contextsetup.createcontextcontainer.md +++ b/docs/development/core/server/kibana-plugin-server.contextsetup.createcontextcontainer.md @@ -9,9 +9,9 @@ Creates a new [IContextContainer](./kibana-plugin-server.icontextcontainer.md) f Signature: ```typescript -createContextContainer(): IContextContainer; +createContextContainer>(): IContextContainer; ``` Returns: -`IContextContainer` +`IContextContainer` diff --git a/docs/development/core/server/kibana-plugin-server.coresetup.http.md b/docs/development/core/server/kibana-plugin-server.coresetup.http.md index 254f2728abef16..8474f4ef940dc6 100644 --- a/docs/development/core/server/kibana-plugin-server.coresetup.http.md +++ b/docs/development/core/server/kibana-plugin-server.coresetup.http.md @@ -14,7 +14,7 @@ http: { registerOnPostAuth: HttpServiceSetup['registerOnPostAuth']; basePath: HttpServiceSetup['basePath']; isTlsEnabled: HttpServiceSetup['isTlsEnabled']; - registerRouteHandlerContext: (name: T, provider: RequestHandlerContextProvider) => RequestHandlerContextContainer; + registerRouteHandlerContext: (name: T, provider: RequestHandlerContextProvider) => RequestHandlerContextContainer; createRouter: () => IRouter; }; ``` diff --git a/docs/development/core/server/kibana-plugin-server.coresetup.md b/docs/development/core/server/kibana-plugin-server.coresetup.md index ed487a570f2863..528557e91bd17f 100644 --- a/docs/development/core/server/kibana-plugin-server.coresetup.md +++ b/docs/development/core/server/kibana-plugin-server.coresetup.md @@ -18,5 +18,5 @@ export interface CoreSetup | --- | --- | --- | | [context](./kibana-plugin-server.coresetup.context.md) | {
createContextContainer: ContextSetup['createContextContainer'];
} | | | [elasticsearch](./kibana-plugin-server.coresetup.elasticsearch.md) | {
adminClient$: Observable<ClusterClient>;
dataClient$: Observable<ClusterClient>;
createClient: (type: string, clientConfig?: Partial<ElasticsearchClientConfig>) => ClusterClient;
} | | -| [http](./kibana-plugin-server.coresetup.http.md) | {
createCookieSessionStorageFactory: HttpServiceSetup['createCookieSessionStorageFactory'];
registerOnPreAuth: HttpServiceSetup['registerOnPreAuth'];
registerAuth: HttpServiceSetup['registerAuth'];
registerOnPostAuth: HttpServiceSetup['registerOnPostAuth'];
basePath: HttpServiceSetup['basePath'];
isTlsEnabled: HttpServiceSetup['isTlsEnabled'];
registerRouteHandlerContext: <T extends keyof RequestHandlerContext>(name: T, provider: RequestHandlerContextProvider<RequestHandlerContext>) => RequestHandlerContextContainer<RequestHandlerContext>;
createRouter: () => IRouter;
} | | +| [http](./kibana-plugin-server.coresetup.http.md) | {
createCookieSessionStorageFactory: HttpServiceSetup['createCookieSessionStorageFactory'];
registerOnPreAuth: HttpServiceSetup['registerOnPreAuth'];
registerAuth: HttpServiceSetup['registerAuth'];
registerOnPostAuth: HttpServiceSetup['registerOnPostAuth'];
basePath: HttpServiceSetup['basePath'];
isTlsEnabled: HttpServiceSetup['isTlsEnabled'];
registerRouteHandlerContext: <T extends keyof RequestHandlerContext>(name: T, provider: RequestHandlerContextProvider<T>) => RequestHandlerContextContainer;
createRouter: () => IRouter;
} | | diff --git a/docs/development/core/server/kibana-plugin-server.handlercontexttype.md b/docs/development/core/server/kibana-plugin-server.handlercontexttype.md new file mode 100644 index 00000000000000..e8f1f346e8b8e7 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.handlercontexttype.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [HandlerContextType](./kibana-plugin-server.handlercontexttype.md) + +## HandlerContextType type + +Extracts the type of the first argument of a [HandlerFunction](./kibana-plugin-server.handlerfunction.md) to represent the type of the context. + +Signature: + +```typescript +export declare type HandlerContextType> = T extends HandlerFunction ? U : never; +``` diff --git a/docs/development/core/server/kibana-plugin-server.handlerfunction.md b/docs/development/core/server/kibana-plugin-server.handlerfunction.md new file mode 100644 index 00000000000000..97acd37946fc94 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.handlerfunction.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [HandlerFunction](./kibana-plugin-server.handlerfunction.md) + +## HandlerFunction type + +A function that accepts a context object and an optional number of additional arguments. Used for the generic types in [IContextContainer](./kibana-plugin-server.icontextcontainer.md) + +Signature: + +```typescript +export declare type HandlerFunction = (context: T, ...args: any[]) => any; +``` diff --git a/docs/development/core/server/kibana-plugin-server.handlerparameters.md b/docs/development/core/server/kibana-plugin-server.handlerparameters.md new file mode 100644 index 00000000000000..3dd7998a71a1f2 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.handlerparameters.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [HandlerParameters](./kibana-plugin-server.handlerparameters.md) + +## HandlerParameters type + +Extracts the types of the additional arguments of a [HandlerFunction](./kibana-plugin-server.handlerfunction.md), excluding the [HandlerContextType](./kibana-plugin-server.handlercontexttype.md). + +Signature: + +```typescript +export declare type HandlerParameters> = T extends (context: any, ...args: infer U) => any ? U : never; +``` diff --git a/docs/development/core/server/kibana-plugin-server.httpservicesetup.md b/docs/development/core/server/kibana-plugin-server.httpservicesetup.md index 92bf158ad33129..eec63cf5c80931 100644 --- a/docs/development/core/server/kibana-plugin-server.httpservicesetup.md +++ b/docs/development/core/server/kibana-plugin-server.httpservicesetup.md @@ -10,6 +10,6 @@ ```typescript export declare type HttpServiceSetup = Omit & { createRouter: (path: string, plugin?: PluginOpaqueId) => IRouter; - registerRouteHandlerContext: (pluginOpaqueId: PluginOpaqueId, contextName: T, provider: RequestHandlerContextProvider) => RequestHandlerContextContainer; + registerRouteHandlerContext: (pluginOpaqueId: PluginOpaqueId, contextName: T, provider: RequestHandlerContextProvider) => RequestHandlerContextContainer; }; ``` diff --git a/docs/development/core/server/kibana-plugin-server.icontextcontainer.createhandler.md b/docs/development/core/server/kibana-plugin-server.icontextcontainer.createhandler.md index c5549ab017e530..09a9e28d6d0fe8 100644 --- a/docs/development/core/server/kibana-plugin-server.icontextcontainer.createhandler.md +++ b/docs/development/core/server/kibana-plugin-server.icontextcontainer.createhandler.md @@ -9,7 +9,7 @@ Create a new handler function pre-wired to context for the plugin. Signature: ```typescript -createHandler(pluginOpaqueId: PluginOpaqueId, handler: IContextHandler): (...rest: THandlerParameters) => THandlerReturn extends Promise ? THandlerReturn : Promise; +createHandler(pluginOpaqueId: PluginOpaqueId, handler: THandler): (...rest: HandlerParameters) => ShallowPromise>; ``` ## Parameters @@ -17,11 +17,11 @@ createHandler(pluginOpaqueId: PluginOpaqueId, handler: IContextHandlerPluginOpaqueId | The plugin opaque ID for the plugin that registers this handler. | -| handler | IContextHandler<TContext, THandlerReturn, THandlerParameters> | Handler function to pass context object to. | +| handler | THandler | Handler function to pass context object to. | Returns: -`(...rest: THandlerParameters) => THandlerReturn extends Promise ? THandlerReturn : Promise` +`(...rest: HandlerParameters) => ShallowPromise>` A function that takes `THandlerParameters`, calls `handler` with a new context, and returns a Promise of the `handler` return value. diff --git a/docs/development/core/server/kibana-plugin-server.icontextcontainer.md b/docs/development/core/server/kibana-plugin-server.icontextcontainer.md index 1ab699be105b4b..114da31442ff9b 100644 --- a/docs/development/core/server/kibana-plugin-server.icontextcontainer.md +++ b/docs/development/core/server/kibana-plugin-server.icontextcontainer.md @@ -9,7 +9,7 @@ An object that handles registration of context providers and configuring handler Signature: ```typescript -export interface IContextContainer +export interface IContextContainer> ``` ## Methods diff --git a/docs/development/core/server/kibana-plugin-server.icontextcontainer.registercontext.md b/docs/development/core/server/kibana-plugin-server.icontextcontainer.registercontext.md index 1a63f63dc91b46..30d3fc154d1e93 100644 --- a/docs/development/core/server/kibana-plugin-server.icontextcontainer.registercontext.md +++ b/docs/development/core/server/kibana-plugin-server.icontextcontainer.registercontext.md @@ -9,7 +9,7 @@ Register a new context provider. Signature: ```typescript -registerContext(pluginOpaqueId: PluginOpaqueId, contextName: TContextName, provider: IContextProvider): this; +registerContext>(pluginOpaqueId: PluginOpaqueId, contextName: TContextName, provider: IContextProvider): this; ``` ## Parameters @@ -18,7 +18,7 @@ registerContext(pluginOpaqueId: PluginOpaqu | --- | --- | --- | | pluginOpaqueId | PluginOpaqueId | The plugin opaque ID for the plugin that registers this context. | | contextName | TContextName | The key of the TContext object this provider supplies the value for. | -| provider | IContextProvider<TContext, TContextName, THandlerParameters> | A [IContextProvider](./kibana-plugin-server.icontextprovider.md) to be called each time a new context is created. | +| provider | IContextProvider<THandler, TContextName> | A [IContextProvider](./kibana-plugin-server.icontextprovider.md) to be called each time a new context is created. | Returns: diff --git a/docs/development/core/server/kibana-plugin-server.icontexthandler.md b/docs/development/core/server/kibana-plugin-server.icontexthandler.md deleted file mode 100644 index c1f5acc22734aa..00000000000000 --- a/docs/development/core/server/kibana-plugin-server.icontexthandler.md +++ /dev/null @@ -1,18 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [IContextHandler](./kibana-plugin-server.icontexthandler.md) - -## IContextHandler type - -A function registered by a plugin to perform some action. - -Signature: - -```typescript -export declare type IContextHandler = (context: TContext, ...rest: THandlerParameters) => TReturn; -``` - -## Remarks - -A new `TContext` will be built for each handler before invoking. - diff --git a/docs/development/core/server/kibana-plugin-server.icontextprovider.md b/docs/development/core/server/kibana-plugin-server.icontextprovider.md index 250e6a2be3f6ae..39ace8b9bc57ee 100644 --- a/docs/development/core/server/kibana-plugin-server.icontextprovider.md +++ b/docs/development/core/server/kibana-plugin-server.icontextprovider.md @@ -9,7 +9,7 @@ A function that returns a context value for a specific key of given context type Signature: ```typescript -export declare type IContextProvider, TContextName extends keyof TContext, TProviderParameters extends any[] = []> = (context: Partial, ...rest: TProviderParameters) => Promise | TContext[TContextName]; +export declare type IContextProvider, TContextName extends keyof HandlerContextType> = (context: Partial>, ...rest: HandlerParameters) => Promise[TContextName]> | HandlerContextType[TContextName]; ``` ## Remarks diff --git a/docs/development/core/server/kibana-plugin-server.md b/docs/development/core/server/kibana-plugin-server.md index d943228bbea06b..3c01e7aeef325b 100644 --- a/docs/development/core/server/kibana-plugin-server.md +++ b/docs/development/core/server/kibana-plugin-server.md @@ -116,11 +116,13 @@ The plugin integrates with the core system via lifecycle events: `setup` | [ElasticsearchClientConfig](./kibana-plugin-server.elasticsearchclientconfig.md) | | | [GetAuthHeaders](./kibana-plugin-server.getauthheaders.md) | Get headers to authenticate a user against Elasticsearch. | | [GetAuthState](./kibana-plugin-server.getauthstate.md) | Get authentication state for a request. Returned by auth interceptor. | +| [HandlerContextType](./kibana-plugin-server.handlercontexttype.md) | Extracts the type of the first argument of a [HandlerFunction](./kibana-plugin-server.handlerfunction.md) to represent the type of the context. | +| [HandlerFunction](./kibana-plugin-server.handlerfunction.md) | A function that accepts a context object and an optional number of additional arguments. Used for the generic types in [IContextContainer](./kibana-plugin-server.icontextcontainer.md) | +| [HandlerParameters](./kibana-plugin-server.handlerparameters.md) | Extracts the types of the additional arguments of a [HandlerFunction](./kibana-plugin-server.handlerfunction.md), excluding the [HandlerContextType](./kibana-plugin-server.handlercontexttype.md). | | [Headers](./kibana-plugin-server.headers.md) | Http request headers to read. | | [HttpResponsePayload](./kibana-plugin-server.httpresponsepayload.md) | Data send to the client as a response payload. | | [HttpServiceSetup](./kibana-plugin-server.httpservicesetup.md) | | | [IBasePath](./kibana-plugin-server.ibasepath.md) | Access or manipulate the Kibana base path[BasePath](./kibana-plugin-server.basepath.md) | -| [IContextHandler](./kibana-plugin-server.icontexthandler.md) | A function registered by a plugin to perform some action. | | [IContextProvider](./kibana-plugin-server.icontextprovider.md) | A function that returns a context value for a specific key of given context type. | | [IsAuthenticated](./kibana-plugin-server.isauthenticated.md) | Return authentication status for a request. | | [KibanaResponseFactory](./kibana-plugin-server.kibanaresponsefactory.md) | Creates an object containing request response payload, HTTP headers, error details, and other data transmitted to the client. | @@ -136,8 +138,6 @@ The plugin integrates with the core system via lifecycle events: `setup` | [RequestHandler](./kibana-plugin-server.requesthandler.md) | A function executed when route path matched requested resource path. Request handler is expected to return a result of one of [KibanaResponseFactory](./kibana-plugin-server.kibanaresponsefactory.md) functions. | | [RequestHandlerContextContainer](./kibana-plugin-server.requesthandlercontextcontainer.md) | An object that handles registration of http request context providers. | | [RequestHandlerContextProvider](./kibana-plugin-server.requesthandlercontextprovider.md) | Context provider for request handler. Extends request context object with provided functionality or data. | -| [RequestHandlerParams](./kibana-plugin-server.requesthandlerparams.md) | Parameters passed to the request handler function. | -| [RequestHandlerReturn](./kibana-plugin-server.requesthandlerreturn.md) | Expected outcome the request handler function. | | [ResponseError](./kibana-plugin-server.responseerror.md) | Error message and optional data send to the client in case of error. | | [ResponseErrorAttributes](./kibana-plugin-server.responseerrorattributes.md) | Additional data to provide error details. | | [ResponseHeaders](./kibana-plugin-server.responseheaders.md) | Http response headers to set. | diff --git a/docs/development/core/server/kibana-plugin-server.requesthandlercontextcontainer.md b/docs/development/core/server/kibana-plugin-server.requesthandlercontextcontainer.md index afdb4885970696..b76a9ce7d235ca 100644 --- a/docs/development/core/server/kibana-plugin-server.requesthandlercontextcontainer.md +++ b/docs/development/core/server/kibana-plugin-server.requesthandlercontextcontainer.md @@ -9,5 +9,5 @@ An object that handles registration of http request context providers. Signature: ```typescript -export declare type RequestHandlerContextContainer = IContextContainer, RequestHandlerParams>; +export declare type RequestHandlerContextContainer = IContextContainer>; ``` diff --git a/docs/development/core/server/kibana-plugin-server.requesthandlercontextprovider.md b/docs/development/core/server/kibana-plugin-server.requesthandlercontextprovider.md index 0d9cc6b70b80c0..ea7294b721aabd 100644 --- a/docs/development/core/server/kibana-plugin-server.requesthandlercontextprovider.md +++ b/docs/development/core/server/kibana-plugin-server.requesthandlercontextprovider.md @@ -9,5 +9,5 @@ Context provider for request handler. Extends request context object with provid Signature: ```typescript -export declare type RequestHandlerContextProvider = IContextProvider; +export declare type RequestHandlerContextProvider = IContextProvider, TContextName>; ``` diff --git a/docs/development/core/server/kibana-plugin-server.requesthandlerparams.md b/docs/development/core/server/kibana-plugin-server.requesthandlerparams.md deleted file mode 100644 index 7f466845b4d460..00000000000000 --- a/docs/development/core/server/kibana-plugin-server.requesthandlerparams.md +++ /dev/null @@ -1,13 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [RequestHandlerParams](./kibana-plugin-server.requesthandlerparams.md) - -## RequestHandlerParams type - -Parameters passed to the request handler function. - -Signature: - -```typescript -export declare type RequestHandlerParams = [KibanaRequest, KibanaResponseFactory]; -``` diff --git a/docs/development/core/server/kibana-plugin-server.requesthandlerreturn.md b/docs/development/core/server/kibana-plugin-server.requesthandlerreturn.md deleted file mode 100644 index 6c01e21b6ecbe9..00000000000000 --- a/docs/development/core/server/kibana-plugin-server.requesthandlerreturn.md +++ /dev/null @@ -1,13 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [RequestHandlerReturn](./kibana-plugin-server.requesthandlerreturn.md) - -## RequestHandlerReturn type - -Expected outcome the request handler function. - -Signature: - -```typescript -export declare type RequestHandlerReturn = KibanaResponse; -``` diff --git a/docs/management/index-patterns.asciidoc b/docs/management/index-patterns.asciidoc index 25c07dc5024840..8d9ef515108eda 100644 --- a/docs/management/index-patterns.asciidoc +++ b/docs/management/index-patterns.asciidoc @@ -35,8 +35,11 @@ image:management/index-patterns/images/rollup-index-pattern.png["Menu with rollu {kib} makes it easy for you to create an index pattern by walking you through the process. Just start typing in the *Index pattern* field, and {kib} looks for -the names of {es} indices that match your input. If you want to include -system indices in your search, toggle the switch in the upper right. +the names of {es} indices that match your input. Make sure that the name of the +index pattern is unique. + +If you want to include system indices in your search, toggle the switch in the +upper right. [role="screenshot"] image:management/index-patterns/images/create-index-pattern.png["Create index pattern"] diff --git a/docs/settings/monitoring-settings.asciidoc b/docs/settings/monitoring-settings.asciidoc index 7330c7e144b60e..97fb891c95bdba 100644 --- a/docs/settings/monitoring-settings.asciidoc +++ b/docs/settings/monitoring-settings.asciidoc @@ -21,7 +21,7 @@ To control how data is collected from your {es} nodes, you configure {ref}/monitoring-settings.html[`xpack.monitoring.collection` settings] in `elasticsearch.yml`. To control how monitoring data is collected from Logstash, you configure -{logstash-ref}/configuring-logstash.html#monitoring-settings[`xpack.monitoring` settings] +{logstash-ref}/monitoring-internal-collection.html#monitoring-settings[`xpack.monitoring` settings] in `logstash.yml`. For more information, see diff --git a/docs/setup/settings.asciidoc b/docs/setup/settings.asciidoc index a875aa134b0d85..a5052123ec14c4 100644 --- a/docs/setup/settings.asciidoc +++ b/docs/setup/settings.asciidoc @@ -271,10 +271,9 @@ identifies this Kibana instance. `server.port:`:: *Default: 5601* Kibana is served by a back end server. This setting specifies the port to use. -`server.rewriteBasePath:`:: *Default: false* Specifies whether Kibana should -rewrite requests that are prefixed with `server.basePath` or require that they -are rewritten by your reverse proxy. This setting was effectively always `false` -before Kibana 6.3 and will default to `true` starting in Kibana 7.0. +`server.rewriteBasePath:`:: *Default: false* Deprecated setting that specifies if Kibana should +rewrite requests that are prefixed with `server.basePath`, or require that they +are rewritten by your reverse proxy. `server.socketTimeout:`:: *Default: "120000"* The number of milliseconds to wait before closing an inactive socket. diff --git a/package.json b/package.json index 2ce0461bb4d3ea..d2e05e0026c2a7 100644 --- a/package.json +++ b/package.json @@ -104,9 +104,9 @@ "dependencies": { "@babel/core": "^7.5.5", "@babel/register": "^7.5.5", - "@elastic/charts": "^12.0.2", + "@elastic/charts": "^12.1.0", "@elastic/datemath": "5.0.2", - "@elastic/eui": "14.3.0", + "@elastic/eui": "14.4.0", "@elastic/filesaver": "1.1.2", "@elastic/good": "8.1.1-kibana2", "@elastic/numeral": "2.3.3", @@ -194,7 +194,6 @@ "markdown-it": "^8.4.1", "mini-css-extract-plugin": "0.8.0", "minimatch": "^3.0.4", - "mkdirp": "0.5.1", "moment": "^2.20.1", "moment-timezone": "^0.5.14", "mustache": "2.3.2", @@ -238,7 +237,7 @@ "style-loader": "0.23.1", "symbol-observable": "^1.2.0", "tar": "4.4.13", - "terser-webpack-plugin": "^1.4.1", + "terser-webpack-plugin": "^2.1.2", "thread-loader": "^2.1.3", "tinygradient": "0.4.3", "tinymath": "1.2.1", @@ -248,7 +247,7 @@ "tslib": "^1.9.3", "type-detect": "^4.0.8", "ui-select": "0.19.8", - "url-loader": "2.1.0", + "url-loader": "2.2.0", "uuid": "3.3.2", "val-loader": "^1.1.1", "validate-npm-package-name": "2.2.2", @@ -257,8 +256,8 @@ "vega-schema-url-parser": "1.0.0", "vega-tooltip": "^0.9.14", "vision": "^5.3.3", - "webpack": "4.39.2", - "webpack-merge": "4.2.1", + "webpack": "4.41.0", + "webpack-merge": "4.2.2", "whatwg-fetch": "^3.0.0", "yauzl": "2.10.0" }, @@ -320,7 +319,6 @@ "@types/lru-cache": "^5.1.0", "@types/markdown-it": "^0.0.7", "@types/minimatch": "^2.0.29", - "@types/mkdirp": "^0.5.2", "@types/mocha": "^5.2.7", "@types/moment-timezone": "^0.5.8", "@types/mustache": "^0.8.31", @@ -338,7 +336,7 @@ "@types/redux-actions": "^2.2.1", "@types/request": "^2.48.2", "@types/rimraf": "^2.0.2", - "@types/selenium-webdriver": "^3.0.16", + "@types/selenium-webdriver": "^4.0.3", "@types/semver": "^5.5.0", "@types/sinon": "^7.0.13", "@types/strip-ansi": "^3.0.0", @@ -346,6 +344,7 @@ "@types/supertest": "^2.0.5", "@types/type-detect": "^4.0.1", "@types/uuid": "^3.4.4", + "@types/vinyl-fs": "^2.4.11", "@types/zen-observable": "^0.8.0", "@typescript-eslint/eslint-plugin": "1.13.0", "@typescript-eslint/parser": "1.13.0", @@ -358,7 +357,7 @@ "chai": "3.5.0", "chance": "1.0.18", "cheerio": "0.22.0", - "chokidar": "3.0.2", + "chokidar": "3.2.1", "chromedriver": "^77.0.0", "classnames": "2.2.6", "dedent": "^0.7.0", @@ -435,7 +434,7 @@ "proxyquire": "1.8.0", "regenerate": "^1.4.0", "sass-lint": "^1.12.1", - "selenium-webdriver": "^4.0.0-alpha.4", + "selenium-webdriver": "^4.0.0-alpha.5", "simple-git": "1.116.0", "sinon": "^7.4.2", "strip-ansi": "^3.0.1", diff --git a/packages/eslint-config-kibana/.eslintrc.js b/packages/eslint-config-kibana/.eslintrc.js index 6d39eb98ddb4bc..b0a6396c90818f 100644 --- a/packages/eslint-config-kibana/.eslintrc.js +++ b/packages/eslint-config-kibana/.eslintrc.js @@ -22,6 +22,11 @@ module.exports = { from: 'expect.js', to: '@kbn/expect', }, + { + from: 'mkdirp', + to: false, + disallowedMessage: `Don't use 'mkdirp', use the new { recursive: true } option of Fs.mkdir instead` + }, { from: 'x-pack', toRelative: 'x-pack', diff --git a/packages/kbn-es-query/src/es_query/index.d.ts b/packages/kbn-es-query/src/es_query/index.d.ts new file mode 100644 index 00000000000000..9510a18441e53c --- /dev/null +++ b/packages/kbn-es-query/src/es_query/index.d.ts @@ -0,0 +1,39 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export function buildQueryFromFilters(filters: unknown[], indexPattern: unknown): unknown; +export function buildEsQuery( + indexPattern: unknown, + queries: unknown, + filters: unknown, + config?: { + allowLeadingWildcards: boolean; + queryStringOptions: unknown; + ignoreFilterIfFieldNotInIndex: boolean; + dateFormatTZ?: string | null; + } +): unknown; +export function getEsQueryConfig(config: { + get: (name: string) => unknown; +}): { + allowLeadingWildcards: boolean; + queryStringOptions: unknown; + ignoreFilterIfFieldNotInIndex: boolean; + dateFormatTZ?: string | null; +}; diff --git a/packages/kbn-es-query/src/index.d.ts b/packages/kbn-es-query/src/index.d.ts index 873636a28889fd..ca4455da33f45d 100644 --- a/packages/kbn-es-query/src/index.d.ts +++ b/packages/kbn-es-query/src/index.d.ts @@ -17,5 +17,6 @@ * under the License. */ +export * from './es_query'; export * from './kuery'; export * from './filters'; diff --git a/packages/kbn-es/package.json b/packages/kbn-es/package.json index 1064d719af837e..5521d57c22e863 100644 --- a/packages/kbn-es/package.json +++ b/packages/kbn-es/package.json @@ -5,7 +5,7 @@ "license": "Apache-2.0", "private": true, "dependencies": { - "@elastic/elasticsearch": "^7.3.0", + "@elastic/elasticsearch": "^7.4.0", "@kbn/dev-utils": "1.0.0", "abort-controller": "^2.0.3", "chalk": "^2.4.2", @@ -14,7 +14,6 @@ "execa": "^1.0.0", "getopts": "^2.2.4", "glob": "^7.1.2", - "mkdirp": "^0.5.1", "node-fetch": "^2.6.0", "simple-git": "^1.91.0", "tar-fs": "^1.16.3", diff --git a/packages/kbn-es/src/artifact.js b/packages/kbn-es/src/artifact.js index 3398663a2acf3d..19d95e82fe4800 100644 --- a/packages/kbn-es/src/artifact.js +++ b/packages/kbn-es/src/artifact.js @@ -22,7 +22,6 @@ const AbortController = require('abort-controller'); const fs = require('fs'); const { promisify } = require('util'); const { pipeline, Transform } = require('stream'); -const mkdirp = require('mkdirp'); const chalk = require('chalk'); const { createHash } = require('crypto'); const path = require('path'); @@ -285,7 +284,8 @@ exports.Artifact = class Artifact { let first500Bytes = Buffer.alloc(0); let contentLength = 0; - mkdirp.sync(path.dirname(tmpPath)); + fs.mkdirSync(path.dirname(tmpPath), { recursive: true }); + await asyncPipeline( resp.body, new Transform({ diff --git a/packages/kbn-es/src/cli_commands/build_snapshots.js b/packages/kbn-es/src/cli_commands/build_snapshots.js index eca904c144af4d..7c2dcff4aa7966 100644 --- a/packages/kbn-es/src/cli_commands/build_snapshots.js +++ b/packages/kbn-es/src/cli_commands/build_snapshots.js @@ -24,7 +24,6 @@ const { pipeline, Transform } = require('stream'); const Fs = require('fs'); const getopts = require('getopts'); -const mkdirp = require('mkdirp'); const del = require('del'); const { buildSnapshot, log } = require('../utils'); @@ -49,7 +48,7 @@ exports.run = async (defaults = {}) => { const outputDir = resolve(process.cwd(), options.output); del.sync(outputDir); - mkdirp.sync(outputDir); + Fs.mkdirSync(outputDir, { recursive: true }); for (const license of ['oss', 'trial']) { for (const platform of ['darwin', 'win32', 'linux']) { diff --git a/packages/kbn-es/src/utils/cache.js b/packages/kbn-es/src/utils/cache.js index 01f4b9f374c925..a8bc663ecf096b 100644 --- a/packages/kbn-es/src/utils/cache.js +++ b/packages/kbn-es/src/utils/cache.js @@ -18,7 +18,6 @@ */ const fs = require('fs'); -const mkdirp = require('mkdirp'); const path = require('path'); exports.readMeta = function readMeta(file) { @@ -48,6 +47,6 @@ exports.writeMeta = function readMeta(file, details = {}) { ...details, }; - mkdirp.sync(path.dirname(file)); + fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(`${file}.meta`, JSON.stringify(meta, null, 2)); }; diff --git a/packages/kbn-es/src/utils/decompress.js b/packages/kbn-es/src/utils/decompress.js index a0e0d832ff7396..b4299594c50627 100644 --- a/packages/kbn-es/src/utils/decompress.js +++ b/packages/kbn-es/src/utils/decompress.js @@ -21,7 +21,6 @@ const fs = require('fs'); const path = require('path'); const yauzl = require('yauzl'); -const mkdirp = require('mkdirp'); const zlib = require('zlib'); const tarFs = require('tar-fs'); @@ -38,7 +37,7 @@ function decompressTarball(archive, dirPath) { } function decompressZip(input, output) { - mkdirp.sync(output); + fs.mkdirSync(output, { recursive: true }); return new Promise((resolve, reject) => { yauzl.open(input, { lazyEntries: true }, (err, zipfile) => { if (err) { @@ -63,7 +62,7 @@ function decompressZip(input, output) { const fileName = path.resolve(output, zipPath); if (/\/$/.test(entry.fileName)) { - mkdirp.sync(fileName); + fs.mkdirSync(fileName, { recursive: true }); zipfile.readEntry(); } else { // file entry diff --git a/packages/kbn-es/src/utils/decompress.test.js b/packages/kbn-es/src/utils/decompress.test.js index ff36e952125761..a267950abc7a2d 100644 --- a/packages/kbn-es/src/utils/decompress.test.js +++ b/packages/kbn-es/src/utils/decompress.test.js @@ -20,7 +20,6 @@ const { decompress } = require('./decompress'); const fs = require('fs'); const path = require('path'); -const mkdirp = require('mkdirp'); const del = require('del'); const os = require('os'); @@ -34,9 +33,9 @@ const zipSnapshot = path.resolve(dataFolder, 'snapshot.zip'); const tarGzSnapshot = path.resolve(dataFolder, 'snapshot.tar.gz'); beforeEach(() => { - mkdirp.sync(tmpFolder); - mkdirp.sync(dataFolder); - mkdirp.sync(esFolder); + fs.mkdirSync(tmpFolder, { recursive: true }); + fs.mkdirSync(dataFolder, { recursive: true }); + fs.mkdirSync(esFolder, { recursive: true }); fs.copyFileSync(path.resolve(fixturesFolder, 'snapshot.zip'), zipSnapshot); fs.copyFileSync(path.resolve(fixturesFolder, 'snapshot.tar.gz'), tarGzSnapshot); diff --git a/packages/kbn-es/src/utils/extract_config_files.js b/packages/kbn-es/src/utils/extract_config_files.js index 7ad75dcbbf340b..a8a44a149e9b37 100644 --- a/packages/kbn-es/src/utils/extract_config_files.js +++ b/packages/kbn-es/src/utils/extract_config_files.js @@ -19,7 +19,6 @@ const path = require('path'); const fs = require('fs'); -const mkdirp = require('mkdirp'); /** * Copies config references to an absolute path to @@ -62,7 +61,7 @@ function copyFileSync(src, dest) { const destPath = path.dirname(dest); if (!fs.existsSync(destPath)) { - mkdirp(destPath); + fs.mkdirSync(destPath, { recursive: true }); } fs.writeFileSync(dest, fs.readFileSync(src)); diff --git a/packages/kbn-eslint-import-resolver-kibana/package.json b/packages/kbn-eslint-import-resolver-kibana/package.json index 14a9224924260e..9fae27011767e1 100755 --- a/packages/kbn-eslint-import-resolver-kibana/package.json +++ b/packages/kbn-eslint-import-resolver-kibana/package.json @@ -16,6 +16,6 @@ "glob-all": "^3.1.0", "lru-cache": "^4.1.5", "resolve": "^1.7.1", - "webpack": "^4.39.2" + "webpack": "^4.41.0" } } diff --git a/packages/kbn-eslint-plugin-eslint/rules/module_migration.js b/packages/kbn-eslint-plugin-eslint/rules/module_migration.js index c5f2aff9bfdcfc..8119d338ee5362 100644 --- a/packages/kbn-eslint-plugin-eslint/rules/module_migration.js +++ b/packages/kbn-eslint-plugin-eslint/rules/module_migration.js @@ -31,6 +31,14 @@ function checkModuleNameNode(context, mappings, node) { let newSource; + if (mapping.to === false) { + context.report({ + message: mapping.disallowedMessage || `Importing "${mapping.from}" is not allowed`, + loc: node.loc, + }); + return; + } + // support for toRelative added to migrate away from X-Pack being bundled // within node modules. after that migration, this can be removed. if (mapping.toRelative) { @@ -66,11 +74,21 @@ module.exports = { type: 'string', }, to: { - type: 'string', + anyOf: [ + { + type: 'string', + }, + { + const: false, + }, + ], }, toRelative: { type: 'string', }, + disallowedMessage: { + type: 'string', + }, }, anyOf: [ { diff --git a/packages/kbn-interpreter/package.json b/packages/kbn-interpreter/package.json index ab382c1390ff77..3e152e29d8e08c 100644 --- a/packages/kbn-interpreter/package.json +++ b/packages/kbn-interpreter/package.json @@ -30,8 +30,8 @@ "sass-loader": "^7.3.1", "style-loader": "0.23.1", "supports-color": "^5.5.0", - "url-loader": "2.1.0", - "webpack": "4.39.2", - "webpack-cli": "^3.3.7" + "url-loader": "2.2.0", + "webpack": "4.41.0", + "webpack-cli": "^3.3.9" } } diff --git a/packages/kbn-plugin-helpers/lib/index.d.ts b/packages/kbn-plugin-helpers/lib/index.d.ts new file mode 100644 index 00000000000000..1515bf6b84bfb2 --- /dev/null +++ b/packages/kbn-plugin-helpers/lib/index.d.ts @@ -0,0 +1,26 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export function babelRegister(): void; +export function resolveKibanaPath(path: string): string; +export function readFtrConfigFile(path: string): any; +export function run( + task: 'build' | 'start' | 'testAll' | 'testBrowser' | 'testServer' | 'postinstall', + options: any +): Promise; diff --git a/packages/kbn-plugin-helpers/package.json b/packages/kbn-plugin-helpers/package.json index c72b3d2abed97c..eca958d3860eec 100644 --- a/packages/kbn-plugin-helpers/package.json +++ b/packages/kbn-plugin-helpers/package.json @@ -21,7 +21,7 @@ "globby": "^8.0.1", "gulp-babel": "^8.0.0", "gulp-rename": "1.4.0", - "gulp-zip": "4.2.0", + "gulp-zip": "5.0.1", "inquirer": "^1.2.2", "minimatch": "^3.0.4", "node-sass": "^4.9.4", diff --git a/packages/kbn-plugin-helpers/tsconfig.json b/packages/kbn-plugin-helpers/tsconfig.json new file mode 100644 index 00000000000000..f5559aa7290c5d --- /dev/null +++ b/packages/kbn-plugin-helpers/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.json", + "include": ["lib/index.d.ts"] +} diff --git a/packages/kbn-pm/dist/index.js b/packages/kbn-pm/dist/index.js index b054e21c856a26..5d2f5c786f2c25 100644 --- a/packages/kbn-pm/dist/index.js +++ b/packages/kbn-pm/dist/index.js @@ -2697,11 +2697,11 @@ async function linkProjectExecutables(projectsByName, projectGraph) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unlink", function() { return unlink; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "copyDirectory", function() { return copyDirectory; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "chmod", function() { return chmod; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readFile", function() { return readFile; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "chmod", function() { return chmod; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mkdirp", function() { return mkdirp; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unlink", function() { return unlink; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "copyDirectory", function() { return copyDirectory; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSymlink", function() { return isSymlink; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDirectory", function() { return isDirectory; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFile", function() { return isFile; }); @@ -2710,14 +2710,12 @@ __webpack_require__.r(__webpack_exports__); /* harmony import */ var cmd_shim__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(cmd_shim__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(23); /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var mkdirp__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(31); -/* harmony import */ var mkdirp__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(mkdirp__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var ncp__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(33); -/* harmony import */ var ncp__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(ncp__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(16); -/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_4__); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(29); -/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_5__); +/* harmony import */ var ncp__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(33); +/* harmony import */ var ncp__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(ncp__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(16); +/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(29); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_4__); /* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with @@ -2741,16 +2739,17 @@ __webpack_require__.r(__webpack_exports__); - -const lstat = Object(util__WEBPACK_IMPORTED_MODULE_5__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.lstat); -const readFile = Object(util__WEBPACK_IMPORTED_MODULE_5__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.readFile); -const symlink = Object(util__WEBPACK_IMPORTED_MODULE_5__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.symlink); -const chmod = Object(util__WEBPACK_IMPORTED_MODULE_5__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.chmod); -const cmdShim = Object(util__WEBPACK_IMPORTED_MODULE_5__["promisify"])(cmd_shim__WEBPACK_IMPORTED_MODULE_0___default.a); -const mkdirp = Object(util__WEBPACK_IMPORTED_MODULE_5__["promisify"])(mkdirp__WEBPACK_IMPORTED_MODULE_2___default.a); -const unlink = Object(util__WEBPACK_IMPORTED_MODULE_5__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.unlink); -const copyDirectory = Object(util__WEBPACK_IMPORTED_MODULE_5__["promisify"])(ncp__WEBPACK_IMPORTED_MODULE_3__["ncp"]); - +const lstat = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.lstat); +const readFile = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.readFile); +const symlink = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.symlink); +const chmod = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.chmod); +const cmdShim = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(cmd_shim__WEBPACK_IMPORTED_MODULE_0___default.a); +const mkdir = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.mkdir); +const mkdirp = async path => await mkdir(path, { + recursive: true +}); +const unlink = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(fs__WEBPACK_IMPORTED_MODULE_1___default.a.unlink); +const copyDirectory = Object(util__WEBPACK_IMPORTED_MODULE_4__["promisify"])(ncp__WEBPACK_IMPORTED_MODULE_2__["ncp"]); async function statTest(path, block) { try { @@ -2808,7 +2807,7 @@ async function createSymlink(src, dest, type) { } } else { const posixType = type === 'exec' ? 'file' : type; - const relativeSource = Object(path__WEBPACK_IMPORTED_MODULE_4__["relative"])(Object(path__WEBPACK_IMPORTED_MODULE_4__["dirname"])(dest), src); + const relativeSource = Object(path__WEBPACK_IMPORTED_MODULE_3__["relative"])(Object(path__WEBPACK_IMPORTED_MODULE_3__["dirname"])(dest), src); await forceCreate(relativeSource, dest, posixType); } } diff --git a/packages/kbn-pm/package.json b/packages/kbn-pm/package.json index a3d3baed3750be..8480e74ceb3a20 100644 --- a/packages/kbn-pm/package.json +++ b/packages/kbn-pm/package.json @@ -26,7 +26,6 @@ "@types/indent-string": "^3.0.0", "@types/lodash.clonedeepwith": "^4.5.3", "@types/log-symbols": "^2.0.0", - "@types/mkdirp": "^0.5.2", "@types/ncp": "^2.0.1", "@types/node": "^10.12.27", "@types/ora": "^1.3.5", @@ -50,10 +49,9 @@ "indent-string": "^3.2.0", "lodash.clonedeepwith": "^4.5.0", "log-symbols": "^2.2.0", - "mkdirp": "^0.5.1", "ncp": "^2.0.0", "ora": "^1.4.0", - "prettier": "^1.14.3", + "prettier": "^1.18.2", "read-pkg": "^5.2.0", "rxjs": "^6.2.1", "spawn-sync": "^1.0.15", @@ -63,8 +61,8 @@ "tempy": "^0.3.0", "typescript": "3.5.3", "unlazy-loader": "^0.1.3", - "webpack": "^4.39.2", - "webpack-cli": "^3.3.7", + "webpack": "^4.41.0", + "webpack-cli": "^3.3.9", "wrap-ansi": "^3.0.1", "write-pkg": "^4.0.0" }, diff --git a/packages/kbn-pm/src/utils/fs.ts b/packages/kbn-pm/src/utils/fs.ts index 8ccaca29f97e08..9484c3a61e6082 100644 --- a/packages/kbn-pm/src/utils/fs.ts +++ b/packages/kbn-pm/src/utils/fs.ts @@ -19,22 +19,20 @@ import cmdShimCb from 'cmd-shim'; import fs from 'fs'; -import mkdirpCb from 'mkdirp'; import { ncp } from 'ncp'; import { dirname, relative } from 'path'; import { promisify } from 'util'; const lstat = promisify(fs.lstat); -const readFile = promisify(fs.readFile); +export const readFile = promisify(fs.readFile); const symlink = promisify(fs.symlink); -const chmod = promisify(fs.chmod); +export const chmod = promisify(fs.chmod); const cmdShim = promisify(cmdShimCb); -const mkdirp = promisify(mkdirpCb); +const mkdir = promisify(fs.mkdir); +export const mkdirp = async (path: string) => await mkdir(path, { recursive: true }); export const unlink = promisify(fs.unlink); export const copyDirectory = promisify(ncp); -export { chmod, readFile, mkdirp }; - async function statTest(path: string, block: (stats: fs.Stats) => boolean) { try { return block(await lstat(path)); diff --git a/packages/kbn-spec-to-console/package.json b/packages/kbn-spec-to-console/package.json index e40ea4dcd4fffb..0bc38fd4023844 100644 --- a/packages/kbn-spec-to-console/package.json +++ b/packages/kbn-spec-to-console/package.json @@ -18,7 +18,7 @@ "homepage": "https://github.com/jbudz/spec-to-console#readme", "devDependencies": { "jest": "^24.9.0", - "prettier": "^1.14.3" + "prettier": "^1.18.2" }, "dependencies": { "commander": "^2.11.0", diff --git a/src/legacy/ui/public/persisted_log/recently_accessed.ts b/packages/kbn-test/index.d.ts similarity index 87% rename from src/legacy/ui/public/persisted_log/recently_accessed.ts rename to packages/kbn-test/index.d.ts index 6d984d155d5516..aa55df9215c2f9 100644 --- a/src/legacy/ui/public/persisted_log/recently_accessed.ts +++ b/packages/kbn-test/index.d.ts @@ -17,6 +17,4 @@ * under the License. */ -import { npStart } from '../new_platform'; - -export const recentlyAccessed = npStart.core.chrome.recentlyAccessed; +export * from './src/index'; diff --git a/packages/kbn-test/package.json b/packages/kbn-test/package.json index 6891f01bae2a97..d02b2cf41d3f8a 100644 --- a/packages/kbn-test/package.json +++ b/packages/kbn-test/package.json @@ -21,7 +21,7 @@ "getopts": "^2.2.4", "glob": "^7.1.2", "rxjs": "^6.2.1", - "tar-fs": "^1.16.2", + "tar-fs": "^1.16.3", "tmp": "^0.1.0", "zlib": "^1.0.5" } diff --git a/packages/kbn-test/src/index.js b/packages/kbn-test/src/index.ts similarity index 86% rename from packages/kbn-test/src/index.js rename to packages/kbn-test/src/index.ts index e8cc694f5252e0..7330789bb2352f 100644 --- a/packages/kbn-test/src/index.js +++ b/packages/kbn-test/src/index.ts @@ -17,18 +17,26 @@ * under the License. */ +// @ts-ignore not typed yet export { runTestsCli, startServersCli } from './functional_tests/cli'; +// @ts-ignore not typed yet export { runTests, startServers } from './functional_tests/tasks'; +// @ts-ignore not typed yet export { OPTIMIZE_BUNDLE_DIR, KIBANA_ROOT } from './functional_tests/lib/paths'; +// @ts-ignore not typed yet export { esTestConfig, createEsTestCluster } from './es'; +// @ts-ignore not typed yet export { kbnTestConfig, kibanaServerTestUser, kibanaTestUser, adminTestUser } from './kbn'; +// @ts-ignore not typed yet export { setupUsers, DEFAULT_SUPERUSER_PASS } from './functional_tests/lib/auth'; +// @ts-ignore not typed yet export { readConfigFile } from './functional_test_runner/lib/config/read_config_file'; +// @ts-ignore not typed yet export { runFtrCli } from './functional_test_runner/cli'; diff --git a/packages/kbn-test/tsconfig.json b/packages/kbn-test/tsconfig.json index 83a0fe04a4b5f1..fdb53de52687bb 100644 --- a/packages/kbn-test/tsconfig.json +++ b/packages/kbn-test/tsconfig.json @@ -2,6 +2,7 @@ "extends": "../../tsconfig.json", "include": [ "types/**/*", - "src/functional_test_runner/**/*" + "src/**/*", + "index.d.ts" ] } diff --git a/packages/kbn-ui-framework/package.json b/packages/kbn-ui-framework/package.json index bd9658934100d0..cb4d2e3cadf956 100644 --- a/packages/kbn-ui-framework/package.json +++ b/packages/kbn-ui-framework/package.json @@ -37,7 +37,7 @@ "babel-loader": "^8.0.6", "brace": "0.11.1", "chalk": "^2.4.2", - "chokidar": "3.0.2", + "chokidar": "3.2.1", "core-js": "^3.2.1", "css-loader": "^2.1.1", "expose-loader": "^0.7.5", @@ -68,8 +68,8 @@ "sass-loader": "^7.3.1", "sinon": "^7.4.2", "style-loader": "^0.23.1", - "webpack": "^4.39.2", - "webpack-dev-server": "^3.8.0", + "webpack": "^4.41.0", + "webpack-dev-server": "^3.8.2", "yeoman-generator": "1.1.1", "yo": "2.0.6" } diff --git a/src/cli/serve/integration_tests/reload_logging_config.test.js b/src/cli/serve/integration_tests/reload_logging_config.test.js index 206118d2d1be85..8e8bdb15abc684 100644 --- a/src/cli/serve/integration_tests/reload_logging_config.test.js +++ b/src/cli/serve/integration_tests/reload_logging_config.test.js @@ -21,7 +21,6 @@ import { spawn } from 'child_process'; import fs from 'fs'; import path from 'path'; import os from 'os'; -import mkdirp from 'mkdirp'; import rimraf from 'rimraf'; import { safeDump } from 'js-yaml'; @@ -59,7 +58,7 @@ describe('Server logging configuration', function () { isJson = true; setLoggingJson(true); - mkdirp.sync(tempDir); + fs.mkdirSync(tempDir, { recursive: true }); }); afterEach(() => { diff --git a/src/cli_plugin/install/download.test.js b/src/cli_plugin/install/download.test.js index 97586f962737c8..9de6491f3c9571 100644 --- a/src/cli_plugin/install/download.test.js +++ b/src/cli_plugin/install/download.test.js @@ -21,7 +21,7 @@ import sinon from 'sinon'; import nock from 'nock'; import glob from 'glob-all'; import rimraf from 'rimraf'; -import mkdirp from 'mkdirp'; +import Fs from 'fs'; import Logger from '../lib/logger'; import { UnsupportedProtocolError } from '../lib/errors'; import { download, _downloadSingle, _getFilePath, _checkFilePathDeprecation } from './download'; @@ -64,7 +64,7 @@ describe('kibana cli', function () { sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); rimraf.sync(testWorkingPath); - mkdirp.sync(testWorkingPath); + Fs.mkdirSync(testWorkingPath, { recursive: true }); }); afterEach(function () { diff --git a/src/cli_plugin/install/install.js b/src/cli_plugin/install/install.js index 57d2d485b9dd27..10816591f7d714 100644 --- a/src/cli_plugin/install/install.js +++ b/src/cli_plugin/install/install.js @@ -17,8 +17,10 @@ * under the License. */ +import Fs from 'fs'; +import { promisify } from 'util'; + import { download } from './download'; -import Promise from 'bluebird'; import path from 'path'; import { cleanPrevious, cleanArtifacts } from './cleanup'; import { extract, getPackData } from './pack'; @@ -27,9 +29,8 @@ import { sync as rimrafSync } from 'rimraf'; import { errorIfXPackInstall } from '../lib/error_if_x_pack'; import { existingInstall, assertVersion } from './kibana'; import { prepareExternalProjectDependencies } from '@kbn/pm'; -import mkdirp from 'mkdirp'; -const mkdir = Promise.promisify(mkdirp); +const mkdir = promisify(Fs.mkdir); export default async function install(settings, logger) { try { @@ -37,7 +38,7 @@ export default async function install(settings, logger) { await cleanPrevious(settings, logger); - await mkdir(settings.workingPath); + await mkdir(settings.workingPath, { recursive: true }); await download(settings, logger); diff --git a/src/cli_plugin/install/kibana.test.js b/src/cli_plugin/install/kibana.test.js index 4a4ca6ebe30342..64de96b34e807a 100644 --- a/src/cli_plugin/install/kibana.test.js +++ b/src/cli_plugin/install/kibana.test.js @@ -27,7 +27,6 @@ import sinon from 'sinon'; import Logger from '../lib/logger'; import { join } from 'path'; import rimraf from 'rimraf'; -import mkdirp from 'mkdirp'; import fs from 'fs'; import { existingInstall, assertVersion } from './kibana'; @@ -55,7 +54,7 @@ describe('kibana cli', function () { beforeEach(function () { rimraf.sync(testWorkingPath); - mkdirp.sync(testWorkingPath); + fs.mkdirSync(testWorkingPath, { recursive: true }); sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); }); diff --git a/src/cli_plugin/install/pack.test.js b/src/cli_plugin/install/pack.test.js index bc854f66a6925f..1bc2504397fb52 100644 --- a/src/cli_plugin/install/pack.test.js +++ b/src/cli_plugin/install/pack.test.js @@ -17,10 +17,11 @@ * under the License. */ +import Fs from 'fs'; + import sinon from 'sinon'; import glob from 'glob-all'; import rimraf from 'rimraf'; -import mkdirp from 'mkdirp'; import Logger from '../lib/logger'; import { extract, getPackData } from './pack'; import { _downloadSingle } from './download'; @@ -58,7 +59,7 @@ describe('kibana cli', function () { logger = new Logger(settings); sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); - mkdirp.sync(testWorkingPath); + Fs.mkdirSync(testWorkingPath, { recursive: true }); }); afterEach(function () { diff --git a/src/cli_plugin/install/zip.js b/src/cli_plugin/install/zip.js index 7f928275525d5e..1d5d49b6c63b6f 100644 --- a/src/cli_plugin/install/zip.js +++ b/src/cli_plugin/install/zip.js @@ -19,8 +19,7 @@ import yauzl from 'yauzl'; import path from 'path'; -import mkdirp from 'mkdirp'; -import { createWriteStream } from 'fs'; +import { createWriteStream, mkdir } from 'fs'; import { get } from 'lodash'; /** @@ -112,7 +111,7 @@ export function extractArchive(archive, targetDir, extractPath) { } if (_isDirectory(fileName)) { - mkdirp(fileName, function (err) { + mkdir(fileName, { recursive: true }, function (err) { if (err) { return reject(err); } @@ -127,7 +126,7 @@ export function extractArchive(archive, targetDir, extractPath) { } // ensure parent directory exists - mkdirp(path.dirname(fileName), function (err) { + mkdir(path.dirname(fileName), { recursive: true }, function (err) { if (err) { return reject(err); } diff --git a/src/cli_plugin/list/list.test.js b/src/cli_plugin/list/list.test.js index c72f6c330543ca..425a6bee5394e1 100644 --- a/src/cli_plugin/list/list.test.js +++ b/src/cli_plugin/list/list.test.js @@ -19,16 +19,15 @@ import sinon from 'sinon'; import rimraf from 'rimraf'; -import mkdirp from 'mkdirp'; import Logger from '../lib/logger'; import list from './list'; import { join } from 'path'; -import { writeFileSync, appendFileSync } from 'fs'; +import { writeFileSync, appendFileSync, mkdirSync } from 'fs'; function createPlugin(name, version, pluginBaseDir) { const pluginDir = join(pluginBaseDir, name); - mkdirp.sync(pluginDir); + mkdirSync(pluginDir, { recursive: true }); appendFileSync(join(pluginDir, 'package.json'), '{"version": "' + version + '"}'); } @@ -48,7 +47,7 @@ describe('kibana cli', function () { sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); rimraf.sync(pluginDir); - mkdirp.sync(pluginDir); + mkdirSync(pluginDir, { recursive: true }); }); afterEach(function () { @@ -97,7 +96,7 @@ describe('kibana cli', function () { it('list should throw an exception if a plugin does not have a package.json', function () { createPlugin('plugin1', '1.0.0', pluginDir); - mkdirp.sync(join(pluginDir, 'empty-plugin')); + mkdirSync(join(pluginDir, 'empty-plugin'), { recursive: true }); expect(function () { list(settings, logger); @@ -107,7 +106,7 @@ describe('kibana cli', function () { it('list should throw an exception if a plugin have an empty package.json', function () { createPlugin('plugin1', '1.0.0', pluginDir); const invalidPluginDir = join(pluginDir, 'invalid-plugin'); - mkdirp.sync(invalidPluginDir); + mkdirSync(invalidPluginDir, { recursive: true }); appendFileSync(join(invalidPluginDir, 'package.json'), ''); expect(function () { diff --git a/src/cli_plugin/remove/remove.test.js b/src/cli_plugin/remove/remove.test.js index 971881dd0b870e..5d936d02785210 100644 --- a/src/cli_plugin/remove/remove.test.js +++ b/src/cli_plugin/remove/remove.test.js @@ -20,11 +20,10 @@ import sinon from 'sinon'; import glob from 'glob-all'; import rimraf from 'rimraf'; -import mkdirp from 'mkdirp'; import Logger from '../lib/logger'; import remove from './remove'; import { join } from 'path'; -import { writeFileSync, existsSync } from 'fs'; +import { writeFileSync, existsSync, mkdirSync } from 'fs'; describe('kibana cli', function () { @@ -42,7 +41,7 @@ describe('kibana cli', function () { sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); rimraf.sync(pluginDir); - mkdirp.sync(pluginDir); + mkdirSync(pluginDir, { recursive: true }); }); afterEach(function () { @@ -72,7 +71,7 @@ describe('kibana cli', function () { it('remove x-pack if it exists', () => { settings.pluginPath = join(pluginDir, 'x-pack'); settings.plugin = 'x-pack'; - mkdirp.sync(join(pluginDir, 'x-pack')); + mkdirSync(join(pluginDir, 'x-pack'), { recursive: true }); expect(existsSync(settings.pluginPath)).toEqual(true); remove(settings, logger); expect(existsSync(settings.pluginPath)).toEqual(false); @@ -88,8 +87,8 @@ describe('kibana cli', function () { it('delete the specified folder.', function () { settings.pluginPath = join(pluginDir, 'foo'); - mkdirp.sync(join(pluginDir, 'foo')); - mkdirp.sync(join(pluginDir, 'bar')); + mkdirSync(join(pluginDir, 'foo'), { recursive: true }); + mkdirSync(join(pluginDir, 'bar'), { recursive: true }); remove(settings, logger); diff --git a/src/core/public/application/application_service.tsx b/src/core/public/application/application_service.tsx index d1855a0370f002..935844baddf86a 100644 --- a/src/core/public/application/application_service.tsx +++ b/src/core/public/application/application_service.tsx @@ -27,12 +27,9 @@ import { AppRouter } from './ui'; import { HttpStart } from '../http'; import { ContextSetup, IContextContainer } from '../context'; import { - AppMountContext, App, LegacyApp, AppMounter, - AppUnmount, - AppMountParameters, InternalApplicationSetup, InternalApplicationStart, } from './types'; @@ -64,11 +61,7 @@ export class ApplicationService { private readonly apps$ = new BehaviorSubject>(new Map()); private readonly legacyApps$ = new BehaviorSubject>(new Map()); private readonly capabilities = new CapabilitiesService(); - private mountContext?: IContextContainer< - AppMountContext, - AppUnmount | Promise, - [AppMountParameters] - >; + private mountContext?: IContextContainer; public setup({ context }: SetupDeps): InternalApplicationSetup { this.mountContext = context.createContextContainer(); @@ -98,7 +91,7 @@ export class ApplicationService { this.legacyApps$.next(new Map([...this.legacyApps$.value.entries(), [app.id, app]])); }, - registerMountContext: this.mountContext.registerContext, + registerMountContext: this.mountContext!.registerContext, }; } diff --git a/src/core/public/application/types.ts b/src/core/public/application/types.ts index 018d7569ce411b..5b1d4affe88405 100644 --- a/src/core/public/application/types.ts +++ b/src/core/public/application/types.ts @@ -114,6 +114,15 @@ export interface AppMountContext { overlays: OverlayStart; /** {@link UiSettingsClient} */ uiSettings: UiSettingsClientContract; + /** + * exposed temporarily until https://github.com/elastic/kibana/issues/41990 done + * use *only* to retrieve config values. There is no way to set injected values + * in the new platform. Use the legacy platform API instead. + * @deprecated + * */ + injectedMetadata: { + getInjectedVar: (name: string, defaultValue?: any) => unknown; + }; }; } @@ -193,7 +202,7 @@ export interface ApplicationSetup { */ registerMountContext( contextName: T, - provider: IContextProvider + provider: IContextProvider ): void; } @@ -224,7 +233,7 @@ export interface InternalApplicationSetup { registerMountContext( pluginOpaqueId: PluginOpaqueId, contextName: T, - provider: IContextProvider + provider: IContextProvider ): void; } @@ -261,7 +270,7 @@ export interface ApplicationStart { */ registerMountContext( contextName: T, - provider: IContextProvider + provider: IContextProvider ): void; } @@ -291,7 +300,7 @@ export interface InternalApplicationStart registerMountContext( pluginOpaqueId: PluginOpaqueId, contextName: T, - provider: IContextProvider + provider: IContextProvider ): void; // Internal APIs diff --git a/src/core/public/chrome/ui/header/header.tsx b/src/core/public/chrome/ui/header/header.tsx index afd9f8e4a38209..f24b0ed1681aab 100644 --- a/src/core/public/chrome/ui/header/header.tsx +++ b/src/core/public/chrome/ui/header/header.tsx @@ -19,7 +19,7 @@ import Url from 'url'; -import React, { Component, createRef, Fragment } from 'react'; +import React, { Component, createRef } from 'react'; import * as Rx from 'rxjs'; import { @@ -376,7 +376,7 @@ class HeaderUI extends Component { ]; return ( - +
@@ -407,11 +407,13 @@ class HeaderUI extends Component { isLocked={isLocked} onIsLockedUpdate={onIsLockedUpdate} > - - - + - +
); } diff --git a/src/core/public/context/context_service.ts b/src/core/public/context/context_service.ts index 704524d8386367..dadc509c97821e 100644 --- a/src/core/public/context/context_service.ts +++ b/src/core/public/context/context_service.ts @@ -18,7 +18,7 @@ */ import { PluginOpaqueId } from '../../server'; -import { IContextContainer, ContextContainer } from '../../utils/context'; +import { IContextContainer, ContextContainer, HandlerFunction } from '../../utils/context'; import { CoreContext } from '../core_system'; interface StartDeps { @@ -31,15 +31,8 @@ export class ContextService { public setup({ pluginDependencies }: StartDeps): ContextSetup { return { - createContextContainer: < - TContext extends {}, - THandlerReturn, - THandlerParameters extends any[] = [] - >() => - new ContextContainer( - pluginDependencies, - this.core.coreId - ), + createContextContainer: >() => + new ContextContainer(pluginDependencies, this.core.coreId), }; } } @@ -111,9 +104,5 @@ export interface ContextSetup { /** * Creates a new {@link IContextContainer} for a service owner. */ - createContextContainer< - TContext extends {}, - THandlerReturn, - THandlerParmaters extends any[] = [] - >(): IContextContainer; + createContextContainer>(): IContextContainer; } diff --git a/src/core/public/context/index.ts b/src/core/public/context/index.ts index 28b2641b2a5a74..f22c4168d75448 100644 --- a/src/core/public/context/index.ts +++ b/src/core/public/context/index.ts @@ -18,4 +18,10 @@ */ export { ContextService, ContextSetup } from './context_service'; -export { IContextContainer, IContextProvider, IContextHandler } from '../../utils/context'; +export { + IContextContainer, + IContextProvider, + HandlerFunction, + HandlerContextType, + HandlerParameters, +} from '../../utils/context'; diff --git a/src/core/public/core_system.ts b/src/core/public/core_system.ts index 7b9ed50f095910..7a87f97208a7ae 100644 --- a/src/core/public/core_system.ts +++ b/src/core/public/core_system.ts @@ -236,6 +236,7 @@ export class CoreSystem { notifications, overlays, uiSettings, + injectedMetadata: pick(injectedMetadata, ['getInjectedVar']), })); const core: InternalCoreStart = { diff --git a/src/core/public/index.ts b/src/core/public/index.ts index d0316604a0d37c..dfdd6f8797f270 100644 --- a/src/core/public/index.ts +++ b/src/core/public/index.ts @@ -67,7 +67,14 @@ import { UiSettingsClient, UiSettingsState, UiSettingsClientContract } from './u import { ApplicationSetup, Capabilities, ApplicationStart } from './application'; import { DocLinksStart } from './doc_links'; import { SavedObjectsStart } from './saved_objects'; -import { IContextContainer, IContextProvider, ContextSetup, IContextHandler } from './context'; +import { + IContextContainer, + IContextProvider, + ContextSetup, + HandlerFunction, + HandlerContextType, + HandlerParameters, +} from './context'; /** @interal */ export { CoreContext, CoreSystem } from './core_system'; @@ -139,6 +146,15 @@ export interface CoreSetup { notifications: NotificationsSetup; /** {@link UiSettingsClient} */ uiSettings: UiSettingsClientContract; + /** + * exposed temporarily until https://github.com/elastic/kibana/issues/41990 done + * use *only* to retrieve config values. There is no way to set injected values + * in the new platform. Use the legacy platform API instead. + * @deprecated + * */ + injectedMetadata: { + getInjectedVar: (name: string, defaultValue?: any) => unknown; + }; } /** @@ -169,6 +185,15 @@ export interface CoreStart { overlays: OverlayStart; /** {@link UiSettingsClient} */ uiSettings: UiSettingsClientContract; + /** + * exposed temporarily until https://github.com/elastic/kibana/issues/41990 done + * use *only* to retrieve config values. There is no way to set injected values + * in the new platform. Use the legacy platform API instead. + * @deprecated + * */ + injectedMetadata: { + getInjectedVar: (name: string, defaultValue?: any) => unknown; + }; } /** @@ -218,7 +243,9 @@ export { ChromeRecentlyAccessedHistoryItem, ChromeStart, IContextContainer, - IContextHandler, + HandlerFunction, + HandlerContextType, + HandlerParameters, IContextProvider, ContextSetup, DocLinksStart, diff --git a/src/core/public/mocks.ts b/src/core/public/mocks.ts index 7c99f69d6fd7ad..8ce163fd59e143 100644 --- a/src/core/public/mocks.ts +++ b/src/core/public/mocks.ts @@ -28,6 +28,7 @@ import { overlayServiceMock } from './overlays/overlay_service.mock'; import { uiSettingsServiceMock } from './ui_settings/ui_settings_service.mock'; import { savedObjectsMock } from './saved_objects/saved_objects_service.mock'; import { contextServiceMock } from './context/context_service.mock'; +import { injectedMetadataServiceMock } from './injected_metadata/injected_metadata_service.mock'; export { chromeServiceMock } from './chrome/chrome_service.mock'; export { docLinksServiceMock } from './doc_links/doc_links_service.mock'; @@ -48,6 +49,9 @@ function createCoreSetupMock() { http: httpServiceMock.createSetupContract(), notifications: notificationServiceMock.createSetupContract(), uiSettings: uiSettingsServiceMock.createSetupContract(), + injectedMetadata: { + getInjectedVar: injectedMetadataServiceMock.createSetupContract().getInjectedVar, + }, }; return mock; @@ -64,6 +68,9 @@ function createCoreStartMock() { overlays: overlayServiceMock.createStartContract(), uiSettings: uiSettingsServiceMock.createStartContract(), savedObjects: savedObjectsMock.createStartContract(), + injectedMetadata: { + getInjectedVar: injectedMetadataServiceMock.createStartContract().getInjectedVar, + }, }; return mock; diff --git a/src/core/public/plugins/plugin_context.ts b/src/core/public/plugins/plugin_context.ts index f4e25d27447bc2..51bd118d280e31 100644 --- a/src/core/public/plugins/plugin_context.ts +++ b/src/core/public/plugins/plugin_context.ts @@ -86,6 +86,9 @@ export function createPluginSetupContext< http: deps.http, notifications: deps.notifications, uiSettings: deps.uiSettings, + injectedMetadata: { + getInjectedVar: deps.injectedMetadata.getInjectedVar, + }, }; } @@ -125,5 +128,8 @@ export function createPluginStartContext< overlays: deps.overlays, uiSettings: deps.uiSettings, savedObjects: deps.savedObjects, + injectedMetadata: { + getInjectedVar: deps.injectedMetadata.getInjectedVar, + }, }; } diff --git a/src/core/public/plugins/plugins_service.test.ts b/src/core/public/plugins/plugins_service.test.ts index d6411554e5f85b..358bf71ac91882 100644 --- a/src/core/public/plugins/plugins_service.test.ts +++ b/src/core/public/plugins/plugins_service.test.ts @@ -17,7 +17,7 @@ * under the License. */ -import { omit } from 'lodash'; +import { omit, pick } from 'lodash'; import { MockedPluginInitializer, @@ -76,12 +76,12 @@ beforeEach(() => { context: contextServiceMock.createSetupContract(), fatalErrors: fatalErrorsServiceMock.createSetupContract(), http: httpServiceMock.createSetupContract(), - injectedMetadata: injectedMetadataServiceMock.createSetupContract(), + injectedMetadata: pick(injectedMetadataServiceMock.createStartContract(), 'getInjectedVar'), notifications: notificationServiceMock.createSetupContract(), uiSettings: uiSettingsServiceMock.createSetupContract(), }; mockSetupContext = { - ...omit(mockSetupDeps, 'injectedMetadata'), + ...mockSetupDeps, application: expect.any(Object), }; mockStartDeps = { @@ -90,14 +90,14 @@ beforeEach(() => { http: httpServiceMock.createStartContract(), chrome: chromeServiceMock.createStartContract(), i18n: i18nServiceMock.createStartContract(), - injectedMetadata: injectedMetadataServiceMock.createStartContract(), + injectedMetadata: pick(injectedMetadataServiceMock.createStartContract(), 'getInjectedVar'), notifications: notificationServiceMock.createStartContract(), overlays: overlayServiceMock.createStartContract(), uiSettings: uiSettingsServiceMock.createStartContract(), savedObjects: savedObjectsMock.createStartContract(), }; mockStartContext = { - ...omit(mockStartDeps, 'injectedMetadata'), + ...mockStartDeps, application: expect.any(Object), chrome: omit(mockStartDeps.chrome, 'getComponent'), }; diff --git a/src/core/public/public.api.md b/src/core/public/public.api.md index 102e77b564a6d6..0156cbaebb9496 100644 --- a/src/core/public/public.api.md +++ b/src/core/public/public.api.md @@ -9,6 +9,7 @@ import { MouseEventHandler } from 'react'; import { Observable } from 'rxjs'; import React from 'react'; import * as Rx from 'rxjs'; +import { ShallowPromise } from '@kbn/utility-types'; import { EuiGlobalToastListToast as Toast } from '@elastic/eui'; // @public @@ -31,7 +32,7 @@ export interface AppBase { // @public (undocumented) export interface ApplicationSetup { register(app: App): void; - registerMountContext(contextName: T, provider: IContextProvider): void; + registerMountContext(contextName: T, provider: IContextProvider): void; } // @public (undocumented) @@ -44,7 +45,7 @@ export interface ApplicationStart { path?: string; state?: any; }): void; - registerMountContext(contextName: T, provider: IContextProvider): void; + registerMountContext(contextName: T, provider: IContextProvider): void; } // @public @@ -58,6 +59,9 @@ export interface AppMountContext { notifications: NotificationsStart; overlays: OverlayStart; uiSettings: UiSettingsClientContract; + injectedMetadata: { + getInjectedVar: (name: string, defaultValue?: any) => unknown; + }; }; } @@ -213,7 +217,7 @@ export interface ChromeStart { // @public export interface ContextSetup { - createContextContainer(): IContextContainer; + createContextContainer>(): IContextContainer; } // @internal (undocumented) @@ -234,6 +238,10 @@ export interface CoreSetup { fatalErrors: FatalErrorsSetup; // (undocumented) http: HttpSetup; + // @deprecated + injectedMetadata: { + getInjectedVar: (name: string, defaultValue?: any) => unknown; + }; // (undocumented) notifications: NotificationsSetup; // (undocumented) @@ -252,6 +260,10 @@ export interface CoreStart { http: HttpStart; // (undocumented) i18n: I18nStart; + // @deprecated + injectedMetadata: { + getInjectedVar: (name: string, defaultValue?: any) => unknown; + }; // (undocumented) notifications: NotificationsStart; // (undocumented) @@ -389,6 +401,15 @@ export interface FatalErrorsSetup { get$: () => Rx.Observable; } +// @public +export type HandlerContextType> = T extends HandlerFunction ? U : never; + +// @public +export type HandlerFunction = (context: T, ...args: any[]) => any; + +// @public +export type HandlerParameters> = T extends (context: any, ...args: infer U) => any ? U : never; + // @public (undocumented) export type HttpBody = BodyInit | null | any; @@ -551,16 +572,13 @@ export interface I18nStart { } // @public -export interface IContextContainer { - createHandler(pluginOpaqueId: PluginOpaqueId, handler: IContextHandler): (...rest: THandlerParameters) => THandlerReturn extends Promise ? THandlerReturn : Promise; - registerContext(pluginOpaqueId: PluginOpaqueId, contextName: TContextName, provider: IContextProvider): this; +export interface IContextContainer> { + createHandler(pluginOpaqueId: PluginOpaqueId, handler: THandler): (...rest: HandlerParameters) => ShallowPromise>; + registerContext>(pluginOpaqueId: PluginOpaqueId, contextName: TContextName, provider: IContextProvider): this; } // @public -export type IContextHandler = (context: TContext, ...rest: THandlerParameters) => TReturn; - -// @public -export type IContextProvider, TContextName extends keyof TContext, TProviderParameters extends any[] = []> = (context: Partial, ...rest: TProviderParameters) => Promise | TContext[TContextName]; +export type IContextProvider, TContextName extends keyof HandlerContextType> = (context: Partial>, ...rest: HandlerParameters) => Promise[TContextName]> | HandlerContextType[TContextName]; // @public @deprecated export interface LegacyCoreSetup extends CoreSetup { diff --git a/src/core/server/context/context_service.ts b/src/core/server/context/context_service.ts index 80935840c55360..1c5bd41a01f0f1 100644 --- a/src/core/server/context/context_service.ts +++ b/src/core/server/context/context_service.ts @@ -18,7 +18,7 @@ */ import { PluginOpaqueId } from '../../server'; -import { IContextContainer, ContextContainer } from '../../utils/context'; +import { IContextContainer, ContextContainer, HandlerFunction } from '../../utils/context'; import { CoreContext } from '../core_context'; interface SetupDeps { @@ -31,15 +31,8 @@ export class ContextService { public setup({ pluginDependencies }: SetupDeps): ContextSetup { return { - createContextContainer: < - TContext extends {}, - THandlerReturn, - THandlerParameters extends any[] = [] - >() => { - return new ContextContainer( - pluginDependencies, - this.core.coreId - ); + createContextContainer: >() => { + return new ContextContainer(pluginDependencies, this.core.coreId); }, }; } @@ -112,9 +105,5 @@ export interface ContextSetup { /** * Creates a new {@link IContextContainer} for a service owner. */ - createContextContainer< - TContext extends {}, - THandlerReturn, - THandlerParmaters extends any[] = [] - >(): IContextContainer; + createContextContainer>(): IContextContainer; } diff --git a/src/core/server/context/index.ts b/src/core/server/context/index.ts index 28b2641b2a5a74..f22c4168d75448 100644 --- a/src/core/server/context/index.ts +++ b/src/core/server/context/index.ts @@ -18,4 +18,10 @@ */ export { ContextService, ContextSetup } from './context_service'; -export { IContextContainer, IContextProvider, IContextHandler } from '../../utils/context'; +export { + IContextContainer, + IContextProvider, + HandlerFunction, + HandlerContextType, + HandlerParameters, +} from '../../utils/context'; diff --git a/src/core/server/http/http_service.ts b/src/core/server/http/http_service.ts index 5814991a2dd27c..0ac5ad92763537 100644 --- a/src/core/server/http/http_service.ts +++ b/src/core/server/http/http_service.ts @@ -83,8 +83,8 @@ export type HttpServiceSetup = Omit & { registerRouteHandlerContext: ( pluginOpaqueId: PluginOpaqueId, contextName: T, - provider: RequestHandlerContextProvider - ) => RequestHandlerContextContainer; + provider: RequestHandlerContextProvider + ) => RequestHandlerContextContainer; }; /** @public */ @@ -103,7 +103,7 @@ export class HttpService implements CoreService; + private requestHandlerContext?: RequestHandlerContextContainer; constructor(private readonly coreContext: CoreContext) { this.logger = coreContext.logger; @@ -150,7 +150,7 @@ export class HttpService implements CoreService( pluginOpaqueId: PluginOpaqueId, contextName: T, - provider: RequestHandlerContextProvider + provider: RequestHandlerContextProvider ) => this.requestHandlerContext!.registerContext(pluginOpaqueId, contextName, provider), }; diff --git a/src/core/server/http/types.ts b/src/core/server/http/types.ts index a391b2e2e5d458..cade4ea4d4f2cc 100644 --- a/src/core/server/http/types.ts +++ b/src/core/server/http/types.ts @@ -16,30 +16,16 @@ * specific language governing permissions and limitations * under the License. */ -import { IContextProvider, IContextContainer } from '../context'; -import { KibanaRequest, KibanaResponseFactory, KibanaResponse } from './router'; - -/** - * Parameters passed to the request handler function. - * @public - */ -export type RequestHandlerParams = [KibanaRequest, KibanaResponseFactory]; -/** - * Expected outcome the request handler function. - * @public - */ -export type RequestHandlerReturn = KibanaResponse; +import { IContextProvider, IContextContainer } from '../context'; +import { RequestHandler } from './router'; +import { RequestHandlerContext } from '..'; /** * An object that handles registration of http request context providers. * @public */ -export type RequestHandlerContextContainer = IContextContainer< - TContext, - RequestHandlerReturn | Promise, - RequestHandlerParams ->; +export type RequestHandlerContextContainer = IContextContainer>; /** * Context provider for request handler. @@ -47,8 +33,6 @@ export type RequestHandlerContextContainer = IContextContainer< * * @public */ -export type RequestHandlerContextProvider = IContextProvider< - TContext, - keyof TContext, - RequestHandlerParams ->; +export type RequestHandlerContextProvider< + TContextName extends keyof RequestHandlerContext +> = IContextProvider, TContextName>; diff --git a/src/core/server/index.ts b/src/core/server/index.ts index d3fe64ddc1e0df..ca497e0f2d32d4 100644 --- a/src/core/server/index.ts +++ b/src/core/server/index.ts @@ -59,7 +59,13 @@ import { SavedObjectsServiceStart } from './saved_objects'; export { bootstrap } from './bootstrap'; export { ConfigPath, ConfigService } from './config'; -export { IContextContainer, IContextProvider, IContextHandler } from './context'; +export { + IContextContainer, + IContextProvider, + HandlerFunction, + HandlerContextType, + HandlerParameters, +} from './context'; export { CoreId } from './core_context'; export { CallAPIOptions, @@ -102,8 +108,6 @@ export { RequestHandler, RequestHandlerContextContainer, RequestHandlerContextProvider, - RequestHandlerParams, - RequestHandlerReturn, ResponseError, ResponseErrorAttributes, ResponseHeaders, @@ -212,8 +216,8 @@ export interface CoreSetup { isTlsEnabled: HttpServiceSetup['isTlsEnabled']; registerRouteHandlerContext: ( name: T, - provider: RequestHandlerContextProvider - ) => RequestHandlerContextContainer; + provider: RequestHandlerContextProvider + ) => RequestHandlerContextContainer; createRouter: () => IRouter; }; } diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index ae839644fc2e29..6451e2b9b7153e 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -21,6 +21,7 @@ import { Request } from 'hapi'; import { ResponseObject } from 'hapi'; import { ResponseToolkit } from 'hapi'; import { Server } from 'hapi'; +import { ShallowPromise } from '@kbn/utility-types'; import { Stream } from 'stream'; import { Type } from '@kbn/config-schema'; import { TypeOf } from '@kbn/config-schema'; @@ -61,11 +62,11 @@ export interface AuthToolkit { export class BasePath { // @internal constructor(serverBasePath?: string); - get: (request: KibanaRequest | LegacyRequest) => string; + get: (request: LegacyRequest | KibanaRequest) => string; prepend: (path: string) => string; remove: (path: string) => string; readonly serverBasePath: string; - set: (request: KibanaRequest | LegacyRequest, requestSpecificBasePath: string) => void; + set: (request: LegacyRequest | KibanaRequest, requestSpecificBasePath: string) => void; } // Warning: (ae-forgotten-export) The symbol "BootstrapArgs" needs to be exported by the entry point index.d.ts @@ -109,7 +110,7 @@ export class ConfigService { // @public export interface ContextSetup { - createContextContainer(): IContextContainer; + createContextContainer>(): IContextContainer; } // @internal (undocumented) @@ -135,7 +136,7 @@ export interface CoreSetup { registerOnPostAuth: HttpServiceSetup['registerOnPostAuth']; basePath: HttpServiceSetup['basePath']; isTlsEnabled: HttpServiceSetup['isTlsEnabled']; - registerRouteHandlerContext: (name: T, provider: RequestHandlerContextProvider) => RequestHandlerContextContainer; + registerRouteHandlerContext: (name: T, provider: RequestHandlerContextProvider) => RequestHandlerContextContainer; createRouter: () => IRouter; }; } @@ -219,6 +220,15 @@ export type GetAuthState = (request: KibanaRequest | LegacyRequest) => { state: unknown; }; +// @public +export type HandlerContextType> = T extends HandlerFunction ? U : never; + +// @public +export type HandlerFunction = (context: T, ...args: any[]) => any; + +// @public +export type HandlerParameters> = T extends (context: any, ...args: infer U) => any ? U : never; + // @public export type Headers = { [header in KnownHeaders]?: string | string[] | undefined; @@ -258,7 +268,7 @@ export interface HttpServerSetup { // @public (undocumented) export type HttpServiceSetup = Omit & { createRouter: (path: string, plugin?: PluginOpaqueId) => IRouter; - registerRouteHandlerContext: (pluginOpaqueId: PluginOpaqueId, contextName: T, provider: RequestHandlerContextProvider) => RequestHandlerContextContainer; + registerRouteHandlerContext: (pluginOpaqueId: PluginOpaqueId, contextName: T, provider: RequestHandlerContextProvider) => RequestHandlerContextContainer; }; // @public (undocumented) @@ -270,16 +280,13 @@ export interface HttpServiceStart { export type IBasePath = Pick; // @public -export interface IContextContainer { - createHandler(pluginOpaqueId: PluginOpaqueId, handler: IContextHandler): (...rest: THandlerParameters) => THandlerReturn extends Promise ? THandlerReturn : Promise; - registerContext(pluginOpaqueId: PluginOpaqueId, contextName: TContextName, provider: IContextProvider): this; +export interface IContextContainer> { + createHandler(pluginOpaqueId: PluginOpaqueId, handler: THandler): (...rest: HandlerParameters) => ShallowPromise>; + registerContext>(pluginOpaqueId: PluginOpaqueId, contextName: TContextName, provider: IContextProvider): this; } // @public -export type IContextHandler = (context: TContext, ...rest: THandlerParameters) => TReturn; - -// @public -export type IContextProvider, TContextName extends keyof TContext, TProviderParameters extends any[] = []> = (context: Partial, ...rest: TProviderParameters) => Promise | TContext[TContextName]; +export type IContextProvider, TContextName extends keyof HandlerContextType> = (context: Partial>, ...rest: HandlerParameters) => Promise[TContextName]> | HandlerContextType[TContextName]; // @public export interface IKibanaSocket { @@ -602,16 +609,10 @@ export interface RequestHandlerContext { } // @public -export type RequestHandlerContextContainer = IContextContainer, RequestHandlerParams>; - -// @public -export type RequestHandlerContextProvider = IContextProvider; - -// @public -export type RequestHandlerParams = [KibanaRequest, KibanaResponseFactory]; +export type RequestHandlerContextContainer = IContextContainer>; // @public -export type RequestHandlerReturn = KibanaResponse; +export type RequestHandlerContextProvider = IContextProvider, TContextName>; // @public export type ResponseError = string | Error | { diff --git a/src/core/utils/context.mock.ts b/src/core/utils/context.mock.ts index 4d91c11542b2f8..de844f3f0f07db 100644 --- a/src/core/utils/context.mock.ts +++ b/src/core/utils/context.mock.ts @@ -19,7 +19,7 @@ import { IContextContainer } from './context'; -export type ContextContainerMock = jest.Mocked>; +export type ContextContainerMock = jest.Mocked>; const createContextMock = () => { const contextMock: ContextContainerMock = { diff --git a/src/core/utils/context.test.ts b/src/core/utils/context.test.ts index 1249c14736fb53..4bfeddc2e08c97 100644 --- a/src/core/utils/context.test.ts +++ b/src/core/utils/context.test.ts @@ -44,7 +44,7 @@ const coreId = Symbol(); describe('ContextContainer', () => { it('does not allow the same context to be registered twice', () => { - const contextContainer = new ContextContainer(plugins, coreId); + const contextContainer = new ContextContainer<(context: MyContext) => string>(plugins, coreId); contextContainer.registerContext(coreId, 'ctxFromA', () => 'aString'); expect(() => @@ -56,7 +56,10 @@ describe('ContextContainer', () => { describe('registerContext', () => { it('throws error if called with an unknown symbol', async () => { - const contextContainer = new ContextContainer(plugins, coreId); + const contextContainer = new ContextContainer<(context: MyContext) => string>( + plugins, + coreId + ); await expect(() => contextContainer.registerContext(Symbol('unknown'), 'ctxFromA', jest.fn()) ).toThrowErrorMatchingInlineSnapshot( @@ -67,7 +70,10 @@ describe('ContextContainer', () => { describe('context building', () => { it('resolves dependencies', async () => { - const contextContainer = new ContextContainer(plugins, coreId); + const contextContainer = new ContextContainer<(context: MyContext) => string>( + plugins, + coreId + ); expect.assertions(8); contextContainer.registerContext(coreId, 'core1', context => { expect(context).toEqual({}); @@ -118,7 +124,10 @@ describe('ContextContainer', () => { it('exposes all core context to all providers regardless of registration order', async () => { expect.assertions(4); - const contextContainer = new ContextContainer(plugins, coreId); + const contextContainer = new ContextContainer<(context: MyContext) => string>( + plugins, + coreId + ); contextContainer .registerContext(pluginA, 'ctxFromA', context => { expect(context).toEqual({ core1: 'core', core2: 101 }); @@ -146,7 +155,10 @@ describe('ContextContainer', () => { it('exposes all core context to core providers', async () => { expect.assertions(4); - const contextContainer = new ContextContainer(plugins, coreId); + const contextContainer = new ContextContainer<(context: MyContext) => string>( + plugins, + coreId + ); contextContainer .registerContext(coreId, 'core1', context => { @@ -171,7 +183,10 @@ describe('ContextContainer', () => { }); it('does not expose plugin contexts to core handler', async () => { - const contextContainer = new ContextContainer(plugins, coreId); + const contextContainer = new ContextContainer<(context: MyContext) => string>( + plugins, + coreId + ); contextContainer .registerContext(coreId, 'core1', context => 'core') @@ -189,10 +204,9 @@ describe('ContextContainer', () => { it('passes additional arguments to providers', async () => { expect.assertions(6); - const contextContainer = new ContextContainer( - plugins, - coreId - ); + const contextContainer = new ContextContainer< + (context: MyContext, arg1: string, arg2: number) => string + >(plugins, coreId); contextContainer.registerContext(coreId, 'core1', (context, str, num) => { expect(str).toEqual('passed string'); @@ -228,7 +242,10 @@ describe('ContextContainer', () => { describe('createHandler', () => { it('throws error if called with an unknown symbol', async () => { - const contextContainer = new ContextContainer(plugins, coreId); + const contextContainer = new ContextContainer<(context: MyContext) => string>( + plugins, + coreId + ); await expect(() => contextContainer.createHandler(Symbol('unknown'), jest.fn()) ).toThrowErrorMatchingInlineSnapshot( @@ -237,8 +254,10 @@ describe('ContextContainer', () => { }); it('returns value from original handler', async () => { - const contextContainer = new ContextContainer(plugins, coreId); - + const contextContainer = new ContextContainer<(context: MyContext) => string>( + plugins, + coreId + ); const rawHandler1 = jest.fn(() => 'handler1'); const handler1 = contextContainer.createHandler(pluginA, rawHandler1); @@ -246,10 +265,9 @@ describe('ContextContainer', () => { }); it('passes additional arguments to handlers', async () => { - const contextContainer = new ContextContainer( - plugins, - coreId - ); + const contextContainer = new ContextContainer< + (context: MyContext, arg1: string, arg2: number) => string + >(plugins, coreId); const rawHandler1 = jest.fn(() => 'handler1'); const handler1 = contextContainer.createHandler(pluginA, rawHandler1); diff --git a/src/core/utils/context.ts b/src/core/utils/context.ts index 6d1732ea06b0e1..022c3e43300322 100644 --- a/src/core/utils/context.ts +++ b/src/core/utils/context.ts @@ -18,6 +18,7 @@ */ import { flatten } from 'lodash'; +import { ShallowPromise } from '@kbn/utility-types'; import { pick } from '.'; import { CoreId, PluginOpaqueId } from '../server'; @@ -35,26 +36,44 @@ import { CoreId, PluginOpaqueId } from '../server'; * @public */ export type IContextProvider< - TContext extends Record, - TContextName extends keyof TContext, - TProviderParameters extends any[] = [] + THandler extends HandlerFunction, + TContextName extends keyof HandlerContextType > = ( - context: Partial, - ...rest: TProviderParameters -) => Promise | TContext[TContextName]; + context: Partial>, + ...rest: HandlerParameters +) => + | Promise[TContextName]> + | HandlerContextType[TContextName]; /** - * A function registered by a plugin to perform some action. + * A function that accepts a context object and an optional number of additional arguments. Used for the generic types + * in {@link IContextContainer} * - * @remarks - * A new `TContext` will be built for each handler before invoking. + * @public + */ +export type HandlerFunction = (context: T, ...args: any[]) => any; + +/** + * Extracts the type of the first argument of a {@link HandlerFunction} to represent the type of the context. * * @public */ -export type IContextHandler = ( - context: TContext, - ...rest: THandlerParameters -) => TReturn; +export type HandlerContextType> = T extends HandlerFunction + ? U + : never; + +/** + * Extracts the types of the additional arguments of a {@link HandlerFunction}, excluding the + * {@link HandlerContextType}. + * + * @public + */ +export type HandlerParameters> = T extends ( + context: any, + ...args: infer U +) => any + ? U + : never; /** * An object that handles registration of context providers and configuring handlers with context. @@ -123,13 +142,12 @@ export type IContextHandler { +export interface IContextContainer> { /** * Register a new context provider. * @@ -144,10 +162,10 @@ export interface IContextContainer< * @param provider - A {@link IContextProvider} to be called each time a new context is created. * @returns The {@link IContextContainer} for method chaining. */ - registerContext( + registerContext>( pluginOpaqueId: PluginOpaqueId, contextName: TContextName, - provider: IContextProvider + provider: IContextProvider ): this; /** @@ -160,31 +178,26 @@ export interface IContextContainer< */ createHandler( pluginOpaqueId: PluginOpaqueId, - handler: IContextHandler - ): ( - ...rest: THandlerParameters - ) => THandlerReturn extends Promise ? THandlerReturn : Promise; + handler: THandler + ): (...rest: HandlerParameters) => ShallowPromise>; } /** @internal */ -export class ContextContainer< - TContext extends Record, - THandlerReturn, - THandlerParameters extends any[] = [] -> implements IContextContainer { +export class ContextContainer> + implements IContextContainer { /** * Used to map contexts to their providers and associated plugin. In registration order which is tightly coupled to * plugin load order. */ private readonly contextProviders = new Map< - keyof TContext, + keyof HandlerContextType, { - provider: IContextProvider; + provider: IContextProvider>; source: symbol; } >(); /** Used to keep track of which plugins registered which contexts for dependency resolution. */ - private readonly contextNamesBySource: Map>; + private readonly contextNamesBySource: Map>>; /** * @param pluginDependencies - A map of plugins to an array of their dependencies. @@ -193,13 +206,15 @@ export class ContextContainer< private readonly pluginDependencies: ReadonlyMap, private readonly coreId: CoreId ) { - this.contextNamesBySource = new Map>([[coreId, []]]); + this.contextNamesBySource = new Map>>([ + [coreId, []], + ]); } - public registerContext = ( + public registerContext = >( source: symbol, contextName: TContextName, - provider: IContextProvider + provider: IContextProvider ): this => { if (this.contextProviders.has(contextName)) { throw new Error(`Context provider for ${contextName} has already been registered.`); @@ -217,27 +232,22 @@ export class ContextContainer< return this; }; - public createHandler = ( - source: symbol, - handler: IContextHandler - ) => { + public createHandler = (source: symbol, handler: THandler) => { if (source !== this.coreId && !this.pluginDependencies.has(source)) { throw new Error(`Cannot create handler for unknown plugin: ${source.toString()}`); } - return (async (...args: THandlerParameters) => { + return (async (...args: HandlerParameters) => { const context = await this.buildContext(source, ...args); return handler(context, ...args); - }) as ( - ...args: THandlerParameters - ) => THandlerReturn extends Promise ? THandlerReturn : Promise; + }) as (...args: HandlerParameters) => ShallowPromise>; }; private async buildContext( source: symbol, - ...contextArgs: THandlerParameters - ): Promise { - const contextsToBuild: ReadonlySet = new Set( + ...contextArgs: HandlerParameters + ): Promise> { + const contextsToBuild: ReadonlySet> = new Set( this.getContextNamesForSource(source) ); @@ -252,18 +262,20 @@ export class ContextContainer< // registered that provider. const exposedContext = pick(resolvedContext, [ ...this.getContextNamesForSource(providerSource), - ]); + ]) as Partial>; return { ...resolvedContext, - [contextName]: await provider(exposedContext as Partial, ...contextArgs), + [contextName]: await provider(exposedContext, ...contextArgs), }; }, - Promise.resolve({}) as Promise + Promise.resolve({}) as Promise> ); } - private getContextNamesForSource(source: symbol): ReadonlySet { + private getContextNamesForSource( + source: symbol + ): ReadonlySet> { if (source === this.coreId) { return this.getContextNamesForCore(); } else { diff --git a/src/dev/build/lib/fs.js b/src/dev/build/lib/fs.js index de0ae5fc72e907..1aeccdb76a4fb3 100644 --- a/src/dev/build/lib/fs.js +++ b/src/dev/build/lib/fs.js @@ -26,14 +26,13 @@ import { inspect } from 'util'; import vfs from 'vinyl-fs'; import { promisify } from 'bluebird'; -import mkdirpCb from 'mkdirp'; import del from 'del'; import deleteEmpty from 'delete-empty'; import { createPromiseFromStreams, createMapStream } from '../../../legacy/utils'; import tar from 'tar'; -const mkdirpAsync = promisify(mkdirpCb); +const mkdirAsync = promisify(fs.mkdir); const writeFileAsync = promisify(fs.writeFile); const readFileAsync = promisify(fs.readFile); const readdirAsync = promisify(fs.readdir); @@ -66,7 +65,7 @@ function longInspect(value) { export async function mkdirp(path) { assertAbsolute(path); - await mkdirpAsync(path); + await mkdirAsync(path, { recursive: true }); } export async function write(path, contents) { @@ -185,7 +184,7 @@ export async function untar(source, destination, extractOptions = {}) { assertAbsolute(source); assertAbsolute(destination); - await mkdirpAsync(destination); + await mkdirAsync(destination, { recursive: true }); await createPromiseFromStreams([ fs.createReadStream(source), diff --git a/src/dev/build/tasks/nodejs/download.js b/src/dev/build/tasks/nodejs/download.js index ee6da41042cd20..48313c0911c247 100644 --- a/src/dev/build/tasks/nodejs/download.js +++ b/src/dev/build/tasks/nodejs/download.js @@ -23,7 +23,8 @@ import { dirname } from 'path'; import chalk from 'chalk'; import { createHash } from 'crypto'; import wreck from '@hapi/wreck'; -import mkdirp from 'mkdirp'; + +import { mkdirp } from '../../lib'; function tryUnlink(path) { try { @@ -43,7 +44,7 @@ export async function download(options) { } // mkdirp and open file outside of try/catch, we don't retry for those errors - mkdirp.sync(dirname(destination)); + await mkdirp(dirname(destination)); const fileHandle = openSync(destination, 'w'); let error; diff --git a/src/dev/build/tasks/nodejs/extract_node_builds_task.js b/src/dev/build/tasks/nodejs/extract_node_builds_task.js index f8e767ac79a4b3..46c6433b27f9c0 100644 --- a/src/dev/build/tasks/nodejs/extract_node_builds_task.js +++ b/src/dev/build/tasks/nodejs/extract_node_builds_task.js @@ -20,13 +20,11 @@ import { dirname, resolve } from 'path'; import fs from 'fs'; import { promisify } from 'util'; -import mkdirp from 'mkdirp'; -import { untar } from '../../lib'; +import { untar, mkdirp } from '../../lib'; import { getNodeDownloadInfo } from './node_download_info'; const statAsync = promisify(fs.stat); -const mkdirpAsync = promisify(mkdirp); const copyFileAsync = promisify(fs.copyFile); export const ExtractNodeBuildsTask = { @@ -50,7 +48,7 @@ export const ExtractNodeBuildsTask = { async copyWindows(source, destination) { // ensure source exists before creating destination directory await statAsync(source); - await mkdirpAsync(dirname(destination)); + await mkdirp(dirname(destination)); // for performance reasons, do a copy-on-write by using the fs.constants.COPYFILE_FICLONE flag return await copyFileAsync(source, destination, fs.constants.COPYFILE_FICLONE); }, diff --git a/src/dev/build/tasks/patch_native_modules_task.js b/src/dev/build/tasks/patch_native_modules_task.js index 7da51ac717c429..4d952f44626cdc 100644 --- a/src/dev/build/tasks/patch_native_modules_task.js +++ b/src/dev/build/tasks/patch_native_modules_task.js @@ -18,10 +18,9 @@ */ import { scanCopy, untar, deleteAll } from '../lib'; -import { createWriteStream } from 'fs'; +import { createWriteStream, mkdirSync } from 'fs'; import { binaryInfo } from '../../../../x-pack/legacy/plugins/code/tasks/nodegit_info'; import wreck from '@hapi/wreck'; -import mkdirp from 'mkdirp'; import { dirname, join, basename } from 'path'; import { createPromiseFromStreams } from '../../../legacy/utils/streams'; @@ -31,7 +30,7 @@ async function download(url, destination, log) { if (response.statusCode !== 200) { throw new Error(`Unexpected status code ${response.statusCode} when downloading ${url}`); } - mkdirp.sync(dirname(destination)); + mkdirSync(dirname(destination), { recursive: true }); await createPromiseFromStreams([response, createWriteStream(destination)]); log.debug('Downloaded ', url); } diff --git a/src/dev/index.ts b/src/dev/index.ts new file mode 100644 index 00000000000000..4586cc2a2ff76f --- /dev/null +++ b/src/dev/index.ts @@ -0,0 +1,25 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +// @ts-ignore not typed yet +export { createAutoJUnitReporter } from './auto_junit_reporter'; +// @ts-ignore not typed yet +export { setupJUnitReportGeneration } from './junit_report_generation'; +// @ts-ignore not typed yet +export { runMochaCli } from './run_mocha_cli'; diff --git a/src/dev/jest/junit_reporter.js b/src/dev/jest/junit_reporter.js index 0f748eff91e566..e32edd783949ab 100644 --- a/src/dev/jest/junit_reporter.js +++ b/src/dev/jest/junit_reporter.js @@ -18,9 +18,8 @@ */ import { resolve, dirname, relative } from 'path'; -import { writeFileSync } from 'fs'; +import { writeFileSync, mkdirSync } from 'fs'; -import mkdirp from 'mkdirp'; import xmlBuilder from 'xmlbuilder'; import { escapeCdata } from '../xml'; @@ -117,7 +116,7 @@ export default class JestJUnitReporter { spacebeforeslash: '', }); - mkdirp.sync(dirname(reportPath)); + mkdirSync(dirname(reportPath), { recursive: true }); writeFileSync(reportPath, reportXML, 'utf8'); } } diff --git a/src/dev/mocha/index.js b/src/dev/mocha/index.js index 9f99f568312632..4586cc2a2ff76f 100644 --- a/src/dev/mocha/index.js +++ b/src/dev/mocha/index.js @@ -17,6 +17,9 @@ * under the License. */ +// @ts-ignore not typed yet export { createAutoJUnitReporter } from './auto_junit_reporter'; +// @ts-ignore not typed yet export { setupJUnitReportGeneration } from './junit_report_generation'; +// @ts-ignore not typed yet export { runMochaCli } from './run_mocha_cli'; diff --git a/src/dev/mocha/junit_report_generation.js b/src/dev/mocha/junit_report_generation.js index 56f03596406442..87899c63dfead4 100644 --- a/src/dev/mocha/junit_report_generation.js +++ b/src/dev/mocha/junit_report_generation.js @@ -18,10 +18,9 @@ */ import { resolve, dirname, relative } from 'path'; -import { writeFileSync } from 'fs'; +import { writeFileSync, mkdirSync } from 'fs'; import { inspect } from 'util'; -import mkdirp from 'mkdirp'; import xmlBuilder from 'xmlbuilder'; import { getSnapshotOfRunnableLogs } from './log_cache'; @@ -150,7 +149,7 @@ export function setupJUnitReportGeneration(runner, options = {}) { spacebeforeslash: '', }); - mkdirp.sync(dirname(reportPath)); + mkdirSync(dirname(reportPath), { recursive: true }); writeFileSync(reportPath, reportXML, 'utf8'); }); } diff --git a/src/dev/notice/generate_notice_from_source.js b/src/dev/notice/generate_notice_from_source.ts similarity index 83% rename from src/dev/notice/generate_notice_from_source.js rename to src/dev/notice/generate_notice_from_source.ts index ba1492b9d82601..08384e1e159f3a 100644 --- a/src/dev/notice/generate_notice_from_source.js +++ b/src/dev/notice/generate_notice_from_source.ts @@ -18,25 +18,30 @@ */ import vfs from 'vinyl-fs'; +import { ToolingLog } from '@kbn/dev-utils'; const NOTICE_COMMENT_RE = /\/\*[\s\n\*]*@notice([\w\W]+?)\*\//g; const NEWLINE_RE = /\r?\n/g; +interface Options { + /** + * Name to print at the top of the notice + */ + productName: string; + /** + * absolute path to the repo to search for @notice comments + */ + directory: string; + log: ToolingLog; +} + /** * Generates the text for the NOTICE.txt file at the root of the * repo which details the licenses for code that is copied/vendored * into the repository. - * - * @param {Object} options - * @property {string} options.productName Name to print at the top of the notice - * @property {ToolingLog} options.log - * @property {string} options.directory absolute path to the repo to search for @notice comments - * @return {string} */ -export async function generateNoticeFromSource({ productName, directory, log }) { - const globs = [ - '**/*.{js,less,css,ts}', - ]; +export async function generateNoticeFromSource({ productName, directory, log }: Options) { + const globs = ['**/*.{js,less,css,ts}']; const options = { cwd: directory, @@ -46,7 +51,7 @@ export async function generateNoticeFromSource({ productName, directory, log }) 'packages/*/{node_modules,build,target,dist}/**', 'x-pack/{node_modules,build,target,dist,optimize}/**', 'x-pack/packages/*/{node_modules,build,target,dist}/**', - ] + ], }; log.debug('vfs.src globs', globs); @@ -54,10 +59,10 @@ export async function generateNoticeFromSource({ productName, directory, log }) log.info(`Searching ${directory} for multi-line comments starting with @notice`); const files = vfs.src(globs, options); - const noticeComments = []; + const noticeComments: string[] = []; await new Promise((resolve, reject) => { files - .on('data', (file) => { + .on('data', file => { log.verbose(`Checking for @notice comments in ${file.relative}`); const source = file.contents.toString('utf8'); @@ -75,19 +80,19 @@ export async function generateNoticeFromSource({ productName, directory, log }) let noticeText = ''; noticeText += `${productName}\n`; - noticeText += `Copyright 2012-${(new Date()).getUTCFullYear()} Elasticsearch B.V.\n`; + noticeText += `Copyright 2012-${new Date().getUTCFullYear()} Elasticsearch B.V.\n`; for (const comment of noticeComments.sort()) { noticeText += '\n---\n'; noticeText += comment .split(NEWLINE_RE) - .map(line => ( + .map(line => line // trim whitespace .trim() // trim leading * and a single space .replace(/(^\* ?)/, '') - )) + ) .join('\n') .trim(); noticeText += '\n'; diff --git a/src/dev/notice/index.js b/src/dev/notice/index.ts similarity index 97% rename from src/dev/notice/index.js rename to src/dev/notice/index.ts index 17fbd20c22061d..9f3fd61a9831e2 100644 --- a/src/dev/notice/index.js +++ b/src/dev/notice/index.ts @@ -18,4 +18,5 @@ */ export { generateNoticeFromSource } from './generate_notice_from_source'; +// @ts-ignore not typed yet export { generateBuildNoticeText } from './generate_build_notice_text'; diff --git a/src/dev/register_git_hook/register_git_hook.js b/src/dev/register_git_hook/register_git_hook.js index bdb3e2d8060302..a61922078e6876 100644 --- a/src/dev/register_git_hook/register_git_hook.js +++ b/src/dev/register_git_hook/register_git_hook.js @@ -37,7 +37,7 @@ const writeFileAsync = promisify(writeFile); async function getPrecommitGitHookScriptPath(rootPath) { // Retrieves the correct location for the .git dir for // every git setup (including git worktree) - const gitDirPath = (await gitRevParseAsync(['--git-dir'])).trim(); + const gitDirPath = (await gitRevParseAsync(['--git-common-dir'])).trim(); return resolve(rootPath, gitDirPath, 'hooks/pre-commit'); } diff --git a/src/es_archiver/actions/save.js b/src/es_archiver/actions/save.js index 610e85f3a89ac6..c515a376ecd7b6 100644 --- a/src/es_archiver/actions/save.js +++ b/src/es_archiver/actions/save.js @@ -18,10 +18,7 @@ */ import { resolve } from 'path'; -import { createWriteStream } from 'fs'; - -import { fromNode } from 'bluebird'; -import mkdirp from 'mkdirp'; +import { createWriteStream, mkdirSync } from 'fs'; import { createListStream, @@ -42,7 +39,7 @@ export async function saveAction({ name, indices, client, dataDir, log, raw }) { log.info('[%s] Creating archive of %j', name, indices); - await fromNode(cb => mkdirp(outputDir, cb)); + mkdirSync(outputDir, { recursive: true }); const progress = new Progress(); progress.activate(log); diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_bar.tsx b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_bar.tsx index 90dec12fb814d4..066adb1e3275e8 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_bar.tsx +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_bar.tsx @@ -31,12 +31,13 @@ import { import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; import classNames from 'classnames'; import React, { useState } from 'react'; -import { UiSettingsClientContract } from 'src/core/public'; +import { CoreStart } from 'src/core/public'; +import { DataPublicPluginStart } from 'src/plugins/data/public'; import { IndexPattern } from '../../index_patterns'; import { FilterEditor } from './filter_editor'; import { FilterItem } from './filter_item'; import { FilterOptions } from './filter_options'; -import { useKibana } from '../../../../../../plugins/kibana_react/public'; +import { useKibana, KibanaContextProvider } from '../../../../../../plugins/kibana_react/public'; interface Props { filters: Filter[]; @@ -45,18 +46,45 @@ interface Props { indexPatterns: IndexPattern[]; intl: InjectedIntl; - // Only for directives! - uiSettings?: UiSettingsClientContract; + // TODO: Only for filter-bar directive! + uiSettings?: CoreStart['uiSettings']; + docLinks?: CoreStart['docLinks']; + pluginDataStart?: DataPublicPluginStart; } function FilterBarUI(props: Props) { const [isAddFilterPopoverOpen, setIsAddFilterPopoverOpen] = useState(false); const kibana = useKibana(); - let { uiSettings } = kibana.services; - if (!uiSettings) { - // Only for directives! - uiSettings = props.uiSettings; + const uiSettings = kibana.services.uiSettings || props.uiSettings; + if (!uiSettings) return null; + + function hasContext() { + return Boolean(kibana.services.uiSettings); + } + + function wrapInContextIfMissing(content: JSX.Element) { + // TODO: Relevant only as long as directives are used! + if (!hasContext()) { + if (props.docLinks && props.uiSettings && props.pluginDataStart) { + return ( + + {content} + + ); + } else { + throw new Error( + 'Rending filter bar requires providing sufficient context: uiSettings, docLinks and NP data plugin' + ); + } + } + return content; } function onFiltersUpdated(filters: Filter[]) { @@ -100,7 +128,7 @@ function FilterBarUI(props: Props) { ); - return ( + return wrapInContextIfMissing( setIsAddFilterPopoverOpen(false)} key={JSON.stringify(newFilter)} - uiSettings={uiSettings!} /> diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/index.tsx b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/index.tsx index 64487df5b22d47..5b295a759d694d 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/index.tsx +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/index.tsx @@ -36,7 +36,6 @@ import { i18n } from '@kbn/i18n'; import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; import { get } from 'lodash'; import React, { Component } from 'react'; -import { UiSettingsClientContract } from 'src/core/public'; import { Field, IndexPattern } from '../../../index_patterns'; import { GenericComboBox, GenericComboBoxProps } from './generic_combo_box'; import { @@ -62,7 +61,6 @@ interface Props { onSubmit: (filter: Filter) => void; onCancel: () => void; intl: InjectedIntl; - uiSettings: UiSettingsClientContract; } interface State { @@ -343,7 +341,6 @@ class FilterEditorUI extends Component { value={this.state.params} onChange={this.onParamsChange} data-test-subj="phraseValueInput" - uiSettings={this.props.uiSettings} /> ); case 'phrases': @@ -353,7 +350,6 @@ class FilterEditorUI extends Component { field={this.state.selectedField} values={this.state.params} onChange={this.onParamsChange} - uiSettings={this.props.uiSettings} /> ); case 'range': diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/phrase_suggestor.tsx b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/phrase_suggestor.tsx index 6b262c66402f23..9ef5f546c0be0f 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/phrase_suggestor.tsx +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/phrase_suggestor.tsx @@ -18,14 +18,17 @@ */ import { Component } from 'react'; -import { getSuggestions } from 'ui/value_suggestions'; -import { UiSettingsClientContract } from 'src/core/public'; import { Field, IndexPattern } from '../../../index_patterns'; +import { + withKibana, + KibanaReactContextValue, +} from '../../../../../../../plugins/kibana_react/public'; +import { IDataPluginServices } from '../../../types'; export interface PhraseSuggestorProps { + kibana: KibanaReactContextValue; indexPattern: IndexPattern; field?: Field; - uiSettings: UiSettingsClientContract; } export interface PhraseSuggestorState { @@ -38,10 +41,11 @@ export interface PhraseSuggestorState { * aggregatable), we pull out the common logic for requesting suggestions into this component * which both of them extend. */ -export class PhraseSuggestor extends Component< +export class PhraseSuggestorUI extends Component< T, PhraseSuggestorState > { + private services = this.props.kibana.services; public state: PhraseSuggestorState = { suggestions: [], isLoading: false, @@ -52,7 +56,7 @@ export class PhraseSuggestor extends Component< } protected isSuggestingValues() { - const shouldSuggestValues = this.props.uiSettings.get('filterEditor:suggestValues'); + const shouldSuggestValues = this.services.uiSettings.get('filterEditor:suggestValues'); const { field } = this.props; return shouldSuggestValues && field && field.aggregatable && field.type === 'string'; } @@ -67,7 +71,9 @@ export class PhraseSuggestor extends Component< return; } this.setState({ isLoading: true }); - const suggestions = await getSuggestions(indexPattern.title, field, value); + const suggestions = await this.services.data.getSuggestions(indexPattern.title, field, value); this.setState({ suggestions, isLoading: false }); } } + +export const PhraseSuggestor = withKibana(PhraseSuggestorUI); diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/phrase_value_input.tsx b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/phrase_value_input.tsx index 0696bacc568b55..7ef51f88ba57e1 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/phrase_value_input.tsx +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/phrase_value_input.tsx @@ -22,8 +22,9 @@ import { InjectedIntl, injectI18n } from '@kbn/i18n/react'; import { uniq } from 'lodash'; import React from 'react'; import { GenericComboBox, GenericComboBoxProps } from './generic_combo_box'; -import { PhraseSuggestor, PhraseSuggestorProps } from './phrase_suggestor'; +import { PhraseSuggestorUI, PhraseSuggestorProps } from './phrase_suggestor'; import { ValueInputType } from './value_input_type'; +import { withKibana } from '../../../../../../../plugins/kibana_react/public'; interface Props extends PhraseSuggestorProps { value?: string; @@ -31,7 +32,7 @@ interface Props extends PhraseSuggestorProps { intl: InjectedIntl; } -class PhraseValueInputUI extends PhraseSuggestor { +class PhraseValueInputUI extends PhraseSuggestorUI { public render() { return ( ) { return GenericComboBox(props); } -export const PhraseValueInput = injectI18n(PhraseValueInputUI); +export const PhraseValueInput = injectI18n(withKibana(PhraseValueInputUI)); diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/phrases_values_input.tsx b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/phrases_values_input.tsx index d35e49b6b07ce7..f3b30e2ad5fd92 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/phrases_values_input.tsx +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_editor/phrases_values_input.tsx @@ -22,7 +22,8 @@ import { InjectedIntl, injectI18n } from '@kbn/i18n/react'; import { uniq } from 'lodash'; import React from 'react'; import { GenericComboBox, GenericComboBoxProps } from './generic_combo_box'; -import { PhraseSuggestor, PhraseSuggestorProps } from './phrase_suggestor'; +import { PhraseSuggestorUI, PhraseSuggestorProps } from './phrase_suggestor'; +import { withKibana } from '../../../../../../../plugins/kibana_react/public'; interface Props extends PhraseSuggestorProps { values?: string[]; @@ -30,7 +31,7 @@ interface Props extends PhraseSuggestorProps { intl: InjectedIntl; } -class PhrasesValuesInputUI extends PhraseSuggestor { +class PhrasesValuesInputUI extends PhraseSuggestorUI { public render() { const { suggestions } = this.state; const { values, intl, onChange } = this.props; @@ -64,4 +65,4 @@ function StringComboBox(props: GenericComboBoxProps) { return GenericComboBox(props); } -export const PhrasesValuesInput = injectI18n(PhrasesValuesInputUI); +export const PhrasesValuesInput = injectI18n(withKibana(PhrasesValuesInputUI)); diff --git a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_item.tsx b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_item.tsx index 250f6ad209fa7b..21259cec51d3ac 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_bar/filter_item.tsx +++ b/src/legacy/core_plugins/data/public/filter/filter_bar/filter_item.tsx @@ -171,7 +171,6 @@ class FilterItemUI extends Component { indexPatterns={this.props.indexPatterns} onSubmit={this.onSubmit} onCancel={this.closePopover} - uiSettings={this.props.uiSettings} /> ), diff --git a/src/legacy/core_plugins/data/public/index.ts b/src/legacy/core_plugins/data/public/index.ts index d96e3be8d7e380..b9554310e2413d 100644 --- a/src/legacy/core_plugins/data/public/index.ts +++ b/src/legacy/core_plugins/data/public/index.ts @@ -18,7 +18,7 @@ */ // /// Define plugin function -import { DataPlugin as Plugin, DataSetup } from './plugin'; +import { DataPlugin as Plugin, DataSetup, DataStart } from './plugin'; export function plugin() { return new Plugin(); @@ -28,6 +28,7 @@ export function plugin() { /** @public types */ export type DataSetup = DataSetup; +export type DataStart = DataStart; export { FilterBar, ApplyFiltersPopover } from './filter'; export { diff --git a/src/legacy/core_plugins/data/public/plugin.ts b/src/legacy/core_plugins/data/public/plugin.ts index a5aa55673cac66..7f2c92cb5c6fe3 100644 --- a/src/legacy/core_plugins/data/public/plugin.ts +++ b/src/legacy/core_plugins/data/public/plugin.ts @@ -107,6 +107,7 @@ export class DataPlugin const timefilterService = this.timefilter.setup({ uiSettings, + store: __LEGACY.storage, }); this.setupApi = { indexPatterns: indexPatternsService, @@ -126,10 +127,10 @@ export class DataPlugin public start(core: CoreStart, { __LEGACY, data }: DataPluginStartDependencies) { const SearchBar = createSearchBar({ core, + data, store: __LEGACY.storage, timefilter: this.setupApi.timefilter, filterManager: this.setupApi.filter.filterManager, - autocomplete: data.autocomplete, }); return { diff --git a/src/legacy/core_plugins/vis_type_timeseries/common/es_types.js b/src/legacy/core_plugins/data/public/query/persisted_log/index.ts similarity index 86% rename from src/legacy/core_plugins/vis_type_timeseries/common/es_types.js rename to src/legacy/core_plugins/data/public/query/persisted_log/index.ts index 7e6a53753fae36..9b21c748da02d7 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/common/es_types.js +++ b/src/legacy/core_plugins/data/public/query/persisted_log/index.ts @@ -17,10 +17,4 @@ * under the License. */ -export const ES_TYPES = { - NUMBER: 'number', - STRING: 'string', - KEYWORD: 'keyword', - TEXT: 'text', - DATE: 'date', -}; +export * from './persisted_log'; diff --git a/src/legacy/ui/public/persisted_log/persisted_log.test.ts b/src/legacy/core_plugins/data/public/query/persisted_log/persisted_log.test.ts similarity index 100% rename from src/legacy/ui/public/persisted_log/persisted_log.test.ts rename to src/legacy/core_plugins/data/public/query/persisted_log/persisted_log.test.ts diff --git a/src/legacy/ui/public/persisted_log/persisted_log.ts b/src/legacy/core_plugins/data/public/query/persisted_log/persisted_log.ts similarity index 95% rename from src/legacy/ui/public/persisted_log/persisted_log.ts rename to src/legacy/core_plugins/data/public/query/persisted_log/persisted_log.ts index 0824d177573115..e0e6a0d0c44e4c 100644 --- a/src/legacy/ui/public/persisted_log/persisted_log.ts +++ b/src/legacy/core_plugins/data/public/query/persisted_log/persisted_log.ts @@ -20,9 +20,7 @@ import _ from 'lodash'; import * as Rx from 'rxjs'; import { map } from 'rxjs/operators'; -import { Storage } from 'ui/storage'; - -const localStorage = new Storage(window.localStorage); +import { Storage } from '../../types'; const defaultIsDuplicate = (oldItem: any, newItem: any) => { return _.isEqual(oldItem, newItem); @@ -44,7 +42,7 @@ export class PersistedLog { private update$ = new Rx.BehaviorSubject(undefined); - constructor(name: string, options: PersistedLogOptions = {}, storage = localStorage) { + constructor(name: string, options: PersistedLogOptions = {}, storage: Storage) { this.name = name; this.maxLength = typeof options.maxLength === 'string' diff --git a/src/legacy/core_plugins/data/public/query/query_bar/components/__snapshots__/query_bar_input.test.tsx.snap b/src/legacy/core_plugins/data/public/query/query_bar/components/__snapshots__/query_bar_input.test.tsx.snap index da756275a83e9a..6fdbf4fce45537 100644 --- a/src/legacy/core_plugins/data/public/query/query_bar/components/__snapshots__/query_bar_input.test.tsx.snap +++ b/src/legacy/core_plugins/data/public/query/query_bar/components/__snapshots__/query_bar_input.test.tsx.snap @@ -583,10 +583,9 @@ exports[`QueryBarInput Should disable autoFocus on EuiFieldText when disableAuto onOutsideClick={[Function]} >
} - aria-activedescendant="" aria-autocomplete="list" - aria-controls="kbnTypeahead__items" - aria-label="You are on search box of Another Screen page. Start typing to search and filter the test" + aria-label="Start typing to search and filter the test page" autoComplete="off" autoFocus={false} compressed={false} @@ -651,10 +648,8 @@ exports[`QueryBarInput Should disable autoFocus on EuiFieldText when disableAuto >
} - aria-activedescendant="" aria-autocomplete="list" - aria-controls="kbnTypeahead__items" - aria-label="You are on search box of Another Screen page. Start typing to search and filter the test" + aria-label="Start typing to search and filter the test page" autoComplete="off" autoFocus={true} compressed={false} @@ -1425,10 +1417,8 @@ exports[`QueryBarInput Should pass the query language to the language switcher 1 >
} - aria-activedescendant="" aria-autocomplete="list" - aria-controls="kbnTypeahead__items" - aria-label="You are on search box of Another Screen page. Start typing to search and filter the test" + aria-label="Start typing to search and filter the test page" autoComplete="off" autoFocus={true} compressed={false} @@ -2199,10 +2186,8 @@ exports[`QueryBarInput Should render the given query 1`] = ` > ({ +jest.mock('../../persisted_log', () => ({ PersistedLog: mockPersistedLogFactory, })); diff --git a/src/legacy/core_plugins/data/public/query/query_bar/components/query_bar_input.tsx b/src/legacy/core_plugins/data/public/query/query_bar/components/query_bar_input.tsx index 6c91da7c28135f..1b232128c744a9 100644 --- a/src/legacy/core_plugins/data/public/query/query_bar/components/query_bar_input.tsx +++ b/src/legacy/core_plugins/data/public/query/query_bar/components/query_bar_input.tsx @@ -19,12 +19,12 @@ import { Component } from 'react'; import React from 'react'; +import { i18n } from '@kbn/i18n'; import { EuiFieldText, EuiOutsideClickDetector, PopoverAnchorPosition } from '@elastic/eui'; import { InjectedIntl, injectI18n } from '@kbn/i18n/react'; import { debounce, compact, isEqual } from 'lodash'; -import { PersistedLog } from 'ui/persisted_log'; import { AutocompleteSuggestion, @@ -35,11 +35,11 @@ import { KibanaReactContextValue, } from '../../../../../../../plugins/kibana_react/public'; import { IndexPattern, StaticIndexPattern } from '../../../index_patterns'; -import { Query } from '../index'; +import { Query, getQueryLog } from '../index'; import { fromUser, matchPairs, toUser } from '../lib'; import { QueryLanguageSwitcher } from './language_switcher'; import { SuggestionsComponent } from './typeahead/suggestions_component'; -import { getQueryLog } from '../lib/get_query_log'; +import { PersistedLog } from '../../persisted_log'; import { fetchIndexPatterns } from '../lib/fetch_index_patterns'; import { IDataPluginServices } from '../../../types'; @@ -134,8 +134,8 @@ export class QueryBarInputUI extends Component { const queryString = this.getQueryString(); const recentSearchSuggestions = this.getRecentSearchSuggestions(queryString); + const autocompleteProvider = this.services.data.autocomplete.getProvider(language); - const autocompleteProvider = this.services.autocomplete.getProvider(language); if ( !autocompleteProvider || !Array.isArray(this.state.indexPatterns) || @@ -391,6 +391,7 @@ export class QueryBarInputUI extends Component { }; public componentDidMount() { + const { uiSettings, store, appName } = this.services; const parsedQuery = fromUser(toUser(this.props.query.query)); if (!isEqual(this.props.query.query, parsedQuery)) { this.onChange({ ...this.props.query, query: parsedQuery }); @@ -398,12 +399,13 @@ export class QueryBarInputUI extends Component { this.persistedLog = this.props.persistedLog ? this.props.persistedLog - : getQueryLog(this.services.uiSettings, this.services.appName, this.props.query.language); + : getQueryLog(uiSettings, store, appName, this.props.query.language); this.fetchIndexPatterns().then(this.updateSuggestions); } public componentDidUpdate(prevProps: Props) { + const { uiSettings, store, appName } = this.services; const parsedQuery = fromUser(toUser(this.props.query.query)); if (!isEqual(this.props.query.query, parsedQuery)) { this.onChange({ ...this.props.query, query: parsedQuery }); @@ -411,7 +413,7 @@ export class QueryBarInputUI extends Component { this.persistedLog = this.props.persistedLog ? this.props.persistedLog - : getQueryLog(this.services.uiSettings, this.services.appName, this.props.query.language); + : getQueryLog(uiSettings, store, appName, this.props.query.language); if (!isEqual(prevProps.indexPatterns, this.props.indexPatterns)) { this.fetchIndexPatterns().then(this.updateSuggestions); @@ -438,23 +440,30 @@ export class QueryBarInputUI extends Component { } public render() { + const isSuggestionsVisible = this.state.isSuggestionsVisible && { + 'aria-controls': 'kbnTypeahead__items', + 'aria-owns': 'kbnTypeahead__items', + }; + const ariaCombobox = { ...isSuggestionsVisible, role: 'combobox' }; + return (
{ }} autoComplete="off" spellCheck={false} - aria-label={ - this.props.screenTitle - ? this.props.intl.formatMessage( - { - id: 'data.query.queryBar.searchInputAriaLabel', - defaultMessage: - 'You are on search box of {previouslyTranslatedPageTitle} page. Start typing to search and filter the {pageType}', - }, - { - previouslyTranslatedPageTitle: this.props.screenTitle, - pageType: this.services.appName, - } - ) - : undefined - } + aria-label={i18n.translate('data.query.queryBar.searchInputAriaLabel', { + defaultMessage: 'Start typing to search and filter the {pageType} page', + values: { pageType: this.services.appName }, + })} type="text" aria-autocomplete="list" - aria-controls="kbnTypeahead__items" + aria-controls={this.state.isSuggestionsVisible ? 'kbnTypeahead__items' : undefined} aria-activedescendant={ - this.state.isSuggestionsVisible ? 'suggestion-' + this.state.index : '' + this.state.isSuggestionsVisible && typeof this.state.index === 'number' + ? `suggestion-${this.state.index}` + : undefined } role="textbox" prepend={this.props.prepend} diff --git a/src/legacy/core_plugins/data/public/query/query_bar/components/query_bar_top_row.tsx b/src/legacy/core_plugins/data/public/query/query_bar/components/query_bar_top_row.tsx index 6895c9ecd018cb..716bb677b946fb 100644 --- a/src/legacy/core_plugins/data/public/query/query_bar/components/query_bar_top_row.tsx +++ b/src/legacy/core_plugins/data/public/query/query_bar/components/query_bar_top_row.tsx @@ -22,7 +22,6 @@ import { doesKueryExpressionHaveLuceneSyntaxError } from '@kbn/es-query'; import classNames from 'classnames'; import React, { useState, useEffect } from 'react'; import { documentationLinks } from 'ui/documentation_links'; -import { PersistedLog } from 'ui/persisted_log'; import { EuiButton, EuiFlexGroup, EuiFlexItem, EuiLink, EuiSuperDatePicker } from '@elastic/eui'; // @ts-ignore @@ -34,10 +33,10 @@ import { useKibana } from '../../../../../../../plugins/kibana_react/public'; import { IndexPattern } from '../../../index_patterns'; import { QueryBarInput } from './query_bar_input'; -import { getQueryLog } from '../lib/get_query_log'; -import { Query } from '../index'; +import { Query, getQueryLog } from '../index'; import { TimeHistoryContract } from '../../../timefilter'; import { IDataPluginServices } from '../../../types'; +import { PersistedLog } from '../../persisted_log'; interface Props { query?: Query; @@ -72,7 +71,7 @@ function QueryBarTopRowUI(props: Props) { useEffect(() => { if (!props.query) return; - persistedLog = getQueryLog(uiSettings!, appName, props.query.language); + persistedLog = getQueryLog(uiSettings!, store, appName, props.query.language); }, [queryLanguage]); function onClickSubmitButton(event: React.MouseEvent) { diff --git a/src/legacy/core_plugins/data/public/query/query_bar/lib/get_query_log.ts b/src/legacy/core_plugins/data/public/query/query_bar/lib/get_query_log.ts index 70dc1d3fe700e0..8b26e14c6ed7bd 100644 --- a/src/legacy/core_plugins/data/public/query/query_bar/lib/get_query_log.ts +++ b/src/legacy/core_plugins/data/public/query/query_bar/lib/get_query_log.ts @@ -17,16 +17,22 @@ * under the License. */ -import { PersistedLog } from 'ui/persisted_log'; import { UiSettingsClientContract } from 'src/core/public'; +import { PersistedLog } from '../../persisted_log'; +import { Storage } from '../../../types'; export function getQueryLog( uiSettings: UiSettingsClientContract, + store: Storage, appName: string, language: string ) { - return new PersistedLog(`typeahead:${appName}-${language}`, { - maxLength: uiSettings.get('history:limit'), - filterDuplicates: true, - }); + return new PersistedLog( + `typeahead:${appName}-${language}`, + { + maxLength: uiSettings.get('history:limit'), + filterDuplicates: true, + }, + store + ); } diff --git a/src/legacy/core_plugins/data/public/search/search_bar/components/create_search_bar.tsx b/src/legacy/core_plugins/data/public/search/search_bar/components/create_search_bar.tsx index add49e47971d34..c84e460a1556ca 100644 --- a/src/legacy/core_plugins/data/public/search/search_bar/components/create_search_bar.tsx +++ b/src/legacy/core_plugins/data/public/search/search_bar/components/create_search_bar.tsx @@ -20,8 +20,8 @@ import React from 'react'; import { Filter } from '@kbn/es-query'; import { CoreStart } from 'src/core/public'; -import { Storage } from 'ui/storage'; -import { AutocompletePublicPluginStart } from 'src/plugins/data/public'; +import { DataPublicPluginStart } from 'src/plugins/data/public'; +import { Storage } from '../../../types'; import { KibanaContextProvider } from '../../../../../../../../src/plugins/kibana_react/public'; import { TimefilterSetup } from '../../../timefilter'; import { FilterManager, SearchBar } from '../../../'; @@ -29,10 +29,10 @@ import { SearchBarOwnProps } from '.'; interface StatefulSearchBarDeps { core: CoreStart; + data: DataPublicPluginStart; store: Storage; timefilter: TimefilterSetup; filterManager: FilterManager; - autocomplete: AutocompletePublicPluginStart; } export type StatetfulSearchBarProps = SearchBarOwnProps & { @@ -59,7 +59,7 @@ export function createSearchBar({ store, timefilter, filterManager, - autocomplete, + data, }: StatefulSearchBarDeps) { // App name should come from the core application service. // Until it's available, we'll ask the user to provide it for the pre-wired component. @@ -71,7 +71,7 @@ export function createSearchBar({ void; + // User has saved the current state as a saved query onSaved?: (savedQuery: SavedQuery) => void; + // User has modified the saved query, your app should persist the update onSavedQueryUpdated?: (savedQuery: SavedQuery) => void; + // User has cleared the active query, your app should clear the entire query bar onClearSavedQuery?: () => void; } diff --git a/src/legacy/core_plugins/data/public/shim/legacy_dependencies_plugin.ts b/src/legacy/core_plugins/data/public/shim/legacy_dependencies_plugin.ts index 126754388f13f2..511482c6239fb1 100644 --- a/src/legacy/core_plugins/data/public/shim/legacy_dependencies_plugin.ts +++ b/src/legacy/core_plugins/data/public/shim/legacy_dependencies_plugin.ts @@ -25,6 +25,7 @@ import { initLegacyModule } from './legacy_module'; /** @internal */ export interface LegacyDependenciesPluginSetup { savedObjectsClient: any; + storage: Storage; } export interface LegacyDependenciesPluginStart { @@ -37,6 +38,7 @@ export class LegacyDependenciesPlugin implements Plugin { return { savedObjectsClient: chrome.getSavedObjectsClient(), + storage: new Storage(window.localStorage), } as LegacyDependenciesPluginSetup; } diff --git a/src/legacy/core_plugins/data/public/shim/legacy_module.ts b/src/legacy/core_plugins/data/public/shim/legacy_module.ts index 4e81a5d4294e6c..fea9409b2ec685 100644 --- a/src/legacy/core_plugins/data/public/shim/legacy_module.ts +++ b/src/legacy/core_plugins/data/public/shim/legacy_module.ts @@ -24,7 +24,7 @@ import { Filter } from '@kbn/es-query'; // @ts-ignore import { uiModules } from 'ui/modules'; -import { npSetup, npStart } from 'ui/new_platform'; +import { npStart } from 'ui/new_platform'; import { FilterBar, ApplyFiltersPopover } from '../filter'; import template from './apply_filter_directive.html'; @@ -49,14 +49,16 @@ export const initLegacyModule = once((): void => { } child.setAttribute('ui-settings', 'uiSettings'); - child.setAttribute('http', 'http'); + child.setAttribute('doc-links', 'docLinks'); + child.setAttribute('plugin-data-start', 'pluginDataStart'); // Append helper directive elem.append(child); const linkFn = ($scope: any) => { - $scope.uiSettings = npSetup.core.uiSettings; - $scope.http = npSetup.core.http; + $scope.uiSettings = npStart.core.uiSettings; + $scope.docLinks = npStart.core.docLinks; + $scope.pluginDataStart = npStart.plugins.data; }; return linkFn; @@ -66,11 +68,12 @@ export const initLegacyModule = once((): void => { .directive('filterBarHelper', (reactDirective: any) => { return reactDirective(wrapInI18nContext(FilterBar), [ ['uiSettings', { watchDepth: 'reference' }], - ['http', { watchDepth: 'reference' }], + ['docLinks', { watchDepth: 'reference' }], ['onFiltersUpdated', { watchDepth: 'reference' }], ['indexPatterns', { watchDepth: 'collection' }], ['filters', { watchDepth: 'collection' }], ['className', { watchDepth: 'reference' }], + ['pluginDataStart', { watchDepth: 'reference' }], ]); }) .directive('applyFiltersPopoverComponent', (reactDirective: any) => diff --git a/src/legacy/core_plugins/data/public/timefilter/time_history.ts b/src/legacy/core_plugins/data/public/timefilter/time_history.ts index 7dcd5843ae5304..22778d1adea3c4 100644 --- a/src/legacy/core_plugins/data/public/timefilter/time_history.ts +++ b/src/legacy/core_plugins/data/public/timefilter/time_history.ts @@ -19,12 +19,13 @@ import moment from 'moment'; import { TimeRange } from 'src/plugins/data/public'; -import { PersistedLog } from 'ui/persisted_log'; +import { PersistedLog } from '../query/persisted_log'; +import { Storage } from '../types'; export class TimeHistory { private history: PersistedLog; - constructor() { + constructor(store: Storage) { const historyOptions = { maxLength: 10, filterDuplicates: true, @@ -32,7 +33,7 @@ export class TimeHistory { return oldItem.from === newItem.from && oldItem.to === newItem.to; }, }; - this.history = new PersistedLog('kibana.timepicker.timeHistory', historyOptions); + this.history = new PersistedLog('kibana.timepicker.timeHistory', historyOptions, store); } add(time: TimeRange) { diff --git a/src/legacy/core_plugins/data/public/timefilter/timefilter_service.ts b/src/legacy/core_plugins/data/public/timefilter/timefilter_service.ts index 96c490a195d3dd..cda9b93ef08aa6 100644 --- a/src/legacy/core_plugins/data/public/timefilter/timefilter_service.ts +++ b/src/legacy/core_plugins/data/public/timefilter/timefilter_service.ts @@ -19,6 +19,7 @@ import { UiSettingsClientContract } from 'src/core/public'; import { TimeHistory, Timefilter, TimeHistoryContract, TimefilterContract } from './index'; +import { Storage } from '../types'; /** * Filter Service @@ -27,15 +28,16 @@ import { TimeHistory, Timefilter, TimeHistoryContract, TimefilterContract } from export interface TimeFilterServiceDependencies { uiSettings: UiSettingsClientContract; + store: Storage; } export class TimefilterService { - public setup({ uiSettings }: TimeFilterServiceDependencies): TimefilterSetup { + public setup({ uiSettings, store }: TimeFilterServiceDependencies): TimefilterSetup { const timefilterConfig = { timeDefaults: uiSettings.get('timepicker:timeDefaults'), refreshIntervalDefaults: uiSettings.get('timepicker:refreshIntervalDefaults'), }; - const history = new TimeHistory(); + const history = new TimeHistory(store); const timefilter = new Timefilter(timefilterConfig, history); return { diff --git a/src/legacy/core_plugins/data/public/types.ts b/src/legacy/core_plugins/data/public/types.ts index 4b7a5c1402ea72..2c02a9b7647555 100644 --- a/src/legacy/core_plugins/data/public/types.ts +++ b/src/legacy/core_plugins/data/public/types.ts @@ -18,7 +18,14 @@ */ import { UiSettingsClientContract, CoreStart } from 'src/core/public'; -import { AutocompletePublicPluginStart } from 'src/plugins/data/public'; +import { DataPublicPluginStart } from 'src/plugins/data/public'; + +export interface Storage { + get: (key: string) => any; + set: (key: string, value: any) => void; + remove: (key: string) => any; + clear: () => void; +} export interface IDataPluginServices extends Partial { appName: string; @@ -27,5 +34,5 @@ export interface IDataPluginServices extends Partial { notifications: CoreStart['notifications']; http: CoreStart['http']; store: Storage; - autocomplete: AutocompletePublicPluginStart; + data: DataPublicPluginStart; } diff --git a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/labels_panel.tsx b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/labels_panel.tsx index a24a37ca971d58..b96132fa29380f 100644 --- a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/labels_panel.tsx +++ b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/labels_panel.tsx @@ -29,12 +29,12 @@ function LabelsPanel({ stateParams, setValue, setGaugeValue }: GaugeOptionsInter return ( -

+

-

+
diff --git a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/ranges_panel.tsx b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/ranges_panel.tsx index 4abfb2e604b1dc..4e3b511782c9e7 100644 --- a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/ranges_panel.tsx +++ b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/ranges_panel.tsx @@ -38,12 +38,12 @@ function RangesPanel({ return ( -

+

-

+
diff --git a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/style_panel.tsx b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/style_panel.tsx index f606080afbdb2f..a76171673d9a82 100644 --- a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/style_panel.tsx +++ b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/gauge/style_panel.tsx @@ -34,12 +34,12 @@ function StylePanel({ aggs, setGaugeValue, stateParams, vis }: GaugeOptionsInter return ( -

+

-

+
diff --git a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/metrics_axes/__snapshots__/category_axis_panel.test.tsx.snap b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/metrics_axes/__snapshots__/category_axis_panel.test.tsx.snap index 6eef5047634f4f..d88654cfdc0c43 100644 --- a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/metrics_axes/__snapshots__/category_axis_panel.test.tsx.snap +++ b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/metrics_axes/__snapshots__/category_axis_panel.test.tsx.snap @@ -7,13 +7,13 @@ exports[`CategoryAxisPanel component should init with the default set of props 1 -

+

-

+
-

+

-

+ -

+

-

+
diff --git a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/metrics_axes/series_panel.tsx b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/metrics_axes/series_panel.tsx index 434202d64d6c30..5a455f4adde31f 100644 --- a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/metrics_axes/series_panel.tsx +++ b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/metrics_axes/series_panel.tsx @@ -38,12 +38,12 @@ function SeriesPanel(props: SeriesPanelProps) { return ( -

+

-

+
diff --git a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/metrics_axes/value_axes_panel.tsx b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/metrics_axes/value_axes_panel.tsx index 34a0d2cd981c5f..eb0ab4333af599 100644 --- a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/metrics_axes/value_axes_panel.tsx +++ b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/metrics_axes/value_axes_panel.tsx @@ -109,12 +109,12 @@ function ValueAxesPanel(props: ValueAxesPanelProps) { -

+

-

+
diff --git a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/pie.tsx b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/pie.tsx index 982c7265d5494c..53dde185ec09fe 100644 --- a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/pie.tsx +++ b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/pie.tsx @@ -36,12 +36,12 @@ function PieOptions(props: VisOptionsProps) { <> -

+

-

+
) { -
+

-

+
-

+

-

+
diff --git a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/point_series/point_series.tsx b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/point_series/point_series.tsx index 11034f7f7335e4..8e3f66d12b9bdf 100644 --- a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/point_series/point_series.tsx +++ b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/point_series/point_series.tsx @@ -34,12 +34,12 @@ function PointSeriesOptions(props: VisOptionsProps) { <> -

+

-

+
diff --git a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/point_series/threshold_panel.tsx b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/point_series/threshold_panel.tsx index 9877b84345a1fe..49e56e377a8d56 100644 --- a/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/point_series/threshold_panel.tsx +++ b/src/legacy/core_plugins/kbn_vislib_vis_types/public/components/options/point_series/threshold_panel.tsx @@ -42,12 +42,12 @@ function ThresholdPanel({ stateParams, setValue, vis }: VisOptionsProps -

+

-

+
diff --git a/src/legacy/core_plugins/kibana/index.js b/src/legacy/core_plugins/kibana/index.js index 3d9dfe6319127d..bb041924215ddd 100644 --- a/src/legacy/core_plugins/kibana/index.js +++ b/src/legacy/core_plugins/kibana/index.js @@ -17,9 +17,9 @@ * under the License. */ -import Promise from 'bluebird'; -import { mkdirp as mkdirpNode } from 'mkdirp'; +import Fs from 'fs'; import { resolve } from 'path'; +import { promisify } from 'util'; import { migrations } from './migrations'; import manageUuid from './server/lib/manage_uuid'; @@ -41,7 +41,7 @@ import { makeKQLUsageCollector } from './server/lib/kql_usage_collector'; import { injectVars } from './inject_vars'; import { i18n } from '@kbn/i18n'; -const mkdirp = Promise.promisify(mkdirpNode); +const mkdirAsync = promisify(Fs.mkdir); export default function (kibana) { const kbnBaseUrl = '/app/kibana'; @@ -320,7 +320,7 @@ export default function (kibana) { try { // Create the data directory (recursively, if the a parent dir doesn't exist). // If it already exists, does nothing. - await mkdirp(server.config().get('path.data')); + await mkdirAsync(server.config().get('path.data'), { recursive: true }); } catch (err) { server.log(['error', 'init'], err); // Stop the server startup with a fatal error diff --git a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app.html b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app.html index 5ceb28e6b225b8..39db357a69321f 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app.html +++ b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app.html @@ -120,6 +120,7 @@
+

{{screenTitle}}

diff --git a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app_controller.tsx b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app_controller.tsx index 741931af11c7de..22f127d12c4387 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app_controller.tsx +++ b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_app_controller.tsx @@ -331,7 +331,8 @@ export class DashboardAppController { getDashboardTitle( dashboardStateManager.getTitle(), dashboardStateManager.getViewMode(), - dashboardStateManager.getIsDirty(timefilter) + dashboardStateManager.getIsDirty(timefilter), + dashboardStateManager.isNew() ); // Push breadcrumbs to new header navigation diff --git a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_state_manager.ts b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_state_manager.ts index c1ce5b764f2f6a..7c1fc771de3491 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_state_manager.ts +++ b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_state_manager.ts @@ -229,6 +229,14 @@ export class DashboardStateManager { return this.appState.title; } + public isSaved() { + return !!this.savedDashboard.id; + } + + public isNew() { + return !this.isSaved(); + } + public getDescription() { return this.appState.description; } diff --git a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_strings.ts b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_strings.ts index b7f9293539abde..d932116d08dc8f 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_strings.ts +++ b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_strings.ts @@ -27,22 +27,31 @@ import { ViewMode } from '../../../../../../src/plugins/embeddable/public'; * end of the title. * @returns {string} A title to display to the user based on the above parameters. */ -export function getDashboardTitle(title: string, viewMode: ViewMode, isDirty: boolean): string { +export function getDashboardTitle( + title: string, + viewMode: ViewMode, + isDirty: boolean, + isNew: boolean +): string { const isEditMode = viewMode === ViewMode.EDIT; let displayTitle: string; + const newDashboardTitle = i18n.translate('kbn.dashboard.savedDashboard.newDashboardTitle', { + defaultMessage: 'New Dashboard', + }); + const dashboardTitle = isNew ? newDashboardTitle : title; if (isEditMode && isDirty) { displayTitle = i18n.translate('kbn.dashboard.strings.dashboardUnsavedEditTitle', { defaultMessage: 'Editing {title} (unsaved)', - values: { title }, + values: { title: dashboardTitle }, }); } else if (isEditMode) { displayTitle = i18n.translate('kbn.dashboard.strings.dashboardEditTitle', { defaultMessage: 'Editing {title}', - values: { title }, + values: { title: dashboardTitle }, }); } else { - displayTitle = title; + displayTitle = dashboardTitle; } return displayTitle; diff --git a/src/legacy/core_plugins/kibana/public/dashboard/index.js b/src/legacy/core_plugins/kibana/public/dashboard/index.js index e22eb8e8db91d0..31e7f58649d382 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/index.js +++ b/src/legacy/core_plugins/kibana/public/dashboard/index.js @@ -33,12 +33,13 @@ import { DashboardConstants, createDashboardEditUrl } from './dashboard_constant import { InvalidJSONProperty, SavedObjectNotFound } from '../../../../../plugins/kibana_utils/public'; import { FeatureCatalogueRegistryProvider, FeatureCatalogueCategory } from 'ui/registry/feature_catalogue'; import { SavedObjectsClientProvider } from 'ui/saved_objects'; -import { recentlyAccessed } from 'ui/persisted_log'; import { SavedObjectRegistryProvider } from 'ui/saved_objects/saved_object_registry'; import { DashboardListing, EMPTY_FILTER } from './listing/dashboard_listing'; import { uiModules } from 'ui/modules'; import 'ui/capabilities/route_setup'; +import { npStart } from 'ui/new_platform'; + // load directives import '../../../data/public'; @@ -156,7 +157,7 @@ uiRoutes return savedDashboards.get(id) .then((savedDashboard) => { - recentlyAccessed.add(savedDashboard.getFullPath(), savedDashboard.title, id); + npStart.core.chrome.recentlyAccessed.add(savedDashboard.getFullPath(), savedDashboard.title, id); return savedDashboard; }) .catch((error) => { diff --git a/src/legacy/core_plugins/kibana/public/dashboard/listing/__snapshots__/dashboard_listing.test.js.snap b/src/legacy/core_plugins/kibana/public/dashboard/listing/__snapshots__/dashboard_listing.test.js.snap index 9b819443808c93..89b8e2ac83ec10 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/listing/__snapshots__/dashboard_listing.test.js.snap +++ b/src/legacy/core_plugins/kibana/public/dashboard/listing/__snapshots__/dashboard_listing.test.js.snap @@ -13,7 +13,6 @@ exports[`after fetch hideWriteControls 1`] = ` noItemsFragment={
@@ -106,7 +105,6 @@ exports[`after fetch initialFilter 1`] = `

} - iconColor="subdued" iconType="dashboardApp" title={

@@ -199,7 +197,6 @@ exports[`after fetch renders call to action when no dashboards exist 1`] = `

} - iconColor="subdued" iconType="dashboardApp" title={

@@ -292,7 +289,6 @@ exports[`after fetch renders table rows 1`] = `

} - iconColor="subdued" iconType="dashboardApp" title={

@@ -385,7 +381,6 @@ exports[`after fetch renders warning when listingLimit is exceeded 1`] = `

} - iconColor="subdued" iconType="dashboardApp" title={

@@ -478,7 +473,6 @@ exports[`renders empty page in before initial fetch to avoid flickering 1`] = `

} - iconColor="subdued" iconType="dashboardApp" title={

diff --git a/src/legacy/core_plugins/kibana/public/dashboard/saved_dashboard/saved_dashboard.js b/src/legacy/core_plugins/kibana/public/dashboard/saved_dashboard/saved_dashboard.js index 36a083ef5a39ce..fe9e7b18d50072 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/saved_dashboard/saved_dashboard.js +++ b/src/legacy/core_plugins/kibana/public/dashboard/saved_dashboard/saved_dashboard.js @@ -18,7 +18,6 @@ */ import angular from 'angular'; -import { i18n } from '@kbn/i18n'; import { uiModules } from 'ui/modules'; import { createDashboardEditUrl } from '../dashboard_constants'; import { createLegacyClass } from 'ui/utils/legacy_class'; @@ -50,7 +49,7 @@ module.factory('SavedDashboard', function (Private) { // default values that will get assigned if the doc is new defaults: { - title: i18n.translate('kbn.dashboard.savedDashboard.newDashboardTitle', { defaultMessage: 'New Dashboard' }), + title: '', hits: 0, description: '', panelsJSON: '[]', diff --git a/src/legacy/core_plugins/kibana/public/discover/components/field_chooser/field_chooser.html b/src/legacy/core_plugins/kibana/public/discover/components/field_chooser/field_chooser.html index 2043dc44c147e7..d1a75adac5b82f 100644 --- a/src/legacy/core_plugins/kibana/public/discover/components/field_chooser/field_chooser.html +++ b/src/legacy/core_plugins/kibana/public/discover/components/field_chooser/field_chooser.html @@ -84,7 +84,7 @@ i18n-default-message="Selected fields" >

-
    +
      { if (savedSearchId) { - recentlyAccessed.add( + npStart.core.chrome.recentlyAccessed.add( savedSearch.getFullPath(), savedSearch.title, savedSearchId); diff --git a/src/legacy/core_plugins/kibana/public/discover/directives/__snapshots__/no_results.test.js.snap b/src/legacy/core_plugins/kibana/public/discover/directives/__snapshots__/no_results.test.js.snap index 9f400e54899afd..ed7a4b5d548ed4 100644 --- a/src/legacy/core_plugins/kibana/public/discover/directives/__snapshots__/no_results.test.js.snap +++ b/src/legacy/core_plugins/kibana/public/discover/directives/__snapshots__/no_results.test.js.snap @@ -377,11 +377,11 @@ Array [
      -

      Expand your time range -

      +

      One or more of the indices you’re looking at contains a date field. Your query may not match anything in the current time range, or there may not be any data at all in the currently selected time range. You can try changing the time range to one which contains data.

      diff --git a/src/legacy/core_plugins/kibana/public/discover/directives/no_results.js b/src/legacy/core_plugins/kibana/public/discover/directives/no_results.js index 9f57c49977f5a5..5f6d32681b50e4 100644 --- a/src/legacy/core_plugins/kibana/public/discover/directives/no_results.js +++ b/src/legacy/core_plugins/kibana/public/discover/directives/no_results.js @@ -119,12 +119,12 @@ export class DiscoverNoResults extends Component { -

      +

      -

      +

      - +

      {{screenTitle}}

      + +

      { + $scope.recentlyAccessed = npStart.core.chrome.recentlyAccessed.get().map(item => { item.link = chrome.addBasePath(item.link); return item; }); diff --git a/src/legacy/core_plugins/kibana/public/visualize/editor/editor.html b/src/legacy/core_plugins/kibana/public/visualize/editor/editor.html index 8513deee800e39..aa59b2d0a81c42 100644 --- a/src/legacy/core_plugins/kibana/public/visualize/editor/editor.html +++ b/src/legacy/core_plugins/kibana/public/visualize/editor/editor.html @@ -91,6 +91,16 @@
      +

      +

      { - recentlyAccessed.add( + npStart.core.chrome.recentlyAccessed.add( savedVis.getFullPath(), savedVis.title, savedVis.id); diff --git a/src/legacy/core_plugins/timelion/public/app.js b/src/legacy/core_plugins/timelion/public/app.js index 29e56f77fd837b..a1f4699a1282ad 100644 --- a/src/legacy/core_plugins/timelion/public/app.js +++ b/src/legacy/core_plugins/timelion/public/app.js @@ -26,8 +26,8 @@ import { docTitle } from 'ui/doc_title'; import { SavedObjectRegistryProvider } from 'ui/saved_objects/saved_object_registry'; import { fatalError, toastNotifications } from 'ui/notify'; import { timezoneProvider } from 'ui/vis/lib/timezone'; -import { recentlyAccessed } from 'ui/persisted_log'; import { timefilter } from 'ui/timefilter'; +import { npStart } from 'ui/new_platform'; import { getSavedSheetBreadcrumbs, getCreateBreadcrumbs } from './breadcrumbs'; // import the uiExports that we want to "use" @@ -97,7 +97,7 @@ require('ui/routes') return savedSheets.get($route.current.params.id) .then((savedSheet) => { if ($route.current.params.id) { - recentlyAccessed.add( + npStart.core.chrome.recentlyAccessed.add( savedSheet.getFullPath(), savedSheet.title, savedSheet.id); diff --git a/src/legacy/core_plugins/vis_type_markdown/public/markdown_options.tsx b/src/legacy/core_plugins/vis_type_markdown/public/markdown_options.tsx index 79628afe485312..53a7b1caef2a47 100644 --- a/src/legacy/core_plugins/vis_type_markdown/public/markdown_options.tsx +++ b/src/legacy/core_plugins/vis_type_markdown/public/markdown_options.tsx @@ -46,7 +46,9 @@ function MarkdownOptions({ stateParams, setValue }: VisOptionsProps -

      Markdown

      +

      + +

      diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/filter_ratio.js b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/filter_ratio.js index abbf2dcaafc810..92558559845bea 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/filter_ratio.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/filter_ratio.js @@ -35,7 +35,7 @@ import { EuiFormRow, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import { ES_FIELD_TYPES } from '../../../../../../plugins/data/common'; +import { KBN_FIELD_TYPES } from '../../../../../../plugins/data/common'; import { METRIC_TYPES } from '../../../common/metric_types'; export const FilterRatioAgg = props => { @@ -56,7 +56,7 @@ export const FilterRatioAgg = props => { const model = { ...defaults, ...props.model }; const htmlId = htmlIdGenerator(); - const restrictFields = model.metric_agg === METRIC_TYPES.CARDINALITY ? [] : [ES_FIELD_TYPES.NUMBER]; + const restrictFields = model.metric_agg === METRIC_TYPES.CARDINALITY ? [] : [KBN_FIELD_TYPES.NUMBER]; return ( { const { series, panel, fields } = props; diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/std_agg.js b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/std_agg.js index 9cbb8ffb716f5d..4b8b356f2af486 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/std_agg.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/std_agg.js @@ -33,14 +33,14 @@ import { EuiSpacer, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import { ES_FIELD_TYPES } from '../../../../../../plugins/data/common'; +import { KBN_FIELD_TYPES } from '../../../../../../plugins/data/common'; import { METRIC_TYPES } from '../../../common/metric_types'; export function StandardAgg(props) { const { model, panel, series, fields, uiRestrictions } = props; const handleChange = createChangeHandler(props.onChange, model); const handleSelectChange = createSelectHandler(handleChange); - const restrictFields = model.type === METRIC_TYPES.CARDINALITY ? [] : [ES_FIELD_TYPES.NUMBER]; + const restrictFields = model.type === METRIC_TYPES.CARDINALITY ? [] : [KBN_FIELD_TYPES.NUMBER]; const indexPattern = (series.override_index_pattern && series.series_index_pattern) || panel.index_pattern; diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/std_deviation.js b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/std_deviation.js index 8ccb37adeda46a..c078bac8d7f9c6 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/std_deviation.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/std_deviation.js @@ -36,9 +36,9 @@ import { EuiSpacer, } from '@elastic/eui'; import { injectI18n, FormattedMessage } from '@kbn/i18n/react'; -import { ES_FIELD_TYPES } from '../../../../../../plugins/data/common'; +import { KBN_FIELD_TYPES } from '../../../../../../plugins/data/common'; -const RESTRICT_FIELDS = [ES_FIELD_TYPES.NUMBER]; +const RESTRICT_FIELDS = [KBN_FIELD_TYPES.NUMBER]; const StandardDeviationAggUi = props => { const { series, panel, fields, intl } = props; diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/top_hit.js b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/top_hit.js index 65bec274021ede..1439768b95643d 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/top_hit.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/top_hit.js @@ -35,7 +35,7 @@ import { EuiFormRow, } from '@elastic/eui'; import { injectI18n, FormattedMessage } from '@kbn/i18n/react'; -import { ES_FIELD_TYPES } from '../../../../../../plugins/data/common'; +import { KBN_FIELD_TYPES } from '../../../../../../plugins/data/common'; import { PANEL_TYPES } from '../../../common/panel_types'; const isFieldTypeEnabled = (fieldRestrictions, fieldType) => @@ -44,7 +44,7 @@ const isFieldTypeEnabled = (fieldRestrictions, fieldType) => const getAggWithOptions = (field = {}, fieldTypesRestriction) => { if (isFieldTypeEnabled(fieldTypesRestriction, field.type)) { switch (field.type) { - case ES_FIELD_TYPES.NUMBER: + case KBN_FIELD_TYPES.NUMBER: return [ { label: i18n.translate('visTypeTimeseries.topHit.aggWithOptions.averageLabel', { @@ -71,8 +71,7 @@ const getAggWithOptions = (field = {}, fieldTypesRestriction) => { value: 'sum', }, ]; - case ES_FIELD_TYPES.KEYWORD: - case ES_FIELD_TYPES.STRING: + case KBN_FIELD_TYPES.STRING: return [ { label: i18n.translate('visTypeTimeseries.topHit.aggWithOptions.concatenate', { @@ -102,7 +101,7 @@ const getOrderOptions = () => [ }, ]; -const ORDER_DATE_RESTRICT_FIELDS = [ES_FIELD_TYPES.DATE]; +const ORDER_DATE_RESTRICT_FIELDS = [KBN_FIELD_TYPES.DATE]; const TopHitAggUi = props => { const { fields, series, panel } = props; @@ -120,8 +119,8 @@ const TopHitAggUi = props => { PANEL_TYPES.METRIC, PANEL_TYPES.MARKDOWN, ].includes(panel.type) - ? [ES_FIELD_TYPES.NUMBER, ES_FIELD_TYPES.KEYWORD, ES_FIELD_TYPES.STRING] - : [ES_FIELD_TYPES.NUMBER]; + ? [KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.STRING] + : [KBN_FIELD_TYPES.NUMBER]; const handleChange = createChangeHandler(props.onChange, model); const handleSelectChange = createSelectHandler(handleChange); diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/components/annotations_editor.js b/src/legacy/core_plugins/vis_type_timeseries/public/components/annotations_editor.js index cf3f5c69c8b0ca..4357d4737fbef6 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/components/annotations_editor.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/components/annotations_editor.js @@ -21,7 +21,7 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; import _ from 'lodash'; import { collectionActions } from './lib/collection_actions'; -import { ES_FIELD_TYPES } from '../../../../../plugins/data/public'; +import { KBN_FIELD_TYPES } from '../../../../../plugins/data/public'; import { AddDeleteButtons } from './add_delete_buttons'; import { ColorPicker } from './color_picker'; import { FieldSelect } from './aggs/field_select'; @@ -57,7 +57,7 @@ function newAnnotation() { }; } -const RESTRICT_FIELDS = [ES_FIELD_TYPES.DATE]; +const RESTRICT_FIELDS = [KBN_FIELD_TYPES.DATE]; export class AnnotationsEditor extends Component { constructor(props) { diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/components/index_pattern.js b/src/legacy/core_plugins/vis_type_timeseries/public/components/index_pattern.js index 61f67a1bde3620..d954b0ab93b564 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/components/index_pattern.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/components/index_pattern.js @@ -33,7 +33,7 @@ import { FieldSelect } from './aggs/field_select'; import { createSelectHandler } from './lib/create_select_handler'; import { createTextHandler } from './lib/create_text_handler'; import { YesNo } from './yes_no'; -import { ES_FIELD_TYPES } from '../../../../../plugins/data/public'; +import { KBN_FIELD_TYPES } from '../../../../../plugins/data/public'; import { FormValidationContext } from '../contexts/form_validation_context'; import { isGteInterval, @@ -47,7 +47,7 @@ import { PANEL_TYPES } from '../../common/panel_types'; import { isTimerangeModeEnabled } from '../lib/check_ui_restrictions'; import { VisDataContext } from '../contexts/vis_data_context'; -const RESTRICT_FIELDS = [ES_FIELD_TYPES.DATE]; +const RESTRICT_FIELDS = [KBN_FIELD_TYPES.DATE]; const validateIntervalValue = intervalValue => { const isAutoOrGteInterval = isGteInterval(intervalValue) || isAutoInterval(intervalValue); diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/components/vis_editor.js b/src/legacy/core_plugins/vis_type_timeseries/public/components/vis_editor.js index 389a84babae87b..3497a35f5c99d3 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/components/vis_editor.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/components/vis_editor.js @@ -170,7 +170,7 @@ export class VisEditor extends Component { services={{ appName: APP_NAME, store: localStorage, - autocomplete: npStart.plugins.data.autocomplete, + data: npStart.plugins.data, ...npStart.core, }} > diff --git a/src/legacy/server/kbn_server.d.ts b/src/legacy/server/kbn_server.d.ts index 9c53a61af575b7..49ea6f9e47380b 100644 --- a/src/legacy/server/kbn_server.d.ts +++ b/src/legacy/server/kbn_server.d.ts @@ -39,6 +39,8 @@ import { CallClusterWithRequest, ElasticsearchPlugin } from '../core_plugins/ela import { CapabilitiesModifier } from './capabilities'; import { IndexPatternsServiceFactory } from './index_patterns'; import { Capabilities } from '../../core/public'; +import { IUiSettingsClient } from '../../legacy/ui/ui_settings/ui_settings_service'; +import { UiSettingsServiceFactoryOptions } from '../../legacy/ui/ui_settings/ui_settings_service_factory'; export interface KibanaConfig { get(key: string): T; @@ -77,14 +79,15 @@ declare module 'hapi' { name: string, factoryFn: (request: Request) => Record ) => void; - uiSettingsServiceFactory: (options: any) => any; + uiSettingsServiceFactory: (options?: UiSettingsServiceFactoryOptions) => IUiSettingsClient; + logWithMetadata: (tags: string[], message: string, meta: Record) => void; } interface Request { getSavedObjectsClient(options?: SavedObjectsClientProviderOptions): SavedObjectsClientContract; getBasePath(): string; getDefaultRoute(): Promise; - getUiSettingsService(): any; + getUiSettingsService(): IUiSettingsClient; getCapabilities(): Promise; } diff --git a/src/legacy/server/sass/build.js b/src/legacy/server/sass/build.js index f33acbd1abd74c..db1b26e1028348 100644 --- a/src/legacy/server/sass/build.js +++ b/src/legacy/server/sass/build.js @@ -24,7 +24,6 @@ import sass from 'node-sass'; import autoprefixer from 'autoprefixer'; import postcss from 'postcss'; import postcssUrl from 'postcss-url'; -import mkdirp from 'mkdirp'; import chalk from 'chalk'; import isPathInside from 'is-path-inside'; import { PUBLIC_PATH_PLACEHOLDER } from '../../../optimize/public_path_placeholder'; @@ -33,7 +32,7 @@ const renderSass = promisify(sass.render); const writeFile = promisify(fs.writeFile); const exists = promisify(fs.exists); const copyFile = promisify(fs.copyFile); -const mkdirpAsync = promisify(mkdirp); +const mkdirAsync = promisify(fs.mkdir); const UI_ASSETS_DIR = resolve(__dirname, '../../ui/public/assets'); const DARK_THEME_IMPORTER = (url) => { @@ -165,7 +164,7 @@ export class Build { })); // write css - await mkdirpAsync(this.targetDir); + await mkdirAsync(this.targetDir, { recursive: true }); await writeFile(this.targetPath, prefixed.css); // copy non-shared urlAssets @@ -174,7 +173,7 @@ export class Build { return; } - await mkdirpAsync(dirname(asset.copyTo)); + await mkdirAsync(dirname(asset.copyTo), { recursive: true }); await copyFile(asset.path, asset.copyTo); })); diff --git a/src/legacy/ui/public/agg_types/buckets/filters.js b/src/legacy/ui/public/agg_types/buckets/filters.js index 9b7795d8fd9fa0..19be75ccf8c1e2 100644 --- a/src/legacy/ui/public/agg_types/buckets/filters.js +++ b/src/legacy/ui/public/agg_types/buckets/filters.js @@ -24,6 +24,7 @@ import { BucketAggType } from './_bucket_agg_type'; import { createFilterFilters } from './create_filter/filters'; import { FiltersParamEditor } from '../../vis/editors/default/controls/filters'; import { i18n } from '@kbn/i18n'; +import { Storage } from 'ui/storage'; import chrome from 'ui/chrome'; import { buildEsQuery } from '@kbn/es-query'; @@ -31,6 +32,7 @@ import { setup as data } from '../../../../core_plugins/data/public/legacy'; const { getQueryLog } = data.query.helpers; const config = chrome.getUiSettingsClient(); +const storage = new Storage(window.localStorage); export const filtersBucketAgg = new BucketAggType({ name: 'filters', @@ -50,7 +52,7 @@ export const filtersBucketAgg = new BucketAggType({ if (!_.size(inFilters)) return; inFilters.forEach((filter) => { - const persistedLog = getQueryLog(config, 'filtersAgg', filter.input.language); + const persistedLog = getQueryLog(config, storage, 'filtersAgg', filter.input.language); persistedLog.add(filter.input.query); }); diff --git a/src/legacy/ui/public/chrome/directives/kbn_chrome.html b/src/legacy/ui/public/chrome/directives/kbn_chrome.html index 541082e68de58d..ced89287d310f2 100644 --- a/src/legacy/ui/public/chrome/directives/kbn_chrome.html +++ b/src/legacy/ui/public/chrome/directives/kbn_chrome.html @@ -1,9 +1,9 @@
      -
      + >
      diff --git a/src/legacy/ui/public/persisted_log/directive.js b/src/legacy/ui/public/courier/search_source/filter_docvalue_fields.js similarity index 76% rename from src/legacy/ui/public/persisted_log/directive.js rename to src/legacy/ui/public/courier/search_source/filter_docvalue_fields.js index 29f2f93093aeb4..cd726709b4b5c2 100644 --- a/src/legacy/ui/public/persisted_log/directive.js +++ b/src/legacy/ui/public/courier/search_source/filter_docvalue_fields.js @@ -17,10 +17,9 @@ * under the License. */ -import { uiModules } from '../modules'; -import { PersistedLog } from './persisted_log'; - -uiModules.get('kibana/persisted_log') - .factory('PersistedLog', function () { - return PersistedLog; +export function filterDocvalueFields(docvalueFields, fields) { + return docvalueFields.filter(docValue => { + const docvalueFieldName = typeof docValue === 'string' ? docValue : docValue.field; + return fields.includes(docvalueFieldName); }); +} diff --git a/src/legacy/ui/public/courier/search_source/filter_docvalue_fields.test.js b/src/legacy/ui/public/courier/search_source/filter_docvalue_fields.test.js new file mode 100644 index 00000000000000..b220361e33b3ba --- /dev/null +++ b/src/legacy/ui/public/courier/search_source/filter_docvalue_fields.test.js @@ -0,0 +1,33 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { filterDocvalueFields } from './filter_docvalue_fields'; + +test('Should exclude docvalue_fields that are not contained in fields', () => { + const docvalueFields = [ + 'my_ip_field', + { field: 'my_keyword_field' }, + { field: 'my_date_field', 'format': 'epoch_millis' } + ]; + const out = filterDocvalueFields(docvalueFields, ['my_ip_field', 'my_keyword_field']); + expect(out).toEqual([ + 'my_ip_field', + { field: 'my_keyword_field' }, + ]); +}); diff --git a/src/legacy/ui/public/courier/search_source/search_source.js b/src/legacy/ui/public/courier/search_source/search_source.js index 671bcf0be74b31..2ff4b6d574ca32 100644 --- a/src/legacy/ui/public/courier/search_source/search_source.js +++ b/src/legacy/ui/public/courier/search_source/search_source.js @@ -81,6 +81,7 @@ import { searchRequestQueue } from '../search_request_queue'; import { FetchSoonProvider } from '../fetch'; import { FieldWildcardProvider } from '../../field_wildcard'; import { getHighlightRequest } from '../../../../../plugins/data/common/field_formats'; +import { filterDocvalueFields } from './filter_docvalue_fields'; const FIELDS = [ 'type', @@ -551,12 +552,13 @@ export function SearchSourceProvider(Promise, Private, config) { flatData.body = flatData.body || {}; const computedFields = flatData.index.getComputedFields(); + flatData.body.stored_fields = computedFields.storedFields; flatData.body.script_fields = flatData.body.script_fields || {}; - flatData.body.docvalue_fields = flatData.body.docvalue_fields || []; - _.extend(flatData.body.script_fields, computedFields.scriptFields); - flatData.body.docvalue_fields = _.union(flatData.body.docvalue_fields, computedFields.docvalueFields); + + const defaultDocValueFields = computedFields.docvalueFields ? computedFields.docvalueFields : []; + flatData.body.docvalue_fields = flatData.body.docvalue_fields || defaultDocValueFields; if (flatData.body._source) { // exclude source fields for this index pattern specified by the user @@ -570,7 +572,7 @@ export function SearchSourceProvider(Promise, Private, config) { const fields = flatData.fields; if (fields) { // filter out the docvalue_fields, and script_fields to only include those that we are concerned with - flatData.body.docvalue_fields = _.intersection(flatData.body.docvalue_fields, fields); + flatData.body.docvalue_fields = filterDocvalueFields(flatData.body.docvalue_fields, fields); flatData.body.script_fields = _.pick(flatData.body.script_fields, fields); // request the remaining fields from both stored_fields and _source diff --git a/src/legacy/ui/public/directives/field_name/__snapshots__/field_name_icon.test.tsx.snap b/src/legacy/ui/public/directives/field_name/__snapshots__/field_name_icon.test.tsx.snap deleted file mode 100644 index ef231622f7cd89..00000000000000 --- a/src/legacy/ui/public/directives/field_name/__snapshots__/field_name_icon.test.tsx.snap +++ /dev/null @@ -1,27 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`FieldNameIcon renders a blackwhite icon for a string 1`] = ` - -`; - -exports[`FieldNameIcon renders a colored icon for a number 1`] = ` - -`; - -exports[`FieldNameIcon renders an icon for an unknown type 1`] = ` - -`; diff --git a/src/legacy/ui/public/directives/field_name/field_name.tsx b/src/legacy/ui/public/directives/field_name/field_name.tsx index 855caa8d0b96e8..0340ce9cb5d1b2 100644 --- a/src/legacy/ui/public/directives/field_name/field_name.tsx +++ b/src/legacy/ui/public/directives/field_name/field_name.tsx @@ -20,7 +20,7 @@ import React from 'react'; import classNames from 'classnames'; // @ts-ignore import { shortenDottedString } from '../../../../core_plugins/kibana/common/utils/shorten_dotted_string'; -import { FieldNameIcon } from './field_name_icon'; +import { FieldIcon } from '../../../../../../src/plugins/kibana_react/public'; import { getFieldTypeName } from './field_type_name'; // property field is provided at discover's field chooser @@ -53,7 +53,7 @@ export function FieldName({ field, fieldName, fieldType, useShortDots }: Props) return ( - + {displayName} ); diff --git a/src/legacy/ui/public/new_platform/new_platform.karma_mock.js b/src/legacy/ui/public/new_platform/new_platform.karma_mock.js index 29868dc9767dc4..bbfa8bd329c657 100644 --- a/src/legacy/ui/public/new_platform/new_platform.karma_mock.js +++ b/src/legacy/ui/public/new_platform/new_platform.karma_mock.js @@ -65,7 +65,9 @@ export const npStart = { registerRenderer: sinon.fake(), registerType: sinon.fake(), }, - data: {}, + data: { + getSuggestions: sinon.fake(), + }, inspector: { isAvailable: () => false, open: () => ({ diff --git a/src/legacy/ui/public/persisted_log/index.ts b/src/legacy/ui/public/new_platform/new_platform.test.mocks.ts similarity index 85% rename from src/legacy/ui/public/persisted_log/index.ts rename to src/legacy/ui/public/new_platform/new_platform.test.mocks.ts index 8821b4d7079a0a..e660ad1f55840a 100644 --- a/src/legacy/ui/public/persisted_log/index.ts +++ b/src/legacy/ui/public/new_platform/new_platform.test.mocks.ts @@ -17,8 +17,8 @@ * under the License. */ -// @ts-ignore -import './directive'; +export const setRootControllerMock = jest.fn(); -export { PersistedLog } from './persisted_log'; -export { recentlyAccessed } from './recently_accessed'; +jest.doMock('ui/chrome', () => ({ + setRootController: setRootControllerMock, +})); diff --git a/src/legacy/ui/public/new_platform/new_platform.test.ts b/src/legacy/ui/public/new_platform/new_platform.test.ts new file mode 100644 index 00000000000000..cbdaccd65f94bb --- /dev/null +++ b/src/legacy/ui/public/new_platform/new_platform.test.ts @@ -0,0 +1,83 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { setRootControllerMock } from './new_platform.test.mocks'; +import { legacyAppRegister, __reset__ } from './new_platform'; + +describe('ui/new_platform', () => { + describe('legacyAppRegister', () => { + beforeEach(() => { + setRootControllerMock.mockReset(); + __reset__(); + }); + + const registerApp = () => { + const unmountMock = jest.fn(); + const mountMock = jest.fn(() => unmountMock); + legacyAppRegister({ + id: 'test', + title: 'Test', + mount: mountMock, + }); + return { mountMock, unmountMock }; + }; + + test('sets ui/chrome root controller', () => { + registerApp(); + expect(setRootControllerMock).toHaveBeenCalledWith('test', expect.any(Function)); + }); + + test('throws if called more than once', () => { + registerApp(); + expect(registerApp).toThrowErrorMatchingInlineSnapshot( + `"core.application.register may only be called once for legacy plugins."` + ); + }); + + test('controller calls app.mount when invoked', () => { + const { mountMock } = registerApp(); + const controller = setRootControllerMock.mock.calls[0][1]; + const scopeMock = { $on: jest.fn() }; + const elementMock = [document.createElement('div')]; + + controller(scopeMock, elementMock); + expect(mountMock).toHaveBeenCalledWith(expect.any(Object), { + element: elementMock[0], + appBasePath: '', + }); + }); + + test('controller calls unmount when $scope.$destroy', async () => { + const { unmountMock } = registerApp(); + const controller = setRootControllerMock.mock.calls[0][1]; + const scopeMock = { $on: jest.fn() }; + const elementMock = [document.createElement('div')]; + + controller(scopeMock, elementMock); + // Flush promise queue. Must be done this way because the controller cannot return a Promise without breaking + // angular. + await new Promise(resolve => setTimeout(resolve, 1)); + + const [event, eventHandler] = scopeMock.$on.mock.calls[0]; + expect(event).toEqual('$destroy'); + eventHandler(); + expect(unmountMock).toHaveBeenCalled(); + }); + }); +}); diff --git a/src/legacy/ui/public/new_platform/new_platform.ts b/src/legacy/ui/public/new_platform/new_platform.ts index ed13af591525c4..b86f9cde0125c2 100644 --- a/src/legacy/ui/public/new_platform/new_platform.ts +++ b/src/legacy/ui/public/new_platform/new_platform.ts @@ -16,9 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +import { IScope } from 'angular'; + import { IUiActionsStart, IUiActionsSetup } from 'src/plugins/ui_actions/public'; import { Start as EmbeddableStart, Setup as EmbeddableSetup } from 'src/plugins/embeddable/public'; -import { LegacyCoreSetup, LegacyCoreStart } from '../../../../core/public'; +import { LegacyCoreSetup, LegacyCoreStart, App } from '../../../../core/public'; import { Plugin as DataPlugin } from '../../../../plugins/data/public'; import { Plugin as ExpressionsPlugin } from '../../../../plugins/expressions/public'; import { @@ -63,14 +65,44 @@ export function __reset__() { npSetup.plugins = {} as any; npStart.core = (null as unknown) as LegacyCoreStart; npStart.plugins = {} as any; + legacyAppRegistered = false; } export function __setup__(coreSetup: LegacyCoreSetup, plugins: PluginsSetup) { npSetup.core = coreSetup; npSetup.plugins = plugins; + + // Setup compatibility layer for AppService in legacy platform + npSetup.core.application.register = legacyAppRegister; } export function __start__(coreStart: LegacyCoreStart, plugins: PluginsStart) { npStart.core = coreStart; npStart.plugins = plugins; } + +/** Flag used to ensure `legacyAppRegister` is only called once. */ +let legacyAppRegistered = false; + +/** + * Exported for testing only. Use `npSetup.core.application.register` in legacy apps. + * @internal + */ +export const legacyAppRegister = (app: App) => { + if (legacyAppRegistered) { + throw new Error(`core.application.register may only be called once for legacy plugins.`); + } + legacyAppRegistered = true; + + require('ui/chrome').setRootController(app.id, ($scope: IScope, $element: JQLite) => { + const element = $element[0]; + + // Root controller cannot return a Promise so use an internal async function and call it immediately + (async () => { + const unmount = await app.mount({ core: npStart.core }, { element, appBasePath: '' }); + $scope.$on('$destroy', () => { + unmount(); + }); + })(); + }); +}; diff --git a/src/legacy/ui/public/saved_objects/saved_object.js b/src/legacy/ui/public/saved_objects/saved_object.js index 2da1573d503a9a..cf83e6ef057f8b 100644 --- a/src/legacy/ui/public/saved_objects/saved_object.js +++ b/src/legacy/ui/public/saved_objects/saved_object.js @@ -39,7 +39,7 @@ import { SearchSourceProvider } from '../courier/search_source'; import { findObjectByTitle } from './find_object_by_title'; import { SavedObjectsClientProvider } from './saved_objects_client_provider'; import { migrateLegacyQuery } from '../utils/migrate_legacy_query'; -import { recentlyAccessed } from '../persisted_log'; +import { npStart } from 'ui/new_platform'; import { i18n } from '@kbn/i18n'; /** @@ -512,7 +512,7 @@ export function SavedObjectProvider(Promise, Private, confirmModalPromise, index }) .then(() => { if (this.showInRecentlyAccessed && this.getFullPath) { - recentlyAccessed.add(this.getFullPath(), this.title, this.id); + npStart.core.chrome.recentlyAccessed.add(this.getFullPath(), this.title, this.id); } this.isSaving = false; this.lastSavedTitle = this.title; diff --git a/src/legacy/ui/public/vis/editors/default/components/__snapshots__/agg_group.test.tsx.snap b/src/legacy/ui/public/vis/editors/default/components/__snapshots__/agg_group.test.tsx.snap index 813b7978d26671..29af0887db2b8c 100644 --- a/src/legacy/ui/public/vis/editors/default/components/__snapshots__/agg_group.test.tsx.snap +++ b/src/legacy/ui/public/vis/editors/default/components/__snapshots__/agg_group.test.tsx.snap @@ -10,9 +10,9 @@ exports[`DefaultEditorAgg component should init with the default set of props 1` -
      +

      Metrics -

      +
      -
      {groupNameLabel}
      +

      {groupNameLabel}

      diff --git a/src/legacy/ui/public/vis/editors/default/controls/filter.tsx b/src/legacy/ui/public/vis/editors/default/controls/filter.tsx index cceaf86b5d85ca..2c0a2b6be37f8e 100644 --- a/src/legacy/ui/public/vis/editors/default/controls/filter.tsx +++ b/src/legacy/ui/public/vis/editors/default/controls/filter.tsx @@ -95,7 +95,7 @@ function FilterRow({ services={{ appName: 'filtersAgg', store: localStorage, - autocomplete: npStart.plugins.data.autocomplete, + data: npStart.plugins.data, ...npStart.core, }} > diff --git a/src/legacy/ui/public/vis/editors/default/sidebar.html b/src/legacy/ui/public/vis/editors/default/sidebar.html index 0434534bddbfdb..b0a03e461fc1ce 100644 --- a/src/legacy/ui/public/vis/editors/default/sidebar.html +++ b/src/legacy/ui/public/vis/editors/default/sidebar.html @@ -7,7 +7,7 @@ ng-keydown="submitEditorWithKeyboard($event)" > -
      {{ vis.indexPattern.title }} -
      +