diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 547776c4cfe661..82568b47a78098 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -16,7 +16,10 @@ /src/legacy/core_plugins/kibana/public/dev_tools/ @elastic/kibana-app /src/legacy/core_plugins/metrics/ @elastic/kibana-app /src/legacy/core_plugins/vis_type_vislib/ @elastic/kibana-app -/src/plugins/home/ @elastic/kibana-app +# Exclude tutorials folder for now because they are not owned by Kibana app and most will move out soon +/src/plugins/home/public @elastic/kibana-app +/src/plugins/home/server/*.ts @elastic/kibana-app +/src/plugins/home/server/services/ @elastic/kibana-app /src/plugins/kibana_legacy/ @elastic/kibana-app /src/plugins/timelion/ @elastic/kibana-app /src/plugins/dev_tools/ @elastic/kibana-app @@ -45,8 +48,10 @@ # APM /x-pack/legacy/plugins/apm/ @elastic/apm-ui +/x-pack/plugins/apm/ @elastic/apm-ui /x-pack/test/functional/apps/apm/ @elastic/apm-ui /src/legacy/core_plugins/apm_oss/ @elastic/apm-ui +/src/plugins/apm_oss/ @elastic/apm-ui # Beats /x-pack/legacy/plugins/beats_management/ @elastic/beats @@ -153,4 +158,4 @@ /x-pack/legacy/plugins/rollup/ @elastic/es-ui /x-pack/plugins/searchprofiler/ @elastic/es-ui /x-pack/legacy/plugins/snapshot_restore/ @elastic/es-ui -/x-pack/legacy/plugins/watcher/ @elastic/es-ui +/x-pack/plugins/watcher/ @elastic/es-ui diff --git a/docs/development/core/public/kibana-plugin-public.doclinksstart.links.md b/docs/development/core/public/kibana-plugin-public.doclinksstart.links.md index 9e662c543eb56d..2a21f00c57461a 100644 --- a/docs/development/core/public/kibana-plugin-public.doclinksstart.links.md +++ b/docs/development/core/public/kibana-plugin-public.doclinksstart.links.md @@ -91,5 +91,6 @@ readonly links: { readonly date: { readonly dateMath: string; }; + readonly management: Record; }; ``` diff --git a/docs/development/core/public/kibana-plugin-public.doclinksstart.md b/docs/development/core/public/kibana-plugin-public.doclinksstart.md index cefac180d88c5b..13c701a8b47dbd 100644 --- a/docs/development/core/public/kibana-plugin-public.doclinksstart.md +++ b/docs/development/core/public/kibana-plugin-public.doclinksstart.md @@ -17,5 +17,5 @@ export interface DocLinksStart | --- | --- | --- | | [DOC\_LINK\_VERSION](./kibana-plugin-public.doclinksstart.doc_link_version.md) | string | | | [ELASTIC\_WEBSITE\_URL](./kibana-plugin-public.doclinksstart.elastic_website_url.md) | string | | -| [links](./kibana-plugin-public.doclinksstart.links.md) | {
readonly filebeat: {
readonly base: string;
readonly installation: string;
readonly configuration: string;
readonly elasticsearchOutput: string;
readonly startup: string;
readonly exportedFields: string;
};
readonly auditbeat: {
readonly base: string;
};
readonly metricbeat: {
readonly base: string;
};
readonly heartbeat: {
readonly base: string;
};
readonly logstash: {
readonly base: string;
};
readonly functionbeat: {
readonly base: string;
};
readonly winlogbeat: {
readonly base: string;
};
readonly aggs: {
readonly date_histogram: string;
readonly date_range: string;
readonly filter: string;
readonly filters: string;
readonly geohash_grid: string;
readonly histogram: string;
readonly ip_range: string;
readonly range: string;
readonly significant_terms: string;
readonly terms: string;
readonly avg: string;
readonly avg_bucket: string;
readonly max_bucket: string;
readonly min_bucket: string;
readonly sum_bucket: string;
readonly cardinality: string;
readonly count: string;
readonly cumulative_sum: string;
readonly derivative: string;
readonly geo_bounds: string;
readonly geo_centroid: string;
readonly max: string;
readonly median: string;
readonly min: string;
readonly moving_avg: string;
readonly percentile_ranks: string;
readonly serial_diff: string;
readonly std_dev: string;
readonly sum: string;
readonly top_hits: string;
};
readonly scriptedFields: {
readonly scriptFields: string;
readonly scriptAggs: string;
readonly painless: string;
readonly painlessApi: string;
readonly painlessSyntax: string;
readonly luceneExpressions: string;
};
readonly indexPatterns: {
readonly loadingData: string;
readonly introduction: string;
};
readonly kibana: string;
readonly siem: {
readonly guide: string;
readonly gettingStarted: string;
};
readonly query: {
readonly luceneQuerySyntax: string;
readonly queryDsl: string;
readonly kueryQuerySyntax: string;
};
readonly date: {
readonly dateMath: string;
};
} | | +| [links](./kibana-plugin-public.doclinksstart.links.md) | {
readonly filebeat: {
readonly base: string;
readonly installation: string;
readonly configuration: string;
readonly elasticsearchOutput: string;
readonly startup: string;
readonly exportedFields: string;
};
readonly auditbeat: {
readonly base: string;
};
readonly metricbeat: {
readonly base: string;
};
readonly heartbeat: {
readonly base: string;
};
readonly logstash: {
readonly base: string;
};
readonly functionbeat: {
readonly base: string;
};
readonly winlogbeat: {
readonly base: string;
};
readonly aggs: {
readonly date_histogram: string;
readonly date_range: string;
readonly filter: string;
readonly filters: string;
readonly geohash_grid: string;
readonly histogram: string;
readonly ip_range: string;
readonly range: string;
readonly significant_terms: string;
readonly terms: string;
readonly avg: string;
readonly avg_bucket: string;
readonly max_bucket: string;
readonly min_bucket: string;
readonly sum_bucket: string;
readonly cardinality: string;
readonly count: string;
readonly cumulative_sum: string;
readonly derivative: string;
readonly geo_bounds: string;
readonly geo_centroid: string;
readonly max: string;
readonly median: string;
readonly min: string;
readonly moving_avg: string;
readonly percentile_ranks: string;
readonly serial_diff: string;
readonly std_dev: string;
readonly sum: string;
readonly top_hits: string;
};
readonly scriptedFields: {
readonly scriptFields: string;
readonly scriptAggs: string;
readonly painless: string;
readonly painlessApi: string;
readonly painlessSyntax: string;
readonly luceneExpressions: string;
};
readonly indexPatterns: {
readonly loadingData: string;
readonly introduction: string;
};
readonly kibana: string;
readonly siem: {
readonly guide: string;
readonly gettingStarted: string;
};
readonly query: {
readonly luceneQuerySyntax: string;
readonly queryDsl: string;
readonly kueryQuerySyntax: string;
};
readonly date: {
readonly dateMath: string;
};
readonly management: Record<string, string>;
} | | diff --git a/docs/development/core/public/kibana-plugin-public.imagevalidation.maxsize.md b/docs/development/core/public/kibana-plugin-public.imagevalidation.maxsize.md new file mode 100644 index 00000000000000..07c4588ff2c8e0 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.imagevalidation.maxsize.md @@ -0,0 +1,14 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [ImageValidation](./kibana-plugin-public.imagevalidation.md) > [maxSize](./kibana-plugin-public.imagevalidation.maxsize.md) + +## ImageValidation.maxSize property + +Signature: + +```typescript +maxSize: { + length: number; + description: string; + }; +``` diff --git a/docs/development/core/public/kibana-plugin-public.imagevalidation.md b/docs/development/core/public/kibana-plugin-public.imagevalidation.md new file mode 100644 index 00000000000000..783f417d0fb4d0 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.imagevalidation.md @@ -0,0 +1,19 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [ImageValidation](./kibana-plugin-public.imagevalidation.md) + +## ImageValidation interface + + +Signature: + +```typescript +export interface ImageValidation +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [maxSize](./kibana-plugin-public.imagevalidation.maxsize.md) | {
length: number;
description: string;
} | | + diff --git a/docs/development/core/public/kibana-plugin-public.md b/docs/development/core/public/kibana-plugin-public.md index 52aca7501e64dd..ad23bfce4f78c2 100644 --- a/docs/development/core/public/kibana-plugin-public.md +++ b/docs/development/core/public/kibana-plugin-public.md @@ -76,6 +76,7 @@ The plugin integrates with the core system via lifecycle events: `setup` | [IHttpInterceptController](./kibana-plugin-public.ihttpinterceptcontroller.md) | Used to halt a request Promise chain in a [HttpInterceptor](./kibana-plugin-public.httpinterceptor.md). | | [IHttpResponse](./kibana-plugin-public.ihttpresponse.md) | | | [IHttpResponseInterceptorOverrides](./kibana-plugin-public.ihttpresponseinterceptoroverrides.md) | Properties that can be returned by HttpInterceptor.request to override the response. | +| [ImageValidation](./kibana-plugin-public.imagevalidation.md) | | | [IUiSettingsClient](./kibana-plugin-public.iuisettingsclient.md) | Client-side client that provides access to the advanced settings stored in elasticsearch. The settings provide control over the behavior of the Kibana application. For example, a user can specify how to display numeric or date fields. Users can adjust the settings via Management UI. [IUiSettingsClient](./kibana-plugin-public.iuisettingsclient.md) | | [LegacyCoreSetup](./kibana-plugin-public.legacycoresetup.md) | Setup interface exposed to the legacy platform via the ui/new_platform module. | | [LegacyCoreStart](./kibana-plugin-public.legacycorestart.md) | Start interface exposed to the legacy platform via the ui/new_platform module. | @@ -110,7 +111,11 @@ The plugin integrates with the core system via lifecycle events: `setup` | [SavedObjectsMigrationVersion](./kibana-plugin-public.savedobjectsmigrationversion.md) | Information about the migrations that have been applied to this SavedObject. When Kibana starts up, KibanaMigrator detects outdated documents and migrates them based on this value. For each migration that has been applied, the plugin's name is used as a key and the latest migration version as the value. | | [SavedObjectsStart](./kibana-plugin-public.savedobjectsstart.md) | | | [SavedObjectsUpdateOptions](./kibana-plugin-public.savedobjectsupdateoptions.md) | | +| [StringValidationRegex](./kibana-plugin-public.stringvalidationregex.md) | StringValidation with regex object | +| [StringValidationRegexString](./kibana-plugin-public.stringvalidationregexstring.md) | StringValidation as regex string | +| [UiSettingsParams](./kibana-plugin-public.uisettingsparams.md) | UiSettings parameters defined by the plugins. | | [UiSettingsState](./kibana-plugin-public.uisettingsstate.md) | | +| [UserProvidedValues](./kibana-plugin-public.userprovidedvalues.md) | Describes the values explicitly set by user. | ## Type Aliases @@ -144,10 +149,12 @@ The plugin integrates with the core system via lifecycle events: `setup` | [SavedObjectAttribute](./kibana-plugin-public.savedobjectattribute.md) | Type definition for a Saved Object attribute value | | [SavedObjectAttributeSingle](./kibana-plugin-public.savedobjectattributesingle.md) | Don't use this type, it's simply a helper type for [SavedObjectAttribute](./kibana-plugin-public.savedobjectattribute.md) | | [SavedObjectsClientContract](./kibana-plugin-public.savedobjectsclientcontract.md) | SavedObjectsClientContract as implemented by the [SavedObjectsClient](./kibana-plugin-public.savedobjectsclient.md) | +| [StringValidation](./kibana-plugin-public.stringvalidation.md) | Allows regex objects or a regex string | | [Toast](./kibana-plugin-public.toast.md) | | | [ToastInput](./kibana-plugin-public.toastinput.md) | Inputs for [IToasts](./kibana-plugin-public.itoasts.md) APIs. | | [ToastInputFields](./kibana-plugin-public.toastinputfields.md) | Allowed fields for [ToastInput](./kibana-plugin-public.toastinput.md). | | [ToastsSetup](./kibana-plugin-public.toastssetup.md) | [IToasts](./kibana-plugin-public.itoasts.md) | | [ToastsStart](./kibana-plugin-public.toastsstart.md) | [IToasts](./kibana-plugin-public.itoasts.md) | +| [UiSettingsType](./kibana-plugin-public.uisettingstype.md) | UI element type to represent the settings. | | [UnmountCallback](./kibana-plugin-public.unmountcallback.md) | A function that will unmount the element previously mounted by the associated [MountPoint](./kibana-plugin-public.mountpoint.md) | diff --git a/docs/development/core/public/kibana-plugin-public.stringvalidation.md b/docs/development/core/public/kibana-plugin-public.stringvalidation.md new file mode 100644 index 00000000000000..bf01e857d262ae --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.stringvalidation.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [StringValidation](./kibana-plugin-public.stringvalidation.md) + +## StringValidation type + +Allows regex objects or a regex string + +Signature: + +```typescript +export declare type StringValidation = StringValidationRegex | StringValidationRegexString; +``` diff --git a/docs/development/core/public/kibana-plugin-public.stringvalidationregex.md b/docs/development/core/public/kibana-plugin-public.stringvalidationregex.md new file mode 100644 index 00000000000000..a60a7bbf742c85 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.stringvalidationregex.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [StringValidationRegex](./kibana-plugin-public.stringvalidationregex.md) + +## StringValidationRegex interface + +StringValidation with regex object + +Signature: + +```typescript +export interface StringValidationRegex +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [message](./kibana-plugin-public.stringvalidationregex.message.md) | string | | +| [regex](./kibana-plugin-public.stringvalidationregex.regex.md) | RegExp | | + diff --git a/docs/development/core/public/kibana-plugin-public.stringvalidationregex.message.md b/docs/development/core/public/kibana-plugin-public.stringvalidationregex.message.md new file mode 100644 index 00000000000000..dae94ae08bde5d --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.stringvalidationregex.message.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [StringValidationRegex](./kibana-plugin-public.stringvalidationregex.md) > [message](./kibana-plugin-public.stringvalidationregex.message.md) + +## StringValidationRegex.message property + +Signature: + +```typescript +message: string; +``` diff --git a/docs/development/core/public/kibana-plugin-public.stringvalidationregex.regex.md b/docs/development/core/public/kibana-plugin-public.stringvalidationregex.regex.md new file mode 100644 index 00000000000000..db7a1fca75aae2 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.stringvalidationregex.regex.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [StringValidationRegex](./kibana-plugin-public.stringvalidationregex.md) > [regex](./kibana-plugin-public.stringvalidationregex.regex.md) + +## StringValidationRegex.regex property + +Signature: + +```typescript +regex: RegExp; +``` diff --git a/docs/development/core/public/kibana-plugin-public.stringvalidationregexstring.md b/docs/development/core/public/kibana-plugin-public.stringvalidationregexstring.md new file mode 100644 index 00000000000000..f64e65122d9d15 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.stringvalidationregexstring.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [StringValidationRegexString](./kibana-plugin-public.stringvalidationregexstring.md) + +## StringValidationRegexString interface + +StringValidation as regex string + +Signature: + +```typescript +export interface StringValidationRegexString +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [message](./kibana-plugin-public.stringvalidationregexstring.message.md) | string | | +| [regexString](./kibana-plugin-public.stringvalidationregexstring.regexstring.md) | string | | + diff --git a/docs/development/core/public/kibana-plugin-public.stringvalidationregexstring.message.md b/docs/development/core/public/kibana-plugin-public.stringvalidationregexstring.message.md new file mode 100644 index 00000000000000..6d844e8dd970ff --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.stringvalidationregexstring.message.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [StringValidationRegexString](./kibana-plugin-public.stringvalidationregexstring.md) > [message](./kibana-plugin-public.stringvalidationregexstring.message.md) + +## StringValidationRegexString.message property + +Signature: + +```typescript +message: string; +``` diff --git a/docs/development/core/public/kibana-plugin-public.stringvalidationregexstring.regexstring.md b/docs/development/core/public/kibana-plugin-public.stringvalidationregexstring.regexstring.md new file mode 100644 index 00000000000000..b779f113f3bbc4 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.stringvalidationregexstring.regexstring.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [StringValidationRegexString](./kibana-plugin-public.stringvalidationregexstring.md) > [regexString](./kibana-plugin-public.stringvalidationregexstring.regexstring.md) + +## StringValidationRegexString.regexString property + +Signature: + +```typescript +regexString: string; +``` diff --git a/docs/development/core/public/kibana-plugin-public.uisettingsparams.category.md b/docs/development/core/public/kibana-plugin-public.uisettingsparams.category.md new file mode 100644 index 00000000000000..859b25cab4be8a --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.uisettingsparams.category.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UiSettingsParams](./kibana-plugin-public.uisettingsparams.md) > [category](./kibana-plugin-public.uisettingsparams.category.md) + +## UiSettingsParams.category property + +used to group the configured setting in the UI + +Signature: + +```typescript +category?: string[]; +``` diff --git a/docs/development/core/public/kibana-plugin-public.uisettingsparams.deprecation.md b/docs/development/core/public/kibana-plugin-public.uisettingsparams.deprecation.md new file mode 100644 index 00000000000000..2364d34bdb8a31 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.uisettingsparams.deprecation.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UiSettingsParams](./kibana-plugin-public.uisettingsparams.md) > [deprecation](./kibana-plugin-public.uisettingsparams.deprecation.md) + +## UiSettingsParams.deprecation property + +optional deprecation information. Used to generate a deprecation warning. + +Signature: + +```typescript +deprecation?: DeprecationSettings; +``` diff --git a/docs/development/core/public/kibana-plugin-public.uisettingsparams.description.md b/docs/development/core/public/kibana-plugin-public.uisettingsparams.description.md new file mode 100644 index 00000000000000..2707c0a456d961 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.uisettingsparams.description.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UiSettingsParams](./kibana-plugin-public.uisettingsparams.md) > [description](./kibana-plugin-public.uisettingsparams.description.md) + +## UiSettingsParams.description property + +description provided to a user in UI + +Signature: + +```typescript +description?: string; +``` diff --git a/docs/development/core/public/kibana-plugin-public.uisettingsparams.md b/docs/development/core/public/kibana-plugin-public.uisettingsparams.md new file mode 100644 index 00000000000000..d8a966d3e69bfa --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.uisettingsparams.md @@ -0,0 +1,30 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UiSettingsParams](./kibana-plugin-public.uisettingsparams.md) + +## UiSettingsParams interface + +UiSettings parameters defined by the plugins. + +Signature: + +```typescript +export interface UiSettingsParams +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [category](./kibana-plugin-public.uisettingsparams.category.md) | string[] | used to group the configured setting in the UI | +| [deprecation](./kibana-plugin-public.uisettingsparams.deprecation.md) | DeprecationSettings | optional deprecation information. Used to generate a deprecation warning. | +| [description](./kibana-plugin-public.uisettingsparams.description.md) | string | description provided to a user in UI | +| [name](./kibana-plugin-public.uisettingsparams.name.md) | string | title in the UI | +| [optionLabels](./kibana-plugin-public.uisettingsparams.optionlabels.md) | Record<string, string> | text labels for 'select' type UI element | +| [options](./kibana-plugin-public.uisettingsparams.options.md) | string[] | array of permitted values for this setting | +| [readonly](./kibana-plugin-public.uisettingsparams.readonly.md) | boolean | a flag indicating that value cannot be changed | +| [requiresPageReload](./kibana-plugin-public.uisettingsparams.requirespagereload.md) | boolean | a flag indicating whether new value applying requires page reloading | +| [type](./kibana-plugin-public.uisettingsparams.type.md) | UiSettingsType | defines a type of UI element [UiSettingsType](./kibana-plugin-public.uisettingstype.md) | +| [validation](./kibana-plugin-public.uisettingsparams.validation.md) | ImageValidation | StringValidation | | +| [value](./kibana-plugin-public.uisettingsparams.value.md) | SavedObjectAttribute | default value to fall back to if a user doesn't provide any | + diff --git a/docs/development/core/public/kibana-plugin-public.uisettingsparams.name.md b/docs/development/core/public/kibana-plugin-public.uisettingsparams.name.md new file mode 100644 index 00000000000000..4397c06c02c3d2 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.uisettingsparams.name.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UiSettingsParams](./kibana-plugin-public.uisettingsparams.md) > [name](./kibana-plugin-public.uisettingsparams.name.md) + +## UiSettingsParams.name property + +title in the UI + +Signature: + +```typescript +name?: string; +``` diff --git a/docs/development/core/public/kibana-plugin-public.uisettingsparams.optionlabels.md b/docs/development/core/public/kibana-plugin-public.uisettingsparams.optionlabels.md new file mode 100644 index 00000000000000..e6e320ae8b09f6 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.uisettingsparams.optionlabels.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UiSettingsParams](./kibana-plugin-public.uisettingsparams.md) > [optionLabels](./kibana-plugin-public.uisettingsparams.optionlabels.md) + +## UiSettingsParams.optionLabels property + +text labels for 'select' type UI element + +Signature: + +```typescript +optionLabels?: Record; +``` diff --git a/docs/development/core/public/kibana-plugin-public.uisettingsparams.options.md b/docs/development/core/public/kibana-plugin-public.uisettingsparams.options.md new file mode 100644 index 00000000000000..e1a637281b44ec --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.uisettingsparams.options.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UiSettingsParams](./kibana-plugin-public.uisettingsparams.md) > [options](./kibana-plugin-public.uisettingsparams.options.md) + +## UiSettingsParams.options property + +array of permitted values for this setting + +Signature: + +```typescript +options?: string[]; +``` diff --git a/docs/development/core/public/kibana-plugin-public.uisettingsparams.readonly.md b/docs/development/core/public/kibana-plugin-public.uisettingsparams.readonly.md new file mode 100644 index 00000000000000..92fcb5eae5232d --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.uisettingsparams.readonly.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UiSettingsParams](./kibana-plugin-public.uisettingsparams.md) > [readonly](./kibana-plugin-public.uisettingsparams.readonly.md) + +## UiSettingsParams.readonly property + +a flag indicating that value cannot be changed + +Signature: + +```typescript +readonly?: boolean; +``` diff --git a/docs/development/core/public/kibana-plugin-public.uisettingsparams.requirespagereload.md b/docs/development/core/public/kibana-plugin-public.uisettingsparams.requirespagereload.md new file mode 100644 index 00000000000000..7d4994208ff1f4 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.uisettingsparams.requirespagereload.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UiSettingsParams](./kibana-plugin-public.uisettingsparams.md) > [requiresPageReload](./kibana-plugin-public.uisettingsparams.requirespagereload.md) + +## UiSettingsParams.requiresPageReload property + +a flag indicating whether new value applying requires page reloading + +Signature: + +```typescript +requiresPageReload?: boolean; +``` diff --git a/docs/development/core/public/kibana-plugin-public.uisettingsparams.type.md b/docs/development/core/public/kibana-plugin-public.uisettingsparams.type.md new file mode 100644 index 00000000000000..e75dbce413ecef --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.uisettingsparams.type.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UiSettingsParams](./kibana-plugin-public.uisettingsparams.md) > [type](./kibana-plugin-public.uisettingsparams.type.md) + +## UiSettingsParams.type property + +defines a type of UI element [UiSettingsType](./kibana-plugin-public.uisettingstype.md) + +Signature: + +```typescript +type?: UiSettingsType; +``` diff --git a/docs/development/core/public/kibana-plugin-public.uisettingsparams.validation.md b/docs/development/core/public/kibana-plugin-public.uisettingsparams.validation.md new file mode 100644 index 00000000000000..21b1de399a332d --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.uisettingsparams.validation.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UiSettingsParams](./kibana-plugin-public.uisettingsparams.md) > [validation](./kibana-plugin-public.uisettingsparams.validation.md) + +## UiSettingsParams.validation property + +Signature: + +```typescript +validation?: ImageValidation | StringValidation; +``` diff --git a/docs/development/core/public/kibana-plugin-public.uisettingsparams.value.md b/docs/development/core/public/kibana-plugin-public.uisettingsparams.value.md new file mode 100644 index 00000000000000..d489b4567ded0a --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.uisettingsparams.value.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UiSettingsParams](./kibana-plugin-public.uisettingsparams.md) > [value](./kibana-plugin-public.uisettingsparams.value.md) + +## UiSettingsParams.value property + +default value to fall back to if a user doesn't provide any + +Signature: + +```typescript +value?: SavedObjectAttribute; +``` diff --git a/docs/development/core/public/kibana-plugin-public.uisettingstype.md b/docs/development/core/public/kibana-plugin-public.uisettingstype.md new file mode 100644 index 00000000000000..cb58152bd093e1 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.uisettingstype.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UiSettingsType](./kibana-plugin-public.uisettingstype.md) + +## UiSettingsType type + +UI element type to represent the settings. + +Signature: + +```typescript +export declare type UiSettingsType = 'undefined' | 'json' | 'markdown' | 'number' | 'select' | 'boolean' | 'string' | 'array' | 'image'; +``` diff --git a/docs/development/core/public/kibana-plugin-public.userprovidedvalues.isoverridden.md b/docs/development/core/public/kibana-plugin-public.userprovidedvalues.isoverridden.md new file mode 100644 index 00000000000000..f62ca61ba91429 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.userprovidedvalues.isoverridden.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UserProvidedValues](./kibana-plugin-public.userprovidedvalues.md) > [isOverridden](./kibana-plugin-public.userprovidedvalues.isoverridden.md) + +## UserProvidedValues.isOverridden property + +Signature: + +```typescript +isOverridden?: boolean; +``` diff --git a/docs/development/core/public/kibana-plugin-public.userprovidedvalues.md b/docs/development/core/public/kibana-plugin-public.userprovidedvalues.md new file mode 100644 index 00000000000000..481bd36dd0ea69 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.userprovidedvalues.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UserProvidedValues](./kibana-plugin-public.userprovidedvalues.md) + +## UserProvidedValues interface + +Describes the values explicitly set by user. + +Signature: + +```typescript +export interface UserProvidedValues +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [isOverridden](./kibana-plugin-public.userprovidedvalues.isoverridden.md) | boolean | | +| [userValue](./kibana-plugin-public.userprovidedvalues.uservalue.md) | T | | + diff --git a/docs/development/core/public/kibana-plugin-public.userprovidedvalues.uservalue.md b/docs/development/core/public/kibana-plugin-public.userprovidedvalues.uservalue.md new file mode 100644 index 00000000000000..132409ad989b1a --- /dev/null +++ b/docs/development/core/public/kibana-plugin-public.userprovidedvalues.uservalue.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-public](./kibana-plugin-public.md) > [UserProvidedValues](./kibana-plugin-public.userprovidedvalues.md) > [userValue](./kibana-plugin-public.userprovidedvalues.uservalue.md) + +## UserProvidedValues.userValue property + +Signature: + +```typescript +userValue?: T; +``` diff --git a/docs/development/core/server/kibana-plugin-server.imagevalidation.md b/docs/development/core/server/kibana-plugin-server.imagevalidation.md index 8d81a7eae19156..0c3e59cc783f95 100644 --- a/docs/development/core/server/kibana-plugin-server.imagevalidation.md +++ b/docs/development/core/server/kibana-plugin-server.imagevalidation.md @@ -4,6 +4,7 @@ ## ImageValidation interface + Signature: ```typescript diff --git a/docs/development/core/server/kibana-plugin-server.md b/docs/development/core/server/kibana-plugin-server.md deleted file mode 100644 index cd469fe6a98c2a..00000000000000 --- a/docs/development/core/server/kibana-plugin-server.md +++ /dev/null @@ -1,224 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) - -## kibana-plugin-server package - -The Kibana Core APIs for server-side plugins. - -A plugin requires a `kibana.json` file at it's root directory that follows [the manfiest schema](./kibana-plugin-server.pluginmanifest.md) to define static plugin information required to load the plugin. - -A plugin's `server/index` file must contain a named import, `plugin`, that implements [PluginInitializer](./kibana-plugin-server.plugininitializer.md) which returns an object that implements [Plugin](./kibana-plugin-server.plugin.md). - -The plugin integrates with the core system via lifecycle events: `setup`, `start`, and `stop`. In each lifecycle method, the plugin will receive the corresponding core services available (either [CoreSetup](./kibana-plugin-server.coresetup.md) or [CoreStart](./kibana-plugin-server.corestart.md)) and any interfaces returned by dependency plugins' lifecycle method. Anything returned by the plugin's lifecycle method will be exposed to downstream dependencies when their corresponding lifecycle methods are invoked. - -## Classes - -| Class | Description | -| --- | --- | -| [BasePath](./kibana-plugin-server.basepath.md) | Access or manipulate the Kibana base path | -| [ClusterClient](./kibana-plugin-server.clusterclient.md) | Represents an Elasticsearch cluster API client created by the platform. It allows to call API on behalf of the internal Kibana user and the actual user that is derived from the request headers (via asScoped(...)).See [ClusterClient](./kibana-plugin-server.clusterclient.md). | -| [CspConfig](./kibana-plugin-server.cspconfig.md) | CSP configuration for use in Kibana. | -| [ElasticsearchErrorHelpers](./kibana-plugin-server.elasticsearcherrorhelpers.md) | Helpers for working with errors returned from the Elasticsearch service.Since the internal data of errors are subject to change, consumers of the Elasticsearch service should always use these helpers to classify errors instead of checking error internals such as body.error.header[WWW-Authenticate] | -| [KibanaRequest](./kibana-plugin-server.kibanarequest.md) | Kibana specific abstraction for an incoming request. | -| [RouteValidationError](./kibana-plugin-server.routevalidationerror.md) | Error to return when the validation is not successful. | -| [SavedObjectsClient](./kibana-plugin-server.savedobjectsclient.md) | | -| [SavedObjectsErrorHelpers](./kibana-plugin-server.savedobjectserrorhelpers.md) | | -| [SavedObjectsRepository](./kibana-plugin-server.savedobjectsrepository.md) | | -| [ScopedClusterClient](./kibana-plugin-server.scopedclusterclient.md) | Serves the same purpose as "normal" ClusterClient but exposes additional callAsCurrentUser method that doesn't use credentials of the Kibana internal user (as callAsInternalUser does) to request Elasticsearch API, but rather passes HTTP headers extracted from the current user request to the API.See [ScopedClusterClient](./kibana-plugin-server.scopedclusterclient.md). | - -## Enumerations - -| Enumeration | Description | -| --- | --- | -| [AuthResultType](./kibana-plugin-server.authresulttype.md) | | -| [AuthStatus](./kibana-plugin-server.authstatus.md) | Status indicating an outcome of the authentication. | - -## Interfaces - -| Interface | Description | -| --- | --- | -| [APICaller](./kibana-plugin-server.apicaller.md) | | -| [AssistanceAPIResponse](./kibana-plugin-server.assistanceapiresponse.md) | | -| [AssistantAPIClientParams](./kibana-plugin-server.assistantapiclientparams.md) | | -| [Authenticated](./kibana-plugin-server.authenticated.md) | | -| [AuthResultParams](./kibana-plugin-server.authresultparams.md) | Result of an incoming request authentication. | -| [AuthToolkit](./kibana-plugin-server.authtoolkit.md) | A tool set defining an outcome of Auth interceptor for incoming request. | -| [CallAPIOptions](./kibana-plugin-server.callapioptions.md) | The set of options that defines how API call should be made and result be processed. | -| [Capabilities](./kibana-plugin-server.capabilities.md) | The read-only set of capabilities available for the current UI session. Capabilities are simple key-value pairs of (string, boolean), where the string denotes the capability ID, and the boolean is a flag indicating if the capability is enabled or disabled. | -| [CapabilitiesSetup](./kibana-plugin-server.capabilitiessetup.md) | APIs to manage the [Capabilities](./kibana-plugin-server.capabilities.md) that will be used by the application.Plugins relying on capabilities to toggle some of their features should register them during the setup phase using the registerProvider method.Plugins having the responsibility to restrict capabilities depending on a given context should register their capabilities switcher using the registerSwitcher method.Refers to the methods documentation for complete description and examples. | -| [CapabilitiesStart](./kibana-plugin-server.capabilitiesstart.md) | APIs to access the application [Capabilities](./kibana-plugin-server.capabilities.md). | -| [ConfigDeprecationFactory](./kibana-plugin-server.configdeprecationfactory.md) | Provides helpers to generates the most commonly used [ConfigDeprecation](./kibana-plugin-server.configdeprecation.md) when invoking a [ConfigDeprecationProvider](./kibana-plugin-server.configdeprecationprovider.md).See methods documentation for more detailed examples. | -| [ContextSetup](./kibana-plugin-server.contextsetup.md) | An object that handles registration of context providers and configuring handlers with context. | -| [CoreSetup](./kibana-plugin-server.coresetup.md) | Context passed to the plugins setup method. | -| [CoreStart](./kibana-plugin-server.corestart.md) | Context passed to the plugins start method. | -| [CustomHttpResponseOptions](./kibana-plugin-server.customhttpresponseoptions.md) | HTTP response parameters for a response with adjustable status code. | -| [DeprecationAPIClientParams](./kibana-plugin-server.deprecationapiclientparams.md) | | -| [DeprecationAPIResponse](./kibana-plugin-server.deprecationapiresponse.md) | | -| [DeprecationInfo](./kibana-plugin-server.deprecationinfo.md) | | -| [DeprecationSettings](./kibana-plugin-server.deprecationsettings.md) | UiSettings deprecation field options. | -| [DiscoveredPlugin](./kibana-plugin-server.discoveredplugin.md) | Small container object used to expose information about discovered plugins that may or may not have been started. | -| [ElasticsearchError](./kibana-plugin-server.elasticsearcherror.md) | | -| [ElasticsearchServiceSetup](./kibana-plugin-server.elasticsearchservicesetup.md) | | -| [EnvironmentMode](./kibana-plugin-server.environmentmode.md) | | -| [ErrorHttpResponseOptions](./kibana-plugin-server.errorhttpresponseoptions.md) | HTTP response parameters | -| [FakeRequest](./kibana-plugin-server.fakerequest.md) | Fake request object created manually by Kibana plugins. | -| [HttpResponseOptions](./kibana-plugin-server.httpresponseoptions.md) | HTTP response parameters | -| [HttpServiceSetup](./kibana-plugin-server.httpservicesetup.md) | Kibana HTTP Service provides own abstraction for work with HTTP stack. Plugins don't have direct access to hapi server and its primitives anymore. Moreover, plugins shouldn't rely on the fact that HTTP Service uses one or another library under the hood. This gives the platform flexibility to upgrade or changing our internal HTTP stack without breaking plugins. If the HTTP Service lacks functionality you need, we are happy to discuss and support your needs. | -| [HttpServiceStart](./kibana-plugin-server.httpservicestart.md) | | -| [IContextContainer](./kibana-plugin-server.icontextcontainer.md) | An object that handles registration of context providers and configuring handlers with context. | -| [ICspConfig](./kibana-plugin-server.icspconfig.md) | CSP configuration for use in Kibana. | -| [IKibanaResponse](./kibana-plugin-server.ikibanaresponse.md) | A response data object, expected to returned as a result of [RequestHandler](./kibana-plugin-server.requesthandler.md) execution | -| [IKibanaSocket](./kibana-plugin-server.ikibanasocket.md) | A tiny abstraction for TCP socket. | -| [ImageValidation](./kibana-plugin-server.imagevalidation.md) | | -| [IndexSettingsDeprecationInfo](./kibana-plugin-server.indexsettingsdeprecationinfo.md) | | -| [IRenderOptions](./kibana-plugin-server.irenderoptions.md) | | -| [IRouter](./kibana-plugin-server.irouter.md) | Registers route handlers for specified resource path and method. See [RouteConfig](./kibana-plugin-server.routeconfig.md) and [RequestHandler](./kibana-plugin-server.requesthandler.md) for more information about arguments to route registrations. | -| [IScopedRenderingClient](./kibana-plugin-server.iscopedrenderingclient.md) | | -| [IUiSettingsClient](./kibana-plugin-server.iuisettingsclient.md) | Server-side client that provides access to the advanced settings stored in elasticsearch. The settings provide control over the behavior of the Kibana application. For example, a user can specify how to display numeric or date fields. Users can adjust the settings via Management UI. | -| [KibanaRequestEvents](./kibana-plugin-server.kibanarequestevents.md) | Request events. | -| [KibanaRequestRoute](./kibana-plugin-server.kibanarequestroute.md) | Request specific route information exposed to a handler. | -| [LegacyRequest](./kibana-plugin-server.legacyrequest.md) | | -| [LegacyServiceSetupDeps](./kibana-plugin-server.legacyservicesetupdeps.md) | | -| [LegacyServiceStartDeps](./kibana-plugin-server.legacyservicestartdeps.md) | | -| [Logger](./kibana-plugin-server.logger.md) | Logger exposes all the necessary methods to log any type of information and this is the interface used by the logging consumers including plugins. | -| [LoggerFactory](./kibana-plugin-server.loggerfactory.md) | The single purpose of LoggerFactory interface is to define a way to retrieve a context-based logger instance. | -| [LogMeta](./kibana-plugin-server.logmeta.md) | Contextual metadata | -| [OnPostAuthToolkit](./kibana-plugin-server.onpostauthtoolkit.md) | A tool set defining an outcome of OnPostAuth interceptor for incoming request. | -| [OnPreAuthToolkit](./kibana-plugin-server.onpreauthtoolkit.md) | A tool set defining an outcome of OnPreAuth interceptor for incoming request. | -| [OnPreResponseExtensions](./kibana-plugin-server.onpreresponseextensions.md) | Additional data to extend a response. | -| [OnPreResponseInfo](./kibana-plugin-server.onpreresponseinfo.md) | Response status code. | -| [OnPreResponseToolkit](./kibana-plugin-server.onpreresponsetoolkit.md) | A tool set defining an outcome of OnPreAuth interceptor for incoming request. | -| [PackageInfo](./kibana-plugin-server.packageinfo.md) | | -| [Plugin](./kibana-plugin-server.plugin.md) | The interface that should be returned by a PluginInitializer. | -| [PluginConfigDescriptor](./kibana-plugin-server.pluginconfigdescriptor.md) | Describes a plugin configuration properties. | -| [PluginInitializerContext](./kibana-plugin-server.plugininitializercontext.md) | Context that's available to plugins during initialization stage. | -| [PluginManifest](./kibana-plugin-server.pluginmanifest.md) | Describes the set of required and optional properties plugin can define in its mandatory JSON manifest file. | -| [PluginsServiceSetup](./kibana-plugin-server.pluginsservicesetup.md) | | -| [PluginsServiceStart](./kibana-plugin-server.pluginsservicestart.md) | | -| [RequestHandlerContext](./kibana-plugin-server.requesthandlercontext.md) | Plugin specific context passed to a route handler.Provides the following clients: - [rendering](./kibana-plugin-server.iscopedrenderingclient.md) - Rendering client which uses the data of the incoming request - [savedObjects.client](./kibana-plugin-server.savedobjectsclient.md) - Saved Objects client which uses the credentials of the incoming request - [elasticsearch.dataClient](./kibana-plugin-server.scopedclusterclient.md) - Elasticsearch data client which uses the credentials of the incoming request - [elasticsearch.adminClient](./kibana-plugin-server.scopedclusterclient.md) - Elasticsearch admin client which uses the credentials of the incoming request - [uiSettings.client](./kibana-plugin-server.iuisettingsclient.md) - uiSettings client which uses the credentials of the incoming request | -| [RouteConfig](./kibana-plugin-server.routeconfig.md) | Route specific configuration. | -| [RouteConfigOptions](./kibana-plugin-server.routeconfigoptions.md) | Additional route options. | -| [RouteConfigOptionsBody](./kibana-plugin-server.routeconfigoptionsbody.md) | Additional body options for a route | -| [RouteValidationResultFactory](./kibana-plugin-server.routevalidationresultfactory.md) | Validation result factory to be used in the custom validation function to return the valid data or validation errorsSee [RouteValidationFunction](./kibana-plugin-server.routevalidationfunction.md). | -| [RouteValidatorConfig](./kibana-plugin-server.routevalidatorconfig.md) | The configuration object to the RouteValidator class. Set params, query and/or body to specify the validation logic to follow for that property. | -| [RouteValidatorOptions](./kibana-plugin-server.routevalidatoroptions.md) | Additional options for the RouteValidator class to modify its default behaviour. | -| [SavedObject](./kibana-plugin-server.savedobject.md) | | -| [SavedObjectAttributes](./kibana-plugin-server.savedobjectattributes.md) | The data for a Saved Object is stored as an object in the attributes property. | -| [SavedObjectReference](./kibana-plugin-server.savedobjectreference.md) | A reference to another saved object. | -| [SavedObjectsBaseOptions](./kibana-plugin-server.savedobjectsbaseoptions.md) | | -| [SavedObjectsBulkCreateObject](./kibana-plugin-server.savedobjectsbulkcreateobject.md) | | -| [SavedObjectsBulkGetObject](./kibana-plugin-server.savedobjectsbulkgetobject.md) | | -| [SavedObjectsBulkResponse](./kibana-plugin-server.savedobjectsbulkresponse.md) | | -| [SavedObjectsBulkUpdateObject](./kibana-plugin-server.savedobjectsbulkupdateobject.md) | | -| [SavedObjectsBulkUpdateOptions](./kibana-plugin-server.savedobjectsbulkupdateoptions.md) | | -| [SavedObjectsBulkUpdateResponse](./kibana-plugin-server.savedobjectsbulkupdateresponse.md) | | -| [SavedObjectsClientProviderOptions](./kibana-plugin-server.savedobjectsclientprovideroptions.md) | Options to control the creation of the Saved Objects Client. | -| [SavedObjectsClientWrapperOptions](./kibana-plugin-server.savedobjectsclientwrapperoptions.md) | Options passed to each SavedObjectsClientWrapperFactory to aid in creating the wrapper instance. | -| [SavedObjectsCreateOptions](./kibana-plugin-server.savedobjectscreateoptions.md) | | -| [SavedObjectsDeleteByNamespaceOptions](./kibana-plugin-server.savedobjectsdeletebynamespaceoptions.md) | | -| [SavedObjectsDeleteOptions](./kibana-plugin-server.savedobjectsdeleteoptions.md) | | -| [SavedObjectsExportOptions](./kibana-plugin-server.savedobjectsexportoptions.md) | Options controlling the export operation. | -| [SavedObjectsExportResultDetails](./kibana-plugin-server.savedobjectsexportresultdetails.md) | Structure of the export result details entry | -| [SavedObjectsFindOptions](./kibana-plugin-server.savedobjectsfindoptions.md) | | -| [SavedObjectsFindResponse](./kibana-plugin-server.savedobjectsfindresponse.md) | Return type of the Saved Objects find() method.\*Note\*: this type is different between the Public and Server Saved Objects clients. | -| [SavedObjectsImportConflictError](./kibana-plugin-server.savedobjectsimportconflicterror.md) | Represents a failure to import due to a conflict. | -| [SavedObjectsImportError](./kibana-plugin-server.savedobjectsimporterror.md) | Represents a failure to import. | -| [SavedObjectsImportMissingReferencesError](./kibana-plugin-server.savedobjectsimportmissingreferenceserror.md) | Represents a failure to import due to missing references. | -| [SavedObjectsImportOptions](./kibana-plugin-server.savedobjectsimportoptions.md) | Options to control the import operation. | -| [SavedObjectsImportResponse](./kibana-plugin-server.savedobjectsimportresponse.md) | The response describing the result of an import. | -| [SavedObjectsImportRetry](./kibana-plugin-server.savedobjectsimportretry.md) | Describes a retry operation for importing a saved object. | -| [SavedObjectsImportUnknownError](./kibana-plugin-server.savedobjectsimportunknownerror.md) | Represents a failure to import due to an unknown reason. | -| [SavedObjectsImportUnsupportedTypeError](./kibana-plugin-server.savedobjectsimportunsupportedtypeerror.md) | Represents a failure to import due to having an unsupported saved object type. | -| [SavedObjectsIncrementCounterOptions](./kibana-plugin-server.savedobjectsincrementcounteroptions.md) | | -| [SavedObjectsMigrationLogger](./kibana-plugin-server.savedobjectsmigrationlogger.md) | | -| [SavedObjectsMigrationVersion](./kibana-plugin-server.savedobjectsmigrationversion.md) | Information about the migrations that have been applied to this SavedObject. When Kibana starts up, KibanaMigrator detects outdated documents and migrates them based on this value. For each migration that has been applied, the plugin's name is used as a key and the latest migration version as the value. | -| [SavedObjectsRawDoc](./kibana-plugin-server.savedobjectsrawdoc.md) | A raw document as represented directly in the saved object index. | -| [SavedObjectsResolveImportErrorsOptions](./kibana-plugin-server.savedobjectsresolveimporterrorsoptions.md) | Options to control the "resolve import" operation. | -| [SavedObjectsServiceSetup](./kibana-plugin-server.savedobjectsservicesetup.md) | Saved Objects is Kibana's data persisentence mechanism allowing plugins to use Elasticsearch for storing and querying state. The SavedObjectsServiceSetup API exposes methods for creating and registering Saved Object client wrappers. | -| [SavedObjectsServiceStart](./kibana-plugin-server.savedobjectsservicestart.md) | Saved Objects is Kibana's data persisentence mechanism allowing plugins to use Elasticsearch for storing and querying state. The SavedObjectsServiceStart API provides a scoped Saved Objects client for interacting with Saved Objects. | -| [SavedObjectsUpdateOptions](./kibana-plugin-server.savedobjectsupdateoptions.md) | | -| [SavedObjectsUpdateResponse](./kibana-plugin-server.savedobjectsupdateresponse.md) | | -| [SessionCookieValidationResult](./kibana-plugin-server.sessioncookievalidationresult.md) | Return type from a function to validate cookie contents. | -| [SessionStorage](./kibana-plugin-server.sessionstorage.md) | Provides an interface to store and retrieve data across requests. | -| [SessionStorageCookieOptions](./kibana-plugin-server.sessionstoragecookieoptions.md) | Configuration used to create HTTP session storage based on top of cookie mechanism. | -| [SessionStorageFactory](./kibana-plugin-server.sessionstoragefactory.md) | SessionStorage factory to bind one to an incoming request | -| [StringValidation](./kibana-plugin-server.stringvalidation.md) | | -| [UiSettingsParams](./kibana-plugin-server.uisettingsparams.md) | UiSettings parameters defined by the plugins. | -| [UiSettingsServiceSetup](./kibana-plugin-server.uisettingsservicesetup.md) | | -| [UiSettingsServiceStart](./kibana-plugin-server.uisettingsservicestart.md) | | -| [UserProvidedValues](./kibana-plugin-server.userprovidedvalues.md) | Describes the values explicitly set by user. | -| [UuidServiceSetup](./kibana-plugin-server.uuidservicesetup.md) | APIs to access the application's instance uuid. | - -## Variables - -| Variable | Description | -| --- | --- | -| [kibanaResponseFactory](./kibana-plugin-server.kibanaresponsefactory.md) | Set of helpers used to create KibanaResponse to form HTTP response on an incoming request. Should be returned as a result of [RequestHandler](./kibana-plugin-server.requesthandler.md) execution. | -| [validBodyOutput](./kibana-plugin-server.validbodyoutput.md) | The set of valid body.output | - -## Type Aliases - -| Type Alias | Description | -| --- | --- | -| [AuthenticationHandler](./kibana-plugin-server.authenticationhandler.md) | See [AuthToolkit](./kibana-plugin-server.authtoolkit.md). | -| [AuthHeaders](./kibana-plugin-server.authheaders.md) | Auth Headers map | -| [AuthResult](./kibana-plugin-server.authresult.md) | | -| [CapabilitiesProvider](./kibana-plugin-server.capabilitiesprovider.md) | See [CapabilitiesSetup](./kibana-plugin-server.capabilitiessetup.md) | -| [CapabilitiesSwitcher](./kibana-plugin-server.capabilitiesswitcher.md) | See [CapabilitiesSetup](./kibana-plugin-server.capabilitiessetup.md) | -| [ConfigDeprecation](./kibana-plugin-server.configdeprecation.md) | Configuration deprecation returned from [ConfigDeprecationProvider](./kibana-plugin-server.configdeprecationprovider.md) that handles a single deprecation from the configuration. | -| [ConfigDeprecationLogger](./kibana-plugin-server.configdeprecationlogger.md) | Logger interface used when invoking a [ConfigDeprecation](./kibana-plugin-server.configdeprecation.md) | -| [ConfigDeprecationProvider](./kibana-plugin-server.configdeprecationprovider.md) | A provider that should returns a list of [ConfigDeprecation](./kibana-plugin-server.configdeprecation.md).See [ConfigDeprecationFactory](./kibana-plugin-server.configdeprecationfactory.md) for more usage examples. | -| [ConfigPath](./kibana-plugin-server.configpath.md) | | -| [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. | -| [IBasePath](./kibana-plugin-server.ibasepath.md) | Access or manipulate the Kibana base path[BasePath](./kibana-plugin-server.basepath.md) | -| [IClusterClient](./kibana-plugin-server.iclusterclient.md) | Represents an Elasticsearch cluster API client created by the platform. It allows to call API on behalf of the internal Kibana user and the actual user that is derived from the request headers (via asScoped(...)).See [ClusterClient](./kibana-plugin-server.clusterclient.md). | -| [IContextProvider](./kibana-plugin-server.icontextprovider.md) | A function that returns a context value for a specific key of given context type. | -| [ICustomClusterClient](./kibana-plugin-server.icustomclusterclient.md) | Represents an Elasticsearch cluster API client created by a plugin. It allows to call API on behalf of the internal Kibana user and the actual user that is derived from the request headers (via asScoped(...)).See [ClusterClient](./kibana-plugin-server.clusterclient.md). | -| [IsAuthenticated](./kibana-plugin-server.isauthenticated.md) | Return authentication status for a request. | -| [ISavedObjectsRepository](./kibana-plugin-server.isavedobjectsrepository.md) | See [SavedObjectsRepository](./kibana-plugin-server.savedobjectsrepository.md) | -| [IScopedClusterClient](./kibana-plugin-server.iscopedclusterclient.md) | Serves the same purpose as "normal" ClusterClient but exposes additional callAsCurrentUser method that doesn't use credentials of the Kibana internal user (as callAsInternalUser does) to request Elasticsearch API, but rather passes HTTP headers extracted from the current user request to the API.See [ScopedClusterClient](./kibana-plugin-server.scopedclusterclient.md). | -| [KibanaRequestRouteOptions](./kibana-plugin-server.kibanarequestrouteoptions.md) | Route options: If 'GET' or 'OPTIONS' method, body options won't be returned. | -| [KibanaResponseFactory](./kibana-plugin-server.kibanaresponsefactory.md) | Creates an object containing request response payload, HTTP headers, error details, and other data transmitted to the client. | -| [KnownHeaders](./kibana-plugin-server.knownheaders.md) | Set of well-known HTTP headers. | -| [LifecycleResponseFactory](./kibana-plugin-server.lifecycleresponsefactory.md) | Creates an object containing redirection or error response with error details, HTTP headers, and other data transmitted to the client. | -| [MIGRATION\_ASSISTANCE\_INDEX\_ACTION](./kibana-plugin-server.migration_assistance_index_action.md) | | -| [MIGRATION\_DEPRECATION\_LEVEL](./kibana-plugin-server.migration_deprecation_level.md) | | -| [MutatingOperationRefreshSetting](./kibana-plugin-server.mutatingoperationrefreshsetting.md) | Elasticsearch Refresh setting for mutating operation | -| [OnPostAuthHandler](./kibana-plugin-server.onpostauthhandler.md) | See [OnPostAuthToolkit](./kibana-plugin-server.onpostauthtoolkit.md). | -| [OnPreAuthHandler](./kibana-plugin-server.onpreauthhandler.md) | See [OnPreAuthToolkit](./kibana-plugin-server.onpreauthtoolkit.md). | -| [OnPreResponseHandler](./kibana-plugin-server.onpreresponsehandler.md) | See [OnPreAuthToolkit](./kibana-plugin-server.onpreauthtoolkit.md). | -| [PluginConfigSchema](./kibana-plugin-server.pluginconfigschema.md) | Dedicated type for plugin configuration schema. | -| [PluginInitializer](./kibana-plugin-server.plugininitializer.md) | The plugin export at the root of a plugin's server directory should conform to this interface. | -| [PluginName](./kibana-plugin-server.pluginname.md) | Dedicated type for plugin name/id that is supposed to make Map/Set/Arrays that use it as a key or value more obvious. | -| [PluginOpaqueId](./kibana-plugin-server.pluginopaqueid.md) | | -| [RecursiveReadonly](./kibana-plugin-server.recursivereadonly.md) | | -| [RedirectResponseOptions](./kibana-plugin-server.redirectresponseoptions.md) | HTTP response parameters for redirection response | -| [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. | -| [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. | -| [RouteContentType](./kibana-plugin-server.routecontenttype.md) | The set of supported parseable Content-Types | -| [RouteMethod](./kibana-plugin-server.routemethod.md) | The set of common HTTP methods supported by Kibana routing. | -| [RouteRegistrar](./kibana-plugin-server.routeregistrar.md) | Route handler common definition | -| [RouteValidationFunction](./kibana-plugin-server.routevalidationfunction.md) | The custom validation function if @kbn/config-schema is not a valid solution for your specific plugin requirements. | -| [RouteValidationSpec](./kibana-plugin-server.routevalidationspec.md) | Allowed property validation options: either @kbn/config-schema validations or custom validation functionsSee [RouteValidationFunction](./kibana-plugin-server.routevalidationfunction.md) for custom validation. | -| [RouteValidatorFullConfig](./kibana-plugin-server.routevalidatorfullconfig.md) | Route validations config and options merged into one object | -| [SavedObjectAttribute](./kibana-plugin-server.savedobjectattribute.md) | Type definition for a Saved Object attribute value | -| [SavedObjectAttributeSingle](./kibana-plugin-server.savedobjectattributesingle.md) | Don't use this type, it's simply a helper type for [SavedObjectAttribute](./kibana-plugin-server.savedobjectattribute.md) | -| [SavedObjectsClientContract](./kibana-plugin-server.savedobjectsclientcontract.md) | Saved Objects is Kibana's data persisentence mechanism allowing plugins to use Elasticsearch for storing plugin state.\#\# SavedObjectsClient errorsSince the SavedObjectsClient has its hands in everything we are a little paranoid about the way we present errors back to to application code. Ideally, all errors will be either:1. Caused by bad implementation (ie. undefined is not a function) and as such unpredictable 2. An error that has been classified and decorated appropriately by the decorators in [SavedObjectsErrorHelpers](./kibana-plugin-server.savedobjectserrorhelpers.md)Type 1 errors are inevitable, but since all expected/handle-able errors should be Type 2 the isXYZError() helpers exposed at SavedObjectsErrorHelpers should be used to understand and manage error responses from the SavedObjectsClient.Type 2 errors are decorated versions of the source error, so if the elasticsearch client threw an error it will be decorated based on its type. That means that rather than looking for error.body.error.type or doing substring checks on error.body.error.reason, just use the helpers to understand the meaning of the error:\`\`\`js if (SavedObjectsErrorHelpers.isNotFoundError(error)) { // handle 404 }if (SavedObjectsErrorHelpers.isNotAuthorizedError(error)) { // 401 handling should be automatic, but in case you wanted to know }// always rethrow the error unless you handle it throw error; \`\`\`\#\#\# 404s from missing indexFrom the perspective of application code and APIs the SavedObjectsClient is a black box that persists objects. One of the internal details that users have no control over is that we use an elasticsearch index for persistance and that index might be missing.At the time of writing we are in the process of transitioning away from the operating assumption that the SavedObjects index is always available. Part of this transition is handling errors resulting from an index missing. These used to trigger a 500 error in most cases, and in others cause 404s with different error messages.From my (Spencer) perspective, a 404 from the SavedObjectsApi is a 404; The object the request/call was targeting could not be found. This is why \#14141 takes special care to ensure that 404 errors are generic and don't distinguish between index missing or document missing.\#\#\# 503s from missing indexUnlike all other methods, create requests are supposed to succeed even when the Kibana index does not exist because it will be automatically created by elasticsearch. When that is not the case it is because Elasticsearch's action.auto_create_index setting prevents it from being created automatically so we throw a special 503 with the intention of informing the user that their Elasticsearch settings need to be updated.See [SavedObjectsClient](./kibana-plugin-server.savedobjectsclient.md) See [SavedObjectsErrorHelpers](./kibana-plugin-server.savedobjectserrorhelpers.md) | -| [SavedObjectsClientFactory](./kibana-plugin-server.savedobjectsclientfactory.md) | Describes the factory used to create instances of the Saved Objects Client. | -| [SavedObjectsClientWrapperFactory](./kibana-plugin-server.savedobjectsclientwrapperfactory.md) | Describes the factory used to create instances of Saved Objects Client Wrappers. | -| [ScopeableRequest](./kibana-plugin-server.scopeablerequest.md) | A user credentials container. It accommodates the necessary auth credentials to impersonate the current user.See [KibanaRequest](./kibana-plugin-server.kibanarequest.md). | -| [SharedGlobalConfig](./kibana-plugin-server.sharedglobalconfig.md) | | -| [UiSettingsType](./kibana-plugin-server.uisettingstype.md) | UI element type to represent the settings. | - diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsclientfactory.md b/docs/development/core/server/kibana-plugin-server.savedobjectsclientfactory.md index 9e307597206800..01c6c6a108b7b0 100644 --- a/docs/development/core/server/kibana-plugin-server.savedobjectsclientfactory.md +++ b/docs/development/core/server/kibana-plugin-server.savedobjectsclientfactory.md @@ -1,15 +1,15 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsClientFactory](./kibana-plugin-server.savedobjectsclientfactory.md) - -## SavedObjectsClientFactory type - -Describes the factory used to create instances of the Saved Objects Client. - -Signature: - -```typescript -export declare type SavedObjectsClientFactory = ({ request, }: { - request: Request; -}) => SavedObjectsClientContract; -``` + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsClientFactory](./kibana-plugin-server.savedobjectsclientfactory.md) + +## SavedObjectsClientFactory type + +Describes the factory used to create instances of the Saved Objects Client. + +Signature: + +```typescript +export declare type SavedObjectsClientFactory = ({ request, }: { + request: KibanaRequest; +}) => SavedObjectsClientContract; +``` diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsclientfactoryprovider.md b/docs/development/core/server/kibana-plugin-server.savedobjectsclientfactoryprovider.md new file mode 100644 index 00000000000000..59617b6be443cd --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.savedobjectsclientfactoryprovider.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsClientFactoryProvider](./kibana-plugin-server.savedobjectsclientfactoryprovider.md) + +## SavedObjectsClientFactoryProvider type + +Provider to invoke to retrieve a [SavedObjectsClientFactory](./kibana-plugin-server.savedobjectsclientfactory.md). + +Signature: + +```typescript +export declare type SavedObjectsClientFactoryProvider = (repositoryFactory: SavedObjectsRepositoryFactory) => SavedObjectsClientFactory; +``` diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsclientwrapperfactory.md b/docs/development/core/server/kibana-plugin-server.savedobjectsclientwrapperfactory.md index 3ef2fac727b018..f429c922099007 100644 --- a/docs/development/core/server/kibana-plugin-server.savedobjectsclientwrapperfactory.md +++ b/docs/development/core/server/kibana-plugin-server.savedobjectsclientwrapperfactory.md @@ -1,13 +1,13 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsClientWrapperFactory](./kibana-plugin-server.savedobjectsclientwrapperfactory.md) - -## SavedObjectsClientWrapperFactory type - -Describes the factory used to create instances of Saved Objects Client Wrappers. - -Signature: - -```typescript -export declare type SavedObjectsClientWrapperFactory = (options: SavedObjectsClientWrapperOptions) => SavedObjectsClientContract; -``` + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsClientWrapperFactory](./kibana-plugin-server.savedobjectsclientwrapperfactory.md) + +## SavedObjectsClientWrapperFactory type + +Describes the factory used to create instances of Saved Objects Client Wrappers. + +Signature: + +```typescript +export declare type SavedObjectsClientWrapperFactory = (options: SavedObjectsClientWrapperOptions) => SavedObjectsClientContract; +``` diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsclientwrapperoptions.md b/docs/development/core/server/kibana-plugin-server.savedobjectsclientwrapperoptions.md index 65e7cfa64c2a66..dfff863898a2b3 100644 --- a/docs/development/core/server/kibana-plugin-server.savedobjectsclientwrapperoptions.md +++ b/docs/development/core/server/kibana-plugin-server.savedobjectsclientwrapperoptions.md @@ -1,21 +1,21 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsClientWrapperOptions](./kibana-plugin-server.savedobjectsclientwrapperoptions.md) - -## SavedObjectsClientWrapperOptions interface - -Options passed to each SavedObjectsClientWrapperFactory to aid in creating the wrapper instance. - -Signature: - -```typescript -export interface SavedObjectsClientWrapperOptions -``` - -## Properties - -| Property | Type | Description | -| --- | --- | --- | -| [client](./kibana-plugin-server.savedobjectsclientwrapperoptions.client.md) | SavedObjectsClientContract | | -| [request](./kibana-plugin-server.savedobjectsclientwrapperoptions.request.md) | Request | | - + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsClientWrapperOptions](./kibana-plugin-server.savedobjectsclientwrapperoptions.md) + +## SavedObjectsClientWrapperOptions interface + +Options passed to each SavedObjectsClientWrapperFactory to aid in creating the wrapper instance. + +Signature: + +```typescript +export interface SavedObjectsClientWrapperOptions +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [client](./kibana-plugin-server.savedobjectsclientwrapperoptions.client.md) | SavedObjectsClientContract | | +| [request](./kibana-plugin-server.savedobjectsclientwrapperoptions.request.md) | KibanaRequest | | + diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsclientwrapperoptions.request.md b/docs/development/core/server/kibana-plugin-server.savedobjectsclientwrapperoptions.request.md index 0ff75028612d03..89c7e0ed207ffb 100644 --- a/docs/development/core/server/kibana-plugin-server.savedobjectsclientwrapperoptions.request.md +++ b/docs/development/core/server/kibana-plugin-server.savedobjectsclientwrapperoptions.request.md @@ -1,11 +1,11 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsClientWrapperOptions](./kibana-plugin-server.savedobjectsclientwrapperoptions.md) > [request](./kibana-plugin-server.savedobjectsclientwrapperoptions.request.md) - -## SavedObjectsClientWrapperOptions.request property - -Signature: - -```typescript -request: Request; -``` + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsClientWrapperOptions](./kibana-plugin-server.savedobjectsclientwrapperoptions.md) > [request](./kibana-plugin-server.savedobjectsclientwrapperoptions.request.md) + +## SavedObjectsClientWrapperOptions.request property + +Signature: + +```typescript +request: KibanaRequest; +``` diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsrepositoryfactory.createinternalrepository.md b/docs/development/core/server/kibana-plugin-server.savedobjectsrepositoryfactory.createinternalrepository.md new file mode 100644 index 00000000000000..b808d38793fffc --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.savedobjectsrepositoryfactory.createinternalrepository.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsRepositoryFactory](./kibana-plugin-server.savedobjectsrepositoryfactory.md) > [createInternalRepository](./kibana-plugin-server.savedobjectsrepositoryfactory.createinternalrepository.md) + +## SavedObjectsRepositoryFactory.createInternalRepository property + +Creates a [Saved Objects repository](./kibana-plugin-server.isavedobjectsrepository.md) that uses the internal Kibana user for authenticating with Elasticsearch. + +Signature: + +```typescript +createInternalRepository: (extraTypes?: string[]) => ISavedObjectsRepository; +``` diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsrepositoryfactory.createscopedrepository.md b/docs/development/core/server/kibana-plugin-server.savedobjectsrepositoryfactory.createscopedrepository.md new file mode 100644 index 00000000000000..20322d809dce76 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.savedobjectsrepositoryfactory.createscopedrepository.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsRepositoryFactory](./kibana-plugin-server.savedobjectsrepositoryfactory.md) > [createScopedRepository](./kibana-plugin-server.savedobjectsrepositoryfactory.createscopedrepository.md) + +## SavedObjectsRepositoryFactory.createScopedRepository property + +Creates a [Saved Objects repository](./kibana-plugin-server.isavedobjectsrepository.md) that uses the credentials from the passed in request to authenticate with Elasticsearch. + +Signature: + +```typescript +createScopedRepository: (req: KibanaRequest, extraTypes?: string[]) => ISavedObjectsRepository; +``` diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsrepositoryfactory.md b/docs/development/core/server/kibana-plugin-server.savedobjectsrepositoryfactory.md new file mode 100644 index 00000000000000..fc6c4a516284ad --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.savedobjectsrepositoryfactory.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsRepositoryFactory](./kibana-plugin-server.savedobjectsrepositoryfactory.md) + +## SavedObjectsRepositoryFactory interface + +Factory provided when invoking a [client factory provider](./kibana-plugin-server.savedobjectsclientfactoryprovider.md) See [SavedObjectsServiceSetup.setClientFactoryProvider](./kibana-plugin-server.savedobjectsservicesetup.setclientfactoryprovider.md) + +Signature: + +```typescript +export interface SavedObjectsRepositoryFactory +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [createInternalRepository](./kibana-plugin-server.savedobjectsrepositoryfactory.createinternalrepository.md) | (extraTypes?: string[]) => ISavedObjectsRepository | Creates a [Saved Objects repository](./kibana-plugin-server.isavedobjectsrepository.md) that uses the internal Kibana user for authenticating with Elasticsearch. | +| [createScopedRepository](./kibana-plugin-server.savedobjectsrepositoryfactory.createscopedrepository.md) | (req: KibanaRequest, extraTypes?: string[]) => ISavedObjectsRepository | Creates a [Saved Objects repository](./kibana-plugin-server.isavedobjectsrepository.md) that uses the credentials from the passed in request to authenticate with Elasticsearch. | + diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.addclientwrapper.md b/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.addclientwrapper.md index e787d737ada17e..becff5bd2821e1 100644 --- a/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.addclientwrapper.md +++ b/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.addclientwrapper.md @@ -1,13 +1,13 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsServiceSetup](./kibana-plugin-server.savedobjectsservicesetup.md) > [addClientWrapper](./kibana-plugin-server.savedobjectsservicesetup.addclientwrapper.md) - -## SavedObjectsServiceSetup.addClientWrapper property - -Add a client wrapper with the given priority. - -Signature: - -```typescript -addClientWrapper: (priority: number, id: string, factory: SavedObjectsClientWrapperFactory) => void; -``` + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsServiceSetup](./kibana-plugin-server.savedobjectsservicesetup.md) > [addClientWrapper](./kibana-plugin-server.savedobjectsservicesetup.addclientwrapper.md) + +## SavedObjectsServiceSetup.addClientWrapper property + +Add a [client wrapper factory](./kibana-plugin-server.savedobjectsclientwrapperfactory.md) with the given priority. + +Signature: + +```typescript +addClientWrapper: (priority: number, id: string, factory: SavedObjectsClientWrapperFactory) => void; +``` diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.createinternalrepository.md b/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.createinternalrepository.md deleted file mode 100644 index 492aa1a2453a19..00000000000000 --- a/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.createinternalrepository.md +++ /dev/null @@ -1,18 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsServiceSetup](./kibana-plugin-server.savedobjectsservicesetup.md) > [createInternalRepository](./kibana-plugin-server.savedobjectsservicesetup.createinternalrepository.md) - -## SavedObjectsServiceSetup.createInternalRepository property - -Creates a [Saved Objects repository](./kibana-plugin-server.isavedobjectsrepository.md) that uses the internal Kibana user for authenticating with Elasticsearch. - -Signature: - -```typescript -createInternalRepository: (extraTypes?: string[]) => ISavedObjectsRepository; -``` - -## Remarks - -The repository should only be used for creating and registering a client factory or client wrapper. Using the repository directly for interacting with Saved Objects is an anti-pattern. Use the Saved Objects client from the [SavedObjectsServiceStart\#getScopedClient](./kibana-plugin-server.savedobjectsservicestart.md) method or the [route handler context](./kibana-plugin-server.requesthandlercontext.md) instead. - diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.createscopedrepository.md b/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.createscopedrepository.md deleted file mode 100644 index fc5aa40c21a208..00000000000000 --- a/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.createscopedrepository.md +++ /dev/null @@ -1,18 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsServiceSetup](./kibana-plugin-server.savedobjectsservicesetup.md) > [createScopedRepository](./kibana-plugin-server.savedobjectsservicesetup.createscopedrepository.md) - -## SavedObjectsServiceSetup.createScopedRepository property - -Creates a [Saved Objects repository](./kibana-plugin-server.isavedobjectsrepository.md) that uses the credentials from the passed in request to authenticate with Elasticsearch. - -Signature: - -```typescript -createScopedRepository: (req: KibanaRequest, extraTypes?: string[]) => ISavedObjectsRepository; -``` - -## Remarks - -The repository should only be used for creating and registering a client factory or client wrapper. Using the repository directly for interacting with Saved Objects is an anti-pattern. Use the Saved Objects client from the [SavedObjectsServiceStart\#getScopedClient](./kibana-plugin-server.savedobjectsservicestart.md) method or the [route handler context](./kibana-plugin-server.requesthandlercontext.md) instead. - diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.md b/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.md index 95bd817a43da68..64fb1f4a5f6389 100644 --- a/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.md +++ b/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.md @@ -1,35 +1,33 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsServiceSetup](./kibana-plugin-server.savedobjectsservicesetup.md) - -## SavedObjectsServiceSetup interface - -Saved Objects is Kibana's data persisentence mechanism allowing plugins to use Elasticsearch for storing and querying state. The SavedObjectsServiceSetup API exposes methods for creating and registering Saved Object client wrappers. - -Signature: - -```typescript -export interface SavedObjectsServiceSetup -``` - -## Remarks - -Note: The Saved Object setup API's should only be used for creating and registering client wrappers. Constructing a Saved Objects client or repository for use within your own plugin won't have any of the registered wrappers applied and is considered an anti-pattern. Use the Saved Objects client from the [SavedObjectsServiceStart\#getScopedClient](./kibana-plugin-server.savedobjectsservicestart.md) method or the [route handler context](./kibana-plugin-server.requesthandlercontext.md) instead. - -When plugins access the Saved Objects client, a new client is created using the factory provided to `setClientFactory` and wrapped by all wrappers registered through `addClientWrapper`. To create a factory or wrapper, plugins will have to construct a Saved Objects client. First create a repository by calling `scopedRepository` or `internalRepository` and then use this repository as the argument to the [SavedObjectsClient](./kibana-plugin-server.savedobjectsclient.md) constructor. - -## Example - -import {SavedObjectsClient, CoreSetup} from 'src/core/server'; - -export class Plugin() { setup: (core: CoreSetup) => { core.savedObjects.setClientFactory(({request: KibanaRequest}) => { return new SavedObjectsClient(core.savedObjects.scopedRepository(request)); }) } } - -## Properties - -| Property | Type | Description | -| --- | --- | --- | -| [addClientWrapper](./kibana-plugin-server.savedobjectsservicesetup.addclientwrapper.md) | (priority: number, id: string, factory: SavedObjectsClientWrapperFactory<KibanaRequest>) => void | Add a client wrapper with the given priority. | -| [createInternalRepository](./kibana-plugin-server.savedobjectsservicesetup.createinternalrepository.md) | (extraTypes?: string[]) => ISavedObjectsRepository | Creates a [Saved Objects repository](./kibana-plugin-server.isavedobjectsrepository.md) that uses the internal Kibana user for authenticating with Elasticsearch. | -| [createScopedRepository](./kibana-plugin-server.savedobjectsservicesetup.createscopedrepository.md) | (req: KibanaRequest, extraTypes?: string[]) => ISavedObjectsRepository | Creates a [Saved Objects repository](./kibana-plugin-server.isavedobjectsrepository.md) that uses the credentials from the passed in request to authenticate with Elasticsearch. | -| [setClientFactory](./kibana-plugin-server.savedobjectsservicesetup.setclientfactory.md) | (customClientFactory: SavedObjectsClientFactory<KibanaRequest>) => void | Set a default factory for creating Saved Objects clients. Only one client factory can be set, subsequent calls to this method will fail. | - + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsServiceSetup](./kibana-plugin-server.savedobjectsservicesetup.md) + +## SavedObjectsServiceSetup interface + +Saved Objects is Kibana's data persistence mechanism allowing plugins to use Elasticsearch for storing and querying state. The SavedObjectsServiceSetup API exposes methods for creating and registering Saved Object client wrappers. + +Signature: + +```typescript +export interface SavedObjectsServiceSetup +``` + +## Remarks + +Note: The Saved Object setup API's should only be used for creating and registering client wrappers. Constructing a Saved Objects client or repository for use within your own plugin won't have any of the registered wrappers applied and is considered an anti-pattern. Use the Saved Objects client from the [SavedObjectsServiceStart\#getScopedClient](./kibana-plugin-server.savedobjectsservicestart.md) method or the [route handler context](./kibana-plugin-server.requesthandlercontext.md) instead. + +When plugins access the Saved Objects client, a new client is created using the factory provided to `setClientFactory` and wrapped by all wrappers registered through `addClientWrapper`. To create a factory or wrapper, plugins will have to construct a Saved Objects client. First create a repository by calling `scopedRepository` or `internalRepository` and then use this repository as the argument to the [SavedObjectsClient](./kibana-plugin-server.savedobjectsclient.md) constructor. + +## Example + +import { SavedObjectsClient, CoreSetup } from 'src/core/server'; + +export class Plugin() { setup: (core: CoreSetup) => { core.savedObjects.setClientFactory(({ request: KibanaRequest }) => { return new SavedObjectsClient(core.savedObjects.scopedRepository(request)); }) } } + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [addClientWrapper](./kibana-plugin-server.savedobjectsservicesetup.addclientwrapper.md) | (priority: number, id: string, factory: SavedObjectsClientWrapperFactory) => void | Add a [client wrapper factory](./kibana-plugin-server.savedobjectsclientwrapperfactory.md) with the given priority. | +| [setClientFactoryProvider](./kibana-plugin-server.savedobjectsservicesetup.setclientfactoryprovider.md) | (clientFactoryProvider: SavedObjectsClientFactoryProvider) => void | Set the default [factory provider](./kibana-plugin-server.savedobjectsclientfactoryprovider.md) for creating Saved Objects clients. Only one provider can be set, subsequent calls to this method will fail. | + diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.setclientfactory.md b/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.setclientfactory.md deleted file mode 100644 index 544e0b9d5fa736..00000000000000 --- a/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.setclientfactory.md +++ /dev/null @@ -1,13 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsServiceSetup](./kibana-plugin-server.savedobjectsservicesetup.md) > [setClientFactory](./kibana-plugin-server.savedobjectsservicesetup.setclientfactory.md) - -## SavedObjectsServiceSetup.setClientFactory property - -Set a default factory for creating Saved Objects clients. Only one client factory can be set, subsequent calls to this method will fail. - -Signature: - -```typescript -setClientFactory: (customClientFactory: SavedObjectsClientFactory) => void; -``` diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.setclientfactoryprovider.md b/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.setclientfactoryprovider.md new file mode 100644 index 00000000000000..ed11255048f19e --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.savedobjectsservicesetup.setclientfactoryprovider.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsServiceSetup](./kibana-plugin-server.savedobjectsservicesetup.md) > [setClientFactoryProvider](./kibana-plugin-server.savedobjectsservicesetup.setclientfactoryprovider.md) + +## SavedObjectsServiceSetup.setClientFactoryProvider property + +Set the default [factory provider](./kibana-plugin-server.savedobjectsclientfactoryprovider.md) for creating Saved Objects clients. Only one provider can be set, subsequent calls to this method will fail. + +Signature: + +```typescript +setClientFactoryProvider: (clientFactoryProvider: SavedObjectsClientFactoryProvider) => void; +``` diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsservicestart.createinternalrepository.md b/docs/development/core/server/kibana-plugin-server.savedobjectsservicestart.createinternalrepository.md new file mode 100644 index 00000000000000..d639a8bc66b7e5 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.savedobjectsservicestart.createinternalrepository.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsServiceStart](./kibana-plugin-server.savedobjectsservicestart.md) > [createInternalRepository](./kibana-plugin-server.savedobjectsservicestart.createinternalrepository.md) + +## SavedObjectsServiceStart.createInternalRepository property + +Creates a [Saved Objects repository](./kibana-plugin-server.isavedobjectsrepository.md) that uses the internal Kibana user for authenticating with Elasticsearch. + +Signature: + +```typescript +createInternalRepository: (extraTypes?: string[]) => ISavedObjectsRepository; +``` diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsservicestart.createscopedrepository.md b/docs/development/core/server/kibana-plugin-server.savedobjectsservicestart.createscopedrepository.md new file mode 100644 index 00000000000000..7683a9e46c51d6 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.savedobjectsservicestart.createscopedrepository.md @@ -0,0 +1,18 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsServiceStart](./kibana-plugin-server.savedobjectsservicestart.md) > [createScopedRepository](./kibana-plugin-server.savedobjectsservicestart.createscopedrepository.md) + +## SavedObjectsServiceStart.createScopedRepository property + +Creates a [Saved Objects repository](./kibana-plugin-server.isavedobjectsrepository.md) that uses the credentials from the passed in request to authenticate with Elasticsearch. + +Signature: + +```typescript +createScopedRepository: (req: KibanaRequest, extraTypes?: string[]) => ISavedObjectsRepository; +``` + +## Remarks + +Prefer using `getScopedClient`. This should only be used when using methods not exposed on [SavedObjectsClientContract](./kibana-plugin-server.savedobjectsclientcontract.md) + diff --git a/docs/development/core/server/kibana-plugin-server.savedobjectsservicestart.md b/docs/development/core/server/kibana-plugin-server.savedobjectsservicestart.md index 5a869b3b6c1cbc..cf2b4f57a74612 100644 --- a/docs/development/core/server/kibana-plugin-server.savedobjectsservicestart.md +++ b/docs/development/core/server/kibana-plugin-server.savedobjectsservicestart.md @@ -1,20 +1,22 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsServiceStart](./kibana-plugin-server.savedobjectsservicestart.md) - -## SavedObjectsServiceStart interface - -Saved Objects is Kibana's data persisentence mechanism allowing plugins to use Elasticsearch for storing and querying state. The SavedObjectsServiceStart API provides a scoped Saved Objects client for interacting with Saved Objects. - -Signature: - -```typescript -export interface SavedObjectsServiceStart -``` - -## Properties - -| Property | Type | Description | -| --- | --- | --- | -| [getScopedClient](./kibana-plugin-server.savedobjectsservicestart.getscopedclient.md) | (req: KibanaRequest, options?: SavedObjectsClientProviderOptions) => SavedObjectsClientContract | Creates a [Saved Objects client](./kibana-plugin-server.savedobjectsclientcontract.md) that uses the credentials from the passed in request to authenticate with Elasticsearch. If other plugins have registered Saved Objects client wrappers, these will be applied to extend the functionality of the client.A client that is already scoped to the incoming request is also exposed from the route handler context see [RequestHandlerContext](./kibana-plugin-server.requesthandlercontext.md). | - + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [SavedObjectsServiceStart](./kibana-plugin-server.savedobjectsservicestart.md) + +## SavedObjectsServiceStart interface + +Saved Objects is Kibana's data persisentence mechanism allowing plugins to use Elasticsearch for storing and querying state. The SavedObjectsServiceStart API provides a scoped Saved Objects client for interacting with Saved Objects. + +Signature: + +```typescript +export interface SavedObjectsServiceStart +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [createInternalRepository](./kibana-plugin-server.savedobjectsservicestart.createinternalrepository.md) | (extraTypes?: string[]) => ISavedObjectsRepository | Creates a [Saved Objects repository](./kibana-plugin-server.isavedobjectsrepository.md) that uses the internal Kibana user for authenticating with Elasticsearch. | +| [createScopedRepository](./kibana-plugin-server.savedobjectsservicestart.createscopedrepository.md) | (req: KibanaRequest, extraTypes?: string[]) => ISavedObjectsRepository | Creates a [Saved Objects repository](./kibana-plugin-server.isavedobjectsrepository.md) that uses the credentials from the passed in request to authenticate with Elasticsearch. | +| [getScopedClient](./kibana-plugin-server.savedobjectsservicestart.getscopedclient.md) | (req: KibanaRequest, options?: SavedObjectsClientProviderOptions) => SavedObjectsClientContract | Creates a [Saved Objects client](./kibana-plugin-server.savedobjectsclientcontract.md) that uses the credentials from the passed in request to authenticate with Elasticsearch. If other plugins have registered Saved Objects client wrappers, these will be applied to extend the functionality of the client.A client that is already scoped to the incoming request is also exposed from the route handler context see [RequestHandlerContext](./kibana-plugin-server.requesthandlercontext.md). | + diff --git a/docs/development/core/server/kibana-plugin-server.stringvalidation.md b/docs/development/core/server/kibana-plugin-server.stringvalidation.md index cc52c853ce2489..0e396f2972c44f 100644 --- a/docs/development/core/server/kibana-plugin-server.stringvalidation.md +++ b/docs/development/core/server/kibana-plugin-server.stringvalidation.md @@ -2,18 +2,12 @@ [Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [StringValidation](./kibana-plugin-server.stringvalidation.md) -## StringValidation interface +## StringValidation type + +Allows regex objects or a regex string Signature: ```typescript -export interface StringValidation +export declare type StringValidation = StringValidationRegex | StringValidationRegexString; ``` - -## Properties - -| Property | Type | Description | -| --- | --- | --- | -| [message](./kibana-plugin-server.stringvalidation.message.md) | string | | -| [regexString](./kibana-plugin-server.stringvalidation.regexstring.md) | string | | - diff --git a/docs/development/core/server/kibana-plugin-server.stringvalidation.message.md b/docs/development/core/server/kibana-plugin-server.stringvalidation.message.md deleted file mode 100644 index a15fe8b9314039..00000000000000 --- a/docs/development/core/server/kibana-plugin-server.stringvalidation.message.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [StringValidation](./kibana-plugin-server.stringvalidation.md) > [message](./kibana-plugin-server.stringvalidation.message.md) - -## StringValidation.message property - -Signature: - -```typescript -message: string; -``` diff --git a/docs/development/core/server/kibana-plugin-server.stringvalidation.regexstring.md b/docs/development/core/server/kibana-plugin-server.stringvalidation.regexstring.md deleted file mode 100644 index e19560237f77de..00000000000000 --- a/docs/development/core/server/kibana-plugin-server.stringvalidation.regexstring.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [StringValidation](./kibana-plugin-server.stringvalidation.md) > [regexString](./kibana-plugin-server.stringvalidation.regexstring.md) - -## StringValidation.regexString property - -Signature: - -```typescript -regexString: string; -``` diff --git a/docs/development/core/server/kibana-plugin-server.stringvalidationregex.md b/docs/development/core/server/kibana-plugin-server.stringvalidationregex.md new file mode 100644 index 00000000000000..46d196ea8e03fe --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.stringvalidationregex.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [StringValidationRegex](./kibana-plugin-server.stringvalidationregex.md) + +## StringValidationRegex interface + +StringValidation with regex object + +Signature: + +```typescript +export interface StringValidationRegex +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [message](./kibana-plugin-server.stringvalidationregex.message.md) | string | | +| [regex](./kibana-plugin-server.stringvalidationregex.regex.md) | RegExp | | + diff --git a/docs/development/core/server/kibana-plugin-server.stringvalidationregex.message.md b/docs/development/core/server/kibana-plugin-server.stringvalidationregex.message.md new file mode 100644 index 00000000000000..383b1f6d8873c2 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.stringvalidationregex.message.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [StringValidationRegex](./kibana-plugin-server.stringvalidationregex.md) > [message](./kibana-plugin-server.stringvalidationregex.message.md) + +## StringValidationRegex.message property + +Signature: + +```typescript +message: string; +``` diff --git a/docs/development/core/server/kibana-plugin-server.stringvalidationregex.regex.md b/docs/development/core/server/kibana-plugin-server.stringvalidationregex.regex.md new file mode 100644 index 00000000000000..69a96a04895039 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.stringvalidationregex.regex.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [StringValidationRegex](./kibana-plugin-server.stringvalidationregex.md) > [regex](./kibana-plugin-server.stringvalidationregex.regex.md) + +## StringValidationRegex.regex property + +Signature: + +```typescript +regex: RegExp; +``` diff --git a/docs/development/core/server/kibana-plugin-server.stringvalidationregexstring.md b/docs/development/core/server/kibana-plugin-server.stringvalidationregexstring.md new file mode 100644 index 00000000000000..d76cb94fdd1a1c --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.stringvalidationregexstring.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [StringValidationRegexString](./kibana-plugin-server.stringvalidationregexstring.md) + +## StringValidationRegexString interface + +StringValidation as regex string + +Signature: + +```typescript +export interface StringValidationRegexString +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [message](./kibana-plugin-server.stringvalidationregexstring.message.md) | string | | +| [regexString](./kibana-plugin-server.stringvalidationregexstring.regexstring.md) | string | | + diff --git a/docs/development/core/server/kibana-plugin-server.stringvalidationregexstring.message.md b/docs/development/core/server/kibana-plugin-server.stringvalidationregexstring.message.md new file mode 100644 index 00000000000000..361dfe788b852e --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.stringvalidationregexstring.message.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [StringValidationRegexString](./kibana-plugin-server.stringvalidationregexstring.md) > [message](./kibana-plugin-server.stringvalidationregexstring.message.md) + +## StringValidationRegexString.message property + +Signature: + +```typescript +message: string; +``` diff --git a/docs/development/core/server/kibana-plugin-server.stringvalidationregexstring.regexstring.md b/docs/development/core/server/kibana-plugin-server.stringvalidationregexstring.regexstring.md new file mode 100644 index 00000000000000..203cc7e7a0aadd --- /dev/null +++ b/docs/development/core/server/kibana-plugin-server.stringvalidationregexstring.regexstring.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-server](./kibana-plugin-server.md) > [StringValidationRegexString](./kibana-plugin-server.stringvalidationregexstring.md) > [regexString](./kibana-plugin-server.stringvalidationregexstring.regexstring.md) + +## StringValidationRegexString.regexString property + +Signature: + +```typescript +regexString: string; +``` diff --git a/docs/development/core/server/kibana-plugin-server.uisettingstype.md b/docs/development/core/server/kibana-plugin-server.uisettingstype.md index 789d4d5788468e..b78932aecc7245 100644 --- a/docs/development/core/server/kibana-plugin-server.uisettingstype.md +++ b/docs/development/core/server/kibana-plugin-server.uisettingstype.md @@ -9,5 +9,5 @@ UI element type to represent the settings. Signature: ```typescript -export declare type UiSettingsType = 'json' | 'markdown' | 'number' | 'select' | 'boolean' | 'string'; +export declare type UiSettingsType = 'undefined' | 'json' | 'markdown' | 'number' | 'select' | 'boolean' | 'string' | 'array' | 'image'; ``` diff --git a/packages/kbn-plugin-helpers/lib/plugin_config.js b/packages/kbn-plugin-helpers/lib/plugin_config.js index 07bbbfedc15da7..60baa7fc976607 100644 --- a/packages/kbn-plugin-helpers/lib/plugin_config.js +++ b/packages/kbn-plugin-helpers/lib/plugin_config.js @@ -32,7 +32,7 @@ module.exports = function(root) { 'yarn.lock', 'tsconfig.json', 'package.json', - 'index.js', + 'index.{js,ts}', '{lib,public,server,webpackShims,translations}/**/*', ]; diff --git a/src/core/public/application/application_service.test.ts b/src/core/public/application/application_service.test.ts index 54489fbd182b47..8757f73a1206ca 100644 --- a/src/core/public/application/application_service.test.ts +++ b/src/core/public/application/application_service.test.ts @@ -19,7 +19,7 @@ import { createElement } from 'react'; import { BehaviorSubject, Subject } from 'rxjs'; -import { bufferCount, skip, take, takeUntil } from 'rxjs/operators'; +import { bufferCount, take, takeUntil } from 'rxjs/operators'; import { shallow } from 'enzyme'; import { injectedMetadataServiceMock } from '../injected_metadata/injected_metadata_service.mock'; @@ -518,6 +518,22 @@ describe('#start()', () => { expect([...availableApps.keys()]).toEqual(['app1', 'legacyApp1']); }); + describe('currentAppId$', () => { + it('emits the legacy app id when in legacy mode', async () => { + setupDeps.injectedMetadata.getLegacyMode.mockReturnValue(true); + setupDeps.injectedMetadata.getLegacyMetadata.mockReturnValue({ + app: { + id: 'legacy', + title: 'Legacy App', + }, + } as any); + await service.setup(setupDeps); + const { currentAppId$ } = await service.start(startDeps); + + expect(await currentAppId$.pipe(take(1)).toPromise()).toEqual('legacy'); + }); + }); + describe('getComponent', () => { it('returns renderable JSX tree', async () => { service.setup(setupDeps); @@ -651,7 +667,7 @@ describe('#start()', () => { const { currentAppId$, navigateToApp } = await service.start(startDeps); const stop$ = new Subject(); - const promise = currentAppId$.pipe(skip(1), bufferCount(4), takeUntil(stop$)).toPromise(); + const promise = currentAppId$.pipe(bufferCount(4), takeUntil(stop$)).toPromise(); await navigateToApp('alpha'); await navigateToApp('beta'); diff --git a/src/core/public/application/application_service.tsx b/src/core/public/application/application_service.tsx index 4d714c8f9dad2d..511f348e118230 100644 --- a/src/core/public/application/application_service.tsx +++ b/src/core/public/application/application_service.tsx @@ -19,7 +19,7 @@ import React from 'react'; import { BehaviorSubject, Observable, Subject, Subscription } from 'rxjs'; -import { map, shareReplay, takeUntil } from 'rxjs/operators'; +import { map, shareReplay, takeUntil, distinctUntilChanged, filter } from 'rxjs/operators'; import { createBrowserHistory, History } from 'history'; import { InjectedMetadataSetup } from '../injected_metadata'; @@ -114,8 +114,10 @@ export class ApplicationService { history, }: SetupDeps): InternalApplicationSetup { const basename = basePath.get(); - // Only setup history if we're not in legacy mode - if (!injectedMetadata.getLegacyMode()) { + if (injectedMetadata.getLegacyMode()) { + this.currentAppId$.next(injectedMetadata.getLegacyMetadata().app.id); + } else { + // Only setup history if we're not in legacy mode this.history = history || createBrowserHistory({ basename }); } @@ -264,7 +266,11 @@ export class ApplicationService { return { applications$, capabilities, - currentAppId$: this.currentAppId$.pipe(takeUntil(this.stop$)), + currentAppId$: this.currentAppId$.pipe( + filter(appId => appId !== undefined), + distinctUntilChanged(), + takeUntil(this.stop$) + ), registerMountContext: this.mountContext.registerContext, getUrlForApp: (appId, { path }: { path?: string } = {}) => getAppUrl(availableMounters, appId, path), diff --git a/src/core/public/application/integration_tests/router.test.tsx b/src/core/public/application/integration_tests/router.test.tsx index 4d83ab67810afa..0c5f5a138d58f5 100644 --- a/src/core/public/application/integration_tests/router.test.tsx +++ b/src/core/public/application/integration_tests/router.test.tsx @@ -23,7 +23,7 @@ import { createMemoryHistory, History, createHashHistory } from 'history'; import { AppRouter, AppNotFound } from '../ui'; import { EitherApp, MockedMounterMap, MockedMounterTuple } from '../test_types'; -import { createRenderer, createAppMounter, createLegacyAppMounter } from './utils'; +import { createRenderer, createAppMounter, createLegacyAppMounter, getUnmounter } from './utils'; import { AppStatus } from '../types'; describe('AppContainer', () => { @@ -36,7 +36,6 @@ describe('AppContainer', () => { history.push(path); return update(); }; - const mockMountersToMounters = () => new Map([...mounters].map(([appId, { mounter }]) => [appId, mounter])); const setAppLeaveHandlerMock = () => undefined; @@ -58,7 +57,8 @@ describe('AppContainer', () => { createLegacyAppMounter('legacyApp1', jest.fn()), createAppMounter('app2', '
App 2
'), createLegacyAppMounter('baseApp:legacyApp2', jest.fn()), - createAppMounter('app3', '
App 3
', '/custom/path'), + createAppMounter('app3', '
Chromeless A
', '/chromeless-a/path'), + createAppMounter('app4', '
Chromeless B
', '/chromeless-b/path'), createAppMounter('disabledApp', '
Disabled app
'), createLegacyAppMounter('disabledLegacyApp', jest.fn()), ] as Array>); @@ -75,23 +75,24 @@ describe('AppContainer', () => { }); it('calls mount handler and returned unmount function when navigating between apps', async () => { - const dom1 = await navigate('/app/app1'); const app1 = mounters.get('app1')!; + const app2 = mounters.get('app2')!; + let dom = await navigate('/app/app1'); expect(app1.mounter.mount).toHaveBeenCalled(); - expect(dom1?.html()).toMatchInlineSnapshot(` + expect(dom?.html()).toMatchInlineSnapshot(` "
basename: /app/app1 html: App 1
" `); - const app1Unmount = await app1.mounter.mount.mock.results[0].value; - const dom2 = await navigate('/app/app2'); + const app1Unmount = await getUnmounter(app1); + dom = await navigate('/app/app2'); expect(app1Unmount).toHaveBeenCalled(); - expect(mounters.get('app2')!.mounter.mount).toHaveBeenCalled(); - expect(dom2?.html()).toMatchInlineSnapshot(` + expect(app2.mounter.mount).toHaveBeenCalled(); + expect(dom?.html()).toMatchInlineSnapshot(` "
basename: /app/app2 html:
App 2
@@ -99,6 +100,82 @@ describe('AppContainer', () => { `); }); + it('can navigate between standard application and one with custom appRoute', async () => { + const standardApp = mounters.get('app1')!; + const chromelessApp = mounters.get('app3')!; + let dom = await navigate('/app/app1'); + + expect(standardApp.mounter.mount).toHaveBeenCalled(); + expect(dom?.html()).toMatchInlineSnapshot(` + "
+ basename: /app/app1 + html: App 1 +
" + `); + + const standardAppUnmount = await getUnmounter(standardApp); + dom = await navigate('/chromeless-a/path'); + + expect(standardAppUnmount).toHaveBeenCalled(); + expect(chromelessApp.mounter.mount).toHaveBeenCalled(); + expect(dom?.html()).toMatchInlineSnapshot(` + "
+ basename: /chromeless-a/path + html:
Chromeless A
+
" + `); + + const chromelessAppUnmount = await getUnmounter(standardApp); + dom = await navigate('/app/app1'); + + expect(chromelessAppUnmount).toHaveBeenCalled(); + expect(standardApp.mounter.mount).toHaveBeenCalledTimes(2); + expect(dom?.html()).toMatchInlineSnapshot(` + "
+ basename: /app/app1 + html: App 1 +
" + `); + }); + + it('can navigate between two applications with custom appRoutes', async () => { + const chromelessAppA = mounters.get('app3')!; + const chromelessAppB = mounters.get('app4')!; + let dom = await navigate('/chromeless-a/path'); + + expect(chromelessAppA.mounter.mount).toHaveBeenCalled(); + expect(dom?.html()).toMatchInlineSnapshot(` + "
+ basename: /chromeless-a/path + html:
Chromeless A
+
" + `); + + const chromelessAppAUnmount = await getUnmounter(chromelessAppA); + dom = await navigate('/chromeless-b/path'); + + expect(chromelessAppAUnmount).toHaveBeenCalled(); + expect(chromelessAppB.mounter.mount).toHaveBeenCalled(); + expect(dom?.html()).toMatchInlineSnapshot(` + "
+ basename: /chromeless-b/path + html:
Chromeless B
+
" + `); + + const chromelessAppBUnmount = await getUnmounter(chromelessAppB); + dom = await navigate('/chromeless-a/path'); + + expect(chromelessAppBUnmount).toHaveBeenCalled(); + expect(chromelessAppA.mounter.mount).toHaveBeenCalledTimes(2); + expect(dom?.html()).toMatchInlineSnapshot(` + "
+ basename: /chromeless-a/path + html:
Chromeless A
+
" + `); + }); + it('should not mount when partial route path matches', async () => { mounters.set(...createAppMounter('spaces', '
Custom Space
', '/spaces/fake-login')); mounters.set(...createAppMounter('login', '
Login Page
', '/fake-login')); diff --git a/src/core/public/application/integration_tests/utils.tsx b/src/core/public/application/integration_tests/utils.tsx index 6367d1fa12697e..4f34438fc822a3 100644 --- a/src/core/public/application/integration_tests/utils.tsx +++ b/src/core/public/application/integration_tests/utils.tsx @@ -23,7 +23,7 @@ import { mount } from 'enzyme'; import { I18nProvider } from '@kbn/i18n/react'; import { App, LegacyApp, AppMountParameters } from '../types'; -import { MockedMounter, MockedMounterTuple } from '../test_types'; +import { EitherApp, MockedMounter, MockedMounterTuple, Mountable } from '../test_types'; type Dom = ReturnType | null; type Renderer = () => Dom | Promise; @@ -80,3 +80,7 @@ export const createLegacyAppMounter = ( unmount: jest.fn(), }, ]; + +export function getUnmounter(app: Mountable) { + return app.mounter.mount.mock.results[0].value; +} diff --git a/src/core/public/application/test_types.ts b/src/core/public/application/test_types.ts index 3d992cb950eb42..b822597e510cb9 100644 --- a/src/core/public/application/test_types.ts +++ b/src/core/public/application/test_types.ts @@ -26,18 +26,19 @@ export type ApplicationServiceContract = PublicMethodsOf; export type EitherApp = App | LegacyApp; /** @internal */ export type MockedUnmount = jest.Mocked; + +/** @internal */ +export interface Mountable { + mounter: MockedMounter; + unmount: MockedUnmount; +} + /** @internal */ export type MockedMounter = jest.Mocked>>; /** @internal */ -export type MockedMounterTuple = [ - string, - { mounter: MockedMounter; unmount: MockedUnmount } -]; +export type MockedMounterTuple = [string, Mountable]; /** @internal */ -export type MockedMounterMap = Map< - string, - { mounter: MockedMounter; unmount: MockedUnmount } ->; +export type MockedMounterMap = Map>; /** @internal */ export type MockLifecycle< T extends keyof ApplicationService, diff --git a/src/core/public/application/ui/app_container.tsx b/src/core/public/application/ui/app_container.tsx index 6a630608b2c205..66c837d238276c 100644 --- a/src/core/public/application/ui/app_container.tsx +++ b/src/core/public/application/ui/app_container.tsx @@ -45,7 +45,6 @@ export const AppContainer: FunctionComponent = ({ const [appNotFound, setAppNotFound] = useState(false); const elementRef = useRef(null); const unmountRef: MutableRefObject = useRef(null); - // const appStatus = useObservable(appStatus$); useLayoutEffect(() => { const unmount = () => { diff --git a/src/core/public/doc_links/doc_links_service.ts b/src/core/public/doc_links/doc_links_service.ts index 1046f7a17dc518..3521d7ef9c66eb 100644 --- a/src/core/public/doc_links/doc_links_service.ts +++ b/src/core/public/doc_links/doc_links_service.ts @@ -214,5 +214,6 @@ export interface DocLinksStart { readonly date: { readonly dateMath: string; }; + readonly management: Record; }; } diff --git a/src/core/public/index.ts b/src/core/public/index.ts index bf8cab9a3c7787..c57d35343087ae 100644 --- a/src/core/public/index.ts +++ b/src/core/public/index.ts @@ -78,7 +78,16 @@ import { export { CoreContext, CoreSystem } from './core_system'; export { RecursiveReadonly, DEFAULT_APP_CATEGORIES } from '../utils'; -export { AppCategory } from '../types'; +export { + AppCategory, + UiSettingsParams, + UserProvidedValues, + UiSettingsType, + ImageValidation, + StringValidation, + StringValidationRegex, + StringValidationRegexString, +} from '../types'; export { ApplicationSetup, diff --git a/src/core/public/injected_metadata/injected_metadata_service.mock.ts b/src/core/public/injected_metadata/injected_metadata_service.mock.ts index 9dfe0191166697..3c06f40d976db6 100644 --- a/src/core/public/injected_metadata/injected_metadata_service.mock.ts +++ b/src/core/public/injected_metadata/injected_metadata_service.mock.ts @@ -35,6 +35,10 @@ const createSetupContractMock = () => { setupContract.getKibanaVersion.mockReturnValue('kibanaVersion'); setupContract.getLegacyMode.mockReturnValue(true); setupContract.getLegacyMetadata.mockReturnValue({ + app: { + id: 'foo', + title: 'Foo App', + }, nav: [], uiSettings: { defaults: { legacyInjectedUiSettingDefaults: true }, diff --git a/src/core/public/injected_metadata/injected_metadata_service.ts b/src/core/public/injected_metadata/injected_metadata_service.ts index 1075a7741ee324..64a8b8a855fb46 100644 --- a/src/core/public/injected_metadata/injected_metadata_service.ts +++ b/src/core/public/injected_metadata/injected_metadata_service.ts @@ -68,7 +68,10 @@ export interface InjectedMetadataParams { uiPlugins: InjectedPluginMetadata[]; legacyMode: boolean; legacyMetadata: { - app: unknown; + app: { + id: string; + title: string; + }; bundleId: string; nav: LegacyNavLink[]; version: string; @@ -171,7 +174,10 @@ export interface InjectedMetadataSetup { /** Indicates whether or not we are rendering a known legacy app. */ getLegacyMode: () => boolean; getLegacyMetadata: () => { - app: unknown; + app: { + id: string; + title: string; + }; bundleId: string; nav: LegacyNavLink[]; version: string; diff --git a/src/core/public/public.api.md b/src/core/public/public.api.md index 0da6e0d422f2d7..a9cea7ae97998d 100644 --- a/src/core/public/public.api.md +++ b/src/core/public/public.api.md @@ -531,6 +531,7 @@ export interface DocLinksStart { readonly date: { readonly dateMath: string; }; + readonly management: Record; }; } @@ -730,6 +731,15 @@ export interface IHttpResponseInterceptorOverrides { readonly response?: Readonly; } +// @public (undocumented) +export interface ImageValidation { + // (undocumented) + maxSize: { + length: number; + description: string; + }; +} + // @public export type IToasts = Pick; @@ -1166,6 +1176,25 @@ export class SimpleSavedObject { _version?: SavedObject['version']; } +// @public +export type StringValidation = StringValidationRegex | StringValidationRegexString; + +// @public +export interface StringValidationRegex { + // (undocumented) + message: string; + // (undocumented) + regex: RegExp; +} + +// @public +export interface StringValidationRegexString { + // (undocumented) + message: string; + // (undocumented) + regexString: string; +} + // Warning: (ae-missing-release-tag) "Toast" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -1207,14 +1236,42 @@ export type ToastsSetup = IToasts; // @public (undocumented) export type ToastsStart = IToasts; +// @public +export interface UiSettingsParams { + category?: string[]; + // Warning: (ae-forgotten-export) The symbol "DeprecationSettings" needs to be exported by the entry point index.d.ts + deprecation?: DeprecationSettings; + description?: string; + name?: string; + optionLabels?: Record; + options?: string[]; + readonly?: boolean; + requiresPageReload?: boolean; + type?: UiSettingsType; + // (undocumented) + validation?: ImageValidation | StringValidation; + value?: SavedObjectAttribute; +} + // @public (undocumented) export interface UiSettingsState { // (undocumented) [key: string]: UiSettingsParams_2 & UserProvidedValues_2; } +// @public +export type UiSettingsType = 'undefined' | 'json' | 'markdown' | 'number' | 'select' | 'boolean' | 'string' | 'array' | 'image'; + // @public export type UnmountCallback = () => void; +// @public +export interface UserProvidedValues { + // (undocumented) + isOverridden?: boolean; + // (undocumented) + userValue?: T; +} + ``` diff --git a/src/core/public/types.ts b/src/core/public/types.ts index 5abbb3c55813ac..267a9e9f7e0145 100644 --- a/src/core/public/types.ts +++ b/src/core/public/types.ts @@ -17,6 +17,14 @@ * under the License. */ +export { + UiSettingsParams, + UserProvidedValues, + UiSettingsType, + ImageValidation, + StringValidationRegex, +} from '../../core/types'; + /** * A function that should mount DOM content inside the provided container element * and return a handler to unmount it. diff --git a/src/core/server/elasticsearch/retry_call_cluster.ts b/src/core/server/elasticsearch/retry_call_cluster.ts index 89d7b88b1675a0..bd72ecf7264616 100644 --- a/src/core/server/elasticsearch/retry_call_cluster.ts +++ b/src/core/server/elasticsearch/retry_call_cluster.ts @@ -22,6 +22,7 @@ import { defer, throwError, iif, timer } from 'rxjs'; import * as legacyElasticsearch from 'elasticsearch'; import { CallAPIOptions } from '.'; +import { APICaller } from './api_types'; import { Logger } from '../logging'; const esErrors = legacyElasticsearch.errors; @@ -34,15 +35,11 @@ const esErrors = legacyElasticsearch.errors; * different error is received. * * @param apiCaller + * @param log + * @param delay */ - -// TODO: Replace with APICaller from './scoped_cluster_client' once #46668 is merged export function migrationsRetryCallCluster( - apiCaller: ( - endpoint: string, - clientParams: Record, - options?: CallAPIOptions - ) => Promise, + apiCaller: APICaller, log: Logger, delay: number = 2500 ) { diff --git a/src/core/server/index.ts b/src/core/server/index.ts index a97d2970dca881..91f38c9f2ddbe9 100644 --- a/src/core/server/index.ts +++ b/src/core/server/index.ts @@ -180,6 +180,7 @@ export { SavedObjectsClientWrapperFactory, SavedObjectsClientWrapperOptions, SavedObjectsClientFactory, + SavedObjectsClientFactoryProvider, SavedObjectsCreateOptions, SavedObjectsErrorHelpers, SavedObjectsExportOptions, @@ -195,6 +196,7 @@ export { SavedObjectsImportUnsupportedTypeError, SavedObjectsMigrationLogger, SavedObjectsRawDoc, + SavedObjectsRepositoryFactory, SavedObjectsResolveImportErrorsOptions, SavedObjectsSchema, SavedObjectsSerializer, @@ -220,6 +222,8 @@ export { ImageValidation, DeprecationSettings, StringValidation, + StringValidationRegex, + StringValidationRegexString, } from './ui_settings'; export { RecursiveReadonly } from '../utils'; diff --git a/src/core/server/legacy/legacy_service.ts b/src/core/server/legacy/legacy_service.ts index 7862412fbad06d..ca1204f0ac05ce 100644 --- a/src/core/server/legacy/legacy_service.ts +++ b/src/core/server/legacy/legacy_service.ts @@ -258,7 +258,11 @@ export class LegacyService implements CoreService { ) { const coreStart: CoreStart = { capabilities: startDeps.core.capabilities, - savedObjects: { getScopedClient: startDeps.core.savedObjects.getScopedClient }, + savedObjects: { + getScopedClient: startDeps.core.savedObjects.getScopedClient, + createScopedRepository: startDeps.core.savedObjects.createScopedRepository, + createInternalRepository: startDeps.core.savedObjects.createInternalRepository, + }, uiSettings: { asScopedToClient: startDeps.core.uiSettings.asScopedToClient }, }; @@ -286,10 +290,8 @@ export class LegacyService implements CoreService { isTlsEnabled: setupDeps.core.http.isTlsEnabled, }, savedObjects: { - setClientFactory: setupDeps.core.savedObjects.setClientFactory, + setClientFactoryProvider: setupDeps.core.savedObjects.setClientFactoryProvider, addClientWrapper: setupDeps.core.savedObjects.addClientWrapper, - createInternalRepository: setupDeps.core.savedObjects.createInternalRepository, - createScopedRepository: setupDeps.core.savedObjects.createScopedRepository, }, uiSettings: { register: setupDeps.core.uiSettings.register, diff --git a/src/core/server/plugins/plugin_context.ts b/src/core/server/plugins/plugin_context.ts index f266172cb4bd9e..99cd4eda7374ce 100644 --- a/src/core/server/plugins/plugin_context.ts +++ b/src/core/server/plugins/plugin_context.ts @@ -165,10 +165,8 @@ export function createPluginSetupContext( isTlsEnabled: deps.http.isTlsEnabled, }, savedObjects: { - setClientFactory: deps.savedObjects.setClientFactory, + setClientFactoryProvider: deps.savedObjects.setClientFactoryProvider, addClientWrapper: deps.savedObjects.addClientWrapper, - createInternalRepository: deps.savedObjects.createInternalRepository, - createScopedRepository: deps.savedObjects.createScopedRepository, }, uiSettings: { register: deps.uiSettings.register, @@ -203,6 +201,8 @@ export function createPluginStartContext( }, savedObjects: { getScopedClient: deps.savedObjects.getScopedClient, + createInternalRepository: deps.savedObjects.createInternalRepository, + createScopedRepository: deps.savedObjects.createScopedRepository, }, uiSettings: { asScopedToClient: deps.uiSettings.asScopedToClient, diff --git a/src/core/server/saved_objects/index.ts b/src/core/server/saved_objects/index.ts index 1100c18bcc72fa..181025d73817dc 100644 --- a/src/core/server/saved_objects/index.ts +++ b/src/core/server/saved_objects/index.ts @@ -41,6 +41,7 @@ export { SavedObjectsServiceStart, SavedObjectsServiceSetup, InternalSavedObjectsServiceSetup, + SavedObjectsRepositoryFactory, } from './saved_objects_service'; export { diff --git a/src/core/server/saved_objects/saved_objects_service.mock.ts b/src/core/server/saved_objects/saved_objects_service.mock.ts index b2596146a02d47..a15d1f5b864b7d 100644 --- a/src/core/server/saved_objects/saved_objects_service.mock.ts +++ b/src/core/server/saved_objects/saved_objects_service.mock.ts @@ -33,29 +33,27 @@ const createStartContractMock = () => { const startContract: jest.Mocked = { clientProvider: savedObjectsClientProviderMock.create(), getScopedClient: jest.fn(), + createInternalRepository: jest.fn(), + createScopedRepository: jest.fn(), migrator: mockKibanaMigrator.create(), }; + startContract.getScopedClient.mockReturnValue(savedObjectsClientMock.create()); + startContract.createInternalRepository.mockReturnValue(savedObjectsRepositoryMock.create()); + startContract.createScopedRepository.mockReturnValue(savedObjectsRepositoryMock.create()); + return startContract; }; const createSetupContractMock = () => { const setupContract: jest.Mocked = { - getScopedClient: jest.fn(), - setClientFactory: jest.fn(), + setClientFactoryProvider: jest.fn(), addClientWrapper: jest.fn(), - createInternalRepository: jest.fn(), - createScopedRepository: jest.fn(), }; - - setupContract.getScopedClient.mockReturnValue(savedObjectsClientMock.create()); - setupContract.createInternalRepository.mockReturnValue(savedObjectsRepositoryMock.create()); - setupContract.createScopedRepository.mockReturnValue(savedObjectsRepositoryMock.create()); - return setupContract; }; -const createsavedObjectsServiceMock = () => { +const createSavedObjectsServiceMock = () => { const mocked: jest.Mocked = { setup: jest.fn(), start: jest.fn(), @@ -69,7 +67,7 @@ const createsavedObjectsServiceMock = () => { }; export const savedObjectsServiceMock = { - create: createsavedObjectsServiceMock, + create: createSavedObjectsServiceMock, createSetupContract: createSetupContractMock, createStartContract: createStartContractMock, }; diff --git a/src/core/server/saved_objects/saved_objects_service.test.mocks.ts b/src/core/server/saved_objects/saved_objects_service.test.mocks.ts new file mode 100644 index 00000000000000..a9ad0778d4757d --- /dev/null +++ b/src/core/server/saved_objects/saved_objects_service.test.mocks.ts @@ -0,0 +1,32 @@ +/* + * 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 { mockKibanaMigrator } from './migrations/kibana/kibana_migrator.mock'; +import { savedObjectsClientProviderMock } from './service/lib/scoped_client_provider.mock'; + +export const migratorInstanceMock = mockKibanaMigrator.create(); +export const KibanaMigratorMock = jest.fn().mockImplementation(() => migratorInstanceMock); +jest.doMock('./migrations/kibana/kibana_migrator', () => ({ + KibanaMigrator: KibanaMigratorMock, +})); + +export const clientProviderInstanceMock = savedObjectsClientProviderMock.create(); +jest.doMock('./service/lib/scoped_client_provider', () => ({ + SavedObjectsClientProvider: jest.fn().mockImplementation(() => clientProviderInstanceMock), +})); diff --git a/src/core/server/saved_objects/saved_objects_service.test.ts b/src/core/server/saved_objects/saved_objects_service.test.ts index deb6f98e17b7b7..6668d57045a957 100644 --- a/src/core/server/saved_objects/saved_objects_service.test.ts +++ b/src/core/server/saved_objects/saved_objects_service.test.ts @@ -17,95 +17,149 @@ * under the License. */ -jest.mock('./migrations/kibana/kibana_migrator'); +import { + KibanaMigratorMock, + migratorInstanceMock, + clientProviderInstanceMock, +} from './saved_objects_service.test.mocks'; -import { SavedObjectsService, SavedObjectsSetupDeps } from './saved_objects_service'; +import { SavedObjectsService } from './saved_objects_service'; import { mockCoreContext } from '../core_context.mock'; -// @ts-ignore Typescript doesn't know about the jest mock -import { KibanaMigrator, mockKibanaMigratorInstance } from './migrations/kibana/kibana_migrator'; import * as legacyElasticsearch from 'elasticsearch'; import { Env } from '../config'; import { configServiceMock } from '../mocks'; - -afterEach(() => { - jest.clearAllMocks(); -}); +import { elasticsearchServiceMock } from '../elasticsearch/elasticsearch_service.mock'; +import { legacyServiceMock } from '../legacy/legacy_service.mock'; +import { SavedObjectsClientFactoryProvider } from './service/lib'; describe('SavedObjectsService', () => { + const createSetupDeps = () => { + return { + elasticsearch: elasticsearchServiceMock.createInternalSetup(), + legacyPlugins: legacyServiceMock.createDiscoverPlugins(), + }; + }; + + afterEach(() => { + jest.clearAllMocks(); + }); + describe('#setup()', () => { + describe('#setClientFactoryProvider', () => { + it('registers the factory to the clientProvider', async () => { + const coreContext = mockCoreContext.create(); + const soService = new SavedObjectsService(coreContext); + const setup = await soService.setup(createSetupDeps()); + + const factory = jest.fn(); + const factoryProvider: SavedObjectsClientFactoryProvider = () => factory; + + setup.setClientFactoryProvider(factoryProvider); + + await soService.start({}); + + expect(clientProviderInstanceMock.setClientFactory).toHaveBeenCalledWith(factory); + }); + it('throws if a factory is already registered', async () => { + const coreContext = mockCoreContext.create(); + const soService = new SavedObjectsService(coreContext); + const setup = await soService.setup(createSetupDeps()); + + const firstFactory = () => jest.fn(); + const secondFactory = () => jest.fn(); + + setup.setClientFactoryProvider(firstFactory); + + expect(() => { + setup.setClientFactoryProvider(secondFactory); + }).toThrowErrorMatchingInlineSnapshot( + `"custom client factory is already set, and can only be set once"` + ); + }); + }); + + describe('#addClientWrapper', () => { + it('registers the wrapper to the clientProvider', async () => { + const coreContext = mockCoreContext.create(); + const soService = new SavedObjectsService(coreContext); + const setup = await soService.setup(createSetupDeps()); + + const wrapperA = jest.fn(); + const wrapperB = jest.fn(); + + setup.addClientWrapper(1, 'A', wrapperA); + setup.addClientWrapper(2, 'B', wrapperB); + + await soService.start({}); + + expect(clientProviderInstanceMock.addClientWrapperFactory).toHaveBeenCalledTimes(2); + expect(clientProviderInstanceMock.addClientWrapperFactory).toHaveBeenCalledWith( + 1, + 'A', + wrapperA + ); + expect(clientProviderInstanceMock.addClientWrapperFactory).toHaveBeenCalledWith( + 2, + 'B', + wrapperB + ); + }); + }); + }); + + describe('#start()', () => { it('creates a KibanaMigrator which retries NoConnections errors from callAsInternalUser', async () => { const coreContext = mockCoreContext.create(); - let i = 0; - const clusterClient = { - callAsInternalUser: jest - .fn() - .mockImplementation(() => - i++ <= 2 - ? Promise.reject(new legacyElasticsearch.errors.NoConnections()) - : Promise.resolve('success') - ), - }; const soService = new SavedObjectsService(coreContext); - const coreSetup = ({ - elasticsearch: { adminClient: clusterClient }, - legacyPlugins: { uiExports: { savedObjectMappings: [] }, pluginExtendedConfig: {} }, - } as unknown) as SavedObjectsSetupDeps; + const coreSetup = createSetupDeps(); + + let i = 0; + coreSetup.elasticsearch.adminClient.callAsInternalUser = jest + .fn() + .mockImplementation(() => + i++ <= 2 + ? Promise.reject(new legacyElasticsearch.errors.NoConnections()) + : Promise.resolve('success') + ); - await soService.setup(coreSetup, 1); + await soService.setup(coreSetup); + await soService.start({}, 1); - return expect((KibanaMigrator as jest.Mock).mock.calls[0][0].callCluster()).resolves.toMatch( - 'success' - ); + return expect(KibanaMigratorMock.mock.calls[0][0].callCluster()).resolves.toMatch('success'); }); - }); - describe('#start()', () => { it('skips KibanaMigrator migrations when --optimize=true', async () => { const coreContext = mockCoreContext.create({ env: ({ cliArgs: { optimize: true }, packageInfo: { version: 'x.x.x' } } as unknown) as Env, }); const soService = new SavedObjectsService(coreContext); - const coreSetup = ({ - elasticsearch: { adminClient: { callAsInternalUser: jest.fn() } }, - legacyPlugins: { uiExports: {}, pluginExtendedConfig: {} }, - } as unknown) as SavedObjectsSetupDeps; - await soService.setup(coreSetup); + await soService.setup(createSetupDeps()); await soService.start({}); - expect(mockKibanaMigratorInstance.runMigrations).toHaveBeenCalledWith(true); + expect(migratorInstanceMock.runMigrations).toHaveBeenCalledWith(true); }); it('skips KibanaMigrator migrations when migrations.skip=true', async () => { const configService = configServiceMock.create({ atPath: { skip: true } }); const coreContext = mockCoreContext.create({ configService }); const soService = new SavedObjectsService(coreContext); - const coreSetup = ({ - elasticsearch: { adminClient: { callAsInternalUser: jest.fn() } }, - legacyPlugins: { uiExports: {}, pluginExtendedConfig: {} }, - } as unknown) as SavedObjectsSetupDeps; - - await soService.setup(coreSetup); + await soService.setup(createSetupDeps()); await soService.start({}); - expect(mockKibanaMigratorInstance.runMigrations).toHaveBeenCalledWith(true); + expect(migratorInstanceMock.runMigrations).toHaveBeenCalledWith(true); }); it('resolves with KibanaMigrator after waiting for migrations to complete', async () => { const configService = configServiceMock.create({ atPath: { skip: false } }); const coreContext = mockCoreContext.create({ configService }); const soService = new SavedObjectsService(coreContext); - const coreSetup = ({ - elasticsearch: { adminClient: { callAsInternalUser: jest.fn() } }, - legacyPlugins: { uiExports: {}, pluginExtendedConfig: {} }, - } as unknown) as SavedObjectsSetupDeps; - - await soService.setup(coreSetup); - expect(mockKibanaMigratorInstance.runMigrations).toHaveBeenCalledTimes(0); + await soService.setup(createSetupDeps()); + expect(migratorInstanceMock.runMigrations).toHaveBeenCalledTimes(0); const startContract = await soService.start({}); - expect(startContract.migrator).toBe(mockKibanaMigratorInstance); - expect(mockKibanaMigratorInstance.runMigrations).toHaveBeenCalledWith(false); - expect(mockKibanaMigratorInstance.runMigrations).toHaveBeenCalledTimes(1); + expect(startContract.migrator).toBe(migratorInstanceMock); + expect(migratorInstanceMock.runMigrations).toHaveBeenCalledWith(false); + expect(migratorInstanceMock.runMigrations).toHaveBeenCalledTimes(1); }); }); }); diff --git a/src/core/server/saved_objects/saved_objects_service.ts b/src/core/server/saved_objects/saved_objects_service.ts index 69ca8306ca4da8..b08033a19242b0 100644 --- a/src/core/server/saved_objects/saved_objects_service.ts +++ b/src/core/server/saved_objects/saved_objects_service.ts @@ -37,13 +37,17 @@ import { KibanaRequest } from '../http'; import { SavedObjectsClientContract } from './types'; import { ISavedObjectsRepository, SavedObjectsRepository } from './service/lib/repository'; import { - SavedObjectsClientFactory, + SavedObjectsClientFactoryProvider, SavedObjectsClientWrapperFactory, } from './service/lib/scoped_client_provider'; -import { Logger } from '..'; +import { Logger } from '../logging'; +import { SavedObjectsMapping } from './mappings'; +import { MigrationDefinition } from './migrations/core/document_migrator'; +import { SavedObjectsSchemaDefinition } from './schema'; +import { PropertyValidators } from './validation'; /** - * Saved Objects is Kibana's data persisentence mechanism allowing plugins to + * Saved Objects is Kibana's data persistence mechanism allowing plugins to * use Elasticsearch for storing and querying state. The * SavedObjectsServiceSetup API exposes methods for creating and registering * Saved Object client wrappers. @@ -66,11 +70,11 @@ import { Logger } from '..'; * constructor. * * @example - * import {SavedObjectsClient, CoreSetup} from 'src/core/server'; + * import { SavedObjectsClient, CoreSetup } from 'src/core/server'; * * export class Plugin() { * setup: (core: CoreSetup) => { - * core.savedObjects.setClientFactory(({request: KibanaRequest}) => { + * core.savedObjects.setClientFactory(({ request: KibanaRequest }) => { * return new SavedObjectsClient(core.savedObjects.scopedRepository(request)); * }) * } @@ -80,61 +84,25 @@ import { Logger } from '..'; */ export interface SavedObjectsServiceSetup { /** - * Set a default factory for creating Saved Objects clients. Only one client - * factory can be set, subsequent calls to this method will fail. + * Set the default {@link SavedObjectsClientFactoryProvider | factory provider} for creating Saved Objects clients. + * Only one provider can be set, subsequent calls to this method will fail. */ - setClientFactory: (customClientFactory: SavedObjectsClientFactory) => void; + setClientFactoryProvider: (clientFactoryProvider: SavedObjectsClientFactoryProvider) => void; /** - * Add a client wrapper with the given priority. + * Add a {@link SavedObjectsClientWrapperFactory | client wrapper factory} with the given priority. */ addClientWrapper: ( priority: number, id: string, - factory: SavedObjectsClientWrapperFactory + factory: SavedObjectsClientWrapperFactory ) => void; - - /** - * Creates a {@link ISavedObjectsRepository | Saved Objects repository} that - * uses the credentials from the passed in request to authenticate with - * Elasticsearch. - * - * @remarks - * The repository should only be used for creating and registering a client - * factory or client wrapper. Using the repository directly for interacting - * with Saved Objects is an anti-pattern. Use the Saved Objects client from - * the - * {@link SavedObjectsServiceStart | SavedObjectsServiceStart#getScopedClient } - * method or the {@link RequestHandlerContext | route handler context} - * instead. - */ - createScopedRepository: (req: KibanaRequest, extraTypes?: string[]) => ISavedObjectsRepository; - - /** - * Creates a {@link ISavedObjectsRepository | Saved Objects repository} that - * uses the internal Kibana user for authenticating with Elasticsearch. - * - * @remarks - * The repository should only be used for creating and registering a client - * factory or client wrapper. Using the repository directly for interacting - * with Saved Objects is an anti-pattern. Use the Saved Objects client from - * the - * {@link SavedObjectsServiceStart | SavedObjectsServiceStart#getScopedClient } - * method or the {@link RequestHandlerContext | route handler context} - * instead. - */ - createInternalRepository: (extraTypes?: string[]) => ISavedObjectsRepository; } /** * @internal */ -export interface InternalSavedObjectsServiceSetup extends SavedObjectsServiceSetup { - getScopedClient: ( - req: KibanaRequest, - options?: SavedObjectsClientProviderOptions - ) => SavedObjectsClientContract; -} +export type InternalSavedObjectsServiceSetup = SavedObjectsServiceSetup; /** * Saved Objects is Kibana's data persisentence mechanism allowing plugins to @@ -158,6 +126,26 @@ export interface SavedObjectsServiceStart { req: KibanaRequest, options?: SavedObjectsClientProviderOptions ) => SavedObjectsClientContract; + /** + * Creates a {@link ISavedObjectsRepository | Saved Objects repository} that + * uses the credentials from the passed in request to authenticate with + * Elasticsearch. + * + * @param req - The request to create the scoped repository from. + * @param extraTypes - A list of additional hidden types the repository should have access to. + * + * @remarks + * Prefer using `getScopedClient`. This should only be used when using methods + * not exposed on {@link SavedObjectsClientContract} + */ + createScopedRepository: (req: KibanaRequest, extraTypes?: string[]) => ISavedObjectsRepository; + /** + * Creates a {@link ISavedObjectsRepository | Saved Objects repository} that + * uses the internal Kibana user for authenticating with Elasticsearch. + * + * @param extraTypes - A list of additional hidden types the repository should have access to. + */ + createInternalRepository: (extraTypes?: string[]) => ISavedObjectsRepository; } export interface InternalSavedObjectsServiceStart extends SavedObjectsServiceStart { @@ -171,130 +159,200 @@ export interface InternalSavedObjectsServiceStart extends SavedObjectsServiceSta clientProvider: ISavedObjectsClientProvider; } +/** + * Factory provided when invoking a {@link SavedObjectsClientFactoryProvider | client factory provider} + * See {@link SavedObjectsServiceSetup.setClientFactoryProvider} + * + * @public + */ +export interface SavedObjectsRepositoryFactory { + /** + * Creates a {@link ISavedObjectsRepository | Saved Objects repository} that + * uses the credentials from the passed in request to authenticate with + * Elasticsearch. + * + * @param extraTypes - A list of additional hidden types the repository should have access to. + */ + createScopedRepository: (req: KibanaRequest, extraTypes?: string[]) => ISavedObjectsRepository; + /** + * Creates a {@link ISavedObjectsRepository | Saved Objects repository} that + * uses the internal Kibana user for authenticating with Elasticsearch. + * + * @param extraTypes - A list of additional hidden types the repository should have access to. + */ + createInternalRepository: (extraTypes?: string[]) => ISavedObjectsRepository; +} + /** @internal */ export interface SavedObjectsSetupDeps { legacyPlugins: LegacyServiceDiscoverPlugins; elasticsearch: InternalElasticsearchServiceSetup; } +interface WrappedClientFactoryWrapper { + priority: number; + id: string; + factory: SavedObjectsClientWrapperFactory; +} + /** @internal */ // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface SavedObjectsStartDeps {} export class SavedObjectsService implements CoreService { - private migrator: KibanaMigrator | undefined; private logger: Logger; - private clientProvider: ISavedObjectsClientProvider | undefined; + + private setupDeps?: SavedObjectsSetupDeps; + private clientFactoryProvider?: SavedObjectsClientFactoryProvider; + private clientFactoryWrappers: WrappedClientFactoryWrapper[] = []; + + private mappings: SavedObjectsMapping[] = []; + private migrations: MigrationDefinition = {}; + private schemas: SavedObjectsSchemaDefinition = {}; + private validations: PropertyValidators = {}; constructor(private readonly coreContext: CoreContext) { this.logger = coreContext.logger.get('savedobjects-service'); } - public async setup( - setupDeps: SavedObjectsSetupDeps, - migrationsRetryDelay?: number - ): Promise { + public async setup(setupDeps: SavedObjectsSetupDeps): Promise { this.logger.debug('Setting up SavedObjects service'); + this.setupDeps = setupDeps; + const { savedObjectSchemas: savedObjectsSchemasDefinition, savedObjectMappings, savedObjectMigrations, savedObjectValidations, } = setupDeps.legacyPlugins.uiExports; + this.mappings = savedObjectMappings; + this.migrations = savedObjectMigrations; + this.schemas = savedObjectsSchemasDefinition; + this.validations = savedObjectValidations; - const savedObjectSchemas = new SavedObjectsSchema(savedObjectsSchemasDefinition); + return { + setClientFactoryProvider: provider => { + if (this.clientFactoryProvider) { + throw new Error('custom client factory is already set, and can only be set once'); + } + this.clientFactoryProvider = provider; + }, + addClientWrapper: (priority, id, factory) => { + this.clientFactoryWrappers.push({ + priority, + id, + factory, + }); + }, + }; + } + + public async start( + core: SavedObjectsStartDeps, + migrationsRetryDelay?: number + ): Promise { + if (!this.setupDeps) { + throw new Error('#setup() needs to be run first'); + } + + this.logger.debug('Starting SavedObjects service'); const kibanaConfig = await this.coreContext.configService .atPath('kibana') .pipe(first()) .toPromise(); - const savedObjectsConfig = await this.coreContext.configService .atPath('migrations') .pipe(first()) .toPromise(); + const adminClient = this.setupDeps!.elasticsearch.adminClient; + const migrator = this.createMigrator(kibanaConfig, savedObjectsConfig, migrationsRetryDelay); - const adminClient = setupDeps.elasticsearch.adminClient; + /** + * Note: We want to ensure that migrations have completed before + * continuing with further Core start steps that might use SavedObjects + * such as running the legacy server, legacy plugins and allowing incoming + * HTTP requests. + * + * However, our build system optimize step and some tests depend on the + * HTTP server running without an Elasticsearch server being available. + * So, when the `migrations.skip` is true, we skip migrations altogether. + */ + const cliArgs = this.coreContext.env.cliArgs; + const skipMigrations = cliArgs.optimize || savedObjectsConfig.skip; - const migrator = (this.migrator = new KibanaMigrator({ - savedObjectSchemas, - savedObjectMappings, - savedObjectMigrations, - savedObjectValidations, - logger: this.coreContext.logger.get('migrations'), - kibanaVersion: this.coreContext.env.packageInfo.version, - config: setupDeps.legacyPlugins.pluginExtendedConfig, - savedObjectsConfig, - kibanaConfig, - callCluster: migrationsRetryCallCluster( - adminClient.callAsInternalUser, - this.coreContext.logger.get('migrations'), - migrationsRetryDelay - ), - })); + this.logger.debug('Starting saved objects migration'); + await migrator.runMigrations(skipMigrations); + this.logger.debug('Saved objects migration completed'); - const createSORepository = (callCluster: APICaller, extraTypes: string[] = []) => { + const createRepository = (callCluster: APICaller, extraTypes: string[] = []) => { return SavedObjectsRepository.createRepository( migrator, - savedObjectSchemas, - setupDeps.legacyPlugins.pluginExtendedConfig, + new SavedObjectsSchema(this.schemas), + this.setupDeps!.legacyPlugins.pluginExtendedConfig, kibanaConfig.index, callCluster, extraTypes ); }; - this.clientProvider = new SavedObjectsClientProvider({ + const repositoryFactory: SavedObjectsRepositoryFactory = { + createInternalRepository: (extraTypes?: string[]) => + createRepository(adminClient.callAsInternalUser, extraTypes), + createScopedRepository: (req: KibanaRequest, extraTypes?: string[]) => + createRepository(adminClient.asScoped(req).callAsCurrentUser, extraTypes), + }; + + const clientProvider = new SavedObjectsClientProvider({ defaultClientFactory({ request }) { - const repository = createSORepository(adminClient.asScoped(request).callAsCurrentUser); + const repository = repositoryFactory.createScopedRepository(request); return new SavedObjectsClient(repository); }, }); + if (this.clientFactoryProvider) { + const clientFactory = this.clientFactoryProvider(repositoryFactory); + clientProvider.setClientFactory(clientFactory); + } + this.clientFactoryWrappers.forEach(({ id, factory, priority }) => { + clientProvider.addClientWrapperFactory(priority, id, factory); + }); return { - getScopedClient: this.clientProvider.getClient.bind(this.clientProvider), - setClientFactory: this.clientProvider.setClientFactory.bind(this.clientProvider), - addClientWrapper: this.clientProvider.addClientWrapperFactory.bind(this.clientProvider), - createInternalRepository: (extraTypes?: string[]) => - createSORepository(adminClient.callAsInternalUser, extraTypes), - createScopedRepository: (req: KibanaRequest, extraTypes?: string[]) => - createSORepository(adminClient.asScoped(req).callAsCurrentUser, extraTypes), + migrator, + clientProvider, + getScopedClient: clientProvider.getClient.bind(clientProvider), + createScopedRepository: repositoryFactory.createScopedRepository, + createInternalRepository: repositoryFactory.createInternalRepository, }; } - public async start(core: SavedObjectsStartDeps): Promise { - if (!this.clientProvider) { - throw new Error('#setup() needs to be run first'); - } - - this.logger.debug('Starting SavedObjects service'); + public async stop() {} - /** - * Note: We want to ensure that migrations have completed before - * continuing with further Core startup steps that might use SavedObjects - * such as running the legacy server, legacy plugins and allowing incoming - * HTTP requests. - * - * However, our build system optimize step and some tests depend on the - * HTTP server running without an Elasticsearch server being available. - * So, when the `migrations.skip` is true, we skip migrations altogether. - */ - const cliArgs = this.coreContext.env.cliArgs; - const savedObjectsConfig = await this.coreContext.configService - .atPath('migrations') - .pipe(first()) - .toPromise(); - const skipMigrations = cliArgs.optimize || savedObjectsConfig.skip; - await this.migrator!.runMigrations(skipMigrations); + private createMigrator( + kibanaConfig: KibanaConfigType, + savedObjectsConfig: SavedObjectsConfigType, + migrationsRetryDelay?: number + ): KibanaMigrator { + const savedObjectSchemas = new SavedObjectsSchema(this.schemas); + const adminClient = this.setupDeps!.elasticsearch.adminClient; - return { - migrator: this.migrator!, - clientProvider: this.clientProvider, - getScopedClient: this.clientProvider.getClient.bind(this.clientProvider), - }; + return new KibanaMigrator({ + savedObjectSchemas, + savedObjectMappings: this.mappings, + savedObjectMigrations: this.migrations, + savedObjectValidations: this.validations, + logger: this.coreContext.logger.get('migrations'), + kibanaVersion: this.coreContext.env.packageInfo.version, + config: this.setupDeps!.legacyPlugins.pluginExtendedConfig, + savedObjectsConfig, + kibanaConfig, + callCluster: migrationsRetryCallCluster( + adminClient.callAsInternalUser, + this.coreContext.logger.get('migrations'), + migrationsRetryDelay + ), + }); } - - public async stop() {} } diff --git a/src/core/server/saved_objects/service/index.ts b/src/core/server/saved_objects/service/index.ts index f50ee1759dad7c..9f625b4732e264 100644 --- a/src/core/server/saved_objects/service/index.ts +++ b/src/core/server/saved_objects/service/index.ts @@ -29,13 +29,11 @@ import { SavedObjectsResolveImportErrorsOptions } from '../import/types'; * @internal * @deprecated */ -export interface SavedObjectsLegacyService { +export interface SavedObjectsLegacyService { // ATTENTION: these types are incomplete - addScopedSavedObjectsClientWrapperFactory: SavedObjectsClientProvider< - Request - >['addClientWrapperFactory']; - setScopedSavedObjectsClientFactory: SavedObjectsClientProvider['setClientFactory']; - getScopedSavedObjectsClient: SavedObjectsClientProvider['getClient']; + addScopedSavedObjectsClientWrapperFactory: SavedObjectsClientProvider['addClientWrapperFactory']; + setScopedSavedObjectsClientFactory: SavedObjectsClientProvider['setClientFactory']; + getScopedSavedObjectsClient: SavedObjectsClientProvider['getClient']; SavedObjectsClient: typeof SavedObjectsClient; types: string[]; schema: SavedObjectsSchema; @@ -59,6 +57,7 @@ export { SavedObjectsClientWrapperOptions, SavedObjectsErrorHelpers, SavedObjectsClientFactory, + SavedObjectsClientFactoryProvider, } from './lib'; export * from './saved_objects_client'; diff --git a/src/core/server/saved_objects/service/lib/index.ts b/src/core/server/saved_objects/service/lib/index.ts index c26128acc5050f..e103120388e354 100644 --- a/src/core/server/saved_objects/service/lib/index.ts +++ b/src/core/server/saved_objects/service/lib/index.ts @@ -26,6 +26,7 @@ export { SavedObjectsClientProvider, SavedObjectsClientProviderOptions, SavedObjectsClientFactory, + SavedObjectsClientFactoryProvider, } from './scoped_client_provider'; export { SavedObjectsErrorHelpers } from './errors'; diff --git a/src/core/server/saved_objects/service/lib/scoped_client_provider.ts b/src/core/server/saved_objects/service/lib/scoped_client_provider.ts index 42f75e25171264..8aadc4f57317c6 100644 --- a/src/core/server/saved_objects/service/lib/scoped_client_provider.ts +++ b/src/core/server/saved_objects/service/lib/scoped_client_provider.ts @@ -18,34 +18,44 @@ */ import { PriorityCollection } from './priority_collection'; import { SavedObjectsClientContract } from '../../types'; +import { SavedObjectsRepositoryFactory } from '../../saved_objects_service'; +import { KibanaRequest } from '../../../http'; /** * Options passed to each SavedObjectsClientWrapperFactory to aid in creating the wrapper instance. * @public */ -export interface SavedObjectsClientWrapperOptions { +export interface SavedObjectsClientWrapperOptions { client: SavedObjectsClientContract; - request: Request; + request: KibanaRequest; } /** * Describes the factory used to create instances of Saved Objects Client Wrappers. * @public */ -export type SavedObjectsClientWrapperFactory = ( - options: SavedObjectsClientWrapperOptions +export type SavedObjectsClientWrapperFactory = ( + options: SavedObjectsClientWrapperOptions ) => SavedObjectsClientContract; /** * Describes the factory used to create instances of the Saved Objects Client. * @public */ -export type SavedObjectsClientFactory = ({ +export type SavedObjectsClientFactory = ({ request, }: { - request: Request; + request: KibanaRequest; }) => SavedObjectsClientContract; +/** + * Provider to invoke to retrieve a {@link SavedObjectsClientFactory}. + * @public + */ +export type SavedObjectsClientFactoryProvider = ( + repositoryFactory: SavedObjectsRepositoryFactory +) => SavedObjectsClientFactory; + /** * Options to control the creation of the Saved Objects Client. * @public @@ -57,8 +67,8 @@ export interface SavedObjectsClientProviderOptions { /** * @internal */ -export type ISavedObjectsClientProvider = Pick< - SavedObjectsClientProvider, +export type ISavedObjectsClientProvider = Pick< + SavedObjectsClientProvider, keyof SavedObjectsClientProvider >; @@ -67,26 +77,22 @@ export type ISavedObjectsClientProvider = Pick< * * @internal */ -export class SavedObjectsClientProvider { +export class SavedObjectsClientProvider { private readonly _wrapperFactories = new PriorityCollection<{ id: string; - factory: SavedObjectsClientWrapperFactory; + factory: SavedObjectsClientWrapperFactory; }>(); - private _clientFactory: SavedObjectsClientFactory; - private readonly _originalClientFactory: SavedObjectsClientFactory; - - constructor({ - defaultClientFactory, - }: { - defaultClientFactory: SavedObjectsClientFactory; - }) { + private _clientFactory: SavedObjectsClientFactory; + private readonly _originalClientFactory: SavedObjectsClientFactory; + + constructor({ defaultClientFactory }: { defaultClientFactory: SavedObjectsClientFactory }) { this._originalClientFactory = this._clientFactory = defaultClientFactory; } addClientWrapperFactory( priority: number, id: string, - factory: SavedObjectsClientWrapperFactory + factory: SavedObjectsClientWrapperFactory ): void { if (this._wrapperFactories.has(entry => entry.id === id)) { throw new Error(`wrapper factory with id ${id} is already defined`); @@ -95,7 +101,7 @@ export class SavedObjectsClientProvider { this._wrapperFactories.add(priority, { id, factory }); } - setClientFactory(customClientFactory: SavedObjectsClientFactory) { + setClientFactory(customClientFactory: SavedObjectsClientFactory) { if (this._clientFactory !== this._originalClientFactory) { throw new Error(`custom client factory is already set, unable to replace the current one`); } @@ -104,7 +110,7 @@ export class SavedObjectsClientProvider { } getClient( - request: Request, + request: KibanaRequest, options: SavedObjectsClientProviderOptions = {} ): SavedObjectsClientContract { const client = this._clientFactory({ diff --git a/src/core/server/saved_objects/types.ts b/src/core/server/saved_objects/types.ts index dfce4a4c8ab189..a3fe2b937635bf 100644 --- a/src/core/server/saved_objects/types.ts +++ b/src/core/server/saved_objects/types.ts @@ -33,6 +33,13 @@ export { SavedObjectsImportRetry, } from './import/types'; +import { SavedObjectAttributes } from '../../types'; +export { + SavedObjectAttributes, + SavedObjectAttribute, + SavedObjectAttributeSingle, +} from '../../types'; + /** * Information about the migrations that have been applied to this SavedObject. * When Kibana starts up, KibanaMigrator detects outdated documents and @@ -52,36 +59,6 @@ export interface SavedObjectsMigrationVersion { [pluginName: string]: string; } -/** - * Don't use this type, it's simply a helper type for {@link SavedObjectAttribute} - * - * @public - */ -export type SavedObjectAttributeSingle = - | string - | number - | boolean - | null - | undefined - | SavedObjectAttributes; - -/** - * Type definition for a Saved Object attribute value - * - * @public - */ -export type SavedObjectAttribute = SavedObjectAttributeSingle | SavedObjectAttributeSingle[]; - -/** - * The data for a Saved Object is stored as an object in the `attributes` - * property. - * - * @public - */ -export interface SavedObjectAttributes { - [key: string]: SavedObjectAttribute; -} - /** * * @public diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index aa9ed8ecdbd40e..629e6a881199be 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -803,8 +803,6 @@ export interface IKibanaSocket { getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate | null; } -// Warning: (ae-missing-release-tag) "ImageValidation" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) -// // @public (undocumented) export interface ImageValidation { // (undocumented) @@ -1498,10 +1496,13 @@ export class SavedObjectsClient { export type SavedObjectsClientContract = Pick; // @public -export type SavedObjectsClientFactory = ({ request, }: { - request: Request; +export type SavedObjectsClientFactory = ({ request, }: { + request: KibanaRequest; }) => SavedObjectsClientContract; +// @public +export type SavedObjectsClientFactoryProvider = (repositoryFactory: SavedObjectsRepositoryFactory) => SavedObjectsClientFactory; + // @public export interface SavedObjectsClientProviderOptions { // (undocumented) @@ -1509,14 +1510,14 @@ export interface SavedObjectsClientProviderOptions { } // @public -export type SavedObjectsClientWrapperFactory = (options: SavedObjectsClientWrapperOptions) => SavedObjectsClientContract; +export type SavedObjectsClientWrapperFactory = (options: SavedObjectsClientWrapperOptions) => SavedObjectsClientContract; // @public -export interface SavedObjectsClientWrapperOptions { +export interface SavedObjectsClientWrapperOptions { // (undocumented) client: SavedObjectsClientContract; // (undocumented) - request: Request; + request: KibanaRequest; } // @public (undocumented) @@ -1752,15 +1753,15 @@ export interface SavedObjectsIncrementCounterOptions extends SavedObjectsBaseOpt } // @internal @deprecated (undocumented) -export interface SavedObjectsLegacyService { +export interface SavedObjectsLegacyService { // Warning: (ae-forgotten-export) The symbol "SavedObjectsClientProvider" needs to be exported by the entry point index.d.ts // // (undocumented) - addScopedSavedObjectsClientWrapperFactory: SavedObjectsClientProvider['addClientWrapperFactory']; + addScopedSavedObjectsClientWrapperFactory: SavedObjectsClientProvider['addClientWrapperFactory']; // (undocumented) getSavedObjectsRepository(...rest: any[]): any; // (undocumented) - getScopedSavedObjectsClient: SavedObjectsClientProvider['getClient']; + getScopedSavedObjectsClient: SavedObjectsClientProvider['getClient']; // (undocumented) importExport: { objectLimit: number; @@ -1773,7 +1774,7 @@ export interface SavedObjectsLegacyService { // (undocumented) schema: SavedObjectsSchema; // (undocumented) - setScopedSavedObjectsClientFactory: SavedObjectsClientProvider['setClientFactory']; + setScopedSavedObjectsClientFactory: SavedObjectsClientProvider['setClientFactory']; // (undocumented) types: string[]; } @@ -1836,6 +1837,12 @@ export class SavedObjectsRepository { update(type: string, id: string, attributes: Partial, options?: SavedObjectsUpdateOptions): Promise>; } +// @public +export interface SavedObjectsRepositoryFactory { + createInternalRepository: (extraTypes?: string[]) => ISavedObjectsRepository; + createScopedRepository: (req: KibanaRequest, extraTypes?: string[]) => ISavedObjectsRepository; +} + // @public export interface SavedObjectsResolveImportErrorsOptions { // (undocumented) @@ -1878,14 +1885,14 @@ export class SavedObjectsSerializer { // @public export interface SavedObjectsServiceSetup { - addClientWrapper: (priority: number, id: string, factory: SavedObjectsClientWrapperFactory) => void; - createInternalRepository: (extraTypes?: string[]) => ISavedObjectsRepository; - createScopedRepository: (req: KibanaRequest, extraTypes?: string[]) => ISavedObjectsRepository; - setClientFactory: (customClientFactory: SavedObjectsClientFactory) => void; + addClientWrapper: (priority: number, id: string, factory: SavedObjectsClientWrapperFactory) => void; + setClientFactoryProvider: (clientFactoryProvider: SavedObjectsClientFactoryProvider) => void; } // @public export interface SavedObjectsServiceStart { + createInternalRepository: (extraTypes?: string[]) => ISavedObjectsRepository; + createScopedRepository: (req: KibanaRequest, extraTypes?: string[]) => ISavedObjectsRepository; getScopedClient: (req: KibanaRequest, options?: SavedObjectsClientProviderOptions) => SavedObjectsClientContract; } @@ -1948,10 +1955,19 @@ export type SharedGlobalConfig = RecursiveReadonly_2<{ path: Pick; }>; -// Warning: (ae-missing-release-tag) "StringValidation" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) -// -// @public (undocumented) -export interface StringValidation { +// @public +export type StringValidation = StringValidationRegex | StringValidationRegexString; + +// @public +export interface StringValidationRegex { + // (undocumented) + message: string; + // (undocumented) + regex: RegExp; +} + +// @public +export interface StringValidationRegexString { // (undocumented) message: string; // (undocumented) @@ -1985,7 +2001,7 @@ export interface UiSettingsServiceStart { } // @public -export type UiSettingsType = 'json' | 'markdown' | 'number' | 'select' | 'boolean' | 'string'; +export type UiSettingsType = 'undefined' | 'json' | 'markdown' | 'number' | 'select' | 'boolean' | 'string' | 'array' | 'image'; // @public export interface UserProvidedValues { diff --git a/src/core/server/server.ts b/src/core/server/server.ts index 89a5bdc4802fd9..96adb3bbcd2104 100644 --- a/src/core/server/server.ts +++ b/src/core/server/server.ts @@ -47,7 +47,7 @@ import { config as uiSettingsConfig } from './ui_settings'; import { mapToObject } from '../utils'; import { ContextService } from './context'; import { RequestHandlerContext } from '.'; -import { InternalCoreSetup } from './internal_types'; +import { InternalCoreSetup, InternalCoreStart } from './internal_types'; import { CapabilitiesService } from './capabilities'; import { UuidService } from './uuid'; @@ -68,6 +68,8 @@ export class Server { private readonly uiSettings: UiSettingsService; private readonly uuid: UuidService; + private coreStart?: InternalCoreStart; + constructor( rawConfigProvider: RawConfigurationProvider, public readonly env: Env, @@ -174,21 +176,24 @@ export class Server { uiSettings: uiSettingsStart, }); - const coreStart = { + this.coreStart = { capabilities: capabilitiesStart, savedObjects: savedObjectsStart, uiSettings: uiSettingsStart, - plugins: pluginsStart, }; + await this.legacy.start({ - core: coreStart, + core: { + ...this.coreStart, + plugins: pluginsStart, + }, plugins: mapToObject(pluginsStart.contracts), }); await this.http.start(); await this.rendering.start(); - return coreStart; + return this.coreStart; } public async stop() { @@ -215,7 +220,7 @@ export class Server { coreId, 'core', async (context, req, res): Promise => { - const savedObjectsClient = coreSetup.savedObjects.getScopedClient(req); + const savedObjectsClient = this.coreStart!.savedObjects.getScopedClient(req); const uiSettingsClient = coreSetup.uiSettings.asScopedToClient(savedObjectsClient); return { diff --git a/src/core/server/ui_settings/create_or_upgrade_saved_config/integration_tests/create_or_upgrade.test.ts b/src/core/server/ui_settings/create_or_upgrade_saved_config/integration_tests/create_or_upgrade.test.ts index f7dbf992e87286..218de8e7acb3ae 100644 --- a/src/core/server/ui_settings/create_or_upgrade_saved_config/integration_tests/create_or_upgrade.test.ts +++ b/src/core/server/ui_settings/create_or_upgrade_saved_config/integration_tests/create_or_upgrade.test.ts @@ -27,6 +27,7 @@ import { } from '../../../../../test_utils/kbn_server'; import { createOrUpgradeSavedConfig } from '../create_or_upgrade_saved_config'; import { loggingServiceMock } from '../../../logging/logging_service.mock'; +import { httpServerMock } from '../../../http/http_server.mocks'; const logger = loggingServiceMock.create().get(); describe('createOrUpgradeSavedConfig()', () => { @@ -48,7 +49,9 @@ describe('createOrUpgradeSavedConfig()', () => { kbnServer = kbn.kbnServer; const savedObjects = kbnServer.server.savedObjects; - savedObjectsClient = savedObjects.getScopedSavedObjectsClient({}); + savedObjectsClient = savedObjects.getScopedSavedObjectsClient( + httpServerMock.createKibanaRequest() + ); await savedObjectsClient.bulkCreate([ { diff --git a/src/core/server/ui_settings/index.ts b/src/core/server/ui_settings/index.ts index 39eb0046010b38..ddb66df3ffcbe1 100644 --- a/src/core/server/ui_settings/index.ts +++ b/src/core/server/ui_settings/index.ts @@ -34,4 +34,6 @@ export { ImageValidation, DeprecationSettings, StringValidation, + StringValidationRegex, + StringValidationRegexString, } from './types'; diff --git a/src/core/server/ui_settings/integration_tests/lib/servers.ts b/src/core/server/ui_settings/integration_tests/lib/servers.ts index 1abe6dc2d06838..57448541d68c58 100644 --- a/src/core/server/ui_settings/integration_tests/lib/servers.ts +++ b/src/core/server/ui_settings/integration_tests/lib/servers.ts @@ -26,6 +26,7 @@ import { TestUtils, } from '../../../../../test_utils/kbn_server'; import { APICaller } from '../../../elasticsearch/'; +import { httpServerMock } from '../../../http/http_server.mocks'; let servers: TestUtils; let esServer: TestElasticsearchUtils; @@ -83,7 +84,9 @@ export function getServices() { const callCluster = esServer.es.getCallCluster(); const savedObjects = kbnServer.server.savedObjects; - const savedObjectsClient = savedObjects.getScopedSavedObjectsClient({}); + const savedObjectsClient = savedObjects.getScopedSavedObjectsClient( + httpServerMock.createKibanaRequest() + ); const uiSettings = kbnServer.server.uiSettingsServiceFactory({ savedObjectsClient, diff --git a/src/core/server/ui_settings/types.ts b/src/core/server/ui_settings/types.ts index a74a31bbbd671a..f3eb1f5a6859cc 100644 --- a/src/core/server/ui_settings/types.ts +++ b/src/core/server/ui_settings/types.ts @@ -16,7 +16,19 @@ * specific language governing permissions and limitations * under the License. */ -import { SavedObjectsClientContract, SavedObjectAttribute } from '../saved_objects/types'; +import { SavedObjectsClientContract } from '../saved_objects/types'; +import { UiSettingsParams, UserProvidedValues } from '../../types'; +export { + UiSettingsParams, + StringValidationRegexString, + StringValidationRegex, + StringValidation, + DeprecationSettings, + ImageValidation, + UiSettingsType, + UserProvidedValues, +} from '../../types'; + /** * Server-side client that provides access to the advanced settings stored in elasticsearch. * The settings provide control over the behavior of the Kibana application. @@ -64,76 +76,6 @@ export interface IUiSettingsClient { isOverridden: (key: string) => boolean; } -/** - * Describes the values explicitly set by user. - * @public - * */ -export interface UserProvidedValues { - userValue?: T; - isOverridden?: boolean; -} - -/** - * UiSettings deprecation field options. - * @public - * */ -export interface DeprecationSettings { - /** Deprecation message */ - message: string; - /** Key to documentation links */ - docLinksKey: string; -} - -/** - * UI element type to represent the settings. - * @public - * */ -export type UiSettingsType = 'json' | 'markdown' | 'number' | 'select' | 'boolean' | 'string'; - -/** - * UiSettings parameters defined by the plugins. - * @public - * */ -export interface UiSettingsParams { - /** title in the UI */ - name?: string; - /** default value to fall back to if a user doesn't provide any */ - value?: SavedObjectAttribute; - /** description provided to a user in UI */ - description?: string; - /** used to group the configured setting in the UI */ - category?: string[]; - /** array of permitted values for this setting */ - options?: string[]; - /** text labels for 'select' type UI element */ - optionLabels?: Record; - /** a flag indicating whether new value applying requires page reloading */ - requiresPageReload?: boolean; - /** a flag indicating that value cannot be changed */ - readonly?: boolean; - /** defines a type of UI element {@link UiSettingsType} */ - type?: UiSettingsType; - /** optional deprecation information. Used to generate a deprecation warning. */ - deprecation?: DeprecationSettings; - /* - * Allows defining a custom validation applicable to value change on the client. - * @deprecated - */ - validation?: ImageValidation | StringValidation; -} - -export interface StringValidation { - regexString: string; - message: string; -} - -export interface ImageValidation { - maxSize: { - length: number; - description: string; - }; -} - /** @internal */ export interface InternalUiSettingsServiceSetup { /** diff --git a/src/core/types/index.ts b/src/core/types/index.ts index 7ddb6b0d8dfbbc..346b4cfce70c1a 100644 --- a/src/core/types/index.ts +++ b/src/core/types/index.ts @@ -24,3 +24,5 @@ export * from './core_service'; export * from './capabilities'; export * from './app_category'; +export * from './ui_settings'; +export * from './saved_objects'; diff --git a/src/core/types/saved_objects.ts b/src/core/types/saved_objects.ts new file mode 100644 index 00000000000000..73eb2db11d62fb --- /dev/null +++ b/src/core/types/saved_objects.ts @@ -0,0 +1,48 @@ +/* + * 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. + */ + +/** + * Don't use this type, it's simply a helper type for {@link SavedObjectAttribute} + * + * @public + */ +export type SavedObjectAttributeSingle = + | string + | number + | boolean + | null + | undefined + | SavedObjectAttributes; + +/** + * Type definition for a Saved Object attribute value + * + * @public + */ +export type SavedObjectAttribute = SavedObjectAttributeSingle | SavedObjectAttributeSingle[]; + +/** + * The data for a Saved Object is stored as an object in the `attributes` + * property. + * + * @public + */ +export interface SavedObjectAttributes { + [key: string]: SavedObjectAttribute; +} diff --git a/src/core/types/ui_settings.ts b/src/core/types/ui_settings.ts new file mode 100644 index 00000000000000..eccd3f9616af07 --- /dev/null +++ b/src/core/types/ui_settings.ts @@ -0,0 +1,121 @@ +/* + * 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 { SavedObjectAttribute } from './saved_objects'; + +/** + * UI element type to represent the settings. + * @public + * */ +export type UiSettingsType = + | 'undefined' // I don't know why malformed UiSettings objects exist + | 'json' + | 'markdown' + | 'number' + | 'select' + | 'boolean' + | 'string' + | 'array' + | 'image'; + +/** + * UiSettings deprecation field options. + * @public + * */ +export interface DeprecationSettings { + /** Deprecation message */ + message: string; + /** Key to documentation links */ + docLinksKey: string; +} + +/** + * UiSettings parameters defined by the plugins. + * @public + * */ +export interface UiSettingsParams { + /** title in the UI */ + name?: string; + /** default value to fall back to if a user doesn't provide any */ + value?: SavedObjectAttribute; + /** description provided to a user in UI */ + description?: string; + /** used to group the configured setting in the UI */ + category?: string[]; + /** array of permitted values for this setting */ + options?: string[]; + /** text labels for 'select' type UI element */ + optionLabels?: Record; + /** a flag indicating whether new value applying requires page reloading */ + requiresPageReload?: boolean; + /** a flag indicating that value cannot be changed */ + readonly?: boolean; + /** defines a type of UI element {@link UiSettingsType} */ + type?: UiSettingsType; + /** optional deprecation information. Used to generate a deprecation warning. */ + deprecation?: DeprecationSettings; + /* + * Allows defining a custom validation applicable to value change on the client. + * @deprecated + */ + validation?: ImageValidation | StringValidation; +} + +/** + * Allows regex objects or a regex string + * @public + * */ +export type StringValidation = StringValidationRegex | StringValidationRegexString; + +/** + * StringValidation with regex object + * @public + * */ +export interface StringValidationRegex { + regex: RegExp; + message: string; +} + +/** + * StringValidation as regex string + * @public + * */ +export interface StringValidationRegexString { + regexString: string; + message: string; +} + +/** + * @public + * */ +export interface ImageValidation { + maxSize: { + length: number; + description: string; + }; +} + +/** + * Describes the values explicitly set by user. + * @public + * */ +export interface UserProvidedValues { + userValue?: T; + isOverridden?: boolean; +} diff --git a/src/legacy/core_plugins/console/public/np_ready/application/styles/_app.scss b/src/legacy/core_plugins/console/public/np_ready/application/styles/_app.scss index c69440225236b0..b89a43f7455a54 100644 --- a/src/legacy/core_plugins/console/public/np_ready/application/styles/_app.scss +++ b/src/legacy/core_plugins/console/public/np_ready/application/styles/_app.scss @@ -27,6 +27,9 @@ // Required on IE11 to render ace editor correctly after first input. position: relative; + // Give the aria selection border priority when the divider is selected + z-index: 0; + &__spinner { width: 100%; } @@ -35,6 +38,8 @@ .conApp__output { display: flex; flex: 1 1 1px; + // Give the aria selection border priority when the divider is selected + z-index: -1; } .conApp__textAreaLabelHack, diff --git a/src/legacy/core_plugins/kibana/public/home/tutorial_resources/logos/statsd.svg b/src/legacy/core_plugins/kibana/public/home/tutorial_resources/logos/statsd.svg new file mode 100644 index 00000000000000..f4458439fceb4b --- /dev/null +++ b/src/legacy/core_plugins/kibana/public/home/tutorial_resources/logos/statsd.svg @@ -0,0 +1,41 @@ + + + + + + + + + + diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/__snapshots__/advanced_settings.test.js.snap b/src/legacy/core_plugins/kibana/public/management/sections/settings/__snapshots__/advanced_settings.test.js.snap deleted file mode 100644 index eef8f3fc93d90f..00000000000000 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/__snapshots__/advanced_settings.test.js.snap +++ /dev/null @@ -1,1022 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`AdvancedSettings should render normally 1`] = ` -
- - - - - - - - - - - - - -
- -
-`; - -exports[`AdvancedSettings should render read-only when saving is disabled 1`] = ` -
- - - - - - - - - - - - - - - -
-`; - -exports[`AdvancedSettings should render specific setting if given setting key 1`] = ` -
- - - - - - - - - - - - - - - -
-`; diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/__snapshots__/advanced_settings.test.tsx.snap b/src/legacy/core_plugins/kibana/public/management/sections/settings/__snapshots__/advanced_settings.test.tsx.snap new file mode 100644 index 00000000000000..4814432c832e2f --- /dev/null +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/__snapshots__/advanced_settings.test.tsx.snap @@ -0,0 +1,367 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`AdvancedSettings should render read-only when saving is disabled 1`] = ` +
+ + + + + + + + + + + + + + + +
+`; + +exports[`AdvancedSettings should render specific setting if given setting key 1`] = ` +
+ + + + + + + + + + + + + + + +
+`; diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/advanced_settings.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/advanced_settings.test.js deleted file mode 100644 index 94128dc5271de1..00000000000000 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/advanced_settings.test.js +++ /dev/null @@ -1,173 +0,0 @@ -/* - * 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 React from 'react'; -import { shallow } from 'enzyme'; -import dedent from 'dedent'; - -import { AdvancedSettings } from './advanced_settings'; - -jest.mock('./components/field', () => ({ - Field: () => { - return 'field'; - }, -})); - -jest.mock('./components/call_outs', () => ({ - CallOuts: () => { - return 'callOuts'; - }, -})); - -jest.mock('./components/search', () => ({ - Search: () => { - return 'search'; - }, -})); - -const config = { - set: () => {}, - remove: () => {}, - isCustom: setting => setting.isCustom, - isOverridden: key => Boolean(config.getAll()[key].isOverridden), - getAll: () => { - return { - 'test:array:setting': { - value: ['default_value'], - name: 'Test array setting', - description: 'Description for Test array setting', - category: ['elasticsearch'], - }, - 'test:boolean:setting': { - value: true, - name: 'Test boolean setting', - description: 'Description for Test boolean setting', - category: ['elasticsearch'], - }, - 'test:image:setting': { - value: null, - name: 'Test image setting', - description: 'Description for Test image setting', - type: 'image', - }, - 'test:json:setting': { - value: '{"foo": "bar"}', - name: 'Test json setting', - description: 'Description for Test json setting', - type: 'json', - }, - 'test:markdown:setting': { - value: '', - name: 'Test markdown setting', - description: 'Description for Test markdown setting', - type: 'markdown', - }, - 'test:number:setting': { - value: 5, - name: 'Test number setting', - description: 'Description for Test number setting', - }, - 'test:select:setting': { - value: 'orange', - name: 'Test select setting', - description: 'Description for Test select setting', - type: 'select', - options: ['apple', 'orange', 'banana'], - }, - 'test:string:setting': { - value: null, - name: 'Test string setting', - description: 'Description for Test string setting', - type: 'string', - isCustom: true, - }, - 'test:readonlystring:setting': { - value: null, - name: 'Test readonly string setting', - description: 'Description for Test readonly string setting', - type: 'string', - readonly: true, - }, - 'test:customstring:setting': { - value: null, - name: 'Test custom string setting', - description: 'Description for Test custom string setting', - type: 'string', - isCustom: true, - }, - 'test:isOverridden:string': { - isOverridden: true, - value: 'foo', - name: 'An overridden string', - description: 'Description for overridden string', - type: 'string', - }, - 'test:isOverridden:number': { - isOverridden: true, - value: 1234, - name: 'An overridden number', - description: 'Description for overridden number', - type: 'number', - }, - 'test:isOverridden:json': { - isOverridden: true, - value: dedent` - { - "foo": "bar" - } - `, - name: 'An overridden json', - description: 'Description for overridden json', - type: 'json', - }, - 'test:isOverridden:select': { - isOverridden: true, - value: 'orange', - name: 'Test overridden select setting', - description: 'Description for overridden select setting', - type: 'select', - options: ['apple', 'orange', 'banana'], - }, - }; - }, -}; - -describe('AdvancedSettings', () => { - it('should render normally', async () => { - const component = shallow(); - - expect(component).toMatchSnapshot(); - }); - - it('should render specific setting if given setting key', async () => { - const component = shallow( - - ); - - expect(component).toMatchSnapshot(); - }); - - it('should render read-only when saving is disabled', async () => { - const component = shallow( - - ); - - expect(component).toMatchSnapshot(); - }); -}); diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/advanced_settings.test.tsx b/src/legacy/core_plugins/kibana/public/management/sections/settings/advanced_settings.test.tsx new file mode 100644 index 00000000000000..2a75c98b721bca --- /dev/null +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/advanced_settings.test.tsx @@ -0,0 +1,237 @@ +/* + * 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 React from 'react'; +import { Observable } from 'rxjs'; +import { shallow } from 'enzyme'; +import dedent from 'dedent'; +import { + UiSettingsParams, + UserProvidedValues, + UiSettingsType, +} from '../../../../../../../core/public'; +import { FieldSetting } from './types'; +import { AdvancedSettings } from './advanced_settings'; + +jest.mock('ui/new_platform', () => ({ + npStart: mockConfig(), +})); + +jest.mock('./components/field', () => ({ + Field: () => { + return 'field'; + }, +})); + +jest.mock('./components/call_outs', () => ({ + CallOuts: () => { + return 'callOuts'; + }, +})); + +jest.mock('./components/search', () => ({ + Search: () => { + return 'search'; + }, +})); + +function mockConfig() { + const defaultConfig: Partial = { + displayName: 'defaultName', + requiresPageReload: false, + isOverridden: false, + ariaName: 'ariaName', + readOnly: false, + isCustom: false, + defVal: 'defVal', + type: 'string' as UiSettingsType, + category: ['category'], + }; + + const config = { + set: (key: string, value: any) => Promise.resolve(true), + remove: (key: string) => Promise.resolve(true), + isCustom: (key: string) => false, + isOverridden: (key: string) => Boolean(config.getAll()[key].isOverridden), + getRegistered: () => ({} as Readonly>), + overrideLocalDefault: (key: string, value: any) => {}, + getUpdate$: () => + new Observable<{ + key: string; + newValue: any; + oldValue: any; + }>(), + isDeclared: (key: string) => true, + isDefault: (key: string) => true, + + getSaved$: () => + new Observable<{ + key: string; + newValue: any; + oldValue: any; + }>(), + + getUpdateErrors$: () => new Observable(), + get: (key: string, defaultOverride?: any): any => config.getAll()[key] || defaultOverride, + get$: (key: string) => new Observable(config.get(key)), + getAll: (): Readonly> => { + return { + 'test:array:setting': { + ...defaultConfig, + value: ['default_value'], + name: 'Test array setting', + description: 'Description for Test array setting', + category: ['elasticsearch'], + }, + 'test:boolean:setting': { + ...defaultConfig, + value: true, + name: 'Test boolean setting', + description: 'Description for Test boolean setting', + category: ['elasticsearch'], + }, + 'test:image:setting': { + ...defaultConfig, + value: null, + name: 'Test image setting', + description: 'Description for Test image setting', + type: 'image', + }, + 'test:json:setting': { + ...defaultConfig, + value: '{"foo": "bar"}', + name: 'Test json setting', + description: 'Description for Test json setting', + type: 'json', + }, + 'test:markdown:setting': { + ...defaultConfig, + value: '', + name: 'Test markdown setting', + description: 'Description for Test markdown setting', + type: 'markdown', + }, + 'test:number:setting': { + ...defaultConfig, + value: 5, + name: 'Test number setting', + description: 'Description for Test number setting', + }, + 'test:select:setting': { + ...defaultConfig, + value: 'orange', + name: 'Test select setting', + description: 'Description for Test select setting', + type: 'select', + options: ['apple', 'orange', 'banana'], + }, + 'test:string:setting': { + ...defaultConfig, + ...{ + value: null, + name: 'Test string setting', + description: 'Description for Test string setting', + type: 'string', + isCustom: true, + }, + }, + 'test:readonlystring:setting': { + ...defaultConfig, + ...{ + value: null, + name: 'Test readonly string setting', + description: 'Description for Test readonly string setting', + type: 'string', + readOnly: true, + }, + }, + 'test:customstring:setting': { + ...defaultConfig, + ...{ + value: null, + name: 'Test custom string setting', + description: 'Description for Test custom string setting', + type: 'string', + isCustom: true, + }, + }, + 'test:isOverridden:string': { + ...defaultConfig, + isOverridden: true, + value: 'foo', + name: 'An overridden string', + description: 'Description for overridden string', + type: 'string', + }, + 'test:isOverridden:number': { + ...defaultConfig, + isOverridden: true, + value: 1234, + name: 'An overridden number', + description: 'Description for overridden number', + type: 'number', + }, + 'test:isOverridden:json': { + ...defaultConfig, + isOverridden: true, + value: dedent` + { + "foo": "bar" + } + `, + name: 'An overridden json', + description: 'Description for overridden json', + type: 'json', + }, + 'test:isOverridden:select': { + ...defaultConfig, + isOverridden: true, + value: 'orange', + name: 'Test overridden select setting', + description: 'Description for overridden select setting', + type: 'select', + options: ['apple', 'orange', 'banana'], + }, + }; + }, + }; + return { + core: { + uiSettings: config, + }, + }; +} + +describe('AdvancedSettings', () => { + it('should render specific setting if given setting key', async () => { + const component = shallow( + + ); + + expect(component).toMatchSnapshot(); + }); + + it('should render read-only when saving is disabled', async () => { + const component = shallow( + + ); + + expect(component).toMatchSnapshot(); + }); +}); diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/advanced_settings.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/advanced_settings.tsx similarity index 62% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/advanced_settings.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/advanced_settings.tsx index 508e05bbf9bb40..569ef73f2b4536 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/advanced_settings.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/advanced_settings.tsx @@ -18,17 +18,19 @@ */ import React, { Component } from 'react'; -import PropTypes from 'prop-types'; - import { Comparators, EuiFlexGroup, EuiFlexItem, EuiSpacer, Query } from '@elastic/eui'; +import { npStart } from 'ui/new_platform'; import { CallOuts } from './components/call_outs'; import { Search } from './components/search'; import { Form } from './components/form'; import { AdvancedSettingsVoiceAnnouncement } from './components/advanced_settings_voice_announcement'; +import { IUiSettingsClient } from '../../../../../../../core/public/'; import { getAriaName, toEditableConfig, DEFAULT_CATEGORY } from './lib'; +import { FieldSetting, IQuery } from './types'; + import { registerDefaultComponents, PAGE_TITLE_COMPONENT, @@ -37,18 +39,37 @@ import { } from './components/default_component_registry'; import { getSettingsComponent } from './components/component_registry'; -export class AdvancedSettings extends Component { - static propTypes = { - config: PropTypes.object.isRequired, - query: PropTypes.string, - enableSaving: PropTypes.bool.isRequired, - }; +interface AdvancedSettingsProps { + queryText: string; + enableSaving: boolean; +} + +interface AdvancedSettingsState { + footerQueryMatched: boolean; + query: IQuery; + filteredSettings: Record; +} - constructor(props) { +type GroupedSettings = Record; + +export class AdvancedSettings extends Component { + private config: IUiSettingsClient; + private settings: FieldSetting[]; + private groupedSettings: GroupedSettings; + private categoryCounts: Record; + private categories: string[] = []; + + constructor(props: AdvancedSettingsProps) { super(props); - const { config, query } = this.props; - const parsedQuery = Query.parse(query ? `ariaName:"${getAriaName(query)}"` : ''); - this.init(config); + const { queryText } = this.props; + const parsedQuery = Query.parse(queryText ? `ariaName:"${getAriaName(queryText)}"` : ''); + + this.config = npStart.core.uiSettings; + this.settings = this.initSettings(this.config); + this.groupedSettings = this.initGroupedSettings(this.settings); + this.categories = this.initCategories(this.groupedSettings); + this.categoryCounts = this.initCategoryCounts(this.groupedSettings); + this.state = { query: parsedQuery, footerQueryMatched: false, @@ -58,34 +79,44 @@ export class AdvancedSettings extends Component { registerDefaultComponents(); } - init(config) { - this.settings = this.mapConfig(config); - this.groupedSettings = this.mapSettings(this.settings); + init(config: IUiSettingsClient) { + this.settings = this.initSettings(config); + this.groupedSettings = this.initGroupedSettings(this.settings); + this.categories = this.initCategories(this.groupedSettings); + this.categoryCounts = this.initCategoryCounts(this.groupedSettings); + } - this.categories = Object.keys(this.groupedSettings).sort((a, b) => { + initSettings = this.mapConfig; + initGroupedSettings = this.mapSettings; + initCategories(groupedSettings: GroupedSettings) { + return Object.keys(groupedSettings).sort((a, b) => { if (a === DEFAULT_CATEGORY) return -1; if (b === DEFAULT_CATEGORY) return 1; if (a > b) return 1; return a === b ? 0 : -1; }); - - this.categoryCounts = Object.keys(this.groupedSettings).reduce((counts, category) => { - counts[category] = this.groupedSettings[category].length; - return counts; - }, {}); + } + initCategoryCounts(groupedSettings: GroupedSettings) { + return Object.keys(groupedSettings).reduce( + (counts: Record, category: string) => { + counts[category] = groupedSettings[category].length; + return counts; + }, + {} + ); } - UNSAFE_componentWillReceiveProps(nextProps) { - const { config } = nextProps; - const { query } = this.state; - - this.init(config); - this.setState({ - filteredSettings: this.mapSettings(Query.execute(query, this.settings)), + componentDidMount() { + this.config.getUpdate$().subscribe(() => { + const { query } = this.state; + this.init(this.config); + this.setState({ + filteredSettings: this.mapSettings(Query.execute(query, this.settings)), + }); }); } - mapConfig(config) { + mapConfig(config: IUiSettingsClient) { const all = config.getAll(); return Object.entries(all) .map(setting => { @@ -101,9 +132,9 @@ export class AdvancedSettings extends Component { .sort(Comparators.property('name', Comparators.default('asc'))); } - mapSettings(settings) { + mapSettings(settings: FieldSetting[]) { // Group settings by category - return settings.reduce((groupedSettings, setting) => { + return settings.reduce((groupedSettings: GroupedSettings, setting) => { // We will want to change this logic when we put each category on its // own page aka allowing a setting to be included in multiple categories. const category = setting.category[0]; @@ -112,15 +143,7 @@ export class AdvancedSettings extends Component { }, {}); } - saveConfig = (name, value) => { - return this.props.config.set(name, value); - }; - - clearConfig = name => { - return this.props.config.remove(name); - }; - - onQueryChange = ({ query }) => { + onQueryChange = ({ query }: { query: IQuery }) => { this.setState({ query, filteredSettings: this.mapSettings(Query.execute(query, this.settings)), @@ -135,7 +158,7 @@ export class AdvancedSettings extends Component { }); }; - onFooterQueryMatchChange = matched => { + onFooterQueryMatchChange = (matched: boolean) => { this.setState({ footerQueryMatched: matched, }); @@ -170,8 +193,8 @@ export class AdvancedSettings extends Component { categories={this.categories} categoryCounts={this.categoryCounts} clearQuery={this.clearQuery} - save={this.saveConfig} - clear={this.clearConfig} + save={this.config.set.bind(this.config)} + clear={this.config.remove.bind(this.config)} showNoResultsMessage={!footerQueryMatched} enableSaving={this.props.enableSaving} /> diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/breadcrumbs.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/breadcrumbs.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/breadcrumbs.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/breadcrumbs.ts diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/__snapshots__/component_registry.test.js.snap b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/__snapshots__/component_registry.test.tsx.snap similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/__snapshots__/component_registry.test.js.snap rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/__snapshots__/component_registry.test.tsx.snap diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/__snapshots__/advanced_settings_voice_announcement.test.js.snap b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/__snapshots__/advanced_settings_voice_announcement.test.tsx.snap similarity index 95% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/__snapshots__/advanced_settings_voice_announcement.test.js.snap rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/__snapshots__/advanced_settings_voice_announcement.test.tsx.snap index 049e4530b795f9..e8c8184cf7e57c 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/__snapshots__/advanced_settings_voice_announcement.test.js.snap +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/__snapshots__/advanced_settings_voice_announcement.test.tsx.snap @@ -15,7 +15,7 @@ exports[`Advanced Settings: Voice Announcement should render announcement 1`] = values={ Object { "optionLenght": 1, - "query": undefined, + "query": "dark theme", "sectionLenght": 1, } } @@ -40,7 +40,7 @@ exports[`Advanced Settings: Voice Announcement should render nothing 1`] = ` values={ Object { "optionLenght": 1, - "query": undefined, + "query": "", "sectionLenght": 1, } } diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.test.tsx similarity index 66% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.test.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.test.tsx index 41b16c5cbda711..66f2d4e784630f 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.test.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.test.tsx @@ -19,28 +19,44 @@ import React from 'react'; import { shallow } from 'enzyme'; +import { UiSettingsType } from '../../../../../../../../../core/public'; import { AdvancedSettingsVoiceAnnouncement } from './advanced_settings_voice_announcement'; +const settingPartial = { + name: 'name', + isOverridden: false, + type: 'string' as UiSettingsType, + value: 'value', + defVal: 'defVal', + optionLabels: { label: 'label' }, + description: 'description', + displayName: 'displayName', + isCustom: false, + requiresPageReload: false, + options: [], + validation: { regex: /a/, message: 'message' }, + category: ['category'], + readOnly: false, +}; + const testProps = { nothing: { query: '', filteredSettings: [ - [ - { - ariaName: 'General', - }, - ], + { + ariaName: 'General', + ...settingPartial, + }, ], }, searchResult: { query: 'dark theme', filteredSettings: [ - [ - { - ariaName: 'General', - }, - ], + { + ariaName: 'General', + ...settingPartial, + }, ], }, }; @@ -50,7 +66,7 @@ describe('Advanced Settings: Voice Announcement', () => { const { query, filteredSettings } = testProps.nothing; const component = shallow( - + ); expect(component).toMatchSnapshot(); @@ -60,7 +76,7 @@ describe('Advanced Settings: Voice Announcement', () => { const { query, filteredSettings } = testProps.searchResult; const component = shallow( - + ); expect(component).toMatchSnapshot(); diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.tsx similarity index 92% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.tsx index 34625e1ce5114f..01f1388ba1eef5 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.tsx @@ -40,9 +40,15 @@ import React, { Component } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; import { EuiScreenReaderOnly, EuiDelayRender } from '@elastic/eui'; +import { FieldSetting } from '../../types'; -export class AdvancedSettingsVoiceAnnouncement extends Component { - shouldComponentUpdate = nextProps => { +interface Props { + queryText: string; + settings: Record; +} + +export class AdvancedSettingsVoiceAnnouncement extends Component { + shouldComponentUpdate = (nextProps: Props) => { /* If a user typed smth new, we should clear the previous timer and start another one + block component rendering. @@ -57,7 +63,7 @@ export class AdvancedSettingsVoiceAnnouncement extends Component { const filteredSections = Object.values(this.props.settings).map(setting => setting.map(option => option.ariaName) ); - const filteredOptions = [].concat(...filteredSections); + const filteredOptions = [...filteredSections]; return (
diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/index.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/index.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/index.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/advanced_settings_voice_announcement/index.ts diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/__snapshots__/call_outs.test.js.snap b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/__snapshots__/call_outs.test.tsx.snap similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/__snapshots__/call_outs.test.js.snap rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/__snapshots__/call_outs.test.tsx.snap diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/call_outs.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/call_outs.test.tsx similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/call_outs.test.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/call_outs.test.tsx diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/call_outs.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/call_outs.tsx similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/call_outs.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/call_outs.tsx diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/index.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/index.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/index.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/call_outs/index.ts diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/component_registry.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/component_registry.test.tsx similarity index 74% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/component_registry.test.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/component_registry.test.tsx index fb3365a102fde6..24e9e5dd3809c8 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/component_registry.test.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/component_registry.test.tsx @@ -17,6 +17,7 @@ * under the License. */ +import React, { FunctionComponent } from 'react'; import { tryRegisterSettingsComponent, registerSettingsComponent, @@ -25,15 +26,15 @@ import { describe('tryRegisterSettingsComponent', () => { it('should allow a component to be registered', () => { - const component = {}; + const component = () =>
; expect(tryRegisterSettingsComponent('tryTest1', component)).toEqual(true); }); it('should return false if the component is already registered, and not allow an override', () => { - const component = {}; + const component = () =>
; expect(tryRegisterSettingsComponent('tryTest2', component)).toEqual(true); - const updatedComponent = { updated: 'yay' }; + const updatedComponent = () =>
; expect(tryRegisterSettingsComponent('tryTest2', updatedComponent)).toEqual(false); expect(getSettingsComponent('tryTest2')).toBe(component); }); @@ -41,49 +42,36 @@ describe('tryRegisterSettingsComponent', () => { describe('registerSettingsComponent', () => { it('should allow a component to be registered', () => { - const component = {}; + const component = () =>
; registerSettingsComponent('test', component); }); it('should disallow registering a component with a duplicate id', () => { - const component = {}; + const component = () =>
; registerSettingsComponent('test2', component); - expect(() => - registerSettingsComponent('test2', 'some other component') - ).toThrowErrorMatchingSnapshot(); + expect(() => registerSettingsComponent('test2', () => )).toThrowErrorMatchingSnapshot(); }); it('should allow a component to be overriden', () => { - const component = {}; + const component = () =>
; registerSettingsComponent('test3', component); - const anotherComponent = { anotherComponent: 'ok' }; + const anotherComponent = () => ; registerSettingsComponent('test3', anotherComponent, true); expect(getSettingsComponent('test3')).toBe(anotherComponent); }); - it('should set a displayName for the component if one does not exist', () => { - const component = {}; + it('should set a displayName for the component', () => { + const component = () =>
; registerSettingsComponent('display_name_component', component); - - expect(component.displayName).toEqual('display_name_component'); - }); - - it('should not set a displayName for the component if one already exists', () => { - const component = { - displayName: '', - }; - - registerSettingsComponent('another_display_name_component', component); - - expect(component.displayName).toEqual(''); + expect((component as FunctionComponent).displayName).toEqual('display_name_component'); }); }); describe('getSettingsComponent', () => { it('should allow a component to be retrieved', () => { - const component = {}; + const component = () =>
; registerSettingsComponent('test4', component); expect(getSettingsComponent('test4')).toBe(component); }); diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/component_registry.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/component_registry.ts similarity index 81% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/component_registry.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/component_registry.ts index 4b81b74d20aa48..b58180c498edfe 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/component_registry.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/component_registry.ts @@ -17,7 +17,10 @@ * under the License. */ -const registry = {}; +import { ComponentType } from 'react'; + +type Id = string; +const registry: Record | undefined>> = {}; /** * Attempts to register the provided component. @@ -26,7 +29,10 @@ const registry = {}; * @param {*} id the id of the component to register * @param {*} component the component */ -export function tryRegisterSettingsComponent(id, component) { +export function tryRegisterSettingsComponent( + id: Id, + component: ComponentType | undefined> +) { if (id in registry) { return false; } @@ -45,7 +51,11 @@ export function tryRegisterSettingsComponent(id, component) { * @param {*} component the component * @param {*} allowOverride (default: false) - optional flag to allow this component to override a previously registered component */ -export function registerSettingsComponent(id, component, allowOverride = false) { +export function registerSettingsComponent( + id: Id, + component: ComponentType | undefined>, + allowOverride = false +) { if (!allowOverride && id in registry) { throw new Error(`Component with id ${id} is already registered.`); } @@ -65,7 +75,7 @@ export function registerSettingsComponent(id, component, allowOverride = false) * * @param {*} id the ID of the component to retrieve */ -export function getSettingsComponent(id) { +export function getSettingsComponent(id: Id): ComponentType | undefined> { if (!(id in registry)) { throw new Error(`Component not found with id ${id}`); } diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/default_component_registry.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/default_component_registry.test.tsx similarity index 96% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/default_component_registry.test.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/default_component_registry.test.tsx index 4fc6dc710f8669..ff3f75b79baefc 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/default_component_registry.test.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/default_component_registry.test.tsx @@ -17,6 +17,7 @@ * under the License. */ +import React from 'react'; import { registerDefaultComponents, PAGE_TITLE_COMPONENT } from './default_component_registry'; import { getSettingsComponent, registerSettingsComponent } from './component_registry'; import { PageTitle } from './page_title'; @@ -34,7 +35,7 @@ describe('default_component_registry', () => { }); it('should not override components if they are already registered', () => { - const newComponent = {}; + const newComponent = () =>
; registerSettingsComponent(PAGE_TITLE_COMPONENT, newComponent, true); registerDefaultComponents(); diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/default_component_registry.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/default_component_registry.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/default_component_registry.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/default_component_registry.ts diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/__snapshots__/field.test.js.snap b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/__snapshots__/field.test.tsx.snap similarity index 99% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/__snapshots__/field.test.js.snap rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/__snapshots__/field.test.tsx.snap index f4d20b45658802..915ee021e9b607 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/__snapshots__/field.test.js.snap +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/__snapshots__/field.test.tsx.snap @@ -1309,7 +1309,6 @@ exports[`Field for json setting should render as read only if saving is disabled Object { "value": {} @@ -1420,7 +1419,6 @@ exports[`Field for json setting should render as read only with help text if ove Object { "value": {} @@ -1637,7 +1635,6 @@ exports[`Field for json setting should render default value if there is no user Object { "value": {} @@ -1765,7 +1762,6 @@ exports[`Field for json setting should render user value if there is user value Object { "value": {} diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.test.tsx similarity index 84% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.test.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.test.tsx index 07ce6f84d2bb64..bd2ba8ac0ebcc6 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.test.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.test.tsx @@ -21,7 +21,10 @@ import React from 'react'; import { I18nProvider } from '@kbn/i18n/react'; import { shallowWithI18nProvider, mountWithI18nProvider } from 'test_utils/enzyme_helpers'; import { mount } from 'enzyme'; +import { FieldSetting } from '../../types'; +import { UiSettingsType, StringValidation } from '../../../../../../../../../core/public'; +// @ts-ignore import { findTestSubject } from '@elastic/eui/lib/test'; import { Field } from './field'; @@ -37,7 +40,13 @@ import { toastNotifications } from 'ui/notify'; jest.mock('brace/theme/textmate', () => 'brace/theme/textmate'); jest.mock('brace/mode/markdown', () => 'brace/mode/markdown'); -const settings = { +const defaults = { + requiresPageReload: false, + readOnly: false, + category: ['category'], +}; + +const settings: Record = { array: { name: 'array:test:setting', ariaName: 'array test setting', @@ -48,7 +57,7 @@ const settings = { defVal: ['default_value'], isCustom: false, isOverridden: false, - options: null, + ...defaults, }, boolean: { name: 'boolean:test:setting', @@ -60,7 +69,7 @@ const settings = { defVal: true, isCustom: false, isOverridden: false, - options: null, + ...defaults, }, image: { name: 'image:test:setting', @@ -78,6 +87,7 @@ const settings = { description: 'Description for 1 kB', }, }, + ...defaults, }, json: { name: 'json:test:setting', @@ -89,7 +99,7 @@ const settings = { defVal: '{}', isCustom: false, isOverridden: false, - options: null, + ...defaults, }, markdown: { name: 'markdown:test:setting', @@ -101,7 +111,7 @@ const settings = { defVal: '', isCustom: false, isOverridden: false, - options: null, + ...defaults, }, number: { name: 'number:test:setting', @@ -113,7 +123,7 @@ const settings = { defVal: 5, isCustom: false, isOverridden: false, - options: null, + ...defaults, }, select: { name: 'select:test:setting', @@ -131,6 +141,7 @@ const settings = { orange: 'Orange', // Deliberately left out `banana` to test if it also works with missing labels }, + ...defaults, }, string: { name: 'string:test:setting', @@ -142,7 +153,7 @@ const settings = { defVal: null, isCustom: false, isOverridden: false, - options: null, + ...defaults, }, stringWithValidation: { name: 'string:test-validation:setting', @@ -158,7 +169,7 @@ const settings = { defVal: 'foo-default', isCustom: false, isOverridden: false, - options: null, + ...defaults, }, }; const userValues = { @@ -175,8 +186,8 @@ const userValues = { const invalidUserValues = { stringWithValidation: 'invalidUserValue', }; -const save = jest.fn(() => Promise.resolve()); -const clear = jest.fn(() => Promise.resolve()); +const save = jest.fn(() => Promise.resolve(true)); +const clear = jest.fn(() => Promise.resolve(true)); describe('Field', () => { Object.keys(settings).forEach(type => { @@ -196,6 +207,7 @@ describe('Field', () => { { { /> ); const select = findTestSubject(component, `advancedSetting-editField-${setting.name}`); + // @ts-ignore const labels = select.find('option').map(option => option.prop('value')); expect(labels).toEqual(['apple', 'orange', 'banana']); }); @@ -280,13 +294,14 @@ describe('Field', () => { /> ); const select = findTestSubject(component, `advancedSetting-editField-${setting.name}`); + // @ts-ignore const labels = select.find('option').map(option => option.text()); expect(labels).toEqual(['Apple', 'Orange', 'banana']); }); } const setup = () => { - const Wrapper = props => ( + const Wrapper = (props: Record) => ( @@ -304,21 +319,22 @@ describe('Field', () => { describe(`for changing ${type} setting`, () => { const { wrapper, component } = setup(); const userValue = userValues[type]; - component.instance().getImageAsBase64 = file => Promise.resolve(file); + (component.instance() as Field).getImageAsBase64 = ({}: Blob) => Promise.resolve(''); it('should be able to change value from no value and cancel', async () => { - await component.instance().onImageChange([userValue]); + await (component.instance() as Field).onImageChange([userValue]); const updated = wrapper.update(); findTestSubject(updated, `advancedSetting-cancelEditField-${setting.name}`).simulate( 'click' ); expect( - component.instance().state.unsavedValue === component.instance().state.savedValue + (component.instance() as Field).state.unsavedValue === + (component.instance() as Field).state.savedValue ).toBe(true); }); it('should be able to change value and save', async () => { - await component.instance().onImageChange([userValue]); + await (component.instance() as Field).onImageChange([userValue]); const updated = wrapper.update(); findTestSubject(updated, `advancedSetting-saveEditField-${setting.name}`).simulate( 'click' @@ -327,12 +343,12 @@ describe('Field', () => { component.setState({ savedValue: userValue }); await wrapper.setProps({ setting: { - ...component.instance().props.setting, + ...(component.instance() as Field).props.setting, value: userValue, }, }); - await component.instance().cancelChangeImage(); + await (component.instance() as Field).cancelChangeImage(); wrapper.update(); }); @@ -341,7 +357,7 @@ describe('Field', () => { findTestSubject(updated, `advancedSetting-changeImage-${setting.name}`).simulate('click'); const newUserValue = `${userValue}=`; - await component.instance().onImageChange([newUserValue]); + await (component.instance() as Field).onImageChange([newUserValue]); const updated2 = wrapper.update(); findTestSubject(updated2, `advancedSetting-saveEditField-${setting.name}`).simulate( 'click' @@ -350,7 +366,7 @@ describe('Field', () => { component.setState({ savedValue: newUserValue }); await wrapper.setProps({ setting: { - ...component.instance().props.setting, + ...(component.instance() as Field).props.setting, value: newUserValue, }, }); @@ -370,18 +386,19 @@ describe('Field', () => { const fieldUserValue = userValue; it('should be able to change value and cancel', async () => { - component.instance().onCodeEditorChange(fieldUserValue); + (component.instance() as Field).onCodeEditorChange(fieldUserValue as UiSettingsType); const updated = wrapper.update(); findTestSubject(updated, `advancedSetting-cancelEditField-${setting.name}`).simulate( 'click' ); expect( - component.instance().state.unsavedValue === component.instance().state.savedValue + (component.instance() as Field).state.unsavedValue === + (component.instance() as Field).state.savedValue ).toBe(true); }); it('should be able to change value and save', async () => { - component.instance().onCodeEditorChange(fieldUserValue); + (component.instance() as Field).onCodeEditorChange(fieldUserValue as UiSettingsType); const updated = wrapper.update(); findTestSubject(updated, `advancedSetting-saveEditField-${setting.name}`).simulate( 'click' @@ -390,7 +407,7 @@ describe('Field', () => { component.setState({ savedValue: fieldUserValue }); await wrapper.setProps({ setting: { - ...component.instance().props.setting, + ...(component.instance() as Field).props.setting, value: userValue, }, }); @@ -399,9 +416,9 @@ describe('Field', () => { if (type === 'json') { it('should be able to clear value and have empty object populate', async () => { - component.instance().onCodeEditorChange(''); + (component.instance() as Field).onCodeEditorChange('' as UiSettingsType); wrapper.update(); - expect(component.instance().state.unsavedValue).toEqual('{}'); + expect((component.instance() as Field).state.unsavedValue).toEqual('{}'); }); } @@ -414,32 +431,35 @@ describe('Field', () => { } else { describe(`for changing ${type} setting`, () => { const { wrapper, component } = setup(); + // @ts-ignore const userValue = userValues[type]; const fieldUserValue = type === 'array' ? userValue.join(', ') : userValue; if (setting.validation) { + // @ts-ignore const invalidUserValue = invalidUserValues[type]; it('should display an error when validation fails', async () => { - component.instance().onFieldChange({ target: { value: invalidUserValue } }); + (component.instance() as Field).onFieldChange(invalidUserValue); const updated = wrapper.update(); const errorMessage = updated.find('.euiFormErrorText').text(); - expect(errorMessage).toEqual(setting.validation.message); + expect(errorMessage).toEqual((setting.validation as StringValidation).message); }); } it('should be able to change value and cancel', async () => { - component.instance().onFieldChange({ target: { value: fieldUserValue } }); + (component.instance() as Field).onFieldChange(fieldUserValue); const updated = wrapper.update(); findTestSubject(updated, `advancedSetting-cancelEditField-${setting.name}`).simulate( 'click' ); expect( - component.instance().state.unsavedValue === component.instance().state.savedValue + (component.instance() as Field).state.unsavedValue === + (component.instance() as Field).state.savedValue ).toBe(true); }); it('should be able to change value and save', async () => { - component.instance().onFieldChange({ target: { value: fieldUserValue } }); + (component.instance() as Field).onFieldChange(fieldUserValue); const updated = wrapper.update(); findTestSubject(updated, `advancedSetting-saveEditField-${setting.name}`).simulate( 'click' @@ -448,7 +468,7 @@ describe('Field', () => { component.setState({ savedValue: fieldUserValue }); await wrapper.setProps({ setting: { - ...component.instance().props.setting, + ...(component.instance() as Field).props.setting, value: userValue, }, }); @@ -472,7 +492,7 @@ describe('Field', () => { const wrapper = mountWithI18nProvider( ); - wrapper.instance().onFieldChange({ target: { value: 'a new value' } }); + (wrapper.instance() as Field).onFieldChange({ target: { value: 'a new value' } }); const updated = wrapper.update(); findTestSubject(updated, `advancedSetting-saveEditField-${setting.name}`).simulate('click'); expect(save).toHaveBeenCalled(); diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.tsx similarity index 81% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.tsx index a2f201cf757f52..524160191d8f08 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.tsx @@ -18,7 +18,7 @@ */ import React, { PureComponent, Fragment } from 'react'; -import PropTypes from 'prop-types'; +import ReactDOM from 'react-dom'; import { npStart } from 'ui/new_platform'; import 'brace/theme/textmate'; @@ -35,6 +35,7 @@ import { EuiDescribedFormGroup, EuiFieldNumber, EuiFieldText, + // @ts-ignore EuiFilePicker, EuiFlexGroup, EuiFlexItem, @@ -47,22 +48,39 @@ import { EuiText, EuiSelect, EuiSwitch, + EuiSwitchEvent, keyCodes, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; - +import { FieldSetting } from '../../types'; import { isDefaultValue } from '../../lib'; +import { + UiSettingsType, + ImageValidation, + StringValidationRegex, +} from '../../../../../../../../../core/public'; + +interface FieldProps { + setting: FieldSetting; + save: (name: string, value: string) => Promise; + clear: (name: string) => Promise; + enableSaving: boolean; +} -export class Field extends PureComponent { - static propTypes = { - setting: PropTypes.object.isRequired, - save: PropTypes.func.isRequired, - clear: PropTypes.func.isRequired, - enableSaving: PropTypes.bool.isRequired, - }; +interface FieldState { + unsavedValue: any; + savedValue: any; + loading: boolean; + isInvalid: boolean; + error: string | null; + changeImage: boolean; + isJsonArray: boolean; +} - constructor(props) { +export class Field extends PureComponent { + private changeImageForm: EuiFilePicker | undefined; + constructor(props: FieldProps) { super(props); const { type, value, defVal } = this.props.setting; const editableValue = this.getEditableValue(type, value, defVal); @@ -74,12 +92,11 @@ export class Field extends PureComponent { changeImage: false, savedValue: editableValue, unsavedValue: editableValue, - isJsonArray: type === 'json' ? Array.isArray(JSON.parse(defVal || '{}')) : false, + isJsonArray: type === 'json' ? Array.isArray(JSON.parse(String(defVal) || '{}')) : false, }; - this.changeImageForm = null; } - UNSAFE_componentWillReceiveProps(nextProps) { + UNSAFE_componentWillReceiveProps(nextProps: FieldProps) { const { unsavedValue } = this.state; const { type, value, defVal } = nextProps.setting; const editableValue = this.getEditableValue(type, value, defVal); @@ -90,11 +107,15 @@ export class Field extends PureComponent { }); } - getEditableValue(type, value, defVal) { + getEditableValue( + type: UiSettingsType, + value: FieldSetting['value'], + defVal: FieldSetting['defVal'] + ) { const val = value === null || value === undefined ? defVal : value; switch (type) { case 'array': - return val.join(', '); + return (val as string[]).join(', '); case 'boolean': return !!val; case 'number': @@ -106,21 +127,27 @@ export class Field extends PureComponent { } } - getDisplayedDefaultValue(type, defVal, optionLabels = {}) { + getDisplayedDefaultValue( + type: UiSettingsType, + defVal: FieldSetting['defVal'], + optionLabels: Record = {} + ) { if (defVal === undefined || defVal === null || defVal === '') { return 'null'; } switch (type) { case 'array': - return defVal.join(', '); + return (defVal as string[]).join(', '); case 'select': - return optionLabels.hasOwnProperty(defVal) ? optionLabels[defVal] : String(defVal); + return optionLabels.hasOwnProperty(String(defVal)) + ? optionLabels[String(defVal)] + : String(defVal); default: return String(defVal); } } - setLoading(loading) { + setLoading(loading: boolean) { this.setState({ loading, }); @@ -133,11 +160,11 @@ export class Field extends PureComponent { }); } - onCodeEditorChange = value => { + onCodeEditorChange = (value: UiSettingsType) => { const { type } = this.props.setting; const { isJsonArray } = this.state; - let newUnsavedValue = undefined; + let newUnsavedValue; let isInvalid = false; let error = null; @@ -148,12 +175,9 @@ export class Field extends PureComponent { JSON.parse(newUnsavedValue); } catch (e) { isInvalid = true; - error = ( - - ); + error = i18n.translate('kbn.management.settings.field.codeEditorSyntaxErrorMessage', { + defaultMessage: 'Invalid JSON syntax', + }); } break; default: @@ -167,12 +191,18 @@ export class Field extends PureComponent { }); }; - onFieldChange = e => { - const value = e.target.value; + onFieldChangeSwitch = (e: EuiSwitchEvent) => { + return this.onFieldChange(e.target.checked); + }; + + onFieldChangeEvent = (e: React.ChangeEvent) => + this.onFieldChange(e.target.value); + + onFieldChange = (value: any) => { const { type, validation } = this.props.setting; const { unsavedValue } = this.state; - let newUnsavedValue = undefined; + let newUnsavedValue; switch (type) { case 'boolean': @@ -186,11 +216,11 @@ export class Field extends PureComponent { } let isInvalid = false; - let error = undefined; + let error = null; - if (validation && validation.regex) { - if (!validation.regex.test(newUnsavedValue)) { - error = validation.message; + if (validation && (validation as StringValidationRegex).regex) { + if (!(validation as StringValidationRegex).regex!.test(newUnsavedValue.toString())) { + error = (validation as StringValidationRegex).message; isInvalid = true; } } @@ -202,7 +232,7 @@ export class Field extends PureComponent { }); }; - onFieldKeyDown = ({ keyCode }) => { + onFieldKeyDown = ({ keyCode }: { keyCode: number }) => { if (keyCode === keyCodes.ENTER) { this.saveEdit(); } @@ -211,13 +241,13 @@ export class Field extends PureComponent { } }; - onFieldEscape = ({ keyCode }) => { + onFieldEscape = ({ keyCode }: { keyCode: number }) => { if (keyCode === keyCodes.ESCAPE) { this.cancelEdit(); } }; - onImageChange = async files => { + onImageChange = async (files: any[]) => { if (!files.length) { this.clearError(); this.setState({ @@ -227,9 +257,12 @@ export class Field extends PureComponent { } const file = files[0]; - const { maxSize } = this.props.setting.validation; + const { maxSize } = this.props.setting.validation as ImageValidation; try { - const base64Image = await this.getImageAsBase64(file); + let base64Image = ''; + if (file instanceof File) { + base64Image = (await this.getImageAsBase64(file)) as string; + } const isInvalid = !!(maxSize && maxSize.length && base64Image.length > maxSize.length); this.setState({ isInvalid, @@ -254,17 +287,13 @@ export class Field extends PureComponent { } }; - getImageAsBase64(file) { - if (!file instanceof File) { - return null; - } - + async getImageAsBase64(file: Blob): Promise { const reader = new FileReader(); reader.readAsDataURL(file); return new Promise((resolve, reject) => { reader.onload = () => { - resolve(reader.result); + resolve(reader.result || undefined); }; reader.onerror = err => { reject(err); @@ -309,20 +338,24 @@ export class Field extends PureComponent { settingName: this.props.setting.displayName || this.props.setting.name, }, }), - text: ( - <> - - - window.location.reload()}> - {i18n.translate( - 'kbn.management.settings.field.requiresPageReloadToastButtonLabel', - { defaultMessage: 'Reload page' } - )} - - - - - ), + text: element => { + const content = ( + <> + + + window.location.reload()}> + {i18n.translate( + 'kbn.management.settings.field.requiresPageReloadToastButtonLabel', + { defaultMessage: 'Reload page' } + )} + + + + + ); + ReactDOM.render(content, element); + return () => ReactDOM.unmountComponentAtNode(element); + }, color: 'success', }); } @@ -341,8 +374,8 @@ export class Field extends PureComponent { switch (type) { case 'array': - valueToSave = valueToSave.split(',').map(val => val.trim()); - isSameValue = valueToSave.join(',') === defVal.join(','); + valueToSave = valueToSave.split(',').map((val: string) => val.trim()); + isSameValue = valueToSave.join(',') === (defVal as string[]).join(','); break; case 'json': valueToSave = valueToSave.trim(); @@ -394,7 +427,7 @@ export class Field extends PureComponent { this.setLoading(false); }; - renderField(setting) { + renderField(setting: FieldSetting) { const { enableSaving } = this.props; const { loading, changeImage, unsavedValue } = this.state; const { name, value, type, options, optionLabels = {}, isOverridden, ariaName } = setting; @@ -414,7 +447,7 @@ export class Field extends PureComponent { ) } checked={!!unsavedValue} - onChange={this.onFieldChange} + onChange={this.onFieldChangeSwitch} disabled={loading || isOverridden || !enableSaving} onKeyDown={this.onFieldKeyDown} data-test-subj={`advancedSetting-editField-${name}`} @@ -449,14 +482,16 @@ export class Field extends PureComponent { ); case 'image': if (!isDefaultValue(setting) && !changeImage) { - return ; + return ( + + ); } else { return ( { + ref={(input: HTMLInputElement) => { this.changeImageForm = input; }} onKeyDown={this.onFieldEscape} @@ -469,13 +504,13 @@ export class Field extends PureComponent { { + options={(options as string[]).map(option => { return { text: optionLabels.hasOwnProperty(option) ? optionLabels[option] : option, value: option, }; })} - onChange={this.onFieldChange} + onChange={this.onFieldChangeEvent} isLoading={loading} disabled={loading || isOverridden || !enableSaving} onKeyDown={this.onFieldKeyDown} @@ -487,7 +522,7 @@ export class Field extends PureComponent { @@ -541,7 +576,7 @@ export class Field extends PureComponent { return null; } - renderTitle(setting) { + renderTitle(setting: FieldSetting) { return (

{setting.displayName || setting.name} @@ -566,7 +601,7 @@ export class Field extends PureComponent { ); } - renderDescription(setting) { + renderDescription(setting: FieldSetting) { let description; let deprecation; @@ -579,7 +614,7 @@ export class Field extends PureComponent { { - window.open(links.management[setting.deprecation.docLinksKey], '_blank'); + window.open(links.management[setting.deprecation!.docLinksKey], '_blank'); }} onClickAriaLabel={i18n.translate( 'kbn.management.settings.field.deprecationClickAreaLabel', @@ -608,7 +643,7 @@ export class Field extends PureComponent { * Justification for dangerouslySetInnerHTML: * Setting description may contain formatting and links to documentation. */ - dangerouslySetInnerHTML={{ __html: setting.description }} //eslint-disable-line react/no-danger + dangerouslySetInnerHTML={{ __html: setting.description || '' }} // eslint-disable-line react/no-danger /> ); } @@ -622,7 +657,7 @@ export class Field extends PureComponent { ); } - renderDefaultValue(setting) { + renderDefaultValue(setting: FieldSetting) { const { type, defVal, optionLabels } = setting; if (isDefaultValue(setting)) { return; @@ -641,7 +676,7 @@ export class Field extends PureComponent { = 500 ? 300 : null} + overflowHeight={(defVal as string).length >= 500 ? 300 : undefined} > {this.getDisplayedDefaultValue(type, defVal)} @@ -667,7 +702,7 @@ export class Field extends PureComponent { ); } - renderResetToDefaultLink(setting) { + renderResetToDefaultLink(setting: FieldSetting) { const { ariaName, name } = setting; if (isDefaultValue(setting)) { return; @@ -694,7 +729,7 @@ export class Field extends PureComponent { ); } - renderChangeImageLink(setting) { + renderChangeImageLink(setting: FieldSetting) { const { changeImage } = this.state; const { type, value, ariaName, name } = setting; if (type !== 'image' || !value || changeImage) { @@ -721,7 +756,7 @@ export class Field extends PureComponent { ); } - renderActions(setting) { + renderActions(setting: FieldSetting) { const { ariaName, name } = setting; const { loading, isInvalid, changeImage, savedValue, unsavedValue } = this.state; const isDisabled = loading || setting.isOverridden; @@ -798,6 +833,7 @@ export class Field extends PureComponent { helpText={this.renderHelpText(setting)} describedByIds={[`${setting.name}-aria`]} className="mgtAdvancedSettings__fieldRow" + // @ts-ignore hasChildLabel={setting.type !== 'boolean'} > {this.renderField(setting)} diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/index.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/index.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/index.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/index.ts diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/__snapshots__/form.test.js.snap b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/__snapshots__/form.test.tsx.snap similarity index 79% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/__snapshots__/form.test.js.snap rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/__snapshots__/form.test.tsx.snap index 4111b3d5fa2d3f..b43c17c2a88656 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/__snapshots__/form.test.js.snap +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/__snapshots__/form.test.tsx.snap @@ -61,9 +61,16 @@ exports[`Form should render normally 1`] = ` "category": Array [ "general", ], - "description": "bar", + "defVal": "defVal", + "description": "description", "displayName": "Test date", + "isCustom": false, + "isOverridden": false, "name": "general:test:date", + "readOnly": false, + "requiresPageReload": false, + "type": "string", + "value": "value", } } /> @@ -78,9 +85,16 @@ exports[`Form should render normally 1`] = ` "category": Array [ "general", ], - "description": "foo", + "defVal": "defVal", + "description": "description", "displayName": "Test setting", + "isCustom": false, + "isOverridden": false, "name": "setting:test", + "readOnly": false, + "requiresPageReload": false, + "type": "string", + "value": "value", } } /> @@ -120,8 +134,16 @@ exports[`Form should render normally 1`] = ` "category": Array [ "dashboard", ], + "defVal": "defVal", + "description": "description", "displayName": "Dashboard test setting", + "isCustom": false, + "isOverridden": false, "name": "dashboard:test:setting", + "readOnly": false, + "requiresPageReload": false, + "type": "string", + "value": "value", } } /> @@ -187,9 +209,16 @@ exports[`Form should render normally 1`] = ` "category": Array [ "x-pack", ], - "description": "bar", + "defVal": "defVal", + "description": "description", "displayName": "X-Pack test setting", + "isCustom": false, + "isOverridden": false, "name": "xpack:test:setting", + "readOnly": false, + "requiresPageReload": false, + "type": "string", + "value": "value", } } /> @@ -234,9 +263,16 @@ exports[`Form should render read-only when saving is disabled 1`] = ` "category": Array [ "general", ], - "description": "bar", + "defVal": "defVal", + "description": "description", "displayName": "Test date", + "isCustom": false, + "isOverridden": false, "name": "general:test:date", + "readOnly": false, + "requiresPageReload": false, + "type": "string", + "value": "value", } } /> @@ -251,9 +287,16 @@ exports[`Form should render read-only when saving is disabled 1`] = ` "category": Array [ "general", ], - "description": "foo", + "defVal": "defVal", + "description": "description", "displayName": "Test setting", + "isCustom": false, + "isOverridden": false, "name": "setting:test", + "readOnly": false, + "requiresPageReload": false, + "type": "string", + "value": "value", } } /> @@ -293,8 +336,16 @@ exports[`Form should render read-only when saving is disabled 1`] = ` "category": Array [ "dashboard", ], + "defVal": "defVal", + "description": "description", "displayName": "Dashboard test setting", + "isCustom": false, + "isOverridden": false, "name": "dashboard:test:setting", + "readOnly": false, + "requiresPageReload": false, + "type": "string", + "value": "value", } } /> @@ -360,9 +411,16 @@ exports[`Form should render read-only when saving is disabled 1`] = ` "category": Array [ "x-pack", ], - "description": "bar", + "defVal": "defVal", + "description": "description", "displayName": "X-Pack test setting", + "isCustom": false, + "isOverridden": false, "name": "xpack:test:setting", + "readOnly": false, + "requiresPageReload": false, + "type": "string", + "value": "value", } } /> diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/form.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/form.test.tsx similarity index 88% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/form.test.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/form.test.tsx index 7befed814e5d0a..6bbcfd543a6290 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/form.test.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/form.test.tsx @@ -19,6 +19,7 @@ import React from 'react'; import { shallowWithI18nProvider } from 'test_utils/enzyme_helpers'; +import { UiSettingsType } from '../../../../../../../../../core/public'; import { Form } from './form'; @@ -28,6 +29,17 @@ jest.mock('../field', () => ({ }, })); +const defaults = { + requiresPageReload: false, + readOnly: false, + value: 'value', + description: 'description', + isOverridden: false, + type: 'string' as UiSettingsType, + isCustom: false, + defVal: 'defVal', +}; + const settings = { dashboard: [ { @@ -35,6 +47,7 @@ const settings = { ariaName: 'dashboard test setting', displayName: 'Dashboard test setting', category: ['dashboard'], + ...defaults, }, ], general: [ @@ -44,6 +57,7 @@ const settings = { displayName: 'Test date', description: 'bar', category: ['general'], + ...defaults, }, { name: 'setting:test', @@ -51,6 +65,7 @@ const settings = { displayName: 'Test setting', description: 'foo', category: ['general'], + ...defaults, }, ], 'x-pack': [ @@ -60,6 +75,7 @@ const settings = { displayName: 'X-Pack test setting', category: ['x-pack'], description: 'bar', + ...defaults, }, ], }; @@ -69,8 +85,8 @@ const categoryCounts = { dashboard: 1, 'x-pack': 10, }; -const save = () => {}; -const clear = () => {}; +const save = (key: string, value: any) => Promise.resolve(true); +const clear = (key: string) => Promise.resolve(true); const clearQuery = () => {}; describe('Form', () => { diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/form.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/form.tsx similarity index 84% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/form.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/form.tsx index 19d8b9da446c76..113e0b2db5f308 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/form.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/form.tsx @@ -18,7 +18,6 @@ */ import React, { PureComponent, Fragment } from 'react'; -import PropTypes from 'prop-types'; import { EuiFlexGroup, @@ -33,20 +32,23 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { getCategoryName } from '../../lib'; import { Field } from '../field'; +import { FieldSetting } from '../../types'; -export class Form extends PureComponent { - static propTypes = { - settings: PropTypes.object.isRequired, - categories: PropTypes.array.isRequired, - categoryCounts: PropTypes.object.isRequired, - clearQuery: PropTypes.func.isRequired, - save: PropTypes.func.isRequired, - clear: PropTypes.func.isRequired, - showNoResultsMessage: PropTypes.bool.isRequired, - enableSaving: PropTypes.bool.isRequired, - }; +type Category = string; - renderClearQueryLink(totalSettings, currentSettings) { +interface FormProps { + settings: Record; + categories: Category[]; + categoryCounts: Record; + clearQuery: () => void; + save: (key: string, value: any) => Promise; + clear: (key: string) => Promise; + showNoResultsMessage: boolean; + enableSaving: boolean; +} + +export class Form extends PureComponent { + renderClearQueryLink(totalSettings: number, currentSettings: number) { const { clearQuery } = this.props; if (totalSettings !== currentSettings) { @@ -78,7 +80,7 @@ export class Form extends PureComponent { return null; } - renderCategory(category, settings, totalSettings) { + renderCategory(category: Category, settings: FieldSetting[], totalSettings: number) { return ( @@ -110,7 +112,7 @@ export class Form extends PureComponent { ); } - maybeRenderNoSettings(clearQuery) { + maybeRenderNoSettings(clearQuery: FormProps['clearQuery']) { if (this.props.showNoResultsMessage) { return ( @@ -136,7 +138,7 @@ export class Form extends PureComponent { render() { const { settings, categories, categoryCounts, clearQuery } = this.props; - const currentCategories = []; + const currentCategories: Category[] = []; categories.forEach(category => { if (settings[category] && settings[category].length) { @@ -148,7 +150,7 @@ export class Form extends PureComponent { {currentCategories.length ? currentCategories.map(category => { - return this.renderCategory(category, settings[category], categoryCounts[category]); // fix this + return this.renderCategory(category, settings[category], categoryCounts[category]); }) : this.maybeRenderNoSettings(clearQuery)} diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/index.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/index.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/index.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/form/index.ts diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/__snapshots__/page_footer.test.js.snap b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/__snapshots__/page_footer.test.tsx.snap similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/__snapshots__/page_footer.test.js.snap rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/__snapshots__/page_footer.test.tsx.snap diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/index.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/index.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/index.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/index.ts diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/page_footer.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/page_footer.test.tsx similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/page_footer.test.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/page_footer.test.tsx diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/page_footer.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/page_footer.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/page_footer.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_footer/page_footer.ts diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/__snapshots__/page_subtitle.test.js.snap b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/__snapshots__/page_subtitle.test.tsx.snap similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/__snapshots__/page_subtitle.test.js.snap rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/__snapshots__/page_subtitle.test.tsx.snap diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/index.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/index.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/index.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/index.ts diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/page_subtitle.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/page_subtitle.test.tsx similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/page_subtitle.test.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/page_subtitle.test.tsx diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/page_subtitle.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/page_subtitle.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/page_subtitle.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_subtitle/page_subtitle.ts diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/__snapshots__/page_title.test.js.snap b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/__snapshots__/page_title.test.tsx.snap similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/__snapshots__/page_title.test.js.snap rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/__snapshots__/page_title.test.tsx.snap diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/index.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/index.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/index.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/index.ts diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/page_title.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/page_title.test.tsx similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/page_title.test.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/page_title.test.tsx diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/page_title.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/page_title.tsx similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/page_title.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/page_title/page_title.tsx diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/__snapshots__/search.test.js.snap b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/__snapshots__/search.test.tsx.snap similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/__snapshots__/search.test.js.snap rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/__snapshots__/search.test.tsx.snap diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/index.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/index.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/index.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/index.ts diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/search.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/search.test.tsx similarity index 97% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/search.test.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/search.test.tsx index 3cd2de6ddccaa7..8e7bac5129ae94 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/search.test.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/search.test.tsx @@ -19,6 +19,7 @@ import React from 'react'; import { shallowWithI18nProvider, mountWithI18nProvider } from 'test_utils/enzyme_helpers'; +// @ts-ignore import { findTestSubject } from '@elastic/eui/lib/test'; import { Query } from '@elastic/eui'; @@ -38,7 +39,7 @@ describe('Search', () => { }); it('should call parent function when query is changed', async () => { - //This test is brittle as it knows about implementation details + // This test is brittle as it knows about implementation details // (EuiFieldSearch uses onKeyup instead of onChange to handle input) const onQueryChange = jest.fn(); const component = mountWithI18nProvider( diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/search.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/search.tsx similarity index 84% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/search.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/search.tsx index 02315e73cc11b8..471f2ba28005ca 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/search.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/search/search.tsx @@ -18,21 +18,26 @@ */ import React, { Fragment, PureComponent } from 'react'; -import PropTypes from 'prop-types'; import { i18n } from '@kbn/i18n'; - -import { EuiSearchBar, EuiFormErrorText } from '@elastic/eui'; +import { + // @ts-ignore + EuiSearchBar, + EuiFormErrorText, +} from '@elastic/eui'; +import { IQuery } from '../../types'; import { getCategoryName } from '../../lib'; -export class Search extends PureComponent { - static propTypes = { - categories: PropTypes.array.isRequired, - query: PropTypes.object.isRequired, - onQueryChange: PropTypes.func.isRequired, - }; +interface SearchProps { + categories: string[]; + query: IQuery; + onQueryChange: ({ query }: { query: IQuery }) => void; +} + +export class Search extends PureComponent { + private categories: Array<{ value: string; name: string }> = []; - constructor(props) { + constructor(props: SearchProps) { super(props); const { categories } = props; this.categories = categories.map(category => { @@ -48,7 +53,7 @@ export class Search extends PureComponent { parseErrorMessage: null, }; - onChange = ({ query, error }) => { + onChange = ({ query, error }: { query: IQuery; error: { message: string } }) => { if (error) { this.setState({ isSearchTextValid: false, diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/index.html b/src/legacy/core_plugins/kibana/public/management/sections/settings/index.html index e1b901a9669606..2fe8fce08b4abc 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/index.html +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/index.html @@ -1,5 +1,5 @@ -
+
diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/index.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/index.js index f03dcd195092aa..6d8987b1a928e5 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/index.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/index.js @@ -29,38 +29,10 @@ import { } from 'ui/registry/feature_catalogue'; import React from 'react'; -import { render, unmountComponentAtNode } from 'react-dom'; import { AdvancedSettings } from './advanced_settings'; import { i18n } from '@kbn/i18n'; import { getBreadcrumbs } from './breadcrumbs'; -const REACT_ADVANCED_SETTINGS_DOM_ELEMENT_ID = 'reactAdvancedSettings'; - -function updateAdvancedSettings($scope, config, query) { - $scope.$$postDigest(() => { - const node = document.getElementById(REACT_ADVANCED_SETTINGS_DOM_ELEMENT_ID); - if (!node) { - return; - } - - render( - - - , - node - ); - }); -} - -function destroyAdvancedSettings() { - const node = document.getElementById(REACT_ADVANCED_SETTINGS_DOM_ELEMENT_ID); - node && unmountComponentAtNode(node); -} - uiRoutes.when('/management/kibana/settings/:setting?', { template: indexTemplate, k7Breadcrumbs: getBreadcrumbs, @@ -82,23 +54,28 @@ uiRoutes.when('/management/kibana/settings/:setting?', { }, }); -uiModules.get('apps/management').directive('kbnManagementAdvanced', function(config, $route) { +uiModules.get('apps/management').directive('kbnManagementAdvanced', function($route) { return { restrict: 'E', link: function($scope) { - config.watchAll(() => { - updateAdvancedSettings($scope, config, $route.current.params.setting || ''); - }, $scope); - - $scope.$on('$destroy', () => { - destroyAdvancedSettings(); - }); - + $scope.query = $route.current.params.setting || ''; $route.updateParams({ setting: null }); }, }; }); +const AdvancedSettingsApp = ({ query = '' }) => { + return ( + + + + ); +}; + +uiModules.get('apps/management').directive('kbnManagementAdvancedReact', function(reactDirective) { + return reactDirective(AdvancedSettingsApp, [['query', { watchDepth: 'reference' }]]); +}); + management.getSection('kibana').register('settings', { display: i18n.translate('kbn.management.settings.sectionLabel', { defaultMessage: 'Advanced Settings', diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/get_category_name.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/get_category_name.test.js deleted file mode 100644 index 731281933161b3..00000000000000 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/get_category_name.test.js +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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 expect from '@kbn/expect'; -import { getCategoryName } from '../get_category_name'; - -describe('Settings', function() { - describe('Advanced', function() { - describe('getCategoryName(category)', function() { - it('should be a function', function() { - expect(getCategoryName).to.be.a(Function); - }); - - it('should return correct name for known categories', function() { - expect(getCategoryName('general')).to.be('General'); - expect(getCategoryName('timelion')).to.be('Timelion'); - expect(getCategoryName('notifications')).to.be('Notifications'); - expect(getCategoryName('visualizations')).to.be('Visualizations'); - expect(getCategoryName('discover')).to.be('Discover'); - expect(getCategoryName('dashboard')).to.be('Dashboard'); - expect(getCategoryName('reporting')).to.be('Reporting'); - expect(getCategoryName('search')).to.be('Search'); - }); - - it('should capitalize unknown category', function() { - expect(getCategoryName('elasticsearch')).to.be('Elasticsearch'); - }); - - it('should return empty string for no category', function() { - expect(getCategoryName()).to.be(''); - expect(getCategoryName('')).to.be(''); - expect(getCategoryName(false)).to.be(''); - }); - }); - }); -}); diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/default_category.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/default_category.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/lib/default_category.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/lib/default_category.ts diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/get_aria_name.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_aria_name.test.ts similarity index 88% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/get_aria_name.test.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_aria_name.test.ts index 0e54480813e3fb..e129481a397c16 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/get_aria_name.test.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_aria_name.test.ts @@ -18,15 +18,11 @@ */ import expect from '@kbn/expect'; -import { getAriaName } from '../get_aria_name'; +import { getAriaName } from './get_aria_name'; describe('Settings', function() { describe('Advanced', function() { describe('getAriaName(name)', function() { - it('should be a function', function() { - expect(getAriaName).to.be.a(Function); - }); - it('should return a space delimited lower-case string with no special characters', function() { expect(getAriaName('xPack:defaultAdminEmail')).to.be('x pack default admin email'); expect(getAriaName('doc_table:highlight')).to.be('doc table highlight'); @@ -36,7 +32,6 @@ describe('Settings', function() { it('should return an empty string if passed undefined or null', function() { expect(getAriaName()).to.be(''); expect(getAriaName(undefined)).to.be(''); - expect(getAriaName(null)).to.be(''); }); }); }); diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_aria_name.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_aria_name.ts similarity index 93% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_aria_name.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_aria_name.ts index c75c761328370d..d5c2be752a278a 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_aria_name.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_aria_name.ts @@ -26,8 +26,8 @@ import { words } from 'lodash'; * * Example: 'xPack:fooBar:foo_bar_baz' -> 'x pack foo bar foo bar baz' */ -export function getAriaName(name) { - return words(name) +export function getAriaName(name?: string) { + return words(name || '') .map(word => word.toLowerCase()) .join(' '); } diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/default_category.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_category_name.test.ts similarity index 69% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/default_category.test.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_category_name.test.ts index 1172542dbce3d0..73e303e20c64d7 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/default_category.test.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_category_name.test.ts @@ -18,13 +18,18 @@ */ import expect from '@kbn/expect'; -import { DEFAULT_CATEGORY } from '../default_category'; +import { getCategoryName } from './get_category_name'; describe('Settings', function() { describe('Advanced', function() { - describe('DEFAULT_CATEGORY', function() { - it('should be general', function() { - expect(DEFAULT_CATEGORY).to.be('general'); + describe('getCategoryName(category)', function() { + it('should capitalize unknown category', function() { + expect(getCategoryName('elasticsearch')).to.be('Elasticsearch'); + }); + + it('should return empty string for no category', function() { + expect(getCategoryName()).to.be(''); + expect(getCategoryName('')).to.be(''); }); }); }); diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_category_name.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_category_name.ts similarity index 92% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_category_name.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_category_name.ts index c64b332e8ebee3..d0361ba698eebf 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_category_name.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_category_name.ts @@ -19,9 +19,9 @@ import { i18n } from '@kbn/i18n'; -const upperFirst = (str = '') => str.replace(/^./, str => str.toUpperCase()); +const upperFirst = (str = '') => str.replace(/^./, strng => strng.toUpperCase()); -const names = { +const names: Record = { general: i18n.translate('kbn.management.settings.categoryNames.generalLabel', { defaultMessage: 'General', }), @@ -51,6 +51,6 @@ const names = { }), }; -export function getCategoryName(category) { +export function getCategoryName(category?: string) { return category ? names[category] || upperFirst(category) : ''; } diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/get_val_type.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_val_type.test.ts similarity index 93% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/get_val_type.test.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_val_type.test.ts index 0a6cce972e518b..ec59dcaa1ea290 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/get_val_type.test.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_val_type.test.ts @@ -18,15 +18,11 @@ */ import expect from '@kbn/expect'; -import { getValType } from '../get_val_type'; +import { getValType } from './get_val_type'; describe('Settings', function() { describe('Advanced', function() { describe('getValType(def, val)', function() { - it('should be a function', function() { - expect(getValType).to.be.a(Function); - }); - it('should return the explicitly defined type of a setting', function() { expect(getValType({ type: 'string' })).to.be('string'); expect(getValType({ type: 'json' })).to.be('json'); diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_val_type.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_val_type.ts similarity index 67% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_val_type.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_val_type.ts index 35ed1f14332ede..e0aafb6710b7b4 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_val_type.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/get_val_type.ts @@ -22,7 +22,11 @@ * @param {?} current value of the setting * @returns {string} the type to use for determining the display and editor */ -export function getValType(def, value) { + +import { UiSettingsType } from 'src/core/public'; +import { FieldSetting } from '../types'; + +export function getValType(def: Partial, value?: any): UiSettingsType { if (def.type) { return def.type; } @@ -31,5 +35,17 @@ export function getValType(def, value) { return 'array'; } - return def.value != null ? typeof def.value : typeof value; + const typeofVal = def.value != null ? typeof def.value : typeof value; + + if (typeofVal === 'bigint') { + return 'number'; + } + + if (typeofVal === 'symbol' || typeofVal === 'object' || typeofVal === 'function') { + throw new Error( + `incompatible UiSettingsType: '${def.name}' type ${typeofVal} | ${JSON.stringify(def)}` + ); + } + + return typeofVal; } diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/index.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/index.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/lib/index.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/lib/index.ts diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/is_default_value.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/is_default_value.test.ts similarity index 84% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/is_default_value.test.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/lib/is_default_value.test.ts index 58ffd0597a34a9..30531ca89b0b58 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/is_default_value.test.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/is_default_value.test.ts @@ -18,20 +18,29 @@ */ import expect from '@kbn/expect'; -import { isDefaultValue } from '../is_default_value'; +import { isDefaultValue } from './is_default_value'; +import { UiSettingsType } from '../../../../../../../../core/public'; describe('Settings', function() { describe('Advanced', function() { describe('getCategoryName(category)', function() { - it('should be a function', function() { - expect(isDefaultValue).to.be.a(Function); - }); - describe('when given a setting definition object', function() { const setting = { isCustom: false, value: 'value', defVal: 'defaultValue', + displayName: 'displayName', + name: 'name', + ariaName: 'ariaName', + description: 'description', + requiresPageReload: false, + type: 'string' as UiSettingsType, + isOverridden: false, + readOnly: false, + options: [], + optionLabels: { option: 'label' }, + category: ['category'], + validation: { regex: /regexString/, message: 'validation description' }, }; describe('that is custom', function() { diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/is_default_value.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/is_default_value.ts similarity index 90% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/lib/is_default_value.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/lib/is_default_value.ts index 166aed6aeb5130..53c2ef3187f091 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/is_default_value.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/is_default_value.ts @@ -16,8 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +import { FieldSetting } from '../types'; -export function isDefaultValue(setting) { +export function isDefaultValue(setting: FieldSetting) { return ( setting.isCustom || setting.value === undefined || diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/to_editable_config.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/to_editable_config.test.ts similarity index 75% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/to_editable_config.test.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/lib/to_editable_config.test.ts index 4896b4516dd1da..881a2eb003cc81 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/__tests__/to_editable_config.test.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/to_editable_config.test.ts @@ -17,8 +17,25 @@ * under the License. */ +import { UiSettingsParams, StringValidationRegex } from 'src/core/public'; import expect from '@kbn/expect'; -import { toEditableConfig } from '../to_editable_config'; +import { toEditableConfig } from './to_editable_config'; + +const defDefault = { + isOverridden: true, +}; + +function invoke({ + def = defDefault, + name = 'woah', + value = 'forreal', +}: { + def?: UiSettingsParams & { isOverridden?: boolean }; + name?: string; + value?: any; +}) { + return toEditableConfig({ def, name, value, isCustom: def === defDefault, isOverridden: true }); +} describe('Settings', function() { describe('Advanced', function() { @@ -38,17 +55,17 @@ describe('Settings', function() { }); describe('when given a setting definition object', function() { - let def; + let def: UiSettingsParams & { isOverridden?: boolean }; beforeEach(function() { def = { value: 'the original', description: 'the one and only', - options: 'all the options', + options: ['all the options'], }; }); it('is not marked as custom', function() { - expect(invoke({ def }).isCustom).to.be.false; + expect(invoke({ def }).isCustom).to.be(false); }); it('sets a default value', function() { @@ -65,7 +82,7 @@ describe('Settings', function() { describe('that contains a type', function() { it('sets that type', function() { - def.type = 'something'; + def.type = 'string'; expect(invoke({ def }).type).to.equal(def.type); }); }); @@ -84,37 +101,34 @@ describe('Settings', function() { message: 'must start with "foo"', }; const result = invoke({ def }); - expect(result.validation.regex).to.be.a(RegExp); - expect(result.validation.message).to.equal('must start with "foo"'); + const validationTyped = result.validation as StringValidationRegex; + expect(validationTyped.regex).to.be.a(RegExp); + expect(validationTyped.message).to.equal('must start with "foo"'); }); }); }); describe('when not given a setting definition object', function() { it('is marked as custom', function() { - expect(invoke().isCustom).to.be.true; + expect(invoke({}).isCustom).to.be(true); }); it('sets defVal to undefined', function() { - expect(invoke().defVal).to.be.undefined; + expect(invoke({}).defVal).to.be(undefined); }); it('sets description to undefined', function() { - expect(invoke().description).to.be.undefined; + expect(invoke({}).description).to.be(undefined); }); it('sets options to undefined', function() { - expect(invoke().options).to.be.undefined; + expect(invoke({}).options).to.be(undefined); }); it('sets validation to undefined', function() { - expect(invoke().validation).to.be.undefined; + expect(invoke({}).validation).to.be(undefined); }); }); }); }); }); - -function invoke({ def = false, name = 'woah', value = 'forreal' } = {}) { - return toEditableConfig({ def, name, value, isCustom: def === false }); -} diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/to_editable_config.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/to_editable_config.ts similarity index 74% rename from src/legacy/core_plugins/kibana/public/management/sections/settings/lib/to_editable_config.js rename to src/legacy/core_plugins/kibana/public/management/sections/settings/lib/to_editable_config.ts index 6efb89cfba2b25..2c27d72f7f645a 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/to_editable_config.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/lib/to_editable_config.ts @@ -17,6 +17,12 @@ * under the License. */ +import { + UiSettingsParams, + UserProvidedValues, + StringValidationRegexString, + SavedObjectAttribute, +} from 'src/core/public'; import { getValType } from './get_val_type'; import { getAriaName } from './get_aria_name'; import { DEFAULT_CATEGORY } from './default_category'; @@ -27,10 +33,25 @@ import { DEFAULT_CATEGORY } from './default_category'; * @param {object} current value of setting * @returns {object} the editable config object */ -export function toEditableConfig({ def, name, value, isCustom, isOverridden }) { +export function toEditableConfig({ + def, + name, + value, + isCustom, + isOverridden, +}: { + def: UiSettingsParams & UserProvidedValues; + name: string; + value: SavedObjectAttribute; + isCustom: boolean; + isOverridden: boolean; +}) { if (!def) { def = {}; } + + const validationTyped = def.validation as StringValidationRegexString; + const conf = { name, displayName: def.name || name, @@ -45,10 +66,10 @@ export function toEditableConfig({ def, name, value, isCustom, isOverridden }) { description: def.description, deprecation: def.deprecation, validation: - def.validation && def.validation.regexString + validationTyped && validationTyped.regexString ? { - regex: new RegExp(def.validation.regexString), - message: def.validation.message, + regex: new RegExp(validationTyped.regexString), + message: validationTyped.message, } : def.validation, options: def.options, diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/types.ts b/src/legacy/core_plugins/kibana/public/management/sections/settings/types.ts new file mode 100644 index 00000000000000..fea70110f60711 --- /dev/null +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/types.ts @@ -0,0 +1,54 @@ +/* + * 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 { + UiSettingsType, + StringValidation, + ImageValidation, + SavedObjectAttribute, +} from '../../../../../../../core/public'; + +export interface FieldSetting { + displayName: string; + name: string; + value: SavedObjectAttribute; + description?: string; + options?: string[]; + optionLabels?: Record; + requiresPageReload: boolean; + type: UiSettingsType; + category: string[]; + ariaName: string; + isOverridden: boolean; + defVal: SavedObjectAttribute; + isCustom: boolean; + validation?: StringValidation | ImageValidation; + readOnly?: boolean; + deprecation?: { + message: string; + docLinksKey: string; + }; +} + +// until eui searchbar and query are typed +export interface IQuery { + ast: any; // incomplete + text: string; + syntax: any; // incomplete +} diff --git a/src/legacy/core_plugins/kibana/ui_setting_defaults.js b/src/legacy/core_plugins/kibana/ui_setting_defaults.js index 9b848666541ce7..02a4f10a543c4a 100644 --- a/src/legacy/core_plugins/kibana/ui_setting_defaults.js +++ b/src/legacy/core_plugins/kibana/ui_setting_defaults.js @@ -257,6 +257,7 @@ export function getUiSettingDefaults() { defaultMessage: 'Default index', }), value: null, + type: 'string', description: i18n.translate('kbn.advancedSettings.defaultIndexText', { defaultMessage: 'The index to access if no index is set', }), diff --git a/src/legacy/core_plugins/telemetry/server/collectors/management/telemetry_management_collector.ts b/src/legacy/core_plugins/telemetry/server/collectors/management/telemetry_management_collector.ts index 44926b644ced5c..481b1e9af2a79b 100644 --- a/src/legacy/core_plugins/telemetry/server/collectors/management/telemetry_management_collector.ts +++ b/src/legacy/core_plugins/telemetry/server/collectors/management/telemetry_management_collector.ts @@ -32,7 +32,7 @@ export async function getTranslationCount(loader: any, locale: string): Promise< export function createCollectorFetch(server: Server) { return async function fetchUsageStats(): Promise { - const internalRepo = server.newPlatform.setup.core.savedObjects.createInternalRepository(); + const internalRepo = server.newPlatform.start.core.savedObjects.createInternalRepository(); const uiSettingsClient = server.newPlatform.start.core.uiSettings.asScopedToClient( new SavedObjectsClient(internalRepo) ); diff --git a/src/legacy/core_plugins/tests_bundle/tests_entry_template.js b/src/legacy/core_plugins/tests_bundle/tests_entry_template.js index 94263e7b76a976..57adf730f3dd96 100644 --- a/src/legacy/core_plugins/tests_bundle/tests_entry_template.js +++ b/src/legacy/core_plugins/tests_bundle/tests_entry_template.js @@ -78,6 +78,10 @@ const coreSystem = new CoreSystem({ buildNumber: 1234, legacyMode: true, legacyMetadata: { + app: { + id: 'karma', + title: 'Karma', + }, nav: [], version: '1.2.3', buildNum: 1234, diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/agg_row.js b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/agg_row.js index b07e1cef4fc812..a2f1640904dd02 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/agg_row.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/agg_row.js @@ -22,14 +22,13 @@ import React from 'react'; import { last } from 'lodash'; import { AddDeleteButtons } from '../add_delete_buttons'; import { EuiIcon, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; -import { injectI18n } from '@kbn/i18n/react'; import { SeriesDragHandler } from '../series_drag_handler'; +import { i18n } from '@kbn/i18n'; -function AggRowUi(props) { +export function AggRow(props) { let iconType = 'eyeClosed'; let iconColor = 'subdued'; const lastSibling = last(props.siblings); - const { intl } = props; if (lastSibling.id === props.model.id) { iconType = 'eye'; @@ -57,12 +56,10 @@ function AggRowUi(props) { { return value === option.value && isMetricEnabled(option.value, uiRestrictions); @@ -247,8 +247,7 @@ function AggSelectUi(props) { options = [ { - label: intl.formatMessage({ - id: 'visTypeTimeseries.aggSelect.aggGroups.metricAggLabel', + label: i18n.translate('visTypeTimeseries.aggSelect.aggGroups.metricAggLabel', { defaultMessage: 'Metric Aggregations', }), options: metricAggs.map(agg => ({ @@ -257,22 +256,19 @@ function AggSelectUi(props) { })), }, { - label: intl.formatMessage({ - id: 'visTypeTimeseries.aggSelect.aggGroups.parentPipelineAggLabel', + label: i18n.translate('visTypeTimeseries.aggSelect.aggGroups.parentPipelineAggLabel', { defaultMessage: 'Parent Pipeline Aggregations', }), options: pipelineAggs.filter(filterByPanelType(panelType)).map(disableSiblingAggs), }, { - label: intl.formatMessage({ - id: 'visTypeTimeseries.aggSelect.aggGroups.siblingPipelineAggLabel', + label: i18n.translate('visTypeTimeseries.aggSelect.aggGroups.siblingPipelineAggLabel', { defaultMessage: 'Sibling Pipeline Aggregations', }), options: siblingAggs.map(disableSiblingAggs), }, { - label: intl.formatMessage({ - id: 'visTypeTimeseries.aggSelect.aggGroups.specialAggLabel', + label: i18n.translate('visTypeTimeseries.aggSelect.aggGroups.specialAggLabel', { defaultMessage: 'Special Aggregations', }), options: specialAggs.map(disableSiblingAggs), @@ -289,8 +285,7 @@ function AggSelectUi(props) {
Array.isArray(model.variables) && model.script !== undefined; - render() { - const { siblings } = this.props; +export function CalculationAgg(props) { + const htmlId = htmlIdGenerator(); + const { siblings, model } = props; - const defaults = { script: '' }; - const model = { ...defaults, ...this.props.model }; + const handleChange = createChangeHandler(props.onChange, model); + const handleSelectChange = createSelectHandler(handleChange); + const handleTextChange = createTextHandler(handleChange); - const handleChange = createChangeHandler(this.props.onChange, model); - const handleSelectChange = createSelectHandler(handleChange); - const handleTextChange = createTextHandler(handleChange); + useEffect(() => { + if (!checkModel(model)) { + handleChange({ + variables: [newVariable()], + script: '', + }); + } + }, [handleChange, model]); - const htmlId = htmlIdGenerator(); + return ( + + + + + + + + + - return ( - - - - - - - - + + - + + + + - - + + - - - - - - - - } - fullWidth - helpText={ -
- params, - paramsName: params.<name>, - paramsInterval: params._interval, - }} - /> -
- } - > - -
-
-
-
- ); - } + values={{ + params: params, + paramsName: params.<name>, + paramsInterval: params._interval, + }} + /> +
+ } + > + + +
+ + + ); } CalculationAgg.propTypes = { diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/math.js b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/math.js index c62012927f951b..5ffcef12c3fcb1 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/math.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/math.js @@ -17,17 +17,15 @@ * under the License. */ -import React, { Component } from 'react'; +import React, { useEffect } from 'react'; import PropTypes from 'prop-types'; -import _ from 'lodash'; -import uuid from 'uuid'; import { AggRow } from './agg_row'; import { AggSelect } from './agg_select'; import { createChangeHandler } from '../lib/create_change_handler'; import { createSelectHandler } from '../lib/create_select_handler'; import { createTextHandler } from '../lib/create_text_handler'; -import { CalculationVars } from './vars'; +import { CalculationVars, newVariable } from './vars'; import { htmlIdGenerator, EuiFlexGroup, @@ -41,125 +39,121 @@ import { } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -export class MathAgg extends Component { - UNSAFE_componentWillMount() { - if (!this.props.model.variables) { - this.props.onChange( - _.assign({}, this.props.model, { - variables: [{ id: uuid.v1() }], - }) - ); - } - } +const checkModel = model => Array.isArray(model.variables) && model.script !== undefined; - render() { - const { siblings } = this.props; - const htmlId = htmlIdGenerator(); +export function MathAgg(props) { + const { siblings, model } = props; + const htmlId = htmlIdGenerator(); - const defaults = { script: '' }; - const model = { ...defaults, ...this.props.model }; + const handleChange = createChangeHandler(props.onChange, model); + const handleSelectChange = createSelectHandler(handleChange); + const handleTextChange = createTextHandler(handleChange); - const handleChange = createChangeHandler(this.props.onChange, model); - const handleSelectChange = createSelectHandler(handleChange); - const handleTextChange = createTextHandler(handleChange); + useEffect(() => { + if (!checkModel(model)) { + handleChange({ + variables: [newVariable()], + script: '', + }); + } + }, [handleChange, model]); - return ( - - - - - - - - + + + + - + + + + - - - - - - + + - + + + + - - - } - fullWidth - helpText={ - + } + fullWidth + helpText={ + - - - ), - params: params, - paramsName: params.<name>, - paramsValues: params._all.<name>.values, - paramsTimestamps: params._all.<name>.timestamps, - paramsTimestamp: params._timestamp, - paramsIndex: params._index, - paramsInterval: params._interval, - }} - /> - } - > - + + + ), + params: params, + paramsName: params.<name>, + paramsValues: params._all.<name>.values, + paramsTimestamps: params._all.<name>.timestamps, + paramsTimestamp: params._timestamp, + paramsIndex: params._index, + paramsInterval: params._interval, + }} /> - - - - - ); - } + } + > + + + + + + ); } MathAgg.propTypes = { diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/percentile.js b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/percentile.js index 3ce5be5b6875a8..500bba14d66c93 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/percentile.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/percentile.js @@ -18,8 +18,7 @@ */ import PropTypes from 'prop-types'; -import React, { Component } from 'react'; -import _ from 'lodash'; +import React, { useEffect } from 'react'; import { AggSelect } from './agg_select'; import { FieldSelect } from './field_select'; import { AggRow } from './agg_row'; @@ -39,82 +38,78 @@ import { Percentiles, newPercentile } from './percentile_ui'; const RESTRICT_FIELDS = [KBN_FIELD_TYPES.NUMBER]; -export class PercentileAgg extends Component { - // eslint-disable-line react/no-multi-comp +const checkModel = model => Array.isArray(model.percentiles); - UNSAFE_componentWillMount() { - if (!this.props.model.percentiles) { - this.props.onChange( - _.assign({}, this.props.model, { - percentiles: [newPercentile({ value: 50 })], - }) - ); - } - } +export function PercentileAgg(props) { + const { series, model, panel, fields } = props; + const htmlId = htmlIdGenerator(); - render() { - const { series, model, panel, fields } = this.props; + const handleChange = createChangeHandler(props.onChange, model); + const handleSelectChange = createSelectHandler(handleChange); + const indexPattern = + (series.override_index_pattern && series.series_index_pattern) || panel.index_pattern; - const handleChange = createChangeHandler(this.props.onChange, model); - const handleSelectChange = createSelectHandler(handleChange); - const indexPattern = - (series.override_index_pattern && series.series_index_pattern) || panel.index_pattern; - const htmlId = htmlIdGenerator(); + useEffect(() => { + if (!checkModel(model)) { + handleChange({ + percentiles: [newPercentile({ value: 50 })], + }); + } + }, [handleChange, model]); - return ( - - - - + return ( + + + + + + + + + + + - - - + - - - - } - > - - - - + + + - + - - - ); - } + + + ); } PercentileAgg.propTypes = { diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/vars.js b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/vars.js index 8553f08af1353e..3d4ce601c7244b 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/vars.js +++ b/src/legacy/core_plugins/vis_type_timeseries/public/components/aggs/vars.js @@ -19,14 +19,17 @@ import PropTypes from 'prop-types'; import React, { Component } from 'react'; +import uuid from 'uuid'; +import { i18n } from '@kbn/i18n'; import _ from 'lodash'; import { AddDeleteButtons } from '../add_delete_buttons'; import { collectionActions } from '../lib/collection_actions'; import { MetricSelect } from './metric_select'; import { EuiFlexGroup, EuiFlexItem, EuiFieldText } from '@elastic/eui'; -import { injectI18n } from '@kbn/i18n/react'; -class CalculationVarsUi extends Component { +export const newVariable = opts => ({ id: uuid.v1(), name: '', field: '', ...opts }); + +export class CalculationVars extends Component { constructor(props) { super(props); this.renderRow = this.renderRow.bind(this); @@ -42,21 +45,19 @@ class CalculationVarsUi extends Component { } renderRow(row, i, items) { - const handleAdd = collectionActions.handleAdd.bind(null, this.props); + const handleAdd = collectionActions.handleAdd.bind(null, this.props, newVariable); const handleDelete = collectionActions.handleDelete.bind(null, this.props, row); - const { intl } = this.props; + return ( { constructor(private initializerContext: PluginInitializerContext) {} public setup( - { http, savedObjects }: CoreSetup, + { http, getStartServices }: CoreSetup, { usageCollection }: { usageCollection?: UsageCollectionSetup } ) { registerKqlTelemetryRoute( http.createRouter(), - savedObjects, + getStartServices, this.initializerContext.logger.get('data', 'kql-telemetry') ); diff --git a/src/plugins/data/server/kql_telemetry/route.ts b/src/plugins/data/server/kql_telemetry/route.ts index 3185da22b12b32..d5725c859c9a90 100644 --- a/src/plugins/data/server/kql_telemetry/route.ts +++ b/src/plugins/data/server/kql_telemetry/route.ts @@ -22,7 +22,7 @@ import { schema } from '@kbn/config-schema'; export function registerKqlTelemetryRoute( router: IRouter, - savedObjects: CoreSetup['savedObjects'], + getStartServices: CoreSetup['getStartServices'], logger: Logger ) { router.post( @@ -35,6 +35,7 @@ export function registerKqlTelemetryRoute( }, }, async (context, request, response) => { + const [{ savedObjects }] = await getStartServices(); const internalRepository = savedObjects.createScopedRepository(request); const { diff --git a/src/plugins/home/server/services/sample_data/sample_data_registry.ts b/src/plugins/home/server/services/sample_data/sample_data_registry.ts index 7a4909668fff2e..aac680211e52e4 100644 --- a/src/plugins/home/server/services/sample_data/sample_data_registry.ts +++ b/src/plugins/home/server/services/sample_data/sample_data_registry.ts @@ -51,7 +51,7 @@ export class SampleDataRegistry { makeSampleDataUsageCollector(usageCollections, this.initContext); } const usageTracker = usage( - core.savedObjects, + core.getStartServices().then(([coreStart]) => coreStart.savedObjects), this.initContext.logger.get('sample_data', 'telemetry') ); const router = core.http.createRouter(); diff --git a/src/plugins/home/server/services/sample_data/usage/usage.ts b/src/plugins/home/server/services/sample_data/usage/usage.ts index a06dde387bb367..59599a1bee68fc 100644 --- a/src/plugins/home/server/services/sample_data/usage/usage.ts +++ b/src/plugins/home/server/services/sample_data/usage/usage.ts @@ -17,7 +17,7 @@ * under the License. */ -import { Logger, SavedObjectsServiceSetup } from 'kibana/server'; +import { Logger, SavedObjectsServiceStart } from 'kibana/server'; const SAVED_OBJECT_ID = 'sample-data-telemetry'; @@ -27,7 +27,7 @@ export interface SampleDataUsageTracker { } export function usage( - savedObjects: SavedObjectsServiceSetup, + savedObjects: Promise, logger: Logger ): SampleDataUsageTracker { const handleIncrementError = (err: Error) => { @@ -37,11 +37,12 @@ export function usage( logger.warn(`saved objects repository incrementCounter encountered an error: ${err}`); }; - const internalRepository = savedObjects.createInternalRepository(); + const internalRepositoryPromise = savedObjects.then(so => so.createInternalRepository()); return { addInstall: async (dataSet: string) => { try { + const internalRepository = await internalRepositoryPromise; await internalRepository.incrementCounter(SAVED_OBJECT_ID, dataSet, `installCount`); } catch (err) { handleIncrementError(err); @@ -49,6 +50,7 @@ export function usage( }, addUninstall: async (dataSet: string) => { try { + const internalRepository = await internalRepositoryPromise; await internalRepository.incrementCounter(SAVED_OBJECT_ID, dataSet, `unInstallCount`); } catch (err) { handleIncrementError(err); diff --git a/src/plugins/home/server/tutorials/register.ts b/src/plugins/home/server/tutorials/register.ts index ae84f1e7ee1d56..ab5788865bd8ea 100644 --- a/src/plugins/home/server/tutorials/register.ts +++ b/src/plugins/home/server/tutorials/register.ts @@ -85,6 +85,7 @@ import { ibmmqLogsSpecProvider } from './ibmmq_logs'; import { stanMetricsSpecProvider } from './stan_metrics'; import { envoyproxyMetricsSpecProvider } from './envoyproxy_metrics'; import { ibmmqMetricsSpecProvider } from './ibmmq_metrics'; +import { statsdMetricsSpecProvider } from './statsd_metrics'; export const builtInTutorials = [ systemLogsSpecProvider, @@ -156,4 +157,5 @@ export const builtInTutorials = [ ibmmqMetricsSpecProvider, stanMetricsSpecProvider, envoyproxyMetricsSpecProvider, + statsdMetricsSpecProvider, ]; diff --git a/src/plugins/home/server/tutorials/statsd_metrics/index.ts b/src/plugins/home/server/tutorials/statsd_metrics/index.ts new file mode 100644 index 00000000000000..c1d4a354e94967 --- /dev/null +++ b/src/plugins/home/server/tutorials/statsd_metrics/index.ts @@ -0,0 +1,61 @@ +/* + * 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 { i18n } from '@kbn/i18n'; +import { TutorialsCategory, TutorialSchema } from '../../services/tutorials'; +import { + onPremInstructions, + cloudInstructions, + onPremCloudInstructions, +} from '../instructions/metricbeat_instructions'; +import { TutorialContext } from '../../services/tutorials/lib/tutorials_registry_types'; + +export function statsdMetricsSpecProvider(context: TutorialContext): TutorialSchema { + const moduleName = 'statsd'; + return { + id: 'statsdMetrics', + name: i18n.translate('home.tutorials.statsdMetrics.nameTitle', { + defaultMessage: 'Statsd metrics', + }), + category: TutorialsCategory.METRICS, + shortDescription: i18n.translate('home.tutorials.statsdMetrics.shortDescription', { + defaultMessage: 'Fetch monitoring metrics from statsd.', + }), + longDescription: i18n.translate('home.tutorials.statsdMetrics.longDescription', { + defaultMessage: + 'The `statsd` Metricbeat module fetches monitoring metrics from statsd. \ +[Learn more]({learnMoreLink}).', + values: { + learnMoreLink: '{config.docs.beats.metricbeat}/metricbeat-module-statsd.html', + }, + }), + euiIconType: '/plugins/kibana/home/tutorial_resources/logos/statsd.svg', + artifacts: { + dashboards: [], + exportedFields: { + documentationUrl: '{config.docs.beats.metricbeat}/exported-fields-statsd.html', + }, + }, + completionTimeMinutes: 10, + // previewImagePath: '', + onPrem: onPremInstructions(moduleName, context), + elasticCloud: cloudInstructions(moduleName), + onPremElasticCloud: onPremCloudInstructions(moduleName), + }; +} diff --git a/src/plugins/vis_type_timeseries/server/validation_telemetry/validation_telemetry_service.ts b/src/plugins/vis_type_timeseries/server/validation_telemetry/validation_telemetry_service.ts index 136f5b9e5cfad8..e49664265b8bbb 100644 --- a/src/plugins/vis_type_timeseries/server/validation_telemetry/validation_telemetry_service.ts +++ b/src/plugins/vis_type_timeseries/server/validation_telemetry/validation_telemetry_service.ts @@ -64,11 +64,14 @@ export class ValidationTelemetryService implements Plugin start.savedObjects.createInternalRepository()); return { logFailedValidation: async () => { try { + const internalRepository = await internalRepositoryPromise; await internalRepository.incrementCounter( 'tsvb-validation-telemetry', 'tsvb-validation-telemetry', diff --git a/test/functional/services/browser.ts b/test/functional/services/browser.ts index 2d799b7daca732..02349b4e6cca2c 100644 --- a/test/functional/services/browser.ts +++ b/test/functional/services/browser.ts @@ -313,11 +313,23 @@ export async function BrowserProvider({ getService }: FtrProviderContext) { /** * Moves forwards in the browser history. * https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_Navigation.html#forward + * + * @return {Promise} */ public async goForward() { await driver.navigate().forward(); } + /** + * Navigates to a URL via the browser history. + * https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_Navigation.html#to + * + * @return {Promise} + */ + public async navigateTo(url: string) { + await driver.navigate().to(url); + } + /** * Sends a sequance of keyboard keys. For each key, this will record a pair of keyDown and keyUp actions * https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/input_exports_Actions.html#sendKeys diff --git a/test/plugin_functional/plugins/core_plugin_chromeless/public/plugin.tsx b/test/plugin_functional/plugins/core_plugin_chromeless/public/plugin.tsx index 03870410fb3342..7ce348fa2111e1 100644 --- a/test/plugin_functional/plugins/core_plugin_chromeless/public/plugin.tsx +++ b/test/plugin_functional/plugins/core_plugin_chromeless/public/plugin.tsx @@ -31,12 +31,6 @@ export class CorePluginChromelessPlugin return renderApp(context, params); }, }); - - return { - getGreeting() { - return 'Hello from Plugin Chromeless!'; - }, - }; } public start() {} diff --git a/test/plugin_functional/plugins/rendering_plugin/public/plugin.tsx b/test/plugin_functional/plugins/rendering_plugin/public/plugin.tsx index 6e80b56953ca07..a4925cdb8f8dfd 100644 --- a/test/plugin_functional/plugins/rendering_plugin/public/plugin.tsx +++ b/test/plugin_functional/plugins/rendering_plugin/public/plugin.tsx @@ -26,13 +26,24 @@ export class RenderingPlugin implements Plugin { core.application.register({ id: 'rendering', title: 'Rendering', - appRoute: '/render', + appRoute: '/render/core', async mount(context, { element }) { render(

rendering service

, element); return () => unmountComponentAtNode(element); }, }); + + core.application.register({ + id: 'custom-app-route', + title: 'Custom App Route', + appRoute: '/custom/appRoute', + async mount(context, { element }) { + render(

Custom App Route

, element); + + return () => unmountComponentAtNode(element); + }, + }); } public start() {} diff --git a/test/plugin_functional/test_suites/core_plugins/rendering.ts b/test/plugin_functional/test_suites/core_plugins/rendering.ts index d0025c82a7ba50..e30d81eedd985b 100644 --- a/test/plugin_functional/test_suites/core_plugins/rendering.ts +++ b/test/plugin_functional/test_suites/core_plugins/rendering.ts @@ -22,43 +22,55 @@ import expect from '@kbn/expect'; import '../../plugins/core_provider_plugin/types'; import { PluginFunctionalProviderContext } from '../../services'; +declare global { + interface Window { + /** + * We use this global variable to track page history changes to ensure that + * navigation is done without causing a full page reload. + */ + __RENDERING_SESSION__: string[]; + } +} + // eslint-disable-next-line import/no-default-export export default function({ getService, getPageObjects }: PluginFunctionalProviderContext) { const PageObjects = getPageObjects(['common']); + const appsMenu = getService('appsMenu'); const browser = getService('browser'); const find = getService('find'); const testSubjects = getService('testSubjects'); - function navigate(path: string) { - return browser.get(`${PageObjects.common.getHostPort()}${path}`); - } - - function getLegacyMode() { + const navigateTo = (path: string) => + browser.navigateTo(`${PageObjects.common.getHostPort()}${path}`); + const navigateToApp = async (title: string) => { + await appsMenu.clickLink(title); return browser.execute(() => { + if (!('__RENDERING_SESSION__' in window)) { + window.__RENDERING_SESSION__ = []; + } + + window.__RENDERING_SESSION__.push(window.location.pathname); + }); + }; + const getLegacyMode = () => + browser.execute(() => { return JSON.parse(document.querySelector('kbn-injected-metadata')!.getAttribute('data')!) .legacyMode; }); - } - - function getUserSettings() { - return browser.execute(() => { + const getUserSettings = () => + browser.execute(() => { return JSON.parse(document.querySelector('kbn-injected-metadata')!.getAttribute('data')!) .legacyMetadata.uiSettings.user; }); - } - - async function init() { - const loading = await testSubjects.find('kbnLoadingMessage', 5000); - - return () => find.waitForElementStale(loading); - } + const exists = (selector: string) => testSubjects.exists(selector, { timeout: 2000 }); + const findLoadingMessage = () => testSubjects.find('kbnLoadingMessage', 5000); describe('rendering service', () => { it('renders "core" application', async () => { - await navigate('/render/core'); + await navigateTo('/render/core'); - const [loaded, legacyMode, userSettings] = await Promise.all([ - init(), + const [loadingMessage, legacyMode, userSettings] = await Promise.all([ + findLoadingMessage(), getLegacyMode(), getUserSettings(), ]); @@ -66,16 +78,16 @@ export default function({ getService, getPageObjects }: PluginFunctionalProvider expect(legacyMode).to.be(false); expect(userSettings).to.not.be.empty(); - await loaded(); + await find.waitForElementStale(loadingMessage); - expect(await testSubjects.exists('renderingHeader')).to.be(true); + expect(await exists('renderingHeader')).to.be(true); }); it('renders "core" application without user settings', async () => { - await navigate('/render/core?includeUserSettings=false'); + await navigateTo('/render/core?includeUserSettings=false'); - const [loaded, legacyMode, userSettings] = await Promise.all([ - init(), + const [loadingMessage, legacyMode, userSettings] = await Promise.all([ + findLoadingMessage(), getLegacyMode(), getUserSettings(), ]); @@ -83,16 +95,16 @@ export default function({ getService, getPageObjects }: PluginFunctionalProvider expect(legacyMode).to.be(false); expect(userSettings).to.be.empty(); - await loaded(); + await find.waitForElementStale(loadingMessage); - expect(await testSubjects.exists('renderingHeader')).to.be(true); + expect(await exists('renderingHeader')).to.be(true); }); it('renders "legacy" application', async () => { - await navigate('/render/core_plugin_legacy'); + await navigateTo('/render/core_plugin_legacy'); - const [loaded, legacyMode, userSettings] = await Promise.all([ - init(), + const [loadingMessage, legacyMode, userSettings] = await Promise.all([ + findLoadingMessage(), getLegacyMode(), getUserSettings(), ]); @@ -100,17 +112,17 @@ export default function({ getService, getPageObjects }: PluginFunctionalProvider expect(legacyMode).to.be(true); expect(userSettings).to.not.be.empty(); - await loaded(); + await find.waitForElementStale(loadingMessage); - expect(await testSubjects.exists('coreLegacyCompatH1')).to.be(true); - expect(await testSubjects.exists('renderingHeader')).to.be(false); + expect(await exists('coreLegacyCompatH1')).to.be(true); + expect(await exists('renderingHeader')).to.be(false); }); it('renders "legacy" application without user settings', async () => { - await navigate('/render/core_plugin_legacy?includeUserSettings=false'); + await navigateTo('/render/core_plugin_legacy?includeUserSettings=false'); - const [loaded, legacyMode, userSettings] = await Promise.all([ - init(), + const [loadingMessage, legacyMode, userSettings] = await Promise.all([ + findLoadingMessage(), getLegacyMode(), getUserSettings(), ]); @@ -118,10 +130,56 @@ export default function({ getService, getPageObjects }: PluginFunctionalProvider expect(legacyMode).to.be(true); expect(userSettings).to.be.empty(); - await loaded(); + await find.waitForElementStale(loadingMessage); + + expect(await exists('coreLegacyCompatH1')).to.be(true); + expect(await exists('renderingHeader')).to.be(false); + }); + + it('navigates between standard application and one with custom appRoute', async () => { + await navigateTo('/'); + await find.waitForElementStale(await findLoadingMessage()); + + await navigateToApp('App Status'); + expect(await exists('appStatusApp')).to.be(true); + expect(await exists('renderingHeader')).to.be(false); + + await navigateToApp('Rendering'); + expect(await exists('appStatusApp')).to.be(false); + expect(await exists('renderingHeader')).to.be(true); + + await navigateToApp('App Status'); + expect(await exists('appStatusApp')).to.be(true); + expect(await exists('renderingHeader')).to.be(false); + + expect( + await browser.execute(() => { + return window.__RENDERING_SESSION__; + }) + ).to.eql(['/app/app_status', '/render/core', '/app/app_status']); + }); + + it('navigates between applications with custom appRoutes', async () => { + await navigateTo('/'); + await find.waitForElementStale(await findLoadingMessage()); + + await navigateToApp('Rendering'); + expect(await exists('renderingHeader')).to.be(true); + expect(await exists('customAppRouteHeader')).to.be(false); + + await navigateToApp('Custom App Route'); + expect(await exists('renderingHeader')).to.be(false); + expect(await exists('customAppRouteHeader')).to.be(true); + + await navigateToApp('Rendering'); + expect(await exists('renderingHeader')).to.be(true); + expect(await exists('customAppRouteHeader')).to.be(false); - expect(await testSubjects.exists('coreLegacyCompatH1')).to.be(true); - expect(await testSubjects.exists('renderingHeader')).to.be(false); + expect( + await browser.execute(() => { + return window.__RENDERING_SESSION__; + }) + ).to.eql(['/render/core', '/custom/appRoute', '/render/core']); }); }); } diff --git a/x-pack/.i18nrc.json b/x-pack/.i18nrc.json index 34ab2c878a19f2..32ff4908629ebe 100644 --- a/x-pack/.i18nrc.json +++ b/x-pack/.i18nrc.json @@ -40,7 +40,7 @@ "xpack.transform": "legacy/plugins/transform", "xpack.upgradeAssistant": "legacy/plugins/upgrade_assistant", "xpack.uptime": "legacy/plugins/uptime", - "xpack.watcher": "legacy/plugins/watcher" + "xpack.watcher": "plugins/watcher" }, "translations": [ "plugins/translations/translations/zh-CN.json", diff --git a/x-pack/dev-tools/jest/create_jest_config.js b/x-pack/dev-tools/jest/create_jest_config.js index b746f0ae258cd1..2d8a0be7a416fa 100644 --- a/x-pack/dev-tools/jest/create_jest_config.js +++ b/x-pack/dev-tools/jest/create_jest_config.js @@ -21,7 +21,6 @@ export function createJestConfig({ kibanaDirectory, xPackKibanaDirectory }) { 'uiExports/(.*)': fileMockPath, '^src/core/(.*)': `${kibanaDirectory}/src/core/$1`, '^src/legacy/(.*)': `${kibanaDirectory}/src/legacy/$1`, - '^plugins/watcher/np_ready/application/models/(.*)': `${xPackKibanaDirectory}/legacy/plugins/watcher/public/np_ready/application/models/$1`, '^plugins/([^/.]*)(.*)': `${kibanaDirectory}/src/legacy/core_plugins/$1/public$2`, '^legacy/plugins/xpack_main/(.*);': `${xPackKibanaDirectory}/legacy/plugins/xpack_main/public/$1`, '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': fileMockPath, diff --git a/x-pack/legacy/plugins/alerting/server/plugin.ts b/x-pack/legacy/plugins/alerting/server/plugin.ts index 357db9e3df97ed..3218d9eeb2ef46 100644 --- a/x-pack/legacy/plugins/alerting/server/plugin.ts +++ b/x-pack/legacy/plugins/alerting/server/plugin.ts @@ -128,11 +128,12 @@ export class Plugin { this.taskRunnerFactory.initialize({ logger: this.logger, - getServices(request: Hapi.Request): Services { + getServices(rawRequest: Hapi.Request): Services { + const request = KibanaRequest.from(rawRequest); return { - callCluster: (...args) => - adminClient!.asScoped(KibanaRequest.from(request)).callAsCurrentUser(...args), - savedObjectsClient: core.savedObjects.getScopedSavedObjectsClient(request), + callCluster: (...args) => adminClient!.asScoped(request).callAsCurrentUser(...args), + // rawRequest is actually a fake request, converting it to KibanaRequest causes issue in SO access + savedObjectsClient: core.savedObjects.getScopedSavedObjectsClient(rawRequest as any), }; }, spaceIdToNamespace, diff --git a/x-pack/legacy/plugins/index_lifecycle_management/public/sections/edit_policy/components/hot_phase/hot_phase.js b/x-pack/legacy/plugins/index_lifecycle_management/public/sections/edit_policy/components/hot_phase/hot_phase.js index d57bf759ad7219..475d26bb2e3c04 100644 --- a/x-pack/legacy/plugins/index_lifecycle_management/public/sections/edit_policy/components/hot_phase/hot_phase.js +++ b/x-pack/legacy/plugins/index_lifecycle_management/public/sections/edit_policy/components/hot_phase/hot_phase.js @@ -169,6 +169,30 @@ export class HotPhase extends PureComponent { defaultMessage: 'megabytes', }), }, + { + value: 'b', + text: i18n.translate('xpack.indexLifecycleMgmt.hotPhase.bytesLabel', { + defaultMessage: 'bytes', + }), + }, + { + value: 'kb', + text: i18n.translate('xpack.indexLifecycleMgmt.hotPhase.kilobytesLabel', { + defaultMessage: 'kilobytes', + }), + }, + { + value: 'tb', + text: i18n.translate('xpack.indexLifecycleMgmt.hotPhase.terabytesLabel', { + defaultMessage: 'terabytes', + }), + }, + { + value: 'pb', + text: i18n.translate('xpack.indexLifecycleMgmt.hotPhase.petabytesLabel', { + defaultMessage: 'petabytes', + }), + }, ]} /> @@ -254,6 +278,45 @@ export class HotPhase extends PureComponent { defaultMessage: 'hours', }), }, + { + value: 'm', + text: i18n.translate('xpack.indexLifecycleMgmt.hotPhase.minutesLabel', { + defaultMessage: 'minutes', + }), + }, + { + value: 's', + text: i18n.translate('xpack.indexLifecycleMgmt.hotPhase.secondsLabel', { + defaultMessage: 'seconds', + }), + }, + { + value: 'ms', + text: i18n.translate( + 'xpack.indexLifecycleMgmt.hotPhase.millisecondsLabel', + { + defaultMessage: 'milliseconds', + } + ), + }, + { + value: 'micros', + text: i18n.translate( + 'xpack.indexLifecycleMgmt.hotPhase.microsecondsLabel', + { + defaultMessage: 'microseconds', + } + ), + }, + { + value: 'nanos', + text: i18n.translate( + 'xpack.indexLifecycleMgmt.hotPhase.nanosecondsLabel', + { + defaultMessage: 'nanoseconds', + } + ), + }, ]} /> diff --git a/x-pack/legacy/plugins/index_lifecycle_management/public/sections/edit_policy/components/min_age_input.js b/x-pack/legacy/plugins/index_lifecycle_management/public/sections/edit_policy/components/min_age_input.js index b4c9f4e958cd22..23009798513296 100644 --- a/x-pack/legacy/plugins/index_lifecycle_management/public/sections/edit_policy/components/min_age_input.js +++ b/x-pack/legacy/plugins/index_lifecycle_management/public/sections/edit_policy/components/min_age_input.js @@ -73,6 +73,11 @@ export const MinAgeInput = props => { let daysOptionLabel; let hoursOptionLabel; + let minutesOptionLabel; + let secondsOptionLabel; + let millisecondsOptionLabel; + let microsecondsOptionLabel; + let nanosecondsOptionLabel; if (rolloverEnabled) { daysOptionLabel = i18n.translate( @@ -88,6 +93,39 @@ export const MinAgeInput = props => { defaultMessage: 'hours from rollover', } ); + minutesOptionLabel = i18n.translate( + 'xpack.indexLifecycleMgmt.editPolicy.rolloverMinutesOptionLabel', + { + defaultMessage: 'minutes from rollover', + } + ); + + secondsOptionLabel = i18n.translate( + 'xpack.indexLifecycleMgmt.editPolicy.rolloverSecondsOptionLabel', + { + defaultMessage: 'seconds from rollover', + } + ); + millisecondsOptionLabel = i18n.translate( + 'xpack.indexLifecycleMgmt.editPolicy.rolloverMilliSecondsOptionLabel', + { + defaultMessage: 'milliseconds from rollover', + } + ); + + microsecondsOptionLabel = i18n.translate( + 'xpack.indexLifecycleMgmt.editPolicy.rolloverMicroSecondsOptionLabel', + { + defaultMessage: 'microseconds from rollover', + } + ); + + nanosecondsOptionLabel = i18n.translate( + 'xpack.indexLifecycleMgmt.editPolicy.rolloverNanoSecondsOptionLabel', + { + defaultMessage: 'nanoseconds from rollover', + } + ); } else { daysOptionLabel = i18n.translate( 'xpack.indexLifecycleMgmt.editPolicy.creationDaysOptionLabel', @@ -150,6 +188,26 @@ export const MinAgeInput = props => { value: 'h', text: hoursOptionLabel, }, + { + value: 'm', + text: minutesOptionLabel, + }, + { + value: 's', + text: secondsOptionLabel, + }, + { + value: 'ms', + text: millisecondsOptionLabel, + }, + { + value: 'micros', + text: microsecondsOptionLabel, + }, + { + value: 'nanos', + text: nanosecondsOptionLabel, + }, ]} /> diff --git a/x-pack/legacy/plugins/index_management/__jest__/client_integration/helpers/template_form.helpers.ts b/x-pack/legacy/plugins/index_management/__jest__/client_integration/helpers/template_form.helpers.ts index 48ae51b711f9cc..a7c87723b33fb8 100644 --- a/x-pack/legacy/plugins/index_management/__jest__/client_integration/helpers/template_form.helpers.ts +++ b/x-pack/legacy/plugins/index_management/__jest__/client_integration/helpers/template_form.helpers.ts @@ -198,7 +198,7 @@ export type TestSubjects = | 'backButton' | 'codeEditorContainer' | 'confirmModalConfirmButton' - | 'createFieldWrapper.addChildButton' + | 'createFieldWrapper.addPropertyButton' | 'createFieldWrapper.addButton' | 'createFieldWrapper.addFieldButton' | 'createFieldWrapper.addMultiFieldButton' diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/__jest__/client_integration/helpers/index.ts b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/__jest__/client_integration/helpers/index.ts new file mode 100644 index 00000000000000..e3313bfba56fd9 --- /dev/null +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/__jest__/client_integration/helpers/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { setup as mappingsEditorSetup } from './mappings_editor.helpers'; + +export { + nextTick, + getRandomString, + findTestSubject, + TestBed, +} from '../../../../../../../../../../test_utils'; + +export const componentHelpers = { + mappingsEditor: { setup: mappingsEditorSetup }, +}; diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/__jest__/client_integration/helpers/mappings_editor.helpers.ts b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/__jest__/client_integration/helpers/mappings_editor.helpers.ts new file mode 100644 index 00000000000000..b8b67a0f36bd2e --- /dev/null +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/__jest__/client_integration/helpers/mappings_editor.helpers.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { registerTestBed } from '../../../../../../../../../../test_utils'; +import { MappingsEditor } from '../../../mappings_editor'; + +export const setup = (props: any) => + registerTestBed(MappingsEditor, { + memoryRouter: { + wrapComponent: false, + }, + defaultProps: props, + }); diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/__jest__/client_integration/mappings_editor.test.tsx b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/__jest__/client_integration/mappings_editor.test.tsx new file mode 100644 index 00000000000000..9e390e785c7d56 --- /dev/null +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/__jest__/client_integration/mappings_editor.test.tsx @@ -0,0 +1,55 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { componentHelpers } from './helpers'; + +const { setup } = componentHelpers.mappingsEditor; +const mockOnUpdate = () => undefined; + +describe('', () => { + describe('multiple mappings detection', () => { + test('should show a warning when multiple mappings are detected', async () => { + const defaultValue = { + type1: { + properties: { + name1: { + type: 'keyword', + }, + }, + }, + type2: { + properties: { + name2: { + type: 'keyword', + }, + }, + }, + }; + const testBed = await setup({ onUpdate: mockOnUpdate, defaultValue })(); + const { exists } = testBed; + + expect(exists('mappingsEditor')).toBe(true); + expect(exists('mappingTypesDetectedCallout')).toBe(true); + expect(exists('documentFields')).toBe(false); + }); + + test('should not show a warning when mappings a single-type', async () => { + const defaultValue = { + properties: { + name1: { + type: 'keyword', + }, + }, + }; + const testBed = await setup({ onUpdate: mockOnUpdate, defaultValue })(); + const { exists } = testBed; + + expect(exists('mappingsEditor')).toBe(true); + expect(exists('mappingTypesDetectedCallout')).toBe(false); + expect(exists('documentFields')).toBe(true); + }); + }); +}); diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/document_fields.tsx b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/document_fields.tsx index 71b5966c3295db..378d669dee69cb 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/document_fields.tsx +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/document_fields.tsx @@ -48,7 +48,7 @@ export const DocumentFields = React.memo(() => { const searchTerm = search.term.trim(); return ( - <> +
{searchTerm !== '' ? ( @@ -57,6 +57,6 @@ export const DocumentFields = React.memo(() => { editor )} {renderEditField()} - +
); }); diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/field_parameters/analyzers_parameter.tsx b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/field_parameters/analyzers_parameter.tsx index 46b0ece4b325ea..0cf22946bf60a6 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/field_parameters/analyzers_parameter.tsx +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/field_parameters/analyzers_parameter.tsx @@ -46,7 +46,11 @@ export const AnalyzersParameter = ({ field, withSearchQuoteAnalyzer = false }: P }); return ( - + ); }} @@ -74,7 +78,7 @@ export const AnalyzersParameter = ({ field, withSearchQuoteAnalyzer = false }: P @@ -88,7 +92,7 @@ export const AnalyzersParameter = ({ field, withSearchQuoteAnalyzer = false }: P diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/field_parameters/dynamic_parameter.tsx b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/field_parameters/dynamic_parameter.tsx new file mode 100644 index 00000000000000..975a6cd9bba4f5 --- /dev/null +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/field_parameters/dynamic_parameter.tsx @@ -0,0 +1,93 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { i18n } from '@kbn/i18n'; + +import { documentationService } from '../../../../../services/documentation'; +import { UseField, CheckBoxField } from '../../../shared_imports'; +import { getFieldConfig } from '../../../lib'; +import { Field } from '../../../types'; +import { EditFieldFormRow } from '../fields/edit_field'; + +/** + * Export custom serializer to be used when we need to serialize the form data to be sent to ES + * @param field The field to be serialized + */ +export const dynamicSerializer = (field: Field): Field => { + if (field.dynamic_toggle === undefined) { + return field; + } + + const dynamic = + field.dynamic_toggle === true ? true : field.dynamic_strict === true ? 'strict' : false; + const { dynamic_toggle, dynamic_strict, ...rest } = field; + + return { + ...rest, + dynamic, + }; +}; + +/** + * Export custom deserializer to be used when we need to deserialize the data coming from ES + * @param field The field to be serialized + */ +export const dynamicDeserializer = (field: Field): Field => { + if (field.dynamic === undefined) { + return field; + } + + const dynamicToggleValue = field.dynamic === true; + const dynamicStrictValue = field.dynamic === 'strict'; + + return { + ...field, + dynamic_toggle: dynamicToggleValue, + dynamic_strict: dynamicStrictValue, + }; +}; +interface Props { + defaultToggleValue: boolean; +} + +export const DynamicParameter = ({ defaultToggleValue }: Props) => { + return ( + + {isOn => { + return isOn === false ? ( + + ) : null; + }} + + ); +}; diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/field_parameters/enabled_parameter.tsx b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/field_parameters/enabled_parameter.tsx new file mode 100644 index 00000000000000..719dd89d4c05c9 --- /dev/null +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/field_parameters/enabled_parameter.tsx @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiCode } from '@elastic/eui'; + +import { documentationService } from '../../../../../services/documentation'; +import { EditFieldFormRow } from '../fields/edit_field'; + +export const EnabledParameter = () => { + return ( + _source, + }} + /> + } + docLink={{ + text: i18n.translate('xpack.idxMgmt.mappingsEditor.enabledDocLinkText', { + defaultMessage: 'Enabled documentation', + }), + href: documentationService.getEnabledLink(), + }} + formFieldPath="enabled" + /> + ); +}; diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/field_parameters/index.ts b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/field_parameters/index.ts index 94a49012f1c3b3..663017e2e47afd 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/field_parameters/index.ts +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/field_parameters/index.ts @@ -5,6 +5,7 @@ */ import { relationsSerializer, relationsDeserializer } from './relations_parameter'; +import { dynamicSerializer, dynamicDeserializer } from './dynamic_parameter'; export * from './name_parameter'; @@ -54,10 +55,14 @@ export * from './split_queries_on_whitespace_parameter'; export * from './locale_parameter'; +export * from './dynamic_parameter'; + +export * from './enabled_parameter'; + export * from './max_shingle_size_parameter'; export * from './relations_parameter'; -export const PARAMETER_SERIALIZERS = [relationsSerializer]; +export const PARAMETER_SERIALIZERS = [relationsSerializer, dynamicSerializer]; -export const PARAMETER_DESERIALIZERS = [relationsDeserializer]; +export const PARAMETER_DESERIALIZERS = [relationsDeserializer, dynamicDeserializer]; diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/date_type.tsx b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/date_type.tsx index 3165f18aff4b3d..0c067d09046d73 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/date_type.tsx +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/date_type.tsx @@ -48,7 +48,7 @@ export const DateType = ({ field }: Props) => { diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/index.ts b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/index.ts index bad41d1f88efcc..6e18e29f827d4c 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/index.ts +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/index.ts @@ -24,6 +24,8 @@ import { SearchAsYouType } from './search_as_you_type'; import { FlattenedType } from './flattened_type'; import { ShapeType } from './shape_type'; import { DenseVectorType } from './dense_vector_type'; +import { ObjectType } from './object_type'; +import { NestedType } from './nested_type'; import { JoinType } from './join_type'; const typeToParametersFormMap: { [key in DataType]?: ComponentType } = { @@ -45,6 +47,8 @@ const typeToParametersFormMap: { [key in DataType]?: ComponentType } = { flattened: FlattenedType, shape: ShapeType, dense_vector: DenseVectorType, + object: ObjectType, + nested: NestedType, join: JoinType, }; diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/nested_type.tsx b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/nested_type.tsx new file mode 100644 index 00000000000000..72aa88ed75ffb4 --- /dev/null +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/nested_type.tsx @@ -0,0 +1,24 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React from 'react'; + +import { NormalizedField } from '../../../../types'; +import { DynamicParameter } from '../../field_parameters'; +import { BasicParametersSection } from '../edit_field'; + +interface Props { + field: NormalizedField; +} + +export const NestedType = ({ field }: Props) => { + return ( + + + + ); +}; diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/numeric_type.tsx b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/numeric_type.tsx index 367a7002815819..89af480d79a205 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/numeric_type.tsx +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/numeric_type.tsx @@ -50,7 +50,7 @@ export const NumericType = ({ field }: Props) => { {formData => formData.subType === 'scaled_float' ? ( diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/object_type.tsx b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/object_type.tsx new file mode 100644 index 00000000000000..fef1f9860ca51f --- /dev/null +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/object_type.tsx @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React from 'react'; + +import { NormalizedField } from '../../../../types'; +import { DynamicParameter, EnabledParameter } from '../../field_parameters'; +import { BasicParametersSection } from '../edit_field'; + +interface Props { + field: NormalizedField; +} + +export const ObjectType = ({ field }: Props) => { + return ( + + + + + + ); +}; diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/range_type.tsx b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/range_type.tsx index 0be754bcfb966d..a7d2af41c83e68 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/range_type.tsx +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/range_type.tsx @@ -36,7 +36,7 @@ export const RangeType = ({ field }: Props) => { {formData => formData.subType === 'date_range' ? ( ) : null diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/token_count_type.tsx b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/token_count_type.tsx index a2b429373a3e4e..42854673269aee 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/token_count_type.tsx +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/field_types/token_count_type.tsx @@ -60,7 +60,7 @@ export const TokenCountType = ({ field }: Props) => { diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/fields_list_item.tsx b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/fields_list_item.tsx index 285598fc8c3c13..4c1c8bc1da1143 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/fields_list_item.tsx +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/document_fields/fields/fields_list_item.tsx @@ -113,9 +113,12 @@ function FieldListItemComponent( } ); - const addChildButtonLabel = i18n.translate('xpack.idxMgmt.mappingsEditor.addChildButtonLabel', { - defaultMessage: 'Add child', - }); + const addPropertyButtonLabel = i18n.translate( + 'xpack.idxMgmt.mappingsEditor.addPropertyButtonLabel', + { + defaultMessage: 'Add property', + } + ); const editButtonLabel = i18n.translate('xpack.idxMgmt.mappingsEditor.editFieldButtonLabel', { defaultMessage: 'Edit', @@ -145,12 +148,12 @@ function FieldListItemComponent( {canHaveChildFields && ( - + diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/index.ts b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/index.ts index d5ad51ba358391..2958ecd75910f3 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/index.ts +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/index.ts @@ -9,3 +9,5 @@ export * from './configuration_form'; export * from './document_fields'; export * from './templates_form'; + +export * from './multiple_mappings_warning'; diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/multiple_mappings_warning.tsx b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/multiple_mappings_warning.tsx new file mode 100644 index 00000000000000..507e4dac262ff0 --- /dev/null +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/components/multiple_mappings_warning.tsx @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiCallOut, EuiLink } from '@elastic/eui'; + +import { documentationService } from '../../../services/documentation'; + +export const MultipleMappingsWarning = () => ( + +

+ + {i18n.translate( + 'xpack.idxMgmt.mappingsEditor.mappingTypesDetectedCallOutDocumentationLink', + { + defaultMessage: 'Consider these alternatives to mapping types.', + } + )} + + ), + }} + /> +

+
+); diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/constants/parameters_definition.tsx b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/constants/parameters_definition.tsx index 2ea525bdb522f5..732449f382f93c 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/constants/parameters_definition.tsx +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/constants/parameters_definition.tsx @@ -17,7 +17,13 @@ import { fieldFormatters, FieldConfig, } from '../shared_imports'; -import { AliasOption, DataType, ComboBoxOption } from '../types'; +import { + AliasOption, + DataType, + ComboBoxOption, + ParameterName, + ParameterDefinition, +} from '../types'; import { documentationService } from '../../../services/documentation'; import { INDEX_DEFAULT } from './default_values'; import { TYPE_DEFINITION } from './data_types_definition'; @@ -124,7 +130,7 @@ const analyzerValidations = [ * * As a consequence, if a parameter is *not* declared here, we won't be able to declare it in the Json editor. */ -export const PARAMETERS_DEFINITION = { +export const PARAMETERS_DEFINITION: { [key in ParameterName]: ParameterDefinition } = { name: { fieldConfig: { label: i18n.translate('xpack.idxMgmt.mappingsEditor.nameFieldLabel', { @@ -537,20 +543,32 @@ export const PARAMETERS_DEFINITION = { }, dynamic: { fieldConfig: { - label: i18n.translate('xpack.idxMgmt.mappingsEditor.dynamicFieldLabel', { - defaultMessage: 'Dynamic', - }), - type: FIELD_TYPES.CHECKBOX, defaultValue: true, }, - schema: t.boolean, + schema: t.union([t.boolean, t.literal('strict')]), }, - enabled: { + dynamic_toggle: { + fieldConfig: { + defaultValue: true, + }, + }, + dynamic_strict: { fieldConfig: { - label: i18n.translate('xpack.idxMgmt.mappingsEditor.enabledFieldLabel', { - defaultMessage: 'Enabled', + defaultValue: false, + label: i18n.translate('xpack.idxMgmt.mappingsEditor.dynamicStrictParameter.fieldTitle', { + defaultMessage: 'Throw an exception when the object contains an unmapped property', }), - type: FIELD_TYPES.CHECKBOX, + helpText: i18n.translate( + 'xpack.idxMgmt.mappingsEditor.dynamicStrictParameter.fieldHelpText', + { + defaultMessage: + 'By default, unmapped properties will be silently ignored when dynamic mapping is disabled. Optionally, you can choose to throw an exception when an object contains an unmapped property.', + } + ), + }, + }, + enabled: { + fieldConfig: { defaultValue: true, }, schema: t.boolean, diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/extract_mappings_definition.test.ts b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/extract_mappings_definition.test.ts new file mode 100644 index 00000000000000..3e38ff5991a8c7 --- /dev/null +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/extract_mappings_definition.test.ts @@ -0,0 +1,128 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { extractMappingsDefinition } from './extract_mappings_definition'; + +describe('extractMappingsDefinition', () => { + test('should detect that the mappings has multiple types and return null', () => { + const mappings = { + type1: { + properties: { + name1: { + type: 'keyword', + }, + }, + }, + type2: { + properties: { + name2: { + type: 'keyword', + }, + }, + }, + }; + + expect(extractMappingsDefinition(mappings)).toBe(null); + }); + + test('should detect that the mappings has multiple types even when one of the type has not defined any "properties"', () => { + const mappings = { + type1: { + _source: { + excludes: [], + includes: [], + enabled: true, + }, + _routing: { + required: false, + }, + }, + type2: { + properties: { + name2: { + type: 'keyword', + }, + }, + }, + }; + + expect(extractMappingsDefinition(mappings)).toBe(null); + }); + + test('should detect that one of the mapping type is invalid and filter it out', () => { + const mappings = { + type1: { + invalidSetting: { + excludes: [], + includes: [], + enabled: true, + }, + _routing: { + required: false, + }, + }, + type2: { + properties: { + name2: { + type: 'keyword', + }, + }, + }, + }; + + expect(extractMappingsDefinition(mappings)).toBe(mappings.type2); + }); + + test('should detect that the mappings has one type and return its mapping definition', () => { + const mappings = { + myType: { + _source: { + excludes: [], + includes: [], + enabled: true, + }, + _meta: {}, + _routing: { + required: false, + }, + dynamic: true, + properties: { + title: { + type: 'keyword', + }, + }, + }, + }; + + expect(extractMappingsDefinition(mappings)).toBe(mappings.myType); + }); + + test('should detect that the mappings has one type at root level', () => { + const mappings = { + _source: { + excludes: [], + includes: [], + enabled: true, + }, + _meta: {}, + _routing: { + required: false, + }, + dynamic: true, + numeric_detection: false, + date_detection: true, + dynamic_date_formats: ['strict_date_optional_time'], + dynamic_templates: [], + properties: { + title: { + type: 'keyword', + }, + }, + }; + + expect(extractMappingsDefinition(mappings)).toBe(mappings); + }); +}); diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/extract_mappings_definition.ts b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/extract_mappings_definition.ts new file mode 100644 index 00000000000000..eae3c5b15759ca --- /dev/null +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/extract_mappings_definition.ts @@ -0,0 +1,103 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { isPlainObject } from 'lodash'; + +import { GenericObject } from '../types'; +import { + validateMappingsConfiguration, + mappingsConfigurationSchemaKeys, +} from './mappings_validator'; + +const ALLOWED_PARAMETERS = [...mappingsConfigurationSchemaKeys, 'dynamic_templates', 'properties']; + +const isMappingDefinition = (obj: GenericObject): boolean => { + const areAllKeysValid = Object.keys(obj).every(key => ALLOWED_PARAMETERS.includes(key)); + + if (!areAllKeysValid) { + return false; + } + + const { properties, dynamic_templates: dynamicTemplates, ...mappingsConfiguration } = obj; + + const { errors } = validateMappingsConfiguration(mappingsConfiguration); + const isConfigurationValid = errors.length === 0; + const isPropertiesValid = properties === undefined || isPlainObject(properties); + const isDynamicTemplatesValid = dynamicTemplates === undefined || Array.isArray(dynamicTemplates); + + // If the configuration, the properties and the dynamic templates are valid + // we can assume that the mapping is declared at root level (no types) + return isConfigurationValid && isPropertiesValid && isDynamicTemplatesValid; +}; + +/** + * 5.x index templates can be created with multiple types. + * e.g. + ``` + const mappings = { + type1: { + properties: { + name1: { + type: 'keyword', + }, + }, + }, + type2: { + properties: { + name2: { + type: 'keyword', + }, + }, + }, + }; + ``` + * A mappings can also be declared under an explicit "_doc" property. + ``` + const mappings = { + _doc: { + _source: { + "enabled": false + }, + properties: { + name1: { + type: 'keyword', + }, + }, + }, + }; + ``` + * This helpers parse the mappings provided an removes any possible mapping "type" declared + * + * @param mappings The mappings object to validate + */ +export const extractMappingsDefinition = (mappings: GenericObject = {}): GenericObject | null => { + if (isMappingDefinition(mappings)) { + // No need to go any further + return mappings; + } + + // At this point there must be one or more type mappings + const typedMappings = Object.values(mappings).reduce((acc: GenericObject[], value) => { + if (isMappingDefinition(value)) { + acc.push(value as GenericObject); + } + return acc; + }, []); + + // If there are no typed mappings found this means that one of the type must did not pass + // the "isMappingDefinition()" validation. + // In theory this should never happen but let's make sure the UI does not try to load an invalid mapping + if (typedMappings.length === 0) { + return null; + } + + // If there's only one mapping type then we can consume it as if the type doesn't exist. + if (typedMappings.length === 1) { + return typedMappings[0]; + } + + // If there's more than one mapping type, then the mappings object isn't usable. + return null; +}; diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/index.ts b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/index.ts index 1b1c5cc8dc8d48..8cd1bbf0764ab0 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/index.ts +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/index.ts @@ -13,3 +13,5 @@ export * from './validators'; export * from './mappings_validator'; export * from './search_fields'; + +export * from './extract_mappings_definition'; diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/mappings_validator.test.ts b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/mappings_validator.test.ts index c8bb7e5b60fb39..f1e6efb06c6492 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/mappings_validator.test.ts +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/mappings_validator.test.ts @@ -3,8 +3,9 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import { isPlainObject } from 'lodash'; -import { validateMappings, validateProperties, isObject } from './mappings_validator'; +import { validateMappings, validateProperties } from './mappings_validator'; describe('Mappings configuration validator', () => { it('should convert non object to empty object', () => { @@ -12,7 +13,7 @@ describe('Mappings configuration validator', () => { tests.forEach(testValue => { const { value, errors } = validateMappings(testValue as any); - expect(isObject(value)).toBe(true); + expect(isPlainObject(value)).toBe(true); expect(errors).toBe(undefined); }); }); @@ -76,7 +77,7 @@ describe('Properties validator', () => { tests.forEach(testValue => { const { value, errors } = validateProperties(testValue as any); - expect(isObject(value)).toBe(true); + expect(isPlainObject(value)).toBe(true); expect(errors).toEqual([]); }); }); @@ -280,7 +281,7 @@ describe('Properties validator', () => { orientation: 'ccw', boost: 1.5, scaling_factor: 2.5, - dynamic: true, + dynamic: 'strict', // true | false | 'strict' are allowed enabled: true, format: 'strict_date_optional_time', analyzer: 'standard', @@ -310,14 +311,24 @@ describe('Properties validator', () => { dims: 'abc', max_shingle_size: 2, }, + goodField2: { + type: 'object', + dynamic: true, + }, + goodField3: { + type: 'object', + dynamic: false, + }, }; const { value, errors } = validateProperties(properties as any); - expect(Object.keys(value)).toEqual(['wrongField', 'goodField']); + expect(Object.keys(value)).toEqual(['wrongField', 'goodField', 'goodField2', 'goodField3']); expect(value.wrongField).toEqual({ type: 'text' }); // All parameters have been stripped out but the "type". expect(value.goodField).toEqual(properties.goodField); // All parameters are stil there. + expect(value.goodField2).toEqual(properties.goodField2); + expect(value.goodField3).toEqual(properties.goodField3); const allWrongParameters = Object.keys(properties.wrongField).filter(v => v !== 'type'); expect(errors).toEqual( diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/mappings_validator.ts b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/mappings_validator.ts index fff735da2e7585..6ccbfeb50dcf44 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/mappings_validator.ts +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/mappings_validator.ts @@ -3,15 +3,16 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { pick } from 'lodash'; +import { pick, isPlainObject } from 'lodash'; import * as t from 'io-ts'; import { ordString } from 'fp-ts/lib/Ord'; import { toArray } from 'fp-ts/lib/Set'; import { isLeft, isRight } from 'fp-ts/lib/Either'; + import { errorReporter } from './error_reporter'; import { ALL_DATA_TYPES, PARAMETERS_DEFINITION } from '../constants'; import { FieldMeta } from '../types'; -import { getFieldMeta } from '../lib'; +import { getFieldMeta } from './utils'; const ALLOWED_FIELD_PROPERTIES = [ ...Object.keys(PARAMETERS_DEFINITION), @@ -49,8 +50,6 @@ interface GenericObject { [key: string]: any; } -export const isObject = (obj: any) => obj != null && obj.constructor.name === 'Object'; - const validateFieldType = (type: any): boolean => { if (typeof type !== 'string') { return false; @@ -72,7 +71,7 @@ const validateParameter = (parameter: string, value: any): boolean => { } if (parameter === 'properties' || parameter === 'fields') { - return isObject(value); + return isPlainObject(value); } const parameterSchema = (PARAMETERS_DEFINITION as any)[parameter]!.schema; @@ -100,7 +99,7 @@ const stripUnknownOrInvalidParameter = (field: GenericObject): FieldValidatorRes const parseField = (field: any): FieldValidatorResponse & { meta?: FieldMeta } => { // Sanitize the input to make sure we are working with an object - if (!isObject(field)) { + if (!isPlainObject(field)) { return { parametersRemoved: [] }; } // Make sure the field "type" is valid @@ -186,7 +185,7 @@ const parseFields = ( */ export const validateProperties = (properties = {}): PropertiesValidatorResponse => { // Sanitize the input to make sure we are working with an object - if (!isObject(properties)) { + if (!isPlainObject(properties)) { return { value: {}, errors: [] }; } @@ -213,9 +212,9 @@ export const mappingsConfigurationSchema = t.partial({ }), }); -const mappingsConfigurationSchemaKeys = Object.keys(mappingsConfigurationSchema.props); +export const mappingsConfigurationSchemaKeys = Object.keys(mappingsConfigurationSchema.props); -const validateMappingsConfiguration = ( +export const validateMappingsConfiguration = ( mappingsConfiguration: any ): { value: any; errors: MappingsValidationError[] } => { // Set to keep track of invalid configuration parameters. @@ -249,7 +248,7 @@ const validateMappingsConfiguration = ( }; export const validateMappings = (mappings: any = {}): MappingsValidatorResponse => { - if (!isObject(mappings)) { + if (!isPlainObject(mappings)) { return { value: {} }; } diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/utils.ts b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/utils.ts index 50e4023c8c7426..337554ab5fa5a1 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/utils.ts +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/lib/utils.ts @@ -79,10 +79,10 @@ export const getFieldConfig = (param: ParameterName, prop?: string): FieldConfig ) { throw new Error(`No field config found for prop "${prop}" on param "${param}" `); } - return (PARAMETERS_DEFINITION[param] as any).props[prop].fieldConfig || {}; + return (PARAMETERS_DEFINITION[param] as any).props[prop]?.fieldConfig || {}; } - return (PARAMETERS_DEFINITION[param] as any).fieldConfig || {}; + return (PARAMETERS_DEFINITION[param] as any)?.fieldConfig || {}; }; /** diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/mappings_editor.tsx b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/mappings_editor.tsx index e3fdf42d889e97..d79a023386e8d6 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/mappings_editor.tsx +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/mappings_editor.tsx @@ -4,14 +4,20 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { useMemo, useState } from 'react'; +import React, { useMemo, useState, useEffect } from 'react'; import { i18n } from '@kbn/i18n'; import { EuiSpacer, EuiTabs, EuiTab } from '@elastic/eui'; -import { ConfigurationForm, DocumentFields, TemplatesForm } from './components'; +import { + ConfigurationForm, + DocumentFields, + TemplatesForm, + MultipleMappingsWarning, +} from './components'; import { IndexSettings } from './types'; +import { extractMappingsDefinition } from './lib'; import { State } from './reducer'; -import { MappingsState, Props as MappingsStateProps } from './mappings_state'; +import { MappingsState, Props as MappingsStateProps, Types } from './mappings_state'; import { IndexSettingsProvider } from './index_settings_context'; interface Props { @@ -25,7 +31,13 @@ type TabName = 'fields' | 'advanced' | 'templates'; export const MappingsEditor = React.memo(({ onUpdate, defaultValue, indexSettings }: Props) => { const [selectedTab, selectTab] = useState('fields'); - const parsedDefaultValue = useMemo(() => { + const { parsedDefaultValue, multipleMappingsDeclared } = useMemo(() => { + const mappingsDefinition = extractMappingsDefinition(defaultValue); + + if (mappingsDefinition === null) { + return { multipleMappingsDeclared: true }; + } + const { _source = {}, _meta = {}, @@ -36,9 +48,9 @@ export const MappingsEditor = React.memo(({ onUpdate, defaultValue, indexSetting dynamic_date_formats, properties = {}, dynamic_templates, - } = defaultValue ?? {}; + } = mappingsDefinition; - return { + const parsed = { configuration: { _source, _meta, @@ -53,8 +65,21 @@ export const MappingsEditor = React.memo(({ onUpdate, defaultValue, indexSetting dynamic_templates, }, }; + + return { parsedDefaultValue: parsed, multipleMappingsDeclared: false }; }, [defaultValue]); + useEffect(() => { + if (multipleMappingsDeclared) { + // We set the data getter here as the user won't be able to make any changes + onUpdate({ + getData: () => defaultValue! as Types['Mappings'], + validate: () => Promise.resolve(true), + isValid: true, + }); + } + }, [multipleMappingsDeclared]); + const changeTab = async (tab: TabName, state: State) => { if (selectedTab === 'advanced') { // When we navigate away we need to submit the form to validate if there are any errors. @@ -63,7 +88,6 @@ export const MappingsEditor = React.memo(({ onUpdate, defaultValue, indexSetting if (!isConfigurationFormValid) { /** * Don't navigate away from the tab if there are errors in the form. - * For now there is no need to display a CallOut as the form can never be invalid. */ return; } @@ -79,51 +103,57 @@ export const MappingsEditor = React.memo(({ onUpdate, defaultValue, indexSetting }; return ( - - - {({ state }) => { - const tabToContentMap = { - fields: , - templates: , - advanced: , - }; - - return ( -
- - changeTab('fields', state)} - isSelected={selectedTab === 'fields'} - > - {i18n.translate('xpack.idxMgmt.mappingsEditor.fieldsTabLabel', { - defaultMessage: 'Mapped fields', - })} - - changeTab('templates', state)} - isSelected={selectedTab === 'templates'} - > - {i18n.translate('xpack.idxMgmt.mappingsEditor.templatesTabLabel', { - defaultMessage: 'Dynamic templates', - })} - - changeTab('advanced', state)} - isSelected={selectedTab === 'advanced'} - > - {i18n.translate('xpack.idxMgmt.mappingsEditor.advancedTabLabel', { - defaultMessage: 'Advanced options', - })} - - - - - - {tabToContentMap[selectedTab]} -
- ); - }} -
-
+
+ {multipleMappingsDeclared ? ( + + ) : ( + + + {({ state }) => { + const tabToContentMap = { + fields: , + templates: , + advanced: , + }; + + return ( +
+ + changeTab('fields', state)} + isSelected={selectedTab === 'fields'} + > + {i18n.translate('xpack.idxMgmt.mappingsEditor.fieldsTabLabel', { + defaultMessage: 'Mapped fields', + })} + + changeTab('templates', state)} + isSelected={selectedTab === 'templates'} + > + {i18n.translate('xpack.idxMgmt.mappingsEditor.templatesTabLabel', { + defaultMessage: 'Dynamic templates', + })} + + changeTab('advanced', state)} + isSelected={selectedTab === 'advanced'} + > + {i18n.translate('xpack.idxMgmt.mappingsEditor.advancedTabLabel', { + defaultMessage: 'Advanced options', + })} + + + + + + {tabToContentMap[selectedTab]} +
+ ); + }} +
+
+ )} +
); }); diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/reducer.ts b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/reducer.ts index 26d5b8e1edfa58..1e6733b1632d76 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/reducer.ts +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/reducer.ts @@ -174,7 +174,7 @@ const updateAliasesReferences = ( ); } - const targetId = field.source.path!; + const targetId = field.source.path! as string; if (!updatedAliases[targetId]) { updatedAliases[targetId] = []; @@ -420,7 +420,7 @@ export const reducer = (state: State, action: Action): State => { /** * If we delete an alias field, we need to remove its id from the reference Array */ - const targetId = field.source.path; + const targetId = field.source.path as string; updatedFields.aliases = { ...updatedFields.aliases, [targetId]: updatedFields.aliases[targetId].filter(aliasId => aliasId !== id), @@ -455,7 +455,7 @@ export const reducer = (state: State, action: Action): State => { updatedFields.aliases = updateAliasesReferences( newField, updatedFields, - previousField.source.path + previousField.source.path as string ); } @@ -489,9 +489,9 @@ export const reducer = (state: State, action: Action): State => { // We need to remove its reference from our state.aliases map updatedFields.aliases = { ...updatedFields.aliases, - [previousField.source.path]: updatedFields.aliases[previousField.source.path].filter( - aliasId => aliasId !== fieldToEdit - ), + [previousField.source.path as string]: updatedFields.aliases[ + previousField.source.path as string + ].filter(aliasId => aliasId !== fieldToEdit), }; } else { const nextTypeCanHaveAlias = !PARAMETERS_DEFINITION.path.targetTypesNotAllowed.includes( diff --git a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/types.ts b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/types.ts index 55ec2fbcc99e65..dbbffe5a0bd316 100644 --- a/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/types.ts +++ b/x-pack/legacy/plugins/index_management/public/app/components/mappings_editor/types.ts @@ -19,6 +19,19 @@ export interface DataTypeDefinition { description?: () => ReactNode; } +export interface ParameterDefinition { + title?: string; + description?: JSX.Element | string; + fieldConfig: FieldConfig; + schema?: any; + props?: { [key: string]: ParameterDefinition }; + documentation?: { + main: string; + [key: string]: string; + }; + [key: string]: any; +} + export type MainType = | 'text' | 'keyword' @@ -88,6 +101,8 @@ export type ParameterName = | 'null_value_ip' | 'copy_to' | 'dynamic' + | 'dynamic_toggle' + | 'dynamic_strict' | 'enabled' | 'boost' | 'locale' @@ -144,10 +159,10 @@ interface FieldBasic { } type FieldParams = { - [K in ParameterName]: typeof PARAMETERS_DEFINITION[K]['fieldConfig']['defaultValue']; + [K in ParameterName]: typeof PARAMETERS_DEFINITION[K]['fieldConfig']['defaultValue'] | unknown; }; -export type Field = FieldBasic & FieldParams; +export type Field = FieldBasic & Partial; export interface FieldMeta { childFieldsName: ChildFieldName | undefined; @@ -272,3 +287,7 @@ export interface SearchMetadata { */ stringMatch: string | null; } + +export interface GenericObject { + [key: string]: any; +} diff --git a/x-pack/legacy/plugins/index_management/public/app/services/documentation.ts b/x-pack/legacy/plugins/index_management/public/app/services/documentation.ts index d705dfa94adcac..9bf0d983df161f 100644 --- a/x-pack/legacy/plugins/index_management/public/app/services/documentation.ts +++ b/x-pack/legacy/plugins/index_management/public/app/services/documentation.ts @@ -40,13 +40,17 @@ class DocumentationService { return `${this.kibanaDocsBase}/managing-indices.html`; } - public getTypeDocLink = (type: DataType, uri = 'main'): string | undefined => { + public getTypeDocLink = (type: DataType, docType = 'main'): string | undefined => { const typeDefinition = TYPE_DEFINITION[type]; - if (!typeDefinition || !typeDefinition.documentation || !typeDefinition.documentation[uri]) { + if ( + !typeDefinition || + !typeDefinition.documentation || + !typeDefinition.documentation[docType] + ) { return undefined; } - return `${this.esDocsBase}${typeDefinition.documentation[uri]}`; + return `${this.esDocsBase}${typeDefinition.documentation[docType]}`; }; public getMappingTypesLink() { @@ -177,10 +181,22 @@ class DocumentationService { return `${this.esDocsBase}/index-options.html`; } + public getAlternativeToMappingTypesLink() { + return `${this.esDocsBase}/removal-of-types.html#_alternatives_to_mapping_types`; + } + public getJoinMultiLevelsPerformanceLink() { return `${this.esDocsBase}/parent-join.html#_parent_join_and_performance`; } + public getDynamicLink() { + return `${this.esDocsBase}/dynamic.html`; + } + + public getEnabledLink() { + return `${this.esDocsBase}/enabled.html`; + } + public getWellKnownTextLink() { return 'http://docs.opengeospatial.org/is/12-063r5/12-063r5.html'; } diff --git a/x-pack/legacy/plugins/infra/public/pages/infrastructure/snapshot/index.tsx b/x-pack/legacy/plugins/infra/public/pages/infrastructure/snapshot/index.tsx index b9651763e43c06..27d276a50c30d0 100644 --- a/x-pack/legacy/plugins/infra/public/pages/infrastructure/snapshot/index.tsx +++ b/x-pack/legacy/plugins/infra/public/pages/infrastructure/snapshot/index.tsx @@ -6,8 +6,9 @@ import { EuiButton, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; - +import { identity } from 'fp-ts/lib/function'; import React, { useContext } from 'react'; + import { SnapshotPageContent } from './page_content'; import { SnapshotToolbar } from './toolbar'; @@ -38,10 +39,11 @@ export const SnapshotPage = () => { loadSource, metricIndicesExist, } = useContext(Source.Context); - const basePath = useKibana().services.http?.basePath || ''; useTrackPageview({ app: 'infra_metrics', path: 'inventory' }); useTrackPageview({ app: 'infra_metrics', path: 'inventory', delay: 15000 }); + const prependBasePath = useKibana().services.http?.basePath.prepend ?? identity; + return ( { { - const basePath = useKibana().services.http?.basePath || ''; - const uiCapabilities = useKibana().services.application?.capabilities; + const { + services: { application, http }, + } = useKibana<{}>(); + + const canConfigureSource = application?.capabilities?.logs?.configureSource ? true : false; + const prependBasePath = http?.basePath.prepend ?? identity; + return ( { { })} - {uiCapabilities?.logs?.configureSource ? ( + {canConfigureSource ? ( = ({ nodeName }) => { - const basePath = useKibana().services.http?.basePath || ''; + const prependBasePath = useKibana().services.http?.basePath.prepend ?? identity; + return ( = diff --git a/x-pack/legacy/plugins/license_management/public/np_ready/application/app.js b/x-pack/legacy/plugins/license_management/public/np_ready/application/app.js index 7122e7269732a2..7c497518b9df50 100644 --- a/x-pack/legacy/plugins/license_management/public/np_ready/application/app.js +++ b/x-pack/legacy/plugins/license_management/public/np_ready/application/app.js @@ -8,7 +8,7 @@ import React, { Component } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; import { LicenseDashboard, UploadLicense } from './sections'; import { Switch, Route } from 'react-router-dom'; -import { APP_PERMISSION } from '../../../common/constants'; +import { APP_PERMISSION, BASE_PATH } from '../../../common/constants'; import { EuiPageBody, EuiEmptyPrompt, EuiText, EuiLoadingSpinner, EuiCallOut } from '@elastic/eui'; export class App extends Component { @@ -88,10 +88,8 @@ export class App extends Component { return ( - - - {/* Match all */} - + + ); diff --git a/x-pack/legacy/plugins/license_management/public/np_ready/application/boot.tsx b/x-pack/legacy/plugins/license_management/public/np_ready/application/boot.tsx index d0bf5deacfac10..2780b54230eba3 100644 --- a/x-pack/legacy/plugins/license_management/public/np_ready/application/boot.tsx +++ b/x-pack/legacy/plugins/license_management/public/np_ready/application/boot.tsx @@ -63,7 +63,7 @@ export const boot = (deps: AppDependencies) => { render( - + diff --git a/x-pack/legacy/plugins/license_management/public/np_ready/application/sections/license_dashboard/license_dashboard.js b/x-pack/legacy/plugins/license_management/public/np_ready/application/sections/license_dashboard/license_dashboard.js index 3dc44796fd0ef0..e14d392fe6706e 100644 --- a/x-pack/legacy/plugins/license_management/public/np_ready/application/sections/license_dashboard/license_dashboard.js +++ b/x-pack/legacy/plugins/license_management/public/np_ready/application/sections/license_dashboard/license_dashboard.js @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; - +import React, { useEffect } from 'react'; import { LicenseStatus } from './license_status'; import { RevertToBasic } from './revert_to_basic'; import { StartTrial } from './start_trial'; @@ -14,7 +13,10 @@ import { RequestTrialExtension } from './request_trial_extension'; import { EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui'; export const LicenseDashboard = ({ setBreadcrumb } = { setBreadcrumb: () => {} }) => { - setBreadcrumb('dashboard'); + useEffect(() => { + setBreadcrumb('dashboard'); + }); + return (
diff --git a/x-pack/legacy/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx b/x-pack/legacy/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx index a28dc41fa1790f..db42c90d49ebbf 100644 --- a/x-pack/legacy/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx +++ b/x-pack/legacy/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx @@ -9,12 +9,11 @@ import React, { useRef, FC } from 'react'; import { TooltipValueFormatter } from '@elastic/charts'; import useObservable from 'react-use/lib/useObservable'; -import { chartTooltip$, ChartTooltipValue } from './chart_tooltip_service'; +import { chartTooltip$, ChartTooltipState, ChartTooltipValue } from './chart_tooltip_service'; type RefValue = HTMLElement | null; -function useRefWithCallback() { - const chartTooltipState = useObservable(chartTooltip$); +function useRefWithCallback(chartTooltipState?: ChartTooltipState) { const ref = useRef(null); return (node: RefValue) => { @@ -66,7 +65,7 @@ const renderHeader = (headerData?: ChartTooltipValue, formatter?: TooltipValueFo export const ChartTooltip: FC = () => { const chartTooltipState = useObservable(chartTooltip$); - const chartTooltipElement = useRefWithCallback(); + const chartTooltipElement = useRefWithCallback(chartTooltipState); if (chartTooltipState === undefined || !chartTooltipState.isTooltipVisible) { return
; diff --git a/x-pack/legacy/plugins/ml/public/application/routing/routes/explorer.tsx b/x-pack/legacy/plugins/ml/public/application/routing/routes/explorer.tsx index 633efc2856dac1..adef7055f97480 100644 --- a/x-pack/legacy/plugins/ml/public/application/routing/routes/explorer.tsx +++ b/x-pack/legacy/plugins/ml/public/application/routing/routes/explorer.tsx @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import moment from 'moment'; import React, { FC, useEffect, useState } from 'react'; import useObservable from 'react-use/lib/useObservable'; @@ -70,7 +69,7 @@ interface ExplorerUrlStateManagerProps { const ExplorerUrlStateManager: FC = ({ jobsWithTimeRange }) => { const [appState, setAppState] = useUrlState('_a'); - const [globalState] = useUrlState('_g'); + const [globalState, setGlobalState] = useUrlState('_g'); const [lastRefresh, setLastRefresh] = useState(0); const { jobIds } = useJobSelection(jobsWithTimeRange, getDateFormatTz()); @@ -79,13 +78,37 @@ const ExplorerUrlStateManager: FC = ({ jobsWithTim useEffect(() => { if (refresh !== undefined) { setLastRefresh(refresh?.lastRefresh); - const activeBounds = timefilter.getActiveBounds(); - if (activeBounds !== undefined) { - explorerService.setBounds(activeBounds); + + if (refresh.timeRange !== undefined) { + const { start, end } = refresh.timeRange; + setGlobalState('time', { + from: start, + to: end, + }); } } }, [refresh?.lastRefresh]); + // We cannot simply infer bounds from the globalState's `time` attribute + // with `moment` since it can contain custom strings such as `now-15m`. + // So when globalState's `time` changes, we update the timefilter and use + // `timefilter.getBounds()` to update `bounds` in this component's state. + useEffect(() => { + if (globalState?.time !== undefined) { + timefilter.setTime({ + from: globalState.time.from, + to: globalState.time.to, + }); + + const timefilterBounds = timefilter.getBounds(); + // Only if both min/max bounds are valid moment times set the bounds. + // An invalid string restored from globalState might return `undefined`. + if (timefilterBounds?.min !== undefined && timefilterBounds?.max !== undefined) { + explorerService.setBounds(timefilterBounds); + } + } + }, [globalState?.time?.from, globalState?.time?.to]); + useEffect(() => { timefilter.enableTimeRangeSelector(); timefilter.enableAutoRefreshSelector(); @@ -101,19 +124,6 @@ const ExplorerUrlStateManager: FC = ({ jobsWithTim } }, []); - useEffect(() => { - if (globalState?.time !== undefined) { - timefilter.setTime({ - from: globalState.time.from, - to: globalState.time.to, - }); - explorerService.setBounds({ - min: moment(globalState.time.from), - max: moment(globalState.time.to), - }); - } - }, [globalState?.time?.from, globalState?.time?.to]); - useEffect(() => { if (jobIds.length > 0) { explorerService.updateJobSelection(jobIds); diff --git a/x-pack/legacy/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx b/x-pack/legacy/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx index f824faf7845c64..bc457f1a3fe89e 100644 --- a/x-pack/legacy/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx +++ b/x-pack/legacy/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx @@ -72,6 +72,11 @@ const PageWrapper: FC = ({ config, deps }) => { ); }; +interface AppStateZoom { + from: string; + to: string; +} + interface TimeSeriesExplorerUrlStateManager { config: any; jobsWithTimeRange: MlJobWithTimeRange[]; @@ -159,10 +164,9 @@ export const TimeSeriesExplorerUrlStateManager: FC( + appState?.mlTimeSeriesExplorer?.forecastId + ); + useEffect(() => { if ( autoZoomDuration !== undefined && @@ -221,6 +231,9 @@ export const TimeSeriesExplorerUrlStateManager: FC { @@ -231,20 +244,6 @@ export const TimeSeriesExplorerUrlStateManager: FC { // eslint-disable-next-line no-console @@ -282,6 +282,11 @@ export const TimeSeriesExplorerUrlStateManager: FC ); diff --git a/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js b/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js index d8e9e4379395a5..4b2d640b99bb3d 100644 --- a/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js +++ b/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js @@ -385,6 +385,7 @@ const TimeseriesChartIntl = injectI18n( drawContextElements(context, this.vizWidth, contextChartHeight, swimlaneHeight); } + contextChartInitialized = false; drawContextChartSelection() { const { contextChartData, @@ -446,7 +447,10 @@ const TimeseriesChartIntl = injectI18n( }; if (!_.isEqual(newSelectedBounds, this.selectedBounds)) { this.selectedBounds = newSelectedBounds; - contextChartSelected({ from: contextXScaleDomain[0], to: contextXScaleDomain[1] }); + if (this.contextChartInitialized === false) { + this.contextChartInitialized = true; + contextChartSelected({ from: contextXScaleDomain[0], to: contextXScaleDomain[1] }); + } } } } diff --git a/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.d.ts b/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.d.ts index 6c1bb01137c917..4253316123f01a 100644 --- a/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.d.ts +++ b/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.d.ts @@ -19,8 +19,7 @@ declare const TimeSeriesExplorer: FC<{ selectedJobId: string; selectedDetectorIndex: number; selectedEntities: any[]; - selectedForecastId: string; - setGlobalState: (arg: any) => void; + selectedForecastId?: string; tableInterval: string; tableSeverity: number; zoom?: { from: string; to: string }; diff --git a/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js b/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js index 6d918a62d721a3..02cb2e3f4e25a5 100644 --- a/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js +++ b/x-pack/legacy/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js @@ -188,6 +188,24 @@ export class TimeSeriesExplorer extends React.Component { */ contextChart$ = new Subject(); + /** + * Returns field names that don't have a selection yet. + */ + getFieldNamesWithEmptyValues = () => { + const latestEntityControls = this.getControlsForDetector(); + return latestEntityControls + .filter(({ fieldValue }) => !fieldValue) + .map(({ fieldName }) => fieldName); + }; + + /** + * Checks if all entity control dropdowns have a selection. + */ + arePartitioningFieldsProvided = () => { + const fieldNamesWithEmptyValues = this.getFieldNamesWithEmptyValues(); + return fieldNamesWithEmptyValues.length === 0; + }; + detectorIndexChangeHandler = e => { const { appStateHandler } = this.props; const id = e.target.value; @@ -296,7 +314,17 @@ export class TimeSeriesExplorer extends React.Component { } contextChartSelected = selection => { + const zoomState = { + from: selection.from.toISOString(), + to: selection.to.toISOString(), + }; + + if (isEqual(this.props.zoom, zoomState) && this.state.focusChartData !== undefined) { + return; + } + this.contextChart$.next(selection); + this.props.appStateHandler(APP_STATE_ACTION.SET_ZOOM, zoomState); }; entityFieldValueChanged = (entity, fieldValue) => { @@ -509,27 +537,38 @@ export class TimeSeriesExplorer extends React.Component { (Array.isArray(stateUpdate.contextForecastData) && stateUpdate.contextForecastData.length > 0); stateUpdate.loading = false; + // Set zoomFrom/zoomTo attributes in scope which will result in the metric chart automatically // selecting the specified range in the context chart, and so loading that date range in the focus chart. - if (stateUpdate.contextChartData.length) { + // Only touch the zoom range if data for the context chart has been loaded and all necessary + // partition fields have a selection. + if ( + stateUpdate.contextChartData.length && + this.arePartitioningFieldsProvided() === true + ) { // Check for a zoom parameter in the appState (URL). let focusRange = calculateInitialFocusRange( zoom, stateUpdate.contextAggregationInterval, bounds ); - - if (focusRange === undefined) { + if ( + focusRange === undefined || + this.previousSelectedForecastId !== this.props.selectedForecastId + ) { focusRange = calculateDefaultFocusRange( autoZoomDuration, stateUpdate.contextAggregationInterval, stateUpdate.contextChartData, stateUpdate.contextForecastData ); + this.previousSelectedForecastId = this.props.selectedForecastId; } - stateUpdate.zoomFrom = focusRange[0]; - stateUpdate.zoomTo = focusRange[1]; + this.contextChartSelected({ + from: focusRange[0], + to: focusRange[1], + }); } this.setState(stateUpdate); @@ -881,11 +920,6 @@ export class TimeSeriesExplorer extends React.Component { ...refreshFocusData, ...tableData, }); - const zoomState = { - from: selection.from.toISOString(), - to: selection.to.toISOString(), - }; - this.props.appStateHandler(APP_STATE_ACTION.SET_ZOOM, zoomState); }) ); @@ -917,6 +951,11 @@ export class TimeSeriesExplorer extends React.Component { if (this.props.selectedForecastId !== undefined) { // Ensure the forecast data will be shown if hidden previously. this.setState({ showForecast: true }); + // Not best practice but we need the previous value for another comparison + // once all the data was loaded. + if (previousProps !== undefined) { + this.previousSelectedForecastId = previousProps.selectedForecastId; + } } } @@ -927,8 +966,7 @@ export class TimeSeriesExplorer extends React.Component { !isEqual(previousProps.selectedDetectorIndex, this.props.selectedDetectorIndex) || !isEqual(previousProps.selectedEntities, this.props.selectedEntities) || !isEqual(previousProps.selectedForecastId, this.props.selectedForecastId) || - previousProps.selectedJobId !== this.props.selectedJobId || - !isEqual(previousProps.zoom, this.props.zoom) + previousProps.selectedJobId !== this.props.selectedJobId ) { const fullRefresh = previousProps === undefined || @@ -961,41 +999,6 @@ export class TimeSeriesExplorer extends React.Component { ) { tableControlsListener(); } - - if ( - this.props.autoZoomDuration === undefined || - this.props.selectedForecastId !== undefined || - this.state.contextAggregationInterval === undefined || - this.state.contextChartData === undefined || - this.state.contextChartData.length === 0 - ) { - return; - } - - const defaultRange = calculateDefaultFocusRange( - this.props.autoZoomDuration, - this.state.contextAggregationInterval, - this.state.contextChartData, - this.state.contextForecastData - ); - - const selection = { - from: this.state.zoomFrom, - to: this.state.zoomTo, - }; - - if ( - (selection.from.getTime() !== defaultRange[0].getTime() || - selection.to.getTime() !== defaultRange[1].getTime()) && - isNaN(Date.parse(selection.from)) === false && - isNaN(Date.parse(selection.to)) === false - ) { - const zoomState = { - from: selection.from.toISOString(), - to: selection.to.toISOString(), - }; - this.props.appStateHandler(APP_STATE_ACTION.SET_ZOOM, zoomState); - } } componentWillUnmount() { @@ -1070,12 +1073,8 @@ export class TimeSeriesExplorer extends React.Component { const selectedJob = mlJobService.getJob(selectedJobId); const entityControls = this.getControlsForDetector(); - - const fieldNamesWithEmptyValues = entityControls - .filter(({ fieldValue }) => !fieldValue) - .map(({ fieldName }) => fieldName); - - const arePartitioningFieldsProvided = fieldNamesWithEmptyValues.length === 0; + const fieldNamesWithEmptyValues = this.getFieldNamesWithEmptyValues(); + const arePartitioningFieldsProvided = this.arePartitioningFieldsProvided(); const detectorSelectOptions = getViewableDetectors(selectedJob).map(d => ({ value: d.index, diff --git a/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts b/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts index b949be384b2aee..d8b4cdd9718eaa 100644 --- a/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts +++ b/x-pack/legacy/plugins/reporting/export_types/csv/server/execute_job.ts @@ -5,6 +5,8 @@ */ import { i18n } from '@kbn/i18n'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { KibanaRequest } from '../../../../../../../src/core/server'; import { CSV_JOB_TYPE } from '../../../common/constants'; import { cryptoFactory } from '../../../server/lib'; import { @@ -83,7 +85,9 @@ export const executeJobFactory: ExecuteJobFactory { const { savedObjects, uiSettingsServiceFactory } = server; - const savedObjectsClient = savedObjects.getScopedSavedObjectsClient(req.getRawRequest()); + const savedObjectsClient = savedObjects.getScopedSavedObjectsClient( + KibanaRequest.from(req.getRawRequest()) + ); const { indexPatternSavedObjectId, timerange } = searchPanel; const savedSearchObjectAttr = searchPanel.attributes as SavedSearchObjectAttributes; const { indexPatternSavedObject } = await getDataSource( diff --git a/x-pack/legacy/plugins/siem/index.ts b/x-pack/legacy/plugins/siem/index.ts index f6f2ead2d64fac..cd9b7f59226b0b 100644 --- a/x-pack/legacy/plugins/siem/index.ts +++ b/x-pack/legacy/plugins/siem/index.ts @@ -153,11 +153,11 @@ export const siem = (kibana: any) => { const { config, newPlatform, plugins, route } = server; const { coreContext, env, setup } = newPlatform; const initializerContext = { ...coreContext, env } as PluginInitializerContext; - const serverFacade = { config, plugins: { alerting: plugins.alerting, + actions: newPlatform.start.plugins.actions, elasticsearch: plugins.elasticsearch, spaces: plugins.spaces, savedObjects: server.savedObjects.SavedObjectsClient, diff --git a/x-pack/legacy/plugins/siem/public/components/alerts_viewer/alerts_table.tsx b/x-pack/legacy/plugins/siem/public/components/alerts_viewer/alerts_table.tsx index 19011019573076..65ade52ef7d3cf 100644 --- a/x-pack/legacy/plugins/siem/public/components/alerts_viewer/alerts_table.tsx +++ b/x-pack/legacy/plugins/siem/public/components/alerts_viewer/alerts_table.tsx @@ -64,6 +64,7 @@ const AlertsTableComponent: React.FC = ({ endDate, startDate, pageFilters documentType: i18n.ALERTS_DOCUMENT_TYPE, footerText: i18n.TOTAL_COUNT_OF_ALERTS, title: i18n.ALERTS_TABLE_TITLE, + unit: i18n.UNIT, }), [] ); diff --git a/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.tsx b/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.tsx index 05a33eeba14349..163b345da40bd8 100644 --- a/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.tsx +++ b/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.tsx @@ -154,20 +154,18 @@ const EventsViewerComponent: React.FC = ({ const totalCountMinusDeleted = totalCount > 0 ? totalCount - deletedEventIds.length : 0; + const subtitle = `${ + i18n.SHOWING + }: ${totalCountMinusDeleted.toLocaleString()} ${timelineTypeContext.unit?.( + totalCountMinusDeleted + ) ?? i18n.UNIT(totalCountMinusDeleted)}`; + // TODO: Reset eventDeletedIds/eventLoadingIds on refresh/loadmore (getUpdatedAt) return ( <> {headerFilterGroup} diff --git a/x-pack/legacy/plugins/siem/public/components/fields_browser/header.tsx b/x-pack/legacy/plugins/siem/public/components/fields_browser/header.tsx index 45b331f133e85e..ccf6ec67521b0b 100644 --- a/x-pack/legacy/plugins/siem/public/components/fields_browser/header.tsx +++ b/x-pack/legacy/plugins/siem/public/components/fields_browser/header.tsx @@ -12,13 +12,16 @@ import { EuiText, EuiTitle, } from '@elastic/eui'; -import React from 'react'; +import React, { useCallback } from 'react'; import styled from 'styled-components'; import { BrowserFields } from '../../containers/source'; +import { signalsHeaders } from '../../pages/detection_engine/components/signals/default_config'; +import { alertsHeaders } from '../alerts_viewer/default_headers'; import { defaultHeaders as eventsDefaultHeaders } from '../events_viewer/default_headers'; import { defaultHeaders } from '../timeline/body/column_headers/default_headers'; import { OnUpdateColumns } from '../timeline/events'; +import { useTimelineTypeContext } from '../timeline/timeline_context'; import { getFieldBrowserSearchInputClassName, getFieldCount, SEARCH_INPUT_WIDTH } from './helpers'; @@ -96,27 +99,44 @@ const TitleRow = React.memo<{ isEventViewer?: boolean; onOutsideClick: () => void; onUpdateColumns: OnUpdateColumns; -}>(({ isEventViewer, onOutsideClick, onUpdateColumns }) => ( - - - -

{i18n.CUSTOMIZE_COLUMNS}

-
-
- - - { - onUpdateColumns(isEventViewer ? eventsDefaultHeaders : defaultHeaders); - onOutsideClick(); - }} - > - {i18n.RESET_FIELDS} - - -
-)); +}>(({ isEventViewer, onOutsideClick, onUpdateColumns }) => { + const timelineTypeContext = useTimelineTypeContext(); + const handleResetColumns = useCallback(() => { + let resetDefaultHeaders = defaultHeaders; + if (isEventViewer) { + if (timelineTypeContext.documentType?.toLocaleLowerCase() === 'alerts') { + resetDefaultHeaders = alertsHeaders; + } else if (timelineTypeContext.documentType?.toLocaleLowerCase() === 'signals') { + resetDefaultHeaders = signalsHeaders; + } else { + resetDefaultHeaders = eventsDefaultHeaders; + } + } + onUpdateColumns(resetDefaultHeaders); + onOutsideClick(); + }, [isEventViewer, onOutsideClick, onUpdateColumns, timelineTypeContext]); + + return ( + + + +

{i18n.CUSTOMIZE_COLUMNS}

+
+
+ + + + {i18n.RESET_FIELDS} + + +
+ ); +}); TitleRow.displayName = 'TitleRow'; diff --git a/x-pack/legacy/plugins/siem/public/components/link_to/link_to.tsx b/x-pack/legacy/plugins/siem/public/components/link_to/link_to.tsx index 3180fc955c6906..3eda945c9224e6 100644 --- a/x-pack/legacy/plugins/siem/public/components/link_to/link_to.tsx +++ b/x-pack/legacy/plugins/siem/public/components/link_to/link_to.tsx @@ -77,16 +77,16 @@ export const LinkToPage = React.memo(({ match }) => ( /> ; @@ -41,14 +42,24 @@ export const RedirectToCreateRulePage = ({ }; export const RedirectToRuleDetailsPage = ({ + match: { + params: { detailName }, + }, location: { search }, }: DetectionEngineComponentProps) => { - return ; + return ; }; -export const RedirectToEditRulePage = ({ location: { search } }: DetectionEngineComponentProps) => { +export const RedirectToEditRulePage = ({ + match: { + params: { detailName }, + }, + location: { search }, +}: DetectionEngineComponentProps) => { return ( - + ); }; diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/body/column_headers/column_header.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/body/column_headers/column_header.tsx index ccaeeff972a812..9df805bddcc827 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/body/column_headers/column_header.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/body/column_headers/column_header.tsx @@ -30,6 +30,7 @@ export interface ColumnHeader { format?: string; id: ColumnId; label?: string; + linkField?: string; placeholder?: string; type?: string; width: number; diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/body/data_driven_columns/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/body/data_driven_columns/index.test.tsx index 36427015260a7f..098bd3108dba16 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/body/data_driven_columns/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/body/data_driven_columns/index.test.tsx @@ -23,6 +23,7 @@ describe('Columns', () => { columnHeaders={headersSansTimestamp} columnRenderers={columnRenderers} data={mockTimelineData[0].data} + ecsData={mockTimelineData[0].ecs} onColumnResized={jest.fn()} timelineId="test" /> diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/body/data_driven_columns/index.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/body/data_driven_columns/index.tsx index 37b6e302150560..416c72cfbc2554 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/body/data_driven_columns/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/body/data_driven_columns/index.tsx @@ -6,7 +6,8 @@ import React from 'react'; -import { TimelineNonEcsData } from '../../../../graphql/types'; +import { getOr } from 'lodash/fp'; +import { Ecs, TimelineNonEcsData } from '../../../../graphql/types'; import { OnColumnResized } from '../../events'; import { EventsTd, EventsTdContent, EventsTdGroupData } from '../../styles'; import { ColumnHeader } from '../column_headers/column_header'; @@ -18,12 +19,13 @@ interface Props { columnHeaders: ColumnHeader[]; columnRenderers: ColumnRenderer[]; data: TimelineNonEcsData[]; + ecsData: Ecs; onColumnResized: OnColumnResized; timelineId: string; } export const DataDrivenColumns = React.memo( - ({ _id, columnHeaders, columnRenderers, data, timelineId }) => { + ({ _id, columnHeaders, columnRenderers, data, ecsData, timelineId }) => { // Passing the styles directly to the component because the width is // being calculated and is recommended by Styled Components for performance // https://github.com/styled-components/styled-components/issues/134#issuecomment-312415291 @@ -36,6 +38,7 @@ export const DataDrivenColumns = React.memo( columnName: header.id, eventId: _id, field: header, + linkValues: getOr([], header.linkField ?? '', ecsData), timelineId, truncate: true, values: getMappedNonEcsValue({ diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/body/events/event_column_view.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/body/events/event_column_view.tsx index 1036c6b53b4c1d..74476c3dc1d617 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/body/events/event_column_view.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/body/events/event_column_view.tsx @@ -127,6 +127,7 @@ export const EventColumnView = React.memo( columnHeaders={columnHeaders} columnRenderers={columnRenderers} data={data} + ecsData={ecsData} onColumnResized={onColumnResized} timelineId={timelineId} /> diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/column_renderer.ts b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/column_renderer.ts index f64d0f39e3b291..d1807c82d188e4 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/column_renderer.ts +++ b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/column_renderer.ts @@ -16,6 +16,7 @@ export interface ColumnRenderer { timelineId, truncate, values, + linkValues, }: { columnName: string; eventId: string; @@ -23,5 +24,6 @@ export interface ColumnRenderer { timelineId: string; truncate?: boolean; values: string[] | null | undefined; + linkValues?: string[] | null | undefined; }) => React.ReactNode; } diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/constants.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/constants.tsx index f22c338f2d8797..0330fb458e3640 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/constants.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/constants.tsx @@ -8,3 +8,4 @@ export const DATE_FIELD_TYPE = 'date'; export const HOST_NAME_FIELD_NAME = 'host.name'; export const IP_FIELD_TYPE = 'ip'; export const MESSAGE_FIELD_NAME = 'message'; +export const SIGNAL_RULE_NAME_FIELD_NAME = 'signal.rule.name'; diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/formatted_field.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/formatted_field.tsx index 888029600d8609..010a328d2993dd 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/formatted_field.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/formatted_field.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiFlexGroup, EuiFlexItem, EuiToolTip } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem, EuiToolTip, EuiLink } from '@elastic/eui'; import { isNumber, isString, isEmpty } from 'lodash/fp'; import React from 'react'; @@ -15,6 +15,7 @@ import { getOrEmptyTagFromValue, getEmptyTagValue } from '../../../empty_value'; import { FormattedDate } from '../../../formatted_date'; import { FormattedIp } from '../../../formatted_ip'; import { HostDetailsLink } from '../../../links'; +import { getRuleDetailsUrl } from '../../../link_to/redirect_to_detection_engine'; import { Port, PORT_NAMES } from '../../../port'; import { TruncatableText } from '../../../truncatable_text'; import { @@ -22,6 +23,7 @@ import { HOST_NAME_FIELD_NAME, IP_FIELD_TYPE, MESSAGE_FIELD_NAME, + SIGNAL_RULE_NAME_FIELD_NAME, } from './constants'; // simple black-list to prevent dragging and dropping fields such as message name @@ -35,7 +37,8 @@ const FormattedFieldValueComponent: React.FC<{ fieldType: string; truncate?: boolean; value: string | number | undefined | null; -}> = ({ contextId, eventId, fieldFormat, fieldName, fieldType, truncate, value }) => { + linkValue?: string | null | undefined; +}> = ({ contextId, eventId, fieldFormat, fieldName, fieldType, truncate, value, linkValue }) => { if (fieldType === IP_FIELD_TYPE) { return ( {value} ); + } else if (fieldName === SIGNAL_RULE_NAME_FIELD_NAME) { + const ruleName = `${value}`; + const ruleId = linkValue; + + return isString(value) && ruleName.length > 0 && ruleId != null ? ( + + + {value} + + + ) : ( + getEmptyTagValue() + ); } else { const contentValue = getOrEmptyTagFromValue(value); const content = truncate ? {contentValue} : contentValue; diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/plain_column_renderer.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/plain_column_renderer.tsx index 70485c41f3b889..deeec05bc07074 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/plain_column_renderer.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/plain_column_renderer.tsx @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import { head } from 'lodash/fp'; import React from 'react'; import { TimelineNonEcsData } from '../../../../graphql/types'; @@ -27,6 +28,7 @@ export const plainColumnRenderer: ColumnRenderer = { timelineId, truncate, values, + linkValues, }: { columnName: string; eventId: string; @@ -34,6 +36,7 @@ export const plainColumnRenderer: ColumnRenderer = { timelineId: string; truncate?: boolean; values: string[] | undefined | null; + linkValues?: string[] | null | undefined; }) => values != null ? values.map(value => ( @@ -46,6 +49,7 @@ export const plainColumnRenderer: ColumnRenderer = { fieldType={field.type || ''} value={parseValue(value)} truncate={truncate} + linkValue={head(linkValues)} /> )) : getEmptyTagValue(), diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/index.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/index.tsx index bb8b04f6e304ef..ff556a1a9bdfc7 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/index.tsx @@ -268,6 +268,7 @@ const StatefulTimelineComponent = React.memo( columns={columns} dataProviders={dataProviders!} end={end} + eventType={eventType} filters={filters} flyoutHeaderHeight={flyoutHeaderHeight} flyoutHeight={flyoutHeight} diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/timeline.test.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/timeline.test.tsx index 0be5e69abea382..f7c0d0b4757347 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/timeline.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/timeline.test.tsx @@ -54,6 +54,7 @@ describe('Timeline', () => { id="foo" dataProviders={mockDataProviders} end={endDate} + eventType="raw" filters={[]} flyoutHeight={testFlyoutHeight} flyoutHeaderHeight={flyoutHeaderHeight} @@ -92,6 +93,7 @@ describe('Timeline', () => { id="foo" dataProviders={mockDataProviders} end={endDate} + eventType="raw" filters={[]} flyoutHeight={testFlyoutHeight} flyoutHeaderHeight={flyoutHeaderHeight} @@ -133,6 +135,7 @@ describe('Timeline', () => { id="foo" dataProviders={mockDataProviders} end={endDate} + eventType="raw" filters={[]} flyoutHeight={testFlyoutHeight} flyoutHeaderHeight={flyoutHeaderHeight} @@ -174,6 +177,7 @@ describe('Timeline', () => { id="foo" dataProviders={mockDataProviders} end={endDate} + eventType="raw" filters={[]} flyoutHeight={testFlyoutHeight} flyoutHeaderHeight={flyoutHeaderHeight} @@ -220,6 +224,7 @@ describe('Timeline', () => { id="foo" dataProviders={mockDataProviders} end={endDate} + eventType="raw" filters={[]} flyoutHeight={testFlyoutHeight} flyoutHeaderHeight={flyoutHeaderHeight} @@ -268,6 +273,7 @@ describe('Timeline', () => { id="foo" dataProviders={mockDataProviders} end={endDate} + eventType="raw" filters={[]} flyoutHeight={testFlyoutHeight} flyoutHeaderHeight={flyoutHeaderHeight} @@ -324,6 +330,7 @@ describe('Timeline', () => { id="foo" dataProviders={mockDataProviders} end={endDate} + eventType="raw" filters={[]} flyoutHeight={testFlyoutHeight} flyoutHeaderHeight={flyoutHeaderHeight} @@ -384,6 +391,7 @@ describe('Timeline', () => { id="foo" dataProviders={mockDataProviders} end={endDate} + eventType="raw" filters={[]} flyoutHeight={testFlyoutHeight} flyoutHeaderHeight={flyoutHeaderHeight} @@ -447,6 +455,7 @@ describe('Timeline', () => { id="foo" dataProviders={dataProviders} end={endDate} + eventType="raw" filters={[]} flyoutHeight={testFlyoutHeight} flyoutHeaderHeight={flyoutHeaderHeight} @@ -500,6 +509,7 @@ describe('Timeline', () => { id="foo" dataProviders={dataProviders} end={endDate} + eventType="raw" filters={[]} flyoutHeight={testFlyoutHeight} flyoutHeaderHeight={flyoutHeaderHeight} @@ -559,6 +569,7 @@ describe('Timeline', () => { id="foo" dataProviders={dataProviders} end={endDate} + eventType="raw" filters={[]} flyoutHeight={testFlyoutHeight} flyoutHeaderHeight={flyoutHeaderHeight} @@ -622,6 +633,7 @@ describe('Timeline', () => { id="foo" dataProviders={dataProviders} end={endDate} + eventType="raw" filters={[]} flyoutHeight={testFlyoutHeight} flyoutHeaderHeight={flyoutHeaderHeight} diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/timeline.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/timeline.tsx index ece5b4fa18d1c4..11886b45b0bec2 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/timeline.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/timeline.tsx @@ -13,7 +13,7 @@ import { BrowserFields } from '../../containers/source'; import { TimelineQuery } from '../../containers/timeline'; import { Direction } from '../../graphql/types'; import { useKibana } from '../../lib/kibana'; -import { KqlMode } from '../../store/timeline/model'; +import { KqlMode, EventType } from '../../store/timeline/model'; import { AutoSizer } from '../auto_sizer'; import { ColumnHeader } from './body/column_headers/column_header'; import { defaultHeaders } from './body/column_headers/default_headers'; @@ -60,6 +60,7 @@ interface Props { columns: ColumnHeader[]; dataProviders: DataProvider[]; end: number; + eventType: EventType; filters: esFilters.Filter[]; flyoutHeaderHeight: number; flyoutHeight: number; @@ -92,6 +93,7 @@ export const TimelineComponent = ({ columns, dataProviders, end, + eventType, filters, flyoutHeaderHeight, flyoutHeight, @@ -159,6 +161,7 @@ export const TimelineComponent = ({ {combinedQueries != null ? ( c.id)} diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/timeline_context.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/timeline_context.tsx index 611452cc7ccd13..15759c2efff0b5 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/timeline_context.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/timeline_context.tsx @@ -23,6 +23,7 @@ export interface TimelineTypeContextProps { selectAll?: boolean; timelineActions?: TimelineAction[]; title?: string; + unit?: (totalCount: number) => string; } const initTimelineType: TimelineTypeContextProps = { documentType: undefined, @@ -32,6 +33,7 @@ const initTimelineType: TimelineTypeContextProps = { selectAll: false, timelineActions: [], title: undefined, + unit: undefined, }; export const TimelineTypeContext = createContext(initTimelineType); export const useTimelineTypeContext = () => useContext(TimelineTypeContext); diff --git a/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/api.ts b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/api.ts index 6c9fd5c0ff3bc7..22fb837ffb8010 100644 --- a/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/api.ts +++ b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/api.ts @@ -28,6 +28,7 @@ import { DETECTION_ENGINE_PREPACKAGED_URL, DETECTION_ENGINE_RULES_STATUS_URL, DETECTION_ENGINE_PREPACKAGED_RULES_STATUS_URL, + DETECTION_ENGINE_TAGS_URL, } from '../../../../common/constants'; import * as i18n from '../../../pages/detection_engine/rules/translations'; @@ -54,61 +55,72 @@ export const addRule = async ({ rule, signal }: AddRulesProps): Promise }; /** - * Fetches all rules or single specified rule from the Detection Engine API + * Fetches all rules from the Detection Engine API * * @param filterOptions desired filters (e.g. filter/sortField/sortOrder) * @param pagination desired pagination options (e.g. page/perPage) - * @param id if specified, will return specific rule if exists * @param signal to cancel request + * */ export const fetchRules = async ({ filterOptions = { filter: '', - sortField: 'name', + sortField: 'enabled', sortOrder: 'desc', + showCustomRules: false, + showElasticRules: false, + tags: [], }, pagination = { page: 1, perPage: 20, total: 0, }, - id, signal, }: FetchRulesProps): Promise => { + const filters = [ + ...(filterOptions.filter.length !== 0 + ? [`alert.attributes.name:%20${encodeURIComponent(filterOptions.filter)}`] + : []), + ...(filterOptions.showCustomRules + ? ['alert.attributes.tags:%20%22__internal_immutable:false%22'] + : []), + ...(filterOptions.showElasticRules + ? ['alert.attributes.tags:%20%22__internal_immutable:true%22'] + : []), + ...(filterOptions.tags?.map(t => `alert.attributes.tags:${encodeURIComponent(t)}`) ?? []), + ]; + const queryParams = [ `page=${pagination.page}`, `per_page=${pagination.perPage}`, `sort_field=${filterOptions.sortField}`, `sort_order=${filterOptions.sortOrder}`, - ...(filterOptions.filter.length !== 0 - ? [`filter=alert.attributes.name:%20${encodeURIComponent(filterOptions.filter)}`] - : []), + ...(filters.length > 0 ? [`filter=${filters.join('%20AND%20')}`] : []), ]; - const endpoint = - id != null - ? `${chrome.getBasePath()}${DETECTION_ENGINE_RULES_URL}?id="${id}"` - : `${chrome.getBasePath()}${DETECTION_ENGINE_RULES_URL}/_find?${queryParams.join('&')}`; - - const response = await fetch(endpoint, { - method: 'GET', - signal, - }); + const response = await fetch( + `${chrome.getBasePath()}${DETECTION_ENGINE_RULES_URL}/_find?${queryParams.join('&')}`, + { + method: 'GET', + credentials: 'same-origin', + headers: { + 'content-type': 'application/json', + 'kbn-xsrf': 'true', + }, + signal, + } + ); await throwIfNotOk(response); - return id != null - ? { - page: 0, - perPage: 1, - total: 1, - data: response.json(), - } - : response.json(); + return response.json(); }; /** * Fetch a Rule by providing a Rule ID * * @param id Rule ID's (not rule_id) + * @param signal to cancel request + * */ export const fetchRuleById = async ({ id, signal }: FetchRuleProps): Promise => { const response = await fetch(`${chrome.getBasePath()}${DETECTION_ENGINE_RULES_URL}?id=${id}`, { @@ -344,6 +356,27 @@ export const getRuleStatusById = async ({ return response.json(); }; +/** + * Fetch all unique Tags used by Rules + * + * @param signal to cancel request + * + */ +export const fetchTags = async ({ signal }: { signal: AbortSignal }): Promise => { + const response = await fetch(`${chrome.getBasePath()}${DETECTION_ENGINE_TAGS_URL}`, { + method: 'GET', + credentials: 'same-origin', + headers: { + 'content-type': 'application/json', + 'kbn-xsrf': 'true', + }, + signal, + }); + + await throwIfNotOk(response); + return response.json(); +}; + /** * Get pre packaged rules Status * diff --git a/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/translations.ts b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/translations.ts index a493e471a9bf6f..84e008312fefe6 100644 --- a/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/translations.ts +++ b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/translations.ts @@ -30,3 +30,10 @@ export const RULE_PREPACKAGED_SUCCESS = i18n.translate( defaultMessage: 'Installed pre-packaged rules from elastic', } ); + +export const TAG_FETCH_FAILURE = i18n.translate( + 'xpack.siem.containers.detectionEngine.tagFetchFailDescription', + { + defaultMessage: 'Failed to fetch Tags', + } +); diff --git a/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/types.ts b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/types.ts index 0dcd0da5be8f61..2e776738547df9 100644 --- a/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/types.ts +++ b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/types.ts @@ -114,7 +114,6 @@ export interface PaginationOptions { export interface FetchRulesProps { pagination?: PaginationOptions; filterOptions?: FilterOptions; - id?: string; signal: AbortSignal; } @@ -122,6 +121,9 @@ export interface FilterOptions { filter: string; sortField: string; sortOrder: 'asc' | 'desc'; + showCustomRules?: boolean; + showElasticRules?: boolean; + tags?: string[]; } export interface FetchRulesResponse { diff --git a/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/use_pre_packaged_rules.tsx b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/use_pre_packaged_rules.tsx index abb43f3570e6c0..ee34cad8730211 100644 --- a/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/use_pre_packaged_rules.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/use_pre_packaged_rules.tsx @@ -25,7 +25,7 @@ interface Return { interface UsePrePackagedRuleProps { canUserCRUD: boolean | null; - hasIndexManage: boolean | null; + hasIndexWrite: boolean | null; hasManageApiKey: boolean | null; isAuthenticated: boolean | null; isSignalIndexExists: boolean | null; @@ -34,7 +34,7 @@ interface UsePrePackagedRuleProps { /** * Hook for using to get status about pre-packaged Rules from the Detection Engine API * - * @param hasIndexManage boolean + * @param hasIndexWrite boolean * @param hasManageApiKey boolean * @param isAuthenticated boolean * @param isSignalIndexExists boolean @@ -42,7 +42,7 @@ interface UsePrePackagedRuleProps { */ export const usePrePackagedRules = ({ canUserCRUD, - hasIndexManage, + hasIndexWrite, hasManageApiKey, isAuthenticated, isSignalIndexExists, @@ -90,7 +90,7 @@ export const usePrePackagedRules = ({ try { if ( canUserCRUD && - hasIndexManage && + hasIndexWrite && hasManageApiKey && isAuthenticated && isSignalIndexExists @@ -152,7 +152,7 @@ export const usePrePackagedRules = ({ isSubscribed = false; abortCtrl.abort(); }; - }, [canUserCRUD, hasIndexManage, hasManageApiKey, isAuthenticated, isSignalIndexExists]); + }, [canUserCRUD, hasIndexWrite, hasManageApiKey, isAuthenticated, isSignalIndexExists]); return { loading, diff --git a/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/use_rules.tsx b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/use_rules.tsx index 04475ab1bc1787..254e8cbdc9a883 100644 --- a/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/use_rules.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/use_rules.tsx @@ -70,6 +70,9 @@ export const useRules = (pagination: PaginationOptions, filterOptions: FilterOpt filterOptions.filter, filterOptions.sortField, filterOptions.sortOrder, + filterOptions.tags?.sort().join(), + filterOptions.showCustomRules, + filterOptions.showElasticRules, ]); return [loading, rules, reFetchRules.current]; diff --git a/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/use_tags.tsx b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/use_tags.tsx new file mode 100644 index 00000000000000..1c961d530422a5 --- /dev/null +++ b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/use_tags.tsx @@ -0,0 +1,57 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { useEffect, useState } from 'react'; +import { useStateToaster } from '../../../components/toasters'; +import { fetchTags } from './api'; +import { errorToToaster } from '../../../components/ml/api/error_to_toaster'; +import * as i18n from './translations'; + +type Return = [boolean, string[]]; + +/** + * Hook for using the list of Tags from the Detection Engine API + * + */ +export const useTags = (): Return => { + const [tags, setTags] = useState([]); + const [loading, setLoading] = useState(true); + const [, dispatchToaster] = useStateToaster(); + + useEffect(() => { + let isSubscribed = true; + const abortCtrl = new AbortController(); + + async function fetchData() { + setLoading(true); + try { + const fetchTagsResult = await fetchTags({ + signal: abortCtrl.signal, + }); + + if (isSubscribed) { + setTags(fetchTagsResult); + } + } catch (error) { + if (isSubscribed) { + errorToToaster({ title: i18n.TAG_FETCH_FAILURE, error, dispatchToaster }); + } + } + if (isSubscribed) { + setLoading(false); + } + } + + fetchData(); + + return () => { + isSubscribed = false; + abortCtrl.abort(); + }; + }, []); + + return [loading, tags]; +}; diff --git a/x-pack/legacy/plugins/siem/public/containers/detection_engine/signals/use_privilege_user.tsx b/x-pack/legacy/plugins/siem/public/containers/detection_engine/signals/use_privilege_user.tsx index 564cf224a9fc8e..d225241875d4bf 100644 --- a/x-pack/legacy/plugins/siem/public/containers/detection_engine/signals/use_privilege_user.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/detection_engine/signals/use_privilege_user.tsx @@ -46,7 +46,12 @@ export const usePrivilegeUser = (): Return => { if (privilege.index != null && Object.keys(privilege.index).length > 0) { const indexName = Object.keys(privilege.index)[0]; setHasIndexManage(privilege.index[indexName].manage); - setHasIndexWrite(privilege.index[indexName].write); + setHasIndexWrite( + privilege.index[indexName].create || + privilege.index[indexName].create_doc || + privilege.index[indexName].index || + privilege.index[indexName].write + ); setHasManageApiKey( privilege.cluster.manage_security || privilege.cluster.manage_api_key || diff --git a/x-pack/legacy/plugins/siem/public/containers/timeline/index.tsx b/x-pack/legacy/plugins/siem/public/containers/timeline/index.tsx index 97f007452854ca..03fe68ca1398d2 100644 --- a/x-pack/legacy/plugins/siem/public/containers/timeline/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/timeline/index.tsx @@ -11,6 +11,7 @@ import { Query } from 'react-apollo'; import { compose } from 'redux'; import { connect } from 'react-redux'; +import { IIndexPattern } from '../../../../../../../src/plugins/data/common/index_patterns'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { GetTimelineQuery, @@ -23,9 +24,8 @@ import { inputsModel, inputsSelectors, State } from '../../store'; import { withKibana, WithKibanaProps } from '../../lib/kibana'; import { createFilter } from '../helpers'; import { QueryTemplate, QueryTemplateProps } from '../query_template'; - +import { EventType } from '../../store/timeline/model'; import { timelineQuery } from './index.gql_query'; -import { IIndexPattern } from '../../../../../../../src/plugins/data/common/index_patterns'; export interface TimelineArgs { events: TimelineItem[]; @@ -45,6 +45,7 @@ export interface TimelineQueryReduxProps { export interface OwnProps extends QueryTemplateProps { children?: (args: TimelineArgs) => React.ReactNode; + eventType?: EventType; id: string; indexPattern?: IIndexPattern; indexToAdd?: string[]; @@ -70,6 +71,7 @@ class TimelineQueryComponent extends QueryTemplate< public render() { const { children, + eventType = 'raw', id, indexPattern, indexToAdd = [], @@ -83,7 +85,10 @@ class TimelineQueryComponent extends QueryTemplate< } = this.props; const defaultKibanaIndex = kibana.services.uiSettings.get(DEFAULT_INDEX_KEY); const defaultIndex = isEmpty(indexPattern) - ? [...defaultKibanaIndex, ...indexToAdd] + ? [ + ...(['all', 'raw'].includes(eventType) ? defaultKibanaIndex : []), + ...(['all', 'signal'].includes(eventType) ? indexToAdd : []), + ] : indexPattern?.title.split(',') ?? []; const variables: GetTimelineQuery.Variables = { fieldRequested: fields, diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/components/signals/actions.tsx b/x-pack/legacy/plugins/siem/public/pages/detection_engine/components/signals/actions.tsx index 4701ed93dc4f0a..a33efeda2196b5 100644 --- a/x-pack/legacy/plugins/siem/public/pages/detection_engine/components/signals/actions.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/components/signals/actions.tsx @@ -151,11 +151,25 @@ export const sendSignalToTimelineAction = async ({ updateTimelineIsLoading({ id: 'timeline-1', isLoading: false }); } } else { - const query = `_id: ${ecsData._id}`; createTimeline({ from, timeline: { ...timelineDefaults, + dataProviders: [ + { + and: [], + id: `send-signal-to-timeline-action-default-draggable-event-details-value-formatted-field-value-timeline-1-signal-id-${ecsData._id}`, + name: ecsData._id, + enabled: true, + excluded: false, + kqlQuery: '', + queryMatch: { + field: '_id', + value: ecsData._id, + operator: ':', + }, + }, + ], id: 'timeline-1', dateRange: { start: from, @@ -166,13 +180,13 @@ export const sendSignalToTimelineAction = async ({ filterQuery: { kuery: { kind: 'kuery', - expression: query, + expression: '', }, - serializedQuery: convertKueryToElasticSearchQuery(query), + serializedQuery: '', }, filterQueryDraft: { kind: 'kuery', - expression: query, + expression: '', }, }, }, diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/components/signals/default_config.tsx b/x-pack/legacy/plugins/siem/public/pages/detection_engine/components/signals/default_config.tsx index f4406c83136063..f5d138a3afcb8c 100644 --- a/x-pack/legacy/plugins/siem/public/pages/detection_engine/components/signals/default_config.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/components/signals/default_config.tsx @@ -90,6 +90,7 @@ export const signalsHeaders: ColumnHeader[] = [ columnHeaderType: defaultColumnHeaderType, id: 'signal.rule.name', label: i18n.SIGNALS_HEADERS_RULE, + linkField: 'signal.rule.id', width: DEFAULT_COLUMN_MIN_WIDTH, }, { diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/__mocks__/mock.ts b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/__mocks__/mock.ts index b79b3ed091f169..b62247e8f9a4f5 100644 --- a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/__mocks__/mock.ts +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/__mocks__/mock.ts @@ -56,13 +56,10 @@ export const mockTableData: TableData[] = [ id: 'abe6c564-050d-45a5-aaf0-386c37dd1f61', immutable: false, isLoading: false, - lastCompletedRun: undefined, - lastResponse: { type: '—' }, - method: 'saved_query', + risk_score: 21, rule: { href: '#/detections/rules/id/abe6c564-050d-45a5-aaf0-386c37dd1f61', name: 'Home Grown!', - status: 'Status Placeholder', }, rule_id: 'b5ba41ab-aaf3-4f43-971b-bdf9434ce0ea', severity: 'low', @@ -108,13 +105,10 @@ export const mockTableData: TableData[] = [ id: '63f06f34-c181-4b2d-af35-f2ace572a1ee', immutable: false, isLoading: false, - lastCompletedRun: undefined, - lastResponse: { type: '—' }, - method: 'saved_query', + risk_score: 21, rule: { href: '#/detections/rules/id/63f06f34-c181-4b2d-af35-f2ace572a1ee', name: 'Home Grown!', - status: 'Status Placeholder', }, rule_id: 'b5ba41ab-aaf3-4f43-971b-bdf9434ce0ea', severity: 'low', diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/columns.tsx b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/columns.tsx index d546c4edb55d35..d648854368c28b 100644 --- a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/columns.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/columns.tsx @@ -31,6 +31,7 @@ import { RuleSwitch } from '../components/rule_switch'; import { SeverityBadge } from '../components/severity_badge'; import { ActionToaster } from '../../../../components/toasters'; import { getStatusColor } from '../components/rule_status/helpers'; +import { TruncatableText } from '../../../../components/truncatable_text'; const getActions = ( dispatch: React.Dispatch, @@ -84,8 +85,8 @@ export const getColumns = ( width: '24%', }, { - field: 'method', - name: i18n.COLUMN_METHOD, + field: 'risk_score', + name: i18n.COLUMN_RISK_SCORE, truncateText: true, width: '14%', }, @@ -129,13 +130,13 @@ export const getColumns = ( field: 'tags', name: i18n.COLUMN_TAGS, render: (value: TableData['tags']) => ( - <> + {value.map((tag, i) => ( {tag} ))} - + ), truncateText: true, width: '20%', diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/helpers.ts b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/helpers.ts index 07a2f2f2789874..3616d4dbaad241 100644 --- a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/helpers.ts +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/helpers.ts @@ -10,7 +10,6 @@ import { RuleResponseBuckets, } from '../../../../containers/detection_engine/rules'; import { TableData } from '../types'; -import { getEmptyValue } from '../../../../components/empty_value'; /** * Formats rules into the correct format for the AllRulesTable @@ -26,14 +25,9 @@ export const formatRules = (rules: Rule[], selectedIds?: string[]): TableData[] rule: { href: `#/detections/rules/id/${encodeURIComponent(rule.id)}`, name: rule.name, - status: 'Status Placeholder', }, - method: rule.type, // TODO: Map to i18n? + risk_score: rule.risk_score, severity: rule.severity, - lastCompletedRun: undefined, // TODO: Not available yet - lastResponse: { - type: getEmptyValue(), // TODO: Not available yet - }, tags: rule.tags ?? [], activate: rule.enabled, status: rule.status ?? null, diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/index.tsx b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/index.tsx index 677033b258837d..a4e7d7a3615ccc 100644 --- a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/index.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/index.tsx @@ -6,8 +6,9 @@ import { EuiBasicTable, + EuiButton, EuiContextMenuPanel, - EuiFieldSearch, + EuiEmptyPrompt, EuiLoadingContent, EuiSpacer, } from '@elastic/eui'; @@ -16,7 +17,11 @@ import React, { useCallback, useEffect, useMemo, useReducer, useState } from 're import { useHistory } from 'react-router-dom'; import uuid from 'uuid'; -import { useRules, CreatePreBuiltRules } from '../../../../containers/detection_engine/rules'; +import { + useRules, + CreatePreBuiltRules, + FilterOptions, +} from '../../../../containers/detection_engine/rules'; import { HeaderSection } from '../../../../components/header_section'; import { UtilityBar, @@ -36,6 +41,8 @@ import { EuiBasicTableOnChange, TableData } from '../types'; import { getBatchItems } from './batch_actions'; import { getColumns } from './columns'; import { allRulesReducer, State } from './reducer'; +import { RulesTableFilters } from './rules_table_filters/rules_table_filters'; +import { DETECTION_ENGINE_PAGE_NAME } from '../../../../components/link_to/redirect_to_detection_engine'; const initialState: State = { isLoading: true, @@ -209,6 +216,20 @@ export const AllRules = React.memo( [] ); + const onFilterChangedCallback = useCallback((newFilterOptions: Partial) => { + dispatch({ + type: 'updateFilterOptions', + filterOptions: { + ...filterOptions, + ...newFilterOptions, + }, + }); + dispatch({ + type: 'updatePagination', + pagination: { ...pagination, page: 1 }, + }); + }, []); + return ( <> ( <> {rulesInstalled != null && rulesInstalled > 0 && ( - - { - dispatch({ - type: 'updateFilterOptions', - filterOptions: { - ...filterOptions, - filter: filterString, - }, - }); - dispatch({ - type: 'updatePagination', - pagination: { ...pagination, page: 1 }, - }); - }} - /> + + )} {isInitialLoad && isEmpty(tableData) && ( @@ -301,6 +304,24 @@ export const AllRules = React.memo( isSelectable={!hasNoPermissions ?? false} itemId="id" items={tableData} + noItemsMessage={ + {i18n.NO_RULES}

} + titleSize="xs" + body={i18n.NO_RULES_BODY} + actions={ + + {i18n.ADD_NEW_RULE} + + } + /> + } onChange={tableOnChangeCallback} pagination={{ pageIndex: pagination.page - 1, diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/rules_table_filters/rules_table_filters.tsx b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/rules_table_filters/rules_table_filters.tsx new file mode 100644 index 00000000000000..daf519f5af6958 --- /dev/null +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/rules_table_filters/rules_table_filters.tsx @@ -0,0 +1,105 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useCallback, useEffect, useState } from 'react'; + +import { + EuiFieldSearch, + EuiFilterButton, + EuiFilterGroup, + EuiFlexGroup, + EuiFlexItem, +} from '@elastic/eui'; +import * as i18n from '../../translations'; + +import { FilterOptions } from '../../../../../containers/detection_engine/rules'; +import { useTags } from '../../../../../containers/detection_engine/rules/use_tags'; +import { TagsFilterPopover } from './tags_filter_popover'; + +interface RulesTableFiltersProps { + onFilterChanged: (filterOptions: Partial) => void; +} + +/** + * Collection of filters for filtering data within the RulesTable. Contains search bar, Elastic/Custom + * Rules filter button toggle, and tag selection + * + * @param onFilterChanged change listener to be notified on filter changes + */ +const RulesTableFiltersComponent = ({ onFilterChanged }: RulesTableFiltersProps) => { + const [filter, setFilter] = useState(''); + const [selectedTags, setSelectedTags] = useState([]); + const [showCustomRules, setShowCustomRules] = useState(false); + const [showElasticRules, setShowElasticRules] = useState(false); + const [isLoadingTags, tags] = useTags(); + + // Propagate filter changes to parent + useEffect(() => { + onFilterChanged({ filter, showCustomRules, showElasticRules, tags: selectedTags }); + }, [filter, selectedTags, showCustomRules, showElasticRules, onFilterChanged]); + + const handleOnSearch = useCallback(filterString => setFilter(filterString.trim()), [setFilter]); + + const handleElasticRulesClick = useCallback(() => { + setShowElasticRules(!showElasticRules); + setShowCustomRules(false); + }, [setShowElasticRules, showElasticRules, setShowCustomRules]); + + const handleCustomRulesClick = useCallback(() => { + setShowCustomRules(!showCustomRules); + setShowElasticRules(false); + }, [setShowElasticRules, showCustomRules, setShowCustomRules]); + + return ( + + + + + + + + + + + + + + + {i18n.ELASTIC_RULES} + + + {i18n.CUSTOM_RULES} + + + + + ); +}; + +RulesTableFiltersComponent.displayName = 'RulesTableFiltersComponent'; + +export const RulesTableFilters = React.memo(RulesTableFiltersComponent); + +RulesTableFilters.displayName = 'RulesTableFilters'; diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/rules_table_filters/tags_filter_popover.tsx b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/rules_table_filters/tags_filter_popover.tsx new file mode 100644 index 00000000000000..b9d2c97f063b1e --- /dev/null +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all/rules_table_filters/tags_filter_popover.tsx @@ -0,0 +1,96 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { Dispatch, SetStateAction, useEffect, useState } from 'react'; +import { + EuiFilterButton, + EuiFilterSelectItem, + EuiFlexGroup, + EuiFlexItem, + EuiPanel, + EuiPopover, + EuiText, +} from '@elastic/eui'; +import styled from 'styled-components'; +import * as i18n from '../../translations'; +import { toggleSelectedGroup } from '../../../../../components/ml_popover/jobs_table/filters/toggle_selected_group'; + +interface TagsFilterPopoverProps { + tags: string[]; + onSelectedTagsChanged: Dispatch>; + isLoading: boolean; +} + +const ScrollableDiv = styled.div` + max-height: 250px; + overflow: auto; +`; + +/** + * Popover for selecting tags to filter on + * + * @param tags to display for filtering + * @param onSelectedTagsChanged change listener to be notified when tag selection changes + */ +export const TagsFilterPopoverComponent = ({ + tags, + onSelectedTagsChanged, +}: TagsFilterPopoverProps) => { + const [isTagPopoverOpen, setIsTagPopoverOpen] = useState(false); + const [selectedTags, setSelectedTags] = useState([]); + + useEffect(() => { + onSelectedTagsChanged(selectedTags); + }, [selectedTags.sort().join()]); + + return ( + setIsTagPopoverOpen(!isTagPopoverOpen)} + isSelected={isTagPopoverOpen} + hasActiveFilters={selectedTags.length > 0} + numActiveFilters={selectedTags.length} + > + {i18n.TAGS} + + } + isOpen={isTagPopoverOpen} + closePopover={() => setIsTagPopoverOpen(!isTagPopoverOpen)} + panelPaddingSize="none" + > + + {tags.map((tag, index) => ( + toggleSelectedGroup(tag, selectedTags, setSelectedTags)} + > + {`${tag}`} + + ))} + + {tags.length === 0 && ( + + + + {i18n.NO_TAGS_AVAILABLE} + + + + )} + + ); +}; + +TagsFilterPopoverComponent.displayName = 'TagsFilterPopoverComponent'; + +export const TagsFilterPopover = React.memo(TagsFilterPopoverComponent); + +TagsFilterPopover.displayName = 'TagsFilterPopover'; diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/index.tsx b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/index.tsx index 8be4f6dd3b99ba..75b1ce71efbb6b 100644 --- a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/index.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/index.tsx @@ -36,7 +36,7 @@ const RulesPageComponent: React.FC = () => { isSignalIndexExists, isAuthenticated, canUserCRUD, - hasIndexManage, + hasIndexWrite, hasManageApiKey, } = useUserInfo(); const { @@ -49,7 +49,7 @@ const RulesPageComponent: React.FC = () => { rulesNotUpdated, } = usePrePackagedRules({ canUserCRUD, - hasIndexManage, + hasIndexWrite, hasManageApiKey, isSignalIndexExists, isAuthenticated, diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/translations.ts b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/translations.ts index 672aab8ef83140..5b1ee049371d28 100644 --- a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/translations.ts +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/translations.ts @@ -213,10 +213,10 @@ export const COLUMN_RULE = i18n.translate( } ); -export const COLUMN_METHOD = i18n.translate( - 'xpack.siem.detectionEngine.rules.allRules.columns.methodTitle', +export const COLUMN_RISK_SCORE = i18n.translate( + 'xpack.siem.detectionEngine.rules.allRules.columns.riskScoreTitle', { - defaultMessage: 'Method', + defaultMessage: 'Risk score', } ); @@ -255,16 +255,42 @@ export const COLUMN_ACTIVATE = i18n.translate( } ); -export const COLUMN_STATUS = i18n.translate( - 'xpack.siem.detectionEngine.rules.allRules.columns.currentStatusTitle', +export const CUSTOM_RULES = i18n.translate( + 'xpack.siem.detectionEngine.rules.allRules.filters.customRulesTitle', { - defaultMessage: 'Current status', + defaultMessage: 'Custom rules', } ); -export const NO_STATUS = i18n.translate( - 'xpack.siem.detectionEngine.rules.allRules.columns.unknownStatusDescription', + +export const ELASTIC_RULES = i18n.translate( + 'xpack.siem.detectionEngine.rules.allRules.filters.elasticRulesTitle', + { + defaultMessage: 'Elastic rules', + } +); + +export const TAGS = i18n.translate('xpack.siem.detectionEngine.rules.allRules.filters.tagsLabel', { + defaultMessage: 'Tags', +}); + +export const NO_TAGS_AVAILABLE = i18n.translate( + 'xpack.siem.detectionEngine.rules.allRules.filters.noTagsAvailableDescription', + { + defaultMessage: 'No tags available', + } +); + +export const NO_RULES = i18n.translate( + 'xpack.siem.detectionEngine.rules.allRules.filters.noRulesTitle', + { + defaultMessage: 'No rules found', + } +); + +export const NO_RULES_BODY = i18n.translate( + 'xpack.siem.detectionEngine.rules.allRules.filters.noRulesBodyTitle', { - defaultMessage: 'Unknown', + defaultMessage: "We weren't able to find any rules with the above filters.", } ); diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/types.ts b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/types.ts index 5ae516dda5b389..2b50e32a367ec4 100644 --- a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/types.ts +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/types.ts @@ -30,15 +30,9 @@ export interface TableData { rule: { href: string; name: string; - status: string; }; - method: string; + risk_score: number; severity: string; - lastCompletedRun: string | undefined; - lastResponse: { - type: string; - message?: string; - }; tags: string[]; activate: boolean; isLoading: boolean; diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/__mocks__/_mock_server.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/__mocks__/_mock_server.ts index ed194188a54040..4bf7b3279374b8 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/__mocks__/_mock_server.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/__mocks__/_mock_server.ts @@ -59,9 +59,12 @@ export const createMockServer = (config: Record = defaultConfig) }; server.decorate('request', 'getAlertsClient', () => alertsClient); server.decorate('request', 'getBasePath', () => '/s/default'); - server.decorate('request', 'getActionsClient', () => actionsClient); server.plugins.elasticsearch = (elasticsearch as unknown) as ElasticsearchPlugin; server.plugins.spaces = { getSpaceId: () => 'default' }; + server.plugins.actions = { + getActionsClientWithRequest: () => actionsClient, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any; // The types have really bad conflicts at the moment so I have to use any server.decorate('request', 'getSavedObjectsClient', () => savedObjectsClient); return { server: server as ServerFacade & Hapi.Server, @@ -79,11 +82,16 @@ export const createMockServerWithoutAlertClientDecoration = ( port: 0, }); + const savedObjectsClient = savedObjectsClientMock.create(); serverWithoutAlertClient.config = () => createMockKibanaConfig(config); + serverWithoutAlertClient.decorate('request', 'getSavedObjectsClient', () => savedObjectsClient); + serverWithoutAlertClient.plugins.actions = { + getActionsClientWithRequest: () => actionsClient, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any; // The types have really bad conflicts at the moment so I have to use any const actionsClient = actionsClientMock.create(); serverWithoutAlertClient.decorate('request', 'getBasePath', () => '/s/default'); - serverWithoutAlertClient.decorate('request', 'getActionsClient', () => actionsClient); return { serverWithoutAlertClient: serverWithoutAlertClient as ServerFacade & Hapi.Server, @@ -91,40 +99,6 @@ export const createMockServerWithoutAlertClientDecoration = ( }; }; -export const createMockServerWithoutActionClientDecoration = ( - config: Record = defaultConfig -) => { - const serverWithoutActionClient = new Hapi.Server({ - port: 0, - }); - - serverWithoutActionClient.config = () => createMockKibanaConfig(config); - - const alertsClient = alertsClientMock.create(); - serverWithoutActionClient.decorate('request', 'getBasePath', () => '/s/default'); - serverWithoutActionClient.decorate('request', 'getAlertsClient', () => alertsClient); - - return { - serverWithoutActionClient: serverWithoutActionClient as ServerFacade & Hapi.Server, - alertsClient, - }; -}; - -export const createMockServerWithoutActionOrAlertClientDecoration = ( - config: Record = defaultConfig -) => { - const serverWithoutActionOrAlertClient = new Hapi.Server({ - port: 0, - }); - - serverWithoutActionOrAlertClient.config = () => createMockKibanaConfig(config); - - return { - serverWithoutActionOrAlertClient: serverWithoutActionOrAlertClient as ServerFacade & - Hapi.Server, - }; -}; - export const getMockIndexName = () => jest.fn().mockImplementation(() => ({ callWithRequest: jest.fn().mockImplementationOnce(() => 'index-name'), diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts index a99893433ea8df..4b04cb257d4ac5 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.test.ts @@ -6,9 +6,7 @@ import { createMockServer, - createMockServerWithoutActionClientDecoration, createMockServerWithoutAlertClientDecoration, - createMockServerWithoutActionOrAlertClientDecoration, getMockEmptyIndex, getMockNonEmptyIndex, } from '../__mocks__/_mock_server'; @@ -67,30 +65,12 @@ describe('add_prepackaged_rules_route', () => { expect(statusCode).toBe(200); }); - test('returns 404 if actionClient is not available on the route', async () => { - const { serverWithoutActionClient } = createMockServerWithoutActionClientDecoration(); - createRulesRoute(serverWithoutActionClient); - const { statusCode } = await serverWithoutActionClient.inject(addPrepackagedRulesRequest()); - expect(statusCode).toBe(404); - }); - test('returns 404 if alertClient is not available on the route', async () => { const { serverWithoutAlertClient } = createMockServerWithoutAlertClientDecoration(); createRulesRoute(serverWithoutAlertClient); const { statusCode } = await serverWithoutAlertClient.inject(addPrepackagedRulesRequest()); expect(statusCode).toBe(404); }); - - test('returns 404 if alertClient and actionClient are both not available on the route', async () => { - const { - serverWithoutActionOrAlertClient, - } = createMockServerWithoutActionOrAlertClientDecoration(); - createRulesRoute(serverWithoutActionOrAlertClient); - const { statusCode } = await serverWithoutActionOrAlertClient.inject( - addPrepackagedRulesRequest() - ); - expect(statusCode).toBe(404); - }); }); describe('validation', () => { diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts index 3c9cad8dc4d4b1..28af530272bc77 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts @@ -18,6 +18,7 @@ import { updatePrepackagedRules } from '../../rules/update_prepacked_rules'; import { getRulesToInstall } from '../../rules/get_rules_to_install'; import { getRulesToUpdate } from '../../rules/get_rules_to_update'; import { getExistingPrepackagedRules } from '../../rules/get_existing_prepackaged_rules'; +import { KibanaRequest } from '../../../../../../../../../src/core/server'; export const createAddPrepackedRulesRoute = (server: ServerFacade): Hapi.ServerRoute => { return { @@ -33,13 +34,13 @@ export const createAddPrepackedRulesRoute = (server: ServerFacade): Hapi.ServerR }, async handler(request: RequestFacade, headers) { const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; - const actionsClient = isFunction(request.getActionsClient) - ? request.getActionsClient() - : null; + const actionsClient = await server.plugins.actions.getActionsClientWithRequest( + KibanaRequest.from((request as unknown) as Hapi.Request) + ); const savedObjectsClient = isFunction(request.getSavedObjectsClient) ? request.getSavedObjectsClient() : null; - if (!alertsClient || !actionsClient || !savedObjectsClient) { + if (!alertsClient || !savedObjectsClient) { return headers.response().code(404); } @@ -60,7 +61,9 @@ export const createAddPrepackedRulesRoute = (server: ServerFacade): Hapi.ServerR ); } } - await installPrepackagedRules(alertsClient, actionsClient, rulesToInstall, spaceIndex); + await Promise.all( + installPrepackagedRules(alertsClient, actionsClient, rulesToInstall, spaceIndex) + ); await updatePrepackagedRules( alertsClient, actionsClient, diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts index 0931e941f8e464..5cf6d8955d8b2a 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_bulk_route.test.ts @@ -6,9 +6,7 @@ import { createMockServer, - createMockServerWithoutActionClientDecoration, createMockServerWithoutAlertClientDecoration, - createMockServerWithoutActionOrAlertClientDecoration, getMockEmptyIndex, } from '../__mocks__/_mock_server'; import { createRulesRoute } from './create_rules_route'; @@ -42,28 +40,12 @@ describe('create_rules_bulk', () => { expect(statusCode).toBe(200); }); - test('returns 404 if actionClient is not available on the route', async () => { - const { serverWithoutActionClient } = createMockServerWithoutActionClientDecoration(); - createRulesRoute(serverWithoutActionClient); - const { statusCode } = await serverWithoutActionClient.inject(getReadBulkRequest()); - expect(statusCode).toBe(404); - }); - test('returns 404 if alertClient is not available on the route', async () => { const { serverWithoutAlertClient } = createMockServerWithoutAlertClientDecoration(); createRulesRoute(serverWithoutAlertClient); const { statusCode } = await serverWithoutAlertClient.inject(getReadBulkRequest()); expect(statusCode).toBe(404); }); - - test('returns 404 if alertClient and actionClient are both not available on the route', async () => { - const { - serverWithoutActionOrAlertClient, - } = createMockServerWithoutActionOrAlertClientDecoration(); - createRulesRoute(serverWithoutActionOrAlertClient); - const { statusCode } = await serverWithoutActionOrAlertClient.inject(getReadBulkRequest()); - expect(statusCode).toBe(404); - }); }); describe('validation', () => { diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts index 00a1d2eb980ec3..0c98507bc6fa8d 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_bulk_route.ts @@ -21,6 +21,7 @@ import { createBulkErrorObject, } from '../utils'; import { createRulesBulkSchema } from '../schemas/create_rules_bulk_schema'; +import { KibanaRequest } from '../../../../../../../../../src/core/server'; export const createCreateRulesBulkRoute = (server: ServerFacade): Hapi.ServerRoute => { return { @@ -37,17 +38,17 @@ export const createCreateRulesBulkRoute = (server: ServerFacade): Hapi.ServerRou }, async handler(request: BulkRulesRequest, headers) { const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; - const actionsClient = isFunction(request.getActionsClient) - ? request.getActionsClient() - : null; + const actionsClient = await server.plugins.actions.getActionsClientWithRequest( + KibanaRequest.from((request as unknown) as Hapi.Request) + ); const savedObjectsClient = isFunction(request.getSavedObjectsClient) ? request.getSavedObjectsClient() : null; - if (!alertsClient || !actionsClient || !savedObjectsClient) { + if (!alertsClient || !savedObjectsClient) { return headers.response().code(404); } - const rules = Promise.all( + const rules = await Promise.all( request.payload.map(async payloadRule => { const { created_at: createdAt, diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_route.test.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_route.test.ts index 77c6f6f3b4840d..27575fb264f7b4 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_route.test.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_route.test.ts @@ -6,9 +6,7 @@ import { createMockServer, - createMockServerWithoutActionClientDecoration, createMockServerWithoutAlertClientDecoration, - createMockServerWithoutActionOrAlertClientDecoration, getMockNonEmptyIndex, getMockEmptyIndex, } from '../__mocks__/_mock_server'; @@ -58,28 +56,12 @@ describe('create_rules', () => { expect(statusCode).toBe(200); }); - test('returns 404 if actionClient is not available on the route', async () => { - const { serverWithoutActionClient } = createMockServerWithoutActionClientDecoration(); - createRulesRoute(serverWithoutActionClient); - const { statusCode } = await serverWithoutActionClient.inject(getCreateRequest()); - expect(statusCode).toBe(404); - }); - test('returns 404 if alertClient is not available on the route', async () => { const { serverWithoutAlertClient } = createMockServerWithoutAlertClientDecoration(); createRulesRoute(serverWithoutAlertClient); const { statusCode } = await serverWithoutAlertClient.inject(getCreateRequest()); expect(statusCode).toBe(404); }); - - test('returns 404 if alertClient and actionClient are both not available on the route', async () => { - const { - serverWithoutActionOrAlertClient, - } = createMockServerWithoutActionOrAlertClientDecoration(); - createRulesRoute(serverWithoutActionOrAlertClient); - const { statusCode } = await serverWithoutActionOrAlertClient.inject(getCreateRequest()); - expect(statusCode).toBe(404); - }); }); describe('validation', () => { diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_route.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_route.ts index 23acd12d341ed8..4480186d9a7a65 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_route.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/create_rules_route.ts @@ -18,6 +18,7 @@ import { ruleStatusSavedObjectType } from '../../rules/saved_object_mappings'; import { transformOrError } from './utils'; import { getIndexExists } from '../../index/get_index_exists'; import { callWithRequestFactory, getIndex, transformError } from '../utils'; +import { KibanaRequest } from '../../../../../../../../../src/core/server'; export const createCreateRulesRoute = (server: ServerFacade): Hapi.ServerRoute => { return { @@ -62,13 +63,13 @@ export const createCreateRulesRoute = (server: ServerFacade): Hapi.ServerRoute = references, } = request.payload; const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; - const actionsClient = isFunction(request.getActionsClient) - ? request.getActionsClient() - : null; + const actionsClient = await server.plugins.actions.getActionsClientWithRequest( + KibanaRequest.from((request as unknown) as Hapi.Request) + ); const savedObjectsClient = isFunction(request.getSavedObjectsClient) ? request.getSavedObjectsClient() : null; - if (!alertsClient || !actionsClient || !savedObjectsClient) { + if (!alertsClient || !savedObjectsClient) { return headers.response().code(404); } diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.test.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.test.ts index 7b8496b2fe7251..e66fc765c08bf5 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.test.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.test.ts @@ -6,9 +6,7 @@ import { createMockServer, - createMockServerWithoutActionClientDecoration, createMockServerWithoutAlertClientDecoration, - createMockServerWithoutActionOrAlertClientDecoration, } from '../__mocks__/_mock_server'; import { ServerInjectOptions } from 'hapi'; @@ -97,28 +95,12 @@ describe('delete_rules', () => { expect(parsed).toEqual(expected); }); - test('returns 404 if actionClient is not available on the route', async () => { - const { serverWithoutActionClient } = createMockServerWithoutActionClientDecoration(); - deleteRulesBulkRoute(serverWithoutActionClient); - const { statusCode } = await serverWithoutActionClient.inject(getDeleteBulkRequest()); - expect(statusCode).toBe(404); - }); - test('returns 404 if alertClient is not available on the route', async () => { const { serverWithoutAlertClient } = createMockServerWithoutAlertClientDecoration(); deleteRulesBulkRoute(serverWithoutAlertClient); const { statusCode } = await serverWithoutAlertClient.inject(getDeleteBulkRequest()); expect(statusCode).toBe(404); }); - - test('returns 404 if alertClient and actionClient are both not available on the route', async () => { - const { - serverWithoutActionOrAlertClient, - } = createMockServerWithoutActionOrAlertClientDecoration(); - deleteRulesBulkRoute(serverWithoutActionOrAlertClient); - const { statusCode } = await serverWithoutActionOrAlertClient.inject(getDeleteBulkRequest()); - expect(statusCode).toBe(404); - }); }); describe('validation', () => { diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts index b77ae56a486c87..c2b5576c091835 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_bulk_route.ts @@ -15,64 +15,69 @@ import { transformOrBulkError, getIdBulkError } from './utils'; import { transformBulkError } from '../utils'; import { QueryBulkRequest, IRuleSavedAttributesSavedObjectAttributes } from '../../rules/types'; import { ruleStatusSavedObjectType } from '../../rules/saved_object_mappings'; +import { KibanaRequest } from '../../../../../../../../../src/core/server'; -export const createDeleteRulesBulkRoute: Hapi.ServerRoute = { - method: ['POST', 'DELETE'], // allow both POST and DELETE in case their client does not support bodies in DELETE - path: `${DETECTION_ENGINE_RULES_URL}/_bulk_delete`, - options: { - tags: ['access:siem'], - validate: { - options: { - abortEarly: false, +export const createDeleteRulesBulkRoute = (server: ServerFacade): Hapi.ServerRoute => { + return { + method: ['POST', 'DELETE'], // allow both POST and DELETE in case their client does not support bodies in DELETE + path: `${DETECTION_ENGINE_RULES_URL}/_bulk_delete`, + options: { + tags: ['access:siem'], + validate: { + options: { + abortEarly: false, + }, + payload: queryRulesBulkSchema, }, - payload: queryRulesBulkSchema, }, - }, - async handler(request: QueryBulkRequest, headers) { - const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; - const actionsClient = isFunction(request.getActionsClient) ? request.getActionsClient() : null; - const savedObjectsClient = isFunction(request.getSavedObjectsClient) - ? request.getSavedObjectsClient() - : null; - if (!alertsClient || !actionsClient || !savedObjectsClient) { - return headers.response().code(404); - } - const rules = Promise.all( - request.payload.map(async payloadRule => { - const { id, rule_id: ruleId } = payloadRule; - const idOrRuleIdOrUnknown = id ?? ruleId ?? '(unknown id)'; - try { - const rule = await deleteRules({ - actionsClient, - alertsClient, - id, - ruleId, - }); - if (rule != null) { - const ruleStatuses = await savedObjectsClient.find< - IRuleSavedAttributesSavedObjectAttributes - >({ - type: ruleStatusSavedObjectType, - perPage: 6, - search: rule.id, - searchFields: ['alertId'], + async handler(request: QueryBulkRequest, headers) { + const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; + const actionsClient = await server.plugins.actions.getActionsClientWithRequest( + KibanaRequest.from((request as unknown) as Hapi.Request) + ); + const savedObjectsClient = isFunction(request.getSavedObjectsClient) + ? request.getSavedObjectsClient() + : null; + if (!alertsClient || !savedObjectsClient) { + return headers.response().code(404); + } + const rules = Promise.all( + request.payload.map(async payloadRule => { + const { id, rule_id: ruleId } = payloadRule; + const idOrRuleIdOrUnknown = id ?? ruleId ?? '(unknown id)'; + try { + const rule = await deleteRules({ + actionsClient, + alertsClient, + id, + ruleId, }); - ruleStatuses.saved_objects.forEach(async obj => - savedObjectsClient.delete(ruleStatusSavedObjectType, obj.id) - ); - return transformOrBulkError(idOrRuleIdOrUnknown, rule); - } else { - return getIdBulkError({ id, ruleId }); + if (rule != null) { + const ruleStatuses = await savedObjectsClient.find< + IRuleSavedAttributesSavedObjectAttributes + >({ + type: ruleStatusSavedObjectType, + perPage: 6, + search: rule.id, + searchFields: ['alertId'], + }); + ruleStatuses.saved_objects.forEach(async obj => + savedObjectsClient.delete(ruleStatusSavedObjectType, obj.id) + ); + return transformOrBulkError(idOrRuleIdOrUnknown, rule); + } else { + return getIdBulkError({ id, ruleId }); + } + } catch (err) { + return transformBulkError(idOrRuleIdOrUnknown, err); } - } catch (err) { - return transformBulkError(idOrRuleIdOrUnknown, err); - } - }) - ); - return rules; - }, + }) + ); + return rules; + }, + }; }; export const deleteRulesBulkRoute = (server: ServerFacade): void => { - server.route(createDeleteRulesBulkRoute); + server.route(createDeleteRulesBulkRoute(server)); }; diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_route.test.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_route.test.ts index 2854312246c5f1..0aa60d3bbd9229 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_route.test.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_route.test.ts @@ -6,9 +6,7 @@ import { createMockServer, - createMockServerWithoutActionClientDecoration, createMockServerWithoutAlertClientDecoration, - createMockServerWithoutActionOrAlertClientDecoration, } from '../__mocks__/_mock_server'; import { deleteRulesRoute } from './delete_rules_route'; @@ -67,28 +65,12 @@ describe('delete_rules', () => { expect(statusCode).toBe(404); }); - test('returns 404 if actionClient is not available on the route', async () => { - const { serverWithoutActionClient } = createMockServerWithoutActionClientDecoration(); - deleteRulesRoute(serverWithoutActionClient); - const { statusCode } = await serverWithoutActionClient.inject(getDeleteRequest()); - expect(statusCode).toBe(404); - }); - test('returns 404 if alertClient is not available on the route', async () => { const { serverWithoutAlertClient } = createMockServerWithoutAlertClientDecoration(); deleteRulesRoute(serverWithoutAlertClient); const { statusCode } = await serverWithoutAlertClient.inject(getDeleteRequest()); expect(statusCode).toBe(404); }); - - test('returns 404 if alertClient and actionClient are both not available on the route', async () => { - const { - serverWithoutActionOrAlertClient, - } = createMockServerWithoutActionOrAlertClientDecoration(); - deleteRulesRoute(serverWithoutActionOrAlertClient); - const { statusCode } = await serverWithoutActionOrAlertClient.inject(getDeleteRequest()); - expect(statusCode).toBe(404); - }); }); describe('validation', () => { diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_route.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_route.ts index ea8b54a79a5e3c..33f181cfbb5a5c 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_route.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/delete_rules_route.ts @@ -15,59 +15,64 @@ import { getIdError, transformOrError } from './utils'; import { transformError } from '../utils'; import { QueryRequest, IRuleSavedAttributesSavedObjectAttributes } from '../../rules/types'; import { ruleStatusSavedObjectType } from '../../rules/saved_object_mappings'; +import { KibanaRequest } from '../../../../../../../../../src/core/server'; -export const createDeleteRulesRoute: Hapi.ServerRoute = { - method: 'DELETE', - path: DETECTION_ENGINE_RULES_URL, - options: { - tags: ['access:siem'], - validate: { - options: { - abortEarly: false, +export const createDeleteRulesRoute = (server: ServerFacade): Hapi.ServerRoute => { + return { + method: 'DELETE', + path: DETECTION_ENGINE_RULES_URL, + options: { + tags: ['access:siem'], + validate: { + options: { + abortEarly: false, + }, + query: queryRulesSchema, }, - query: queryRulesSchema, }, - }, - async handler(request: QueryRequest, headers) { - const { id, rule_id: ruleId } = request.query; - const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; - const actionsClient = isFunction(request.getActionsClient) ? request.getActionsClient() : null; - const savedObjectsClient = isFunction(request.getSavedObjectsClient) - ? request.getSavedObjectsClient() - : null; - if (!alertsClient || !actionsClient || !savedObjectsClient) { - return headers.response().code(404); - } + async handler(request: QueryRequest, headers) { + const { id, rule_id: ruleId } = request.query; + const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; + const actionsClient = await server.plugins.actions.getActionsClientWithRequest( + KibanaRequest.from((request as unknown) as Hapi.Request) + ); + const savedObjectsClient = isFunction(request.getSavedObjectsClient) + ? request.getSavedObjectsClient() + : null; + if (!alertsClient || !savedObjectsClient) { + return headers.response().code(404); + } - try { - const rule = await deleteRules({ - actionsClient, - alertsClient, - id, - ruleId, - }); - if (rule != null) { - const ruleStatuses = await savedObjectsClient.find< - IRuleSavedAttributesSavedObjectAttributes - >({ - type: ruleStatusSavedObjectType, - perPage: 6, - search: rule.id, - searchFields: ['alertId'], + try { + const rule = await deleteRules({ + actionsClient, + alertsClient, + id, + ruleId, }); - ruleStatuses.saved_objects.forEach(async obj => - savedObjectsClient.delete(ruleStatusSavedObjectType, obj.id) - ); - return transformOrError(rule, ruleStatuses.saved_objects[0]); - } else { - return getIdError({ id, ruleId }); + if (rule != null) { + const ruleStatuses = await savedObjectsClient.find< + IRuleSavedAttributesSavedObjectAttributes + >({ + type: ruleStatusSavedObjectType, + perPage: 6, + search: rule.id, + searchFields: ['alertId'], + }); + ruleStatuses.saved_objects.forEach(async obj => + savedObjectsClient.delete(ruleStatusSavedObjectType, obj.id) + ); + return transformOrError(rule, ruleStatuses.saved_objects[0]); + } else { + return getIdError({ id, ruleId }); + } + } catch (err) { + return transformError(err); } - } catch (err) { - return transformError(err); - } - }, + }, + }; }; export const deleteRulesRoute = (server: ServerFacade): void => { - server.route(createDeleteRulesRoute); + server.route(createDeleteRulesRoute(server)); }; diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/export_rules_route.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/export_rules_route.ts index aa17946849027c..b9ff2e60186242 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/export_rules_route.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/export_rules_route.ts @@ -31,11 +31,8 @@ export const createExportRulesRoute = (server: ServerFacade): Hapi.ServerRoute = }, async handler(request: ExportRulesRequest, headers) { const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; - const actionsClient = isFunction(request.getActionsClient) - ? request.getActionsClient() - : null; - if (!alertsClient || !actionsClient) { + if (!alertsClient) { return headers.response().code(404); } diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/find_rules_route.test.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/find_rules_route.test.ts index 0aab02281a5364..62c9f44da1e332 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/find_rules_route.test.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/find_rules_route.test.ts @@ -6,9 +6,7 @@ import { createMockServer, - createMockServerWithoutActionClientDecoration, createMockServerWithoutAlertClientDecoration, - createMockServerWithoutActionOrAlertClientDecoration, } from '../__mocks__/_mock_server'; import { findRulesRoute } from './find_rules_route'; @@ -43,28 +41,12 @@ describe('find_rules', () => { expect(statusCode).toBe(200); }); - test('returns 404 if actionClient is not available on the route', async () => { - const { serverWithoutActionClient } = createMockServerWithoutActionClientDecoration(); - findRulesRoute(serverWithoutActionClient); - const { statusCode } = await serverWithoutActionClient.inject(getFindRequest()); - expect(statusCode).toBe(404); - }); - test('returns 404 if alertClient is not available on the route', async () => { const { serverWithoutAlertClient } = createMockServerWithoutAlertClientDecoration(); findRulesRoute(serverWithoutAlertClient); const { statusCode } = await serverWithoutAlertClient.inject(getFindRequest()); expect(statusCode).toBe(404); }); - - test('returns 404 if alertClient and actionClient are both not available on the route', async () => { - const { - serverWithoutActionOrAlertClient, - } = createMockServerWithoutActionOrAlertClientDecoration(); - findRulesRoute(serverWithoutActionOrAlertClient); - const { statusCode } = await serverWithoutActionOrAlertClient.inject(getFindRequest()); - expect(statusCode).toBe(404); - }); }); describe('validation', () => { diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/find_rules_route.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/find_rules_route.ts index 6cbc794751f9fb..5b12703590407c 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/find_rules_route.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/find_rules_route.ts @@ -15,58 +15,61 @@ import { transformFindAlertsOrError } from './utils'; import { transformError } from '../utils'; import { ruleStatusSavedObjectType } from '../../rules/saved_object_mappings'; -export const createFindRulesRoute: Hapi.ServerRoute = { - method: 'GET', - path: `${DETECTION_ENGINE_RULES_URL}/_find`, - options: { - tags: ['access:siem'], - validate: { - options: { - abortEarly: false, +export const createFindRulesRoute = (): Hapi.ServerRoute => { + return { + method: 'GET', + path: `${DETECTION_ENGINE_RULES_URL}/_find`, + options: { + tags: ['access:siem'], + validate: { + options: { + abortEarly: false, + }, + query: findRulesSchema, }, - query: findRulesSchema, }, - }, - async handler(request: FindRulesRequest, headers) { - const { query } = request; - const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; - const actionsClient = isFunction(request.getActionsClient) ? request.getActionsClient() : null; - const savedObjectsClient = isFunction(request.getSavedObjectsClient) - ? request.getSavedObjectsClient() - : null; - if (!alertsClient || !actionsClient || !savedObjectsClient) { - return headers.response().code(404); - } + async handler(request: FindRulesRequest, headers) { + const { query } = request; + const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; + const savedObjectsClient = isFunction(request.getSavedObjectsClient) + ? request.getSavedObjectsClient() + : null; + if (!alertsClient || !savedObjectsClient) { + return headers.response().code(404); + } - try { - const rules = await findRules({ - alertsClient, - perPage: query.per_page, - page: query.page, - sortField: query.sort_field, - sortOrder: query.sort_order, - filter: query.filter, - }); - const ruleStatuses = await Promise.all( - rules.data.map(async rule => { - const results = await savedObjectsClient.find({ - type: ruleStatusSavedObjectType, - perPage: 1, - sortField: 'statusDate', - sortOrder: 'desc', - search: rule.id, - searchFields: ['alertId'], - }); - return results; - }) - ); - return transformFindAlertsOrError(rules, ruleStatuses); - } catch (err) { - return transformError(err); - } - }, + try { + const rules = await findRules({ + alertsClient, + perPage: query.per_page, + page: query.page, + sortField: query.sort_field, + sortOrder: query.sort_order, + filter: query.filter, + }); + const ruleStatuses = await Promise.all( + rules.data.map(async rule => { + const results = await savedObjectsClient.find< + IRuleSavedAttributesSavedObjectAttributes + >({ + type: ruleStatusSavedObjectType, + perPage: 1, + sortField: 'statusDate', + sortOrder: 'desc', + search: rule.id, + searchFields: ['alertId'], + }); + return results; + }) + ); + return transformFindAlertsOrError(rules, ruleStatuses); + } catch (err) { + return transformError(err); + } + }, + }; }; export const findRulesRoute = (server: ServerFacade) => { - server.route(createFindRulesRoute); + server.route(createFindRulesRoute()); }; diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/find_rules_status_route.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/find_rules_status_route.ts index 545c2e488b1c8b..8b3113a044b5ac 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/find_rules_status_route.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/find_rules_status_route.ts @@ -44,11 +44,10 @@ export const createFindRulesStatusRoute: Hapi.ServerRoute = { async handler(request: FindRulesStatusesRequest, headers) { const { query } = request; const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; - const actionsClient = isFunction(request.getActionsClient) ? request.getActionsClient() : null; const savedObjectsClient = isFunction(request.getSavedObjectsClient) ? request.getSavedObjectsClient() : null; - if (!alertsClient || !actionsClient || !savedObjectsClient) { + if (!alertsClient || !savedObjectsClient) { return headers.response().code(404); } diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/get_prepackaged_rule_status_route.test.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/get_prepackaged_rule_status_route.test.ts index f07d6a9fc65a6f..67680a8f86eec2 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/get_prepackaged_rule_status_route.test.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/get_prepackaged_rule_status_route.test.ts @@ -6,9 +6,7 @@ import { createMockServer, - createMockServerWithoutActionClientDecoration, createMockServerWithoutAlertClientDecoration, - createMockServerWithoutActionOrAlertClientDecoration, getMockNonEmptyIndex, } from '../__mocks__/_mock_server'; import { createRulesRoute } from './create_rules_route'; @@ -65,15 +63,6 @@ describe('get_prepackaged_rule_status_route', () => { expect(statusCode).toBe(200); }); - test('returns 404 if actionClient is not available on the route', async () => { - const { serverWithoutActionClient } = createMockServerWithoutActionClientDecoration(); - createRulesRoute(serverWithoutActionClient); - const { statusCode } = await serverWithoutActionClient.inject( - getPrepackagedRulesStatusRequest() - ); - expect(statusCode).toBe(404); - }); - test('returns 404 if alertClient is not available on the route', async () => { const { serverWithoutAlertClient } = createMockServerWithoutAlertClientDecoration(); createRulesRoute(serverWithoutAlertClient); @@ -82,17 +71,6 @@ describe('get_prepackaged_rule_status_route', () => { ); expect(statusCode).toBe(404); }); - - test('returns 404 if alertClient and actionClient are both not available on the route', async () => { - const { - serverWithoutActionOrAlertClient, - } = createMockServerWithoutActionOrAlertClientDecoration(); - createRulesRoute(serverWithoutActionOrAlertClient); - const { statusCode } = await serverWithoutActionOrAlertClient.inject( - getPrepackagedRulesStatusRequest() - ); - expect(statusCode).toBe(404); - }); }); describe('payload', () => { diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts index 99e29242bced07..0208a209c5eaef 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/get_prepackaged_rules_status_route.ts @@ -29,11 +29,8 @@ export const createGetPrepackagedRulesStatusRoute = (): Hapi.ServerRoute => { }, async handler(request: RequestFacade, headers) { const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; - const actionsClient = isFunction(request.getActionsClient) - ? request.getActionsClient() - : null; - if (!alertsClient || !actionsClient) { + if (!alertsClient) { return headers.response().code(404); } diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/import_rules_route.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/import_rules_route.ts index 6efaa1fea60d08..0dfdee2d713756 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/import_rules_route.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/import_rules_route.ts @@ -27,6 +27,7 @@ import { ImportRuleAlertRest } from '../../types'; import { transformOrImportError } from './utils'; import { updateRules } from '../../rules/update_rules'; import { importRulesQuerySchema, importRulesPayloadSchema } from '../schemas/import_rules_schema'; +import { KibanaRequest } from '../../../../../../../../../src/core/server'; export const createImportRulesRoute = (server: ServerFacade): Hapi.ServerRoute => { return { @@ -49,13 +50,13 @@ export const createImportRulesRoute = (server: ServerFacade): Hapi.ServerRoute = }, async handler(request: ImportRulesRequest, headers) { const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; - const actionsClient = isFunction(request.getActionsClient) - ? request.getActionsClient() - : null; + const actionsClient = await server.plugins.actions.getActionsClientWithRequest( + KibanaRequest.from((request as unknown) as Hapi.Request) + ); const savedObjectsClient = isFunction(request.getSavedObjectsClient) ? request.getSavedObjectsClient() : null; - if (!alertsClient || !actionsClient || !savedObjectsClient) { + if (!alertsClient || !savedObjectsClient) { return headers.response().code(404); } const { filename } = request.payload.file.hapi; diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/read_rules_route.test.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/read_rules_route.test.ts index 4190225bea1f1e..000cd29af8ba9c 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/read_rules_route.test.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/read_rules_route.test.ts @@ -6,9 +6,7 @@ import { createMockServer, - createMockServerWithoutActionClientDecoration, createMockServerWithoutAlertClientDecoration, - createMockServerWithoutActionOrAlertClientDecoration, } from '../__mocks__/_mock_server'; import { readRulesRoute } from './read_rules_route'; @@ -44,28 +42,12 @@ describe('read_signals', () => { expect(statusCode).toBe(200); }); - test('returns 404 if actionClient is not available on the route', async () => { - const { serverWithoutActionClient } = createMockServerWithoutActionClientDecoration(); - readRulesRoute(serverWithoutActionClient); - const { statusCode } = await serverWithoutActionClient.inject(getReadRequest()); - expect(statusCode).toBe(404); - }); - test('returns 404 if alertClient is not available on the route', async () => { const { serverWithoutAlertClient } = createMockServerWithoutAlertClientDecoration(); readRulesRoute(serverWithoutAlertClient); const { statusCode } = await serverWithoutAlertClient.inject(getReadRequest()); expect(statusCode).toBe(404); }); - - test('returns 404 if alertClient and actionClient are both not available on the route', async () => { - const { - serverWithoutActionOrAlertClient, - } = createMockServerWithoutActionOrAlertClientDecoration(); - readRulesRoute(serverWithoutActionOrAlertClient); - const { statusCode } = await serverWithoutActionOrAlertClient.inject(getReadRequest()); - expect(statusCode).toBe(404); - }); }); describe('validation', () => { diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/read_rules_route.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/read_rules_route.ts index 25d8e6770f6999..55fecdc14f7558 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/read_rules_route.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/read_rules_route.ts @@ -31,11 +31,10 @@ export const createReadRulesRoute: Hapi.ServerRoute = { async handler(request: QueryRequest, headers) { const { id, rule_id: ruleId } = request.query; const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; - const actionsClient = isFunction(request.getActionsClient) ? request.getActionsClient() : null; const savedObjectsClient = isFunction(request.getSavedObjectsClient) ? request.getSavedObjectsClient() : null; - if (!alertsClient || !actionsClient || !savedObjectsClient) { + if (!alertsClient || !savedObjectsClient) { return headers.response().code(404); } try { diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_bulk.test.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_bulk.test.ts index cc41800671d7d1..81b6444f386031 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_bulk.test.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_bulk.test.ts @@ -6,9 +6,7 @@ import { createMockServer, - createMockServerWithoutActionClientDecoration, createMockServerWithoutAlertClientDecoration, - createMockServerWithoutActionOrAlertClientDecoration, } from '../__mocks__/_mock_server'; import { updateRulesRoute } from './update_rules_route'; @@ -70,28 +68,12 @@ describe('update_rules_bulk', () => { expect(parsed).toEqual(expected); }); - test('returns 404 if actionClient is not available on the route', async () => { - const { serverWithoutActionClient } = createMockServerWithoutActionClientDecoration(); - updateRulesRoute(serverWithoutActionClient); - const { statusCode } = await serverWithoutActionClient.inject(getUpdateBulkRequest()); - expect(statusCode).toBe(404); - }); - test('returns 404 if alertClient is not available on the route', async () => { const { serverWithoutAlertClient } = createMockServerWithoutAlertClientDecoration(); updateRulesRoute(serverWithoutAlertClient); const { statusCode } = await serverWithoutAlertClient.inject(getUpdateBulkRequest()); expect(statusCode).toBe(404); }); - - test('returns 404 if alertClient and actionClient are both not available on the route', async () => { - const { - serverWithoutActionOrAlertClient, - } = createMockServerWithoutActionOrAlertClientDecoration(); - updateRulesRoute(serverWithoutActionOrAlertClient); - const { statusCode } = await serverWithoutActionOrAlertClient.inject(getUpdateBulkRequest()); - expect(statusCode).toBe(404); - }); }); describe('validation', () => { diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts index e0d2672cf356a5..cf98043529bc03 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_bulk_route.ts @@ -17,6 +17,7 @@ import { transformBulkError } from '../utils'; import { updateRulesBulkSchema } from '../schemas/update_rules_bulk_schema'; import { updateRules } from '../../rules/update_rules'; import { ruleStatusSavedObjectType } from '../../rules/saved_object_mappings'; +import { KibanaRequest } from '../../../../../../../../../src/core/server'; export const createUpdateRulesBulkRoute = (server: ServerFacade): Hapi.ServerRoute => { return { @@ -33,13 +34,13 @@ export const createUpdateRulesBulkRoute = (server: ServerFacade): Hapi.ServerRou }, async handler(request: BulkUpdateRulesRequest, headers) { const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; - const actionsClient = isFunction(request.getActionsClient) - ? request.getActionsClient() - : null; + const actionsClient = await server.plugins.actions.getActionsClientWithRequest( + KibanaRequest.from((request as unknown) as Hapi.Request) + ); const savedObjectsClient = isFunction(request.getSavedObjectsClient) ? request.getSavedObjectsClient() : null; - if (!alertsClient || !actionsClient || !savedObjectsClient) { + if (!alertsClient || !savedObjectsClient) { return headers.response().code(404); } diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_route.test.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_route.test.ts index a7e8f1b1c0a7e5..c4f10d7a203271 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_route.test.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_route.test.ts @@ -6,9 +6,7 @@ import { createMockServer, - createMockServerWithoutActionClientDecoration, createMockServerWithoutAlertClientDecoration, - createMockServerWithoutActionOrAlertClientDecoration, } from '../__mocks__/_mock_server'; import { updateRulesRoute } from './update_rules_route'; @@ -55,28 +53,12 @@ describe('update_rules', () => { expect(statusCode).toBe(404); }); - test('returns 404 if actionClient is not available on the route', async () => { - const { serverWithoutActionClient } = createMockServerWithoutActionClientDecoration(); - updateRulesRoute(serverWithoutActionClient); - const { statusCode } = await serverWithoutActionClient.inject(getUpdateRequest()); - expect(statusCode).toBe(404); - }); - test('returns 404 if alertClient is not available on the route', async () => { const { serverWithoutAlertClient } = createMockServerWithoutAlertClientDecoration(); updateRulesRoute(serverWithoutAlertClient); const { statusCode } = await serverWithoutAlertClient.inject(getUpdateRequest()); expect(statusCode).toBe(404); }); - - test('returns 404 if alertClient and actionClient are both not available on the route', async () => { - const { - serverWithoutActionOrAlertClient, - } = createMockServerWithoutActionOrAlertClientDecoration(); - updateRulesRoute(serverWithoutActionOrAlertClient); - const { statusCode } = await serverWithoutActionOrAlertClient.inject(getUpdateRequest()); - expect(statusCode).toBe(404); - }); }); describe('validation', () => { diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_route.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_route.ts index 49c9304ae2d25a..cbb66317186a13 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_route.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/rules/update_rules_route.ts @@ -14,81 +14,41 @@ import { ServerFacade } from '../../../../types'; import { getIdError, transformOrError } from './utils'; import { transformError } from '../utils'; import { ruleStatusSavedObjectType } from '../../rules/saved_object_mappings'; +import { KibanaRequest } from '../../../../../../../../../src/core/server'; -export const createUpdateRulesRoute: Hapi.ServerRoute = { - method: 'PUT', - path: DETECTION_ENGINE_RULES_URL, - options: { - tags: ['access:siem'], - validate: { - options: { - abortEarly: false, +export const createUpdateRulesRoute = (server: ServerFacade): Hapi.ServerRoute => { + return { + method: 'PUT', + path: DETECTION_ENGINE_RULES_URL, + options: { + tags: ['access:siem'], + validate: { + options: { + abortEarly: false, + }, + payload: updateRulesSchema, }, - payload: updateRulesSchema, }, - }, - async handler(request: UpdateRulesRequest, headers) { - const { - description, - enabled, - false_positives: falsePositives, - from, - query, - language, - output_index: outputIndex, - saved_id: savedId, - timeline_id: timelineId, - timeline_title: timelineTitle, - meta, - filters, - rule_id: ruleId, - id, - index, - interval, - max_signals: maxSignals, - risk_score: riskScore, - name, - severity, - tags, - to, - type, - threats, - references, - version, - } = request.payload; - - const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; - const actionsClient = isFunction(request.getActionsClient) ? request.getActionsClient() : null; - const savedObjectsClient = isFunction(request.getSavedObjectsClient) - ? request.getSavedObjectsClient() - : null; - if (!alertsClient || !actionsClient || !savedObjectsClient) { - return headers.response().code(404); - } - - try { - const rule = await updateRules({ - alertsClient, - actionsClient, + async handler(request: UpdateRulesRequest, headers) { + const { description, enabled, - falsePositives, + false_positives: falsePositives, from, query, language, - outputIndex, - savedId, - savedObjectsClient, - timelineId, - timelineTitle, + output_index: outputIndex, + saved_id: savedId, + timeline_id: timelineId, + timeline_title: timelineTitle, meta, filters, + rule_id: ruleId, id, - ruleId, index, interval, - maxSignals, - riskScore, + max_signals: maxSignals, + risk_score: riskScore, name, severity, tags, @@ -97,28 +57,73 @@ export const createUpdateRulesRoute: Hapi.ServerRoute = { threats, references, version, - }); - if (rule != null) { - const ruleStatuses = await savedObjectsClient.find< - IRuleSavedAttributesSavedObjectAttributes - >({ - type: ruleStatusSavedObjectType, - perPage: 1, - sortField: 'statusDate', - sortOrder: 'desc', - search: rule.id, - searchFields: ['alertId'], + } = request.payload; + + const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; + const actionsClient = await server.plugins.actions.getActionsClientWithRequest( + KibanaRequest.from((request as unknown) as Hapi.Request) + ); + const savedObjectsClient = isFunction(request.getSavedObjectsClient) + ? request.getSavedObjectsClient() + : null; + if (!alertsClient || !savedObjectsClient) { + return headers.response().code(404); + } + + try { + const rule = await updateRules({ + alertsClient, + actionsClient, + description, + enabled, + falsePositives, + from, + query, + language, + outputIndex, + savedId, + savedObjectsClient, + timelineId, + timelineTitle, + meta, + filters, + id, + ruleId, + index, + interval, + maxSignals, + riskScore, + name, + severity, + tags, + to, + type, + threats, + references, + version, }); - return transformOrError(rule, ruleStatuses.saved_objects[0]); - } else { - return getIdError({ id, ruleId }); + if (rule != null) { + const ruleStatuses = await savedObjectsClient.find< + IRuleSavedAttributesSavedObjectAttributes + >({ + type: ruleStatusSavedObjectType, + perPage: 1, + sortField: 'statusDate', + sortOrder: 'desc', + search: rule.id, + searchFields: ['alertId'], + }); + return transformOrError(rule, ruleStatuses.saved_objects[0]); + } else { + return getIdError({ id, ruleId }); + } + } catch (err) { + return transformError(err); } - } catch (err) { - return transformError(err); - } - }, + }, + }; }; export const updateRulesRoute = (server: ServerFacade) => { - server.route(createUpdateRulesRoute); + server.route(createUpdateRulesRoute(server)); }; diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/tags/read_tags_route.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/tags/read_tags_route.ts index beef8b4199c15e..c598e22ff596c5 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/tags/read_tags_route.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/routes/tags/read_tags_route.ts @@ -24,9 +24,7 @@ export const createReadTagsRoute: Hapi.ServerRoute = { }, async handler(request: RequestFacade, headers) { const alertsClient = isFunction(request.getAlertsClient) ? request.getAlertsClient() : null; - const actionsClient = isFunction(request.getActionsClient) ? request.getActionsClient() : null; - - if (!alertsClient || !actionsClient) { + if (!alertsClient) { return headers.response().code(404); } diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/rules/create_rules.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/rules/create_rules.ts index d2f76907d7aa3e..1d3801d80de113 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/rules/create_rules.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/rules/create_rules.ts @@ -8,7 +8,7 @@ import { APP_ID, SIGNALS_ID } from '../../../../common/constants'; import { RuleParams } from './types'; import { addTags } from './add_tags'; -export const createRules = async ({ +export const createRules = ({ alertsClient, actionsClient, // TODO: Use this actionsClient once we have actions such as email, etc... description, diff --git a/x-pack/legacy/plugins/siem/server/lib/detection_engine/rules/install_prepacked_rules.ts b/x-pack/legacy/plugins/siem/server/lib/detection_engine/rules/install_prepacked_rules.ts index 78ad5dd54f70b0..555063854dc60e 100644 --- a/x-pack/legacy/plugins/siem/server/lib/detection_engine/rules/install_prepacked_rules.ts +++ b/x-pack/legacy/plugins/siem/server/lib/detection_engine/rules/install_prepacked_rules.ts @@ -6,16 +6,17 @@ import { ActionsClient } from '../../../../../../../plugins/actions/server'; import { AlertsClient } from '../../../../../alerting'; +import { Alert } from '../../../../../alerting/server/types'; import { createRules } from './create_rules'; import { PrepackagedRules } from '../types'; -export const installPrepackagedRules = async ( +export const installPrepackagedRules = ( alertsClient: AlertsClient, actionsClient: ActionsClient, rules: PrepackagedRules[], outputIndex: string -): Promise => { - await rules.forEach(async rule => { +): Array> => + rules.reduce>>((acc, rule) => { const { description, enabled, @@ -43,37 +44,39 @@ export const installPrepackagedRules = async ( references, version, } = rule; - createRules({ - alertsClient, - actionsClient, - description, - enabled, - falsePositives, - from, - immutable, - query, - language, - outputIndex, - savedId, - timelineId, - timelineTitle, - meta, - filters, - ruleId, - index, - interval, - maxSignals, - riskScore, - name, - severity, - tags, - to, - type, - threats, - references, - version, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - }); - }); -}; + return [ + ...acc, + createRules({ + alertsClient, + actionsClient, + description, + enabled, + falsePositives, + from, + immutable, + query, + language, + outputIndex, + savedId, + timelineId, + timelineTitle, + meta, + filters, + ruleId, + index, + interval, + maxSignals, + riskScore, + name, + severity, + tags, + to, + type, + threats, + references, + version, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }), + ]; + }, []); diff --git a/x-pack/legacy/plugins/siem/server/plugin.ts b/x-pack/legacy/plugins/siem/server/plugin.ts index 9d1983cf1d4daa..96eef2f44e5a06 100644 --- a/x-pack/legacy/plugins/siem/server/plugin.ts +++ b/x-pack/legacy/plugins/siem/server/plugin.ts @@ -14,6 +14,7 @@ import { noteSavedObjectType, pinnedEventSavedObjectType, timelineSavedObjectType, + ruleStatusSavedObjectType, } from './saved_objects'; export type SiemPluginSecurity = Pick; @@ -57,6 +58,7 @@ export class Plugin { noteSavedObjectType, pinnedEventSavedObjectType, timelineSavedObjectType, + ruleStatusSavedObjectType, ], read: ['config'], }, @@ -80,6 +82,7 @@ export class Plugin { noteSavedObjectType, pinnedEventSavedObjectType, timelineSavedObjectType, + ruleStatusSavedObjectType, ], }, ui: [ diff --git a/x-pack/legacy/plugins/siem/server/saved_objects.ts b/x-pack/legacy/plugins/siem/server/saved_objects.ts index 1d65e351fc86a9..8b9a1891c8a500 100644 --- a/x-pack/legacy/plugins/siem/server/saved_objects.ts +++ b/x-pack/legacy/plugins/siem/server/saved_objects.ts @@ -12,9 +12,17 @@ import { timelineSavedObjectType, timelineSavedObjectMappings, } from './lib/timeline/saved_object_mappings'; -import { ruleStatusSavedObjectMappings } from './lib/detection_engine/rules/saved_object_mappings'; +import { + ruleStatusSavedObjectMappings, + ruleStatusSavedObjectType, +} from './lib/detection_engine/rules/saved_object_mappings'; -export { noteSavedObjectType, pinnedEventSavedObjectType, timelineSavedObjectType }; +export { + noteSavedObjectType, + pinnedEventSavedObjectType, + ruleStatusSavedObjectType, + timelineSavedObjectType, +}; export const savedObjectMappings = { ...timelineSavedObjectMappings, ...noteSavedObjectMappings, diff --git a/x-pack/legacy/plugins/siem/server/types.ts b/x-pack/legacy/plugins/siem/server/types.ts index bbcfbe7b9c0ec8..3fa2268afe92c3 100644 --- a/x-pack/legacy/plugins/siem/server/types.ts +++ b/x-pack/legacy/plugins/siem/server/types.ts @@ -9,6 +9,8 @@ import { Legacy } from 'kibana'; export interface ServerFacade { config: Legacy.Server['config']; plugins: { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + actions: any; // We have to do this at the moment because the types are not compatible alerting?: Legacy.Server['plugins']['alerting']; elasticsearch: Legacy.Server['plugins']['elasticsearch']; spaces: Legacy.Server['plugins']['spaces']; diff --git a/x-pack/legacy/plugins/uptime/server/lib/adapters/framework/adapter_types.ts b/x-pack/legacy/plugins/uptime/server/lib/adapters/framework/adapter_types.ts index b490bf17e292c3..2f72081a709884 100644 --- a/x-pack/legacy/plugins/uptime/server/lib/adapters/framework/adapter_types.ts +++ b/x-pack/legacy/plugins/uptime/server/lib/adapters/framework/adapter_types.ts @@ -48,7 +48,7 @@ export interface UptimeCoreSetup { } export interface UptimeCorePlugins { - savedObjects: SavedObjectsLegacyService; + savedObjects: SavedObjectsLegacyService; usageCollection: UsageCollectionSetup; xpack: any; } diff --git a/x-pack/legacy/plugins/watcher/index.ts b/x-pack/legacy/plugins/watcher/index.ts new file mode 100644 index 00000000000000..fdf9ba1bad6e44 --- /dev/null +++ b/x-pack/legacy/plugins/watcher/index.ts @@ -0,0 +1,19 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { resolve } from 'path'; + +const pluginDefinition = { + id: 'watcher', + configPrefix: 'xpack.watcher', + publicDir: resolve(__dirname, 'public'), + require: ['kibana'], + uiExports: { + styleSheetPaths: resolve(__dirname, 'public/index.scss'), + }, + init(server: any) {}, +}; + +export const watcher = (kibana: any) => new kibana.Plugin(pluginDefinition); diff --git a/x-pack/legacy/plugins/watcher/plugin_definition.ts b/x-pack/legacy/plugins/watcher/plugin_definition.ts deleted file mode 100644 index 2da05253fdb325..00000000000000 --- a/x-pack/legacy/plugins/watcher/plugin_definition.ts +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { resolve } from 'path'; -import { plugin } from './server/np_ready'; -import { PLUGIN } from './common/constants'; - -export const pluginDefinition = { - id: PLUGIN.ID, - configPrefix: 'xpack.watcher', - publicDir: resolve(__dirname, 'public'), - require: ['kibana', 'elasticsearch', 'xpack_main'], - uiExports: { - styleSheetPaths: resolve(__dirname, 'public/np_ready/application/index.scss'), - managementSections: ['plugins/watcher/legacy'], - home: ['plugins/watcher/register_feature'], - }, - init(server: any) { - plugin({} as any).setup(server.newPlatform.setup.core, { - __LEGACY: { - route: server.route.bind(server), - plugins: { - watcher: server.plugins[PLUGIN.ID], - xpack_main: server.plugins.xpack_main, - }, - }, - }); - }, -}; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/index.scss b/x-pack/legacy/plugins/watcher/public/index.scss similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/index.scss rename to x-pack/legacy/plugins/watcher/public/index.scss diff --git a/x-pack/legacy/plugins/watcher/public/legacy.ts b/x-pack/legacy/plugins/watcher/public/legacy.ts deleted file mode 100644 index 21fcd718ea1b73..00000000000000 --- a/x-pack/legacy/plugins/watcher/public/legacy.ts +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { CoreSetup, App, AppUnmount } from 'src/core/public'; -import { i18n } from '@kbn/i18n'; - -/* Legacy UI imports */ -import { npSetup, npStart } from 'ui/new_platform'; -import routes from 'ui/routes'; -import { management, MANAGEMENT_BREADCRUMB } from 'ui/management'; -import { TimeBuckets } from 'ui/time_buckets'; -// @ts-ignore -import { xpackInfo } from 'plugins/xpack_main/services/xpack_info'; -/* Legacy UI imports */ - -import { plugin } from './np_ready'; -import { PLUGIN } from '../common/constants'; -import { LICENSE_STATUS_INVALID, LICENSE_STATUS_UNAVAILABLE } from '../../../common/constants'; -import { manageAngularLifecycle } from './manage_angular_lifecycle'; - -const template = ` -
-
`; - -let elem: HTMLElement; -let mountApp: () => AppUnmount | Promise; -let unmountApp: AppUnmount | Promise; -routes.when('/management/elasticsearch/watcher/:param1?/:param2?/:param3?/:param4?', { - template, - controller: class WatcherController { - constructor($injector: any, $scope: any) { - const $route = $injector.get('$route'); - const licenseStatus = xpackInfo.get(`features.${PLUGIN.ID}`); - const shimCore: CoreSetup = { - ...npSetup.core, - application: { - ...npSetup.core.application, - register(app: App): void { - mountApp = () => - app.mount(npStart as any, { - element: elem, - appBasePath: '/management/elasticsearch/watcher/', - onAppLeave: () => undefined, - }); - }, - }, - }; - - // clean up previously rendered React app if one exists - // this happens because of React Router redirects - if (elem) { - ((unmountApp as unknown) as AppUnmount)(); - } - - $scope.$$postDigest(() => { - elem = document.getElementById('watchReactRoot')!; - const instance = plugin(); - instance.setup(shimCore, { - ...(npSetup.plugins as typeof npSetup.plugins & { eui_utils: any }), - __LEGACY: { - MANAGEMENT_BREADCRUMB, - TimeBuckets, - licenseStatus, - }, - }); - - instance.start(npStart.core, npStart.plugins); - - (mountApp() as Promise).then(fn => (unmountApp = fn)); - - manageAngularLifecycle($scope, $route, elem); - }); - } - } as any, - // @ts-ignore - controllerAs: 'watchRoute', -}); - -routes.defaults(/\/management/, { - resolve: { - watcherManagementSection: () => { - const watchesSection = management.getSection('elasticsearch/watcher'); - const licenseStatus = xpackInfo.get(`features.${PLUGIN.ID}`); - const { status } = licenseStatus; - - if (status === LICENSE_STATUS_INVALID || status === LICENSE_STATUS_UNAVAILABLE) { - return watchesSection.hide(); - } - - watchesSection.show(); - }, - }, -}); - -management.getSection('elasticsearch').register('watcher', { - display: i18n.translate('xpack.watcher.sections.watchList.managementSection.watcherDisplayName', { - defaultMessage: 'Watcher', - }), - order: 6, - url: '#/management/elasticsearch/watcher/', -} as any); - -management.getSection('elasticsearch/watcher').register('watches', { - display: i18n.translate('xpack.watcher.sections.watchList.managementSection.watchesDisplayName', { - defaultMessage: 'Watches', - }), - order: 1, -} as any); - -management.getSection('elasticsearch/watcher').register('watch', { - visible: false, -} as any); - -management.getSection('elasticsearch/watcher/watch').register('status', { - display: i18n.translate('xpack.watcher.sections.watchList.managementSection.statusDisplayName', { - defaultMessage: 'Status', - }), - order: 1, - visible: false, -} as any); - -management.getSection('elasticsearch/watcher/watch').register('edit', { - display: i18n.translate('xpack.watcher.sections.watchList.managementSection.editDisplayName', { - defaultMessage: 'Edit', - }), - order: 2, - visible: false, -} as any); - -management.getSection('elasticsearch/watcher/watch').register('new', { - display: i18n.translate( - 'xpack.watcher.sections.watchList.managementSection.newWatchDisplayName', - { - defaultMessage: 'New Watch', - } - ), - order: 1, - visible: false, -} as any); - -management.getSection('elasticsearch/watcher/watch').register('history-item', { - order: 1, - visible: false, -} as any); diff --git a/x-pack/legacy/plugins/watcher/public/manage_angular_lifecycle.ts b/x-pack/legacy/plugins/watcher/public/manage_angular_lifecycle.ts deleted file mode 100644 index efd40eaf83daad..00000000000000 --- a/x-pack/legacy/plugins/watcher/public/manage_angular_lifecycle.ts +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { unmountComponentAtNode } from 'react-dom'; - -export const manageAngularLifecycle = ($scope: any, $route: any, elem: HTMLElement) => { - const lastRoute = $route.current; - - const deregister = $scope.$on('$locationChangeSuccess', () => { - const currentRoute = $route.current; - if (lastRoute.$$route.template === currentRoute.$$route.template) { - $route.current = lastRoute; - } - }); - - $scope.$on('$destroy', () => { - if (deregister) { - deregister(); - } - - if (elem) { - unmountComponentAtNode(elem); - } - }); -}; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/index.d.ts b/x-pack/legacy/plugins/watcher/public/np_ready/application/models/index.d.ts deleted file mode 100644 index a8ddb6ca2b76db..00000000000000 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/index.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -declare module 'plugins/watcher/np_ready/application/models/visualize_options' { - export const VisualizeOptions: any; -} - -declare module 'plugins/watcher/np_ready/application/models/watch' { - export const Watch: any; -} - -declare module 'plugins/watcher/np_ready/application/models/watch/threshold_watch' { - export const ThresholdWatch: any; -} - -declare module 'plugins/watcher/np_ready/application/models/watch/json_watch' { - export const JsonWatch: any; -} - -declare module 'plugins/watcher/np_ready/application/models/execute_details/execute_details' { - export const ExecuteDetails: any; -} - -declare module 'plugins/watcher/np_ready/application/models/watch_history_item' { - export const WatchHistoryItem: any; -} - -declare module 'plugins/watcher/np_ready/application/models/watch_status' { - export const WatchStatus: any; -} - -declare module 'plugins/watcher/np_ready/application/models/settings' { - export const Settings: any; -} -declare module 'plugins/watcher/np_ready/application/models/action' { - export const Action: any; -} diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/plugin.ts b/x-pack/legacy/plugins/watcher/public/np_ready/plugin.ts deleted file mode 100644 index 161de9b5fc0606..00000000000000 --- a/x-pack/legacy/plugins/watcher/public/np_ready/plugin.ts +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { Plugin, CoreSetup, CoreStart } from 'src/core/public'; - -import { LegacyDependencies } from './types'; - -interface LegacyPlugins { - __LEGACY: LegacyDependencies; -} - -export class WatcherUIPlugin implements Plugin { - /* TODO: Remove this in future. We need this at mount (setup) but it's only available on start plugins. */ - euiUtils: any = null; - - setup({ application, notifications, http, uiSettings }: CoreSetup, { __LEGACY }: LegacyPlugins) { - application.register({ - id: 'watcher', - title: 'Watcher', - mount: async ( - { - core: { - docLinks, - chrome, - // Waiting for types to be updated. - // @ts-ignore - savedObjects, - i18n: { Context: I18nContext }, - }, - }, - { element } - ) => { - const euiUtils = this.euiUtils!; - const { boot } = await import('./application/boot'); - return boot({ - element, - toasts: notifications.toasts, - http, - uiSettings, - docLinks, - chrome, - euiUtils, - savedObjects: savedObjects.client, - I18nContext, - legacy: { - ...__LEGACY, - }, - }); - }, - }); - } - - start(core: CoreStart, { eui_utils }: any) { - // eslint-disable-next-line @typescript-eslint/camelcase - this.euiUtils = eui_utils; - } - - stop() {} -} diff --git a/x-pack/legacy/plugins/watcher/public/register_feature.ts b/x-pack/legacy/plugins/watcher/public/register_feature.ts deleted file mode 100644 index 0de41e09f788e1..00000000000000 --- a/x-pack/legacy/plugins/watcher/public/register_feature.ts +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { i18n } from '@kbn/i18n'; -import { npSetup } from 'ui/new_platform'; -import { FeatureCatalogueCategory } from 'ui/registry/feature_catalogue'; - -npSetup.plugins.home.featureCatalogue.register({ - id: 'watcher', - title: 'Watcher', // This is a product name so we don't translate it. - category: FeatureCatalogueCategory.ADMIN, - description: i18n.translate('xpack.watcher.watcherDescription', { - defaultMessage: 'Detect changes in your data by creating, managing, and monitoring alerts.', - }), - icon: 'watchesApp', - path: '/app/kibana#/management/elasticsearch/watcher/watches', - showOnHomePage: true, -}); diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/__tests__/license_pre_routing_factory.js b/x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/__tests__/license_pre_routing_factory.js deleted file mode 100644 index 4a6ad50d6ebc57..00000000000000 --- a/x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/__tests__/license_pre_routing_factory.js +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import expect from '@kbn/expect'; -import { kibanaResponseFactory } from '../../../../../../../../../src/core/server'; -import { licensePreRoutingFactory } from '../license_pre_routing_factory'; -import { - LICENSE_STATUS_VALID, - LICENSE_STATUS_EXPIRED, -} from '../../../../../../../common/constants/license_status'; - -describe('license_pre_routing_factory', () => { - describe('#reportingFeaturePreRoutingFactory', () => { - let mockServer; - let mockLicenseCheckResults; - - beforeEach(() => { - mockServer = { - plugins: { - xpack_main: { - info: { - feature: () => ({ - getLicenseCheckResults: () => mockLicenseCheckResults, - }), - }, - }, - }, - }; - }); - - describe('status is not valid', () => { - beforeEach(() => { - mockLicenseCheckResults = { - status: LICENSE_STATUS_EXPIRED, - }; - }); - - it('replies with 403', () => { - const licensePreRouting = licensePreRoutingFactory(mockServer, () => {}); - const stubRequest = {}; - const response = licensePreRouting({}, stubRequest, kibanaResponseFactory); - expect(response.status).to.be(403); - }); - }); - - describe('status is valid', () => { - beforeEach(() => { - mockLicenseCheckResults = { - status: LICENSE_STATUS_VALID, - }; - }); - - it('replies with nothing', () => { - const licensePreRouting = licensePreRoutingFactory(mockServer, () => null); - const stubRequest = {}; - const response = licensePreRouting({}, stubRequest, kibanaResponseFactory); - expect(response).to.be(null); - }); - }); - }); -}); diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/license_pre_routing_factory.ts b/x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/license_pre_routing_factory.ts deleted file mode 100644 index d2f49672461047..00000000000000 --- a/x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/license_pre_routing_factory.ts +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { - KibanaRequest, - KibanaResponseFactory, - RequestHandler, - RequestHandlerContext, -} from 'src/core/server'; -import { PLUGIN } from '../../../../common/constants'; -import { LICENSE_STATUS_VALID } from '../../../../../../common/constants/license_status'; -import { ServerShim } from '../../types'; - -export const licensePreRoutingFactory = ( - server: ServerShim, - handler: RequestHandler -): RequestHandler => { - const xpackMainPlugin = server.plugins.xpack_main; - - // License checking and enable/disable logic - return function licensePreRouting( - ctx: RequestHandlerContext, - request: KibanaRequest, - response: KibanaResponseFactory - ) { - const licenseCheckResults = xpackMainPlugin.info.feature(PLUGIN.ID).getLicenseCheckResults(); - const { status } = licenseCheckResults; - - if (status !== LICENSE_STATUS_VALID) { - return response.customError({ - body: { - message: licenseCheckResults.messsage, - }, - statusCode: 403, - }); - } - - return handler(ctx, request, response); - }; -}; diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/plugin.ts b/x-pack/legacy/plugins/watcher/server/np_ready/plugin.ts deleted file mode 100644 index a311c31082183c..00000000000000 --- a/x-pack/legacy/plugins/watcher/server/np_ready/plugin.ts +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { Plugin, CoreSetup } from 'src/core/server'; -import { i18n } from '@kbn/i18n'; -import { PLUGIN } from '../../common/constants'; -import { ServerShim, RouteDependencies } from './types'; - -import { registerLicenseChecker } from '../../../../server/lib/register_license_checker'; -import { registerSettingsRoutes } from './routes/api/settings'; -import { registerIndicesRoutes } from './routes/api/indices'; -import { registerLicenseRoutes } from './routes/api/license'; -import { registerWatchesRoutes } from './routes/api/watches'; -import { registerWatchRoutes } from './routes/api/watch'; -import { registerListFieldsRoute } from './routes/api/register_list_fields_route'; -import { registerLoadHistoryRoute } from './routes/api/register_load_history_route'; - -export class WatcherServerPlugin implements Plugin { - async setup( - { http, elasticsearch: elasticsearchService }: CoreSetup, - { __LEGACY: serverShim }: { __LEGACY: ServerShim } - ) { - const elasticsearch = await elasticsearchService.adminClient; - const router = http.createRouter(); - const routeDependencies: RouteDependencies = { - elasticsearch, - elasticsearchService, - router, - }; - // Register license checker - registerLicenseChecker( - serverShim as any, - PLUGIN.ID, - PLUGIN.getI18nName(i18n), - PLUGIN.MINIMUM_LICENSE_REQUIRED - ); - - registerListFieldsRoute(routeDependencies, serverShim); - registerLoadHistoryRoute(routeDependencies, serverShim); - registerIndicesRoutes(routeDependencies, serverShim); - registerLicenseRoutes(routeDependencies, serverShim); - registerSettingsRoutes(routeDependencies, serverShim); - registerWatchesRoutes(routeDependencies, serverShim); - registerWatchRoutes(routeDependencies, serverShim); - } - start() {} - stop() {} -} diff --git a/x-pack/plugins/encrypted_saved_objects/server/plugin.ts b/x-pack/plugins/encrypted_saved_objects/server/plugin.ts index 39da4c7d2d3531..ecd917ff90d003 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/plugin.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/plugin.ts @@ -71,7 +71,11 @@ export class Plugin { ) ); - this.savedObjectsSetup = setupSavedObjects({ service, savedObjects: core.savedObjects }); + this.savedObjectsSetup = setupSavedObjects({ + service, + savedObjects: core.savedObjects, + getStartServices: core.getStartServices, + }); return { registerType: (typeRegistration: EncryptedSavedObjectTypeRegistration) => diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts index c967c92deb6ffb..80bd2ab7b5171b 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts @@ -16,6 +16,7 @@ import { EncryptedSavedObjectsClientWrapper } from './encrypted_saved_objects_cl interface SetupSavedObjectsParams { service: PublicMethodsOf; savedObjects: CoreSetup['savedObjects']; + getStartServices: CoreSetup['getStartServices']; } export interface SavedObjectsSetup { @@ -29,6 +30,7 @@ export interface SavedObjectsSetup { export function setupSavedObjects({ service, savedObjects, + getStartServices, }: SetupSavedObjectsParams): SavedObjectsSetup { // Register custom saved object client that will encrypt, decrypt and strip saved object // attributes where appropriate for any saved object repository request. We choose max possible @@ -41,13 +43,16 @@ export function setupSavedObjects({ ({ client: baseClient }) => new EncryptedSavedObjectsClientWrapper({ baseClient, service }) ); - const internalRepository = savedObjects.createInternalRepository(); + const internalRepositoryPromise = getStartServices().then(([core]) => + core.savedObjects.createInternalRepository() + ); return { getDecryptedAsInternalUser: async ( type: string, id: string, options?: SavedObjectsBaseOptions ): Promise> => { + const internalRepository = await internalRepositoryPromise; const savedObject = await internalRepository.get(type, id, options); return { ...savedObject, diff --git a/x-pack/plugins/security/server/saved_objects/index.ts b/x-pack/plugins/security/server/saved_objects/index.ts index 556dc4fda85cf5..59547295628479 100644 --- a/x-pack/plugins/security/server/saved_objects/index.ts +++ b/x-pack/plugins/security/server/saved_objects/index.ts @@ -24,12 +24,12 @@ export function setupSavedObjects({ auditLogger, authz, savedObjects }: SetupSav const getKibanaRequest = (request: KibanaRequest | LegacyRequest) => request instanceof KibanaRequest ? request : KibanaRequest.from(request); - savedObjects.setClientFactory(({ request }) => { + savedObjects.setClientFactoryProvider(repositoryFactory => ({ request }) => { const kibanaRequest = getKibanaRequest(request); return new SavedObjectsClient( authz.mode.useRbacForRequest(kibanaRequest) - ? savedObjects.createInternalRepository() - : savedObjects.createScopedRepository(kibanaRequest) + ? repositoryFactory.createInternalRepository() + : repositoryFactory.createScopedRepository(kibanaRequest) ); }); diff --git a/x-pack/plugins/task_manager/server/plugin.ts b/x-pack/plugins/task_manager/server/plugin.ts index 9bdd1ce6d87485..8b09f8f2b445a8 100644 --- a/x-pack/plugins/task_manager/server/plugin.ts +++ b/x-pack/plugins/task_manager/server/plugin.ts @@ -38,12 +38,13 @@ export class TaskManagerPlugin public setup(core: CoreSetup, plugins: any): TaskManagerSetupContract { const logger = this.initContext.logger.get('taskManager'); const config$ = this.initContext.config.create(); - const savedObjectsRepository = core.savedObjects.createInternalRepository(['task']); const elasticsearch = core.elasticsearch.adminClient; return { config$, registerLegacyAPI: once((__LEGACY: PluginLegacyDependencies) => { config$.subscribe(async config => { + const [{ savedObjects }] = await core.getStartServices(); + const savedObjectsRepository = savedObjects.createInternalRepository(['task']); this.legacyTaskManager$.next( createTaskManager(core, { logger, diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 4a5d2c5e9de2e5..1c0c44540781d9 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -13151,11 +13151,7 @@ "xpack.watcher.sections.watchList.errorTitle": "ウォッチの読み込み中にエラーが発生しました", "xpack.watcher.sections.watchList.header": "しきい値アラートを作成", "xpack.watcher.sections.watchList.loadingWatchesDescription": "ウォッチの読み込み中...", - "xpack.watcher.sections.watchList.managementSection.editDisplayName": "編集", - "xpack.watcher.sections.watchList.managementSection.newWatchDisplayName": "新規ウォッチ", - "xpack.watcher.sections.watchList.managementSection.statusDisplayName": "ステータス", "xpack.watcher.sections.watchList.managementSection.watcherDisplayName": "Watcher", - "xpack.watcher.sections.watchList.managementSection.watchesDisplayName": "ウォッチ", "xpack.watcher.sections.watchList.subhead": "特定のパラメーターに到達した際にメール、Slack メッセージ、ログイベントを送信します。", "xpack.watcher.sections.watchList.toggleActivatationErrorNotification.activateDescriptionText": "ウォッチを有効化できませんでした", "xpack.watcher.sections.watchList.toggleActivatationErrorNotification.deactivateDescriptionText": "ウォッチを無効化できませんでした", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 6291b5f1bb6632..9500b1ce887a6d 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -13150,11 +13150,7 @@ "xpack.watcher.sections.watchList.errorTitle": "加载监视时出错", "xpack.watcher.sections.watchList.header": "创建阈值告警", "xpack.watcher.sections.watchList.loadingWatchesDescription": "正在加载监视……", - "xpack.watcher.sections.watchList.managementSection.editDisplayName": "编辑", - "xpack.watcher.sections.watchList.managementSection.newWatchDisplayName": "新建监视", - "xpack.watcher.sections.watchList.managementSection.statusDisplayName": "状态", "xpack.watcher.sections.watchList.managementSection.watcherDisplayName": "Watcher", - "xpack.watcher.sections.watchList.managementSection.watchesDisplayName": "监视", "xpack.watcher.sections.watchList.subhead": "特定参数命中时,发出电子邮件、Slack 消息和日志事件", "xpack.watcher.sections.watchList.toggleActivatationErrorNotification.activateDescriptionText": "无法激活监视", "xpack.watcher.sections.watchList.toggleActivatationErrorNotification.deactivateDescriptionText": "无法停用监视", diff --git a/x-pack/legacy/plugins/watcher/README.md b/x-pack/plugins/watcher/README.md similarity index 100% rename from x-pack/legacy/plugins/watcher/README.md rename to x-pack/plugins/watcher/README.md diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx b/x-pack/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx similarity index 69% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx rename to x-pack/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx index de285ee15b59d9..3d8ae2894b3206 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx @@ -12,26 +12,28 @@ import { uiSettingsServiceMock, notificationServiceMock, httpServiceMock, -} from '../../../../../../../src/core/public/mocks'; -import { AppContextProvider } from '../../../public/np_ready/application/app_context'; +} from '../../../../../../src/core/public/mocks'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { AppContextProvider } from '../../../public/application/app_context'; +class MockTimeBuckets { + setBounds(_domain: any) { + return {}; + } + getInterval() { + return { + expression: {}, + }; + } +} export const mockContextValue = { + getLicenseStatus: () => ({ + valid: true, + }), docLinks: docLinksServiceMock.createStartContract(), chrome: chromeServiceMock.createStartContract(), - legacy: { - TimeBuckets: class MockTimeBuckets { - setBounds(_domain: any) { - return {}; - } - getInterval() { - return { - expression: {}, - }; - } - }, - MANAGEMENT_BREADCRUMB: { text: 'test' }, - licenseStatus: {}, - }, + MANAGEMENT_BREADCRUMB: { text: 'test' }, + createTimeBuckets: () => new MockTimeBuckets(), uiSettings: uiSettingsServiceMock.createSetupContract(), toasts: notificationServiceMock.createSetupContract().toasts, euiUtils: { diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/body_response.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/body_response.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/body_response.ts rename to x-pack/plugins/watcher/__jest__/client_integration/helpers/body_response.ts diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/constants.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/constants.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/constants.ts rename to x-pack/plugins/watcher/__jest__/client_integration/helpers/constants.ts diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/http_requests.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/http_requests.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/http_requests.ts rename to x-pack/plugins/watcher/__jest__/client_integration/helpers/http_requests.ts diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/index.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/index.ts similarity index 96% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/index.ts rename to x-pack/plugins/watcher/__jest__/client_integration/helpers/index.ts index 814028fe599ff6..7c5ec0917494ad 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/index.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/index.ts @@ -10,7 +10,7 @@ import { setup as watchCreateJsonSetup } from './watch_create_json.helpers'; import { setup as watchCreateThresholdSetup } from './watch_create_threshold.helpers'; import { setup as watchEditSetup } from './watch_edit.helpers'; -export { nextTick, getRandomString, findTestSubject, TestBed } from '../../../../../../test_utils'; +export { nextTick, getRandomString, findTestSubject, TestBed } from '../../../../../test_utils'; export { wrapBodyResponse, unwrapBodyResponse } from './body_response'; export { setupEnvironment } from './setup_environment'; diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/setup_environment.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/setup_environment.ts similarity index 92% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/setup_environment.ts rename to x-pack/plugins/watcher/__jest__/client_integration/helpers/setup_environment.ts index 7e748073c1c6b2..c084f87ea8c3ad 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/setup_environment.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/setup_environment.ts @@ -7,7 +7,8 @@ import axios from 'axios'; import axiosXhrAdapter from 'axios/lib/adapters/xhr'; import { init as initHttpRequests } from './http_requests'; -import { setHttpClient, setSavedObjectsClient } from '../../../public/np_ready/application/lib/api'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { setHttpClient, setSavedObjectsClient } from '../../../public/application/lib/api'; const mockHttpClient = axios.create({ adapter: axiosXhrAdapter }); mockHttpClient.interceptors.response.use( diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_create_json.helpers.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_json.helpers.ts similarity index 87% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_create_json.helpers.ts rename to x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_json.helpers.ts index dafcf3a7070d22..77d5a76257fd2d 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_create_json.helpers.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_json.helpers.ts @@ -4,10 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ import { withAppContext } from './app_context.mock'; -import { registerTestBed, TestBed, TestBedConfig } from '../../../../../../test_utils'; -import { WatchEdit } from '../../../public/np_ready/application/sections/watch_edit/components/watch_edit'; +import { registerTestBed, TestBed, TestBedConfig } from '../../../../../test_utils'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { WatchEdit } from '../../../public/application/sections/watch_edit/components/watch_edit'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { registerRouter } from '../../../public/application/lib/navigation'; import { ROUTES, WATCH_TYPES } from '../../../common/constants'; -import { registerRouter } from '../../../public/np_ready/application/lib/navigation'; const testBedConfig: TestBedConfig = { memoryRouter: { diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_create_threshold.helpers.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_threshold.helpers.ts similarity index 90% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_create_threshold.helpers.ts rename to x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_threshold.helpers.ts index 65648ae5f5a959..8262e6702be700 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_create_threshold.helpers.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_threshold.helpers.ts @@ -3,10 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { registerTestBed, TestBed, TestBedConfig } from '../../../../../../test_utils'; -import { WatchEdit } from '../../../public/np_ready/application/sections/watch_edit/components/watch_edit'; +import { registerTestBed, TestBed, TestBedConfig } from '../../../../../test_utils'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { WatchEdit } from '../../../public/application/sections/watch_edit/components/watch_edit'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { registerRouter } from '../../../public/application/lib/navigation'; import { ROUTES, WATCH_TYPES } from '../../../common/constants'; -import { registerRouter } from '../../../public/np_ready/application/lib/navigation'; import { withAppContext } from './app_context.mock'; const testBedConfig: TestBedConfig = { diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_edit.helpers.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_edit.helpers.ts similarity index 81% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_edit.helpers.ts rename to x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_edit.helpers.ts index 187f4dcaa0a76f..949d43e7742123 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_edit.helpers.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_edit.helpers.ts @@ -3,10 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { registerTestBed, TestBed, TestBedConfig } from '../../../../../../test_utils'; -import { WatchEdit } from '../../../public/np_ready/application/sections/watch_edit/components/watch_edit'; +import { registerTestBed, TestBed, TestBedConfig } from '../../../../../test_utils'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { WatchEdit } from '../../../public/application/sections/watch_edit/components/watch_edit'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { registerRouter } from '../../../public/application/lib/navigation'; import { ROUTES } from '../../../common/constants'; -import { registerRouter } from '../../../public/np_ready/application/lib/navigation'; import { WATCH_ID } from './constants'; import { withAppContext } from './app_context.mock'; diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_list.helpers.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_list.helpers.ts similarity index 93% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_list.helpers.ts rename to x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_list.helpers.ts index e33327ea42ffe8..b5cf3df9509fc7 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_list.helpers.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_list.helpers.ts @@ -12,8 +12,9 @@ import { TestBed, TestBedConfig, nextTick, -} from '../../../../../../test_utils'; -import { WatchList } from '../../../public/np_ready/application/sections/watch_list/components/watch_list'; +} from '../../../../../test_utils'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { WatchList } from '../../../public/application/sections/watch_list/components/watch_list'; import { ROUTES } from '../../../common/constants'; import { withAppContext } from './app_context.mock'; diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_status.helpers.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_status.helpers.ts similarity index 95% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_status.helpers.ts rename to x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_status.helpers.ts index e7bffe8924e319..e67c98ff9e9a0c 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/helpers/watch_status.helpers.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_status.helpers.ts @@ -12,8 +12,9 @@ import { TestBed, TestBedConfig, nextTick, -} from '../../../../../../test_utils'; -import { WatchStatus } from '../../../public/np_ready/application/sections/watch_status/components/watch_status'; +} from '../../../../../test_utils'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { WatchStatus } from '../../../public/application/sections/watch_status/components/watch_status'; import { ROUTES } from '../../../common/constants'; import { WATCH_ID } from './constants'; import { withAppContext } from './app_context.mock'; diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_create_json.test.ts b/x-pack/plugins/watcher/__jest__/client_integration/watch_create_json.test.ts similarity index 98% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_create_json.test.ts rename to x-pack/plugins/watcher/__jest__/client_integration/watch_create_json.test.ts index 4c893978ee5cbc..26be3421b534ed 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_create_json.test.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/watch_create_json.test.ts @@ -7,7 +7,7 @@ import { act } from 'react-dom/test-utils'; import { setupEnvironment, pageHelpers, nextTick, wrapBodyResponse } from './helpers'; import { WatchCreateJsonTestBed } from './helpers/watch_create_json.helpers'; import { WATCH } from './helpers/constants'; -import defaultWatchJson from '../../public/np_ready/application/models/watch/default_watch.json'; +import defaultWatchJson from '../../public/application/models/watch/default_watch.json'; import { getExecuteDetails } from '../../test/fixtures'; const { setup } = pageHelpers.watchCreateJson; diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_create_threshold.test.tsx b/x-pack/plugins/watcher/__jest__/client_integration/watch_create_threshold.test.tsx similarity index 99% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_create_threshold.test.tsx rename to x-pack/plugins/watcher/__jest__/client_integration/watch_create_threshold.test.tsx index 2800b0107da240..431eb1cae0608a 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_create_threshold.test.tsx +++ b/x-pack/plugins/watcher/__jest__/client_integration/watch_create_threshold.test.tsx @@ -48,8 +48,8 @@ const WATCH_VISUALIZE_DATA = { const mockHttpClient = axios.create({ adapter: axiosXhrAdapter }); -jest.mock('../../public/np_ready/application/lib/api', () => ({ - ...jest.requireActual('../../public/np_ready/application/lib/api'), +jest.mock('../../public/application/lib/api', () => ({ + ...jest.requireActual('../../public/application/lib/api'), loadIndexPatterns: async () => { const INDEX_PATTERNS = [ { attributes: { title: 'index1' } }, diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_edit.test.ts b/x-pack/plugins/watcher/__jest__/client_integration/watch_edit.test.ts similarity index 95% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_edit.test.ts rename to x-pack/plugins/watcher/__jest__/client_integration/watch_edit.test.ts index 131400a8702c46..545bfbdf7cbc28 100644 --- a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_edit.test.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/watch_edit.test.ts @@ -9,14 +9,14 @@ import axios from 'axios'; import { setupEnvironment, pageHelpers, nextTick, wrapBodyResponse } from './helpers'; import { WatchEditTestBed } from './helpers/watch_edit.helpers'; import { WATCH } from './helpers/constants'; -import defaultWatchJson from '../../public/np_ready/application/models/watch/default_watch.json'; +import defaultWatchJson from '../../public/application/models/watch/default_watch.json'; import { getWatch } from '../../test/fixtures'; -import { getRandomString } from '../../../../../test_utils'; +import { getRandomString } from '../../../../test_utils'; const mockHttpClient = axios.create({ adapter: axiosXhrAdapter }); -jest.mock('../../public/np_ready/application/lib/api', () => ({ - ...jest.requireActual('../../public/np_ready/application/lib/api'), +jest.mock('../../public/application/lib/api', () => ({ + ...jest.requireActual('../../public/application/lib/api'), loadIndexPatterns: async () => { const INDEX_PATTERNS = [ { attributes: { title: 'index1' } }, diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_list.test.ts b/x-pack/plugins/watcher/__jest__/client_integration/watch_list.test.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_list.test.ts rename to x-pack/plugins/watcher/__jest__/client_integration/watch_list.test.ts diff --git a/x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_status.test.ts b/x-pack/plugins/watcher/__jest__/client_integration/watch_status.test.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/__jest__/client_integration/watch_status.test.ts rename to x-pack/plugins/watcher/__jest__/client_integration/watch_status.test.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/action_modes.ts b/x-pack/plugins/watcher/common/constants/action_modes.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/action_modes.ts rename to x-pack/plugins/watcher/common/constants/action_modes.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/action_states.ts b/x-pack/plugins/watcher/common/constants/action_states.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/action_states.ts rename to x-pack/plugins/watcher/common/constants/action_states.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/action_types.ts b/x-pack/plugins/watcher/common/constants/action_types.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/action_types.ts rename to x-pack/plugins/watcher/common/constants/action_types.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/agg_types.ts b/x-pack/plugins/watcher/common/constants/agg_types.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/agg_types.ts rename to x-pack/plugins/watcher/common/constants/agg_types.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/comparators.ts b/x-pack/plugins/watcher/common/constants/comparators.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/comparators.ts rename to x-pack/plugins/watcher/common/constants/comparators.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/error_codes.ts b/x-pack/plugins/watcher/common/constants/error_codes.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/error_codes.ts rename to x-pack/plugins/watcher/common/constants/error_codes.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/es_scroll_settings.ts b/x-pack/plugins/watcher/common/constants/es_scroll_settings.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/es_scroll_settings.ts rename to x-pack/plugins/watcher/common/constants/es_scroll_settings.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/index.ts b/x-pack/plugins/watcher/common/constants/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/index.ts rename to x-pack/plugins/watcher/common/constants/index.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/index_names.ts b/x-pack/plugins/watcher/common/constants/index_names.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/index_names.ts rename to x-pack/plugins/watcher/common/constants/index_names.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/lists.ts b/x-pack/plugins/watcher/common/constants/lists.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/lists.ts rename to x-pack/plugins/watcher/common/constants/lists.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/pagination.ts b/x-pack/plugins/watcher/common/constants/pagination.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/pagination.ts rename to x-pack/plugins/watcher/common/constants/pagination.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/plugin.ts b/x-pack/plugins/watcher/common/constants/plugin.ts similarity index 85% rename from x-pack/legacy/plugins/watcher/common/constants/plugin.ts rename to x-pack/plugins/watcher/common/constants/plugin.ts index a4279a0dd0c414..f89ef95e9261f5 100644 --- a/x-pack/legacy/plugins/watcher/common/constants/plugin.ts +++ b/x-pack/plugins/watcher/common/constants/plugin.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { LICENSE_TYPE_GOLD, LicenseType } from '../../../../common/constants'; +import { LICENSE_TYPE_GOLD, LicenseType } from '../../../../legacy/common/constants'; export const PLUGIN = { ID: 'watcher', diff --git a/x-pack/legacy/plugins/watcher/common/constants/refresh_intervals.ts b/x-pack/plugins/watcher/common/constants/refresh_intervals.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/refresh_intervals.ts rename to x-pack/plugins/watcher/common/constants/refresh_intervals.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/routes.ts b/x-pack/plugins/watcher/common/constants/routes.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/routes.ts rename to x-pack/plugins/watcher/common/constants/routes.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/sort_orders.ts b/x-pack/plugins/watcher/common/constants/sort_orders.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/sort_orders.ts rename to x-pack/plugins/watcher/common/constants/sort_orders.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/time_units.ts b/x-pack/plugins/watcher/common/constants/time_units.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/time_units.ts rename to x-pack/plugins/watcher/common/constants/time_units.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/watch_history.ts b/x-pack/plugins/watcher/common/constants/watch_history.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/watch_history.ts rename to x-pack/plugins/watcher/common/constants/watch_history.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/watch_state_comments.ts b/x-pack/plugins/watcher/common/constants/watch_state_comments.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/watch_state_comments.ts rename to x-pack/plugins/watcher/common/constants/watch_state_comments.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/watch_states.ts b/x-pack/plugins/watcher/common/constants/watch_states.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/watch_states.ts rename to x-pack/plugins/watcher/common/constants/watch_states.ts diff --git a/x-pack/legacy/plugins/watcher/common/constants/watch_types.ts b/x-pack/plugins/watcher/common/constants/watch_types.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/constants/watch_types.ts rename to x-pack/plugins/watcher/common/constants/watch_types.ts diff --git a/x-pack/legacy/plugins/watcher/common/lib/get_action_type/__tests__/get_action_type.js b/x-pack/plugins/watcher/common/lib/get_action_type/__tests__/get_action_type.js similarity index 97% rename from x-pack/legacy/plugins/watcher/common/lib/get_action_type/__tests__/get_action_type.js rename to x-pack/plugins/watcher/common/lib/get_action_type/__tests__/get_action_type.js index 164bbab285fce4..1410488ee64131 100644 --- a/x-pack/legacy/plugins/watcher/common/lib/get_action_type/__tests__/get_action_type.js +++ b/x-pack/plugins/watcher/common/lib/get_action_type/__tests__/get_action_type.js @@ -6,7 +6,7 @@ import expect from '@kbn/expect'; import { getActionType } from '../get_action_type'; -import { ACTION_TYPES } from '../../../../common/constants'; +import { ACTION_TYPES } from '../../../constants'; describe('get_action_type', () => { describe('getActionType', () => { diff --git a/x-pack/legacy/plugins/watcher/common/lib/get_action_type/get_action_type.ts b/x-pack/plugins/watcher/common/lib/get_action_type/get_action_type.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/get_action_type/get_action_type.ts rename to x-pack/plugins/watcher/common/lib/get_action_type/get_action_type.ts diff --git a/x-pack/legacy/plugins/watcher/common/lib/get_action_type/index.ts b/x-pack/plugins/watcher/common/lib/get_action_type/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/get_action_type/index.ts rename to x-pack/plugins/watcher/common/lib/get_action_type/index.ts diff --git a/x-pack/legacy/plugins/watcher/common/lib/get_moment/__tests__/get_moment.js b/x-pack/plugins/watcher/common/lib/get_moment/__tests__/get_moment.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/get_moment/__tests__/get_moment.js rename to x-pack/plugins/watcher/common/lib/get_moment/__tests__/get_moment.js diff --git a/x-pack/legacy/plugins/watcher/common/lib/get_moment/get_moment.js b/x-pack/plugins/watcher/common/lib/get_moment/get_moment.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/get_moment/get_moment.js rename to x-pack/plugins/watcher/common/lib/get_moment/get_moment.js diff --git a/x-pack/legacy/plugins/watcher/common/lib/get_moment/index.js b/x-pack/plugins/watcher/common/lib/get_moment/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/get_moment/index.js rename to x-pack/plugins/watcher/common/lib/get_moment/index.js diff --git a/x-pack/legacy/plugins/watcher/common/lib/serialization/index.d.ts b/x-pack/plugins/watcher/common/lib/serialization/index.d.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/serialization/index.d.ts rename to x-pack/plugins/watcher/common/lib/serialization/index.d.ts diff --git a/x-pack/legacy/plugins/watcher/common/lib/serialization/index.js b/x-pack/plugins/watcher/common/lib/serialization/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/serialization/index.js rename to x-pack/plugins/watcher/common/lib/serialization/index.js diff --git a/x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/build_actions.js b/x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_actions.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/build_actions.js rename to x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_actions.js diff --git a/x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/build_condition.js b/x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_condition.js similarity index 98% rename from x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/build_condition.js rename to x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_condition.js index 472349b87fbc19..620859608bc267 100644 --- a/x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/build_condition.js +++ b/x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_condition.js @@ -5,7 +5,7 @@ */ import { singleLineScript } from './single_line_script'; -import { COMPARATORS } from '../../../../common/constants'; +import { COMPARATORS } from '../../../constants'; const { BETWEEN } = COMPARATORS; /* watch.condition.script.inline diff --git a/x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/build_input.js b/x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_input.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/build_input.js rename to x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_input.js diff --git a/x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/build_metadata.js b/x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_metadata.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/build_metadata.js rename to x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_metadata.js diff --git a/x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/build_transform.js b/x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_transform.js similarity index 98% rename from x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/build_transform.js rename to x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_transform.js index 1ac4adb8218040..1fcbd75aeaeea6 100644 --- a/x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/build_transform.js +++ b/x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_transform.js @@ -5,7 +5,7 @@ */ import { singleLineScript } from './single_line_script'; -import { COMPARATORS } from '../../../../common/constants'; +import { COMPARATORS } from '../../../constants'; const { BETWEEN } = COMPARATORS; /* watch.transform.script.inline diff --git a/x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/build_trigger.js b/x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_trigger.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/build_trigger.js rename to x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_trigger.js diff --git a/x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/index.js b/x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/index.js rename to x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/index.js diff --git a/x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/single_line_script.js b/x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/single_line_script.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/serialization/serialization_helpers/single_line_script.js rename to x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/single_line_script.js diff --git a/x-pack/legacy/plugins/watcher/common/lib/serialization/serialize_json_watch.js b/x-pack/plugins/watcher/common/lib/serialization/serialize_json_watch.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/serialization/serialize_json_watch.js rename to x-pack/plugins/watcher/common/lib/serialization/serialize_json_watch.js diff --git a/x-pack/legacy/plugins/watcher/common/lib/serialization/serialize_json_watch.test.js b/x-pack/plugins/watcher/common/lib/serialization/serialize_json_watch.test.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/serialization/serialize_json_watch.test.js rename to x-pack/plugins/watcher/common/lib/serialization/serialize_json_watch.test.js diff --git a/x-pack/legacy/plugins/watcher/common/lib/serialization/serialize_threshold_watch.js b/x-pack/plugins/watcher/common/lib/serialization/serialize_threshold_watch.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/serialization/serialize_threshold_watch.js rename to x-pack/plugins/watcher/common/lib/serialization/serialize_threshold_watch.js diff --git a/x-pack/legacy/plugins/watcher/common/lib/serialization/serialize_threshold_watch.test.js b/x-pack/plugins/watcher/common/lib/serialization/serialize_threshold_watch.test.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/lib/serialization/serialize_threshold_watch.test.js rename to x-pack/plugins/watcher/common/lib/serialization/serialize_threshold_watch.test.js diff --git a/x-pack/legacy/plugins/watcher/common/models/action/action.js b/x-pack/plugins/watcher/common/models/action/action.js similarity index 92% rename from x-pack/legacy/plugins/watcher/common/models/action/action.js rename to x-pack/plugins/watcher/common/models/action/action.js index e66a63eaed1862..0375b6ebf5d475 100644 --- a/x-pack/legacy/plugins/watcher/common/models/action/action.js +++ b/x-pack/plugins/watcher/common/models/action/action.js @@ -5,8 +5,8 @@ */ import { set } from 'lodash'; -import { getActionType } from '../../../common/lib/get_action_type'; -import { ACTION_TYPES } from '../../../common/constants'; +import { getActionType } from '../../lib/get_action_type'; +import { ACTION_TYPES } from '../../constants'; import { LoggingAction } from './logging_action'; import { EmailAction } from './email_action'; import { SlackAction } from './slack_action'; diff --git a/x-pack/legacy/plugins/watcher/common/models/action/action.test.js b/x-pack/plugins/watcher/common/models/action/action.test.js similarity index 97% rename from x-pack/legacy/plugins/watcher/common/models/action/action.test.js rename to x-pack/plugins/watcher/common/models/action/action.test.js index ee1265cd2edeec..8a5f47fe0e5caf 100644 --- a/x-pack/legacy/plugins/watcher/common/models/action/action.test.js +++ b/x-pack/plugins/watcher/common/models/action/action.test.js @@ -5,7 +5,7 @@ */ import { Action } from './action'; -import { ACTION_TYPES } from '../../../common/constants'; +import { ACTION_TYPES } from '../../constants'; jest.mock('./logging_action', () => ({ LoggingAction: { diff --git a/x-pack/legacy/plugins/watcher/common/models/action/base_action.js b/x-pack/plugins/watcher/common/models/action/base_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/models/action/base_action.js rename to x-pack/plugins/watcher/common/models/action/base_action.js diff --git a/x-pack/legacy/plugins/watcher/common/models/action/email_action.js b/x-pack/plugins/watcher/common/models/action/email_action.js similarity index 98% rename from x-pack/legacy/plugins/watcher/common/models/action/email_action.js rename to x-pack/plugins/watcher/common/models/action/email_action.js index de948100951ad1..918a2d125c09a1 100644 --- a/x-pack/legacy/plugins/watcher/common/models/action/email_action.js +++ b/x-pack/plugins/watcher/common/models/action/email_action.js @@ -5,7 +5,7 @@ */ import { BaseAction } from './base_action'; -import { ACTION_TYPES, ERROR_CODES } from '../../../common/constants'; +import { ACTION_TYPES, ERROR_CODES } from '../../constants'; import { i18n } from '@kbn/i18n'; export class EmailAction extends BaseAction { diff --git a/x-pack/legacy/plugins/watcher/common/models/action/index.js b/x-pack/plugins/watcher/common/models/action/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/common/models/action/index.js rename to x-pack/plugins/watcher/common/models/action/index.js diff --git a/x-pack/legacy/plugins/watcher/common/models/action/index_action.js b/x-pack/plugins/watcher/common/models/action/index_action.js similarity index 97% rename from x-pack/legacy/plugins/watcher/common/models/action/index_action.js rename to x-pack/plugins/watcher/common/models/action/index_action.js index 73932079977fd6..3db4e4f9b0dabd 100644 --- a/x-pack/legacy/plugins/watcher/common/models/action/index_action.js +++ b/x-pack/plugins/watcher/common/models/action/index_action.js @@ -5,7 +5,7 @@ */ import { BaseAction } from './base_action'; -import { ACTION_TYPES, ERROR_CODES } from '../../../common/constants'; +import { ACTION_TYPES, ERROR_CODES } from '../../constants'; import { i18n } from '@kbn/i18n'; export class IndexAction extends BaseAction { diff --git a/x-pack/legacy/plugins/watcher/common/models/action/jira_action.js b/x-pack/plugins/watcher/common/models/action/jira_action.js similarity index 98% rename from x-pack/legacy/plugins/watcher/common/models/action/jira_action.js rename to x-pack/plugins/watcher/common/models/action/jira_action.js index 75fa60986c49a3..87bca6c480229f 100644 --- a/x-pack/legacy/plugins/watcher/common/models/action/jira_action.js +++ b/x-pack/plugins/watcher/common/models/action/jira_action.js @@ -5,7 +5,7 @@ */ import { BaseAction } from './base_action'; -import { ACTION_TYPES, ERROR_CODES } from '../../../common/constants'; +import { ACTION_TYPES, ERROR_CODES } from '../../constants'; import { i18n } from '@kbn/i18n'; import { get } from 'lodash'; diff --git a/x-pack/legacy/plugins/watcher/common/models/action/logging_action.js b/x-pack/plugins/watcher/common/models/action/logging_action.js similarity index 97% rename from x-pack/legacy/plugins/watcher/common/models/action/logging_action.js rename to x-pack/plugins/watcher/common/models/action/logging_action.js index c3754b7ace2384..e9dd0b3d7ddfb5 100644 --- a/x-pack/legacy/plugins/watcher/common/models/action/logging_action.js +++ b/x-pack/plugins/watcher/common/models/action/logging_action.js @@ -5,7 +5,7 @@ */ import { BaseAction } from './base_action'; -import { ACTION_TYPES, ERROR_CODES } from '../../../common/constants'; +import { ACTION_TYPES, ERROR_CODES } from '../../constants'; import { i18n } from '@kbn/i18n'; export class LoggingAction extends BaseAction { diff --git a/x-pack/legacy/plugins/watcher/common/models/action/pagerduty_action.js b/x-pack/plugins/watcher/common/models/action/pagerduty_action.js similarity index 97% rename from x-pack/legacy/plugins/watcher/common/models/action/pagerduty_action.js rename to x-pack/plugins/watcher/common/models/action/pagerduty_action.js index cc15d10f7c6225..b92fbf55bda16c 100644 --- a/x-pack/legacy/plugins/watcher/common/models/action/pagerduty_action.js +++ b/x-pack/plugins/watcher/common/models/action/pagerduty_action.js @@ -5,7 +5,7 @@ */ import { BaseAction } from './base_action'; -import { ACTION_TYPES, ERROR_CODES } from '../../../common/constants'; +import { ACTION_TYPES, ERROR_CODES } from '../../constants'; import { i18n } from '@kbn/i18n'; export class PagerDutyAction extends BaseAction { diff --git a/x-pack/legacy/plugins/watcher/common/models/action/slack_action.js b/x-pack/plugins/watcher/common/models/action/slack_action.js similarity index 97% rename from x-pack/legacy/plugins/watcher/common/models/action/slack_action.js rename to x-pack/plugins/watcher/common/models/action/slack_action.js index a1986977c4633e..24caa9ccfd5816 100644 --- a/x-pack/legacy/plugins/watcher/common/models/action/slack_action.js +++ b/x-pack/plugins/watcher/common/models/action/slack_action.js @@ -5,7 +5,7 @@ */ import { BaseAction } from './base_action'; -import { ACTION_TYPES, ERROR_CODES } from '../../../common/constants'; +import { ACTION_TYPES, ERROR_CODES } from '../../constants'; import { i18n } from '@kbn/i18n'; export class SlackAction extends BaseAction { diff --git a/x-pack/legacy/plugins/watcher/common/models/action/unknown_action.js b/x-pack/plugins/watcher/common/models/action/unknown_action.js similarity index 96% rename from x-pack/legacy/plugins/watcher/common/models/action/unknown_action.js rename to x-pack/plugins/watcher/common/models/action/unknown_action.js index 95ed542e66fa55..4f304be2d58b6d 100644 --- a/x-pack/legacy/plugins/watcher/common/models/action/unknown_action.js +++ b/x-pack/plugins/watcher/common/models/action/unknown_action.js @@ -5,7 +5,7 @@ */ import { BaseAction } from './base_action'; -import { ACTION_TYPES, ERROR_CODES } from '../../../common/constants'; +import { ACTION_TYPES, ERROR_CODES } from '../../constants'; import { i18n } from '@kbn/i18n'; export class UnknownAction extends BaseAction { diff --git a/x-pack/legacy/plugins/watcher/common/models/action/webhook_action.js b/x-pack/plugins/watcher/common/models/action/webhook_action.js similarity index 98% rename from x-pack/legacy/plugins/watcher/common/models/action/webhook_action.js rename to x-pack/plugins/watcher/common/models/action/webhook_action.js index d6f921a75a9ea3..f0e9fc9fc44df5 100644 --- a/x-pack/legacy/plugins/watcher/common/models/action/webhook_action.js +++ b/x-pack/plugins/watcher/common/models/action/webhook_action.js @@ -5,7 +5,7 @@ */ import { BaseAction } from './base_action'; -import { ACTION_TYPES, ERROR_CODES } from '../../../common/constants'; +import { ACTION_TYPES, ERROR_CODES } from '../../constants'; import { i18n } from '@kbn/i18n'; export class WebhookAction extends BaseAction { diff --git a/x-pack/legacy/plugins/watcher/common/types/action_types.ts b/x-pack/plugins/watcher/common/types/action_types.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/types/action_types.ts rename to x-pack/plugins/watcher/common/types/action_types.ts diff --git a/x-pack/legacy/plugins/watcher/index.js b/x-pack/plugins/watcher/common/types/license_status.ts similarity index 65% rename from x-pack/legacy/plugins/watcher/index.js rename to x-pack/plugins/watcher/common/types/license_status.ts index 64237b532ea8d5..3872559fc00662 100644 --- a/x-pack/legacy/plugins/watcher/index.js +++ b/x-pack/plugins/watcher/common/types/license_status.ts @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { pluginDefinition } from './plugin_definition'; - -export const watcher = kibana => new kibana.Plugin(pluginDefinition); +export interface LicenseStatus { + valid: boolean; + message?: string; +} diff --git a/x-pack/legacy/plugins/watcher/common/types/watch_types.ts b/x-pack/plugins/watcher/common/types/watch_types.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/common/types/watch_types.ts rename to x-pack/plugins/watcher/common/types/watch_types.ts diff --git a/x-pack/legacy/plugins/watcher/kibana.json b/x-pack/plugins/watcher/kibana.json similarity index 58% rename from x-pack/legacy/plugins/watcher/kibana.json rename to x-pack/plugins/watcher/kibana.json index ccec8a1b776836..93a28f8f59ed5a 100644 --- a/x-pack/legacy/plugins/watcher/kibana.json +++ b/x-pack/plugins/watcher/kibana.json @@ -2,7 +2,11 @@ "id": "watcher", "version": "kibana", "requiredPlugins": [ - "home" + "home", + "licensing", + "management", + "eui_utils", + "data" ], "server": true, "ui": true diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/app.tsx b/x-pack/plugins/watcher/public/application/app.tsx similarity index 89% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/app.tsx rename to x-pack/plugins/watcher/public/application/app.tsx index 36fa1cce9d6ddc..83501eca1429b1 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/app.tsx +++ b/x-pack/plugins/watcher/public/application/app.tsx @@ -11,9 +11,8 @@ import { HttpSetup, ToastsSetup, IUiSettingsClient, -} from 'src/core/public'; +} from 'kibana/public'; -import { EuiCallOut, EuiLink } from '@elastic/eui'; import { HashRouter, Switch, @@ -22,15 +21,18 @@ import { withRouter, RouteComponentProps, } from 'react-router-dom'; + +import { EuiCallOut, EuiLink } from '@elastic/eui'; + import { FormattedMessage } from '@kbn/i18n/react'; + +import { LicenseStatus } from '../../common/types/license_status'; import { WatchStatus } from './sections/watch_status/components/watch_status'; import { WatchEdit } from './sections/watch_edit/components/watch_edit'; import { WatchList } from './sections/watch_list/components/watch_list'; import { registerRouter } from './lib/navigation'; import { BASE_PATH } from './constants'; -import { LICENSE_STATUS_VALID } from '../../../../../common/constants'; import { AppContextProvider } from './app_context'; -import { LegacyDependencies } from '../types'; const ShareRouter = withRouter(({ children, history }: RouteComponentProps & { children: any }) => { registerRouter({ history }); @@ -43,14 +45,16 @@ export interface AppDeps { toasts: ToastsSetup; http: HttpSetup; uiSettings: IUiSettingsClient; - legacy: LegacyDependencies; euiUtils: any; + createTimeBuckets: () => any; + getLicenseStatus: () => LicenseStatus; + MANAGEMENT_BREADCRUMB: any; } export const App = (deps: AppDeps) => { - const { status, message } = deps.legacy.licenseStatus; + const { valid, message } = deps.getLicenseStatus(); - if (status !== LICENSE_STATUS_VALID) { + if (!valid) { return ( { defaultMessage="License error" /> } - color="warning" + color="danger" iconType="help" > {message}{' '} @@ -72,7 +76,6 @@ export const App = (deps: AppDeps) => { ); } - return ( diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/app_context.tsx b/x-pack/plugins/watcher/public/application/app_context.tsx similarity index 94% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/app_context.tsx rename to x-pack/plugins/watcher/public/application/app_context.tsx index 5696ab3cb91ba1..e5cf4c33b477ac 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/app_context.tsx +++ b/x-pack/plugins/watcher/public/application/app_context.tsx @@ -5,8 +5,8 @@ */ import React, { createContext, useContext } from 'react'; -import { DocLinksStart } from 'src/core/public'; -import { ACTION_TYPES } from '../../../common/constants'; +import { DocLinksStart } from 'kibana/public'; +import { ACTION_TYPES } from '../../common/constants'; import { AppDeps } from './app'; interface ContextValue extends Omit { diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/boot.tsx b/x-pack/plugins/watcher/public/application/boot.tsx similarity index 70% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/boot.tsx rename to x-pack/plugins/watcher/public/application/boot.tsx index 3f2a10f0046495..8461bd65bbd5e5 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/boot.tsx +++ b/x-pack/plugins/watcher/public/application/boot.tsx @@ -6,30 +6,30 @@ import React from 'react'; import { render, unmountComponentAtNode } from 'react-dom'; -import { SavedObjectsClientContract } from 'src/core/public'; +import { SavedObjectsClientContract } from 'kibana/public'; import { App, AppDeps } from './app'; import { setHttpClient, setSavedObjectsClient } from './lib/api'; -import { LegacyDependencies } from '../types'; interface BootDeps extends AppDeps { element: HTMLElement; savedObjects: SavedObjectsClientContract; I18nContext: any; - legacy: LegacyDependencies; } export const boot = (bootDeps: BootDeps) => { - const { I18nContext, element, legacy, savedObjects, ...appDeps } = bootDeps; + const { I18nContext, element, savedObjects, ...appDeps } = bootDeps; setHttpClient(appDeps.http); setSavedObjectsClient(savedObjects); render( - + , element ); - return () => unmountComponentAtNode(element); + return () => { + unmountComponentAtNode(element); + }; }; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/components/confirm_watches_modal.tsx b/x-pack/plugins/watcher/public/application/components/confirm_watches_modal.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/components/confirm_watches_modal.tsx rename to x-pack/plugins/watcher/public/application/components/confirm_watches_modal.tsx diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/components/delete_watches_modal.tsx b/x-pack/plugins/watcher/public/application/components/delete_watches_modal.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/components/delete_watches_modal.tsx rename to x-pack/plugins/watcher/public/application/components/delete_watches_modal.tsx diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/components/form_errors.tsx b/x-pack/plugins/watcher/public/application/components/form_errors.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/components/form_errors.tsx rename to x-pack/plugins/watcher/public/application/components/form_errors.tsx diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/components/index.ts b/x-pack/plugins/watcher/public/application/components/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/components/index.ts rename to x-pack/plugins/watcher/public/application/components/index.ts diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/index.ts b/x-pack/plugins/watcher/public/application/components/page_error/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/index.ts rename to x-pack/plugins/watcher/public/application/components/page_error/index.ts diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/page_error.tsx b/x-pack/plugins/watcher/public/application/components/page_error/page_error.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/page_error.tsx rename to x-pack/plugins/watcher/public/application/components/page_error/page_error.tsx diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/page_error_forbidden.tsx b/x-pack/plugins/watcher/public/application/components/page_error/page_error_forbidden.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/page_error_forbidden.tsx rename to x-pack/plugins/watcher/public/application/components/page_error/page_error_forbidden.tsx diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/page_error_not_exist.tsx b/x-pack/plugins/watcher/public/application/components/page_error/page_error_not_exist.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/components/page_error/page_error_not_exist.tsx rename to x-pack/plugins/watcher/public/application/components/page_error/page_error_not_exist.tsx diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/components/section_error.tsx b/x-pack/plugins/watcher/public/application/components/section_error.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/components/section_error.tsx rename to x-pack/plugins/watcher/public/application/components/section_error.tsx diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/components/section_loading.tsx b/x-pack/plugins/watcher/public/application/components/section_loading.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/components/section_loading.tsx rename to x-pack/plugins/watcher/public/application/components/section_loading.tsx diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/components/watch_status.tsx b/x-pack/plugins/watcher/public/application/components/watch_status.tsx similarity index 95% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/components/watch_status.tsx rename to x-pack/plugins/watcher/public/application/components/watch_status.tsx index a254f43723877a..088f476dfb4cf3 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/components/watch_status.tsx +++ b/x-pack/plugins/watcher/public/application/components/watch_status.tsx @@ -6,7 +6,7 @@ import React from 'react'; import { EuiIcon, EuiFlexGroup, EuiFlexItem, EuiText } from '@elastic/eui'; -import { ACTION_STATES, WATCH_STATES } from '../../../../common/constants'; +import { ACTION_STATES, WATCH_STATES } from '../../../common/constants'; function StatusIcon({ status }: { status: string }) { switch (status) { diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/constants/base_path.ts b/x-pack/plugins/watcher/public/application/constants/base_path.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/constants/base_path.ts rename to x-pack/plugins/watcher/public/application/constants/base_path.ts diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/constants/index.ts b/x-pack/plugins/watcher/public/application/constants/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/constants/index.ts rename to x-pack/plugins/watcher/public/application/constants/index.ts diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/api.ts b/x-pack/plugins/watcher/public/application/lib/api.ts similarity index 88% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/lib/api.ts rename to x-pack/plugins/watcher/public/application/lib/api.ts index c08545904e3516..82ec2925ba6dca 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/api.ts +++ b/x-pack/plugins/watcher/public/application/lib/api.ts @@ -3,16 +3,17 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { HttpSetup, SavedObjectsClientContract } from 'src/core/public'; -import { Settings } from 'plugins/watcher/np_ready/application/models/settings'; -import { Watch } from 'plugins/watcher/np_ready/application/models/watch'; -import { WatchHistoryItem } from 'plugins/watcher/np_ready/application/models/watch_history_item'; -import { WatchStatus } from 'plugins/watcher/np_ready/application/models/watch_status'; +import { HttpSetup, SavedObjectsClientContract } from 'kibana/public'; -import { BaseWatch, ExecutedWatchDetails } from '../../../../common/types/watch_types'; +import { Settings } from '../models/settings'; +import { Watch } from '../models/watch'; +import { WatchHistoryItem } from '../models/watch_history_item'; +import { WatchStatus } from '../models/watch_status'; + +import { BaseWatch, ExecutedWatchDetails } from '../../../common/types/watch_types'; import { useRequest, sendRequest } from './use_request'; -import { ROUTES } from '../../../../common/constants'; +import { ROUTES } from '../../../common/constants'; let httpClient: HttpSetup; @@ -155,7 +156,7 @@ export const useGetWatchVisualizationData = (watchModel: BaseWatch, visualizeOpt watch: watchModel.upstreamJson, options: visualizeOptions.upstreamJson, }), - deserializer: ({ visualizeData }: { visualizeData: any }) => visualizeData, + deserializer: (data: { visualizeData: any }) => data?.visualizeData, }); }; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/breadcrumbs.ts b/x-pack/plugins/watcher/public/application/lib/breadcrumbs.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/lib/breadcrumbs.ts rename to x-pack/plugins/watcher/public/application/lib/breadcrumbs.ts diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/format_date.ts b/x-pack/plugins/watcher/public/application/lib/format_date.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/lib/format_date.ts rename to x-pack/plugins/watcher/public/application/lib/format_date.ts diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/get_search_value.ts b/x-pack/plugins/watcher/public/application/lib/get_search_value.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/lib/get_search_value.ts rename to x-pack/plugins/watcher/public/application/lib/get_search_value.ts diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/get_time_unit_label.ts b/x-pack/plugins/watcher/public/application/lib/get_time_unit_label.ts similarity index 95% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/lib/get_time_unit_label.ts rename to x-pack/plugins/watcher/public/application/lib/get_time_unit_label.ts index ce3b96ac17def3..5cb78b61488b73 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/get_time_unit_label.ts +++ b/x-pack/plugins/watcher/public/application/lib/get_time_unit_label.ts @@ -5,7 +5,7 @@ */ import { i18n } from '@kbn/i18n'; -import { TIME_UNITS } from '../../../../common/constants'; +import { TIME_UNITS } from '../../../common/constants'; export function getTimeUnitLabel(timeUnit = TIME_UNITS.SECOND, timeValue = '0') { switch (timeUnit) { diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/navigation.ts b/x-pack/plugins/watcher/public/application/lib/navigation.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/lib/navigation.ts rename to x-pack/plugins/watcher/public/application/lib/navigation.ts diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/lib/use_request.ts b/x-pack/plugins/watcher/public/application/lib/use_request.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/lib/use_request.ts rename to x-pack/plugins/watcher/public/application/lib/use_request.ts diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/action.js b/x-pack/plugins/watcher/public/application/models/action/action.js similarity index 95% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/action.js rename to x-pack/plugins/watcher/public/application/models/action/action.js index 5d5c44d7ae5341..43874c9ee1dd1a 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/action.js +++ b/x-pack/plugins/watcher/public/application/models/action/action.js @@ -5,7 +5,7 @@ */ import { get, set } from 'lodash'; -import { ACTION_TYPES } from '../../../../../common/constants'; +import { ACTION_TYPES } from '../../../../common/constants'; import { EmailAction } from './email_action'; import { LoggingAction } from './logging_action'; import { SlackAction } from './slack_action'; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/base_action.js b/x-pack/plugins/watcher/public/application/models/action/base_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/base_action.js rename to x-pack/plugins/watcher/public/application/models/action/base_action.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/email_action.js b/x-pack/plugins/watcher/public/application/models/action/email_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/email_action.js rename to x-pack/plugins/watcher/public/application/models/action/email_action.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/types.ts b/x-pack/plugins/watcher/public/application/models/action/index.d.ts similarity index 63% rename from x-pack/legacy/plugins/watcher/public/np_ready/types.ts rename to x-pack/plugins/watcher/public/application/models/action/index.d.ts index 22109f99c2c48b..5415194b729583 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/types.ts +++ b/x-pack/plugins/watcher/public/application/models/action/index.d.ts @@ -4,8 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export interface LegacyDependencies { - MANAGEMENT_BREADCRUMB: { text: string; href?: string }; - TimeBuckets: any; - licenseStatus: any; -} +export const Action: any; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/index.js b/x-pack/plugins/watcher/public/application/models/action/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/index.js rename to x-pack/plugins/watcher/public/application/models/action/index.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/index_action.js b/x-pack/plugins/watcher/public/application/models/action/index_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/index_action.js rename to x-pack/plugins/watcher/public/application/models/action/index_action.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/jira_action.js b/x-pack/plugins/watcher/public/application/models/action/jira_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/jira_action.js rename to x-pack/plugins/watcher/public/application/models/action/jira_action.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/logging_action.js b/x-pack/plugins/watcher/public/application/models/action/logging_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/logging_action.js rename to x-pack/plugins/watcher/public/application/models/action/logging_action.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/pagerduty_action.js b/x-pack/plugins/watcher/public/application/models/action/pagerduty_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/pagerduty_action.js rename to x-pack/plugins/watcher/public/application/models/action/pagerduty_action.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/slack_action.js b/x-pack/plugins/watcher/public/application/models/action/slack_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/slack_action.js rename to x-pack/plugins/watcher/public/application/models/action/slack_action.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/unknown_action.js b/x-pack/plugins/watcher/public/application/models/action/unknown_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/unknown_action.js rename to x-pack/plugins/watcher/public/application/models/action/unknown_action.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/webhook_action.js b/x-pack/plugins/watcher/public/application/models/action/webhook_action.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/action/webhook_action.js rename to x-pack/plugins/watcher/public/application/models/action/webhook_action.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action_status/action_status.js b/x-pack/plugins/watcher/public/application/models/action_status/action_status.js similarity index 95% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/action_status/action_status.js rename to x-pack/plugins/watcher/public/application/models/action_status/action_status.js index b177eb5bb22914..f38fa23b68f5a8 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action_status/action_status.js +++ b/x-pack/plugins/watcher/public/application/models/action_status/action_status.js @@ -5,7 +5,7 @@ */ import { get } from 'lodash'; -import { getMoment } from '../../../../../common/lib/get_moment'; +import { getMoment } from '../../../../common/lib/get_moment'; export class ActionStatus { constructor(props = {}) { diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/action_status/index.js b/x-pack/plugins/watcher/public/application/models/action_status/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/action_status/index.js rename to x-pack/plugins/watcher/public/application/models/action_status/index.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/execute_details/execute_details.js b/x-pack/plugins/watcher/public/application/models/execute_details/execute_details.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/execute_details/execute_details.js rename to x-pack/plugins/watcher/public/application/models/execute_details/execute_details.js diff --git a/x-pack/plugins/watcher/public/application/models/execute_details/index.d.ts b/x-pack/plugins/watcher/public/application/models/execute_details/index.d.ts new file mode 100644 index 00000000000000..417c073cf05681 --- /dev/null +++ b/x-pack/plugins/watcher/public/application/models/execute_details/index.d.ts @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const ExecuteDetails: any; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/execute_details/index.js b/x-pack/plugins/watcher/public/application/models/execute_details/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/execute_details/index.js rename to x-pack/plugins/watcher/public/application/models/execute_details/index.js diff --git a/x-pack/plugins/watcher/public/application/models/settings/index.d.ts b/x-pack/plugins/watcher/public/application/models/settings/index.d.ts new file mode 100644 index 00000000000000..92a5de1df413ce --- /dev/null +++ b/x-pack/plugins/watcher/public/application/models/settings/index.d.ts @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const Settings: any; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/settings/index.js b/x-pack/plugins/watcher/public/application/models/settings/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/settings/index.js rename to x-pack/plugins/watcher/public/application/models/settings/index.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/settings/settings.js b/x-pack/plugins/watcher/public/application/models/settings/settings.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/settings/settings.js rename to x-pack/plugins/watcher/public/application/models/settings/settings.js diff --git a/x-pack/plugins/watcher/public/application/models/visualize_options/index.d.ts b/x-pack/plugins/watcher/public/application/models/visualize_options/index.d.ts new file mode 100644 index 00000000000000..cea10ff1e10460 --- /dev/null +++ b/x-pack/plugins/watcher/public/application/models/visualize_options/index.d.ts @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const VisualizeOptions: any; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/visualize_options/index.js b/x-pack/plugins/watcher/public/application/models/visualize_options/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/visualize_options/index.js rename to x-pack/plugins/watcher/public/application/models/visualize_options/index.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/visualize_options/visualize_options.js b/x-pack/plugins/watcher/public/application/models/visualize_options/visualize_options.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/visualize_options/visualize_options.js rename to x-pack/plugins/watcher/public/application/models/visualize_options/visualize_options.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/agg_types.ts b/x-pack/plugins/watcher/public/application/models/watch/agg_types.ts similarity index 94% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/agg_types.ts rename to x-pack/plugins/watcher/public/application/models/watch/agg_types.ts index cefaaa3b1abd3a..d2b1ddebf12a27 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/agg_types.ts +++ b/x-pack/plugins/watcher/public/application/models/watch/agg_types.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { AGG_TYPES } from '../../../../../common/constants'; +import { AGG_TYPES } from '../../../../common/constants'; export interface AggType { text: string; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/base_watch.js b/x-pack/plugins/watcher/public/application/models/watch/base_watch.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/base_watch.js rename to x-pack/plugins/watcher/public/application/models/watch/base_watch.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/comparators.ts b/x-pack/plugins/watcher/public/application/models/watch/comparators.ts similarity index 96% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/comparators.ts rename to x-pack/plugins/watcher/public/application/models/watch/comparators.ts index edc3a03c252271..96904719098a0c 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/comparators.ts +++ b/x-pack/plugins/watcher/public/application/models/watch/comparators.ts @@ -6,7 +6,7 @@ import { i18n } from '@kbn/i18n'; -import { COMPARATORS } from '../../../../../common/constants'; +import { COMPARATORS } from '../../../../common/constants'; export interface Comparator { text: string; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/default_watch.json b/x-pack/plugins/watcher/public/application/models/watch/default_watch.json similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/default_watch.json rename to x-pack/plugins/watcher/public/application/models/watch/default_watch.json diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/group_by_types.ts b/x-pack/plugins/watcher/public/application/models/watch/group_by_types.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/group_by_types.ts rename to x-pack/plugins/watcher/public/application/models/watch/group_by_types.ts diff --git a/x-pack/plugins/watcher/public/application/models/watch/index.d.ts b/x-pack/plugins/watcher/public/application/models/watch/index.d.ts new file mode 100644 index 00000000000000..73ee2279d3912f --- /dev/null +++ b/x-pack/plugins/watcher/public/application/models/watch/index.d.ts @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const Watch: any; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/index.js b/x-pack/plugins/watcher/public/application/models/watch/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/index.js rename to x-pack/plugins/watcher/public/application/models/watch/index.js diff --git a/x-pack/plugins/watcher/public/application/models/watch/json_watch.d.ts b/x-pack/plugins/watcher/public/application/models/watch/json_watch.d.ts new file mode 100644 index 00000000000000..cef21880e63466 --- /dev/null +++ b/x-pack/plugins/watcher/public/application/models/watch/json_watch.d.ts @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const JsonWatch: any; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/json_watch.js b/x-pack/plugins/watcher/public/application/models/watch/json_watch.js similarity index 98% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/json_watch.js rename to x-pack/plugins/watcher/public/application/models/watch/json_watch.js index 2d18c233ed5b45..19d016fcc48eb5 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/json_watch.js +++ b/x-pack/plugins/watcher/public/application/models/watch/json_watch.js @@ -7,7 +7,7 @@ import uuid from 'uuid'; import { get } from 'lodash'; import { BaseWatch } from './base_watch'; -import { ACTION_TYPES, WATCH_TYPES } from '../../../../../common/constants'; +import { ACTION_TYPES, WATCH_TYPES } from '../../../../common/constants'; import defaultWatchJson from './default_watch.json'; import { i18n } from '@kbn/i18n'; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/check_action_id_collision/check_action_id_collision.js b/x-pack/plugins/watcher/public/application/models/watch/lib/check_action_id_collision/check_action_id_collision.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/check_action_id_collision/check_action_id_collision.js rename to x-pack/plugins/watcher/public/application/models/watch/lib/check_action_id_collision/check_action_id_collision.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/check_action_id_collision/index.js b/x-pack/plugins/watcher/public/application/models/watch/lib/check_action_id_collision/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/check_action_id_collision/index.js rename to x-pack/plugins/watcher/public/application/models/watch/lib/check_action_id_collision/index.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/create_action_id/create_action_id.js b/x-pack/plugins/watcher/public/application/models/watch/lib/create_action_id/create_action_id.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/create_action_id/create_action_id.js rename to x-pack/plugins/watcher/public/application/models/watch/lib/create_action_id/create_action_id.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/create_action_id/index.js b/x-pack/plugins/watcher/public/application/models/watch/lib/create_action_id/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/lib/create_action_id/index.js rename to x-pack/plugins/watcher/public/application/models/watch/lib/create_action_id/index.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/monitoring_watch.js b/x-pack/plugins/watcher/public/application/models/watch/monitoring_watch.js similarity index 92% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/monitoring_watch.js rename to x-pack/plugins/watcher/public/application/models/watch/monitoring_watch.js index 850953ebd963e7..82cdffc79edc42 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/monitoring_watch.js +++ b/x-pack/plugins/watcher/public/application/models/watch/monitoring_watch.js @@ -5,7 +5,7 @@ */ import { BaseWatch } from './base_watch'; -import { WATCH_TYPES } from '../../../../../common/constants'; +import { WATCH_TYPES } from '../../../../common/constants'; /** * {@code MonitoringWatch} system defined watches created by the Monitoring plugin. diff --git a/x-pack/plugins/watcher/public/application/models/watch/threshold_watch.d.ts b/x-pack/plugins/watcher/public/application/models/watch/threshold_watch.d.ts new file mode 100644 index 00000000000000..ae85ae01304d6e --- /dev/null +++ b/x-pack/plugins/watcher/public/application/models/watch/threshold_watch.d.ts @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const ThresholdWatch: any; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/threshold_watch.js b/x-pack/plugins/watcher/public/application/models/watch/threshold_watch.js similarity index 99% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/threshold_watch.js rename to x-pack/plugins/watcher/public/application/models/watch/threshold_watch.js index 2383388dd89bf2..c9db4237942b00 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/threshold_watch.js +++ b/x-pack/plugins/watcher/public/application/models/watch/threshold_watch.js @@ -6,7 +6,7 @@ import { BaseWatch } from './base_watch'; import uuid from 'uuid'; -import { WATCH_TYPES, SORT_ORDERS, COMPARATORS } from '../../../../../common/constants'; +import { WATCH_TYPES, SORT_ORDERS, COMPARATORS } from '../../../../common/constants'; import { getTimeUnitLabel } from '../../lib/get_time_unit_label'; import { i18n } from '@kbn/i18n'; import { aggTypes } from './agg_types'; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/watch.js b/x-pack/plugins/watcher/public/application/models/watch/watch.js similarity index 93% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/watch.js rename to x-pack/plugins/watcher/public/application/models/watch/watch.js index fc33fab56d07c2..934d1e338ed0c6 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch/watch.js +++ b/x-pack/plugins/watcher/public/application/models/watch/watch.js @@ -5,7 +5,7 @@ */ import { get, set } from 'lodash'; -import { WATCH_TYPES } from '../../../../../common/constants'; +import { WATCH_TYPES } from '../../../../common/constants'; import { JsonWatch } from './json_watch'; import { ThresholdWatch } from './threshold_watch'; import { MonitoringWatch } from './monitoring_watch'; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_errors/index.js b/x-pack/plugins/watcher/public/application/models/watch_errors/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_errors/index.js rename to x-pack/plugins/watcher/public/application/models/watch_errors/index.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_errors/watch_errors.js b/x-pack/plugins/watcher/public/application/models/watch_errors/watch_errors.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_errors/watch_errors.js rename to x-pack/plugins/watcher/public/application/models/watch_errors/watch_errors.js diff --git a/x-pack/plugins/watcher/public/application/models/watch_history_item/index.d.ts b/x-pack/plugins/watcher/public/application/models/watch_history_item/index.d.ts new file mode 100644 index 00000000000000..48fe71e2c55c03 --- /dev/null +++ b/x-pack/plugins/watcher/public/application/models/watch_history_item/index.d.ts @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const WatchHistoryItem: any; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_history_item/index.js b/x-pack/plugins/watcher/public/application/models/watch_history_item/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_history_item/index.js rename to x-pack/plugins/watcher/public/application/models/watch_history_item/index.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_history_item/watch_history_item.js b/x-pack/plugins/watcher/public/application/models/watch_history_item/watch_history_item.js similarity index 91% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_history_item/watch_history_item.js rename to x-pack/plugins/watcher/public/application/models/watch_history_item/watch_history_item.js index 785f9d19b23dd9..36fa9fa5aefe27 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_history_item/watch_history_item.js +++ b/x-pack/plugins/watcher/public/application/models/watch_history_item/watch_history_item.js @@ -6,7 +6,7 @@ import 'moment-duration-format'; import { get } from 'lodash'; -import { getMoment } from '../../../../../common/lib/get_moment'; +import { getMoment } from '../../../../common/lib/get_moment'; import { WatchStatus } from '../watch_status'; export class WatchHistoryItem { diff --git a/x-pack/plugins/watcher/public/application/models/watch_status/index.d.ts b/x-pack/plugins/watcher/public/application/models/watch_status/index.d.ts new file mode 100644 index 00000000000000..f8ff6889612992 --- /dev/null +++ b/x-pack/plugins/watcher/public/application/models/watch_status/index.d.ts @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const WatchStatus: any; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_status/index.js b/x-pack/plugins/watcher/public/application/models/watch_status/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_status/index.js rename to x-pack/plugins/watcher/public/application/models/watch_status/index.js diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_status/watch_status.js b/x-pack/plugins/watcher/public/application/models/watch_status/watch_status.js similarity index 94% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_status/watch_status.js rename to x-pack/plugins/watcher/public/application/models/watch_status/watch_status.js index 7b35493ebdfa22..8cbdc1b5b30cc8 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/models/watch_status/watch_status.js +++ b/x-pack/plugins/watcher/public/application/models/watch_status/watch_status.js @@ -5,7 +5,7 @@ */ import { get } from 'lodash'; -import { getMoment } from '../../../../../common/lib/get_moment'; +import { getMoment } from '../../../../common/lib/get_moment'; import { ActionStatus } from '../action_status'; export class WatchStatus { diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/index.ts b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/index.ts rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/index.ts diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit.tsx similarity index 92% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit.tsx index 010e430c0719a1..b87fc355c3eade 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit.tsx @@ -16,10 +16,10 @@ import { EuiTitle, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { ExecuteDetails } from 'plugins/watcher/np_ready/application/models/execute_details/execute_details'; -import { getActionType } from '../../../../../../../common/lib/get_action_type'; -import { BaseWatch, ExecutedWatchDetails } from '../../../../../../../common/types/watch_types'; -import { ACTION_MODES, TIME_UNITS } from '../../../../../../../common/constants'; +import { ExecuteDetails } from '../../../../models/execute_details'; +import { getActionType } from '../../../../../../common/lib/get_action_type'; +import { BaseWatch, ExecutedWatchDetails } from '../../../../../../common/types/watch_types'; +import { ACTION_MODES, TIME_UNITS } from '../../../../../../common/constants'; import { JsonWatchEditForm } from './json_watch_edit_form'; import { JsonWatchEditSimulate } from './json_watch_edit_simulate'; import { WatchContext } from '../../watch_context'; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx similarity index 99% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx index 376aeb205b855c..91185ac604b345 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_form.tsx @@ -20,7 +20,7 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { serializeJsonWatch } from '../../../../../../../common/lib/serialization'; +import { serializeJsonWatch } from '../../../../../../common/lib/serialization'; import { ErrableFormRow, SectionError, Error as ServerError } from '../../../../components'; import { onWatchSave } from '../../watch_edit_actions'; import { WatchContext } from '../../watch_context'; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate.tsx similarity index 97% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate.tsx index 9ea2b3bcd1e9a4..8bb1770d2f44da 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate.tsx @@ -24,13 +24,15 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { ExecuteDetails } from 'plugins/watcher/np_ready/application/models/execute_details/execute_details'; -import { WatchHistoryItem } from 'plugins/watcher/np_ready/application/models/watch_history_item'; -import { ACTION_MODES, TIME_UNITS } from '../../../../../../../common/constants'; + +import { WatchHistoryItem } from '../../../../models/watch_history_item'; + +import { ACTION_MODES, TIME_UNITS } from '../../../../../../common/constants'; +import { ExecuteDetails } from '../../../../models/execute_details'; import { ExecutedWatchDetails, ExecutedWatchResults, -} from '../../../../../../../common/types/watch_types'; +} from '../../../../../../common/types/watch_types'; import { ErrableFormRow } from '../../../../components/form_errors'; import { executeWatch } from '../../../../lib/api'; import { WatchContext } from '../../watch_context'; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate_results.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate_results.tsx similarity index 99% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate_results.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate_results.tsx index c3f11c6c3fa465..0a61e4401fdf12 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate_results.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/json_watch_edit/json_watch_edit_simulate_results.tsx @@ -21,7 +21,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { ExecutedWatchDetails, ExecutedWatchResults, -} from '../../../../../../../common/types/watch_types'; +} from '../../../../../../common/types/watch_types'; import { getTypeFromAction } from '../../watch_edit_actions'; import { WatchContext } from '../../watch_context'; import { WatchStatus, SectionError } from '../../../../components'; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/monitoring_watch_edit/index.ts b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/monitoring_watch_edit/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/monitoring_watch_edit/index.ts rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/monitoring_watch_edit/index.ts diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/monitoring_watch_edit/monitoring_watch_edit.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/monitoring_watch_edit/monitoring_watch_edit.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/monitoring_watch_edit/monitoring_watch_edit.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/monitoring_watch_edit/monitoring_watch_edit.tsx diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/request_flyout.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/request_flyout.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/request_flyout.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/request_flyout.tsx diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/email_action_fields.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/email_action_fields.tsx similarity index 97% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/email_action_fields.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/email_action_fields.tsx index 3e70e49f423504..a94055271ff5b8 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/email_action_fields.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/email_action_fields.tsx @@ -8,7 +8,7 @@ import React, { Fragment } from 'react'; import { EuiComboBox, EuiFieldText, EuiFormRow, EuiTextArea } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { ErrableFormRow } from '../../../../../components/form_errors'; -import { EmailAction } from '../../../../../../../../common/types/action_types'; +import { EmailAction } from '../../../../../../../common/types/action_types'; interface Props { action: EmailAction; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/index.ts b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/index.ts rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/index.ts diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/index_action_fields.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/index_action_fields.tsx similarity index 94% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/index_action_fields.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/index_action_fields.tsx index b7ab76d9890bcf..f1d36bce415d3e 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/index_action_fields.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/index_action_fields.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { EuiFieldText } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { ErrableFormRow } from '../../../../../components/form_errors'; -import { IndexAction } from '../../../../../../../../common/types/action_types'; +import { IndexAction } from '../../../../../../../common/types/action_types'; interface Props { action: IndexAction; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/jira_action_fields.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/jira_action_fields.tsx similarity index 97% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/jira_action_fields.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/jira_action_fields.tsx index c09b3c44fde65c..2bfc4f2eb1b5d3 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/jira_action_fields.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/jira_action_fields.tsx @@ -8,7 +8,7 @@ import React, { Fragment } from 'react'; import { EuiFieldText } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { ErrableFormRow } from '../../../../../components/form_errors'; -import { JiraAction } from '../../../../../../../../common/types/action_types'; +import { JiraAction } from '../../../../../../../common/types/action_types'; interface Props { action: JiraAction; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/logging_action_fields.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/logging_action_fields.tsx similarity index 94% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/logging_action_fields.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/logging_action_fields.tsx index 7da2a22ecd6c45..17c69a7b05bb3c 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/logging_action_fields.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/logging_action_fields.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { EuiFieldText } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { ErrableFormRow } from '../../../../../components/form_errors'; -import { LoggingAction } from '../../../../../../../../common/types/action_types'; +import { LoggingAction } from '../../../../../../../common/types/action_types'; interface Props { action: LoggingAction; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/pagerduty_action_fields.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/pagerduty_action_fields.tsx similarity index 95% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/pagerduty_action_fields.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/pagerduty_action_fields.tsx index 3287bdefa08aa5..95215e8eac763d 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/pagerduty_action_fields.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/pagerduty_action_fields.tsx @@ -7,7 +7,7 @@ import React, { Fragment } from 'react'; import { EuiFieldText } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { ErrableFormRow } from '../../../../../components/form_errors'; -import { PagerDutyAction } from '../../../../../../../../common/types/action_types'; +import { PagerDutyAction } from '../../../../../../../common/types/action_types'; interface Props { action: PagerDutyAction; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/slack_action_fields.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/slack_action_fields.tsx similarity index 96% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/slack_action_fields.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/slack_action_fields.tsx index a72cf232d8d093..5e8aaf8415898a 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/slack_action_fields.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/slack_action_fields.tsx @@ -6,7 +6,7 @@ import React, { Fragment } from 'react'; import { EuiComboBox, EuiTextArea, EuiFormRow } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { SlackAction } from '../../../../../../../../common/types/action_types'; +import { SlackAction } from '../../../../../../../common/types/action_types'; interface Props { action: SlackAction; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/webhook_action_fields.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/webhook_action_fields.tsx similarity index 98% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/webhook_action_fields.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/webhook_action_fields.tsx index be0b551f4a39c8..c1ebcdc2628637 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/action_fields/webhook_action_fields.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/action_fields/webhook_action_fields.tsx @@ -18,7 +18,7 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { ErrableFormRow } from '../../../../../components/form_errors'; -import { WebhookAction } from '../../../../../../../../common/types/action_types'; +import { WebhookAction } from '../../../../../../../common/types/action_types'; interface Props { action: WebhookAction; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/index.ts b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/index.ts rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/index.ts diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_accordion.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_accordion.tsx similarity index 94% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_accordion.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_accordion.tsx index 4fca772a182175..36ca706ed1be2c 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_accordion.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_accordion.tsx @@ -21,13 +21,16 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { ExecuteDetails } from 'plugins/watcher/np_ready/application/models/execute_details/execute_details'; -import { Action } from 'plugins/watcher/np_ready/application/models/action'; -import { WatchHistoryItem } from 'plugins/watcher/np_ready/application/models/watch_history_item'; -import { ThresholdWatch } from 'plugins/watcher/np_ready/application/models/watch/threshold_watch'; -import { ActionType } from '../../../../../../../common/types/action_types'; -import { ACTION_TYPES, ACTION_MODES } from '../../../../../../../common/constants'; + +import { Action } from '../../../../models/action'; +import { WatchHistoryItem } from '../../../../models/watch_history_item'; +import { ThresholdWatch } from '../../../../models/watch/threshold_watch'; +import { ExecuteDetails } from '../../../../models/execute_details'; + +import { ActionType } from '../../../../../../common/types/action_types'; +import { ACTION_TYPES, ACTION_MODES } from '../../../../../../common/constants'; import { WatchContext } from '../../watch_context'; + import { WebhookActionFields, LoggingActionFields, diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_dropdown.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_dropdown.tsx similarity index 96% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_dropdown.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_dropdown.tsx index d92cccfa00f148..7a760ee58acbc9 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_dropdown.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_dropdown.tsx @@ -16,9 +16,10 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { useContext, useState } from 'react'; -import { Action } from 'plugins/watcher/np_ready/application/models/action'; import { FormattedMessage } from '@kbn/i18n/react'; -import { ACTION_TYPES } from '../../../../../../../common/constants'; + +import { Action } from '../../../../models/action'; +import { ACTION_TYPES } from '../../../../../../common/constants'; import { WatchContext } from '../../watch_context'; const disabledMessage = i18n.translate( diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_panel.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_panel.tsx similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_panel.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_action_panel.tsx diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_edit.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_edit.tsx similarity index 99% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_edit.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_edit.tsx index f1b5d2c9eab7b8..e3d729c33fddff 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_edit.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/threshold_watch_edit.tsx @@ -26,8 +26,8 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { TIME_UNITS } from '../../../../../../../common/constants'; -import { serializeThresholdWatch } from '../../../../../../../common/lib/serialization'; +import { TIME_UNITS } from '../../../../../../common/constants'; +import { serializeThresholdWatch } from '../../../../../../common/lib/serialization'; import { ErrableFormRow, SectionError, Error as ServerError } from '../../../../components'; import { fetchFields, getMatchingIndices, loadIndexPatterns } from '../../../../lib/api'; import { aggTypes } from '../../../../models/watch/agg_types'; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx similarity index 93% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx index 3901f84f506ef6..35d9efd36ad0fe 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/threshold_watch_edit/watch_visualization.tsx @@ -17,11 +17,12 @@ import { } from '@elastic/charts'; import dateMath from '@elastic/datemath'; import moment from 'moment-timezone'; -import { IUiSettingsClient } from 'src/core/public'; +import { IUiSettingsClient } from 'kibana/public'; import { EuiCallOut, EuiLoadingChart, EuiSpacer, EuiEmptyPrompt, EuiText } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import { VisualizeOptions } from 'plugins/watcher/np_ready/application/models/visualize_options'; -import { ThresholdWatch } from 'plugins/watcher/np_ready/application/models/watch/threshold_watch'; + +import { VisualizeOptions } from '../../../../models/visualize_options'; +import { ThresholdWatch } from '../../../../models/watch/threshold_watch'; import { useGetWatchVisualizationData } from '../../../../lib/api'; import { WatchContext } from '../../watch_context'; @@ -85,11 +86,7 @@ const getTimeBuckets = (watch: any, timeBuckets: any) => { }; export const WatchVisualization = () => { - const { - legacy: { TimeBuckets }, - euiUtils, - uiSettings, - } = useAppContext(); + const { createTimeBuckets, euiUtils, uiSettings } = useAppContext(); const { watch } = useContext(WatchContext); const chartsTheme = euiUtils.useChartsTheme(); const { @@ -109,7 +106,7 @@ export const WatchVisualization = () => { } = watch; const domain = getDomain(watch); - const timeBuckets = new TimeBuckets(); + const timeBuckets = createTimeBuckets(); timeBuckets.setBounds(domain); const interval = timeBuckets.getInterval().expression; const visualizeOptions = new VisualizeOptions({ @@ -196,8 +193,8 @@ export const WatchVisualization = () => { const actualThreshold = getThreshold(watch); let maxY = actualThreshold[actualThreshold.length - 1]; - (Object.values(watchVisualizationData) as number[][][]).forEach(data => { - data.forEach(([, y]) => { + (Object.values(watchVisualizationData) as number[][][]).forEach(watchData => { + watchData.forEach(([, y]) => { if (y > maxY) { maxY = y; } @@ -206,7 +203,7 @@ export const WatchVisualization = () => { const dateFormatter = (d: number) => { return moment(d) .tz(timezone) - .format(getTimeBuckets(watch, new TimeBuckets()).getScaledDateFormat()); + .format(getTimeBuckets(watch, createTimeBuckets()).getScaledDateFormat()); }; const aggLabel = aggTypes[watch.aggType].text; return ( diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/watch_edit.tsx b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/watch_edit.tsx similarity index 94% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/watch_edit.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_edit/components/watch_edit.tsx index 9f252d3e542e0e..59a6079d74b428 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/components/watch_edit.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/components/watch_edit.tsx @@ -10,10 +10,10 @@ import { isEqual } from 'lodash'; import { EuiPageContent } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { Watch } from 'plugins/watcher/np_ready/application/models/watch'; import { FormattedMessage } from '@kbn/i18n/react'; -import { WATCH_TYPES } from '../../../../../../common/constants'; -import { BaseWatch } from '../../../../../../common/types/watch_types'; +import { Watch } from '../../../models/watch'; +import { WATCH_TYPES } from '../../../../../common/constants'; +import { BaseWatch } from '../../../../../common/types/watch_types'; import { getPageErrorCode, PageError, SectionLoading, SectionError } from '../../../components'; import { loadWatch } from '../../../lib/api'; import { listBreadcrumb, editBreadcrumb, createBreadcrumb } from '../../../lib/breadcrumbs'; @@ -96,10 +96,7 @@ export const WatchEdit = ({ }; }) => { // hooks - const { - legacy: { MANAGEMENT_BREADCRUMB }, - chrome, - } = useAppContext(); + const { MANAGEMENT_BREADCRUMB, chrome } = useAppContext(); const [{ watch, loadError }, dispatch] = useReducer(watchReducer, { watch: null }); const setWatchProperty = (property: string, value: any) => { diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/watch_context.ts b/x-pack/plugins/watcher/public/application/sections/watch_edit/watch_context.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/watch_context.ts rename to x-pack/plugins/watcher/public/application/sections/watch_edit/watch_context.ts diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/watch_edit_actions.ts b/x-pack/plugins/watcher/public/application/sections/watch_edit/watch_edit_actions.ts similarity index 95% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/watch_edit_actions.ts rename to x-pack/plugins/watcher/public/application/sections/watch_edit/watch_edit_actions.ts index b93c2c510047db..ba2a3a7ce84e50 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_edit/watch_edit_actions.ts +++ b/x-pack/plugins/watcher/public/application/sections/watch_edit/watch_edit_actions.ts @@ -4,11 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { ToastsSetup } from 'src/core/public'; +import { ToastsSetup } from 'kibana/public'; import { i18n } from '@kbn/i18n'; import { get } from 'lodash'; -import { ACTION_TYPES, WATCH_TYPES } from '../../../../../common/constants'; -import { BaseWatch } from '../../../../../common/types/watch_types'; +import { ACTION_TYPES, WATCH_TYPES } from '../../../../common/constants'; +import { BaseWatch } from '../../../../common/types/watch_types'; import { createWatch } from '../../lib/api'; import { goToWatchList } from '../../lib/navigation'; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_list/components/watch_list.tsx b/x-pack/plugins/watcher/public/application/sections/watch_list/components/watch_list.tsx similarity index 99% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_list/components/watch_list.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_list/components/watch_list.tsx index 5165915aa84065..9f6a8ddbc843e8 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_list/components/watch_list.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_list/components/watch_list.tsx @@ -28,7 +28,7 @@ import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { Moment } from 'moment'; -import { REFRESH_INTERVALS, PAGINATION, WATCH_TYPES } from '../../../../../../common/constants'; +import { REFRESH_INTERVALS, PAGINATION, WATCH_TYPES } from '../../../../../common/constants'; import { listBreadcrumb } from '../../../lib/breadcrumbs'; import { getPageErrorCode, @@ -47,7 +47,7 @@ export const WatchList = () => { // hooks const { chrome, - legacy: { MANAGEMENT_BREADCRUMB }, + MANAGEMENT_BREADCRUMB, links: { watcherGettingStartedUrl }, } = useAppContext(); const [selection, setSelection] = useState([]); diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_detail.tsx b/x-pack/plugins/watcher/public/application/sections/watch_status/components/watch_detail.tsx similarity index 99% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_detail.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_status/components/watch_detail.tsx index 197342bba4180c..ce52114fd5fdfd 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_detail.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_status/components/watch_detail.tsx @@ -20,7 +20,7 @@ import { } from '@elastic/eui'; import { ackWatchAction } from '../../../lib/api'; import { WatchStatus } from '../../../components'; -import { PAGINATION } from '../../../../../../common/constants'; +import { PAGINATION } from '../../../../../common/constants'; import { WatchDetailsContext } from '../watch_details_context'; import { useAppContext } from '../../../app_context'; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_history.tsx b/x-pack/plugins/watcher/public/application/sections/watch_status/components/watch_history.tsx similarity index 99% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_history.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_status/components/watch_history.tsx index 16897d74665ef7..b78a2e4230171f 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_history.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_status/components/watch_history.tsx @@ -23,7 +23,7 @@ import { EuiTitle, } from '@elastic/eui'; -import { PAGINATION } from '../../../../../../common/constants'; +import { PAGINATION } from '../../../../../common/constants'; import { WatchStatus, SectionError, Error } from '../../../components'; import { useLoadWatchHistory, useLoadWatchHistoryDetail } from '../../../lib/api'; import { WatchDetailsContext } from '../watch_details_context'; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_status.tsx b/x-pack/plugins/watcher/public/application/sections/watch_status/components/watch_status.tsx similarity index 98% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_status.tsx rename to x-pack/plugins/watcher/public/application/sections/watch_status/components/watch_status.tsx index 53817c23e72eb7..b15c047d06f67c 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/components/watch_status.tsx +++ b/x-pack/plugins/watcher/public/application/sections/watch_status/components/watch_status.tsx @@ -67,11 +67,7 @@ export const WatchStatus = ({ }; }; }) => { - const { - chrome, - legacy: { MANAGEMENT_BREADCRUMB }, - toasts, - } = useAppContext(); + const { chrome, MANAGEMENT_BREADCRUMB, toasts } = useAppContext(); const { error: watchDetailError, data: watchDetail, diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/watch_details_context.ts b/x-pack/plugins/watcher/public/application/sections/watch_status/watch_details_context.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/sections/watch_status/watch_details_context.ts rename to x-pack/plugins/watcher/public/application/sections/watch_status/watch_details_context.ts diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/application/shared_imports.ts b/x-pack/plugins/watcher/public/application/shared_imports.ts similarity index 79% rename from x-pack/legacy/plugins/watcher/public/np_ready/application/shared_imports.ts rename to x-pack/plugins/watcher/public/application/shared_imports.ts index 60445b00c09858..cbc4dde7448ff0 100644 --- a/x-pack/legacy/plugins/watcher/public/np_ready/application/shared_imports.ts +++ b/x-pack/plugins/watcher/public/application/shared_imports.ts @@ -10,4 +10,4 @@ export { UseRequestConfig, sendRequest, useRequest, -} from '../../../../../../../src/plugins/es_ui_shared/public/request/np_ready_request'; +} from '../../../../../src/plugins/es_ui_shared/public/request/np_ready_request'; diff --git a/x-pack/legacy/plugins/watcher/public/np_ready/index.ts b/x-pack/plugins/watcher/public/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/public/np_ready/index.ts rename to x-pack/plugins/watcher/public/index.ts diff --git a/x-pack/plugins/watcher/public/legacy/calc_auto_interval.ts b/x-pack/plugins/watcher/public/legacy/calc_auto_interval.ts new file mode 100644 index 00000000000000..c910f1e6752d4a --- /dev/null +++ b/x-pack/plugins/watcher/public/legacy/calc_auto_interval.ts @@ -0,0 +1,132 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import moment from 'moment'; + +const boundsDescending = [ + { + bound: Infinity, + interval: Number(moment.duration(1, 'year')), + }, + { + bound: Number(moment.duration(1, 'year')), + interval: Number(moment.duration(1, 'month')), + }, + { + bound: Number(moment.duration(3, 'week')), + interval: Number(moment.duration(1, 'week')), + }, + { + bound: Number(moment.duration(1, 'week')), + interval: Number(moment.duration(1, 'd')), + }, + { + bound: Number(moment.duration(24, 'hour')), + interval: Number(moment.duration(12, 'hour')), + }, + { + bound: Number(moment.duration(6, 'hour')), + interval: Number(moment.duration(3, 'hour')), + }, + { + bound: Number(moment.duration(2, 'hour')), + interval: Number(moment.duration(1, 'hour')), + }, + { + bound: Number(moment.duration(45, 'minute')), + interval: Number(moment.duration(30, 'minute')), + }, + { + bound: Number(moment.duration(20, 'minute')), + interval: Number(moment.duration(10, 'minute')), + }, + { + bound: Number(moment.duration(9, 'minute')), + interval: Number(moment.duration(5, 'minute')), + }, + { + bound: Number(moment.duration(3, 'minute')), + interval: Number(moment.duration(1, 'minute')), + }, + { + bound: Number(moment.duration(45, 'second')), + interval: Number(moment.duration(30, 'second')), + }, + { + bound: Number(moment.duration(15, 'second')), + interval: Number(moment.duration(10, 'second')), + }, + { + bound: Number(moment.duration(7.5, 'second')), + interval: Number(moment.duration(5, 'second')), + }, + { + bound: Number(moment.duration(5, 'second')), + interval: Number(moment.duration(1, 'second')), + }, + { + bound: Number(moment.duration(500, 'ms')), + interval: Number(moment.duration(100, 'ms')), + }, +]; + +function getPerBucketMs(count: number, duration: number) { + const ms = duration / count; + return isFinite(ms) ? ms : NaN; +} + +function normalizeMinimumInterval(targetMs: number) { + const value = isNaN(targetMs) ? 0 : Math.max(Math.floor(targetMs), 1); + return moment.duration(value); +} + +/** + * Using some simple rules we pick a "pretty" interval that will + * produce around the number of buckets desired given a time range. + * + * @param targetBucketCount desired number of buckets + * @param duration time range the agg covers + */ +export function calcAutoIntervalNear(targetBucketCount: number, duration: number) { + const targetPerBucketMs = getPerBucketMs(targetBucketCount, duration); + + // Find the first bound which is smaller than our target. + const lowerBoundIndex = boundsDescending.findIndex(({ bound }) => { + const boundMs = Number(bound); + return boundMs <= targetPerBucketMs; + }); + + // The bound immediately preceeding that lower bound contains the + // interval most closely matching our target. + if (lowerBoundIndex !== -1) { + const nearestInterval = boundsDescending[lowerBoundIndex - 1].interval; + return moment.duration(nearestInterval); + } + + // If the target is smaller than any of our bounds, then we'll use it for the interval as-is. + return normalizeMinimumInterval(targetPerBucketMs); +} + +/** + * Pick a "pretty" interval that produces no more than the maxBucketCount + * for the given time range. + * + * @param maxBucketCount maximum number of buckets to create + * @param duration amount of time covered by the agg + */ +export function calcAutoIntervalLessThan(maxBucketCount: number, duration: number) { + const maxPerBucketMs = getPerBucketMs(maxBucketCount, duration); + + for (const { interval } of boundsDescending) { + // Find the highest interval which meets our per bucket limitation. + if (interval <= maxPerBucketMs) { + return moment.duration(interval); + } + } + + // If the max is smaller than any of our intervals, then we'll use it for the interval as-is. + return normalizeMinimumInterval(maxPerBucketMs); +} diff --git a/x-pack/plugins/watcher/public/legacy/calc_es_interval.js b/x-pack/plugins/watcher/public/legacy/calc_es_interval.js new file mode 100644 index 00000000000000..234fb67772fef8 --- /dev/null +++ b/x-pack/plugins/watcher/public/legacy/calc_es_interval.js @@ -0,0 +1,58 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import dateMath from '@elastic/datemath'; + +import { parseEsInterval } from './index'; + +const unitsDesc = dateMath.unitsDesc; +const largeMax = unitsDesc.indexOf('M'); + +/** + * Convert a moment.duration into an es + * compatible expression, and provide + * associated metadata + * + * @param {moment.duration} duration + * @return {object} + */ +export function convertDurationToNormalizedEsInterval(duration) { + for (let i = 0; i < unitsDesc.length; i++) { + const unit = unitsDesc[i]; + const val = duration.as(unit); + // find a unit that rounds neatly + if (val >= 1 && Math.floor(val) === val) { + // if the unit is "large", like years, but + // isn't set to 1 ES will puke. So keep going until + // we get out of the "large" units + if (i <= largeMax && val !== 1) { + continue; + } + + return { + value: val, + unit: unit, + expression: val + unit, + }; + } + } + + const ms = duration.as('ms'); + return { + value: ms, + unit: 'ms', + expression: ms + 'ms', + }; +} + +export function convertIntervalToEsInterval(interval) { + const { value, unit } = parseEsInterval(interval); + return { + value, + unit, + expression: interval, + }; +} diff --git a/x-pack/plugins/watcher/public/legacy/index.d.ts b/x-pack/plugins/watcher/public/legacy/index.d.ts new file mode 100644 index 00000000000000..307e365040fb7d --- /dev/null +++ b/x-pack/plugins/watcher/public/legacy/index.d.ts @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export declare const MANAGEMENT_BREADCRUMB: { text: string; href?: string }; diff --git a/x-pack/plugins/watcher/public/legacy/index.ts b/x-pack/plugins/watcher/public/legacy/index.ts new file mode 100644 index 00000000000000..d14081a667acc4 --- /dev/null +++ b/x-pack/plugins/watcher/public/legacy/index.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { i18n } from '@kbn/i18n'; + +export { TimeBuckets } from './time_buckets'; + +export const MANAGEMENT_BREADCRUMB = Object.freeze({ + text: i18n.translate('xpack.watcher.management.breadcrumb', { + defaultMessage: 'Management', + }), + href: '#/management', +}); diff --git a/x-pack/plugins/watcher/public/legacy/parse_es_interval/index.ts b/x-pack/plugins/watcher/public/legacy/parse_es_interval/index.ts new file mode 100644 index 00000000000000..6c8e29211078c5 --- /dev/null +++ b/x-pack/plugins/watcher/public/legacy/parse_es_interval/index.ts @@ -0,0 +1,10 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export { parseEsInterval, ParsedInterval } from './parse_es_interval'; +export { InvalidEsCalendarIntervalError } from './invalid_es_calendar_interval_error'; +export { InvalidEsIntervalFormatError } from './invalid_es_interval_format_error'; +export { isValidEsInterval } from './is_valid_es_interval'; diff --git a/x-pack/plugins/watcher/public/legacy/parse_es_interval/invalid_es_calendar_interval_error.ts b/x-pack/plugins/watcher/public/legacy/parse_es_interval/invalid_es_calendar_interval_error.ts new file mode 100644 index 00000000000000..62864c91756c48 --- /dev/null +++ b/x-pack/plugins/watcher/public/legacy/parse_es_interval/invalid_es_calendar_interval_error.ts @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { Unit } from '@elastic/datemath'; +import { i18n } from '@kbn/i18n'; + +export class InvalidEsCalendarIntervalError extends Error { + constructor( + public readonly interval: string, + public readonly value: number, + public readonly unit: Unit, + public readonly type: string + ) { + super( + i18n.translate('xpack.watcher.data.parseEsInterval.invalidEsCalendarIntervalErrorMessage', { + defaultMessage: 'Invalid calendar interval: {interval}, value must be 1', + values: { interval }, + }) + ); + + this.name = 'InvalidEsCalendarIntervalError'; + this.value = value; + this.unit = unit; + this.type = type; + + // captureStackTrace is only available in the V8 engine, so any browser using + // a different JS engine won't have access to this method. + if (Error.captureStackTrace) { + Error.captureStackTrace(this, InvalidEsCalendarIntervalError); + } + + // Babel doesn't support traditional `extends` syntax for built-in classes. + // https://babeljs.io/docs/en/caveats/#classes + Object.setPrototypeOf(this, InvalidEsCalendarIntervalError.prototype); + } +} diff --git a/x-pack/plugins/watcher/public/legacy/parse_es_interval/invalid_es_interval_format_error.ts b/x-pack/plugins/watcher/public/legacy/parse_es_interval/invalid_es_interval_format_error.ts new file mode 100644 index 00000000000000..894a4fd5d69224 --- /dev/null +++ b/x-pack/plugins/watcher/public/legacy/parse_es_interval/invalid_es_interval_format_error.ts @@ -0,0 +1,30 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; + +export class InvalidEsIntervalFormatError extends Error { + constructor(public readonly interval: string) { + super( + i18n.translate('xpack.watcher.data.parseEsInterval.invalidEsIntervalFormatErrorMessage', { + defaultMessage: 'Invalid interval format: {interval}', + values: { interval }, + }) + ); + + this.name = 'InvalidEsIntervalFormatError'; + + // captureStackTrace is only available in the V8 engine, so any browser using + // a different JS engine won't have access to this method. + if (Error.captureStackTrace) { + Error.captureStackTrace(this, InvalidEsIntervalFormatError); + } + + // Babel doesn't support traditional `extends` syntax for built-in classes. + // https://babeljs.io/docs/en/caveats/#classes + Object.setPrototypeOf(this, InvalidEsIntervalFormatError.prototype); + } +} diff --git a/x-pack/plugins/watcher/public/legacy/parse_es_interval/is_valid_es_interval.ts b/x-pack/plugins/watcher/public/legacy/parse_es_interval/is_valid_es_interval.ts new file mode 100644 index 00000000000000..1bdb65740409a2 --- /dev/null +++ b/x-pack/plugins/watcher/public/legacy/parse_es_interval/is_valid_es_interval.ts @@ -0,0 +1,25 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { parseEsInterval } from './parse_es_interval'; + +/** + * Checks whether a given interval string (e.g. 1w, 24h, ...) is a valid Elasticsearch interval. + * Will return false if the interval is not valid in Elasticsearch, otherwise true. + * Invalid intervals might be: 2f, since there is no unit 'f'; 2w, since weeks and month intervals + * are only allowed with a value of 1, etc. + * + * @param interval The interval string like 1w, 24h + * @returns True if the interval is valid for Elasticsearch + */ +export function isValidEsInterval(interval: string): boolean { + try { + parseEsInterval(interval); + return true; + } catch { + return false; + } +} diff --git a/x-pack/plugins/watcher/public/legacy/parse_es_interval/parse_es_interval.test.ts b/x-pack/plugins/watcher/public/legacy/parse_es_interval/parse_es_interval.test.ts new file mode 100644 index 00000000000000..76de807101559b --- /dev/null +++ b/x-pack/plugins/watcher/public/legacy/parse_es_interval/parse_es_interval.test.ts @@ -0,0 +1,56 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { InvalidEsCalendarIntervalError } from './invalid_es_calendar_interval_error'; +import { InvalidEsIntervalFormatError } from './invalid_es_interval_format_error'; +import { parseEsInterval } from './parse_es_interval'; + +describe('parseEsInterval', () => { + it('should correctly parse an interval containing unit and single value', () => { + expect(parseEsInterval('1ms')).toEqual({ value: 1, unit: 'ms', type: 'fixed' }); + expect(parseEsInterval('1s')).toEqual({ value: 1, unit: 's', type: 'fixed' }); + expect(parseEsInterval('1m')).toEqual({ value: 1, unit: 'm', type: 'calendar' }); + expect(parseEsInterval('1h')).toEqual({ value: 1, unit: 'h', type: 'calendar' }); + expect(parseEsInterval('1d')).toEqual({ value: 1, unit: 'd', type: 'calendar' }); + expect(parseEsInterval('1w')).toEqual({ value: 1, unit: 'w', type: 'calendar' }); + expect(parseEsInterval('1M')).toEqual({ value: 1, unit: 'M', type: 'calendar' }); + expect(parseEsInterval('1y')).toEqual({ value: 1, unit: 'y', type: 'calendar' }); + }); + + it('should correctly parse an interval containing unit and multiple value', () => { + expect(parseEsInterval('250ms')).toEqual({ value: 250, unit: 'ms', type: 'fixed' }); + expect(parseEsInterval('90s')).toEqual({ value: 90, unit: 's', type: 'fixed' }); + expect(parseEsInterval('60m')).toEqual({ value: 60, unit: 'm', type: 'fixed' }); + expect(parseEsInterval('12h')).toEqual({ value: 12, unit: 'h', type: 'fixed' }); + expect(parseEsInterval('7d')).toEqual({ value: 7, unit: 'd', type: 'fixed' }); + }); + + it('should throw a InvalidEsCalendarIntervalError for intervals containing calendar unit and multiple value', () => { + const intervals = ['4w', '12M', '10y']; + expect.assertions(intervals.length); + + intervals.forEach(interval => { + try { + parseEsInterval(interval); + } catch (error) { + expect(error instanceof InvalidEsCalendarIntervalError).toBe(true); + } + }); + }); + + it('should throw a InvalidEsIntervalFormatError for invalid interval formats', () => { + const intervals = ['1', 'h', '0m', '0.5h']; + expect.assertions(intervals.length); + + intervals.forEach(interval => { + try { + parseEsInterval(interval); + } catch (error) { + expect(error instanceof InvalidEsIntervalFormatError).toBe(true); + } + }); + }); +}); diff --git a/x-pack/plugins/watcher/public/legacy/parse_es_interval/parse_es_interval.ts b/x-pack/plugins/watcher/public/legacy/parse_es_interval/parse_es_interval.ts new file mode 100644 index 00000000000000..19ac03da034111 --- /dev/null +++ b/x-pack/plugins/watcher/public/legacy/parse_es_interval/parse_es_interval.ts @@ -0,0 +1,62 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import dateMath, { Unit } from '@elastic/datemath'; + +import { InvalidEsCalendarIntervalError } from './invalid_es_calendar_interval_error'; +import { InvalidEsIntervalFormatError } from './invalid_es_interval_format_error'; + +const ES_INTERVAL_STRING_REGEX = new RegExp( + '^([1-9][0-9]*)\\s*(' + dateMath.units.join('|') + ')$' +); + +export type ParsedInterval = ReturnType; + +/** + * Extracts interval properties from an ES interval string. Disallows unrecognized interval formats + * and fractional values. Converts some intervals from "calendar" to "fixed" when the number of + * units is larger than 1, and throws an error for others. + * + * Conversion rules: + * + * | Interval | Single unit type | Multiple units type | + * | -------- | ---------------- | ------------------- | + * | ms | fixed | fixed | + * | s | fixed | fixed | + * | m | calendar | fixed | + * | h | calendar | fixed | + * | d | calendar | fixed | + * | w | calendar | N/A - disallowed | + * | M | calendar | N/A - disallowed | + * | y | calendar | N/A - disallowed | + * + */ +export function parseEsInterval(interval: string) { + const matches = String(interval) + .trim() + .match(ES_INTERVAL_STRING_REGEX); + + if (!matches) { + throw new InvalidEsIntervalFormatError(interval); + } + + const value = parseFloat(matches[1]); + const unit = matches[2] as Unit; + const type = dateMath.unitsMap[unit].type; + + if (type === 'calendar' && value !== 1) { + throw new InvalidEsCalendarIntervalError(interval, value, unit, type); + } + + return { + value, + unit, + type: + (type === 'mixed' && value === 1) || type === 'calendar' + ? ('calendar' as 'calendar') + : ('fixed' as 'fixed'), + }; +} diff --git a/x-pack/plugins/watcher/public/legacy/time_buckets.d.ts b/x-pack/plugins/watcher/public/legacy/time_buckets.d.ts new file mode 100644 index 00000000000000..e84051b0863443 --- /dev/null +++ b/x-pack/plugins/watcher/public/legacy/time_buckets.d.ts @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export declare const TimeBuckets: any; diff --git a/x-pack/plugins/watcher/public/legacy/time_buckets.js b/x-pack/plugins/watcher/public/legacy/time_buckets.js new file mode 100644 index 00000000000000..8b7e4be784fe72 --- /dev/null +++ b/x-pack/plugins/watcher/public/legacy/time_buckets.js @@ -0,0 +1,397 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import _ from 'lodash'; +import moment from 'moment'; +import { parseInterval, FIELD_FORMAT_IDS } from '../../../../../src/plugins/data/public'; +import { calcAutoIntervalLessThan, calcAutoIntervalNear } from './calc_auto_interval'; +import { + convertDurationToNormalizedEsInterval, + convertIntervalToEsInterval, +} from './calc_es_interval'; + +function isValidMoment(m) { + return m && 'isValid' in m && m.isValid(); +} + +/** + * Helper class for wrapping the concept of an "Interval", + * which describes a timespan that will separate moments. + * + * @param {state} object - one of "" + * @param {[type]} display [description] + */ +function TimeBuckets(uiSettings, data) { + this.data = data; + this.getConfig = (...args) => uiSettings.get(...args); + return TimeBuckets.__cached__(this); +} + +/**** + * PUBLIC API + ****/ + +/** + * Set the bounds that these buckets are expected to cover. + * This is required to support interval "auto" as well + * as interval scaling. + * + * @param {object} input - an object with properties min and max, + * representing the edges for the time span + * we should cover + * + * @returns {undefined} + */ +TimeBuckets.prototype.setBounds = function(input) { + if (!input) return this.clearBounds(); + + let bounds; + if (_.isPlainObject(input)) { + // accept the response from timefilter.getActiveBounds() + bounds = [input.min, input.max]; + } else { + bounds = Array.isArray(input) ? input : []; + } + + const moments = _(bounds) + .map(_.ary(moment, 1)) + .sortBy(Number); + + const valid = moments.size() === 2 && moments.every(isValidMoment); + if (!valid) { + this.clearBounds(); + throw new Error('invalid bounds set: ' + input); + } + + this._lb = moments.shift(); + this._ub = moments.pop(); + if (this.getDuration().asSeconds() < 0) { + throw new TypeError('Intervals must be positive'); + } +}; + +/** + * Clear the stored bounds + * + * @return {undefined} + */ +TimeBuckets.prototype.clearBounds = function() { + this._lb = this._ub = null; +}; + +/** + * Check to see if we have received bounds yet + * + * @return {Boolean} + */ +TimeBuckets.prototype.hasBounds = function() { + return isValidMoment(this._ub) && isValidMoment(this._lb); +}; + +/** + * Return the current bounds, if we have any. + * + * THIS DOES NOT CLONE THE BOUNDS, so editing them + * may have unexpected side-effects. Always + * call bounds.min.clone() before editing + * + * @return {object|undefined} - If bounds are not defined, this + * returns undefined, else it returns the bounds + * for these buckets. This object has two props, + * min and max. Each property will be a moment() + * object + * + */ +TimeBuckets.prototype.getBounds = function() { + if (!this.hasBounds()) return; + return { + min: this._lb, + max: this._ub, + }; +}; + +/** + * Get a moment duration object representing + * the distance between the bounds, if the bounds + * are set. + * + * @return {moment.duration|undefined} + */ +TimeBuckets.prototype.getDuration = function() { + if (!this.hasBounds()) return; + return moment.duration(this._ub - this._lb, 'ms'); +}; + +/** + * Update the interval at which buckets should be + * generated. + * + * Input can be one of the following: + * - Any object from src/legacy/ui/agg_types/buckets/_interval_options.js + * - "auto" + * - Pass a valid moment unit + * - a moment.duration object. + * + * @param {object|string|moment.duration} input - see desc + */ +TimeBuckets.prototype.setInterval = function(input) { + // Preserve the original units because they're lost when the interval is converted to a + // moment duration object. + this.originalInterval = input; + + let interval = input; + + // selection object -> val + if (_.isObject(input)) { + interval = input.val; + } + + if (!interval || interval === 'auto') { + this._i = 'auto'; + return; + } + + if (_.isString(interval)) { + input = interval; + interval = parseInterval(interval); + if (+interval === 0) { + interval = null; + } + } + + // if the value wasn't converted to a duration, and isn't + // already a duration, we have a problem + if (!moment.isDuration(interval)) { + throw new TypeError('"' + input + '" is not a valid interval.'); + } + + this._i = interval; +}; + +/** + * Get the interval for the buckets. If the + * number of buckets created by the interval set + * is larger than config:histogram:maxBars then the + * interval will be scaled up. If the number of buckets + * created is less than one, the interval is scaled back. + * + * The interval object returned is a moment.duration + * object that has been decorated with the following + * properties. + * + * interval.description: a text description of the interval. + * designed to be used list "field per {{ desc }}". + * - "minute" + * - "10 days" + * - "3 years" + * + * interval.expr: the elasticsearch expression that creates this + * interval. If the interval does not properly form an elasticsearch + * expression it will be forced into one. + * + * interval.scaled: the interval was adjusted to + * accommodate the maxBars setting. + * + * interval.scale: the number that y-values should be + * multiplied by + * + * interval.scaleDescription: a description that reflects + * the values which will be produced by using the + * interval.scale. + * + * + * @return {[type]} [description] + */ +TimeBuckets.prototype.getInterval = function(useNormalizedEsInterval = true) { + const self = this; + const duration = self.getDuration(); + const parsedInterval = readInterval(); + + if (useNormalizedEsInterval) { + return decorateInterval(maybeScaleInterval(parsedInterval)); + } else { + return decorateInterval(parsedInterval); + } + + // either pull the interval from state or calculate the auto-interval + function readInterval() { + const interval = self._i; + if (moment.isDuration(interval)) return interval; + return calcAutoIntervalNear(self.getConfig('histogram:barTarget'), Number(duration)); + } + + // check to see if the interval should be scaled, and scale it if so + function maybeScaleInterval(interval) { + if (!self.hasBounds()) return interval; + + const maxLength = self.getConfig('histogram:maxBars'); + const approxLen = duration / interval; + let scaled; + + if (approxLen > maxLength) { + scaled = calcAutoIntervalLessThan(maxLength, Number(duration)); + } else { + return interval; + } + + if (+scaled === +interval) return interval; + + decorateInterval(interval); + return _.assign(scaled, { + preScaled: interval, + scale: interval / scaled, + scaled: true, + }); + } + + // append some TimeBuckets specific props to the interval + function decorateInterval(interval) { + const esInterval = useNormalizedEsInterval + ? convertDurationToNormalizedEsInterval(interval) + : convertIntervalToEsInterval(self.originalInterval); + interval.esValue = esInterval.value; + interval.esUnit = esInterval.unit; + interval.expression = esInterval.expression; + interval.overflow = duration > interval ? moment.duration(interval - duration) : false; + + const prettyUnits = moment.normalizeUnits(esInterval.unit); + if (esInterval.value === 1) { + interval.description = prettyUnits; + } else { + interval.description = esInterval.value + ' ' + prettyUnits + 's'; + } + + return interval; + } +}; + +/** + * Get a date format string that will represent dates that + * progress at our interval. + * + * Since our interval can be as small as 1ms, the default + * date format is usually way too much. with `dateFormat:scaled` + * users can modify how dates are formatted within series + * produced by TimeBuckets + * + * @return {string} + */ +TimeBuckets.prototype.getScaledDateFormat = function() { + const interval = this.getInterval(); + const rules = this.getConfig('dateFormat:scaled'); + + for (let i = rules.length - 1; i >= 0; i--) { + const rule = rules[i]; + if (!rule[0] || interval >= moment.duration(rule[0])) { + return rule[1]; + } + } + + return this.getConfig('dateFormat'); +}; + +TimeBuckets.prototype.getScaledDateFormatter = function() { + const fieldFormats = this.data.fieldFormats; + const DateFieldFormat = fieldFormats.getType(FIELD_FORMAT_IDS.DATE); + + return new DateFieldFormat( + { + pattern: this.getScaledDateFormat(), + }, + this.getConfig.bind(this) + ); +}; + +TimeBuckets.__cached__ = function(self) { + let cache = {}; + const sameMoment = same(moment.isMoment); + const sameDuration = same(moment.isDuration); + + const desc = { + __cached__: { + value: self, + }, + }; + + const breakers = { + setBounds: 'bounds', + clearBounds: 'bounds', + setInterval: 'interval', + }; + + const resources = { + bounds: { + setup: function() { + return [self._lb, self._ub]; + }, + changes: function(prev) { + return !sameMoment(prev[0], self._lb) || !sameMoment(prev[1], self._ub); + }, + }, + interval: { + setup: function() { + return self._i; + }, + changes: function(prev) { + return !sameDuration(prev, this._i); + }, + }, + }; + + function cachedGetter(prop) { + return { + value: function cachedGetter(...rest) { + if (cache.hasOwnProperty(prop)) { + return cache[prop]; + } + + return (cache[prop] = self[prop](...rest)); + }, + }; + } + + function cacheBreaker(prop) { + const resource = resources[breakers[prop]]; + const setup = resource.setup; + const changes = resource.changes; + const fn = self[prop]; + + return { + value: function cacheBreaker() { + const prev = setup.call(self); + const ret = fn.apply(self, arguments); + + if (changes.call(self, prev)) { + cache = {}; + } + + return ret; + }, + }; + } + + function same(checkType) { + return function(a, b) { + if (a === b) return true; + if (checkType(a) === checkType(b)) return +a === +b; + return false; + }; + } + + _.forOwn(TimeBuckets.prototype, function(fn, prop) { + if (prop[0] === '_') return; + + if (breakers.hasOwnProperty(prop)) { + desc[prop] = cacheBreaker(prop); + } else { + desc[prop] = cachedGetter(prop); + } + }); + + return Object.create(self, desc); +}; + +export { TimeBuckets }; diff --git a/x-pack/plugins/watcher/public/plugin.ts b/x-pack/plugins/watcher/public/plugin.ts new file mode 100644 index 00000000000000..d59041b41253d6 --- /dev/null +++ b/x-pack/plugins/watcher/public/plugin.ts @@ -0,0 +1,89 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { i18n } from '@kbn/i18n'; +import { CoreSetup, Plugin, CoreStart } from 'kibana/public'; + +import { FeatureCatalogueCategory } from '../../../../src/plugins/home/public'; + +import { LicenseStatus } from '../common/types/license_status'; + +import { LICENSE_CHECK_STATE } from '../../licensing/public'; +import { TimeBuckets, MANAGEMENT_BREADCRUMB } from './legacy'; +import { PLUGIN } from '../common/constants'; +import { Dependencies } from './types'; + +export class WatcherUIPlugin implements Plugin { + // Reference for when `mount` gets called, we don't want to render if + // we don't have a valid license. Under certain conditions the Watcher app link + // may still be present so this is a final guard. + private licenseStatus: LicenseStatus = { valid: false }; + private hasRegisteredESManagementSection = false; + + setup( + { application, notifications, http, uiSettings, getStartServices }: CoreSetup, + { licensing, management, data, home }: Dependencies + ) { + licensing.license$.subscribe(license => { + const { state, message } = license.check(PLUGIN.ID, PLUGIN.MINIMUM_LICENSE_REQUIRED); + this.licenseStatus = { + valid: state === LICENSE_CHECK_STATE.Valid && license.getFeature(PLUGIN.ID).isAvailable, + message, + }; + if (this.licenseStatus.valid) { + const esSection = management.sections.getSection('elasticsearch'); + if (esSection && !this.hasRegisteredESManagementSection) { + esSection.registerApp({ + id: 'watcher', + title: i18n.translate( + 'xpack.watcher.sections.watchList.managementSection.watcherDisplayName', + { defaultMessage: 'Watcher' } + ), + mount: async ({ element }) => { + const [core, plugins] = await getStartServices(); + const { chrome, i18n: i18nDep, docLinks, savedObjects } = core; + const { eui_utils } = plugins as any; + const { boot } = await import('./application/boot'); + + return boot({ + getLicenseStatus: () => this.licenseStatus, + element, + toasts: notifications.toasts, + http, + uiSettings, + docLinks, + chrome, + euiUtils: eui_utils, + savedObjects: savedObjects.client, + I18nContext: i18nDep.Context, + createTimeBuckets: () => new TimeBuckets(uiSettings, data), + MANAGEMENT_BREADCRUMB, + }); + }, + }); + + home.featureCatalogue.register({ + id: 'watcher', + title: 'Watcher', // This is a product name so we don't translate it. + category: FeatureCatalogueCategory.ADMIN, + description: i18n.translate('xpack.watcher.watcherDescription', { + defaultMessage: + 'Detect changes in your data by creating, managing, and monitoring alerts.', + }), + icon: 'watchesApp', + path: '/app/kibana#/management/elasticsearch/watcher/watches', + showOnHomePage: true, + }); + + this.hasRegisteredESManagementSection = true; + } + } + }); + } + + start(core: CoreStart) {} + + stop() {} +} diff --git a/x-pack/plugins/watcher/public/types.ts b/x-pack/plugins/watcher/public/types.ts new file mode 100644 index 00000000000000..930185051514a9 --- /dev/null +++ b/x-pack/plugins/watcher/public/types.ts @@ -0,0 +1,19 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ManagementSetup } from 'src/plugins/management/public'; +import { EuiUtilsStart } from 'src/plugins/eui_utils/public'; +import { LicensingPluginSetup } from '../../licensing/public'; +import { DataPublicPluginSetup } from '../../../../src/plugins/data/public'; +import { HomePublicPluginSetup } from '../../../../src/plugins/home/public'; + +export interface Dependencies { + home: HomePublicPluginSetup; + management: ManagementSetup; + licensing: LicensingPluginSetup; + eui_utils: EuiUtilsStart; + data: DataPublicPluginSetup; +} diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/index.ts b/x-pack/plugins/watcher/server/index.ts similarity index 81% rename from x-pack/legacy/plugins/watcher/server/np_ready/index.ts rename to x-pack/plugins/watcher/server/index.ts index 3f5e1a91209ead..51eb7bfa543fe1 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/index.ts +++ b/x-pack/plugins/watcher/server/index.ts @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { PluginInitializerContext } from 'src/core/server'; +import { PluginInitializerContext } from 'kibana/server'; import { WatcherServerPlugin } from './plugin'; -export const plugin = (ctx: PluginInitializerContext) => new WatcherServerPlugin(); +export const plugin = (ctx: PluginInitializerContext) => new WatcherServerPlugin(ctx); diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/lib/call_with_request_factory.ts b/x-pack/plugins/watcher/server/lib/call_with_request_factory.ts similarity index 93% rename from x-pack/legacy/plugins/watcher/server/np_ready/lib/call_with_request_factory.ts rename to x-pack/plugins/watcher/server/lib/call_with_request_factory.ts index eaec9cd91b23cd..4884c75436c246 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/lib/call_with_request_factory.ts +++ b/x-pack/plugins/watcher/server/lib/call_with_request_factory.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { ElasticsearchServiceSetup } from 'src/core/server'; +import { ElasticsearchServiceSetup } from 'kibana/server'; import { once } from 'lodash'; import { elasticsearchJsPlugin } from './elasticsearch_js_plugin'; diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/lib/elasticsearch_js_plugin.ts b/x-pack/plugins/watcher/server/lib/elasticsearch_js_plugin.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/lib/elasticsearch_js_plugin.ts rename to x-pack/plugins/watcher/server/lib/elasticsearch_js_plugin.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/lib/fetch_all_from_scroll/__tests__/fetch_all_from_scroll.js b/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/__tests__/fetch_all_from_scroll.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/lib/fetch_all_from_scroll/__tests__/fetch_all_from_scroll.js rename to x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/__tests__/fetch_all_from_scroll.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts b/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts similarity index 92% rename from x-pack/legacy/plugins/watcher/server/np_ready/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts rename to x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts index d762b05f01d79e..de01bd59655040 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts +++ b/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts @@ -5,7 +5,7 @@ */ import { get } from 'lodash'; -import { ES_SCROLL_SETTINGS } from '../../../../common/constants'; +import { ES_SCROLL_SETTINGS } from '../../../common/constants'; export function fetchAllFromScroll(response: any, callWithRequest: any, hits: any[] = []) { const newHits = get(response, 'hits.hits', []); diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/lib/fetch_all_from_scroll/index.ts b/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/lib/fetch_all_from_scroll/index.ts rename to x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/lib/is_es_error/index.ts b/x-pack/plugins/watcher/server/lib/is_es_error/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/lib/is_es_error/index.ts rename to x-pack/plugins/watcher/server/lib/is_es_error/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/lib/is_es_error/is_es_error.ts b/x-pack/plugins/watcher/server/lib/is_es_error/is_es_error.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/lib/is_es_error/is_es_error.ts rename to x-pack/plugins/watcher/server/lib/is_es_error/is_es_error.ts diff --git a/x-pack/plugins/watcher/server/lib/license_pre_routing_factory/__tests__/license_pre_routing_factory.test.js b/x-pack/plugins/watcher/server/lib/license_pre_routing_factory/__tests__/license_pre_routing_factory.test.js new file mode 100644 index 00000000000000..be6873a61e902d --- /dev/null +++ b/x-pack/plugins/watcher/server/lib/license_pre_routing_factory/__tests__/license_pre_routing_factory.test.js @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; +import { kibanaResponseFactory } from '../../../../../../../src/core/server'; +import { licensePreRoutingFactory } from '../license_pre_routing_factory'; + +describe('license_pre_routing_factory', () => { + describe('#reportingFeaturePreRoutingFactory', () => { + let mockDeps; + let licenseStatus; + + beforeEach(() => { + mockDeps = { getLicenseStatus: () => licenseStatus }; + }); + + describe('status is not valid', () => { + it('replies with 403', () => { + licenseStatus = { hasRequired: false }; + const routeWithLicenseCheck = licensePreRoutingFactory(mockDeps, () => {}); + const stubRequest = {}; + const response = routeWithLicenseCheck({}, stubRequest, kibanaResponseFactory); + expect(response.status).to.be(403); + }); + }); + + describe('status is valid', () => { + it('replies with nothing', () => { + licenseStatus = { hasRequired: true }; + const routeWithLicenseCheck = licensePreRoutingFactory(mockDeps, () => null); + const stubRequest = {}; + const response = routeWithLicenseCheck({}, stubRequest, kibanaResponseFactory); + expect(response).to.be(null); + }); + }); + }); +}); diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/index.ts b/x-pack/plugins/watcher/server/lib/license_pre_routing_factory/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/lib/license_pre_routing_factory/index.ts rename to x-pack/plugins/watcher/server/lib/license_pre_routing_factory/index.ts diff --git a/x-pack/plugins/watcher/server/lib/license_pre_routing_factory/license_pre_routing_factory.ts b/x-pack/plugins/watcher/server/lib/license_pre_routing_factory/license_pre_routing_factory.ts new file mode 100644 index 00000000000000..d010a239527254 --- /dev/null +++ b/x-pack/plugins/watcher/server/lib/license_pre_routing_factory/license_pre_routing_factory.ts @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + KibanaRequest, + KibanaResponseFactory, + RequestHandler, + RequestHandlerContext, +} from 'kibana/server'; +import { RouteDependencies } from '../../types'; + +export const licensePreRoutingFactory = ( + { getLicenseStatus }: RouteDependencies, + handler: RequestHandler +) => { + return function licenseCheck( + ctx: RequestHandlerContext, + request: KibanaRequest, + response: KibanaResponseFactory + ) { + const licenseStatus = getLicenseStatus(); + if (!licenseStatus.hasRequired) { + return response.customError({ + body: { + message: licenseStatus.message || '', + }, + statusCode: 403, + }); + } + + return handler(ctx, request, response); + }; +}; diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/lib/normalized_field_types/index.ts b/x-pack/plugins/watcher/server/lib/normalized_field_types/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/lib/normalized_field_types/index.ts rename to x-pack/plugins/watcher/server/lib/normalized_field_types/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/lib/normalized_field_types/normalized_field_types.ts b/x-pack/plugins/watcher/server/lib/normalized_field_types/normalized_field_types.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/lib/normalized_field_types/normalized_field_types.ts rename to x-pack/plugins/watcher/server/lib/normalized_field_types/normalized_field_types.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/__tests__/action_status.js b/x-pack/plugins/watcher/server/models/action_status/__tests__/action_status.js similarity index 99% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/__tests__/action_status.js rename to x-pack/plugins/watcher/server/models/action_status/__tests__/action_status.js index 7b55ff16926033..cc5f11da1b5d2c 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/__tests__/action_status.js +++ b/x-pack/plugins/watcher/server/models/action_status/__tests__/action_status.js @@ -6,7 +6,7 @@ import expect from '@kbn/expect'; import { ActionStatus } from '../action_status'; -import { ACTION_STATES } from '../../../../../common/constants'; +import { ACTION_STATES } from '../../../../common/constants'; import moment from 'moment'; describe('action_status', () => { diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/action_status.js b/x-pack/plugins/watcher/server/models/action_status/action_status.js similarity index 97% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/action_status.js rename to x-pack/plugins/watcher/server/models/action_status/action_status.js index 9f6b7da1e3a699..01ec9a436675db 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/action_status.js +++ b/x-pack/plugins/watcher/server/models/action_status/action_status.js @@ -6,8 +6,8 @@ import { get } from 'lodash'; import { badRequest } from 'boom'; -import { getMoment } from '../../../../common/lib/get_moment'; -import { ACTION_STATES } from '../../../../common/constants'; +import { getMoment } from '../../../common/lib/get_moment'; +import { ACTION_STATES } from '../../../common/constants'; import { i18n } from '@kbn/i18n'; export class ActionStatus { diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/index.js b/x-pack/plugins/watcher/server/models/action_status/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/action_status/index.js rename to x-pack/plugins/watcher/server/models/action_status/index.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/execute_details/__tests__/execute_details.js b/x-pack/plugins/watcher/server/models/execute_details/__tests__/execute_details.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/execute_details/__tests__/execute_details.js rename to x-pack/plugins/watcher/server/models/execute_details/__tests__/execute_details.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/execute_details/execute_details.js b/x-pack/plugins/watcher/server/models/execute_details/execute_details.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/execute_details/execute_details.js rename to x-pack/plugins/watcher/server/models/execute_details/execute_details.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/execute_details/index.js b/x-pack/plugins/watcher/server/models/execute_details/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/execute_details/index.js rename to x-pack/plugins/watcher/server/models/execute_details/index.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/fields/__tests__/fields.js b/x-pack/plugins/watcher/server/models/fields/__tests__/fields.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/fields/__tests__/fields.js rename to x-pack/plugins/watcher/server/models/fields/__tests__/fields.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/fields/fields.js b/x-pack/plugins/watcher/server/models/fields/fields.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/fields/fields.js rename to x-pack/plugins/watcher/server/models/fields/fields.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/fields/index.js b/x-pack/plugins/watcher/server/models/fields/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/fields/index.js rename to x-pack/plugins/watcher/server/models/fields/index.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/settings/__tests__/settings.js b/x-pack/plugins/watcher/server/models/settings/__tests__/settings.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/settings/__tests__/settings.js rename to x-pack/plugins/watcher/server/models/settings/__tests__/settings.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/settings/index.js b/x-pack/plugins/watcher/server/models/settings/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/settings/index.js rename to x-pack/plugins/watcher/server/models/settings/index.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/settings/settings.js b/x-pack/plugins/watcher/server/models/settings/settings.js similarity index 97% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/settings/settings.js rename to x-pack/plugins/watcher/server/models/settings/settings.js index 4aa524731d88da..42fbda9cbe91de 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/settings/settings.js +++ b/x-pack/plugins/watcher/server/models/settings/settings.js @@ -5,7 +5,7 @@ */ import { merge } from 'lodash'; -import { ACTION_TYPES } from '../../../../common/constants'; +import { ACTION_TYPES } from '../../../common/constants'; function isEnabledByDefault(actionType) { switch (actionType) { diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/visualize_options/index.js b/x-pack/plugins/watcher/server/models/visualize_options/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/visualize_options/index.js rename to x-pack/plugins/watcher/server/models/visualize_options/index.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/visualize_options/visualize_options.js b/x-pack/plugins/watcher/server/models/visualize_options/visualize_options.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/visualize_options/visualize_options.js rename to x-pack/plugins/watcher/server/models/visualize_options/visualize_options.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/base_watch.js b/x-pack/plugins/watcher/server/models/watch/base_watch.js similarity index 98% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/base_watch.js rename to x-pack/plugins/watcher/server/models/watch/base_watch.js index d77e6d6caa2fa8..ea09fac6f85236 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/base_watch.js +++ b/x-pack/plugins/watcher/server/models/watch/base_watch.js @@ -6,7 +6,7 @@ import { get, map, pick } from 'lodash'; import { badRequest } from 'boom'; -import { Action } from '../../../../common/models/action'; +import { Action } from '../../../common/models/action'; import { WatchStatus } from '../watch_status'; import { i18n } from '@kbn/i18n'; import { WatchErrors } from '../watch_errors'; diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/base_watch.test.js b/x-pack/plugins/watcher/server/models/watch/base_watch.test.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/base_watch.test.js rename to x-pack/plugins/watcher/server/models/watch/base_watch.test.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/index.js b/x-pack/plugins/watcher/server/models/watch/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/index.js rename to x-pack/plugins/watcher/server/models/watch/index.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/json_watch.js b/x-pack/plugins/watcher/server/models/watch/json_watch.js similarity index 92% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/json_watch.js rename to x-pack/plugins/watcher/server/models/watch/json_watch.js index 2440d4ef338816..dbb34e971f94ac 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/json_watch.js +++ b/x-pack/plugins/watcher/server/models/watch/json_watch.js @@ -6,8 +6,8 @@ import { isEmpty, cloneDeep, has, merge } from 'lodash'; import { BaseWatch } from './base_watch'; -import { WATCH_TYPES } from '../../../../common/constants'; -import { serializeJsonWatch } from '../../../../common/lib/serialization'; +import { WATCH_TYPES } from '../../../common/constants'; +import { serializeJsonWatch } from '../../../common/lib/serialization'; export class JsonWatch extends BaseWatch { // This constructor should not be used directly. diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/json_watch.test.js b/x-pack/plugins/watcher/server/models/watch/json_watch.test.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/json_watch.test.js rename to x-pack/plugins/watcher/server/models/watch/json_watch.test.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/lib/get_watch_type/get_watch_type.js b/x-pack/plugins/watcher/server/models/watch/lib/get_watch_type/get_watch_type.js similarity index 88% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/lib/get_watch_type/get_watch_type.js rename to x-pack/plugins/watcher/server/models/watch/lib/get_watch_type/get_watch_type.js index 72c725eda2bd18..2bdd03e23c6dcd 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/lib/get_watch_type/get_watch_type.js +++ b/x-pack/plugins/watcher/server/models/watch/lib/get_watch_type/get_watch_type.js @@ -5,7 +5,7 @@ */ import { get, contains, values } from 'lodash'; -import { WATCH_TYPES } from '../../../../../../common/constants'; +import { WATCH_TYPES } from '../../../../../common/constants'; export function getWatchType(watchJson) { const type = get(watchJson, 'metadata.xpack.type'); diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/lib/get_watch_type/index.js b/x-pack/plugins/watcher/server/models/watch/lib/get_watch_type/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/lib/get_watch_type/index.js rename to x-pack/plugins/watcher/server/models/watch/lib/get_watch_type/index.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/monitoring_watch.js b/x-pack/plugins/watcher/server/models/watch/monitoring_watch.js similarity index 97% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/monitoring_watch.js rename to x-pack/plugins/watcher/server/models/watch/monitoring_watch.js index 4aced5d0092d96..8f32621bfbb867 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/monitoring_watch.js +++ b/x-pack/plugins/watcher/server/models/watch/monitoring_watch.js @@ -7,7 +7,7 @@ import { merge } from 'lodash'; import { badRequest } from 'boom'; import { BaseWatch } from './base_watch'; -import { WATCH_TYPES } from '../../../../common/constants'; +import { WATCH_TYPES } from '../../../common/constants'; import { i18n } from '@kbn/i18n'; export class MonitoringWatch extends BaseWatch { diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/monitoring_watch.test.js b/x-pack/plugins/watcher/server/models/watch/monitoring_watch.test.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/monitoring_watch.test.js rename to x-pack/plugins/watcher/server/models/watch/monitoring_watch.test.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/__tests__/format_visualize_data.js b/x-pack/plugins/watcher/server/models/watch/threshold_watch/__tests__/format_visualize_data.js similarity index 99% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/__tests__/format_visualize_data.js rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/__tests__/format_visualize_data.js index 14aa8f7873e18f..99e88c3628ea8e 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/__tests__/format_visualize_data.js +++ b/x-pack/plugins/watcher/server/models/watch/threshold_watch/__tests__/format_visualize_data.js @@ -5,7 +5,7 @@ */ import expect from '@kbn/expect'; -import { AGG_TYPES } from '../../../../../../common/constants'; +import { AGG_TYPES } from '../../../../../common/constants'; import { formatVisualizeData } from '../format_visualize_data'; describe('watch', () => { diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/build_visualize_query.js b/x-pack/plugins/watcher/server/models/watch/threshold_watch/build_visualize_query.js similarity index 95% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/build_visualize_query.js rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/build_visualize_query.js index cc79aec682400d..84bdae6ad95fdf 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/build_visualize_query.js +++ b/x-pack/plugins/watcher/server/models/watch/threshold_watch/build_visualize_query.js @@ -5,8 +5,8 @@ */ import { cloneDeep } from 'lodash'; -import { buildInput } from '../../../../../common/lib/serialization'; -import { AGG_TYPES } from '../../../../../common/constants'; +import { buildInput } from '../../../../common/lib/serialization'; +import { AGG_TYPES } from '../../../../common/constants'; /* input.search.request.body.query.bool.filter.range diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count.json b/x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/count.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count.json rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/count.json diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count.query.date.json b/x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/count.query.date.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count.query.date.json rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/count.query.date.json diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count.query.json b/x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/count.query.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count.query.json rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/count.query.json diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count_terms.json b/x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/count_terms.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count_terms.json rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/count_terms.json diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count_terms.query.date.json b/x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/count_terms.query.date.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count_terms.query.date.json rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/count_terms.query.date.json diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count_terms.query.json b/x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/count_terms.query.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/count_terms.query.json rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/count_terms.query.json diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count.json b/x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count.json rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count.json diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count.query.date.json b/x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count.query.date.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count.query.date.json rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count.query.date.json diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count.query.json b/x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count.query.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count.query.json rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count.query.json diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count_terms.json b/x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count_terms.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count_terms.json rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count_terms.json diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count_terms.query.date.json b/x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count_terms.query.date.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count_terms.query.date.json rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count_terms.query.date.json diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count_terms.query.json b/x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count_terms.query.json similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/data_samples/non_count_terms.query.json rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/data_samples/non_count_terms.query.json diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/format_visualize_data.js b/x-pack/plugins/watcher/server/models/watch/threshold_watch/format_visualize_data.js similarity index 97% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/format_visualize_data.js rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/format_visualize_data.js index c8a6ac08df2c15..c93add71bfe38f 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/format_visualize_data.js +++ b/x-pack/plugins/watcher/server/models/watch/threshold_watch/format_visualize_data.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { AGG_TYPES } from '../../../../../common/constants'; +import { AGG_TYPES } from '../../../../common/constants'; export function formatVisualizeData({ aggType, termField }, results) { if (aggType === AGG_TYPES.COUNT && !Boolean(termField)) { diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/index.js b/x-pack/plugins/watcher/server/models/watch/threshold_watch/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/index.js rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/index.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/threshold_watch.js b/x-pack/plugins/watcher/server/models/watch/threshold_watch/threshold_watch.js similarity index 97% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/threshold_watch.js rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/threshold_watch.js index e5410588ab566c..ebef741200e003 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/threshold_watch.js +++ b/x-pack/plugins/watcher/server/models/watch/threshold_watch/threshold_watch.js @@ -6,8 +6,8 @@ import { merge } from 'lodash'; import { BaseWatch } from '../base_watch'; -import { WATCH_TYPES, COMPARATORS, SORT_ORDERS } from '../../../../../common/constants'; -import { serializeThresholdWatch } from '../../../../../common/lib/serialization'; +import { WATCH_TYPES, COMPARATORS, SORT_ORDERS } from '../../../../common/constants'; +import { serializeThresholdWatch } from '../../../../common/lib/serialization'; import { buildVisualizeQuery } from './build_visualize_query'; import { formatVisualizeData } from './format_visualize_data'; diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/threshold_watch.test.js b/x-pack/plugins/watcher/server/models/watch/threshold_watch/threshold_watch.test.js similarity index 99% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/threshold_watch.test.js rename to x-pack/plugins/watcher/server/models/watch/threshold_watch/threshold_watch.test.js index e65342708c9d5a..af4aae54fbfeac 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/threshold_watch/threshold_watch.test.js +++ b/x-pack/plugins/watcher/server/models/watch/threshold_watch/threshold_watch.test.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { COMPARATORS, SORT_ORDERS } from '../../../../../common/constants'; +import { COMPARATORS, SORT_ORDERS } from '../../../../common/constants'; import { WatchErrors } from '../../watch_errors'; import { ThresholdWatch } from './threshold_watch'; diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/watch.js b/x-pack/plugins/watcher/server/models/watch/watch.js similarity index 97% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/watch.js rename to x-pack/plugins/watcher/server/models/watch/watch.js index cc92741de73ae0..febf9c20b07a65 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/watch.js +++ b/x-pack/plugins/watcher/server/models/watch/watch.js @@ -6,7 +6,7 @@ import { set } from 'lodash'; import { badRequest } from 'boom'; -import { WATCH_TYPES } from '../../../../common/constants'; +import { WATCH_TYPES } from '../../../common/constants'; import { JsonWatch } from './json_watch'; import { MonitoringWatch } from './monitoring_watch'; import { ThresholdWatch } from './threshold_watch'; diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/watch.test.js b/x-pack/plugins/watcher/server/models/watch/watch.test.js similarity index 98% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch/watch.test.js rename to x-pack/plugins/watcher/server/models/watch/watch.test.js index d6e23e727d5750..51eeb6a8c05386 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch/watch.test.js +++ b/x-pack/plugins/watcher/server/models/watch/watch.test.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { WATCH_TYPES } from '../../../../common/constants'; +import { WATCH_TYPES } from '../../../common/constants'; import { Watch } from './watch'; import { JsonWatch } from './json_watch'; import { MonitoringWatch } from './monitoring_watch'; diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_errors/index.js b/x-pack/plugins/watcher/server/models/watch_errors/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch_errors/index.js rename to x-pack/plugins/watcher/server/models/watch_errors/index.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_errors/watch_errors.js b/x-pack/plugins/watcher/server/models/watch_errors/watch_errors.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch_errors/watch_errors.js rename to x-pack/plugins/watcher/server/models/watch_errors/watch_errors.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_errors/watch_errors.test.js b/x-pack/plugins/watcher/server/models/watch_errors/watch_errors.test.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch_errors/watch_errors.test.js rename to x-pack/plugins/watcher/server/models/watch_errors/watch_errors.test.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_history_item/__tests__/watch_history_item.js b/x-pack/plugins/watcher/server/models/watch_history_item/__tests__/watch_history_item.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch_history_item/__tests__/watch_history_item.js rename to x-pack/plugins/watcher/server/models/watch_history_item/__tests__/watch_history_item.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_history_item/index.js b/x-pack/plugins/watcher/server/models/watch_history_item/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch_history_item/index.js rename to x-pack/plugins/watcher/server/models/watch_history_item/index.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_history_item/watch_history_item.js b/x-pack/plugins/watcher/server/models/watch_history_item/watch_history_item.js similarity index 97% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch_history_item/watch_history_item.js rename to x-pack/plugins/watcher/server/models/watch_history_item/watch_history_item.js index 391c68debfbd9f..134b201628195e 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_history_item/watch_history_item.js +++ b/x-pack/plugins/watcher/server/models/watch_history_item/watch_history_item.js @@ -5,7 +5,7 @@ */ import { badRequest } from 'boom'; -import { getMoment } from '../../../../common/lib/get_moment'; +import { getMoment } from '../../../common/lib/get_moment'; import { get, cloneDeep } from 'lodash'; import { WatchStatus } from '../watch_status'; import { i18n } from '@kbn/i18n'; diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/__tests__/watch_status.js b/x-pack/plugins/watcher/server/models/watch_status/__tests__/watch_status.js similarity index 99% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/__tests__/watch_status.js rename to x-pack/plugins/watcher/server/models/watch_status/__tests__/watch_status.js index 505e1733e03cd1..0d6731b90abe65 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/__tests__/watch_status.js +++ b/x-pack/plugins/watcher/server/models/watch_status/__tests__/watch_status.js @@ -6,7 +6,7 @@ import expect from '@kbn/expect'; import { WatchStatus } from '../watch_status'; -import { ACTION_STATES, WATCH_STATES, WATCH_STATE_COMMENTS } from '../../../../../common/constants'; +import { ACTION_STATES, WATCH_STATES, WATCH_STATE_COMMENTS } from '../../../../common/constants'; import moment from 'moment'; describe('watch_status', () => { diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/index.js b/x-pack/plugins/watcher/server/models/watch_status/index.js similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/index.js rename to x-pack/plugins/watcher/server/models/watch_status/index.js diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/watch_status.js b/x-pack/plugins/watcher/server/models/watch_status/watch_status.js similarity index 98% rename from x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/watch_status.js rename to x-pack/plugins/watcher/server/models/watch_status/watch_status.js index 3cdc1d8eb62e70..a346885965a166 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/models/watch_status/watch_status.js +++ b/x-pack/plugins/watcher/server/models/watch_status/watch_status.js @@ -6,9 +6,9 @@ import { get, map, forEach, max } from 'lodash'; import { badRequest } from 'boom'; -import { getMoment } from '../../../../common/lib/get_moment'; +import { getMoment } from '../../../common/lib/get_moment'; import { ActionStatus } from '../action_status'; -import { ACTION_STATES, WATCH_STATES, WATCH_STATE_COMMENTS } from '../../../../common/constants'; +import { ACTION_STATES, WATCH_STATES, WATCH_STATE_COMMENTS } from '../../../common/constants'; import { i18n } from '@kbn/i18n'; function getActionStatusTotals(watchStatus) { diff --git a/x-pack/plugins/watcher/server/plugin.ts b/x-pack/plugins/watcher/server/plugin.ts new file mode 100644 index 00000000000000..1f7b3823609eca --- /dev/null +++ b/x-pack/plugins/watcher/server/plugin.ts @@ -0,0 +1,72 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { CoreSetup, Logger, Plugin, PluginInitializerContext } from 'kibana/server'; +import { PLUGIN } from '../common/constants'; +import { Dependencies, LicenseStatus, RouteDependencies } from './types'; +import { LICENSE_CHECK_STATE } from '../../licensing/server'; + +import { registerSettingsRoutes } from './routes/api/settings'; +import { registerIndicesRoutes } from './routes/api/indices'; +import { registerLicenseRoutes } from './routes/api/license'; +import { registerWatchesRoutes } from './routes/api/watches'; +import { registerWatchRoutes } from './routes/api/watch'; +import { registerListFieldsRoute } from './routes/api/register_list_fields_route'; +import { registerLoadHistoryRoute } from './routes/api/register_load_history_route'; + +export class WatcherServerPlugin implements Plugin { + log: Logger; + + private licenseStatus: LicenseStatus = { + hasRequired: false, + }; + + constructor(ctx: PluginInitializerContext) { + this.log = ctx.logger.get(); + } + + async setup( + { http, elasticsearch: elasticsearchService }: CoreSetup, + { licensing }: Dependencies + ) { + const elasticsearch = await elasticsearchService.adminClient; + const router = http.createRouter(); + const routeDependencies: RouteDependencies = { + elasticsearch, + elasticsearchService, + router, + getLicenseStatus: () => this.licenseStatus, + }; + + registerListFieldsRoute(routeDependencies); + registerLoadHistoryRoute(routeDependencies); + registerIndicesRoutes(routeDependencies); + registerLicenseRoutes(routeDependencies); + registerSettingsRoutes(routeDependencies); + registerWatchesRoutes(routeDependencies); + registerWatchRoutes(routeDependencies); + + licensing.license$.subscribe(async license => { + const { state, message } = license.check(PLUGIN.ID, PLUGIN.MINIMUM_LICENSE_REQUIRED); + const hasMinimumLicense = state === LICENSE_CHECK_STATE.Valid; + if (hasMinimumLicense && license.getFeature(PLUGIN.ID)) { + this.log.info('Enabling Watcher plugin.'); + this.licenseStatus = { + hasRequired: true, + }; + } else { + if (message) { + this.log.info(message); + } + this.licenseStatus = { + hasRequired: false, + message, + }; + } + }); + } + start() {} + stop() {} +} diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/index.ts b/x-pack/plugins/watcher/server/routes/api/indices/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/index.ts rename to x-pack/plugins/watcher/server/routes/api/indices/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/register_get_route.ts b/x-pack/plugins/watcher/server/routes/api/indices/register_get_route.ts similarity index 91% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/register_get_route.ts rename to x-pack/plugins/watcher/server/routes/api/indices/register_get_route.ts index 6b6b643dc4adf1..30607b82e32950 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/register_get_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/indices/register_get_route.ts @@ -5,12 +5,12 @@ */ import { schema } from '@kbn/config-schema'; -import { RequestHandler } from 'src/core/server'; +import { RequestHandler } from 'kibana/server'; import { reduce, size } from 'lodash'; import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; import { isEsError } from '../../../lib/is_es_error'; +import { RouteDependencies } from '../../../types'; import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; -import { RouteDependencies, ServerShim } from '../../../types'; function getIndexNamesFromAliasesResponse(json: Record) { return reduce( @@ -61,7 +61,7 @@ function getIndices(callWithRequest: any, pattern: string, limit = 10) { }); } -export function registerGetRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerGetRoute(deps: RouteDependencies) { const handler: RequestHandler = async (ctx, request, response) => { const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); const { pattern } = request.body; @@ -87,6 +87,6 @@ export function registerGetRoute(deps: RouteDependencies, legacy: ServerShim) { body: schema.object({}, { allowUnknowns: true }), }, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/register_indices_routes.ts b/x-pack/plugins/watcher/server/routes/api/indices/register_indices_routes.ts similarity index 62% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/register_indices_routes.ts rename to x-pack/plugins/watcher/server/routes/api/indices/register_indices_routes.ts index 647a85c311532b..db8dbdc8618d45 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/indices/register_indices_routes.ts +++ b/x-pack/plugins/watcher/server/routes/api/indices/register_indices_routes.ts @@ -5,8 +5,8 @@ */ import { registerGetRoute } from './register_get_route'; -import { RouteDependencies, ServerShim } from '../../../types'; +import { RouteDependencies } from '../../../types'; -export function registerIndicesRoutes(deps: RouteDependencies, legacy: ServerShim) { - registerGetRoute(deps, legacy); +export function registerIndicesRoutes(deps: RouteDependencies) { + registerGetRoute(deps); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/index.ts b/x-pack/plugins/watcher/server/routes/api/license/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/index.ts rename to x-pack/plugins/watcher/server/routes/api/license/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/register_license_routes.ts b/x-pack/plugins/watcher/server/routes/api/license/register_license_routes.ts similarity index 62% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/register_license_routes.ts rename to x-pack/plugins/watcher/server/routes/api/license/register_license_routes.ts index c5965d9315b01e..9b7f6272442bd9 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/register_license_routes.ts +++ b/x-pack/plugins/watcher/server/routes/api/license/register_license_routes.ts @@ -5,8 +5,8 @@ */ import { registerRefreshRoute } from './register_refresh_route'; -import { RouteDependencies, ServerShim } from '../../../types'; +import { RouteDependencies } from '../../../types'; -export function registerLicenseRoutes(deps: RouteDependencies, legacy: ServerShim) { - registerRefreshRoute(deps, legacy); +export function registerLicenseRoutes(deps: RouteDependencies) { + registerRefreshRoute(deps); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/register_refresh_route.ts b/x-pack/plugins/watcher/server/routes/api/license/register_refresh_route.ts similarity index 78% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/register_refresh_route.ts rename to x-pack/plugins/watcher/server/routes/api/license/register_refresh_route.ts index 08f1f26a84a4fb..a61fd16e8be4ad 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/license/register_refresh_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/license/register_refresh_route.ts @@ -4,17 +4,16 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandler } from 'src/core/server'; +import { RequestHandler } from 'kibana/server'; +import { RouteDependencies } from '../../../types'; import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; -import { RouteDependencies, ServerShim } from '../../../types'; - /* In order for the client to have the most up-to-date snapshot of the current license, it needs to make a round-trip to the kibana server. This refresh endpoint is provided for when the client needs to check the license, but doesn't need to pull data from the server for any reason, i.e., when adding a new watch. */ -export function registerRefreshRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerRefreshRoute(deps: RouteDependencies) { const handler: RequestHandler = (ctx, request, response) => { return response.ok({ body: { success: true } }); }; @@ -24,6 +23,6 @@ export function registerRefreshRoute(deps: RouteDependencies, legacy: ServerShim path: '/api/watcher/license/refresh', validate: false, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/register_list_fields_route.ts b/x-pack/plugins/watcher/server/routes/api/register_list_fields_route.ts similarity index 86% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/register_list_fields_route.ts rename to x-pack/plugins/watcher/server/routes/api/register_list_fields_route.ts index f3222d24f0adf9..7c47379b875892 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/register_list_fields_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/register_list_fields_route.ts @@ -5,13 +5,13 @@ */ import { schema } from '@kbn/config-schema'; -import { RequestHandler } from 'src/core/server'; +import { RequestHandler } from 'kibana/server'; import { callWithRequestFactory } from '../../lib/call_with_request_factory'; import { isEsError } from '../../lib/is_es_error'; -import { licensePreRoutingFactory } from '../../lib/license_pre_routing_factory'; // @ts-ignore -import { Fields } from '../../models/fields'; -import { RouteDependencies, ServerShim } from '../../types'; +import { Fields } from '../../models/fields/index'; +import { licensePreRoutingFactory } from '../../lib/license_pre_routing_factory'; +import { RouteDependencies } from '../../types'; function fetchFields(callWithRequest: any, indexes: string[]) { const params = { @@ -25,7 +25,7 @@ function fetchFields(callWithRequest: any, indexes: string[]) { return callWithRequest('fieldCaps', params); } -export function registerListFieldsRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerListFieldsRoute(deps: RouteDependencies) { const handler: RequestHandler = async (ctx, request, response) => { const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); const { indexes } = request.body; @@ -60,6 +60,6 @@ export function registerListFieldsRoute(deps: RouteDependencies, legacy: ServerS }), }, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/register_load_history_route.ts b/x-pack/plugins/watcher/server/routes/api/register_load_history_route.ts similarity index 90% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/register_load_history_route.ts rename to x-pack/plugins/watcher/server/routes/api/register_load_history_route.ts index d62e4f48c56296..1be8477df79bc7 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/register_load_history_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/register_load_history_route.ts @@ -6,14 +6,14 @@ import { schema } from '@kbn/config-schema'; import { get } from 'lodash'; -import { RequestHandler } from 'src/core/server'; +import { RequestHandler } from 'kibana/server'; import { callWithRequestFactory } from '../../lib/call_with_request_factory'; import { isEsError } from '../../lib/is_es_error'; -import { INDEX_NAMES } from '../../../../common/constants'; +import { INDEX_NAMES } from '../../../common/constants'; +import { RouteDependencies } from '../../types'; import { licensePreRoutingFactory } from '../../lib/license_pre_routing_factory'; -import { RouteDependencies, ServerShim } from '../../types'; // @ts-ignore -import { WatchHistoryItem } from '../../models/watch_history_item'; +import { WatchHistoryItem } from '../../models/watch_history_item/index'; function fetchHistoryItem(callWithRequest: any, watchHistoryItemId: string) { return callWithRequest('search', { @@ -28,7 +28,7 @@ function fetchHistoryItem(callWithRequest: any, watchHistoryItemId: string) { }); } -export function registerLoadHistoryRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerLoadHistoryRoute(deps: RouteDependencies) { const handler: RequestHandler = async (ctx, request, response) => { const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); const id = request.params.id; @@ -72,6 +72,6 @@ export function registerLoadHistoryRoute(deps: RouteDependencies, legacy: Server }), }, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/index.ts b/x-pack/plugins/watcher/server/routes/api/settings/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/index.ts rename to x-pack/plugins/watcher/server/routes/api/settings/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/register_load_route.ts b/x-pack/plugins/watcher/server/routes/api/settings/register_load_route.ts similarity index 79% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/register_load_route.ts rename to x-pack/plugins/watcher/server/routes/api/settings/register_load_route.ts index 710d079d810da8..6c70c2d0d07b6a 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/register_load_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/settings/register_load_route.ts @@ -4,12 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IClusterClient, RequestHandler } from 'src/core/server'; +import { IClusterClient, RequestHandler } from 'kibana/server'; import { isEsError } from '../../../lib/is_es_error'; -import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; // @ts-ignore -import { Settings } from '../../../models/settings'; -import { RouteDependencies, ServerShim } from '../../../types'; +import { Settings } from '../../../models/settings/index'; +import { RouteDependencies } from '../../../types'; +import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; function fetchClusterSettings(client: IClusterClient) { return client.callAsInternalUser('cluster.getSettings', { @@ -18,7 +18,7 @@ function fetchClusterSettings(client: IClusterClient) { }); } -export function registerLoadRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerLoadRoute(deps: RouteDependencies) { const handler: RequestHandler = async (ctx, request, response) => { try { const settings = await fetchClusterSettings(deps.elasticsearch); @@ -38,6 +38,6 @@ export function registerLoadRoute(deps: RouteDependencies, legacy: ServerShim) { path: '/api/watcher/settings', validate: false, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/register_settings_routes.ts b/x-pack/plugins/watcher/server/routes/api/settings/register_settings_routes.ts similarity index 62% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/register_settings_routes.ts rename to x-pack/plugins/watcher/server/routes/api/settings/register_settings_routes.ts index 0b24ec0e90bd42..ea4aa6ea4381d9 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/settings/register_settings_routes.ts +++ b/x-pack/plugins/watcher/server/routes/api/settings/register_settings_routes.ts @@ -5,8 +5,8 @@ */ import { registerLoadRoute } from './register_load_route'; -import { RouteDependencies, ServerShim } from '../../../types'; +import { RouteDependencies } from '../../../types'; -export function registerSettingsRoutes(deps: RouteDependencies, legacy: ServerShim) { - registerLoadRoute(deps, legacy); +export function registerSettingsRoutes(deps: RouteDependencies) { + registerLoadRoute(deps); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/index.ts b/x-pack/plugins/watcher/server/routes/api/watch/action/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/index.ts rename to x-pack/plugins/watcher/server/routes/api/watch/action/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/register_acknowledge_route.ts b/x-pack/plugins/watcher/server/routes/api/watch/action/register_acknowledge_route.ts similarity index 88% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/register_acknowledge_route.ts rename to x-pack/plugins/watcher/server/routes/api/watch/action/register_acknowledge_route.ts index d0cc0a27e87ff1..08eec7456e3a57 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/register_acknowledge_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/watch/action/register_acknowledge_route.ts @@ -6,13 +6,13 @@ import { schema } from '@kbn/config-schema'; import { get } from 'lodash'; -import { RequestHandler } from 'src/core/server'; +import { RequestHandler } from 'kibana/server'; import { callWithRequestFactory } from '../../../../lib/call_with_request_factory'; import { isEsError } from '../../../../lib/is_es_error'; -import { licensePreRoutingFactory } from '../../../../lib/license_pre_routing_factory'; // @ts-ignore -import { WatchStatus } from '../../../../models/watch_status'; -import { RouteDependencies, ServerShim } from '../../../../types'; +import { WatchStatus } from '../../../../models/watch_status/index'; +import { RouteDependencies } from '../../../../types'; +import { licensePreRoutingFactory } from '../../../../lib/license_pre_routing_factory'; function acknowledgeAction(callWithRequest: any, watchId: string, actionId: string) { return callWithRequest('watcher.ackWatch', { @@ -21,7 +21,7 @@ function acknowledgeAction(callWithRequest: any, watchId: string, actionId: stri }); } -export function registerAcknowledgeRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerAcknowledgeRoute(deps: RouteDependencies) { const handler: RequestHandler = async (ctx, request, response) => { const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); const { watchId, actionId } = request.params; @@ -60,6 +60,6 @@ export function registerAcknowledgeRoute(deps: RouteDependencies, legacy: Server }), }, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/register_action_routes.ts b/x-pack/plugins/watcher/server/routes/api/watch/action/register_action_routes.ts similarity index 61% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/register_action_routes.ts rename to x-pack/plugins/watcher/server/routes/api/watch/action/register_action_routes.ts index 022c844867938b..c3109e1d091c10 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/action/register_action_routes.ts +++ b/x-pack/plugins/watcher/server/routes/api/watch/action/register_action_routes.ts @@ -5,8 +5,8 @@ */ import { registerAcknowledgeRoute } from './register_acknowledge_route'; -import { RouteDependencies, ServerShim } from '../../../../types'; +import { RouteDependencies } from '../../../../types'; -export function registerActionRoutes(server: RouteDependencies, legacy: ServerShim) { - registerAcknowledgeRoute(server, legacy); +export function registerActionRoutes(deps: RouteDependencies) { + registerAcknowledgeRoute(deps); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/index.ts b/x-pack/plugins/watcher/server/routes/api/watch/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/index.ts rename to x-pack/plugins/watcher/server/routes/api/watch/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_activate_route.ts b/x-pack/plugins/watcher/server/routes/api/watch/register_activate_route.ts similarity index 85% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_activate_route.ts rename to x-pack/plugins/watcher/server/routes/api/watch/register_activate_route.ts index 28c482124aaee0..fdc20854ed8c22 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_activate_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/watch/register_activate_route.ts @@ -5,14 +5,14 @@ */ import { schema } from '@kbn/config-schema'; -import { RequestHandler } from 'src/core/server'; +import { RequestHandler } from 'kibana/server'; import { get } from 'lodash'; import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; import { isEsError } from '../../../lib/is_es_error'; +import { RouteDependencies } from '../../../types'; import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; -import { RouteDependencies, ServerShim } from '../../../types'; // @ts-ignore -import { WatchStatus } from '../../../models/watch_status'; +import { WatchStatus } from '../../../models/watch_status/index'; function activateWatch(callWithRequest: any, watchId: string) { return callWithRequest('watcher.activateWatch', { @@ -20,7 +20,7 @@ function activateWatch(callWithRequest: any, watchId: string) { }); } -export function registerActivateRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerActivateRoute(deps: RouteDependencies) { const handler: RequestHandler = async (ctx, request, response) => { const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); @@ -61,6 +61,6 @@ export function registerActivateRoute(deps: RouteDependencies, legacy: ServerShi }), }, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_deactivate_route.ts b/x-pack/plugins/watcher/server/routes/api/watch/register_deactivate_route.ts similarity index 85% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_deactivate_route.ts rename to x-pack/plugins/watcher/server/routes/api/watch/register_deactivate_route.ts index ac87066379a20c..08d99f42df0540 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_deactivate_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/watch/register_deactivate_route.ts @@ -4,14 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ import { schema } from '@kbn/config-schema'; -import { RequestHandler } from 'src/core/server'; +import { RequestHandler } from 'kibana/server'; import { get } from 'lodash'; import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; import { isEsError } from '../../../lib/is_es_error'; +import { RouteDependencies } from '../../../types'; import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; -import { RouteDependencies, ServerShim } from '../../../types'; // @ts-ignore -import { WatchStatus } from '../../../models/watch_status'; +import { WatchStatus } from '../../../models/watch_status/index'; function deactivateWatch(callWithRequest: any, watchId: string) { return callWithRequest('watcher.deactivateWatch', { @@ -19,7 +19,7 @@ function deactivateWatch(callWithRequest: any, watchId: string) { }); } -export function registerDeactivateRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerDeactivateRoute(deps: RouteDependencies) { const handler: RequestHandler = async (ctx, request, response) => { const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); @@ -60,6 +60,6 @@ export function registerDeactivateRoute(deps: RouteDependencies, legacy: ServerS }), }, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_delete_route.ts b/x-pack/plugins/watcher/server/routes/api/watch/register_delete_route.ts similarity index 86% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_delete_route.ts rename to x-pack/plugins/watcher/server/routes/api/watch/register_delete_route.ts index 26b6f96f6cb8cc..6e95cf959bc9ca 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_delete_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/watch/register_delete_route.ts @@ -5,11 +5,11 @@ */ import { schema } from '@kbn/config-schema'; -import { RequestHandler } from 'src/core/server'; +import { RequestHandler } from 'kibana/server'; import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; import { isEsError } from '../../../lib/is_es_error'; +import { RouteDependencies } from '../../../types'; import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; -import { RouteDependencies, ServerShim } from '../../../types'; function deleteWatch(callWithRequest: any, watchId: string) { return callWithRequest('watcher.deleteWatch', { @@ -17,7 +17,7 @@ function deleteWatch(callWithRequest: any, watchId: string) { }); } -export function registerDeleteRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerDeleteRoute(deps: RouteDependencies) { const handler: RequestHandler = async (ctx, request, response) => { const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); @@ -48,6 +48,6 @@ export function registerDeleteRoute(deps: RouteDependencies, legacy: ServerShim) }), }, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_execute_route.ts b/x-pack/plugins/watcher/server/routes/api/watch/register_execute_route.ts similarity index 86% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_execute_route.ts rename to x-pack/plugins/watcher/server/routes/api/watch/register_execute_route.ts index f3bce228653fe5..fef6d07317da5c 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_execute_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/watch/register_execute_route.ts @@ -5,19 +5,19 @@ */ import { schema } from '@kbn/config-schema'; -import { RequestHandler } from 'src/core/server'; +import { RequestHandler } from 'kibana/server'; import { get } from 'lodash'; import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; import { isEsError } from '../../../lib/is_es_error'; import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; -import { RouteDependencies, ServerShim } from '../../../types'; +import { RouteDependencies } from '../../../types'; // @ts-ignore -import { ExecuteDetails } from '../../../models/execute_details'; +import { ExecuteDetails } from '../../../models/execute_details/index'; // @ts-ignore -import { Watch } from '../../../models/watch'; +import { Watch } from '../../../models/watch/index'; // @ts-ignore -import { WatchHistoryItem } from '../../../models/watch_history_item'; +import { WatchHistoryItem } from '../../../models/watch_history_item/index'; function executeWatch(callWithRequest: any, executeDetails: any, watchJson: any) { const body = executeDetails; @@ -28,7 +28,7 @@ function executeWatch(callWithRequest: any, executeDetails: any, watchJson: any) }); } -export function registerExecuteRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerExecuteRoute(deps: RouteDependencies) { const handler: RequestHandler = async (ctx, request, response) => { const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); const executeDetails = ExecuteDetails.fromDownstreamJson(request.body.executeDetails); @@ -73,6 +73,6 @@ export function registerExecuteRoute(deps: RouteDependencies, legacy: ServerShim }), }, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_history_route.ts b/x-pack/plugins/watcher/server/routes/api/watch/register_history_route.ts similarity index 89% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_history_route.ts rename to x-pack/plugins/watcher/server/routes/api/watch/register_history_route.ts index e236d7dd642a39..7f0f1ac8d66a31 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_history_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/watch/register_history_route.ts @@ -5,16 +5,16 @@ */ import { schema } from '@kbn/config-schema'; -import { RequestHandler } from 'src/core/server'; +import { RequestHandler } from 'kibana/server'; import { get } from 'lodash'; import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; import { fetchAllFromScroll } from '../../../lib/fetch_all_from_scroll'; -import { INDEX_NAMES, ES_SCROLL_SETTINGS } from '../../../../../common/constants'; +import { INDEX_NAMES, ES_SCROLL_SETTINGS } from '../../../../common/constants'; import { isEsError } from '../../../lib/is_es_error'; +import { RouteDependencies } from '../../../types'; import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; -import { RouteDependencies, ServerShim } from '../../../types'; // @ts-ignore -import { WatchHistoryItem } from '../../../models/watch_history_item'; +import { WatchHistoryItem } from '../../../models/watch_history_item/index'; function fetchHistoryItems(callWithRequest: any, watchId: any, startTime: any) { const params: any = { @@ -42,7 +42,7 @@ function fetchHistoryItems(callWithRequest: any, watchId: any, startTime: any) { ); } -export function registerHistoryRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerHistoryRoute(deps: RouteDependencies) { const handler: RequestHandler = async (ctx, request, response) => { const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); const { watchId } = request.params; @@ -92,6 +92,6 @@ export function registerHistoryRoute(deps: RouteDependencies, legacy: ServerShim }), }, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_load_route.ts b/x-pack/plugins/watcher/server/routes/api/watch/register_load_route.ts similarity index 86% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_load_route.ts rename to x-pack/plugins/watcher/server/routes/api/watch/register_load_route.ts index 7311ad08f73a60..91d71cd737121f 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_load_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/watch/register_load_route.ts @@ -5,14 +5,14 @@ */ import { schema } from '@kbn/config-schema'; -import { RequestHandler } from 'src/core/server'; +import { RequestHandler } from 'kibana/server'; import { get } from 'lodash'; import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; import { isEsError } from '../../../lib/is_es_error'; import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; // @ts-ignore -import { Watch } from '../../../models/watch'; -import { RouteDependencies, ServerShim } from '../../../types'; +import { Watch } from '../../../models/watch/index'; +import { RouteDependencies } from '../../../types'; function fetchWatch(callWithRequest: any, watchId: string) { return callWithRequest('watcher.getWatch', { @@ -20,7 +20,7 @@ function fetchWatch(callWithRequest: any, watchId: string) { }); } -export function registerLoadRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerLoadRoute(deps: RouteDependencies) { const handler: RequestHandler = async (ctx, request, response) => { const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); @@ -64,6 +64,6 @@ export function registerLoadRoute(deps: RouteDependencies, legacy: ServerShim) { }), }, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_save_route.ts b/x-pack/plugins/watcher/server/routes/api/watch/register_save_route.ts similarity index 87% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_save_route.ts rename to x-pack/plugins/watcher/server/routes/api/watch/register_save_route.ts index df4117dee2bfda..7986424e6229a7 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_save_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/watch/register_save_route.ts @@ -5,17 +5,14 @@ */ import { schema } from '@kbn/config-schema'; -import { RequestHandler } from 'src/core/server'; +import { RequestHandler } from 'kibana/server'; import { i18n } from '@kbn/i18n'; -import { WATCH_TYPES } from '../../../../../common/constants'; -import { - serializeJsonWatch, - serializeThresholdWatch, -} from '../../../../../common/lib/serialization'; +import { WATCH_TYPES } from '../../../../common/constants'; +import { serializeJsonWatch, serializeThresholdWatch } from '../../../../common/lib/serialization'; import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; import { isEsError } from '../../../lib/is_es_error'; +import { RouteDependencies } from '../../../types'; import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; -import { RouteDependencies, ServerShim } from '../../../types'; function fetchWatch(callWithRequest: any, watchId: string) { return callWithRequest('watcher.getWatch', { @@ -30,7 +27,7 @@ function saveWatch(callWithRequest: any, id: string, body: any) { }); } -export function registerSaveRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerSaveRoute(deps: RouteDependencies) { const handler: RequestHandler = async (ctx, request, response) => { const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); const { id } = request.params; @@ -100,6 +97,6 @@ export function registerSaveRoute(deps: RouteDependencies, legacy: ServerShim) { body: schema.object({}, { allowUnknowns: true }), }, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_visualize_route.ts b/x-pack/plugins/watcher/server/routes/api/watch/register_visualize_route.ts similarity index 86% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_visualize_route.ts rename to x-pack/plugins/watcher/server/routes/api/watch/register_visualize_route.ts index d07a264b0b2b1f..f2110bcc0ebdbc 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_visualize_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/watch/register_visualize_route.ts @@ -5,16 +5,16 @@ */ import { schema } from '@kbn/config-schema'; -import { RequestHandler } from 'src/core/server'; +import { RequestHandler } from 'kibana/server'; import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; import { isEsError } from '../../../lib/is_es_error'; +import { RouteDependencies } from '../../../types'; import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; -import { RouteDependencies, ServerShim } from '../../../types'; // @ts-ignore -import { Watch } from '../../../models/watch'; +import { Watch } from '../../../models/watch/index'; // @ts-ignore -import { VisualizeOptions } from '../../../models/visualize_options'; +import { VisualizeOptions } from '../../../models/visualize_options/index'; function fetchVisualizeData(callWithRequest: any, index: any, body: any) { const params = { @@ -28,7 +28,7 @@ function fetchVisualizeData(callWithRequest: any, index: any, body: any) { return callWithRequest('search', params); } -export function registerVisualizeRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerVisualizeRoute(deps: RouteDependencies) { const handler: RequestHandler = async (ctx, request, response) => { const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); const watch = Watch.fromDownstreamJson(request.body.watch); @@ -65,6 +65,6 @@ export function registerVisualizeRoute(deps: RouteDependencies, legacy: ServerSh }), }, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_watch_routes.ts b/x-pack/plugins/watcher/server/routes/api/watch/register_watch_routes.ts similarity index 62% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_watch_routes.ts rename to x-pack/plugins/watcher/server/routes/api/watch/register_watch_routes.ts index 5ecbf3e0d2b46f..fd295ff81782c2 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watch/register_watch_routes.ts +++ b/x-pack/plugins/watcher/server/routes/api/watch/register_watch_routes.ts @@ -13,16 +13,16 @@ import { registerActivateRoute } from './register_activate_route'; import { registerDeactivateRoute } from './register_deactivate_route'; import { registerVisualizeRoute } from './register_visualize_route'; import { registerActionRoutes } from './action'; -import { RouteDependencies, ServerShim } from '../../../types'; +import { RouteDependencies } from '../../../types'; -export function registerWatchRoutes(deps: RouteDependencies, legacy: ServerShim) { - registerDeleteRoute(deps, legacy); - registerExecuteRoute(deps, legacy); - registerLoadRoute(deps, legacy); - registerSaveRoute(deps, legacy); - registerHistoryRoute(deps, legacy); - registerActivateRoute(deps, legacy); - registerDeactivateRoute(deps, legacy); - registerActionRoutes(deps, legacy); - registerVisualizeRoute(deps, legacy); +export function registerWatchRoutes(deps: RouteDependencies) { + registerDeleteRoute(deps); + registerExecuteRoute(deps); + registerLoadRoute(deps); + registerSaveRoute(deps); + registerHistoryRoute(deps); + registerActivateRoute(deps); + registerDeactivateRoute(deps); + registerActionRoutes(deps); + registerVisualizeRoute(deps); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/index.ts b/x-pack/plugins/watcher/server/routes/api/watches/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/index.ts rename to x-pack/plugins/watcher/server/routes/api/watches/index.ts diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_delete_route.ts b/x-pack/plugins/watcher/server/routes/api/watches/register_delete_route.ts similarity index 87% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_delete_route.ts rename to x-pack/plugins/watcher/server/routes/api/watches/register_delete_route.ts index 29c539a0de138a..2ac824529f9a6d 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_delete_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/watches/register_delete_route.ts @@ -5,10 +5,10 @@ */ import { schema } from '@kbn/config-schema'; -import { RequestHandler } from 'src/core/server'; +import { RequestHandler } from 'kibana/server'; import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; +import { RouteDependencies } from '../../../types'; import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; -import { RouteDependencies, ServerShim } from '../../../types'; function deleteWatches(callWithRequest: any, watchIds: string[]) { const deletePromises = watchIds.map(watchId => { @@ -37,7 +37,7 @@ function deleteWatches(callWithRequest: any, watchIds: string[]) { }); } -export function registerDeleteRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerDeleteRoute(deps: RouteDependencies) { const handler: RequestHandler = async (ctx, request, response) => { const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); @@ -58,6 +58,6 @@ export function registerDeleteRoute(deps: RouteDependencies, legacy: ServerShim) }), }, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_list_route.ts b/x-pack/plugins/watcher/server/routes/api/watches/register_list_route.ts similarity index 85% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_list_route.ts rename to x-pack/plugins/watcher/server/routes/api/watches/register_list_route.ts index b94c29e0f98926..fcbdf688a2ab40 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_list_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/watches/register_list_route.ts @@ -4,16 +4,16 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandler } from 'src/core/server'; +import { RequestHandler } from 'kibana/server'; import { get } from 'lodash'; import { callWithRequestFactory } from '../../../lib/call_with_request_factory'; import { fetchAllFromScroll } from '../../../lib/fetch_all_from_scroll'; -import { INDEX_NAMES, ES_SCROLL_SETTINGS } from '../../../../../common/constants'; +import { INDEX_NAMES, ES_SCROLL_SETTINGS } from '../../../../common/constants'; import { isEsError } from '../../../lib/is_es_error'; +import { RouteDependencies } from '../../../types'; import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory'; -import { RouteDependencies, ServerShim } from '../../../types'; // @ts-ignore -import { Watch } from '../../../models/watch'; +import { Watch } from '../../../models/watch/index'; function fetchWatches(callWithRequest: any) { const params = { @@ -30,7 +30,7 @@ function fetchWatches(callWithRequest: any) { ); } -export function registerListRoute(deps: RouteDependencies, legacy: ServerShim) { +export function registerListRoute(deps: RouteDependencies) { const handler: RequestHandler = async (ctx, request, response) => { const callWithRequest = callWithRequestFactory(deps.elasticsearchService, request); @@ -81,6 +81,6 @@ export function registerListRoute(deps: RouteDependencies, legacy: ServerShim) { path: '/api/watcher/watches', validate: false, }, - licensePreRoutingFactory(legacy, handler) + licensePreRoutingFactory(deps, handler) ); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_watches_routes.ts b/x-pack/plugins/watcher/server/routes/api/watches/register_watches_routes.ts similarity index 62% rename from x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_watches_routes.ts rename to x-pack/plugins/watcher/server/routes/api/watches/register_watches_routes.ts index dd5f55078e5913..b515b6264a544a 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/routes/api/watches/register_watches_routes.ts +++ b/x-pack/plugins/watcher/server/routes/api/watches/register_watches_routes.ts @@ -6,9 +6,9 @@ import { registerListRoute } from './register_list_route'; import { registerDeleteRoute } from './register_delete_route'; -import { RouteDependencies, ServerShim } from '../../../types'; +import { RouteDependencies } from '../../../types'; -export function registerWatchesRoutes(deps: RouteDependencies, legacy: ServerShim) { - registerListRoute(deps, legacy); - registerDeleteRoute(deps, legacy); +export function registerWatchesRoutes(deps: RouteDependencies) { + registerListRoute(deps); + registerDeleteRoute(deps); } diff --git a/x-pack/legacy/plugins/watcher/server/np_ready/types.ts b/x-pack/plugins/watcher/server/types.ts similarity index 60% rename from x-pack/legacy/plugins/watcher/server/np_ready/types.ts rename to x-pack/plugins/watcher/server/types.ts index 3d4454aa2a8b77..d9f2d3c3b1e7a6 100644 --- a/x-pack/legacy/plugins/watcher/server/np_ready/types.ts +++ b/x-pack/plugins/watcher/server/types.ts @@ -4,8 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IRouter, ElasticsearchServiceSetup, IClusterClient } from 'src/core/server'; -import { XPackMainPlugin } from '../../../xpack_main/server/xpack_main'; +import { IRouter, ElasticsearchServiceSetup, IClusterClient } from 'kibana/server'; +import { LicensingPluginSetup } from '../../licensing/server'; + +import { XPackMainPlugin } from '../../../legacy/plugins/xpack_main/server/xpack_main'; + +export interface Dependencies { + licensing: LicensingPluginSetup; +} export interface ServerShim { route: any; @@ -17,6 +23,12 @@ export interface ServerShim { export interface RouteDependencies { router: IRouter; + getLicenseStatus: () => LicenseStatus; elasticsearchService: ElasticsearchServiceSetup; elasticsearch: IClusterClient; } + +export interface LicenseStatus { + hasRequired: boolean; + message?: string; +} diff --git a/x-pack/legacy/plugins/watcher/test/fixtures/execute_details.ts b/x-pack/plugins/watcher/test/fixtures/execute_details.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/test/fixtures/execute_details.ts rename to x-pack/plugins/watcher/test/fixtures/execute_details.ts diff --git a/x-pack/legacy/plugins/watcher/test/fixtures/index.ts b/x-pack/plugins/watcher/test/fixtures/index.ts similarity index 100% rename from x-pack/legacy/plugins/watcher/test/fixtures/index.ts rename to x-pack/plugins/watcher/test/fixtures/index.ts diff --git a/x-pack/legacy/plugins/watcher/test/fixtures/watch.ts b/x-pack/plugins/watcher/test/fixtures/watch.ts similarity index 95% rename from x-pack/legacy/plugins/watcher/test/fixtures/watch.ts rename to x-pack/plugins/watcher/test/fixtures/watch.ts index d948fddeefd588..3342ebc1497702 100644 --- a/x-pack/legacy/plugins/watcher/test/fixtures/watch.ts +++ b/x-pack/plugins/watcher/test/fixtures/watch.ts @@ -5,7 +5,7 @@ */ import { Moment } from 'moment'; -import { getRandomString } from '../../../../../test_utils'; +import { getRandomString } from '../../../../test_utils'; interface Watch { id: string; diff --git a/x-pack/legacy/plugins/watcher/test/fixtures/watch_history.ts b/x-pack/plugins/watcher/test/fixtures/watch_history.ts similarity index 93% rename from x-pack/legacy/plugins/watcher/test/fixtures/watch_history.ts rename to x-pack/plugins/watcher/test/fixtures/watch_history.ts index 70275e6e8869eb..b8f725aa84a18e 100644 --- a/x-pack/legacy/plugins/watcher/test/fixtures/watch_history.ts +++ b/x-pack/plugins/watcher/test/fixtures/watch_history.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { getRandomString } from '../../../../../test_utils'; +import { getRandomString } from '../../../../test_utils'; interface WatchHistory { startTime: string;