diff --git a/.buildkite/pipelines/hourly.yml b/.buildkite/pipelines/hourly.yml index b03a46b5b5c66..4b2b17d272d17 100644 --- a/.buildkite/pipelines/hourly.yml +++ b/.buildkite/pipelines/hourly.yml @@ -147,6 +147,13 @@ steps: key: linting timeout_in_minutes: 90 + - command: .buildkite/scripts/steps/lint_with_types.sh + label: 'Linting (with types)' + agents: + queue: c2-16 + key: linting_with_types + timeout_in_minutes: 90 + - command: .buildkite/scripts/steps/checks.sh label: 'Checks' agents: diff --git a/.buildkite/pipelines/pull_request/base.yml b/.buildkite/pipelines/pull_request/base.yml index 1013a841dfd27..0f2a4a1026af8 100644 --- a/.buildkite/pipelines/pull_request/base.yml +++ b/.buildkite/pipelines/pull_request/base.yml @@ -145,6 +145,13 @@ steps: key: linting timeout_in_minutes: 90 + - command: .buildkite/scripts/steps/lint_with_types.sh + label: 'Linting (with types)' + agents: + queue: c2-16 + key: linting_with_types + timeout_in_minutes: 90 + - command: .buildkite/scripts/steps/checks.sh label: 'Checks' agents: diff --git a/.buildkite/scripts/bootstrap.sh b/.buildkite/scripts/bootstrap.sh index df38c105d2fd3..272cd0a086170 100755 --- a/.buildkite/scripts/bootstrap.sh +++ b/.buildkite/scripts/bootstrap.sh @@ -6,7 +6,17 @@ source .buildkite/scripts/common/util.sh source .buildkite/scripts/common/setup_bazel.sh echo "--- yarn install and bootstrap" -retry 2 15 yarn kbn bootstrap +if ! yarn kbn bootstrap; then + echo "bootstrap failed, trying again in 15 seconds" + sleep 15 + + # Most bootstrap failures will result in a problem inside node_modules that does not get fixed on the next bootstrap + # So, we should just delete node_modules in between attempts + rm -rf node_modules + + echo "--- yarn install and bootstrap, attempt 2" + yarn kbn bootstrap +fi ### ### upload ts-refs-cache artifacts as quickly as possible so they are available for download diff --git a/.buildkite/scripts/steps/lint_with_types.sh b/.buildkite/scripts/steps/lint_with_types.sh new file mode 100755 index 0000000000000..81d5ef03f4989 --- /dev/null +++ b/.buildkite/scripts/steps/lint_with_types.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +set -euo pipefail + +source .buildkite/scripts/common/util.sh + +export BUILD_TS_REFS_DISABLE=false +.buildkite/scripts/bootstrap.sh + +echo '--- Lint: eslint (with types)' +checks-reporter-with-killswitch "Lint: eslint (with types)" \ + node scripts/eslint_with_types diff --git a/.eslintrc.js b/.eslintrc.js index 60f3ae1528fbc..00c96e5cf0491 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -902,17 +902,6 @@ module.exports = { }, }, - /** - * Cases overrides - */ - { - files: ['x-pack/plugins/cases/**/*.{js,mjs,ts,tsx}'], - rules: { - 'no-duplicate-imports': 'off', - '@typescript-eslint/no-duplicate-imports': ['error'], - }, - }, - /** * Security Solution overrides. These rules below are maintained and owned by * the people within the security-solution-platform team. Please see ping them @@ -928,6 +917,8 @@ module.exports = { 'x-pack/plugins/security_solution/common/**/*.{js,mjs,ts,tsx}', 'x-pack/plugins/timelines/public/**/*.{js,mjs,ts,tsx}', 'x-pack/plugins/timelines/common/**/*.{js,mjs,ts,tsx}', + 'x-pack/plugins/cases/public/**/*.{js,mjs,ts,tsx}', + 'x-pack/plugins/cases/common/**/*.{js,mjs,ts,tsx}', ], rules: { 'import/no-nodejs-modules': 'error', @@ -949,10 +940,12 @@ module.exports = { files: [ 'x-pack/plugins/security_solution/**/*.{ts,tsx}', 'x-pack/plugins/timelines/**/*.{ts,tsx}', + 'x-pack/plugins/cases/**/*.{ts,tsx}', ], excludedFiles: [ 'x-pack/plugins/security_solution/**/*.{test,mock,test_helper}.{ts,tsx}', 'x-pack/plugins/timelines/**/*.{test,mock,test_helper}.{ts,tsx}', + 'x-pack/plugins/cases/**/*.{test,mock,test_helper}.{ts,tsx}', ], rules: { '@typescript-eslint/no-non-null-assertion': 'error', @@ -963,6 +956,7 @@ module.exports = { files: [ 'x-pack/plugins/security_solution/**/*.{ts,tsx}', 'x-pack/plugins/timelines/**/*.{ts,tsx}', + 'x-pack/plugins/cases/**/*.{ts,tsx}', ], rules: { '@typescript-eslint/no-this-alias': 'error', @@ -985,6 +979,7 @@ module.exports = { files: [ 'x-pack/plugins/security_solution/**/*.{js,mjs,ts,tsx}', 'x-pack/plugins/timelines/**/*.{js,mjs,ts,tsx}', + 'x-pack/plugins/cases/**/*.{js,mjs,ts,tsx}', ], plugins: ['eslint-plugin-node', 'react'], env: { diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 227041522ac78..e807885e17294 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -232,6 +232,7 @@ /src/core/ @elastic/kibana-core /src/plugins/saved_objects_tagging_oss @elastic/kibana-core /config/kibana.yml @elastic/kibana-core +/typings/ @elastic/kibana-core /x-pack/plugins/banners/ @elastic/kibana-core /x-pack/plugins/features/ @elastic/kibana-core /x-pack/plugins/licensing/ @elastic/kibana-core diff --git a/.gitignore b/.gitignore index c08ae529c2c36..cd79644e5d060 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,7 @@ target .idea *.iml *.log +types.eslint.config.js # Ignore example plugin builds /examples/*/build diff --git a/dev_docs/contributing/how_we_use_github.mdx b/dev_docs/contributing/how_we_use_github.mdx index ff7901fdf08da..3b455b7682c33 100644 --- a/dev_docs/contributing/how_we_use_github.mdx +++ b/dev_docs/contributing/how_we_use_github.mdx @@ -37,6 +37,28 @@ Pull requests are made into the master branch and then backported when it is saf - Resolve merge conflicts by rebasing the target branch over your feature branch, and force-pushing (see below for instructions). - When merging, we’ll squash your commits into a single commit. +### Commit using your `@elastic.co` email address + +In order to assist with developer tooling we ask that all Elastic engineers use their `@elastic.co` email address when committing to the Kibana repo. We have implemented a CI check that validates any PR opened by a member of the `@elastic` organization has at least one commit that is attributed to an `@elastic.co` email address. If you have a PR that is failing because of this check you can fix your PR by following these steps: + + 1. Ensure that you don't have any staged changes + 1. Checkout the branch for your PR + 1. Update the git config for your current repository to commit with your `@elastic.co` email: + + ```bash + git config --local user.email YOUR_ELASTIC_EMAIL@elastic.co + ``` + + 1. Create a commit using the new email address + + ```bash + git commit -m 'commit using @elastic.co' --allow-empty + ``` + + 1. Push the new commit to your PR and the status should now be green + +**Note:** If doing this prevents your commits from being attributed to your Github account then make sure to add your `@elastic.co` address at [https://github.com/settings/emails](https://github.com/settings/emails). + ### Rebasing and fixing merge conflicts Rebasing can be tricky, and fixing merge conflicts can be even trickier because it involves force pushing. This is all compounded by the fact that attempting to push a rebased branch remotely will be rejected by git, and you’ll be prompted to do a pull, which is not at all what you should do (this will really mess up your branch’s history). diff --git a/docs/CHANGELOG.asciidoc b/docs/CHANGELOG.asciidoc index 9fce6285bfa3d..8111172893795 100644 --- a/docs/CHANGELOG.asciidoc +++ b/docs/CHANGELOG.asciidoc @@ -846,7 +846,7 @@ The default values for the session timeout `xpack.security.session.{lifespan|idl *Impact* + Use the following default values: -* `xpack.security.session.idleTimeout: 1h` +* `xpack.security.session.idleTimeout: 8h` * `xpack.security.session.lifespan: 30d` ==== diff --git a/docs/api/dashboard-api.asciidoc b/docs/api/dashboard-api.asciidoc index 94511c3154fe0..e6f54dd9156ec 100644 --- a/docs/api/dashboard-api.asciidoc +++ b/docs/api/dashboard-api.asciidoc @@ -1,7 +1,7 @@ [[dashboard-api]] == Import and export dashboard APIs -deprecated::[7.15.0,These experimental APIs have been deprecated in favor of <> and <>.] +deprecated::[7.15.0,Both of these APIs have been deprecated in favor of <> and <>.] Import and export dashboards with the corresponding saved objects, such as visualizations, saved searches, and index patterns. diff --git a/docs/api/dashboard/export-dashboard.asciidoc b/docs/api/dashboard/export-dashboard.asciidoc index 098ec976569bd..3a20eff0a54d2 100644 --- a/docs/api/dashboard/export-dashboard.asciidoc +++ b/docs/api/dashboard/export-dashboard.asciidoc @@ -6,7 +6,7 @@ deprecated::[7.15.0,Use <> instead.] -experimental[] Export dashboards and corresponding saved objects. +Export dashboards and corresponding saved objects. [[dashboard-api-export-request]] ==== Request diff --git a/docs/api/dashboard/import-dashboard.asciidoc b/docs/api/dashboard/import-dashboard.asciidoc index 41eb47500c8d7..e4817d6cb7ee9 100644 --- a/docs/api/dashboard/import-dashboard.asciidoc +++ b/docs/api/dashboard/import-dashboard.asciidoc @@ -6,7 +6,7 @@ deprecated::[7.15.0,Use <> instead.] -experimental[] Import dashboards and corresponding saved objects. +Import dashboards and corresponding saved objects. [[dashboard-api-import-request]] ==== Request diff --git a/docs/developer/contributing/development-github.asciidoc b/docs/developer/contributing/development-github.asciidoc index c5a3d942f2af3..44736bf4027c1 100644 --- a/docs/developer/contributing/development-github.asciidoc +++ b/docs/developer/contributing/development-github.asciidoc @@ -42,6 +42,28 @@ explanation of _why_ you made the changes that you did. feature branch, and force-pushing (see below for instructions). * When merging, we'll squash your commits into a single commit. +[discrete] +==== Commit using your `@elastic.co` email address + +In order to assist with developer tooling we ask that all Elastic engineers use their `@elastic.co` email address when committing to the Kibana repo. We have implemented a CI check that validates any PR opened by a member of the `@elastic` organization has at least one commit that is attributed to an `@elastic.co` email address. If you have a PR that is failing because of this check you can fix your PR by following these steps: + + 1. Ensure that you don't have any staged changes + 2. Checkout the branch for your PR + 3. Update the git config for your current repository to commit with your `@elastic.co` email: ++ +["source","shell"] +----------- +git config --local user.email YOUR_ELASTIC_EMAIL@elastic.co +----------- + 4. Create a commit using the new email address ++ +["source","shell"] +----------- +git commit -m 'commit using @elastic.co' --allow-empty +----------- ++ + 5. Push the new commit to your PR and the status should now be green + [discrete] ==== Rebasing and fixing merge conflicts diff --git a/docs/maps/asset-tracking-tutorial.asciidoc b/docs/maps/asset-tracking-tutorial.asciidoc index 4ba045681e148..ff62f5c019b74 100644 --- a/docs/maps/asset-tracking-tutorial.asciidoc +++ b/docs/maps/asset-tracking-tutorial.asciidoc @@ -156,16 +156,16 @@ image::maps/images/asset-tracking-tutorial/logstash_output.png[] . Leave the terminal window open and Logstash running throughout this tutorial. [float] -==== Step 3: Create a {kib} index pattern for the tri_met_tracks {es} index +==== Step 3: Create a data view for the tri_met_tracks {es} index -. In Kibana, open the main menu, and click *Stack Management > Index Patterns*. -. Click *Create index pattern*. -. Give the index pattern a name: *tri_met_tracks**. +. In {kib}, open the main menu, and click *Stack Management > Data Views*. +. Click *Create data view*. +. Give the data view a name: *tri_met_tracks**. . Click *Next step*. . Set the *Time field* to *time*. -. Click *Create index pattern*. +. Click *Create data view*. -{kib} shows the fields in your index pattern. +{kib} shows the fields in your data view. [role="screenshot"] image::maps/images/asset-tracking-tutorial/index_pattern.png[] @@ -174,7 +174,7 @@ image::maps/images/asset-tracking-tutorial/index_pattern.png[] ==== Step 4: Explore the Portland bus data . Open the main menu, and click *Discover*. -. Set the index pattern to *tri_met_tracks**. +. Set the data view to *tri_met_tracks**. . Open the <>, and set the time range to the last 15 minutes. . Expand a document and explore some of the fields that you will use later in this tutorial: `bearing`, `in_congestion`, `location`, and `vehicle_id`. @@ -202,7 +202,7 @@ Add a layer to show the bus routes for the last 15 minutes. . Click *Add layer*. . Click *Tracks*. -. Select the *tri_met_tracks** index pattern. +. Select the *tri_met_tracks** data view. . Define the tracks: .. Set *Entity* to *vehicle_id*. .. Set *Sort* to *time*. @@ -225,7 +225,7 @@ image::maps/images/asset-tracking-tutorial/tracks_layer.png[] Add a layer that uses attributes in the data to set the style and orientation of the buses. You’ll see the direction buses are headed and what traffic is like. . Click *Add layer*, and then select *Top Hits per entity*. -. Select the *tri_met_tracks** index pattern. +. Select the *tri_met_tracks** data view. . To display the most recent location per bus: .. Set *Entity* to *vehicle_id*. .. Set *Documents per entity* to 1. diff --git a/docs/maps/geojson-upload.asciidoc b/docs/maps/geojson-upload.asciidoc index 3c9bea11176cc..15ef3471e58d7 100644 --- a/docs/maps/geojson-upload.asciidoc +++ b/docs/maps/geojson-upload.asciidoc @@ -30,11 +30,11 @@ a preview of the data on the map. . Use the default *Index type* of {ref}/geo-point.html[geo_point] for point data, or override it and select {ref}/geo-shape.html[geo_shape]. All other shapes will default to a type of `geo_shape`. -. Leave the default *Index name* and *Index pattern* names (the name of the uploaded +. Leave the default *Index name* and *Data view* names (the name of the uploaded file minus its extension). You might need to change the index name if it is invalid. . Click *Import file*. + -Upon completing the indexing process and creating the associated index pattern, +Upon completing the indexing process and creating the associated data view, the Elasticsearch responses are shown on the *Layer add panel* and the indexed data appears on the map. The geospatial data on the map should be identical to the locally-previewed data, but now it's indexed data from Elasticsearch. diff --git a/docs/maps/indexing-geojson-data-tutorial.asciidoc b/docs/maps/indexing-geojson-data-tutorial.asciidoc index 434c9ab369a5b..50f2e9aed9248 100644 --- a/docs/maps/indexing-geojson-data-tutorial.asciidoc +++ b/docs/maps/indexing-geojson-data-tutorial.asciidoc @@ -58,8 +58,8 @@ auto-populate *Index type* with either {ref}/geo-point.html[geo_point] or . Click *Import file*. + You'll see activity as the GeoJSON Upload utility creates a new index -and index pattern for the data set. When the process is complete, you should -receive messages that the creation of the new index and index pattern +and data view for the data set. When the process is complete, you should +receive messages that the creation of the new index and data view were successful. . Click *Add layer*. diff --git a/docs/maps/maps-aggregations.asciidoc b/docs/maps/maps-aggregations.asciidoc index 7f4af952653e7..fced15771c386 100644 --- a/docs/maps/maps-aggregations.asciidoc +++ b/docs/maps/maps-aggregations.asciidoc @@ -62,7 +62,7 @@ To enable a grid aggregation layer: To enable a blended layer that dynamically shows clusters or documents: . Click *Add layer*, then select the *Documents* layer. -. Configure *Index pattern* and the *Geospatial field*. +. Configure *Data view* and the *Geospatial field*. . In *Scaling*, select *Show clusters when results exceed 10000*. @@ -77,7 +77,7 @@ then accumulates the most relevant documents based on sort order for each entry To enable top hits: . Click *Add layer*, then select the *Top hits per entity* layer. -. Configure *Index pattern* and *Geospatial field*. +. Configure *Data view* and *Geospatial field*. . Set *Entity* to the field that identifies entities in your documents. This field will be used in the terms aggregation to group your documents into entity buckets. . Set *Documents per entity* to configure the maximum number of documents accumulated per entity. diff --git a/docs/maps/maps-getting-started.asciidoc b/docs/maps/maps-getting-started.asciidoc index 014be570253bb..89d06fce60183 100644 --- a/docs/maps/maps-getting-started.asciidoc +++ b/docs/maps/maps-getting-started.asciidoc @@ -49,7 +49,7 @@ and lighter shades will symbolize countries with less traffic. . From the **Layer** dropdown menu, select **World Countries**. . In **Statistics source**, set: -** **Index pattern** to **kibana_sample_data_logs** +** **Data view** to **kibana_sample_data_logs** ** **Join field** to **geo.dest** . Click **Add layer**. @@ -95,7 +95,7 @@ The layer is only visible when users zoom in. . Click **Add layer**, and then click **Documents**. -. Set **Index pattern** to **kibana_sample_data_logs**. +. Set **Data view** to **kibana_sample_data_logs**. . Set **Scaling** to *Limits results to 10000.* @@ -129,7 +129,7 @@ more total bytes transferred, and smaller circles will symbolize grids with less bytes transferred. . Click **Add layer**, and select **Clusters and grids**. -. Set **Index pattern** to **kibana_sample_data_logs**. +. Set **Data view** to **kibana_sample_data_logs**. . Click **Add layer**. . In **Layer settings**, set: ** **Name** to `Total Requests and Bytes` diff --git a/docs/maps/reverse-geocoding-tutorial.asciidoc b/docs/maps/reverse-geocoding-tutorial.asciidoc index 0c942f120a4da..8760d3ab4df8b 100644 --- a/docs/maps/reverse-geocoding-tutorial.asciidoc +++ b/docs/maps/reverse-geocoding-tutorial.asciidoc @@ -141,7 +141,7 @@ PUT kibana_sample_data_logs/_settings ---------------------------------- . Open the main menu, and click *Discover*. -. Set the index pattern to *kibana_sample_data_logs*. +. Set the data view to *kibana_sample_data_logs*. . Open the <>, and set the time range to the last 30 days. . Scan through the list of *Available fields* until you find the `csa.GEOID` field. You can also search for the field by name. . Click image:images/reverse-geocoding-tutorial/add-icon.png[Add icon] to toggle the field into the document table. @@ -162,10 +162,10 @@ Now that our web traffic contains CSA region identifiers, you'll visualize CSA r . Click *Choropleth*. . For *Boundaries source*: .. Select *Points, lines, and polygons from Elasticsearch*. -.. Set *Index pattern* to *csa*. +.. Set *Data view* to *csa*. .. Set *Join field* to *GEOID*. . For *Statistics source*: -.. Set *Index pattern* to *kibana_sample_data_logs*. +.. Set *Data view* to *kibana_sample_data_logs*. .. Set *Join field* to *csa.GEOID.keyword*. . Click *Add layer*. . Scroll to *Layer Style* and Set *Label* to *Fixed*. diff --git a/docs/maps/trouble-shooting.asciidoc b/docs/maps/trouble-shooting.asciidoc index 60bcabad3a6b4..13c8b97c30b3d 100644 --- a/docs/maps/trouble-shooting.asciidoc +++ b/docs/maps/trouble-shooting.asciidoc @@ -21,18 +21,18 @@ image::maps/images/inspector.png[] === Solutions to common problems [float] -==== Index not listed when adding layer +==== Data view not listed when adding layer * Verify your geospatial data is correctly mapped as {ref}/geo-point.html[geo_point] or {ref}/geo-shape.html[geo_shape]. - ** Run `GET myIndexPatternTitle/_field_caps?fields=myGeoFieldName` in <>, replacing `myIndexPatternTitle` and `myGeoFieldName` with your index pattern title and geospatial field name. + ** Run `GET myIndexName/_field_caps?fields=myGeoFieldName` in <>, replacing `myIndexName` and `myGeoFieldName` with your index and geospatial field name. ** Ensure response specifies `type` as `geo_point` or `geo_shape`. -* Verify your geospatial data is correctly mapped in your <>. - ** Open your index pattern in <>. +* Verify your geospatial data is correctly mapped in your <>. + ** Open your data view in <>. ** Ensure your geospatial field type is `geo_point` or `geo_shape`. ** Ensure your geospatial field is searchable and aggregatable. ** If your geospatial field type does not match your Elasticsearch mapping, click the *Refresh* button to refresh the field list from Elasticsearch. -* Index patterns with thousands of fields can exceed the default maximum payload size. -Increase <> for large index patterns. +* Data views with thousands of fields can exceed the default maximum payload size. +Increase <> for large data views. [float] ==== Features are not displayed diff --git a/docs/maps/vector-tooltips.asciidoc b/docs/maps/vector-tooltips.asciidoc index 2dda35aa28f76..2e4ee99d5b84f 100644 --- a/docs/maps/vector-tooltips.asciidoc +++ b/docs/maps/vector-tooltips.asciidoc @@ -18,7 +18,7 @@ image::maps/images/multifeature_tooltip.png[] ==== Format tooltips You can format the attributes in a tooltip by adding <> to your -index pattern. You can use field formatters to round numbers, provide units, +data view. You can use field formatters to round numbers, provide units, and even display images in your tooltip. [float] diff --git a/docs/user/security/audit-logging.asciidoc b/docs/user/security/audit-logging.asciidoc index 5391e88350943..926331008e990 100644 --- a/docs/user/security/audit-logging.asciidoc +++ b/docs/user/security/audit-logging.asciidoc @@ -144,6 +144,10 @@ Refer to the corresponding {es} logs for potential write errors. | `unknown` | User is updating a space. | `failure` | User is not authorized to update a space. +.2+| `alert_update` +| `unknown` | User is updating an alert. +| `failure` | User is not authorized to update an alert. + 3+a| ====== Type: deletion @@ -214,6 +218,14 @@ Refer to the corresponding {es} logs for potential write errors. | `success` | User has accessed a space as part of a search operation. | `failure` | User is not authorized to search for spaces. +.2+| `alert_get` +| `success` | User has accessed an alert. +| `failure` | User is not authorized to access an alert. + +.2+| `alert_find` +| `success` | User has accessed an alert as part of a search operation. +| `failure` | User is not authorized to access alerts. + 3+a| ===== Category: web diff --git a/examples/developer_examples/public/index.ts b/examples/developer_examples/public/index.ts index a6e5748765ab6..8fcbda387abf0 100644 --- a/examples/developer_examples/public/index.ts +++ b/examples/developer_examples/public/index.ts @@ -10,4 +10,4 @@ import { DeveloperExamplesPlugin } from './plugin'; export const plugin = () => new DeveloperExamplesPlugin(); -export { DeveloperExamplesSetup } from './plugin'; +export type { DeveloperExamplesSetup } from './plugin'; diff --git a/examples/embeddable_examples/common/index.ts b/examples/embeddable_examples/common/index.ts index bea814e5a3ed0..4ff60ffb3afcf 100644 --- a/examples/embeddable_examples/common/index.ts +++ b/examples/embeddable_examples/common/index.ts @@ -6,5 +6,6 @@ * Side Public License, v 1. */ -export { TodoSavedObjectAttributes } from './todo_saved_object_attributes'; -export { BookSavedObjectAttributes, BOOK_SAVED_OBJECT } from './book_saved_object_attributes'; +export type { TodoSavedObjectAttributes } from './todo_saved_object_attributes'; +export type { BookSavedObjectAttributes } from './book_saved_object_attributes'; +export { BOOK_SAVED_OBJECT } from './book_saved_object_attributes'; diff --git a/examples/embeddable_examples/public/index.ts b/examples/embeddable_examples/public/index.ts index 365c001559843..43d8db39692c7 100644 --- a/examples/embeddable_examples/public/index.ts +++ b/examples/embeddable_examples/public/index.ts @@ -6,14 +6,16 @@ * Side Public License, v 1. */ +export type { HelloWorldEmbeddableFactory } from './hello_world'; export { HELLO_WORLD_EMBEDDABLE, HelloWorldEmbeddable, HelloWorldEmbeddableFactoryDefinition, - HelloWorldEmbeddableFactory, } from './hello_world'; -export { ListContainer, LIST_CONTAINER, ListContainerFactory } from './list_container'; -export { TODO_EMBEDDABLE, TodoEmbeddableFactory } from './todo'; +export type { ListContainerFactory } from './list_container'; +export { ListContainer, LIST_CONTAINER } from './list_container'; +export type { TodoEmbeddableFactory } from './todo'; +export { TODO_EMBEDDABLE } from './todo'; export { BOOK_EMBEDDABLE } from './book'; @@ -21,10 +23,8 @@ export { SIMPLE_EMBEDDABLE } from './migrations'; import { EmbeddableExamplesPlugin } from './plugin'; -export { - SearchableListContainer, - SEARCHABLE_LIST_CONTAINER, - SearchableListContainerFactory, -} from './searchable_list_container'; -export { MULTI_TASK_TODO_EMBEDDABLE, MultiTaskTodoEmbeddableFactory } from './multi_task_todo'; +export type { SearchableListContainerFactory } from './searchable_list_container'; +export { SearchableListContainer, SEARCHABLE_LIST_CONTAINER } from './searchable_list_container'; +export type { MultiTaskTodoEmbeddableFactory } from './multi_task_todo'; +export { MULTI_TASK_TODO_EMBEDDABLE } from './multi_task_todo'; export const plugin = () => new EmbeddableExamplesPlugin(); diff --git a/examples/embeddable_examples/public/list_container/index.ts b/examples/embeddable_examples/public/list_container/index.ts index cda0e55e59eef..299c3eeae42cd 100644 --- a/examples/embeddable_examples/public/list_container/index.ts +++ b/examples/embeddable_examples/public/list_container/index.ts @@ -7,4 +7,5 @@ */ export { ListContainer, LIST_CONTAINER } from './list_container'; -export { ListContainerFactoryDefinition, ListContainerFactory } from './list_container_factory'; +export type { ListContainerFactory } from './list_container_factory'; +export { ListContainerFactoryDefinition } from './list_container_factory'; diff --git a/examples/embeddable_examples/public/searchable_list_container/index.ts b/examples/embeddable_examples/public/searchable_list_container/index.ts index 5448731abf2c1..cea0154be812d 100644 --- a/examples/embeddable_examples/public/searchable_list_container/index.ts +++ b/examples/embeddable_examples/public/searchable_list_container/index.ts @@ -7,7 +7,5 @@ */ export { SearchableListContainer, SEARCHABLE_LIST_CONTAINER } from './searchable_list_container'; -export { - SearchableListContainerFactoryDefinition, - SearchableListContainerFactory, -} from './searchable_list_container_factory'; +export type { SearchableListContainerFactory } from './searchable_list_container_factory'; +export { SearchableListContainerFactoryDefinition } from './searchable_list_container_factory'; diff --git a/examples/locator_examples/public/index.ts b/examples/locator_examples/public/index.ts index 50da3501805fa..e71d6bf1e5b01 100644 --- a/examples/locator_examples/public/index.ts +++ b/examples/locator_examples/public/index.ts @@ -8,12 +8,12 @@ import { LocatorExamplesPlugin } from './plugin'; -export { +export type { HelloLocator, HelloLocatorV1Params, HelloLocatorV2Params, HelloLocatorParams, - HELLO_LOCATOR, } from './locator'; +export { HELLO_LOCATOR } from './locator'; export const plugin = () => new LocatorExamplesPlugin(); diff --git a/examples/search_examples/public/index.ts b/examples/search_examples/public/index.ts index fd557f752a38e..c1361facc2941 100644 --- a/examples/search_examples/public/index.ts +++ b/examples/search_examples/public/index.ts @@ -15,4 +15,4 @@ import { SearchExamplesPlugin } from './plugin'; export function plugin() { return new SearchExamplesPlugin(); } -export { SearchExamplesPluginSetup, SearchExamplesPluginStart } from './types'; +export type { SearchExamplesPluginSetup, SearchExamplesPluginStart } from './types'; diff --git a/examples/search_examples/server/index.ts b/examples/search_examples/server/index.ts index f351681a1041a..75c23e8e89257 100644 --- a/examples/search_examples/server/index.ts +++ b/examples/search_examples/server/index.ts @@ -13,4 +13,4 @@ export function plugin(initializerContext: PluginInitializerContext) { return new SearchExamplesPlugin(initializerContext); } -export { SearchExamplesPluginSetup, SearchExamplesPluginStart } from './types'; +export type { SearchExamplesPluginSetup, SearchExamplesPluginStart } from './types'; diff --git a/package.json b/package.json index ae8c9621b1893..440a30d36534e 100644 --- a/package.json +++ b/package.json @@ -95,9 +95,9 @@ "@dnd-kit/core": "^3.1.1", "@dnd-kit/sortable": "^4.0.0", "@dnd-kit/utilities": "^2.0.0", - "@elastic/apm-synthtrace": "link:bazel-bin/packages/elastic-apm-synthtrace", "@elastic/apm-rum": "^5.9.1", "@elastic/apm-rum-react": "^1.3.1", + "@elastic/apm-synthtrace": "link:bazel-bin/packages/elastic-apm-synthtrace", "@elastic/charts": "38.1.3", "@elastic/datemath": "link:bazel-bin/packages/elastic-datemath", "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.35", @@ -111,7 +111,10 @@ "@elastic/request-crypto": "1.1.4", "@elastic/safer-lodash-set": "link:bazel-bin/packages/elastic-safer-lodash-set", "@elastic/search-ui-app-search-connector": "^1.6.0", + "@emotion/cache": "^11.4.0", + "@emotion/css": "^11.4.0", "@emotion/react": "^11.4.0", + "@emotion/serialize": "^1.0.2", "@hapi/accept": "^5.0.2", "@hapi/boom": "^9.1.4", "@hapi/cookie": "^11.0.2", @@ -542,6 +545,7 @@ "@types/jest-when": "^2.7.2", "@types/joi": "^17.2.3", "@types/jquery": "^3.3.31", + "@types/js-levenshtein": "^1.1.0", "@types/js-search": "^1.4.0", "@types/js-yaml": "^3.11.1", "@types/jsdom": "^16.2.3", @@ -595,6 +599,7 @@ "@types/react-router-dom": "^5.1.5", "@types/react-test-renderer": "^16.9.1", "@types/react-virtualized": "^9.18.7", + "@types/react-vis": "^1.11.9", "@types/read-pkg": "^4.0.0", "@types/recompose": "^0.30.6", "@types/reduce-reducers": "^1.0.0", @@ -633,9 +638,9 @@ "@types/xml2js": "^0.4.5", "@types/yauzl": "^2.9.1", "@types/zen-observable": "^0.8.0", - "@typescript-eslint/eslint-plugin": "^4.31.2", - "@typescript-eslint/parser": "^4.31.2", - "@typescript-eslint/typescript-estree": "^4.31.2", + "@typescript-eslint/eslint-plugin": "^5.2.0", + "@typescript-eslint/parser": "^5.2.0", + "@typescript-eslint/typescript-estree": "^5.2.0", "@yarnpkg/lockfile": "^1.1.0", "abab": "^2.0.4", "aggregate-error": "^3.1.0", diff --git a/packages/kbn-cli-dev-mode/src/get_server_watch_paths.test.ts b/packages/kbn-cli-dev-mode/src/get_server_watch_paths.test.ts index 9cb902882ffd7..9fa13b013f195 100644 --- a/packages/kbn-cli-dev-mode/src/get_server_watch_paths.test.ts +++ b/packages/kbn-cli-dev-mode/src/get_server_watch_paths.test.ts @@ -68,6 +68,7 @@ it('produces the right watch and ignore list', () => { /x-pack/plugins/reporting/chromium, /x-pack/plugins/security_solution/cypress, /x-pack/plugins/apm/scripts, + /x-pack/plugins/apm/ftr_e2e, /x-pack/plugins/canvas/canvas_plugin_src, /x-pack/plugins/cases/server/scripts, /x-pack/plugins/lists/scripts, diff --git a/packages/kbn-cli-dev-mode/src/get_server_watch_paths.ts b/packages/kbn-cli-dev-mode/src/get_server_watch_paths.ts index 53f52279c8be8..e1bd431d280a4 100644 --- a/packages/kbn-cli-dev-mode/src/get_server_watch_paths.ts +++ b/packages/kbn-cli-dev-mode/src/get_server_watch_paths.ts @@ -59,6 +59,7 @@ export function getServerWatchPaths({ pluginPaths, pluginScanDirs }: Options) { fromRoot('x-pack/plugins/reporting/chromium'), fromRoot('x-pack/plugins/security_solution/cypress'), fromRoot('x-pack/plugins/apm/scripts'), + fromRoot('x-pack/plugins/apm/ftr_e2e'), // prevents restarts for APM cypress tests fromRoot('x-pack/plugins/canvas/canvas_plugin_src'), // prevents server from restarting twice for Canvas plugin changes, fromRoot('x-pack/plugins/cases/server/scripts'), fromRoot('x-pack/plugins/lists/scripts'), diff --git a/packages/kbn-config-schema/src/duration/index.ts b/packages/kbn-config-schema/src/duration/index.ts index 6a05a00c9e871..1b1d47a24abd3 100644 --- a/packages/kbn-config-schema/src/duration/index.ts +++ b/packages/kbn-config-schema/src/duration/index.ts @@ -7,7 +7,8 @@ */ import { Duration, duration as momentDuration, DurationInputArg2, isDuration } from 'moment'; -export { Duration, isDuration }; +export type { Duration }; +export { isDuration }; const timeFormatRegex = /^(0|[1-9][0-9]*)(ms|s|m|h|d|w|M|Y)$/; diff --git a/packages/kbn-config-schema/src/index.ts b/packages/kbn-config-schema/src/index.ts index 68500a18530bc..8635421beb0a1 100644 --- a/packages/kbn-config-schema/src/index.ts +++ b/packages/kbn-config-schema/src/index.ts @@ -49,7 +49,8 @@ import { StreamType, } from './types'; -export { ObjectType, TypeOf, Type, Props, NullableProps }; +export type { TypeOf, Props, NullableProps }; +export { ObjectType, Type }; export { ByteSizeValue } from './byte_size_value'; export { SchemaTypeError, ValidationError } from './errors'; export { isConfigSchema } from './typeguards'; diff --git a/packages/kbn-config-schema/src/types/index.ts b/packages/kbn-config-schema/src/types/index.ts index d4098a2abf352..5152137985ff3 100644 --- a/packages/kbn-config-schema/src/types/index.ts +++ b/packages/kbn-config-schema/src/types/index.ts @@ -6,23 +6,35 @@ * Side Public License, v 1. */ -export { Type, TypeOptions } from './type'; +export type { TypeOptions } from './type'; +export { Type } from './type'; export { AnyType } from './any_type'; -export { ArrayOptions, ArrayType } from './array_type'; +export type { ArrayOptions } from './array_type'; +export { ArrayType } from './array_type'; export { BooleanType } from './boolean_type'; export { BufferType } from './buffer_type'; -export { ByteSizeOptions, ByteSizeType } from './byte_size_type'; -export { ConditionalType, ConditionalTypeValue } from './conditional_type'; -export { DurationOptions, DurationType } from './duration_type'; +export type { ByteSizeOptions } from './byte_size_type'; +export { ByteSizeType } from './byte_size_type'; +export type { ConditionalTypeValue } from './conditional_type'; +export { ConditionalType } from './conditional_type'; +export type { DurationOptions } from './duration_type'; +export { DurationType } from './duration_type'; export { LiteralType } from './literal_type'; export { MaybeType } from './maybe_type'; -export { MapOfOptions, MapOfType } from './map_type'; -export { NumberOptions, NumberType } from './number_type'; -export { ObjectType, ObjectTypeOptions, Props, NullableProps, TypeOf } from './object_type'; -export { RecordOfOptions, RecordOfType } from './record_type'; +export type { MapOfOptions } from './map_type'; +export { MapOfType } from './map_type'; +export type { NumberOptions } from './number_type'; +export { NumberType } from './number_type'; +export type { ObjectTypeOptions, Props, NullableProps, TypeOf } from './object_type'; +export { ObjectType } from './object_type'; +export type { RecordOfOptions } from './record_type'; +export { RecordOfType } from './record_type'; export { StreamType } from './stream_type'; -export { StringOptions, StringType } from './string_type'; +export type { StringOptions } from './string_type'; +export { StringType } from './string_type'; export { UnionType } from './union_type'; -export { URIOptions, URIType } from './uri_type'; +export type { URIOptions } from './uri_type'; +export { URIType } from './uri_type'; export { NeverType } from './never_type'; -export { IpType, IpOptions } from './ip_type'; +export type { IpOptions } from './ip_type'; +export { IpType } from './ip_type'; diff --git a/packages/kbn-config/src/index.ts b/packages/kbn-config/src/index.ts index 0068fc87855b0..272ee7598570c 100644 --- a/packages/kbn-config/src/index.ts +++ b/packages/kbn-config/src/index.ts @@ -19,16 +19,15 @@ export type { export { applyDeprecations, configDeprecationFactory } from './deprecation'; -export { - RawConfigurationProvider, - RawConfigService, - RawConfigAdapter, - getConfigFromFiles, -} from './raw'; +export type { RawConfigurationProvider, RawConfigAdapter } from './raw'; +export { RawConfigService, getConfigFromFiles } from './raw'; -export { ConfigService, IConfigService, ConfigValidateParameters } from './config_service'; -export { Config, ConfigPath, isConfigPath, hasConfigPathIntersection } from './config'; +export type { IConfigService, ConfigValidateParameters } from './config_service'; +export { ConfigService } from './config_service'; +export type { Config, ConfigPath } from './config'; +export { isConfigPath, hasConfigPathIntersection } from './config'; export { ObjectToConfigAdapter } from './object_to_config_adapter'; -export { CliArgs, Env, RawPackageInfo } from './env'; -export { EnvironmentMode, PackageInfo } from './types'; +export type { CliArgs, RawPackageInfo } from './env'; +export { Env } from './env'; +export type { EnvironmentMode, PackageInfo } from './types'; export { getPluginSearchPaths } from './plugins'; diff --git a/packages/kbn-config/src/raw/index.ts b/packages/kbn-config/src/raw/index.ts index 01ad83728aa08..be0a206e16b66 100644 --- a/packages/kbn-config/src/raw/index.ts +++ b/packages/kbn-config/src/raw/index.ts @@ -6,5 +6,6 @@ * Side Public License, v 1. */ -export { RawConfigService, RawConfigurationProvider, RawConfigAdapter } from './raw_config_service'; +export type { RawConfigurationProvider, RawConfigAdapter } from './raw_config_service'; +export { RawConfigService } from './raw_config_service'; export { getConfigFromFiles } from './read_config'; diff --git a/packages/kbn-dev-utils/src/proc_runner/errors.ts b/packages/kbn-dev-utils/src/proc_runner/errors.ts deleted file mode 100644 index d4d252476b76e..0000000000000 --- a/packages/kbn-dev-utils/src/proc_runner/errors.ts +++ /dev/null @@ -1,23 +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 - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -const $isCliError = Symbol('isCliError'); - -interface CliError extends Error { - [$isCliError]: boolean; -} - -export function createCliError(message: string) { - const error: Partial = new Error(message); - error[$isCliError] = true; - return error as CliError; -} - -export function isCliError(error: any): error is CliError { - return error && !!error[$isCliError]; -} diff --git a/packages/kbn-dev-utils/src/proc_runner/proc.ts b/packages/kbn-dev-utils/src/proc_runner/proc.ts index c9a520de6eb4d..8238e29413309 100644 --- a/packages/kbn-dev-utils/src/proc_runner/proc.ts +++ b/packages/kbn-dev-utils/src/proc_runner/proc.ts @@ -19,7 +19,7 @@ const treeKillAsync = promisify((...args: [number, string, any]) => treeKill(... import { ToolingLog } from '../tooling_log'; import { observeLines } from '../stdio'; -import { createCliError } from './errors'; +import { createFailError } from '../run'; const SECOND = 1000; const STOP_TIMEOUT = 30 * SECOND; @@ -57,7 +57,7 @@ export type Proc = ReturnType; export function startProc(name: string, options: ProcOptions, log: ToolingLog) { const { cmd, args, cwd, env, stdin } = options; - log.info('[%s] > %s', name, cmd, args.join(' ')); + log.info('[%s] > %s', name, cmd === process.execPath ? 'node' : cmd, args.join(' ')); // spawn fails with ENOENT when either the // cmd or cwd don't exist, so we check for the cwd @@ -97,7 +97,9 @@ export function startProc(name: string, options: ProcOptions, log: ToolingLog) { } // JVM exits with 143 on SIGTERM and 130 on SIGINT, dont' treat then as errors if (code > 0 && !(code === 143 || code === 130)) { - throw createCliError(`[${name}] exited with code ${code}`); + throw createFailError(`[${name}] exited with code ${code}`, { + exitCode: code, + }); } return code; diff --git a/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts b/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts index 8ef32411621f8..cb2ac2604e035 100644 --- a/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts +++ b/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts @@ -11,7 +11,7 @@ import { filter, first, catchError, map } from 'rxjs/operators'; import exitHook from 'exit-hook'; import { ToolingLog } from '../tooling_log'; -import { createCliError } from './errors'; +import { createFailError } from '../run'; import { Proc, ProcOptions, startProc } from './proc'; const SECOND = 1000; @@ -61,7 +61,6 @@ export class ProcRunner { */ async run(name: string, options: RunOptions) { const { - cmd, args = [], cwd = process.cwd(), stdin = undefined, @@ -69,6 +68,7 @@ export class ProcRunner { waitTimeout = 15 * MINUTE, env = process.env, } = options; + const cmd = options.cmd === 'node' ? process.execPath : options.cmd; if (this.closing) { throw new Error('ProcRunner is closing'); @@ -99,7 +99,7 @@ export class ProcRunner { first(), catchError((err) => { if (err.name !== 'EmptyError') { - throw createCliError(`[${name}] exited without matching pattern: ${wait}`); + throw createFailError(`[${name}] exited without matching pattern: ${wait}`); } else { throw err; } @@ -110,7 +110,7 @@ export class ProcRunner { : Rx.timer(waitTimeout).pipe( map(() => { const sec = waitTimeout / SECOND; - throw createCliError( + throw createFailError( `[${name}] failed to match pattern within ${sec} seconds [pattern=${wait}]` ); }) diff --git a/packages/kbn-dev-utils/src/tooling_log/index.ts b/packages/kbn-dev-utils/src/tooling_log/index.ts index 4da54ee9bfeae..2c7216c87c419 100644 --- a/packages/kbn-dev-utils/src/tooling_log/index.ts +++ b/packages/kbn-dev-utils/src/tooling_log/index.ts @@ -8,8 +8,10 @@ export { ToolingLog } from './tooling_log'; export type { ToolingLogOptions } from './tooling_log'; -export { ToolingLogTextWriter, ToolingLogTextWriterConfig } from './tooling_log_text_writer'; -export { pickLevelFromFlags, parseLogLevel, LogLevel, ParsedLogLevel } from './log_levels'; +export type { ToolingLogTextWriterConfig } from './tooling_log_text_writer'; +export { ToolingLogTextWriter } from './tooling_log_text_writer'; +export type { LogLevel, ParsedLogLevel } from './log_levels'; +export { pickLevelFromFlags, parseLogLevel } from './log_levels'; export { ToolingLogCollectingWriter } from './tooling_log_collecting_writer'; export type { Writer } from './writer'; export type { Message } from './message'; diff --git a/packages/kbn-dev-utils/src/vscode_config/managed_config_keys.ts b/packages/kbn-dev-utils/src/vscode_config/managed_config_keys.ts index 32cc91ad74c50..63a05910653af 100644 --- a/packages/kbn-dev-utils/src/vscode_config/managed_config_keys.ts +++ b/packages/kbn-dev-utils/src/vscode_config/managed_config_keys.ts @@ -37,6 +37,8 @@ export const MANAGED_CONFIG_KEYS: ManagedConfigKey[] = [ value: { ['**/packages/kbn-pm/dist/index.js']: true, ['**/api_docs']: true, + ['**/tsconfig.tsbuildinfo']: true, + ['**/*.map']: true, }, }, { diff --git a/packages/kbn-es-archiver/src/lib/index.ts b/packages/kbn-es-archiver/src/lib/index.ts index 0e47294909add..ee37591e1f2c3 100644 --- a/packages/kbn-es-archiver/src/lib/index.ts +++ b/packages/kbn-es-archiver/src/lib/index.ts @@ -20,7 +20,8 @@ export { export { createFilterRecordsStream } from './records'; -export { createStats, Stats } from './stats'; +export type { Stats } from './stats'; +export { createStats } from './stats'; export { isGzip, diff --git a/packages/kbn-es-query/src/es_query/index.ts b/packages/kbn-es-query/src/es_query/index.ts index 8045b625cd921..192834c9fd485 100644 --- a/packages/kbn-es-query/src/es_query/index.ts +++ b/packages/kbn-es-query/src/es_query/index.ts @@ -7,11 +7,12 @@ */ export { migrateFilter } from './migrate_filter'; -export { buildEsQuery, EsQueryConfig } from './build_es_query'; +export type { EsQueryConfig } from './build_es_query'; +export { buildEsQuery } from './build_es_query'; export { buildQueryFromFilters } from './from_filters'; export { luceneStringToDsl } from './lucene_string_to_dsl'; export { decorateQuery } from './decorate_query'; -export { +export type { IndexPatternBase, IndexPatternFieldBase, IFieldSubType, diff --git a/packages/kbn-es-query/src/filters/index.ts b/packages/kbn-es-query/src/filters/index.ts index 21011db9462ca..c202892cd9c3f 100644 --- a/packages/kbn-es-query/src/filters/index.ts +++ b/packages/kbn-es-query/src/filters/index.ts @@ -6,12 +6,12 @@ * Side Public License, v 1. */ +export type { FilterCompareOptions } from './helpers'; export { dedupFilters, uniqFilters, compareFilters, COMPARE_ALL_OPTIONS, - FilterCompareOptions, cleanFilter, isFilter, isFilters, @@ -53,7 +53,7 @@ export { getFilterParams, } from './build_filters'; -export { +export type { Query, Filter, LatLon, diff --git a/packages/kbn-es-query/src/kuery/index.ts b/packages/kbn-es-query/src/kuery/index.ts index 6e03b3cb18f4c..868904125dc44 100644 --- a/packages/kbn-es-query/src/kuery/index.ts +++ b/packages/kbn-es-query/src/kuery/index.ts @@ -23,4 +23,4 @@ export const toElasticsearchQuery = (...params: Parameters index) { + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } + } + } + + if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') { + closeCurlyIndex = str.indexOf('}', index); + if (closeCurlyIndex > index) { + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) { + return true; + } + } + } + + if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') { + closeParenIndex = str.indexOf(')', index); + if (closeParenIndex > index) { + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } + } + } + + if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') { + if (pipeIndex < index) { + pipeIndex = str.indexOf('|', index); + } + if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') { + closeParenIndex = str.indexOf(')', pipeIndex); + if (closeParenIndex > pipeIndex) { + backSlashIndex = str.indexOf('\\', pipeIndex); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } + } + } + } + + if (str[index] === '\\') { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) { + index = n + 1; + } + } + + if (str[index] === '!') { + return true; + } + } else { + index++; + } + } + return false; +}; + +var relaxedCheck = function(str) { + if (str[0] === '!') { + return true; + } + var index = 0; + while (index < str.length) { + if (/[*?{}()[\]]/.test(str[index])) { + return true; + } + + if (str[index] === '\\') { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) { + index = n + 1; + } + } + + if (str[index] === '!') { + return true; + } + } else { + index++; + } + } + return false; +}; module.exports = function isGlob(str, options) { if (typeof str !== 'string' || str === '') { @@ -22209,32 +22309,14 @@ module.exports = function isGlob(str, options) { return true; } - var regex = strictRegex; - var match; + var check = strictCheck; - // optionally relax regex + // optionally relax check if (options && options.strict === false) { - regex = relaxedRegex; + check = relaxedCheck; } - while ((match = regex.exec(str))) { - if (match[2]) return true; - var idx = match.index + match[0].length; - - // if an open bracket/brace/paren is escaped, - // set the index to the next closing character - var open = match[1]; - var close = open ? chars[open] : null; - if (open && close) { - var n = str.indexOf(close, idx); - if (n !== -1) { - idx = n + 1; - } - } - - str = str.slice(idx); - } - return false; + return check(str); }; diff --git a/packages/kbn-pm/src/utils/log.ts b/packages/kbn-pm/src/utils/log.ts index 9dbfad2895793..ba4ee6941f540 100644 --- a/packages/kbn-pm/src/utils/log.ts +++ b/packages/kbn-pm/src/utils/log.ts @@ -38,4 +38,5 @@ class Log extends ToolingLog { } export const log = new Log(); -export { LogLevel, Log }; +export type { LogLevel }; +export { Log }; diff --git a/packages/kbn-securitysolution-autocomplete/src/field/index.tsx b/packages/kbn-securitysolution-autocomplete/src/field/index.tsx index 69408e919bb1e..a89e0a096b673 100644 --- a/packages/kbn-securitysolution-autocomplete/src/field/index.tsx +++ b/packages/kbn-securitysolution-autocomplete/src/field/index.tsx @@ -8,7 +8,7 @@ import React, { useCallback, useMemo, useState } from 'react'; import { EuiComboBox, EuiComboBoxOptionOption } from '@elastic/eui'; -import { IndexPatternBase, IndexPatternFieldBase } from '@kbn/es-query'; +import { DataViewBase, DataViewFieldBase } from '@kbn/es-query'; import { getGenericComboBoxProps, @@ -20,14 +20,14 @@ const AS_PLAIN_TEXT = { asPlainText: true }; interface OperatorProps { fieldInputWidth?: number; fieldTypeFilter?: string[]; - indexPattern: IndexPatternBase | undefined; + indexPattern: DataViewBase | undefined; isClearable: boolean; isDisabled: boolean; isLoading: boolean; isRequired?: boolean; - onChange: (a: IndexPatternFieldBase[]) => void; + onChange: (a: DataViewFieldBase[]) => void; placeholder: string; - selectedField: IndexPatternFieldBase | undefined; + selectedField: DataViewFieldBase | undefined; } export const FieldComponent: React.FC = ({ @@ -56,7 +56,7 @@ export const FieldComponent: React.FC = ({ const handleValuesChange = useCallback( (newOptions: EuiComboBoxOptionOption[]): void => { - const newValues: IndexPatternFieldBase[] = newOptions.map( + const newValues: DataViewFieldBase[] = newOptions.map( ({ label }) => availableFields[labels.indexOf(label)] ); onChange(newValues); @@ -94,13 +94,13 @@ export const FieldComponent: React.FC = ({ FieldComponent.displayName = 'Field'; interface ComboBoxFields { - availableFields: IndexPatternFieldBase[]; - selectedFields: IndexPatternFieldBase[]; + availableFields: DataViewFieldBase[]; + selectedFields: DataViewFieldBase[]; } const getComboBoxFields = ( - indexPattern: IndexPatternBase | undefined, - selectedField: IndexPatternFieldBase | undefined, + indexPattern: DataViewBase | undefined, + selectedField: DataViewFieldBase | undefined, fieldTypeFilter: string[] ): ComboBoxFields => { const existingFields = getExistingFields(indexPattern); @@ -113,29 +113,27 @@ const getComboBoxFields = ( const getComboBoxProps = (fields: ComboBoxFields): GetGenericComboBoxPropsReturn => { const { availableFields, selectedFields } = fields; - return getGenericComboBoxProps({ + return getGenericComboBoxProps({ getLabel: (field) => field.name, options: availableFields, selectedOptions: selectedFields, }); }; -const getExistingFields = (indexPattern: IndexPatternBase | undefined): IndexPatternFieldBase[] => { +const getExistingFields = (indexPattern: DataViewBase | undefined): DataViewFieldBase[] => { return indexPattern != null ? indexPattern.fields : []; }; -const getSelectedFields = ( - selectedField: IndexPatternFieldBase | undefined -): IndexPatternFieldBase[] => { +const getSelectedFields = (selectedField: DataViewFieldBase | undefined): DataViewFieldBase[] => { return selectedField ? [selectedField] : []; }; const getAvailableFields = ( - existingFields: IndexPatternFieldBase[], - selectedFields: IndexPatternFieldBase[], + existingFields: DataViewFieldBase[], + selectedFields: DataViewFieldBase[], fieldTypeFilter: string[] -): IndexPatternFieldBase[] => { - const fieldsByName = new Map(); +): DataViewFieldBase[] => { + const fieldsByName = new Map(); existingFields.forEach((f) => fieldsByName.set(f.name, f)); selectedFields.forEach((f) => fieldsByName.set(f.name, f)); diff --git a/packages/kbn-securitysolution-hook-utils/src/use_async/index.test.ts b/packages/kbn-securitysolution-hook-utils/src/use_async/index.test.ts index 886a3dd27befc..7503f2c5c2be8 100644 --- a/packages/kbn-securitysolution-hook-utils/src/use_async/index.test.ts +++ b/packages/kbn-securitysolution-hook-utils/src/use_async/index.test.ts @@ -18,6 +18,13 @@ interface TestArgs { type TestReturn = Promise; describe('useAsync', () => { + /** + * Timeout for both jest tests and for the waitForNextUpdate. + * jest tests default to 5 seconds and waitForNextUpdate defaults to 1 second. + * 20_0000 = 20,000 milliseconds = 20 seconds + */ + const timeout = 20_000; + let fn: jest.Mock; let args: TestArgs; @@ -31,16 +38,20 @@ describe('useAsync', () => { expect(fn).not.toHaveBeenCalled(); }); - it('invokes the function when start is called', async () => { - const { result, waitForNextUpdate } = renderHook(() => useAsync(fn)); + it( + 'invokes the function when start is called', + async () => { + const { result, waitForNextUpdate } = renderHook(() => useAsync(fn)); - act(() => { - result.current.start(args); - }); - await waitForNextUpdate(); + act(() => { + result.current.start(args); + }); + await waitForNextUpdate({ timeout }); - expect(fn).toHaveBeenCalled(); - }); + expect(fn).toHaveBeenCalled(); + }, + timeout + ); it('invokes the function with start args', async () => { const { result, waitForNextUpdate } = renderHook(() => useAsync(fn)); @@ -49,84 +60,99 @@ describe('useAsync', () => { act(() => { result.current.start(args); }); - await waitForNextUpdate(); + await waitForNextUpdate({ timeout }); expect(fn).toHaveBeenCalledWith(expectedArgs); }); - it('populates result with the resolved value of the fn', async () => { - const { result, waitForNextUpdate } = renderHook(() => useAsync(fn)); - fn.mockResolvedValue({ resolved: 'value' }); - - act(() => { - result.current.start(args); - }); - await waitForNextUpdate(); - - expect(result.current.result).toEqual({ resolved: 'value' }); - expect(result.current.error).toBeUndefined(); - }); - - it('populates error if function rejects', async () => { - fn.mockRejectedValue(new Error('whoops')); - const { result, waitForNextUpdate } = renderHook(() => useAsync(fn)); - - act(() => { - result.current.start(args); - }); - await waitForNextUpdate(); - - expect(result.current.result).toBeUndefined(); - expect(result.current.error).toEqual(new Error('whoops')); - }); - - it('populates the loading state while the function is pending', async () => { - let resolve: () => void; - fn.mockImplementation(() => new Promise((_resolve) => (resolve = _resolve))); - - const { result, waitForNextUpdate } = renderHook(() => useAsync(fn)); - - act(() => { - result.current.start(args); - }); - - expect(result.current.loading).toBe(true); - - act(() => resolve()); - await waitForNextUpdate(); - - expect(result.current.loading).toBe(false); - }); - - it('multiple start calls reset state', async () => { - let resolve: (result: string) => void; - fn.mockImplementation(() => new Promise((_resolve) => (resolve = _resolve))); - - const { result, waitForNextUpdate } = renderHook(() => useAsync(fn)); - - act(() => { - result.current.start(args); - }); - - expect(result.current.loading).toBe(true); - - act(() => resolve('result')); - await waitForNextUpdate(); - - expect(result.current.loading).toBe(false); - expect(result.current.result).toBe('result'); - - act(() => { - result.current.start(args); - }); - - expect(result.current.loading).toBe(true); - expect(result.current.result).toBe(undefined); - - act(() => resolve('result')); - await waitForNextUpdate(); - - expect(result.current.loading).toBe(false); - expect(result.current.result).toBe('result'); - }); + it( + 'populates result with the resolved value of the fn', + async () => { + const { result, waitForNextUpdate } = renderHook(() => useAsync(fn)); + fn.mockResolvedValue({ resolved: 'value' }); + + act(() => { + result.current.start(args); + }); + await waitForNextUpdate({ timeout }); + + expect(result.current.result).toEqual({ resolved: 'value' }); + expect(result.current.error).toBeUndefined(); + }, + timeout + ); + + it( + 'populates error if function rejects', + async () => { + fn.mockRejectedValue(new Error('whoops')); + const { result, waitForNextUpdate } = renderHook(() => useAsync(fn)); + + act(() => { + result.current.start(args); + }); + await waitForNextUpdate({ timeout }); + + expect(result.current.result).toBeUndefined(); + expect(result.current.error).toEqual(new Error('whoops')); + }, + timeout + ); + + it( + 'populates the loading state while the function is pending', + async () => { + let resolve: () => void; + fn.mockImplementation(() => new Promise((_resolve) => (resolve = _resolve))); + + const { result, waitForNextUpdate } = renderHook(() => useAsync(fn)); + + act(() => { + result.current.start(args); + }); + + expect(result.current.loading).toBe(true); + + act(() => resolve()); + await waitForNextUpdate({ timeout }); + + expect(result.current.loading).toBe(false); + }, + timeout + ); + + it( + 'multiple start calls reset state', + async () => { + let resolve: (result: string) => void; + fn.mockImplementation(() => new Promise((_resolve) => (resolve = _resolve))); + + const { result, waitForNextUpdate } = renderHook(() => useAsync(fn)); + + act(() => { + result.current.start(args); + }); + + expect(result.current.loading).toBe(true); + + act(() => resolve('result')); + await waitForNextUpdate({ timeout }); + + expect(result.current.loading).toBe(false); + expect(result.current.result).toBe('result'); + + act(() => { + result.current.start(args); + }); + + expect(result.current.loading).toBe(true); + expect(result.current.result).toBe(undefined); + act(() => resolve('result')); + await waitForNextUpdate({ timeout }); + + expect(result.current.loading).toBe(false); + expect(result.current.result).toBe('result'); + }, + timeout + ); }); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.mock.ts new file mode 100644 index 0000000000000..703c26ffc3ff1 --- /dev/null +++ b/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.mock.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { ExportExceptionDetails } from '.'; + +export interface ExportExceptionDetailsMock { + listCount?: number; + missingListsCount?: number; + missingLists?: Array>; + itemCount?: number; + missingItemCount?: number; + missingItems?: Array>; +} + +export const getExceptionExportDetailsMock = ( + details?: ExportExceptionDetailsMock +): ExportExceptionDetails => ({ + exported_exception_list_count: details?.listCount ?? 0, + exported_exception_list_item_count: details?.itemCount ?? 0, + missing_exception_list_item_count: details?.missingItemCount ?? 0, + missing_exception_list_items: details?.missingItems ?? [], + missing_exception_lists: details?.missingLists ?? [], + missing_exception_lists_count: details?.missingListsCount ?? 0, +}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.test.ts new file mode 100644 index 0000000000000..96e25a024c71b --- /dev/null +++ b/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.test.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 + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { getExceptionExportDetailsMock } from './index.mock'; +import { exportExceptionDetailsSchema, ExportExceptionDetails } from '.'; +import { foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +describe('exportExceptionDetails', () => { + test('it should validate export meta', () => { + const payload = getExceptionExportDetailsMock(); + const decoded = exportExceptionDetailsSchema.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should strip out extra keys', () => { + const payload: ExportExceptionDetails & { + extraKey?: string; + } = getExceptionExportDetailsMock(); + payload.extraKey = 'some extra key'; + const decoded = exportExceptionDetailsSchema.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getExceptionExportDetailsMock()); + }); +}); diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.ts new file mode 100644 index 0000000000000..3617ae8c9b8b4 --- /dev/null +++ b/packages/kbn-securitysolution-io-ts-list-types/src/common/exception_export_details/index.ts @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import * as t from 'io-ts'; +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; + +export const exportExceptionDetails = { + exported_exception_list_count: t.number, + exported_exception_list_item_count: t.number, + missing_exception_list_item_count: t.number, + missing_exception_list_items: t.array( + t.exact( + t.type({ + item_id: NonEmptyString, + }) + ) + ), + missing_exception_lists: t.array( + t.exact( + t.type({ + list_id: NonEmptyString, + }) + ) + ), + missing_exception_lists_count: t.number, +}; + +export const exportExceptionDetailsSchema = t.exact(t.type(exportExceptionDetails)); + +export type ExportExceptionDetails = t.TypeOf; diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/index.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/index.ts index 51b32f3fafa77..81ecd58cb397c 100644 --- a/packages/kbn-securitysolution-io-ts-list-types/src/common/index.ts +++ b/packages/kbn-securitysolution-io-ts-list-types/src/common/index.ts @@ -23,6 +23,7 @@ export * from './entry_match'; export * from './entry_match_any'; export * from './entry_match_wildcard'; export * from './entry_nested'; +export * from './exception_export_details'; export * from './exception_list'; export * from './exception_list_item_type'; export * from './filter'; diff --git a/packages/kbn-server-route-repository/src/index.ts b/packages/kbn-server-route-repository/src/index.ts index 23621c5b213bc..1cc7bd0fdeebe 100644 --- a/packages/kbn-server-route-repository/src/index.ts +++ b/packages/kbn-server-route-repository/src/index.ts @@ -12,7 +12,7 @@ export { formatRequest } from './format_request'; export { parseEndpoint } from './parse_endpoint'; export { decodeRequestParams } from './decode_request_params'; export { routeValidationObject } from './route_validation_object'; -export { +export type { RouteRepositoryClient, ReturnOf, EndpointOf, diff --git a/packages/kbn-std/src/index.ts b/packages/kbn-std/src/index.ts index 33b40c20039f2..66fb98888444f 100644 --- a/packages/kbn-std/src/index.ts +++ b/packages/kbn-std/src/index.ts @@ -7,13 +7,15 @@ */ export { assertNever } from './assert_never'; -export { deepFreeze, Freezable } from './deep_freeze'; +export type { Freezable } from './deep_freeze'; +export { deepFreeze } from './deep_freeze'; export { get } from './get'; export { mapToObject } from './map_to_object'; export { merge } from './merge'; export { pick } from './pick'; export { withTimeout, isPromise } from './promise'; -export { isRelativeUrl, modifyUrl, getUrlOrigin, URLMeaningfulParts } from './url'; +export type { URLMeaningfulParts } from './url'; +export { isRelativeUrl, modifyUrl, getUrlOrigin } from './url'; export { unset } from './unset'; export { getFlattenedObject } from './get_flattened_object'; export { ensureNoUnsafeProperties } from './ensure_no_unsafe_properties'; diff --git a/packages/kbn-test/src/functional_test_runner/public_types.ts b/packages/kbn-test/src/functional_test_runner/public_types.ts index d94f61e23b8b8..d1a0f7998b0a9 100644 --- a/packages/kbn-test/src/functional_test_runner/public_types.ts +++ b/packages/kbn-test/src/functional_test_runner/public_types.ts @@ -103,4 +103,4 @@ export interface FtrConfigProviderContext { readConfigFile(path: string): Promise; } -export { Test, Suite }; +export type { Test, Suite }; diff --git a/packages/kbn-test/src/functional_tests/lib/index.ts b/packages/kbn-test/src/functional_tests/lib/index.ts index 93700a692dc81..bf2cc43159526 100644 --- a/packages/kbn-test/src/functional_tests/lib/index.ts +++ b/packages/kbn-test/src/functional_tests/lib/index.ts @@ -8,6 +8,7 @@ export { runKibanaServer } from './run_kibana_server'; export { runElasticsearch } from './run_elasticsearch'; -export { runFtr, hasTests, assertNoneExcluded, CreateFtrOptions, CreateFtrParams } from './run_ftr'; +export type { CreateFtrOptions, CreateFtrParams } from './run_ftr'; +export { runFtr, hasTests, assertNoneExcluded } from './run_ftr'; export { KIBANA_ROOT, KIBANA_FTR_SCRIPT, FUNCTIONAL_CONFIG_PATH, API_CONFIG_PATH } from './paths'; export { runCli } from './run_cli'; diff --git a/packages/kbn-test/src/index.ts b/packages/kbn-test/src/index.ts index 0ef9fbfed07a0..29e7e775ec171 100644 --- a/packages/kbn-test/src/index.ts +++ b/packages/kbn-test/src/index.ts @@ -25,14 +25,8 @@ export { runTests, startServers } from './functional_tests/tasks'; // @internal export { KIBANA_ROOT } from './functional_tests/lib/paths'; -export { - esTestConfig, - createTestEsCluster, - CreateTestEsClusterOptions, - EsTestCluster, - ICluster, - convertToKibanaClient, -} from './es'; +export type { CreateTestEsClusterOptions, EsTestCluster, ICluster } from './es'; +export { esTestConfig, createTestEsCluster, convertToKibanaClient } from './es'; export { kbnTestConfig, kibanaServerTestUser, kibanaTestUser, adminTestUser } from './kbn'; diff --git a/packages/kbn-test/src/jest/utils/testbed/index.ts b/packages/kbn-test/src/jest/utils/testbed/index.ts index 7abd4f000ab58..dfa5f011853c0 100644 --- a/packages/kbn-test/src/jest/utils/testbed/index.ts +++ b/packages/kbn-test/src/jest/utils/testbed/index.ts @@ -7,4 +7,4 @@ */ export { registerTestBed } from './testbed'; -export { TestBed, TestBedConfig, SetupFunc, UnwrapPromise } from './types'; +export type { TestBed, TestBedConfig, SetupFunc, UnwrapPromise } from './types'; diff --git a/packages/kbn-utility-types/src/index.ts b/packages/kbn-utility-types/src/index.ts index 921f056c6b755..92aa8d7ecc989 100644 --- a/packages/kbn-utility-types/src/index.ts +++ b/packages/kbn-utility-types/src/index.ts @@ -7,7 +7,7 @@ */ import { PromiseType } from 'utility-types'; -export { $Values, Assign, Class, Optional, Required } from 'utility-types'; +export type { $Values, Assign, Class, Optional, Required } from 'utility-types'; export type { JsonArray, diff --git a/typings/react_vis.d.ts b/scripts/eslint_with_types.js similarity index 80% rename from typings/react_vis.d.ts rename to scripts/eslint_with_types.js index 209dd398e86f4..e0371bc532170 100644 --- a/typings/react_vis.d.ts +++ b/scripts/eslint_with_types.js @@ -6,4 +6,5 @@ * Side Public License, v 1. */ -declare module 'react-vis'; +require('../src/setup_node_env'); +require('../src/dev/eslint').runEslintWithTypes(); diff --git a/src/core/public/doc_links/doc_links_service.ts b/src/core/public/doc_links/doc_links_service.ts index 7284a1a3f06f0..5dc214407e206 100644 --- a/src/core/public/doc_links/doc_links_service.ts +++ b/src/core/public/doc_links/doc_links_service.ts @@ -305,9 +305,9 @@ export class DocLinksService { }, observability: { guide: `${ELASTIC_WEBSITE_URL}guide/en/observability/${DOC_LINK_VERSION}/index.html`, - infrastructureThreshold: `{ELASTIC_WEBSITE_URL}guide/en/observability/${DOC_LINK_VERSION}/infrastructure-threshold-alert.html`, - logsThreshold: `{ELASTIC_WEBSITE_URL}guide/en/observability/${DOC_LINK_VERSION}/logs-threshold-alert.html`, - metricsThreshold: `{ELASTIC_WEBSITE_URL}guide/en/observability/${DOC_LINK_VERSION}/metrics-threshold-alert.html`, + infrastructureThreshold: `${ELASTIC_WEBSITE_URL}guide/en/observability/${DOC_LINK_VERSION}/infrastructure-threshold-alert.html`, + logsThreshold: `${ELASTIC_WEBSITE_URL}guide/en/observability/${DOC_LINK_VERSION}/logs-threshold-alert.html`, + metricsThreshold: `${ELASTIC_WEBSITE_URL}guide/en/observability/${DOC_LINK_VERSION}/metrics-threshold-alert.html`, monitorStatus: `${ELASTIC_WEBSITE_URL}guide/en/observability/${DOC_LINK_VERSION}/monitor-status-alert.html`, monitorUptime: `${ELASTIC_WEBSITE_URL}guide/en/observability/${DOC_LINK_VERSION}/monitor-uptime.html`, tlsCertificate: `${ELASTIC_WEBSITE_URL}guide/en/observability/${DOC_LINK_VERSION}/tls-certificate-alert.html`, diff --git a/src/core/server/saved_objects/object_types/registration.ts b/src/core/server/saved_objects/object_types/registration.ts index ce10896747178..a199ce947f96b 100644 --- a/src/core/server/saved_objects/object_types/registration.ts +++ b/src/core/server/saved_objects/object_types/registration.ts @@ -16,8 +16,9 @@ const legacyUrlAliasType: SavedObjectsType = { dynamic: false, properties: { sourceId: { type: 'keyword' }, - targetType: { type: 'keyword' }, targetNamespace: { type: 'keyword' }, + targetType: { type: 'keyword' }, + targetId: { type: 'keyword' }, resolveCounter: { type: 'long' }, disabled: { type: 'boolean' }, // other properties exist, but we aren't querying or aggregating on those, so we don't need to specify them (because we use `dynamic: false` above) diff --git a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.mock.ts b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.mock.ts index 382212cfbbd11..728f3b847b631 100644 --- a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.mock.ts +++ b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.mock.ts @@ -6,14 +6,14 @@ * Side Public License, v 1. */ -import type { findLegacyUrlAliases } from './find_legacy_url_aliases'; +import type { findLegacyUrlAliases } from './legacy_url_aliases'; import type * as InternalUtils from './internal_utils'; export const mockFindLegacyUrlAliases = jest.fn() as jest.MockedFunction< typeof findLegacyUrlAliases >; -jest.mock('./find_legacy_url_aliases', () => { +jest.mock('./legacy_url_aliases', () => { return { findLegacyUrlAliases: mockFindLegacyUrlAliases }; }); diff --git a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts index 87bb5017aab95..fd2afea999a07 100644 --- a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts +++ b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts @@ -9,7 +9,7 @@ import type { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import type { SavedObjectsSerializer } from '../../serialization'; import type { SavedObject, SavedObjectsBaseOptions } from '../../types'; -import { findLegacyUrlAliases } from './find_legacy_url_aliases'; +import { findLegacyUrlAliases } from './legacy_url_aliases'; import { getRootFields } from './included_fields'; import { getObjectKey, diff --git a/src/core/server/saved_objects/service/lib/legacy_url_aliases/delete_legacy_url_aliases.test.mock.ts b/src/core/server/saved_objects/service/lib/legacy_url_aliases/delete_legacy_url_aliases.test.mock.ts new file mode 100644 index 0000000000000..9585c40e6a161 --- /dev/null +++ b/src/core/server/saved_objects/service/lib/legacy_url_aliases/delete_legacy_url_aliases.test.mock.ts @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import type { getErrorMessage } from '../../../../elasticsearch'; + +export const mockGetEsErrorMessage = jest.fn() as jest.MockedFunction; + +jest.mock('../../../../elasticsearch', () => { + return { getErrorMessage: mockGetEsErrorMessage }; +}); + +// Mock these functions to return empty results, as this simplifies test cases and we don't need to exercise alternate code paths for these +jest.mock('@kbn/es-query', () => { + return { nodeTypes: { function: { buildNode: jest.fn() } } }; +}); +jest.mock('../search_dsl', () => { + return { getSearchDsl: jest.fn() }; +}); diff --git a/src/core/server/saved_objects/service/lib/legacy_url_aliases/delete_legacy_url_aliases.test.ts b/src/core/server/saved_objects/service/lib/legacy_url_aliases/delete_legacy_url_aliases.test.ts new file mode 100644 index 0000000000000..22c57fe3f280f --- /dev/null +++ b/src/core/server/saved_objects/service/lib/legacy_url_aliases/delete_legacy_url_aliases.test.ts @@ -0,0 +1,152 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { mockGetEsErrorMessage } from './delete_legacy_url_aliases.test.mock'; // Note: importing this file applies default mocks for other functions too + +import { errors as EsErrors } from '@elastic/elasticsearch'; + +import { elasticsearchClientMock } from '../../../../elasticsearch/client/mocks'; +import { typeRegistryMock } from '../../../saved_objects_type_registry.mock'; +import { ALL_NAMESPACES_STRING } from '../utils'; +import { deleteLegacyUrlAliases } from './delete_legacy_url_aliases'; +import type { DeleteLegacyUrlAliasesParams } from './delete_legacy_url_aliases'; + +type SetupParams = Pick< + DeleteLegacyUrlAliasesParams, + 'type' | 'id' | 'namespaces' | 'deleteBehavior' +>; + +describe('deleteLegacyUrlAliases', () => { + function setup(setupParams: SetupParams) { + return { + mappings: { properties: {} }, // doesn't matter, only used as an argument to getSearchDsl which is mocked + registry: typeRegistryMock.create(), // doesn't matter, only used as an argument to getSearchDsl which is mocked + client: elasticsearchClientMock.createElasticsearchClient(), + getIndexForType: jest.fn(), // doesn't matter + ...setupParams, + }; + } + + const type = 'obj-type'; + const id = 'obj-id'; + + it('throws an error if namespaces includes the "all namespaces" string', async () => { + const namespaces = [ALL_NAMESPACES_STRING]; + const params = setup({ type, id, namespaces, deleteBehavior: 'inclusive' }); + + await expect(() => deleteLegacyUrlAliases(params)).rejects.toThrowError( + `Failed to delete legacy URL aliases for ${type}/${id}: "namespaces" cannot include the * string` + ); + expect(params.client.updateByQuery).not.toHaveBeenCalled(); + }); + + it('throws an error if updateByQuery fails', async () => { + const namespaces = ['space-a', 'space-b']; + const params = setup({ type, id, namespaces, deleteBehavior: 'inclusive' }); + const esError = new EsErrors.ResponseError( + elasticsearchClientMock.createApiResponse({ + statusCode: 500, + body: { error: { type: 'es_type', reason: 'es_reason' } }, + }) + ); + params.client.updateByQuery.mockResolvedValueOnce( + elasticsearchClientMock.createErrorTransportRequestPromise(esError) + ); + mockGetEsErrorMessage.mockClear(); + mockGetEsErrorMessage.mockReturnValue('Oh no!'); + + await expect(() => deleteLegacyUrlAliases(params)).rejects.toThrowError( + `Failed to delete legacy URL aliases for ${type}/${id}: Oh no!` + ); + expect(params.client.updateByQuery).toHaveBeenCalledTimes(1); + expect(mockGetEsErrorMessage).toHaveBeenCalledTimes(1); + expect(mockGetEsErrorMessage).toHaveBeenCalledWith(esError); + }); + + describe('deleteBehavior "inclusive"', () => { + const deleteBehavior = 'inclusive' as const; + + it('when filtered namespaces is not empty, returns early', async () => { + const namespaces = ['default']; + const params = setup({ type, id, namespaces, deleteBehavior }); + + await deleteLegacyUrlAliases(params); + expect(params.client.updateByQuery).not.toHaveBeenCalled(); + }); + + it('when filtered namespaces is not empty, calls updateByQuery with expected script params', async () => { + const namespaces = ['space-a', 'default', 'space-b']; + const params = setup({ type, id, namespaces, deleteBehavior }); + + await deleteLegacyUrlAliases(params); + expect(params.client.updateByQuery).toHaveBeenCalledTimes(1); + expect(params.client.updateByQuery).toHaveBeenCalledWith( + expect.objectContaining({ + body: expect.objectContaining({ + script: expect.objectContaining({ + params: { + namespaces: ['space-a', 'space-b'], // 'default' is filtered out + matchTargetNamespaceOp: 'delete', + notMatchTargetNamespaceOp: 'noop', + }, + }), + }), + }), + expect.anything() + ); + }); + }); + + describe('deleteBehavior "exclusive"', () => { + const deleteBehavior = 'exclusive' as const; + + it('when filtered namespaces is empty, calls updateByQuery with expected script params', async () => { + const namespaces = ['default']; + const params = setup({ type, id, namespaces, deleteBehavior }); + + await deleteLegacyUrlAliases(params); + expect(params.client.updateByQuery).toHaveBeenCalledTimes(1); + expect(params.client.updateByQuery).toHaveBeenCalledWith( + expect.objectContaining({ + body: expect.objectContaining({ + script: expect.objectContaining({ + params: { + namespaces: [], // 'default' is filtered out + matchTargetNamespaceOp: 'noop', + notMatchTargetNamespaceOp: 'delete', + }, + }), + }), + }), + expect.anything() + ); + }); + + it('when filtered namespaces is not empty, calls updateByQuery with expected script params', async () => { + const namespaces = ['space-a', 'default', 'space-b']; + const params = setup({ type, id, namespaces, deleteBehavior }); + + await deleteLegacyUrlAliases(params); + expect(params.client.updateByQuery).toHaveBeenCalledTimes(1); + expect(params.client.updateByQuery).toHaveBeenCalledWith( + expect.objectContaining({ + body: expect.objectContaining({ + script: expect.objectContaining({ + params: { + namespaces: ['space-a', 'space-b'], // 'default' is filtered out + matchTargetNamespaceOp: 'noop', + notMatchTargetNamespaceOp: 'delete', + }, + }), + }), + }), + expect.anything() + ); + }); + }); +}); diff --git a/src/core/server/saved_objects/service/lib/legacy_url_aliases/delete_legacy_url_aliases.ts b/src/core/server/saved_objects/service/lib/legacy_url_aliases/delete_legacy_url_aliases.ts new file mode 100644 index 0000000000000..59c73d1f781a2 --- /dev/null +++ b/src/core/server/saved_objects/service/lib/legacy_url_aliases/delete_legacy_url_aliases.ts @@ -0,0 +1,113 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import * as esKuery from '@kbn/es-query'; + +import { getErrorMessage as getEsErrorMessage } from '../../../../elasticsearch'; +import type { ISavedObjectTypeRegistry } from '../../../saved_objects_type_registry'; +import type { IndexMapping } from '../../../mappings'; +import { LEGACY_URL_ALIAS_TYPE } from '../../../object_types'; +import type { RepositoryEsClient } from '../repository_es_client'; +import { getSearchDsl } from '../search_dsl'; +import { ALL_NAMESPACES_STRING, DEFAULT_NAMESPACE_STRING } from '../utils'; + +/** @internal */ +export interface DeleteLegacyUrlAliasesParams { + mappings: IndexMapping; + registry: ISavedObjectTypeRegistry; + client: RepositoryEsClient; + getIndexForType: (type: string) => string; + /** The object type. */ + type: string; + /** The object ID. */ + id: string; + /** + * The namespaces to include or exclude when searching for legacy URL alias targets (depends on the `deleteBehavior` parameter). + * Note that using `namespaces: [], deleteBehavior: 'exclusive'` will delete all aliases for this object in all spaces. + */ + namespaces: string[]; + /** + * If this is equal to 'inclusive', all aliases with a `targetNamespace` in the `namespaces` array will be deleted. + * If this is equal to 'exclusive', all aliases with a `targetNamespace` _not_ in the `namespaces` array will be deleted. + */ + deleteBehavior: 'inclusive' | 'exclusive'; +} + +/** + * Deletes legacy URL aliases that point to a given object. + * + * Note that aliases are only created when an object is converted to become share-capable, and each targetId is deterministically generated + * with uuidv5 -- this means that the chances of there actually being _multiple_ legacy URL aliases that target a given type/ID are slim to + * none. However, we don't always know exactly what space an alias could be in (if an object exists in multiple spaces, or in all spaces), + * so the most straightforward way for us to ensure that aliases are reliably deleted is to use updateByQuery, which is what this function + * does. + * + * @internal + */ +export async function deleteLegacyUrlAliases(params: DeleteLegacyUrlAliasesParams) { + const { mappings, registry, client, getIndexForType, type, id, namespaces, deleteBehavior } = + params; + + if (namespaces.includes(ALL_NAMESPACES_STRING)) { + throwError(type, id, '"namespaces" cannot include the * string'); + } + + // Legacy URL aliases cannot exist in the default space; filter that out + const filteredNamespaces = namespaces.filter( + (namespace) => namespace !== DEFAULT_NAMESPACE_STRING + ); + if (!filteredNamespaces.length && deleteBehavior === 'inclusive') { + // nothing to do, return early + return; + } + + const { buildNode } = esKuery.nodeTypes.function; + const match1 = buildNode('is', `${LEGACY_URL_ALIAS_TYPE}.targetType`, type); + const match2 = buildNode('is', `${LEGACY_URL_ALIAS_TYPE}.targetId`, id); + const kueryNode = buildNode('and', [match1, match2]); + + try { + await client.updateByQuery( + { + index: getIndexForType(LEGACY_URL_ALIAS_TYPE), + refresh: false, // This could be called many times in succession, intentionally do not wait for a refresh + body: { + ...getSearchDsl(mappings, registry, { + type: LEGACY_URL_ALIAS_TYPE, + kueryNode, + }), + script: { + // Intentionally use one script source with variable params to take advantage of ES script caching + source: ` + if (params['namespaces'].indexOf(ctx._source['${LEGACY_URL_ALIAS_TYPE}']['targetNamespace']) > -1) { + ctx.op = params['matchTargetNamespaceOp']; + } else { + ctx.op = params['notMatchTargetNamespaceOp']; + } + `, + params: { + namespaces: filteredNamespaces, + matchTargetNamespaceOp: deleteBehavior === 'inclusive' ? 'delete' : 'noop', + notMatchTargetNamespaceOp: deleteBehavior === 'inclusive' ? 'noop' : 'delete', + }, + lang: 'painless', + }, + conflicts: 'proceed', + }, + }, + { ignore: [404] } + ); + } catch (err) { + const errorMessage = getEsErrorMessage(err); + throwError(type, id, `${errorMessage}`); + } +} + +function throwError(type: string, id: string, message: string) { + throw new Error(`Failed to delete legacy URL aliases for ${type}/${id}: ${message}`); +} diff --git a/src/core/server/saved_objects/service/lib/find_legacy_url_aliases.test.ts b/src/core/server/saved_objects/service/lib/legacy_url_aliases/find_legacy_url_aliases.test.ts similarity index 94% rename from src/core/server/saved_objects/service/lib/find_legacy_url_aliases.test.ts rename to src/core/server/saved_objects/service/lib/legacy_url_aliases/find_legacy_url_aliases.test.ts index 134ea26d53b7d..755fa5794b575 100644 --- a/src/core/server/saved_objects/service/lib/find_legacy_url_aliases.test.ts +++ b/src/core/server/saved_objects/service/lib/legacy_url_aliases/find_legacy_url_aliases.test.ts @@ -8,12 +8,12 @@ import type { DeeplyMockedKeys } from '@kbn/utility-types/jest'; -import { LegacyUrlAlias, LEGACY_URL_ALIAS_TYPE } from '../../object_types'; +import { LegacyUrlAlias, LEGACY_URL_ALIAS_TYPE } from '../../../object_types'; +import type { CreatePointInTimeFinderFn, PointInTimeFinder } from '../point_in_time_finder'; +import { savedObjectsPointInTimeFinderMock } from '../point_in_time_finder.mock'; +import type { ISavedObjectsRepository } from '../repository'; +import { savedObjectsRepositoryMock } from '../repository.mock'; import { findLegacyUrlAliases } from './find_legacy_url_aliases'; -import type { CreatePointInTimeFinderFn, PointInTimeFinder } from './point_in_time_finder'; -import { savedObjectsPointInTimeFinderMock } from './point_in_time_finder.mock'; -import type { ISavedObjectsRepository } from './repository'; -import { savedObjectsRepositoryMock } from './repository.mock'; describe('findLegacyUrlAliases', () => { let savedObjectsMock: jest.Mocked; diff --git a/src/core/server/saved_objects/service/lib/find_legacy_url_aliases.ts b/src/core/server/saved_objects/service/lib/legacy_url_aliases/find_legacy_url_aliases.ts similarity index 87% rename from src/core/server/saved_objects/service/lib/find_legacy_url_aliases.ts rename to src/core/server/saved_objects/service/lib/legacy_url_aliases/find_legacy_url_aliases.ts index aac022fc32098..7c1ce82129710 100644 --- a/src/core/server/saved_objects/service/lib/find_legacy_url_aliases.ts +++ b/src/core/server/saved_objects/service/lib/legacy_url_aliases/find_legacy_url_aliases.ts @@ -7,9 +7,9 @@ */ import * as esKuery from '@kbn/es-query'; -import { LegacyUrlAlias, LEGACY_URL_ALIAS_TYPE } from '../../object_types'; -import { getObjectKey } from './internal_utils'; -import type { CreatePointInTimeFinderFn } from './point_in_time_finder'; +import { LegacyUrlAlias, LEGACY_URL_ALIAS_TYPE } from '../../../object_types'; +import { getObjectKey } from '../internal_utils'; +import type { CreatePointInTimeFinderFn } from '../point_in_time_finder'; interface FindLegacyUrlAliasesObject { type: string; @@ -68,6 +68,7 @@ export async function findLegacyUrlAliases( function createAliasKueryFilter(objects: Array<{ type: string; id: string }>) { const { buildNode } = esKuery.nodeTypes.function; + // Note: these nodes include '.attributes' for type-level fields because these are eventually passed to `validateConvertFilterToKueryNode`, which requires it const kueryNodes = objects.reduce((acc, { type, id }) => { const match1 = buildNode('is', `${LEGACY_URL_ALIAS_TYPE}.attributes.targetType`, type); const match2 = buildNode('is', `${LEGACY_URL_ALIAS_TYPE}.attributes.sourceId`, id); diff --git a/typings/global_fetch.d.ts b/src/core/server/saved_objects/service/lib/legacy_url_aliases/index.ts similarity index 61% rename from typings/global_fetch.d.ts rename to src/core/server/saved_objects/service/lib/legacy_url_aliases/index.ts index 597bc7e89497c..ec10668940d72 100644 --- a/typings/global_fetch.d.ts +++ b/src/core/server/saved_objects/service/lib/legacy_url_aliases/index.ts @@ -6,6 +6,7 @@ * Side Public License, v 1. */ -// This type needs to still exist due to apollo-link-http-common hasn't yet updated -// it's usage (https://github.com/apollographql/apollo-link/issues/1131) -declare type GlobalFetch = WindowOrWorkerGlobalScope; +export { findLegacyUrlAliases } from './find_legacy_url_aliases'; + +export { deleteLegacyUrlAliases } from './delete_legacy_url_aliases'; +export type { DeleteLegacyUrlAliasesParams } from './delete_legacy_url_aliases'; diff --git a/src/core/server/saved_objects/service/lib/preflight_check_for_create.test.mock.ts b/src/core/server/saved_objects/service/lib/preflight_check_for_create.test.mock.ts index e774a178abd49..fe8076b51e5dd 100644 --- a/src/core/server/saved_objects/service/lib/preflight_check_for_create.test.mock.ts +++ b/src/core/server/saved_objects/service/lib/preflight_check_for_create.test.mock.ts @@ -6,14 +6,14 @@ * Side Public License, v 1. */ -import type { findLegacyUrlAliases } from './find_legacy_url_aliases'; +import type { findLegacyUrlAliases } from './legacy_url_aliases'; import type * as InternalUtils from './internal_utils'; export const mockFindLegacyUrlAliases = jest.fn() as jest.MockedFunction< typeof findLegacyUrlAliases >; -jest.mock('./find_legacy_url_aliases', () => { +jest.mock('./legacy_url_aliases', () => { return { findLegacyUrlAliases: mockFindLegacyUrlAliases }; }); diff --git a/src/core/server/saved_objects/service/lib/preflight_check_for_create.ts b/src/core/server/saved_objects/service/lib/preflight_check_for_create.ts index 6788cd8aa3abf..e5b96a22631c1 100644 --- a/src/core/server/saved_objects/service/lib/preflight_check_for_create.ts +++ b/src/core/server/saved_objects/service/lib/preflight_check_for_create.ts @@ -13,7 +13,7 @@ import type { SavedObjectsRawDocSource, SavedObjectsSerializer, } from '../../serialization'; -import { findLegacyUrlAliases } from './find_legacy_url_aliases'; +import { findLegacyUrlAliases } from './legacy_url_aliases'; import { Either, rawDocExistsInNamespaces } from './internal_utils'; import { getObjectKey, isLeft, isRight } from './internal_utils'; import type { CreatePointInTimeFinderFn } from './point_in_time_finder'; diff --git a/src/core/server/saved_objects/service/lib/repository.test.js b/src/core/server/saved_objects/service/lib/repository.test.js index 51ec81503956a..f61a79ca9de66 100644 --- a/src/core/server/saved_objects/service/lib/repository.test.js +++ b/src/core/server/saved_objects/service/lib/repository.test.js @@ -14,6 +14,7 @@ import { mockUpdateObjectsSpaces, mockGetCurrentTime, mockPreflightCheckForCreate, + mockDeleteLegacyUrlAliases, } from './repository.test.mock'; import { SavedObjectsRepository } from './repository'; @@ -2394,9 +2395,11 @@ describe('SavedObjectsRepository', () => { const id = 'logstash-*'; const namespace = 'foo-namespace'; - const deleteSuccess = async (type, id, options) => { + const deleteSuccess = async (type, id, options, internalOptions = {}) => { + const { mockGetResponseValue } = internalOptions; if (registry.isMultiNamespace(type)) { - const mockGetResponse = getMockGetResponse({ type, id }, options?.namespace); + const mockGetResponse = + mockGetResponseValue ?? getMockGetResponse({ type, id }, options?.namespace); client.get.mockResolvedValueOnce( elasticsearchClientMock.createSuccessTransportRequestPromise(mockGetResponse) ); @@ -2409,6 +2412,11 @@ describe('SavedObjectsRepository', () => { return result; }; + beforeEach(() => { + mockDeleteLegacyUrlAliases.mockClear(); + mockDeleteLegacyUrlAliases.mockResolvedValue(); + }); + describe('client calls', () => { it(`should use the ES delete action when not using a multi-namespace type`, async () => { await deleteSuccess(type, id); @@ -2482,6 +2490,64 @@ describe('SavedObjectsRepository', () => { }); }); + describe('legacy URL aliases', () => { + it(`doesn't delete legacy URL aliases for single-namespace object types`, async () => { + await deleteSuccess(type, id, { namespace }); + expect(mockDeleteLegacyUrlAliases).not.toHaveBeenCalled(); + }); + + // We intentionally do not include a test case for a multi-namespace object with a "not found" preflight result, because that throws + // an error (without deleting aliases) and we already have a test case for that + + it(`deletes legacy URL aliases for multi-namespace object types (all spaces)`, async () => { + const internalOptions = { + mockGetResponseValue: getMockGetResponse( + { type: MULTI_NAMESPACE_TYPE, id }, + ALL_NAMESPACES_STRING + ), + }; + await deleteSuccess(MULTI_NAMESPACE_TYPE, id, { namespace, force: true }, internalOptions); + expect(mockDeleteLegacyUrlAliases).toHaveBeenCalledWith( + expect.objectContaining({ + type: MULTI_NAMESPACE_TYPE, + id, + namespaces: [], + deleteBehavior: 'exclusive', + }) + ); + }); + + it(`deletes legacy URL aliases for multi-namespace object types (specific spaces)`, async () => { + await deleteSuccess(MULTI_NAMESPACE_TYPE, id, { namespace }); // this function mocks a preflight response with the given namespace by default + expect(mockDeleteLegacyUrlAliases).toHaveBeenCalledWith( + expect.objectContaining({ + type: MULTI_NAMESPACE_TYPE, + id, + namespaces: [namespace], + deleteBehavior: 'inclusive', + }) + ); + }); + + it(`logs a message when deleteLegacyUrlAliases returns an error`, async () => { + client.get.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise( + getMockGetResponse({ type: MULTI_NAMESPACE_ISOLATED_TYPE, id, namespace }) + ) + ); + client.delete.mockResolvedValueOnce( + elasticsearchClientMock.createSuccessTransportRequestPromise({ result: 'deleted' }) + ); + mockDeleteLegacyUrlAliases.mockRejectedValueOnce(new Error('Oh no!')); + await savedObjectsRepository.delete(MULTI_NAMESPACE_ISOLATED_TYPE, id, { namespace }); + expect(client.get).toHaveBeenCalledTimes(1); + expect(logger.error).toHaveBeenCalledTimes(1); + expect(logger.error).toHaveBeenCalledWith( + 'Unable to delete aliases when deleting an object: Oh no!' + ); + }); + }); + describe('errors', () => { const expectNotFoundError = async (type, id, options) => { await expect(savedObjectsRepository.delete(type, id, options)).rejects.toThrowError( diff --git a/src/core/server/saved_objects/service/lib/repository.test.mock.ts b/src/core/server/saved_objects/service/lib/repository.test.mock.ts index 88eb13e3ca46b..3ec2cb0a5d8b9 100644 --- a/src/core/server/saved_objects/service/lib/repository.test.mock.ts +++ b/src/core/server/saved_objects/service/lib/repository.test.mock.ts @@ -11,6 +11,7 @@ import type { internalBulkResolve } from './internal_bulk_resolve'; import type * as InternalUtils from './internal_utils'; import type { preflightCheckForCreate } from './preflight_check_for_create'; import type { updateObjectsSpaces } from './update_objects_spaces'; +import type { deleteLegacyUrlAliases } from './legacy_url_aliases'; export const mockCollectMultiNamespaceReferences = jest.fn() as jest.MockedFunction< typeof collectMultiNamespaceReferences @@ -60,3 +61,10 @@ export const pointInTimeFinderMock = jest.fn(); jest.doMock('./point_in_time_finder', () => ({ PointInTimeFinder: pointInTimeFinderMock, })); + +export const mockDeleteLegacyUrlAliases = jest.fn() as jest.MockedFunction< + typeof deleteLegacyUrlAliases +>; +jest.mock('./legacy_url_aliases', () => ({ + deleteLegacyUrlAliases: mockDeleteLegacyUrlAliases, +})); diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts index ab802d2f36677..d538690fb1920 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -100,6 +100,7 @@ import { preflightCheckForCreate, PreflightCheckForCreateObject, } from './preflight_check_for_create'; +import { deleteLegacyUrlAliases } from './legacy_url_aliases'; // BEWARE: The SavedObjectClient depends on the implementation details of the SavedObjectsRepository // so any breaking changes to this repository are considered breaking changes to the SavedObjectsClient. @@ -717,6 +718,25 @@ export class SavedObjectsRepository { const deleted = body.result === 'deleted'; if (deleted) { + const namespaces = preflightResult?.savedObjectNamespaces; + if (namespaces) { + // This is a multi-namespace object type, and it might have legacy URL aliases that need to be deleted. + await deleteLegacyUrlAliases({ + mappings: this._mappings, + registry: this._registry, + client: this.client, + getIndexForType: this.getIndexForType.bind(this), + type, + id, + ...(namespaces.includes(ALL_NAMESPACES_STRING) + ? { namespaces: [], deleteBehavior: 'exclusive' } // delete legacy URL aliases for this type/ID for all spaces + : { namespaces, deleteBehavior: 'inclusive' }), // delete legacy URL aliases for this type/ID for these specific spaces + }).catch((err) => { + // The object has already been deleted, but we caught an error when attempting to delete aliases. + // A consumer cannot attempt to delete the object again, so just log the error and swallow it. + this._logger.error(`Unable to delete aliases when deleting an object: ${err.message}`); + }); + } return {}; } @@ -1344,10 +1364,12 @@ export class SavedObjectsRepository { options?: SavedObjectsUpdateObjectsSpacesOptions ) { return updateObjectsSpaces({ + mappings: this._mappings, registry: this._registry, allowedTypes: this._allowedTypes, client: this.client, serializer: this._serializer, + logger: this._logger, getIndexForType: this.getIndexForType.bind(this), objects, spacesToAdd, diff --git a/src/core/server/saved_objects/service/lib/update_objects_spaces.test.mock.ts b/src/core/server/saved_objects/service/lib/update_objects_spaces.test.mock.ts index d7aa762e01aab..043975d5bb52b 100644 --- a/src/core/server/saved_objects/service/lib/update_objects_spaces.test.mock.ts +++ b/src/core/server/saved_objects/service/lib/update_objects_spaces.test.mock.ts @@ -7,6 +7,7 @@ */ import type * as InternalUtils from './internal_utils'; +import type { deleteLegacyUrlAliases } from './legacy_url_aliases'; export const mockGetBulkOperationError = jest.fn() as jest.MockedFunction< typeof InternalUtils['getBulkOperationError'] @@ -27,3 +28,10 @@ jest.mock('./internal_utils', () => { rawDocExistsInNamespace: mockRawDocExistsInNamespace, }; }); + +export const mockDeleteLegacyUrlAliases = jest.fn() as jest.MockedFunction< + typeof deleteLegacyUrlAliases +>; +jest.mock('./legacy_url_aliases', () => ({ + deleteLegacyUrlAliases: mockDeleteLegacyUrlAliases, +})); diff --git a/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts b/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts index 11dbe6149878c..d5b79b70a55a1 100644 --- a/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts +++ b/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts @@ -10,12 +10,14 @@ import { mockGetBulkOperationError, mockGetExpectedVersionProperties, mockRawDocExistsInNamespace, + mockDeleteLegacyUrlAliases, } from './update_objects_spaces.test.mock'; import type { DeeplyMockedKeys } from '@kbn/utility-types/jest'; import type { ElasticsearchClient } from 'src/core/server/elasticsearch'; import { elasticsearchClientMock } from 'src/core/server/elasticsearch/client/mocks'; +import { loggerMock } from '../../../logging/logger.mock'; import { typeRegistryMock } from '../../saved_objects_type_registry.mock'; import { SavedObjectsSerializer } from '../../serialization'; import type { @@ -23,6 +25,7 @@ import type { UpdateObjectsSpacesParams, } from './update_objects_spaces'; import { updateObjectsSpaces } from './update_objects_spaces'; +import { ALL_NAMESPACES_STRING } from './utils'; type SetupParams = Partial< Pick @@ -53,6 +56,8 @@ beforeEach(() => { mockGetExpectedVersionProperties.mockReturnValue(EXPECTED_VERSION_PROPS); mockRawDocExistsInNamespace.mockReset(); mockRawDocExistsInNamespace.mockReturnValue(true); // return true by default + mockDeleteLegacyUrlAliases.mockReset(); + mockDeleteLegacyUrlAliases.mockResolvedValue(); // resolve an empty promise by default }); afterAll(() => { @@ -71,10 +76,12 @@ describe('#updateObjectsSpaces', () => { client = elasticsearchClientMock.createElasticsearchClient(); const serializer = new SavedObjectsSerializer(registry); return { + mappings: { properties: {} }, // doesn't matter, only used as an argument to deleteLegacyUrlAliases which is mocked registry, allowedTypes: [SHAREABLE_OBJ_TYPE, NON_SHAREABLE_OBJ_TYPE], // SHAREABLE_HIDDEN_OBJ_TYPE is excluded client, serializer, + logger: loggerMock.create(), getIndexForType: (type: string) => `index-for-${type}`, objects, spacesToAdd, @@ -382,6 +389,149 @@ describe('#updateObjectsSpaces', () => { expect(client.bulk).not.toHaveBeenCalled(); }); }); + + describe('legacy URL aliases', () => { + it('does not delete aliases for objects that were not removed from any spaces', async () => { + const space1 = 'space-to-add'; + const space2 = 'space-to-remove'; + const space3 = 'other-space'; + const obj1 = { type: SHAREABLE_OBJ_TYPE, id: 'id-1', spaces: [space1] }; // will not be changed + const obj2 = { type: SHAREABLE_OBJ_TYPE, id: 'id-2', spaces: [space3] }; // will be updated + + const objects = [obj1, obj2]; + const spacesToAdd = [space1]; + const spacesToRemove = [space2]; + const params = setup({ objects, spacesToAdd, spacesToRemove }); + // this test case does not call mget + mockBulkResults({ error: false }); // result for obj2 + + await updateObjectsSpaces(params); + expect(client.bulk).toHaveBeenCalledTimes(1); + expectBulkArgs({ action: 'update', object: { ...obj2, namespaces: [space3, space1] } }); + expect(mockDeleteLegacyUrlAliases).not.toHaveBeenCalled(); + expect(params.logger.error).not.toHaveBeenCalled(); + }); + + it('does not delete aliases for objects that were removed from spaces but were also added to All Spaces (*)', async () => { + const space2 = 'space-to-remove'; + const obj1 = { type: SHAREABLE_OBJ_TYPE, id: 'id-1', spaces: [space2] }; + + const objects = [obj1]; + const spacesToAdd = [ALL_NAMESPACES_STRING]; + const spacesToRemove = [space2]; + const params = setup({ objects, spacesToAdd, spacesToRemove }); + // this test case does not call mget + mockBulkResults({ error: false }); // result for obj1 + + await updateObjectsSpaces(params); + expect(client.bulk).toHaveBeenCalledTimes(1); + expectBulkArgs({ + action: 'update', + object: { ...obj1, namespaces: [ALL_NAMESPACES_STRING] }, + }); + expect(mockDeleteLegacyUrlAliases).not.toHaveBeenCalled(); + expect(params.logger.error).not.toHaveBeenCalled(); + }); + + it('deletes aliases for objects that were removed from specific spaces using "deleteBehavior: exclusive"', async () => { + const space1 = 'space-to-remove'; + const space2 = 'another-space-to-remove'; + const space3 = 'other-space'; + const obj1 = { type: SHAREABLE_OBJ_TYPE, id: 'id-1', spaces: [space3] }; // will not be changed + const obj2 = { type: SHAREABLE_OBJ_TYPE, id: 'id-1', spaces: [space1, space2, space3] }; // will be updated + const obj3 = { type: SHAREABLE_OBJ_TYPE, id: 'id-1', spaces: [space1] }; // will be deleted + + const objects = [obj1, obj2, obj3]; + const spacesToRemove = [space1, space2]; + const params = setup({ objects, spacesToRemove }); + // this test case does not call mget + mockBulkResults({ error: false }, { error: false }); // result2 for obj2 and obj3 + + await updateObjectsSpaces(params); + expect(client.bulk).toHaveBeenCalledTimes(1); + expectBulkArgs( + { action: 'update', object: { ...obj2, namespaces: [space3] } }, + { action: 'delete', object: obj3 } + ); + expect(mockDeleteLegacyUrlAliases).toHaveBeenCalledTimes(2); + expect(mockDeleteLegacyUrlAliases).toHaveBeenNthCalledWith( + 1, // the first call resulted in an error which generated a log message (see assertion below) + expect.objectContaining({ + type: obj2.type, + id: obj2.id, + namespaces: [space1, space2], + deleteBehavior: 'inclusive', + }) + ); + expect(mockDeleteLegacyUrlAliases).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ + type: obj3.type, + id: obj3.id, + namespaces: [space1], + deleteBehavior: 'inclusive', + }) + ); + expect(params.logger.error).not.toHaveBeenCalled(); + }); + + it('deletes aliases for objects that were removed from all spaces using "deleteBehavior: inclusive"', async () => { + const space1 = 'space-to-add'; + const space2 = 'other-space'; + const obj1 = { type: SHAREABLE_OBJ_TYPE, id: 'id-1', spaces: [space2] }; // will be updated to add space1 + const obj2 = { + type: SHAREABLE_OBJ_TYPE, + id: 'id-2', + spaces: [space2, ALL_NAMESPACES_STRING], // will be updated to add space1 and remove * + }; + + const objects = [obj1, obj2]; + const spacesToAdd = [space1]; + const spacesToRemove = [ALL_NAMESPACES_STRING]; + const params = setup({ objects, spacesToAdd, spacesToRemove }); + // this test case does not call mget + mockBulkResults({ error: false }); // result for obj1 + + await updateObjectsSpaces(params); + expect(client.bulk).toHaveBeenCalledTimes(1); + expectBulkArgs( + { action: 'update', object: { ...obj1, namespaces: [space2, space1] } }, + { action: 'update', object: { ...obj2, namespaces: [space2, space1] } } + ); + expect(mockDeleteLegacyUrlAliases).toHaveBeenCalledTimes(1); + expect(mockDeleteLegacyUrlAliases).toHaveBeenCalledWith( + expect.objectContaining({ + type: obj2.type, + id: obj2.id, + namespaces: [space2, space1], + deleteBehavior: 'exclusive', + }) + ); + expect(params.logger.error).not.toHaveBeenCalled(); + }); + + it('logs a message when deleteLegacyUrlAliases returns an error', async () => { + const space1 = 'space-to-remove'; + const space2 = 'other-space'; + const obj1 = { type: SHAREABLE_OBJ_TYPE, id: 'id-1', spaces: [space1, space2] }; // will be updated + + const objects = [obj1]; + const spacesToRemove = [space1]; + const params = setup({ objects, spacesToRemove }); + // this test case does not call mget + mockBulkResults({ error: false }); // result for obj1 + mockDeleteLegacyUrlAliases.mockRejectedValueOnce(new Error('Oh no!')); // result for deleting aliases for obj1 + + await updateObjectsSpaces(params); + expect(client.bulk).toHaveBeenCalledTimes(1); + expectBulkArgs({ action: 'update', object: { ...obj1, namespaces: [space2] } }); + expect(mockDeleteLegacyUrlAliases).toHaveBeenCalledTimes(1); // don't assert deleteLegacyUrlAliases args, we have tests for that above + expect(params.logger.error).toHaveBeenCalledTimes(1); + expect(params.logger.error).toHaveBeenCalledWith( + 'Unable to delete aliases when unsharing an object: Oh no!' + ); + }); + }); }); describe('returns expected results', () => { diff --git a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts index d88bf700a900e..90e914b9796c3 100644 --- a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts +++ b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts @@ -6,9 +6,12 @@ * Side Public License, v 1. */ +import pMap from 'p-map'; import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import intersection from 'lodash/intersection'; +import type { Logger } from '../../../logging'; +import type { IndexMapping } from '../../mappings'; import type { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import type { SavedObjectsRawDocSource, SavedObjectsSerializer } from '../../serialization'; import type { @@ -28,6 +31,9 @@ import { } from './internal_utils'; import { DEFAULT_REFRESH_SETTING } from './repository'; import type { RepositoryEsClient } from './repository_es_client'; +import { ALL_NAMESPACES_STRING } from './utils'; +import type { DeleteLegacyUrlAliasesParams } from './legacy_url_aliases'; +import { deleteLegacyUrlAliases } from './legacy_url_aliases'; /** * An object that should have its spaces updated. @@ -94,10 +100,12 @@ export interface SavedObjectsUpdateObjectsSpacesResponseObject { * @internal */ export interface UpdateObjectsSpacesParams { + mappings: IndexMapping; registry: ISavedObjectTypeRegistry; allowedTypes: string[]; client: RepositoryEsClient; serializer: SavedObjectsSerializer; + logger: Logger; getIndexForType: (type: string) => string; objects: SavedObjectsUpdateObjectsSpacesObject[]; spacesToAdd: string[]; @@ -105,15 +113,24 @@ export interface UpdateObjectsSpacesParams { options?: SavedObjectsUpdateObjectsSpacesOptions; } +type ObjectToDeleteAliasesFor = Pick< + DeleteLegacyUrlAliasesParams, + 'type' | 'id' | 'namespaces' | 'deleteBehavior' +>; + +const MAX_CONCURRENT_ALIAS_DELETIONS = 10; + /** * Gets all references and transitive references of the given objects. Ignores any object and/or reference that is not a multi-namespace * type. */ export async function updateObjectsSpaces({ + mappings, registry, allowedTypes, client, serializer, + logger, getIndexForType, objects, spacesToAdd, @@ -190,8 +207,12 @@ export async function updateObjectsSpaces({ const time = new Date().toISOString(); let bulkOperationRequestIndexCounter = 0; const bulkOperationParams: estypes.BulkOperationContainer[] = []; + const objectsToDeleteAliasesFor: ObjectToDeleteAliasesFor[] = []; const expectedBulkOperationResults: Array< - Either> + Either< + SavedObjectsUpdateObjectsSpacesResponseObject, + { type: string; id: string; updatedSpaces: string[]; esRequestIndex?: number } + > > = expectedBulkGetResults.map((expectedBulkGetResult) => { if (isLeft(expectedBulkGetResult)) { return expectedBulkGetResult; @@ -225,7 +246,7 @@ export async function updateObjectsSpaces({ versionProperties = getExpectedVersionProperties(version); } - const { newSpaces, isUpdateRequired } = getNewSpacesArray( + const { updatedSpaces, removedSpaces, isUpdateRequired } = analyzeSpaceChanges( currentSpaces, spacesToAdd, spacesToRemove @@ -233,7 +254,7 @@ export async function updateObjectsSpaces({ const expectedResult = { type, id, - newSpaces, + updatedSpaces, ...(isUpdateRequired && { esRequestIndex: bulkOperationRequestIndexCounter++ }), }; @@ -243,13 +264,24 @@ export async function updateObjectsSpaces({ _index: getIndexForType(type), ...versionProperties, }; - if (newSpaces.length) { - const documentToSave = { updated_at: time, namespaces: newSpaces }; + if (updatedSpaces.length) { + const documentToSave = { updated_at: time, namespaces: updatedSpaces }; // @ts-expect-error BulkOperation.retry_on_conflict, BulkOperation.routing. BulkOperation.version, and BulkOperation.version_type are optional bulkOperationParams.push({ update: documentMetadata }, { doc: documentToSave }); } else { bulkOperationParams.push({ delete: documentMetadata }); } + + if (removedSpaces.length && !updatedSpaces.includes(ALL_NAMESPACES_STRING)) { + // The object is being removed from at least one space; make sure to delete aliases appropriately + objectsToDeleteAliasesFor.push({ + type, + id, + ...(removedSpaces.includes(ALL_NAMESPACES_STRING) + ? { namespaces: updatedSpaces, deleteBehavior: 'exclusive' } + : { namespaces: removedSpaces, deleteBehavior: 'inclusive' }), + }); + } } return { tag: 'Right', value: expectedResult }; @@ -260,6 +292,24 @@ export async function updateObjectsSpaces({ ? await client.bulk({ refresh, body: bulkOperationParams, require_alias: true }) : undefined; + // Delete aliases if necessary, ensuring we don't have too many concurrent operations running. + const mapper = async ({ type, id, namespaces, deleteBehavior }: ObjectToDeleteAliasesFor) => + deleteLegacyUrlAliases({ + mappings, + registry, + client, + getIndexForType, + type, + id, + namespaces, + deleteBehavior, + }).catch((err) => { + // The object has already been unshared, but we caught an error when attempting to delete aliases. + // A consumer cannot attempt to unshare the object again, so just log the error and swallow it. + logger.error(`Unable to delete aliases when unsharing an object: ${err.message}`); + }); + await pMap(objectsToDeleteAliasesFor, mapper, { concurrency: MAX_CONCURRENT_ALIAS_DELETIONS }); + return { objects: expectedBulkOperationResults.map( (expectedResult) => { @@ -267,7 +317,7 @@ export async function updateObjectsSpaces({ return expectedResult.value; } - const { type, id, newSpaces, esRequestIndex } = expectedResult.value; + const { type, id, updatedSpaces, esRequestIndex } = expectedResult.value; if (esRequestIndex !== undefined) { const response = bulkOperationResponse?.body.items[esRequestIndex] ?? {}; const rawResponse = Object.values(response)[0] as any; @@ -277,7 +327,7 @@ export async function updateObjectsSpaces({ } } - return { id, type, spaces: newSpaces }; + return { id, type, spaces: updatedSpaces }; } ), }; @@ -289,17 +339,22 @@ function errorContent(error: DecoratedError) { } /** Gets the remaining spaces for an object after adding new ones and removing old ones. */ -function getNewSpacesArray( +function analyzeSpaceChanges( existingSpaces: string[], spacesToAdd: string[], spacesToRemove: string[] ) { const addSet = new Set(spacesToAdd); const removeSet = new Set(spacesToRemove); - const newSpaces = existingSpaces + const removedSpaces: string[] = []; + const updatedSpaces = existingSpaces .filter((x) => { addSet.delete(x); - return !removeSet.delete(x); + const removed = removeSet.delete(x); + if (removed) { + removedSpaces.push(x); + } + return !removed; }) .concat(Array.from(addSet)); @@ -307,5 +362,5 @@ function getNewSpacesArray( const isAnySpaceRemoved = removeSet.size < spacesToRemove.length; const isUpdateRequired = isAnySpaceAdded || isAnySpaceRemoved; - return { newSpaces, isUpdateRequired }; + return { updatedSpaces, removedSpaces, isUpdateRequired }; } diff --git a/src/core/server/ui_settings/integration_tests/index.test.ts b/src/core/server/ui_settings/integration_tests/index.test.ts index 44d98afdf54f5..ef635e90dac70 100644 --- a/src/core/server/ui_settings/integration_tests/index.test.ts +++ b/src/core/server/ui_settings/integration_tests/index.test.ts @@ -20,9 +20,9 @@ describe('uiSettings/routes', function () { jest.setTimeout(120_000); beforeAll(startServers); - /* eslint-disable jest/valid-describe */ + // eslint-disable-next-line jest/valid-describe describe('doc missing', docMissingSuite(savedObjectIndex)); + // eslint-disable-next-line jest/valid-describe describe('doc exists', docExistsSuite(savedObjectIndex)); - /* eslint-enable jest/valid-describe */ afterAll(stopServers); }); diff --git a/src/core/server/ui_settings/settings/misc.test.ts b/src/core/server/ui_settings/settings/misc.test.ts deleted file mode 100644 index 7b6788664c997..0000000000000 --- a/src/core/server/ui_settings/settings/misc.test.ts +++ /dev/null @@ -1,31 +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 - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { UiSettingsParams } from '../../../types'; -import { getMiscUiSettings } from './misc'; - -describe('misc settings', () => { - const miscSettings = getMiscUiSettings(); - - const getValidationFn = (setting: UiSettingsParams) => (value: any) => - setting.schema.validate(value); - - describe('truncate:maxHeight', () => { - const validate = getValidationFn(miscSettings['truncate:maxHeight']); - - it('should only accept positive numeric values', () => { - expect(() => validate(127)).not.toThrow(); - expect(() => validate(-12)).toThrowErrorMatchingInlineSnapshot( - `"Value must be equal to or greater than [0]."` - ); - expect(() => validate('foo')).toThrowErrorMatchingInlineSnapshot( - `"expected value of type [number] but got [string]"` - ); - }); - }); -}); diff --git a/src/core/server/ui_settings/settings/misc.ts b/src/core/server/ui_settings/settings/misc.ts index cd9e43400d3c9..ad7411dfd12af 100644 --- a/src/core/server/ui_settings/settings/misc.ts +++ b/src/core/server/ui_settings/settings/misc.ts @@ -6,23 +6,11 @@ * Side Public License, v 1. */ -import { i18n } from '@kbn/i18n'; import { schema } from '@kbn/config-schema'; import { UiSettingsParams } from '../types'; export const getMiscUiSettings = (): Record => { return { - 'truncate:maxHeight': { - name: i18n.translate('core.ui_settings.params.maxCellHeightTitle', { - defaultMessage: 'Maximum table cell height', - }), - value: 115, - description: i18n.translate('core.ui_settings.params.maxCellHeightText', { - defaultMessage: - 'The maximum height that a cell in a table should occupy. Set to 0 to disable truncation', - }), - schema: schema.number({ min: 0 }), - }, buildNum: { readonly: true, schema: schema.maybe(schema.number()), diff --git a/src/dev/bazel/index.bzl b/src/dev/bazel/index.bzl index e38d3d78c0071..313cc9f06236c 100644 --- a/src/dev/bazel/index.bzl +++ b/src/dev/bazel/index.bzl @@ -11,5 +11,7 @@ Please do not import from any other files when looking to use a custom rule """ load("//src/dev/bazel:jsts_transpiler.bzl", _jsts_transpiler = "jsts_transpiler") +load("//src/dev/bazel:ts_project.bzl", _ts_project = "ts_project") jsts_transpiler = _jsts_transpiler +ts_project = _ts_project diff --git a/src/dev/bazel/ts_project.bzl b/src/dev/bazel/ts_project.bzl new file mode 100644 index 0000000000000..afd28fa513164 --- /dev/null +++ b/src/dev/bazel/ts_project.bzl @@ -0,0 +1,16 @@ +"Simple wrapper over the general ts_project rule from rules_nodejs so we can override some configs" + +load("@npm//@bazel/typescript:index.bzl", _ts_project = "ts_project") + +def ts_project(validate = False, **kwargs): + """A macro around the upstream ts_project rule. + + Args: + validate: boolean; whether to check that the tsconfig JSON settings match the attributes on this target. Defaults to false + **kwargs: the rest + """ + + _ts_project( + validate = validate, + **kwargs + ) diff --git a/src/dev/build/tasks/os_packages/docker_generator/templates/kibana_yml.template.ts b/src/dev/build/tasks/os_packages/docker_generator/templates/kibana_yml.template.ts index 340a035adea4c..96d66b111b062 100644 --- a/src/dev/build/tasks/os_packages/docker_generator/templates/kibana_yml.template.ts +++ b/src/dev/build/tasks/os_packages/docker_generator/templates/kibana_yml.template.ts @@ -22,7 +22,7 @@ function generator({ imageFlavor }: TemplateContext) { server.host: "0.0.0.0" server.shutdownTimeout: "5s" elasticsearch.hosts: [ "http://elasticsearch:9200" ] - ${!imageFlavor ? 'monitoring.ui.container.elasticsearch.enabled: true' : ''} + monitoring.ui.container.elasticsearch.enabled: true `); } diff --git a/src/dev/eslint/index.ts b/src/dev/eslint/index.ts index 765c7dfce9ed0..5aeb83c45ad05 100644 --- a/src/dev/eslint/index.ts +++ b/src/dev/eslint/index.ts @@ -8,3 +8,4 @@ export { pickFilesToLint } from './pick_files_to_lint'; export { lintFiles } from './lint_files'; +export { runEslintWithTypes } from './run_eslint_with_types'; diff --git a/src/dev/eslint/run_eslint_with_types.ts b/src/dev/eslint/run_eslint_with_types.ts new file mode 100644 index 0000000000000..750011dea1031 --- /dev/null +++ b/src/dev/eslint/run_eslint_with_types.ts @@ -0,0 +1,171 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import Path from 'path'; +import Fs from 'fs'; +import Os from 'os'; + +import execa from 'execa'; +import * as Rx from 'rxjs'; +import { mergeMap, reduce } from 'rxjs/operators'; +import { supportsColor } from 'chalk'; +import { REPO_ROOT, run, createFailError } from '@kbn/dev-utils'; +import { lastValueFrom } from '@kbn/std'; + +import { PROJECTS } from '../typescript/projects'; +import { Project } from '../typescript/project'; + +export function runEslintWithTypes() { + run( + async ({ log, flags }) => { + const eslintPath = require.resolve('eslint/bin/eslint'); + const ignoreFilePath = Path.resolve(REPO_ROOT, '.eslintignore'); + const configTemplate = Fs.readFileSync( + Path.resolve(__dirname, 'types.eslint.config.template.js'), + 'utf8' + ); + + const projectFilter = + flags.project && typeof flags.project === 'string' + ? Path.resolve(flags.project) + : undefined; + + const projects = PROJECTS.filter((project) => { + if (project.disableTypeCheck) { + log.verbose(`[${project.name}] skipping project with type checking disabled`); + return false; + } + + if (projectFilter && project.tsConfigPath !== projectFilter) { + log.verbose(`[${project.name}] skipping because it doesn't match --project`); + return false; + } + + return true; + }); + + if (!projects.length) { + if (projectFilter) { + throw createFailError(`[${projectFilter}] is not a valid tsconfig project`); + } + + throw createFailError('unable to find projects to lint'); + } + + const concurrency = Math.max(1, Math.round((Os.cpus() || []).length / 2) || 1) || 1; + log.info(`Linting ${projects.length} projects, ${concurrency} at a time`); + + const failures = await lastValueFrom( + Rx.from(projects).pipe( + mergeMap(async (project) => { + const configFilePath = Path.resolve(project.directory, 'types.eslint.config.js'); + + Fs.writeFileSync( + configFilePath, + configTemplate.replace( + `'{PACKAGE_CONFIG}'`, + JSON.stringify(JSON.stringify({ rootDir: project.directory })) + ), + 'utf8' + ); + + const proc = await execa( + process.execPath, + [ + Path.relative(project.directory, eslintPath), + ...project.getIncludePatterns().map((p) => (p.endsWith('*') ? `${p}.{ts,tsx}` : p)), + ...project.getExcludePatterns().flatMap((p) => ['--ignore-pattern', p]), + ...['--ignore-pattern', '**/*.json'], + ...['--ext', '.ts,.tsx'], + '--no-error-on-unmatched-pattern', + '--no-inline-config', + '--no-eslintrc', + ...['--config', Path.relative(project.directory, configFilePath)], + ...['--ignore-path', Path.relative(project.directory, ignoreFilePath)], + ...(flags.verbose ? ['--debug'] : []), + ...(flags.fix ? ['--fix'] : []), + ], + { + cwd: project.directory, + env: { + ...(supportsColor ? { FORCE_COLOR: 'true' } : {}), + ...process.env, + }, + buffer: true, + all: true, + reject: false, + } + ); + + if (proc.exitCode === 0) { + Fs.unlinkSync(configFilePath); + log.success(project.name); + return undefined; + } else { + log.error(`${project.name} failed`); + log.indent(4); + log.write(proc.all); + log.indent(-4); + return project; + } + }, concurrency), + reduce((acc: Project[], project) => { + if (project) { + return [...acc, project]; + } else { + return acc; + } + }, []) + ) + ); + + if (!failures.length) { + log.success(`All projects validated successfully!`); + if (flags.fix) { + log.info(` +❗️ After staging your changes, don't forget to run eslint/prettier on them with: + + node scripts/precommit_hook --fix +`); + } + + return; + } + + throw createFailError( + ` + ${ + failures.length + } projects failed, run the following commands locally to try auto-fixing them: + + ${failures + .map( + (p) => + `node scripts/eslint_with_types --fix --project ${Path.relative( + REPO_ROOT, + p.tsConfigPath + )}` + ) + .join('\n ')} + ` + ); + }, + { + description: + 'Run ESLint in each TS project, feeding it the TS config so it can validate our code using the type information', + flags: { + string: ['project'], + boolean: ['fix'], + help: ` + --project Only run eslint on a specific ts project + --fix Run eslint in --fix mode + `, + }, + } + ); +} diff --git a/src/dev/eslint/types.eslint.config.template.js b/src/dev/eslint/types.eslint.config.template.js new file mode 100644 index 0000000000000..08cbaf3b02325 --- /dev/null +++ b/src/dev/eslint/types.eslint.config.template.js @@ -0,0 +1,27 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +/** + * THIS FILE IS WRITTEN AUTOMATICALLY by `node scripts/eslint_with_types` and + * should be deleted automatically unless something goes wrong + */ + +const config = JSON.parse('{PACKAGE_CONFIG}'); + +module.exports = { + root: true, + parser: '@typescript-eslint/parser', + parserOptions: { + tsconfigRootDir: config.rootDir, + project: ['./tsconfig.json'], + }, + plugins: ['@typescript-eslint'], + rules: { + '@typescript-eslint/consistent-type-exports': 'error', + }, +}; diff --git a/src/dev/i18n/index.ts b/src/dev/i18n/index.ts index 111dc6b688e9f..54ea36a9f82c4 100644 --- a/src/dev/i18n/index.ts +++ b/src/dev/i18n/index.ts @@ -12,10 +12,6 @@ export { extractMessagesFromPathToMap } from './extract_default_translations'; export { matchEntriesWithExctractors } from './extract_default_translations'; export { arrayify, writeFileAsync, readFileAsync, normalizePath, ErrorReporter } from './utils'; export { serializeToJson, serializeToJson5 } from './serializers'; -export { - I18nConfig, - filterConfigPaths, - assignConfigFromPath, - checkConfigNamespacePrefix, -} from './config'; +export type { I18nConfig } from './config'; +export { filterConfigPaths, assignConfigFromPath, checkConfigNamespacePrefix } from './config'; export { integrateLocaleFiles } from './integrate_locale_files'; diff --git a/src/dev/typescript/project.ts b/src/dev/typescript/project.ts index a0c196dd8e919..baeaf39ec288d 100644 --- a/src/dev/typescript/project.ts +++ b/src/dev/typescript/project.ts @@ -66,8 +66,10 @@ export class Project { const disableTypeCheck = projectOptions?.disableTypeCheck || false; const name = projectOptions?.name || Path.relative(REPO_ROOT, directory) || Path.basename(directory); - const include = config.include ? makeMatchers(directory, config.include) : undefined; - const exclude = config.exclude ? makeMatchers(directory, config.exclude) : undefined; + const includePatterns = config.include; + const include = includePatterns ? makeMatchers(directory, includePatterns) : undefined; + const excludePatterns = config.exclude; + const exclude = excludePatterns ? makeMatchers(directory, excludePatterns) : undefined; let baseProject; if (config.extends) { @@ -99,7 +101,9 @@ export class Project { disableTypeCheck, baseProject, include, - exclude + includePatterns, + exclude, + excludePatterns ); cache.set(tsConfigPath, project); return project; @@ -114,9 +118,22 @@ export class Project { public readonly baseProject?: Project, private readonly include?: IMinimatch[], - private readonly exclude?: IMinimatch[] + private readonly includePatterns?: string[], + private readonly exclude?: IMinimatch[], + private readonly excludePatterns?: string[] ) {} + public getIncludePatterns(): string[] { + return this.includePatterns + ? this.includePatterns + : this.baseProject?.getIncludePatterns() ?? []; + } + public getExcludePatterns(): string[] { + return this.excludePatterns + ? this.excludePatterns + : this.baseProject?.getExcludePatterns() ?? []; + } + private getInclude(): IMinimatch[] { return this.include ? this.include : this.baseProject?.getInclude() ?? []; } diff --git a/src/plugins/advanced_settings/public/index.ts b/src/plugins/advanced_settings/public/index.ts index be57576d176c6..83676b4f7c38d 100644 --- a/src/plugins/advanced_settings/public/index.ts +++ b/src/plugins/advanced_settings/public/index.ts @@ -9,7 +9,7 @@ import React from 'react'; import { PluginInitializerContext } from 'kibana/public'; import { AdvancedSettingsPlugin } from './plugin'; -export { AdvancedSettingsSetup, AdvancedSettingsStart } from './types'; +export type { AdvancedSettingsSetup, AdvancedSettingsStart } from './types'; export { ComponentRegistry } from './component_registry'; /** diff --git a/src/plugins/bfetch/public/batching/index.ts b/src/plugins/bfetch/public/batching/index.ts index 115fd84cbe979..e3a8d0169af27 100644 --- a/src/plugins/bfetch/public/batching/index.ts +++ b/src/plugins/bfetch/public/batching/index.ts @@ -6,7 +6,5 @@ * Side Public License, v 1. */ -export { - createStreamingBatchedFunction, - StreamingBatchedFunctionParams, -} from './create_streaming_batched_function'; +export type { StreamingBatchedFunctionParams } from './create_streaming_batched_function'; +export { createStreamingBatchedFunction } from './create_streaming_batched_function'; diff --git a/src/plugins/bfetch/public/index.ts b/src/plugins/bfetch/public/index.ts index 59ee2d63ac57e..6ab5480327538 100644 --- a/src/plugins/bfetch/public/index.ts +++ b/src/plugins/bfetch/public/index.ts @@ -9,10 +9,10 @@ import { PluginInitializerContext } from '../../../core/public'; import { BfetchPublicPlugin } from './plugin'; -export { BfetchPublicSetup, BfetchPublicStart, BfetchPublicContract } from './plugin'; +export type { BfetchPublicSetup, BfetchPublicStart, BfetchPublicContract } from './plugin'; export { split } from './streaming'; -export { BatchedFunc } from './batching/types'; +export type { BatchedFunc } from './batching/types'; export function plugin(initializerContext: PluginInitializerContext) { return new BfetchPublicPlugin(initializerContext); diff --git a/src/plugins/bfetch/server/index.ts b/src/plugins/bfetch/server/index.ts index f4c41d10e42cb..76f86e6975070 100644 --- a/src/plugins/bfetch/server/index.ts +++ b/src/plugins/bfetch/server/index.ts @@ -9,7 +9,7 @@ import { PluginInitializerContext } from '../../../core/server'; import { BfetchServerPlugin } from './plugin'; -export { BfetchServerSetup, BfetchServerStart, BatchProcessingRouteParams } from './plugin'; +export type { BfetchServerSetup, BfetchServerStart, BatchProcessingRouteParams } from './plugin'; export function plugin(initializerContext: PluginInitializerContext) { return new BfetchServerPlugin(initializerContext); diff --git a/src/plugins/charts/common/index.ts b/src/plugins/charts/common/index.ts index 936ad2d10ac64..825fd74e24041 100644 --- a/src/plugins/charts/common/index.ts +++ b/src/plugins/charts/common/index.ts @@ -9,23 +9,19 @@ export const COLOR_MAPPING_SETTING = 'visualization:colorMapping'; export const LEGACY_TIME_AXIS = 'visualization:useLegacyTimeAxis'; -export { +export type { CustomPaletteArguments, CustomPaletteState, SystemPaletteArguments, PaletteOutput, - defaultCustomColors, - palette, - systemPalette, } from './palette'; +export { defaultCustomColors, palette, systemPalette } from './palette'; export { paletteIds } from './constants'; +export type { ColorSchema, RawColorSchema, ColorMap } from './static'; export { ColorSchemas, - ColorSchema, - RawColorSchema, - ColorMap, vislibColorMaps, colorSchemas, getHeatmapColors, @@ -37,4 +33,4 @@ export { MULTILAYER_TIME_AXIS_STYLE, } from './static'; -export { ColorSchemaParams, Labels, Style } from './types'; +export type { ColorSchemaParams, Labels, Style } from './types'; diff --git a/src/plugins/charts/common/static/color_maps/index.ts b/src/plugins/charts/common/static/color_maps/index.ts index c624c5ceb6685..115758988f04b 100644 --- a/src/plugins/charts/common/static/color_maps/index.ts +++ b/src/plugins/charts/common/static/color_maps/index.ts @@ -6,13 +6,7 @@ * Side Public License, v 1. */ -export { - ColorSchemas, - ColorSchema, - RawColorSchema, - ColorMap, - vislibColorMaps, - colorSchemas, -} from './color_maps'; +export type { ColorSchema, RawColorSchema, ColorMap } from './color_maps'; +export { ColorSchemas, vislibColorMaps, colorSchemas } from './color_maps'; export { getHeatmapColors } from './heatmap_color'; export { truncatedColorMaps, truncatedColorSchemas } from './truncated_color_maps'; diff --git a/src/plugins/charts/common/static/index.ts b/src/plugins/charts/common/static/index.ts index ac706ac7869c5..4a6b3ec2b52bb 100644 --- a/src/plugins/charts/common/static/index.ts +++ b/src/plugins/charts/common/static/index.ts @@ -6,11 +6,9 @@ * Side Public License, v 1. */ +export type { ColorSchema, RawColorSchema, ColorMap } from './color_maps'; export { ColorSchemas, - ColorSchema, - RawColorSchema, - ColorMap, vislibColorMaps, colorSchemas, getHeatmapColors, diff --git a/src/plugins/charts/public/index.ts b/src/plugins/charts/public/index.ts index e3d38b797c576..51d2722e3a24f 100644 --- a/src/plugins/charts/public/index.ts +++ b/src/plugins/charts/public/index.ts @@ -13,23 +13,28 @@ import { ChartsPlugin } from './plugin'; export const plugin = () => new ChartsPlugin(); -export { ChartsPluginSetup, ChartsPluginStart } from './plugin'; +export type { ChartsPluginSetup, ChartsPluginStart } from './plugin'; export * from './static'; export * from './services/palettes/types'; export { lightenColor } from './services/palettes/lighten_color'; export { useActiveCursor } from './services/active_cursor'; -export { +export type { PaletteOutput, CustomPaletteArguments, CustomPaletteState, SystemPaletteArguments, - paletteIds, - ColorSchemas, ColorSchema, RawColorSchema, ColorMap, + ColorSchemaParams, + Labels, + Style, +} from '../common'; +export { + paletteIds, + ColorSchemas, vislibColorMaps, colorSchemas, getHeatmapColors, @@ -38,7 +43,4 @@ export { ColorMode, LabelRotation, defaultCountLabel, - ColorSchemaParams, - Labels, - Style, } from '../common'; diff --git a/src/plugins/charts/public/services/theme/theme.ts b/src/plugins/charts/public/services/theme/theme.ts index dfea367327e7a..1aad4f0ab6328 100644 --- a/src/plugins/charts/public/services/theme/theme.ts +++ b/src/plugins/charts/public/services/theme/theme.ts @@ -39,10 +39,8 @@ export class ThemeService { /** A React hook for consuming the dark mode value */ public useDarkMode = (): boolean => { - // eslint-disable-next-line react-hooks/rules-of-hooks const [value, update] = useState(false); - // eslint-disable-next-line react-hooks/rules-of-hooks useEffect(() => { const s = this.darkModeEnabled$.subscribe(update); return () => s.unsubscribe(); @@ -53,12 +51,9 @@ export class ThemeService { /** A React hook for consuming the charts theme */ public useChartsTheme = (): PartialTheme => { - // eslint-disable-next-line react-hooks/rules-of-hooks const [value, update] = useState(this._chartsTheme$.getValue()); - // eslint-disable-next-line react-hooks/rules-of-hooks const ref = useRef(value); - // eslint-disable-next-line react-hooks/rules-of-hooks useEffect(() => { const s = this.chartsTheme$.subscribe((val) => { if (val !== ref.current) { @@ -74,12 +69,9 @@ export class ThemeService { /** A React hook for consuming the charts theme */ public useChartsBaseTheme = (): Theme => { - // eslint-disable-next-line react-hooks/rules-of-hooks const [value, update] = useState(this._chartsBaseTheme$.getValue()); - // eslint-disable-next-line react-hooks/rules-of-hooks const ref = useRef(value); - // eslint-disable-next-line react-hooks/rules-of-hooks useEffect(() => { const s = this.chartsBaseTheme$.subscribe((val) => { if (val !== ref.current) { diff --git a/src/plugins/charts/server/index.ts b/src/plugins/charts/server/index.ts index e65318747224d..73524964efb9b 100644 --- a/src/plugins/charts/server/index.ts +++ b/src/plugins/charts/server/index.ts @@ -7,12 +7,12 @@ */ import { ChartsServerPlugin } from './plugin'; -export { +export type { PaletteOutput, CustomPaletteArguments, CustomPaletteState, SystemPaletteArguments, - paletteIds, } from '../common'; +export { paletteIds } from '../common'; export const plugin = () => new ChartsServerPlugin(); diff --git a/src/plugins/console/public/application/components/index.ts b/src/plugins/console/public/application/components/index.ts index 7bf3bc8a9c33b..8f8292477cb94 100644 --- a/src/plugins/console/public/application/components/index.ts +++ b/src/plugins/console/public/application/components/index.ts @@ -8,9 +8,11 @@ export { NetworkRequestStatusBar } from './network_request_status_bar'; export { SomethingWentWrongCallout } from './something_went_wrong_callout'; -export { TopNavMenuItem, TopNavMenu } from './top_nav_menu'; +export type { TopNavMenuItem } from './top_nav_menu'; +export { TopNavMenu } from './top_nav_menu'; export { ConsoleMenu } from './console_menu'; export { WelcomePanel } from './welcome_panel'; -export { AutocompleteOptions, DevToolsSettingsModal } from './settings_modal'; +export type { AutocompleteOptions } from './settings_modal'; +export { DevToolsSettingsModal } from './settings_modal'; export { HelpPanel } from './help_panel'; export { EditorContentSpinner } from './editor_content_spinner'; diff --git a/src/plugins/console/public/application/contexts/index.ts b/src/plugins/console/public/application/contexts/index.ts index 693056ec23af6..2239c4f3354c2 100644 --- a/src/plugins/console/public/application/contexts/index.ts +++ b/src/plugins/console/public/application/contexts/index.ts @@ -6,7 +6,8 @@ * Side Public License, v 1. */ -export { useServicesContext, ServicesContextProvider, ContextValue } from './services_context'; +export type { ContextValue } from './services_context'; +export { useServicesContext, ServicesContextProvider } from './services_context'; export { useRequestActionContext, diff --git a/src/plugins/console/public/application/lib/index.ts b/src/plugins/console/public/application/lib/index.ts index 3c67718d170ee..8eba015910362 100644 --- a/src/plugins/console/public/application/lib/index.ts +++ b/src/plugins/console/public/application/lib/index.ts @@ -6,5 +6,6 @@ * Side Public License, v 1. */ -export { createApi, Api } from './api'; +export type { Api } from './api'; +export { createApi } from './api'; export { createEsHostService, EsHostService } from './es_host_service'; diff --git a/src/plugins/console/public/services/index.ts b/src/plugins/console/public/services/index.ts index 2b1e64525d0f9..c37c9d9359a16 100644 --- a/src/plugins/console/public/services/index.ts +++ b/src/plugins/console/public/services/index.ts @@ -8,4 +8,5 @@ export { createHistory, History } from './history'; export { createStorage, Storage, StorageKeys } from './storage'; -export { createSettings, Settings, DevToolsSettings, DEFAULT_SETTINGS } from './settings'; +export type { DevToolsSettings } from './settings'; +export { createSettings, Settings, DEFAULT_SETTINGS } from './settings'; diff --git a/src/plugins/console/public/types/index.ts b/src/plugins/console/public/types/index.ts index d8b6aaf7b12c4..2a86e53e55b80 100644 --- a/src/plugins/console/public/types/index.ts +++ b/src/plugins/console/public/types/index.ts @@ -11,5 +11,5 @@ export * from './core_editor'; export * from './token'; export * from './tokens_provider'; export * from './common'; -export { ClientConfigType } from './config'; -export { ConsoleUILocatorParams } from './locator'; +export type { ClientConfigType } from './config'; +export type { ConsoleUILocatorParams } from './locator'; diff --git a/src/plugins/console/server/index.ts b/src/plugins/console/server/index.ts index b270b89a3d45a..598dfa23958c9 100644 --- a/src/plugins/console/server/index.ts +++ b/src/plugins/console/server/index.ts @@ -10,7 +10,7 @@ import { PluginInitializerContext } from 'kibana/server'; import { ConsoleServerPlugin } from './plugin'; -export { ConsoleSetup, ConsoleStart } from './types'; +export type { ConsoleSetup, ConsoleStart } from './types'; export { config } from './config'; diff --git a/src/plugins/custom_integrations/public/components/replacement_card/index.ts b/src/plugins/custom_integrations/public/components/replacement_card/index.ts index 631dc1fcb2ba2..3c378d7603f95 100644 --- a/src/plugins/custom_integrations/public/components/replacement_card/index.ts +++ b/src/plugins/custom_integrations/public/components/replacement_card/index.ts @@ -8,7 +8,8 @@ import { ReplacementCard } from './replacement_card'; -export { ReplacementCard, Props } from './replacement_card'; +export type { Props } from './replacement_card'; +export { ReplacementCard } from './replacement_card'; // required for dynamic import using React.lazy() // eslint-disable-next-line import/no-default-export diff --git a/src/plugins/custom_integrations/public/index.ts b/src/plugins/custom_integrations/public/index.ts index 91da75c634a44..27176c4c5acbe 100755 --- a/src/plugins/custom_integrations/public/index.ts +++ b/src/plugins/custom_integrations/public/index.ts @@ -14,7 +14,7 @@ export function plugin() { return new CustomIntegrationsPlugin(); } -export { CustomIntegrationsSetup, CustomIntegrationsStart } from './types'; +export type { CustomIntegrationsSetup, CustomIntegrationsStart } from './types'; export { withSuspense, LazyReplacementCard } from './components'; export { filterCustomIntegrations } from './services/find'; diff --git a/src/plugins/custom_integrations/server/index.ts b/src/plugins/custom_integrations/server/index.ts index 00372df501435..e2da055e745c2 100755 --- a/src/plugins/custom_integrations/server/index.ts +++ b/src/plugins/custom_integrations/server/index.ts @@ -17,7 +17,7 @@ export function plugin(initializerContext: PluginInitializerContext) { return new CustomIntegrationsPlugin(initializerContext); } -export { CustomIntegrationsPluginSetup, CustomIntegrationsPluginStart } from './types'; +export type { CustomIntegrationsPluginSetup, CustomIntegrationsPluginStart } from './types'; export type { IntegrationCategory, CustomIntegration } from '../common'; diff --git a/src/plugins/dashboard/common/index.ts b/src/plugins/dashboard/common/index.ts index 1ed5bfba3abb9..73e01693977d9 100644 --- a/src/plugins/dashboard/common/index.ts +++ b/src/plugins/dashboard/common/index.ts @@ -6,14 +6,14 @@ * Side Public License, v 1. */ -export { GridData } from './embeddable/types'; -export { +export type { GridData } from './embeddable/types'; +export type { RawSavedDashboardPanel730ToLatest, DashboardDoc730ToLatest, DashboardDoc700To720, DashboardDocPre700, } from './bwc/types'; -export { +export type { DashboardContainerStateWithType, SavedDashboardPanelTo60, SavedDashboardPanel610, diff --git a/src/plugins/dashboard/public/application/actions/index.ts b/src/plugins/dashboard/public/application/actions/index.ts index 827ae5bcb4419..2c6263314cb25 100644 --- a/src/plugins/dashboard/public/application/actions/index.ts +++ b/src/plugins/dashboard/public/application/actions/index.ts @@ -6,39 +6,22 @@ * Side Public License, v 1. */ +export type { ExpandPanelActionContext } from './expand_panel_action'; +export { ExpandPanelAction, ACTION_EXPAND_PANEL } from './expand_panel_action'; +export type { ReplacePanelActionContext } from './replace_panel_action'; +export { ReplacePanelAction, ACTION_REPLACE_PANEL } from './replace_panel_action'; +export type { ClonePanelActionContext } from './clone_panel_action'; +export { ClonePanelAction, ACTION_CLONE_PANEL } from './clone_panel_action'; +export type { AddToLibraryActionContext } from './add_to_library_action'; +export { AddToLibraryAction, ACTION_ADD_TO_LIBRARY } from './add_to_library_action'; +export type { UnlinkFromLibraryActionContext } from './unlink_from_library_action'; +export { UnlinkFromLibraryAction, ACTION_UNLINK_FROM_LIBRARY } from './unlink_from_library_action'; +export type { CopyToDashboardActionContext } from './copy_to_dashboard_action'; +export { CopyToDashboardAction, ACTION_COPY_TO_DASHBOARD } from './copy_to_dashboard_action'; +export type { LibraryNotificationActionContext } from './library_notification_action'; export { - ExpandPanelAction, - ExpandPanelActionContext, - ACTION_EXPAND_PANEL, -} from './expand_panel_action'; -export { - ReplacePanelAction, - ReplacePanelActionContext, - ACTION_REPLACE_PANEL, -} from './replace_panel_action'; -export { - ClonePanelAction, - ClonePanelActionContext, - ACTION_CLONE_PANEL, -} from './clone_panel_action'; -export { - AddToLibraryAction, - AddToLibraryActionContext, - ACTION_ADD_TO_LIBRARY, -} from './add_to_library_action'; -export { - UnlinkFromLibraryAction, - UnlinkFromLibraryActionContext, - ACTION_UNLINK_FROM_LIBRARY, -} from './unlink_from_library_action'; -export { - CopyToDashboardAction, - CopyToDashboardActionContext, - ACTION_COPY_TO_DASHBOARD, -} from './copy_to_dashboard_action'; -export { - LibraryNotificationActionContext, LibraryNotificationAction, ACTION_LIBRARY_NOTIFICATION, } from './library_notification_action'; -export { ExportContext, ExportCSVAction, ACTION_EXPORT_CSV } from './export_csv_action'; +export type { ExportContext } from './export_csv_action'; +export { ExportCSVAction, ACTION_EXPORT_CSV } from './export_csv_action'; diff --git a/src/plugins/dashboard/public/application/embeddable/index.ts b/src/plugins/dashboard/public/application/embeddable/index.ts index b3ee0f83ee852..ce8bb5b7169ac 100644 --- a/src/plugins/dashboard/public/application/embeddable/index.ts +++ b/src/plugins/dashboard/public/application/embeddable/index.ts @@ -6,10 +6,8 @@ * Side Public License, v 1. */ -export { - DashboardContainerFactoryDefinition, - DashboardContainerFactory, -} from './dashboard_container_factory'; +export type { DashboardContainerFactory } from './dashboard_container_factory'; +export { DashboardContainerFactoryDefinition } from './dashboard_container_factory'; export type { DashboardContainer } from './dashboard_container'; export { createPanelState } from './panel'; diff --git a/src/plugins/dashboard/public/index.ts b/src/plugins/dashboard/public/index.ts index ff7708689c221..f25a92275d723 100644 --- a/src/plugins/dashboard/public/index.ts +++ b/src/plugins/dashboard/public/index.ts @@ -16,22 +16,19 @@ export { } from './application'; export { DashboardConstants, createDashboardEditUrl } from './dashboard_constants'; -export { +export type { DashboardSetup, DashboardStart, DashboardUrlGenerator, DashboardFeatureFlagConfig, } from './plugin'; -export { - DASHBOARD_APP_URL_GENERATOR, - createDashboardUrlGenerator, - DashboardUrlGeneratorState, -} from './url_generator'; -export { DashboardAppLocator, DashboardAppLocatorParams } from './locator'; +export type { DashboardUrlGeneratorState } from './url_generator'; +export { DASHBOARD_APP_URL_GENERATOR, createDashboardUrlGenerator } from './url_generator'; +export type { DashboardAppLocator, DashboardAppLocatorParams } from './locator'; -export { DashboardSavedObject } from './saved_dashboards'; -export { SavedDashboardPanel, DashboardContainerInput } from './types'; +export type { DashboardSavedObject } from './saved_dashboards'; +export type { SavedDashboardPanel, DashboardContainerInput } from './types'; export function plugin(initializerContext: PluginInitializerContext) { return new DashboardPlugin(initializerContext); diff --git a/src/plugins/dashboard/public/services/core.ts b/src/plugins/dashboard/public/services/core.ts index e805c6cd706a9..38c91842de4f2 100644 --- a/src/plugins/dashboard/public/services/core.ts +++ b/src/plugins/dashboard/public/services/core.ts @@ -6,12 +6,12 @@ * Side Public License, v 1. */ -export { +export type { AppMountParameters, CoreSetup, Capabilities, PluginInitializerContext, - ScopedHistory, NotificationsStart, ApplicationStart, } from '../../../../core/public'; +export { ScopedHistory } from '../../../../core/public'; diff --git a/src/plugins/dashboard/public/services/home.ts b/src/plugins/dashboard/public/services/home.ts index 692a1218b9535..ebbb715e53ca6 100644 --- a/src/plugins/dashboard/public/services/home.ts +++ b/src/plugins/dashboard/public/services/home.ts @@ -6,4 +6,5 @@ * Side Public License, v 1. */ -export { FeatureCatalogueCategory, HomePublicPluginSetup } from '../../../home/public'; +export type { HomePublicPluginSetup } from '../../../home/public'; +export { FeatureCatalogueCategory } from '../../../home/public'; diff --git a/src/plugins/dashboard/public/services/kibana_react.ts b/src/plugins/dashboard/public/services/kibana_react.ts index 203b6aa9cd2cb..4d5a3a5b57657 100644 --- a/src/plugins/dashboard/public/services/kibana_react.ts +++ b/src/plugins/dashboard/public/services/kibana_react.ts @@ -6,6 +6,11 @@ * Side Public License, v 1. */ +export type { + KibanaReactContext, + KibanaReactContextValue, + ExitFullScreenButtonProps, +} from '../../../kibana_react/public'; export { context, useKibana, @@ -13,9 +18,6 @@ export { toMountPoint, TableListView, reactToUiComponent, - KibanaReactContext, ExitFullScreenButton, KibanaContextProvider, - KibanaReactContextValue, - ExitFullScreenButtonProps, } from '../../../kibana_react/public'; diff --git a/src/plugins/dashboard/public/services/kibana_utils.ts b/src/plugins/dashboard/public/services/kibana_utils.ts index 94128f902df02..599e9b73f504f 100644 --- a/src/plugins/dashboard/public/services/kibana_utils.ts +++ b/src/plugins/dashboard/public/services/kibana_utils.ts @@ -6,19 +6,21 @@ * Side Public License, v 1. */ +export type { + ISyncStateRef, + IKbnUrlStateStorage, + ReduxLikeStateContainer, +} from '../../../kibana_utils/public'; export { Storage, unhashUrl, syncState, - ISyncStateRef, getQueryParams, setStateToKbnUrl, removeQueryParam, withNotifyOnErrors, - IKbnUrlStateStorage, createKbnUrlTracker, SavedObjectNotFound, createStateContainer, - ReduxLikeStateContainer, createKbnUrlStateStorage, } from '../../../kibana_utils/public'; diff --git a/src/plugins/dashboard/public/services/navigation.ts b/src/plugins/dashboard/public/services/navigation.ts index 60373b0eb44ec..eb1622eba35e0 100644 --- a/src/plugins/dashboard/public/services/navigation.ts +++ b/src/plugins/dashboard/public/services/navigation.ts @@ -6,4 +6,4 @@ * Side Public License, v 1. */ -export { NavigationPublicPluginStart } from '../../../navigation/public'; +export type { NavigationPublicPluginStart } from '../../../navigation/public'; diff --git a/src/plugins/dashboard/public/services/presentation_util.ts b/src/plugins/dashboard/public/services/presentation_util.ts index 17bc97db9ac63..d640b6326729d 100644 --- a/src/plugins/dashboard/public/services/presentation_util.ts +++ b/src/plugins/dashboard/public/services/presentation_util.ts @@ -6,9 +6,5 @@ * Side Public License, v 1. */ -export { - PresentationUtilPluginStart, - LazyDashboardPicker, - withSuspense, - useLabs, -} from '../../../presentation_util/public'; +export type { PresentationUtilPluginStart } from '../../../presentation_util/public'; +export { LazyDashboardPicker, withSuspense, useLabs } from '../../../presentation_util/public'; diff --git a/src/plugins/dashboard/public/services/saved_objects.ts b/src/plugins/dashboard/public/services/saved_objects.ts index bd4a73f8ed817..305ff3c2014f8 100644 --- a/src/plugins/dashboard/public/services/saved_objects.ts +++ b/src/plugins/dashboard/public/services/saved_objects.ts @@ -6,14 +6,16 @@ * Side Public License, v 1. */ -export { +export type { SaveResult, SavedObject, - showSaveModal, - SavedObjectLoader, SavedObjectsStart, SavedObjectSaveOpts, + SavedObjectLoaderFindOptions, +} from '../../../saved_objects/public'; +export { + showSaveModal, + SavedObjectLoader, SavedObjectSaveModal, getSavedObjectFinder, - SavedObjectLoaderFindOptions, } from '../../../saved_objects/public'; diff --git a/src/plugins/dashboard/public/services/share.ts b/src/plugins/dashboard/public/services/share.ts index 38a516ff80ecb..7ed9b86571596 100644 --- a/src/plugins/dashboard/public/services/share.ts +++ b/src/plugins/dashboard/public/services/share.ts @@ -6,9 +6,9 @@ * Side Public License, v 1. */ -export { +export type { SharePluginStart, SharePluginSetup, - downloadMultipleAs, UrlGeneratorContract, } from '../../../share/public'; +export { downloadMultipleAs } from '../../../share/public'; diff --git a/src/plugins/dashboard/public/services/spaces.ts b/src/plugins/dashboard/public/services/spaces.ts index 89a0acaf611bd..4ebe6644e2393 100644 --- a/src/plugins/dashboard/public/services/spaces.ts +++ b/src/plugins/dashboard/public/services/spaces.ts @@ -6,4 +6,4 @@ * Side Public License, v 1. */ -export { SpacesPluginStart } from '../../../../../x-pack/plugins/spaces/public'; +export type { SpacesPluginStart } from '../../../../../x-pack/plugins/spaces/public'; diff --git a/src/plugins/dashboard/public/services/ui_actions.ts b/src/plugins/dashboard/public/services/ui_actions.ts index 017f5b232d11e..5dc2e016a121c 100644 --- a/src/plugins/dashboard/public/services/ui_actions.ts +++ b/src/plugins/dashboard/public/services/ui_actions.ts @@ -6,9 +6,5 @@ * Side Public License, v 1. */ -export { - Action, - IncompatibleActionError, - UiActionsSetup, - UiActionsStart, -} from '../../../ui_actions/public'; +export type { Action, UiActionsSetup, UiActionsStart } from '../../../ui_actions/public'; +export { IncompatibleActionError } from '../../../ui_actions/public'; diff --git a/src/plugins/dashboard/public/services/usage_collection.ts b/src/plugins/dashboard/public/services/usage_collection.ts index 4bf43106f4e8f..dee7499c61138 100644 --- a/src/plugins/dashboard/public/services/usage_collection.ts +++ b/src/plugins/dashboard/public/services/usage_collection.ts @@ -6,4 +6,4 @@ * Side Public License, v 1. */ -export { UsageCollectionSetup } from '../../../usage_collection/public'; +export type { UsageCollectionSetup } from '../../../usage_collection/public'; diff --git a/src/plugins/dashboard/public/types.ts b/src/plugins/dashboard/public/types.ts index c4cc00838a343..d4a6cb20bc551 100644 --- a/src/plugins/dashboard/public/types.ts +++ b/src/plugins/dashboard/public/types.ts @@ -39,7 +39,7 @@ import { DashboardAppLocatorParams } from './locator'; import { SpacesPluginStart } from './services/spaces'; import type { DashboardControlGroupInput } from './application/lib/dashboard_control_group'; -export { SavedDashboardPanel }; +export type { SavedDashboardPanel }; export type NavAction = (anchorElement?: any) => void; export interface SavedDashboardPanelMap { diff --git a/src/plugins/dashboard/server/index.ts b/src/plugins/dashboard/server/index.ts index 3af8833d5e4a4..c99ca43ad835e 100644 --- a/src/plugins/dashboard/server/index.ts +++ b/src/plugins/dashboard/server/index.ts @@ -24,5 +24,5 @@ export function plugin(initializerContext: PluginInitializerContext) { return new DashboardPlugin(initializerContext); } -export { DashboardPluginSetup, DashboardPluginStart } from './types'; +export type { DashboardPluginSetup, DashboardPluginStart } from './types'; export { findByValueEmbeddables } from './usage/find_by_value_embeddables'; diff --git a/src/plugins/data/common/es_query/index.ts b/src/plugins/data/common/es_query/index.ts index 7029e9d064b21..28361114be6e1 100644 --- a/src/plugins/data/common/es_query/index.ts +++ b/src/plugins/data/common/es_query/index.ts @@ -373,6 +373,21 @@ type EsQueryConfig = oldEsQueryConfig; * @removeBy 8.1 */ +export type { + Filter, + RangeFilterMeta, + RangeFilterParams, + ExistsFilter, + PhrasesFilter, + PhraseFilter, + MatchAllFilter, + CustomFilter, + RangeFilter, + KueryNode, + FilterMeta, + IFieldSubType, + EsQueryConfig, +}; export { COMPARE_ALL_OPTIONS, compareFilters, @@ -414,17 +429,4 @@ export { onlyDisabledFiltersChanged, uniqFilters, FilterStateStore, - Filter, - RangeFilterMeta, - RangeFilterParams, - ExistsFilter, - PhrasesFilter, - PhraseFilter, - MatchAllFilter, - CustomFilter, - RangeFilter, - KueryNode, - FilterMeta, - IFieldSubType, - EsQueryConfig, }; diff --git a/src/plugins/data/common/index.ts b/src/plugins/data/common/index.ts index 34a75f8f24dc6..9a58b73d2c49c 100644 --- a/src/plugins/data/common/index.ts +++ b/src/plugins/data/common/index.ts @@ -51,6 +51,12 @@ export type { IndexPatternLoadStartDependencies, IndexPatternLoadExpressionFunctionDefinition, } from '../../data_views/common'; +export type { + IndexPatternsContract, + DataViewsContract, + IndexPatternListItem, + DataViewListItem, +} from '../../data_views/common'; export { RUNTIME_FIELD_TYPES, FLEET_ASSETS_TO_IGNORE, @@ -64,13 +70,9 @@ export { DataViewType, IndexPatternType, IndexPatternsService, - IndexPatternsContract, DataViewsService, - DataViewsContract, IndexPattern, - IndexPatternListItem, DataView, - DataViewListItem, DuplicateDataViewError, DataViewSavedObjectConflictError, getIndexPatternLoadMeta, diff --git a/src/plugins/data/common/kbn_field_types/types.ts b/src/plugins/data/common/kbn_field_types/types.ts index cea35a53e9da1..29471e95a36b8 100644 --- a/src/plugins/data/common/kbn_field_types/types.ts +++ b/src/plugins/data/common/kbn_field_types/types.ts @@ -8,4 +8,5 @@ import { KbnFieldTypeOptions, ES_FIELD_TYPES, KBN_FIELD_TYPES } from '@kbn/field-types'; -export { KbnFieldTypeOptions, ES_FIELD_TYPES, KBN_FIELD_TYPES }; +export type { KbnFieldTypeOptions }; +export { ES_FIELD_TYPES, KBN_FIELD_TYPES }; diff --git a/src/plugins/data/common/search/aggs/types.ts b/src/plugins/data/common/search/aggs/types.ts index fec02a5ae23fd..34c4f0fbf98c5 100644 --- a/src/plugins/data/common/search/aggs/types.ts +++ b/src/plugins/data/common/search/aggs/types.ts @@ -89,14 +89,14 @@ import { aggSinglePercentile, } from './'; -export { IAggConfig, AggConfigSerialized } from './agg_config'; -export { CreateAggConfigParams, IAggConfigs } from './agg_configs'; -export { IAggType } from './agg_type'; -export { AggParam, AggParamOption } from './agg_params'; -export { IFieldParamType } from './param_types'; -export { IMetricAggType } from './metrics/metric_agg_type'; -export { IpRangeKey } from './buckets/lib/ip_range'; -export { OptionedValueProp } from './param_types/optioned'; +export type { IAggConfig, AggConfigSerialized } from './agg_config'; +export type { CreateAggConfigParams, IAggConfigs } from './agg_configs'; +export type { IAggType } from './agg_type'; +export type { AggParam, AggParamOption } from './agg_params'; +export type { IFieldParamType } from './param_types'; +export type { IMetricAggType } from './metrics/metric_agg_type'; +export type { IpRangeKey } from './buckets/lib/ip_range'; +export type { OptionedValueProp } from './param_types/optioned'; /** @internal */ export interface AggsCommonSetup { diff --git a/src/plugins/data/public/actions/index.ts b/src/plugins/data/public/actions/index.ts index cb4eff5c274bb..0ec33f7e46523 100644 --- a/src/plugins/data/public/actions/index.ts +++ b/src/plugins/data/public/actions/index.ts @@ -6,11 +6,8 @@ * Side Public License, v 1. */ -export { - ACTION_GLOBAL_APPLY_FILTER, - createFilterAction, - ApplyGlobalFilterActionContext, -} from './apply_filter_action'; +export type { ApplyGlobalFilterActionContext } from './apply_filter_action'; +export { ACTION_GLOBAL_APPLY_FILTER, createFilterAction } from './apply_filter_action'; export { createFiltersFromValueClickAction } from './filters/create_filters_from_value_click'; export { createFiltersFromRangeSelectAction } from './filters/create_filters_from_range_select'; export * from './select_range_action'; diff --git a/src/plugins/data/public/autocomplete/collectors/index.ts b/src/plugins/data/public/autocomplete/collectors/index.ts index 5cfaab19787da..e9b5736008ab1 100644 --- a/src/plugins/data/public/autocomplete/collectors/index.ts +++ b/src/plugins/data/public/autocomplete/collectors/index.ts @@ -7,4 +7,5 @@ */ export { createUsageCollector } from './create_usage_collector'; -export { AUTOCOMPLETE_EVENT_TYPE, AutocompleteUsageCollector } from './types'; +export type { AutocompleteUsageCollector } from './types'; +export { AUTOCOMPLETE_EVENT_TYPE } from './types'; diff --git a/src/plugins/data/public/autocomplete/index.ts b/src/plugins/data/public/autocomplete/index.ts index 00aa14b86409a..b36af8f12eb52 100644 --- a/src/plugins/data/public/autocomplete/index.ts +++ b/src/plugins/data/public/autocomplete/index.ts @@ -6,13 +6,14 @@ * Side Public License, v 1. */ -export { +export type { QuerySuggestion, - QuerySuggestionTypes, QuerySuggestionGetFn, QuerySuggestionGetFnArgs, QuerySuggestionBasic, QuerySuggestionField, } from './providers/query_suggestion_provider'; +export { QuerySuggestionTypes } from './providers/query_suggestion_provider'; -export { AutocompleteService, AutocompleteSetup, AutocompleteStart } from './autocomplete_service'; +export type { AutocompleteSetup, AutocompleteStart } from './autocomplete_service'; +export { AutocompleteService } from './autocomplete_service'; diff --git a/src/plugins/data/public/deprecated.ts b/src/plugins/data/public/deprecated.ts index 163d329858293..8b90f92b932e0 100644 --- a/src/plugins/data/public/deprecated.ts +++ b/src/plugins/data/public/deprecated.ts @@ -137,7 +137,7 @@ export const esFilters = { /** * Deprecated type exports */ -export { +export type { KueryNode, RangeFilter, RangeFilterMeta, @@ -149,9 +149,8 @@ export { MatchAllFilter, IFieldSubType, EsQueryConfig, - isFilter, - isFilters, }; +export { isFilter, isFilters }; /** * @deprecated Import helpers from the "@kbn/es-query" package directly instead. diff --git a/src/plugins/data/public/index.ts b/src/plugins/data/public/index.ts index 4d51a7ae0ad77..0b749d90f7152 100644 --- a/src/plugins/data/public/index.ts +++ b/src/plugins/data/public/index.ts @@ -70,29 +70,26 @@ export const indexPatterns = { validate: validateDataView, }; -export { - IndexPatternsContract, - DataViewsContract, - IndexPattern, - IndexPatternField, - TypeMeta, -} from './data_views'; +export type { IndexPatternsContract, DataViewsContract, TypeMeta } from './data_views'; +export { IndexPattern, IndexPatternField } from './data_views'; -export { +export type { IIndexPattern, IFieldType, - ES_FIELD_TYPES, - KBN_FIELD_TYPES, IndexPatternAttributes, - UI_SETTINGS, AggregationRestrictions as IndexPatternAggRestrictions, IndexPatternSpec, IndexPatternLoadExpressionFunctionDefinition, - fieldList, GetFieldsOptions, AggregationRestrictions, - IndexPatternType, IndexPatternListItem, +} from '../common'; +export { + ES_FIELD_TYPES, + KBN_FIELD_TYPES, + UI_SETTINGS, + fieldList, + IndexPatternType, DuplicateDataViewError, } from '../common'; @@ -217,7 +214,8 @@ export type { SearchUsageCollector, } from './search'; -export { ISearchOptions, isErrorResponse, isCompleteResponse, isPartialResponse } from '../common'; +export type { ISearchOptions } from '../common'; +export { isErrorResponse, isCompleteResponse, isPartialResponse } from '../common'; // Search namespace export const search = { @@ -301,7 +299,8 @@ export { export { isTimeRange, isQuery } from '../common'; -export { ACTION_GLOBAL_APPLY_FILTER, ApplyGlobalFilterActionContext } from './actions'; +export type { ApplyGlobalFilterActionContext } from './actions'; +export { ACTION_GLOBAL_APPLY_FILTER } from './actions'; export { APPLY_FILTER_TRIGGER } from './triggers'; /* diff --git a/src/plugins/data/public/now_provider/index.ts b/src/plugins/data/public/now_provider/index.ts index 4d22d674b60b4..b3bfd31fca2c4 100644 --- a/src/plugins/data/public/now_provider/index.ts +++ b/src/plugins/data/public/now_provider/index.ts @@ -6,8 +6,5 @@ * Side Public License, v 1. */ -export { - NowProvider, - NowProviderInternalContract, - NowProviderPublicContract, -} from './now_provider'; +export type { NowProviderInternalContract, NowProviderPublicContract } from './now_provider'; +export { NowProvider } from './now_provider'; diff --git a/src/plugins/data/public/query/query_string/index.ts b/src/plugins/data/public/query/query_string/index.ts index feef1965f8b24..63cc777f6688d 100644 --- a/src/plugins/data/public/query/query_string/index.ts +++ b/src/plugins/data/public/query/query_string/index.ts @@ -6,4 +6,5 @@ * Side Public License, v 1. */ -export { QueryStringContract, QueryStringManager } from './query_string_manager'; +export type { QueryStringContract } from './query_string_manager'; +export { QueryStringManager } from './query_string_manager'; diff --git a/src/plugins/data/public/query/saved_query/index.ts b/src/plugins/data/public/query/saved_query/index.ts index 6cde77c7a7722..03d8f0b35b9b1 100644 --- a/src/plugins/data/public/query/saved_query/index.ts +++ b/src/plugins/data/public/query/saved_query/index.ts @@ -6,5 +6,10 @@ * Side Public License, v 1. */ -export { SavedQuery, SavedQueryAttributes, SavedQueryService, SavedQueryTimeFilter } from './types'; +export type { + SavedQuery, + SavedQueryAttributes, + SavedQueryService, + SavedQueryTimeFilter, +} from './types'; export { createSavedQueryService } from './saved_query_service'; diff --git a/src/plugins/data/public/query/state_sync/index.ts b/src/plugins/data/public/query/state_sync/index.ts index dac51411dfd40..58740cfab06d0 100644 --- a/src/plugins/data/public/query/state_sync/index.ts +++ b/src/plugins/data/public/query/state_sync/index.ts @@ -8,4 +8,4 @@ export { connectToQueryState } from './connect_to_query_state'; export { syncQueryStateWithUrl } from './sync_state_with_url'; -export { QueryState, QueryStateChange } from './types'; +export type { QueryState, QueryStateChange } from './types'; diff --git a/src/plugins/data/public/query/timefilter/index.ts b/src/plugins/data/public/query/timefilter/index.ts index 3dfd4e0fe514f..604213054fd02 100644 --- a/src/plugins/data/public/query/timefilter/index.ts +++ b/src/plugins/data/public/query/timefilter/index.ts @@ -6,11 +6,14 @@ * Side Public License, v 1. */ -export { TimefilterService, TimefilterSetup } from './timefilter_service'; +export type { TimefilterSetup } from './timefilter_service'; +export { TimefilterService } from './timefilter_service'; export * from './types'; -export { Timefilter, TimefilterContract, AutoRefreshDoneFn } from './timefilter'; -export { TimeHistory, TimeHistoryContract } from './time_history'; +export type { TimefilterContract, AutoRefreshDoneFn } from './timefilter'; +export { Timefilter } from './timefilter'; +export type { TimeHistoryContract } from './time_history'; +export { TimeHistory } from './time_history'; export { changeTimeFilter, convertRangeFilterToTimeRangeString } from './lib/change_time_filter'; export { extractTimeFilter, extractTimeRange } from './lib/extract_time_filter'; export { validateTimeRange } from './lib/validate_timerange'; diff --git a/src/plugins/data/public/query/timefilter/timefilter.ts b/src/plugins/data/public/query/timefilter/timefilter.ts index 3b537562586a7..f3520abb2f46e 100644 --- a/src/plugins/data/public/query/timefilter/timefilter.ts +++ b/src/plugins/data/public/query/timefilter/timefilter.ts @@ -25,7 +25,7 @@ import { import { TimeHistoryContract } from './time_history'; import { createAutoRefreshLoop, AutoRefreshDoneFn } from './lib/auto_refresh_loop'; -export { AutoRefreshDoneFn }; +export type { AutoRefreshDoneFn }; // TODO: remove! export class Timefilter { diff --git a/src/plugins/data/public/query/timefilter/types.ts b/src/plugins/data/public/query/timefilter/types.ts index 66584358ccb34..3c35ae2d79ae5 100644 --- a/src/plugins/data/public/query/timefilter/types.ts +++ b/src/plugins/data/public/query/timefilter/types.ts @@ -23,4 +23,4 @@ export type InputTimeRange = to: Moment; }; -export { TimeRangeBounds } from '../../../common'; +export type { TimeRangeBounds } from '../../../common'; diff --git a/src/plugins/data/public/search/aggs/types.ts b/src/plugins/data/public/search/aggs/types.ts index 34ec3415427d3..5a8110034bbc1 100644 --- a/src/plugins/data/public/search/aggs/types.ts +++ b/src/plugins/data/public/search/aggs/types.ts @@ -9,4 +9,4 @@ import { AggsCommonSetup } from '../../../common'; export type AggsSetup = AggsCommonSetup; -export { AggsStart } from '../../../common'; +export type { AggsStart } from '../../../common'; diff --git a/src/plugins/data/public/search/collectors/index.ts b/src/plugins/data/public/search/collectors/index.ts index b6640a8e61f6c..9eb96be5a0455 100644 --- a/src/plugins/data/public/search/collectors/index.ts +++ b/src/plugins/data/public/search/collectors/index.ts @@ -7,4 +7,5 @@ */ export { createUsageCollector } from './create_usage_collector'; -export { SEARCH_EVENT_TYPE, SearchUsageCollector } from './types'; +export type { SearchUsageCollector } from './types'; +export { SEARCH_EVENT_TYPE } from './types'; diff --git a/src/plugins/data/public/search/index.ts b/src/plugins/data/public/search/index.ts index 21d607eedb152..821f16e0cf68a 100644 --- a/src/plugins/data/public/search/index.ts +++ b/src/plugins/data/public/search/index.ts @@ -8,46 +8,51 @@ export * from './expressions'; -export { +export type { ISearchSetup, ISearchStart, ISearchStartSearchSource, SearchUsageCollector, } from './types'; -export { - ES_SEARCH_STRATEGY, +export type { EsQuerySortValue, - extractReferences as extractSearchSourceReferences, - getSearchParamsFromRequest, IEsSearchRequest, IEsSearchResponse, IKibanaSearchRequest, IKibanaSearchResponse, - injectReferences as injectSearchSourceReferences, ISearchGeneric, ISearchSource, - parseSearchSourceJSON, SearchError, SearchRequest, - SearchSource, SearchSourceDependencies, SearchSourceFields, - SortDirection, } from '../../common/search'; export { - SessionService, + ES_SEARCH_STRATEGY, + extractReferences as extractSearchSourceReferences, + getSearchParamsFromRequest, + injectReferences as injectSearchSourceReferences, + parseSearchSourceJSON, + SearchSource, + SortDirection, +} from '../../common/search'; +export type { ISessionService, SearchSessionInfoProvider, + ISessionsClient, + WaitUntilNextSessionCompletesOptions, +} from './session'; +export { + SessionService, SearchSessionState, SessionsClient, - ISessionsClient, noSearchSessionStorageCapabilityMessage, SEARCH_SESSIONS_MANAGEMENT_ID, waitUntilNextSessionCompletes$, - WaitUntilNextSessionCompletesOptions, } from './session'; export { getEsPreference } from './es_search'; -export { SearchInterceptor, SearchInterceptorDeps } from './search_interceptor'; +export type { SearchInterceptorDeps } from './search_interceptor'; +export { SearchInterceptor } from './search_interceptor'; export * from './errors'; diff --git a/src/plugins/data/public/search/search_interceptor/index.ts b/src/plugins/data/public/search/search_interceptor/index.ts index 411c4beefe96c..bf6930276020e 100644 --- a/src/plugins/data/public/search/search_interceptor/index.ts +++ b/src/plugins/data/public/search/search_interceptor/index.ts @@ -6,4 +6,5 @@ * Side Public License, v 1. */ -export { SearchInterceptor, ISearchInterceptor, SearchInterceptorDeps } from './search_interceptor'; +export type { ISearchInterceptor, SearchInterceptorDeps } from './search_interceptor'; +export { SearchInterceptor } from './search_interceptor'; diff --git a/src/plugins/data/public/search/session/index.ts b/src/plugins/data/public/search/session/index.ts index ce578378a2fe8..c48362538a5fd 100644 --- a/src/plugins/data/public/search/session/index.ts +++ b/src/plugins/data/public/search/session/index.ts @@ -6,12 +6,12 @@ * Side Public License, v 1. */ -export { SessionService, ISessionService, SearchSessionInfoProvider } from './session_service'; +export type { ISessionService, SearchSessionInfoProvider } from './session_service'; +export { SessionService } from './session_service'; export { SearchSessionState } from './search_session_state'; -export { SessionsClient, ISessionsClient } from './sessions_client'; +export type { ISessionsClient } from './sessions_client'; +export { SessionsClient } from './sessions_client'; export { noSearchSessionStorageCapabilityMessage } from './i18n'; export { SEARCH_SESSIONS_MANAGEMENT_ID } from './constants'; -export { - waitUntilNextSessionCompletes$, - WaitUntilNextSessionCompletesOptions, -} from './session_helpers'; +export type { WaitUntilNextSessionCompletesOptions } from './session_helpers'; +export { waitUntilNextSessionCompletes$ } from './session_helpers'; diff --git a/src/plugins/data/public/search/types.ts b/src/plugins/data/public/search/types.ts index 764933d15e065..3dacad42273ae 100644 --- a/src/plugins/data/public/search/types.ts +++ b/src/plugins/data/public/search/types.ts @@ -14,7 +14,7 @@ import { IndexPatternsContract } from '../../common'; import { UsageCollectionSetup } from '../../../usage_collection/public'; import { ISessionsClient, ISessionService } from './session'; -export { ISearchStartSearchSource, SearchUsageCollector }; +export type { ISearchStartSearchSource, SearchUsageCollector }; /** * The setup contract exposed by the Search plugin exposes the search strategy extension diff --git a/src/plugins/data/public/ui/index.ts b/src/plugins/data/public/ui/index.ts index 1c8df359602b9..026db1b7c09ee 100644 --- a/src/plugins/data/public/ui/index.ts +++ b/src/plugins/data/public/ui/index.ts @@ -6,8 +6,10 @@ * Side Public License, v 1. */ -export { IndexPatternSelectProps } from './index_pattern_select'; +export type { IndexPatternSelectProps } from './index_pattern_select'; export { FilterLabel, FilterItem } from './filter_bar'; -export { QueryStringInput, QueryStringInputProps } from './query_string_input'; -export { SearchBar, SearchBarProps, StatefulSearchBarProps } from './search_bar'; +export type { QueryStringInputProps } from './query_string_input'; +export { QueryStringInput } from './query_string_input'; +export type { SearchBarProps, StatefulSearchBarProps } from './search_bar'; +export { SearchBar } from './search_bar'; export { SuggestionsComponent } from './typeahead'; diff --git a/src/plugins/data/public/ui/saved_query_form/index.ts b/src/plugins/data/public/ui/saved_query_form/index.ts index f440294dc6eb7..1590b8fc98927 100644 --- a/src/plugins/data/public/ui/saved_query_form/index.ts +++ b/src/plugins/data/public/ui/saved_query_form/index.ts @@ -7,4 +7,5 @@ */ // @internal -export { SavedQueryMeta, SaveQueryForm } from '../saved_query_form/save_query_form'; +export type { SavedQueryMeta } from '../saved_query_form/save_query_form'; +export { SaveQueryForm } from '../saved_query_form/save_query_form'; diff --git a/src/plugins/data/public/ui/search_bar/index.tsx b/src/plugins/data/public/ui/search_bar/index.tsx index 64dacee4ad363..fac421dd743d7 100644 --- a/src/plugins/data/public/ui/search_bar/index.tsx +++ b/src/plugins/data/public/ui/search_bar/index.tsx @@ -21,5 +21,5 @@ const WrappedSearchBar = (props: SearchBarProps) => ( ); export const SearchBar = injectI18n(withKibana(WrappedSearchBar)); -export { StatefulSearchBarProps } from './create_search_bar'; +export type { StatefulSearchBarProps } from './create_search_bar'; export type { SearchBarProps, SearchBarOwnProps } from './search_bar'; diff --git a/src/plugins/data/server/index.ts b/src/plugins/data/server/index.ts index fce73e65dc699..939d4a9fa3237 100644 --- a/src/plugins/data/server/index.ts +++ b/src/plugins/data/server/index.ts @@ -36,20 +36,18 @@ export { DATA_VIEW_SAVED_OBJECT_TYPE } from '../common'; * Index patterns: */ +export type { FieldDescriptor, IndexPatternsServiceStart } from './data_views'; export { IndexPatternsFetcher, - shouldReadFieldFromDocValues, // used only in logstash_fields fixture - FieldDescriptor, + shouldReadFieldFromDocValues, getCapabilitiesForRollupIndices, - IndexPatternsServiceStart, } from './data_views'; +export type { IFieldType, IndexPatternAttributes } from '../common'; export { IndexPatternField, - IFieldType, ES_FIELD_TYPES, KBN_FIELD_TYPES, - IndexPatternAttributes, UI_SETTINGS, IndexPattern, IndexPatternsService, @@ -72,29 +70,24 @@ import { } from '../common'; import { autocompleteConfigDeprecationProvider } from './config_deprecations'; -export { - // aggs - METRIC_TYPES, +export type { ParsedInterval, - // search ISearchOptions, IEsSearchRequest, IEsSearchResponse, - ES_SEARCH_STRATEGY, } from '../common'; +export { METRIC_TYPES, ES_SEARCH_STRATEGY } from '../common'; -export { +export type { IScopedSearchClient, ISearchStrategy, SearchStrategyDependencies, - shimHitsTotal, - SearchSessionService, ISearchSessionService, SearchRequestHandlerContext, DataRequestHandlerContext, AsyncSearchStatusResponse, - NoSearchIdInSessionError, } from './search'; +export { shimHitsTotal, SearchSessionService, NoSearchIdInSessionError } from './search'; // Search namespace export const search = { @@ -112,14 +105,8 @@ export const search = { * @public */ -export { - castEsToKbnFieldTypeName, - getTime, - // timefilter - TimeRange, - // utils - parseInterval, -} from '../common'; +export type { TimeRange } from '../common'; +export { castEsToKbnFieldTypeName, getTime, parseInterval } from '../common'; /** * Static code to be shared externally @@ -130,11 +117,8 @@ export function plugin(initializerContext: PluginInitializerContext = { deprecations: autocompleteConfigDeprecationProvider, diff --git a/src/plugins/data/server/search/index.ts b/src/plugins/data/server/search/index.ts index b9affe96ea2dd..b7087e95c0a2c 100644 --- a/src/plugins/data/server/search/index.ts +++ b/src/plugins/data/server/search/index.ts @@ -10,7 +10,8 @@ export * from './types'; export * from './strategies/es_search'; export * from './strategies/ese_search'; export * from './strategies/eql_search'; -export { usageProvider, SearchUsage, searchUsageObserver } from './collectors'; +export type { SearchUsage } from './collectors'; +export { usageProvider, searchUsageObserver } from './collectors'; export * from './aggs'; export * from './session'; export * from './errors/no_search_id_in_session'; diff --git a/src/plugins/data/server/search/strategies/es_search/index.ts b/src/plugins/data/server/search/strategies/es_search/index.ts index d43fab0a86e69..53a791455e64e 100644 --- a/src/plugins/data/server/search/strategies/es_search/index.ts +++ b/src/plugins/data/server/search/strategies/es_search/index.ts @@ -9,4 +9,5 @@ export { esSearchStrategyProvider } from './es_search_strategy'; export * from './request_utils'; export * from './response_utils'; -export { ES_SEARCH_STRATEGY, IEsSearchRequest, IEsSearchResponse } from '../../../../common'; +export type { IEsSearchRequest, IEsSearchResponse } from '../../../../common'; +export { ES_SEARCH_STRATEGY } from '../../../../common'; diff --git a/src/plugins/data_views/common/index.ts b/src/plugins/data_views/common/index.ts index b057a1ba84174..b3123df2597cc 100644 --- a/src/plugins/data_views/common/index.ts +++ b/src/plugins/data_views/common/index.ts @@ -55,13 +55,10 @@ export type { SourceFilter, } from './types'; export { DataViewType, IndexPatternType } from './types'; -export { - IndexPatternsService, - IndexPatternsContract, - DataViewsService, - DataViewsContract, -} from './data_views'; -export { IndexPattern, IndexPatternListItem, DataView, DataViewListItem } from './data_views'; +export type { IndexPatternsContract, DataViewsContract } from './data_views'; +export { IndexPatternsService, DataViewsService } from './data_views'; +export type { IndexPatternListItem, DataViewListItem } from './data_views'; +export { IndexPattern, DataView } from './data_views'; export { DuplicateDataViewError, DataViewSavedObjectConflictError } from './errors'; export type { IndexPatternExpressionType, diff --git a/src/plugins/data_views/public/index.ts b/src/plugins/data_views/public/index.ts index 3a6b5ccb237f2..650d2132212f8 100644 --- a/src/plugins/data_views/public/index.ts +++ b/src/plugins/data_views/public/index.ts @@ -15,15 +15,15 @@ export { } from '../common/lib'; export { onRedirectNoIndexPattern } from './data_views'; -export { IndexPatternField, IIndexPatternFieldList, TypeMeta } from '../common'; +export type { IIndexPatternFieldList, TypeMeta } from '../common'; +export { IndexPatternField } from '../common'; +export type { IndexPatternsContract, DataViewsContract } from './data_views'; export { IndexPatternsService, - IndexPatternsContract, IndexPattern, DataViewsApiClient, DataViewsService, - DataViewsContract, DataView, } from './data_views'; export { UiSettingsPublicToCommon } from './ui_settings_wrapper'; diff --git a/src/plugins/data_views/server/fetcher/index_patterns_fetcher.test.ts b/src/plugins/data_views/server/fetcher/index_patterns_fetcher.test.ts index a65d4d551cf7c..1a8b705480258 100644 --- a/src/plugins/data_views/server/fetcher/index_patterns_fetcher.test.ts +++ b/src/plugins/data_views/server/fetcher/index_patterns_fetcher.test.ts @@ -5,7 +5,6 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - import { IndexPatternsFetcher } from '.'; import { ElasticsearchClient } from 'kibana/server'; import * as indexNotFoundException from './index_not_found_exception.json'; @@ -15,36 +14,36 @@ describe('Index Pattern Fetcher - server', () => { let esClient: ElasticsearchClient; const emptyResponse = { body: { - count: 0, + indices: [], }, }; const response = { body: { - count: 1115, + indices: ['b'], + fields: [{ name: 'foo' }, { name: 'bar' }, { name: 'baz' }], }, }; const patternList = ['a', 'b', 'c']; beforeEach(() => { + jest.clearAllMocks(); esClient = { - count: jest.fn().mockResolvedValueOnce(emptyResponse).mockResolvedValue(response), + fieldCaps: jest.fn().mockResolvedValueOnce(emptyResponse).mockResolvedValue(response), } as unknown as ElasticsearchClient; indexPatterns = new IndexPatternsFetcher(esClient); }); - it('Removes pattern without matching indices', async () => { const result = await indexPatterns.validatePatternListActive(patternList); expect(result).toEqual(['b', 'c']); }); - it('Returns all patterns when all match indices', async () => { esClient = { - count: jest.fn().mockResolvedValue(response), + fieldCaps: jest.fn().mockResolvedValue(response), } as unknown as ElasticsearchClient; indexPatterns = new IndexPatternsFetcher(esClient); const result = await indexPatterns.validatePatternListActive(patternList); expect(result).toEqual(patternList); }); - it('Removes pattern when "index_not_found_exception" error is thrown', async () => { + it('Removes pattern when error is thrown', async () => { class ServerError extends Error { public body?: Record; constructor( @@ -56,9 +55,8 @@ describe('Index Pattern Fetcher - server', () => { this.body = errBody; } } - esClient = { - count: jest + fieldCaps: jest .fn() .mockResolvedValueOnce(response) .mockRejectedValue( @@ -69,4 +67,22 @@ describe('Index Pattern Fetcher - server', () => { const result = await indexPatterns.validatePatternListActive(patternList); expect(result).toEqual([patternList[0]]); }); + it('When allowNoIndices is false, run validatePatternListActive', async () => { + const fieldCapsMock = jest.fn(); + esClient = { + fieldCaps: fieldCapsMock.mockResolvedValue(response), + } as unknown as ElasticsearchClient; + indexPatterns = new IndexPatternsFetcher(esClient); + await indexPatterns.getFieldsForWildcard({ pattern: patternList }); + expect(fieldCapsMock.mock.calls).toHaveLength(4); + }); + it('When allowNoIndices is true, do not run validatePatternListActive', async () => { + const fieldCapsMock = jest.fn(); + esClient = { + fieldCaps: fieldCapsMock.mockResolvedValue(response), + } as unknown as ElasticsearchClient; + indexPatterns = new IndexPatternsFetcher(esClient, true); + await indexPatterns.getFieldsForWildcard({ pattern: patternList }); + expect(fieldCapsMock.mock.calls).toHaveLength(1); + }); }); diff --git a/src/plugins/data_views/server/fetcher/index_patterns_fetcher.ts b/src/plugins/data_views/server/fetcher/index_patterns_fetcher.ts index 7dae85c920ebf..c054d547e956f 100644 --- a/src/plugins/data_views/server/fetcher/index_patterns_fetcher.ts +++ b/src/plugins/data_views/server/fetcher/index_patterns_fetcher.ts @@ -36,12 +36,10 @@ interface FieldSubType { export class IndexPatternsFetcher { private elasticsearchClient: ElasticsearchClient; private allowNoIndices: boolean; - constructor(elasticsearchClient: ElasticsearchClient, allowNoIndices: boolean = false) { this.elasticsearchClient = elasticsearchClient; this.allowNoIndices = allowNoIndices; } - /** * Get a list of field objects for an index pattern that may contain wildcards * @@ -60,23 +58,22 @@ export class IndexPatternsFetcher { }): Promise { const { pattern, metaFields, fieldCapsOptions, type, rollupIndex } = options; const patternList = Array.isArray(pattern) ? pattern : pattern.split(','); + const allowNoIndices = fieldCapsOptions + ? fieldCapsOptions.allow_no_indices + : this.allowNoIndices; let patternListActive: string[] = patternList; // if only one pattern, don't bother with validation. We let getFieldCapabilities fail if the single pattern is bad regardless - if (patternList.length > 1) { + if (patternList.length > 1 && !allowNoIndices) { patternListActive = await this.validatePatternListActive(patternList); } const fieldCapsResponse = await getFieldCapabilities( this.elasticsearchClient, - // if none of the patterns are active, pass the original list to get an error - patternListActive.length > 0 ? patternListActive : patternList, + patternListActive, metaFields, { - allow_no_indices: fieldCapsOptions - ? fieldCapsOptions.allow_no_indices - : this.allowNoIndices, + allow_no_indices: allowNoIndices, } ); - if (type === 'rollup' && rollupIndex) { const rollupFields: FieldDescriptor[] = []; const rollupIndexCapabilities = getCapabilitiesForRollupIndices( @@ -87,13 +84,11 @@ export class IndexPatternsFetcher { ).body )[rollupIndex].aggs; const fieldCapsResponseObj = keyBy(fieldCapsResponse, 'name'); - // Keep meta fields metaFields!.forEach( (field: string) => fieldCapsResponseObj[field] && rollupFields.push(fieldCapsResponseObj[field]) ); - return mergeCapabilitiesWithFields( rollupIndexCapabilities, fieldCapsResponseObj, @@ -137,23 +132,20 @@ export class IndexPatternsFetcher { async validatePatternListActive(patternList: string[]) { const result = await Promise.all( patternList - .map((pattern) => - this.elasticsearchClient.count({ - index: pattern, - }) - ) - .map((p) => - p.catch((e) => { - if (e.body.error.type === 'index_not_found_exception') { - return { body: { count: 0 } }; - } - throw e; - }) - ) + .map(async (index) => { + const searchResponse = await this.elasticsearchClient.fieldCaps({ + index, + fields: '_id', + ignore_unavailable: true, + allow_no_indices: false, + }); + return searchResponse.body.indices.length > 0; + }) + .map((p) => p.catch(() => false)) ); return result.reduce( - (acc: string[], { body: { count } }, patternListIndex) => - count > 0 ? [...acc, patternList[patternListIndex]] : acc, + (acc: string[], isValid, patternListIndex) => + isValid ? [...acc, patternList[patternListIndex]] : acc, [] ); } diff --git a/src/plugins/data_views/server/index.ts b/src/plugins/data_views/server/index.ts index 1c7eeb073bbe2..7a4df9518b435 100644 --- a/src/plugins/data_views/server/index.ts +++ b/src/plugins/data_views/server/index.ts @@ -7,14 +7,14 @@ */ export { getFieldByName, findIndexPatternById } from './utils'; +export type { FieldDescriptor } from './fetcher'; export { IndexPatternsFetcher, - FieldDescriptor, shouldReadFieldFromDocValues, mergeCapabilitiesWithFields, getCapabilitiesForRollupIndices, } from './fetcher'; -export { IndexPatternsServiceStart } from './types'; +export type { IndexPatternsServiceStart } from './types'; import { PluginInitializerContext } from 'src/core/server'; import { DataViewsServerPlugin } from './plugin'; @@ -30,8 +30,8 @@ export function plugin(initializerContext: PluginInitializerContext) { return new DataViewsServerPlugin(initializerContext); } -export { - DataViewsServerPlugin as Plugin, +export type { DataViewsServerPluginSetup as PluginSetup, DataViewsServerPluginStart as PluginStart, }; +export { DataViewsServerPlugin as Plugin }; diff --git a/src/plugins/discover/common/index.ts b/src/plugins/discover/common/index.ts index 32704d95423f7..6262855409b29 100644 --- a/src/plugins/discover/common/index.ts +++ b/src/plugins/discover/common/index.ts @@ -21,4 +21,5 @@ export const SEARCH_FIELDS_FROM_SOURCE = 'discover:searchFieldsFromSource'; export const MAX_DOC_FIELDS_DISPLAYED = 'discover:maxDocFieldsDisplayed'; export const SHOW_FIELD_STATISTICS = 'discover:showFieldStatistics'; export const SHOW_MULTIFIELDS = 'discover:showMultiFields'; +export const TRUNCATE_MAX_HEIGHT = 'truncate:maxHeight'; export const SEARCH_EMBEDDABLE_TYPE = 'search'; diff --git a/src/plugins/discover/public/application/apps/context/context_app_content.tsx b/src/plugins/discover/public/application/apps/context/context_app_content.tsx index 153639edc29a1..c8f3cfe0a568f 100644 --- a/src/plugins/discover/public/application/apps/context/context_app_content.tsx +++ b/src/plugins/discover/public/application/apps/context/context_app_content.tsx @@ -141,7 +141,7 @@ export function ContextAppContent({ dataTestSubj="contextDocTable" /> )} - {!isLegacy && rows && rows.length && ( + {!isLegacy && (
{ @@ -182,6 +190,47 @@ export function DiscoverHistogram({ const useLegacyTimeAxis = uiSettings.get(LEGACY_TIME_AXIS, false); + const toolTipTitle = i18n.translate('discover.timeIntervalWithValueWarning', { + defaultMessage: 'Warning', + }); + + const toolTipContent = i18n.translate('discover.bucketIntervalTooltip', { + defaultMessage: + 'This interval creates {bucketsDescription} to show in the selected time range, so it has been scaled to {bucketIntervalDescription}.', + values: { + bucketsDescription: + bucketInterval!.scale && bucketInterval!.scale > 1 + ? i18n.translate('discover.bucketIntervalTooltip.tooLargeBucketsText', { + defaultMessage: 'buckets that are too large', + }) + : i18n.translate('discover.bucketIntervalTooltip.tooManyBucketsText', { + defaultMessage: 'too many buckets', + }), + bucketIntervalDescription: bucketInterval?.description, + }, + }); + + let timeRange = ( + + {timeRangeText} + + ); + if (bucketInterval?.scaled) { + timeRange = ( + + {timeRange} + + + + + ); + } + return (
@@ -232,9 +281,7 @@ export function DiscoverHistogram({ />
- - {timeRangeText} - + {timeRange}
); } diff --git a/src/plugins/discover/public/application/apps/main/components/chart/use_chart_panels.ts b/src/plugins/discover/public/application/apps/main/components/chart/use_chart_panels.ts index 72f921bca5f53..3660173ef761d 100644 --- a/src/plugins/discover/public/application/apps/main/components/chart/use_chart_panels.ts +++ b/src/plugins/discover/public/application/apps/main/components/chart/use_chart_panels.ts @@ -12,8 +12,7 @@ import type { } from '@elastic/eui'; import { search } from '../../../../../../../data/public'; import { AppState } from '../../services/discover_state'; -import { DataCharts$, DataChartsMessage } from '../../services/use_saved_search'; -import { useDataState } from '../../utils/use_data_state'; +import { DataCharts$ } from '../../services/use_saved_search'; export function useChartPanels( state: AppState, @@ -22,8 +21,6 @@ export function useChartPanels( onChangeInterval: (value: string) => void, closePopover: () => void ) { - const dataState: DataChartsMessage = useDataState(savedSearchDataChart$); - const { bucketInterval } = dataState; const { interval, hideChart } = state; const selectedOptionIdx = search.aggs.intervalOptions.findIndex((opt) => opt.val === interval); const intervalDisplay = @@ -56,29 +53,6 @@ export function useChartPanels( timeInterval: intervalDisplay, }, }), - icon: bucketInterval?.scaled ? 'alert' : '', - toolTipTitle: bucketInterval?.scaled - ? i18n.translate('discover.timeIntervalWithValueWarning', { - defaultMessage: 'Warning', - }) - : '', - toolTipContent: bucketInterval?.scaled - ? i18n.translate('discover.bucketIntervalTooltip', { - defaultMessage: - 'This interval creates {bucketsDescription} to show in the selected time range, so it has been scaled to {bucketIntervalDescription}.', - values: { - bucketsDescription: - bucketInterval!.scale && bucketInterval!.scale > 1 - ? i18n.translate('discover.bucketIntervalTooltip.tooLargeBucketsText', { - defaultMessage: 'buckets that are too large', - }) - : i18n.translate('discover.bucketIntervalTooltip.tooManyBucketsText', { - defaultMessage: 'too many buckets', - }), - bucketIntervalDescription: bucketInterval?.description, - }, - }) - : '', panel: 1, 'data-test-subj': 'discoverTimeIntervalPanel', }); diff --git a/src/plugins/discover/public/application/apps/main/components/doc_table/_doc_table.scss b/src/plugins/discover/public/application/apps/main/components/doc_table/_doc_table.scss index d19a1fd042069..164b61d42df19 100644 --- a/src/plugins/discover/public/application/apps/main/components/doc_table/_doc_table.scss +++ b/src/plugins/discover/public/application/apps/main/components/doc_table/_doc_table.scss @@ -103,10 +103,6 @@ text-align: center; } -.truncate-by-height { - overflow: hidden; -} - .table { // Nesting .table { diff --git a/src/plugins/discover/public/application/apps/main/components/doc_table/components/table_row.tsx b/src/plugins/discover/public/application/apps/main/components/doc_table/components/table_row.tsx index 0bf4a36555d16..515782ce23f45 100644 --- a/src/plugins/discover/public/application/apps/main/components/doc_table/components/table_row.tsx +++ b/src/plugins/discover/public/application/apps/main/components/doc_table/components/table_row.tsx @@ -88,7 +88,7 @@ export const TableRow = ({ return ( // formatFieldValue always returns sanitized HTML // eslint-disable-next-line react/no-danger -
+
); }; const inlineFilter = useCallback( diff --git a/src/plugins/discover/public/application/apps/main/components/doc_table/lib/row_formatter.tsx b/src/plugins/discover/public/application/apps/main/components/doc_table/lib/row_formatter.tsx index a73bc3f175be1..d5660a091f0aa 100644 --- a/src/plugins/discover/public/application/apps/main/components/doc_table/lib/row_formatter.tsx +++ b/src/plugins/discover/public/application/apps/main/components/doc_table/lib/row_formatter.tsx @@ -20,7 +20,7 @@ interface Props { } const TemplateComponent = ({ defPairs }: Props) => { return ( -
+
{defPairs.map((pair, idx) => (
{pair[0]}:
diff --git a/src/plugins/discover/public/application/components/table/table.test.tsx b/src/plugins/discover/public/application/components/table/table.test.tsx index e61333cce1166..176a1961378aa 100644 --- a/src/plugins/discover/public/application/components/table/table.test.tsx +++ b/src/plugins/discover/public/application/components/table/table.test.tsx @@ -236,7 +236,7 @@ describe('DocViewTable at Discover Context', () => { const btn = findTestSubject(component, `collapseBtn`); const html = component.html(); - expect(component.html()).toContain('truncate-by-height'); + expect(component.html()).toContain('dscTruncateByHeight'); expect(btn.length).toBe(1); btn.simulate('click'); diff --git a/src/plugins/discover/public/application/components/table/table_cell_value.tsx b/src/plugins/discover/public/application/components/table/table_cell_value.tsx index e006de1cd7aeb..ebb4ea243fb25 100644 --- a/src/plugins/discover/public/application/components/table/table_cell_value.tsx +++ b/src/plugins/discover/public/application/components/table/table_cell_value.tsx @@ -104,7 +104,7 @@ export const TableFieldValue = ({ const valueClassName = classNames({ // eslint-disable-next-line @typescript-eslint/naming-convention kbnDocViewer__value: true, - 'truncate-by-height': isCollapsible && isCollapsed, + dscTruncateByHeight: isCollapsible && isCollapsed, }); const onToggleCollapse = () => setFieldOpen((fieldOpenPrev) => !fieldOpenPrev); diff --git a/src/plugins/discover/public/application/discover_router.tsx b/src/plugins/discover/public/application/discover_router.tsx index 320ce3e5f644a..b3fe36358bbd4 100644 --- a/src/plugins/discover/public/application/discover_router.tsx +++ b/src/plugins/discover/public/application/discover_router.tsx @@ -22,6 +22,7 @@ export const discoverRouter = (services: DiscoverServices, history: History) => services, history, }; + return ( diff --git a/src/plugins/discover/public/application/helpers/truncate_styles.ts b/src/plugins/discover/public/application/helpers/truncate_styles.ts new file mode 100644 index 0000000000000..dbe8b770e1793 --- /dev/null +++ b/src/plugins/discover/public/application/helpers/truncate_styles.ts @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import createCache from '@emotion/cache'; +import { cache } from '@emotion/css'; +import { serializeStyles } from '@emotion/serialize'; + +/** + * The following emotion cache management was introduced here + * https://ntsim.uk/posts/how-to-update-or-remove-global-styles-in-emotion/ + */ +const TRUNCATE_GRADIENT_HEIGHT = 15; +const globalThemeCache = createCache({ key: 'truncation' }); + +const buildStylesheet = (maxHeight: number) => { + return [ + ` + .dscTruncateByHeight { + overflow: hidden; + max-height: ${maxHeight}px !important; + display: inline-block; + } + .dscTruncateByHeight:before { + top: ${maxHeight - TRUNCATE_GRADIENT_HEIGHT}px; + } + `, + ]; +}; + +const flushThemedGlobals = () => { + globalThemeCache.sheet.flush(); + globalThemeCache.inserted = {}; + globalThemeCache.registered = {}; +}; + +export const injectTruncateStyles = (maxHeight: number) => { + if (maxHeight <= 0) { + flushThemedGlobals(); + return; + } + + const serialized = serializeStyles(buildStylesheet(maxHeight), cache.registered); + if (!globalThemeCache.inserted[serialized.name]) { + globalThemeCache.insert('', serialized, globalThemeCache.sheet, true); + } +}; diff --git a/src/plugins/discover/public/index.ts b/src/plugins/discover/public/index.ts index 21f1c31e774ee..cb7b29afe3f9a 100644 --- a/src/plugins/discover/public/index.ts +++ b/src/plugins/discover/public/index.ts @@ -9,22 +9,24 @@ import { PluginInitializerContext } from 'kibana/public'; import { DiscoverPlugin } from './plugin'; +export type { SavedSearch } from './saved_searches'; export { getSavedSearch, getSavedSearchFullPathUrl, getSavedSearchUrl, getSavedSearchUrlConflictMessage, throwErrorOnSavedSearchUrlConflict, - SavedSearch, } from './saved_searches'; -export { DiscoverSetup, DiscoverStart } from './plugin'; +export type { DiscoverSetup, DiscoverStart } from './plugin'; export function plugin(initializerContext: PluginInitializerContext) { return new DiscoverPlugin(initializerContext); } -export { ISearchEmbeddable, SEARCH_EMBEDDABLE_TYPE, SearchInput } from './application/embeddable'; +export type { ISearchEmbeddable, SearchInput } from './application/embeddable'; +export { SEARCH_EMBEDDABLE_TYPE } from './application/embeddable'; export { loadSharingDataHelpers } from './shared'; -export { DISCOVER_APP_URL_GENERATOR, DiscoverUrlGeneratorState } from './url_generator'; -export { DiscoverAppLocator, DiscoverAppLocatorParams } from './locator'; +export type { DiscoverUrlGeneratorState } from './url_generator'; +export { DISCOVER_APP_URL_GENERATOR } from './url_generator'; +export type { DiscoverAppLocator, DiscoverAppLocatorParams } from './locator'; diff --git a/src/plugins/discover/public/plugin.tsx b/src/plugins/discover/public/plugin.tsx index c91bcf3897e14..62a5a7972a278 100644 --- a/src/plugins/discover/public/plugin.tsx +++ b/src/plugins/discover/public/plugin.tsx @@ -62,6 +62,8 @@ import { DeferredSpinner } from './shared'; import { ViewSavedSearchAction } from './application/embeddable/view_saved_search_action'; import type { SpacesPluginStart } from '../../../../x-pack/plugins/spaces/public'; import { FieldFormatsStart } from '../../field_formats/public'; +import { injectTruncateStyles } from './application/helpers/truncate_styles'; +import { TRUNCATE_MAX_HEIGHT } from '../common'; declare module '../../share/public' { export interface UrlGeneratorStateMapping { @@ -413,6 +415,8 @@ export class DiscoverPlugin const services = buildServices(core, plugins, this.initializerContext); setServices(services); + injectTruncateStyles(services.uiSettings.get(TRUNCATE_MAX_HEIGHT)); + return { urlGenerator: this.urlGenerator, locator: this.locator, diff --git a/src/plugins/discover/public/saved_searches/index.ts b/src/plugins/discover/public/saved_searches/index.ts index da9dd047fb5ac..c41c92df30084 100644 --- a/src/plugins/discover/public/saved_searches/index.ts +++ b/src/plugins/discover/public/saved_searches/index.ts @@ -15,6 +15,7 @@ export { } from './saved_searches_utils'; export { useSavedSearchAliasMatchRedirect } from './saved_search_alias_match_redirect'; export { SavedSearchURLConflictCallout } from './saved_search_url_conflict_callout'; -export { saveSavedSearch, SaveSavedSearchOptions } from './save_saved_searches'; +export type { SaveSavedSearchOptions } from './save_saved_searches'; +export { saveSavedSearch } from './save_saved_searches'; export { SAVED_SEARCH_TYPE } from './constants'; export type { SavedSearch, SortOrder } from './types'; diff --git a/src/plugins/discover/server/ui_settings.ts b/src/plugins/discover/server/ui_settings.ts index 529ba0d1beef1..df06260d45d21 100644 --- a/src/plugins/discover/server/ui_settings.ts +++ b/src/plugins/discover/server/ui_settings.ts @@ -26,6 +26,7 @@ import { SEARCH_FIELDS_FROM_SOURCE, MAX_DOC_FIELDS_DISPLAYED, SHOW_MULTIFIELDS, + TRUNCATE_MAX_HEIGHT, SHOW_FIELD_STATISTICS, } from '../common'; @@ -241,4 +242,16 @@ export const getUiSettings: () => Record = () => ({ category: ['discover'], schema: schema.boolean(), }, + [TRUNCATE_MAX_HEIGHT]: { + name: i18n.translate('discover.advancedSettings.params.maxCellHeightTitle', { + defaultMessage: 'Maximum table cell height', + }), + value: 115, + category: ['discover'], + description: i18n.translate('discover.advancedSettings.params.maxCellHeightText', { + defaultMessage: + 'The maximum height that a cell in a table should occupy. Set to 0 to disable truncation', + }), + schema: schema.number({ min: 0 }), + }, }); diff --git a/src/plugins/embeddable/public/index.ts b/src/plugins/embeddable/public/index.ts index 80171e1ad2fab..6a6b5b2df2ddd 100644 --- a/src/plugins/embeddable/public/index.ts +++ b/src/plugins/embeddable/public/index.ts @@ -11,76 +11,78 @@ import './index.scss'; import { PluginInitializerContext } from 'src/core/public'; import { EmbeddablePublicPlugin } from './plugin'; -export { - ACTION_ADD_PANEL, - ACTION_EDIT_PANEL, +export type { Adapters, - AddPanelAction, ReferenceOrValueEmbeddable, - isReferenceOrValueEmbeddable, ChartActionContext, - Container, ContainerInput, ContainerOutput, - CONTEXT_MENU_TRIGGER, - contextMenuTrigger, - defaultEmbeddableFactoryProvider, - EditPanelAction, - Embeddable, - EmbeddableChildPanel, EmbeddableChildPanelProps, EmbeddableContext, EmbeddableFactory, EmbeddableFactoryDefinition, - EmbeddableFactoryNotFoundError, EmbeddableInput, EmbeddableInstanceConfiguration, EmbeddableOutput, - EmbeddablePanel, - EmbeddableRoot, ValueClickContext, RangeSelectContext, - ErrorEmbeddable, IContainer, IEmbeddable, + OutputSpec, + PanelState, + PropertySpec, + SavedObjectEmbeddableInput, + EmbeddableEditorState, + EmbeddablePackageState, + EmbeddableRendererProps, +} from './lib'; +export { + ACTION_ADD_PANEL, + ACTION_EDIT_PANEL, + AddPanelAction, + isReferenceOrValueEmbeddable, + Container, + CONTEXT_MENU_TRIGGER, + contextMenuTrigger, + defaultEmbeddableFactoryProvider, + EditPanelAction, + Embeddable, + EmbeddableChildPanel, + EmbeddableFactoryNotFoundError, + EmbeddablePanel, + EmbeddableRoot, + ErrorEmbeddable, isEmbeddable, isErrorEmbeddable, openAddPanelFlyout, - OutputSpec, PANEL_BADGE_TRIGGER, panelBadgeTrigger, PANEL_NOTIFICATION_TRIGGER, panelNotificationTrigger, PanelNotFoundError, - PanelState, - PropertySpec, SELECT_RANGE_TRIGGER, VALUE_CLICK_TRIGGER, ViewMode, withEmbeddableSubscription, - SavedObjectEmbeddableInput, isSavedObjectEmbeddableInput, isRangeSelectTriggerContext, isValueClickTriggerContext, isRowClickTriggerContext, isContextMenuTriggerContext, EmbeddableStateTransfer, - EmbeddableEditorState, - EmbeddablePackageState, EmbeddableRenderer, - EmbeddableRendererProps, useEmbeddableFactory, } from './lib'; export { AttributeService, ATTRIBUTE_SERVICE_KEY } from './lib/attribute_service'; -export { EnhancementRegistryDefinition } from './types'; +export type { EnhancementRegistryDefinition } from './types'; export function plugin(initializerContext: PluginInitializerContext) { return new EmbeddablePublicPlugin(initializerContext); } -export { +export type { EmbeddableSetup, EmbeddableStart, EmbeddableSetupDependencies, diff --git a/src/plugins/embeddable/public/lib/containers/i_container.ts b/src/plugins/embeddable/public/lib/containers/i_container.ts index f68a3ada33c07..c4593cac4969a 100644 --- a/src/plugins/embeddable/public/lib/containers/i_container.ts +++ b/src/plugins/embeddable/public/lib/containers/i_container.ts @@ -15,7 +15,7 @@ import { } from '../embeddables'; import { PanelState } from '../../../common/types'; -export { PanelState }; +export type { PanelState }; export interface ContainerOutput extends EmbeddableOutput { embeddableLoaded: { [key: string]: boolean }; diff --git a/src/plugins/embeddable/public/lib/containers/index.ts b/src/plugins/embeddable/public/lib/containers/index.ts index cc2c0bfa58223..041923188e175 100644 --- a/src/plugins/embeddable/public/lib/containers/index.ts +++ b/src/plugins/embeddable/public/lib/containers/index.ts @@ -6,6 +6,6 @@ * Side Public License, v 1. */ -export { IContainer, PanelState, ContainerInput, ContainerOutput } from './i_container'; +export type { IContainer, PanelState, ContainerInput, ContainerOutput } from './i_container'; export { Container } from './container'; export * from './embeddable_child_panel'; diff --git a/src/plugins/embeddable/public/lib/embeddables/i_embeddable.ts b/src/plugins/embeddable/public/lib/embeddables/i_embeddable.ts index bbac617d41590..b53f036024259 100644 --- a/src/plugins/embeddable/public/lib/embeddables/i_embeddable.ts +++ b/src/plugins/embeddable/public/lib/embeddables/i_embeddable.ts @@ -16,7 +16,7 @@ export interface EmbeddableError { message: string; } -export { EmbeddableInput }; +export type { EmbeddableInput }; export interface EmbeddableOutput { // Whether the embeddable is actively loading. diff --git a/src/plugins/embeddable/public/lib/embeddables/index.ts b/src/plugins/embeddable/public/lib/embeddables/index.ts index eede745f31794..1745c64c73bf5 100644 --- a/src/plugins/embeddable/public/lib/embeddables/index.ts +++ b/src/plugins/embeddable/public/lib/embeddables/index.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -export { EmbeddableOutput, EmbeddableInput, IEmbeddable } from './i_embeddable'; +export type { EmbeddableOutput, EmbeddableInput, IEmbeddable } from './i_embeddable'; export { isEmbeddable } from './is_embeddable'; export { Embeddable } from './embeddable'; export * from './embeddable_factory'; @@ -16,8 +16,5 @@ export { ErrorEmbeddable, isErrorEmbeddable } from './error_embeddable'; export { withEmbeddableSubscription } from './with_subscription'; export { EmbeddableRoot } from './embeddable_root'; export * from '../../../common/lib/saved_object_embeddable'; -export { - EmbeddableRenderer, - EmbeddableRendererProps, - useEmbeddableFactory, -} from './embeddable_renderer'; +export type { EmbeddableRendererProps } from './embeddable_renderer'; +export { EmbeddableRenderer, useEmbeddableFactory } from './embeddable_renderer'; diff --git a/src/plugins/embeddable/public/lib/reference_or_value_embeddable/index.ts b/src/plugins/embeddable/public/lib/reference_or_value_embeddable/index.ts index a448eb1319ab4..41554e8efce1d 100644 --- a/src/plugins/embeddable/public/lib/reference_or_value_embeddable/index.ts +++ b/src/plugins/embeddable/public/lib/reference_or_value_embeddable/index.ts @@ -6,4 +6,5 @@ * Side Public License, v 1. */ -export { ReferenceOrValueEmbeddable, isReferenceOrValueEmbeddable } from './types'; +export type { ReferenceOrValueEmbeddable } from './types'; +export { isReferenceOrValueEmbeddable } from './types'; diff --git a/src/plugins/embeddable/public/lib/state_transfer/index.ts b/src/plugins/embeddable/public/lib/state_transfer/index.ts index 6643f048d6425..009b2994f9caa 100644 --- a/src/plugins/embeddable/public/lib/state_transfer/index.ts +++ b/src/plugins/embeddable/public/lib/state_transfer/index.ts @@ -7,4 +7,4 @@ */ export { EmbeddableStateTransfer } from './embeddable_state_transfer'; -export { EmbeddableEditorState, EmbeddablePackageState } from './types'; +export type { EmbeddableEditorState, EmbeddablePackageState } from './types'; diff --git a/src/plugins/embeddable/public/lib/types.ts b/src/plugins/embeddable/public/lib/types.ts index 2def03c742e7b..d22bcbd12bef9 100644 --- a/src/plugins/embeddable/public/lib/types.ts +++ b/src/plugins/embeddable/public/lib/types.ts @@ -22,4 +22,4 @@ export interface PropertySpec { value?: string; } export { ViewMode } from '../../common/types'; -export { Adapters }; +export type { Adapters }; diff --git a/src/plugins/embeddable/server/index.ts b/src/plugins/embeddable/server/index.ts index aac081f9467b6..8d88f35a4be22 100644 --- a/src/plugins/embeddable/server/index.ts +++ b/src/plugins/embeddable/server/index.ts @@ -8,8 +8,8 @@ import { EmbeddableServerPlugin, EmbeddableSetup, EmbeddableStart } from './plugin'; -export { EmbeddableSetup, EmbeddableStart }; +export type { EmbeddableSetup, EmbeddableStart }; -export { EnhancementRegistryDefinition, EmbeddableRegistryDefinition } from './types'; +export type { EnhancementRegistryDefinition, EmbeddableRegistryDefinition } from './types'; export const plugin = () => new EmbeddableServerPlugin(); diff --git a/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/index.ts b/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/index.ts index 75d79a204f141..a43e7c1b31e45 100644 --- a/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/index.ts +++ b/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/index.ts @@ -6,11 +6,11 @@ * Side Public License, v 1. */ +export type { Authorization } from './authorization_provider'; export { AuthorizationProvider, AuthorizationContext, useAuthorizationContext, - Authorization, } from './authorization_provider'; export { WithPrivileges } from './with_privileges'; diff --git a/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/index.ts b/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/index.ts index 9ccbc5a5cd3df..57d5cd88d3e4a 100644 --- a/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/index.ts +++ b/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/index.ts @@ -6,6 +6,7 @@ * Side Public License, v 1. */ +export type { Authorization } from './components'; export { WithPrivileges, NotAuthorizedSection, @@ -14,7 +15,6 @@ export { SectionError, PageError, useAuthorizationContext, - Authorization, } from './components'; -export { Privileges, MissingPrivileges, Error } from './types'; +export type { Privileges, MissingPrivileges, Error } from './types'; diff --git a/src/plugins/es_ui_shared/common/index.ts b/src/plugins/es_ui_shared/common/index.ts index 1c2955b8e5e28..4f0185ba110d9 100644 --- a/src/plugins/es_ui_shared/common/index.ts +++ b/src/plugins/es_ui_shared/common/index.ts @@ -6,4 +6,7 @@ * Side Public License, v 1. */ -export { Privileges, MissingPrivileges } from '../__packages_do_not_import__/authorization/types'; +export type { + Privileges, + MissingPrivileges, +} from '../__packages_do_not_import__/authorization/types'; diff --git a/src/plugins/es_ui_shared/public/authorization/index.ts b/src/plugins/es_ui_shared/public/authorization/index.ts index b8fb2f45794ee..8175d6b80d298 100644 --- a/src/plugins/es_ui_shared/public/authorization/index.ts +++ b/src/plugins/es_ui_shared/public/authorization/index.ts @@ -6,16 +6,18 @@ * Side Public License, v 1. */ +export type { + Error, + MissingPrivileges, + Privileges, + Authorization, +} from '../../__packages_do_not_import__/authorization'; export { AuthorizationContext, AuthorizationProvider, - Error, - MissingPrivileges, NotAuthorizedSection, - Privileges, SectionError, PageError, useAuthorizationContext, WithPrivileges, - Authorization, } from '../../__packages_do_not_import__/authorization'; diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/index.ts b/src/plugins/es_ui_shared/public/components/cron_editor/index.ts index 88176c429fcf3..bee0bc412fb55 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/index.ts +++ b/src/plugins/es_ui_shared/public/components/cron_editor/index.ts @@ -6,5 +6,5 @@ * Side Public License, v 1. */ -export { Frequency } from './types'; +export type { Frequency } from './types'; export { CronEditor } from './cron_editor'; diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/services/index.ts b/src/plugins/es_ui_shared/public/components/cron_editor/services/index.ts index 85d650994b33c..8988c640cd09e 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/services/index.ts +++ b/src/plugins/es_ui_shared/public/components/cron_editor/services/index.ts @@ -7,10 +7,5 @@ */ export { cronExpressionToParts, cronPartsToExpression } from './cron'; -export { - getOrdinalValue, - getDayName, - getMonthName, - DayOrdinal, - MonthOrdinal, -} from './humanized_numbers'; +export type { DayOrdinal, MonthOrdinal } from './humanized_numbers'; +export { getOrdinalValue, getDayName, getMonthName } from './humanized_numbers'; diff --git a/src/plugins/es_ui_shared/public/components/json_editor/index.ts b/src/plugins/es_ui_shared/public/components/json_editor/index.ts index bf7697523d3fe..f31f586f1033e 100644 --- a/src/plugins/es_ui_shared/public/components/json_editor/index.ts +++ b/src/plugins/es_ui_shared/public/components/json_editor/index.ts @@ -8,4 +8,4 @@ export * from './json_editor'; -export { OnJsonEditorUpdateHandler, JsonEditorState } from './use_json'; +export type { OnJsonEditorUpdateHandler, JsonEditorState } from './use_json'; diff --git a/src/plugins/es_ui_shared/public/forms/form_wizard/index.ts b/src/plugins/es_ui_shared/public/forms/form_wizard/index.ts index 6c4912f7e4b33..0f868712553c7 100644 --- a/src/plugins/es_ui_shared/public/forms/form_wizard/index.ts +++ b/src/plugins/es_ui_shared/public/forms/form_wizard/index.ts @@ -10,12 +10,12 @@ export { FormWizard } from './form_wizard'; export { FormWizardStep } from './form_wizard_step'; +export type { Step, Steps } from './form_wizard_context'; export { FormWizardProvider, FormWizardConsumer, useFormWizardContext, - Step, - Steps, } from './form_wizard_context'; -export { FormWizardNav, NavTexts } from './form_wizard_nav'; +export type { NavTexts } from './form_wizard_nav'; +export { FormWizardNav } from './form_wizard_nav'; diff --git a/src/plugins/es_ui_shared/public/forms/multi_content/index.ts b/src/plugins/es_ui_shared/public/forms/multi_content/index.ts index 76ff8a9ff3066..bae46ad0abfd8 100644 --- a/src/plugins/es_ui_shared/public/forms/multi_content/index.ts +++ b/src/plugins/es_ui_shared/public/forms/multi_content/index.ts @@ -13,6 +13,7 @@ export { useContent, } from './multi_content_context'; -export { useMultiContent, HookProps, Content, MultiContent } from './use_multi_content'; +export type { HookProps, Content, MultiContent } from './use_multi_content'; +export { useMultiContent } from './use_multi_content'; export { WithMultiContent } from './with_multi_content'; diff --git a/src/plugins/es_ui_shared/public/index.ts b/src/plugins/es_ui_shared/public/index.ts index 2dc50536ca631..c21587c9a6040 100644 --- a/src/plugins/es_ui_shared/public/index.ts +++ b/src/plugins/es_ui_shared/public/index.ts @@ -15,37 +15,36 @@ import * as ace from './ace'; import * as GlobalFlyout from './global_flyout'; import * as XJson from './xjson'; -export { JsonEditor, OnJsonEditorUpdateHandler, JsonEditorState } from './components/json_editor'; +export type { OnJsonEditorUpdateHandler, JsonEditorState } from './components/json_editor'; +export { JsonEditor } from './components/json_editor'; export { PageLoading } from './components/page_loading'; export { SectionLoading } from './components/section_loading'; -export { EuiCodeEditor, EuiCodeEditorProps } from './components/code_editor'; -export { Frequency, CronEditor } from './components/cron_editor'; +export type { EuiCodeEditorProps } from './components/code_editor'; +export { EuiCodeEditor } from './components/code_editor'; +export type { Frequency } from './components/cron_editor'; +export { CronEditor } from './components/cron_editor'; -export { +export type { SendRequestConfig, SendRequestResponse, UseRequestConfig, UseRequestResponse, - sendRequest, - useRequest, } from './request'; +export { sendRequest, useRequest } from './request'; export { indices } from './indices'; +export type { Privileges, MissingPrivileges, Error, Authorization } from './authorization'; export { AuthorizationContext, AuthorizationProvider, NotAuthorizedSection, WithPrivileges, - Privileges, - MissingPrivileges, SectionError, PageError, - Error, useAuthorizationContext, - Authorization, } from './authorization'; export { Forms, ace, GlobalFlyout, XJson }; diff --git a/src/plugins/es_ui_shared/public/request/index.ts b/src/plugins/es_ui_shared/public/request/index.ts index da407d0013037..5cfcc77f8e117 100644 --- a/src/plugins/es_ui_shared/public/request/index.ts +++ b/src/plugins/es_ui_shared/public/request/index.ts @@ -6,5 +6,7 @@ * Side Public License, v 1. */ -export { SendRequestConfig, SendRequestResponse, sendRequest } from './send_request'; -export { UseRequestConfig, UseRequestResponse, useRequest } from './use_request'; +export type { SendRequestConfig, SendRequestResponse } from './send_request'; +export { sendRequest } from './send_request'; +export type { UseRequestConfig, UseRequestResponse } from './use_request'; +export { useRequest } from './use_request'; diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/index.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/index.ts index 8438e5de871bd..6f2dc768508ec 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/index.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/index.ts @@ -6,7 +6,8 @@ * Side Public License, v 1. */ -export { useField, InternalFieldConfig } from './use_field'; +export type { InternalFieldConfig } from './use_field'; +export { useField } from './use_field'; export { useForm } from './use_form'; export { useFormData } from './use_form_data'; export { useFormIsModified } from './use_form_is_modified'; diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/index.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/index.ts index 79d1067cd36b2..0bbaedcf2e90e 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/index.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/index.ts @@ -6,5 +6,6 @@ * Side Public License, v 1. */ -export { Subject, Subscription } from './subject'; +export type { Subscription } from './subject'; +export { Subject } from './subject'; export * from './utils'; diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/shared_imports.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/shared_imports.ts index c57333d788ef5..cd9bb97cab8d9 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/shared_imports.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/shared_imports.ts @@ -7,7 +7,9 @@ */ // eslint-disable-next-line import/no-extraneous-dependencies -export { registerTestBed, TestBed } from '@kbn/test/jest'; +export type { TestBed } from '@kbn/test/jest'; +// eslint-disable-next-line import/no-extraneous-dependencies +export { registerTestBed } from '@kbn/test/jest'; // eslint-disable-next-line import/no-extraneous-dependencies export { getRandomString } from '@kbn/test/jest'; diff --git a/src/plugins/expressions/common/expression_functions/specs/index.ts b/src/plugins/expressions/common/expression_functions/specs/index.ts index de9a1dedd8248..0e473e4a79e5a 100644 --- a/src/plugins/expressions/common/expression_functions/specs/index.ts +++ b/src/plugins/expressions/common/expression_functions/specs/index.ts @@ -17,6 +17,9 @@ export * from './overall_metric'; export * from './derivative'; export * from './moving_average'; export * from './ui_setting'; -export { mapColumn, MapColumnArguments } from './map_column'; -export { math, MathArguments, MathInput } from './math'; -export { mathColumn, MathColumnArguments } from './math_column'; +export type { MapColumnArguments } from './map_column'; +export { mapColumn } from './map_column'; +export type { MathArguments, MathInput } from './math'; +export { math } from './math'; +export type { MathColumnArguments } from './math_column'; +export { mathColumn } from './math_column'; diff --git a/src/plugins/expressions/common/types/index.ts b/src/plugins/expressions/common/types/index.ts index 00a79289c0b5f..a7fc51d88c236 100644 --- a/src/plugins/expressions/common/types/index.ts +++ b/src/plugins/expressions/common/types/index.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -export { TypeToString, KnownTypeToString, TypeString, UnmappedTypeStrings } from './common'; +export type { TypeToString, KnownTypeToString, TypeString, UnmappedTypeStrings } from './common'; export * from './style'; export * from './registry'; diff --git a/src/plugins/expressions/server/index.ts b/src/plugins/expressions/server/index.ts index 7c0662ad54e4b..db94ed6dbd440 100644 --- a/src/plugins/expressions/server/index.ts +++ b/src/plugins/expressions/server/index.ts @@ -12,7 +12,7 @@ import { PluginInitializerContext } from 'src/core/server'; import { ExpressionsServerPlugin } from './plugin'; -export { ExpressionsServerSetup, ExpressionsServerStart } from './plugin'; +export type { ExpressionsServerSetup, ExpressionsServerStart } from './plugin'; // Kibana Platform. export { ExpressionsServerPlugin as Plugin }; @@ -22,22 +22,18 @@ export function plugin(initializerContext: PluginInitializerContext) { } // Static exports. -export { +export type { AnyExpressionFunctionDefinition, AnyExpressionTypeDefinition, ArgumentType, - buildExpression, - buildExpressionFunction, Datatable, DatatableColumn, DatatableColumnType, DatatableRow, - Execution, ExecutionContainer, ExecutionContext, ExecutionParams, ExecutionState, - Executor, ExecutorContainer, ExecutorState, ExpressionAstArgument, @@ -46,15 +42,10 @@ export { ExpressionAstFunction, ExpressionAstFunctionBuilder, ExpressionAstNode, - ExpressionFunction, ExpressionFunctionDefinition, ExpressionFunctionDefinitions, - ExpressionFunctionParameter, ExpressionImage, ExpressionRenderDefinition, - ExpressionRenderer, - ExpressionRendererRegistry, - ExpressionType, ExpressionTypeDefinition, ExpressionTypeStyle, ExpressionValue, @@ -67,20 +58,11 @@ export { ExpressionValueFilter, Font, FontLabel, - FontStyle, FontValue, - FontWeight, - format, - formatExpression, - FunctionsRegistry, IInterpreterRenderHandlers, InterpreterErrorType, IRegistry, - isExpressionAstBuilder, KnownTypeToString, - Overflow, - parse, - parseExpression, PointSeries, PointSeriesColumn, PointSeriesColumnName, @@ -89,11 +71,31 @@ export { Range, SerializedDatatable, Style, - TextAlignment, - TextDecoration, - TypesRegistry, TypeString, TypeToString, UnmappedTypeStrings, ExpressionValueRender as Render, } from '../common'; +export { + buildExpression, + buildExpressionFunction, + Execution, + Executor, + ExpressionFunction, + ExpressionFunctionParameter, + ExpressionRenderer, + ExpressionRendererRegistry, + ExpressionType, + FontStyle, + FontWeight, + format, + formatExpression, + FunctionsRegistry, + isExpressionAstBuilder, + Overflow, + parse, + parseExpression, + TextAlignment, + TextDecoration, + TypesRegistry, +} from '../common'; diff --git a/src/plugins/field_formats/common/index.ts b/src/plugins/field_formats/common/index.ts index aeb5e0af220db..092fc49af3d28 100644 --- a/src/plugins/field_formats/common/index.ts +++ b/src/plugins/field_formats/common/index.ts @@ -12,7 +12,8 @@ import { FieldFormatsRegistry } from './field_formats_registry'; /** @public */ type IFieldFormatsRegistry = PublicMethodsOf; -export { FieldFormatsRegistry, IFieldFormatsRegistry }; +export type { IFieldFormatsRegistry }; +export { FieldFormatsRegistry }; export { FieldFormat } from './field_format'; export { baseFormatters } from './constants/base_formatters'; export { @@ -24,7 +25,6 @@ export { NumberFormat, PercentFormat, RelativeDateFormat, - SourceFormat, StaticLookupFormat, UrlFormat, StringFormat, @@ -39,7 +39,7 @@ export { FORMATS_UI_SETTINGS } from './constants/ui_settings'; export { FIELD_FORMAT_IDS } from './types'; export { HTML_CONTEXT_TYPE, TEXT_CONTEXT_TYPE } from './content_types'; -export { +export type { FieldFormatsGetConfigFn, FieldFormatsContentType, FieldFormatConfig, diff --git a/src/plugins/field_formats/public/index.ts b/src/plugins/field_formats/public/index.ts index f765513fb4c4c..f4f7019fe772d 100755 --- a/src/plugins/field_formats/public/index.ts +++ b/src/plugins/field_formats/public/index.ts @@ -12,4 +12,4 @@ export { DateFormat, DateNanosFormat } from './lib/converters'; export function plugin() { return new FieldFormatsPlugin(); } -export { FieldFormatsSetup, FieldFormatsStart } from './plugin'; +export type { FieldFormatsSetup, FieldFormatsStart } from './plugin'; diff --git a/src/plugins/field_formats/server/index.ts b/src/plugins/field_formats/server/index.ts index 44de8fde558ec..d3cac3bfb00c2 100755 --- a/src/plugins/field_formats/server/index.ts +++ b/src/plugins/field_formats/server/index.ts @@ -14,4 +14,4 @@ export function plugin(initializerContext: PluginInitializerContext) { return new FieldFormatsPlugin(initializerContext); } -export { FieldFormatsSetup, FieldFormatsStart } from './types'; +export type { FieldFormatsSetup, FieldFormatsStart } from './types'; diff --git a/src/plugins/index_pattern_editor/public/components/index.ts b/src/plugins/index_pattern_editor/public/components/index.ts index c32c4081e973f..b78ac6946ad94 100644 --- a/src/plugins/index_pattern_editor/public/components/index.ts +++ b/src/plugins/index_pattern_editor/public/components/index.ts @@ -6,10 +6,8 @@ * Side Public License, v 1. */ -export { - IndexPatternEditorFlyoutContent, - Props as IndexPatternEditorFlyoutContentProps, -} from './index_pattern_editor_flyout_content'; +export type { Props as IndexPatternEditorFlyoutContentProps } from './index_pattern_editor_flyout_content'; +export { IndexPatternEditorFlyoutContent } from './index_pattern_editor_flyout_content'; export { IndexPatternEditor } from './index_pattern_editor'; diff --git a/src/plugins/index_pattern_editor/public/shared_imports.ts b/src/plugins/index_pattern_editor/public/shared_imports.ts index c99d32e0c8a28..7edb7dfd0f599 100644 --- a/src/plugins/index_pattern_editor/public/shared_imports.ts +++ b/src/plugins/index_pattern_editor/public/shared_imports.ts @@ -6,14 +6,13 @@ * Side Public License, v 1. */ -export { - IndexPattern, - IndexPatternField, +export type { DataPublicPluginStart, IndexPatternSpec, GetFieldsOptions, IndexPatternAggRestrictions, } from '../../data/public'; +export { IndexPattern, IndexPatternField } from '../../data/public'; export { createKibanaReactContext, @@ -22,18 +21,20 @@ export { useKibana, } from '../../kibana_react/public'; +export type { + FormSchema, + FormHook, + ValidationFunc, + FieldConfig, + ValidationConfig, +} from '../../es_ui_shared/static/forms/hook_form_lib'; export { useForm, useFormData, useFormContext, Form, - FormSchema, UseField, - FormHook, - ValidationFunc, - FieldConfig, getFieldValidityAndErrorMessage, - ValidationConfig, } from '../../es_ui_shared/static/forms/hook_form_lib'; export { fieldValidators } from '../../es_ui_shared/static/forms/helpers'; @@ -47,4 +48,4 @@ export { SuperSelectField, } from '../../es_ui_shared/static/forms/components'; -export { HttpStart } from '../../../core/public'; +export type { HttpStart } from '../../../core/public'; diff --git a/src/plugins/index_pattern_editor/public/test_utils/test_utils.ts b/src/plugins/index_pattern_editor/public/test_utils/test_utils.ts index c8e4aedc26471..311d93d31b593 100644 --- a/src/plugins/index_pattern_editor/public/test_utils/test_utils.ts +++ b/src/plugins/index_pattern_editor/public/test_utils/test_utils.ts @@ -8,4 +8,5 @@ export { getRandomString } from '@kbn/test/jest'; -export { registerTestBed, TestBed } from '@kbn/test/jest'; +export type { TestBed } from '@kbn/test/jest'; +export { registerTestBed } from '@kbn/test/jest'; diff --git a/src/plugins/index_pattern_field_editor/__jest__/client_integration/helpers/index.ts b/src/plugins/index_pattern_field_editor/__jest__/client_integration/helpers/index.ts index 6a1f1aa74036a..e8ff7eb7538f2 100644 --- a/src/plugins/index_pattern_field_editor/__jest__/client_integration/helpers/index.ts +++ b/src/plugins/index_pattern_field_editor/__jest__/client_integration/helpers/index.ts @@ -6,7 +6,8 @@ * Side Public License, v 1. */ -export { findTestSubject, TestBed } from '@kbn/test/jest'; +export type { TestBed } from '@kbn/test/jest'; +export { findTestSubject } from '@kbn/test/jest'; export { setupEnvironment, diff --git a/src/plugins/index_pattern_field_editor/kibana.json b/src/plugins/index_pattern_field_editor/kibana.json index 898e7c564e57f..df09fd56136c3 100644 --- a/src/plugins/index_pattern_field_editor/kibana.json +++ b/src/plugins/index_pattern_field_editor/kibana.json @@ -5,7 +5,7 @@ "ui": true, "requiredPlugins": ["data"], "optionalPlugins": ["usageCollection"], - "requiredBundles": ["kibanaReact", "esUiShared", "usageCollection", "fieldFormats"], + "requiredBundles": ["kibanaReact", "esUiShared", "fieldFormats"], "owner": { "name": "App Services", "githubTeam": "kibana-app-services" diff --git a/src/plugins/index_pattern_field_editor/public/components/field_editor/form_fields/index.ts b/src/plugins/index_pattern_field_editor/public/components/field_editor/form_fields/index.ts index e958e1362bb05..693709729ed92 100644 --- a/src/plugins/index_pattern_field_editor/public/components/field_editor/form_fields/index.ts +++ b/src/plugins/index_pattern_field_editor/public/components/field_editor/form_fields/index.ts @@ -12,6 +12,7 @@ export { CustomLabelField } from './custom_label_field'; export { PopularityField } from './popularity_field'; -export { ScriptField, ScriptSyntaxError } from './script_field'; +export type { ScriptSyntaxError } from './script_field'; +export { ScriptField } from './script_field'; export { FormatField } from './format_field'; diff --git a/src/plugins/index_pattern_field_editor/public/components/field_format_editor/editors/default/index.ts b/src/plugins/index_pattern_field_editor/public/components/field_format_editor/editors/default/index.ts index 31d7e95897090..4cadb6e837620 100644 --- a/src/plugins/index_pattern_field_editor/public/components/field_format_editor/editors/default/index.ts +++ b/src/plugins/index_pattern_field_editor/public/components/field_format_editor/editors/default/index.ts @@ -9,7 +9,8 @@ import { FieldFormatEditorFactory } from '../types'; import { formatId } from './constants'; -export { defaultState, FormatEditorState } from './default'; +export type { FormatEditorState } from './default'; +export { defaultState } from './default'; export type { FormatEditorProps } from '../types'; export type { DefaultFormatEditor } from './default'; diff --git a/src/plugins/index_pattern_field_editor/public/components/field_format_editor/index.ts b/src/plugins/index_pattern_field_editor/public/components/field_format_editor/index.ts index 34619f53e9eed..0c23c8de616cf 100644 --- a/src/plugins/index_pattern_field_editor/public/components/field_format_editor/index.ts +++ b/src/plugins/index_pattern_field_editor/public/components/field_format_editor/index.ts @@ -6,5 +6,6 @@ * Side Public License, v 1. */ -export { FormatSelectEditor, FormatSelectEditorProps } from './field_format_editor'; +export type { FormatSelectEditorProps } from './field_format_editor'; +export { FormatSelectEditor } from './field_format_editor'; export * from './editors'; diff --git a/src/plugins/index_pattern_field_editor/public/components/index.ts b/src/plugins/index_pattern_field_editor/public/components/index.ts index 927e28a8e3adf..e6fa42a591f5e 100644 --- a/src/plugins/index_pattern_field_editor/public/components/index.ts +++ b/src/plugins/index_pattern_field_editor/public/components/index.ts @@ -6,6 +6,7 @@ * Side Public License, v 1. */ -export { getDeleteFieldProvider, Props as DeleteFieldProviderProps } from './delete_field_provider'; +export type { Props as DeleteFieldProviderProps } from './delete_field_provider'; +export { getDeleteFieldProvider } from './delete_field_provider'; export * from './field_format_editor'; diff --git a/src/plugins/index_pattern_field_editor/public/index.ts b/src/plugins/index_pattern_field_editor/public/index.ts index 6546dabcb2c44..55af27fdb29eb 100644 --- a/src/plugins/index_pattern_field_editor/public/index.ts +++ b/src/plugins/index_pattern_field_editor/public/index.ts @@ -25,7 +25,7 @@ export type { PluginStart as IndexPatternFieldEditorStart, } from './types'; export { DefaultFormatEditor } from './components/field_format_editor/editors/default/default'; -export { FieldFormatEditorFactory, FieldFormatEditor, FormatEditorProps } from './components'; +export type { FieldFormatEditorFactory, FieldFormatEditor, FormatEditorProps } from './components'; export function plugin() { return new IndexPatternFieldEditorPlugin(); diff --git a/src/plugins/index_pattern_field_editor/public/lib/index.ts b/src/plugins/index_pattern_field_editor/public/lib/index.ts index 336de9574c460..d9aaab77ff66a 100644 --- a/src/plugins/index_pattern_field_editor/public/lib/index.ts +++ b/src/plugins/index_pattern_field_editor/public/lib/index.ts @@ -10,10 +10,8 @@ export { deserializeField } from './serialization'; export { getLinks } from './documentation'; -export { - getRuntimeFieldValidator, - RuntimeFieldPainlessError, - parseEsError, -} from './runtime_field_validation'; +export type { RuntimeFieldPainlessError } from './runtime_field_validation'; +export { getRuntimeFieldValidator, parseEsError } from './runtime_field_validation'; -export { initApi, ApiService } from './api'; +export type { ApiService } from './api'; +export { initApi } from './api'; diff --git a/src/plugins/index_pattern_field_editor/public/shared_imports.ts b/src/plugins/index_pattern_field_editor/public/shared_imports.ts index 2827928d1c060..e2154800908cb 100644 --- a/src/plugins/index_pattern_field_editor/public/shared_imports.ts +++ b/src/plugins/index_pattern_field_editor/public/shared_imports.ts @@ -6,27 +6,31 @@ * Side Public License, v 1. */ -export { IndexPattern, IndexPatternField, DataPublicPluginStart } from '../../data/public'; +export type { DataPublicPluginStart } from '../../data/public'; +export { IndexPattern, IndexPatternField } from '../../data/public'; -export { UsageCollectionStart } from '../../usage_collection/public'; +export type { UsageCollectionStart } from '../../usage_collection/public'; -export { RuntimeType, RuntimeField, KBN_FIELD_TYPES, ES_FIELD_TYPES } from '../../data/common'; +export type { RuntimeType, RuntimeField } from '../../data/common'; +export { KBN_FIELD_TYPES, ES_FIELD_TYPES } from '../../data/common'; export { createKibanaReactContext, toMountPoint, CodeEditor } from '../../kibana_react/public'; export { FieldFormat } from '../../field_formats/common'; +export type { + FormSchema, + FormHook, + ValidationFunc, + FieldConfig, +} from '../../es_ui_shared/static/forms/hook_form_lib'; export { useForm, useFormData, useFormContext, useFormIsModified, Form, - FormSchema, UseField, - FormHook, - ValidationFunc, - FieldConfig, } from '../../es_ui_shared/static/forms/hook_form_lib'; export { fieldValidators } from '../../es_ui_shared/static/forms/helpers'; diff --git a/src/plugins/index_pattern_management/public/index.ts b/src/plugins/index_pattern_management/public/index.ts index 45a2f0b5a468b..65b71ee6053e3 100644 --- a/src/plugins/index_pattern_management/public/index.ts +++ b/src/plugins/index_pattern_management/public/index.ts @@ -19,7 +19,7 @@ */ import { PluginInitializerContext } from 'src/core/public'; import { IndexPatternManagementPlugin } from './plugin'; -export { IndexPatternManagementSetup, IndexPatternManagementStart } from './plugin'; +export type { IndexPatternManagementSetup, IndexPatternManagementStart } from './plugin'; export function plugin(initializerContext: PluginInitializerContext) { return new IndexPatternManagementPlugin(initializerContext); diff --git a/src/plugins/inspector/common/adapters/request/index.ts b/src/plugins/inspector/common/adapters/request/index.ts index 807f11569ba2c..d1654ea66b93d 100644 --- a/src/plugins/inspector/common/adapters/request/index.ts +++ b/src/plugins/inspector/common/adapters/request/index.ts @@ -6,6 +6,7 @@ * Side Public License, v 1. */ -export { Request, RequestStatistic, RequestStatistics, RequestStatus } from './types'; +export type { Request, RequestStatistic, RequestStatistics } from './types'; +export { RequestStatus } from './types'; export { RequestAdapter } from './request_adapter'; export { RequestResponder } from './request_responder'; diff --git a/src/plugins/inspector/common/index.ts b/src/plugins/inspector/common/index.ts index e92c9b670475a..995846fadd921 100644 --- a/src/plugins/inspector/common/index.ts +++ b/src/plugins/inspector/common/index.ts @@ -6,12 +6,5 @@ * Side Public License, v 1. */ -export { - Adapters, - Request, - RequestAdapter, - RequestStatistic, - RequestStatistics, - RequestStatus, - RequestResponder, -} from './adapters'; +export type { Adapters, Request, RequestStatistic, RequestStatistics } from './adapters'; +export { RequestAdapter, RequestStatus, RequestResponder } from './adapters'; diff --git a/src/plugins/inspector/public/index.ts b/src/plugins/inspector/public/index.ts index c611d13c06ca2..5ad7898550974 100644 --- a/src/plugins/inspector/public/index.ts +++ b/src/plugins/inspector/public/index.ts @@ -18,6 +18,7 @@ export function plugin(initializerContext: PluginInitializerContext) { return new InspectorPublicPlugin(initializerContext); } -export { InspectorPublicPlugin as Plugin, Setup, Start } from './plugin'; +export type { Setup, Start } from './plugin'; +export { InspectorPublicPlugin as Plugin } from './plugin'; export * from './types'; export * from '../common/adapters'; diff --git a/src/plugins/kibana_legacy/public/plugin.ts b/src/plugins/kibana_legacy/public/plugin.ts index ac78e8cac4f07..a154770bbfffd 100644 --- a/src/plugins/kibana_legacy/public/plugin.ts +++ b/src/plugins/kibana_legacy/public/plugin.ts @@ -6,16 +6,14 @@ * Side Public License, v 1. */ -import { CoreStart, CoreSetup } from 'kibana/public'; -import { injectHeaderStyle } from './utils/inject_header_style'; +import type { CoreSetup } from 'kibana/public'; export class KibanaLegacyPlugin { public setup(core: CoreSetup<{}, KibanaLegacyStart>) { return {}; } - public start({ uiSettings }: CoreStart) { - injectHeaderStyle(uiSettings); + public start() { return { /** * Loads the font-awesome icon font. Should be removed once the last consumer has migrated to EUI diff --git a/src/plugins/kibana_legacy/public/utils/inject_header_style.ts b/src/plugins/kibana_legacy/public/utils/inject_header_style.ts deleted file mode 100644 index 967aa2232838e..0000000000000 --- a/src/plugins/kibana_legacy/public/utils/inject_header_style.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 - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { IUiSettingsClient } from 'kibana/public'; - -export function buildCSS(maxHeight = 0, truncateGradientHeight = 15) { - return ` -.truncate-by-height { - max-height: ${maxHeight > 0 ? `${maxHeight}px !important` : 'none'}; - display: inline-block; -} -.truncate-by-height:before { - top: ${maxHeight > 0 ? maxHeight - truncateGradientHeight : truncateGradientHeight * -1}px; -} -`; -} - -export function injectHeaderStyle(uiSettings: IUiSettingsClient) { - const style = document.createElement('style'); - style.setAttribute('id', 'style-compile'); - document.getElementsByTagName('head')[0].appendChild(style); - - uiSettings.get$('truncate:maxHeight').subscribe((value: number) => { - // eslint-disable-next-line no-unsanitized/property - style.innerHTML = buildCSS(value); - }); -} diff --git a/src/plugins/kibana_overview/public/index.ts b/src/plugins/kibana_overview/public/index.ts index eae86edf1d426..aef16587e3de5 100644 --- a/src/plugins/kibana_overview/public/index.ts +++ b/src/plugins/kibana_overview/public/index.ts @@ -15,4 +15,4 @@ import { KibanaOverviewPlugin } from './plugin'; export function plugin() { return new KibanaOverviewPlugin(); } -export { KibanaOverviewPluginSetup, KibanaOverviewPluginStart } from './types'; +export type { KibanaOverviewPluginSetup, KibanaOverviewPluginStart } from './types'; diff --git a/src/plugins/kibana_react/public/context/index.ts b/src/plugins/kibana_react/public/context/index.ts index b34951b298836..8647a1414b9dd 100644 --- a/src/plugins/kibana_react/public/context/index.ts +++ b/src/plugins/kibana_react/public/context/index.ts @@ -13,4 +13,4 @@ export { useKibana, withKibana, } from './context'; -export { KibanaReactContext, KibanaReactContextValue, KibanaServices } from './types'; +export type { KibanaReactContext, KibanaReactContextValue, KibanaServices } from './types'; diff --git a/src/plugins/kibana_react/public/exit_full_screen_button/index.tsx b/src/plugins/kibana_react/public/exit_full_screen_button/index.tsx index d2d7cbc2f570c..16466f5c0f6a2 100644 --- a/src/plugins/kibana_react/public/exit_full_screen_button/index.tsx +++ b/src/plugins/kibana_react/public/exit_full_screen_button/index.tsx @@ -6,4 +6,5 @@ * Side Public License, v 1. */ -export { ExitFullScreenButton, ExitFullScreenButtonProps } from './exit_full_screen_button'; +export type { ExitFullScreenButtonProps } from './exit_full_screen_button'; +export { ExitFullScreenButton } from './exit_full_screen_button'; diff --git a/src/plugins/kibana_react/public/index.ts b/src/plugins/kibana_react/public/index.ts index 6fccb804c357f..03e2bb5f9c272 100644 --- a/src/plugins/kibana_react/public/index.ts +++ b/src/plugins/kibana_react/public/index.ts @@ -23,7 +23,8 @@ export * from './toolbar_button'; export * from './split_panel'; export * from './react_router_navigate'; export * from './page_template'; -export { ValidatedDualRange, Value } from './validated_range'; +export type { Value } from './validated_range'; +export { ValidatedDualRange } from './validated_range'; export * from './notifications'; export { Markdown, MarkdownSimple } from './markdown'; export { reactToUiComponent, uiToReactComponent } from './adapters'; diff --git a/src/plugins/kibana_react/public/page_template/index.ts b/src/plugins/kibana_react/public/page_template/index.ts index 193dc8cd07eee..41eeaab01ef39 100644 --- a/src/plugins/kibana_react/public/page_template/index.ts +++ b/src/plugins/kibana_react/public/page_template/index.ts @@ -6,6 +6,7 @@ * Side Public License, v 1. */ -export { KibanaPageTemplate, KibanaPageTemplateProps } from './page_template'; +export type { KibanaPageTemplateProps } from './page_template'; +export { KibanaPageTemplate } from './page_template'; export { KibanaPageTemplateSolutionNavAvatar } from './solution_nav'; export * from './no_data_page'; diff --git a/src/plugins/kibana_react/public/page_template/solution_nav/index.ts b/src/plugins/kibana_react/public/page_template/solution_nav/index.ts index 3dace6524fef5..81c2033a7ce7c 100644 --- a/src/plugins/kibana_react/public/page_template/solution_nav/index.ts +++ b/src/plugins/kibana_react/public/page_template/solution_nav/index.ts @@ -6,12 +6,9 @@ * Side Public License, v 1. */ -export { KibanaPageTemplateSolutionNav, KibanaPageTemplateSolutionNavProps } from './solution_nav'; -export { - KibanaPageTemplateSolutionNavAvatar, - KibanaPageTemplateSolutionNavAvatarProps, -} from './solution_nav_avatar'; -export { - KibanaPageTemplateSolutionNavCollapseButton, - KibanaPageTemplateSolutionNavCollapseButtonProps, -} from './solution_nav_collapse_button'; +export type { KibanaPageTemplateSolutionNavProps } from './solution_nav'; +export { KibanaPageTemplateSolutionNav } from './solution_nav'; +export type { KibanaPageTemplateSolutionNavAvatarProps } from './solution_nav_avatar'; +export { KibanaPageTemplateSolutionNavAvatar } from './solution_nav_avatar'; +export type { KibanaPageTemplateSolutionNavCollapseButtonProps } from './solution_nav_collapse_button'; +export { KibanaPageTemplateSolutionNavCollapseButton } from './solution_nav_collapse_button'; diff --git a/src/plugins/kibana_react/public/validated_range/index.ts b/src/plugins/kibana_react/public/validated_range/index.ts index d5ecfd23382b8..14f4333cde240 100644 --- a/src/plugins/kibana_react/public/validated_range/index.ts +++ b/src/plugins/kibana_react/public/validated_range/index.ts @@ -6,4 +6,5 @@ * Side Public License, v 1. */ -export { ValidatedDualRange, Value } from './validated_dual_range'; +export type { Value } from './validated_dual_range'; +export { ValidatedDualRange } from './validated_dual_range'; diff --git a/src/plugins/kibana_utils/common/index.ts b/src/plugins/kibana_utils/common/index.ts index be00a13715fc7..365ff52ac9d4b 100644 --- a/src/plugins/kibana_utils/common/index.ts +++ b/src/plugins/kibana_utils/common/index.ts @@ -16,7 +16,8 @@ export * from './ui'; export * from './state_containers'; export * from './errors'; export { AbortError, abortSignalToPromise } from './abort_utils'; -export { createGetterSetter, Get, Set } from './create_getter_setter'; +export type { Get, Set } from './create_getter_setter'; +export { createGetterSetter } from './create_getter_setter'; export { distinctUntilChangedWithInitialValue } from './distinct_until_changed_with_initial_value'; export { url } from './url'; export { now } from './now'; diff --git a/src/plugins/kibana_utils/common/state_containers/index.ts b/src/plugins/kibana_utils/common/state_containers/index.ts index c96b48cc045b7..8c4d3f87a0681 100644 --- a/src/plugins/kibana_utils/common/state_containers/index.ts +++ b/src/plugins/kibana_utils/common/state_containers/index.ts @@ -13,7 +13,7 @@ * @packageDocumentation */ -export { +export type { BaseState, BaseStateContainer, TransitionDescription, @@ -37,7 +37,8 @@ export { PureTransition, Transition, } from './types'; -export { createStateContainer, CreateStateContainerOptions } from './create_state_container'; +export type { CreateStateContainerOptions } from './create_state_container'; +export { createStateContainer } from './create_state_container'; export { createStateContainerReactHelpers, useContainerSelector, diff --git a/src/plugins/kibana_utils/index.ts b/src/plugins/kibana_utils/index.ts index ecffc0544c7db..9b7e91b747db8 100644 --- a/src/plugins/kibana_utils/index.ts +++ b/src/plugins/kibana_utils/index.ts @@ -6,4 +6,5 @@ * Side Public License, v 1. */ -export { createStateContainer, StateContainer, of } from './common'; +export type { StateContainer } from './common'; +export { createStateContainer, of } from './common'; diff --git a/src/plugins/kibana_utils/public/index.ts b/src/plugins/kibana_utils/public/index.ts index 0ac4c61f4a711..090c33e121370 100644 --- a/src/plugins/kibana_utils/public/index.ts +++ b/src/plugins/kibana_utils/public/index.ts @@ -12,6 +12,7 @@ import { KibanaUtilsPublicPlugin } from './plugin'; // TODO: https://github.com/elastic/kibana/issues/109893 /* eslint-disable @kbn/eslint/no_export_all */ +export type { Get, Set, UiComponent, UiComponentInstance } from '../common'; export { AbortError, abortSignalToPromise, @@ -20,11 +21,7 @@ export { Defer, fieldWildcardFilter, fieldWildcardMatcher, - Get, of, - Set, - UiComponent, - UiComponentInstance, url, createGetterSetter, } from '../common'; @@ -56,11 +53,7 @@ export { replaceUrlQuery, replaceUrlHashQuery, } from './state_management/url'; -export { - syncState, - syncStates, - createKbnUrlStateStorage, - createSessionStorageStateStorage, +export type { IStateSyncConfig, ISyncStateRef, IKbnUrlStateStorage, @@ -69,7 +62,13 @@ export { StartSyncStateFnType, StopSyncStateFnType, } from './state_sync'; -export { Configurable, CollectConfigProps } from './ui'; +export { + syncState, + syncStates, + createKbnUrlStateStorage, + createSessionStorageStateStorage, +} from './state_sync'; +export type { Configurable, CollectConfigProps } from './ui'; export { removeQueryParam, redirectWhenMissing, @@ -79,9 +78,10 @@ export { createQueryParamObservable, } from './history'; export { applyDiff } from './state_management/utils/diff_object'; -export { createStartServicesGetter, StartServicesGetter } from './core/create_start_service_getter'; +export type { StartServicesGetter } from './core/create_start_service_getter'; +export { createStartServicesGetter } from './core/create_start_service_getter'; -export { KibanaUtilsSetup } from './plugin'; +export type { KibanaUtilsSetup } from './plugin'; export function plugin(initializerContext: PluginInitializerContext) { return new KibanaUtilsPublicPlugin(initializerContext); diff --git a/src/plugins/kibana_utils/public/state_management/url/index.ts b/src/plugins/kibana_utils/public/state_management/url/index.ts index b180232b21526..7f39e9ac1b698 100644 --- a/src/plugins/kibana_utils/public/state_management/url/index.ts +++ b/src/plugins/kibana_utils/public/state_management/url/index.ts @@ -7,12 +7,12 @@ */ export { hashUrl, hashQuery, unhashUrl, unhashQuery } from './hash_unhash_url'; +export type { IKbnUrlControls } from './kbn_url_storage'; export { createKbnUrlControls, setStateToKbnUrl, getStateFromKbnUrl, getStatesFromKbnUrl, - IKbnUrlControls, } from './kbn_url_storage'; export { createKbnUrlTracker } from './kbn_url_tracker'; export { createUrlTracker } from './url_tracker'; diff --git a/src/plugins/kibana_utils/public/state_sync/index.ts b/src/plugins/kibana_utils/public/state_sync/index.ts index 2e14096c23950..603e7582c7b16 100644 --- a/src/plugins/kibana_utils/public/state_sync/index.ts +++ b/src/plugins/kibana_utils/public/state_sync/index.ts @@ -26,18 +26,15 @@ * @packageDocumentation */ -export { - createSessionStorageStateStorage, - createKbnUrlStateStorage, +export type { IKbnUrlStateStorage, ISessionStorageStateStorage, IStateStorage, } from './state_sync_state_storage'; -export { IStateSyncConfig, INullableBaseStateContainer } from './types'; export { - syncState, - syncStates, - StopSyncStateFnType, - StartSyncStateFnType, - ISyncStateRef, -} from './state_sync'; + createSessionStorageStateStorage, + createKbnUrlStateStorage, +} from './state_sync_state_storage'; +export type { IStateSyncConfig, INullableBaseStateContainer } from './types'; +export type { StopSyncStateFnType, StartSyncStateFnType, ISyncStateRef } from './state_sync'; +export { syncState, syncStates } from './state_sync'; diff --git a/src/plugins/kibana_utils/public/state_sync/state_sync_state_storage/index.ts b/src/plugins/kibana_utils/public/state_sync/state_sync_state_storage/index.ts index 8ac6c4eaaf3d0..55f62b5183379 100644 --- a/src/plugins/kibana_utils/public/state_sync/state_sync_state_storage/index.ts +++ b/src/plugins/kibana_utils/public/state_sync/state_sync_state_storage/index.ts @@ -6,9 +6,8 @@ * Side Public License, v 1. */ -export { IStateStorage } from './types'; -export { createKbnUrlStateStorage, IKbnUrlStateStorage } from './create_kbn_url_state_storage'; -export { - createSessionStorageStateStorage, - ISessionStorageStateStorage, -} from './create_session_storage_state_storage'; +export type { IStateStorage } from './types'; +export type { IKbnUrlStateStorage } from './create_kbn_url_state_storage'; +export { createKbnUrlStateStorage } from './create_kbn_url_state_storage'; +export type { ISessionStorageStateStorage } from './create_session_storage_state_storage'; +export { createSessionStorageStateStorage } from './create_session_storage_state_storage'; diff --git a/src/plugins/kibana_utils/public/storage/index.ts b/src/plugins/kibana_utils/public/storage/index.ts index 9423741145319..26859bb86107e 100644 --- a/src/plugins/kibana_utils/public/storage/index.ts +++ b/src/plugins/kibana_utils/public/storage/index.ts @@ -7,4 +7,4 @@ */ export { Storage } from './storage'; -export { IStorage, IStorageWrapper } from './types'; +export type { IStorage, IStorageWrapper } from './types'; diff --git a/src/plugins/kibana_utils/server/index.ts b/src/plugins/kibana_utils/server/index.ts index 42847042be151..2e4f7c7cc52f1 100644 --- a/src/plugins/kibana_utils/server/index.ts +++ b/src/plugins/kibana_utils/server/index.ts @@ -6,14 +6,13 @@ * Side Public License, v 1. */ +export type { Get, Set } from '../common'; export { AbortError, abortSignalToPromise, createGetterSetter, fieldWildcardFilter, fieldWildcardMatcher, - Get, - Set, url, mergeMigrationFunctionMaps, } from '../common'; diff --git a/src/plugins/management/common/index.ts b/src/plugins/management/common/index.ts index c701ba846bcac..77ae14c3c1d2d 100644 --- a/src/plugins/management/common/index.ts +++ b/src/plugins/management/common/index.ts @@ -6,4 +6,4 @@ * Side Public License, v 1. */ -export { ManagementAppLocator } from './locator'; +export type { ManagementAppLocator } from './locator'; diff --git a/src/plugins/management/public/components/management_app/index.ts b/src/plugins/management/public/components/management_app/index.ts index 1a5cc3945344f..aa768e3837922 100644 --- a/src/plugins/management/public/components/management_app/index.ts +++ b/src/plugins/management/public/components/management_app/index.ts @@ -6,4 +6,5 @@ * Side Public License, v 1. */ -export { ManagementApp, ManagementAppDependencies } from './management_app'; +export type { ManagementAppDependencies } from './management_app'; +export { ManagementApp } from './management_app'; diff --git a/src/plugins/management/public/index.ts b/src/plugins/management/public/index.ts index 2f5550acbaf6b..41d244ad44d5a 100644 --- a/src/plugins/management/public/index.ts +++ b/src/plugins/management/public/index.ts @@ -13,9 +13,10 @@ export function plugin(initializerContext: PluginInitializerContext) { return new ManagementPlugin(initializerContext); } -export { RegisterManagementAppArgs, ManagementSection, ManagementApp } from './utils'; +export type { RegisterManagementAppArgs } from './utils'; +export { ManagementSection, ManagementApp } from './utils'; -export { +export type { ManagementAppMountParams, ManagementSetup, ManagementStart, diff --git a/src/plugins/management/public/utils/index.ts b/src/plugins/management/public/utils/index.ts index c51c6b050753a..4bdf6979c28f2 100644 --- a/src/plugins/management/public/utils/index.ts +++ b/src/plugins/management/public/utils/index.ts @@ -7,5 +7,7 @@ */ export { MANAGEMENT_BREADCRUMB } from './breadcrumbs'; -export { ManagementApp, RegisterManagementAppArgs } from './management_app'; -export { ManagementSection, RegisterManagementSectionArgs } from './management_section'; +export type { RegisterManagementAppArgs } from './management_app'; +export { ManagementApp } from './management_app'; +export type { RegisterManagementSectionArgs } from './management_section'; +export { ManagementSection } from './management_section'; diff --git a/src/plugins/maps_ems/public/index.ts b/src/plugins/maps_ems/public/index.ts index a4a0fc45d9164..74b831e058801 100644 --- a/src/plugins/maps_ems/public/index.ts +++ b/src/plugins/maps_ems/public/index.ts @@ -12,7 +12,7 @@ import { IServiceSettings } from './service_settings'; import type { MapsEmsConfig } from '../config'; /** @public */ -export { +export type { VectorLayer, FileLayerField, FileLayer, diff --git a/src/plugins/navigation/public/index.ts b/src/plugins/navigation/public/index.ts index 21d63c72cdd62..91b68ecab644b 100644 --- a/src/plugins/navigation/public/index.ts +++ b/src/plugins/navigation/public/index.ts @@ -13,9 +13,10 @@ export function plugin(initializerContext: PluginInitializerContext) { return new NavigationPublicPlugin(initializerContext); } -export { TopNavMenuData, TopNavMenu, TopNavMenuProps } from './top_nav_menu'; +export type { TopNavMenuData, TopNavMenuProps } from './top_nav_menu'; +export { TopNavMenu } from './top_nav_menu'; -export { NavigationPublicPluginSetup, NavigationPublicPluginStart } from './types'; +export type { NavigationPublicPluginSetup, NavigationPublicPluginStart } from './types'; // Export plugin after all other imports import { NavigationPublicPlugin } from './plugin'; diff --git a/src/plugins/navigation/public/top_nav_menu/index.ts b/src/plugins/navigation/public/top_nav_menu/index.ts index 19f359e60ba7a..16c92aaaaf712 100644 --- a/src/plugins/navigation/public/top_nav_menu/index.ts +++ b/src/plugins/navigation/public/top_nav_menu/index.ts @@ -7,9 +7,8 @@ */ export { createTopNav } from './create_top_nav_menu'; -export { TopNavMenu, TopNavMenuProps } from './top_nav_menu'; -export { TopNavMenuData } from './top_nav_menu_data'; -export { - TopNavMenuExtensionsRegistrySetup, - TopNavMenuExtensionsRegistry, -} from './top_nav_menu_extensions_registry'; +export type { TopNavMenuProps } from './top_nav_menu'; +export { TopNavMenu } from './top_nav_menu'; +export type { TopNavMenuData } from './top_nav_menu_data'; +export type { TopNavMenuExtensionsRegistrySetup } from './top_nav_menu_extensions_registry'; +export { TopNavMenuExtensionsRegistry } from './top_nav_menu_extensions_registry'; diff --git a/src/plugins/newsfeed/public/index.ts b/src/plugins/newsfeed/public/index.ts index 324306f889d15..f9d59ca6d99dd 100644 --- a/src/plugins/newsfeed/public/index.ts +++ b/src/plugins/newsfeed/public/index.ts @@ -15,13 +15,8 @@ import { import { FetchResult, NewsfeedItem } from './types'; import { NewsfeedApiEndpoint } from './lib/api'; -export { - NewsfeedPublicPluginSetup, - NewsfeedPublicPluginStart, - FetchResult, - NewsfeedItem, - NewsfeedApiEndpoint, -}; +export type { NewsfeedPublicPluginSetup, NewsfeedPublicPluginStart, FetchResult, NewsfeedItem }; +export { NewsfeedApiEndpoint }; export function plugin(initializerContext: PluginInitializerContext) { return new NewsfeedPublicPlugin(initializerContext); diff --git a/src/plugins/presentation_util/public/components/controls/control_group/index.ts b/src/plugins/presentation_util/public/components/controls/control_group/index.ts index 45a91a87a7962..95988d2e8143c 100644 --- a/src/plugins/presentation_util/public/components/controls/control_group/index.ts +++ b/src/plugins/presentation_util/public/components/controls/control_group/index.ts @@ -6,6 +6,6 @@ * Side Public License, v 1. */ -export { ControlGroupInput, ControlGroupOutput } from './types'; +export type { ControlGroupInput, ControlGroupOutput } from './types'; export type { ControlGroupContainer } from './embeddable/control_group_container'; export { ControlGroupContainerFactory } from './embeddable/control_group_container_factory'; diff --git a/src/plugins/presentation_util/public/components/solution_toolbar/items/index.ts b/src/plugins/presentation_util/public/components/solution_toolbar/items/index.ts index 654831e86d3f6..6076dbf8cf123 100644 --- a/src/plugins/presentation_util/public/components/solution_toolbar/items/index.ts +++ b/src/plugins/presentation_util/public/components/solution_toolbar/items/index.ts @@ -9,6 +9,7 @@ export { SolutionToolbarButton } from './button'; export { SolutionToolbarPopover } from './popover'; export { AddFromLibraryButton } from './add_from_library'; -export { QuickButtonProps, QuickButtonGroup } from './quick_group'; +export type { QuickButtonProps } from './quick_group'; +export { QuickButtonGroup } from './quick_group'; export { PrimaryActionButton } from './primary_button'; export { PrimaryActionPopover } from './primary_popover'; diff --git a/src/plugins/presentation_util/public/index.ts b/src/plugins/presentation_util/public/index.ts index 478e8a7cda032..91f1e3a937f62 100644 --- a/src/plugins/presentation_util/public/index.ts +++ b/src/plugins/presentation_util/public/index.ts @@ -11,26 +11,25 @@ import { PresentationUtilPlugin } from './plugin'; -export { +export type { PresentationCapabilitiesService, PresentationDashboardsService, PresentationLabsService, - getStubPluginServices, } from './services'; +export { getStubPluginServices } from './services'; -export { +export type { KibanaPluginServiceFactory, PluginServiceFactory, - PluginServices, PluginServiceProviders, - PluginServiceProvider, - PluginServiceRegistry, KibanaPluginServiceParams, } from './services/create'; +export { PluginServices, PluginServiceProvider, PluginServiceRegistry } from './services/create'; -export { PresentationUtilPluginSetup, PresentationUtilPluginStart } from './types'; -export { SaveModalDashboardProps } from './components/types'; -export { projectIDs, ProjectID, Project } from '../common/labs'; +export type { PresentationUtilPluginSetup, PresentationUtilPluginStart } from './types'; +export type { SaveModalDashboardProps } from './components/types'; +export type { ProjectID, Project } from '../common/labs'; +export { projectIDs } from '../common/labs'; export * from '../common/lib'; export { @@ -43,12 +42,12 @@ export { export * from './components/types'; +export type { QuickButtonProps } from './components/solution_toolbar'; export { AddFromLibraryButton, PrimaryActionButton, PrimaryActionPopover, QuickButtonGroup, - QuickButtonProps, SolutionToolbar, SolutionToolbarButton, SolutionToolbarPopover, diff --git a/src/plugins/presentation_util/public/services/create/index.ts b/src/plugins/presentation_util/public/services/create/index.ts index 163e25e26babf..d616d7bee20c8 100644 --- a/src/plugins/presentation_util/public/services/create/index.ts +++ b/src/plugins/presentation_util/public/services/create/index.ts @@ -9,8 +9,9 @@ import { PluginServiceRegistry } from './registry'; export { PluginServiceRegistry } from './registry'; -export { PluginServiceProvider, PluginServiceProviders } from './provider'; -export { +export type { PluginServiceProviders } from './provider'; +export { PluginServiceProvider } from './provider'; +export type { PluginServiceFactory, KibanaPluginServiceFactory, KibanaPluginServiceParams, diff --git a/src/plugins/presentation_util/public/services/index.ts b/src/plugins/presentation_util/public/services/index.ts index c7d8d2617888a..cafb01594bd3c 100644 --- a/src/plugins/presentation_util/public/services/index.ts +++ b/src/plugins/presentation_util/public/services/index.ts @@ -17,9 +17,9 @@ import { PresentationControlsService } from './controls'; import { PresentationDataViewsService } from './data_views'; import { PresentationDataService } from './data'; -export { PresentationCapabilitiesService } from './capabilities'; -export { PresentationDashboardsService } from './dashboards'; -export { PresentationLabsService } from './labs'; +export type { PresentationCapabilitiesService } from './capabilities'; +export type { PresentationDashboardsService } from './dashboards'; +export type { PresentationLabsService } from './labs'; export interface PresentationUtilServices { dashboards: PresentationDashboardsService; dataViews: PresentationDataViewsService; diff --git a/src/plugins/presentation_util/public/services/storybook/index.ts b/src/plugins/presentation_util/public/services/storybook/index.ts index 1639316a1fe19..a2d729f6d730a 100644 --- a/src/plugins/presentation_util/public/services/storybook/index.ts +++ b/src/plugins/presentation_util/public/services/storybook/index.ts @@ -21,8 +21,9 @@ import { controlsServiceFactory } from './controls'; import { dataViewsServiceFactory } from './data_views'; import { dataServiceFactory } from './data'; -export { PluginServiceProviders, PluginServiceProvider, PluginServiceRegistry } from '../create'; -export { PresentationUtilServices } from '..'; +export type { PluginServiceProviders } from '../create'; +export { PluginServiceProvider, PluginServiceRegistry } from '../create'; +export type { PresentationUtilServices } from '..'; export interface StorybookParams { canAccessDashboards?: boolean; diff --git a/src/plugins/saved_objects/public/finder/index.ts b/src/plugins/saved_objects/public/finder/index.ts index de6a54795fce5..aaf6259daca1d 100644 --- a/src/plugins/saved_objects/public/finder/index.ts +++ b/src/plugins/saved_objects/public/finder/index.ts @@ -6,9 +6,5 @@ * Side Public License, v 1. */ -export { - SavedObjectMetaData, - SavedObjectFinderUi, - SavedObjectFinderUiProps, - getSavedObjectFinder, -} from './saved_object_finder'; +export type { SavedObjectMetaData, SavedObjectFinderUiProps } from './saved_object_finder'; +export { SavedObjectFinderUi, getSavedObjectFinder } from './saved_object_finder'; diff --git a/src/plugins/saved_objects/public/index.ts b/src/plugins/saved_objects/public/index.ts index bc84298a63717..d63e20f5f5673 100644 --- a/src/plugins/saved_objects/public/index.ts +++ b/src/plugins/saved_objects/public/index.ts @@ -8,33 +8,24 @@ import { SavedObjectsPublicPlugin } from './plugin'; -export { - OnSaveProps, - SavedObjectSaveModal, - SavedObjectSaveModalOrigin, - OriginSaveModalProps, - SaveModalState, - SaveResult, - showSaveModal, -} from './save_modal'; -export { - getSavedObjectFinder, - SavedObjectFinderUi, - SavedObjectFinderUiProps, - SavedObjectMetaData, -} from './finder'; +export type { OnSaveProps, OriginSaveModalProps, SaveModalState, SaveResult } from './save_modal'; +export { SavedObjectSaveModal, SavedObjectSaveModalOrigin, showSaveModal } from './save_modal'; +export type { SavedObjectFinderUiProps, SavedObjectMetaData } from './finder'; +export { getSavedObjectFinder, SavedObjectFinderUi } from './finder'; +export type { + SavedObjectLoaderFindOptions, + SavedObjectDecorator, + SavedObjectDecoratorFactory, + SavedObjectDecoratorConfig, +} from './saved_object'; export { SavedObjectLoader, - SavedObjectLoaderFindOptions, checkForDuplicateTitle, saveWithConfirmation, isErrorNonFatal, - SavedObjectDecorator, - SavedObjectDecoratorFactory, - SavedObjectDecoratorConfig, } from './saved_object'; -export { SavedObjectSaveOpts, SavedObject, SavedObjectConfig } from './types'; +export type { SavedObjectSaveOpts, SavedObject, SavedObjectConfig } from './types'; export { PER_PAGE_SETTING, LISTING_LIMIT_SETTING } from '../common'; -export { SavedObjectsStart, SavedObjectSetup } from './plugin'; +export type { SavedObjectsStart, SavedObjectSetup } from './plugin'; export const plugin = () => new SavedObjectsPublicPlugin(); diff --git a/src/plugins/saved_objects/public/save_modal/index.ts b/src/plugins/saved_objects/public/save_modal/index.ts index cd10374e57343..8c23b797a05db 100644 --- a/src/plugins/saved_objects/public/save_modal/index.ts +++ b/src/plugins/saved_objects/public/save_modal/index.ts @@ -6,6 +6,9 @@ * Side Public License, v 1. */ -export { SavedObjectSaveModal, OnSaveProps, SaveModalState } from './saved_object_save_modal'; -export { SavedObjectSaveModalOrigin, OriginSaveModalProps } from './saved_object_save_modal_origin'; -export { showSaveModal, SaveResult } from './show_saved_object_save_modal'; +export type { OnSaveProps, SaveModalState } from './saved_object_save_modal'; +export { SavedObjectSaveModal } from './saved_object_save_modal'; +export type { OriginSaveModalProps } from './saved_object_save_modal_origin'; +export { SavedObjectSaveModalOrigin } from './saved_object_save_modal_origin'; +export type { SaveResult } from './show_saved_object_save_modal'; +export { showSaveModal } from './show_saved_object_save_modal'; diff --git a/src/plugins/saved_objects/public/saved_object/decorators/index.ts b/src/plugins/saved_objects/public/saved_object/decorators/index.ts index d7aed32b5e2e7..1b43ae9808bf7 100644 --- a/src/plugins/saved_objects/public/saved_object/decorators/index.ts +++ b/src/plugins/saved_objects/public/saved_object/decorators/index.ts @@ -6,9 +6,6 @@ * Side Public License, v 1. */ -export { - ISavedObjectDecoratorRegistry, - SavedObjectDecoratorRegistry, - SavedObjectDecoratorConfig, -} from './registry'; -export { SavedObjectDecorator, SavedObjectDecoratorFactory } from './types'; +export type { ISavedObjectDecoratorRegistry, SavedObjectDecoratorConfig } from './registry'; +export { SavedObjectDecoratorRegistry } from './registry'; +export type { SavedObjectDecorator, SavedObjectDecoratorFactory } from './types'; diff --git a/src/plugins/saved_objects/public/saved_object/helpers/field_mapping/index.ts b/src/plugins/saved_objects/public/saved_object/helpers/field_mapping/index.ts index b8a7b7ecc31a1..9a52f9b0e8458 100644 --- a/src/plugins/saved_objects/public/saved_object/helpers/field_mapping/index.ts +++ b/src/plugins/saved_objects/public/saved_object/helpers/field_mapping/index.ts @@ -6,5 +6,5 @@ * Side Public License, v 1. */ -export { FieldMappingSpec, MappingObject } from './types'; +export type { FieldMappingSpec, MappingObject } from './types'; export { expandShorthand } from './mapping_setup'; diff --git a/src/plugins/saved_objects/public/saved_object/index.ts b/src/plugins/saved_objects/public/saved_object/index.ts index 116999afb71ae..f30730a1c39ac 100644 --- a/src/plugins/saved_objects/public/saved_object/index.ts +++ b/src/plugins/saved_objects/public/saved_object/index.ts @@ -7,13 +7,14 @@ */ export { createSavedObjectClass } from './saved_object'; -export { SavedObjectLoader, SavedObjectLoaderFindOptions } from './saved_object_loader'; +export type { SavedObjectLoaderFindOptions } from './saved_object_loader'; +export { SavedObjectLoader } from './saved_object_loader'; export { checkForDuplicateTitle } from './helpers/check_for_duplicate_title'; export { saveWithConfirmation } from './helpers/save_with_confirmation'; export { isErrorNonFatal } from './helpers/save_saved_object'; -export { - SavedObjectDecoratorRegistry, +export type { SavedObjectDecoratorFactory, SavedObjectDecorator, SavedObjectDecoratorConfig, } from './decorators'; +export { SavedObjectDecoratorRegistry } from './decorators'; diff --git a/src/plugins/saved_objects_management/public/index.ts b/src/plugins/saved_objects_management/public/index.ts index 92e01ab903699..99ffae349bb48 100644 --- a/src/plugins/saved_objects_management/public/index.ts +++ b/src/plugins/saved_objects_management/public/index.ts @@ -9,18 +9,22 @@ import { PluginInitializerContext } from 'kibana/public'; import { SavedObjectsManagementPlugin } from './plugin'; -export { SavedObjectsManagementPluginSetup, SavedObjectsManagementPluginStart } from './plugin'; -export { +export type { + SavedObjectsManagementPluginSetup, + SavedObjectsManagementPluginStart, +} from './plugin'; +export type { SavedObjectsManagementActionServiceSetup, SavedObjectsManagementActionServiceStart, - SavedObjectsManagementAction, SavedObjectsManagementColumnServiceSetup, SavedObjectsManagementColumnServiceStart, SavedObjectsManagementColumn, SavedObjectsManagementRecord, } from './services'; -export { ProcessedImportResponse, processImportResponse, FailedImport } from './lib'; -export { SavedObjectRelation, SavedObjectWithMetadata, SavedObjectMetadata } from './types'; +export { SavedObjectsManagementAction } from './services'; +export type { ProcessedImportResponse, FailedImport } from './lib'; +export { processImportResponse } from './lib'; +export type { SavedObjectRelation, SavedObjectWithMetadata, SavedObjectMetadata } from './types'; export function plugin(initializerContext: PluginInitializerContext) { return new SavedObjectsManagementPlugin(); diff --git a/src/plugins/saved_objects_management/public/lib/index.ts b/src/plugins/saved_objects_management/public/lib/index.ts index e317bb5e39f73..258387c39ecd9 100644 --- a/src/plugins/saved_objects_management/public/lib/index.ts +++ b/src/plugins/saved_objects_management/public/lib/index.ts @@ -14,14 +14,12 @@ export { getSavedObjectLabel } from './get_saved_object_label'; export { importFile } from './import_file'; export { parseQuery } from './parse_query'; export { resolveImportErrors } from './resolve_import_errors'; -export { - processImportResponse, - ProcessedImportResponse, - FailedImport, -} from './process_import_response'; +export type { ProcessedImportResponse, FailedImport } from './process_import_response'; +export { processImportResponse } from './process_import_response'; export { getDefaultTitle } from './get_default_title'; export { findObjects } from './find_objects'; export { bulkGetObjects } from './bulk_get_objects'; -export { extractExportDetails, SavedObjectsExportResultDetails } from './extract_export_details'; +export type { SavedObjectsExportResultDetails } from './extract_export_details'; +export { extractExportDetails } from './extract_export_details'; export { getAllowedTypes } from './get_allowed_types'; export { getTagFindReferences } from './get_tag_references'; diff --git a/src/plugins/saved_objects_management/public/services/index.ts b/src/plugins/saved_objects_management/public/services/index.ts index f3c0100d61599..c45c81d3122ad 100644 --- a/src/plugins/saved_objects_management/public/services/index.ts +++ b/src/plugins/saved_objects_management/public/services/index.ts @@ -6,18 +6,15 @@ * Side Public License, v 1. */ -export { - SavedObjectsManagementActionService, +export type { SavedObjectsManagementActionServiceStart, SavedObjectsManagementActionServiceSetup, } from './action_service'; -export { - SavedObjectsManagementColumnService, +export { SavedObjectsManagementActionService } from './action_service'; +export type { SavedObjectsManagementColumnServiceStart, SavedObjectsManagementColumnServiceSetup, } from './column_service'; -export { - SavedObjectsManagementAction, - SavedObjectsManagementColumn, - SavedObjectsManagementRecord, -} from './types'; +export { SavedObjectsManagementColumnService } from './column_service'; +export type { SavedObjectsManagementColumn, SavedObjectsManagementRecord } from './types'; +export { SavedObjectsManagementAction } from './types'; diff --git a/src/plugins/saved_objects_management/public/services/types/index.ts b/src/plugins/saved_objects_management/public/services/types/index.ts index 457ade0a295e7..82b45f9df33f0 100644 --- a/src/plugins/saved_objects_management/public/services/types/index.ts +++ b/src/plugins/saved_objects_management/public/services/types/index.ts @@ -7,5 +7,5 @@ */ export { SavedObjectsManagementAction } from './action'; -export { SavedObjectsManagementColumn } from './column'; -export { SavedObjectsManagementRecord } from './record'; +export type { SavedObjectsManagementColumn } from './column'; +export type { SavedObjectsManagementRecord } from './record'; diff --git a/src/plugins/saved_objects_management/public/types.ts b/src/plugins/saved_objects_management/public/types.ts index cd6e3e9eaa32c..61766e1cb8c10 100644 --- a/src/plugins/saved_objects_management/public/types.ts +++ b/src/plugins/saved_objects_management/public/types.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -export { +export type { SavedObjectMetadata, SavedObjectWithMetadata, SavedObjectRelationKind, diff --git a/src/plugins/saved_objects_management/server/index.ts b/src/plugins/saved_objects_management/server/index.ts index b56382113e1ea..942d7b0734aee 100644 --- a/src/plugins/saved_objects_management/server/index.ts +++ b/src/plugins/saved_objects_management/server/index.ts @@ -12,7 +12,7 @@ import { SavedObjectsManagementPlugin } from './plugin'; export const plugin = (context: PluginInitializerContext) => new SavedObjectsManagementPlugin(context); -export { +export type { SavedObjectsManagementPluginSetup, SavedObjectsManagementPluginStart, SavedObjectMetadata, diff --git a/src/plugins/saved_objects_management/server/services/index.ts b/src/plugins/saved_objects_management/server/services/index.ts index 7bee337f59a98..f0f6d9e7fa978 100644 --- a/src/plugins/saved_objects_management/server/services/index.ts +++ b/src/plugins/saved_objects_management/server/services/index.ts @@ -6,4 +6,5 @@ * Side Public License, v 1. */ -export { SavedObjectsManagement, ISavedObjectsManagement } from './management'; +export type { ISavedObjectsManagement } from './management'; +export { SavedObjectsManagement } from './management'; diff --git a/src/plugins/saved_objects_management/server/types.ts b/src/plugins/saved_objects_management/server/types.ts index 5779c6d98e35d..93f6f3d09547a 100644 --- a/src/plugins/saved_objects_management/server/types.ts +++ b/src/plugins/saved_objects_management/server/types.ts @@ -12,7 +12,7 @@ export interface SavedObjectsManagementPluginSetup {} // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface SavedObjectsManagementPluginStart {} -export { +export type { SavedObjectMetadata, SavedObjectWithMetadata, SavedObjectRelationKind, diff --git a/src/plugins/saved_objects_tagging_oss/common/index.ts b/src/plugins/saved_objects_tagging_oss/common/index.ts index a892f41c69314..0a8bd890614b7 100644 --- a/src/plugins/saved_objects_tagging_oss/common/index.ts +++ b/src/plugins/saved_objects_tagging_oss/common/index.ts @@ -6,4 +6,4 @@ * Side Public License, v 1. */ -export { Tag, TagAttributes, GetAllTagsOptions, ITagsClient } from './types'; +export type { Tag, TagAttributes, GetAllTagsOptions, ITagsClient } from './types'; diff --git a/src/plugins/saved_objects_tagging_oss/public/decorator/index.ts b/src/plugins/saved_objects_tagging_oss/public/decorator/index.ts index 6ea905b1db245..7ca7c50505f27 100644 --- a/src/plugins/saved_objects_tagging_oss/public/decorator/index.ts +++ b/src/plugins/saved_objects_tagging_oss/public/decorator/index.ts @@ -10,7 +10,7 @@ import { SavedObjectDecoratorConfig } from '../../../saved_objects/public'; import { tagDecoratorFactory, decoratorId } from './factory'; import { InternalTagDecoratedSavedObject } from './types'; -export { TagDecoratedSavedObject } from './types'; +export type { TagDecoratedSavedObject } from './types'; export const tagDecoratorConfig: SavedObjectDecoratorConfig = { id: decoratorId, diff --git a/src/plugins/saved_objects_tagging_oss/public/index.ts b/src/plugins/saved_objects_tagging_oss/public/index.ts index eb38614f90539..6e9a0bf3d832e 100644 --- a/src/plugins/saved_objects_tagging_oss/public/index.ts +++ b/src/plugins/saved_objects_tagging_oss/public/index.ts @@ -9,9 +9,9 @@ import { PluginInitializerContext } from '../../../../src/core/public'; import { SavedObjectTaggingOssPlugin } from './plugin'; -export { SavedObjectTaggingOssPluginSetup, SavedObjectTaggingOssPluginStart } from './types'; +export type { SavedObjectTaggingOssPluginSetup, SavedObjectTaggingOssPluginStart } from './types'; -export { +export type { SavedObjectsTaggingApi, SavedObjectsTaggingApiUi, SavedObjectsTaggingApiUiComponent, @@ -25,7 +25,7 @@ export { SavedObjectTagDecoratorTypeGuard, } from './api'; -export { TagDecoratedSavedObject } from './decorator'; +export type { TagDecoratedSavedObject } from './decorator'; export const plugin = (initializerContext: PluginInitializerContext) => new SavedObjectTaggingOssPlugin(initializerContext); diff --git a/src/plugins/screenshot_mode/public/index.ts b/src/plugins/screenshot_mode/public/index.ts index 012f57e837f41..591ddbfdf49c5 100644 --- a/src/plugins/screenshot_mode/public/index.ts +++ b/src/plugins/screenshot_mode/public/index.ts @@ -18,4 +18,4 @@ export { KBN_SCREENSHOT_MODE_ENABLED_KEY, } from '../common'; -export { ScreenshotModePluginSetup, ScreenshotModePluginStart } from './types'; +export type { ScreenshotModePluginSetup, ScreenshotModePluginStart } from './types'; diff --git a/src/plugins/screenshot_mode/server/index.ts b/src/plugins/screenshot_mode/server/index.ts index b9f19a474ccbe..cc5d45b7be732 100644 --- a/src/plugins/screenshot_mode/server/index.ts +++ b/src/plugins/screenshot_mode/server/index.ts @@ -14,7 +14,7 @@ export { KBN_SCREENSHOT_MODE_ENABLED_KEY, } from '../common'; -export { +export type { ScreenshotModeRequestHandlerContext, ScreenshotModePluginSetup, ScreenshotModePluginStart, diff --git a/src/plugins/share/common/index.ts b/src/plugins/share/common/index.ts index 992ec2447855f..0269dda43b9c5 100644 --- a/src/plugins/share/common/index.ts +++ b/src/plugins/share/common/index.ts @@ -6,5 +6,6 @@ * Side Public License, v 1. */ -export { LocatorDefinition, LocatorPublic, useLocatorUrl, formatSearchParams } from './url_service'; +export type { LocatorDefinition, LocatorPublic } from './url_service'; +export { useLocatorUrl } from './url_service'; export type { AnonymousAccessServiceContract, AnonymousAccessState } from './anonymous_access'; diff --git a/src/plugins/share/common/url_service/locators/locator.ts b/src/plugins/share/common/url_service/locators/locator.ts index 2d33f701df595..2bacdd67875bd 100644 --- a/src/plugins/share/common/url_service/locators/locator.ts +++ b/src/plugins/share/common/url_service/locators/locator.ts @@ -118,11 +118,9 @@ export class Locator

implements LocatorPublic

{ }); } - /* eslint-disable react-hooks/rules-of-hooks */ public readonly useUrl = ( params: P, getUrlParams?: LocatorGetUrlParams, deps: DependencyList = [] ): string => useLocatorUrl

(this, params, getUrlParams, deps); - /* eslint-enable react-hooks/rules-of-hooks */ } diff --git a/src/plugins/share/public/index.ts b/src/plugins/share/public/index.ts index 75f541dd5ae3d..2e57a9347b057 100644 --- a/src/plugins/share/public/index.ts +++ b/src/plugins/share/public/index.ts @@ -10,13 +10,13 @@ import type { PluginInitializerContext } from 'src/core/public'; export { CSV_QUOTE_VALUES_SETTING, CSV_SEPARATOR_SETTING } from '../common/constants'; -export { LocatorDefinition, LocatorPublic, KibanaLocation } from '../common/url_service'; +export type { LocatorDefinition, LocatorPublic, KibanaLocation } from '../common/url_service'; -export { UrlGeneratorStateMapping } from './url_generators/url_generator_definition'; +export type { UrlGeneratorStateMapping } from './url_generators/url_generator_definition'; -export { SharePluginSetup, SharePluginStart } from './plugin'; +export type { SharePluginSetup, SharePluginStart } from './plugin'; -export { +export type { ShareContext, ShareMenuProvider, ShareMenuItem, @@ -24,15 +24,15 @@ export { ShareContextMenuPanelItem, } from './types'; -export { +export type { UrlGeneratorId, UrlGeneratorState, UrlGeneratorsDefinition, UrlGeneratorContract, - UrlGeneratorsService, } from './url_generators'; +export { UrlGeneratorsService } from './url_generators'; -export { RedirectOptions } from '../common/url_service'; +export type { RedirectOptions } from '../common/url_service'; export { useLocatorUrl } from '../common/url_service/locators/use_locator_url'; import { SharePlugin } from './plugin'; diff --git a/src/plugins/share/public/url_generators/url_generator_contract.ts b/src/plugins/share/public/url_generators/url_generator_contract.ts index b21e0f2a35c88..22ccae8909a69 100644 --- a/src/plugins/share/public/url_generators/url_generator_contract.ts +++ b/src/plugins/share/public/url_generators/url_generator_contract.ts @@ -12,8 +12,4 @@ export interface UrlGeneratorContract { id: Id; createUrl(state: UrlGeneratorStateMapping[Id]['State']): Promise; isDeprecated: boolean; - migrate(state: UrlGeneratorStateMapping[Id]['State']): Promise<{ - state: UrlGeneratorStateMapping[Id]['MigratedState']; - id: UrlGeneratorStateMapping[Id]['MigratedId']; - }>; } diff --git a/src/plugins/share/public/url_generators/url_generator_internal.ts b/src/plugins/share/public/url_generators/url_generator_internal.ts index 9059a26566f92..7f7dc0f63f87b 100644 --- a/src/plugins/share/public/url_generators/url_generator_internal.ts +++ b/src/plugins/share/public/url_generators/url_generator_internal.ts @@ -72,17 +72,6 @@ export class UrlGeneratorInternal { return this.spec.createUrl!(state); }, isDeprecated: !!this.spec.isDeprecated, - migrate: async (state: UrlGeneratorStateMapping[Id]['State']) => { - if (!this.spec.isDeprecated) { - throw new Error( - i18n.translate('share.urlGenerators.error.migrateCalledNotDeprecated', { - defaultMessage: 'You cannot call migrate on a non-deprecated generator.', - }) - ); - } - - return this.spec.migrate!(state); - }, }; } } diff --git a/src/plugins/share/public/url_generators/url_generator_service.test.ts b/src/plugins/share/public/url_generators/url_generator_service.test.ts index cb70f1af2c195..c07aa3f915b2e 100644 --- a/src/plugins/share/public/url_generators/url_generator_service.test.ts +++ b/src/plugins/share/public/url_generators/url_generator_service.test.ts @@ -29,12 +29,8 @@ test('Registering and retrieving a generator', async () => { "createUrl": [Function], "id": "TEST_GENERATOR", "isDeprecated": false, - "migrate": [Function], } `); - await expect(generator.migrate({})).rejects.toEqual( - new Error('You cannot call migrate on a non-deprecated generator.') - ); expect(await generator.createUrl({})).toBe('myurl'); const retrievedGenerator = start.getUrlGenerator('TEST_GENERATOR'); @@ -43,12 +39,8 @@ test('Registering and retrieving a generator', async () => { "createUrl": [Function], "id": "TEST_GENERATOR", "isDeprecated": false, - "migrate": [Function], } `); - await expect(generator.migrate({})).rejects.toEqual( - new Error('You cannot call migrate on a non-deprecated generator.') - ); expect(await generator.createUrl({})).toBe('myurl'); }); @@ -124,6 +116,5 @@ test('Generator returns migrated url', async () => { const generator = start.getUrlGenerator('v1'); expect(generator.isDeprecated).toBe(true); - expect(await generator.migrate({ bar: 'hi' })).toEqual({ id: 'v2', state: { foo: 'hi' } }); expect(await generator.createUrl({ bar: 'hi' })).toEqual('www.hi.com'); }); diff --git a/src/plugins/share/server/index.ts b/src/plugins/share/server/index.ts index d820a362131a4..73cd4cc89af70 100644 --- a/src/plugins/share/server/index.ts +++ b/src/plugins/share/server/index.ts @@ -9,7 +9,7 @@ import { PluginInitializerContext } from '../../../core/server'; import { SharePlugin } from './plugin'; -export { SharePluginSetup, SharePluginStart } from './plugin'; +export type { SharePluginSetup, SharePluginStart } from './plugin'; export { CSV_QUOTE_VALUES_SETTING, CSV_SEPARATOR_SETTING } from '../common/constants'; diff --git a/src/plugins/ui_actions/public/index.ts b/src/plugins/ui_actions/public/index.ts index 0804ed43cbe10..8a6b7ed931490 100644 --- a/src/plugins/ui_actions/public/index.ts +++ b/src/plugins/ui_actions/public/index.ts @@ -13,33 +13,29 @@ export function plugin(initializerContext: PluginInitializerContext) { return new UiActionsPlugin(initializerContext); } -export { UiActionsSetup, UiActionsStart } from './plugin'; -export { UiActionsServiceParams, UiActionsService } from './service'; -export { - Action, - ActionDefinition as UiActionsActionDefinition, - createAction, - IncompatibleActionError, -} from './actions'; +export type { UiActionsSetup, UiActionsStart } from './plugin'; +export type { UiActionsServiceParams } from './service'; +export { UiActionsService } from './service'; +export type { Action, ActionDefinition as UiActionsActionDefinition } from './actions'; +export { createAction, IncompatibleActionError } from './actions'; export { buildContextMenuForActions } from './context_menu'; -export { +export type { Presentable as UiActionsPresentable, PresentableGrouping as UiActionsPresentableGrouping, } from './util'; +export type { Trigger, RowClickContext } from './triggers'; export { - Trigger, VISUALIZE_FIELD_TRIGGER, visualizeFieldTrigger, VISUALIZE_GEO_FIELD_TRIGGER, visualizeGeoFieldTrigger, ROW_CLICK_TRIGGER, rowClickTrigger, - RowClickContext, } from './triggers'; +export type { VisualizeFieldContext } from './types'; export { - VisualizeFieldContext, ACTION_VISUALIZE_FIELD, ACTION_VISUALIZE_GEO_FIELD, ACTION_VISUALIZE_LENS_FIELD, } from './types'; -export { ActionExecutionContext, ActionExecutionMeta } from './actions'; +export type { ActionExecutionContext, ActionExecutionMeta } from './actions'; diff --git a/src/plugins/vis_default_editor/public/components/options/index.ts b/src/plugins/vis_default_editor/public/components/options/index.ts index 62ce76014f9fc..4d45da690c3c8 100644 --- a/src/plugins/vis_default_editor/public/components/options/index.ts +++ b/src/plugins/vis_default_editor/public/components/options/index.ts @@ -9,8 +9,10 @@ export { BasicOptions } from './basic_options'; export { SwitchOption } from './switch'; export { SelectOption } from './select'; -export { ColorRanges, SetColorRangeValue } from './color_ranges'; -export { ColorSchemaOptions, SetColorSchemaOptionsValue } from './color_schema'; +export type { SetColorRangeValue } from './color_ranges'; +export { ColorRanges } from './color_ranges'; +export type { SetColorSchemaOptionsValue } from './color_schema'; +export { ColorSchemaOptions } from './color_schema'; export { NumberInputOption } from './number_input'; export { RangeOption } from './range'; export { RequiredNumberInputOption } from './required_number_input'; diff --git a/src/plugins/vis_default_editor/public/index.ts b/src/plugins/vis_default_editor/public/index.ts index ec1f514b9f2ff..d89a898467b98 100644 --- a/src/plugins/vis_default_editor/public/index.ts +++ b/src/plugins/vis_default_editor/public/index.ts @@ -17,7 +17,8 @@ export { DefaultEditorController }; export { useValidation } from './components/controls/utils'; export { PalettePicker } from './components/controls/palette_picker'; export * from './components/options'; -export { RangesParamEditor, RangeValues } from './components/controls/ranges'; +export type { RangeValues } from './components/controls/ranges'; +export { RangesParamEditor } from './components/controls/ranges'; export * from './editor_size'; export * from './utils'; diff --git a/src/plugins/vis_types/pie/public/index.ts b/src/plugins/vis_types/pie/public/index.ts index adf8b2d073f39..d7c5e9a2dfb2a 100644 --- a/src/plugins/vis_types/pie/public/index.ts +++ b/src/plugins/vis_types/pie/public/index.ts @@ -9,6 +9,6 @@ import { VisTypePiePlugin } from './plugin'; export { pieVisType } from './vis_type'; -export { Dimensions, Dimension } from './types'; +export type { Dimensions, Dimension } from './types'; export const plugin = () => new VisTypePiePlugin(); diff --git a/src/plugins/vis_types/table/common/index.ts b/src/plugins/vis_types/table/common/index.ts index ad8e27c95a5ec..c5737c58fdbb3 100644 --- a/src/plugins/vis_types/table/common/index.ts +++ b/src/plugins/vis_types/table/common/index.ts @@ -6,4 +6,5 @@ * Side Public License, v 1. */ -export { AggTypes, TableVisParams, VIS_TYPE_TABLE } from './types'; +export type { TableVisParams } from './types'; +export { AggTypes, VIS_TYPE_TABLE } from './types'; diff --git a/src/plugins/vis_types/timelion/public/index.ts b/src/plugins/vis_types/timelion/public/index.ts index 8161f844e8f73..960eda3dc558f 100644 --- a/src/plugins/vis_types/timelion/public/index.ts +++ b/src/plugins/vis_types/timelion/public/index.ts @@ -13,4 +13,4 @@ export function plugin(initializerContext: PluginInitializerContext) { return new Plugin(initializerContext); } -export { VisTypeTimelionPluginStart } from './plugin'; +export type { VisTypeTimelionPluginStart } from './plugin'; diff --git a/src/plugins/vis_types/timelion/server/types.ts b/src/plugins/vis_types/timelion/server/types.ts index 06b6afa613b06..0cbf2b0882089 100644 --- a/src/plugins/vis_types/timelion/server/types.ts +++ b/src/plugins/vis_types/timelion/server/types.ts @@ -6,4 +6,7 @@ * Side Public License, v 1. */ -export { TimelionFunctionInterface, TimelionFunctionConfig } from './lib/classes/timelion_function'; +export type { + TimelionFunctionInterface, + TimelionFunctionConfig, +} from './lib/classes/timelion_function'; diff --git a/src/plugins/vis_types/timeseries/common/types/index.ts b/src/plugins/vis_types/timeseries/common/types/index.ts index 123b6723d8ccd..5e04fee0d015c 100644 --- a/src/plugins/vis_types/timeseries/common/types/index.ts +++ b/src/plugins/vis_types/timeseries/common/types/index.ts @@ -9,8 +9,8 @@ import { Filter, IndexPattern, Query } from '../../../../data/common'; import { Panel } from './panel_model'; -export { Metric, Series, Panel, MetricType } from './panel_model'; -export { TimeseriesVisData, PanelData, SeriesData, TableData } from './vis_data'; +export type { Metric, Series, Panel, MetricType } from './panel_model'; +export type { TimeseriesVisData, PanelData, SeriesData, TableData } from './vis_data'; export interface FetchedIndexPattern { indexPattern: IndexPattern | undefined | null; diff --git a/src/plugins/vis_types/timeseries/public/application/components/lib/index_pattern_select/index.ts b/src/plugins/vis_types/timeseries/public/application/components/lib/index_pattern_select/index.ts index 4920677a04a2e..24b49ca8f4d47 100644 --- a/src/plugins/vis_types/timeseries/public/application/components/lib/index_pattern_select/index.ts +++ b/src/plugins/vis_types/timeseries/public/application/components/lib/index_pattern_select/index.ts @@ -6,4 +6,5 @@ * Side Public License, v 1. */ -export { IndexPatternSelect, IndexPatternSelectProps } from './index_pattern_select'; +export type { IndexPatternSelectProps } from './index_pattern_select'; +export { IndexPatternSelect } from './index_pattern_select'; diff --git a/src/plugins/vis_types/timeseries/server/index.ts b/src/plugins/vis_types/timeseries/server/index.ts index 7a10740a53d32..d6b1174177bb6 100644 --- a/src/plugins/vis_types/timeseries/server/index.ts +++ b/src/plugins/vis_types/timeseries/server/index.ts @@ -10,7 +10,7 @@ import { PluginInitializerContext, PluginConfigDescriptor } from 'src/core/serve import { VisTypeTimeseriesConfig, config as configSchema } from './config'; import { VisTypeTimeseriesPlugin } from './plugin'; -export { VisTypeTimeseriesSetup } from './plugin'; +export type { VisTypeTimeseriesSetup } from './plugin'; export const config: PluginConfigDescriptor = { schema: configSchema, @@ -20,5 +20,5 @@ export function plugin(initializerContext: PluginInitializerContext) { return new VisTypeTimeseriesPlugin(initializerContext); } -export { TimeseriesVisData } from '../common/types'; +export type { TimeseriesVisData } from '../common/types'; export { isVisSeriesData, isVisTableData } from '../common/vis_data_utils'; diff --git a/src/plugins/vis_types/vega/public/vega_inspector/index.ts b/src/plugins/vis_types/vega/public/vega_inspector/index.ts index e79d2ee356aef..72dc539dc2ea7 100644 --- a/src/plugins/vis_types/vega/public/vega_inspector/index.ts +++ b/src/plugins/vis_types/vega/public/vega_inspector/index.ts @@ -6,8 +6,5 @@ * Side Public License, v 1. */ -export { - createInspectorAdapters, - getVegaInspectorView, - VegaInspectorAdapters, -} from './vega_inspector'; +export type { VegaInspectorAdapters } from './vega_inspector'; +export { createInspectorAdapters, getVegaInspectorView } from './vega_inspector'; diff --git a/src/plugins/vis_types/vega/server/index.ts b/src/plugins/vis_types/vega/server/index.ts index 9c448f6c618d3..62bc9a1494acf 100644 --- a/src/plugins/vis_types/vega/server/index.ts +++ b/src/plugins/vis_types/vega/server/index.ts @@ -22,4 +22,4 @@ export function plugin(initializerContext: PluginInitializerContext) { return new VisTypeVegaPlugin(initializerContext); } -export { VisTypeVegaPluginStart, VisTypeVegaPluginSetup } from './types'; +export type { VisTypeVegaPluginStart, VisTypeVegaPluginSetup } from './types'; diff --git a/src/plugins/vis_types/xy/public/editor/components/common/index.ts b/src/plugins/vis_types/xy/public/editor/components/common/index.ts index 5eec1fff7b7a6..5a91629c50611 100644 --- a/src/plugins/vis_types/xy/public/editor/components/common/index.ts +++ b/src/plugins/vis_types/xy/public/editor/components/common/index.ts @@ -7,4 +7,5 @@ */ export { TruncateLabelsOption } from './truncate_labels'; -export { ValidationWrapper, ValidationVisOptionsProps } from './validation_wrapper'; +export type { ValidationVisOptionsProps } from './validation_wrapper'; +export { ValidationWrapper } from './validation_wrapper'; diff --git a/src/plugins/vis_types/xy/public/expression_functions/index.ts b/src/plugins/vis_types/xy/public/expression_functions/index.ts index 32c50e3adff1e..4d6b2305a3651 100644 --- a/src/plugins/vis_types/xy/public/expression_functions/index.ts +++ b/src/plugins/vis_types/xy/public/expression_functions/index.ts @@ -8,10 +8,17 @@ export { visTypeXyVisFn } from './xy_vis_fn'; -export { categoryAxis, ExpressionValueCategoryAxis } from './category_axis'; -export { timeMarker, ExpressionValueTimeMarker } from './time_marker'; -export { valueAxis, ExpressionValueValueAxis } from './value_axis'; -export { seriesParam, ExpressionValueSeriesParam } from './series_param'; -export { thresholdLine, ExpressionValueThresholdLine } from './threshold_line'; -export { label, ExpressionValueLabel } from './label'; -export { visScale, ExpressionValueScale } from './vis_scale'; +export type { ExpressionValueCategoryAxis } from './category_axis'; +export { categoryAxis } from './category_axis'; +export type { ExpressionValueTimeMarker } from './time_marker'; +export { timeMarker } from './time_marker'; +export type { ExpressionValueValueAxis } from './value_axis'; +export { valueAxis } from './value_axis'; +export type { ExpressionValueSeriesParam } from './series_param'; +export { seriesParam } from './series_param'; +export type { ExpressionValueThresholdLine } from './threshold_line'; +export { thresholdLine } from './threshold_line'; +export type { ExpressionValueLabel } from './label'; +export { label } from './label'; +export type { ExpressionValueScale } from './vis_scale'; +export { visScale } from './vis_scale'; diff --git a/src/plugins/vis_types/xy/public/index.ts b/src/plugins/vis_types/xy/public/index.ts index 1ee96fab35253..41a8e08fa1ad2 100644 --- a/src/plugins/vis_types/xy/public/index.ts +++ b/src/plugins/vis_types/xy/public/index.ts @@ -11,11 +11,11 @@ import { VisTypeXyPlugin as Plugin } from './plugin'; -export { VisTypeXyPluginSetup } from './plugin'; +export type { VisTypeXyPluginSetup } from './plugin'; // TODO: Remove when vis_type_vislib is removed // https://github.com/elastic/kibana/issues/56143 -export { +export type { CategoryAxis, ThresholdLine, ValueAxis, @@ -23,9 +23,8 @@ export { SeriesParam, Dimension, Dimensions, - ScaleType, - AxisType, } from './types'; +export { ScaleType, AxisType } from './types'; export type { ValidationVisOptionsProps } from './editor/components/common/validation_wrapper'; export { TruncateLabelsOption } from './editor/components/common/truncate_labels'; export { getPositions } from './editor/positions'; diff --git a/src/plugins/visualizations/public/index.ts b/src/plugins/visualizations/public/index.ts index e6ea3cd489556..8ae0c426689ac 100644 --- a/src/plugins/visualizations/public/index.ts +++ b/src/plugins/visualizations/public/index.ts @@ -22,17 +22,17 @@ export { VisualizationContainer } from './components'; export { getVisSchemas } from './vis_schemas'; /** @public types */ -export { VisualizationsSetup, VisualizationsStart }; +export type { VisualizationsSetup, VisualizationsStart }; export { VisGroups } from './vis_types/vis_groups_enum'; export type { BaseVisType, VisTypeAlias, VisTypeDefinition, Schema, ISchemas } from './vis_types'; export type { Vis, SerializedVis, SerializedVisData, VisData } from './vis'; export type VisualizeEmbeddableFactoryContract = PublicContract; export type VisualizeEmbeddableContract = PublicContract; -export { VisualizeInput } from './embeddable'; -export { SchemaConfig } from './vis_schemas'; +export type { VisualizeInput } from './embeddable'; +export type { SchemaConfig } from './vis_schemas'; export { updateOldState } from './legacy/vis_update_state'; export type { PersistedState } from './persisted_state'; -export { +export type { ISavedVis, VisSavedObject, VisToExpressionAst, @@ -40,11 +40,15 @@ export { VisEditorOptionsProps, GetVisOptions, } from './types'; -export { VisualizationListItem, VisualizationStage } from './vis_types/vis_type_alias_registry'; +export type { + VisualizationListItem, + VisualizationStage, +} from './vis_types/vis_type_alias_registry'; export { VISUALIZE_ENABLE_LABS_SETTING } from '../common/constants'; -export { SavedVisState, VisParams, prepareLogTable, Dimension } from '../common'; -export { ExpressionValueVisDimension } from '../common/expression_functions/vis_dimension'; -export { +export type { SavedVisState, VisParams, Dimension } from '../common'; +export { prepareLogTable } from '../common'; +export type { ExpressionValueVisDimension } from '../common/expression_functions/vis_dimension'; +export type { ExpressionValueXYDimension, DateHistogramParams, FakeParams, diff --git a/src/plugins/visualizations/public/vis_types/types_service.ts b/src/plugins/visualizations/public/vis_types/types_service.ts index 567da272dfd0a..ae8ba8b8ad518 100644 --- a/src/plugins/visualizations/public/vis_types/types_service.ts +++ b/src/plugins/visualizations/public/vis_types/types_service.ts @@ -110,4 +110,4 @@ export type TypesSetup = ReturnType; export type TypesStart = ReturnType; /** @public types */ -export { VisTypeAlias }; +export type { VisTypeAlias }; diff --git a/src/plugins/visualizations/server/index.ts b/src/plugins/visualizations/server/index.ts index d093a6829f307..f10caf44b3ccd 100644 --- a/src/plugins/visualizations/server/index.ts +++ b/src/plugins/visualizations/server/index.ts @@ -18,4 +18,4 @@ export function plugin(initializerContext: PluginInitializerContext) { return new VisualizationsPlugin(initializerContext); } -export { VisualizationsPluginSetup, VisualizationsPluginStart } from './types'; +export type { VisualizationsPluginSetup, VisualizationsPluginStart } from './types'; diff --git a/src/plugins/visualize/public/application/types.ts b/src/plugins/visualize/public/application/types.ts index e77520c962d88..b15b521f6251d 100644 --- a/src/plugins/visualize/public/application/types.ts +++ b/src/plugins/visualize/public/application/types.ts @@ -145,4 +145,4 @@ export interface EditorRenderProps { linked: boolean; } -export { PureVisState }; +export type { PureVisState }; diff --git a/src/plugins/visualize/public/index.ts b/src/plugins/visualize/public/index.ts index ff1b2ba4c3bf5..dd77987f6a722 100644 --- a/src/plugins/visualize/public/index.ts +++ b/src/plugins/visualize/public/index.ts @@ -11,9 +11,9 @@ import { VisualizePlugin, VisualizePluginSetup } from './plugin'; export { VisualizeConstants } from './application/visualize_constants'; -export { IEditorController, EditorRenderProps } from './application/types'; +export type { IEditorController, EditorRenderProps } from './application/types'; -export { VisualizePluginSetup }; +export type { VisualizePluginSetup }; export const plugin = (context: PluginInitializerContext) => { return new VisualizePlugin(context); diff --git a/test/api_integration/apis/custom_integration/integrations.ts b/test/api_integration/apis/custom_integration/integrations.ts index 0784a86e4b546..036eb2ef33c78 100644 --- a/test/api_integration/apis/custom_integration/integrations.ts +++ b/test/api_integration/apis/custom_integration/integrations.ts @@ -22,7 +22,7 @@ export default function ({ getService }: FtrProviderContext) { expect(resp.body).to.be.an('array'); - expect(resp.body.length).to.be(33); + expect(resp.body.length).to.be(34); // Test for sample data card expect(resp.body.findIndex((c: { id: string }) => c.id === 'sample_data_all')).to.be.above( @@ -40,7 +40,7 @@ export default function ({ getService }: FtrProviderContext) { expect(resp.body).to.be.an('array'); - expect(resp.body.length).to.be.above(109); // at least the beats + apm + expect(resp.body.length).to.be(109); // the beats }); }); }); diff --git a/test/functional/apps/discover/_discover.ts b/test/functional/apps/discover/_discover.ts index 0a8f56ee250ea..8374ccbc389f7 100644 --- a/test/functional/apps/discover/_discover.ts +++ b/test/functional/apps/discover/_discover.ts @@ -28,16 +28,16 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { describe('discover test', function describeIndexTests() { before(async function () { log.debug('load kibana index with default index pattern'); - - await kibanaServer.importExport.load('test/functional/fixtures/kbn_archiver/discover.json'); - + await kibanaServer.importExport.load('test/functional/fixtures/kbn_archiver/discover'); // and load a set of makelogs data await esArchiver.loadIfNeeded('test/functional/fixtures/es_archiver/logstash_functional'); await kibanaServer.uiSettings.replace(defaultSettings); await PageObjects.common.navigateToApp('discover'); await PageObjects.timePicker.setDefaultAbsoluteRange(); }); - + after(async () => { + await kibanaServer.savedObjects.clean({ types: ['search', 'index-pattern'] }); + }); describe('query', function () { const queryName1 = 'Query # 1'; diff --git a/test/functional/page_objects/common_page.ts b/test/functional/page_objects/common_page.ts index a40465b00dbeb..69fbf7e49df3c 100644 --- a/test/functional/page_objects/common_page.ts +++ b/test/functional/page_objects/common_page.ts @@ -11,6 +11,7 @@ import expect from '@kbn/expect'; // @ts-ignore import fetch from 'node-fetch'; import { getUrl } from '@kbn/test'; +import moment from 'moment'; import { FtrService } from '../ftr_provider_context'; interface NavigateProps { @@ -502,11 +503,47 @@ export class CommonPageObject extends FtrService { } } - async setTime(time: { from: string; to: string }) { - await this.kibanaServer.uiSettings.replace({ 'timepicker:timeDefaults': JSON.stringify(time) }); + /** + * Due to a warning thrown, documented at: + * https://github.com/elastic/kibana/pull/114997#issuecomment-950823874 + * this fn formats time in a format specified, or defaulted + * to the same format in + * [getTimeDurationInHours()](https://github.com/elastic/kibana/blob/main/test/functional/page_objects/time_picker.ts#L256) + * @param time + * @param fmt + */ + formatTime(time: TimeStrings, fmt: string = 'MMM D, YYYY @ HH:mm:ss.SSS') { + return Object.keys(time) + .map((x) => moment(time[x], [fmt]).format()) + .reduce( + (acc, curr, idx) => { + if (idx === 0) acc.from = curr; + acc.to = curr; + return acc; + }, + { from: '', to: '' } + ); + } + + /** + * Previously, many tests were using the time picker. + * To speed things up, we are now setting time here. + * The formatting fn is called here, such that the tests + * that were using the time picker can use the same time + * parameters as before, but they are auto-formatted. + * @param time + */ + async setTime(time: TimeStrings) { + await this.kibanaServer.uiSettings.replace({ + 'timepicker:timeDefaults': JSON.stringify(this.formatTime(time)), + }); } async unsetTime() { await this.kibanaServer.uiSettings.unset('timepicker:timeDefaults'); } } +export interface TimeStrings extends Record { + from: string; + to: string; +} diff --git a/test/functional/services/common/index.ts b/test/functional/services/common/index.ts index 95f58027fd5fb..c5f442c191543 100644 --- a/test/functional/services/common/index.ts +++ b/test/functional/services/common/index.ts @@ -6,7 +6,8 @@ * Side Public License, v 1. */ -export { BrowserProvider, Browser } from './browser'; +export type { Browser } from './browser'; +export { BrowserProvider } from './browser'; export { FailureDebuggingProvider } from './failure_debugging'; export { FindProvider } from './find'; export { ScreenshotsService } from './screenshots'; diff --git a/test/interpreter_functional/plugins/kbn_tp_run_pipeline/public/index.ts b/test/interpreter_functional/plugins/kbn_tp_run_pipeline/public/index.ts index 22afda2fdce1b..897fbf832d561 100644 --- a/test/interpreter_functional/plugins/kbn_tp_run_pipeline/public/index.ts +++ b/test/interpreter_functional/plugins/kbn_tp_run_pipeline/public/index.ts @@ -8,7 +8,7 @@ import { PluginInitializer, PluginInitializerContext } from 'src/core/public'; import { Plugin, StartDeps } from './plugin'; -export { StartDeps }; +export type { StartDeps }; export const plugin: PluginInitializer = ( initializerContext: PluginInitializerContext diff --git a/test/interpreter_functional/plugins/kbn_tp_run_pipeline/public/types.ts b/test/interpreter_functional/plugins/kbn_tp_run_pipeline/public/types.ts index a9b597ebf1e05..02872843cf8bc 100644 --- a/test/interpreter_functional/plugins/kbn_tp_run_pipeline/public/types.ts +++ b/test/interpreter_functional/plugins/kbn_tp_run_pipeline/public/types.ts @@ -9,4 +9,5 @@ import { ExpressionsStart, ExpressionRenderHandler } from 'src/plugins/expressions/public'; import { Adapters } from 'src/plugins/inspector/public'; -export { ExpressionsStart, ExpressionRenderHandler, Adapters }; +export type { ExpressionsStart, Adapters }; +export { ExpressionRenderHandler }; diff --git a/test/plugin_functional/plugins/core_plugin_a/server/index.ts b/test/plugin_functional/plugins/core_plugin_a/server/index.ts index f4b9f96f1bcdd..7fad3cf7a9e3b 100644 --- a/test/plugin_functional/plugins/core_plugin_a/server/index.ts +++ b/test/plugin_functional/plugins/core_plugin_a/server/index.ts @@ -7,6 +7,6 @@ */ import { CorePluginAPlugin } from './plugin'; -export { PluginAApiRequestContext } from './plugin'; +export type { PluginAApiRequestContext } from './plugin'; export const plugin = () => new CorePluginAPlugin(); diff --git a/typings/@elastic/eui/index.d.ts b/typings/@elastic/eui/index.d.ts index f5baf73df7057..814a386a3b5e7 100644 --- a/typings/@elastic/eui/index.d.ts +++ b/typings/@elastic/eui/index.d.ts @@ -11,7 +11,3 @@ declare module '@elastic/eui/lib/services' { export const RIGHT_ALIGNMENT: any; } - -declare module '@elastic/eui/lib/services/format' { - export const dateFormatAliases: any; -} diff --git a/typings/accept.d.ts b/typings/accept.d.ts deleted file mode 100644 index e868063c7f7c0..0000000000000 --- a/typings/accept.d.ts +++ /dev/null @@ -1,12 +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 - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -declare module 'accept' { - // @types/accept does not include the `preferences` argument so we override the type to include it - export function encodings(encodingHeader?: string, preferences?: string[]): string[]; -} diff --git a/typings/js_levenshtein.d.ts b/typings/js_levenshtein.d.ts deleted file mode 100644 index 7c934333dbc7b..0000000000000 --- a/typings/js_levenshtein.d.ts +++ /dev/null @@ -1,12 +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 - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -declare module 'js-levenshtein' { - const levenshtein: (a: string, b: string) => number; - export = levenshtein; -} diff --git a/x-pack/examples/reporting_example/common/index.ts b/x-pack/examples/reporting_example/common/index.ts index 893bd4dee8ae1..991ec30a03b14 100644 --- a/x-pack/examples/reporting_example/common/index.ts +++ b/x-pack/examples/reporting_example/common/index.ts @@ -8,10 +8,7 @@ export const PLUGIN_ID = 'reportingExample'; export const PLUGIN_NAME = 'reportingExample'; -export { MyForwardableState } from './types'; +export type { MyForwardableState } from './types'; -export { - REPORTING_EXAMPLE_LOCATOR_ID, - ReportingExampleLocatorDefinition, - ReportingExampleLocatorParams, -} from './locator'; +export type { ReportingExampleLocatorParams } from './locator'; +export { REPORTING_EXAMPLE_LOCATOR_ID, ReportingExampleLocatorDefinition } from './locator'; diff --git a/x-pack/examples/reporting_example/public/containers/main.tsx b/x-pack/examples/reporting_example/public/containers/main.tsx index 8673c476fdc7b..e3f45b4359556 100644 --- a/x-pack/examples/reporting_example/public/containers/main.tsx +++ b/x-pack/examples/reporting_example/public/containers/main.tsx @@ -34,9 +34,12 @@ import { BrowserRouter as Router, useHistory } from 'react-router-dom'; import * as Rx from 'rxjs'; import { takeWhile } from 'rxjs/operators'; import { ScreenshotModePluginSetup } from 'src/plugins/screenshot_mode/public'; +import type { + JobAppParamsPDF, + JobParamsPDFV2, + JobParamsPNGV2, +} from '../../../../plugins/reporting/public'; import { constants, ReportingStart } from '../../../../plugins/reporting/public'; -import type { JobParamsPDFV2 } from '../../../../plugins/reporting/server/export_types/printable_pdf_v2/types'; -import type { JobParamsPNGV2 } from '../../../../plugins/reporting/server/export_types/png_v2/types'; import { REPORTING_EXAMPLE_LOCATOR_ID } from '../../common'; @@ -81,7 +84,7 @@ export const Main = ({ basename, reporting, screenshotMode }: ReportingExampleAp }); }); - const getPDFJobParamsDefault = () => { + const getPDFJobParamsDefault = (): JobAppParamsPDF => { return { layout: { id: constants.LAYOUT_TYPES.PRESERVE_LAYOUT, diff --git a/x-pack/examples/reporting_example/public/index.ts b/x-pack/examples/reporting_example/public/index.ts index f9f749e2b0cd0..c4c0a9b48f2cb 100644 --- a/x-pack/examples/reporting_example/public/index.ts +++ b/x-pack/examples/reporting_example/public/index.ts @@ -10,4 +10,4 @@ import { ReportingExamplePlugin } from './plugin'; export function plugin() { return new ReportingExamplePlugin(); } -export { PluginSetup, PluginStart } from './types'; +export type { PluginSetup, PluginStart } from './types'; diff --git a/x-pack/examples/ui_actions_enhanced_examples/public/drilldowns/dashboard_to_discover_drilldown/index.ts b/x-pack/examples/ui_actions_enhanced_examples/public/drilldowns/dashboard_to_discover_drilldown/index.ts index f6e1f28864140..f6c6f48e1774c 100644 --- a/x-pack/examples/ui_actions_enhanced_examples/public/drilldowns/dashboard_to_discover_drilldown/index.ts +++ b/x-pack/examples/ui_actions_enhanced_examples/public/drilldowns/dashboard_to_discover_drilldown/index.ts @@ -6,11 +6,9 @@ */ export { SAMPLE_DASHBOARD_TO_DISCOVER_DRILLDOWN } from './constants'; -export { - DashboardToDiscoverDrilldown, - Params as DashboardToDiscoverDrilldownParams, -} from './drilldown'; -export { +export type { Params as DashboardToDiscoverDrilldownParams } from './drilldown'; +export { DashboardToDiscoverDrilldown } from './drilldown'; +export type { ActionContext as DashboardToDiscoverActionContext, Config as DashboardToDiscoverConfig, } from './types'; diff --git a/x-pack/plugins/actions/server/builtin_action_types/index.ts b/x-pack/plugins/actions/server/builtin_action_types/index.ts index 3351a36b38344..9988e951ae86d 100644 --- a/x-pack/plugins/actions/server/builtin_action_types/index.ts +++ b/x-pack/plugins/actions/server/builtin_action_types/index.ts @@ -25,36 +25,30 @@ import { getActionType as getJiraActionType } from './jira'; import { getActionType as getResilientActionType } from './resilient'; import { getActionType as getTeamsActionType } from './teams'; import { ENABLE_ITOM } from '../constants/connectors'; -export { ActionParamsType as EmailActionParams, ActionTypeId as EmailActionTypeId } from './email'; +export type { ActionParamsType as EmailActionParams } from './email'; +export { ActionTypeId as EmailActionTypeId } from './email'; +export type { ActionParamsType as IndexActionParams } from './es_index'; +export { ActionTypeId as IndexActionTypeId } from './es_index'; +export type { ActionParamsType as PagerDutyActionParams } from './pagerduty'; +export { ActionTypeId as PagerDutyActionTypeId } from './pagerduty'; +export type { ActionParamsType as ServerLogActionParams } from './server_log'; +export { ActionTypeId as ServerLogActionTypeId } from './server_log'; +export type { ActionParamsType as SlackActionParams } from './slack'; +export { ActionTypeId as SlackActionTypeId } from './slack'; +export type { ActionParamsType as WebhookActionParams } from './webhook'; +export { ActionTypeId as WebhookActionTypeId } from './webhook'; +export type { ActionParamsType as ServiceNowActionParams } from './servicenow'; export { - ActionParamsType as IndexActionParams, - ActionTypeId as IndexActionTypeId, -} from './es_index'; -export { - ActionParamsType as PagerDutyActionParams, - ActionTypeId as PagerDutyActionTypeId, -} from './pagerduty'; -export { - ActionParamsType as ServerLogActionParams, - ActionTypeId as ServerLogActionTypeId, -} from './server_log'; -export { ActionParamsType as SlackActionParams, ActionTypeId as SlackActionTypeId } from './slack'; -export { - ActionParamsType as WebhookActionParams, - ActionTypeId as WebhookActionTypeId, -} from './webhook'; -export { - ActionParamsType as ServiceNowActionParams, ServiceNowITSMActionTypeId, ServiceNowSIRActionTypeId, ServiceNowITOMActionTypeId, } from './servicenow'; -export { ActionParamsType as JiraActionParams, ActionTypeId as JiraActionTypeId } from './jira'; -export { - ActionParamsType as ResilientActionParams, - ActionTypeId as ResilientActionTypeId, -} from './resilient'; -export { ActionParamsType as TeamsActionParams, ActionTypeId as TeamsActionTypeId } from './teams'; +export type { ActionParamsType as JiraActionParams } from './jira'; +export { ActionTypeId as JiraActionTypeId } from './jira'; +export type { ActionParamsType as ResilientActionParams } from './resilient'; +export { ActionTypeId as ResilientActionTypeId } from './resilient'; +export type { ActionParamsType as TeamsActionParams } from './teams'; +export { ActionTypeId as TeamsActionTypeId } from './teams'; export function registerBuiltInActionTypes({ actionsConfigUtils: configurationUtilities, diff --git a/x-pack/plugins/actions/server/lib/errors/index.ts b/x-pack/plugins/actions/server/lib/errors/index.ts index e4035213359a3..bae42db6dd1e9 100644 --- a/x-pack/plugins/actions/server/lib/errors/index.ts +++ b/x-pack/plugins/actions/server/lib/errors/index.ts @@ -13,4 +13,5 @@ export function isErrorThatHandlesItsOwnResponse( return typeof (e as ErrorThatHandlesItsOwnResponse).sendResponse === 'function'; } -export { ActionTypeDisabledError, ActionTypeDisabledReason } from './action_type_disabled'; +export type { ActionTypeDisabledReason } from './action_type_disabled'; +export { ActionTypeDisabledError } from './action_type_disabled'; diff --git a/x-pack/plugins/actions/server/lib/index.ts b/x-pack/plugins/actions/server/lib/index.ts index c52a8b14ee6d8..d981b3bcc82e0 100644 --- a/x-pack/plugins/actions/server/lib/index.ts +++ b/x-pack/plugins/actions/server/lib/index.ts @@ -13,8 +13,10 @@ export { validateConnector, } from './validate_with_schema'; export { TaskRunnerFactory } from './task_runner_factory'; -export { ActionExecutor, ActionExecutorContract } from './action_executor'; -export { ILicenseState, LicenseState } from './license_state'; +export type { ActionExecutorContract } from './action_executor'; +export { ActionExecutor } from './action_executor'; +export type { ILicenseState } from './license_state'; +export { LicenseState } from './license_state'; export { verifyApiAccess } from './verify_api_access'; export { getActionTypeFeatureUsageName } from './get_action_type_feature_usage_name'; export { spaceIdToNamespace } from './space_id_to_namespace'; @@ -22,13 +24,10 @@ export { extractSavedObjectReferences, injectSavedObjectReferences, } from './action_task_params_utils'; +export type { ActionTypeDisabledReason } from './errors'; +export { ActionTypeDisabledError, isErrorThatHandlesItsOwnResponse } from './errors'; +export type { ActionExecutionSource } from './action_execution_source'; export { - ActionTypeDisabledError, - ActionTypeDisabledReason, - isErrorThatHandlesItsOwnResponse, -} from './errors'; -export { - ActionExecutionSource, asSavedObjectExecutionSource, isSavedObjectExecutionSource, asHttpRequestExecutionSource, diff --git a/x-pack/plugins/actions/server/types.ts b/x-pack/plugins/actions/server/types.ts index 627cd7028e5b1..9b7a8280cd27c 100644 --- a/x-pack/plugins/actions/server/types.ts +++ b/x-pack/plugins/actions/server/types.ts @@ -20,11 +20,11 @@ import { } from '../../../../src/core/server'; import { ActionTypeExecutorResult } from '../common'; import { TaskInfo } from './lib/action_executor'; -export { ActionTypeExecutorResult } from '../common'; -export { GetFieldsByIssueTypeResponse as JiraGetFieldsResponse } from './builtin_action_types/jira/types'; -export { GetCommonFieldsResponse as ServiceNowGetFieldsResponse } from './builtin_action_types/servicenow/types'; -export { GetCommonFieldsResponse as ResilientGetFieldsResponse } from './builtin_action_types/resilient/types'; -export { SwimlanePublicConfigurationType } from './builtin_action_types/swimlane/types'; +export type { ActionTypeExecutorResult } from '../common'; +export type { GetFieldsByIssueTypeResponse as JiraGetFieldsResponse } from './builtin_action_types/jira/types'; +export type { GetCommonFieldsResponse as ServiceNowGetFieldsResponse } from './builtin_action_types/servicenow/types'; +export type { GetCommonFieldsResponse as ResilientGetFieldsResponse } from './builtin_action_types/resilient/types'; +export type { SwimlanePublicConfigurationType } from './builtin_action_types/swimlane/types'; export type WithoutQueryAndParams = Pick>; export type GetServicesFunction = (request: KibanaRequest) => Services; export type ActionTypeRegistryContract = PublicMethodsOf; diff --git a/x-pack/plugins/alerting/server/alert_instance/index.ts b/x-pack/plugins/alerting/server/alert_instance/index.ts index c342c2f6bd051..7b5dd064c5dca 100644 --- a/x-pack/plugins/alerting/server/alert_instance/index.ts +++ b/x-pack/plugins/alerting/server/alert_instance/index.ts @@ -5,5 +5,6 @@ * 2.0. */ -export { AlertInstance, PublicAlertInstance } from './alert_instance'; +export type { PublicAlertInstance } from './alert_instance'; +export { AlertInstance } from './alert_instance'; export { createAlertInstanceFactory } from './create_alert_instance_factory'; diff --git a/x-pack/plugins/alerting/server/index.ts b/x-pack/plugins/alerting/server/index.ts index 2ddb6ff711c46..8ed91cc821412 100644 --- a/x-pack/plugins/alerting/server/index.ts +++ b/x-pack/plugins/alerting/server/index.ts @@ -30,9 +30,9 @@ export type { RuleParamsAndRefs, } from './types'; export { DEFAULT_MAX_EPHEMERAL_ACTIONS_PER_ALERT } from './config'; -export { PluginSetupContract, PluginStartContract } from './plugin'; -export { FindResult } from './rules_client'; -export { PublicAlertInstance as AlertInstance } from './alert_instance'; +export type { PluginSetupContract, PluginStartContract } from './plugin'; +export type { FindResult } from './rules_client'; +export type { PublicAlertInstance as AlertInstance } from './alert_instance'; export { parseDuration } from './lib'; export { getEsErrorMessage } from './lib/errors'; export { diff --git a/x-pack/plugins/alerting/server/lib/errors/index.ts b/x-pack/plugins/alerting/server/lib/errors/index.ts index 66db39916832a..36ca30bc95ba8 100644 --- a/x-pack/plugins/alerting/server/lib/errors/index.ts +++ b/x-pack/plugins/alerting/server/lib/errors/index.ts @@ -14,5 +14,7 @@ export function isErrorThatHandlesItsOwnResponse( return typeof (e as ErrorThatHandlesItsOwnResponse).sendResponse === 'function'; } -export { ErrorThatHandlesItsOwnResponse, ElasticsearchError, getEsErrorMessage }; -export { AlertTypeDisabledError, AlertTypeDisabledReason } from './alert_type_disabled'; +export type { ErrorThatHandlesItsOwnResponse, ElasticsearchError }; +export { getEsErrorMessage }; +export type { AlertTypeDisabledReason } from './alert_type_disabled'; +export { AlertTypeDisabledError } from './alert_type_disabled'; diff --git a/x-pack/plugins/alerting/server/lib/index.ts b/x-pack/plugins/alerting/server/lib/index.ts index ed55548307e7c..24f2513e1c650 100644 --- a/x-pack/plugins/alerting/server/lib/index.ts +++ b/x-pack/plugins/alerting/server/lib/index.ts @@ -6,18 +6,18 @@ */ export { parseDuration, validateDurationSchema } from '../../common/parse_duration'; -export { ILicenseState, LicenseState } from './license_state'; +export type { ILicenseState } from './license_state'; +export { LicenseState } from './license_state'; export { validateAlertTypeParams } from './validate_alert_type_params'; export { getAlertNotifyWhenType } from './get_alert_notify_when_type'; export { verifyApiAccess } from './license_api_access'; export { ErrorWithReason, getReasonFromError, isErrorWithReason } from './error_with_reason'; -export { - AlertTypeDisabledError, +export type { AlertTypeDisabledReason, ErrorThatHandlesItsOwnResponse, - isErrorThatHandlesItsOwnResponse, ElasticsearchError, } from './errors'; +export { AlertTypeDisabledError, isErrorThatHandlesItsOwnResponse } from './errors'; export { executionStatusFromState, executionStatusFromError, diff --git a/x-pack/plugins/alerting/server/routes/lib/index.ts b/x-pack/plugins/alerting/server/routes/lib/index.ts index dc8f3ac3b5de9..2c14660ae47de 100644 --- a/x-pack/plugins/alerting/server/routes/lib/index.ts +++ b/x-pack/plugins/alerting/server/routes/lib/index.ts @@ -11,6 +11,10 @@ export { isSecurityPluginDisabledError, } from './error_handler'; export { renameKeys } from './rename_keys'; -export { AsApiContract, RewriteRequestCase, RewriteResponseCase } from './rewrite_request_case'; +export type { + AsApiContract, + RewriteRequestCase, + RewriteResponseCase, +} from './rewrite_request_case'; export { verifyAccessAndContext } from './verify_access_and_context'; export { countUsageOfPredefinedIds } from './count_usage_of_predefined_ids'; diff --git a/x-pack/plugins/apm/dev_docs/routing_and_linking.md b/x-pack/plugins/apm/dev_docs/routing_and_linking.md index a1fdff3821c4c..1f6160a6c4a99 100644 --- a/x-pack/plugins/apm/dev_docs/routing_and_linking.md +++ b/x-pack/plugins/apm/dev_docs/routing_and_linking.md @@ -52,7 +52,7 @@ const { `useApmParams` will strip query parameters for which there is no validation. The route path should match exactly, but you can also use wildcards: `useApmParams('/*)`. In that case, the return type will be a union type of all possible matching routes. -Previously we used `useUrlParams` for path and query parameters, which we are trying to get away from. When possible, any usage of `useUrlParams` should be replaced by `useApmParams` or other custom hooks that use `useApmParams` internally. +Previously we used `useLegacyUrlParams` for path and query parameters, which we are trying to get away from. When possible, any usage of `useLegacyUrlParams` should be replaced by `useApmParams` or other custom hooks that use `useApmParams` internally. ## Linking diff --git a/x-pack/plugins/apm/dev_docs/testing.md b/x-pack/plugins/apm/dev_docs/testing.md index 95ba2467befcd..2a7533402ecca 100644 --- a/x-pack/plugins/apm/dev_docs/testing.md +++ b/x-pack/plugins/apm/dev_docs/testing.md @@ -27,7 +27,7 @@ API tests are separated in two suites: node scripts/test/api [--trial] [--help] ``` -The API tests are located in `x-pack/test/apm_api_integration/`. +The API tests are located in [`x-pack/test/apm_api_integration/`](/x-pack/test/apm_api_integration/). **API Test tips** @@ -43,11 +43,12 @@ The API tests are located in `x-pack/test/apm_api_integration/`. node scripts/test/e2e [--trial] [--help] ``` -The E2E tests are located [here](../ftr_e2e) +The E2E tests are located in [`x-pack/plugins/apm/ftr_e2e`](../ftr_e2e) --- ## Functional tests (Security and Correlations tests) + TODO: We could try moving this tests to the new e2e tests located at `x-pack/plugins/apm/ftr_e2e`. **Start server** @@ -66,10 +67,10 @@ APM tests are located in `x-pack/test/functional/apps/apm`. For debugging access Elasticsearch on http://localhost:9220` (elastic/changeme) diff --git a/x-pack/plugins/apm/scripts/test/README.md b/x-pack/plugins/apm/scripts/test/README.md - ## Storybook ### Start + ``` yarn storybook apm ``` @@ -77,6 +78,7 @@ yarn storybook apm All files with a .stories.tsx extension will be loaded. You can access the development environment at http://localhost:9001. ## Data generation + For end-to-end (e.g. agent -> apm server -> elasticsearch <- kibana) development and testing of Elastic APM please check the the [APM Integration Testing repository](https://github.com/elastic/apm-integration-testing). -Data can also be generated using the [elastic-apm-synthtrace](../../../../packages/elastic-apm-synthtrace/README.md) CLI. \ No newline at end of file +Data can also be generated using the [elastic-apm-synthtrace](../../../../packages/elastic-apm-synthtrace/README.md) CLI. diff --git a/x-pack/plugins/apm/ftr_e2e/cypress_open.ts b/x-pack/plugins/apm/ftr_e2e/cypress_open.ts deleted file mode 100644 index 3f7758b40b90d..0000000000000 --- a/x-pack/plugins/apm/ftr_e2e/cypress_open.ts +++ /dev/null @@ -1,20 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { FtrConfigProviderContext } from '@kbn/test'; -import { cypressOpenTests } from './cypress_start'; - -async function openE2ETests({ readConfigFile }: FtrConfigProviderContext) { - const kibanaConfig = await readConfigFile(require.resolve('./config.ts')); - return { - ...kibanaConfig.getAll(), - testRunner: cypressOpenTests, - }; -} - -// eslint-disable-next-line import/no-default-export -export default openE2ETests; diff --git a/x-pack/plugins/apm/ftr_e2e/cypress_run.ts b/x-pack/plugins/apm/ftr_e2e/cypress_run.ts deleted file mode 100644 index 16f93b39910f3..0000000000000 --- a/x-pack/plugins/apm/ftr_e2e/cypress_run.ts +++ /dev/null @@ -1,22 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ -import { argv } from 'yargs'; -import { FtrConfigProviderContext } from '@kbn/test'; -import { cypressRunTests } from './cypress_start'; - -const specArg = argv.spec as string | undefined; - -async function runE2ETests({ readConfigFile }: FtrConfigProviderContext) { - const kibanaConfig = await readConfigFile(require.resolve('./config.ts')); - return { - ...kibanaConfig.getAll(), - testRunner: cypressRunTests(specArg), - }; -} - -// eslint-disable-next-line import/no-default-export -export default runE2ETests; diff --git a/x-pack/plugins/apm/ftr_e2e/cypress_start.ts b/x-pack/plugins/apm/ftr_e2e/cypress_start.ts index 2d0be8c007089..c8ab216cbce5c 100644 --- a/x-pack/plugins/apm/ftr_e2e/cypress_start.ts +++ b/x-pack/plugins/apm/ftr_e2e/cypress_start.ts @@ -7,30 +7,16 @@ /* eslint-disable no-console */ +import { argv } from 'yargs'; import Url from 'url'; import cypress from 'cypress'; import { FtrProviderContext } from './ftr_provider_context'; import { createApmUsersAndRoles } from '../scripts/create-apm-users-and-roles/create_apm_users_and_roles'; import { esArchiverLoad, esArchiverUnload } from './cypress/tasks/es_archiver'; -export function cypressRunTests(spec?: string) { - return async ({ getService }: FtrProviderContext) => { - const result = await cypressStart(getService, cypress.run, spec); - - if (result && (result.status === 'failed' || result.totalFailed > 0)) { - throw new Error(`APM Cypress tests failed`); - } - }; -} - -export async function cypressOpenTests({ getService }: FtrProviderContext) { - await cypressStart(getService, cypress.open); -} - -async function cypressStart( +export async function cypressStart( getService: FtrProviderContext['getService'], - cypressExecution: typeof cypress.run | typeof cypress.open, - spec?: string + cypressExecution: typeof cypress.run | typeof cypress.open ) { const config = getService('config'); @@ -68,8 +54,9 @@ async function cypressStart( console.log(`Loading ES archive "${archiveName}"`); await esArchiverLoad(archiveName); + const spec = argv.grep as string | undefined; const res = await cypressExecution({ - ...(spec !== undefined ? { spec } : {}), + ...(spec ? { spec } : {}), config: { baseUrl: kibanaUrl }, env: { KIBANA_URL: kibanaUrl, diff --git a/x-pack/plugins/apm/ftr_e2e/config.ts b/x-pack/plugins/apm/ftr_e2e/ftr_config.ts similarity index 100% rename from x-pack/plugins/apm/ftr_e2e/config.ts rename to x-pack/plugins/apm/ftr_e2e/ftr_config.ts diff --git a/x-pack/plugins/apm/ftr_e2e/ftr_config_open.ts b/x-pack/plugins/apm/ftr_e2e/ftr_config_open.ts new file mode 100644 index 0000000000000..92f605d328789 --- /dev/null +++ b/x-pack/plugins/apm/ftr_e2e/ftr_config_open.ts @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FtrConfigProviderContext } from '@kbn/test'; +import cypress from 'cypress'; +import { FtrProviderContext } from './ftr_provider_context'; +import { cypressStart } from './cypress_start'; + +async function ftrConfigOpen({ readConfigFile }: FtrConfigProviderContext) { + const kibanaConfig = await readConfigFile(require.resolve('./ftr_config.ts')); + return { + ...kibanaConfig.getAll(), + testRunner, + }; +} + +export async function testRunner({ getService }: FtrProviderContext) { + await cypressStart(getService, cypress.open); +} + +// eslint-disable-next-line import/no-default-export +export default ftrConfigOpen; diff --git a/x-pack/plugins/apm/ftr_e2e/ftr_config_run.ts b/x-pack/plugins/apm/ftr_e2e/ftr_config_run.ts new file mode 100644 index 0000000000000..51c859a8477f2 --- /dev/null +++ b/x-pack/plugins/apm/ftr_e2e/ftr_config_run.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { FtrConfigProviderContext } from '@kbn/test'; +import cypress from 'cypress'; +import { cypressStart } from './cypress_start'; +import { FtrProviderContext } from './ftr_provider_context'; + +async function ftrConfigRun({ readConfigFile }: FtrConfigProviderContext) { + const kibanaConfig = await readConfigFile(require.resolve('./ftr_config.ts')); + return { + ...kibanaConfig.getAll(), + testRunner, + }; +} + +async function testRunner({ getService }: FtrProviderContext) { + const result = await cypressStart(getService, cypress.run); + + if (result && (result.status === 'failed' || result.totalFailed > 0)) { + throw new Error(`APM Cypress tests failed`); + } +} + +// eslint-disable-next-line import/no-default-export +export default ftrConfigRun; diff --git a/x-pack/plugins/apm/jest.config.js b/x-pack/plugins/apm/jest.config.js index 66b4b164a794c..cc985407698bf 100644 --- a/x-pack/plugins/apm/jest.config.js +++ b/x-pack/plugins/apm/jest.config.js @@ -19,5 +19,6 @@ module.exports = { coverageReporters: ['text', 'html'], collectCoverageFrom: [ '/x-pack/plugins/apm/{common,public,server}/**/*.{js,ts,tsx}', + '!/**/*.stories.*', ], }; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/ActionMenu/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/ActionMenu/index.tsx index 593de7c3a6f70..3bf21de7487de 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/ActionMenu/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/ActionMenu/index.tsx @@ -12,7 +12,7 @@ import { createExploratoryViewUrl, HeaderMenuPortal, } from '../../../../../../observability/public'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { useKibana } from '../../../../../../../../src/plugins/kibana_react/public'; import { AppMountParameters } from '../../../../../../../../src/core/public'; import { InspectorHeaderLink } from '../../../shared/apm_header_action_menu/inspector_header_link'; @@ -38,7 +38,7 @@ export function UXActionMenu({ const { services: { http }, } = useKibana(); - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const { rangeTo, rangeFrom, serviceName } = urlParams; const uxExploratoryViewLink = createExploratoryViewUrl( diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/Charts/PageViewsChart.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/Charts/PageViewsChart.tsx index 6be2eada6a9ec..e5ee427e16677 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/Charts/PageViewsChart.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/Charts/PageViewsChart.tsx @@ -28,7 +28,7 @@ import moment from 'moment'; import React from 'react'; import { useHistory } from 'react-router-dom'; import { useUiSetting$ } from '../../../../../../../../src/plugins/kibana_react/public'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { fromQuery, toQuery } from '../../../shared/Links/url_helpers'; import { ChartWrapper } from '../ChartWrapper'; import { I18LABELS } from '../translations'; @@ -43,7 +43,7 @@ interface Props { export function PageViewsChart({ data, loading }: Props) { const history = useHistory(); - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const { start, end } = urlParams; const diffInDays = moment(new Date(end as string)).diff( diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/ClientMetrics/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/ClientMetrics/index.tsx index c525a71ea4589..7c48531d21990 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/ClientMetrics/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/ClientMetrics/index.tsx @@ -15,13 +15,13 @@ import { } from '@elastic/eui'; import { I18LABELS } from '../translations'; import { getPercentileLabel } from '../UXMetrics/translations'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { Metrics } from './Metrics'; export function ClientMetrics() { const { urlParams: { percentile }, - } = useUrlParams(); + } = useLegacyUrlParams(); return ( diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/ImpactfulMetrics/JSErrors.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/ImpactfulMetrics/JSErrors.tsx index c8956c091d267..b8bdc36ed4e0d 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/ImpactfulMetrics/JSErrors.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/ImpactfulMetrics/JSErrors.tsx @@ -18,7 +18,7 @@ import { import numeral from '@elastic/numeral'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { FETCH_STATUS, useFetcher } from '../../../../hooks/use_fetcher'; import { I18LABELS } from '../translations'; import { CsmSharedContext } from '../CsmSharedContext'; @@ -31,7 +31,7 @@ interface JSErrorItem { } export function JSErrors() { - const { urlParams, uxUiFilters } = useUrlParams(); + const { urlParams, uxUiFilters } = useLegacyUrlParams(); const { start, end, serviceName, searchTerm } = urlParams; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/LocalUIFilters/SelectedFilters.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/LocalUIFilters/SelectedFilters.tsx index ee0827c4d81e5..d9f9154c5c100 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/LocalUIFilters/SelectedFilters.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/LocalUIFilters/SelectedFilters.tsx @@ -9,7 +9,7 @@ import React, { Fragment } from 'react'; import { EuiButtonEmpty, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import styled from 'styled-components'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { FilterValueLabel } from '../../../../../../observability/public'; import { FiltersUIHook } from '../hooks/useLocalUIFilters'; import { UxLocalUIFilterName } from '../../../../../common/ux_ui_filter'; @@ -38,7 +38,7 @@ export function SelectedFilters({ const { uxUiFilters, urlParams: { searchTerm }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { transactionUrl } = uxUiFilters; const urlValues = transactionUrl ?? []; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/LocalUIFilters/selected_wildcards.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/LocalUIFilters/selected_wildcards.tsx index 1bc0807bd2f71..6a9dfd1fddd11 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/LocalUIFilters/selected_wildcards.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/LocalUIFilters/selected_wildcards.tsx @@ -9,7 +9,7 @@ import * as React from 'react'; import { useCallback } from 'react'; import { useHistory } from 'react-router-dom'; import { FilterValueLabel } from '../../../../../../observability/public'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { fromQuery, toQuery } from '../../../shared/Links/url_helpers'; import { TRANSACTION_URL } from '../../../../../common/elasticsearch_fieldnames'; import { IndexPattern } from '../../../../../../../../src/plugins/data_views/common'; @@ -22,7 +22,7 @@ export function SelectedWildcards({ indexPattern }: Props) { const { urlParams: { searchTerm }, - } = useUrlParams(); + } = useLegacyUrlParams(); const updateSearchTerm = useCallback( (searchTermN: string) => { diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/index.tsx index a9dac0a37c353..f75d0fd093b5a 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/index.tsx @@ -14,7 +14,7 @@ import { EuiTitle, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { useFetcher } from '../../../../hooks/use_fetcher'; import { I18LABELS } from '../translations'; import { BreakdownFilter } from '../Breakdowns/BreakdownFilter'; @@ -34,7 +34,7 @@ export function PageLoadDistribution() { services: { http }, } = useKibana(); - const { urlParams, uxUiFilters } = useUrlParams(); + const { urlParams, uxUiFilters } = useLegacyUrlParams(); const { start, end, rangeFrom, rangeTo, searchTerm } = urlParams; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/use_breakdowns.ts b/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/use_breakdowns.ts index e43ba9c7e557e..0cfa293c87844 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/use_breakdowns.ts +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/use_breakdowns.ts @@ -6,7 +6,7 @@ */ import { useFetcher } from '../../../../hooks/use_fetcher'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { PercentileRange } from './index'; interface Props { @@ -16,7 +16,7 @@ interface Props { } export const useBreakdowns = ({ percentileRange, field, value }: Props) => { - const { urlParams, uxUiFilters } = useUrlParams(); + const { urlParams, uxUiFilters } = useLegacyUrlParams(); const { start, end, searchTerm } = urlParams; const { min: minP, max: maxP } = percentileRange ?? {}; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/PageViewsTrend/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/PageViewsTrend/index.tsx index 5f7c0738e5642..581260f5931e7 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/PageViewsTrend/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/PageViewsTrend/index.tsx @@ -14,7 +14,7 @@ import { EuiTitle, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { useFetcher } from '../../../../hooks/use_fetcher'; import { I18LABELS } from '../translations'; import { BreakdownFilter } from '../Breakdowns/BreakdownFilter'; @@ -28,7 +28,7 @@ export function PageViewsTrend() { services: { http }, } = useKibana(); - const { urlParams, uxUiFilters } = useUrlParams(); + const { urlParams, uxUiFilters } = useLegacyUrlParams(); const { serviceName } = uxUiFilters; const { start, end, searchTerm, rangeTo, rangeFrom } = urlParams; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/Panels/WebApplicationSelect.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/Panels/WebApplicationSelect.tsx index 58cffb39d0a04..5b1cca0ec44fa 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/Panels/WebApplicationSelect.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/Panels/WebApplicationSelect.tsx @@ -9,12 +9,12 @@ import React from 'react'; import { ServiceNameFilter } from '../URLFilter/ServiceNameFilter'; import { useFetcher } from '../../../../hooks/use_fetcher'; import { RUM_AGENT_NAMES } from '../../../../../common/agent_name'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; export function WebApplicationSelect() { const { urlParams: { start, end }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { data, status } = useFetcher( (callApmApi) => { diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/RumHome.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/RumHome.tsx index cc4bd0d14e290..54c34121ea0cb 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/RumHome.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/RumHome.tsx @@ -48,7 +48,7 @@ export function RumHome() { 'Enable RUM with the APM agent to collect user experience data.', } ), - href: core.http.basePath.prepend(`integrations/detail/apm`), + href: core.http.basePath.prepend(`/app/home#/tutorial/apm`), }, }, docsLink: core.docLinks.links.observability.guide, diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/ServiceNameFilter/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/ServiceNameFilter/index.tsx index 5750dd9cf441e..f6891a5d8fb67 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/ServiceNameFilter/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/ServiceNameFilter/index.tsx @@ -9,7 +9,7 @@ import { EuiSelect } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React, { useEffect, useCallback } from 'react'; import { useHistory } from 'react-router-dom'; -import { useUrlParams } from '../../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../../context/url_params_context/use_url_params'; import { fromQuery, toQuery } from '../../../../shared/Links/url_helpers'; interface Props { @@ -21,7 +21,7 @@ function ServiceNameFilter({ loading, serviceNames }: Props) { const history = useHistory(); const { urlParams: { serviceName: selectedServiceName }, - } = useUrlParams(); + } = useLegacyUrlParams(); const options = serviceNames.map((type) => ({ text: type, diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/index.tsx index 7aa8d5d85e539..e34270f963599 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/index.tsx @@ -8,7 +8,7 @@ import React, { useEffect, useState } from 'react'; import { isEqual, map } from 'lodash'; import { i18n } from '@kbn/i18n'; -import { useUrlParams } from '../../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../../context/url_params_context/use_url_params'; import { I18LABELS } from '../../translations'; import { formatToSec } from '../../UXMetrics/KeyUXMetrics'; import { getPercentileLabel } from '../../UXMetrics/translations'; @@ -93,7 +93,7 @@ export function URLSearch({ const { uxUiFilters: { transactionUrl, transactionUrlExcluded }, urlParams, - } = useUrlParams(); + } = useLegacyUrlParams(); const { searchTerm, percentile } = urlParams; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/use_url_search.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/use_url_search.tsx index 64f51714ed66e..7b6b093c70367 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/use_url_search.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/URLFilter/URLSearch/use_url_search.tsx @@ -9,7 +9,7 @@ import useDebounce from 'react-use/lib/useDebounce'; import { useState } from 'react'; import { useFetcher } from '../../../../../hooks/use_fetcher'; import { useUxQuery } from '../../hooks/useUxQuery'; -import { useUrlParams } from '../../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../../context/url_params_context/use_url_params'; interface Props { popoverIsOpen: boolean; @@ -19,7 +19,7 @@ interface Props { export const useUrlSearch = ({ popoverIsOpen, query }: Props) => { const uxQuery = useUxQuery(); - const { uxUiFilters } = useUrlParams(); + const { uxUiFilters } = useLegacyUrlParams(); const { transactionUrl, transactionUrlExcluded, ...restFilters } = uxUiFilters; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/UXMetrics/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/UXMetrics/index.tsx index dd93a0143c05a..673f045ecfb97 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/UXMetrics/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/UXMetrics/index.tsx @@ -20,13 +20,13 @@ import { useFetcher } from '../../../../hooks/use_fetcher'; import { useUxQuery } from '../hooks/useUxQuery'; import { getCoreVitalsComponent } from '../../../../../../observability/public'; import { CsmSharedContext } from '../CsmSharedContext'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { getPercentileLabel } from './translations'; export function UXMetrics() { const { urlParams: { percentile }, - } = useUrlParams(); + } = useLegacyUrlParams(); const uxQuery = useUxQuery(); diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/UserPercentile/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/UserPercentile/index.tsx index 0a5669095c2e5..7d05b188e9bbe 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/UserPercentile/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/UserPercentile/index.tsx @@ -9,7 +9,7 @@ import React, { useCallback, useEffect } from 'react'; import { EuiSelect } from '@elastic/eui'; import { useHistory } from 'react-router-dom'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { fromQuery, toQuery } from '../../../shared/Links/url_helpers'; import { I18LABELS } from '../translations'; @@ -20,7 +20,7 @@ export function UserPercentile() { const { urlParams: { percentile }, - } = useUrlParams(); + } = useLegacyUrlParams(); const updatePercentile = useCallback( (percentileN?: number, replaceHistory?: boolean) => { diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdown/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdown/index.tsx index a4edd56310ea1..f044890a9b649 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdown/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdown/index.tsx @@ -10,10 +10,10 @@ import { EuiFlexGroup, EuiFlexItem, EuiTitle, EuiSpacer } from '@elastic/eui'; import { VisitorBreakdownChart } from '../Charts/VisitorBreakdownChart'; import { I18LABELS, VisitorBreakdownLabel } from '../translations'; import { useFetcher } from '../../../../hooks/use_fetcher'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; export function VisitorBreakdown() { - const { urlParams, uxUiFilters } = useUrlParams(); + const { urlParams, uxUiFilters } = useLegacyUrlParams(); const { start, end, searchTerm } = urlParams; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/EmbeddedMap.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/EmbeddedMap.tsx index b468b5c913387..17a380f4d5e35 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/EmbeddedMap.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/EmbeddedMap.tsx @@ -21,7 +21,7 @@ import { isErrorEmbeddable, } from '../../../../../../../../src/plugins/embeddable/public'; import { useLayerList } from './useLayerList'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context'; import type { RenderTooltipContentParams } from '../../../../../../maps/public'; import { MapToolTip } from './MapToolTip'; @@ -50,7 +50,7 @@ interface KibanaDeps { embeddable: EmbeddableStart; } export function EmbeddedMapComponent() { - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const apmPluginContext = useApmPluginContext(); const { start, end, serviceName } = urlParams; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/useLayerList.ts b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/useLayerList.ts index ce42b530b80f5..7f81e9d105186 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/useLayerList.ts +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/useLayerList.ts @@ -22,7 +22,7 @@ import { } from '../../../../../../maps/common'; import { APM_STATIC_INDEX_PATTERN_ID } from '../../../../../common/index_pattern_constants'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { SERVICE_NAME, TRANSACTION_TYPE, @@ -84,7 +84,7 @@ interface VectorLayerDescriptor extends BaseVectorLayerDescriptor { } export function useLayerList() { - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const { serviceName } = urlParams; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/useMapFilters.ts b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/useMapFilters.ts index c9e8b41c26ea0..0c1b7b6b9e7ee 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/useMapFilters.ts +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdownMap/useMapFilters.ts @@ -7,7 +7,7 @@ import { useMemo } from 'react'; import { FieldFilter as Filter } from '@kbn/es-query'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { CLIENT_GEO_COUNTRY_ISO_CODE, SERVICE_NAME, @@ -92,7 +92,7 @@ const existFilter: Filter = { }; export const useMapFilters = (): Filter[] => { - const { urlParams, uxUiFilters } = useUrlParams(); + const { urlParams, uxUiFilters } = useLegacyUrlParams(); const { serviceName, searchTerm } = urlParams; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/hooks/useLocalUIFilters.ts b/x-pack/plugins/apm/public/components/app/RumDashboard/hooks/useLocalUIFilters.ts index 28c9488d7c82c..8045e4947dcb0 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/hooks/useLocalUIFilters.ts +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/hooks/useLocalUIFilters.ts @@ -17,7 +17,7 @@ import { toQuery, } from '../../../../components/shared/Links/url_helpers'; import { removeUndefinedProps } from '../../../../context/url_params_context/helpers'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { getExcludedName } from '../LocalUIFilters'; export type FiltersUIHook = ReturnType; @@ -28,7 +28,7 @@ export function useLocalUIFilters({ filterNames: UxLocalUIFilterName[]; }) { const history = useHistory(); - const { uxUiFilters } = useUrlParams(); + const { uxUiFilters } = useLegacyUrlParams(); const setFilterValue = (name: UxLocalUIFilterName, value: string[]) => { const search = omit(toQuery(history.location.search), name); diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/hooks/useUxQuery.ts b/x-pack/plugins/apm/public/components/app/RumDashboard/hooks/useUxQuery.ts index 585070d479fa8..e3f697e02a295 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/hooks/useUxQuery.ts +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/hooks/useUxQuery.ts @@ -6,10 +6,10 @@ */ import { useMemo } from 'react'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; export function useUxQuery() { - const { urlParams, uxUiFilters } = useUrlParams(); + const { urlParams, uxUiFilters } = useLegacyUrlParams(); const { start, end, searchTerm, percentile } = urlParams; diff --git a/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_detail_dependencies_table.tsx b/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_detail_dependencies_table.tsx index 72273bf8c9e19..4e3f7f4bee811 100644 --- a/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_detail_dependencies_table.tsx +++ b/x-pack/plugins/apm/public/components/app/backend_detail_overview/backend_detail_dependencies_table.tsx @@ -9,7 +9,7 @@ import { i18n } from '@kbn/i18n'; import React from 'react'; import { getNodeName, NodeType } from '../../../../common/connections'; import { useApmParams } from '../../../hooks/use_apm_params'; -import { useUrlParams } from '../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../context/url_params_context/use_url_params'; import { useFetcher } from '../../../hooks/use_fetcher'; import { getTimeRangeComparison } from '../../shared/time_comparison/get_time_range_comparison'; import { DependenciesTable } from '../../shared/dependencies_table'; @@ -19,7 +19,7 @@ import { useTimeRange } from '../../../hooks/use_time_range'; export function BackendDetailDependenciesTable() { const { urlParams: { comparisonEnabled, comparisonType }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { query: { backendName, rangeFrom, rangeTo, kuery, environment }, diff --git a/x-pack/plugins/apm/public/components/app/backend_inventory/backend_inventory_dependencies_table/index.tsx b/x-pack/plugins/apm/public/components/app/backend_inventory/backend_inventory_dependencies_table/index.tsx index b84e8830aae5f..9782afc8df3e8 100644 --- a/x-pack/plugins/apm/public/components/app/backend_inventory/backend_inventory_dependencies_table/index.tsx +++ b/x-pack/plugins/apm/public/components/app/backend_inventory/backend_inventory_dependencies_table/index.tsx @@ -10,7 +10,7 @@ import { i18n } from '@kbn/i18n'; import React from 'react'; import { useUiTracker } from '../../../../../../observability/public'; import { getNodeName, NodeType } from '../../../../../common/connections'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { useApmParams } from '../../../../hooks/use_apm_params'; import { useFetcher } from '../../../../hooks/use_fetcher'; import { useTimeRange } from '../../../../hooks/use_time_range'; @@ -21,7 +21,7 @@ import { getTimeRangeComparison } from '../../../shared/time_comparison/get_time export function BackendInventoryDependenciesTable() { const { urlParams: { comparisonEnabled, comparisonType }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { query: { rangeFrom, rangeTo, environment, kuery }, diff --git a/x-pack/plugins/apm/public/components/app/error_group_details/Distribution/index.tsx b/x-pack/plugins/apm/public/components/app/error_group_details/Distribution/index.tsx index abff050457359..4c6aa78278093 100644 --- a/x-pack/plugins/apm/public/components/app/error_group_details/Distribution/index.tsx +++ b/x-pack/plugins/apm/public/components/app/error_group_details/Distribution/index.tsx @@ -29,7 +29,7 @@ import { getAlertAnnotations } from '../../../shared/charts/helper/get_alert_ann import { ChartContainer } from '../../../shared/charts/chart_container'; import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context'; import { LazyAlertsFlyout } from '../../../../../../observability/public'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { getTimeZone } from '../../../shared/charts/helper/timezone'; const ALERT_RULE_TYPE_ID: typeof ALERT_RULE_TYPE_ID_TYPED = @@ -48,7 +48,7 @@ export function ErrorDistribution({ distribution, title, fetchStatus }: Props) { const { core } = useApmPluginContext(); const theme = useTheme(); - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const { comparisonEnabled } = urlParams; const timeseries = [ diff --git a/x-pack/plugins/apm/public/components/app/error_group_details/index.tsx b/x-pack/plugins/apm/public/components/app/error_group_details/index.tsx index bc12b0c64f179..f3bd8812dfd36 100644 --- a/x-pack/plugins/apm/public/components/app/error_group_details/index.tsx +++ b/x-pack/plugins/apm/public/components/app/error_group_details/index.tsx @@ -20,7 +20,7 @@ import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common' import { NOT_AVAILABLE_LABEL } from '../../../../common/i18n'; import { useApmServiceContext } from '../../../context/apm_service/use_apm_service_context'; import { useBreadcrumb } from '../../../context/breadcrumbs/use_breadcrumb'; -import { useUrlParams } from '../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../context/url_params_context/use_url_params'; import { useApmParams } from '../../../hooks/use_apm_params'; import { useApmRouter } from '../../../hooks/use_apm_router'; import { useErrorGroupDistributionFetcher } from '../../../hooks/use_error_group_distribution_fetcher'; @@ -94,7 +94,7 @@ function ErrorGroupHeader({ } export function ErrorGroupDetails() { - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const { serviceName } = useApmServiceContext(); diff --git a/x-pack/plugins/apm/public/components/app/error_group_overview/error_group_list/index.tsx b/x-pack/plugins/apm/public/components/app/error_group_overview/error_group_list/index.tsx index d7c5b1f4bc358..7facc9a4ca376 100644 --- a/x-pack/plugins/apm/public/components/app/error_group_overview/error_group_list/index.tsx +++ b/x-pack/plugins/apm/public/components/app/error_group_overview/error_group_list/index.tsx @@ -16,7 +16,7 @@ import { i18n } from '@kbn/i18n'; import React, { useMemo } from 'react'; import { euiStyled } from '../../../../../../../../src/plugins/kibana_react/common'; import { NOT_AVAILABLE_LABEL } from '../../../../../common/i18n'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { APIReturnType } from '../../../../services/rest/createCallApmApi'; import { truncate, unit } from '../../../../utils/style'; import { ErrorDetailLink } from '../../../shared/Links/apm/ErrorDetailLink'; @@ -56,7 +56,7 @@ interface Props { } function ErrorGroupList({ items, serviceName }: Props) { - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const columns = useMemo(() => { return [ diff --git a/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx b/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx index aea7c1faab601..155de8fbdd947 100644 --- a/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_inventory/index.tsx @@ -17,7 +17,7 @@ import uuid from 'uuid'; import { toMountPoint } from '../../../../../../../src/plugins/kibana_react/public'; import { useAnomalyDetectionJobsContext } from '../../../context/anomaly_detection_jobs/use_anomaly_detection_jobs_context'; import { useApmPluginContext } from '../../../context/apm_plugin/use_apm_plugin_context'; -import { useUrlParams } from '../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../context/url_params_context/use_url_params'; import { useLocalStorage } from '../../../hooks/useLocalStorage'; import { useApmParams } from '../../../hooks/use_apm_params'; import { FETCH_STATUS, useFetcher } from '../../../hooks/use_fetcher'; @@ -42,7 +42,7 @@ let hasDisplayedToast = false; function useServicesFetcher() { const { urlParams: { comparisonEnabled, comparisonType }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { query: { rangeFrom, rangeTo, environment, kuery }, diff --git a/x-pack/plugins/apm/public/components/app/service_inventory/service_inventory.stories.tsx b/x-pack/plugins/apm/public/components/app/service_inventory/service_inventory.stories.tsx new file mode 100644 index 0000000000000..0a4adc07e1a98 --- /dev/null +++ b/x-pack/plugins/apm/public/components/app/service_inventory/service_inventory.stories.tsx @@ -0,0 +1,81 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Meta, Story } from '@storybook/react'; +import React from 'react'; +import { MemoryRouter } from 'react-router-dom'; +import { CoreStart } from '../../../../../../../src/core/public'; +import { createKibanaReactContext } from '../../../../../../../src/plugins/kibana_react/public'; +import { TimeRangeComparisonEnum } from '../../../../common/runtime_types/comparison_type_rt'; +import { AnomalyDetectionJobsContext } from '../../../context/anomaly_detection_jobs/anomaly_detection_jobs_context'; +import { ApmPluginContextValue } from '../../../context/apm_plugin/apm_plugin_context'; +import { MockApmPluginContextWrapper } from '../../../context/apm_plugin/mock_apm_plugin_context'; +import { MockUrlParamsContextProvider } from '../../../context/url_params_context/mock_url_params_context_provider'; +import { FETCH_STATUS } from '../../../hooks/use_fetcher'; +import { ServiceInventory } from './'; + +const stories: Meta<{}> = { + title: 'app/ServiceInventory', + component: ServiceInventory, + decorators: [ + (StoryComponent) => { + const coreMock = { + http: { + get: (endpoint: string) => { + switch (endpoint) { + case '/internal/apm/services': + return { items: [] }; + default: + return {}; + } + return {}; + }, + }, + notifications: { toasts: { add: () => {}, addWarning: () => {} } }, + uiSettings: { get: () => [] }, + } as unknown as CoreStart; + + const KibanaReactContext = createKibanaReactContext(coreMock); + + const anomlyDetectionJobsContextValue = { + anomalyDetectionJobsData: { jobs: [], hasLegacyJobs: false }, + anomalyDetectionJobsStatus: FETCH_STATUS.SUCCESS, + anomalyDetectionJobsRefetch: () => {}, + }; + + return ( + + + + + + + + + + + + ); + }, + ], +}; +export default stories; + +export const Example: Story<{}> = () => { + return ; +}; diff --git a/x-pack/plugins/apm/public/components/app/service_inventory/service_inventory.test.tsx b/x-pack/plugins/apm/public/components/app/service_inventory/service_inventory.test.tsx index 4a020f9b0db4e..36b1053248d25 100644 --- a/x-pack/plugins/apm/public/components/app/service_inventory/service_inventory.test.tsx +++ b/x-pack/plugins/apm/public/components/app/service_inventory/service_inventory.test.tsx @@ -5,249 +5,17 @@ * 2.0. */ -import { render, waitFor } from '@testing-library/react'; -import { CoreStart } from 'kibana/public'; -import { merge } from 'lodash'; -import React, { ReactNode } from 'react'; -import { MemoryRouter } from 'react-router-dom'; -import { EuiThemeProvider } from '../../../../../../../src/plugins/kibana_react/common'; -import { createKibanaReactContext } from '../../../../../../../src/plugins/kibana_react/public'; -import { ServiceHealthStatus } from '../../../../common/service_health_status'; -import { TimeRangeComparisonEnum } from '../../../../common/runtime_types/comparison_type_rt'; -import { ServiceInventory } from '.'; -import { ApmPluginContextValue } from '../../../context/apm_plugin/apm_plugin_context'; -import { - mockApmPluginContextValue, - MockApmPluginContextWrapper, -} from '../../../context/apm_plugin/mock_apm_plugin_context'; -import { FETCH_STATUS } from '../../../hooks/use_fetcher'; -import { clearCache } from '../../../services/rest/callApi'; -import * as useDynamicDataViewHooks from '../../../hooks/use_dynamic_data_view'; -import { SessionStorageMock } from '../../../services/__mocks__/SessionStorageMock'; -import { MockUrlParamsContextProvider } from '../../../context/url_params_context/mock_url_params_context_provider'; -import * as hook from '../../../context/anomaly_detection_jobs/use_anomaly_detection_jobs_context'; +import { composeStories } from '@storybook/testing-react'; +import { render, screen } from '@testing-library/react'; +import React from 'react'; +import * as stories from './service_inventory.stories'; -const KibanaReactContext = createKibanaReactContext({ - usageCollection: { reportUiCounter: () => {} }, -} as Partial); - -const addWarning = jest.fn(); -const httpGet = jest.fn(); - -function wrapper({ children }: { children?: ReactNode }) { - const mockPluginContext = merge({}, mockApmPluginContextValue, { - core: { - http: { - get: httpGet, - }, - notifications: { - toasts: { - addWarning, - }, - }, - }, - }) as unknown as ApmPluginContextValue; - - return ( - - - - - - {children} - - - - - - ); -} +const { Example } = composeStories(stories); describe('ServiceInventory', () => { - beforeEach(() => { - // @ts-expect-error - global.sessionStorage = new SessionStorageMock(); - clearCache(); - - jest.spyOn(hook, 'useAnomalyDetectionJobsContext').mockReturnValue({ - anomalyDetectionJobsData: { jobs: [], hasLegacyJobs: false }, - anomalyDetectionJobsStatus: FETCH_STATUS.SUCCESS, - anomalyDetectionJobsRefetch: () => {}, - }); - - jest - .spyOn(useDynamicDataViewHooks, 'useDynamicDataViewFetcher') - .mockReturnValue({ - dataView: undefined, - status: FETCH_STATUS.SUCCESS, - }); - }); - - afterEach(() => { - jest.resetAllMocks(); - }); - - it('should render services, when list is not empty', async () => { - // mock rest requests - httpGet - .mockResolvedValueOnce({ fallbackToTransactions: false }) - .mockResolvedValueOnce({ - hasLegacyData: false, - hasHistoricalData: true, - items: [ - { - serviceName: 'My Python Service', - agentName: 'python', - transactionsPerMinute: 100, - errorsPerMinute: 200, - avgResponseTime: 300, - environments: ['test', 'dev'], - healthStatus: ServiceHealthStatus.warning, - }, - { - serviceName: 'My Go Service', - agentName: 'go', - transactionsPerMinute: 400, - errorsPerMinute: 500, - avgResponseTime: 600, - environments: [], - severity: ServiceHealthStatus.healthy, - }, - ], - }); - - const { container, findByText } = render(, { wrapper }); - - // wait for requests to be made - await waitFor(() => expect(httpGet).toHaveBeenCalledTimes(2)); - await findByText('My Python Service'); - - expect(container.querySelectorAll('.euiTableRow')).toHaveLength(2); - }); - - it('should render empty message, when list is empty and historical data is found', async () => { - httpGet - .mockResolvedValueOnce({ fallbackToTransactions: false }) - .mockResolvedValueOnce({ - hasLegacyData: false, - hasHistoricalData: true, - items: [], - }); - - const { findByText } = render(, { wrapper }); - - // wait for requests to be made - await waitFor(() => expect(httpGet).toHaveBeenCalledTimes(2)); - const noServicesText = await findByText('No services found'); - - expect(noServicesText).not.toBeEmptyDOMElement(); - }); - - describe('when legacy data is found', () => { - it('renders an upgrade migration notification', async () => { - httpGet - .mockResolvedValueOnce({ fallbackToTransactions: false }) - .mockResolvedValueOnce({ - hasLegacyData: true, - hasHistoricalData: true, - items: [], - }); - - render(, { wrapper }); - - // wait for requests to be made - await waitFor(() => expect(httpGet).toHaveBeenCalledTimes(2)); - - expect(addWarning).toHaveBeenLastCalledWith( - expect.objectContaining({ - title: 'Legacy data was detected within the selected time range', - }) - ); - }); - }); - - describe('when legacy data is not found', () => { - it('does not render an upgrade migration notification', async () => { - httpGet - .mockResolvedValueOnce({ fallbackToTransactions: false }) - .mockResolvedValueOnce({ - hasLegacyData: false, - hasHistoricalData: true, - items: [], - }); - - render(, { wrapper }); - - // wait for requests to be made - await waitFor(() => expect(httpGet).toHaveBeenCalledTimes(2)); - - expect(addWarning).not.toHaveBeenCalled(); - }); - }); - - describe('when ML data is not found', () => { - it('does not render the health column', async () => { - httpGet - .mockResolvedValueOnce({ fallbackToTransactions: false }) - .mockResolvedValueOnce({ - hasLegacyData: false, - hasHistoricalData: true, - items: [ - { - serviceName: 'My Python Service', - agentName: 'python', - transactionsPerMinute: 100, - errorsPerMinute: 200, - avgResponseTime: 300, - environments: ['test', 'dev'], - }, - ], - }); - - const { queryByText } = render(, { wrapper }); - - // wait for requests to be made - await waitFor(() => expect(httpGet).toHaveBeenCalledTimes(2)); - - expect(queryByText('Health')).toBeNull(); - }); - }); - - describe('when ML data is found', () => { - it('renders the health column', async () => { - httpGet - .mockResolvedValueOnce({ fallbackToTransactions: false }) - .mockResolvedValueOnce({ - hasLegacyData: false, - hasHistoricalData: true, - items: [ - { - serviceName: 'My Python Service', - agentName: 'python', - transactionsPerMinute: 100, - errorsPerMinute: 200, - avgResponseTime: 300, - environments: ['test', 'dev'], - healthStatus: ServiceHealthStatus.warning, - }, - ], - }); - - const { queryAllByText } = render(, { wrapper }); - - // wait for requests to be made - await waitFor(() => expect(httpGet).toHaveBeenCalledTimes(2)); + it('renders', async () => { + render(); - expect(queryAllByText('Health').length).toBeGreaterThan(1); - }); + expect(await screen.findByRole('table')).toBeInTheDocument(); }); }); diff --git a/x-pack/plugins/apm/public/components/app/service_map/Controls.tsx b/x-pack/plugins/apm/public/components/app/service_map/Controls.tsx index 69644216fc267..4605952a6f396 100644 --- a/x-pack/plugins/apm/public/components/app/service_map/Controls.tsx +++ b/x-pack/plugins/apm/public/components/app/service_map/Controls.tsx @@ -11,8 +11,8 @@ import React, { useContext, useEffect, useState } from 'react'; import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common'; import { useApmPluginContext } from '../../../context/apm_plugin/use_apm_plugin_context'; import { useTheme } from '../../../hooks/use_theme'; -import { useUrlParams } from '../../../context/url_params_context/use_url_params'; import { getLegacyApmHref } from '../../shared/Links/apm/APMLink'; +import { useLegacyUrlParams } from '../../../context/url_params_context/use_url_params'; import { APMQueryParams } from '../../shared/Links/url_helpers'; import { CytoscapeContext } from './Cytoscape'; import { getAnimationOptions, getNodeHeight } from './cytoscape_options'; @@ -103,7 +103,7 @@ export function Controls() { const { basePath } = core.http; const theme = useTheme(); const cy = useContext(CytoscapeContext); - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const { query: { kuery }, diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview.stories.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview.stories.tsx new file mode 100644 index 0000000000000..b632d3a33dea8 --- /dev/null +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview.stories.tsx @@ -0,0 +1,76 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Meta, Story } from '@storybook/react'; +import React from 'react'; +import { MemoryRouter } from 'react-router-dom'; +import type { CoreStart } from '../../../../../../../src/core/public'; +import { createKibanaReactContext } from '../../../../../../../src/plugins/kibana_react/public'; +import type { ApmPluginContextValue } from '../../../context/apm_plugin/apm_plugin_context'; +import { MockApmPluginContextWrapper } from '../../../context/apm_plugin/mock_apm_plugin_context'; +import { + APMServiceContext, + APMServiceContextValue, +} from '../../../context/apm_service/apm_service_context'; +import { ServiceOverview } from './'; + +const stories: Meta<{}> = { + title: 'app/ServiceOverview', + component: ServiceOverview, + decorators: [ + (StoryComponent) => { + const serviceName = 'testServiceName'; + const mockCore = { + http: { + basePath: { prepend: () => {} }, + get: (endpoint: string) => { + switch (endpoint) { + case `/api/apm/services/${serviceName}/annotation/search`: + return { annotations: [] }; + case '/internal/apm/fallback_to_transactions': + return { fallbackToTransactions: false }; + case `/internal/apm/services/${serviceName}/dependencies`: + return { serviceDependencies: [] }; + default: + return {}; + } + }, + }, + notifications: { toasts: { add: () => {} } }, + uiSettings: { get: () => 'Browser' }, + } as unknown as CoreStart; + const serviceContextValue = { + alerts: [], + serviceName, + } as unknown as APMServiceContextValue; + const KibanaReactContext = createKibanaReactContext(mockCore); + + return ( + + + + + + + + + + ); + }, + ], +}; +export default stories; + +export const Example: Story<{}> = () => { + return ; +}; diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview.test.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview.test.tsx index 7e9b4325591d9..fb60604aa53b2 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview.test.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview.test.tsx @@ -5,178 +5,19 @@ * 2.0. */ -import React, { ReactNode } from 'react'; -import { MemoryRouter } from 'react-router-dom'; -import { CoreStart } from 'src/core/public'; -import { isEqual } from 'lodash'; -import { createKibanaReactContext } from '../../../../../../../src/plugins/kibana_react/public'; -import { ApmPluginContextValue } from '../../../context/apm_plugin/apm_plugin_context'; -import { - mockApmPluginContextValue, - MockApmPluginContextWrapper, -} from '../../../context/apm_plugin/mock_apm_plugin_context'; -import * as useDynamicDataViewHooks from '../../../hooks/use_dynamic_data_view'; -import { FETCH_STATUS } from '../../../hooks/use_fetcher'; -import * as useAnnotationsHooks from '../../../context/annotations/use_annotations_context'; -import * as useTransactionBreakdownHooks from '../../shared/charts/transaction_breakdown_chart/use_transaction_breakdown'; -import { renderWithTheme } from '../../../utils/testHelpers'; -import { ServiceOverview } from './'; -import { waitFor } from '@testing-library/dom'; -import * as useApmServiceContextHooks from '../../../context/apm_service/use_apm_service_context'; -import { LatencyAggregationType } from '../../../../common/latency_aggregation_types'; -import { - getCallApmApiSpy, - getCreateCallApmApiSpy, -} from '../../../services/rest/callApmApiSpy'; -import { fromQuery } from '../../shared/Links/url_helpers'; -import { MockUrlParamsContextProvider } from '../../../context/url_params_context/mock_url_params_context_provider'; -import { uiSettingsServiceMock } from '../../../../../../../src/core/public/mocks'; +import { composeStories } from '@storybook/testing-react'; +import { render, screen } from '@testing-library/react'; +import React from 'react'; +import * as stories from './service_overview.stories'; -const uiSettings = uiSettingsServiceMock.create().setup({} as any); - -const KibanaReactContext = createKibanaReactContext({ - notifications: { toasts: { add: () => {} } }, - uiSettings, - usageCollection: { reportUiCounter: () => {} }, -} as unknown as Partial); - -const mockParams = { - rangeFrom: 'now-15m', - rangeTo: 'now', - latencyAggregationType: LatencyAggregationType.avg, -}; - -const location = { - pathname: '/services/test%20service%20name/overview', - search: fromQuery(mockParams), -}; - -function Wrapper({ children }: { children?: ReactNode }) { - const value = { - ...mockApmPluginContextValue, - core: { - ...mockApmPluginContextValue.core, - http: { - basePath: { prepend: () => {} }, - get: () => {}, - }, - }, - } as unknown as ApmPluginContextValue; - - return ( - - - - - {children} - - - - - ); -} +const { Example } = composeStories(stories); describe('ServiceOverview', () => { it('renders', async () => { - jest - .spyOn(useApmServiceContextHooks, 'useApmServiceContext') - .mockReturnValue({ - serviceName: 'test service name', - agentName: 'java', - transactionType: 'request', - transactionTypes: ['request'], - alerts: [], - }); - jest - .spyOn(useAnnotationsHooks, 'useAnnotationsContext') - .mockReturnValue({ annotations: [] }); - jest - .spyOn(useDynamicDataViewHooks, 'useDynamicDataViewFetcher') - .mockReturnValue({ - dataView: undefined, - status: FETCH_STATUS.SUCCESS, - }); - - /* eslint-disable @typescript-eslint/naming-convention */ - const calls = { - 'GET /internal/apm/services/{serviceName}/error_groups/main_statistics': { - error_groups: [] as any[], - }, - 'GET /internal/apm/services/{serviceName}/transactions/groups/main_statistics': - { - transactionGroups: [] as any[], - totalTransactionGroups: 0, - isAggregationAccurate: true, - }, - 'GET /internal/apm/services/{serviceName}/dependencies': { - serviceDependencies: [], - }, - 'GET /internal/apm/services/{serviceName}/service_overview_instances/main_statistics': - [], - 'GET /internal/apm/services/{serviceName}/transactions/charts/latency': { - currentPeriod: { - overallAvgDuration: null, - latencyTimeseries: [], - }, - previousPeriod: { - overallAvgDuration: null, - latencyTimeseries: [], - }, - }, - 'GET /internal/apm/services/{serviceName}/throughput': { - currentPeriod: [], - previousPeriod: [], - }, - 'GET /internal/apm/services/{serviceName}/transactions/charts/error_rate': - { - currentPeriod: { - timeseries: [], - average: null, - }, - previousPeriod: { - timeseries: [], - average: null, - }, - }, - 'GET /api/apm/services/{serviceName}/annotation/search': { - annotations: [], - }, - 'GET /internal/apm/fallback_to_transactions': { - fallbackToTransactions: false, - }, - }; - /* eslint-enable @typescript-eslint/naming-convention */ - - const callApmApiSpy = getCallApmApiSpy().mockImplementation( - ({ endpoint }) => { - const response = calls[endpoint as keyof typeof calls]; - - return response - ? Promise.resolve(response) - : Promise.reject(`Response for ${endpoint} is not defined`); - } - ); - - getCreateCallApmApiSpy().mockImplementation(() => callApmApiSpy as any); - jest - .spyOn(useTransactionBreakdownHooks, 'useTransactionBreakdown') - .mockReturnValue({ - data: { timeseries: [] }, - error: undefined, - status: FETCH_STATUS.SUCCESS, - }); - - const { findAllByText } = renderWithTheme(, { - wrapper: Wrapper, - }); - - await waitFor(() => { - const endpoints = callApmApiSpy.mock.calls.map( - (call) => call[0].endpoint - ); - return isEqual(endpoints.sort(), Object.keys(calls).sort()); - }); + render(); - expect((await findAllByText('Latency')).length).toBeGreaterThan(0); + expect( + await screen.findByRole('heading', { name: /Latency/ }) + ).toBeInTheDocument(); }); }); diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_dependencies_table/index.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_dependencies_table/index.tsx index 208d1a30a46d1..cbf60b7b59e4d 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_dependencies_table/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_dependencies_table/index.tsx @@ -11,7 +11,7 @@ import React, { ReactNode } from 'react'; import { useUiTracker } from '../../../../../../observability/public'; import { getNodeName, NodeType } from '../../../../../common/connections'; import { useApmServiceContext } from '../../../../context/apm_service/use_apm_service_context'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { useApmParams } from '../../../../hooks/use_apm_params'; import { useFetcher } from '../../../../hooks/use_fetcher'; import { useTimeRange } from '../../../../hooks/use_time_range'; @@ -33,7 +33,7 @@ export function ServiceOverviewDependenciesTable({ }: ServiceOverviewDependenciesTableProps) { const { urlParams: { comparisonEnabled, comparisonType, latencyAggregationType }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { query: { environment, kuery, rangeFrom, rangeTo }, diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/index.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/index.tsx index d711676378039..ce4ba85b233e2 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_errors_table/index.tsx @@ -16,7 +16,7 @@ import { orderBy } from 'lodash'; import React, { useState } from 'react'; import uuid from 'uuid'; import { useApmServiceContext } from '../../../../context/apm_service/use_apm_service_context'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { FETCH_STATUS, useFetcher } from '../../../../hooks/use_fetcher'; import { APIReturnType } from '../../../../services/rest/createCallApmApi'; import { ErrorOverviewLink } from '../../../shared/Links/apm/ErrorOverviewLink'; @@ -61,7 +61,7 @@ const INITIAL_STATE_DETAILED_STATISTICS: ErrorGroupDetailedStatistics = { export function ServiceOverviewErrorsTable({ serviceName }: Props) { const { urlParams: { comparisonType, comparisonEnabled }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { transactionType } = useApmServiceContext(); const [tableOptions, setTableOptions] = useState<{ pageIndex: number; diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_chart_and_table.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_chart_and_table.tsx index 74a9a60afd915..07e4e81e4d216 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_chart_and_table.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_chart_and_table.tsx @@ -10,7 +10,7 @@ import { orderBy } from 'lodash'; import React, { useState } from 'react'; import uuid from 'uuid'; import { useApmServiceContext } from '../../../context/apm_service/use_apm_service_context'; -import { useUrlParams } from '../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../context/url_params_context/use_url_params'; import { useApmParams } from '../../../hooks/use_apm_params'; import { FETCH_STATUS, useFetcher } from '../../../hooks/use_fetcher'; import { useTimeRange } from '../../../hooks/use_time_range'; @@ -78,7 +78,7 @@ export function ServiceOverviewInstancesChartAndTable({ const { urlParams: { latencyAggregationType, comparisonType, comparisonEnabled }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { start, end } = useTimeRange({ rangeFrom, rangeTo }); diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/index.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/index.tsx index 9084ffdda59f8..71ea1412c6426 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/index.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_instances_table/index.tsx @@ -14,7 +14,7 @@ import { import { i18n } from '@kbn/i18n'; import React, { ReactNode, useEffect, useState } from 'react'; import { useApmServiceContext } from '../../../../context/apm_service/use_apm_service_context'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { FETCH_STATUS } from '../../../../hooks/use_fetcher'; import { APIReturnType } from '../../../../services/rest/createCallApmApi'; import { @@ -76,7 +76,7 @@ export function ServiceOverviewInstancesTable({ const { urlParams: { latencyAggregationType, comparisonEnabled }, - } = useUrlParams(); + } = useLegacyUrlParams(); const [itemIdToOpenActionMenuRowMap, setItemIdToOpenActionMenuRowMap] = useState>({}); diff --git a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_throughput_chart.tsx b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_throughput_chart.tsx index 6648eaec80fa6..058c7d97b43cc 100644 --- a/x-pack/plugins/apm/public/components/app/service_overview/service_overview_throughput_chart.tsx +++ b/x-pack/plugins/apm/public/components/app/service_overview/service_overview_throughput_chart.tsx @@ -16,7 +16,7 @@ import { i18n } from '@kbn/i18n'; import React from 'react'; import { asExactTransactionRate } from '../../../../common/utils/formatters'; import { useApmServiceContext } from '../../../context/apm_service/use_apm_service_context'; -import { useUrlParams } from '../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../context/url_params_context/use_url_params'; import { useApmParams } from '../../../hooks/use_apm_params'; import { useFetcher } from '../../../hooks/use_fetcher'; import { useTheme } from '../../../hooks/use_theme'; @@ -48,7 +48,7 @@ export function ServiceOverviewThroughputChart({ const { urlParams: { comparisonEnabled, comparisonType }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { query: { rangeFrom, rangeTo }, diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/distribution/index.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/distribution/index.tsx index 8862596fd6d2a..ad52adfa13a52 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/distribution/index.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/distribution/index.tsx @@ -25,7 +25,7 @@ import { useUiTracker } from '../../../../../../observability/public'; import { getDurationFormatter } from '../../../../../common/utils/formatters'; import { DEFAULT_PERCENTILE_THRESHOLD } from '../../../../../common/search_strategies/constants'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { FETCH_STATUS } from '../../../../hooks/use_fetcher'; import { TransactionDistributionChart } from '../../../shared/charts/transaction_distribution_chart'; @@ -69,7 +69,7 @@ export function TransactionDistribution({ traceSamples, }: TransactionDistributionProps) { const transactionColors = useTransactionColors(); - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const { waterfall, status: waterfallStatus } = useWaterfallFetcher(); const markerCurrentTransaction = diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/distribution/use_transaction_distribution_chart_data.ts b/x-pack/plugins/apm/public/components/app/transaction_details/distribution/use_transaction_distribution_chart_data.ts index 0edf5f648a980..9fb945100414f 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/distribution/use_transaction_distribution_chart_data.ts +++ b/x-pack/plugins/apm/public/components/app/transaction_details/distribution/use_transaction_distribution_chart_data.ts @@ -16,7 +16,7 @@ import { EventOutcome } from '../../../../../common/event_outcome'; import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context'; import { useApmServiceContext } from '../../../../context/apm_service/use_apm_service_context'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { useApmParams } from '../../../../hooks/use_apm_params'; import { useFetcher, FETCH_STATUS } from '../../../../hooks/use_fetcher'; import { useTimeRange } from '../../../../hooks/use_time_range'; @@ -37,7 +37,7 @@ export const useTransactionDistributionChartData = () => { core: { notifications }, } = useApmPluginContext(); - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const { transactionName } = urlParams; const { diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/transaction_details_tabs.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/transaction_details_tabs.tsx index 9ccca9886e679..f379369e86643 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/transaction_details_tabs.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/transaction_details_tabs.tsx @@ -13,7 +13,7 @@ import { useHistory } from 'react-router-dom'; import { XYBrushEvent } from '@elastic/charts'; import { EuiPanel, EuiSpacer, EuiTabs, EuiTab } from '@elastic/eui'; -import { useUrlParams } from '../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../context/url_params_context/use_url_params'; import { useApmParams } from '../../../hooks/use_apm_params'; import { useTransactionTraceSamplesFetcher } from '../../../hooks/use_transaction_trace_samples_fetcher'; @@ -34,7 +34,7 @@ const tabs = [ export function TransactionDetailsTabs() { const { query } = useApmParams('/services/{serviceName}/transactions/view'); - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const history = useHistory(); const [currentTab, setCurrentTab] = useState(traceSamplesTab.key); diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/use_waterfall_fetcher.ts b/x-pack/plugins/apm/public/components/app/transaction_details/use_waterfall_fetcher.ts index e7fbc315522e4..4f26a5875347c 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/use_waterfall_fetcher.ts +++ b/x-pack/plugins/apm/public/components/app/transaction_details/use_waterfall_fetcher.ts @@ -6,7 +6,7 @@ */ import { useMemo } from 'react'; -import { useUrlParams } from '../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../context/url_params_context/use_url_params'; import { useApmParams } from '../../../hooks/use_apm_params'; import { useFetcher } from '../../../hooks/use_fetcher'; import { useTimeRange } from '../../../hooks/use_time_range'; @@ -19,7 +19,7 @@ const INITIAL_DATA = { }; export function useWaterfallFetcher() { - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const { traceId, transactionId } = urlParams; const { diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/MaybeViewTraceLink.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/MaybeViewTraceLink.tsx index 359dcdfda0a14..c18bc42a98b2c 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/MaybeViewTraceLink.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/MaybeViewTraceLink.tsx @@ -9,7 +9,7 @@ import { EuiButton, EuiFlexItem, EuiToolTip } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import React from 'react'; import { getNextEnvironmentUrlParam } from '../../../../../common/environment_filter_values'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { Transaction as ITransaction } from '../../../../../typings/es_schemas/ui/transaction'; import { TransactionDetailLink } from '../../../shared/Links/apm/transaction_detail_link'; import { IWaterfall } from './waterfall_container/Waterfall/waterfall_helpers/waterfall_helpers'; @@ -26,7 +26,7 @@ export function MaybeViewTraceLink({ }) { const { urlParams: { latencyAggregationType }, - } = useUrlParams(); + } = useLegacyUrlParams(); const viewFullTraceButtonLabel = i18n.translate( 'xpack.apm.transactionDetails.viewFullTraceButtonLabel', diff --git a/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/FlyoutTopLevelProperties.tsx b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/FlyoutTopLevelProperties.tsx index 8954081f9ab47..e34fdd893ff7f 100644 --- a/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/FlyoutTopLevelProperties.tsx +++ b/x-pack/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/Waterfall/FlyoutTopLevelProperties.tsx @@ -13,7 +13,7 @@ import { } from '../../../../../../../common/elasticsearch_fieldnames'; import { getNextEnvironmentUrlParam } from '../../../../../../../common/environment_filter_values'; import { Transaction } from '../../../../../../../typings/es_schemas/ui/transaction'; -import { useUrlParams } from '../../../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../../../context/url_params_context/use_url_params'; import { useApmParams } from '../../../../../../hooks/use_apm_params'; import { TransactionDetailLink } from '../../../../../shared/Links/apm/transaction_detail_link'; import { ServiceLink } from '../../../../../shared/service_link'; @@ -26,7 +26,7 @@ interface Props { export function FlyoutTopLevelProperties({ transaction }: Props) { const { urlParams: { latencyAggregationType }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { query } = useApmParams('/services/{serviceName}/transactions/view'); if (!transaction) { diff --git a/x-pack/plugins/apm/public/components/fleet_integration/apm_policy_form/settings_definition/apm_settings.ts b/x-pack/plugins/apm/public/components/fleet_integration/apm_policy_form/settings_definition/apm_settings.ts index 2b88e1a1df9ed..ec9f740932376 100644 --- a/x-pack/plugins/apm/public/components/fleet_integration/apm_policy_form/settings_definition/apm_settings.ts +++ b/x-pack/plugins/apm/public/components/fleet_integration/apm_policy_form/settings_definition/apm_settings.ts @@ -33,7 +33,7 @@ export function getApmSettings({ 'xpack.apm.fleet_integration.settings.apm.hostDescription', { defaultMessage: - 'Choose a name and description to help identify how this integration will be used.', + 'Host defines the host and port the server is listening on. URL is the unchangeable, publicly reachable server URL for deployments on Elastic Cloud or ECK.', } ), @@ -164,10 +164,7 @@ export function getApmSettings({ ), rowDescription: i18n.translate( 'xpack.apm.fleet_integration.settings.apm.responseHeadersDescription', - { - defaultMessage: - 'Set limits on request headers sizes and timing configurations.', - } + { defaultMessage: 'Custom HTTP headers added to HTTP responses' } ), }, { diff --git a/x-pack/plugins/apm/public/components/fleet_integration/apm_policy_form/typings.ts b/x-pack/plugins/apm/public/components/fleet_integration/apm_policy_form/typings.ts index 7df1ccf1fb18f..4f741ceb46f49 100644 --- a/x-pack/plugins/apm/public/components/fleet_integration/apm_policy_form/typings.ts +++ b/x-pack/plugins/apm/public/components/fleet_integration/apm_policy_form/typings.ts @@ -7,12 +7,12 @@ import * as t from 'io-ts'; import { PackagePolicyConfigRecordEntry } from '../../../../../fleet/common'; -export { +export type { PackagePolicyCreateExtensionComponentProps, PackagePolicyEditExtensionComponentProps, } from '../../../../../fleet/public'; -export { +export type { NewPackagePolicy, PackagePolicy, PackagePolicyConfigRecordEntry, diff --git a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLExplorerLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLExplorerLink.tsx index 11b29f00155fc..72a29a079bc67 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLExplorerLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLExplorerLink.tsx @@ -10,7 +10,7 @@ import { EuiLink } from '@elastic/eui'; import { UI_SETTINGS } from '../../../../../../../../src/plugins/data/common'; import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context'; import { useMlHref, ML_PAGES } from '../../../../../../ml/public'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { TimePickerRefreshInterval } from '../../DatePicker/typings'; interface Props { @@ -37,7 +37,7 @@ export function useExplorerHref({ jobId }: { jobId: string }) { core, plugins: { ml }, } = useApmPluginContext(); - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const timePickerRefreshIntervalDefaults = core.uiSettings.get( diff --git a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLManageJobsLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLManageJobsLink.tsx index 5c8d464204090..eb7b531121753 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLManageJobsLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLManageJobsLink.tsx @@ -10,7 +10,7 @@ import React from 'react'; import { UI_SETTINGS } from '../../../../../../../../src/plugins/data/common'; import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context'; import { useMlHref, ML_PAGES } from '../../../../../../ml/public'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { TimePickerRefreshInterval } from '../../DatePicker/typings'; interface Props { @@ -24,7 +24,7 @@ export function MLManageJobsLink({ children, external }: Props) { plugins: { ml }, } = useApmPluginContext(); - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const timePickerRefreshIntervalDefaults = core.uiSettings.get( diff --git a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLSingleMetricLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLSingleMetricLink.tsx index a36beccd16be5..2964a8e2578c7 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLSingleMetricLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/MachineLearningLinks/MLSingleMetricLink.tsx @@ -10,7 +10,7 @@ import { EuiLink } from '@elastic/eui'; import { UI_SETTINGS } from '../../../../../../../../src/plugins/data/common'; import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context'; import { useMlHref, ML_PAGES } from '../../../../../../ml/public'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { TimePickerRefreshInterval } from '../../DatePicker/typings'; interface Props { @@ -53,7 +53,7 @@ export function useSingleMetricHref({ core, plugins: { ml }, } = useApmPluginContext(); - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const timePickerRefreshIntervalDefaults = core.uiSettings.get( diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/APMLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/APMLink.tsx index fbf4dff24fbf4..bcb305bd38ec3 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/APMLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/APMLink.tsx @@ -13,7 +13,7 @@ import { useLocation } from 'react-router-dom'; import url from 'url'; import { pickKeys } from '../../../../../common/utils/pick_keys'; import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { APMQueryParams, fromQuery, toQuery } from '../url_helpers'; interface Props extends EuiLinkAnchorProps { @@ -46,7 +46,7 @@ export function useAPMHref({ persistedFilters?: Array; query?: APMQueryParams; }) { - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const { basePath } = useApmPluginContext().core.http; const { search } = useLocation(); const nextQuery = { diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorOverviewLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorOverviewLink.tsx index b06de47472a11..ccd9bdff960b6 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorOverviewLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/ErrorOverviewLink.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { pickKeys } from '../../../../../common/utils/pick_keys'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { APMQueryParams } from '../url_helpers'; import { APMLink, APMLinkExtendProps } from './APMLink'; @@ -24,7 +24,7 @@ interface Props extends APMLinkExtendProps { } export function ErrorOverviewLink({ serviceName, query, ...rest }: Props) { - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); return ( showPopover(!isPopoverOpen); diff --git a/x-pack/plugins/apm/public/components/shared/charts/failed_transaction_rate_chart/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/failed_transaction_rate_chart/index.tsx index cda0058bdacd3..a5952a363a9e0 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/failed_transaction_rate_chart/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/failed_transaction_rate_chart/index.tsx @@ -14,7 +14,7 @@ import { APIReturnType } from '../../../../services/rest/createCallApmApi'; import { asPercent } from '../../../../../common/utils/formatters'; import { useFetcher } from '../../../../hooks/use_fetcher'; import { useTheme } from '../../../../hooks/use_theme'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { TimeseriesChart } from '../timeseries_chart'; import { useApmServiceContext } from '../../../../context/apm_service/use_apm_service_context'; import { @@ -58,7 +58,7 @@ export function FailedTransactionRateChart({ const theme = useTheme(); const { urlParams: { transactionName, comparisonEnabled, comparisonType }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { query: { rangeFrom, rangeTo }, diff --git a/x-pack/plugins/apm/public/components/shared/charts/latency_chart/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/latency_chart/index.tsx index 3cee9c22174ad..e19f78006d9fe 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/latency_chart/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/latency_chart/index.tsx @@ -17,7 +17,7 @@ import { useApmServiceContext } from '../../../../context/apm_service/use_apm_se import { LatencyAggregationType } from '../../../../../common/latency_aggregation_types'; import { getDurationFormatter } from '../../../../../common/utils/formatters'; import { useLicenseContext } from '../../../../context/license/use_license_context'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { useTheme } from '../../../../hooks/use_theme'; import { useTransactionLatencyChartsFetcher } from '../../../../hooks/use_transaction_latency_chart_fetcher'; import { TimeseriesChart } from '../../../shared/charts/timeseries_chart'; @@ -52,7 +52,7 @@ export function LatencyChart({ height, kuery, environment }: Props) { const history = useHistory(); const theme = useTheme(); const comparisonChartTheme = getComparisonChartTheme(theme); - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const { latencyAggregationType, comparisonEnabled } = urlParams; const license = useLicenseContext(); diff --git a/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/use_transaction_breakdown.ts b/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/use_transaction_breakdown.ts index 079b8455de7ad..a32f7ededea40 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/use_transaction_breakdown.ts +++ b/x-pack/plugins/apm/public/components/shared/charts/transaction_breakdown_chart/use_transaction_breakdown.ts @@ -6,7 +6,7 @@ */ import { useFetcher } from '../../../../hooks/use_fetcher'; -import { useUrlParams } from '../../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params'; import { useApmServiceContext } from '../../../../context/apm_service/use_apm_service_context'; import { useApmParams } from '../../../../hooks/use_apm_params'; import { useTimeRange } from '../../../../hooks/use_time_range'; @@ -20,7 +20,7 @@ export function useTransactionBreakdown({ }) { const { urlParams: { transactionName }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { query: { rangeFrom, rangeTo }, diff --git a/x-pack/plugins/apm/public/components/shared/kuery_bar/index.tsx b/x-pack/plugins/apm/public/components/shared/kuery_bar/index.tsx index 4dc24567259e6..20484e691d50b 100644 --- a/x-pack/plugins/apm/public/components/shared/kuery_bar/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/kuery_bar/index.tsx @@ -16,7 +16,7 @@ import { QuerySuggestion, } from '../../../../../../../src/plugins/data/public'; import { useApmPluginContext } from '../../../context/apm_plugin/use_apm_plugin_context'; -import { useUrlParams } from '../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../context/url_params_context/use_url_params'; import { useApmParams } from '../../../hooks/use_apm_params'; import { useDynamicDataViewFetcher } from '../../../hooks/use_dynamic_data_view'; import { fromQuery, toQuery } from '../Links/url_helpers'; @@ -52,7 +52,7 @@ export function KueryBar(props: { suggestions: [], isLoadingSuggestions: false, }); - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const location = useLocation(); const { data } = useApmPluginContext().plugins; diff --git a/x-pack/plugins/apm/public/components/shared/managed_table/index.tsx b/x-pack/plugins/apm/public/components/shared/managed_table/index.tsx index f1776abe83e97..5d49f1d9a8f18 100644 --- a/x-pack/plugins/apm/public/components/shared/managed_table/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/managed_table/index.tsx @@ -10,7 +10,7 @@ import { EuiBasicTable, EuiBasicTableColumn } from '@elastic/eui'; import { orderBy } from 'lodash'; import React, { ReactNode, useCallback, useMemo } from 'react'; import { useHistory } from 'react-router-dom'; -import { useUrlParams } from '../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../context/url_params_context/use_url_params'; import { fromQuery, toQuery } from '../Links/url_helpers'; // TODO: this should really be imported from EUI @@ -79,7 +79,7 @@ function UnoptimizedManagedTable(props: Props) { sortField = initialSortField, sortDirection = initialSortDirection, }, - } = useUrlParams(); + } = useLegacyUrlParams(); const renderedItems = useMemo(() => { const sortedItems = sortItems diff --git a/x-pack/plugins/apm/public/components/shared/time_comparison/index.tsx b/x-pack/plugins/apm/public/components/shared/time_comparison/index.tsx index 35a6bc7634813..9d077713ff12e 100644 --- a/x-pack/plugins/apm/public/components/shared/time_comparison/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/time_comparison/index.tsx @@ -13,7 +13,7 @@ import { useHistory } from 'react-router-dom'; import { euiStyled } from '../../../../../../../src/plugins/kibana_react/common'; import { useUiTracker } from '../../../../../observability/public'; import { TimeRangeComparisonEnum } from '../../../../common/runtime_types/comparison_type_rt'; -import { useUrlParams } from '../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../context/url_params_context/use_url_params'; import { useApmParams } from '../../../hooks/use_apm_params'; import { useBreakpoints } from '../../../hooks/use_breakpoints'; import { useTimeRange } from '../../../hooks/use_time_range'; @@ -127,7 +127,7 @@ export function TimeComparison() { const { urlParams: { comparisonEnabled, comparisonType }, - } = useUrlParams(); + } = useLegacyUrlParams(); const comparisonTypes = getComparisonTypes({ start: exactStart, diff --git a/x-pack/plugins/apm/public/components/shared/transaction_action_menu/TransactionActionMenu.tsx b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/TransactionActionMenu.tsx index a4f7c2b663484..2f856dce387bf 100644 --- a/x-pack/plugins/apm/public/components/shared/transaction_action_menu/TransactionActionMenu.tsx +++ b/x-pack/plugins/apm/public/components/shared/transaction_action_menu/TransactionActionMenu.tsx @@ -21,7 +21,7 @@ import { import { Transaction } from '../../../../typings/es_schemas/ui/transaction'; import { useApmPluginContext } from '../../../context/apm_plugin/use_apm_plugin_context'; import { useLicenseContext } from '../../../context/license/use_license_context'; -import { useUrlParams } from '../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../context/url_params_context/use_url_params'; import { CustomLinkMenuSection } from './custom_link_menu_section'; import { getSections } from './sections'; @@ -45,7 +45,7 @@ export function TransactionActionMenu({ transaction }: Props) { const { core } = useApmPluginContext(); const location = useLocation(); - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const [isActionPopoverOpen, setIsActionPopoverOpen] = useState(false); diff --git a/x-pack/plugins/apm/public/components/shared/transactions_table/index.tsx b/x-pack/plugins/apm/public/components/shared/transactions_table/index.tsx index d6d955b8ef5ab..6c934cc51e2f7 100644 --- a/x-pack/plugins/apm/public/components/shared/transactions_table/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/transactions_table/index.tsx @@ -20,7 +20,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { EuiCode } from '@elastic/eui'; import { APIReturnType } from '../../../services/rest/createCallApmApi'; import { useApmServiceContext } from '../../../context/apm_service/use_apm_service_context'; -import { useUrlParams } from '../../../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../../../context/url_params_context/use_url_params'; import { FETCH_STATUS, useFetcher } from '../../../hooks/use_fetcher'; import { TransactionOverviewLink } from '../Links/apm/transaction_overview_link'; import { getTimeRangeComparison } from '../time_comparison/get_time_range_comparison'; @@ -100,7 +100,7 @@ export function TransactionsTable({ const { transactionType, serviceName } = useApmServiceContext(); const { urlParams: { latencyAggregationType, comparisonType, comparisonEnabled }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { comparisonStart, comparisonEnd } = getTimeRangeComparison({ start, diff --git a/x-pack/plugins/apm/public/context/apm_service/apm_service_context.tsx b/x-pack/plugins/apm/public/context/apm_service/apm_service_context.tsx index 9d207eee2fbaa..c99ef519f9e69 100644 --- a/x-pack/plugins/apm/public/context/apm_service/apm_service_context.tsx +++ b/x-pack/plugins/apm/public/context/apm_service/apm_service_context.tsx @@ -23,14 +23,20 @@ export type APMServiceAlert = ValuesType< APIReturnType<'GET /internal/apm/services/{serviceName}/alerts'>['alerts'] >; -export const APMServiceContext = createContext<{ +export interface APMServiceContextValue { serviceName: string; agentName?: string; transactionType?: string; transactionTypes: string[]; alerts: APMServiceAlert[]; runtimeName?: string; -}>({ serviceName: '', transactionTypes: [], alerts: [] }); +} + +export const APMServiceContext = createContext({ + serviceName: '', + transactionTypes: [], + alerts: [], +}); export function ApmServiceContextProvider({ children, diff --git a/x-pack/plugins/apm/public/context/url_params_context/use_url_params.tsx b/x-pack/plugins/apm/public/context/url_params_context/use_url_params.tsx index 5e91bfd1549ed..7c7a00da728ad 100644 --- a/x-pack/plugins/apm/public/context/url_params_context/use_url_params.tsx +++ b/x-pack/plugins/apm/public/context/url_params_context/use_url_params.tsx @@ -10,7 +10,7 @@ import { useMemo, useContext } from 'react'; import type { ApmUrlParams } from './types'; import { UrlParamsContext } from './url_params_context'; -export function useUrlParams(): Assign< +export function useLegacyUrlParams(): Assign< React.ContextType, { urlParams: ApmUrlParams } > { diff --git a/x-pack/plugins/apm/public/hooks/use_comparison.ts b/x-pack/plugins/apm/public/hooks/use_comparison.ts index 2875d973a5e18..dbd37c25784cf 100644 --- a/x-pack/plugins/apm/public/hooks/use_comparison.ts +++ b/x-pack/plugins/apm/public/hooks/use_comparison.ts @@ -9,7 +9,7 @@ import { getComparisonChartTheme, getTimeRangeComparison, } from '../components/shared/time_comparison/get_time_range_comparison'; -import { useUrlParams } from '../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../context/url_params_context/use_url_params'; import { useApmParams } from './use_apm_params'; import { useTheme } from './use_theme'; import { useTimeRange } from './use_time_range'; @@ -31,7 +31,7 @@ export function useComparison() { const { urlParams: { comparisonType, comparisonEnabled }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { offset } = getTimeRangeComparison({ start, diff --git a/x-pack/plugins/apm/public/hooks/use_search_strategy.ts b/x-pack/plugins/apm/public/hooks/use_search_strategy.ts index 275eddb68ae00..95bc8cb7435a2 100644 --- a/x-pack/plugins/apm/public/hooks/use_search_strategy.ts +++ b/x-pack/plugins/apm/public/hooks/use_search_strategy.ts @@ -31,7 +31,7 @@ import { APM_SEARCH_STRATEGIES, } from '../../common/search_strategies/constants'; import { useApmServiceContext } from '../context/apm_service/use_apm_service_context'; -import { useUrlParams } from '../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../context/url_params_context/use_url_params'; import { ApmPluginStartDeps } from '../plugin'; @@ -103,7 +103,7 @@ export function useSearchStrategy< query: { kuery, environment, rangeFrom, rangeTo }, } = useApmParams('/services/{serviceName}/transactions/view'); const { start, end } = useTimeRange({ rangeFrom, rangeTo }); - const { urlParams } = useUrlParams(); + const { urlParams } = useLegacyUrlParams(); const { transactionName } = urlParams; const [rawResponse, setRawResponse] = useReducer( diff --git a/x-pack/plugins/apm/public/hooks/use_transaction_latency_chart_fetcher.ts b/x-pack/plugins/apm/public/hooks/use_transaction_latency_chart_fetcher.ts index d44ec853a242c..0ed3de14c129f 100644 --- a/x-pack/plugins/apm/public/hooks/use_transaction_latency_chart_fetcher.ts +++ b/x-pack/plugins/apm/public/hooks/use_transaction_latency_chart_fetcher.ts @@ -7,7 +7,7 @@ import { useMemo } from 'react'; import { useFetcher } from './use_fetcher'; -import { useUrlParams } from '../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../context/url_params_context/use_url_params'; import { useApmServiceContext } from '../context/apm_service/use_apm_service_context'; import { getLatencyChartSelector } from '../selectors/latency_chart_selectors'; import { useTheme } from './use_theme'; @@ -31,7 +31,7 @@ export function useTransactionLatencyChartsFetcher({ comparisonType, comparisonEnabled, }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { query: { rangeFrom, rangeTo }, diff --git a/x-pack/plugins/apm/public/hooks/use_transaction_trace_samples_fetcher.ts b/x-pack/plugins/apm/public/hooks/use_transaction_trace_samples_fetcher.ts index 741100aca16e9..93349d3f955b8 100644 --- a/x-pack/plugins/apm/public/hooks/use_transaction_trace_samples_fetcher.ts +++ b/x-pack/plugins/apm/public/hooks/use_transaction_trace_samples_fetcher.ts @@ -6,7 +6,7 @@ */ import { useFetcher } from './use_fetcher'; -import { useUrlParams } from '../context/url_params_context/use_url_params'; +import { useLegacyUrlParams } from '../context/url_params_context/use_url_params'; import { useApmServiceContext } from '../context/apm_service/use_apm_service_context'; import { useApmParams } from './use_apm_params'; import { useTimeRange } from './use_time_range'; @@ -39,7 +39,7 @@ export function useTransactionTraceSamplesFetcher({ const { urlParams: { transactionId, traceId, sampleRangeFrom, sampleRangeTo }, - } = useUrlParams(); + } = useLegacyUrlParams(); const { data = INITIAL_DATA, diff --git a/x-pack/plugins/apm/public/index.ts b/x-pack/plugins/apm/public/index.ts index 2734269b9cff9..9b2175dd465bc 100644 --- a/x-pack/plugins/apm/public/index.ts +++ b/x-pack/plugins/apm/public/index.ts @@ -23,4 +23,4 @@ export const plugin: PluginInitializer = ( pluginInitializerContext: PluginInitializerContext ) => new ApmPlugin(pluginInitializerContext); -export { ApmPluginSetup, ApmPluginStart }; +export type { ApmPluginSetup, ApmPluginStart }; diff --git a/x-pack/plugins/apm/scripts/test/api.js b/x-pack/plugins/apm/scripts/test/api.js index 4f0d82d0c1163..1905c8eb7c2dd 100644 --- a/x-pack/plugins/apm/scripts/test/api.js +++ b/x-pack/plugins/apm/scripts/test/api.js @@ -33,9 +33,15 @@ const { argv } = yargs(process.argv.slice(2)) description: 'Run all tests (an instance of Elasticsearch and kibana are needs to be available)', }) + .option('grep', { + alias: 'spec', + default: false, + type: 'string', + description: 'Specify the spec files to run', + }) .help(); -const { trial, server, runner } = argv; +const { trial, server, runner, grep } = argv; const license = trial ? 'trial' : 'basic'; console.log(`License: ${license}`); @@ -46,7 +52,10 @@ if (server) { } else if (runner) { ftrScript = 'functional_test_runner'; } -childProcess.execSync( - `node ../../../../scripts/${ftrScript} --config ../../../../test/apm_api_integration/${license}/config.ts`, - { cwd: path.join(__dirname), stdio: 'inherit' } -); + +const grepArg = grep ? `--grep "${grep}"` : ''; +const cmd = `node ../../../../scripts/${ftrScript} ${grepArg} --config ../../../../test/apm_api_integration/${license}/config.ts`; + +console.log(`Running ${cmd}`); + +childProcess.execSync(cmd, { cwd: path.join(__dirname), stdio: 'inherit' }); diff --git a/x-pack/plugins/apm/scripts/test/e2e.js b/x-pack/plugins/apm/scripts/test/e2e.js index b3ce510a8e569..13055dce2fec5 100644 --- a/x-pack/plugins/apm/scripts/test/e2e.js +++ b/x-pack/plugins/apm/scripts/test/e2e.js @@ -20,7 +20,7 @@ const { argv } = yargs(process.argv.slice(2)) .option('server', { default: false, type: 'boolean', - description: 'Start Elasticsearch and kibana', + description: 'Start Elasticsearch and Kibana', }) .option('runner', { default: false, @@ -28,14 +28,26 @@ const { argv } = yargs(process.argv.slice(2)) description: 'Run all tests (an instance of Elasticsearch and kibana are needs to be available)', }) + .option('grep', { + alias: 'spec', + default: false, + type: 'string', + description: + 'Specify the spec files to run (use doublequotes for glob matching)', + }) .option('open', { default: false, type: 'boolean', description: 'Opens the Cypress Test Runner', }) + .option('bail', { + default: false, + type: 'boolean', + description: 'stop tests after the first failure', + }) .help(); -const { server, runner, open, kibanaInstallDir } = argv; +const { server, runner, open, grep, bail, kibanaInstallDir } = argv; const e2eDir = path.join(__dirname, '../../ftr_e2e'); @@ -46,9 +58,10 @@ if (server) { ftrScript = 'functional_test_runner'; } -const config = open ? './cypress_open.ts' : './cypress_run.ts'; +const config = open ? './ftr_config_open.ts' : './ftr_config_run.ts'; +const grepArg = grep ? `--grep "${grep}"` : ''; +const bailArg = bail ? `--bail` : ''; +const cmd = `node ../../../../scripts/${ftrScript} --config ${config} ${grepArg} ${bailArg} --kibana-install-dir '${kibanaInstallDir}'`; -childProcess.execSync( - `node ../../../../scripts/${ftrScript} --config ${config} --kibana-install-dir '${kibanaInstallDir}'`, - { cwd: e2eDir, stdio: 'inherit' } -); +console.log(`Running ${cmd}`); +childProcess.execSync(cmd, { cwd: e2eDir, stdio: 'inherit' }); diff --git a/x-pack/plugins/apm/server/index.ts b/x-pack/plugins/apm/server/index.ts index 4b5c2b5d6134d..bd30f9e212687 100644 --- a/x-pack/plugins/apm/server/index.ts +++ b/x-pack/plugins/apm/server/index.ts @@ -37,7 +37,7 @@ const configSchema = schema.object({ schema.literal(SearchAggregatedTransactionSetting.always), schema.literal(SearchAggregatedTransactionSetting.never), ], - { defaultValue: SearchAggregatedTransactionSetting.never } + { defaultValue: SearchAggregatedTransactionSetting.auto } ), telemetryCollectionEnabled: schema.boolean({ defaultValue: true }), metricsInterval: schema.number({ defaultValue: 30 }), @@ -112,11 +112,11 @@ export const plugin = (initContext: PluginInitializerContext) => export { APM_SERVER_FEATURE_ID } from '../common/alert_types'; export { APMPlugin } from './plugin'; -export { APMPluginSetup } from './types'; -export { +export type { APMPluginSetup } from './types'; +export type { APMServerRouteRepository, APIEndpoint, } from './routes/get_global_apm_server_route_repository'; -export { APMRouteHandlerResources } from './routes/typings'; +export type { APMRouteHandlerResources } from './routes/typings'; export type { ProcessorEvent } from '../common/processor_event'; diff --git a/x-pack/plugins/apm/server/lib/helpers/transactions/index.ts b/x-pack/plugins/apm/server/lib/helpers/transactions/index.ts index 473d34cd5b6fc..edaae8cadc1d5 100644 --- a/x-pack/plugins/apm/server/lib/helpers/transactions/index.ts +++ b/x-pack/plugins/apm/server/lib/helpers/transactions/index.ts @@ -63,18 +63,23 @@ export async function getSearchAggregatedTransactions({ apmEventClient: APMEventClient; kuery: string; }): Promise { - const searchAggregatedTransactions = config.searchAggregatedTransactions; + switch (config.searchAggregatedTransactions) { + case SearchAggregatedTransactionSetting.always: + return kuery + ? getHasAggregatedTransactions({ start, end, apmEventClient, kuery }) + : true; - if ( - kuery || - searchAggregatedTransactions === SearchAggregatedTransactionSetting.auto - ) { - return getHasAggregatedTransactions({ start, end, apmEventClient, kuery }); - } + case SearchAggregatedTransactionSetting.auto: + return getHasAggregatedTransactions({ + start, + end, + apmEventClient, + kuery, + }); - return ( - searchAggregatedTransactions === SearchAggregatedTransactionSetting.always - ); + case SearchAggregatedTransactionSetting.never: + return false; + } } export function getTransactionDurationFieldForTransactions( diff --git a/x-pack/plugins/apm/server/lib/services/get_services_detailed_statistics/get_service_transaction_detailed_statistics.ts b/x-pack/plugins/apm/server/lib/services/get_services_detailed_statistics/get_service_transaction_detailed_statistics.ts index 686555e7764ab..ea153a5ddcd4c 100644 --- a/x-pack/plugins/apm/server/lib/services/get_services_detailed_statistics/get_service_transaction_detailed_statistics.ts +++ b/x-pack/plugins/apm/server/lib/services/get_services_detailed_statistics/get_service_transaction_detailed_statistics.ts @@ -70,7 +70,7 @@ export async function getServiceTransactionDetailedStatistics({ }; const response = await apmEventClient.search( - 'get_service_transaction_stats', + 'get_service_transaction_detail_stats', { apm: { events: [ @@ -82,6 +82,7 @@ export async function getServiceTransactionDetailedStatistics({ query: { bool: { filter: [ + { terms: { [SERVICE_NAME]: serviceNames } }, ...getDocumentTypeFilterForTransactions( searchAggregatedTransactions ), @@ -95,8 +96,6 @@ export async function getServiceTransactionDetailedStatistics({ services: { terms: { field: SERVICE_NAME, - include: serviceNames, - size: serviceNames.length, }, aggs: { transactionType: { diff --git a/x-pack/plugins/apm/server/lib/settings/apm_indices/get_apm_indices.ts b/x-pack/plugins/apm/server/lib/settings/apm_indices/get_apm_indices.ts index 107493af1a0c0..a37720cbc3790 100644 --- a/x-pack/plugins/apm/server/lib/settings/apm_indices/get_apm_indices.ts +++ b/x-pack/plugins/apm/server/lib/settings/apm_indices/get_apm_indices.ts @@ -16,7 +16,7 @@ import { APMRouteHandlerResources } from '../../../routes/typings'; import { withApmSpan } from '../../../utils/with_apm_span'; import { ApmIndicesConfig } from '../../../../../observability/common/typings'; -export { ApmIndicesConfig }; +export type { ApmIndicesConfig }; type ISavedObjectsClient = Pick; diff --git a/x-pack/plugins/apm/server/tutorial/index.ts b/x-pack/plugins/apm/server/tutorial/index.ts index 66ff8f5b2c92c..f04b794091ff2 100644 --- a/x-pack/plugins/apm/server/tutorial/index.ts +++ b/x-pack/plugins/apm/server/tutorial/index.ts @@ -103,7 +103,6 @@ It allows you to monitor the performance of thousands of applications in real ti } ), euiIconType: 'apmApp', - eprPackageOverlap: 'apm', integrationBrowserCategories: ['web'], artifacts, customStatusCheckName: 'apm_fleet_server_status_check', diff --git a/x-pack/plugins/banners/common/index.ts b/x-pack/plugins/banners/common/index.ts index a4c38a58ab572..348d42adb7d8f 100644 --- a/x-pack/plugins/banners/common/index.ts +++ b/x-pack/plugins/banners/common/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export { BannerInfoResponse, BannerPlacement, BannerConfiguration } from './types'; +export type { BannerInfoResponse, BannerPlacement, BannerConfiguration } from './types'; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/expression_types/embeddable.ts b/x-pack/plugins/canvas/canvas_plugin_src/expression_types/embeddable.ts index ac2e8e8babee1..66cb95a4a210a 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/expression_types/embeddable.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/expression_types/embeddable.ts @@ -10,7 +10,8 @@ import { EmbeddableInput } from '../../../../../src/plugins/embeddable/common/'; import { EmbeddableTypes } from './embeddable_types'; export const EmbeddableExpressionType = 'embeddable'; -export { EmbeddableTypes, EmbeddableInput }; +export type { EmbeddableInput }; +export { EmbeddableTypes }; export interface EmbeddableExpression { /** diff --git a/x-pack/plugins/canvas/common/index.ts b/x-pack/plugins/canvas/common/index.ts index 5bae69e8601b2..51a661f6e8d1e 100644 --- a/x-pack/plugins/canvas/common/index.ts +++ b/x-pack/plugins/canvas/common/index.ts @@ -9,4 +9,5 @@ export const UI_SETTINGS = { ENABLE_LABS_UI: 'labs:canvas:enable_ui', }; -export { CANVAS_APP_LOCATOR, CanvasAppLocator, CanvasAppLocatorParams } from './locator'; +export type { CanvasAppLocator, CanvasAppLocatorParams } from './locator'; +export { CANVAS_APP_LOCATOR } from './locator'; diff --git a/x-pack/plugins/canvas/public/components/color_manager/index.ts b/x-pack/plugins/canvas/public/components/color_manager/index.ts index 17856a88bcc00..937afeb438006 100644 --- a/x-pack/plugins/canvas/public/components/color_manager/index.ts +++ b/x-pack/plugins/canvas/public/components/color_manager/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { ColorManager, Props } from './color_manager'; +export type { Props } from './color_manager'; +export { ColorManager } from './color_manager'; diff --git a/x-pack/plugins/canvas/public/components/color_picker/index.ts b/x-pack/plugins/canvas/public/components/color_picker/index.ts index ba411db1129e5..709b3535b5d58 100644 --- a/x-pack/plugins/canvas/public/components/color_picker/index.ts +++ b/x-pack/plugins/canvas/public/components/color_picker/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { ColorPicker, Props } from './color_picker'; +export type { Props } from './color_picker'; +export { ColorPicker } from './color_picker'; diff --git a/x-pack/plugins/canvas/public/components/color_picker_popover/index.ts b/x-pack/plugins/canvas/public/components/color_picker_popover/index.ts index 76663397ff695..08bf41f2fbc03 100644 --- a/x-pack/plugins/canvas/public/components/color_picker_popover/index.ts +++ b/x-pack/plugins/canvas/public/components/color_picker_popover/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { ColorPickerPopover, Props } from './color_picker_popover'; +export type { Props } from './color_picker_popover'; +export { ColorPickerPopover } from './color_picker_popover'; diff --git a/x-pack/plugins/canvas/public/components/embeddable_flyout/index.ts b/x-pack/plugins/canvas/public/components/embeddable_flyout/index.ts index 6acc4051e1ecc..98943a820e37a 100644 --- a/x-pack/plugins/canvas/public/components/embeddable_flyout/index.ts +++ b/x-pack/plugins/canvas/public/components/embeddable_flyout/index.ts @@ -6,7 +6,5 @@ */ export { EmbeddableFlyoutPortal, AddEmbeddablePanel } from './flyout'; -export { - AddEmbeddableFlyout as AddEmbeddableFlyoutComponent, - Props as AddEmbeddableFlyoutComponentProps, -} from './flyout.component'; +export type { Props as AddEmbeddableFlyoutComponentProps } from './flyout.component'; +export { AddEmbeddableFlyout as AddEmbeddableFlyoutComponent } from './flyout.component'; diff --git a/x-pack/plugins/canvas/public/components/paginate/index.tsx b/x-pack/plugins/canvas/public/components/paginate/index.tsx index f320860bd903b..12717a07f4cf9 100644 --- a/x-pack/plugins/canvas/public/components/paginate/index.tsx +++ b/x-pack/plugins/canvas/public/components/paginate/index.tsx @@ -9,7 +9,7 @@ import React, { useState, useEffect, useRef } from 'react'; import PropTypes from 'prop-types'; import { Paginate as Component, PaginateProps, PaginateChildProps } from './paginate'; -export { PaginateProps, PaginateChildProps }; +export type { PaginateProps, PaginateChildProps }; export interface InPaginateProps { perPage?: number; startPage?: number; diff --git a/x-pack/plugins/canvas/public/components/popover/index.ts b/x-pack/plugins/canvas/public/components/popover/index.ts index e1d8a5c63c28b..f9d7e3c0501a8 100644 --- a/x-pack/plugins/canvas/public/components/popover/index.ts +++ b/x-pack/plugins/canvas/public/components/popover/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { Popover, ClosePopoverFn } from './popover'; +export type { ClosePopoverFn } from './popover'; +export { Popover } from './popover'; diff --git a/x-pack/plugins/canvas/public/components/saved_elements_modal/index.ts b/x-pack/plugins/canvas/public/components/saved_elements_modal/index.ts index 9656dfa8ad487..b4b5d78646aa4 100644 --- a/x-pack/plugins/canvas/public/components/saved_elements_modal/index.ts +++ b/x-pack/plugins/canvas/public/components/saved_elements_modal/index.ts @@ -6,7 +6,5 @@ */ export { SavedElementsModal } from './saved_elements_modal'; -export { - SavedElementsModal as SavedElementsModalComponent, - Props as SavedElementsModalComponentProps, -} from './saved_elements_modal.component'; +export type { Props as SavedElementsModalComponentProps } from './saved_elements_modal.component'; +export { SavedElementsModal as SavedElementsModalComponent } from './saved_elements_modal.component'; diff --git a/x-pack/plugins/canvas/public/components/workpad/workpad.component.tsx b/x-pack/plugins/canvas/public/components/workpad/workpad.component.tsx index 1ac737bc543eb..740f71eab085a 100644 --- a/x-pack/plugins/canvas/public/components/workpad/workpad.component.tsx +++ b/x-pack/plugins/canvas/public/components/workpad/workpad.component.tsx @@ -11,7 +11,11 @@ import Style from 'style-it'; // @ts-expect-error import { WorkpadPage } from '../workpad_page'; import { Fullscreen } from '../fullscreen'; -import { HEADER_BANNER_HEIGHT, WORKPAD_CANVAS_BUFFER } from '../../../common/lib/constants'; +import { + HEADER_BANNER_HEIGHT, + WORKPAD_CANVAS_BUFFER, + DEFAULT_WORKPAD_CSS, +} from '../../../common/lib/constants'; import { CommitFn, CanvasPage } from '../../../types'; import { WorkpadShortcuts } from './workpad_shortcuts.component'; @@ -122,7 +126,7 @@ export const Workpad: FC = ({ // NOTE: the data-shared-* attributes here are used for reporting return Style.it( - workpadCss, + workpadCss || DEFAULT_WORKPAD_CSS,

{ const renderers: string[] = []; diff --git a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/utils.ts b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/utils.ts index 311ef73e1c973..bee0e1f3a5177 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/utils.ts +++ b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/utils.ts @@ -9,6 +9,7 @@ import type { RedirectOptions } from 'src/plugins/share/public'; import { CANVAS_APP_LOCATOR } from '../../../../common/locator'; import { CanvasAppLocatorParams } from '../../../../common/locator'; import { CanvasWorkpad } from '../../../../types'; +import { JobAppParamsPDFV2 } from '../../../../../reporting/public'; export interface CanvasWorkpadSharingData { workpad: Pick; @@ -18,7 +19,7 @@ export interface CanvasWorkpadSharingData { export function getPdfJobParams( { workpad: { id, name: title, width, height }, pageCount }: CanvasWorkpadSharingData, version: string -) { +): JobAppParamsPDFV2 { // The viewport in Reporting by specifying the dimensions. In order for things to work, // we need a viewport that will include all of the pages in the workpad. The viewport // also needs to include any offset values from the 0,0 position, otherwise the cropped diff --git a/x-pack/plugins/canvas/public/index.ts b/x-pack/plugins/canvas/public/index.ts index a15b15fcae333..95d4333c6e9e5 100644 --- a/x-pack/plugins/canvas/public/index.ts +++ b/x-pack/plugins/canvas/public/index.ts @@ -10,7 +10,7 @@ import { CoreStart } from '../../../../src/core/public'; import { CanvasServices } from './services'; import { CanvasSetup, CanvasStart, CanvasStartDeps, CanvasPlugin } from './plugin'; -export { CanvasSetup, CanvasStart }; +export type { CanvasSetup, CanvasStart }; export interface WithKibanaProps { kibana: { diff --git a/x-pack/plugins/canvas/public/plugin.tsx b/x-pack/plugins/canvas/public/plugin.tsx index 723d1afea2860..5d1f05fdbe8bf 100644 --- a/x-pack/plugins/canvas/public/plugin.tsx +++ b/x-pack/plugins/canvas/public/plugin.tsx @@ -37,7 +37,7 @@ import { getPluginApi, CanvasApi } from './plugin_api'; import { setupExpressions } from './setup_expressions'; import { pluginServiceRegistry } from './services/kibana'; -export { CoreStart, CoreSetup }; +export type { CoreStart, CoreSetup }; /** * These are the private interfaces for the services your plugin depends on. diff --git a/x-pack/plugins/canvas/public/routes/workpad/index.tsx b/x-pack/plugins/canvas/public/routes/workpad/index.tsx index 0b6153bc06afd..1b46a5cf78df1 100644 --- a/x-pack/plugins/canvas/public/routes/workpad/index.tsx +++ b/x-pack/plugins/canvas/public/routes/workpad/index.tsx @@ -9,7 +9,8 @@ import { RouteComponentProps } from 'react-router-dom'; export { WorkpadRoute, ExportWorkpadRoute } from './workpad_route'; -export { WorkpadRoutingContext, WorkpadRoutingContextType } from './workpad_routing_context'; +export type { WorkpadRoutingContextType } from './workpad_routing_context'; +export { WorkpadRoutingContext } from './workpad_routing_context'; export interface WorkpadRouteParams { id: string; diff --git a/x-pack/plugins/canvas/public/services/legacy/index.ts b/x-pack/plugins/canvas/public/services/legacy/index.ts index fdc4e30cabe51..82ef3f248f7fd 100644 --- a/x-pack/plugins/canvas/public/services/legacy/index.ts +++ b/x-pack/plugins/canvas/public/services/legacy/index.ts @@ -10,7 +10,7 @@ import { CoreSetup, CoreStart, AppUpdater } from '../../../../../../src/core/pub import { CanvasSetupDeps, CanvasStartDeps } from '../../plugin'; import { searchServiceFactory } from './search'; -export { SearchService } from './search'; +export type { SearchService } from './search'; export { ExpressionsService } from '../../../../../../src/plugins/expressions/common'; export * from './context'; diff --git a/x-pack/plugins/canvas/server/mocks/index.ts b/x-pack/plugins/canvas/server/mocks/index.ts index 1cb39c690df97..f3d3ef955d0e4 100644 --- a/x-pack/plugins/canvas/server/mocks/index.ts +++ b/x-pack/plugins/canvas/server/mocks/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { workpadRouteContextMock, MockWorkpadRouteContext } from './workpad_route_context'; +export type { MockWorkpadRouteContext } from './workpad_route_context'; +export { workpadRouteContextMock } from './workpad_route_context'; diff --git a/x-pack/plugins/cases/common/api/runtime_types.ts b/x-pack/plugins/cases/common/api/runtime_types.ts index 7edc1162c0e81..c807d4b31b751 100644 --- a/x-pack/plugins/cases/common/api/runtime_types.ts +++ b/x-pack/plugins/cases/common/api/runtime_types.ts @@ -60,7 +60,7 @@ export const decodeOrThrow = const getExcessProps = (props: rt.Props, r: Record): string[] => { const ex: string[] = []; for (const k of Object.keys(r)) { - if (!props.hasOwnProperty(k)) { + if (!Object.prototype.hasOwnProperty.call(props, k)) { ex.push(k); } } @@ -89,5 +89,5 @@ export function excess | rt.PartialType & { + rule?: Exclude & { uuid: string[] }; + building_block_type?: string[]; + workflow_status?: string[]; +}; + export interface Ecs { _id: string; _index?: string; signal?: SignalEcs; + kibana?: { + alert: SignalEcsAAD; + }; } export type CaseActionConnector = ActionConnector; diff --git a/x-pack/plugins/cases/public/common/lib/kibana/kibana_react.mock.ts b/x-pack/plugins/cases/public/common/lib/kibana/kibana_react.mock.ts index 09f0215f5629f..19276a7afd1b8 100644 --- a/x-pack/plugins/cases/public/common/lib/kibana/kibana_react.mock.ts +++ b/x-pack/plugins/cases/public/common/lib/kibana/kibana_react.mock.ts @@ -5,6 +5,8 @@ * 2.0. */ +/* eslint-disable react/display-name */ + import React from 'react'; import { RecursivePartial } from '@elastic/eui/src/components/common'; diff --git a/x-pack/plugins/cases/public/common/shared_imports.ts b/x-pack/plugins/cases/public/common/shared_imports.ts index 4641fcfa2167c..21040543fae69 100644 --- a/x-pack/plugins/cases/public/common/shared_imports.ts +++ b/x-pack/plugins/cases/public/common/shared_imports.ts @@ -5,31 +5,33 @@ * 2.0. */ +export type { + FieldHook, + FieldValidateResponse, + FormData, + FormHook, + FormSchema, + ValidationError, + ValidationFunc, + FieldConfig, + ValidationConfig, +} from '../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; export { getUseField, getFieldValidityAndErrorMessage, - FieldHook, - FieldValidateResponse, FIELD_TYPES, Form, - FormData, FormDataProvider, - FormHook, - FormSchema, UseField, UseMultiFields, useForm, useFormContext, useFormData, - ValidationError, - ValidationFunc, VALIDATION_TYPES, - FieldConfig, - ValidationConfig, } from '../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; export { Field, SelectField, } from '../../../../../src/plugins/es_ui_shared/static/forms/components'; export { fieldValidators } from '../../../../../src/plugins/es_ui_shared/static/forms/helpers'; -export { ERROR_CODE } from '../../../../../src/plugins/es_ui_shared/static/forms/helpers/field_validators/types'; +export type { ERROR_CODE } from '../../../../../src/plugins/es_ui_shared/static/forms/helpers/field_validators/types'; diff --git a/x-pack/plugins/cases/public/components/__mock__/form.ts b/x-pack/plugins/cases/public/components/__mock__/form.ts index aa40ea0421b4c..a2bd59d5dd541 100644 --- a/x-pack/plugins/cases/public/components/__mock__/form.ts +++ b/x-pack/plugins/cases/public/components/__mock__/form.ts @@ -36,7 +36,7 @@ export const mockFormHook = { __readFieldConfigFromSchema: jest.fn(), }; -export const getFormMock = (sampleData: any) => ({ +export const getFormMock = (sampleData: unknown) => ({ ...mockFormHook, submit: () => Promise.resolve({ diff --git a/x-pack/plugins/cases/public/components/all_cases/expanded_row.tsx b/x-pack/plugins/cases/public/components/all_cases/expanded_row.tsx index 59efcf868c9ee..2b43fbf63095e 100644 --- a/x-pack/plugins/cases/public/components/all_cases/expanded_row.tsx +++ b/x-pack/plugins/cases/public/components/all_cases/expanded_row.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { EuiBasicTable as _EuiBasicTable } from '@elastic/eui'; +import { EuiBasicTable } from '@elastic/eui'; import styled from 'styled-components'; import { Case, SubCase } from '../../containers/types'; import { CasesColumns } from './columns'; @@ -14,7 +14,7 @@ import { AssociationType } from '../../../common'; type ExpandedRowMap = Record | {}; -const EuiBasicTable: any = _EuiBasicTable; +// @ts-expect-error TS2769 const BasicTable = styled(EuiBasicTable)` thead { display: none; diff --git a/x-pack/plugins/cases/public/components/all_cases/index.test.tsx b/x-pack/plugins/cases/public/components/all_cases/index.test.tsx index a387c5eae3834..f55c871f4922a 100644 --- a/x-pack/plugins/cases/public/components/all_cases/index.test.tsx +++ b/x-pack/plugins/cases/public/components/all_cases/index.test.tsx @@ -303,7 +303,10 @@ describe('AllCasesGeneric', () => { await waitFor(() => { result.current.map( - (i, key) => i.name != null && !i.hasOwnProperty('actions') && checkIt(`${i.name}`, key) + (i, key) => + i.name != null && + !Object.prototype.hasOwnProperty.call(i, 'actions') && + checkIt(`${i.name}`, key) ); }); }); @@ -378,7 +381,9 @@ describe('AllCasesGeneric', () => { }) ); await waitFor(() => { - result.current.map((i) => i.name != null && !i.hasOwnProperty('actions')); + result.current.map( + (i) => i.name != null && !Object.prototype.hasOwnProperty.call(i, 'actions') + ); expect(wrapper.find(`a[data-test-subj="case-details-link"]`).exists()).toBeFalsy(); }); }); diff --git a/x-pack/plugins/cases/public/components/all_cases/selector_modal/index.tsx b/x-pack/plugins/cases/public/components/all_cases/selector_modal/index.tsx index 4e8334ebceec0..cbfb24f18c97e 100644 --- a/x-pack/plugins/cases/public/components/all_cases/selector_modal/index.tsx +++ b/x-pack/plugins/cases/public/components/all_cases/selector_modal/index.tsx @@ -87,5 +87,8 @@ export const AllCasesSelectorModal: React.FC = React ); }); + +AllCasesSelectorModal.displayName = 'AllCasesSelectorModal'; + // eslint-disable-next-line import/no-default-export export { AllCasesSelectorModal as default }; diff --git a/x-pack/plugins/cases/public/components/all_cases/table.tsx b/x-pack/plugins/cases/public/components/all_cases/table.tsx index 876007494d276..3f80fc8f0d7c4 100644 --- a/x-pack/plugins/cases/public/components/all_cases/table.tsx +++ b/x-pack/plugins/cases/public/components/all_cases/table.tsx @@ -10,7 +10,7 @@ import { EuiEmptyPrompt, EuiLoadingContent, EuiTableSelectionType, - EuiBasicTable as _EuiBasicTable, + EuiBasicTable, EuiBasicTableProps, } from '@elastic/eui'; import classnames from 'classnames'; @@ -40,12 +40,12 @@ interface CasesTableProps { selection: EuiTableSelectionType; showActions: boolean; sorting: EuiBasicTableProps['sorting']; - tableRef: MutableRefObject<_EuiBasicTable | undefined>; + tableRef: MutableRefObject; tableRowProps: EuiBasicTableProps['rowProps']; userCanCrud: boolean; } -const EuiBasicTable: any = _EuiBasicTable; +// @ts-expect-error TS2769 const BasicTable = styled(EuiBasicTable)` ${({ theme }) => ` .euiTableRow-isExpandedRow.euiTableRow-isSelectable .euiTableCellContent { diff --git a/x-pack/plugins/cases/public/components/configure_cases/index.tsx b/x-pack/plugins/cases/public/components/configure_cases/index.tsx index 788c6eeb61b32..cf7962f08db93 100644 --- a/x-pack/plugins/cases/public/components/configure_cases/index.tsx +++ b/x-pack/plugins/cases/public/components/configure_cases/index.tsx @@ -242,5 +242,7 @@ export const ConfigureCases: React.FC = React.memo((props) ); }); +ConfigureCases.displayName = 'ConfigureCases'; + // eslint-disable-next-line import/no-default-export export default ConfigureCases; diff --git a/x-pack/plugins/cases/public/components/connectors/connectors_registry.ts b/x-pack/plugins/cases/public/components/connectors/connectors_registry.ts index 2e02cb290c3c8..8174733301348 100644 --- a/x-pack/plugins/cases/public/components/connectors/connectors_registry.ts +++ b/x-pack/plugins/cases/public/components/connectors/connectors_registry.ts @@ -9,8 +9,25 @@ import { i18n } from '@kbn/i18n'; import { CaseConnector, CaseConnectorsRegistry } from './types'; export const createCaseConnectorsRegistry = (): CaseConnectorsRegistry => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any const connectors: Map> = new Map(); + function assertConnectorExists( + connector: CaseConnector | undefined | null, + id: string + ): asserts connector { + if (!connector) { + throw new Error( + i18n.translate('xpack.cases.connecors.get.missingCaseConnectorErrorMessage', { + defaultMessage: 'Object type "{id}" is not registered.', + values: { + id, + }, + }) + ); + } + } + const registry: CaseConnectorsRegistry = { has: (id: string) => connectors.has(id), register: (connector: CaseConnector) => { @@ -28,17 +45,9 @@ export const createCaseConnectorsRegistry = (): CaseConnectorsRegistry => { connectors.set(connector.id, connector); }, get: (id: string): CaseConnector => { - if (!connectors.has(id)) { - throw new Error( - i18n.translate('xpack.cases.connecors.get.missingCaseConnectorErrorMessage', { - defaultMessage: 'Object type "{id}" is not registered.', - values: { - id, - }, - }) - ); - } - return connectors.get(id)!; + const connector = connectors.get(id); + assertConnectorExists(connector, id); + return connector; }, list: () => { return Array.from(connectors).map(([id, connector]) => connector); diff --git a/x-pack/plugins/cases/public/components/connectors/types.ts b/x-pack/plugins/cases/public/components/connectors/types.ts index 5bbd77c790901..8bc978152b796 100644 --- a/x-pack/plugins/cases/public/components/connectors/types.ts +++ b/x-pack/plugins/cases/public/components/connectors/types.ts @@ -15,7 +15,7 @@ import { } from '../../../common'; import { CaseActionConnector } from '../types'; -export { ThirdPartyField as AllThirdPartyFields } from '../../../common'; +export type { ThirdPartyField as AllThirdPartyFields } from '../../../common'; export interface ThirdPartyField { label: string; diff --git a/x-pack/plugins/cases/public/components/create/description.tsx b/x-pack/plugins/cases/public/components/create/description.tsx index e1bd563a3d798..c1545a42df3f5 100644 --- a/x-pack/plugins/cases/public/components/create/description.tsx +++ b/x-pack/plugins/cases/public/components/create/description.tsx @@ -21,7 +21,7 @@ const DescriptionComponent: React.FC = ({ isLoading }) => { useLensDraftComment(); const { setFieldValue } = useFormContext(); const [{ title, tags }] = useFormData({ watch: ['title', 'tags'] }); - const editorRef = useRef>(); + const editorRef = useRef>(); useEffect(() => { if (draftComment?.commentId === fieldName && editorRef.current) { diff --git a/x-pack/plugins/cases/public/components/create/index.tsx b/x-pack/plugins/cases/public/components/create/index.tsx index d3eaba1ea0bc4..39f10a89290d8 100644 --- a/x-pack/plugins/cases/public/components/create/index.tsx +++ b/x-pack/plugins/cases/public/components/create/index.tsx @@ -98,5 +98,8 @@ export const CreateCase: React.FC = React.memo((props) => ( )); + +CreateCase.displayName = 'CreateCase'; + // eslint-disable-next-line import/no-default-export export { CreateCase as default }; diff --git a/x-pack/plugins/cases/public/components/markdown_editor/editor.tsx b/x-pack/plugins/cases/public/components/markdown_editor/editor.tsx index 4bf25b23403e1..e2067d75e843e 100644 --- a/x-pack/plugins/cases/public/components/markdown_editor/editor.tsx +++ b/x-pack/plugins/cases/public/components/markdown_editor/editor.tsx @@ -96,4 +96,6 @@ const MarkdownEditorComponent = forwardRef + <> {this.renderSearchBar()} {this.renderListing()} - + ); } @@ -481,16 +481,23 @@ export class SavedObjectFinderUi extends React.Component< {items.map((item) => { const currentSavedObjectMetaData = savedObjectMetaData.find( (metaData) => metaData.type === item.type - )!; + ); + + if (currentSavedObjectMetaData == null) { + return null; + } + const fullName = currentSavedObjectMetaData.getTooltipForSavedObject ? currentSavedObjectMetaData.getTooltipForSavedObject(item.savedObject) - : `${item.title} (${currentSavedObjectMetaData!.name})`; + : `${item.title} (${currentSavedObjectMetaData.name})`; + const iconType = ( currentSavedObjectMetaData || ({ getIconForSavedObject: () => 'document', } as Pick, 'getIconForSavedObject'>) ).getIconForSavedObject(item.savedObject); + return ( => { + const MarkdownLinkProcessingComponent: React.FC = memo((props) => ( + + )); + + MarkdownLinkProcessingComponent.displayName = 'MarkdownLinkProcessingComponent'; + + return MarkdownLinkProcessingComponent; +}; + const MarkdownRendererComponent: React.FC = ({ children, disableLinks }) => { const { processingPlugins, parsingPlugins } = usePlugins(); - const MarkdownLinkProcessingComponent: React.FC = useMemo( - () => (props) => , - [disableLinks] - ); // Deep clone of the processing plugins to prevent affecting the markdown editor. const processingPluginList = cloneDeep(processingPlugins); // This line of code is TS-compatible and it will break if [1][1] change in the future. - processingPluginList[1][1].components.a = MarkdownLinkProcessingComponent; + processingPluginList[1][1].components.a = useMemo( + () => withDisabledLinks(disableLinks), + [disableLinks] + ); return ( = React.memo((props) => { ); }); +RecentCases.displayName = 'RecentCases'; + // eslint-disable-next-line import/no-default-export export { RecentCases as default }; diff --git a/x-pack/plugins/cases/public/components/types.ts b/x-pack/plugins/cases/public/components/types.ts index 07ab5814b082b..71c846eb922d7 100644 --- a/x-pack/plugins/cases/public/components/types.ts +++ b/x-pack/plugins/cases/public/components/types.ts @@ -5,4 +5,4 @@ * 2.0. */ -export { CaseActionConnector } from '../../common'; +export type { CaseActionConnector } from '../../common'; diff --git a/x-pack/plugins/cases/public/components/user_action_tree/helpers.tsx b/x-pack/plugins/cases/public/components/user_action_tree/helpers.tsx index 2eb44f91190c6..2419ac0d048e9 100644 --- a/x-pack/plugins/cases/public/components/user_action_tree/helpers.tsx +++ b/x-pack/plugins/cases/public/components/user_action_tree/helpers.tsx @@ -396,6 +396,8 @@ const ActionIcon = React.memo<{ ); }); +ActionIcon.displayName = 'ActionIcon'; + export const getActionAttachment = ({ comment, userCanCrud, diff --git a/x-pack/plugins/cases/public/components/user_action_tree/index.tsx b/x-pack/plugins/cases/public/components/user_action_tree/index.tsx index 92640a34548e8..95c4f76eae0a2 100644 --- a/x-pack/plugins/cases/public/components/user_action_tree/index.tsx +++ b/x-pack/plugins/cases/public/components/user_action_tree/index.tsx @@ -12,8 +12,10 @@ import { EuiCommentList, EuiCommentProps, } from '@elastic/eui'; +import { ALERT_RULE_NAME, ALERT_RULE_UUID } from '@kbn/rule-data-utils'; + import classNames from 'classnames'; -import { isEmpty } from 'lodash'; +import { get, isEmpty } from 'lodash'; import React, { useCallback, useMemo, useRef, useState, useEffect } from 'react'; import { useParams } from 'react-router-dom'; import styled from 'styled-components'; @@ -23,7 +25,7 @@ import * as i18n from './translations'; import { useUpdateComment } from '../../containers/use_update_comment'; import { useCurrentUser } from '../../common/lib/kibana'; -import { AddComment } from '../add_comment'; +import { AddComment, AddCommentRefObject } from '../add_comment'; import { ActionConnector, ActionsCommentRequestRt, @@ -50,7 +52,7 @@ import { getActionAttachment, } from './helpers'; import { UserActionAvatar } from './user_action_avatar'; -import { UserActionMarkdown } from './user_action_markdown'; +import { UserActionMarkdown, UserActionMarkdownRefObject } from './user_action_markdown'; import { UserActionTimestamp } from './user_action_timestamp'; import { UserActionUsername } from './user_action_username'; import { UserActionContentToolbar } from './user_action_content_toolbar'; @@ -129,6 +131,17 @@ const MyEuiCommentList = styled(EuiCommentList)` const DESCRIPTION_ID = 'description'; const NEW_ID = 'newComment'; +const isAddCommentRef = ( + ref: AddCommentRefObject | UserActionMarkdownRefObject | null | undefined +): ref is AddCommentRefObject => { + const commentRef = ref as AddCommentRefObject; + if (commentRef?.addQuote != null) { + return true; + } + + return false; +}; + export const UserActionTree = React.memo( ({ caseServices, @@ -165,7 +178,9 @@ export const UserActionTree = React.memo( const { isLoadingIds, patchComment } = useUpdateComment(); const currentUser = useCurrentUser(); const [manageMarkdownEditIds, setManageMarkdownEditIds] = useState([]); - const commentRefs = useRef>({}); + const commentRefs = useRef< + Record + >({}); const { clearDraftComment, draftComment, hasIncomingLensState, openLensModal } = useLensDraftComment(); @@ -226,8 +241,9 @@ export const UserActionTree = React.memo( const handleManageQuote = useCallback( (quote: string) => { - if (commentRefs.current[NEW_ID]) { - commentRefs.current[NEW_ID].addQuote(quote); + const ref = commentRefs?.current[NEW_ID]; + if (isAddCommentRef(ref)) { + ref.addQuote(quote); } handleOutlineComment('add-comment'); @@ -335,6 +351,8 @@ export const UserActionTree = React.memo( const userActions: EuiCommentProps[] = useMemo( () => caseUserActions.reduce( + // TODO: Decrease complexity. https://github.com/elastic/kibana/issues/115730 + // eslint-disable-next-line complexity (comments, action, index) => { // Comment creation if (action.commentId != null && action.action === 'create') { @@ -421,9 +439,15 @@ export const UserActionTree = React.memo( } const ruleId = - comment?.rule?.id ?? manualAlertsData[alertId]?.signal?.rule?.id?.[0] ?? null; + comment?.rule?.id ?? + manualAlertsData[alertId]?.signal?.rule?.id?.[0] ?? + get(manualAlertsData[alertId], ALERT_RULE_UUID)[0] ?? + null; const ruleName = - comment?.rule?.name ?? manualAlertsData[alertId]?.signal?.rule?.name?.[0] ?? null; + comment?.rule?.name ?? + manualAlertsData[alertId]?.signal?.rule?.name?.[0] ?? + get(manualAlertsData[alertId], ALERT_RULE_NAME)[0] ?? + null; return [ ...comments, @@ -656,15 +680,12 @@ export const UserActionTree = React.memo( return prevManageMarkdownEditIds; }); - if ( - commentRefs.current && - commentRefs.current[draftComment.commentId] && - commentRefs.current[draftComment.commentId].editor?.textarea && - commentRefs.current[draftComment.commentId].editor?.toolbar - ) { - commentRefs.current[draftComment.commentId].setComment(draftComment.comment); + const ref = commentRefs?.current?.[draftComment.commentId]; + + if (isAddCommentRef(ref) && ref.editor?.textarea) { + ref.setComment(draftComment.comment); if (hasIncomingLensState) { - openLensModal({ editorRef: commentRefs.current[draftComment.commentId].editor }); + openLensModal({ editorRef: ref.editor }); } else { clearDraftComment(); } diff --git a/x-pack/plugins/cases/public/components/user_action_tree/user_action_markdown.tsx b/x-pack/plugins/cases/public/components/user_action_tree/user_action_markdown.tsx index f7a6932b35856..93212d2b11016 100644 --- a/x-pack/plugins/cases/public/components/user_action_tree/user_action_markdown.tsx +++ b/x-pack/plugins/cases/public/components/user_action_tree/user_action_markdown.tsx @@ -26,7 +26,7 @@ interface UserActionMarkdownProps { onSaveContent: (content: string) => void; } -interface UserActionMarkdownRefObject { +export interface UserActionMarkdownRefObject { setComment: (newComment: string) => void; } diff --git a/x-pack/plugins/cases/public/containers/api.ts b/x-pack/plugins/cases/public/containers/api.ts index 75e8c8f58705d..14f617b19db52 100644 --- a/x-pack/plugins/cases/public/containers/api.ts +++ b/x-pack/plugins/cases/public/containers/api.ts @@ -87,7 +87,7 @@ export const resolveCase = async ( signal: AbortSignal ): Promise => { const response = await KibanaServices.get().http.fetch( - getCaseDetailsUrl(caseId) + '/resolve', + `${getCaseDetailsUrl(caseId)}/resolve`, { method: 'GET', query: { diff --git a/x-pack/plugins/cases/public/containers/configure/types.ts b/x-pack/plugins/cases/public/containers/configure/types.ts index 61c81a8ce97c1..5ee09add196bd 100644 --- a/x-pack/plugins/cases/public/containers/configure/types.ts +++ b/x-pack/plugins/cases/public/containers/configure/types.ts @@ -17,7 +17,7 @@ import { ThirdPartyField, } from '../../../common'; -export { +export type { ActionConnector, ActionTypeConnector, ActionType, diff --git a/x-pack/plugins/cases/public/utils/use_mount_appended.ts b/x-pack/plugins/cases/public/utils/use_mount_appended.ts index d43b0455f47da..48b71e6dbabfe 100644 --- a/x-pack/plugins/cases/public/utils/use_mount_appended.ts +++ b/x-pack/plugins/cases/public/utils/use_mount_appended.ts @@ -5,6 +5,8 @@ * 2.0. */ +/* eslint-disable @typescript-eslint/no-explicit-any */ + // eslint-disable-next-line import/no-extraneous-dependencies import { mount } from 'enzyme'; diff --git a/x-pack/plugins/cases/server/authorization/authorization.ts b/x-pack/plugins/cases/server/authorization/authorization.ts index 3598c5b8956fa..7a474ff4db402 100644 --- a/x-pack/plugins/cases/server/authorization/authorization.ts +++ b/x-pack/plugins/cases/server/authorization/authorization.ts @@ -231,8 +231,10 @@ export class Authorization { ? Array.from(featureCaseOwners) : privileges.kibana.reduce((authorizedOwners, { authorized, privilege }) => { if (authorized && requiredPrivileges.has(privilege)) { - const owner = requiredPrivileges.get(privilege)!; - authorizedOwners.push(owner); + const owner = requiredPrivileges.get(privilege); + if (owner) { + authorizedOwners.push(owner); + } } return authorizedOwners; diff --git a/x-pack/plugins/cases/server/client/attachments/add.ts b/x-pack/plugins/cases/server/client/attachments/add.ts index b84a6bd84c43b..159ff3b41aba9 100644 --- a/x-pack/plugins/cases/server/client/attachments/add.ts +++ b/x-pack/plugins/cases/server/client/attachments/add.ts @@ -263,7 +263,7 @@ async function getCombinedCase({ id, }), ] - : [Promise.reject('case connector feature is disabled')]), + : [Promise.reject(new Error('case connector feature is disabled'))]), ]); if (subCasePromise.status === 'fulfilled') { diff --git a/x-pack/plugins/cases/server/client/index.ts b/x-pack/plugins/cases/server/client/index.ts index 7904e65ca6276..5560d535f971a 100644 --- a/x-pack/plugins/cases/server/client/index.ts +++ b/x-pack/plugins/cases/server/client/index.ts @@ -7,6 +7,6 @@ export { CasesClient } from './client'; export { CasesClientInternal } from './client_internal'; -export { CasesClientArgs } from './types'; +export type { CasesClientArgs } from './types'; export { createCasesClient } from './client'; export { createCasesClientInternal } from './client_internal'; diff --git a/x-pack/plugins/cases/server/common/error.ts b/x-pack/plugins/cases/server/common/error.ts index 1b53eb9fdb218..3478131f65537 100644 --- a/x-pack/plugins/cases/server/common/error.ts +++ b/x-pack/plugins/cases/server/common/error.ts @@ -8,10 +8,14 @@ import { Boom, isBoom } from '@hapi/boom'; import { Logger } from 'src/core/server'; +export interface HTTPError extends Error { + statusCode: number; +} + /** * Helper class for wrapping errors while preserving the original thrown error. */ -class CaseError extends Error { +export class CaseError extends Error { public readonly wrappedError?: Error; constructor(message?: string, originalError?: Error) { super(message); @@ -51,6 +55,13 @@ export function isCaseError(error: unknown): error is CaseError { return error instanceof CaseError; } +/** + * Type guard for determining if an error is an HTTPError + */ +export function isHTTPError(error: unknown): error is HTTPError { + return (error as HTTPError)?.statusCode != null; +} + /** * Create a CaseError that wraps the original thrown error. This also logs the message that will be placed in the CaseError * if the logger was defined. diff --git a/x-pack/plugins/cases/server/connectors/case/schema.ts b/x-pack/plugins/cases/server/connectors/case/schema.ts index 79d3bf62e8a9e..b8e46fdf5aa8c 100644 --- a/x-pack/plugins/cases/server/connectors/case/schema.ts +++ b/x-pack/plugins/cases/server/connectors/case/schema.ts @@ -83,6 +83,7 @@ const SwimlaneFieldsSchema = schema.object({ const NoneFieldsSchema = schema.nullable(schema.object({})); +// eslint-disable-next-line @typescript-eslint/no-explicit-any const ReducedConnectorFieldsSchema: { [x: string]: any } = { [ConnectorTypes.jira]: JiraFieldsSchema, [ConnectorTypes.resilient]: ResilientFieldsSchema, diff --git a/x-pack/plugins/cases/server/connectors/servicenow/sir_format.test.ts b/x-pack/plugins/cases/server/connectors/servicenow/sir_format.test.ts index b09272d0a5505..706b9f2f23ab5 100644 --- a/x-pack/plugins/cases/server/connectors/servicenow/sir_format.test.ts +++ b/x-pack/plugins/cases/server/connectors/servicenow/sir_format.test.ts @@ -8,7 +8,7 @@ import { CaseResponse } from '../../../common'; import { format } from './sir_format'; -describe('ITSM formatter', () => { +describe('SIR formatter', () => { const theCase = { id: 'case-id', connector: { diff --git a/x-pack/plugins/cases/server/connectors/servicenow/sir_format.ts b/x-pack/plugins/cases/server/connectors/servicenow/sir_format.ts index 9108408c4d089..02c9fe629f4f8 100644 --- a/x-pack/plugins/cases/server/connectors/servicenow/sir_format.ts +++ b/x-pack/plugins/cases/server/connectors/servicenow/sir_format.ts @@ -45,12 +45,16 @@ export const format: ServiceNowSIRFormat = (theCase, alerts) => { if (fieldsToAdd.length > 0) { sirFields = alerts.reduce>((acc, alert) => { + let temp = {}; fieldsToAdd.forEach((alertField) => { const field = get(alertFieldMapping[alertField].alertPath, alert); + if (field && !manageDuplicate[alertFieldMapping[alertField].sirFieldKey].has(field)) { manageDuplicate[alertFieldMapping[alertField].sirFieldKey].add(field); - acc = { + + temp = { ...acc, + ...temp, [alertFieldMapping[alertField].sirFieldKey]: [ ...acc[alertFieldMapping[alertField].sirFieldKey], field, @@ -58,7 +62,8 @@ export const format: ServiceNowSIRFormat = (theCase, alerts) => { }; } }); - return acc; + + return { ...acc, ...temp }; }, sirFields); } diff --git a/x-pack/plugins/cases/server/connectors/types.ts b/x-pack/plugins/cases/server/connectors/types.ts index a8673c1262580..62b2c8e6f1551 100644 --- a/x-pack/plugins/cases/server/connectors/types.ts +++ b/x-pack/plugins/cases/server/connectors/types.ts @@ -11,7 +11,7 @@ import { CasesClientGetAlertsResponse } from '../client/alerts/types'; import { CasesClientFactory } from '../client/factory'; import { RegisterActionType } from '../types'; -export { +export type { ContextTypeGeneratedAlertType, CommentSchemaType, ContextTypeAlertSchemaType, diff --git a/x-pack/plugins/cases/server/index.ts b/x-pack/plugins/cases/server/index.ts index 5e433b46b80e5..57db6e5565fff 100644 --- a/x-pack/plugins/cases/server/index.ts +++ b/x-pack/plugins/cases/server/index.ts @@ -22,4 +22,4 @@ export const config: PluginConfigDescriptor = { export const plugin = (initializerContext: PluginInitializerContext) => new CasePlugin(initializerContext); -export { PluginStartContract } from './plugin'; +export type { PluginStartContract } from './plugin'; diff --git a/x-pack/plugins/cases/server/plugin.ts b/x-pack/plugins/cases/server/plugin.ts index bef8d45bd86f6..9bbc7089c033c 100644 --- a/x-pack/plugins/cases/server/plugin.ts +++ b/x-pack/plugins/cases/server/plugin.ts @@ -126,6 +126,11 @@ export class CasePlugin { }, featuresPluginStart: plugins.features, actionsPluginStart: plugins.actions, + /** + * Lens will be always defined as + * it is declared as required plugin in kibana.json + */ + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion lensEmbeddableFactory: this.lensEmbeddableFactory!, }); diff --git a/x-pack/plugins/cases/server/routes/api/utils.test.ts b/x-pack/plugins/cases/server/routes/api/utils.test.ts index 3fce38b27446e..fd7c038f06bc1 100644 --- a/x-pack/plugins/cases/server/routes/api/utils.test.ts +++ b/x-pack/plugins/cases/server/routes/api/utils.test.ts @@ -5,8 +5,9 @@ * 2.0. */ -import { wrapError } from './utils'; import { isBoom, boomify } from '@hapi/boom'; +import { HTTPError } from '../../common'; +import { wrapError } from './utils'; describe('Utils', () => { describe('wrapError', () => { @@ -25,7 +26,7 @@ describe('Utils', () => { }); it('it set statusCode to errors status code', () => { - const error = new Error('Something happened') as any; + const error = new Error('Something happened') as HTTPError; error.statusCode = 404; const res = wrapError(error); diff --git a/x-pack/plugins/cases/server/routes/api/utils.ts b/x-pack/plugins/cases/server/routes/api/utils.ts index b2b5417ecae0f..cb4804aab0054 100644 --- a/x-pack/plugins/cases/server/routes/api/utils.ts +++ b/x-pack/plugins/cases/server/routes/api/utils.ts @@ -9,18 +9,21 @@ import { Boom, boomify, isBoom } from '@hapi/boom'; import { schema } from '@kbn/config-schema'; import { CustomHttpResponseOptions, ResponseError } from 'kibana/server'; -import { isCaseError } from '../../common'; +import { CaseError, isCaseError, HTTPError, isHTTPError } from '../../common'; /** * Transforms an error into the correct format for a kibana response. */ -export function wrapError(error: any): CustomHttpResponseOptions { + +export function wrapError( + error: CaseError | Boom | HTTPError | Error +): CustomHttpResponseOptions { let boom: Boom; if (isCaseError(error)) { boom = error.boomify(); } else { - const options = { statusCode: error.statusCode ?? 500 }; + const options = { statusCode: isHTTPError(error) ? error.statusCode : 500 }; boom = isBoom(error) ? error : boomify(error, options); } diff --git a/x-pack/plugins/cases/server/saved_object_types/migrations/index.ts b/x-pack/plugins/cases/server/saved_object_types/migrations/index.ts index a4f50fbfcde5b..b0f9c7d2145de 100644 --- a/x-pack/plugins/cases/server/saved_object_types/migrations/index.ts +++ b/x-pack/plugins/cases/server/saved_object_types/migrations/index.ts @@ -14,7 +14,8 @@ import { SECURITY_SOLUTION_OWNER } from '../../../common'; export { caseMigrations } from './cases'; export { configureMigrations } from './configuration'; export { userActionsMigrations } from './user_actions'; -export { createCommentsMigrations, CreateCommentsMigrationsDeps } from './comments'; +export type { CreateCommentsMigrationsDeps } from './comments'; +export { createCommentsMigrations } from './comments'; export interface SanitizedCaseOwner { owner: string; diff --git a/x-pack/plugins/cases/server/scripts/sub_cases/index.ts b/x-pack/plugins/cases/server/scripts/sub_cases/index.ts index 3cb013bd2e3fd..28672160a0737 100644 --- a/x-pack/plugins/cases/server/scripts/sub_cases/index.ts +++ b/x-pack/plugins/cases/server/scripts/sub_cases/index.ts @@ -4,7 +4,11 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ + +/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable no-console */ +/* eslint-disable no-process-exit */ + import yargs from 'yargs'; import { ToolingLog } from '@kbn/dev-utils'; import { KbnClient } from '@kbn/test'; diff --git a/x-pack/plugins/cases/server/services/alerts/index.ts b/x-pack/plugins/cases/server/services/alerts/index.ts index 6bb2fb3ee3c56..d8a09fe1baf23 100644 --- a/x-pack/plugins/cases/server/services/alerts/index.ts +++ b/x-pack/plugins/cases/server/services/alerts/index.ts @@ -48,8 +48,6 @@ function isEmptyAlert(alert: AlertInfo): boolean { } export class AlertService { - constructor() {} - public async updateAlertsStatus({ alerts, scopedClusterClient, logger }: UpdateAlertsStatusArgs) { try { const bucketedAlerts = bucketAlertsByIndexAndStatus(alerts, logger); diff --git a/x-pack/plugins/cases/server/services/index.ts b/x-pack/plugins/cases/server/services/index.ts index f910099c0cc20..a1cb5d8138c40 100644 --- a/x-pack/plugins/cases/server/services/index.ts +++ b/x-pack/plugins/cases/server/services/index.ts @@ -12,7 +12,8 @@ export { CasesService } from './cases'; export { CaseConfigureService } from './configure'; export { CaseUserActionService } from './user_actions'; export { ConnectorMappingsService } from './connector_mappings'; -export { AlertService, AlertServiceContract } from './alerts'; +export type { AlertServiceContract } from './alerts'; +export { AlertService } from './alerts'; export { AttachmentService } from './attachments'; export interface ClientArgs { diff --git a/x-pack/plugins/cloud/public/index.ts b/x-pack/plugins/cloud/public/index.ts index 9f4f6b979c344..d51def6fa6641 100644 --- a/x-pack/plugins/cloud/public/index.ts +++ b/x-pack/plugins/cloud/public/index.ts @@ -8,7 +8,7 @@ import { PluginInitializerContext } from '../../../../src/core/public'; import { CloudPlugin } from './plugin'; -export { CloudSetup, CloudConfigType } from './plugin'; +export type { CloudSetup, CloudConfigType } from './plugin'; export function plugin(initializerContext: PluginInitializerContext) { return new CloudPlugin(initializerContext); } diff --git a/x-pack/plugins/cloud/server/index.ts b/x-pack/plugins/cloud/server/index.ts index 8d212bb4e1593..eda2fa0a7324e 100644 --- a/x-pack/plugins/cloud/server/index.ts +++ b/x-pack/plugins/cloud/server/index.ts @@ -8,7 +8,7 @@ import { PluginInitializerContext } from 'src/core/server'; import { CloudPlugin } from './plugin'; -export { CloudSetup } from './plugin'; +export type { CloudSetup } from './plugin'; export { config } from './config'; export const plugin = (initializerContext: PluginInitializerContext) => { return new CloudPlugin(initializerContext); diff --git a/x-pack/plugins/dashboard_enhanced/common/drilldowns/dashboard_drilldown/index.ts b/x-pack/plugins/dashboard_enhanced/common/drilldowns/dashboard_drilldown/index.ts index dae19cf02e230..fde3b5b06de2d 100644 --- a/x-pack/plugins/dashboard_enhanced/common/drilldowns/dashboard_drilldown/index.ts +++ b/x-pack/plugins/dashboard_enhanced/common/drilldowns/dashboard_drilldown/index.ts @@ -7,4 +7,4 @@ export { createExtract, createInject } from './dashboard_drilldown_persistable_state'; export { EMBEDDABLE_TO_DASHBOARD_DRILLDOWN } from './constants'; -export { DrilldownConfig } from './types'; +export type { DrilldownConfig } from './types'; diff --git a/x-pack/plugins/dashboard_enhanced/public/index.ts b/x-pack/plugins/dashboard_enhanced/public/index.ts index 82b0fc322bb83..545696abb0ac5 100644 --- a/x-pack/plugins/dashboard_enhanced/public/index.ts +++ b/x-pack/plugins/dashboard_enhanced/public/index.ts @@ -8,18 +8,18 @@ import { PluginInitializerContext } from 'src/core/public'; import { DashboardEnhancedPlugin } from './plugin'; -export { +export type { SetupContract as DashboardEnhancedSetupContract, SetupDependencies as DashboardEnhancedSetupDependencies, StartContract as DashboardEnhancedStartContract, StartDependencies as DashboardEnhancedStartDependencies, } from './plugin'; -export { - AbstractDashboardDrilldown as DashboardEnhancedAbstractDashboardDrilldown, +export type { AbstractDashboardDrilldownConfig as DashboardEnhancedAbstractDashboardDrilldownConfig, AbstractDashboardDrilldownParams as DashboardEnhancedAbstractDashboardDrilldownParams, } from './services/drilldowns/abstract_dashboard_drilldown'; +export { AbstractDashboardDrilldown as DashboardEnhancedAbstractDashboardDrilldown } from './services/drilldowns/abstract_dashboard_drilldown'; export function plugin(context: PluginInitializerContext) { return new DashboardEnhancedPlugin(context); diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/abstract_dashboard_drilldown/components/index.ts b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/abstract_dashboard_drilldown/components/index.ts index ffdce9e91d156..9215f067fc851 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/abstract_dashboard_drilldown/components/index.ts +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/abstract_dashboard_drilldown/components/index.ts @@ -5,7 +5,5 @@ * 2.0. */ -export { - CollectConfigContainer, - DashboardDrilldownCollectConfigProps, -} from './collect_config_container'; +export type { DashboardDrilldownCollectConfigProps } from './collect_config_container'; +export { CollectConfigContainer } from './collect_config_container'; diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/abstract_dashboard_drilldown/index.ts b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/abstract_dashboard_drilldown/index.ts index 3acea2f76d73c..3b76303bda388 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/abstract_dashboard_drilldown/index.ts +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/abstract_dashboard_drilldown/index.ts @@ -5,8 +5,6 @@ * 2.0. */ -export { - AbstractDashboardDrilldown, - Params as AbstractDashboardDrilldownParams, -} from './abstract_dashboard_drilldown'; -export { Config as AbstractDashboardDrilldownConfig } from './types'; +export type { Params as AbstractDashboardDrilldownParams } from './abstract_dashboard_drilldown'; +export { AbstractDashboardDrilldown } from './abstract_dashboard_drilldown'; +export type { Config as AbstractDashboardDrilldownConfig } from './types'; diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_create_drilldown/index.ts b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_create_drilldown/index.ts index 3a0389ac2b546..f7d98d7681396 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_create_drilldown/index.ts +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_create_drilldown/index.ts @@ -5,8 +5,5 @@ * 2.0. */ -export { - FlyoutCreateDrilldownAction, - OpenFlyoutAddDrilldownParams, - OPEN_FLYOUT_ADD_DRILLDOWN, -} from './flyout_create_drilldown'; +export type { OpenFlyoutAddDrilldownParams } from './flyout_create_drilldown'; +export { FlyoutCreateDrilldownAction, OPEN_FLYOUT_ADD_DRILLDOWN } from './flyout_create_drilldown'; diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_edit_drilldown/index.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_edit_drilldown/index.tsx index c150c55120e59..76d61a7367d7e 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_edit_drilldown/index.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/actions/flyout_edit_drilldown/index.tsx @@ -5,8 +5,5 @@ * 2.0. */ -export { - FlyoutEditDrilldownAction, - FlyoutEditDrilldownParams, - OPEN_FLYOUT_EDIT_DRILLDOWN, -} from './flyout_edit_drilldown'; +export type { FlyoutEditDrilldownParams } from './flyout_edit_drilldown'; +export { FlyoutEditDrilldownAction, OPEN_FLYOUT_EDIT_DRILLDOWN } from './flyout_edit_drilldown'; diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/embeddable_to_dashboard_drilldown/index.ts b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/embeddable_to_dashboard_drilldown/index.ts index 423007d548db5..3a34de6299fc4 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/embeddable_to_dashboard_drilldown/index.ts +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/embeddable_to_dashboard_drilldown/index.ts @@ -6,7 +6,5 @@ */ export { EMBEDDABLE_TO_DASHBOARD_DRILLDOWN } from './constants'; -export { - EmbeddableToDashboardDrilldown, - Params as EmbeddableToDashboardDrilldownParams, -} from './embeddable_to_dashboard_drilldown'; +export type { Params as EmbeddableToDashboardDrilldownParams } from './embeddable_to_dashboard_drilldown'; +export { EmbeddableToDashboardDrilldown } from './embeddable_to_dashboard_drilldown'; diff --git a/x-pack/plugins/dashboard_enhanced/server/index.ts b/x-pack/plugins/dashboard_enhanced/server/index.ts index 1f4659c2c781a..3351cd9547903 100644 --- a/x-pack/plugins/dashboard_enhanced/server/index.ts +++ b/x-pack/plugins/dashboard_enhanced/server/index.ts @@ -8,7 +8,7 @@ import { PluginInitializerContext } from 'src/core/server'; import { DashboardEnhancedPlugin } from './plugin'; -export { +export type { SetupContract as DashboardEnhancedSetupContract, SetupDependencies as DashboardEnhancedSetupDependencies, StartContract as DashboardEnhancedStartContract, diff --git a/x-pack/plugins/data_enhanced/public/index.ts b/x-pack/plugins/data_enhanced/public/index.ts index c3adf19fabe13..38b8d7d5c5fdf 100644 --- a/x-pack/plugins/data_enhanced/public/index.ts +++ b/x-pack/plugins/data_enhanced/public/index.ts @@ -12,7 +12,7 @@ import { ConfigSchema } from '../config'; export const plugin = (initializerContext: PluginInitializerContext) => new DataEnhancedPlugin(initializerContext); -export { DataEnhancedSetup, DataEnhancedStart }; +export type { DataEnhancedSetup, DataEnhancedStart }; export { ENHANCED_ES_SEARCH_STRATEGY, diff --git a/x-pack/plugins/data_enhanced/public/search/sessions_mgmt/components/index.tsx b/x-pack/plugins/data_enhanced/public/search/sessions_mgmt/components/index.tsx index f57ad73c3c760..2970c75e651d6 100644 --- a/x-pack/plugins/data_enhanced/public/search/sessions_mgmt/components/index.tsx +++ b/x-pack/plugins/data_enhanced/public/search/sessions_mgmt/components/index.tsx @@ -9,7 +9,8 @@ import { EuiLinkProps, EuiText, EuiTextProps } from '@elastic/eui'; import React from 'react'; import extendSessionIcon from '../icons/extend_session.svg'; -export { OnActionComplete, PopoverActionsMenu } from './actions'; +export type { OnActionComplete } from './actions'; +export { PopoverActionsMenu } from './actions'; export const TableText = ({ children, ...props }: EuiTextProps) => { return ( diff --git a/x-pack/plugins/data_enhanced/public/search/ui/connected_search_session_indicator/index.ts b/x-pack/plugins/data_enhanced/public/search/ui/connected_search_session_indicator/index.ts index 122321691439d..fec61f8115486 100644 --- a/x-pack/plugins/data_enhanced/public/search/ui/connected_search_session_indicator/index.ts +++ b/x-pack/plugins/data_enhanced/public/search/ui/connected_search_session_indicator/index.ts @@ -5,7 +5,5 @@ * 2.0. */ -export { - SearchSessionIndicatorDeps, - createConnectedSearchSessionIndicator, -} from './connected_search_session_indicator'; +export type { SearchSessionIndicatorDeps } from './connected_search_session_indicator'; +export { createConnectedSearchSessionIndicator } from './connected_search_session_indicator'; diff --git a/x-pack/plugins/data_visualizer/public/application/common/components/combined_fields/index.ts b/x-pack/plugins/data_visualizer/public/application/common/components/combined_fields/index.ts index 862128f2e856b..834813ddc2411 100644 --- a/x-pack/plugins/data_visualizer/public/application/common/components/combined_fields/index.ts +++ b/x-pack/plugins/data_visualizer/public/application/common/components/combined_fields/index.ts @@ -13,4 +13,4 @@ export { export { CombinedFieldsReadOnlyForm } from './combined_fields_read_only_form'; export { CombinedFieldsForm } from './combined_fields_form'; -export { CombinedField } from './types'; +export type { CombinedField } from './types'; diff --git a/x-pack/plugins/data_visualizer/public/application/common/components/document_count_content/document_count_chart/index.ts b/x-pack/plugins/data_visualizer/public/application/common/components/document_count_content/document_count_chart/index.ts index 97b42053b34e6..1b69f9b825165 100644 --- a/x-pack/plugins/data_visualizer/public/application/common/components/document_count_content/document_count_chart/index.ts +++ b/x-pack/plugins/data_visualizer/public/application/common/components/document_count_content/document_count_chart/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { DocumentCountChart, DocumentCountChartPoint } from './document_count_chart'; +export type { DocumentCountChartPoint } from './document_count_chart'; +export { DocumentCountChart } from './document_count_chart'; diff --git a/x-pack/plugins/data_visualizer/public/application/common/components/multi_select_picker/index.ts b/x-pack/plugins/data_visualizer/public/application/common/components/multi_select_picker/index.ts index 9d32228e1c4bc..a42ce68d9aa10 100644 --- a/x-pack/plugins/data_visualizer/public/application/common/components/multi_select_picker/index.ts +++ b/x-pack/plugins/data_visualizer/public/application/common/components/multi_select_picker/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { MultiSelectPicker, Option } from './multi_select_picker'; +export type { Option } from './multi_select_picker'; +export { MultiSelectPicker } from './multi_select_picker'; diff --git a/x-pack/plugins/data_visualizer/public/application/common/components/results_links/index.ts b/x-pack/plugins/data_visualizer/public/application/common/components/results_links/index.ts index 1dca4b7bf2254..24c36f97d7633 100644 --- a/x-pack/plugins/data_visualizer/public/application/common/components/results_links/index.ts +++ b/x-pack/plugins/data_visualizer/public/application/common/components/results_links/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { ResultsLinks, ResultLink } from './results_links'; +export type { ResultLink } from './results_links'; +export { ResultsLinks } from './results_links'; diff --git a/x-pack/plugins/data_visualizer/public/application/common/components/results_links/results_links.tsx b/x-pack/plugins/data_visualizer/public/application/common/components/results_links/results_links.tsx index f1de0b0b8b8fa..ed6ab29748a86 100644 --- a/x-pack/plugins/data_visualizer/public/application/common/components/results_links/results_links.tsx +++ b/x-pack/plugins/data_visualizer/public/application/common/components/results_links/results_links.tsx @@ -58,7 +58,13 @@ export const ResultsLinks: FC = ({ additionalLinks, }) => { const { - services: { fileUpload }, + services: { + fileUpload, + application: { getUrlForApp, capabilities }, + share: { + urlGenerators: { getUrlGenerator }, + }, + }, } = useDataVisualizerKibana(); const [duration, setDuration] = useState({ @@ -72,15 +78,6 @@ export const ResultsLinks: FC = ({ const [indexPatternManagementLink, setIndexPatternManagementLink] = useState(''); const [generatedLinks, setGeneratedLinks] = useState>({}); - const { - services: { - application: { getUrlForApp, capabilities }, - share: { - urlGenerators: { getUrlGenerator }, - }, - }, - } = useDataVisualizerKibana(); - useEffect(() => { let unmounted = false; @@ -137,11 +134,14 @@ export const ResultsLinks: FC = ({ setIndexManagementLink( getUrlForApp('management', { path: '/data/index_management/indices' }) ); - setIndexPatternManagementLink( - getUrlForApp('management', { - path: `/kibana/indexPatterns${createIndexPattern ? `/patterns/${indexPatternId}` : ''}`, - }) - ); + + if (capabilities.indexPatterns.save === true) { + setIndexPatternManagementLink( + getUrlForApp('management', { + path: `/kibana/indexPatterns${createIndexPattern ? `/patterns/${indexPatternId}` : ''}`, + }) + ); + } } return () => { diff --git a/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/components/field_count_stats/index.ts b/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/components/field_count_stats/index.ts index d841ee2959f62..ccd7c6b73a577 100644 --- a/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/components/field_count_stats/index.ts +++ b/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/components/field_count_stats/index.ts @@ -5,9 +5,7 @@ * 2.0. */ -export { TotalFieldsCount, TotalFieldsCountProps, TotalFieldsStats } from './total_fields_count'; -export { - MetricFieldsCount, - MetricFieldsCountProps, - MetricFieldsStats, -} from './metric_fields_count'; +export type { TotalFieldsCountProps, TotalFieldsStats } from './total_fields_count'; +export { TotalFieldsCount } from './total_fields_count'; +export type { MetricFieldsCountProps, MetricFieldsStats } from './metric_fields_count'; +export { MetricFieldsCount } from './metric_fields_count'; diff --git a/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/components/metric_distribution_chart/index.ts b/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/components/metric_distribution_chart/index.ts index 72947f2953cb8..5012426e8f7ca 100644 --- a/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/components/metric_distribution_chart/index.ts +++ b/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/components/metric_distribution_chart/index.ts @@ -5,5 +5,6 @@ * 2.0. */ -export { MetricDistributionChart, MetricDistributionChartData } from './metric_distribution_chart'; +export type { MetricDistributionChartData } from './metric_distribution_chart'; +export { MetricDistributionChart } from './metric_distribution_chart'; export { buildChartDataFromStats } from './metric_distribution_chart_data_builder'; diff --git a/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/index.ts b/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/index.ts index 3009470af4858..a8aae70ccfc63 100644 --- a/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/index.ts +++ b/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { DataVisualizerTable, ItemIdToExpandedRowMap } from './data_visualizer_stats_table'; +export type { ItemIdToExpandedRowMap } from './data_visualizer_stats_table'; +export { DataVisualizerTable } from './data_visualizer_stats_table'; diff --git a/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/types/index.ts b/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/types/index.ts index 171d029482e27..00f8ac0c74eb9 100644 --- a/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/types/index.ts +++ b/x-pack/plugins/data_visualizer/public/application/common/components/stats_table/types/index.ts @@ -5,11 +5,10 @@ * 2.0. */ -export { FieldDataRowProps } from './field_data_row'; -export { +export type { FieldDataRowProps } from './field_data_row'; +export type { FieldVisConfig, FileBasedFieldVisConfig, MetricFieldVisStats, - isFileBasedFieldVisConfig, - isIndexBasedFieldVisConfig, } from './field_vis_config'; +export { isFileBasedFieldVisConfig, isIndexBasedFieldVisConfig } from './field_vis_config'; diff --git a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/file_data_visualizer_view/file_data_visualizer_view.js b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/file_data_visualizer_view/file_data_visualizer_view.js index 054416ad7ba36..fa437cce29268 100644 --- a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/file_data_visualizer_view/file_data_visualizer_view.js +++ b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/file_data_visualizer_view/file_data_visualizer_view.js @@ -295,12 +295,7 @@ export class FileDataVisualizerView extends Component {
{mode === MODE.READ && ( <> - {!loading && !loaded && ( - - )} + {!loading && !loaded && } {loading && } @@ -373,6 +368,7 @@ export class FileDataVisualizerView extends Component { savedObjectsClient={this.savedObjectsClient} fileUpload={this.props.fileUpload} resultsLinks={this.props.resultsLinks} + capabilities={this.props.capabilities} /> {bottomBarVisible && ( diff --git a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_progress/index.ts b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_progress/index.ts index fe2d6ab7d826b..65ebab329a83c 100644 --- a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_progress/index.ts +++ b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_progress/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { ImportProgress, IMPORT_STATUS, Statuses } from './import_progress'; +export type { Statuses } from './import_progress'; +export { ImportProgress, IMPORT_STATUS } from './import_progress'; diff --git a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_settings/advanced.tsx b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_settings/advanced.tsx index 83e7c556f033f..23ad2b967bc28 100644 --- a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_settings/advanced.tsx +++ b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_settings/advanced.tsx @@ -21,6 +21,7 @@ import { import { CombinedField, CombinedFieldsForm } from '../../../common/components/combined_fields'; import { JsonEditor, EDITOR_MODE } from '../json_editor'; import { FindFileStructureResponse } from '../../../../../../file_upload/common'; +import { CreateDataViewToolTip } from './create_data_view_tooltip'; const EDITOR_HEIGHT = '300px'; interface Props { @@ -42,6 +43,7 @@ interface Props { combinedFields: CombinedField[]; onCombinedFieldsChange(combinedFields: CombinedField[]): void; results: FindFileStructureResponse; + canCreateDataView: boolean; } export const AdvancedSettings: FC = ({ @@ -63,6 +65,7 @@ export const AdvancedSettings: FC = ({ combinedFields, onCombinedFieldsChange, results, + canCreateDataView, }) => { return ( @@ -98,18 +101,20 @@ export const AdvancedSettings: FC = ({ - - } - checked={createIndexPattern === true} - disabled={initialized === true} - onChange={onCreateIndexPatternChange} - /> + + + } + checked={createIndexPattern === true} + disabled={initialized === true || canCreateDataView === false} + onChange={onCreateIndexPatternChange} + /> + diff --git a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_settings/create_data_view_tooltip.tsx b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_settings/create_data_view_tooltip.tsx new file mode 100644 index 0000000000000..84af5b08b3d49 --- /dev/null +++ b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_settings/create_data_view_tooltip.tsx @@ -0,0 +1,33 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { FC } from 'react'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiToolTip } from '@elastic/eui'; + +interface Props { + children?: React.ReactElement; + showTooltip: boolean; +} + +export const CreateDataViewToolTip: FC = ({ children, showTooltip }) => { + return ( + + ) : null + } + > + {children} + + ); +}; diff --git a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_settings/import_settings.tsx b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_settings/import_settings.tsx index 4e36dc42b54a5..c2b9779f3624d 100644 --- a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_settings/import_settings.tsx +++ b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_settings/import_settings.tsx @@ -14,6 +14,7 @@ import { SimpleSettings } from './simple'; import { AdvancedSettings } from './advanced'; import { CombinedField } from '../../../common/components/combined_fields'; import { FindFileStructureResponse } from '../../../../../../file_upload/common'; +import { useDataVisualizerKibana } from '../../../kibana_context'; interface Props { index: string; @@ -56,6 +57,15 @@ export const ImportSettings: FC = ({ onCombinedFieldsChange, results, }) => { + const { + services: { + application: { capabilities }, + }, + } = useDataVisualizerKibana(); + + const canCreateDataView = + capabilities.savedObjectsManagement.edit === true || capabilities.indexPatterns.save === true; + const tabs = [ { id: 'simple-settings', @@ -74,6 +84,7 @@ export const ImportSettings: FC = ({ onCreateIndexPatternChange={onCreateIndexPatternChange} indexNameError={indexNameError} combinedFields={combinedFields} + canCreateDataView={canCreateDataView} /> ), @@ -106,6 +117,7 @@ export const ImportSettings: FC = ({ combinedFields={combinedFields} onCombinedFieldsChange={onCombinedFieldsChange} results={results} + canCreateDataView={canCreateDataView} /> ), diff --git a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_settings/simple.tsx b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_settings/simple.tsx index 284a5aa3d4f3f..a080f62f54fc1 100644 --- a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_settings/simple.tsx +++ b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_settings/simple.tsx @@ -14,6 +14,7 @@ import { CombinedField, CombinedFieldsReadOnlyForm, } from '../../../common/components/combined_fields'; +import { CreateDataViewToolTip } from './create_data_view_tooltip'; interface Props { index: string; @@ -23,6 +24,7 @@ interface Props { onCreateIndexPatternChange(): void; indexNameError: string; combinedFields: CombinedField[]; + canCreateDataView: boolean; } export const SimpleSettings: FC = ({ @@ -33,6 +35,7 @@ export const SimpleSettings: FC = ({ onCreateIndexPatternChange, indexNameError, combinedFields, + canCreateDataView, }) => { return ( @@ -69,19 +72,21 @@ export const SimpleSettings: FC = ({ - - } - checked={createIndexPattern === true} - disabled={initialized === true} - onChange={onCreateIndexPatternChange} - data-test-subj="dataVisualizerFileCreateIndexPatternCheckbox" - /> + + + } + checked={createIndexPattern === true} + disabled={initialized === true || canCreateDataView === false} + onChange={onCreateIndexPatternChange} + data-test-subj="dataVisualizerFileCreateIndexPatternCheckbox" + /> + diff --git a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_view/import_view.js b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_view/import_view.js index 3b3a11a5dff22..b65e2c35ff4ff 100644 --- a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_view/import_view.js +++ b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/components/import_view/import_view.js @@ -76,7 +76,7 @@ export class ImportView extends Component { constructor(props) { super(props); - this.state = getDefaultState(DEFAULT_STATE, this.props.results); + this.state = getDefaultState(DEFAULT_STATE, this.props.results, this.props.capabilities); this.savedObjectsClient = props.savedObjectsClient; } @@ -85,7 +85,7 @@ export class ImportView extends Component { } clickReset = () => { - const state = getDefaultState(this.state, this.props.results); + const state = getDefaultState(this.state, this.props.results, this.props.capabilities); this.setState(state, () => { this.loadIndexPatternNames(); }); @@ -640,7 +640,7 @@ async function createKibanaIndexPattern(indexPatternName, indexPatterns, timeFie } } -function getDefaultState(state, results) { +function getDefaultState(state, results, capabilities) { const indexSettingsString = state.indexSettingsString === '' ? JSON.stringify(DEFAULT_INDEX_SETTINGS, null, 2) @@ -666,6 +666,11 @@ function getDefaultState(state, results) { const timeFieldName = results.timestamp_field; + const createIndexPattern = + capabilities.savedObjectsManagement.edit === false && capabilities.indexPatterns.save === false + ? false + : state.createIndexPattern; + return { ...DEFAULT_STATE, indexSettingsString, @@ -673,6 +678,7 @@ function getDefaultState(state, results) { pipelineString, timeFieldName, combinedFields, + createIndexPattern, }; } diff --git a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/file_data_visualizer.tsx b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/file_data_visualizer.tsx index 3644f7053f1e8..a82a2b7e25d85 100644 --- a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/file_data_visualizer.tsx +++ b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/file_data_visualizer.tsx @@ -39,6 +39,7 @@ export const FileDataVisualizer: FC = ({ additionalLinks }) => { http={coreStart.http} fileUpload={fileUpload} resultsLinks={additionalLinks} + capabilities={coreStart.application.capabilities} /> ); diff --git a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/index.ts b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/index.ts index ca87d73b6a758..4cd3755726ad2 100644 --- a/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/index.ts +++ b/x-pack/plugins/data_visualizer/public/application/file_data_visualizer/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { FileDataVisualizer, FileDataVisualizerSpec } from './file_data_visualizer'; +export type { FileDataVisualizerSpec } from './file_data_visualizer'; +export { FileDataVisualizer } from './file_data_visualizer'; diff --git a/x-pack/plugins/data_visualizer/public/application/index.ts b/x-pack/plugins/data_visualizer/public/application/index.ts index 6229f61be85e9..7e84bd84adf6f 100644 --- a/x-pack/plugins/data_visualizer/public/application/index.ts +++ b/x-pack/plugins/data_visualizer/public/application/index.ts @@ -5,9 +5,10 @@ * 2.0. */ -export { FileDataVisualizer, FileDataVisualizerSpec } from './file_data_visualizer'; -export { - IndexDataVisualizer, +export type { FileDataVisualizerSpec } from './file_data_visualizer'; +export { FileDataVisualizer } from './file_data_visualizer'; +export type { IndexDataVisualizerSpec, IndexDataVisualizerViewProps, } from './index_data_visualizer'; +export { IndexDataVisualizer } from './index_data_visualizer'; diff --git a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/full_time_range_selector/index.tsx b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/full_time_range_selector/index.tsx index c79df59ee3f69..14ad77e2adc3a 100644 --- a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/full_time_range_selector/index.tsx +++ b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/full_time_range_selector/index.tsx @@ -6,4 +6,5 @@ */ export { FullTimeRangeSelector } from './full_time_range_selector'; -export { getTimeFilterRange, TimeRange } from './full_time_range_selector_service'; +export type { TimeRange } from './full_time_range_selector_service'; +export { getTimeFilterRange } from './full_time_range_selector_service'; diff --git a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/index_data_visualizer_view/index.ts b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/index_data_visualizer_view/index.ts index bcdef0966039d..9bb579f7af55d 100644 --- a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/index_data_visualizer_view/index.ts +++ b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/index_data_visualizer_view/index.ts @@ -5,7 +5,5 @@ * 2.0. */ -export { - IndexDataVisualizerViewProps, - IndexDataVisualizerView, -} from './index_data_visualizer_view'; +export type { IndexDataVisualizerViewProps } from './index_data_visualizer_view'; +export { IndexDataVisualizerView } from './index_data_visualizer_view'; diff --git a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/index.ts b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/index.ts index 77b6f9b5ab18c..82abdf185f9ab 100644 --- a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/index.ts +++ b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/index.ts @@ -5,5 +5,6 @@ * 2.0. */ -export { IndexDataVisualizer, IndexDataVisualizerSpec } from './index_data_visualizer'; +export type { IndexDataVisualizerSpec } from './index_data_visualizer'; +export { IndexDataVisualizer } from './index_data_visualizer'; export type { IndexDataVisualizerViewProps } from './components/index_data_visualizer_view'; diff --git a/x-pack/plugins/data_visualizer/public/index.ts b/x-pack/plugins/data_visualizer/public/index.ts index 1a045f144c015..4a579f4e3abcc 100644 --- a/x-pack/plugins/data_visualizer/public/index.ts +++ b/x-pack/plugins/data_visualizer/public/index.ts @@ -11,7 +11,7 @@ export function plugin() { return new DataVisualizerPlugin(); } -export { DataVisualizerPluginStart } from './plugin'; +export type { DataVisualizerPluginStart } from './plugin'; export type { FileDataVisualizerSpec, diff --git a/x-pack/plugins/data_visualizer/public/lazy_load_bundle/lazy/index.ts b/x-pack/plugins/data_visualizer/public/lazy_load_bundle/lazy/index.ts index a895a0eb98385..0001f912bff0d 100644 --- a/x-pack/plugins/data_visualizer/public/lazy_load_bundle/lazy/index.ts +++ b/x-pack/plugins/data_visualizer/public/lazy_load_bundle/lazy/index.ts @@ -5,9 +5,5 @@ * 2.0. */ -export { - FileDataVisualizer, - IndexDataVisualizer, - FileDataVisualizerSpec, - IndexDataVisualizerSpec, -} from '../../application'; +export type { FileDataVisualizerSpec, IndexDataVisualizerSpec } from '../../application'; +export { FileDataVisualizer, IndexDataVisualizer } from '../../application'; diff --git a/x-pack/plugins/drilldowns/url_drilldown/public/lib/url_drilldown.tsx b/x-pack/plugins/drilldowns/url_drilldown/public/lib/url_drilldown.tsx index 4c46b84008766..163a2130f657c 100644 --- a/x-pack/plugins/drilldowns/url_drilldown/public/lib/url_drilldown.tsx +++ b/x-pack/plugins/drilldowns/url_drilldown/public/lib/url_drilldown.tsx @@ -93,7 +93,6 @@ export class UrlDrilldown implements Drilldown { - // eslint-disable-next-line react-hooks/rules-of-hooks const variables = React.useMemo(() => this.getVariableList(context), [context]); return ( diff --git a/x-pack/plugins/embeddable_enhanced/public/index.ts b/x-pack/plugins/embeddable_enhanced/public/index.ts index 0512bedd2a57a..8c64f376754a5 100644 --- a/x-pack/plugins/embeddable_enhanced/public/index.ts +++ b/x-pack/plugins/embeddable_enhanced/public/index.ts @@ -8,7 +8,7 @@ import { PluginInitializerContext } from 'src/core/public'; import { EmbeddableEnhancedPlugin } from './plugin'; -export { +export type { SetupContract as EmbeddableEnhancedSetupContract, SetupDependencies as EmbeddableEnhancedSetupDependencies, StartContract as EmbeddableEnhancedStartContract, @@ -19,6 +19,6 @@ export function plugin(context: PluginInitializerContext) { return new EmbeddableEnhancedPlugin(context); } -export { EnhancedEmbeddable, EnhancedEmbeddableContext } from './types'; +export type { EnhancedEmbeddable, EnhancedEmbeddableContext } from './types'; export { isEnhancedEmbeddable } from './embeddables'; export { drilldownGrouping as embeddableEnhancedDrilldownGrouping } from './actions'; diff --git a/x-pack/plugins/encrypted_saved_objects/server/crypto/index.ts b/x-pack/plugins/encrypted_saved_objects/server/crypto/index.ts index 31086f56c3b86..532702f213192 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/crypto/index.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/crypto/index.ts @@ -5,12 +5,11 @@ * 2.0. */ -export { - EncryptedSavedObjectsService, +export type { EncryptedSavedObjectTypeRegistration, - descriptorToArray, SavedObjectDescriptor, } from './encrypted_saved_objects_service'; +export { EncryptedSavedObjectsService, descriptorToArray } from './encrypted_saved_objects_service'; export { EncryptionError, EncryptionErrorOperation } from './encryption_error'; export { EncryptedSavedObjectAttributesDefinition } from './encrypted_saved_object_type_definition'; export { EncryptionKeyRotationService } from './encryption_key_rotation_service'; diff --git a/x-pack/plugins/encrypted_saved_objects/server/index.ts b/x-pack/plugins/encrypted_saved_objects/server/index.ts index d462f06939f6b..873c8c0d52cb5 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/index.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/index.ts @@ -10,9 +10,10 @@ import type { PluginConfigDescriptor, PluginInitializerContext } from 'src/core/ import { ConfigSchema } from './config'; import { EncryptedSavedObjectsPlugin } from './plugin'; -export { EncryptedSavedObjectTypeRegistration, EncryptionError } from './crypto'; -export { EncryptedSavedObjectsPluginSetup, EncryptedSavedObjectsPluginStart } from './plugin'; -export { EncryptedSavedObjectsClient } from './saved_objects'; +export type { EncryptedSavedObjectTypeRegistration } from './crypto'; +export { EncryptionError } from './crypto'; +export type { EncryptedSavedObjectsPluginSetup, EncryptedSavedObjectsPluginStart } from './plugin'; +export type { EncryptedSavedObjectsClient } from './saved_objects'; export type { IsMigrationNeededPredicate } from './create_migration'; export const config: PluginConfigDescriptor = { diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation_history.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation_history.test.tsx index b7d1b6f9ed809..cd8ba123b5843 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation_history.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation_history.test.tsx @@ -17,7 +17,7 @@ describe('AutomatedCurationHistory', () => { it('renders', () => { const wrapper = shallow(); expect(wrapper.find(EntSearchLogStream).prop('query')).toEqual( - 'appsearch.search_relevance_suggestions.query: some text and event.kind: event and event.dataset: search-relevance-suggestions and appsearch.search_relevance_suggestions.engine: foo and event.action: curation_suggestion and appsearch.search_relevance_suggestions.suggestion.new_status: automated' + 'appsearch.adaptive_relevance.query: some text and event.kind: event and event.dataset: search-relevance-suggestions and appsearch.adaptive_relevance.engine: foo and event.action: curation_suggestion and appsearch.adaptive_relevance.suggestion.new_status: automated' ); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation_history.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation_history.tsx index debe8f86cfe2b..7fb91daf2e590 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation_history.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation_history.tsx @@ -19,12 +19,12 @@ interface Props { export const AutomatedCurationHistory: React.FC = ({ query, engineName }) => { const filters = [ - `appsearch.search_relevance_suggestions.query: ${query}`, + `appsearch.adaptive_relevance.query: ${query}`, 'event.kind: event', 'event.dataset: search-relevance-suggestions', - `appsearch.search_relevance_suggestions.engine: ${engineName}`, + `appsearch.adaptive_relevance.engine: ${engineName}`, 'event.action: curation_suggestion', - 'appsearch.search_relevance_suggestions.suggestion.new_status: automated', + 'appsearch.adaptive_relevance.suggestion.new_status: automated', ]; return ( diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/suggested_documents_callout.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/suggested_documents_callout.test.tsx index b1f02b960aa8a..4fdce0bcd0299 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/suggested_documents_callout.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/suggested_documents_callout.test.tsx @@ -28,7 +28,7 @@ const MOCK_VALUES = { }, // EngineLogic engine: { - search_relevance_suggestions_active: true, + adaptive_relevance_suggestions_active: true, }, }; @@ -53,7 +53,7 @@ describe('SuggestedDocumentsCallout', () => { }); it('is empty when suggestions are not active', () => { - const values = set('engine.search_relevance_suggestions_active', false, MOCK_VALUES); + const values = set('engine.adaptive_relevance_suggestions_active', false, MOCK_VALUES); setMockValues(values); const wrapper = shallow(); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/suggested_documents_callout.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/suggested_documents_callout.tsx index af76ebee16bad..ec296089a1086 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/suggested_documents_callout.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/suggested_documents_callout.tsx @@ -22,13 +22,13 @@ export const SuggestedDocumentsCallout: React.FC = () => { curation: { suggestion, queries }, } = useValues(CurationLogic); const { - engine: { search_relevance_suggestions_active: searchRelevanceSuggestionsActive }, + engine: { adaptive_relevance_suggestions_active: adaptiveRelevanceSuggestionsActive }, } = useValues(EngineLogic); if ( typeof suggestion === 'undefined' || suggestion.status !== 'pending' || - searchRelevanceSuggestionsActive === false + adaptiveRelevanceSuggestionsActive === false ) { return null; } diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations.test.tsx index 49d48c8c05ba6..ba3ac33be3c47 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations.test.tsx @@ -55,7 +55,7 @@ describe('Curations', () => { }, // EngineLogic engine: { - search_relevance_suggestions_active: true, + adaptive_relevance_suggestions_active: true, }, }; @@ -89,7 +89,7 @@ describe('Curations', () => { }); it('renders less tabs when suggestions are not active', () => { - setMockValues(set('engine.search_relevance_suggestions_active', false, values)); + setMockValues(set('engine.adaptive_relevance_suggestions_active', false, values)); const wrapper = shallow(); expect(getPageTitle(wrapper)).toEqual('Curated results'); @@ -99,7 +99,7 @@ describe('Curations', () => { }); it('renders a New! badge when suggestions are not active', () => { - setMockValues(set('engine.search_relevance_suggestions_active', false, values)); + setMockValues(set('engine.adaptive_relevance_suggestions_active', false, values)); const wrapper = shallow(); expect(getPageTitle(wrapper)).toEqual('Curated results'); @@ -109,7 +109,7 @@ describe('Curations', () => { }); it('hides the badge when suggestions are active', () => { - setMockValues(set('engine.search_relevance_suggestions_active', true, values)); + setMockValues(set('engine.adaptive_relevance_suggestions_active', true, values)); const wrapper = shallow(); expect(getPageTitle(wrapper)).toEqual('Curated results'); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations.tsx index b0f4f03789af2..048566409ab9f 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations.tsx @@ -30,10 +30,10 @@ export const Curations: React.FC = () => { const { dataLoading, meta, selectedPageTab } = useValues(CurationsLogic); const { loadCurations, onSelectPageTab } = useActions(CurationsLogic); const { - engine: { search_relevance_suggestions_active: searchRelevanceSuggestionsActive }, + engine: { adaptive_relevance_suggestions_active: adaptiveRelevanceSuggestionsActive }, } = useValues(EngineLogic); - const suggestionsEnabled = searchRelevanceSuggestionsActive; + const suggestionsEnabled = adaptiveRelevanceSuggestionsActive; const OVERVIEW_TAB = { label: i18n.translate( @@ -72,7 +72,7 @@ export const Curations: React.FC = () => { ), }; - const pageTabs = searchRelevanceSuggestionsActive + const pageTabs = adaptiveRelevanceSuggestionsActive ? [OVERVIEW_TAB, HISTORY_TAB, SETTINGS_TAB] : [OVERVIEW_TAB, SETTINGS_TAB]; diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/automated_curations_history_panel.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/automated_curations_history_panel.test.tsx index 044637ff1c823..36703dc0d0d85 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/automated_curations_history_panel.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/automated_curations_history_panel.test.tsx @@ -29,7 +29,7 @@ describe('AutomatedCurationsHistoryPanel', () => { expect(wrapper.is(DataPanel)).toBe(true); expect(wrapper.find(EntSearchLogStream).prop('query')).toEqual( - 'event.kind: event and event.dataset: search-relevance-suggestions and appsearch.search_relevance_suggestions.engine: some-engine and event.action: curation_suggestion and appsearch.search_relevance_suggestions.suggestion.new_status: automated' + 'event.kind: event and event.dataset: search-relevance-suggestions and appsearch.adaptive_relevance.engine: some-engine and event.action: curation_suggestion and appsearch.adaptive_relevance.suggestion.new_status: automated' ); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/automated_curations_history_panel.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/automated_curations_history_panel.tsx index 901609718c8ec..04f786b1ee1e1 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/automated_curations_history_panel.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/automated_curations_history_panel.tsx @@ -21,9 +21,9 @@ export const AutomatedCurationsHistoryPanel: React.FC = () => { const filters = [ 'event.kind: event', 'event.dataset: search-relevance-suggestions', - `appsearch.search_relevance_suggestions.engine: ${engineName}`, + `appsearch.adaptive_relevance.engine: ${engineName}`, 'event.action: curation_suggestion', - 'appsearch.search_relevance_suggestions.suggestion.new_status: automated', + 'appsearch.adaptive_relevance.suggestion.new_status: automated', ]; return ( @@ -54,7 +54,7 @@ export const AutomatedCurationsHistoryPanel: React.FC = () => { columns={[ { type: 'field', - field: 'appsearch.search_relevance_suggestions.query', + field: 'appsearch.adaptive_relevance.query', header: i18n.translate( 'xpack.enterpriseSearch.appSearch.engine.curations.automatedCurationsHistoryPanel.queryColumnHeader', { defaultMessage: 'Query' } diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/rejected_curations_history_panel.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/rejected_curations_history_panel.test.tsx index 28bb317941e1c..58bf89a36d5ee 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/rejected_curations_history_panel.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/rejected_curations_history_panel.test.tsx @@ -29,7 +29,7 @@ describe('RejectedCurationsHistoryPanel', () => { expect(wrapper.is(DataPanel)).toBe(true); expect(wrapper.find(EntSearchLogStream).prop('query')).toEqual( - 'event.kind: event and event.dataset: search-relevance-suggestions and appsearch.search_relevance_suggestions.engine: some-engine and event.action: curation_suggestion and appsearch.search_relevance_suggestions.suggestion.new_status: rejected' + 'event.kind: event and event.dataset: search-relevance-suggestions and appsearch.adaptive_relevance.engine: some-engine and event.action: curation_suggestion and appsearch.adaptive_relevance.suggestion.new_status: rejected' ); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/rejected_curations_history_panel.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/rejected_curations_history_panel.tsx index 275083f91c0fb..e7d66fc35a506 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/rejected_curations_history_panel.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/rejected_curations_history_panel.tsx @@ -21,9 +21,9 @@ export const RejectedCurationsHistoryPanel: React.FC = () => { const filters = [ 'event.kind: event', 'event.dataset: search-relevance-suggestions', - `appsearch.search_relevance_suggestions.engine: ${engineName}`, + `appsearch.adaptive_relevance.engine: ${engineName}`, 'event.action: curation_suggestion', - 'appsearch.search_relevance_suggestions.suggestion.new_status: rejected', + 'appsearch.adaptive_relevance.suggestion.new_status: rejected', ]; return ( @@ -53,7 +53,7 @@ export const RejectedCurationsHistoryPanel: React.FC = () => { columns={[ { type: 'field', - field: 'appsearch.search_relevance_suggestions.query', + field: 'appsearch.adaptive_relevance.query', header: i18n.translate( 'xpack.enterpriseSearch.appSearch.engine.curations.rejectedCurationsHistoryPanel.queryColumnHeader', { defaultMessage: 'Query' } diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_overview.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_overview.test.tsx index 43ef9dfd7ad2b..b7da6d64b6a8a 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_overview.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_overview.test.tsx @@ -36,7 +36,7 @@ const MOCK_VALUES = { ], // EngineLogic engine: { - search_relevance_suggestions_active: true, + adaptive_relevance_suggestions_active: true, }, }; @@ -71,14 +71,14 @@ describe('CurationsOverview', () => { }); it('renders a suggestions table when suggestions are active', () => { - setMockValues(set('engine.search_relevance_suggestions_active', true, MOCK_VALUES)); + setMockValues(set('engine.adaptive_relevance_suggestions_active', true, MOCK_VALUES)); const wrapper = shallow(); expect(wrapper.find(SuggestionsTable).exists()).toBe(true); }); it('doesn\t render a suggestions table when suggestions are not active', () => { - setMockValues(set('engine.search_relevance_suggestions_active', false, MOCK_VALUES)); + setMockValues(set('engine.adaptive_relevance_suggestions_active', false, MOCK_VALUES)); const wrapper = shallow(); expect(wrapper.find(SuggestionsTable).exists()).toBe(false); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_overview.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_overview.tsx index a611ca88cefd4..f763c297ea1de 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_overview.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_overview.tsx @@ -19,10 +19,10 @@ import { CurationsLogic } from '../curations_logic'; export const CurationsOverview: React.FC = () => { const { curations } = useValues(CurationsLogic); const { - engine: { search_relevance_suggestions_active: searchRelevanceSuggestionsActive }, + engine: { adaptive_relevance_suggestions_active: adaptiveRelevanceSuggestionsActive }, } = useValues(EngineLogic); - const shouldShowSuggestions = searchRelevanceSuggestionsActive; + const shouldShowSuggestions = adaptiveRelevanceSuggestionsActive; return ( <> diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine/engine_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine/engine_logic.test.ts index bb30190833dd3..adcc6bc546629 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine/engine_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine/engine_logic.test.ts @@ -43,7 +43,7 @@ describe('EngineLogic', () => { schema: { test: SchemaType.Text }, apiTokens: [], apiKey: 'some-key', - search_relevance_suggestions_active: true, + adaptive_relevance_suggestions_active: true, }; const DEFAULT_VALUES = { diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine/types.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine/types.ts index 0bfbc185b85f3..6faa749f95864 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine/types.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine/types.ts @@ -53,8 +53,8 @@ export interface EngineDetails extends Engine { isMeta: boolean; engine_count?: number; includedEngines?: EngineDetails[]; - search_relevance_suggestions?: SearchRelevanceSuggestionDetails; - search_relevance_suggestions_active: boolean; + adaptive_relevance_suggestions?: SearchRelevanceSuggestionDetails; + adaptive_relevance_suggestions_active: boolean; } interface ResultField { diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview/components/suggested_curations_callout.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview/components/suggested_curations_callout.test.tsx index c65d95a5254ee..2fb9bb255110d 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview/components/suggested_curations_callout.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview/components/suggested_curations_callout.test.tsx @@ -19,12 +19,12 @@ import { SuggestedCurationsCallout } from './suggested_curations_callout'; const MOCK_VALUES = { engine: { - search_relevance_suggestions: { + adaptive_relevance_suggestions: { curation: { pending: 1, }, }, - search_relevance_suggestions_active: true, + adaptive_relevance_suggestions_active: true, }, }; @@ -44,7 +44,7 @@ describe('SuggestedCurationsCallout', () => { setMockValues({ ...MOCK_VALUES, engine: { - search_relevance_suggestions_active: true, + adaptive_relevance_suggestions_active: true, }, }); @@ -54,7 +54,7 @@ describe('SuggestedCurationsCallout', () => { }); it('is empty when suggestions are not active', () => { - const values = set('engine.search_relevance_suggestions_active', false, MOCK_VALUES); + const values = set('engine.adaptive_relevance_suggestions_active', false, MOCK_VALUES); setMockValues(values); const wrapper = shallow(); @@ -63,7 +63,7 @@ describe('SuggestedCurationsCallout', () => { }); it('is empty when no pending curations', () => { - const values = set('engine.search_relevance_suggestions.curation.pending', 0, MOCK_VALUES); + const values = set('engine.adaptive_relevance_suggestions.curation.pending', 0, MOCK_VALUES); setMockValues(values); const wrapper = shallow(); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview/components/suggested_curations_callout.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview/components/suggested_curations_callout.tsx index 04b2d2b207e94..e1f984581438f 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview/components/suggested_curations_callout.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/engine_overview/components/suggested_curations_callout.tsx @@ -17,17 +17,17 @@ import { EngineLogic, generateEnginePath } from '../../engine'; export const SuggestedCurationsCallout: React.FC = () => { const { engine: { - search_relevance_suggestions: searchRelevanceSuggestions, - search_relevance_suggestions_active: searchRelevanceSuggestionsActive, + adaptive_relevance_suggestions: adaptiveRelevanceSuggestions, + adaptive_relevance_suggestions_active: adaptiveRelevanceSuggestionsActive, }, } = useValues(EngineLogic); - const pendingCount = searchRelevanceSuggestions?.curation.pending; + const pendingCount = adaptiveRelevanceSuggestions?.curation.pending; if ( - typeof searchRelevanceSuggestions === 'undefined' || + typeof adaptiveRelevanceSuggestions === 'undefined' || pendingCount === 0 || - searchRelevanceSuggestionsActive === false + adaptiveRelevanceSuggestionsActive === false ) { return null; } @@ -46,7 +46,7 @@ export const SuggestedCurationsCallout: React.FC = () => { } )} buttonTo={generateEnginePath(ENGINE_CURATIONS_PATH)} - lastUpdatedTimestamp={searchRelevanceSuggestions.curation.last_updated} + lastUpdatedTimestamp={adaptiveRelevanceSuggestions.curation.last_updated} /> ); }; diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/types.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/types.ts index ca3e67129846b..0efa8880cca22 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/types.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/types.ts @@ -6,5 +6,5 @@ */ export * from '../../../common/types/app_search'; -export { Role, RoleTypes, AbilityTypes, ASRoleMapping, AdvanceRoleType } from './utils/role'; -export { Engine } from './components/engine/types'; +export type { Role, RoleTypes, AbilityTypes, ASRoleMapping, AdvanceRoleType } from './utils/role'; +export type { Engine } from './components/engine/types'; diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/flash_messages/index.ts b/x-pack/plugins/enterprise_search/public/applications/shared/flash_messages/index.ts index 38a5d6e8b0b30..097d38e0691c5 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/flash_messages/index.ts +++ b/x-pack/plugins/enterprise_search/public/applications/shared/flash_messages/index.ts @@ -7,7 +7,7 @@ export { FlashMessages, Toasts } from './flash_messages'; export { FlashMessagesLogic, mountFlashMessagesLogic } from './flash_messages_logic'; -export { IFlashMessage } from './types'; +export type { IFlashMessage } from './types'; export { flashAPIErrors } from './handle_api_errors'; export { setSuccessMessage, diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/layout/index.ts b/x-pack/plugins/enterprise_search/public/applications/shared/layout/index.ts index 41f8869ad5f61..79919e925c625 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/layout/index.ts +++ b/x-pack/plugins/enterprise_search/public/applications/shared/layout/index.ts @@ -5,5 +5,6 @@ * 2.0. */ -export { EnterpriseSearchPageTemplate, PageTemplateProps } from './page_template'; +export type { PageTemplateProps } from './page_template'; +export { EnterpriseSearchPageTemplate } from './page_template'; export { generateNavLink } from './nav_link_helpers'; diff --git a/x-pack/plugins/enterprise_search/public/applications/shared/react_router_helpers/index.ts b/x-pack/plugins/enterprise_search/public/applications/shared/react_router_helpers/index.ts index fe76c13c2b707..a05792d5fb545 100644 --- a/x-pack/plugins/enterprise_search/public/applications/shared/react_router_helpers/index.ts +++ b/x-pack/plugins/enterprise_search/public/applications/shared/react_router_helpers/index.ts @@ -6,8 +6,10 @@ */ export { letBrowserHandleEvent } from './link_events'; -export { createHref, CreateHrefOptions } from './create_href'; -export { generateReactRouterProps, ReactRouterProps } from './generate_react_router_props'; +export type { CreateHrefOptions } from './create_href'; +export { createHref } from './create_href'; +export type { ReactRouterProps } from './generate_react_router_props'; +export { generateReactRouterProps } from './generate_react_router_props'; export { EuiLinkTo, EuiButtonTo, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/shared/source_row/index.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/shared/source_row/index.ts index 9bc16553b1a0c..7b0ba4206cff4 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/shared/source_row/index.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/shared/source_row/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { SourceRow, ISourceRow } from './source_row'; +export type { ISourceRow } from './source_row'; +export { SourceRow } from './source_row'; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.ts index 06055e9562676..05a5fd5a73fe8 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.ts @@ -546,8 +546,8 @@ export const AddSourceLogic = kea { diff --git a/x-pack/plugins/event_log/server/es/index.ts b/x-pack/plugins/event_log/server/es/index.ts index 2631df882cc07..a5bc5dce7f250 100644 --- a/x-pack/plugins/event_log/server/es/index.ts +++ b/x-pack/plugins/event_log/server/es/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { EsContext, createEsContext } from './context'; +export type { EsContext } from './context'; +export { createEsContext } from './context'; diff --git a/x-pack/plugins/event_log/server/index.ts b/x-pack/plugins/event_log/server/index.ts index 14c121664d4a8..877c39a02edc5 100644 --- a/x-pack/plugins/event_log/server/index.ts +++ b/x-pack/plugins/event_log/server/index.ts @@ -9,7 +9,7 @@ import { PluginInitializerContext, PluginConfigDescriptor } from 'src/core/serve import { ConfigSchema, IEventLogConfig } from './types'; import { Plugin } from './plugin'; -export { +export type { IEventLogService, IEventLogger, IEventLogClientService, @@ -17,8 +17,8 @@ export { IValidatedEvent, IEventLogClient, QueryEventsBySavedObjectResult, - SAVED_OBJECT_REL_PRIMARY, } from './types'; +export { SAVED_OBJECT_REL_PRIMARY } from './types'; export { ClusterClientAdapter } from './es/cluster_client_adapter'; diff --git a/x-pack/plugins/event_log/server/types.ts b/x-pack/plugins/event_log/server/types.ts index 6ffde7fd6dbe0..0cc2e7a145147 100644 --- a/x-pack/plugins/event_log/server/types.ts +++ b/x-pack/plugins/event_log/server/types.ts @@ -8,11 +8,12 @@ import { schema, TypeOf } from '@kbn/config-schema'; import type { IRouter, KibanaRequest, RequestHandlerContext } from 'src/core/server'; -export { IEvent, IValidatedEvent, EventSchema, ECS_VERSION } from '../generated/schemas'; +export type { IEvent, IValidatedEvent } from '../generated/schemas'; +export { EventSchema, ECS_VERSION } from '../generated/schemas'; import { IEvent } from '../generated/schemas'; import { FindOptionsType } from './event_log_client'; import { QueryEventsBySavedObjectResult } from './es/cluster_client_adapter'; -export { QueryEventsBySavedObjectResult } from './es/cluster_client_adapter'; +export type { QueryEventsBySavedObjectResult } from './es/cluster_client_adapter'; import { SavedObjectProvider } from './saved_object_provider_registry'; export const SAVED_OBJECT_REL_PRIMARY = 'primary'; diff --git a/x-pack/plugins/features/common/index.ts b/x-pack/plugins/features/common/index.ts index 450b474744fe9..9db2a1073cd07 100644 --- a/x-pack/plugins/features/common/index.ts +++ b/x-pack/plugins/features/common/index.ts @@ -5,14 +5,16 @@ * 2.0. */ -export { FeatureElasticsearchPrivileges } from './feature_elasticsearch_privileges'; -export { FeatureKibanaPrivileges } from './feature_kibana_privileges'; -export { ElasticsearchFeature, ElasticsearchFeatureConfig } from './elasticsearch_feature'; -export { KibanaFeature, KibanaFeatureConfig } from './kibana_feature'; -export { - SubFeature, +export type { FeatureElasticsearchPrivileges } from './feature_elasticsearch_privileges'; +export type { FeatureKibanaPrivileges } from './feature_kibana_privileges'; +export type { ElasticsearchFeatureConfig } from './elasticsearch_feature'; +export { ElasticsearchFeature } from './elasticsearch_feature'; +export type { KibanaFeatureConfig } from './kibana_feature'; +export { KibanaFeature } from './kibana_feature'; +export type { SubFeatureConfig, SubFeaturePrivilegeConfig, SubFeaturePrivilegeGroupConfig, SubFeaturePrivilegeGroupType, } from './sub_feature'; +export { SubFeature } from './sub_feature'; diff --git a/x-pack/plugins/features/public/index.ts b/x-pack/plugins/features/public/index.ts index d1a828f51029a..2895d83ed114e 100644 --- a/x-pack/plugins/features/public/index.ts +++ b/x-pack/plugins/features/public/index.ts @@ -8,15 +8,15 @@ import { PluginInitializer } from 'src/core/public'; import { FeaturesPlugin, FeaturesPluginSetup, FeaturesPluginStart } from './plugin'; -export { - KibanaFeature, +export type { KibanaFeatureConfig, FeatureKibanaPrivileges, SubFeatureConfig, SubFeaturePrivilegeConfig, } from '../common'; +export { KibanaFeature } from '../common'; -export { FeaturesPluginSetup, FeaturesPluginStart } from './plugin'; +export type { FeaturesPluginSetup, FeaturesPluginStart } from './plugin'; export const plugin: PluginInitializer = () => new FeaturesPlugin(); diff --git a/x-pack/plugins/features/server/index.ts b/x-pack/plugins/features/server/index.ts index 0890274fed950..934fcd9d556f6 100644 --- a/x-pack/plugins/features/server/index.ts +++ b/x-pack/plugins/features/server/index.ts @@ -14,15 +14,14 @@ import { FeaturesPlugin } from './plugin'; // run-time contracts. export { uiCapabilitiesRegex } from './feature_schema'; -export { - KibanaFeature, +export type { KibanaFeatureConfig, FeatureKibanaPrivileges, - ElasticsearchFeature, ElasticsearchFeatureConfig, FeatureElasticsearchPrivileges, } from '../common'; -export { PluginSetupContract, PluginStartContract } from './plugin'; +export { KibanaFeature, ElasticsearchFeature } from '../common'; +export type { PluginSetupContract, PluginStartContract } from './plugin'; export const plugin = (initializerContext: PluginInitializerContext) => new FeaturesPlugin(initializerContext); diff --git a/x-pack/plugins/file_upload/public/components/geojson_upload_form/index.ts b/x-pack/plugins/file_upload/public/components/geojson_upload_form/index.ts index 6168835a3a145..837c8a0f02694 100644 --- a/x-pack/plugins/file_upload/public/components/geojson_upload_form/index.ts +++ b/x-pack/plugins/file_upload/public/components/geojson_upload_form/index.ts @@ -6,4 +6,4 @@ */ export { GeoJsonUploadForm } from './geojson_upload_form'; -export { OnFileSelectParameters } from './geojson_file_picker'; +export type { OnFileSelectParameters } from './geojson_file_picker'; diff --git a/x-pack/plugins/file_upload/public/importer/geojson_importer/index.ts b/x-pack/plugins/file_upload/public/importer/geojson_importer/index.ts index b5f6845e28324..7d9d8e144fd25 100644 --- a/x-pack/plugins/file_upload/public/importer/geojson_importer/index.ts +++ b/x-pack/plugins/file_upload/public/importer/geojson_importer/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { GeoJsonImporter, GeoJsonPreview, GEOJSON_FILE_TYPES } from './geojson_importer'; +export type { GeoJsonPreview } from './geojson_importer'; +export { GeoJsonImporter, GEOJSON_FILE_TYPES } from './geojson_importer'; diff --git a/x-pack/plugins/file_upload/public/index.ts b/x-pack/plugins/file_upload/public/index.ts index b9e289ef00eeb..00b39dca1180d 100644 --- a/x-pack/plugins/file_upload/public/index.ts +++ b/x-pack/plugins/file_upload/public/index.ts @@ -16,7 +16,7 @@ export function plugin() { export * from './importer/types'; -export { Props as IndexNameFormProps } from './components/geojson_upload_form/index_name_form'; +export type { Props as IndexNameFormProps } from './components/geojson_upload_form/index_name_form'; -export { FileUploadPluginStart } from './plugin'; -export { FileUploadComponentProps, FileUploadGeoResults } from './lazy_load_bundle'; +export type { FileUploadPluginStart } from './plugin'; +export type { FileUploadComponentProps, FileUploadGeoResults } from './lazy_load_bundle'; diff --git a/x-pack/plugins/fleet/common/services/index.ts b/x-pack/plugins/fleet/common/services/index.ts index a6f4cd319b970..ba3fb44753643 100644 --- a/x-pack/plugins/fleet/common/services/index.ts +++ b/x-pack/plugins/fleet/common/services/index.ts @@ -21,10 +21,12 @@ export { isDiffPathProtocol } from './is_diff_path_protocol'; export { LicenseService } from './license'; export { isAgentUpgradeable } from './is_agent_upgradeable'; export { doesPackageHaveIntegrations } from './packages_with_integrations'; -export { +export type { PackagePolicyValidationResults, PackagePolicyConfigValidationResults, PackagePolicyInputValidationResults, +} from './validate_package_policy'; +export { validatePackagePolicy, validatePackagePolicyConfig, validationHasErrors, diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/services/index.ts b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/services/index.ts index 0e1953316fd53..38ef2a60e41d0 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/services/index.ts +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/services/index.ts @@ -7,10 +7,12 @@ export { isAdvancedVar } from './is_advanced_var'; export { hasInvalidButRequiredVar } from './has_invalid_but_required_var'; -export { +export type { PackagePolicyValidationResults, PackagePolicyConfigValidationResults, PackagePolicyInputValidationResults, +} from '../../../../services'; +export { validatePackagePolicy, validatePackagePolicyConfig, validationHasErrors, diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_define_package_policy.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_define_package_policy.tsx index e11aaabb4fd95..63e9ba64ad753 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_define_package_policy.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_define_package_policy.tsx @@ -22,16 +22,12 @@ import { import styled from 'styled-components'; -import type { - AgentPolicy, - PackageInfo, - PackagePolicy, - NewPackagePolicy, - RegistryVarsEntry, -} from '../../../types'; +import type { AgentPolicy, PackageInfo, NewPackagePolicy, RegistryVarsEntry } from '../../../types'; import { packageToPackagePolicy, pkgKeyFromPackageInfo } from '../../../services'; import { Loading } from '../../../components'; -import { useStartServices } from '../../../hooks'; +import { useStartServices, useGetPackagePolicies } from '../../../hooks'; +import { PACKAGE_POLICY_SAVED_OBJECT_TYPE } from '../../../../../constants'; +import { SO_SEARCH_LIMIT } from '../../../../../../common'; import { isAdvancedVar } from './services'; import type { PackagePolicyValidationResults } from './services'; @@ -65,6 +61,14 @@ export const StepDefinePackagePolicy: React.FunctionComponent<{ submitAttempted, }) => { const { docLinks } = useStartServices(); + + // Fetch all packagePolicies having the package name + const { data: packagePolicyData, isLoading: isLoadingPackagePolicies } = useGetPackagePolicies({ + perPage: SO_SEARCH_LIMIT, + page: 1, + kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name:${packageInfo.name}`, + }); + // Form show/hide states const [isShowingAdvanced, setIsShowingAdvanced] = useState(false); @@ -84,33 +88,37 @@ export const StepDefinePackagePolicy: React.FunctionComponent<{ // Update package policy's package and agent policy info useEffect(() => { + if (isLoadingPackagePolicies) { + return; + } const pkg = packagePolicy.package; const currentPkgKey = pkg ? pkgKeyFromPackageInfo(pkg) : ''; const pkgKey = pkgKeyFromPackageInfo(packageInfo); // If package has changed, create shell package policy with input&stream values based on package info if (currentPkgKey !== pkgKey) { - // Existing package policies on the agent policy using the package name, retrieve highest number appended to package policy name + // Retrieve highest number appended to package policy name and increment it by one const pkgPoliciesNamePattern = new RegExp(`${packageInfo.name}-(\\d+)`); - const pkgPoliciesWithMatchingNames = agentPolicy - ? (agentPolicy.package_policies as PackagePolicy[]) + const pkgPoliciesWithMatchingNames = packagePolicyData?.items + ? packagePolicyData.items .filter((ds) => Boolean(ds.name.match(pkgPoliciesNamePattern))) .map((ds) => parseInt(ds.name.match(pkgPoliciesNamePattern)![1], 10)) .sort((a, b) => a - b) : []; + const incrementedName = `${packageInfo.name}-${ + pkgPoliciesWithMatchingNames.length + ? pkgPoliciesWithMatchingNames[pkgPoliciesWithMatchingNames.length - 1] + 1 + : 1 + }`; + updatePackagePolicy( packageToPackagePolicy( packageInfo, agentPolicy?.id || '', packagePolicy.output_id, packagePolicy.namespace, - packagePolicy.name || - `${packageInfo.name}-${ - pkgPoliciesWithMatchingNames.length - ? pkgPoliciesWithMatchingNames[pkgPoliciesWithMatchingNames.length - 1] + 1 - : 1 - }`, + packagePolicy.name || incrementedName, packagePolicy.description, integrationToEnable ) @@ -124,7 +132,15 @@ export const StepDefinePackagePolicy: React.FunctionComponent<{ namespace: agentPolicy.namespace, }); } - }, [packagePolicy, agentPolicy, packageInfo, updatePackagePolicy, integrationToEnable]); + }, [ + packagePolicy, + agentPolicy, + packageInfo, + updatePackagePolicy, + integrationToEnable, + packagePolicyData, + isLoadingPackagePolicies, + ]); return validationResults ? ( (false); useEffect(() => { - const stateStorage = createKbnUrlStateStorage(); + const stateStorage = createKbnUrlStateStorage({ useHashQuery: false, useHash: false }); const { start, stop } = syncState({ storageKey: STATE_STORAGE_KEY, stateContainer: stateContainer as INullableBaseStateContainer, diff --git a/x-pack/plugins/fleet/public/applications/integrations/app.tsx b/x-pack/plugins/fleet/public/applications/integrations/app.tsx index c2f6f53627e38..3a091c30bb792 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/app.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/app.tsx @@ -5,21 +5,14 @@ * 2.0. */ -import React, { memo, useEffect, useState } from 'react'; +import React, { memo } from 'react'; import type { AppMountParameters } from 'kibana/public'; import { EuiErrorBoundary, EuiPortal } from '@elastic/eui'; import type { History } from 'history'; import { Router, Redirect, Route, Switch } from 'react-router-dom'; -import { FormattedMessage } from '@kbn/i18n/react'; import useObservable from 'react-use/lib/useObservable'; -import { - ConfigContext, - FleetStatusProvider, - KibanaVersionContext, - sendGetPermissionsCheck, - sendSetup, -} from '../../hooks'; +import { ConfigContext, FleetStatusProvider, KibanaVersionContext } from '../../hooks'; import type { FleetConfigType, FleetStartServices } from '../../plugin'; @@ -32,91 +25,14 @@ import { EuiThemeProvider } from '../../../../../../src/plugins/kibana_react/com import { AgentPolicyContextProvider, useUrlModal } from './hooks'; import { INTEGRATIONS_ROUTING_PATHS, pagePathGetters } from './constants'; -import { Error, Loading, SettingFlyout } from './components'; +import { SettingFlyout } from './components'; import type { UIExtensionsStorage } from './types'; import { EPMApp } from './sections/epm'; -import { DefaultLayout } from './layouts'; -import { PackageInstallProvider } from './hooks'; -import { useBreadcrumbs, UIExtensionsContext } from './hooks'; +import { PackageInstallProvider, UIExtensionsContext } from './hooks'; import { IntegrationsHeader } from './components/header'; -const ErrorLayout = ({ children }: { children: JSX.Element }) => ( - - {children} - -); - -export const WithPermissionsAndSetup: React.FC = memo(({ children }) => { - useBreadcrumbs('integrations'); - - const [isPermissionsLoading, setIsPermissionsLoading] = useState(false); - const [isInitialized, setIsInitialized] = useState(false); - const [initializationError, setInitializationError] = useState(null); - - useEffect(() => { - (async () => { - setIsInitialized(false); - setInitializationError(null); - try { - // Attempt Fleet Setup if user has permissions, otherwise skip - setIsPermissionsLoading(true); - const permissionsResponse = await sendGetPermissionsCheck(); - setIsPermissionsLoading(false); - - if (permissionsResponse.data?.success) { - try { - const setupResponse = await sendSetup(); - if (setupResponse.error) { - setInitializationError(setupResponse.error); - } - } catch (err) { - setInitializationError(err); - } - setIsInitialized(true); - } else { - setIsInitialized(true); - } - } catch { - // If there's an error checking permissions, default to proceeding without running setup - // User will only have access to EPM endpoints if they actually have permission - setIsInitialized(true); - } - })(); - }, []); - - if (isPermissionsLoading) { - return ( - - - - ); - } - - if (!isInitialized || initializationError) { - return ( - - {initializationError ? ( - - } - error={initializationError} - /> - ) : ( - - )} - - ); - } - - return <>{children}; -}); - /** * Fleet Application context all the way down to the Router, but with no permissions or setup checks * and no routes defined diff --git a/x-pack/plugins/fleet/public/applications/integrations/hooks/use_merge_epr_with_replacements.test.ts b/x-pack/plugins/fleet/public/applications/integrations/hooks/use_merge_epr_with_replacements.test.ts index d5d8aa093e300..f69132d9a6452 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/hooks/use_merge_epr_with_replacements.test.ts +++ b/x-pack/plugins/fleet/public/applications/integrations/hooks/use_merge_epr_with_replacements.test.ts @@ -120,6 +120,17 @@ describe('useMergeEprWithReplacements', () => { ]); }); + test('should filter out apm from package list', () => { + const eprPackages: PackageListItem[] = mockEprPackages([ + { + name: 'apm', + release: 'beta', + }, + ]); + + expect(useMergeEprPackagesWithReplacements(eprPackages, [])).toEqual([]); + }); + test('should consists of all 3 types (ga eprs, replacements for non-ga eprs, replacements without epr equivalent', () => { const eprPackages: PackageListItem[] = mockEprPackages([ { @@ -136,6 +147,10 @@ describe('useMergeEprWithReplacements', () => { name: 'activemq', release: 'beta', }, + { + name: 'apm', + release: 'ga', + }, ]); const replacements: CustomIntegration[] = mockIntegrations([ { diff --git a/x-pack/plugins/fleet/public/applications/integrations/hooks/use_merge_epr_with_replacements.ts b/x-pack/plugins/fleet/public/applications/integrations/hooks/use_merge_epr_with_replacements.ts index 4c59f0ef45123..ff1b51ef19a81 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/hooks/use_merge_epr_with_replacements.ts +++ b/x-pack/plugins/fleet/public/applications/integrations/hooks/use_merge_epr_with_replacements.ts @@ -8,6 +8,7 @@ import type { PackageListItem } from '../../../../common/types/models'; import type { CustomIntegration } from '../../../../../../../src/plugins/custom_integrations/common'; import { filterCustomIntegrations } from '../../../../../../../src/plugins/custom_integrations/public'; +import { FLEET_APM_PACKAGE } from '../../../../common/constants'; // Export this as a utility to find replacements for a package (e.g. in the overview-page for an EPR package) function findReplacementsForEprPackage( @@ -22,12 +23,17 @@ function findReplacementsForEprPackage( } export function useMergeEprPackagesWithReplacements( - eprPackages: PackageListItem[], + rawEprPackages: PackageListItem[], replacements: CustomIntegration[] ): Array { const merged: Array = []; const filteredReplacements = replacements; + // APM EPR-packages should _never_ show. They have special handling. + const eprPackages = rawEprPackages.filter((p) => { + return p.name !== FLEET_APM_PACKAGE; + }); + // Either select replacement or select beat eprPackages.forEach((eprPackage: PackageListItem) => { const hits = findReplacementsForEprPackage( diff --git a/x-pack/plugins/fleet/public/applications/integrations/index.tsx b/x-pack/plugins/fleet/public/applications/integrations/index.tsx index 4099879538afa..620cf83fd762d 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/index.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/index.tsx @@ -15,7 +15,7 @@ import type { FleetConfigType, FleetStartServices } from '../../plugin'; import { licenseService } from '../../hooks'; import type { UIExtensionsStorage } from '../../types'; -import { AppRoutes, IntegrationsAppContext, WithPermissionsAndSetup } from './app'; +import { AppRoutes, IntegrationsAppContext } from './app'; export interface ProtectedRouteProps extends RouteProps { isAllowed?: boolean; @@ -58,9 +58,7 @@ const IntegrationsApp = ({ extensions={extensions} setHeaderActionMenu={setHeaderActionMenu} > - - - + ); }; diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/home/available_packages.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/home/available_packages.tsx index f1d0717584e2e..ca932554290bb 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/home/available_packages.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/home/available_packages.tsx @@ -221,6 +221,7 @@ export const AvailablePackages: React.FC = memo(() => { if (selectedCategory === '') { return true; } + return c.categories.includes(selectedCategory); }); @@ -255,7 +256,7 @@ export const AvailablePackages: React.FC = memo(() => { defaultMessage: 'Monitor, detect and diagnose complex performance issues from your application.', })} - href={addBasePath('/app/integrations/detail/apm')} + href={addBasePath('/app/home#/tutorial/apm')} icon={} /> diff --git a/x-pack/plugins/fleet/public/components/home_integration/tutorial_module_notice.tsx b/x-pack/plugins/fleet/public/components/home_integration/tutorial_module_notice.tsx index 24d9dc8e2c100..1b0d90098fa48 100644 --- a/x-pack/plugins/fleet/public/components/home_integration/tutorial_module_notice.tsx +++ b/x-pack/plugins/fleet/public/components/home_integration/tutorial_module_notice.tsx @@ -13,6 +13,7 @@ import type { TutorialModuleNoticeComponent } from 'src/plugins/home/public'; import { useGetPackages, useLink, useCapabilities } from '../../hooks'; import { pkgKeyFromPackageInfo } from '../../services'; +import { FLEET_APM_PACKAGE } from '../../../common/constants'; const TutorialModuleNotice: TutorialModuleNoticeComponent = memo(({ moduleName }) => { const { getHref } = useLink(); @@ -22,7 +23,7 @@ const TutorialModuleNotice: TutorialModuleNoticeComponent = memo(({ moduleName } const pkgInfo = !isLoading && packagesData?.response && - packagesData.response.find((pkg) => pkg.name === moduleName); + packagesData.response.find((pkg) => pkg.name === moduleName && pkg.name !== FLEET_APM_PACKAGE); // APM needs special handling if (hasIngestManager && pkgInfo) { return ( diff --git a/x-pack/plugins/fleet/public/components/index.ts b/x-pack/plugins/fleet/public/components/index.ts index 3252315312d02..9015071450bf0 100644 --- a/x-pack/plugins/fleet/public/components/index.ts +++ b/x-pack/plugins/fleet/public/components/index.ts @@ -13,7 +13,8 @@ export { LinkedAgentCount } from './linked_agent_count'; export { ExtensionWrapper } from './extension_wrapper'; export { AlphaMessaging } from './alpha_messaging'; export { AlphaFlyout } from './alpha_flyout'; -export { HeaderProps, Header } from './header'; +export type { HeaderProps } from './header'; +export { Header } from './header'; export { NewEnrollmentTokenModal } from './new_enrollment_key_modal'; export { AgentPolicyPackageBadges } from './agent_policy_package_badges'; export { DangerEuiContextMenuItem } from './danger_eui_context_menu_item'; diff --git a/x-pack/plugins/fleet/public/hooks/index.ts b/x-pack/plugins/fleet/public/hooks/index.ts index c41dd1ad42a72..16454a266c3c4 100644 --- a/x-pack/plugins/fleet/public/hooks/index.ts +++ b/x-pack/plugins/fleet/public/hooks/index.ts @@ -12,8 +12,10 @@ export { useKibanaVersion, KibanaVersionContext } from './use_kibana_version'; export { licenseService, useLicense } from './use_license'; export { useLink } from './use_link'; export { useKibanaLink, getHrefToObjectInKibanaApp } from './use_kibana_link'; -export { usePackageIconType, UsePackageIconType } from './use_package_icon_type'; -export { usePagination, Pagination, PAGE_SIZE_OPTIONS } from './use_pagination'; +export type { UsePackageIconType } from './use_package_icon_type'; +export { usePackageIconType } from './use_package_icon_type'; +export type { Pagination } from './use_pagination'; +export { usePagination, PAGE_SIZE_OPTIONS } from './use_pagination'; export { useUrlPagination } from './use_url_pagination'; export { useSorting } from './use_sorting'; export { useDebounce } from './use_debounce'; diff --git a/x-pack/plugins/fleet/public/index.ts b/x-pack/plugins/fleet/public/index.ts index b54d00eafdaab..ee4fe526fb0e4 100644 --- a/x-pack/plugins/fleet/public/index.ts +++ b/x-pack/plugins/fleet/public/index.ts @@ -12,7 +12,7 @@ import type { PluginInitializerContext } from 'src/core/public'; import { FleetPlugin } from './plugin'; -export { FleetSetup, FleetStart } from './plugin'; +export type { FleetSetup, FleetStart } from './plugin'; export const plugin = (initializerContext: PluginInitializerContext) => { return new FleetPlugin(initializerContext); @@ -24,7 +24,5 @@ export * from './types/ui_extensions'; export { pagePathGetters } from './constants'; export { pkgKeyFromPackageInfo } from './services'; -export { - CustomAssetsAccordion, - CustomAssetsAccordionProps, -} from './components/custom_assets_accordion'; +export type { CustomAssetsAccordionProps } from './components/custom_assets_accordion'; +export { CustomAssetsAccordion } from './components/custom_assets_accordion'; diff --git a/x-pack/plugins/fleet/public/layouts/index.ts b/x-pack/plugins/fleet/public/layouts/index.ts index e6e366654a866..62e3c5b889ca8 100644 --- a/x-pack/plugins/fleet/public/layouts/index.ts +++ b/x-pack/plugins/fleet/public/layouts/index.ts @@ -5,5 +5,6 @@ * 2.0. */ -export { WithHeaderLayout, WithHeaderLayoutProps } from './with_header'; +export type { WithHeaderLayoutProps } from './with_header'; +export { WithHeaderLayout } from './with_header'; export { WithoutHeaderLayout } from './without_header'; diff --git a/x-pack/plugins/fleet/public/plugin.ts b/x-pack/plugins/fleet/public/plugin.ts index b0e4e56aa344a..039c1da9b934c 100644 --- a/x-pack/plugins/fleet/public/plugin.ts +++ b/x-pack/plugins/fleet/public/plugin.ts @@ -52,7 +52,7 @@ import { createExtensionRegistrationCallback } from './services/ui_extensions'; import type { UIExtensionRegistrationCallback, UIExtensionsStorage } from './types'; import { LazyCustomLogsAssetsExtension } from './lazy_custom_logs_assets_extension'; -export { FleetConfigType } from '../common/types'; +export type { FleetConfigType } from '../common/types'; import { setCustomIntegrations } from './services/custom_integrations'; diff --git a/x-pack/plugins/fleet/public/services/index.ts b/x-pack/plugins/fleet/public/services/index.ts index fbd3bddde744b..10dfe6b59d6ba 100644 --- a/x-pack/plugins/fleet/public/services/index.ts +++ b/x-pack/plugins/fleet/public/services/index.ts @@ -7,6 +7,11 @@ export { getFlattenedObject } from '@kbn/std'; +export type { + PackagePolicyValidationResults, + PackagePolicyConfigValidationResults, + PackagePolicyInputValidationResults, +} from '../../common'; export { AgentStatusKueryHelper, agentPolicyRouteService, @@ -30,9 +35,6 @@ export { LicenseService, isAgentUpgradeable, doesPackageHaveIntegrations, - PackagePolicyValidationResults, - PackagePolicyConfigValidationResults, - PackagePolicyInputValidationResults, validatePackagePolicy, validatePackagePolicyConfig, validationHasErrors, diff --git a/x-pack/plugins/fleet/public/types/index.ts b/x-pack/plugins/fleet/public/types/index.ts index 3ff0a760b5882..d61223f0cebc7 100644 --- a/x-pack/plugins/fleet/public/types/index.ts +++ b/x-pack/plugins/fleet/public/types/index.ts @@ -5,10 +5,7 @@ * 2.0. */ -export { - // utility function - entries, - // Object types +export type { Agent, AgentMetadata, AgentPolicy, @@ -28,9 +25,7 @@ export { Output, DataStream, Settings, - // API schema - misc setup, status GetFleetStatusResponse, - // API schemas - Agent policy GetAgentPoliciesRequest, GetAgentPoliciesResponse, GetAgentPoliciesResponseItem, @@ -44,7 +39,6 @@ export { CopyAgentPolicyResponse, DeleteAgentPolicyRequest, DeleteAgentPolicyResponse, - // API schemas - Package policy CreatePackagePolicyRequest, CreatePackagePolicyResponse, UpdatePackagePolicyRequest, @@ -53,9 +47,7 @@ export { DryRunPackagePolicy, UpgradePackagePolicyResponse, UpgradePackagePolicyDryRunResponse, - // API schemas - Data streams GetDataStreamsResponse, - // API schemas - Agents GetAgentsResponse, GetAgentsRequest, GetOneAgentResponse, @@ -75,24 +67,19 @@ export { PostBulkAgentReassignResponse, PostNewAgentActionResponse, PostNewAgentActionRequest, - // API schemas - Enrollment API Keys GetEnrollmentAPIKeysResponse, GetEnrollmentAPIKeysRequest, GetOneEnrollmentAPIKeyResponse, PostEnrollmentAPIKeyRequest, PostEnrollmentAPIKeyResponse, - // API schemas - Outputs GetOutputsResponse, PutOutputRequest, PutOutputResponse, - // API schemas - Settings GetSettingsResponse, PutSettingsRequest, PutSettingsResponse, - // API schemas - app CheckPermissionsResponse, GenerateServiceTokenResponse, - // EPM types AssetReference, AssetsGroupedByServiceByType, AssetType, @@ -100,8 +87,6 @@ export { CategoryId, CategorySummaryItem, CategorySummaryList, - ElasticsearchAssetType, - KibanaAssetType, PackageInfo, RegistryVarsEntry, RegistryInput, @@ -123,7 +108,6 @@ export { InstallPackageResponse, DeletePackageResponse, DetailViewPanelName, - InstallStatus, InstallationStatus, Installable, RegistryRelease, @@ -131,6 +115,7 @@ export { UpdatePackageRequest, UpdatePackageResponse, } from '../../common'; +export { entries, ElasticsearchAssetType, KibanaAssetType, InstallStatus } from '../../common'; export * from './intra_app_route_state'; export * from './ui_extensions'; diff --git a/x-pack/plugins/fleet/server/index.ts b/x-pack/plugins/fleet/server/index.ts index cdc0dfddc01e5..e1ee2652594cc 100644 --- a/x-pack/plugins/fleet/server/index.ts +++ b/x-pack/plugins/fleet/server/index.ts @@ -18,18 +18,18 @@ import { import { FleetPlugin } from './plugin'; export { default as apm } from 'elastic-apm-node'; -export { +export type { AgentService, ESIndexPatternService, - getRegistryUrl, PackageService, AgentPolicyServiceInterface, ArtifactsClientInterface, Artifact, ListArtifactsProps, } from './services'; +export { getRegistryUrl } from './services'; -export { FleetSetupContract, FleetSetupDeps, FleetStartContract } from './plugin'; +export type { FleetSetupContract, FleetSetupDeps, FleetStartContract } from './plugin'; export type { ExternalCallback, PutPackagePolicyUpdateCallback, @@ -45,42 +45,59 @@ export const config: PluginConfigDescriptor = { }, deprecations: ({ renameFromRoot, unused, unusedFromRoot }) => [ // Fleet plugin was named ingestManager before - renameFromRoot('xpack.ingestManager.enabled', 'xpack.fleet.enabled'), - renameFromRoot('xpack.ingestManager.registryUrl', 'xpack.fleet.registryUrl'), - renameFromRoot('xpack.ingestManager.registryProxyUrl', 'xpack.fleet.registryProxyUrl'), - renameFromRoot('xpack.ingestManager.fleet', 'xpack.ingestManager.agents'), - renameFromRoot('xpack.ingestManager.agents.enabled', 'xpack.fleet.agents.enabled'), - renameFromRoot('xpack.ingestManager.agents.elasticsearch', 'xpack.fleet.agents.elasticsearch'), + renameFromRoot('xpack.ingestManager.enabled', 'xpack.fleet.enabled', { level: 'critical' }), + renameFromRoot('xpack.ingestManager.registryUrl', 'xpack.fleet.registryUrl', { + level: 'critical', + }), + renameFromRoot('xpack.ingestManager.registryProxyUrl', 'xpack.fleet.registryProxyUrl', { + level: 'critical', + }), + renameFromRoot('xpack.ingestManager.fleet', 'xpack.ingestManager.agents', { + level: 'critical', + }), + renameFromRoot('xpack.ingestManager.agents.enabled', 'xpack.fleet.agents.enabled', { + level: 'critical', + }), + renameFromRoot('xpack.ingestManager.agents.elasticsearch', 'xpack.fleet.agents.elasticsearch', { + level: 'critical', + }), renameFromRoot( 'xpack.ingestManager.agents.tlsCheckDisabled', - 'xpack.fleet.agents.tlsCheckDisabled' + 'xpack.fleet.agents.tlsCheckDisabled', + { level: 'critical' } ), renameFromRoot( 'xpack.ingestManager.agents.pollingRequestTimeout', - 'xpack.fleet.agents.pollingRequestTimeout' + 'xpack.fleet.agents.pollingRequestTimeout', + { level: 'critical' } ), renameFromRoot( 'xpack.ingestManager.agents.maxConcurrentConnections', - 'xpack.fleet.agents.maxConcurrentConnections' + 'xpack.fleet.agents.maxConcurrentConnections', + { level: 'critical' } ), - renameFromRoot('xpack.ingestManager.agents.kibana', 'xpack.fleet.agents.kibana'), + renameFromRoot('xpack.ingestManager.agents.kibana', 'xpack.fleet.agents.kibana', { + level: 'critical', + }), renameFromRoot( 'xpack.ingestManager.agents.agentPolicyRolloutRateLimitIntervalMs', - 'xpack.fleet.agents.agentPolicyRolloutRateLimitIntervalMs' + 'xpack.fleet.agents.agentPolicyRolloutRateLimitIntervalMs', + { level: 'critical' } ), renameFromRoot( 'xpack.ingestManager.agents.agentPolicyRolloutRateLimitRequestPerInterval', - 'xpack.fleet.agents.agentPolicyRolloutRateLimitRequestPerInterval' + 'xpack.fleet.agents.agentPolicyRolloutRateLimitRequestPerInterval', + { level: 'critical' } ), - unusedFromRoot('xpack.ingestManager'), + unusedFromRoot('xpack.ingestManager', { level: 'critical' }), // Unused settings before Fleet server exists - unused('agents.kibana'), - unused('agents.maxConcurrentConnections'), - unused('agents.agentPolicyRolloutRateLimitIntervalMs'), - unused('agents.agentPolicyRolloutRateLimitRequestPerInterval'), - unused('agents.pollingRequestTimeout'), - unused('agents.tlsCheckDisabled'), - unused('agents.fleetServerEnabled'), + unused('agents.kibana', { level: 'critical' }), + unused('agents.maxConcurrentConnections', { level: 'critical' }), + unused('agents.agentPolicyRolloutRateLimitIntervalMs', { level: 'critical' }), + unused('agents.agentPolicyRolloutRateLimitRequestPerInterval', { level: 'critical' }), + unused('agents.pollingRequestTimeout', { level: 'critical' }), + unused('agents.tlsCheckDisabled', { level: 'critical' }), + unused('agents.fleetServerEnabled', { level: 'critical' }), // Renaming elasticsearch.host => elasticsearch.hosts (fullConfig, fromPath, addDeprecation) => { const oldValue = fullConfig?.xpack?.fleet?.agents?.elasticsearch?.host; @@ -95,6 +112,7 @@ export const config: PluginConfigDescriptor = { `Use [xpack.fleet.agents.elasticsearch.hosts] with an array of host instead.`, ], }, + level: 'critical', }); } @@ -129,7 +147,7 @@ export const config: PluginConfigDescriptor = { export type FleetConfigType = TypeOf; -export { PackagePolicyServiceInterface } from './services/package_policy'; +export type { PackagePolicyServiceInterface } from './services/package_policy'; export { relativeDownloadUrlFromArtifact } from './services/artifacts/mappings'; diff --git a/x-pack/plugins/fleet/server/services/agent_policy.ts b/x-pack/plugins/fleet/server/services/agent_policy.ts index 321bc7f289594..7de907b9a15fa 100644 --- a/x-pack/plugins/fleet/server/services/agent_policy.ts +++ b/x-pack/plugins/fleet/server/services/agent_policy.ts @@ -410,12 +410,16 @@ class AgentPolicyService { options ); - // Copy all package policies + // Copy all package policies and append (copy) to their names if (baseAgentPolicy.package_policies.length) { const newPackagePolicies = (baseAgentPolicy.package_policies as PackagePolicy[]).map( (packagePolicy: PackagePolicy) => { const { id: packagePolicyId, version, ...newPackagePolicy } = packagePolicy; - return newPackagePolicy; + const updatedPackagePolicy = { + ...newPackagePolicy, + name: `${packagePolicy.name} (copy)`, + }; + return updatedPackagePolicy; } ); await packagePolicyService.bulkCreate( diff --git a/x-pack/plugins/fleet/server/services/epm/packages/get.ts b/x-pack/plugins/fleet/server/services/epm/packages/get.ts index 8d3c1fbe0daa4..b6a1850fed5b8 100644 --- a/x-pack/plugins/fleet/server/services/epm/packages/get.ts +++ b/x-pack/plugins/fleet/server/services/epm/packages/get.ts @@ -30,7 +30,8 @@ import { normalizeKuery } from '../../saved_object'; import { createInstallableFrom, isUnremovablePackage } from './index'; -export { getFile, SearchParams } from '../registry'; +export type { SearchParams } from '../registry'; +export { getFile } from '../registry'; function nameAsTitle(name: string) { return name.charAt(0).toUpperCase() + name.substr(1).toLowerCase(); diff --git a/x-pack/plugins/fleet/server/services/epm/packages/index.ts b/x-pack/plugins/fleet/server/services/epm/packages/index.ts index 58e7c9e8928d8..a6970a8d19db4 100644 --- a/x-pack/plugins/fleet/server/services/epm/packages/index.ts +++ b/x-pack/plugins/fleet/server/services/epm/packages/index.ts @@ -12,6 +12,7 @@ import { KibanaAssetType } from '../../../types'; import type { AssetType, Installable, Installation } from '../../../types'; export { bulkInstallPackages, isBulkInstallError } from './bulk_install_packages'; +export type { SearchParams } from './get'; export { getCategories, getFile, @@ -21,16 +22,10 @@ export { getPackageInfo, getPackages, getLimitedPackages, - SearchParams, } from './get'; -export { - BulkInstallResponse, - IBulkInstallPackageError, - handleInstallPackageFailure, - installPackage, - ensureInstalledPackage, -} from './install'; +export type { BulkInstallResponse, IBulkInstallPackageError } from './install'; +export { handleInstallPackageFailure, installPackage, ensureInstalledPackage } from './install'; export { removeInstallation } from './remove'; export function isUnremovablePackage(value: string): boolean { diff --git a/x-pack/plugins/fleet/server/services/package_policy.ts b/x-pack/plugins/fleet/server/services/package_policy.ts index 8968b1b4af3fd..985351c3e981b 100644 --- a/x-pack/plugins/fleet/server/services/package_policy.ts +++ b/x-pack/plugins/fleet/server/services/package_policy.ts @@ -42,7 +42,6 @@ import type { } from '../../common'; import { PACKAGE_POLICY_SAVED_OBJECT_TYPE } from '../constants'; import { - HostedAgentPolicyRestrictionRelatedError, IngestManagerError, ingestErrorToResponseOptions, PackagePolicyIneligibleForUpgradeError, @@ -99,24 +98,14 @@ class PackagePolicyService { skipEnsureInstalled?: boolean; } ): Promise { - // Check that its agent policy does not have a package policy with the same name - const parentAgentPolicy = await agentPolicyService.get(soClient, packagePolicy.policy_id); - if (!parentAgentPolicy) { - throw new Error('Agent policy not found'); - } - if (parentAgentPolicy.is_managed && !options?.force) { - throw new HostedAgentPolicyRestrictionRelatedError( - `Cannot add integrations to hosted agent policy ${parentAgentPolicy.id}` - ); - } - if ( - (parentAgentPolicy.package_policies as PackagePolicy[]).find( - (siblingPackagePolicy) => siblingPackagePolicy.name === packagePolicy.name - ) - ) { - throw new IngestManagerError( - 'There is already a package with the same name on this agent policy' - ); + const existingPoliciesWithName = await this.list(soClient, { + perPage: 1, + kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.name: "${packagePolicy.name}"`, + }); + + // Check that the name does not exist already + if (existingPoliciesWithName.items.length > 0) { + throw new IngestManagerError('There is already a package with the same name'); } let elasticsearch: PackagePolicy['elasticsearch']; // Add ids to stream @@ -320,12 +309,12 @@ class PackagePolicyService { }); return { - items: packagePolicies.saved_objects.map((packagePolicySO) => ({ + items: packagePolicies?.saved_objects.map((packagePolicySO) => ({ id: packagePolicySO.id, version: packagePolicySO.version, ...packagePolicySO.attributes, })), - total: packagePolicies.total, + total: packagePolicies?.total, page, perPage, }; @@ -369,19 +358,15 @@ class PackagePolicyService { if (!oldPackagePolicy) { throw new Error('Package policy not found'); } + // Check that the name does not exist already but exclude the current package policy + const existingPoliciesWithName = await this.list(soClient, { + perPage: 1, + kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.name: "${packagePolicy.name}"`, + }); + const filtered = (existingPoliciesWithName?.items || []).filter((p) => p.id !== id); - // Check that its agent policy does not have a package policy with the same name - const parentAgentPolicy = await agentPolicyService.get(soClient, packagePolicy.policy_id); - if (!parentAgentPolicy) { - throw new Error('Agent policy not found'); - } - if ( - (parentAgentPolicy.package_policies as PackagePolicy[]).find( - (siblingPackagePolicy) => - siblingPackagePolicy.id !== id && siblingPackagePolicy.name === packagePolicy.name - ) - ) { - throw new Error('There is already a package with the same name on this agent policy'); + if (filtered.length > 0) { + throw new IngestManagerError('There is already a package with the same name'); } let inputs = restOfPackagePolicy.inputs.map((input) => diff --git a/x-pack/plugins/fleet/server/types/index.tsx b/x-pack/plugins/fleet/server/types/index.tsx index 5bdd95ef0b874..174aac03d6a3c 100644 --- a/x-pack/plugins/fleet/server/types/index.tsx +++ b/x-pack/plugins/fleet/server/types/index.tsx @@ -5,8 +5,7 @@ * 2.0. */ -export { - // Object types +export type { Agent, AgentMetadata, AgentSOAttributes, @@ -51,13 +50,10 @@ export { AssetReference, EsAssetReference, KibanaAssetReference, - ElasticsearchAssetType, RegistryPackage, InstallablePackage, AssetType, Installable, - KibanaAssetType, - KibanaSavedObjectType, AssetParts, AssetsGroupedByServiceByType, CategoryId, @@ -74,13 +70,17 @@ export { InstallResult, GetCategoriesRequest, DataType, - dataTypes, - // Fleet Server types FleetServerEnrollmentAPIKey, FleetServerAgent, FleetServerAgentAction, FleetServerPolicy, } from '../../common'; +export { + ElasticsearchAssetType, + KibanaAssetType, + KibanaSavedObjectType, + dataTypes, +} from '../../common'; export type AgentPolicyUpdateHandler = ( action: 'created' | 'updated' | 'deleted', @@ -96,4 +96,4 @@ export interface BulkActionResult { export * from './models'; export * from './rest_spec'; export * from './extensions'; -export { FleetRequestHandler, FleetRequestHandlerContext } from './request_context'; +export type { FleetRequestHandler, FleetRequestHandlerContext } from './request_context'; diff --git a/x-pack/plugins/global_search/public/index.ts b/x-pack/plugins/global_search/public/index.ts index adb392cc61a5a..55a16407eb603 100644 --- a/x-pack/plugins/global_search/public/index.ts +++ b/x-pack/plugins/global_search/public/index.ts @@ -20,7 +20,7 @@ export const plugin: PluginInitializer< GlobalSearchPluginStartDeps > = (context) => new GlobalSearchPlugin(context); -export { +export type { GlobalSearchBatchedResults, GlobalSearchProviderFindOptions, GlobalSearchProviderResult, @@ -29,9 +29,9 @@ export { GlobalSearchFindParams, GlobalSearchProviderFindParams, } from '../common/types'; -export { +export type { GlobalSearchPluginSetup, GlobalSearchPluginStart, GlobalSearchResultProvider, } from './types'; -export { GlobalSearchFindOptions } from './services/types'; +export type { GlobalSearchFindOptions } from './services/types'; diff --git a/x-pack/plugins/global_search/public/services/index.ts b/x-pack/plugins/global_search/public/services/index.ts index 0405a6d8899c8..b178d3e76f849 100644 --- a/x-pack/plugins/global_search/public/services/index.ts +++ b/x-pack/plugins/global_search/public/services/index.ts @@ -5,5 +5,6 @@ * 2.0. */ -export { SearchService, SearchServiceSetup, SearchServiceStart } from './search_service'; -export { GlobalSearchFindOptions } from './types'; +export type { SearchServiceSetup, SearchServiceStart } from './search_service'; +export { SearchService } from './search_service'; +export type { GlobalSearchFindOptions } from './types'; diff --git a/x-pack/plugins/global_search/server/index.ts b/x-pack/plugins/global_search/server/index.ts index 1da9a10fad84a..d98e10f404306 100644 --- a/x-pack/plugins/global_search/server/index.ts +++ b/x-pack/plugins/global_search/server/index.ts @@ -22,14 +22,14 @@ export const plugin: PluginInitializer< export { config } from './config'; -export { +export type { GlobalSearchBatchedResults, GlobalSearchProviderFindOptions, GlobalSearchProviderResult, GlobalSearchProviderResultUrl, GlobalSearchResult, } from '../common/types'; -export { +export type { GlobalSearchFindOptions, GlobalSearchProviderContext, GlobalSearchPluginStart, diff --git a/x-pack/plugins/global_search/server/services/index.ts b/x-pack/plugins/global_search/server/services/index.ts index 32ae3805038db..ac5b326dd5c05 100644 --- a/x-pack/plugins/global_search/server/services/index.ts +++ b/x-pack/plugins/global_search/server/services/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { SearchService, SearchServiceSetup, SearchServiceStart } from './search_service'; +export type { SearchServiceSetup, SearchServiceStart } from './search_service'; +export { SearchService } from './search_service'; diff --git a/x-pack/plugins/global_search_bar/public/search_syntax/index.ts b/x-pack/plugins/global_search_bar/public/search_syntax/index.ts index 87d370d0c9055..7bf8ee39df148 100644 --- a/x-pack/plugins/global_search_bar/public/search_syntax/index.ts +++ b/x-pack/plugins/global_search_bar/public/search_syntax/index.ts @@ -6,4 +6,4 @@ */ export { parseSearchParams } from './parse_search_params'; -export { ParsedSearchParams, FilterValues, FilterValueType } from './types'; +export type { ParsedSearchParams, FilterValues, FilterValueType } from './types'; diff --git a/x-pack/plugins/global_search_bar/public/suggestions/index.ts b/x-pack/plugins/global_search_bar/public/suggestions/index.ts index 0c19601f21ebb..32fcdea79550f 100644 --- a/x-pack/plugins/global_search_bar/public/suggestions/index.ts +++ b/x-pack/plugins/global_search_bar/public/suggestions/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { getSuggestions, SearchSuggestion } from './get_suggestions'; +export type { SearchSuggestion } from './get_suggestions'; +export { getSuggestions } from './get_suggestions'; diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/index.ts b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/index.ts index f31fedfac6681..0439e9d5ec13d 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/index.ts +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/index.ts @@ -19,10 +19,7 @@ export { ConfigurationProvider, useConfiguration } from './configuration_context export { FormErrorsProvider, useFormErrorsContext } from './form_errors_context'; -export { - PhaseTimingsProvider, - usePhaseTimings, - PhaseTimingConfiguration, -} from './phase_timings_context'; +export type { PhaseTimingConfiguration } from './phase_timings_context'; +export { PhaseTimingsProvider, usePhaseTimings } from './phase_timings_context'; export { useGlobalFields, globalFields } from './global_fields_context'; diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/lib/index.ts b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/lib/index.ts index 607c62cd3ce8b..5bc887c5a3c73 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/lib/index.ts +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/lib/index.ts @@ -5,13 +5,15 @@ * 2.0. */ +export type { + AbsoluteTimings, + PhaseAgeInMilliseconds, + RelativePhaseTimingInMs, +} from './absolute_timing_to_relative_timing'; export { calculateRelativeFromAbsoluteMilliseconds, formDataToAbsoluteTimings, getPhaseMinAgeInMilliseconds, - AbsoluteTimings, - PhaseAgeInMilliseconds, - RelativePhaseTimingInMs, } from './absolute_timing_to_relative_timing'; export { getDefaultRepository } from './get_default_repository'; diff --git a/x-pack/plugins/index_lifecycle_management/public/index.ts b/x-pack/plugins/index_lifecycle_management/public/index.ts index cbd23a14a6114..2b8573902781b 100644 --- a/x-pack/plugins/index_lifecycle_management/public/index.ts +++ b/x-pack/plugins/index_lifecycle_management/public/index.ts @@ -14,4 +14,5 @@ export const plugin = (initializerContext: PluginInitializerContext) => { return new IndexLifecycleManagementPlugin(initializerContext); }; -export { ILM_LOCATOR_ID, IlmLocatorParams } from './locator'; +export type { IlmLocatorParams } from './locator'; +export { ILM_LOCATOR_ID } from './locator'; diff --git a/x-pack/plugins/index_lifecycle_management/public/shared_imports.ts b/x-pack/plugins/index_lifecycle_management/public/shared_imports.ts index e191c4bd799a1..dab299c476eea 100644 --- a/x-pack/plugins/index_lifecycle_management/public/shared_imports.ts +++ b/x-pack/plugins/index_lifecycle_management/public/shared_imports.ts @@ -8,10 +8,7 @@ import { AppServicesContext } from './types'; import { useKibana as _useKibana } from '../../../../src/plugins/kibana_react/public'; -export { - useForm, - useFormData, - Form, +export type { FormHook, FieldHook, FormData, @@ -19,11 +16,16 @@ export { FieldConfig, OnFormUpdateArg, ValidationFunc, - getFieldValidityAndErrorMessage, - useFormContext, FormSchema, ValidationConfig, ValidationError, +} from '../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; +export { + useForm, + useFormData, + Form, + getFieldValidityAndErrorMessage, + useFormContext, UseMultiFields, } from '../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; diff --git a/x-pack/plugins/index_lifecycle_management/server/shared_imports.ts b/x-pack/plugins/index_lifecycle_management/server/shared_imports.ts index 5c91a0a57ce5e..4598814d63c02 100644 --- a/x-pack/plugins/index_lifecycle_management/server/shared_imports.ts +++ b/x-pack/plugins/index_lifecycle_management/server/shared_imports.ts @@ -6,4 +6,4 @@ */ export { handleEsError } from '../../../../src/plugins/es_ui_shared/server'; -export { ILicense, LicenseType } from '../../licensing/common/types'; +export type { ILicense, LicenseType } from '../../licensing/common/types'; diff --git a/x-pack/plugins/index_management/__jest__/client_integration/helpers/index.ts b/x-pack/plugins/index_management/__jest__/client_integration/helpers/index.ts index 997f234cf3090..79df6e8e9f20c 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/helpers/index.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/helpers/index.ts @@ -7,7 +7,8 @@ import './mocks'; -export { nextTick, getRandomString, findTestSubject, TestBed } from '@kbn/test/jest'; +export type { TestBed } from '@kbn/test/jest'; +export { nextTick, getRandomString, findTestSubject } from '@kbn/test/jest'; export { setupEnvironment, @@ -16,4 +17,4 @@ export { kibanaVersion, } from './setup_environment'; -export { TestSubjects } from './test_subjects'; +export type { TestSubjects } from './test_subjects'; diff --git a/x-pack/plugins/index_management/common/types/index.ts b/x-pack/plugins/index_management/common/types/index.ts index 9908e9598412b..0cc514b47024f 100644 --- a/x-pack/plugins/index_management/common/types/index.ts +++ b/x-pack/plugins/index_management/common/types/index.ts @@ -13,6 +13,6 @@ export * from './mappings'; export * from './templates'; -export { DataStreamFromEs, Health, DataStream, DataStreamIndex } from './data_streams'; +export type { DataStreamFromEs, Health, DataStream, DataStreamIndex } from './data_streams'; export * from './component_templates'; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/index.ts b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/index.ts index 2545c47e47c22..fd65eb0401608 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/index.ts +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/index.ts @@ -5,8 +5,8 @@ * 2.0. */ +export type { Props as ComponentTemplateDetailsProps } from './component_template_details'; export { ComponentTemplateDetailsFlyoutContent, defaultFlyoutProps, - Props as ComponentTemplateDetailsProps, } from './component_template_details'; diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/shared_imports.ts b/x-pack/plugins/index_management/public/application/components/component_templates/shared_imports.ts index 15528f5b4e8e5..2f5b98e59bb22 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/shared_imports.ts +++ b/x-pack/plugins/index_management/public/application/components/component_templates/shared_imports.ts @@ -5,11 +5,14 @@ * 2.0. */ -export { +export type { UseRequestConfig, UseRequestResponse, SendRequestConfig, SendRequestResponse, + Error, +} from '../../../../../../../src/plugins/es_ui_shared/public'; +export { sendRequest, useRequest, WithPrivileges, @@ -18,7 +21,6 @@ export { SectionLoading, PageLoading, PageError, - Error, useAuthorizationContext, NotAuthorizedSection, Forms, @@ -32,11 +34,13 @@ export { fieldFormatters, } from '../../../../../../../src/plugins/es_ui_shared/static/forms/helpers'; -export { +export type { FormSchema, + FieldConfig, +} from '../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; +export { FIELD_TYPES, VALIDATION_TYPES, - FieldConfig, useForm, Form, getUseField, @@ -50,17 +54,17 @@ export { export { isJSON } from '../../../../../../../src/plugins/es_ui_shared/static/validators/string'; +export type { CommonWizardSteps } from '../shared'; export { TabMappings, TabSettings, TabAliases, - CommonWizardSteps, StepSettingsContainer, StepMappingsContainer, StepAliasesContainer, } from '../shared'; -export { +export type { ComponentTemplateSerialized, ComponentTemplateDeserialized, ComponentTemplateListItem, diff --git a/x-pack/plugins/index_management/public/application/components/index.ts b/x-pack/plugins/index_management/public/application/components/index.ts index eeba6e16b543c..fe3e41c34a870 100644 --- a/x-pack/plugins/index_management/public/application/components/index.ts +++ b/x-pack/plugins/index_management/public/application/components/index.ts @@ -5,7 +5,8 @@ * 2.0. */ -export { SectionError, Error } from './section_error'; +export type { Error } from './section_error'; +export { SectionError } from './section_error'; export { NoMatch } from './no_match'; export { TemplateDeleteModal } from './template_delete_modal'; export { TemplateForm } from './template_form'; diff --git a/x-pack/plugins/index_management/public/application/components/index_templates/index.ts b/x-pack/plugins/index_management/public/application/components/index_templates/index.ts index d460175543ac5..f51fe3f5d6fe3 100644 --- a/x-pack/plugins/index_management/public/application/components/index_templates/index.ts +++ b/x-pack/plugins/index_management/public/application/components/index_templates/index.ts @@ -5,12 +5,11 @@ * 2.0. */ +export type { SimulateTemplateProps, SimulateTemplateFilters } from './simulate_template'; export { SimulateTemplateFlyoutContent, simulateTemplateFlyoutProps, - SimulateTemplateProps, SimulateTemplate, - SimulateTemplateFilters, } from './simulate_template'; export { LegacyIndexTemplatesDeprecation } from './legacy_index_template_deprecation'; diff --git a/x-pack/plugins/index_management/public/application/components/index_templates/simulate_template/index.ts b/x-pack/plugins/index_management/public/application/components/index_templates/simulate_template/index.ts index 91273dc82f902..2837eb8f1f40c 100644 --- a/x-pack/plugins/index_management/public/application/components/index_templates/simulate_template/index.ts +++ b/x-pack/plugins/index_management/public/application/components/index_templates/simulate_template/index.ts @@ -5,10 +5,11 @@ * 2.0. */ +export type { Props as SimulateTemplateProps } from './simulate_template_flyout'; export { SimulateTemplateFlyoutContent, defaultFlyoutProps as simulateTemplateFlyoutProps, - Props as SimulateTemplateProps, } from './simulate_template_flyout'; -export { SimulateTemplate, Filters as SimulateTemplateFilters } from './simulate_template'; +export type { Filters as SimulateTemplateFilters } from './simulate_template'; +export { SimulateTemplate } from './simulate_template'; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/index.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/index.ts index fbe24557ae6a1..d436492756659 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/index.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/index.ts @@ -12,11 +12,12 @@ import { getMappingsEditorDataFactory, } from './mappings_editor.helpers'; -export { nextTick, getRandomString, findTestSubject, TestBed } from '@kbn/test/jest'; +export type { TestBed } from '@kbn/test/jest'; +export { nextTick, getRandomString, findTestSubject } from '@kbn/test/jest'; export { kibanaVersion } from './setup_environment'; export const componentHelpers = { mappingsEditor: { setup: mappingsEditorSetup, getMappingsEditorDataFactory }, }; -export { MappingsEditorTestBed, DomFields }; +export type { MappingsEditorTestBed, DomFields }; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/index.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/index.ts index a171959daf2cb..4b3e2657ba6ac 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/index.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/index.ts @@ -5,11 +5,8 @@ * 2.0. */ -export { - EditFieldContainer, - defaultFlyoutProps, - Props as EditFieldContainerProps, -} from './edit_field_container'; +export type { Props as EditFieldContainerProps } from './edit_field_container'; +export { EditFieldContainer, defaultFlyoutProps } from './edit_field_container'; export * from './basic_parameters_section'; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/index.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/index.ts index 9692e5d6c22b0..2d284297041e7 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/index.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/index.ts @@ -13,4 +13,4 @@ export { LoadMappingsFromJsonButton, LoadMappingsProvider } from './components/l export { MappingsEditorProvider } from './mappings_editor_context'; -export { IndexSettings, OnUpdateHandler } from './types'; +export type { IndexSettings, OnUpdateHandler } from './types'; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/shared_imports.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/shared_imports.ts index 4ea8412d4ffe3..de9c1985239f5 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/shared_imports.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/shared_imports.ts @@ -5,26 +5,28 @@ * 2.0. */ -export { - FIELD_TYPES, +export type { FieldConfig, FieldHook, - Form, - FormDataProvider, FormHook, FormSchema, - getUseField, OnFormUpdateArg, SerializerFunc, + ArrayItem, + ValidationFunc, + ValidationFuncArg, +} from '../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; +export { + FIELD_TYPES, + Form, + FormDataProvider, + getUseField, UseField, UseArray, - ArrayItem, useForm, useFormContext, UseMultiFields, VALIDATION_TYPES, - ValidationFunc, - ValidationFuncArg, } from '../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; export { @@ -47,20 +49,17 @@ export { fieldValidators, } from '../../../../../../../src/plugins/es_ui_shared/static/forms/helpers'; -export { - JsonEditor, - OnJsonEditorUpdateHandler, - GlobalFlyout, -} from '../../../../../../../src/plugins/es_ui_shared/public'; +export type { OnJsonEditorUpdateHandler } from '../../../../../../../src/plugins/es_ui_shared/public'; +export { JsonEditor, GlobalFlyout } from '../../../../../../../src/plugins/es_ui_shared/public'; export { documentationService } from '../../services/documentation'; -export { +export type { RuntimeField, - RuntimeFieldEditorFlyoutContent, RuntimeFieldEditorFlyoutContentProps, } from '../../../../../runtime_fields/public'; +export { RuntimeFieldEditorFlyoutContent } from '../../../../../runtime_fields/public'; export { createKibanaReactContext } from '../../../../../../../src/plugins/kibana_react/public'; -export { DocLinksStart } from '../../../../../../../src/core/public'; +export type { DocLinksStart } from '../../../../../../../src/core/public'; diff --git a/x-pack/plugins/index_management/public/application/components/shared/components/index.ts b/x-pack/plugins/index_management/public/application/components/shared/components/index.ts index 6011bd6aed4f9..3c564c0caf6e3 100644 --- a/x-pack/plugins/index_management/public/application/components/shared/components/index.ts +++ b/x-pack/plugins/index_management/public/application/components/shared/components/index.ts @@ -7,11 +7,7 @@ export { TabAliases, TabMappings, TabSettings } from './details_panel'; -export { - StepAliasesContainer, - StepMappingsContainer, - StepSettingsContainer, - CommonWizardSteps, -} from './wizard_steps'; +export type { CommonWizardSteps } from './wizard_steps'; +export { StepAliasesContainer, StepMappingsContainer, StepSettingsContainer } from './wizard_steps'; export { TemplateContentIndicator } from './template_content_indicator'; diff --git a/x-pack/plugins/index_management/public/application/components/shared/components/wizard_steps/index.ts b/x-pack/plugins/index_management/public/application/components/shared/components/wizard_steps/index.ts index 224c753b82304..2197e5140fc98 100644 --- a/x-pack/plugins/index_management/public/application/components/shared/components/wizard_steps/index.ts +++ b/x-pack/plugins/index_management/public/application/components/shared/components/wizard_steps/index.ts @@ -9,4 +9,4 @@ export { StepAliasesContainer } from './step_aliases_container'; export { StepMappingsContainer } from './step_mappings_container'; export { StepSettingsContainer } from './step_settings_container'; -export { CommonWizardSteps } from './types'; +export type { CommonWizardSteps } from './types'; diff --git a/x-pack/plugins/index_management/public/application/components/shared/index.ts b/x-pack/plugins/index_management/public/application/components/shared/index.ts index 96b4131f8282d..06899e202ef82 100644 --- a/x-pack/plugins/index_management/public/application/components/shared/index.ts +++ b/x-pack/plugins/index_management/public/application/components/shared/index.ts @@ -5,6 +5,7 @@ * 2.0. */ +export type { CommonWizardSteps } from './components'; export { TabAliases, TabMappings, @@ -12,6 +13,5 @@ export { StepAliasesContainer, StepMappingsContainer, StepSettingsContainer, - CommonWizardSteps, TemplateContentIndicator, } from './components'; diff --git a/x-pack/plugins/index_management/public/application/index.tsx b/x-pack/plugins/index_management/public/application/index.tsx index b7a4bd2135147..854826681adae 100644 --- a/x-pack/plugins/index_management/public/application/index.tsx +++ b/x-pack/plugins/index_management/public/application/index.tsx @@ -93,4 +93,5 @@ const useKibana = () => { return useKibanaReactPlugin(); }; -export { AppDependencies, useKibana }; +export type { AppDependencies }; +export { useKibana }; diff --git a/x-pack/plugins/index_management/public/application/sections/home/components/index.ts b/x-pack/plugins/index_management/public/application/sections/home/components/index.ts index df1218f6f0686..8cd35ead5d308 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/components/index.ts +++ b/x-pack/plugins/index_management/public/application/sections/home/components/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { FilterListButton, Filters } from './filter_list_button'; +export type { Filters } from './filter_list_button'; +export { FilterListButton } from './filter_list_button'; diff --git a/x-pack/plugins/index_management/public/index.ts b/x-pack/plugins/index_management/public/index.ts index f9ccc788a36c0..01635ed2a9b8f 100644 --- a/x-pack/plugins/index_management/public/index.ts +++ b/x-pack/plugins/index_management/public/index.ts @@ -14,7 +14,7 @@ export const plugin = (ctx: PluginInitializerContext) => { return new IndexMgmtUIPlugin(ctx); }; -export { IndexManagementPluginSetup } from './types'; +export type { IndexManagementPluginSetup } from './types'; export { getIndexListUri, getTemplateDetailsLink } from './application/services/routing'; diff --git a/x-pack/plugins/index_management/public/services/index.ts b/x-pack/plugins/index_management/public/services/index.ts index fe91e700236cc..f32787a427b89 100644 --- a/x-pack/plugins/index_management/public/services/index.ts +++ b/x-pack/plugins/index_management/public/services/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { ExtensionsService, ExtensionsSetup } from './extensions_service'; +export type { ExtensionsSetup } from './extensions_service'; +export { ExtensionsService } from './extensions_service'; diff --git a/x-pack/plugins/index_management/public/shared_imports.ts b/x-pack/plugins/index_management/public/shared_imports.ts index 4e1c420795904..7fadcd9e71502 100644 --- a/x-pack/plugins/index_management/public/shared_imports.ts +++ b/x-pack/plugins/index_management/public/shared_imports.ts @@ -7,11 +7,14 @@ export { APP_WRAPPER_CLASS } from '../../../../src/core/public'; -export { +export type { SendRequestConfig, SendRequestResponse, UseRequestConfig, UseRequestResponse, + Error, +} from '../../../../src/plugins/es_ui_shared/public'; +export { sendRequest, useRequest, Forms, @@ -20,16 +23,17 @@ export { attemptToURIDecode, PageLoading, PageError, - Error, SectionLoading, EuiCodeEditor, } from '../../../../src/plugins/es_ui_shared/public'; -export { +export type { FormSchema, + FieldConfig, +} from '../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; +export { FIELD_TYPES, VALIDATION_TYPES, - FieldConfig, useForm, useFormData, Form, diff --git a/x-pack/plugins/index_management/server/index.ts b/x-pack/plugins/index_management/server/index.ts index 29291116e44fc..8eb882d29de2d 100644 --- a/x-pack/plugins/index_management/server/index.ts +++ b/x-pack/plugins/index_management/server/index.ts @@ -14,7 +14,7 @@ export { config } from './config'; export const plugin = (context: PluginInitializerContext) => new IndexMgmtServerPlugin(context); /** @public */ -export { Dependencies } from './types'; -export { IndexManagementPluginSetup } from './plugin'; -export { Index, LegacyTemplateSerialized } from '../common'; -export { IndexManagementConfig } from './config'; +export type { Dependencies } from './types'; +export type { IndexManagementPluginSetup } from './plugin'; +export type { Index, LegacyTemplateSerialized } from '../common'; +export type { IndexManagementConfig } from './config'; diff --git a/x-pack/plugins/index_management/server/services/index.ts b/x-pack/plugins/index_management/server/services/index.ts index 576d7c46fa086..bd62f2df80cc8 100644 --- a/x-pack/plugins/index_management/server/services/index.ts +++ b/x-pack/plugins/index_management/server/services/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { IndexDataEnricher, Enricher } from './index_data_enricher'; +export type { Enricher } from './index_data_enricher'; +export { IndexDataEnricher } from './index_data_enricher'; diff --git a/x-pack/plugins/infra/common/constants.ts b/x-pack/plugins/infra/common/constants.ts index 1c3aa550f2f62..4c70e34c9899f 100644 --- a/x-pack/plugins/infra/common/constants.ts +++ b/x-pack/plugins/infra/common/constants.ts @@ -8,7 +8,6 @@ export const DEFAULT_SOURCE_ID = 'default'; export const METRICS_INDEX_PATTERN = 'metrics-*,metricbeat-*'; export const LOGS_INDEX_PATTERN = 'logs-*,filebeat-*,kibana_sample_data_logs*'; -export const TIMESTAMP_FIELD = '@timestamp'; export const METRICS_APP = 'metrics'; export const LOGS_APP = 'logs'; @@ -16,3 +15,9 @@ export const METRICS_FEATURE_ID = 'infrastructure'; export const LOGS_FEATURE_ID = 'logs'; export type InfraFeatureId = typeof METRICS_FEATURE_ID | typeof LOGS_FEATURE_ID; + +export const TIMESTAMP_FIELD = '@timestamp'; +export const TIEBREAKER_FIELD = '_doc'; +export const HOST_FIELD = 'host.name'; +export const CONTAINER_FIELD = 'container.id'; +export const POD_FIELD = 'kubernetes.pod.uid'; diff --git a/x-pack/plugins/infra/common/http_api/host_details/process_list.ts b/x-pack/plugins/infra/common/http_api/host_details/process_list.ts index 79835a0a78f26..395b1527379a9 100644 --- a/x-pack/plugins/infra/common/http_api/host_details/process_list.ts +++ b/x-pack/plugins/infra/common/http_api/host_details/process_list.ts @@ -14,7 +14,6 @@ const AggValueRT = rt.type({ export const ProcessListAPIRequestRT = rt.type({ hostTerm: rt.record(rt.string, rt.string), - timefield: rt.string, indexPattern: rt.string, to: rt.number, sortBy: rt.type({ @@ -102,7 +101,6 @@ export type ProcessListAPIResponse = rt.TypeOf; export const ProcessListAPIChartRequestRT = rt.type({ hostTerm: rt.record(rt.string, rt.string), - timefield: rt.string, indexPattern: rt.string, to: rt.number, command: rt.string, diff --git a/x-pack/plugins/infra/common/http_api/metrics_api.ts b/x-pack/plugins/infra/common/http_api/metrics_api.ts index c2449707647d7..315a42380397b 100644 --- a/x-pack/plugins/infra/common/http_api/metrics_api.ts +++ b/x-pack/plugins/infra/common/http_api/metrics_api.ts @@ -10,7 +10,6 @@ import { MetricsUIAggregationRT } from '../inventory_models/types'; import { afterKeyObjectRT } from './metrics_explorer'; export const MetricsAPITimerangeRT = rt.type({ - field: rt.string, from: rt.number, to: rt.number, interval: rt.string, diff --git a/x-pack/plugins/infra/common/http_api/metrics_explorer.ts b/x-pack/plugins/infra/common/http_api/metrics_explorer.ts index 5617bd0954f5d..de00d521126e3 100644 --- a/x-pack/plugins/infra/common/http_api/metrics_explorer.ts +++ b/x-pack/plugins/infra/common/http_api/metrics_explorer.ts @@ -41,7 +41,6 @@ export const metricsExplorerMetricRT = rt.intersection([ ]); export const timeRangeRT = rt.type({ - field: rt.string, from: rt.number, to: rt.number, interval: rt.string, diff --git a/x-pack/plugins/infra/common/inventory_models/index.ts b/x-pack/plugins/infra/common/inventory_models/index.ts index 6350e76ca7f29..81f89be8cd6a6 100644 --- a/x-pack/plugins/infra/common/inventory_models/index.ts +++ b/x-pack/plugins/infra/common/inventory_models/index.ts @@ -6,6 +6,7 @@ */ import { i18n } from '@kbn/i18n'; +import { POD_FIELD, HOST_FIELD, CONTAINER_FIELD } from '../constants'; import { host } from './host'; import { pod } from './pod'; import { awsEC2 } from './aws_ec2'; @@ -30,31 +31,23 @@ export const findInventoryModel = (type: InventoryItemType) => { return model; }; -interface InventoryFields { - host: string; - pod: string; - container: string; - timestamp: string; - tiebreaker: string; -} - const LEGACY_TYPES = ['host', 'pod', 'container']; -const getFieldByType = (type: InventoryItemType, fields: InventoryFields) => { +export const getFieldByType = (type: InventoryItemType) => { switch (type) { case 'pod': - return fields.pod; + return POD_FIELD; case 'host': - return fields.host; + return HOST_FIELD; case 'container': - return fields.container; + return CONTAINER_FIELD; } }; -export const findInventoryFields = (type: InventoryItemType, fields?: InventoryFields) => { +export const findInventoryFields = (type: InventoryItemType) => { const inventoryModel = findInventoryModel(type); - if (fields && LEGACY_TYPES.includes(type)) { - const id = getFieldByType(type, fields) || inventoryModel.fields.id; + if (LEGACY_TYPES.includes(type)) { + const id = getFieldByType(type) || inventoryModel.fields.id; return { ...inventoryModel.fields, id, diff --git a/x-pack/plugins/infra/common/log_search_result/index.ts b/x-pack/plugins/infra/common/log_search_result/index.ts index d1b2672fbfbaf..592b23dfc70ad 100644 --- a/x-pack/plugins/infra/common/log_search_result/index.ts +++ b/x-pack/plugins/infra/common/log_search_result/index.ts @@ -5,9 +5,9 @@ * 2.0. */ +export type { SearchResult } from './log_search_result'; export { getSearchResultIndexBeforeTime, getSearchResultIndexAfterTime, getSearchResultKey, - SearchResult, } from './log_search_result'; diff --git a/x-pack/plugins/infra/common/log_search_summary/index.ts b/x-pack/plugins/infra/common/log_search_summary/index.ts index feb64dee7d31a..32652753f7799 100644 --- a/x-pack/plugins/infra/common/log_search_summary/index.ts +++ b/x-pack/plugins/infra/common/log_search_summary/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export { SearchSummaryBucket } from './log_search_summary'; +export type { SearchSummaryBucket } from './log_search_summary'; diff --git a/x-pack/plugins/infra/common/log_sources/log_source_configuration.ts b/x-pack/plugins/infra/common/log_sources/log_source_configuration.ts index ab98ad75b8433..5d46ce59457da 100644 --- a/x-pack/plugins/infra/common/log_sources/log_source_configuration.ts +++ b/x-pack/plugins/infra/common/log_sources/log_source_configuration.ts @@ -16,11 +16,6 @@ export const logSourceConfigurationOriginRT = rt.keyof({ export type LogSourceConfigurationOrigin = rt.TypeOf; const logSourceFieldsConfigurationRT = rt.strict({ - container: rt.string, - host: rt.string, - pod: rt.string, - timestamp: rt.string, - tiebreaker: rt.string, message: rt.array(rt.string), }); diff --git a/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts b/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts index c6bc10901fcb8..d3459b30a060e 100644 --- a/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts +++ b/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts @@ -8,6 +8,7 @@ import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { DataView, DataViewsContract } from '../../../../../src/plugins/data_views/common'; import { ObjectEntries } from '../utility_types'; +import { TIMESTAMP_FIELD, TIEBREAKER_FIELD } from '../constants'; import { ResolveLogSourceConfigurationError } from './errors'; import { LogSourceColumnConfiguration, @@ -61,8 +62,8 @@ const resolveLegacyReference = async ( return { indices: sourceConfiguration.logIndices.indexName, - timestampField: sourceConfiguration.fields.timestamp, - tiebreakerField: sourceConfiguration.fields.tiebreaker, + timestampField: TIMESTAMP_FIELD, + tiebreakerField: TIEBREAKER_FIELD, messageField: sourceConfiguration.fields.message, fields, runtimeMappings: {}, @@ -91,8 +92,8 @@ const resolveKibanaIndexPatternReference = async ( return { indices: indexPattern.title, - timestampField: indexPattern.timeFieldName ?? '@timestamp', - tiebreakerField: '_doc', + timestampField: indexPattern.timeFieldName ?? TIMESTAMP_FIELD, + tiebreakerField: TIEBREAKER_FIELD, messageField: ['message'], fields: indexPattern.fields, runtimeMappings: resolveRuntimeMappings(indexPattern), diff --git a/x-pack/plugins/infra/common/metrics_sources/index.ts b/x-pack/plugins/infra/common/metrics_sources/index.ts index a697c65e5a0aa..7fae908707a89 100644 --- a/x-pack/plugins/infra/common/metrics_sources/index.ts +++ b/x-pack/plugins/infra/common/metrics_sources/index.ts @@ -6,7 +6,6 @@ */ import * as rt from 'io-ts'; -import { omit } from 'lodash'; import { SourceConfigurationRT, SourceStatusRuntimeType, @@ -22,7 +21,6 @@ export const metricsSourceConfigurationPropertiesRT = rt.strict({ metricAlias: SourceConfigurationRT.props.metricAlias, inventoryDefaultView: SourceConfigurationRT.props.inventoryDefaultView, metricsExplorerDefaultView: SourceConfigurationRT.props.metricsExplorerDefaultView, - fields: rt.strict(omit(SourceConfigurationRT.props.fields.props, 'message')), anomalyThreshold: rt.number, }); @@ -32,9 +30,6 @@ export type MetricsSourceConfigurationProperties = rt.TypeOf< export const partialMetricsSourceConfigurationPropertiesRT = rt.partial({ ...metricsSourceConfigurationPropertiesRT.type.props, - fields: rt.partial({ - ...metricsSourceConfigurationPropertiesRT.type.props.fields.type.props, - }), }); export type PartialMetricsSourceConfigurationProperties = rt.TypeOf< diff --git a/x-pack/plugins/infra/common/source_configuration/source_configuration.ts b/x-pack/plugins/infra/common/source_configuration/source_configuration.ts index 257cccc86595c..0c30c3d678b2a 100644 --- a/x-pack/plugins/infra/common/source_configuration/source_configuration.ts +++ b/x-pack/plugins/infra/common/source_configuration/source_configuration.ts @@ -50,12 +50,7 @@ export const sourceConfigurationConfigFilePropertiesRT = rt.type({ sources: rt.type({ default: rt.partial({ fields: rt.partial({ - timestamp: rt.string, message: rt.array(rt.string), - tiebreaker: rt.string, - host: rt.string, - container: rt.string, - pod: rt.string, }), }), }), @@ -113,11 +108,6 @@ export type InfraSourceConfigurationColumn = rt.TypeOf; diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx index 6a5019d4683c8..4d57674c94dad 100644 --- a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx @@ -19,6 +19,7 @@ import { EuiFieldSearch, EuiAccordion, EuiPanel, + EuiLink, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; @@ -58,7 +59,7 @@ export { defaultExpression }; export const Expressions: React.FC = (props) => { const { setAlertParams, alertParams, errors, metadata } = props; - const { http, notifications } = useKibanaContextForPlugin().services; + const { http, notifications, docLinks } = useKibanaContextForPlugin().services; const { source, createDerivedIndexPattern } = useSourceViaHttp({ sourceId: 'default', fetch: http.fetch, @@ -260,6 +261,9 @@ export const Expressions: React.FC = (props) => { [alertParams.groupBy] ); + // Test to see if any of the group fields in groupBy are already filtered down to a single + // group by the filterQuery. If this is the case, then a groupBy is unnecessary, as it would only + // ever produce one group instance const groupByFilterTestPatterns = useMemo(() => { if (!alertParams.groupBy) return null; const groups = !Array.isArray(alertParams.groupBy) @@ -456,10 +460,20 @@ export const Expressions: React.FC = (props) => { {redundantFilterGroupBy.join(', ')}, groupCount: redundantFilterGroupBy.length, + filteringAndGroupingLink: ( + + {i18n.translate( + 'xpack.infra.metrics.alertFlyout.alertPerRedundantFilterError.docsLink', + { defaultMessage: 'the docs' } + )} + + ), }} /> diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.test.tsx b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.test.tsx index ec97d01a1cd6f..c2c1fa719bb95 100644 --- a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.test.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.test.tsx @@ -54,14 +54,6 @@ describe('ExpressionChart', () => { metricAlias: 'metricbeat-*', inventoryDefaultView: 'host', metricsExplorerDefaultView: 'host', - // @ts-ignore - fields: { - timestamp: '@timestamp', - container: 'container.id', - host: 'host.name', - pod: 'kubernetes.pod.uid', - tiebreaker: '_doc', - }, anomalyThreshold: 20, }, }; diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/validation.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/validation.tsx index b78a63e61e524..67b3fa164d90c 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/validation.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/validation.tsx @@ -9,7 +9,8 @@ import * as rt from 'io-ts'; import { ValidationIndicesError, validationIndicesErrorRT } from '../../../../../common/http_api'; import { DatasetFilter } from '../../../../../common/log_analysis'; -export { ValidationIndicesError, validationIndicesErrorRT }; +export type { ValidationIndicesError }; +export { validationIndicesErrorRT }; export const timeRangeValidationErrorRT = rt.strict({ error: rt.literal('INVALID_TIME_RANGE'), diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/index.ts b/x-pack/plugins/infra/public/components/logging/log_text_stream/index.ts index c3716d8c97ae1..dbd5bd49d0240 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/index.ts +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/index.ts @@ -5,12 +5,8 @@ * 2.0. */ -export { - LogEntryColumn, - LogEntryColumnWidths, - useColumnWidths, - iconColumnId, -} from './log_entry_column'; +export type { LogEntryColumnWidths } from './log_entry_column'; +export { LogEntryColumn, useColumnWidths, iconColumnId } from './log_entry_column'; export { LogEntryFieldColumn } from './log_entry_field_column'; export { LogEntryMessageColumn } from './log_entry_message_column'; export { LogEntryRowWrapper } from './log_entry_row'; diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/get_latest_categories_datasets_stats.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/get_latest_categories_datasets_stats.ts index bfabcdb4af7c1..d715fb9f45194 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/get_latest_categories_datasets_stats.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/get_latest_categories_datasets_stats.ts @@ -15,7 +15,7 @@ import { } from '../../../../../common/http_api'; import { decodeOrThrow } from '../../../../../common/runtime_types'; -export { LogEntryCategoriesDatasetStats }; +export type { LogEntryCategoriesDatasetStats }; export const callGetLatestCategoriesDatasetsStatsAPI = async ( { diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/index.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/index.ts index 40ac39e3fa22a..5cccbdb78e46e 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/index.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/index.ts @@ -14,4 +14,4 @@ export * from './log_analysis_module_status'; export * from './log_analysis_module_types'; export * from './log_analysis_setup_state'; -export { JobModelSizeStats, JobSummary } from './api/ml_get_jobs_summary_api'; +export type { JobModelSizeStats, JobSummary } from './api/ml_get_jobs_summary_api'; diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts index 4ff8c0c3c08e0..c8ce9a7b0127b 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts @@ -17,7 +17,7 @@ import { FetchJobStatusResponsePayload } from './api/ml_get_jobs_summary_api'; import { GetMlModuleResponsePayload } from './api/ml_get_module'; import { SetupMlModuleResponsePayload } from './api/ml_setup_module_api'; -export { JobModelSizeStats, JobSummary } from './api/ml_get_jobs_summary_api'; +export type { JobModelSizeStats, JobSummary } from './api/ml_get_jobs_summary_api'; export interface ModuleDescriptor { moduleId: string; diff --git a/x-pack/plugins/infra/public/containers/logs/log_source/log_source.mock.ts b/x-pack/plugins/infra/public/containers/logs/log_source/log_source.mock.ts index 6021c728d32af..204fae7dc0f2b 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_source/log_source.mock.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_source/log_source.mock.ts @@ -73,11 +73,6 @@ export const createBasicSourceConfiguration = (sourceId: string): LogSourceConfi }, logColumns: [], fields: { - container: 'CONTAINER_FIELD', - host: 'HOST_FIELD', - pod: 'POD_FIELD', - tiebreaker: 'TIEBREAKER_FIELD', - timestamp: 'TIMESTAMP_FIELD', message: ['MESSAGE_FIELD'], }, name: sourceId, diff --git a/x-pack/plugins/infra/public/containers/logs/log_source/log_source.ts b/x-pack/plugins/infra/public/containers/logs/log_source/log_source.ts index 8f744a1d6df6d..54f3f70b98a4b 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_source/log_source.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_source/log_source.ts @@ -26,14 +26,14 @@ import { callFetchLogSourceConfigurationAPI } from './api/fetch_log_source_confi import { callFetchLogSourceStatusAPI } from './api/fetch_log_source_status'; import { callPatchLogSourceConfigurationAPI } from './api/patch_log_source_configuration'; -export { +export type { LogIndexField, LogSourceConfiguration, LogSourceConfigurationProperties, LogSourceConfigurationPropertiesPatch, LogSourceStatus, - ResolveLogSourceConfigurationError, }; +export { ResolveLogSourceConfigurationError }; export const useLogSource = ({ sourceId, diff --git a/x-pack/plugins/infra/public/containers/ml/infra_ml_module.tsx b/x-pack/plugins/infra/public/containers/ml/infra_ml_module.tsx index 198a99f394850..22376648ca003 100644 --- a/x-pack/plugins/infra/public/containers/ml/infra_ml_module.tsx +++ b/x-pack/plugins/infra/public/containers/ml/infra_ml_module.tsx @@ -19,7 +19,7 @@ export const useInfraMLModule = ({ moduleDescriptor: ModuleDescriptor; }) => { const { services } = useKibanaContextForPlugin(); - const { spaceId, sourceId, timestampField } = sourceConfiguration; + const { spaceId, sourceId } = sourceConfiguration; const [moduleStatus, dispatchModuleStatus] = useModuleStatus(moduleDescriptor.jobTypes); const [, fetchJobStatus] = useTrackedPromise( @@ -64,7 +64,6 @@ export const useInfraMLModule = ({ indices: selectedIndices, sourceId, spaceId, - timestampField, }, partitionField, }, @@ -91,7 +90,7 @@ export const useInfraMLModule = ({ dispatchModuleStatus({ type: 'failedSetup' }); }, }, - [moduleDescriptor.setUpModule, spaceId, sourceId, timestampField] + [moduleDescriptor.setUpModule, spaceId, sourceId] ); const [cleanUpModuleRequest, cleanUpModule] = useTrackedPromise( diff --git a/x-pack/plugins/infra/public/containers/ml/infra_ml_module_configuration.ts b/x-pack/plugins/infra/public/containers/ml/infra_ml_module_configuration.ts index 4c876c1705364..c258debdddbca 100644 --- a/x-pack/plugins/infra/public/containers/ml/infra_ml_module_configuration.ts +++ b/x-pack/plugins/infra/public/containers/ml/infra_ml_module_configuration.ts @@ -45,8 +45,7 @@ export const isJobConfigurationOutdated = isSubset( new Set(jobConfiguration.indexPattern.split(',')), new Set(currentSourceConfiguration.indices) - ) && - jobConfiguration.timestampField === currentSourceConfiguration.timestampField + ) ); }; diff --git a/x-pack/plugins/infra/public/containers/ml/infra_ml_module_types.ts b/x-pack/plugins/infra/public/containers/ml/infra_ml_module_types.ts index 5a5272f783053..9b172a7c82a98 100644 --- a/x-pack/plugins/infra/public/containers/ml/infra_ml_module_types.ts +++ b/x-pack/plugins/infra/public/containers/ml/infra_ml_module_types.ts @@ -15,7 +15,7 @@ import { FetchJobStatusResponsePayload } from './api/ml_get_jobs_summary_api'; import { GetMlModuleResponsePayload } from './api/ml_get_module'; import { SetupMlModuleResponsePayload } from './api/ml_setup_module_api'; -export { JobModelSizeStats, JobSummary } from './api/ml_get_jobs_summary_api'; +export type { JobModelSizeStats, JobSummary } from './api/ml_get_jobs_summary_api'; export interface SetUpModuleArgs { start?: number | undefined; @@ -49,12 +49,10 @@ export interface ModuleDescriptor { ) => Promise; validateSetupIndices?: ( indices: string[], - timestampField: string, fetch: HttpHandler ) => Promise; validateSetupDatasets?: ( indices: string[], - timestampField: string, startTime: number, endTime: number, fetch: HttpHandler @@ -65,7 +63,6 @@ export interface ModuleSourceConfiguration { indices: string[]; sourceId: string; spaceId: string; - timestampField: string; } interface ManyCategoriesWarningReason { diff --git a/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module.tsx b/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module.tsx index f892ab62ee3d8..f200ab22c043f 100644 --- a/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module.tsx +++ b/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module.tsx @@ -17,21 +17,18 @@ export const useMetricHostsModule = ({ indexPattern, sourceId, spaceId, - timestampField, }: { indexPattern: string; sourceId: string; spaceId: string; - timestampField: string; }) => { const sourceConfiguration: ModuleSourceConfiguration = useMemo( () => ({ indices: indexPattern.split(','), sourceId, spaceId, - timestampField, }), - [indexPattern, sourceId, spaceId, timestampField] + [indexPattern, sourceId, spaceId] ); const infraMLModule = useInfraMLModule({ diff --git a/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module_descriptor.ts b/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module_descriptor.ts index a7ab948d052aa..f87cd78f4ff34 100644 --- a/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module_descriptor.ts +++ b/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module_descriptor.ts @@ -18,6 +18,7 @@ import { MetricsHostsJobType, bucketSpan, } from '../../../../../common/infra_ml'; +import { TIMESTAMP_FIELD } from '../../../../../common/constants'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import MemoryJob from '../../../../../../ml/server/models/data_recognizer/modules/metrics_ui_hosts/ml/hosts_memory_usage.json'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths @@ -68,7 +69,7 @@ const setUpModule = async (setUpModuleArgs: SetUpModuleArgs, fetch: HttpHandler) start, end, filter, - moduleSourceConfiguration: { spaceId, sourceId, indices, timestampField }, + moduleSourceConfiguration: { spaceId, sourceId, indices }, partitionField, } = setUpModuleArgs; @@ -93,13 +94,13 @@ const setUpModule = async (setUpModuleArgs: SetUpModuleArgs, fetch: HttpHandler) return { job_id: id, data_description: { - time_field: timestampField, + time_field: TIMESTAMP_FIELD, }, analysis_config, custom_settings: { metrics_source_config: { indexPattern: indexNamePattern, - timestampField, + timestampField: TIMESTAMP_FIELD, bucketSpan, }, }, diff --git a/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module.tsx b/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module.tsx index eadc374434817..08f4f49058dbe 100644 --- a/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module.tsx +++ b/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module.tsx @@ -17,21 +17,18 @@ export const useMetricK8sModule = ({ indexPattern, sourceId, spaceId, - timestampField, }: { indexPattern: string; sourceId: string; spaceId: string; - timestampField: string; }) => { const sourceConfiguration: ModuleSourceConfiguration = useMemo( () => ({ indices: indexPattern.split(','), sourceId, spaceId, - timestampField, }), - [indexPattern, sourceId, spaceId, timestampField] + [indexPattern, sourceId, spaceId] ); const infraMLModule = useInfraMLModule({ diff --git a/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module_descriptor.ts b/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module_descriptor.ts index 4c5eb5fd4bf23..388a7dd0a5656 100644 --- a/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module_descriptor.ts +++ b/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module_descriptor.ts @@ -18,6 +18,7 @@ import { MetricK8sJobType, bucketSpan, } from '../../../../../common/infra_ml'; +import { TIMESTAMP_FIELD } from '../../../../../common/constants'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import MemoryJob from '../../../../../../ml/server/models/data_recognizer/modules/metrics_ui_k8s/ml/k8s_memory_usage.json'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths @@ -69,7 +70,7 @@ const setUpModule = async (setUpModuleArgs: SetUpModuleArgs, fetch: HttpHandler) start, end, filter, - moduleSourceConfiguration: { spaceId, sourceId, indices, timestampField }, + moduleSourceConfiguration: { spaceId, sourceId, indices }, partitionField, } = setUpModuleArgs; @@ -93,13 +94,13 @@ const setUpModule = async (setUpModuleArgs: SetUpModuleArgs, fetch: HttpHandler) return { job_id: id, data_description: { - time_field: timestampField, + time_field: TIMESTAMP_FIELD, }, analysis_config, custom_settings: { metrics_source_config: { indexPattern: indexNamePattern, - timestampField, + timestampField: TIMESTAMP_FIELD, bucketSpan, }, }, diff --git a/x-pack/plugins/infra/public/lib/lib.ts b/x-pack/plugins/infra/public/lib/lib.ts index 97a3f8eabbe4e..a37a9af7d9320 100644 --- a/x-pack/plugins/infra/public/lib/lib.ts +++ b/x-pack/plugins/infra/public/lib/lib.ts @@ -14,7 +14,6 @@ import { SnapshotNodeMetric, SnapshotNodePath, } from '../../common/http_api/snapshot_api'; -import { MetricsSourceConfigurationProperties } from '../../common/metrics_sources'; import { WaffleSortOption } from '../pages/metrics/inventory_view/hooks/use_waffle_options'; export interface InfraWaffleMapNode { @@ -124,7 +123,6 @@ export enum InfraWaffleMapRuleOperator { } export interface InfraWaffleMapOptions { - fields?: Omit | null; formatter: InfraFormatterType; formatTemplate: string; metric: SnapshotMetricInput; diff --git a/x-pack/plugins/infra/public/pages/link_to/link_to_logs.test.tsx b/x-pack/plugins/infra/public/pages/link_to/link_to_logs.test.tsx index f9c80edd2c199..cfcf8db771b78 100644 --- a/x-pack/plugins/infra/public/pages/link_to/link_to_logs.test.tsx +++ b/x-pack/plugins/infra/public/pages/link_to/link_to_logs.test.tsx @@ -151,7 +151,7 @@ describe('LinkToLogsPage component', () => { const searchParams = new URLSearchParams(history.location.search); expect(searchParams.get('sourceId')).toEqual('default'); expect(searchParams.get('logFilter')).toMatchInlineSnapshot( - `"(language:kuery,query:'HOST_FIELD: HOST_NAME')"` + `"(language:kuery,query:'host.name: HOST_NAME')"` ); expect(searchParams.get('logPosition')).toEqual(null); }); @@ -172,7 +172,7 @@ describe('LinkToLogsPage component', () => { const searchParams = new URLSearchParams(history.location.search); expect(searchParams.get('sourceId')).toEqual('default'); expect(searchParams.get('logFilter')).toMatchInlineSnapshot( - `"(language:kuery,query:'(HOST_FIELD: HOST_NAME) and (FILTER_FIELD:FILTER_VALUE)')"` + `"(language:kuery,query:'(host.name: HOST_NAME) and (FILTER_FIELD:FILTER_VALUE)')"` ); expect(searchParams.get('logPosition')).toMatchInlineSnapshot( `"(end:'2019-02-20T14:58:09.404Z',position:(tiebreaker:0,time:1550671089404),start:'2019-02-20T12:58:09.404Z',streamLive:!f)"` @@ -193,7 +193,7 @@ describe('LinkToLogsPage component', () => { const searchParams = new URLSearchParams(history.location.search); expect(searchParams.get('sourceId')).toEqual('OTHER_SOURCE'); expect(searchParams.get('logFilter')).toMatchInlineSnapshot( - `"(language:kuery,query:'HOST_FIELD: HOST_NAME')"` + `"(language:kuery,query:'host.name: HOST_NAME')"` ); expect(searchParams.get('logPosition')).toEqual(null); }); @@ -229,7 +229,7 @@ describe('LinkToLogsPage component', () => { const searchParams = new URLSearchParams(history.location.search); expect(searchParams.get('sourceId')).toEqual('default'); expect(searchParams.get('logFilter')).toMatchInlineSnapshot( - `"(language:kuery,query:'CONTAINER_FIELD: CONTAINER_ID')"` + `"(language:kuery,query:'container.id: CONTAINER_ID')"` ); expect(searchParams.get('logPosition')).toEqual(null); }); @@ -250,7 +250,7 @@ describe('LinkToLogsPage component', () => { const searchParams = new URLSearchParams(history.location.search); expect(searchParams.get('sourceId')).toEqual('default'); expect(searchParams.get('logFilter')).toMatchInlineSnapshot( - `"(language:kuery,query:'(CONTAINER_FIELD: CONTAINER_ID) and (FILTER_FIELD:FILTER_VALUE)')"` + `"(language:kuery,query:'(container.id: CONTAINER_ID) and (FILTER_FIELD:FILTER_VALUE)')"` ); expect(searchParams.get('logPosition')).toMatchInlineSnapshot( `"(end:'2019-02-20T14:58:09.404Z',position:(tiebreaker:0,time:1550671089404),start:'2019-02-20T12:58:09.404Z',streamLive:!f)"` @@ -287,7 +287,7 @@ describe('LinkToLogsPage component', () => { const searchParams = new URLSearchParams(history.location.search); expect(searchParams.get('sourceId')).toEqual('default'); expect(searchParams.get('logFilter')).toMatchInlineSnapshot( - `"(language:kuery,query:'POD_FIELD: POD_UID')"` + `"(language:kuery,query:'kubernetes.pod.uid: POD_UID')"` ); expect(searchParams.get('logPosition')).toEqual(null); }); @@ -306,7 +306,7 @@ describe('LinkToLogsPage component', () => { const searchParams = new URLSearchParams(history.location.search); expect(searchParams.get('sourceId')).toEqual('default'); expect(searchParams.get('logFilter')).toMatchInlineSnapshot( - `"(language:kuery,query:'(POD_FIELD: POD_UID) and (FILTER_FIELD:FILTER_VALUE)')"` + `"(language:kuery,query:'(kubernetes.pod.uid: POD_UID) and (FILTER_FIELD:FILTER_VALUE)')"` ); expect(searchParams.get('logPosition')).toMatchInlineSnapshot( `"(end:'2019-02-20T14:58:09.404Z',position:(tiebreaker:0,time:1550671089404),start:'2019-02-20T12:58:09.404Z',streamLive:!f)"` diff --git a/x-pack/plugins/infra/public/pages/link_to/redirect_to_node_logs.tsx b/x-pack/plugins/infra/public/pages/link_to/redirect_to_node_logs.tsx index bc8c5699229d8..a8d339cfe979a 100644 --- a/x-pack/plugins/infra/public/pages/link_to/redirect_to_node_logs.tsx +++ b/x-pack/plugins/infra/public/pages/link_to/redirect_to_node_logs.tsx @@ -34,12 +34,11 @@ export const RedirectToNodeLogs = ({ location, }: RedirectToNodeLogsType) => { const { services } = useKibanaContextForPlugin(); - const { isLoading, loadSource, sourceConfiguration } = useLogSource({ + const { isLoading, loadSource } = useLogSource({ fetch: services.http.fetch, sourceId, indexPatternsService: services.data.indexPatterns, }); - const fields = sourceConfiguration?.configuration.fields; useMount(() => { loadSource(); @@ -57,11 +56,9 @@ export const RedirectToNodeLogs = ({ })} /> ); - } else if (fields == null) { - return null; } - const nodeFilter = `${findInventoryFields(nodeType, fields).id}: ${nodeId}`; + const nodeFilter = `${findInventoryFields(nodeType).id}: ${nodeId}`; const userFilter = getFilterFromLocation(location); const filter = userFilter ? `(${nodeFilter}) and (${userFilter})` : nodeFilter; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx index de0a56c5be73d..f46a379f52d50 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx @@ -18,7 +18,6 @@ import { PageContent } from '../../../../components/page'; import { useWaffleTimeContext } from '../hooks/use_waffle_time'; import { useWaffleFiltersContext } from '../hooks/use_waffle_filters'; import { DEFAULT_LEGEND, useWaffleOptionsContext } from '../hooks/use_waffle_options'; -import { useSourceContext } from '../../../../containers/metrics_source'; import { InfraFormatterType } from '../../../../lib/lib'; import { euiStyled } from '../../../../../../../../src/plugins/kibana_react/common'; import { Toolbar } from './toolbars/toolbar'; @@ -41,7 +40,6 @@ interface Props { export const Layout = React.memo( ({ shouldLoadDefault, currentView, reload, interval, nodes, loading }: Props) => { const [showLoading, setShowLoading] = useState(true); - const { source } = useSourceContext(); const { metric, groupBy, @@ -65,7 +63,6 @@ export const Layout = React.memo( legend: createLegend(legendPalette, legendSteps, legendReverseColors), metric, sort, - fields: source?.configuration?.fields, groupBy, }; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomaly_detection_flyout.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomaly_detection_flyout.tsx index 4e28fb4202bdc..1fcec291fcc29 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomaly_detection_flyout.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomaly_detection_flyout.tsx @@ -67,13 +67,11 @@ export const AnomalyDetectionFlyout = () => { indexPattern={source?.configuration.metricAlias ?? ''} sourceId={'default'} spaceId={space.id} - timestampField={source?.configuration.fields.timestamp ?? ''} > {screenName === 'home' && ( diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/logs.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/logs.tsx index b792078c394e9..8b5224068589c 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/logs.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/logs.tsx @@ -25,15 +25,13 @@ const TabComponent = (props: TabProps) => { const endTimestamp = props.currentTime; const startTimestamp = endTimestamp - 60 * 60 * 1000; // 60 minutes const { nodeType } = useWaffleOptionsContext(); - const { options, node } = props; + const { node } = props; const throttledTextQuery = useThrottle(textQuery, textQueryThrottleInterval); const filter = useMemo(() => { const query = [ - ...(options.fields != null - ? [`${findInventoryFields(nodeType, options.fields).id}: "${node.id}"`] - : []), + `${findInventoryFields(nodeType).id}: "${node.id}"`, ...(throttledTextQuery !== '' ? [throttledTextQuery] : []), ].join(' and '); @@ -41,7 +39,7 @@ const TabComponent = (props: TabProps) => { language: 'kuery', query, }; - }, [options.fields, nodeType, node.id, throttledTextQuery]); + }, [nodeType, node.id, throttledTextQuery]); const onQueryChange = useCallback((e: React.ChangeEvent) => { setTextQuery(e.target.value); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/metrics/metrics.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/metrics/metrics.tsx index fbb8bd469c1e1..7ff4720aec01e 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/metrics/metrics.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/metrics/metrics.tsx @@ -71,14 +71,12 @@ const TabComponent = (props: TabProps) => { ]); const { sourceId, createDerivedIndexPattern } = useSourceContext(); const { nodeType, accountId, region, customMetrics } = useWaffleOptionsContext(); - const { currentTime, options, node } = props; + const { currentTime, node } = props; const derivedIndexPattern = useMemo( () => createDerivedIndexPattern('metrics'), [createDerivedIndexPattern] ); - let filter = options.fields - ? `${findInventoryFields(nodeType, options.fields).id}: "${node.id}"` - : ''; + let filter = `${findInventoryFields(nodeType).id}: "${node.id}"`; if (filter) { filter = convertKueryToElasticSearchQuery(filter, derivedIndexPattern); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx index c227a31edc4ab..2bed7681b8d56 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx @@ -17,6 +17,7 @@ import { EuiIconTip, Query, } from '@elastic/eui'; +import { getFieldByType } from '../../../../../../../../common/inventory_models'; import { useProcessList, SortBy, @@ -28,7 +29,7 @@ import { SummaryTable } from './summary_table'; import { ProcessesTable } from './processes_table'; import { parseSearchString } from './parse_search_string'; -const TabComponent = ({ currentTime, node, nodeType, options }: TabProps) => { +const TabComponent = ({ currentTime, node, nodeType }: TabProps) => { const [searchBarState, setSearchBarState] = useState(Query.MATCH_ALL); const [searchFilter, setSearchFilter] = useState(''); const [sortBy, setSortBy] = useState({ @@ -36,22 +37,17 @@ const TabComponent = ({ currentTime, node, nodeType, options }: TabProps) => { isAscending: false, }); - const timefield = options.fields!.timestamp; - const hostTerm = useMemo(() => { - const field = - options.fields && Reflect.has(options.fields, nodeType) - ? Reflect.get(options.fields, nodeType) - : nodeType; + const field = getFieldByType(nodeType) ?? nodeType; return { [field]: node.name }; - }, [options, node, nodeType]); + }, [node, nodeType]); const { loading, error, response, makeRequest: reload, - } = useProcessList(hostTerm, timefield, currentTime, sortBy, parseSearchString(searchFilter)); + } = useProcessList(hostTerm, currentTime, sortBy, parseSearchString(searchFilter)); const debouncedSearchOnChange = useMemo( () => debounce<(queryText: string) => void>((queryText) => setSearchFilter(queryText), 500), @@ -73,7 +69,7 @@ const TabComponent = ({ currentTime, node, nodeType, options }: TabProps) => { return ( - + { {isAlertFlyoutVisible && ( = withTheme return { label: host.ip, value: node.ip }; } } else { - if (options.fields) { - const { id } = findInventoryFields(nodeType, options.fields); - return { - label: {id}, - value: node.id, - }; - } + const { id } = findInventoryFields(nodeType); + return { + label: {id}, + value: node.id, + }; } return { label: '', value: '' }; - }, [nodeType, node.ip, node.id, options.fields]); + }, [nodeType, node.ip, node.id]); const nodeLogsMenuItemLinkProps = useLinkProps( getNodeLogsUrl({ @@ -184,11 +182,7 @@ export const NodeContextMenu: React.FC = withTheme {flyoutVisible && ( , - timefield: string, to: number, sortBy: SortBy, searchFilter: object @@ -51,7 +50,6 @@ export function useProcessList( 'POST', JSON.stringify({ hostTerm, - timefield, indexPattern, to, sortBy: parsedSortBy, @@ -75,15 +73,11 @@ export function useProcessList( }; } -function useProcessListParams(props: { - hostTerm: Record; - timefield: string; - to: number; -}) { - const { hostTerm, timefield, to } = props; +function useProcessListParams(props: { hostTerm: Record; to: number }) { + const { hostTerm, to } = props; const { createDerivedIndexPattern } = useSourceContext(); const indexPattern = createDerivedIndexPattern('metrics').title; - return { hostTerm, indexPattern, timefield, to }; + return { hostTerm, indexPattern, to }; } const ProcessListContext = createContainter(useProcessListParams); export const [ProcessListContextProvider, useProcessListContext] = ProcessListContext; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_process_list_row_chart.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_process_list_row_chart.ts index 30d4e5960ba5e..0d718ffbe210c 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_process_list_row_chart.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_process_list_row_chart.ts @@ -25,14 +25,13 @@ export function useProcessListRowChart(command: string) { fold(throwErrors(createPlainError), identity) ); }; - const { hostTerm, timefield, indexPattern, to } = useProcessListContext(); + const { hostTerm, indexPattern, to } = useProcessListContext(); const { error, loading, response, makeRequest } = useHTTPRequest( '/api/metrics/process_list/chart', 'POST', JSON.stringify({ hostTerm, - timefield, indexPattern, to, command, diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_uptime_link.test.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_uptime_link.test.ts index dbe45a387891c..af93f6c0d62ce 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_uptime_link.test.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_uptime_link.test.ts @@ -10,13 +10,6 @@ import { InfraWaffleMapOptions, InfraFormatterType } from '../../../../lib/lib'; import { SnapshotMetricType } from '../../../../../common/inventory_models/types'; const options: InfraWaffleMapOptions = { - fields: { - container: 'container.id', - pod: 'kubernetes.pod.uid', - host: 'host.name', - timestamp: '@timestanp', - tiebreaker: '@timestamp', - }, formatter: InfraFormatterType.percent, formatTemplate: '{{value}}', metric: { type: 'cpu' }, diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_uptime_link.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_uptime_link.ts index 5c02893b867de..b6fa4fe4273ab 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_uptime_link.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_uptime_link.ts @@ -5,9 +5,9 @@ * 2.0. */ -import { get } from 'lodash'; import { InfraWaffleMapNode, InfraWaffleMapOptions } from '../../../../lib/lib'; import { InventoryItemType } from '../../../../../common/inventory_models/types'; +import { getFieldByType } from '../../../../../common/inventory_models'; import { LinkDescriptor } from '../../../../hooks/use_link_props'; export const createUptimeLink = ( @@ -24,7 +24,7 @@ export const createUptimeLink = ( }, }; } - const field = get(options, ['fields', nodeType], ''); + const field = getFieldByType(nodeType); return { app: 'uptime', hash: '/', diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/lib/get_filtered_metrics.ts b/x-pack/plugins/infra/public/pages/metrics/metric_detail/lib/get_filtered_metrics.ts index 2339319926da8..d1ba4502f37c3 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/lib/get_filtered_metrics.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/lib/get_filtered_metrics.ts @@ -8,6 +8,7 @@ import { InfraMetadataFeature } from '../../../../../common/http_api/metadata_api'; import { InventoryMetric } from '../../../../../common/inventory_models/types'; import { metrics } from '../../../../../common/inventory_models/metrics'; +import { TIMESTAMP_FIELD } from '../../../../../common/constants'; export const getFilteredMetrics = ( requiredMetrics: InventoryMetric[], @@ -20,7 +21,7 @@ export const getFilteredMetrics = ( const metricModelCreator = metrics.tsvb[metric]; // We just need to get a dummy version of the model so we can filter // using the `requires` attribute. - const metricModel = metricModelCreator('@timestamp', 'test', '>=1m'); + const metricModel = metricModelCreator(TIMESTAMP_FIELD, 'test', '>=1m'); return metricMetadata.some((m) => m && metricModel.requires.includes(m)); }); }; diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/chart_context_menu.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/chart_context_menu.tsx index 005dd5cc8c078..581eec3e824ae 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/chart_context_menu.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/chart_context_menu.tsx @@ -27,6 +27,7 @@ import { import { createTSVBLink } from './helpers/create_tsvb_link'; import { getNodeDetailUrl } from '../../../link_to/redirect_to_node_detail'; import { InventoryItemType } from '../../../../../common/inventory_models/types'; +import { HOST_FIELD, POD_FIELD, CONTAINER_FIELD } from '../../../../../common/constants'; import { useLinkProps } from '../../../../hooks/use_link_props'; export interface Props { @@ -44,13 +45,13 @@ const fieldToNodeType = ( groupBy: string | string[] ): InventoryItemType | undefined => { const fields = Array.isArray(groupBy) ? groupBy : [groupBy]; - if (fields.includes(source.fields.host)) { + if (fields.includes(HOST_FIELD)) { return 'host'; } - if (fields.includes(source.fields.pod)) { + if (fields.includes(POD_FIELD)) { return 'pod'; } - if (fields.includes(source.fields.container)) { + if (fields.includes(CONTAINER_FIELD)) { return 'container'; } }; diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.test.ts b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.test.ts index a9e65bc30a3c6..472e86200cba3 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.test.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.test.ts @@ -79,7 +79,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'my-beats-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'my-beats-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:time,type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'my-beats-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'my-beats-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -97,7 +97,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'my-beats-*',filter:(language:kuery,query:'system.network.name:lo* and host.name : \"example-01\"'),id:test-id,index_pattern:'my-beats-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:time,type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'my-beats-*',filter:(language:kuery,query:'system.network.name:lo* and host.name : \"example-01\"'),id:test-id,index_pattern:'my-beats-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -161,7 +161,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metric*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metric*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:time,type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metric*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metric*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts index 84d87ee4ad1b7..5d1f9bafdedaf 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts @@ -8,6 +8,7 @@ import { encode } from 'rison-node'; import uuid from 'uuid'; import { set } from '@elastic/safer-lodash-set'; +import { TIMESTAMP_FIELD } from '../../../../../../common/constants'; import { MetricsSourceConfigurationProperties } from '../../../../../../common/metrics_sources'; import { colorTransformer, Color } from '../../../../../../common/color_palette'; import { MetricsExplorerSeries } from '../../../../../../common/http_api/metrics_explorer'; @@ -169,7 +170,7 @@ export const createTSVBLink = ( series: options.metrics.map(mapMetricToSeries(chartOptions)), show_grid: 1, show_legend: 1, - time_field: (source && source.fields.timestamp) || '@timestamp', + time_field: TIMESTAMP_FIELD, type: 'timeseries', filter: createFilterFromOptions(options, series), }, diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts index c0d0b15217df3..788760a0dfe1c 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts @@ -84,7 +84,6 @@ export function useMetricsExplorerData( void 0, timerange: { ...timerange, - field: source.fields.timestamp, from: from.valueOf(), to: to.valueOf(), }, diff --git a/x-pack/plugins/infra/public/utils/loading_state/index.ts b/x-pack/plugins/infra/public/utils/loading_state/index.ts index f0f42f1afa6a4..f93d0638b3366 100644 --- a/x-pack/plugins/infra/public/utils/loading_state/index.ts +++ b/x-pack/plugins/infra/public/utils/loading_state/index.ts @@ -5,18 +5,21 @@ * 2.0. */ -export { initialLoadingState, LoadingState } from './loading_state'; +export type { LoadingState } from './loading_state'; +export { initialLoadingState } from './loading_state'; -export { isManualLoadingPolicy, isIntervalLoadingPolicy, LoadingPolicy } from './loading_policy'; +export type { LoadingPolicy } from './loading_policy'; +export { isManualLoadingPolicy, isIntervalLoadingPolicy } from './loading_policy'; +export type { LoadingProgress } from './loading_progress'; export { createRunningProgressReducer, createIdleProgressReducer, isIdleLoadingProgress, isRunningLoadingProgress, - LoadingProgress, } from './loading_progress'; +export type { LoadingResult } from './loading_result'; export { createFailureResult, createFailureResultReducer, @@ -27,5 +30,4 @@ export { isFailureLoadingResult, isSuccessLoadingResult, isUninitializedLoadingResult, - LoadingResult, } from './loading_result'; diff --git a/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts b/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts index 44f65b9e8071a..6843bc631ce27 100644 --- a/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts +++ b/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts @@ -8,7 +8,7 @@ import { encode } from 'rison-node'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { FetchData, FetchDataParams, LogsFetchDataResponse } from '../../../observability/public'; -import { DEFAULT_SOURCE_ID } from '../../common/constants'; +import { DEFAULT_SOURCE_ID, TIMESTAMP_FIELD } from '../../common/constants'; import { callFetchLogSourceConfigurationAPI } from '../containers/logs/log_source/api/fetch_log_source_configuration'; import { callFetchLogSourceStatusAPI } from '../containers/logs/log_source/api/fetch_log_source_status'; import { InfraClientCoreSetup, InfraClientStartDeps } from '../types'; @@ -30,7 +30,6 @@ interface StatsAggregation { interface LogParams { index: string; - timestampField: string; } type StatsAndSeries = Pick; @@ -63,7 +62,6 @@ export function getLogsOverviewDataFetcher( const { stats, series } = await fetchLogsOverview( { index: resolvedLogSourceConfiguration.indices, - timestampField: resolvedLogSourceConfiguration.timestampField, }, params, data @@ -117,7 +115,7 @@ async function fetchLogsOverview( function buildLogOverviewQuery(logParams: LogParams, params: FetchDataParams) { return { range: { - [logParams.timestampField]: { + [TIMESTAMP_FIELD]: { gt: new Date(params.absoluteTime.start).toISOString(), lte: new Date(params.absoluteTime.end).toISOString(), format: 'strict_date_optional_time', @@ -137,7 +135,7 @@ function buildLogOverviewAggregations(logParams: LogParams, params: FetchDataPar aggs: { series: { date_histogram: { - field: logParams.timestampField, + field: TIMESTAMP_FIELD, fixed_interval: params.intervalString, }, }, diff --git a/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts b/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts index d0349ab20710f..8a1920f534cd6 100644 --- a/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts +++ b/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts @@ -150,7 +150,6 @@ describe('Logs UI Observability Homepage Functions', () => { type: 'index_pattern', indexPatternId: 'test-index-pattern', }, - fields: { timestamp: '@timestamp', tiebreaker: '_doc' }, }, }, } as GetLogSourceConfigurationSuccessResponsePayload); diff --git a/x-pack/plugins/infra/server/deprecations.ts b/x-pack/plugins/infra/server/deprecations.ts index 4c2f5f6a9b3d1..5e016bc094826 100644 --- a/x-pack/plugins/infra/server/deprecations.ts +++ b/x-pack/plugins/infra/server/deprecations.ts @@ -13,6 +13,13 @@ import { DeprecationsDetails, GetDeprecationsContext, } from 'src/core/server'; +import { + TIMESTAMP_FIELD, + TIEBREAKER_FIELD, + CONTAINER_FIELD, + HOST_FIELD, + POD_FIELD, +} from '../common/constants'; import { InfraSources } from './lib/sources'; const deprecatedFieldMessage = (fieldName: string, defaultValue: string, configNames: string[]) => @@ -28,11 +35,11 @@ const deprecatedFieldMessage = (fieldName: string, defaultValue: string, configN }); const DEFAULT_VALUES = { - timestamp: '@timestamp', - tiebreaker: '_doc', - container: 'container.id', - host: 'host.name', - pod: 'kubernetes.pod.uid', + timestamp: TIMESTAMP_FIELD, + tiebreaker: TIEBREAKER_FIELD, + container: CONTAINER_FIELD, + host: HOST_FIELD, + pod: POD_FIELD, }; const FIELD_DEPRECATION_FACTORIES: Record DeprecationsDetails> = diff --git a/x-pack/plugins/infra/server/index.ts b/x-pack/plugins/infra/server/index.ts index a25bba48d673e..93be23356dfc3 100644 --- a/x-pack/plugins/infra/server/index.ts +++ b/x-pack/plugins/infra/server/index.ts @@ -8,8 +8,9 @@ import { PluginInitializerContext } from 'src/core/server'; import { config, InfraConfig, InfraServerPlugin, InfraPluginSetup } from './plugin'; -export { config, InfraConfig, InfraPluginSetup }; -export { InfraRequestHandlerContext } from './types'; +export type { InfraConfig, InfraPluginSetup }; +export { config }; +export type { InfraRequestHandlerContext } from './types'; export function plugin(context: PluginInitializerContext) { return new InfraServerPlugin(context); diff --git a/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts index 75a86ae654d6c..7e8f5ebfd5af4 100644 --- a/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts @@ -24,6 +24,7 @@ import { import { SortedSearchHit } from '../framework'; import { KibanaFramework } from '../framework/kibana_framework_adapter'; import { ResolvedLogSourceConfiguration } from '../../../../common/log_sources'; +import { TIMESTAMP_FIELD, TIEBREAKER_FIELD } from '../../../../common/constants'; const TIMESTAMP_FORMAT = 'epoch_millis'; @@ -64,8 +65,8 @@ export class InfraKibanaLogEntriesAdapter implements LogEntriesAdapter { : {}; const sort = { - [resolvedLogSourceConfiguration.timestampField]: sortDirection, - [resolvedLogSourceConfiguration.tiebreakerField]: sortDirection, + [TIMESTAMP_FIELD]: sortDirection, + [TIEBREAKER_FIELD]: sortDirection, }; const esQuery = { @@ -83,7 +84,7 @@ export class InfraKibanaLogEntriesAdapter implements LogEntriesAdapter { ...createFilterClauses(query, highlightQuery), { range: { - [resolvedLogSourceConfiguration.timestampField]: { + [TIMESTAMP_FIELD]: { gte: startTimestamp, lte: endTimestamp, format: TIMESTAMP_FORMAT, @@ -146,7 +147,7 @@ export class InfraKibanaLogEntriesAdapter implements LogEntriesAdapter { aggregations: { count_by_date: { date_range: { - field: resolvedLogSourceConfiguration.timestampField, + field: TIMESTAMP_FIELD, format: TIMESTAMP_FORMAT, ranges: bucketIntervalStarts.map((bucketIntervalStart) => ({ from: bucketIntervalStart.getTime(), @@ -157,10 +158,7 @@ export class InfraKibanaLogEntriesAdapter implements LogEntriesAdapter { top_hits_by_key: { top_hits: { size: 1, - sort: [ - { [resolvedLogSourceConfiguration.timestampField]: 'asc' }, - { [resolvedLogSourceConfiguration.tiebreakerField]: 'asc' }, - ], + sort: [{ [TIMESTAMP_FIELD]: 'asc' }, { [TIEBREAKER_FIELD]: 'asc' }], _source: false, }, }, @@ -173,7 +171,7 @@ export class InfraKibanaLogEntriesAdapter implements LogEntriesAdapter { ...createQueryFilterClauses(filterQuery), { range: { - [resolvedLogSourceConfiguration.timestampField]: { + [TIMESTAMP_FIELD]: { gte: startTimestamp, lte: endTimestamp, format: TIMESTAMP_FORMAT, diff --git a/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts index 730da9511dc38..e05a5b647ad2b 100644 --- a/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts @@ -8,6 +8,7 @@ import { i18n } from '@kbn/i18n'; import { flatten, get } from 'lodash'; import { KibanaRequest } from 'src/core/server'; +import { TIMESTAMP_FIELD } from '../../../../common/constants'; import { NodeDetailsMetricData } from '../../../../common/http_api/node_details_api'; import { KibanaFramework } from '../framework/kibana_framework_adapter'; import { InfraMetricsAdapter, InfraMetricsRequestOptions } from './adapter_types'; @@ -36,7 +37,7 @@ export class KibanaMetricsAdapter implements InfraMetricsAdapter { rawRequest: KibanaRequest ): Promise { const indexPattern = `${options.sourceConfiguration.metricAlias}`; - const fields = findInventoryFields(options.nodeType, options.sourceConfiguration.fields); + const fields = findInventoryFields(options.nodeType); const nodeField = fields.id; const search = (searchOptions: object) => @@ -122,11 +123,7 @@ export class KibanaMetricsAdapter implements InfraMetricsAdapter { max: options.timerange.to, }; - const model = createTSVBModel( - options.sourceConfiguration.fields.timestamp, - indexPattern, - options.timerange.interval - ); + const model = createTSVBModel(TIMESTAMP_FIELD, indexPattern, options.timerange.interval); const client = ( opts: CallWithRequestParams @@ -137,7 +134,6 @@ export class KibanaMetricsAdapter implements InfraMetricsAdapter { client, { indexPattern: `${options.sourceConfiguration.metricAlias}`, - timestampField: options.sourceConfiguration.fields.timestamp, timerange: options.timerange, }, model.requires diff --git a/x-pack/plugins/infra/server/lib/alerting/log_threshold/mocks/index.ts b/x-pack/plugins/infra/server/lib/alerting/log_threshold/mocks/index.ts index 296a540b4a920..f02dac2139097 100644 --- a/x-pack/plugins/infra/server/lib/alerting/log_threshold/mocks/index.ts +++ b/x-pack/plugins/infra/server/lib/alerting/log_threshold/mocks/index.ts @@ -17,7 +17,6 @@ export const libsMock = { type: 'index_pattern', indexPatternId: 'some-id', }, - fields: { timestamp: '@timestamp' }, }, }); }, diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts index 71c18d9f7cf04..8991c884336d3 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts @@ -74,7 +74,6 @@ export const evaluateAlert = { timeSize: 1, } as MetricExpressionParams; - const timefield = '@timestamp'; const groupBy = 'host.doggoname'; const timeframe = { start: moment().subtract(5, 'minutes').valueOf(), @@ -25,7 +24,7 @@ describe("The Metric Threshold Alert's getElasticsearchMetricQuery", () => { }; describe('when passed no filterQuery', () => { - const searchBody = getElasticsearchMetricQuery(expressionParams, timefield, timeframe, groupBy); + const searchBody = getElasticsearchMetricQuery(expressionParams, timeframe, groupBy); test('includes a range filter', () => { expect( searchBody.query.bool.filter.find((filter) => filter.hasOwnProperty('range')) @@ -47,7 +46,6 @@ describe("The Metric Threshold Alert's getElasticsearchMetricQuery", () => { const searchBody = getElasticsearchMetricQuery( expressionParams, - timefield, timeframe, groupBy, filterQuery diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/metric_query.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/metric_query.ts index 59dc398973f8c..588b77250e6a6 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/metric_query.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/metric_query.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { TIMESTAMP_FIELD } from '../../../../../common/constants'; import { networkTraffic } from '../../../../../common/inventory_models/shared/metrics/snapshot/network_traffic'; import { MetricExpressionParams, Aggregators } from '../types'; import { createPercentileAggregation } from './create_percentile_aggregation'; @@ -21,7 +22,6 @@ const getParsedFilterQuery: (filterQuery: string | undefined) => Record { const body = { size: 0, @@ -22,7 +23,7 @@ export const getProcessList = async ( filter: [ { range: { - [timefield]: { + [TIMESTAMP_FIELD]: { gte: to - 60 * 1000, // 1 minute lte: to, }, @@ -47,7 +48,7 @@ export const getProcessList = async ( size: 1, sort: [ { - [timefield]: { + [TIMESTAMP_FIELD]: { order: 'desc', }, }, @@ -93,7 +94,7 @@ export const getProcessList = async ( size: 1, sort: [ { - [timefield]: { + [TIMESTAMP_FIELD]: { order: 'desc', }, }, diff --git a/x-pack/plugins/infra/server/lib/host_details/process_list_chart.ts b/x-pack/plugins/infra/server/lib/host_details/process_list_chart.ts index 413a97cb7a058..7ff66a80e967b 100644 --- a/x-pack/plugins/infra/server/lib/host_details/process_list_chart.ts +++ b/x-pack/plugins/infra/server/lib/host_details/process_list_chart.ts @@ -6,6 +6,7 @@ */ import { first } from 'lodash'; +import { TIMESTAMP_FIELD } from '../../../common/constants'; import { ProcessListAPIChartRequest, ProcessListAPIChartQueryAggregation, @@ -17,7 +18,7 @@ import { CMDLINE_FIELD } from './common'; export const getProcessListChart = async ( search: ESSearchClient, - { hostTerm, timefield, indexPattern, to, command }: ProcessListAPIChartRequest + { hostTerm, indexPattern, to, command }: ProcessListAPIChartRequest ) => { const body = { size: 0, @@ -26,7 +27,7 @@ export const getProcessListChart = async ( filter: [ { range: { - [timefield]: { + [TIMESTAMP_FIELD]: { gte: to - 60 * 1000, // 1 minute lte: to, }, @@ -60,7 +61,7 @@ export const getProcessListChart = async ( aggs: { timeseries: { date_histogram: { - field: timefield, + field: TIMESTAMP_FIELD, fixed_interval: '1m', extended_bounds: { min: to - 60 * 15 * 1000, // 15 minutes, diff --git a/x-pack/plugins/infra/server/lib/infra_ml/index.ts b/x-pack/plugins/infra/server/lib/infra_ml/index.ts index 82093b1a359d0..853ef8d0d60b2 100644 --- a/x-pack/plugins/infra/server/lib/infra_ml/index.ts +++ b/x-pack/plugins/infra/server/lib/infra_ml/index.ts @@ -8,4 +8,4 @@ export * from './errors'; export * from './metrics_hosts_anomalies'; export * from './metrics_k8s_anomalies'; -export { MappedAnomalyHit } from './common'; +export type { MappedAnomalyHit } from './common'; diff --git a/x-pack/plugins/infra/server/lib/infra_ml/queries/metrics_hosts_anomalies.ts b/x-pack/plugins/infra/server/lib/infra_ml/queries/metrics_hosts_anomalies.ts index ab50986c3b3d5..9c0f4313c6bdb 100644 --- a/x-pack/plugins/infra/server/lib/infra_ml/queries/metrics_hosts_anomalies.ts +++ b/x-pack/plugins/infra/server/lib/infra_ml/queries/metrics_hosts_anomalies.ts @@ -6,6 +6,7 @@ */ import * as rt from 'io-ts'; +import { TIEBREAKER_FIELD } from '../../../../common/constants'; import { ANOMALY_THRESHOLD } from '../../../../common/infra_ml'; import { commonSearchSuccessResponseFieldsRT } from '../../../utils/elasticsearch_runtime_types'; import { @@ -20,9 +21,6 @@ import { import { InfluencerFilter } from '../common'; import { Sort, Pagination } from '../../../../common/http_api/infra_ml'; -// TODO: Reassess validity of this against ML docs -const TIEBREAKER_FIELD = '_doc'; - const sortToMlFieldMap = { dataset: 'partition_field_value', anomalyScore: 'record_score', diff --git a/x-pack/plugins/infra/server/lib/infra_ml/queries/metrics_k8s_anomalies.ts b/x-pack/plugins/infra/server/lib/infra_ml/queries/metrics_k8s_anomalies.ts index 8fb8df5eef3d7..23592aad2e322 100644 --- a/x-pack/plugins/infra/server/lib/infra_ml/queries/metrics_k8s_anomalies.ts +++ b/x-pack/plugins/infra/server/lib/infra_ml/queries/metrics_k8s_anomalies.ts @@ -6,6 +6,7 @@ */ import * as rt from 'io-ts'; +import { TIEBREAKER_FIELD } from '../../../../common/constants'; import { ANOMALY_THRESHOLD } from '../../../../common/infra_ml'; import { commonSearchSuccessResponseFieldsRT } from '../../../utils/elasticsearch_runtime_types'; import { @@ -20,9 +21,6 @@ import { import { InfluencerFilter } from '../common'; import { Sort, Pagination } from '../../../../common/http_api/infra_ml'; -// TODO: Reassess validity of this against ML docs -const TIEBREAKER_FIELD = '_doc'; - const sortToMlFieldMap = { dataset: 'partition_field_value', anomalyScore: 'record_score', diff --git a/x-pack/plugins/infra/server/lib/metrics/index.ts b/x-pack/plugins/infra/server/lib/metrics/index.ts index d291dbf88b49a..c4641e265ea55 100644 --- a/x-pack/plugins/infra/server/lib/metrics/index.ts +++ b/x-pack/plugins/infra/server/lib/metrics/index.ts @@ -7,6 +7,7 @@ import { set } from '@elastic/safer-lodash-set'; import { ThrowReporter } from 'io-ts/lib/ThrowReporter'; +import { TIMESTAMP_FIELD } from '../../../common/constants'; import { MetricsAPIRequest, MetricsAPIResponse, afterKeyObjectRT } from '../../../common/http_api'; import { ESSearchClient, @@ -36,7 +37,7 @@ export const query = async ( const filter: Array> = [ { range: { - [options.timerange.field]: { + [TIMESTAMP_FIELD]: { gte: options.timerange.from, lte: options.timerange.to, format: 'epoch_millis', diff --git a/x-pack/plugins/infra/server/lib/metrics/lib/calculate_interval.ts b/x-pack/plugins/infra/server/lib/metrics/lib/calculate_interval.ts index f6bdfb2de0a29..ee309ad449b2d 100644 --- a/x-pack/plugins/infra/server/lib/metrics/lib/calculate_interval.ts +++ b/x-pack/plugins/infra/server/lib/metrics/lib/calculate_interval.ts @@ -21,7 +21,6 @@ export const calculatedInterval = async (search: ESSearchClient, options: Metric search, { indexPattern: options.indexPattern, - timestampField: options.timerange.field, timerange: { from: options.timerange.from, to: options.timerange.to }, }, options.modules diff --git a/x-pack/plugins/infra/server/lib/metrics/lib/convert_histogram_buckets_to_timeseries.test.ts b/x-pack/plugins/infra/server/lib/metrics/lib/convert_histogram_buckets_to_timeseries.test.ts index b49560f8c25f6..8fe22e6f81d71 100644 --- a/x-pack/plugins/infra/server/lib/metrics/lib/convert_histogram_buckets_to_timeseries.test.ts +++ b/x-pack/plugins/infra/server/lib/metrics/lib/convert_histogram_buckets_to_timeseries.test.ts @@ -13,7 +13,6 @@ const keys = ['example-0']; const options: MetricsAPIRequest = { timerange: { - field: '@timestamp', from: moment('2020-01-01T00:00:00Z').valueOf(), to: moment('2020-01-01T00:00:00Z').add(5, 'minute').valueOf(), interval: '1m', diff --git a/x-pack/plugins/infra/server/lib/metrics/lib/create_aggregations.test.ts b/x-pack/plugins/infra/server/lib/metrics/lib/create_aggregations.test.ts index 91bf544b7e48f..9b92793129d44 100644 --- a/x-pack/plugins/infra/server/lib/metrics/lib/create_aggregations.test.ts +++ b/x-pack/plugins/infra/server/lib/metrics/lib/create_aggregations.test.ts @@ -11,7 +11,6 @@ import { MetricsAPIRequest } from '../../../../common/http_api'; const options: MetricsAPIRequest = { timerange: { - field: '@timestamp', from: moment('2020-01-01T00:00:00Z').valueOf(), to: moment('2020-01-01T01:00:00Z').valueOf(), interval: '>=1m', diff --git a/x-pack/plugins/infra/server/lib/metrics/lib/create_aggregations.ts b/x-pack/plugins/infra/server/lib/metrics/lib/create_aggregations.ts index 65cd4ebe2d501..769ccce409e65 100644 --- a/x-pack/plugins/infra/server/lib/metrics/lib/create_aggregations.ts +++ b/x-pack/plugins/infra/server/lib/metrics/lib/create_aggregations.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { TIMESTAMP_FIELD } from '../../../../common/constants'; import { MetricsAPIRequest } from '../../../../common/http_api/metrics_api'; import { calculateDateHistogramOffset } from './calculate_date_histogram_offset'; import { createMetricsAggregations } from './create_metrics_aggregations'; @@ -15,7 +16,7 @@ export const createAggregations = (options: MetricsAPIRequest) => { const histogramAggregation = { histogram: { date_histogram: { - field: options.timerange.field, + field: TIMESTAMP_FIELD, fixed_interval: intervalString, offset: options.alignDataToEnd ? calculateDateHistogramOffset(options.timerange) : '0s', extended_bounds: { diff --git a/x-pack/plugins/infra/server/lib/metrics/lib/create_metrics_aggregations.test.ts b/x-pack/plugins/infra/server/lib/metrics/lib/create_metrics_aggregations.test.ts index 27fe491d3964b..2e2d1736e5925 100644 --- a/x-pack/plugins/infra/server/lib/metrics/lib/create_metrics_aggregations.test.ts +++ b/x-pack/plugins/infra/server/lib/metrics/lib/create_metrics_aggregations.test.ts @@ -11,7 +11,6 @@ import { createMetricsAggregations } from './create_metrics_aggregations'; const options: MetricsAPIRequest = { timerange: { - field: '@timestamp', from: moment('2020-01-01T00:00:00Z').valueOf(), to: moment('2020-01-01T01:00:00Z').valueOf(), interval: '>=1m', diff --git a/x-pack/plugins/infra/server/lib/sources/defaults.ts b/x-pack/plugins/infra/server/lib/sources/defaults.ts index b6139613cfce3..db262a432b3fc 100644 --- a/x-pack/plugins/infra/server/lib/sources/defaults.ts +++ b/x-pack/plugins/infra/server/lib/sources/defaults.ts @@ -5,11 +5,7 @@ * 2.0. */ -import { - METRICS_INDEX_PATTERN, - LOGS_INDEX_PATTERN, - TIMESTAMP_FIELD, -} from '../../../common/constants'; +import { METRICS_INDEX_PATTERN, LOGS_INDEX_PATTERN } from '../../../common/constants'; import { InfraSourceConfiguration } from '../../../common/source_configuration/source_configuration'; export const defaultSourceConfiguration: InfraSourceConfiguration = { @@ -21,12 +17,7 @@ export const defaultSourceConfiguration: InfraSourceConfiguration = { indexName: LOGS_INDEX_PATTERN, }, fields: { - container: 'container.id', - host: 'host.name', message: ['message', '@message'], - pod: 'kubernetes.pod.uid', - tiebreaker: '_doc', - timestamp: TIMESTAMP_FIELD, }, inventoryDefaultView: '0', metricsExplorerDefaultView: '0', diff --git a/x-pack/plugins/infra/server/lib/sources/saved_object_references.test.ts b/x-pack/plugins/infra/server/lib/sources/saved_object_references.test.ts index 9f6f9cd284c67..fb550390e25be 100644 --- a/x-pack/plugins/infra/server/lib/sources/saved_object_references.test.ts +++ b/x-pack/plugins/infra/server/lib/sources/saved_object_references.test.ts @@ -101,12 +101,7 @@ const sourceConfigurationWithIndexPatternReference: InfraSourceConfiguration = { name: 'NAME', description: 'DESCRIPTION', fields: { - container: 'CONTAINER_FIELD', - host: 'HOST_FIELD', message: ['MESSAGE_FIELD'], - pod: 'POD_FIELD', - tiebreaker: 'TIEBREAKER_FIELD', - timestamp: 'TIMESTAMP_FIELD', }, logColumns: [], logIndices: { diff --git a/x-pack/plugins/infra/server/lib/sources/sources.test.ts b/x-pack/plugins/infra/server/lib/sources/sources.test.ts index 904f51d12673f..396d2c22a100f 100644 --- a/x-pack/plugins/infra/server/lib/sources/sources.test.ts +++ b/x-pack/plugins/infra/server/lib/sources/sources.test.ts @@ -24,13 +24,6 @@ describe('the InfraSources lib', () => { attributes: { metricAlias: 'METRIC_ALIAS', logIndices: { type: 'index_pattern', indexPatternId: 'log_index_pattern_0' }, - fields: { - container: 'CONTAINER', - host: 'HOST', - pod: 'POD', - tiebreaker: 'TIEBREAKER', - timestamp: 'TIMESTAMP', - }, }, references: [ { @@ -50,13 +43,6 @@ describe('the InfraSources lib', () => { configuration: { metricAlias: 'METRIC_ALIAS', logIndices: { type: 'index_pattern', indexPatternId: 'LOG_INDEX_PATTERN' }, - fields: { - container: 'CONTAINER', - host: 'HOST', - pod: 'POD', - tiebreaker: 'TIEBREAKER', - timestamp: 'TIMESTAMP', - }, }, }); }); @@ -67,12 +53,6 @@ describe('the InfraSources lib', () => { default: { metricAlias: 'METRIC_ALIAS', logIndices: { type: 'index_pattern', indexPatternId: 'LOG_ALIAS' }, - fields: { - host: 'HOST', - pod: 'POD', - tiebreaker: 'TIEBREAKER', - timestamp: 'TIMESTAMP', - }, }, }), }); @@ -82,11 +62,7 @@ describe('the InfraSources lib', () => { version: 'foo', type: infraSourceConfigurationSavedObjectName, updated_at: '2000-01-01T00:00:00.000Z', - attributes: { - fields: { - container: 'CONTAINER', - }, - }, + attributes: {}, references: [], }); @@ -99,13 +75,6 @@ describe('the InfraSources lib', () => { configuration: { metricAlias: 'METRIC_ALIAS', logIndices: { type: 'index_pattern', indexPatternId: 'LOG_ALIAS' }, - fields: { - container: 'CONTAINER', - host: 'HOST', - pod: 'POD', - tiebreaker: 'TIEBREAKER', - timestamp: 'TIMESTAMP', - }, }, }); }); @@ -133,13 +102,6 @@ describe('the InfraSources lib', () => { configuration: { metricAlias: expect.any(String), logIndices: expect.any(Object), - fields: { - container: expect.any(String), - host: expect.any(String), - pod: expect.any(String), - tiebreaker: expect.any(String), - timestamp: expect.any(String), - }, }, }); }); diff --git a/x-pack/plugins/infra/server/plugin.ts b/x-pack/plugins/infra/server/plugin.ts index 26d9f115405a6..4e655f200d94f 100644 --- a/x-pack/plugins/infra/server/plugin.ts +++ b/x-pack/plugins/infra/server/plugin.ts @@ -53,12 +53,7 @@ export const config: PluginConfigDescriptor = { schema.object({ fields: schema.maybe( schema.object({ - timestamp: schema.maybe(schema.string()), message: schema.maybe(schema.arrayOf(schema.string())), - tiebreaker: schema.maybe(schema.string()), - host: schema.maybe(schema.string()), - container: schema.maybe(schema.string()), - pod: schema.maybe(schema.string()), }) ), }) diff --git a/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts b/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts index c721ca75ea978..5c4ae1981c5cd 100644 --- a/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts +++ b/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { TIMESTAMP_FIELD } from '../../../../common/constants'; import { InventoryCloudAccount } from '../../../../common/http_api/inventory_meta_api'; import { InfraMetadataAggregationResponse, @@ -49,7 +50,7 @@ export const getCloudMetadata = async ( must: [ { range: { - [sourceConfiguration.fields.timestamp]: { + [TIMESTAMP_FIELD]: { gte: currentTime - 86400000, // 24 hours ago lte: currentTime, format: 'epoch_millis', diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts b/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts index d9da7bce2246f..126d1485cb702 100644 --- a/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts +++ b/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts @@ -13,6 +13,7 @@ import { import { KibanaFramework } from '../../../lib/adapters/framework/kibana_framework_adapter'; import { InfraSourceConfiguration } from '../../../lib/sources'; import { CLOUD_METRICS_MODULES } from '../../../lib/constants'; +import { TIMESTAMP_FIELD } from '../../../../common/constants'; export interface InfraCloudMetricsAdapterResponse { buckets: InfraMetadataAggregationBucket[]; @@ -36,7 +37,7 @@ export const getCloudMetricsMetadata = async ( { match: { 'cloud.instance.id': instanceId } }, { range: { - [sourceConfiguration.fields.timestamp]: { + [TIMESTAMP_FIELD]: { gte: timeRange.from, lte: timeRange.to, format: 'epoch_millis', diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/get_metric_metadata.ts b/x-pack/plugins/infra/server/routes/metadata/lib/get_metric_metadata.ts index bfa0884bfe199..1962a24f7d4db 100644 --- a/x-pack/plugins/infra/server/routes/metadata/lib/get_metric_metadata.ts +++ b/x-pack/plugins/infra/server/routes/metadata/lib/get_metric_metadata.ts @@ -15,6 +15,7 @@ import { KibanaFramework } from '../../../lib/adapters/framework/kibana_framewor import { InfraSourceConfiguration } from '../../../lib/sources'; import { findInventoryFields } from '../../../../common/inventory_models'; import { InventoryItemType } from '../../../../common/inventory_models/types'; +import { TIMESTAMP_FIELD } from '../../../../common/constants'; export interface InfraMetricsAdapterResponse { id: string; @@ -30,7 +31,7 @@ export const getMetricMetadata = async ( nodeType: InventoryItemType, timeRange: { from: number; to: number } ): Promise => { - const fields = findInventoryFields(nodeType, sourceConfiguration.fields); + const fields = findInventoryFields(nodeType); const metricQuery = { allow_no_indices: true, ignore_unavailable: true, @@ -45,7 +46,7 @@ export const getMetricMetadata = async ( }, { range: { - [sourceConfiguration.fields.timestamp]: { + [TIMESTAMP_FIELD]: { gte: timeRange.from, lte: timeRange.to, format: 'epoch_millis', diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts b/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts index 94becdf6d2811..97a0707a4c215 100644 --- a/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts +++ b/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts @@ -15,6 +15,7 @@ import { getPodNodeName } from './get_pod_node_name'; import { CLOUD_METRICS_MODULES } from '../../../lib/constants'; import { findInventoryFields } from '../../../../common/inventory_models'; import { InventoryItemType } from '../../../../common/inventory_models/types'; +import { TIMESTAMP_FIELD } from '../../../../common/constants'; export const getNodeInfo = async ( framework: KibanaFramework, @@ -50,8 +51,7 @@ export const getNodeInfo = async ( } return {}; } - const fields = findInventoryFields(nodeType, sourceConfiguration.fields); - const timestampField = sourceConfiguration.fields.timestamp; + const fields = findInventoryFields(nodeType); const params = { allow_no_indices: true, ignore_unavailable: true, @@ -60,14 +60,14 @@ export const getNodeInfo = async ( body: { size: 1, _source: ['host.*', 'cloud.*', 'agent.*'], - sort: [{ [timestampField]: 'desc' }], + sort: [{ [TIMESTAMP_FIELD]: 'desc' }], query: { bool: { filter: [ { match: { [fields.id]: nodeId } }, { range: { - [timestampField]: { + [TIMESTAMP_FIELD]: { gte: timeRange.from, lte: timeRange.to, format: 'epoch_millis', diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/get_pod_node_name.ts b/x-pack/plugins/infra/server/routes/metadata/lib/get_pod_node_name.ts index 164d94d9f692f..3afb6a8abcb58 100644 --- a/x-pack/plugins/infra/server/routes/metadata/lib/get_pod_node_name.ts +++ b/x-pack/plugins/infra/server/routes/metadata/lib/get_pod_node_name.ts @@ -10,6 +10,7 @@ import { KibanaFramework } from '../../../lib/adapters/framework/kibana_framewor import { InfraSourceConfiguration } from '../../../lib/sources'; import { findInventoryFields } from '../../../../common/inventory_models'; import type { InfraPluginRequestHandlerContext } from '../../../types'; +import { TIMESTAMP_FIELD } from '../../../../common/constants'; export const getPodNodeName = async ( framework: KibanaFramework, @@ -19,8 +20,7 @@ export const getPodNodeName = async ( nodeType: 'host' | 'pod' | 'container', timeRange: { from: number; to: number } ): Promise => { - const fields = findInventoryFields(nodeType, sourceConfiguration.fields); - const timestampField = sourceConfiguration.fields.timestamp; + const fields = findInventoryFields(nodeType); const params = { allow_no_indices: true, ignore_unavailable: true, @@ -29,7 +29,7 @@ export const getPodNodeName = async ( body: { size: 1, _source: ['kubernetes.node.name'], - sort: [{ [timestampField]: 'desc' }], + sort: [{ [TIMESTAMP_FIELD]: 'desc' }], query: { bool: { filter: [ @@ -37,7 +37,7 @@ export const getPodNodeName = async ( { exists: { field: `kubernetes.node.name` } }, { range: { - [timestampField]: { + [TIMESTAMP_FIELD]: { gte: timeRange.from, lte: timeRange.to, format: 'epoch_millis', diff --git a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/convert_request_to_metrics_api_options.test.ts b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/convert_request_to_metrics_api_options.test.ts index 539e9a1fee6ef..a6848e4f7a2dd 100644 --- a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/convert_request_to_metrics_api_options.test.ts +++ b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/convert_request_to_metrics_api_options.test.ts @@ -10,7 +10,6 @@ import { convertRequestToMetricsAPIOptions } from './convert_request_to_metrics_ const BASE_REQUEST: MetricsExplorerRequestBody = { timerange: { - field: '@timestamp', from: new Date('2020-01-01T00:00:00Z').getTime(), to: new Date('2020-01-01T01:00:00Z').getTime(), interval: '1m', @@ -22,7 +21,6 @@ const BASE_REQUEST: MetricsExplorerRequestBody = { const BASE_METRICS_UI_OPTIONS: MetricsAPIRequest = { timerange: { - field: '@timestamp', from: new Date('2020-01-01T00:00:00Z').getTime(), to: new Date('2020-01-01T01:00:00Z').getTime(), interval: '1m', diff --git a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/find_interval_for_metrics.ts b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/find_interval_for_metrics.ts index 9ca8c085eac44..62e99cf8ffd32 100644 --- a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/find_interval_for_metrics.ts +++ b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/find_interval_for_metrics.ts @@ -44,7 +44,6 @@ export const findIntervalForMetrics = async ( client, { indexPattern: options.indexPattern, - timestampField: options.timerange.field, timerange: options.timerange, }, modules.filter(Boolean) as string[] diff --git a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_dataset_for_field.ts b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_dataset_for_field.ts index 640d62c366726..97154a7361c96 100644 --- a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_dataset_for_field.ts +++ b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_dataset_for_field.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { TIMESTAMP_FIELD } from '../../../../common/constants'; import { ESSearchClient } from '../../../lib/metrics/types'; interface EventDatasetHit { @@ -19,7 +20,7 @@ export const getDatasetForField = async ( client: ESSearchClient, field: string, indexPattern: string, - timerange: { field: string; to: number; from: number } + timerange: { to: number; from: number } ) => { const params = { allow_no_indices: true, @@ -33,7 +34,7 @@ export const getDatasetForField = async ( { exists: { field } }, { range: { - [timerange.field]: { + [TIMESTAMP_FIELD]: { gte: timerange.from, lte: timerange.to, format: 'epoch_millis', @@ -45,7 +46,7 @@ export const getDatasetForField = async ( }, size: 1, _source: ['event.dataset'], - sort: [{ [timerange.field]: { order: 'desc' } }], + sort: [{ [TIMESTAMP_FIELD]: { order: 'desc' } }], }, }; diff --git a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/query_total_groupings.ts b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/query_total_groupings.ts index a2bf778d5016d..b2e22752609c1 100644 --- a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/query_total_groupings.ts +++ b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/query_total_groupings.ts @@ -6,6 +6,7 @@ */ import { isArray } from 'lodash'; +import { TIMESTAMP_FIELD } from '../../../../common/constants'; import { MetricsAPIRequest } from '../../../../common/http_api'; import { ESSearchClient } from '../../../lib/metrics/types'; @@ -26,7 +27,7 @@ export const queryTotalGroupings = async ( let filters: Array> = [ { range: { - [options.timerange.field]: { + [TIMESTAMP_FIELD]: { gte: options.timerange.from, lte: options.timerange.to, format: 'epoch_millis', diff --git a/x-pack/plugins/infra/server/routes/overview/lib/create_top_nodes_query.ts b/x-pack/plugins/infra/server/routes/overview/lib/create_top_nodes_query.ts index 7533f2801607c..ccead528749cd 100644 --- a/x-pack/plugins/infra/server/routes/overview/lib/create_top_nodes_query.ts +++ b/x-pack/plugins/infra/server/routes/overview/lib/create_top_nodes_query.ts @@ -7,6 +7,7 @@ import { MetricsSourceConfiguration } from '../../../../common/metrics_sources'; import { TopNodesRequest } from '../../../../common/http_api/overview_api'; +import { TIMESTAMP_FIELD } from '../../../../common/constants'; export const createTopNodesQuery = ( options: TopNodesRequest, @@ -22,7 +23,7 @@ export const createTopNodesQuery = ( filter: [ { range: { - [source.configuration.fields.timestamp]: { + [TIMESTAMP_FIELD]: { gte: options.timerange.from, lte: options.timerange.to, }, @@ -49,7 +50,7 @@ export const createTopNodesQuery = ( { field: 'host.name' }, { field: 'cloud.provider' }, ], - sort: { '@timestamp': 'desc' }, + sort: { [TIMESTAMP_FIELD]: 'desc' }, size: 1, }, }, diff --git a/x-pack/plugins/infra/server/routes/snapshot/lib/apply_metadata_to_last_path.ts b/x-pack/plugins/infra/server/routes/snapshot/lib/apply_metadata_to_last_path.ts index 7de63ae59a329..2931555fc06b0 100644 --- a/x-pack/plugins/infra/server/routes/snapshot/lib/apply_metadata_to_last_path.ts +++ b/x-pack/plugins/infra/server/routes/snapshot/lib/apply_metadata_to_last_path.ts @@ -42,10 +42,7 @@ export const applyMetadataToLastPath = ( if (firstMetaDoc && lastPath) { // We will need the inventory fields so we can use the field paths to get // the values from the metadata document - const inventoryFields = findInventoryFields( - snapshotRequest.nodeType, - source.configuration.fields - ); + const inventoryFields = findInventoryFields(snapshotRequest.nodeType); // Set the label as the name and fallback to the id OR path.value lastPath.label = (firstMetaDoc[inventoryFields.name] ?? lastPath.value) as string; // If the inventory fields contain an ip address, we need to try and set that diff --git a/x-pack/plugins/infra/server/routes/snapshot/lib/create_timerange_with_interval.ts b/x-pack/plugins/infra/server/routes/snapshot/lib/create_timerange_with_interval.ts index 7473907b7410b..bf6e51b9fe94f 100644 --- a/x-pack/plugins/infra/server/routes/snapshot/lib/create_timerange_with_interval.ts +++ b/x-pack/plugins/infra/server/routes/snapshot/lib/create_timerange_with_interval.ts @@ -25,7 +25,6 @@ const createInterval = async (client: ESSearchClient, options: InfraSnapshotRequ client, { indexPattern: options.sourceConfiguration.metricAlias, - timestampField: options.sourceConfiguration.fields.timestamp, timerange: { from: timerange.from, to: timerange.to }, }, modules, @@ -81,7 +80,6 @@ const aggregationsToModules = async ( async (field) => await getDatasetForField(client, field as string, options.sourceConfiguration.metricAlias, { ...options.timerange, - field: options.sourceConfiguration.fields.timestamp, }) ) ); diff --git a/x-pack/plugins/infra/server/routes/snapshot/lib/get_nodes.ts b/x-pack/plugins/infra/server/routes/snapshot/lib/get_nodes.ts index f59756e0c5b25..a3ca2cfd683bb 100644 --- a/x-pack/plugins/infra/server/routes/snapshot/lib/get_nodes.ts +++ b/x-pack/plugins/infra/server/routes/snapshot/lib/get_nodes.ts @@ -16,7 +16,6 @@ import { LogQueryFields } from '../../../services/log_queries/get_log_query_fiel export interface SourceOverrides { indexPattern: string; - timestamp: string; } const transformAndQueryData = async ({ diff --git a/x-pack/plugins/infra/server/routes/snapshot/lib/transform_request_to_metrics_api_request.test.ts b/x-pack/plugins/infra/server/routes/snapshot/lib/transform_request_to_metrics_api_request.test.ts index b4e6983a09900..aac5f9e145022 100644 --- a/x-pack/plugins/infra/server/routes/snapshot/lib/transform_request_to_metrics_api_request.test.ts +++ b/x-pack/plugins/infra/server/routes/snapshot/lib/transform_request_to_metrics_api_request.test.ts @@ -47,12 +47,7 @@ const source: InfraSource = { indexPatternId: 'kibana_index_pattern', }, fields: { - container: 'container.id', - host: 'host.name', message: ['message', '@message'], - pod: 'kubernetes.pod.uid', - tiebreaker: '_doc', - timestamp: '@timestamp', }, inventoryDefaultView: '0', metricsExplorerDefaultView: '0', @@ -80,7 +75,7 @@ const snapshotRequest: SnapshotRequest = { const metricsApiRequest = { indexPattern: 'metrics-*,metricbeat-*', - timerange: { field: '@timestamp', from: 1605705900000, to: 1605706200000, interval: '60s' }, + timerange: { from: 1605705900000, to: 1605706200000, interval: '60s' }, metrics: [ { id: 'cpu', diff --git a/x-pack/plugins/infra/server/routes/snapshot/lib/transform_request_to_metrics_api_request.ts b/x-pack/plugins/infra/server/routes/snapshot/lib/transform_request_to_metrics_api_request.ts index 3901c8677ae9b..b7e389cae9126 100644 --- a/x-pack/plugins/infra/server/routes/snapshot/lib/transform_request_to_metrics_api_request.ts +++ b/x-pack/plugins/infra/server/routes/snapshot/lib/transform_request_to_metrics_api_request.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { TIMESTAMP_FIELD } from '../../../../common/constants'; import { findInventoryFields, findInventoryModel } from '../../../../common/inventory_models'; import { MetricsAPIRequest, SnapshotRequest } from '../../../../common/http_api'; import { ESSearchClient } from '../../../lib/metrics/types'; @@ -37,7 +38,6 @@ export const transformRequestToMetricsAPIRequest = async ({ const metricsApiRequest: MetricsAPIRequest = { indexPattern: sourceOverrides?.indexPattern ?? source.configuration.metricAlias, timerange: { - field: sourceOverrides?.timestamp ?? source.configuration.fields.timestamp, from: timeRangeWithIntervalApplied.from, to: timeRangeWithIntervalApplied.to, interval: timeRangeWithIntervalApplied.interval, @@ -69,10 +69,7 @@ export const transformRequestToMetricsAPIRequest = async ({ inventoryModel.nodeFilter?.forEach((f) => filters.push(f)); } - const inventoryFields = findInventoryFields( - snapshotRequest.nodeType, - source.configuration.fields - ); + const inventoryFields = findInventoryFields(snapshotRequest.nodeType); if (snapshotRequest.groupBy) { const groupBy = snapshotRequest.groupBy.map((g) => g.field).filter(Boolean) as string[]; metricsApiRequest.groupBy = [...groupBy, inventoryFields.id]; @@ -86,7 +83,7 @@ export const transformRequestToMetricsAPIRequest = async ({ size: 1, metrics: [{ field: inventoryFields.name }], sort: { - [source.configuration.fields.timestamp]: 'desc', + [TIMESTAMP_FIELD]: 'desc', }, }, }, diff --git a/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.test.ts b/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.test.ts index b0d2eeb987861..e48c990d7822f 100644 --- a/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.test.ts +++ b/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.test.ts @@ -289,12 +289,7 @@ const createSourceConfigurationMock = (): InfraSource => ({ }, ], fields: { - pod: 'POD_FIELD', - host: 'HOST_FIELD', - container: 'CONTAINER_FIELD', message: ['MESSAGE_FIELD'], - timestamp: 'TIMESTAMP_FIELD', - tiebreaker: 'TIEBREAKER_FIELD', }, anomalyThreshold: 20, }, diff --git a/x-pack/plugins/infra/server/services/log_entries/log_entry_search_strategy.test.ts b/x-pack/plugins/infra/server/services/log_entries/log_entry_search_strategy.test.ts index 1f03878ba6feb..685f11cb00a86 100644 --- a/x-pack/plugins/infra/server/services/log_entries/log_entry_search_strategy.test.ts +++ b/x-pack/plugins/infra/server/services/log_entries/log_entry_search_strategy.test.ts @@ -244,12 +244,7 @@ const createSourceConfigurationMock = (): InfraSource => ({ metricsExplorerDefaultView: 'DEFAULT_VIEW', logColumns: [], fields: { - pod: 'POD_FIELD', - host: 'HOST_FIELD', - container: 'CONTAINER_FIELD', message: ['MESSAGE_FIELD'], - timestamp: 'TIMESTAMP_FIELD', - tiebreaker: 'TIEBREAKER_FIELD', }, anomalyThreshold: 20, }, diff --git a/x-pack/plugins/infra/server/services/log_queries/get_log_query_fields.ts b/x-pack/plugins/infra/server/services/log_queries/get_log_query_fields.ts index 55491db97dbd6..db1696854db83 100644 --- a/x-pack/plugins/infra/server/services/log_queries/get_log_query_fields.ts +++ b/x-pack/plugins/infra/server/services/log_queries/get_log_query_fields.ts @@ -12,7 +12,6 @@ import { KibanaFramework } from '../../lib/adapters/framework/kibana_framework_a export interface LogQueryFields { indexPattern: string; - timestamp: string; } export const createGetLogQueryFields = (sources: InfraSources, framework: KibanaFramework) => { @@ -29,7 +28,6 @@ export const createGetLogQueryFields = (sources: InfraSources, framework: Kibana return { indexPattern: resolvedLogSourceConfiguration.indices, - timestamp: resolvedLogSourceConfiguration.timestampField, }; }; }; diff --git a/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts b/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts index 3357b1a842183..cb754153c6615 100644 --- a/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts +++ b/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { TIMESTAMP_FIELD } from '../../common/constants'; import { findInventoryModel } from '../../common/inventory_models'; // import { KibanaFramework } from '../lib/adapters/framework/kibana_framework_adapter'; import { InventoryItemType } from '../../common/inventory_models/types'; @@ -12,7 +13,6 @@ import { ESSearchClient } from '../lib/metrics/types'; interface Options { indexPattern: string; - timestampField: string; timerange: { from: number; to: number; @@ -44,7 +44,7 @@ export const calculateMetricInterval = async ( filter: [ { range: { - [options.timestampField]: { + [TIMESTAMP_FIELD]: { gte: from, lte: options.timerange.to, format: 'epoch_millis', diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/index.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/index.ts index 5c59e6c0e2449..0d63e9cd2462b 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/index.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/index.ts @@ -5,9 +5,11 @@ * 2.0. */ -export { ProcessorForm, ProcessorFormOnSubmitArg, OnSubmitHandler } from './processor_form'; +export type { ProcessorFormOnSubmitArg, OnSubmitHandler } from './processor_form'; +export { ProcessorForm } from './processor_form'; -export { ProcessorsTree, ProcessorInfo, OnActionHandler } from './processors_tree'; +export type { ProcessorInfo, OnActionHandler } from './processors_tree'; +export { ProcessorsTree } from './processors_tree'; export { PipelineProcessorsEditor } from './pipeline_processors_editor'; @@ -15,11 +17,13 @@ export { PipelineProcessorsEditorItem } from './pipeline_processors_editor_item' export { ProcessorRemoveModal } from './processor_remove_modal'; -export { OnDoneLoadJsonHandler, LoadFromJsonButton } from './load_from_json'; +export type { OnDoneLoadJsonHandler } from './load_from_json'; +export { LoadFromJsonButton } from './load_from_json'; export { TestPipelineActions } from './test_pipeline'; -export { PipelineProcessorsItemTooltip, Position } from './pipeline_processors_editor_item_tooltip'; +export type { Position } from './pipeline_processors_editor_item_tooltip'; +export { PipelineProcessorsItemTooltip } from './pipeline_processors_editor_item_tooltip'; export { ProcessorsEmptyPrompt } from './processors_empty_prompt'; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/load_from_json/index.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/load_from_json/index.ts index 2e89e4b907f07..1d8fd204b4583 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/load_from_json/index.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/load_from_json/index.ts @@ -6,4 +6,4 @@ */ export { LoadFromJsonButton } from './button'; -export { OnDoneLoadJsonHandler } from './modal_provider'; +export type { OnDoneLoadJsonHandler } from './modal_provider'; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/pipeline_processors_editor_item/index.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/pipeline_processors_editor_item/index.ts index a88f51cda2ebd..8b029747c1cbf 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/pipeline_processors_editor_item/index.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/pipeline_processors_editor_item/index.ts @@ -7,4 +7,4 @@ export { PipelineProcessorsEditorItem } from './pipeline_processors_editor_item.container'; -export { Handlers } from './types'; +export type { Handlers } from './types'; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/pipeline_processors_editor_item_tooltip/index.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/pipeline_processors_editor_item_tooltip/index.ts index e51d286a2b013..f8967a8945b2a 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/pipeline_processors_editor_item_tooltip/index.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/pipeline_processors_editor_item_tooltip/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { PipelineProcessorsItemTooltip, Position } from './pipeline_processors_editor_item_tooltip'; +export type { Position } from './pipeline_processors_editor_item_tooltip'; +export { PipelineProcessorsItemTooltip } from './pipeline_processors_editor_item_tooltip'; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/index.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/index.ts index 75c0e4ec7cccd..1418c919cb6b1 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/index.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/index.ts @@ -5,8 +5,5 @@ * 2.0. */ -export { - ProcessorFormContainer as ProcessorForm, - ProcessorFormOnSubmitArg, - OnSubmitHandler, -} from './processor_form.container'; +export type { ProcessorFormOnSubmitArg, OnSubmitHandler } from './processor_form.container'; +export { ProcessorFormContainer as ProcessorForm } from './processor_form.container'; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/index.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/index.ts index 1a2422b40d0b0..e3a0fae36e577 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/index.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/index.ts @@ -45,4 +45,4 @@ export { UrlDecode } from './url_decode'; export { UserAgent } from './user_agent'; export { UriParts } from './uri_parts'; -export { FormFieldsComponent } from './shared'; +export type { FormFieldsComponent } from './shared'; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processors_tree/index.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processors_tree/index.ts index e8ac8bce8c4c8..3cb4f1f0f3505 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processors_tree/index.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processors_tree/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { ProcessorsTree, OnActionHandler, ProcessorInfo } from './processors_tree'; +export type { OnActionHandler, ProcessorInfo } from './processors_tree'; +export { ProcessorsTree } from './processors_tree'; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/shared/index.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/shared/index.ts index d62ebab7c650c..8d71908bca5e4 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/shared/index.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/shared/index.ts @@ -5,10 +5,7 @@ * 2.0. */ -export { - getProcessorDescriptor, - mapProcessorTypeToDescriptor, - ProcessorType, -} from './map_processor_type_to_form'; +export type { ProcessorType } from './map_processor_type_to_form'; +export { getProcessorDescriptor, mapProcessorTypeToDescriptor } from './map_processor_type_to_form'; export { ErrorIcon, ErrorIgnoredIcon, SkippedIcon } from './status_icons'; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/test_pipeline/test_pipeline_tabs/index.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/test_pipeline/test_pipeline_tabs/index.ts index 725f65f28ab91..82ba99a438522 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/test_pipeline/test_pipeline_tabs/index.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/test_pipeline/test_pipeline_tabs/index.ts @@ -5,7 +5,8 @@ * 2.0. */ -export { Tabs, TestPipelineFlyoutTab } from './test_pipeline_tabs'; +export type { TestPipelineFlyoutTab } from './test_pipeline_tabs'; +export { Tabs } from './test_pipeline_tabs'; export { DocumentsTab } from './tab_documents'; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/context/index.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/context/index.ts index 261393e35a2bb..6a83b29dc0d06 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/context/index.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/context/index.ts @@ -7,15 +7,11 @@ export { ProcessorsEditorContextProvider } from './context'; -export { - TestPipelineContextProvider, - useTestPipelineContext, - TestPipelineData, - TestPipelineContext, -} from './test_pipeline_context'; +export type { TestPipelineData, TestPipelineContext } from './test_pipeline_context'; +export { TestPipelineContextProvider, useTestPipelineContext } from './test_pipeline_context'; +export type { Props } from './processors_context'; export { PipelineProcessorsContextProvider, usePipelineProcessorsContext, - Props, } from './processors_context'; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/index.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/index.ts index 3149abeb8e1e6..a3996721ed748 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/index.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/index.ts @@ -5,12 +5,13 @@ * 2.0. */ -export { Props, ProcessorsEditorContextProvider } from './context'; +export type { Props } from './context'; +export { ProcessorsEditorContextProvider } from './context'; -export { OnUpdateHandlerArg, OnUpdateHandler } from './types'; +export type { OnUpdateHandlerArg, OnUpdateHandler } from './types'; -export { SerializeResult } from './serialize'; +export type { SerializeResult } from './serialize'; -export { OnDoneLoadJsonHandler } from './components'; +export type { OnDoneLoadJsonHandler } from './components'; export { PipelineEditor } from './pipeline_editor'; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/processors_reducer/index.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/processors_reducer/index.ts index 664e82e81a12c..59753e5cfdbba 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/processors_reducer/index.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/processors_reducer/index.ts @@ -5,13 +5,8 @@ * 2.0. */ -export { - State, - reducer, - useProcessorsState, - ProcessorsDispatch, - Action, -} from './processors_reducer'; +export type { State, ProcessorsDispatch, Action } from './processors_reducer'; +export { reducer, useProcessorsState } from './processors_reducer'; export * from './constants'; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/types.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/types.ts index efb2c4a42c763..fba905d8e26bf 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/types.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/types.ts @@ -31,7 +31,7 @@ export interface ProcessorInternal { onFailure?: ProcessorInternal[]; } -export { OnFormUpdateArg }; +export type { OnFormUpdateArg }; export interface FormValidityState { validate: OnFormUpdateArg['validate']; diff --git a/x-pack/plugins/ingest_pipelines/public/shared_imports.ts b/x-pack/plugins/ingest_pipelines/public/shared_imports.ts index 29be11430bf64..bcc0060c1e5d4 100644 --- a/x-pack/plugins/ingest_pipelines/public/shared_imports.ts +++ b/x-pack/plugins/ingest_pipelines/public/shared_imports.ts @@ -10,51 +10,55 @@ import { AppServices } from './application'; export { CodeEditor }; +export type { + Error, + SendRequestConfig, + SendRequestResponse, + UseRequestConfig, + OnJsonEditorUpdateHandler, +} from '../../../../src/plugins/es_ui_shared/public/'; export { AuthorizationProvider, - Error, NotAuthorizedSection, SectionError, SectionLoading, sendRequest, - SendRequestConfig, - SendRequestResponse, useAuthorizationContext, useRequest, - UseRequestConfig, WithPrivileges, XJson, JsonEditor, - OnJsonEditorUpdateHandler, attemptToURIDecode, } from '../../../../src/plugins/es_ui_shared/public/'; -export { +export type { FormSchema, - FIELD_TYPES, FormConfig, - useForm, - Form, - getUseField, ValidationFuncArg, FormData, - UseField, - UseArray, ArrayItem, FormHook, - useFormContext, - UseMultiFields, - FormDataProvider, OnFormUpdateArg, FieldConfig, FieldHook, - getFieldValidityAndErrorMessage, ValidationFunc, ValidationConfig, - useFormData, FormOptions, SerializerFunc, } from '../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; +export { + FIELD_TYPES, + useForm, + Form, + getUseField, + UseField, + UseArray, + useFormContext, + UseMultiFields, + FormDataProvider, + getFieldValidityAndErrorMessage, + useFormData, +} from '../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; export { fieldFormatters, diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.tsx index 427306cb54fb9..250359822e068 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.tsx @@ -336,6 +336,7 @@ export const ChartSwitch = memo(function ChartSwitch(props: Props) { {v.selection.dataLoss !== 'nothing' ? ( diff --git a/x-pack/plugins/lens/public/index.ts b/x-pack/plugins/lens/public/index.ts index 9be07a4f44dcd..fb7cefb22d175 100644 --- a/x-pack/plugins/lens/public/index.ts +++ b/x-pack/plugins/lens/public/index.ts @@ -58,6 +58,6 @@ export type { } from './indexpattern_datasource/types'; export type { LensEmbeddableInput } from './embeddable'; -export { LensPublicStart } from './plugin'; +export type { LensPublicStart } from './plugin'; export const plugin = () => new LensPlugin(); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx index d90dc83bc1fef..bdcc0e621cc36 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx @@ -58,7 +58,8 @@ import { GeoFieldWorkspacePanel } from '../editor_frame_service/editor_frame/wor import { DraggingIdentifier } from '../drag_drop'; import { getStateTimeShiftWarningMessages } from './time_shift_utils'; -export { OperationType, IndexPatternColumn, deleteColumn } from './operations'; +export type { OperationType, IndexPatternColumn } from './operations'; +export { deleteColumn } from './operations'; export function columnToOperation(column: IndexPatternColumn, uniqueLabel?: string): Operation { const { dataType, label, isBucketed, scale } = column; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/index.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/index.ts index a7741bc60d646..1ffbdea00b775 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/index.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/calculations/index.ts @@ -5,17 +5,23 @@ * 2.0. */ -export { counterRateOperation, CounterRateIndexPatternColumn } from './counter_rate'; -export { cumulativeSumOperation, CumulativeSumIndexPatternColumn } from './cumulative_sum'; -export { derivativeOperation, DerivativeIndexPatternColumn } from './differences'; -export { movingAverageOperation, MovingAverageIndexPatternColumn } from './moving_average'; +export type { CounterRateIndexPatternColumn } from './counter_rate'; +export { counterRateOperation } from './counter_rate'; +export type { CumulativeSumIndexPatternColumn } from './cumulative_sum'; +export { cumulativeSumOperation } from './cumulative_sum'; +export type { DerivativeIndexPatternColumn } from './differences'; +export { derivativeOperation } from './differences'; +export type { MovingAverageIndexPatternColumn } from './moving_average'; +export { movingAverageOperation } from './moving_average'; +export type { + OverallSumIndexPatternColumn, + OverallMinIndexPatternColumn, + OverallMaxIndexPatternColumn, + OverallAverageIndexPatternColumn, +} from './overall_metric'; export { overallSumOperation, - OverallSumIndexPatternColumn, overallMinOperation, - OverallMinIndexPatternColumn, overallMaxOperation, - OverallMaxIndexPatternColumn, overallAverageOperation, - OverallAverageIndexPatternColumn, } from './overall_metric'; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/formula/index.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/formula/index.ts index bafde0d37b3e9..5ff0c4e2d4bd7 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/formula/index.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/formula/index.ts @@ -5,6 +5,8 @@ * 2.0. */ -export { formulaOperation, FormulaIndexPatternColumn } from './formula'; +export type { FormulaIndexPatternColumn } from './formula'; +export { formulaOperation } from './formula'; export { regenerateLayerFromAst } from './parse'; -export { mathOperation, MathIndexPatternColumn } from './math'; +export type { MathIndexPatternColumn } from './math'; +export { mathOperation } from './math'; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/index.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/index.ts index 0212c73f46879..392b2b135ca22 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/index.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/index.ts @@ -93,21 +93,21 @@ export type IndexPatternColumn = export type FieldBasedIndexPatternColumn = Extract; -export { IncompleteColumn } from './column_types'; +export type { IncompleteColumn } from './column_types'; -export { TermsIndexPatternColumn } from './terms'; -export { FiltersIndexPatternColumn } from './filters'; -export { CardinalityIndexPatternColumn } from './cardinality'; -export { PercentileIndexPatternColumn } from './percentile'; -export { +export type { TermsIndexPatternColumn } from './terms'; +export type { FiltersIndexPatternColumn } from './filters'; +export type { CardinalityIndexPatternColumn } from './cardinality'; +export type { PercentileIndexPatternColumn } from './percentile'; +export type { MinIndexPatternColumn, AvgIndexPatternColumn, SumIndexPatternColumn, MaxIndexPatternColumn, MedianIndexPatternColumn, } from './metrics'; -export { DateHistogramIndexPatternColumn } from './date_histogram'; -export { +export type { DateHistogramIndexPatternColumn } from './date_histogram'; +export type { CumulativeSumIndexPatternColumn, CounterRateIndexPatternColumn, DerivativeIndexPatternColumn, @@ -117,11 +117,11 @@ export { OverallMaxIndexPatternColumn, OverallAverageIndexPatternColumn, } from './calculations'; -export { CountIndexPatternColumn } from './count'; -export { LastValueIndexPatternColumn } from './last_value'; -export { RangeIndexPatternColumn } from './ranges'; -export { FormulaIndexPatternColumn, MathIndexPatternColumn } from './formula'; -export { StaticValueIndexPatternColumn } from './static_value'; +export type { CountIndexPatternColumn } from './count'; +export type { LastValueIndexPatternColumn } from './last_value'; +export type { RangeIndexPatternColumn } from './ranges'; +export type { FormulaIndexPatternColumn, MathIndexPatternColumn } from './formula'; +export type { StaticValueIndexPatternColumn } from './static_value'; // List of all operation definitions registered to this data source. // If you want to implement a new operation, add the definition to this array and diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/index.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/index.ts index 7899ce9efcedf..86add22b2b8ce 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/index.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/index.ts @@ -8,7 +8,7 @@ export * from './operations'; export * from './layer_helpers'; export * from './time_scale_utils'; -export { +export type { OperationType, IndexPatternColumn, FieldBasedIndexPatternColumn, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/types.ts b/x-pack/plugins/lens/public/indexpattern_datasource/types.ts index 588b259520272..515693b4dd5c8 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/types.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/types.ts @@ -11,7 +11,7 @@ import type { FieldSpec } from '../../../../../src/plugins/data/common'; import type { DragDropIdentifier } from '../drag_drop/providers'; import type { FieldFormatParams } from '../../../../../src/plugins/field_formats/common'; -export { +export type { FieldBasedIndexPatternColumn, IndexPatternColumn, OperationType, diff --git a/x-pack/plugins/lens/public/mocks/index.ts b/x-pack/plugins/lens/public/mocks/index.ts index 2dd32a1679f1b..e9f03cde2642e 100644 --- a/x-pack/plugins/lens/public/mocks/index.ts +++ b/x-pack/plugins/lens/public/mocks/index.ts @@ -16,12 +16,12 @@ export { datasourceMap, mockDatasourceMap, createMockDatasource } from './dataso export type { DatasourceMock } from './datasource_mock'; export { createExpressionRendererMock } from './expression_renderer_mock'; export { defaultDoc, exactMatchDoc, makeDefaultServices } from './services_mock'; +export type { MountStoreProps } from './store_mocks'; export { mockStoreDeps, mockDatasourceStates, defaultState, makeLensStore, - MountStoreProps, mountWithProvider, } from './store_mocks'; export { lensPluginMock } from './lens_plugin_mock'; diff --git a/x-pack/plugins/lens/public/shared_components/index.ts b/x-pack/plugins/lens/public/shared_components/index.ts index f268d6816910e..9ffddaa1a135b 100644 --- a/x-pack/plugins/lens/public/shared_components/index.ts +++ b/x-pack/plugins/lens/public/shared_components/index.ts @@ -6,7 +6,8 @@ */ export * from './empty_placeholder'; -export { ToolbarPopoverProps, ToolbarPopover } from './toolbar_popover'; +export type { ToolbarPopoverProps } from './toolbar_popover'; +export { ToolbarPopover } from './toolbar_popover'; export { LegendSettingsPopover } from './legend_settings_popover'; export { PalettePicker } from './palette_picker'; export { TooltipWrapper } from './tooltip_wrapper'; diff --git a/x-pack/plugins/license_management/public/application/index.tsx b/x-pack/plugins/license_management/public/application/index.tsx index a289a40e72da8..16b6ebb1afdf9 100644 --- a/x-pack/plugins/license_management/public/application/index.tsx +++ b/x-pack/plugins/license_management/public/application/index.tsx @@ -36,4 +36,4 @@ export const renderApp = (element: Element, dependencies: AppDependencies) => { }; }; -export { AppDependencies }; +export type { AppDependencies }; diff --git a/x-pack/plugins/license_management/public/index.ts b/x-pack/plugins/license_management/public/index.ts index d36a08a999f41..c63cab6f4ad09 100644 --- a/x-pack/plugins/license_management/public/index.ts +++ b/x-pack/plugins/license_management/public/index.ts @@ -9,5 +9,5 @@ import { PluginInitializerContext } from 'src/core/public'; import { LicenseManagementUIPlugin } from './plugin'; import './application/index.scss'; -export { LicenseManagementUIPluginSetup, LicenseManagementUIPluginStart } from './plugin'; +export type { LicenseManagementUIPluginSetup, LicenseManagementUIPluginStart } from './plugin'; export const plugin = (ctx: PluginInitializerContext) => new LicenseManagementUIPlugin(ctx); diff --git a/x-pack/plugins/lists/common/schemas/response/exception_export_details_schema.mock.ts b/x-pack/plugins/lists/common/schemas/response/exception_export_details_schema.mock.ts new file mode 100644 index 0000000000000..91b20a49213d6 --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/response/exception_export_details_schema.mock.ts @@ -0,0 +1,28 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ExportExceptionDetails } from '@kbn/securitysolution-io-ts-list-types'; + +export interface ExportExceptionDetailsMock { + listCount?: number; + missingListsCount?: number; + missingLists?: Array>; + itemCount?: number; + missingItemCount?: number; + missingItems?: Array>; +} + +export const getExceptionExportDetailsMock = ( + details?: ExportExceptionDetailsMock +): ExportExceptionDetails => ({ + exported_exception_list_count: details?.listCount ?? 0, + exported_exception_list_item_count: details?.itemCount ?? 0, + missing_exception_list_item_count: details?.missingItemCount ?? 0, + missing_exception_list_items: details?.missingItems ?? [], + missing_exception_lists: details?.missingLists ?? [], + missing_exception_lists_count: details?.missingListsCount ?? 0, +}); diff --git a/x-pack/plugins/lists/server/index.ts b/x-pack/plugins/lists/server/index.ts index 9f395cb0d94bc..d8e13e86329c1 100644 --- a/x-pack/plugins/lists/server/index.ts +++ b/x-pack/plugins/lists/server/index.ts @@ -12,7 +12,7 @@ import { ListPlugin } from './plugin'; // exporting these since its required at top level in siem plugin export { ListClient } from './services/lists/list_client'; -export { +export type { CreateExceptionListItemOptions, UpdateExceptionListItemOptions, } from './services/exception_lists/exception_list_client_types'; diff --git a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts b/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts index 14de474974c11..d6edf83428587 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts @@ -15,6 +15,7 @@ import type { ExceptionListItemTypeOrUndefined, ExceptionListType, ExceptionListTypeOrUndefined, + ExportExceptionDetails, FilterOrUndefined, Id, IdOrUndefined, @@ -229,12 +230,5 @@ export interface ExportExceptionListAndItemsOptions { export interface ExportExceptionListAndItemsReturn { exportData: string; - exportDetails: { - exported_exception_list_count: number; - exported_exception_list_item_count: number; - missing_exception_list_item_count: number; - missing_exception_list_items: string[]; - missing_exception_lists: string[]; - missing_exception_lists_count: number; - }; + exportDetails: ExportExceptionDetails; } diff --git a/x-pack/plugins/lists/server/services/exception_lists/export_exception_list_and_items.ts b/x-pack/plugins/lists/server/services/exception_lists/export_exception_list_and_items.ts index 46b3df4e5ac44..b071c72a9b122 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/export_exception_list_and_items.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/export_exception_list_and_items.ts @@ -6,6 +6,7 @@ */ import type { + ExportExceptionDetails, IdOrUndefined, ListIdOrUndefined, NamespaceType, @@ -25,14 +26,7 @@ interface ExportExceptionListAndItemsOptions { export interface ExportExceptionListAndItemsReturn { exportData: string; - exportDetails: { - exported_exception_list_count: number; - exported_exception_list_item_count: number; - missing_exception_list_item_count: number; - missing_exception_list_items: string[]; - missing_exception_lists: string[]; - missing_exception_lists_count: number; - }; + exportDetails: ExportExceptionDetails; } export const exportExceptionListAndItems = async ({ diff --git a/x-pack/plugins/maps/common/elasticsearch_util/index.ts b/x-pack/plugins/maps/common/elasticsearch_util/index.ts index 6febb237cdda7..b5b20d70a7c76 100644 --- a/x-pack/plugins/maps/common/elasticsearch_util/index.ts +++ b/x-pack/plugins/maps/common/elasticsearch_util/index.ts @@ -9,4 +9,5 @@ export * from './es_agg_utils'; export * from './elasticsearch_geo_utils'; export * from './spatial_filter_utils'; export * from './types'; -export { isTotalHitsGreaterThan, TotalHits } from './total_hits'; +export type { TotalHits } from './total_hits'; +export { isTotalHitsGreaterThan } from './total_hits'; diff --git a/x-pack/plugins/maps/common/index.ts b/x-pack/plugins/maps/common/index.ts index 8374a4d0dbaa3..517ed0bceff10 100644 --- a/x-pack/plugins/maps/common/index.ts +++ b/x-pack/plugins/maps/common/index.ts @@ -19,7 +19,7 @@ export { SYMBOLIZE_AS_TYPES, } from './constants'; -export { +export type { EMSFileSourceDescriptor, ESTermSourceDescriptor, LayerDescriptor, diff --git a/x-pack/plugins/maps/public/actions/index.ts b/x-pack/plugins/maps/public/actions/index.ts index 4c869698d5ac1..f4d6997333c6c 100644 --- a/x-pack/plugins/maps/public/actions/index.ts +++ b/x-pack/plugins/maps/public/actions/index.ts @@ -10,9 +10,9 @@ export * from './ui_actions'; export * from './map_actions'; export * from './map_action_constants'; export * from './layer_actions'; +export type { DataRequestContext } from './data_request_actions'; export { cancelAllInFlightRequests, - DataRequestContext, fitToLayerExtent, fitToDataBounds, } from './data_request_actions'; diff --git a/x-pack/plugins/maps/public/api/index.ts b/x-pack/plugins/maps/public/api/index.ts index 9cf7577f448be..0bbeca6f8160d 100644 --- a/x-pack/plugins/maps/public/api/index.ts +++ b/x-pack/plugins/maps/public/api/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -export { MapsStartApi } from './start_api'; -export { MapsSetupApi } from './setup_api'; +export type { MapsStartApi } from './start_api'; +export type { MapsSetupApi } from './setup_api'; export { createLayerDescriptors } from './create_layer_descriptors'; export { suggestEMSTermJoinConfig } from './ems'; diff --git a/x-pack/plugins/maps/public/classes/fields/agg/index.ts b/x-pack/plugins/maps/public/classes/fields/agg/index.ts index f8de2db85db91..bd0b5184fe157 100644 --- a/x-pack/plugins/maps/public/classes/fields/agg/index.ts +++ b/x-pack/plugins/maps/public/classes/fields/agg/index.ts @@ -6,4 +6,4 @@ */ export { esAggFieldsFactory } from './es_agg_factory'; -export { IESAggField } from './agg_field_types'; +export type { IESAggField } from './agg_field_types'; diff --git a/x-pack/plugins/maps/public/classes/layers/vector_layer/index.ts b/x-pack/plugins/maps/public/classes/layers/vector_layer/index.ts index cb964f77613da..2b14b78f92946 100644 --- a/x-pack/plugins/maps/public/classes/layers/vector_layer/index.ts +++ b/x-pack/plugins/maps/public/classes/layers/vector_layer/index.ts @@ -6,10 +6,5 @@ */ export { addGeoJsonMbSource, getVectorSourceBounds, syncVectorSource } from './utils'; -export { - isVectorLayer, - IVectorLayer, - VectorLayer, - VectorLayerArguments, - NO_RESULTS_ICON_AND_TOOLTIPCONTENT, -} from './vector_layer'; +export type { IVectorLayer, VectorLayerArguments } from './vector_layer'; +export { isVectorLayer, VectorLayer, NO_RESULTS_ICON_AND_TOOLTIPCONTENT } from './vector_layer'; diff --git a/x-pack/plugins/maps/public/classes/sources/ems_file_source/index.ts b/x-pack/plugins/maps/public/classes/sources/ems_file_source/index.ts index 2d4d59c5c4159..6c9d7060e9a4b 100644 --- a/x-pack/plugins/maps/public/classes/sources/ems_file_source/index.ts +++ b/x-pack/plugins/maps/public/classes/sources/ems_file_source/index.ts @@ -6,4 +6,5 @@ */ export { emsBoundariesLayerWizardConfig } from './ems_boundaries_layer_wizard'; -export { EMSFileSource, IEmsFileSource } from './ems_file_source'; +export type { IEmsFileSource } from './ems_file_source'; +export { EMSFileSource } from './ems_file_source'; diff --git a/x-pack/plugins/maps/public/classes/sources/es_search_source/index.ts b/x-pack/plugins/maps/public/classes/sources/es_search_source/index.ts index 75217c0a29c08..54686f91c133d 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_search_source/index.ts +++ b/x-pack/plugins/maps/public/classes/sources/es_search_source/index.ts @@ -5,7 +5,8 @@ * 2.0. */ -export { createLayerDescriptor, CreateLayerDescriptorParams } from './create_layer_descriptor'; +export type { CreateLayerDescriptorParams } from './create_layer_descriptor'; +export { createLayerDescriptor } from './create_layer_descriptor'; export { ESSearchSource } from './es_search_source'; export { createDefaultLayerDescriptor, diff --git a/x-pack/plugins/maps/public/classes/sources/term_join_source/index.ts b/x-pack/plugins/maps/public/classes/sources/term_join_source/index.ts index a40533d98be87..78f7705104f73 100644 --- a/x-pack/plugins/maps/public/classes/sources/term_join_source/index.ts +++ b/x-pack/plugins/maps/public/classes/sources/term_join_source/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export { ITermJoinSource } from './term_join_source'; +export type { ITermJoinSource } from './term_join_source'; diff --git a/x-pack/plugins/maps/public/classes/sources/tiled_single_layer_vector_source/index.ts b/x-pack/plugins/maps/public/classes/sources/tiled_single_layer_vector_source/index.ts index 30177751a8d55..c60cedba61c83 100644 --- a/x-pack/plugins/maps/public/classes/sources/tiled_single_layer_vector_source/index.ts +++ b/x-pack/plugins/maps/public/classes/sources/tiled_single_layer_vector_source/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export { ITiledSingleLayerVectorSource } from './tiled_single_layer_vector_source'; +export type { ITiledSingleLayerVectorSource } from './tiled_single_layer_vector_source'; diff --git a/x-pack/plugins/maps/public/connected_components/edit_layer_panel/join_editor/index.ts b/x-pack/plugins/maps/public/connected_components/edit_layer_panel/join_editor/index.ts index 7971017a3d52b..570c1ba8fb896 100644 --- a/x-pack/plugins/maps/public/connected_components/edit_layer_panel/join_editor/index.ts +++ b/x-pack/plugins/maps/public/connected_components/edit_layer_panel/join_editor/index.ts @@ -31,4 +31,4 @@ function mapDispatchToProps(dispatch: ThunkDispatch + onClick={blurButtonOnClick(() => { influencerFilter( influencer.influencerFieldName, influencer.influencerFieldValue, '+' - ) - } + ); + })} iconType="plusInCircle" aria-label={i18n.translate( 'xpack.ml.anomaliesTable.influencersCell.addFilterAriaLabel', @@ -86,13 +87,13 @@ export class InfluencersCell extends Component { + onClick={blurButtonOnClick(() => { influencerFilter( influencer.influencerFieldName, influencer.influencerFieldValue, '-' - ) - } + ); + })} iconType="minusInCircle" aria-label={i18n.translate( 'xpack.ml.anomaliesTable.influencersCell.removeFilterAriaLabel', diff --git a/x-pack/plugins/ml/public/application/components/color_range_legend/index.ts b/x-pack/plugins/ml/public/application/components/color_range_legend/index.ts index 37495d0ef739e..e72a835cb1f63 100644 --- a/x-pack/plugins/ml/public/application/components/color_range_legend/index.ts +++ b/x-pack/plugins/ml/public/application/components/color_range_legend/index.ts @@ -6,6 +6,7 @@ */ export { ColorRangeLegend } from './color_range_legend'; +export type { EuiThemeType } from './use_color_range'; export { colorRangeOptions, colorRangeScaleOptions, @@ -13,5 +14,4 @@ export { COLOR_RANGE, COLOR_RANGE_SCALE, useCurrentEuiTheme, - EuiThemeType, } from './use_color_range'; diff --git a/x-pack/plugins/ml/public/application/components/data_grid/index.ts b/x-pack/plugins/ml/public/application/components/data_grid/index.ts index 481ff432e0156..b2bd1ff228923 100644 --- a/x-pack/plugins/ml/public/application/components/data_grid/index.ts +++ b/x-pack/plugins/ml/public/application/components/data_grid/index.ts @@ -19,7 +19,7 @@ export { export { getFieldType } from './use_column_chart'; export { useDataGrid } from './use_data_grid'; export { DataGrid } from './data_grid'; -export { +export type { DataGridItem, EsSorting, RenderCellValue, diff --git a/x-pack/plugins/ml/public/application/components/entity_cell/entity_cell.tsx b/x-pack/plugins/ml/public/application/components/entity_cell/entity_cell.tsx index a79c8a63b3bc6..f4a3b6dbf69c4 100644 --- a/x-pack/plugins/ml/public/application/components/entity_cell/entity_cell.tsx +++ b/x-pack/plugins/ml/public/application/components/entity_cell/entity_cell.tsx @@ -13,6 +13,7 @@ import { i18n } from '@kbn/i18n'; import { EMPTY_FIELD_VALUE_LABEL } from '../../timeseriesexplorer/components/entity_control/entity_control'; import { MLCATEGORY } from '../../../../common/constants/field_types'; import { ENTITY_FIELD_OPERATIONS } from '../../../../common/util/anomaly_utils'; +import { blurButtonOnClick } from '../../util/component_utils'; export type EntityCellFilter = ( entityName: string, @@ -41,7 +42,9 @@ function getAddFilter({ entityName, entityValue, filter }: EntityCellProps) { filter(entityName, entityValue, ENTITY_FIELD_OPERATIONS.ADD)} + onClick={blurButtonOnClick(() => { + filter(entityName, entityValue, ENTITY_FIELD_OPERATIONS.ADD); + })} iconType="plusInCircle" aria-label={i18n.translate('xpack.ml.anomaliesTable.entityCell.addFilterAriaLabel', { defaultMessage: 'Add filter', @@ -66,7 +69,9 @@ function getRemoveFilter({ entityName, entityValue, filter }: EntityCellProps) { filter(entityName, entityValue, ENTITY_FIELD_OPERATIONS.REMOVE)} + onClick={blurButtonOnClick(() => { + filter(entityName, entityValue, ENTITY_FIELD_OPERATIONS.REMOVE); + })} iconType="minusInCircle" aria-label={i18n.translate('xpack.ml.anomaliesTable.entityCell.removeFilterAriaLabel', { defaultMessage: 'Remove filter', diff --git a/x-pack/plugins/ml/public/application/components/entity_cell/index.ts b/x-pack/plugins/ml/public/application/components/entity_cell/index.ts index d29e2adf66bfe..e0d57bce48514 100644 --- a/x-pack/plugins/ml/public/application/components/entity_cell/index.ts +++ b/x-pack/plugins/ml/public/application/components/entity_cell/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { EntityCell, EntityCellFilter } from './entity_cell'; +export type { EntityCellFilter } from './entity_cell'; +export { EntityCell } from './entity_cell'; diff --git a/x-pack/plugins/ml/public/application/components/full_time_range_selector/index.tsx b/x-pack/plugins/ml/public/application/components/full_time_range_selector/index.tsx index c79df59ee3f69..14ad77e2adc3a 100644 --- a/x-pack/plugins/ml/public/application/components/full_time_range_selector/index.tsx +++ b/x-pack/plugins/ml/public/application/components/full_time_range_selector/index.tsx @@ -6,4 +6,5 @@ */ export { FullTimeRangeSelector } from './full_time_range_selector'; -export { getTimeFilterRange, TimeRange } from './full_time_range_selector_service'; +export type { TimeRange } from './full_time_range_selector_service'; +export { getTimeFilterRange } from './full_time_range_selector_service'; diff --git a/x-pack/plugins/ml/public/application/components/multi_select_picker/index.ts b/x-pack/plugins/ml/public/application/components/multi_select_picker/index.ts index 9d32228e1c4bc..a42ce68d9aa10 100644 --- a/x-pack/plugins/ml/public/application/components/multi_select_picker/index.ts +++ b/x-pack/plugins/ml/public/application/components/multi_select_picker/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { MultiSelectPicker, Option } from './multi_select_picker'; +export type { Option } from './multi_select_picker'; +export { MultiSelectPicker } from './multi_select_picker'; diff --git a/x-pack/plugins/ml/public/application/components/scatterplot_matrix/index.ts b/x-pack/plugins/ml/public/application/components/scatterplot_matrix/index.ts index 216b0d8d5e992..7f7642732b2e2 100644 --- a/x-pack/plugins/ml/public/application/components/scatterplot_matrix/index.ts +++ b/x-pack/plugins/ml/public/application/components/scatterplot_matrix/index.ts @@ -6,4 +6,5 @@ */ export { useScatterplotFieldOptions } from './use_scatterplot_field_options'; -export { ScatterplotMatrix, ScatterplotMatrixProps } from './scatterplot_matrix'; +export type { ScatterplotMatrixProps } from './scatterplot_matrix'; +export { ScatterplotMatrix } from './scatterplot_matrix'; diff --git a/x-pack/plugins/ml/public/application/components/stats_bar/index.ts b/x-pack/plugins/ml/public/application/components/stats_bar/index.ts index c3c44477e7f91..e1638c90c9e49 100644 --- a/x-pack/plugins/ml/public/application/components/stats_bar/index.ts +++ b/x-pack/plugins/ml/public/application/components/stats_bar/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { StatsBar, AnalyticStatsBarStats, JobStatsBarStats, ModelsBarStats } from './stats_bar'; +export type { AnalyticStatsBarStats, JobStatsBarStats, ModelsBarStats } from './stats_bar'; +export { StatsBar } from './stats_bar'; diff --git a/x-pack/plugins/ml/public/application/contexts/kibana/index.ts b/x-pack/plugins/ml/public/application/contexts/kibana/index.ts index 7331ebe34e915..0873d395f0b79 100644 --- a/x-pack/plugins/ml/public/application/contexts/kibana/index.ts +++ b/x-pack/plugins/ml/public/application/contexts/kibana/index.ts @@ -5,8 +5,10 @@ * 2.0. */ -export { useMlKibana, StartServices, MlKibanaReactContextValue } from './kibana_context'; -export { useNavigateToPath, NavigateToPath } from './use_navigate_to_path'; +export type { StartServices, MlKibanaReactContextValue } from './kibana_context'; +export { useMlKibana } from './kibana_context'; +export type { NavigateToPath } from './use_navigate_to_path'; +export { useNavigateToPath } from './use_navigate_to_path'; export { useUiSettings } from './use_ui_settings_context'; export { useTimefilter } from './use_timefilter'; export { useNotifications } from './use_notifications_context'; diff --git a/x-pack/plugins/ml/public/application/contexts/ml/index.ts b/x-pack/plugins/ml/public/application/contexts/ml/index.ts index 20d5dca4e6c18..a5ca1ded4f1ae 100644 --- a/x-pack/plugins/ml/public/application/contexts/ml/index.ts +++ b/x-pack/plugins/ml/public/application/contexts/ml/index.ts @@ -5,5 +5,6 @@ * 2.0. */ -export { MlContext, MlContextValue, SavedSearchQuery } from './ml_context'; +export type { MlContextValue, SavedSearchQuery } from './ml_context'; +export { MlContext } from './ml_context'; export { useMlContext } from './use_ml_context'; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/index.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/index.ts index 54372b5f6afc7..2fb0daa1ed45e 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/index.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/index.ts @@ -5,6 +5,13 @@ * 2.0. */ +export type { + UpdateDataFrameAnalyticsConfig, + IndexPattern, + RegressionEvaluateResponse, + Eval, + SearchQuery, +} from './analytics'; export { getAnalysisType, getDependentVar, @@ -13,38 +20,26 @@ export { isOutlierAnalysis, refreshAnalyticsList$, useRefreshAnalyticsList, - UpdateDataFrameAnalyticsConfig, - IndexPattern, REFRESH_ANALYTICS_LIST_STATE, OUTLIER_ANALYSIS_METHOD, - RegressionEvaluateResponse, getValuesFromResponse, loadEvalData, loadDocsCount, - Eval, getPredictedFieldName, INDEX_STATUS, SEARCH_SIZE, defaultSearchQuery, - SearchQuery, ANALYSIS_CONFIG_TYPE, } from './analytics'; -export { - getDefaultFieldsFromJobCaps, - sortExplorationResultsFields, - EsId, - EsDoc, - EsDocSource, - EsFieldName, - MAX_COLUMNS, -} from './fields'; +export type { EsId, EsDoc, EsDocSource, EsFieldName } from './fields'; +export { getDefaultFieldsFromJobCaps, sortExplorationResultsFields, MAX_COLUMNS } from './fields'; export { getIndexData } from './get_index_data'; export { getIndexFields } from './get_index_fields'; export { getScatterplotMatrixLegendType } from './get_scatterplot_matrix_legend_type'; export { useResultsViewConfig } from './use_results_view_config'; -export { DataFrameAnalyticsConfig } from '../../../../common/types/data_frame_analytics'; -export { DataFrameAnalyticsId } from '../../../../common/types/data_frame_analytics'; -export { IndexName } from '../../../../common/types/data_frame_analytics'; +export type { DataFrameAnalyticsConfig } from '../../../../common/types/data_frame_analytics'; +export type { DataFrameAnalyticsId } from '../../../../common/types/data_frame_analytics'; +export type { IndexName } from '../../../../common/types/data_frame_analytics'; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/expandable_section/index.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/expandable_section/index.ts index c8ea83aa489ce..8979a350294a5 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/expandable_section/index.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/expandable_section/index.ts @@ -5,11 +5,8 @@ * 2.0. */ -export { - ExpandableSection, - ExpandableSectionProps, - HEADER_ITEMS_LOADING, -} from './expandable_section'; +export type { ExpandableSectionProps } from './expandable_section'; +export { ExpandableSection, HEADER_ITEMS_LOADING } from './expandable_section'; export { ExpandableSectionAnalytics } from './expandable_section_analytics'; export { ExpandableSectionResults } from './expandable_section_results'; export { ExpandableSectionSplom } from './expandable_section_splom'; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_page_wrapper/index.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_page_wrapper/index.ts index c91301942daa8..75d9c1e89affc 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_page_wrapper/index.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_page_wrapper/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { EvaluatePanelProps, ExplorationPageWrapper } from './exploration_page_wrapper'; +export type { EvaluatePanelProps } from './exploration_page_wrapper'; +export { ExplorationPageWrapper } from './exploration_page_wrapper'; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_clone/index.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_clone/index.ts index 12d5b4be9ac6c..ba26d84d6a475 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_clone/index.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_clone/index.ts @@ -5,9 +5,6 @@ * 2.0. */ -export { - extractCloningConfig, - isAdvancedConfig, - CloneDataFrameAnalyticsConfig, -} from './clone_action_name'; +export type { CloneDataFrameAnalyticsConfig } from './clone_action_name'; +export { extractCloningConfig, isAdvancedConfig } from './clone_action_name'; export { useCloneAction } from './use_clone_action'; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/common.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/common.ts index 1be9186a8468c..78e5a80b4cc4c 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/common.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/common.ts @@ -10,7 +10,7 @@ import { EuiTableActionsColumnType, Query, Ast } from '@elastic/eui'; import { DATA_FRAME_TASK_STATE } from '../../../../../../../common/constants/data_frame_analytics'; import { DataFrameTaskStateType } from '../../../../../../../common/types/data_frame_analytics'; export { DATA_FRAME_TASK_STATE }; -export { DataFrameTaskStateType }; +export type { DataFrameTaskStateType }; import { DataFrameAnalyticsId, DataFrameAnalyticsConfig } from '../../../../common'; import { @@ -18,7 +18,7 @@ import { DataFrameAnalyticsStats, } from '../../../../../../../common/types/data_frame_analytics'; -export { DataFrameAnalyticsStats } from '../../../../../../../common/types/data_frame_analytics'; +export type { DataFrameAnalyticsStats } from '../../../../../../../common/types/data_frame_analytics'; export enum DATA_FRAME_MODE { BATCH = 'batch', diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/index.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/index.ts index f07b06ada93cf..848b8f76ab14c 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/index.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/index.ts @@ -6,9 +6,9 @@ */ export { DEFAULT_NUM_TOP_FEATURE_IMPORTANCE_VALUES } from './state'; -export { +export type { AnalyticsCreationStep, - useCreateAnalyticsForm, CreateAnalyticsFormProps, CreateAnalyticsStepProps, } from './use_create_analytics_form'; +export { useCreateAnalyticsForm } from './use_create_analytics_form'; diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/file_datavisualizer.tsx b/x-pack/plugins/ml/public/application/datavisualizer/file_based/file_datavisualizer.tsx index 93c0291d4f9d4..90b152453cecb 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/file_datavisualizer.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/file_datavisualizer.tsx @@ -89,7 +89,7 @@ export const FileDataVisualizerPage: FC = () => { }, }); }, - canDisplay: async () => true, + canDisplay: async ({ indexPatternId }) => indexPatternId !== '', }, ], [] diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/components/explorer_chart_label/entity_filter/entity_filter.tsx b/x-pack/plugins/ml/public/application/explorer/explorer_charts/components/explorer_chart_label/entity_filter/entity_filter.tsx index 2ede9d380f3bf..66f4052a6952f 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/components/explorer_chart_label/entity_filter/entity_filter.tsx +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/components/explorer_chart_label/entity_filter/entity_filter.tsx @@ -12,6 +12,7 @@ import { ENTITY_FIELD_OPERATIONS, EntityFieldOperation, } from '../../../../../../../common/util/anomaly_utils'; +import { blurButtonOnClick } from '../../../../../util/component_utils'; import './_entity_filter.scss'; interface EntityFilterProps { @@ -41,13 +42,13 @@ export const EntityFilter: FC = ({ + onClick={blurButtonOnClick(() => { onFilter({ influencerFieldName, influencerFieldValue, action: ENTITY_FIELD_OPERATIONS.ADD, - }) - } + }); + })} iconType="plusInCircle" aria-label={i18n.translate('xpack.ml.entityFilter.addFilterAriaLabel', { defaultMessage: 'Add filter for {influencerFieldName} {influencerFieldValue}', @@ -66,13 +67,13 @@ export const EntityFilter: FC = ({ + onClick={blurButtonOnClick(() => { onFilter({ influencerFieldName, influencerFieldValue, action: ENTITY_FIELD_OPERATIONS.REMOVE, - }) - } + }); + })} iconType="minusInCircle" aria-label={i18n.translate('xpack.ml.entityFilter.removeFilterAriaLabel', { defaultMessage: 'Remove filter for {influencerFieldName} {influencerFieldValue}', diff --git a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/index.ts b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/index.ts index 91ae73628fd77..74b6c88fba8d4 100644 --- a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/index.ts +++ b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/index.ts @@ -7,4 +7,5 @@ export { getIndexPattern } from './get_index_pattern'; export { explorerReducer } from './reducer'; -export { getExplorerDefaultState, ExplorerState } from './state'; +export type { ExplorerState } from './state'; +export { getExplorerDefaultState } from './state'; diff --git a/x-pack/plugins/ml/public/application/explorer/reducers/index.ts b/x-pack/plugins/ml/public/application/explorer/reducers/index.ts index 6652bbf132d4e..db44d1864daa1 100644 --- a/x-pack/plugins/ml/public/application/explorer/reducers/index.ts +++ b/x-pack/plugins/ml/public/application/explorer/reducers/index.ts @@ -5,9 +5,5 @@ * 2.0. */ -export { - explorerReducer, - getExplorerDefaultState, - getIndexPattern, - ExplorerState, -} from './explorer_reducer'; +export type { ExplorerState } from './explorer_reducer'; +export { explorerReducer, getExplorerDefaultState, getIndexPattern } from './explorer_reducer'; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/chart_loader/index.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/chart_loader/index.ts index ee05f3777a515..f4932f4536add 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/chart_loader/index.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/chart_loader/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { ChartLoader, LineChartData, LineChartPoint } from './chart_loader'; +export type { LineChartData, LineChartPoint } from './chart_loader'; +export { ChartLoader } from './chart_loader'; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/components/index.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/components/index.ts index f8de9af407285..cabbdf302f87f 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/components/index.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/components/index.ts @@ -6,4 +6,5 @@ */ export { JobGroupsInput } from './job_groups_input'; -export { TimeRangePicker, TimeRange } from './time_range_picker'; +export type { TimeRange } from './time_range_picker'; +export { TimeRangePicker } from './time_range_picker'; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/index.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/index.ts index ec4e4c0e0c7ec..ccc26a3e0b6ae 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/index.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/index.ts @@ -12,8 +12,8 @@ export { PopulationJobCreator } from './population_job_creator'; export { AdvancedJobCreator } from './advanced_job_creator'; export { CategorizationJobCreator } from './categorization_job_creator'; export { RareJobCreator } from './rare_job_creator'; +export type { JobCreatorType } from './type_guards'; export { - JobCreatorType, isSingleMetricJobCreator, isMultiMetricJobCreator, isPopulationJobCreator, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/index.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/index.ts index 72460af14623d..2178086de5b91 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/index.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { JobRunner, ProgressSubscriber } from './job_runner'; +export type { ProgressSubscriber } from './job_runner'; +export { JobRunner } from './job_runner'; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/index.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/index.ts index 054fcbab0c7a8..71de7aa3724f1 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/index.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { JobValidator, Validation, BasicValidations, ValidationSummary } from './job_validator'; +export type { Validation, BasicValidations, ValidationSummary } from './job_validator'; +export { JobValidator } from './job_validator'; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/index.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/index.ts index 19c950439fdda..e13a74e76f5ba 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/index.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/index.ts @@ -5,5 +5,6 @@ * 2.0. */ -export { ResultsLoader, Results, ModelItem, Anomaly } from './results_loader'; +export type { Results, ModelItem, Anomaly } from './results_loader'; +export { ResultsLoader } from './results_loader'; export { CategorizationExamplesLoader } from './categorization_examples_loader'; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/index.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/index.tsx index 7758ec28f4bbf..75a331ce5d0eb 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/index.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/index.tsx @@ -5,4 +5,5 @@ * 2.0. */ -export { AdvancedDetectorModal, ModalPayload } from './advanced_detector_modal'; +export type { ModalPayload } from './advanced_detector_modal'; +export { AdvancedDetectorModal } from './advanced_detector_modal'; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/agg_select/index.ts b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/agg_select/index.ts index eefa14d903242..eecbacfaecccc 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/agg_select/index.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/agg_select/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { AggSelect, DropDownLabel, DropDownOption, DropDownProps, createLabel } from './agg_select'; +export type { DropDownLabel, DropDownOption, DropDownProps } from './agg_select'; +export { AggSelect, createLabel } from './agg_select'; diff --git a/x-pack/plugins/ml/public/application/routing/index.ts b/x-pack/plugins/ml/public/application/routing/index.ts index f4b076db7ab37..1aac673b5411c 100644 --- a/x-pack/plugins/ml/public/application/routing/index.ts +++ b/x-pack/plugins/ml/public/application/routing/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { MlRouter, MlRoute } from './router'; +export type { MlRoute } from './router'; +export { MlRouter } from './router'; diff --git a/x-pack/plugins/ml/public/application/services/toast_notification_service/index.ts b/x-pack/plugins/ml/public/application/services/toast_notification_service/index.ts index d303cef3203b6..d2f946777284d 100644 --- a/x-pack/plugins/ml/public/application/services/toast_notification_service/index.ts +++ b/x-pack/plugins/ml/public/application/services/toast_notification_service/index.ts @@ -5,8 +5,8 @@ * 2.0. */ +export type { ToastNotificationService } from './toast_notification_service'; export { - ToastNotificationService, toastNotificationServiceProvider, useToastNotificationService, getToastNotificationService, diff --git a/x-pack/plugins/ml/public/application/util/component_utils.ts b/x-pack/plugins/ml/public/application/util/component_utils.ts new file mode 100644 index 0000000000000..764e4f0edd83b --- /dev/null +++ b/x-pack/plugins/ml/public/application/util/component_utils.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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { MouseEvent } from 'react'; + +/** + * Removes focus from a button element when clicked, for example to + * ensure a wrapping tooltip is hidden on click. + */ +export const blurButtonOnClick = (callback: Function) => (event: MouseEvent) => { + (event.target as HTMLButtonElement).blur(); + callback(); +}; diff --git a/x-pack/plugins/ml/public/index.ts b/x-pack/plugins/ml/public/index.ts index 6af8b8a6c876d..4913969bf5483 100755 --- a/x-pack/plugins/ml/public/index.ts +++ b/x-pack/plugins/ml/public/index.ts @@ -54,7 +54,8 @@ export { export { ES_CLIENT_TOTAL_HITS_RELATION } from '../common/types/es_client'; export { ANOMALY_SEVERITY } from '../common'; -export { useMlHref, ML_PAGES, MlLocator, MlLocatorDefinition } from './locator'; +export type { MlLocator } from './locator'; +export { useMlHref, ML_PAGES, MlLocatorDefinition } from './locator'; // Bundled shared exports // Exported this way so the code doesn't end up in ML's page load bundle diff --git a/x-pack/plugins/ml/public/locator/ml_locator.ts b/x-pack/plugins/ml/public/locator/ml_locator.ts index f1bcd84e77d7d..7fa573c3e653d 100644 --- a/x-pack/plugins/ml/public/locator/ml_locator.ts +++ b/x-pack/plugins/ml/public/locator/ml_locator.ts @@ -28,7 +28,7 @@ import { } from './formatters'; import { formatTrainedModelsManagementUrl } from './formatters/trained_models'; -export { MlLocatorParams, MlLocator }; +export type { MlLocatorParams, MlLocator }; export class MlLocatorDefinition implements LocatorDefinition { public readonly id = ML_APP_LOCATOR; diff --git a/x-pack/plugins/ml/server/lib/capabilities/index.ts b/x-pack/plugins/ml/server/lib/capabilities/index.ts index 623ebe56085ff..7c27aee6bf4af 100644 --- a/x-pack/plugins/ml/server/lib/capabilities/index.ts +++ b/x-pack/plugins/ml/server/lib/capabilities/index.ts @@ -5,9 +5,6 @@ * 2.0. */ -export { - capabilitiesProvider, - hasMlCapabilitiesProvider, - HasMlCapabilities, -} from './check_capabilities'; +export type { HasMlCapabilities } from './check_capabilities'; +export { capabilitiesProvider, hasMlCapabilitiesProvider } from './check_capabilities'; export { setupCapabilitiesSwitcher } from './capabilities_switcher'; diff --git a/x-pack/plugins/ml/server/lib/ml_client/index.ts b/x-pack/plugins/ml/server/lib/ml_client/index.ts index 509b83ef1edf7..b5329ba2cfbca 100644 --- a/x-pack/plugins/ml/server/lib/ml_client/index.ts +++ b/x-pack/plugins/ml/server/lib/ml_client/index.ts @@ -7,4 +7,4 @@ export { getMlClient } from './ml_client'; export { MLJobNotFound } from './errors'; -export { MlClient } from './types'; +export type { MlClient } from './types'; diff --git a/x-pack/plugins/ml/server/models/calendar/index.ts b/x-pack/plugins/ml/server/models/calendar/index.ts index c5177dd675ca1..ca05246dff010 100644 --- a/x-pack/plugins/ml/server/models/calendar/index.ts +++ b/x-pack/plugins/ml/server/models/calendar/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { CalendarManager, Calendar, FormCalendar } from './calendar_manager'; +export type { Calendar, FormCalendar } from './calendar_manager'; +export { CalendarManager } from './calendar_manager'; diff --git a/x-pack/plugins/ml/server/models/data_frame_analytics/models_provider.ts b/x-pack/plugins/ml/server/models/data_frame_analytics/models_provider.ts index fb8480d621d55..2f40081f1458d 100644 --- a/x-pack/plugins/ml/server/models/data_frame_analytics/models_provider.ts +++ b/x-pack/plugins/ml/server/models/data_frame_analytics/models_provider.ts @@ -49,26 +49,31 @@ export function modelsProvider( modelIds.map((id: string) => [id, null]) ); - const { body, statusCode } = await client.asCurrentUser.ingest.getPipeline(); - - if (statusCode !== 200) { - return modelIdsMap; - } - - for (const [pipelineName, pipelineDefinition] of Object.entries(body)) { - const { processors } = pipelineDefinition as { processors: Array> }; - - for (const processor of processors) { - const id = processor.inference?.model_id; - if (modelIdsMap.has(id)) { - const obj = modelIdsMap.get(id); - if (obj === null) { - modelIdsMap.set(id, { [pipelineName]: pipelineDefinition }); - } else { - obj![pipelineName] = pipelineDefinition; + try { + const { body } = await client.asCurrentUser.ingest.getPipeline(); + + for (const [pipelineName, pipelineDefinition] of Object.entries(body)) { + const { processors } = pipelineDefinition as { processors: Array> }; + + for (const processor of processors) { + const id = processor.inference?.model_id; + if (modelIdsMap.has(id)) { + const obj = modelIdsMap.get(id); + if (obj === null) { + modelIdsMap.set(id, { [pipelineName]: pipelineDefinition }); + } else { + obj![pipelineName] = pipelineDefinition; + } } } } + } catch (error) { + if (error.statusCode === 404) { + // ES returns 404 when there are no pipelines + // Instead, we should return the modelIdsMap and a 200 + return modelIdsMap; + } + throw error; } return modelIdsMap; diff --git a/x-pack/plugins/ml/server/models/data_frame_analytics/types.ts b/x-pack/plugins/ml/server/models/data_frame_analytics/types.ts index c9cca5756ada6..216cfe50cc539 100644 --- a/x-pack/plugins/ml/server/models/data_frame_analytics/types.ts +++ b/x-pack/plugins/ml/server/models/data_frame_analytics/types.ts @@ -11,7 +11,7 @@ import { AnalyticsMapNodeElement, AnalyticsMapEdgeElement, } from '../../../common/types/data_frame_analytics'; -export { +export type { MapElements, AnalyticsMapReturnType, AnalyticsMapNodeElement, diff --git a/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts b/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts index 1cd9aae79777b..9e02a93a3c0f1 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts +++ b/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts @@ -293,6 +293,8 @@ export class DataRecognizer { index, size, body: searchBody, + // Ignored indices that are frozen + ignore_throttled: true, }); // @ts-expect-error incorrect search response type diff --git a/x-pack/plugins/ml/server/models/data_recognizer/index.ts b/x-pack/plugins/ml/server/models/data_recognizer/index.ts index fbddf17a50ede..55595c3a12bde 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/index.ts +++ b/x-pack/plugins/ml/server/models/data_recognizer/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { DataRecognizer, RecognizeResult, dataRecognizerFactory } from './data_recognizer'; +export type { RecognizeResult } from './data_recognizer'; +export { DataRecognizer, dataRecognizerFactory } from './data_recognizer'; diff --git a/x-pack/plugins/ml/server/models/filter/index.ts b/x-pack/plugins/ml/server/models/filter/index.ts index d5663478b4812..678fe73007ea2 100644 --- a/x-pack/plugins/ml/server/models/filter/index.ts +++ b/x-pack/plugins/ml/server/models/filter/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { FilterManager, FormFilter, UpdateFilter } from './filter_manager'; +export type { FormFilter, UpdateFilter } from './filter_manager'; +export { FilterManager } from './filter_manager'; diff --git a/x-pack/plugins/ml/server/saved_objects/index.ts b/x-pack/plugins/ml/server/saved_objects/index.ts index cbd31c9261130..652f47122ae2f 100644 --- a/x-pack/plugins/ml/server/saved_objects/index.ts +++ b/x-pack/plugins/ml/server/saved_objects/index.ts @@ -6,7 +6,8 @@ */ export { setupSavedObjects } from './saved_objects'; -export { JobObject, JobSavedObjectService, jobSavedObjectServiceFactory } from './service'; +export type { JobObject, JobSavedObjectService } from './service'; +export { jobSavedObjectServiceFactory } from './service'; export { checksFactory } from './checks'; export { syncSavedObjectsFactory } from './sync'; export { jobSavedObjectsInitializationFactory } from './initialization'; diff --git a/x-pack/plugins/ml/server/shared_services/index.ts b/x-pack/plugins/ml/server/shared_services/index.ts index 4126850918f6d..3a38b0b76bac6 100644 --- a/x-pack/plugins/ml/server/shared_services/index.ts +++ b/x-pack/plugins/ml/server/shared_services/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { SharedServices, createSharedServices } from './shared_services'; +export type { SharedServices } from './shared_services'; +export { createSharedServices } from './shared_services'; diff --git a/x-pack/plugins/ml/server/shared_services/license_checks/index.ts b/x-pack/plugins/ml/server/shared_services/license_checks/index.ts index 5939ff18a9376..9810084488cae 100644 --- a/x-pack/plugins/ml/server/shared_services/license_checks/index.ts +++ b/x-pack/plugins/ml/server/shared_services/license_checks/index.ts @@ -5,5 +5,6 @@ * 2.0. */ -export { LicenseCheck, licenseChecks } from './license_checks'; +export type { LicenseCheck } from './license_checks'; +export { licenseChecks } from './license_checks'; export { InsufficientBasicLicenseError, InsufficientFullLicenseError } from './errors'; diff --git a/x-pack/plugins/monitoring/public/types.ts b/x-pack/plugins/monitoring/public/types.ts index 4817ac235e2bd..fa92cfacafdcc 100644 --- a/x-pack/plugins/monitoring/public/types.ts +++ b/x-pack/plugins/monitoring/public/types.ts @@ -12,9 +12,9 @@ import { TriggersAndActionsUIPublicPluginStart } from '../../triggers_actions_ui import { UsageCollectionSetup } from '../../../../src/plugins/usage_collection/public'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths -export { MonitoringConfig } from '../server'; +export type { MonitoringConfig } from '../server'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths -export { MLJobs } from '../server/lib/elasticsearch/get_ml_jobs'; +export type { MLJobs } from '../server/lib/elasticsearch/get_ml_jobs'; export interface MonitoringStartPluginDependencies { navigation: NavigationStart; diff --git a/x-pack/plugins/monitoring/server/index.ts b/x-pack/plugins/monitoring/server/index.ts index 63cc61e503917..44aaff7d51c4a 100644 --- a/x-pack/plugins/monitoring/server/index.ts +++ b/x-pack/plugins/monitoring/server/index.ts @@ -11,9 +11,9 @@ import { MonitoringPlugin } from './plugin'; import { configSchema } from './config'; import { deprecations } from './deprecations'; -export { KibanaSettingsCollector } from './kibana_monitoring/collectors'; -export { MonitoringConfig } from './config'; -export { MonitoringPluginSetup, IBulkUploader } from './types'; +export type { KibanaSettingsCollector } from './kibana_monitoring/collectors'; +export type { MonitoringConfig } from './config'; +export type { MonitoringPluginSetup, IBulkUploader } from './types'; export const plugin = (initContext: PluginInitializerContext) => new MonitoringPlugin(initContext); export const config: PluginConfigDescriptor> = { diff --git a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/index.ts b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/index.ts index 06d47f0044728..9fa7ea8fdaf6a 100644 --- a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/index.ts +++ b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/index.ts @@ -11,7 +11,8 @@ import { getSettingsCollector } from './get_settings_collector'; import { getMonitoringUsageCollector } from './get_usage_collector'; import { MonitoringConfig } from '../../config'; -export { KibanaSettingsCollector, getKibanaSettings } from './get_settings_collector'; +export type { KibanaSettingsCollector } from './get_settings_collector'; +export { getKibanaSettings } from './get_settings_collector'; export function registerCollectors( usageCollection: UsageCollectionSetup, diff --git a/x-pack/plugins/monitoring/server/lib/elasticsearch/nodes/index.ts b/x-pack/plugins/monitoring/server/lib/elasticsearch/nodes/index.ts index 8f474c0284844..00f3370dfde51 100644 --- a/x-pack/plugins/monitoring/server/lib/elasticsearch/nodes/index.ts +++ b/x-pack/plugins/monitoring/server/lib/elasticsearch/nodes/index.ts @@ -7,6 +7,7 @@ export { getNodes } from './get_nodes'; export { getNodeSummary } from './get_node_summary'; -export { calculateNodeType, Node } from './calculate_node_type'; +export type { Node } from './calculate_node_type'; +export { calculateNodeType } from './calculate_node_type'; export { getNodeTypeClassLabel } from './get_node_type_class_label'; export { getDefaultNodeFromId } from './get_default_node_from_id'; diff --git a/x-pack/plugins/monitoring/server/lib/metrics/index.ts b/x-pack/plugins/monitoring/server/lib/metrics/index.ts index ba43a8c316d3b..2fdaeb81ee620 100644 --- a/x-pack/plugins/monitoring/server/lib/metrics/index.ts +++ b/x-pack/plugins/monitoring/server/lib/metrics/index.ts @@ -9,9 +9,11 @@ export { ElasticsearchMetric } from './elasticsearch/classes'; // @ts-ignore export { KibanaClusterMetric, KibanaMetric } from './kibana/classes'; -export { ApmMetric, ApmClusterMetric, ApmMetricFields } from './apm/classes'; +export type { ApmMetricFields } from './apm/classes'; +export { ApmMetric, ApmClusterMetric } from './apm/classes'; // @ts-ignore export { LogstashClusterMetric, LogstashMetric } from './logstash/classes'; -export { BeatsClusterMetric, BeatsMetric, BeatsMetricFields } from './beats/classes'; +export type { BeatsMetricFields } from './beats/classes'; +export { BeatsClusterMetric, BeatsMetric } from './beats/classes'; // @ts-ignore export { metrics } from './metrics'; diff --git a/x-pack/plugins/observability/public/context/has_data_context.test.tsx b/x-pack/plugins/observability/public/context/has_data_context.test.tsx index a586a8bf0bcce..1eb4108b12181 100644 --- a/x-pack/plugins/observability/public/context/has_data_context.test.tsx +++ b/x-pack/plugins/observability/public/context/has_data_context.test.tsx @@ -556,7 +556,7 @@ describe('HasDataContextProvider', () => { status: 'success', }, }, - hasAnyData: false, + hasAnyData: true, isAllRequestsComplete: true, forceUpdate: expect.any(String), onRefreshTimeRange: expect.any(Function), diff --git a/x-pack/plugins/observability/public/context/has_data_context.tsx b/x-pack/plugins/observability/public/context/has_data_context.tsx index caed130543acc..b6a45784a53b4 100644 --- a/x-pack/plugins/observability/public/context/has_data_context.tsx +++ b/x-pack/plugins/observability/public/context/has_data_context.tsx @@ -146,9 +146,12 @@ export function HasDataContextProvider({ children }: { children: React.ReactNode return appStatus !== undefined && appStatus !== FETCH_STATUS.LOADING; }); - const hasAnyData = (Object.keys(hasDataMap) as ObservabilityFetchDataPlugins[]).some( - (app) => hasDataMap[app]?.hasData === true - ); + const hasAnyData = (Object.keys(hasDataMap) as ObservabilityFetchDataPlugins[]).some((app) => { + const appHasData = hasDataMap[app]?.hasData; + return ( + appHasData === true || (Array.isArray(appHasData) && (appHasData as Alert[])?.length > 0) + ); + }); return ( ; -export { ObservabilityAPIReturnType }; +export type { ObservabilityAPIReturnType }; diff --git a/x-pack/plugins/observability/server/index.ts b/x-pack/plugins/observability/server/index.ts index 22a469dbedbdd..d4d7127d8baee 100644 --- a/x-pack/plugins/observability/server/index.ts +++ b/x-pack/plugins/observability/server/index.ts @@ -43,11 +43,5 @@ export type ObservabilityConfig = TypeOf; export const plugin = (initContext: PluginInitializerContext) => new ObservabilityPlugin(initContext); -export { - createOrUpdateIndex, - Mappings, - ObservabilityPluginSetup, - ScopedAnnotationsClient, - unwrapEsResponse, - WrappedElasticsearchClientError, -}; +export type { Mappings, ObservabilityPluginSetup, ScopedAnnotationsClient }; +export { createOrUpdateIndex, unwrapEsResponse, WrappedElasticsearchClientError }; diff --git a/x-pack/plugins/observability/server/routes/types.ts b/x-pack/plugins/observability/server/routes/types.ts index 5075b21fdf1fa..b316b1fffc770 100644 --- a/x-pack/plugins/observability/server/routes/types.ts +++ b/x-pack/plugins/observability/server/routes/types.ts @@ -17,7 +17,7 @@ import { RuleDataPluginService } from '../../../rule_registry/server'; import { ObservabilityServerRouteRepository } from './get_global_observability_server_route_repository'; import { ObservabilityRequestHandlerContext } from '../types'; -export { ObservabilityServerRouteRepository }; +export type { ObservabilityServerRouteRepository }; export interface ObservabilityRouteHandlerResources { core: { diff --git a/x-pack/plugins/observability/typings/common.ts b/x-pack/plugins/observability/typings/common.ts index 2bc95447d9203..368dd33f1f13f 100644 --- a/x-pack/plugins/observability/typings/common.ts +++ b/x-pack/plugins/observability/typings/common.ts @@ -23,6 +23,6 @@ export type PromiseReturnType = Func extends (...args: any[]) => Promise new RemoteClustersUIPlugin(initializerContext); diff --git a/x-pack/plugins/remote_clusters/public/types.ts b/x-pack/plugins/remote_clusters/public/types.ts index 15a34c84bb30c..bcd162599ab77 100644 --- a/x-pack/plugins/remote_clusters/public/types.ts +++ b/x-pack/plugins/remote_clusters/public/types.ts @@ -23,6 +23,6 @@ export interface ClientConfigType { }; } -export { RegisterManagementAppArgs }; +export type { RegisterManagementAppArgs }; -export { I18nStart }; +export type { I18nStart }; diff --git a/x-pack/plugins/remote_clusters/server/index.ts b/x-pack/plugins/remote_clusters/server/index.ts index 33be5d88a3e4b..9447f9d9209e3 100644 --- a/x-pack/plugins/remote_clusters/server/index.ts +++ b/x-pack/plugins/remote_clusters/server/index.ts @@ -9,6 +9,6 @@ import { PluginInitializerContext } from 'kibana/server'; import { RemoteClustersServerPlugin } from './plugin'; export { config } from './config'; -export { RemoteClustersPluginSetup } from './plugin'; +export type { RemoteClustersPluginSetup } from './plugin'; export const plugin = (ctx: PluginInitializerContext) => new RemoteClustersServerPlugin(ctx); diff --git a/x-pack/plugins/reporting/common/types/base.ts b/x-pack/plugins/reporting/common/types/base.ts new file mode 100644 index 0000000000000..44960c57f61c1 --- /dev/null +++ b/x-pack/plugins/reporting/common/types/base.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { Ensure, SerializableRecord } from '@kbn/utility-types'; +import type { LayoutParams } from './layout'; + +export type JobId = string; + +export type BaseParams = Ensure< + { + layout?: LayoutParams; + objectType: string; + title: string; + browserTimezone: string; // to format dates in the user's time zone + version: string; // to handle any state migrations + }, + SerializableRecord +>; + +// base params decorated with encrypted headers that come into runJob functions +export interface BasePayload extends BaseParams { + headers: string; + spaceId?: string; + isDeprecated?: boolean; +} diff --git a/x-pack/plugins/reporting/server/export_types/csv/types.d.ts b/x-pack/plugins/reporting/common/types/export_types/csv.ts similarity index 86% rename from x-pack/plugins/reporting/server/export_types/csv/types.d.ts rename to x-pack/plugins/reporting/common/types/export_types/csv.ts index fff6f0bcf9538..8249c129052d7 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/types.d.ts +++ b/x-pack/plugins/reporting/common/types/export_types/csv.ts @@ -5,8 +5,7 @@ * 2.0. */ -import type { FieldSpec } from 'src/plugins/data/common'; -import { BaseParams, BasePayload } from '../../types'; +import { BaseParams, BasePayload } from '../base'; export type RawValue = string | object | null | undefined; @@ -57,16 +56,6 @@ export interface SearchRequestDeprecatedCSV { | any; } -type FormatsMapDeprecatedCSV = Map< - string, - { - id: string; - params: { - pattern: string; - }; - } ->; - export interface SavedSearchGeneratorResultDeprecatedCSV { maxSizeReached: boolean; csvContainsFormulas?: boolean; diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource/types.d.ts b/x-pack/plugins/reporting/common/types/export_types/csv_searchsource.ts similarity index 81% rename from x-pack/plugins/reporting/server/export_types/csv_searchsource/types.d.ts rename to x-pack/plugins/reporting/common/types/export_types/csv_searchsource.ts index 170b03c2dfbff..2ba88426e8786 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_searchsource/types.d.ts +++ b/x-pack/plugins/reporting/common/types/export_types/csv_searchsource.ts @@ -6,9 +6,7 @@ */ import type { SearchSourceFields } from 'src/plugins/data/common'; -import type { BaseParams, BasePayload } from '../../types'; - -export type RawValue = string | object | null | undefined; +import type { BaseParams, BasePayload } from '../base'; interface BaseParamsCSV { searchSource: SearchSourceFields; diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/types.d.ts b/x-pack/plugins/reporting/common/types/export_types/csv_searchsource_immediate.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/types.d.ts rename to x-pack/plugins/reporting/common/types/export_types/csv_searchsource_immediate.ts diff --git a/x-pack/plugins/reporting/common/types/export_types/index.ts b/x-pack/plugins/reporting/common/types/export_types/index.ts new file mode 100644 index 0000000000000..0ad47e7414031 --- /dev/null +++ b/x-pack/plugins/reporting/common/types/export_types/index.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export * from './csv'; +export * from './csv_searchsource'; +export * from './csv_searchsource_immediate'; +export * from './png'; +export * from './png_v2'; +export * from './printable_pdf'; +export * from './printable_pdf_v2'; diff --git a/x-pack/plugins/reporting/server/export_types/png/types.d.ts b/x-pack/plugins/reporting/common/types/export_types/png.ts similarity index 84% rename from x-pack/plugins/reporting/server/export_types/png/types.d.ts rename to x-pack/plugins/reporting/common/types/export_types/png.ts index d266b5c849185..3b850b5bd8b33 100644 --- a/x-pack/plugins/reporting/server/export_types/png/types.d.ts +++ b/x-pack/plugins/reporting/common/types/export_types/png.ts @@ -5,8 +5,8 @@ * 2.0. */ -import { LayoutParams } from '../../lib/layouts'; -import { BaseParams, BasePayload } from '../../types'; +import type { LayoutParams } from '../layout'; +import type { BaseParams, BasePayload } from '../base'; interface BaseParamsPNG { layout: LayoutParams; diff --git a/x-pack/plugins/reporting/server/export_types/png_v2/types.d.ts b/x-pack/plugins/reporting/common/types/export_types/png_v2.ts similarity index 83% rename from x-pack/plugins/reporting/server/export_types/png_v2/types.d.ts rename to x-pack/plugins/reporting/common/types/export_types/png_v2.ts index 50c857b66934b..c937d01ce0be1 100644 --- a/x-pack/plugins/reporting/server/export_types/png_v2/types.d.ts +++ b/x-pack/plugins/reporting/common/types/export_types/png_v2.ts @@ -5,9 +5,9 @@ * 2.0. */ -import type { LocatorParams } from '../../../common/types'; -import type { LayoutParams } from '../../lib/layouts'; -import type { BaseParams, BasePayload } from '../../types'; +import type { LocatorParams } from '../url'; +import type { LayoutParams } from '../layout'; +import type { BaseParams, BasePayload } from '../base'; // Job params: structure of incoming user request data export interface JobParamsPNGV2 extends BaseParams { diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/types.d.ts b/x-pack/plugins/reporting/common/types/export_types/printable_pdf.ts similarity index 74% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/types.d.ts rename to x-pack/plugins/reporting/common/types/export_types/printable_pdf.ts index 8e4c45ad79506..a424706430f2c 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf/types.d.ts +++ b/x-pack/plugins/reporting/common/types/export_types/printable_pdf.ts @@ -5,8 +5,8 @@ * 2.0. */ -import { LayoutParams } from '../../lib/layouts'; -import { BaseParams, BasePayload } from '../../types'; +import type { LayoutParams } from '../layout'; +import type { BaseParams, BasePayload } from '../base'; interface BaseParamsPDF { layout: LayoutParams; @@ -17,6 +17,8 @@ interface BaseParamsPDF { // Job params: structure of incoming user request data, after being parsed from RISON export type JobParamsPDF = BaseParamsPDF & BaseParams; +export type JobAppParamsPDF = Omit; + // Job payload: structure of stored job data provided by create_job export interface TaskPayloadPDF extends BasePayload { layout: LayoutParams; @@ -24,8 +26,7 @@ export interface TaskPayloadPDF extends BasePayload { objects: Array<{ relativeUrl: string }>; } -type Legacy = Omit; -export interface JobParamsPDFLegacy extends Legacy { +export interface JobParamsPDFLegacy extends Omit { savedObjectId: string; queryString: string; } diff --git a/x-pack/plugins/reporting/common/types/export_types/printable_pdf_v2.ts b/x-pack/plugins/reporting/common/types/export_types/printable_pdf_v2.ts new file mode 100644 index 0000000000000..c9a7a2ce2331a --- /dev/null +++ b/x-pack/plugins/reporting/common/types/export_types/printable_pdf_v2.ts @@ -0,0 +1,33 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { LocatorParams } from '../url'; +import type { LayoutParams } from '../layout'; +import type { BaseParams, BasePayload } from '../base'; + +interface BaseParamsPDFV2 { + layout: LayoutParams; + + /** + * This value is used to re-create the same visual state as when the report was requested as well as navigate to the correct page. + */ + locatorParams: LocatorParams[]; +} + +// Job params: structure of incoming user request data, after being parsed from RISON +export type JobParamsPDFV2 = BaseParamsPDFV2 & BaseParams; + +export type JobAppParamsPDFV2 = Omit; + +// Job payload: structure of stored job data provided by create_job +export interface TaskPayloadPDFV2 extends BasePayload, BaseParamsPDFV2 { + layout: LayoutParams; + /** + * The value of forceNow is injected server-side every time a given report is generated. + */ + forceNow: string; +} diff --git a/x-pack/plugins/reporting/common/types.ts b/x-pack/plugins/reporting/common/types/index.ts similarity index 75% rename from x-pack/plugins/reporting/common/types.ts rename to x-pack/plugins/reporting/common/types/index.ts index fe018feab0f8b..75e8cb0af9698 100644 --- a/x-pack/plugins/reporting/common/types.ts +++ b/x-pack/plugins/reporting/common/types/index.ts @@ -5,7 +5,20 @@ * 2.0. */ -import type { Ensure, SerializableRecord } from '@kbn/utility-types'; +import type { Size, LayoutParams } from './layout'; +import type { JobId, BaseParams, BasePayload } from './base'; + +export type { JobId, BaseParams, BasePayload }; +export type { Size, LayoutParams }; +export type { + DownloadReportFn, + IlmPolicyMigrationStatus, + IlmPolicyStatusResponse, + LocatorParams, + ManagementLinkFn, + UrlOrUrlLocatorTuple, +} from './url'; +export * from './export_types'; export interface PageSizeParams { pageMarginTop: number; @@ -21,22 +34,6 @@ export interface PdfImageSize { height?: number; } -export type Size = Ensure< - { - width: number; - height: number; - }, - SerializableRecord ->; - -export type LayoutParams = Ensure< - { - id: string; - dimensions?: Size; - }, - SerializableRecord ->; - export interface ReportDocumentHead { _id: string; _index: string; @@ -56,24 +53,6 @@ export interface TaskRunResult { warnings?: string[]; } -export type BaseParams = Ensure< - { - layout?: LayoutParams; - objectType: string; - title: string; - browserTimezone: string; // to format dates in the user's time zone - version: string; // to handle any state migrations - }, - SerializableRecord ->; - -// base params decorated with encrypted headers that come into runJob functions -export interface BasePayload extends BaseParams { - headers: string; - spaceId?: string; - isDeprecated?: boolean; -} - export interface ReportSource { /* * Required fields: populated in RequestHandler.enqueueJob when the request comes in to @@ -119,8 +98,6 @@ export interface ReportDocument extends ReportDocumentHead { _source: ReportSource; } -export type JobId = string; - /* * JobStatus: * - Begins as 'pending' @@ -173,28 +150,3 @@ export interface JobSummarySet { completed: JobSummary[]; failed: JobSummary[]; } - -type DownloadLink = string; -export type DownloadReportFn = (jobId: JobId) => DownloadLink; - -type ManagementLink = string; -export type ManagementLinkFn = () => ManagementLink; - -export interface LocatorParams< - P extends SerializableRecord = SerializableRecord & { forceNow?: string } -> { - id: string; - version: string; - params: P; -} - -export type IlmPolicyMigrationStatus = 'policy-not-found' | 'indices-not-managed-by-policy' | 'ok'; - -export interface IlmPolicyStatusResponse { - status: IlmPolicyMigrationStatus; -} - -type Url = string; -type UrlLocatorTuple = [url: Url, locatorParams: LocatorParams]; - -export type UrlOrUrlLocatorTuple = Url | UrlLocatorTuple; diff --git a/x-pack/plugins/reporting/common/types/layout.ts b/x-pack/plugins/reporting/common/types/layout.ts new file mode 100644 index 0000000000000..b22d6b59d0873 --- /dev/null +++ b/x-pack/plugins/reporting/common/types/layout.ts @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { Ensure, SerializableRecord } from '@kbn/utility-types'; + +export type Size = Ensure< + { + width: number; + height: number; + }, + SerializableRecord +>; + +export type LayoutParams = Ensure< + { + id: string; + dimensions?: Size; + }, + SerializableRecord +>; diff --git a/x-pack/plugins/reporting/common/types/url.ts b/x-pack/plugins/reporting/common/types/url.ts new file mode 100644 index 0000000000000..dfb8ee9f908e3 --- /dev/null +++ b/x-pack/plugins/reporting/common/types/url.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import type { SerializableRecord } from '@kbn/utility-types'; +import type { JobId } from './base'; + +type DownloadLink = string; +export type DownloadReportFn = (jobId: JobId) => DownloadLink; + +type ManagementLink = string; +export type ManagementLinkFn = () => ManagementLink; + +export interface LocatorParams< + P extends SerializableRecord = SerializableRecord & { forceNow?: string } +> { + id: string; + version: string; + params: P; +} + +export type IlmPolicyMigrationStatus = 'policy-not-found' | 'indices-not-managed-by-policy' | 'ok'; + +export interface IlmPolicyStatusResponse { + status: IlmPolicyMigrationStatus; +} + +type Url = string; +type UrlLocatorTuple = [url: Url, locatorParams: LocatorParams]; + +export type UrlOrUrlLocatorTuple = Url | UrlLocatorTuple; diff --git a/x-pack/plugins/reporting/public/index.ts b/x-pack/plugins/reporting/public/index.ts index 2df236e6e3079..a634f87140e73 100644 --- a/x-pack/plugins/reporting/public/index.ts +++ b/x-pack/plugins/reporting/public/index.ts @@ -18,6 +18,17 @@ export interface ReportingSetup { export type ReportingStart = ReportingSetup; export { constants } from '../common'; +export type { + JobParamsCSV, + JobParamsDownloadCSV, + JobParamsPNG, + JobParamsPNGV2, + JobAppParamsPDFV2, + JobParamsPDF, + JobParamsPDFV2, + JobAppParamsPDF, +} from '../common/types'; + export { ReportingAPIClient, ReportingPublicPlugin as Plugin }; export function plugin(initializerContext: PluginInitializerContext) { diff --git a/x-pack/plugins/reporting/public/share_context_menu/reporting_panel_content/index.ts b/x-pack/plugins/reporting/public/share_context_menu/reporting_panel_content/index.ts index 843a0b6747e4c..94ee7f940b917 100644 --- a/x-pack/plugins/reporting/public/share_context_menu/reporting_panel_content/index.ts +++ b/x-pack/plugins/reporting/public/share_context_menu/reporting_panel_content/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { ReportingPanelContent, Props, ReportingPanelProps } from './reporting_panel_content'; +export type { Props, ReportingPanelProps } from './reporting_panel_content'; +export { ReportingPanelContent } from './reporting_panel_content'; diff --git a/x-pack/plugins/reporting/public/shared_imports.ts b/x-pack/plugins/reporting/public/shared_imports.ts index e719d720a7895..30e6cd12e3ed9 100644 --- a/x-pack/plugins/reporting/public/shared_imports.ts +++ b/x-pack/plugins/reporting/public/shared_imports.ts @@ -7,7 +7,8 @@ export type { SharePluginSetup, SharePluginStart, LocatorPublic } from 'src/plugins/share/public'; -export { useRequest, UseRequestResponse } from '../../../../src/plugins/es_ui_shared/public'; +export type { UseRequestResponse } from '../../../../src/plugins/es_ui_shared/public'; +export { useRequest } from '../../../../src/plugins/es_ui_shared/public'; export { KibanaContextProvider } from '../../../../src/plugins/kibana_react/public'; diff --git a/x-pack/plugins/reporting/server/config/__snapshots__/schema.test.ts.snap b/x-pack/plugins/reporting/server/config/__snapshots__/schema.test.ts.snap new file mode 100644 index 0000000000000..a384550f18462 --- /dev/null +++ b/x-pack/plugins/reporting/server/config/__snapshots__/schema.test.ts.snap @@ -0,0 +1,197 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Reporting Config Schema context {"dev":false,"dist":false} produces correct config 1`] = ` +Object { + "capture": Object { + "browser": Object { + "autoDownload": true, + "chromium": Object { + "proxy": Object { + "enabled": false, + }, + }, + "type": "chromium", + }, + "loadDelay": "PT3S", + "maxAttempts": 1, + "networkPolicy": Object { + "enabled": true, + "rules": Array [ + Object { + "allow": true, + "host": undefined, + "protocol": "http:", + }, + Object { + "allow": true, + "host": undefined, + "protocol": "https:", + }, + Object { + "allow": true, + "host": undefined, + "protocol": "ws:", + }, + Object { + "allow": true, + "host": undefined, + "protocol": "wss:", + }, + Object { + "allow": true, + "host": undefined, + "protocol": "data:", + }, + Object { + "allow": false, + "host": undefined, + "protocol": undefined, + }, + ], + }, + "timeouts": Object { + "openUrl": "PT1M", + "renderComplete": "PT30S", + "waitForElements": "PT30S", + }, + "zoom": 2, + }, + "csv": Object { + "checkForFormulas": true, + "enablePanelActionDownload": true, + "escapeFormulaValues": false, + "maxSizeBytes": ByteSizeValue { + "valueInBytes": 10485760, + }, + "scroll": Object { + "duration": "30s", + "size": 500, + }, + "useByteOrderMarkEncoding": false, + }, + "enabled": true, + "encryptionKey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "kibanaServer": Object {}, + "poll": Object { + "jobCompletionNotifier": Object { + "interval": 10000, + "intervalErrorMultiplier": 5, + }, + "jobsRefresh": Object { + "interval": 5000, + "intervalErrorMultiplier": 5, + }, + }, + "queue": Object { + "indexInterval": "week", + "pollEnabled": true, + "pollInterval": "PT3S", + "pollIntervalErrorMultiplier": 10, + "timeout": "PT2M", + }, + "roles": Object { + "allow": Array [ + "reporting_user", + ], + "enabled": true, + }, +} +`; + +exports[`Reporting Config Schema context {"dev":false,"dist":true} produces correct config 1`] = ` +Object { + "capture": Object { + "browser": Object { + "autoDownload": false, + "chromium": Object { + "inspect": false, + "proxy": Object { + "enabled": false, + }, + }, + "type": "chromium", + }, + "loadDelay": "PT3S", + "maxAttempts": 3, + "networkPolicy": Object { + "enabled": true, + "rules": Array [ + Object { + "allow": true, + "host": undefined, + "protocol": "http:", + }, + Object { + "allow": true, + "host": undefined, + "protocol": "https:", + }, + Object { + "allow": true, + "host": undefined, + "protocol": "ws:", + }, + Object { + "allow": true, + "host": undefined, + "protocol": "wss:", + }, + Object { + "allow": true, + "host": undefined, + "protocol": "data:", + }, + Object { + "allow": false, + "host": undefined, + "protocol": undefined, + }, + ], + }, + "timeouts": Object { + "openUrl": "PT1M", + "renderComplete": "PT30S", + "waitForElements": "PT30S", + }, + "zoom": 2, + }, + "csv": Object { + "checkForFormulas": true, + "enablePanelActionDownload": true, + "escapeFormulaValues": false, + "maxSizeBytes": ByteSizeValue { + "valueInBytes": 10485760, + }, + "scroll": Object { + "duration": "30s", + "size": 500, + }, + "useByteOrderMarkEncoding": false, + }, + "enabled": true, + "kibanaServer": Object {}, + "poll": Object { + "jobCompletionNotifier": Object { + "interval": 10000, + "intervalErrorMultiplier": 5, + }, + "jobsRefresh": Object { + "interval": 5000, + "intervalErrorMultiplier": 5, + }, + }, + "queue": Object { + "indexInterval": "week", + "pollEnabled": true, + "pollInterval": "PT3S", + "pollIntervalErrorMultiplier": 10, + "timeout": "PT2M", + }, + "roles": Object { + "allow": Array [ + "reporting_user", + ], + "enabled": true, + }, +} +`; diff --git a/x-pack/plugins/reporting/server/config/create_config.test.ts b/x-pack/plugins/reporting/server/config/create_config.test.ts index 718638e1ba62b..3c5ecdc1dab0b 100644 --- a/x-pack/plugins/reporting/server/config/create_config.test.ts +++ b/x-pack/plugins/reporting/server/config/create_config.test.ts @@ -43,10 +43,10 @@ describe('Reporting server createConfig$', () => { const result = await createConfig$(mockCoreSetup, mockConfig$, mockLogger).toPromise(); expect(result.encryptionKey).toMatch(/\S{32,}/); // random 32 characters - expect(mockLogger.warn.mock.calls.length).toBe(1); - expect(mockLogger.warn.mock.calls[0]).toMatchObject([ - 'Generating a random key for xpack.reporting.encryptionKey. To prevent sessions from being invalidated on restart, please set xpack.reporting.encryptionKey in the kibana.yml or use the bin/kibana-encryption-keys command.', - ]); + expect(mockLogger.warn).toHaveBeenCalledTimes(1); + expect(mockLogger.warn).toHaveBeenCalledWith( + 'Generating a random key for xpack.reporting.encryptionKey. To prevent sessions from being invalidated on restart, please set xpack.reporting.encryptionKey in the kibana.yml or use the bin/kibana-encryption-keys command.' + ); }); it('uses the user-provided encryption key', async () => { @@ -58,7 +58,7 @@ describe('Reporting server createConfig$', () => { const mockConfig$ = createMockConfig(mockInitContext); const result = await createConfig$(mockCoreSetup, mockConfig$, mockLogger).toPromise(); expect(result.encryptionKey).toMatch('iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii'); - expect(mockLogger.warn.mock.calls.length).toBe(0); + expect(mockLogger.warn).not.toHaveBeenCalled(); }); it('uses the user-provided encryption key, reporting kibanaServer settings to override server info', async () => { @@ -103,7 +103,7 @@ describe('Reporting server createConfig$', () => { }, } `); - expect(mockLogger.warn.mock.calls.length).toBe(0); + expect(mockLogger.warn).not.toHaveBeenCalled(); }); it('uses user-provided disableSandbox: false', async () => { @@ -117,7 +117,7 @@ describe('Reporting server createConfig$', () => { const result = await createConfig$(mockCoreSetup, mockConfig$, mockLogger).toPromise(); expect(result.capture.browser.chromium).toMatchObject({ disableSandbox: false }); - expect(mockLogger.warn.mock.calls.length).toBe(0); + expect(mockLogger.warn).not.toHaveBeenCalled(); }); it('uses user-provided disableSandbox: true', async () => { @@ -131,7 +131,7 @@ describe('Reporting server createConfig$', () => { const result = await createConfig$(mockCoreSetup, mockConfig$, mockLogger).toPromise(); expect(result.capture.browser.chromium).toMatchObject({ disableSandbox: true }); - expect(mockLogger.warn.mock.calls.length).toBe(0); + expect(mockLogger.warn).not.toHaveBeenCalled(); }); it('provides a default for disableSandbox', async () => { @@ -144,18 +144,12 @@ describe('Reporting server createConfig$', () => { const result = await createConfig$(mockCoreSetup, mockConfig$, mockLogger).toPromise(); expect(result.capture.browser.chromium).toMatchObject({ disableSandbox: expect.any(Boolean) }); - expect(mockLogger.warn.mock.calls.length).toBe(0); + expect(mockLogger.warn).not.toHaveBeenCalled(); }); - for (const hostname of [ - '0', - '0.0', - '0.0.0', - '0.0.0.0', - '0000:0000:0000:0000:0000:0000:0000:0000', - '::', - ]) { - it(`apply failover logic when hostname is given as ${hostname}`, async () => { + it.each(['0', '0.0', '0.0.0', '0.0.0.0', '0000:0000:0000:0000:0000:0000:0000:0000', '::'])( + `apply failover logic when hostname is given as "%s"`, + async (hostname) => { mockInitContext = coreMock.createPluginInitializerContext( createMockConfigSchema({ encryptionKey: 'aaaaaaaaaaaaabbbbbbbbbbbbaaaaaaaaa', @@ -167,7 +161,7 @@ describe('Reporting server createConfig$', () => { }, }) ); - mockCoreSetup.http.getServerInfo = jest.fn().mockImplementation( + mockCoreSetup.http.getServerInfo = jest.fn( (): HttpServerInfo => ({ name: 'cool server', hostname, @@ -177,12 +171,16 @@ describe('Reporting server createConfig$', () => { ); const mockConfig$ = createMockConfig(mockInitContext); - const result = await createConfig$(mockCoreSetup, mockConfig$, mockLogger).toPromise(); - expect(result.kibanaServer).toMatchObject({ - hostname: 'localhost', - port: 5601, - protocol: 'http', - }); - }); - } + await expect( + createConfig$(mockCoreSetup, mockConfig$, mockLogger).toPromise() + ).resolves.toHaveProperty( + 'kibanaServer', + expect.objectContaining({ + hostname: 'localhost', + port: 5601, + protocol: 'http', + }) + ); + } + ); }); diff --git a/x-pack/plugins/reporting/server/config/index.ts b/x-pack/plugins/reporting/server/config/index.ts index c20b5e16c7f04..fa836fd47cde3 100644 --- a/x-pack/plugins/reporting/server/config/index.ts +++ b/x-pack/plugins/reporting/server/config/index.ts @@ -11,7 +11,8 @@ import { get } from 'lodash'; import { ConfigSchema, ReportingConfigType } from './schema'; export { buildConfig } from './config'; export { registerUiSettings } from './ui_settings'; -export { ConfigSchema, ReportingConfigType }; +export type { ReportingConfigType }; +export { ConfigSchema }; export const config: PluginConfigDescriptor = { exposeToBrowser: { poll: true, roles: true }, diff --git a/x-pack/plugins/reporting/server/config/schema.test.ts b/x-pack/plugins/reporting/server/config/schema.test.ts index 7f1da5b55ccb6..c49490be87a15 100644 --- a/x-pack/plugins/reporting/server/config/schema.test.ts +++ b/x-pack/plugins/reporting/server/config/schema.test.ts @@ -9,203 +9,11 @@ import { ConfigSchema } from './schema'; describe('Reporting Config Schema', () => { it(`context {"dev":false,"dist":false} produces correct config`, () => { - expect(ConfigSchema.validate({}, { dev: false, dist: false })).toMatchInlineSnapshot(` - Object { - "capture": Object { - "browser": Object { - "autoDownload": true, - "chromium": Object { - "proxy": Object { - "enabled": false, - }, - }, - "type": "chromium", - }, - "loadDelay": "PT3S", - "maxAttempts": 1, - "networkPolicy": Object { - "enabled": true, - "rules": Array [ - Object { - "allow": true, - "host": undefined, - "protocol": "http:", - }, - Object { - "allow": true, - "host": undefined, - "protocol": "https:", - }, - Object { - "allow": true, - "host": undefined, - "protocol": "ws:", - }, - Object { - "allow": true, - "host": undefined, - "protocol": "wss:", - }, - Object { - "allow": true, - "host": undefined, - "protocol": "data:", - }, - Object { - "allow": false, - "host": undefined, - "protocol": undefined, - }, - ], - }, - "timeouts": Object { - "openUrl": "PT1M", - "renderComplete": "PT30S", - "waitForElements": "PT30S", - }, - "zoom": 2, - }, - "csv": Object { - "checkForFormulas": true, - "enablePanelActionDownload": true, - "escapeFormulaValues": false, - "maxSizeBytes": ByteSizeValue { - "valueInBytes": 10485760, - }, - "scroll": Object { - "duration": "30s", - "size": 500, - }, - "useByteOrderMarkEncoding": false, - }, - "enabled": true, - "encryptionKey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "kibanaServer": Object {}, - "poll": Object { - "jobCompletionNotifier": Object { - "interval": 10000, - "intervalErrorMultiplier": 5, - }, - "jobsRefresh": Object { - "interval": 5000, - "intervalErrorMultiplier": 5, - }, - }, - "queue": Object { - "indexInterval": "week", - "pollEnabled": true, - "pollInterval": "PT3S", - "pollIntervalErrorMultiplier": 10, - "timeout": "PT2M", - }, - "roles": Object { - "allow": Array [ - "reporting_user", - ], - "enabled": true, - }, - } - `); + expect(ConfigSchema.validate({}, { dev: false, dist: false })).toMatchSnapshot(); }); it(`context {"dev":false,"dist":true} produces correct config`, () => { - expect(ConfigSchema.validate({}, { dev: false, dist: true })).toMatchInlineSnapshot(` - Object { - "capture": Object { - "browser": Object { - "autoDownload": false, - "chromium": Object { - "inspect": false, - "proxy": Object { - "enabled": false, - }, - }, - "type": "chromium", - }, - "loadDelay": "PT3S", - "maxAttempts": 3, - "networkPolicy": Object { - "enabled": true, - "rules": Array [ - Object { - "allow": true, - "host": undefined, - "protocol": "http:", - }, - Object { - "allow": true, - "host": undefined, - "protocol": "https:", - }, - Object { - "allow": true, - "host": undefined, - "protocol": "ws:", - }, - Object { - "allow": true, - "host": undefined, - "protocol": "wss:", - }, - Object { - "allow": true, - "host": undefined, - "protocol": "data:", - }, - Object { - "allow": false, - "host": undefined, - "protocol": undefined, - }, - ], - }, - "timeouts": Object { - "openUrl": "PT1M", - "renderComplete": "PT30S", - "waitForElements": "PT30S", - }, - "zoom": 2, - }, - "csv": Object { - "checkForFormulas": true, - "enablePanelActionDownload": true, - "escapeFormulaValues": false, - "maxSizeBytes": ByteSizeValue { - "valueInBytes": 10485760, - }, - "scroll": Object { - "duration": "30s", - "size": 500, - }, - "useByteOrderMarkEncoding": false, - }, - "enabled": true, - "kibanaServer": Object {}, - "poll": Object { - "jobCompletionNotifier": Object { - "interval": 10000, - "intervalErrorMultiplier": 5, - }, - "jobsRefresh": Object { - "interval": 5000, - "intervalErrorMultiplier": 5, - }, - }, - "queue": Object { - "indexInterval": "week", - "pollEnabled": true, - "pollInterval": "PT3S", - "pollIntervalErrorMultiplier": 10, - "timeout": "PT2M", - }, - "roles": Object { - "allow": Array [ - "reporting_user", - ], - "enabled": true, - }, - } - `); + expect(ConfigSchema.validate({}, { dev: false, dist: true })).toMatchSnapshot(); }); it('allows Duration values for certain keys', () => { @@ -288,18 +96,20 @@ describe('Reporting Config Schema', () => { `); }); - for (const address of ['0', '0.0', '0.0.0']) { - it(`fails to validate "kibanaServer.hostname" with an invalid hostname: "${address}"`, () => { + it.each(['0', '0.0', '0.0.0'])( + `fails to validate "kibanaServer.hostname" with an invalid hostname: "%s"`, + (address) => { expect(() => ConfigSchema.validate({ kibanaServer: { hostname: address }, }) ).toThrowError(`[kibanaServer.hostname]: value must be a valid hostname (see RFC 1123).`); - }); - } + } + ); - for (const address of ['0.0.0.0', '0000:0000:0000:0000:0000:0000:0000:0000', '::']) { - it(`fails to validate "kibanaServer.hostname" hostname as zero: "${address}"`, () => { + it.each(['0.0.0.0', '0000:0000:0000:0000:0000:0000:0000:0000', '::'])( + `fails to validate "kibanaServer.hostname" hostname as zero: "%s"`, + (address) => { expect(() => ConfigSchema.validate({ kibanaServer: { hostname: address }, @@ -307,6 +117,6 @@ describe('Reporting Config Schema', () => { ).toThrowError( `[kibanaServer.hostname]: cannot use '0.0.0.0' as Kibana host name, consider using the default (localhost) instead` ); - }); - } + } + ); }); diff --git a/x-pack/plugins/reporting/server/export_types/csv/types.ts b/x-pack/plugins/reporting/server/export_types/csv/types.ts new file mode 100644 index 0000000000000..5531f2d670128 --- /dev/null +++ b/x-pack/plugins/reporting/server/export_types/csv/types.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export type { + RawValue, + JobParamsDeprecatedCSV, + TaskPayloadDeprecatedCSV, + SearchRequestDeprecatedCSV, + SavedSearchGeneratorResultDeprecatedCSV, +} from '../../../common/types'; diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource/types.ts b/x-pack/plugins/reporting/server/export_types/csv_searchsource/types.ts new file mode 100644 index 0000000000000..57e154eb2b26f --- /dev/null +++ b/x-pack/plugins/reporting/server/export_types/csv_searchsource/types.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export type { RawValue, JobParamsCSV, TaskPayloadCSV } from '../../../common/types'; diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/types.ts b/x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/types.ts new file mode 100644 index 0000000000000..1475c0cc2cf63 --- /dev/null +++ b/x-pack/plugins/reporting/server/export_types/csv_searchsource_immediate/types.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export type { + FakeRequest, + JobParamsDownloadCSV, + SavedObjectServiceError, +} from '../../../common/types'; diff --git a/x-pack/plugins/reporting/server/export_types/png/types.ts b/x-pack/plugins/reporting/server/export_types/png/types.ts new file mode 100644 index 0000000000000..ccfca04b02499 --- /dev/null +++ b/x-pack/plugins/reporting/server/export_types/png/types.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export type { JobParamsPNG, TaskPayloadPNG } from '../../../common/types'; diff --git a/x-pack/plugins/reporting/server/export_types/png_v2/types.ts b/x-pack/plugins/reporting/server/export_types/png_v2/types.ts new file mode 100644 index 0000000000000..3773bfae2b3ff --- /dev/null +++ b/x-pack/plugins/reporting/server/export_types/png_v2/types.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export type { JobParamsPNGV2, TaskPayloadPNGV2 } from '../../../common/types'; diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/types.ts b/x-pack/plugins/reporting/server/export_types/printable_pdf/types.ts new file mode 100644 index 0000000000000..763fb8942b470 --- /dev/null +++ b/x-pack/plugins/reporting/server/export_types/printable_pdf/types.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export type { JobParamsPDF, TaskPayloadPDF, JobParamsPDFLegacy } from '../../../common/types'; diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/types.ts b/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/types.ts index a629eea9f21f7..ba8427feda914 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/types.ts +++ b/x-pack/plugins/reporting/server/export_types/printable_pdf_v2/types.ts @@ -5,27 +5,4 @@ * 2.0. */ -import { LocatorParams } from '../../../common/types'; -import { LayoutParams } from '../../lib/layouts'; -import { BaseParams, BasePayload } from '../../types'; - -interface BaseParamsPDFV2 { - layout: LayoutParams; - - /** - * This value is used to re-create the same visual state as when the report was requested as well as navigate to the correct page. - */ - locatorParams: LocatorParams[]; -} - -// Job params: structure of incoming user request data, after being parsed from RISON -export type JobParamsPDFV2 = BaseParamsPDFV2 & BaseParams; - -// Job payload: structure of stored job data provided by create_job -export interface TaskPayloadPDFV2 extends BasePayload, BaseParamsPDFV2 { - layout: LayoutParams; - /** - * The value of forceNow is injected server-side every time a given report is generated. - */ - forceNow: string; -} +export type { JobParamsPDFV2, TaskPayloadPDFV2 } from '../../../common/types'; diff --git a/x-pack/plugins/reporting/server/index.ts b/x-pack/plugins/reporting/server/index.ts index bc6529eb90782..2c851a9dffc1b 100644 --- a/x-pack/plugins/reporting/server/index.ts +++ b/x-pack/plugins/reporting/server/index.ts @@ -13,10 +13,20 @@ export const plugin = (initContext: PluginInitializerContext ({ openUrl: { diff --git a/x-pack/plugins/reporting/server/lib/store/index.ts b/x-pack/plugins/reporting/server/lib/store/index.ts index 9ba8d44f19e65..e5f1c65e47948 100644 --- a/x-pack/plugins/reporting/server/lib/store/index.ts +++ b/x-pack/plugins/reporting/server/lib/store/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -export { ReportDocument } from '../../../common/types'; +export type { ReportDocument } from '../../../common/types'; export { Report } from './report'; export { SavedReport } from './saved_report'; export { ReportingStore } from './store'; diff --git a/x-pack/plugins/reporting/server/lib/store/report.ts b/x-pack/plugins/reporting/server/lib/store/report.ts index 2feb162fbf37e..2f802334eb6ff 100644 --- a/x-pack/plugins/reporting/server/lib/store/report.ts +++ b/x-pack/plugins/reporting/server/lib/store/report.ts @@ -17,8 +17,8 @@ import { } from '../../../common/types'; import type { ReportTaskParams } from '../tasks'; -export { ReportDocument }; -export { ReportApiJSON, ReportSource }; +export type { ReportDocument }; +export type { ReportApiJSON, ReportSource }; const puid = new Puid(); export const MIGRATION_VERSION = '7.14.0'; diff --git a/x-pack/plugins/reporting/server/lib/tasks/index.ts b/x-pack/plugins/reporting/server/lib/tasks/index.ts index f464383c0b533..6be8299d1d26a 100644 --- a/x-pack/plugins/reporting/server/lib/tasks/index.ts +++ b/x-pack/plugins/reporting/server/lib/tasks/index.ts @@ -14,7 +14,7 @@ export const REPORTING_MONITOR_TYPE = 'reports:monitor'; export { ExecuteReportTask } from './execute_report'; export { MonitorReportsTask } from './monitor_reports'; -export { TaskRunResult }; +export type { TaskRunResult }; export interface ReportTaskParams { id: string; diff --git a/x-pack/plugins/reporting/server/types.ts b/x-pack/plugins/reporting/server/types.ts index 84fa6fb5b10d6..af9a973b0bb45 100644 --- a/x-pack/plugins/reporting/server/types.ts +++ b/x-pack/plugins/reporting/server/types.ts @@ -57,7 +57,7 @@ export type ReportingUser = { username: AuthenticatedUser['username'] } | false; export type CaptureConfig = ReportingConfigType['capture']; export type ScrollConfig = ReportingConfigType['csv']['scroll']; -export { BaseParams, BasePayload }; +export type { BaseParams, BasePayload }; // default fn type for CreateJobFnFactory export type CreateJobFn = ( diff --git a/x-pack/plugins/rule_registry/server/index.ts b/x-pack/plugins/rule_registry/server/index.ts index d6c5b61706415..d52cd0ebf608c 100644 --- a/x-pack/plugins/rule_registry/server/index.ts +++ b/x-pack/plugins/rule_registry/server/index.ts @@ -12,9 +12,9 @@ import { PluginInitializerContext } from 'src/core/server'; import { RuleRegistryPlugin } from './plugin'; export type { RuleRegistryPluginSetupContract, RuleRegistryPluginStartContract } from './plugin'; -export { IRuleDataService, RuleDataPluginService } from './rule_data_plugin_service'; +export type { IRuleDataService, RuleDataPluginService } from './rule_data_plugin_service'; export { RuleDataClient } from './rule_data_client'; -export { IRuleDataClient } from './rule_data_client/types'; +export type { IRuleDataClient } from './rule_data_client/types'; export type { RacRequestHandlerContext, RacApiRequestHandlerContext, @@ -24,14 +24,15 @@ export type { export * from './config'; export * from './rule_data_plugin_service'; export * from './rule_data_client'; +export * from './alert_data_client/audit_events'; export { createLifecycleRuleTypeFactory } from './utils/create_lifecycle_rule_type_factory'; -export { +export type { LifecycleRuleExecutor, LifecycleAlertService, LifecycleAlertServices, - createLifecycleExecutor, } from './utils/create_lifecycle_executor'; +export { createLifecycleExecutor } from './utils/create_lifecycle_executor'; export { createPersistenceRuleTypeWrapper } from './utils/create_persistence_rule_type_wrapper'; export * from './utils/persistence_types'; export type { AlertsClient } from './alert_data_client/alerts_client'; diff --git a/x-pack/plugins/runtime_fields/public/components/index.ts b/x-pack/plugins/runtime_fields/public/components/index.ts index 8fbec39b4abfb..47db4087dab6e 100644 --- a/x-pack/plugins/runtime_fields/public/components/index.ts +++ b/x-pack/plugins/runtime_fields/public/components/index.ts @@ -5,11 +5,10 @@ * 2.0. */ -export { RuntimeFieldForm, FormState as RuntimeFieldFormState } from './runtime_field_form'; +export type { FormState as RuntimeFieldFormState } from './runtime_field_form'; +export { RuntimeFieldForm } from './runtime_field_form'; export { RuntimeFieldEditor } from './runtime_field_editor'; -export { - RuntimeFieldEditorFlyoutContent, - RuntimeFieldEditorFlyoutContentProps, -} from './runtime_field_editor_flyout_content'; +export type { RuntimeFieldEditorFlyoutContentProps } from './runtime_field_editor_flyout_content'; +export { RuntimeFieldEditorFlyoutContent } from './runtime_field_editor_flyout_content'; diff --git a/x-pack/plugins/runtime_fields/public/components/runtime_field_editor_flyout_content/index.ts b/x-pack/plugins/runtime_fields/public/components/runtime_field_editor_flyout_content/index.ts index 7ac0165fc9d41..e626cdb5b2312 100644 --- a/x-pack/plugins/runtime_fields/public/components/runtime_field_editor_flyout_content/index.ts +++ b/x-pack/plugins/runtime_fields/public/components/runtime_field_editor_flyout_content/index.ts @@ -5,7 +5,5 @@ * 2.0. */ -export { - RuntimeFieldEditorFlyoutContent, - Props as RuntimeFieldEditorFlyoutContentProps, -} from './runtime_field_editor_flyout_content'; +export type { Props as RuntimeFieldEditorFlyoutContentProps } from './runtime_field_editor_flyout_content'; +export { RuntimeFieldEditorFlyoutContent } from './runtime_field_editor_flyout_content'; diff --git a/x-pack/plugins/runtime_fields/public/components/runtime_field_form/index.ts b/x-pack/plugins/runtime_fields/public/components/runtime_field_form/index.ts index bc8d6d8bdc1b3..a8f29539c4f2c 100644 --- a/x-pack/plugins/runtime_fields/public/components/runtime_field_form/index.ts +++ b/x-pack/plugins/runtime_fields/public/components/runtime_field_form/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { RuntimeFieldForm, FormState } from './runtime_field_form'; +export type { FormState } from './runtime_field_form'; +export { RuntimeFieldForm } from './runtime_field_form'; diff --git a/x-pack/plugins/runtime_fields/public/index.ts b/x-pack/plugins/runtime_fields/public/index.ts index 1a3c6943c3a5c..ece935d0d5571 100644 --- a/x-pack/plugins/runtime_fields/public/index.ts +++ b/x-pack/plugins/runtime_fields/public/index.ts @@ -7,14 +7,10 @@ import { RuntimeFieldsPlugin } from './plugin'; -export { - RuntimeFieldEditorFlyoutContent, - RuntimeFieldEditorFlyoutContentProps, - RuntimeFieldEditor, - RuntimeFieldFormState, -} from './components'; +export type { RuntimeFieldEditorFlyoutContentProps, RuntimeFieldFormState } from './components'; +export { RuntimeFieldEditorFlyoutContent, RuntimeFieldEditor } from './components'; export { RUNTIME_FIELD_OPTIONS } from './constants'; -export { RuntimeField, RuntimeType, PluginSetup as RuntimeFieldsSetup } from './types'; +export type { RuntimeField, RuntimeType, PluginSetup as RuntimeFieldsSetup } from './types'; export function plugin() { return new RuntimeFieldsPlugin(); diff --git a/x-pack/plugins/runtime_fields/public/shared_imports.ts b/x-pack/plugins/runtime_fields/public/shared_imports.ts index a6dd23440176a..61b517a4e1117 100644 --- a/x-pack/plugins/runtime_fields/public/shared_imports.ts +++ b/x-pack/plugins/runtime_fields/public/shared_imports.ts @@ -5,15 +5,17 @@ * 2.0. */ +export type { + FormSchema, + FormHook, + ValidationFunc, + FieldConfig, +} from '../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; export { useForm, useFormData, Form, - FormSchema, UseField, - FormHook, - ValidationFunc, - FieldConfig, } from '../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; export { fieldValidators } from '../../../../src/plugins/es_ui_shared/static/forms/helpers'; diff --git a/x-pack/plugins/runtime_fields/public/test_utils.ts b/x-pack/plugins/runtime_fields/public/test_utils.ts index d3b02257c2ff2..1c052cd666e56 100644 --- a/x-pack/plugins/runtime_fields/public/test_utils.ts +++ b/x-pack/plugins/runtime_fields/public/test_utils.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { registerTestBed, TestBed } from '@kbn/test/jest'; +export type { TestBed } from '@kbn/test/jest'; +export { registerTestBed } from '@kbn/test/jest'; diff --git a/x-pack/plugins/saved_objects_tagging/common/index.ts b/x-pack/plugins/saved_objects_tagging/common/index.ts index 500e656014e9a..a513822adb5e0 100644 --- a/x-pack/plugins/saved_objects_tagging/common/index.ts +++ b/x-pack/plugins/saved_objects_tagging/common/index.ts @@ -5,11 +5,12 @@ * 2.0. */ -export { TagsCapabilities, getTagsCapabilities } from './capabilities'; +export type { TagsCapabilities } from './capabilities'; +export { getTagsCapabilities } from './capabilities'; export { tagFeatureId, tagSavedObjectTypeName, tagManagementSectionId } from './constants'; -export { TagWithRelations, TagAttributes, Tag, ITagsClient, TagSavedObject } from './types'; +export type { TagWithRelations, TagAttributes, Tag, ITagsClient, TagSavedObject } from './types'; +export type { TagValidation } from './validation'; export { - TagValidation, validateTagColor, validateTagName, validateTagDescription, diff --git a/x-pack/plugins/saved_objects_tagging/public/components/assign_flyout/index.ts b/x-pack/plugins/saved_objects_tagging/public/components/assign_flyout/index.ts index 2dc3449199cf6..d785d241edb6c 100644 --- a/x-pack/plugins/saved_objects_tagging/public/components/assign_flyout/index.ts +++ b/x-pack/plugins/saved_objects_tagging/public/components/assign_flyout/index.ts @@ -5,9 +5,9 @@ * 2.0. */ -export { - getAssignFlyoutOpener, +export type { AssignFlyoutOpener, GetAssignFlyoutOpenerOptions, OpenAssignFlyoutOptions, } from './open_assign_flyout'; +export { getAssignFlyoutOpener } from './open_assign_flyout'; diff --git a/x-pack/plugins/saved_objects_tagging/public/components/base/index.ts b/x-pack/plugins/saved_objects_tagging/public/components/base/index.ts index 34500b978df00..29c75be50a392 100644 --- a/x-pack/plugins/saved_objects_tagging/public/components/base/index.ts +++ b/x-pack/plugins/saved_objects_tagging/public/components/base/index.ts @@ -5,7 +5,11 @@ * 2.0. */ -export { TagBadge, TagBadgeProps } from './tag_badge'; -export { TagList, TagListProps } from './tag_list'; -export { TagSelector, TagSelectorProps } from './tag_selector'; -export { TagSearchBarOption, TagSearchBarOptionProps } from './tag_searchbar_option'; +export type { TagBadgeProps } from './tag_badge'; +export { TagBadge } from './tag_badge'; +export type { TagListProps } from './tag_list'; +export { TagList } from './tag_list'; +export type { TagSelectorProps } from './tag_selector'; +export { TagSelector } from './tag_selector'; +export type { TagSearchBarOptionProps } from './tag_searchbar_option'; +export { TagSearchBarOption } from './tag_searchbar_option'; diff --git a/x-pack/plugins/saved_objects_tagging/public/components/edition_modal/index.ts b/x-pack/plugins/saved_objects_tagging/public/components/edition_modal/index.ts index 0436e8c57e59b..ac6994453443e 100644 --- a/x-pack/plugins/saved_objects_tagging/public/components/edition_modal/index.ts +++ b/x-pack/plugins/saved_objects_tagging/public/components/edition_modal/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { getCreateModalOpener, getEditModalOpener, CreateModalOpener } from './open_modal'; +export type { CreateModalOpener } from './open_modal'; +export { getCreateModalOpener, getEditModalOpener } from './open_modal'; diff --git a/x-pack/plugins/saved_objects_tagging/public/components/index.ts b/x-pack/plugins/saved_objects_tagging/public/components/index.ts index c6142d8552bcc..5c7c491df9bd4 100644 --- a/x-pack/plugins/saved_objects_tagging/public/components/index.ts +++ b/x-pack/plugins/saved_objects_tagging/public/components/index.ts @@ -5,13 +5,10 @@ * 2.0. */ -export { - TagSelector, +export type { TagSelectorProps, - TagList, TagListProps, - TagBadge, TagBadgeProps, - TagSearchBarOption, TagSearchBarOptionProps, } from './base'; +export { TagSelector, TagList, TagBadge, TagSearchBarOption } from './base'; diff --git a/x-pack/plugins/saved_objects_tagging/public/index.ts b/x-pack/plugins/saved_objects_tagging/public/index.ts index c110e629f0ca3..1da147f4f168a 100644 --- a/x-pack/plugins/saved_objects_tagging/public/index.ts +++ b/x-pack/plugins/saved_objects_tagging/public/index.ts @@ -8,8 +8,8 @@ import { PluginInitializerContext } from '../../../../src/core/public'; import { SavedObjectTaggingPlugin } from './plugin'; -export { SavedObjectTaggingPluginStart } from './types'; -export { Tag } from '../common'; +export type { SavedObjectTaggingPluginStart } from './types'; +export type { Tag } from '../common'; export const plugin = (initializerContext: PluginInitializerContext) => new SavedObjectTaggingPlugin(initializerContext); diff --git a/x-pack/plugins/saved_objects_tagging/public/management/actions/index.ts b/x-pack/plugins/saved_objects_tagging/public/management/actions/index.ts index a18ef5afd445f..5503cec4af9dc 100644 --- a/x-pack/plugins/saved_objects_tagging/public/management/actions/index.ts +++ b/x-pack/plugins/saved_objects_tagging/public/management/actions/index.ts @@ -14,7 +14,7 @@ import { getDeleteAction } from './delete'; import { getEditAction } from './edit'; import { getAssignAction } from './assign'; -export { TagAction } from './types'; +export type { TagAction } from './types'; interface GetActionsOptions { core: CoreStart; diff --git a/x-pack/plugins/saved_objects_tagging/public/services/assignments/index.ts b/x-pack/plugins/saved_objects_tagging/public/services/assignments/index.ts index 8b26da9cc5674..763c70a93ab41 100644 --- a/x-pack/plugins/saved_objects_tagging/public/services/assignments/index.ts +++ b/x-pack/plugins/saved_objects_tagging/public/services/assignments/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { ITagAssignmentService, TagAssignmentService } from './assignment_service'; +export type { ITagAssignmentService } from './assignment_service'; +export { TagAssignmentService } from './assignment_service'; diff --git a/x-pack/plugins/saved_objects_tagging/public/services/index.ts b/x-pack/plugins/saved_objects_tagging/public/services/index.ts index 1909aaea5c4ee..29d5ad7a7e027 100644 --- a/x-pack/plugins/saved_objects_tagging/public/services/index.ts +++ b/x-pack/plugins/saved_objects_tagging/public/services/index.ts @@ -5,13 +5,12 @@ * 2.0. */ -export { +export type { ITagInternalClient, - TagsCache, ITagsCache, - TagsClient, ITagsChangeListener, - isServerValidationError, TagServerValidationError, } from './tags'; -export { TagAssignmentService, ITagAssignmentService } from './assignments'; +export { TagsCache, TagsClient, isServerValidationError } from './tags'; +export type { ITagAssignmentService } from './assignments'; +export { TagAssignmentService } from './assignments'; diff --git a/x-pack/plugins/saved_objects_tagging/public/services/tags/index.ts b/x-pack/plugins/saved_objects_tagging/public/services/tags/index.ts index 4b4e6d6c84123..b69f7124b0c8f 100644 --- a/x-pack/plugins/saved_objects_tagging/public/services/tags/index.ts +++ b/x-pack/plugins/saved_objects_tagging/public/services/tags/index.ts @@ -5,6 +5,9 @@ * 2.0. */ -export { TagsClient, ITagInternalClient } from './tags_client'; -export { TagsCache, ITagsChangeListener, ITagsCache } from './tags_cache'; -export { isServerValidationError, TagServerValidationError } from './errors'; +export type { ITagInternalClient } from './tags_client'; +export { TagsClient } from './tags_client'; +export type { ITagsChangeListener, ITagsCache } from './tags_cache'; +export { TagsCache } from './tags_cache'; +export type { TagServerValidationError } from './errors'; +export { isServerValidationError } from './errors'; diff --git a/x-pack/plugins/saved_objects_tagging/public/services/tags/tags_cache.ts b/x-pack/plugins/saved_objects_tagging/public/services/tags/tags_cache.ts index 1d8fda1e5912d..15d207aca47c0 100644 --- a/x-pack/plugins/saved_objects_tagging/public/services/tags/tags_cache.ts +++ b/x-pack/plugins/saved_objects_tagging/public/services/tags/tags_cache.ts @@ -11,7 +11,7 @@ import { takeUntil } from 'rxjs/operators'; import { ITagsCache } from '../../../../../../src/plugins/saved_objects_tagging_oss/public'; import { Tag, TagAttributes } from '../../../common/types'; -export { ITagsCache }; +export type { ITagsCache }; export interface ITagsChangeListener { onDelete: (id: string) => void; diff --git a/x-pack/plugins/saved_objects_tagging/server/services/assignments/index.ts b/x-pack/plugins/saved_objects_tagging/server/services/assignments/index.ts index c465f89369a1e..7bf69b6c02304 100644 --- a/x-pack/plugins/saved_objects_tagging/server/services/assignments/index.ts +++ b/x-pack/plugins/saved_objects_tagging/server/services/assignments/index.ts @@ -5,5 +5,6 @@ * 2.0. */ -export { AssignmentService, IAssignmentService } from './assignment_service'; +export type { IAssignmentService } from './assignment_service'; +export { AssignmentService } from './assignment_service'; export { AssignmentError } from './errors'; diff --git a/x-pack/plugins/saved_objects_tagging/server/services/index.ts b/x-pack/plugins/saved_objects_tagging/server/services/index.ts index 695d90e496f60..36c5e32b816c6 100644 --- a/x-pack/plugins/saved_objects_tagging/server/services/index.ts +++ b/x-pack/plugins/saved_objects_tagging/server/services/index.ts @@ -6,4 +6,5 @@ */ export { TagsClient, savedObjectToTag, TagValidationError } from './tags'; -export { IAssignmentService, AssignmentService, AssignmentError } from './assignments'; +export type { IAssignmentService } from './assignments'; +export { AssignmentService, AssignmentError } from './assignments'; diff --git a/x-pack/plugins/searchprofiler/common/index.ts b/x-pack/plugins/searchprofiler/common/index.ts index 5b4f922231af3..154846bb3daa6 100644 --- a/x-pack/plugins/searchprofiler/common/index.ts +++ b/x-pack/plugins/searchprofiler/common/index.ts @@ -7,4 +7,4 @@ export { PLUGIN } from './constants'; -export { LicenseStatus } from './types'; +export type { LicenseStatus } from './types'; diff --git a/x-pack/plugins/searchprofiler/public/application/components/highlight_details_flyout/index.ts b/x-pack/plugins/searchprofiler/public/application/components/highlight_details_flyout/index.ts index a48ee9be0c0d1..3e1b4c208f157 100644 --- a/x-pack/plugins/searchprofiler/public/application/components/highlight_details_flyout/index.ts +++ b/x-pack/plugins/searchprofiler/public/application/components/highlight_details_flyout/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { HighlightDetailsFlyout, Props } from './highlight_details_flyout'; +export type { Props } from './highlight_details_flyout'; +export { HighlightDetailsFlyout } from './highlight_details_flyout'; diff --git a/x-pack/plugins/searchprofiler/public/application/components/index.ts b/x-pack/plugins/searchprofiler/public/application/components/index.ts index 86f7e2b6af557..ea5ba226fc5f6 100644 --- a/x-pack/plugins/searchprofiler/public/application/components/index.ts +++ b/x-pack/plugins/searchprofiler/public/application/components/index.ts @@ -7,7 +7,8 @@ export { SearchProfilerTabs } from './searchprofiler_tabs'; export { LicenseWarningNotice } from './license_warning_notice'; -export { ProfileTree, OnHighlightChangeArgs } from './profile_tree'; +export type { OnHighlightChangeArgs } from './profile_tree'; +export { ProfileTree } from './profile_tree'; export { HighlightDetailsFlyout } from './highlight_details_flyout'; export { ProfileLoadingPlaceholder } from './profile_loading_placeholder'; export { EmptyTreePlaceHolder } from './empty_tree_placeholder'; diff --git a/x-pack/plugins/searchprofiler/public/application/components/profile_query_editor/editor/index.ts b/x-pack/plugins/searchprofiler/public/application/components/profile_query_editor/editor/index.ts index 3d90bf2670525..5d8be48041176 100644 --- a/x-pack/plugins/searchprofiler/public/application/components/profile_query_editor/editor/index.ts +++ b/x-pack/plugins/searchprofiler/public/application/components/profile_query_editor/editor/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { Editor, EditorInstance } from './editor'; +export type { EditorInstance } from './editor'; +export { Editor } from './editor'; diff --git a/x-pack/plugins/searchprofiler/public/application/components/profile_tree/index.ts b/x-pack/plugins/searchprofiler/public/application/components/profile_tree/index.ts index eb1eb29d7d09b..8768c5b8b85f0 100644 --- a/x-pack/plugins/searchprofiler/public/application/components/profile_tree/index.ts +++ b/x-pack/plugins/searchprofiler/public/application/components/profile_tree/index.ts @@ -6,4 +6,4 @@ */ export { ProfileTree } from './profile_tree'; -export { OnHighlightChangeArgs } from './highlight_context'; +export type { OnHighlightChangeArgs } from './highlight_context'; diff --git a/x-pack/plugins/searchprofiler/public/application/store/index.ts b/x-pack/plugins/searchprofiler/public/application/store/index.ts index ce5a6fe832b8c..ed350a47181d0 100644 --- a/x-pack/plugins/searchprofiler/public/application/store/index.ts +++ b/x-pack/plugins/searchprofiler/public/application/store/index.ts @@ -5,5 +5,6 @@ * 2.0. */ -export { useStore, State } from './store'; -export { Action } from './reducer'; +export type { State } from './store'; +export { useStore } from './store'; +export type { Action } from './reducer'; diff --git a/x-pack/plugins/security/common/licensing/index.ts b/x-pack/plugins/security/common/licensing/index.ts index ec82007524fa4..48329aeb99925 100644 --- a/x-pack/plugins/security/common/licensing/index.ts +++ b/x-pack/plugins/security/common/licensing/index.ts @@ -5,6 +5,7 @@ * 2.0. */ -export { SecurityLicenseService, SecurityLicense } from './license_service'; +export type { SecurityLicense } from './license_service'; +export { SecurityLicenseService } from './license_service'; -export { LoginLayout, SecurityLicenseFeatures } from './license_features'; +export type { LoginLayout, SecurityLicenseFeatures } from './license_features'; diff --git a/x-pack/plugins/security/common/model/index.ts b/x-pack/plugins/security/common/model/index.ts index 082e6bdc12cd0..bc1666af3200c 100644 --- a/x-pack/plugins/security/common/model/index.ts +++ b/x-pack/plugins/security/common/model/index.ts @@ -5,17 +5,18 @@ * 2.0. */ -export { ApiKey, ApiKeyToInvalidate, ApiKeyRoleDescriptors } from './api_key'; -export { User, EditUser, getUserDisplayName } from './user'; -export { AuthenticatedUser, canUserChangePassword } from './authenticated_user'; -export { AuthenticationProvider, shouldProviderUseLoginForm } from './authentication_provider'; -export { BuiltinESPrivileges } from './builtin_es_privileges'; -export { RawKibanaPrivileges, RawKibanaFeaturePrivileges } from './raw_kibana_privileges'; -export { FeaturesPrivileges } from './features_privileges'; +export type { ApiKey, ApiKeyToInvalidate, ApiKeyRoleDescriptors } from './api_key'; +export type { User, EditUser } from './user'; +export { getUserDisplayName } from './user'; +export type { AuthenticatedUser } from './authenticated_user'; +export { canUserChangePassword } from './authenticated_user'; +export type { AuthenticationProvider } from './authentication_provider'; +export { shouldProviderUseLoginForm } from './authentication_provider'; +export type { BuiltinESPrivileges } from './builtin_es_privileges'; +export type { RawKibanaPrivileges, RawKibanaFeaturePrivileges } from './raw_kibana_privileges'; +export type { FeaturesPrivileges } from './features_privileges'; +export type { Role, RoleIndexPrivilege, RoleKibanaPrivilege } from './role'; export { - Role, - RoleIndexPrivilege, - RoleKibanaPrivilege, copyRole, isRoleDeprecated, isRoleReadOnly, @@ -26,14 +27,14 @@ export { prepareRoleClone, getExtendedRoleDeprecationNotice, } from './role'; -export { +export type { InlineRoleTemplate, StoredRoleTemplate, InvalidRoleTemplate, RoleTemplate, RoleMapping, } from './role_mapping'; -export { +export type { PrivilegeDeprecationsRolesByFeatureIdRequest, PrivilegeDeprecationsRolesByFeatureIdResponse, PrivilegeDeprecationsService, diff --git a/x-pack/plugins/security/public/authentication/index.ts b/x-pack/plugins/security/public/authentication/index.ts index 50d6b0c74376e..dd7cb006d879e 100644 --- a/x-pack/plugins/security/public/authentication/index.ts +++ b/x-pack/plugins/security/public/authentication/index.ts @@ -5,8 +5,8 @@ * 2.0. */ -export { - AuthenticationService, +export type { AuthenticationServiceSetup, AuthenticationServiceStart, } from './authentication_service'; +export { AuthenticationService } from './authentication_service'; diff --git a/x-pack/plugins/security/public/index.ts b/x-pack/plugins/security/public/index.ts index e8d5f739821ed..55925e142ff24 100644 --- a/x-pack/plugins/security/public/index.ts +++ b/x-pack/plugins/security/public/index.ts @@ -7,15 +7,20 @@ import type { PluginInitializer, PluginInitializerContext } from 'src/core/public'; -import type { PluginSetupDependencies, PluginStartDependencies } from './plugin'; -import { SecurityPlugin, SecurityPluginSetup, SecurityPluginStart } from './plugin'; +import type { + PluginSetupDependencies, + PluginStartDependencies, + SecurityPluginSetup, + SecurityPluginStart, +} from './plugin'; +import { SecurityPlugin } from './plugin'; -export { SecurityPluginSetup, SecurityPluginStart }; -export { AuthenticatedUser } from '../common/model'; -export { SecurityLicense, SecurityLicenseFeatures } from '../common/licensing'; -export { UserMenuLink, SecurityNavControlServiceStart } from '../public/nav_control'; +export type { SecurityPluginSetup, SecurityPluginStart }; +export type { AuthenticatedUser } from '../common/model'; +export type { SecurityLicense, SecurityLicenseFeatures } from '../common/licensing'; +export type { UserMenuLink, SecurityNavControlServiceStart } from '../public/nav_control'; -export { AuthenticationServiceStart, AuthenticationServiceSetup } from './authentication'; +export type { AuthenticationServiceStart, AuthenticationServiceSetup } from './authentication'; export const plugin: PluginInitializer< SecurityPluginSetup, diff --git a/x-pack/plugins/security/public/management/api_keys/api_keys_grid/api_keys_grid_page.test.tsx b/x-pack/plugins/security/public/management/api_keys/api_keys_grid/api_keys_grid_page.test.tsx index 72fd79805f970..6e3de061fd191 100644 --- a/x-pack/plugins/security/public/management/api_keys/api_keys_grid/api_keys_grid_page.test.tsx +++ b/x-pack/plugins/security/public/management/api_keys/api_keys_grid/api_keys_grid_page.test.tsx @@ -5,13 +5,7 @@ * 2.0. */ -import { - fireEvent, - render, - waitFor, - waitForElementToBeRemoved, - within, -} from '@testing-library/react'; +import { render } from '@testing-library/react'; import { createMemoryHistory } from 'history'; import React from 'react'; @@ -22,60 +16,75 @@ import { Providers } from '../api_keys_management_app'; import { apiKeysAPIClientMock } from '../index.mock'; import { APIKeysGridPage } from './api_keys_grid_page'; -jest.mock('@elastic/eui/lib/services/accessibility/html_id_generator', () => ({ - htmlIdGenerator: () => () => `id-${Math.random()}`, -})); +/* + * Note to engineers + * we moved these 4 tests below to "x-pack/test/functional/apps/api_keys/home_page.ts": + * 1-"creates API key when submitting form, redirects back and displays base64" + * 2-"creates API key with optional expiration, redirects back and displays base64" + * 3-"deletes multiple api keys using bulk select" + * 4-"deletes api key using cta button" + * to functional tests to avoid flakyness + */ -jest.setTimeout(15000); +describe('APIKeysGridPage', () => { + // We are spying on the console.error to avoid react to throw error + // in our test "displays error when fetching API keys fails" + // since we are using EuiErrorBoundary and react will console.error any errors + const consoleWarnMock = jest.spyOn(console, 'error').mockImplementation(); -const coreStart = coreMock.createStart(); + const coreStart = coreMock.createStart(); + const apiClientMock = apiKeysAPIClientMock.create(); + const { authc } = securityMock.createSetup(); -const apiClientMock = apiKeysAPIClientMock.create(); -apiClientMock.checkPrivileges.mockResolvedValue({ - areApiKeysEnabled: true, - canManage: true, - isAdmin: true, -}); -apiClientMock.getApiKeys.mockResolvedValue({ - apiKeys: [ - { - creation: 1571322182082, - expiration: 1571408582082, - id: '0QQZ2m0BO2XZwgJFuWTT', - invalidated: false, - name: 'first-api-key', - realm: 'reserved', - username: 'elastic', - }, - { - creation: 1571322182082, - expiration: 1571408582082, - id: 'BO2XZwgJFuWTT0QQZ2m0', - invalidated: false, - name: 'second-api-key', - realm: 'reserved', - username: 'elastic', - }, - ], -}); + beforeEach(() => { + apiClientMock.checkPrivileges.mockClear(); + apiClientMock.getApiKeys.mockClear(); + coreStart.http.get.mockClear(); + coreStart.http.post.mockClear(); + authc.getCurrentUser.mockClear(); -const authc = securityMock.createSetup().authc; -authc.getCurrentUser.mockResolvedValue( - mockAuthenticatedUser({ - username: 'jdoe', - full_name: '', - email: '', - enabled: true, - roles: ['superuser'], - }) -); + apiClientMock.checkPrivileges.mockResolvedValue({ + areApiKeysEnabled: true, + canManage: true, + isAdmin: true, + }); + apiClientMock.getApiKeys.mockResolvedValue({ + apiKeys: [ + { + creation: 1571322182082, + expiration: 1571408582082, + id: '0QQZ2m0BO2XZwgJFuWTT', + invalidated: false, + name: 'first-api-key', + realm: 'reserved', + username: 'elastic', + }, + { + creation: 1571322182082, + expiration: 1571408582082, + id: 'BO2XZwgJFuWTT0QQZ2m0', + invalidated: false, + name: 'second-api-key', + realm: 'reserved', + username: 'elastic', + }, + ], + }); -// FLAKY: https://github.com/elastic/kibana/issues/97085 -describe.skip('APIKeysGridPage', () => { + authc.getCurrentUser.mockResolvedValue( + mockAuthenticatedUser({ + username: 'jdoe', + full_name: '', + email: '', + enabled: true, + roles: ['superuser'], + }) + ); + }); it('loads and displays API keys', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }); - const { getByText } = render( + const { findByText } = render( { ); - await waitForElementToBeRemoved(() => getByText(/Loading API keys/)); - getByText(/first-api-key/); - getByText(/second-api-key/); + expect(await findByText(/Loading API keys/)).not.toBeInTheDocument(); + await findByText(/first-api-key/); + await findByText(/second-api-key/); + }); + + afterAll(() => { + // Let's make sure we restore everything just in case + consoleWarnMock.mockRestore(); }); it('displays callout when API keys are disabled', async () => { @@ -98,7 +112,7 @@ describe.skip('APIKeysGridPage', () => { isAdmin: true, }); - const { getByText } = render( + const { findByText } = render( { ); - await waitForElementToBeRemoved(() => getByText(/Loading API keys/)); - getByText(/API keys not enabled/); + expect(await findByText(/Loading API keys/)).not.toBeInTheDocument(); + await findByText(/API keys not enabled/); }); it('displays error when user does not have required permissions', async () => { @@ -120,7 +134,7 @@ describe.skip('APIKeysGridPage', () => { isAdmin: false, }); - const { getByText } = render( + const { findByText } = render( { ); - await waitForElementToBeRemoved(() => getByText(/Loading API keys/)); - getByText(/You need permission to manage API keys/); + expect(await findByText(/Loading API keys/)).not.toBeInTheDocument(); + await findByText(/You need permission to manage API keys/); }); it('displays error when fetching API keys fails', async () => { apiClientMock.getApiKeys.mockRejectedValueOnce({ - body: { error: 'Internal Server Error', message: '', statusCode: 500 }, - }); - const history = createMemoryHistory({ initialEntries: ['/'] }); - - const { getByText } = render( - - - - ); - - await waitForElementToBeRemoved(() => getByText(/Loading API keys/)); - getByText(/Could not load API keys/); - }); - - it('creates API key when submitting form, redirects back and displays base64', async () => { - const history = createMemoryHistory({ initialEntries: ['/create'] }); - coreStart.http.get.mockResolvedValue([{ name: 'superuser' }]); - coreStart.http.post.mockResolvedValue({ id: '1D', api_key: 'AP1_K3Y' }); - - const { findByRole, findByDisplayValue } = render( - - - - ); - expect(coreStart.http.get).toHaveBeenCalledWith('/api/security/role'); - - const dialog = await findByRole('dialog'); - - fireEvent.click(await findByRole('button', { name: 'Create API key' })); - - const alert = await findByRole('alert'); - within(alert).getByText(/Enter a name/i); - - fireEvent.change(await within(dialog).findByLabelText('Name'), { - target: { value: 'Test' }, - }); - - fireEvent.click(await findByRole('button', { name: 'Create API key' })); - - await waitFor(() => { - expect(coreStart.http.post).toHaveBeenLastCalledWith('/internal/security/api_key', { - body: JSON.stringify({ name: 'Test' }), - }); - expect(history.location.pathname).toBe('/'); - }); - - await findByDisplayValue(btoa('1D:AP1_K3Y')); - }); - - it('creates API key with optional expiration, redirects back and displays base64', async () => { - const history = createMemoryHistory({ initialEntries: ['/create'] }); - coreStart.http.get.mockResolvedValue([{ name: 'superuser' }]); - coreStart.http.post.mockResolvedValue({ id: '1D', api_key: 'AP1_K3Y' }); - - const { findByRole, findByDisplayValue } = render( - - - - ); - expect(coreStart.http.get).toHaveBeenCalledWith('/api/security/role'); - - const dialog = await findByRole('dialog'); - - fireEvent.change(await within(dialog).findByLabelText('Name'), { - target: { value: 'Test' }, - }); - - fireEvent.click(await within(dialog).findByLabelText('Expire after time')); - - fireEvent.click(await findByRole('button', { name: 'Create API key' })); - - const alert = await findByRole('alert'); - within(alert).getByText(/Enter a valid duration or disable this option\./i); - - fireEvent.change(await within(dialog).findByLabelText('Lifetime (days)'), { - target: { value: '12' }, - }); - - fireEvent.click(await findByRole('button', { name: 'Create API key' })); - - await waitFor(() => { - expect(coreStart.http.post).toHaveBeenLastCalledWith('/internal/security/api_key', { - body: JSON.stringify({ name: 'Test', expiration: '12d' }), - }); - expect(history.location.pathname).toBe('/'); + body: { + error: 'Internal Server Error', + message: 'Internal Server Error', + statusCode: 500, + }, }); - - await findByDisplayValue(btoa('1D:AP1_K3Y')); - }); - - it('deletes api key using cta button', async () => { - const history = createMemoryHistory({ initialEntries: ['/'] }); - - const { findByRole, findAllByLabelText } = render( - - - - ); - - const [deleteButton] = await findAllByLabelText(/Delete/i); - fireEvent.click(deleteButton); - - const dialog = await findByRole('dialog'); - fireEvent.click(await within(dialog).findByRole('button', { name: 'Delete API key' })); - - await waitFor(() => { - expect(apiClientMock.invalidateApiKeys).toHaveBeenLastCalledWith( - [{ id: '0QQZ2m0BO2XZwgJFuWTT', name: 'first-api-key' }], - true - ); - }); - }); - - it('deletes multiple api keys using bulk select', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }); - const { findByRole, findAllByRole } = render( + const { findByText } = render( { ); - const deleteCheckboxes = await findAllByRole('checkbox', { name: 'Select this row' }); - deleteCheckboxes.forEach((checkbox) => fireEvent.click(checkbox)); - fireEvent.click(await findByRole('button', { name: 'Delete API keys' })); - - const dialog = await findByRole('dialog'); - fireEvent.click(await within(dialog).findByRole('button', { name: 'Delete API keys' })); - - await waitFor(() => { - expect(apiClientMock.invalidateApiKeys).toHaveBeenLastCalledWith( - [ - { id: '0QQZ2m0BO2XZwgJFuWTT', name: 'first-api-key' }, - { id: 'BO2XZwgJFuWTT0QQZ2m0', name: 'second-api-key' }, - ], - true - ); - }); + expect(await findByText(/Loading API keys/)).not.toBeInTheDocument(); + await findByText(/Could not load API keys/); }); }); diff --git a/x-pack/plugins/security/public/management/api_keys/api_keys_grid/api_keys_grid_page.tsx b/x-pack/plugins/security/public/management/api_keys/api_keys_grid/api_keys_grid_page.tsx index dcf2a7bfe5165..a4843e4637d8b 100644 --- a/x-pack/plugins/security/public/management/api_keys/api_keys_grid/api_keys_grid_page.tsx +++ b/x-pack/plugins/security/public/management/api_keys/api_keys_grid/api_keys_grid_page.tsx @@ -164,6 +164,7 @@ export class APIKeysGridPage extends Component { {...reactRouterNavigate(this.props.history, '/create')} fill iconType="plusInCircleFilled" + data-test-subj="apiKeysCreatePromptButton" > { {...reactRouterNavigate(this.props.history, '/create')} fill iconType="plusInCircleFilled" + data-test-subj="apiKeysCreateTableButton" > { color: 'danger', onClick: (item) => invalidateApiKeyPrompt([{ id: item.id, name: item.name }], this.onApiKeysInvalidated), + 'data-test-subj': 'apiKeysTableDeleteAction', }, ], }, diff --git a/x-pack/plugins/security/public/management/api_keys/api_keys_grid/create_api_key_flyout.tsx b/x-pack/plugins/security/public/management/api_keys/api_keys_grid/create_api_key_flyout.tsx index e1ffc3b4b3515..f2fa6f7de468e 100644 --- a/x-pack/plugins/security/public/management/api_keys/api_keys_grid/create_api_key_flyout.tsx +++ b/x-pack/plugins/security/public/management/api_keys/api_keys_grid/create_api_key_flyout.tsx @@ -202,6 +202,7 @@ export const CreateApiKeyFlyout: FunctionComponent = ({ isInvalid={form.touched.name && !!form.errors.name} inputRef={firstFieldRef} fullWidth + data-test-subj="apiKeyNameInput" /> @@ -258,6 +259,7 @@ export const CreateApiKeyFlyout: FunctionComponent = ({ )} checked={!!form.values.customExpiration} onChange={(e) => form.setValue('customExpiration', e.target.checked)} + data-test-subj="apiKeyCustomExpirationSwitch" /> {form.values.customExpiration && ( <> @@ -284,6 +286,7 @@ export const CreateApiKeyFlyout: FunctionComponent = ({ defaultValue={form.values.expiration} isInvalid={form.touched.expiration && !!form.errors.expiration} fullWidth + data-test-subj="apiKeyCustomExpirationInput" /> diff --git a/x-pack/plugins/security/public/management/api_keys/api_keys_grid/invalidate_provider/index.ts b/x-pack/plugins/security/public/management/api_keys/api_keys_grid/invalidate_provider/index.ts index dc99861ce0a8d..3af1e9d37c17d 100644 --- a/x-pack/plugins/security/public/management/api_keys/api_keys_grid/invalidate_provider/index.ts +++ b/x-pack/plugins/security/public/management/api_keys/api_keys_grid/invalidate_provider/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { InvalidateProvider, InvalidateApiKeys } from './invalidate_provider'; +export type { InvalidateApiKeys } from './invalidate_provider'; +export { InvalidateProvider } from './invalidate_provider'; diff --git a/x-pack/plugins/security/public/management/role_mappings/model/index.ts b/x-pack/plugins/security/public/management/role_mappings/model/index.ts index 25e66bda35034..d80eb4d7d6943 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/index.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/index.ts @@ -11,6 +11,7 @@ export { Rule } from './rule'; export { RuleGroup } from './rule_group'; export { ExceptAllRule } from './except_all_rule'; export { ExceptAnyRule } from './except_any_rule'; -export { FieldRule, FieldRuleValue } from './field_rule'; +export type { FieldRuleValue } from './field_rule'; +export { FieldRule } from './field_rule'; export { generateRulesFromRaw } from './rule_builder'; export { RuleBuilderError } from './rule_builder_error'; diff --git a/x-pack/plugins/security/public/nav_control/index.ts b/x-pack/plugins/security/public/nav_control/index.ts index 5ec306fa97170..95331b7504070 100644 --- a/x-pack/plugins/security/public/nav_control/index.ts +++ b/x-pack/plugins/security/public/nav_control/index.ts @@ -5,5 +5,6 @@ * 2.0. */ -export { SecurityNavControlService, SecurityNavControlServiceStart } from './nav_control_service'; +export type { SecurityNavControlServiceStart } from './nav_control_service'; +export { SecurityNavControlService } from './nav_control_service'; export type { UserMenuLink } from './nav_control_component'; diff --git a/x-pack/plugins/security/server/anonymous_access/index.ts b/x-pack/plugins/security/server/anonymous_access/index.ts index 2d86cb3a3e3b4..6e41ab1bae780 100644 --- a/x-pack/plugins/security/server/anonymous_access/index.ts +++ b/x-pack/plugins/security/server/anonymous_access/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { AnonymousAccessService, AnonymousAccessServiceStart } from './anonymous_access_service'; +export type { AnonymousAccessServiceStart } from './anonymous_access_service'; +export { AnonymousAccessService } from './anonymous_access_service'; diff --git a/x-pack/plugins/security/server/audit/index.ts b/x-pack/plugins/security/server/audit/index.ts index 5cae122c94cc3..b859e773552a3 100644 --- a/x-pack/plugins/security/server/audit/index.ts +++ b/x-pack/plugins/security/server/audit/index.ts @@ -5,9 +5,10 @@ * 2.0. */ -export { AuditService, AuditServiceSetup, AuditLogger } from './audit_service'; +export type { AuditServiceSetup, AuditLogger } from './audit_service'; +export { AuditService } from './audit_service'; +export type { AuditEvent } from './audit_events'; export { - AuditEvent, userLoginEvent, accessAgreementAcknowledgedEvent, httpRequestEvent, diff --git a/x-pack/plugins/security/server/authentication/api_keys/index.ts b/x-pack/plugins/security/server/authentication/api_keys/index.ts index b14d09d559700..44fe48f04debb 100644 --- a/x-pack/plugins/security/server/authentication/api_keys/index.ts +++ b/x-pack/plugins/security/server/authentication/api_keys/index.ts @@ -5,11 +5,11 @@ * 2.0. */ -export { - APIKeys, +export type { CreateAPIKeyResult, InvalidateAPIKeyResult, CreateAPIKeyParams, InvalidateAPIKeysParams, GrantAPIKeyResult, } from './api_keys'; +export { APIKeys } from './api_keys'; diff --git a/x-pack/plugins/security/server/authentication/index.ts b/x-pack/plugins/security/server/authentication/index.ts index 1e46d2aaf560e..f6f6f1da36952 100644 --- a/x-pack/plugins/security/server/authentication/index.ts +++ b/x-pack/plugins/security/server/authentication/index.ts @@ -6,11 +6,11 @@ */ export { canRedirectRequest } from './can_redirect_request'; -export { - AuthenticationService, +export type { AuthenticationServiceStart, InternalAuthenticationServiceStart, } from './authentication_service'; +export { AuthenticationService } from './authentication_service'; export { AuthenticationResult } from './authentication_result'; export { DeauthenticationResult } from './deauthentication_result'; export { diff --git a/x-pack/plugins/security/server/authentication/providers/index.ts b/x-pack/plugins/security/server/authentication/providers/index.ts index c589371331eaf..31f89889b3892 100644 --- a/x-pack/plugins/security/server/authentication/providers/index.ts +++ b/x-pack/plugins/security/server/authentication/providers/index.ts @@ -5,11 +5,8 @@ * 2.0. */ -export { - BaseAuthenticationProvider, - AuthenticationProviderOptions, - AuthenticationProviderSpecificOptions, -} from './base'; +export type { AuthenticationProviderOptions, AuthenticationProviderSpecificOptions } from './base'; +export { BaseAuthenticationProvider } from './base'; export { AnonymousAuthenticationProvider } from './anonymous'; export { BasicAuthenticationProvider } from './basic'; export { KerberosAuthenticationProvider } from './kerberos'; diff --git a/x-pack/plugins/security/server/authorization/authorization_service.tsx b/x-pack/plugins/security/server/authorization/authorization_service.tsx index 72f2c9843daec..004c82d2c3f3f 100644 --- a/x-pack/plugins/security/server/authorization/authorization_service.tsx +++ b/x-pack/plugins/security/server/authorization/authorization_service.tsx @@ -50,7 +50,7 @@ import { validateFeaturePrivileges } from './validate_feature_privileges'; import { validateReservedPrivileges } from './validate_reserved_privileges'; export { Actions } from './actions'; -export { CheckSavedObjectsPrivileges } from './check_saved_objects_privileges'; +export type { CheckSavedObjectsPrivileges } from './check_saved_objects_privileges'; interface AuthorizationServiceSetupParams { packageVersion: string; diff --git a/x-pack/plugins/security/server/authorization/index.ts b/x-pack/plugins/security/server/authorization/index.ts index 221baa85a65f6..265ec2dce5a31 100644 --- a/x-pack/plugins/security/server/authorization/index.ts +++ b/x-pack/plugins/security/server/authorization/index.ts @@ -6,11 +6,12 @@ */ export { Actions } from './actions'; -export { - AuthorizationService, +export type { AuthorizationServiceSetup, AuthorizationServiceSetupInternal, } from './authorization_service'; -export { CheckSavedObjectsPrivileges } from './check_saved_objects_privileges'; -export { CheckPrivilegesPayload } from './types'; -export { transformElasticsearchRoleToRole, ElasticsearchRole } from './roles'; +export { AuthorizationService } from './authorization_service'; +export type { CheckSavedObjectsPrivileges } from './check_saved_objects_privileges'; +export type { CheckPrivilegesPayload } from './types'; +export type { ElasticsearchRole } from './roles'; +export { transformElasticsearchRoleToRole } from './roles'; diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts index 81d1339052301..d46f30ef53ab4 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts @@ -14,13 +14,13 @@ import { FeaturePrivilegeApiBuilder } from './api'; import { FeaturePrivilegeAppBuilder } from './app'; import { FeaturePrivilegeCasesBuilder } from './cases'; import { FeaturePrivilegeCatalogueBuilder } from './catalogue'; -import { FeaturePrivilegeBuilder } from './feature_privilege_builder'; +import type { FeaturePrivilegeBuilder } from './feature_privilege_builder'; import { FeaturePrivilegeManagementBuilder } from './management'; import { FeaturePrivilegeNavlinkBuilder } from './navlink'; import { FeaturePrivilegeSavedObjectBuilder } from './saved_object'; import { FeaturePrivilegeUIBuilder } from './ui'; -export { FeaturePrivilegeBuilder }; +export type { FeaturePrivilegeBuilder }; export const featurePrivilegeBuilderFactory = (actions: Actions): FeaturePrivilegeBuilder => { const builders = [ diff --git a/x-pack/plugins/security/server/authorization/privileges/index.ts b/x-pack/plugins/security/server/authorization/privileges/index.ts index 31c9cf2713c9d..7e98730abd71e 100644 --- a/x-pack/plugins/security/server/authorization/privileges/index.ts +++ b/x-pack/plugins/security/server/authorization/privileges/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { privilegesFactory, PrivilegesService } from './privileges'; +export type { PrivilegesService } from './privileges'; +export { privilegesFactory } from './privileges'; diff --git a/x-pack/plugins/security/server/authorization/roles/index.ts b/x-pack/plugins/security/server/authorization/roles/index.ts index a5047a1872c09..205c339b45fbc 100644 --- a/x-pack/plugins/security/server/authorization/roles/index.ts +++ b/x-pack/plugins/security/server/authorization/roles/index.ts @@ -5,4 +5,5 @@ * 2.0. */ -export { transformElasticsearchRoleToRole, ElasticsearchRole } from './elasticsearch_role'; +export type { ElasticsearchRole } from './elasticsearch_role'; +export { transformElasticsearchRoleToRole } from './elasticsearch_role'; diff --git a/x-pack/plugins/security/server/elasticsearch/index.ts b/x-pack/plugins/security/server/elasticsearch/index.ts index 1c3bdd3054dd7..46acb874f7fc2 100644 --- a/x-pack/plugins/security/server/elasticsearch/index.ts +++ b/x-pack/plugins/security/server/elasticsearch/index.ts @@ -8,8 +8,8 @@ import type { AuthenticatedUser } from '../../common/model'; export type AuthenticationInfo = Omit; -export { - ElasticsearchService, +export type { ElasticsearchServiceStart, OnlineStatusRetryScheduler, } from './elasticsearch_service'; +export { ElasticsearchService } from './elasticsearch_service'; diff --git a/x-pack/plugins/security/server/feature_usage/index.ts b/x-pack/plugins/security/server/feature_usage/index.ts index 81d4336ef7bbb..b58dacfa97d3a 100644 --- a/x-pack/plugins/security/server/feature_usage/index.ts +++ b/x-pack/plugins/security/server/feature_usage/index.ts @@ -5,7 +5,5 @@ * 2.0. */ -export { - SecurityFeatureUsageService, - SecurityFeatureUsageServiceStart, -} from './feature_usage_service'; +export type { SecurityFeatureUsageServiceStart } from './feature_usage_service'; +export { SecurityFeatureUsageService } from './feature_usage_service'; diff --git a/x-pack/plugins/security/server/index.ts b/x-pack/plugins/security/server/index.ts index d1600b52df0ad..10b1e8167c14a 100644 --- a/x-pack/plugins/security/server/index.ts +++ b/x-pack/plugins/security/server/index.ts @@ -29,11 +29,11 @@ export type { } from './authentication'; export type { CheckPrivilegesPayload } from './authorization'; export type AuthorizationServiceSetup = SecurityPluginStart['authz']; -export { AuditLogger, AuditEvent } from './audit'; +export type { AuditLogger, AuditEvent } from './audit'; export type { SecurityPluginSetup, SecurityPluginStart }; export type { AuthenticatedUser } from '../common/model'; export { ROUTE_TAG_CAN_REDIRECT } from './routes/tags'; -export { AuditServiceSetup } from './audit'; +export type { AuditServiceSetup } from './audit'; export const config: PluginConfigDescriptor> = { schema: ConfigSchema, diff --git a/x-pack/plugins/security/server/routes/authorization/roles/model/index.ts b/x-pack/plugins/security/server/routes/authorization/roles/model/index.ts index e090cd26dc39f..cb5bb8a91152c 100644 --- a/x-pack/plugins/security/server/routes/authorization/roles/model/index.ts +++ b/x-pack/plugins/security/server/routes/authorization/roles/model/index.ts @@ -5,5 +5,6 @@ * 2.0. */ -export { ElasticsearchRole, transformElasticsearchRoleToRole } from '../../../../authorization'; +export type { ElasticsearchRole } from '../../../../authorization'; +export { transformElasticsearchRoleToRole } from '../../../../authorization'; export { getPutPayloadSchema, transformPutPayloadToElasticsearchRole } from './put_payload'; diff --git a/x-pack/plugins/security/server/session_management/index.ts b/x-pack/plugins/security/server/session_management/index.ts index a9ac23ad6354b..09787ed419854 100644 --- a/x-pack/plugins/security/server/session_management/index.ts +++ b/x-pack/plugins/security/server/session_management/index.ts @@ -5,8 +5,7 @@ * 2.0. */ -export { Session, SessionValue } from './session'; -export { - SessionManagementServiceStart, - SessionManagementService, -} from './session_management_service'; +export type { SessionValue } from './session'; +export { Session } from './session'; +export type { SessionManagementServiceStart } from './session_management_service'; +export { SessionManagementService } from './session_management_service'; diff --git a/x-pack/plugins/security_solution/common/constants.ts b/x-pack/plugins/security_solution/common/constants.ts index 2772c3de51065..584f3ed334d89 100644 --- a/x-pack/plugins/security_solution/common/constants.ts +++ b/x-pack/plugins/security_solution/common/constants.ts @@ -11,8 +11,16 @@ import type { TransformConfigSchema } from './transforms/types'; import { ENABLE_CASE_CONNECTOR } from '../../cases/common'; import { METADATA_TRANSFORMS_PATTERN } from './endpoint/constants'; +/** + * as const + * + * The const assertion ensures that type widening does not occur + * https://mariusschulz.com/blog/literal-type-widening-in-typescript + * Please follow this convention when adding to this file + */ + export const APP_ID = 'securitySolution' as const; -export const APP_UI_ID = 'securitySolutionUI'; +export const APP_UI_ID = 'securitySolutionUI' as const; export const CASES_FEATURE_ID = 'securitySolutionCases' as const; export const SERVER_APP_ID = 'siem' as const; export const APP_NAME = 'Security' as const; @@ -26,6 +34,8 @@ export const DEFAULT_DATE_FORMAT_TZ = 'dateFormat:tz' as const; export const DEFAULT_DARK_MODE = 'theme:darkMode' as const; export const DEFAULT_INDEX_KEY = 'securitySolution:defaultIndex' as const; export const DEFAULT_NUMBER_FORMAT = 'format:number:defaultPattern' as const; +export const DEFAULT_DATA_VIEW_ID = 'security-solution' as const; +export const DEFAULT_TIME_FIELD = '@timestamp' as const; export const DEFAULT_TIME_RANGE = 'timepicker:timeDefaults' as const; export const DEFAULT_REFRESH_RATE_INTERVAL = 'timepicker:refreshIntervalDefaults' as const; export const DEFAULT_APP_TIME_RANGE = 'securitySolution:timeDefaults' as const; @@ -51,7 +61,6 @@ export const DEFAULT_TIMEPICKER_QUICK_RANGES = 'timepicker:quickRanges' as const export const DEFAULT_TRANSFORMS = 'securitySolution:transforms' as const; export const SCROLLING_DISABLED_CLASS_NAME = 'scrolling-disabled' as const; export const GLOBAL_HEADER_HEIGHT = 96 as const; // px -export const GLOBAL_HEADER_HEIGHT_WITH_GLOBAL_BANNER = 128 as const; // px export const FILTERS_GLOBAL_HEIGHT = 109 as const; // px export const FULL_SCREEN_TOGGLED_CLASS_NAME = 'fullScreenToggled' as const; export const NO_ALERT_INDEX = 'no-alert-index-049FC71A-4C2C-446F-9901-37XMC5024C51' as const; @@ -268,6 +277,7 @@ export const TIMELINE_PREPACKAGED_URL = `${TIMELINE_URL}/_prepackaged` as const; export const NOTE_URL = '/api/note' as const; export const PINNED_EVENT_URL = '/api/pinned_event' as const; +export const SOURCERER_API_URL = '/api/sourcerer' as const; /** * Default signals index key for kibana.dev.yml @@ -355,7 +365,7 @@ export const ELASTIC_NAME = 'estc' as const; export const METADATA_TRANSFORM_STATS_URL = `/api/transform/transforms/${METADATA_TRANSFORMS_PATTERN}/_stats`; -export const RISKY_HOSTS_INDEX_PREFIX = 'ml_host_risk_score_latest_'; +export const RISKY_HOSTS_INDEX_PREFIX = 'ml_host_risk_score_latest_' as const; export const TRANSFORM_STATES = { ABORTING: 'aborting', diff --git a/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts b/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts index 033e979d2814c..42c10614975eb 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts @@ -11,7 +11,7 @@ import type { CreateExceptionListItemSchema, } from '@kbn/securitysolution-io-ts-list-types'; import { buildExceptionFilter } from '@kbn/securitysolution-list-utils'; -import { Filter, EsQueryConfig, IndexPatternBase, buildEsQuery } from '@kbn/es-query'; +import { Filter, EsQueryConfig, DataViewBase, buildEsQuery } from '@kbn/es-query'; import { ESBoolQuery } from '../typed_json'; import { Query, Index, TimestampOverrideOrUndefined } from './schemas/common/schemas'; @@ -24,7 +24,7 @@ export const getQueryFilter = ( lists: Array, excludeExceptions: boolean = true ): ESBoolQuery => { - const indexPattern: IndexPatternBase = { + const indexPattern: DataViewBase = { fields: [], title: index.join(), }; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/export_rules_details_schema.mock.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/export_rules_details_schema.mock.ts new file mode 100644 index 0000000000000..a47d57c299117 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/export_rules_details_schema.mock.ts @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ExportRulesDetails } from './export_rules_details_schema'; +import { + ExportExceptionDetailsMock, + getExceptionExportDetailsMock, +} from '../../../../../lists/common/schemas/response/exception_export_details_schema.mock'; + +interface RuleDetailsMock { + totalCount?: number; + rulesCount?: number; + missingCount?: number; + missingRules?: Array>; +} + +export const getOutputDetailsSample = (ruleDetails?: RuleDetailsMock): ExportRulesDetails => ({ + exported_count: ruleDetails?.totalCount ?? 0, + exported_rules_count: ruleDetails?.rulesCount ?? 0, + missing_rules: ruleDetails?.missingRules ?? [], + missing_rules_count: ruleDetails?.missingCount ?? 0, +}); + +export const getOutputDetailsSampleWithExceptions = ( + ruleDetails?: RuleDetailsMock, + exceptionDetails?: ExportExceptionDetailsMock +): ExportRulesDetails => ({ + ...getOutputDetailsSample(ruleDetails), + ...getExceptionExportDetailsMock(exceptionDetails), +}); + +export const getSampleDetailsAsNdjson = (sample: ExportRulesDetails): string => { + return `${JSON.stringify(sample)}\n`; +}; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/export_rules_details_schema.test.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/export_rules_details_schema.test.ts new file mode 100644 index 0000000000000..af0295ee46046 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/export_rules_details_schema.test.ts @@ -0,0 +1,60 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; +import { exactCheck, foldLeftRight, getPaths } from '@kbn/securitysolution-io-ts-utils'; + +import { + getOutputDetailsSample, + getOutputDetailsSampleWithExceptions, +} from './export_rules_details_schema.mock'; +import { + ExportRulesDetails, + exportRulesDetailsWithExceptionsSchema, +} from './export_rules_details_schema'; + +describe('exportRulesDetailsWithExceptionsSchema', () => { + test('it should validate export details response', () => { + const payload = getOutputDetailsSample(); + const decoded = exportRulesDetailsWithExceptionsSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should validate export details with exceptions details response', () => { + const payload = getOutputDetailsSampleWithExceptions(); + const decoded = exportRulesDetailsWithExceptionsSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should strip out extra keys', () => { + const payload: ExportRulesDetails & { + extraKey?: string; + } = getOutputDetailsSample(); + payload.extraKey = 'some extra key'; + const decoded = exportRulesDetailsWithExceptionsSchema.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(getOutputDetailsSample()); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/response/export_rules_details_schema.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/export_rules_details_schema.ts new file mode 100644 index 0000000000000..00e34ca9d7326 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/response/export_rules_details_schema.ts @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as t from 'io-ts'; +import { exportExceptionDetails } from '@kbn/securitysolution-io-ts-list-types'; +import { NonEmptyString } from '@kbn/securitysolution-io-ts-types'; + +const createSchema = ( + requiredFields: Required, + optionalFields: Optional +) => { + return t.intersection([t.exact(t.type(requiredFields)), t.exact(t.partial(optionalFields))]); +}; + +export const exportRulesDetails = { + exported_count: t.number, + exported_rules_count: t.number, + missing_rules: t.array( + t.exact( + t.type({ + rule_id: NonEmptyString, + }) + ) + ), + missing_rules_count: t.number, +}; + +const exportRulesDetailsSchema = t.exact(t.type(exportRulesDetails)); +export type ExportRulesDetailsSchema = t.TypeOf; + +// With exceptions +export const exportRulesDetailsWithExceptionsSchema = createSchema( + exportRulesDetails, + exportExceptionDetails +); + +export type ExportRulesDetails = t.TypeOf; diff --git a/x-pack/plugins/security_solution/common/experimental_features.ts b/x-pack/plugins/security_solution/common/experimental_features.ts index b6a0724faebed..4fd1b00ae3bee 100644 --- a/x-pack/plugins/security_solution/common/experimental_features.ts +++ b/x-pack/plugins/security_solution/common/experimental_features.ts @@ -21,6 +21,7 @@ export const allowedExperimentalValues = Object.freeze({ uebaEnabled: false, disableIsolationUIPendingStatuses: false, riskyHostsEnabled: false, + pendingActionResponsesWithAck: true, }); type ExperimentalConfigKeys = Array; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/field_maps/alerts.ts b/x-pack/plugins/security_solution/common/field_maps/alerts.ts similarity index 98% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/field_maps/alerts.ts rename to x-pack/plugins/security_solution/common/field_maps/alerts.ts index 5a7ceb83baf8c..08ce8f098f6fd 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/field_maps/alerts.ts +++ b/x-pack/plugins/security_solution/common/field_maps/alerts.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { FieldMap } from '../../../../../../rule_registry/common/field_map'; +import { FieldMap } from '../../../rule_registry/common/field_map'; export const alertsFieldMap: FieldMap = { 'kibana.alert.ancestors': { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/field_maps/field_names.ts b/x-pack/plugins/security_solution/common/field_maps/field_names.ts similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/field_maps/field_names.ts rename to x-pack/plugins/security_solution/common/field_maps/field_names.ts index 62c20217d23f0..1cb40063202d0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/field_maps/field_names.ts +++ b/x-pack/plugins/security_solution/common/field_maps/field_names.ts @@ -13,6 +13,7 @@ export const ALERT_DEPTH = `${ALERT_NAMESPACE}.depth` as const; export const ALERT_GROUP_ID = `${ALERT_NAMESPACE}.group.id` as const; export const ALERT_GROUP_INDEX = `${ALERT_NAMESPACE}.group.index` as const; export const ALERT_ORIGINAL_TIME = `${ALERT_NAMESPACE}.original_time` as const; +export const ALERT_THRESHOLD_RESULT = `${ALERT_NAMESPACE}.threshold_result` as const; export const ALERT_ORIGINAL_EVENT = `${ALERT_NAMESPACE}.original_event` as const; export const ALERT_ORIGINAL_EVENT_ACTION = `${ALERT_ORIGINAL_EVENT}.action` as const; @@ -24,3 +25,4 @@ export const ALERT_ORIGINAL_EVENT_TYPE = `${ALERT_ORIGINAL_EVENT}.type` as const export const ALERT_RULE_THRESHOLD = `${ALERT_RULE_NAMESPACE}.threshold` as const; export const ALERT_RULE_THRESHOLD_FIELD = `${ALERT_RULE_THRESHOLD}.field` as const; +export const ALERT_RULE_TIMELINE_ID = `${ALERT_RULE_NAMESPACE}.timeline_id` as const; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/field_maps/index.ts b/x-pack/plugins/security_solution/common/field_maps/index.ts similarity index 80% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/field_maps/index.ts rename to x-pack/plugins/security_solution/common/field_maps/index.ts index 0f19e2b3d3a91..e293dac663816 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/field_maps/index.ts +++ b/x-pack/plugins/security_solution/common/field_maps/index.ts @@ -7,4 +7,5 @@ import { AlertsFieldMap, alertsFieldMap } from './alerts'; import { RulesFieldMap, rulesFieldMap } from './rules'; -export { AlertsFieldMap, RulesFieldMap, alertsFieldMap, rulesFieldMap }; +export type { AlertsFieldMap, RulesFieldMap }; +export { alertsFieldMap, rulesFieldMap }; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/field_maps/rules.ts b/x-pack/plugins/security_solution/common/field_maps/rules.ts similarity index 100% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rule_types/field_maps/rules.ts rename to x-pack/plugins/security_solution/common/field_maps/rules.ts diff --git a/x-pack/plugins/security_solution/common/search_strategy/index_fields/index.ts b/x-pack/plugins/security_solution/common/search_strategy/index_fields/index.ts index be5fd3b5c4dc5..86bc11f7a596d 100644 --- a/x-pack/plugins/security_solution/common/search_strategy/index_fields/index.ts +++ b/x-pack/plugins/security_solution/common/search_strategy/index_fields/index.ts @@ -5,79 +5,17 @@ * 2.0. */ -import type { IFieldSubType } from '@kbn/es-query'; - -import type { - IEsSearchRequest, - IEsSearchResponse, - IIndexPattern, -} from '../../../../../../src/plugins/data/common'; -import type { DocValueFields, Maybe } from '../common'; - -interface FieldInfo { - category: string; - description?: string; - example?: string | number; - format?: string; - name: string; - type?: string; -} - -export interface IndexField { - /** Where the field belong */ - category: string; - /** Example of field's value */ - example?: Maybe; - /** whether the field's belong to an alias index */ - indexes: Array>; - /** The name of the field */ - name: string; - /** The type of the field's values as recognized by Kibana */ - type: string; - /** Whether the field's values can be efficiently searched for */ - searchable: boolean; - /** Whether the field's values can be aggregated */ - aggregatable: boolean; - /** Description of the field */ - description?: Maybe; - format?: Maybe; - /** the elastic type as mapped in the index */ - esTypes?: string[]; - subType?: IFieldSubType; - readFromDocValues: boolean; -} - -export type BeatFields = Record; - -export interface IndexFieldsStrategyRequest extends IEsSearchRequest { - indices: string[]; - onlyCheckIfIndicesExist: boolean; -} - -export interface IndexFieldsStrategyResponse extends IEsSearchResponse { - indexFields: IndexField[]; - indicesExist: string[]; -} - -export interface BrowserField { - aggregatable: boolean; - category: string; - description: string | null; - example: string | number | null; - fields: Readonly>>; - format: string; - indexes: string[]; - name: string; - searchable: boolean; - type: string; - subType?: IFieldSubType; -} - -export type BrowserFields = Readonly>>; - -export const EMPTY_BROWSER_FIELDS = {}; -export const EMPTY_DOCVALUE_FIELD: DocValueFields[] = []; -export const EMPTY_INDEX_PATTERN: IIndexPattern = { - fields: [], - title: '', -}; +export type { + FieldInfo, + IndexField, + BeatFields, + IndexFieldsStrategyRequest, + IndexFieldsStrategyResponse, + BrowserField, + BrowserFields, +} from '../../../../timelines/common'; +export { + EMPTY_BROWSER_FIELDS, + EMPTY_DOCVALUE_FIELD, + EMPTY_INDEX_FIELDS, +} from '../../../../timelines/common'; diff --git a/x-pack/plugins/security_solution/common/search_strategy/timeline/events/last_event_time/index.ts b/x-pack/plugins/security_solution/common/search_strategy/timeline/events/last_event_time/index.ts index 39f23a63c8afe..d6735b59c229d 100644 --- a/x-pack/plugins/security_solution/common/search_strategy/timeline/events/last_event_time/index.ts +++ b/x-pack/plugins/security_solution/common/search_strategy/timeline/events/last_event_time/index.ts @@ -10,6 +10,7 @@ export { LastEventIndexKey } from '../../../../../../timelines/common'; export type { LastTimeDetails, TimelineEventsLastEventTimeStrategyResponse, + TimelineKpiStrategyRequest, TimelineKpiStrategyResponse, TimelineEventsLastEventTimeRequestOptions, } from '../../../../../../timelines/common'; diff --git a/x-pack/plugins/security_solution/common/search_strategy/timeline/index.ts b/x-pack/plugins/security_solution/common/search_strategy/timeline/index.ts index 548560ac5cb8c..2d94a36a937d5 100644 --- a/x-pack/plugins/security_solution/common/search_strategy/timeline/index.ts +++ b/x-pack/plugins/security_solution/common/search_strategy/timeline/index.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { MappingRuntimeFields } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { IEsSearchRequest } from '../../../../../../src/plugins/data/common'; import { ESQuery } from '../../typed_json'; import { @@ -41,6 +42,7 @@ export interface TimelineRequestBasicOptions extends IEsSearchRequest { defaultIndex: string[]; docValueFields?: DocValueFields[]; factoryQueryType?: TimelineFactoryQueryTypes; + runtimeMappings: MappingRuntimeFields; } export interface TimelineRequestSortField extends SortField { @@ -171,6 +173,7 @@ export interface SortTimelineInput { export interface TimelineInput { columns?: Maybe; dataProviders?: Maybe; + dataViewId?: Maybe; description?: Maybe; eqlOptions?: Maybe; eventType?: Maybe; diff --git a/x-pack/plugins/security_solution/common/test/index.ts b/x-pack/plugins/security_solution/common/test/index.ts index 6d5df76b306a3..53261d54e84b0 100644 --- a/x-pack/plugins/security_solution/common/test/index.ts +++ b/x-pack/plugins/security_solution/common/test/index.ts @@ -7,12 +7,12 @@ // For the source of these roles please consult the PR these were introduced https://github.com/elastic/kibana/pull/81866#issue-511165754 export enum ROLES { + soc_manager = 'soc_manager', reader = 'reader', t1_analyst = 't1_analyst', t2_analyst = 't2_analyst', hunter = 'hunter', rule_author = 'rule_author', - soc_manager = 'soc_manager', platform_engineer = 'platform_engineer', detections_admin = 'detections_admin', } diff --git a/x-pack/plugins/security_solution/common/types/timeline/index.ts b/x-pack/plugins/security_solution/common/types/timeline/index.ts index c0046f7535db8..60fd126e6fd85 100644 --- a/x-pack/plugins/security_solution/common/types/timeline/index.ts +++ b/x-pack/plugins/security_solution/common/types/timeline/index.ts @@ -272,6 +272,7 @@ export type TimelineTypeLiteralWithNull = runtimeTypes.TypeOf; +export type TimelineWithoutExternalRefs = Omit; /* * Timeline IDs @@ -719,6 +720,7 @@ export interface TimelineResult { created?: Maybe; createdBy?: Maybe; dataProviders?: Maybe; + dataViewId?: Maybe; dateRange?: Maybe; description?: Maybe; eqlOptions?: Maybe; diff --git a/x-pack/plugins/security_solution/common/types/timeline/store.ts b/x-pack/plugins/security_solution/common/types/timeline/store.ts index 03cf0c39378e5..75cd44ba2b7d7 100644 --- a/x-pack/plugins/security_solution/common/types/timeline/store.ts +++ b/x-pack/plugins/security_solution/common/types/timeline/store.ts @@ -38,19 +38,20 @@ export interface SortColumnTimeline { } export interface TimelinePersistInput { - id: string; + columns: ColumnHeaderOptions[]; dataProviders?: DataProvider[]; + dataViewId: string; dateRange?: { start: string; end: string; }; + defaultColumns?: ColumnHeaderOptions[]; excludedRowRendererIds?: RowRendererId[]; expandedDetail?: TimelineExpandedDetail; filters?: Filter[]; - columns: ColumnHeaderOptions[]; - defaultColumns?: ColumnHeaderOptions[]; - itemsPerPage?: number; + id: string; indexNames: string[]; + itemsPerPage?: number; kqlQuery?: { filterQuery: SerializedFilterQuery | null; }; diff --git a/x-pack/plugins/security_solution/cypress/cypress.json b/x-pack/plugins/security_solution/cypress/cypress.json index 6a9a240af5873..8c27309becf08 100644 --- a/x-pack/plugins/security_solution/cypress/cypress.json +++ b/x-pack/plugins/security_solution/cypress/cypress.json @@ -12,5 +12,10 @@ "video": false, "videosFolder": "../../../target/kibana-security-solution/cypress/videos", "viewportHeight": 900, - "viewportWidth": 1440 + "viewportWidth": 1440, + "env": { + "protocol": "http", + "hostname": "localhost", + "configport": "5601" + } } diff --git a/x-pack/plugins/security_solution/cypress/downloads/timelines_export.ndjson b/x-pack/plugins/security_solution/cypress/downloads/timelines_export.ndjson new file mode 100644 index 0000000000000..8cf76734ad876 --- /dev/null +++ b/x-pack/plugins/security_solution/cypress/downloads/timelines_export.ndjson @@ -0,0 +1 @@ +{"savedObjectId":"46cca0e0-2580-11ec-8e56-9dafa0b0343b","version":"WzIyNjIzNCwxXQ==","columns":[{"id":"@timestamp"},{"id":"user.name"},{"id":"event.category"},{"id":"event.action"},{"id":"host.name"}],"kqlMode":"filter","kqlQuery":{"filterQuery":{"kuery":{"expression":"host.name: *","kind":"kuery"}}},"dateRange":{"start":"1514809376000","end":"1577881376000"},"description":"This is the best timeline","title":"Security Timeline","created":1633399341550,"createdBy":"elastic","updated":1633399341550,"updatedBy":"elastic","savedQueryId":null,"dataViewId":null,"timelineType":"default","sort":[],"eventNotes":[],"globalNotes":[],"pinnedEventIds":[]} diff --git a/x-pack/plugins/security_solution/cypress/integration/cases/privileges.spec.ts b/x-pack/plugins/security_solution/cypress/integration/cases/privileges.spec.ts index 23016ecc512b1..0337cd3bd6e17 100644 --- a/x-pack/plugins/security_solution/cypress/integration/cases/privileges.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/cases/privileges.spec.ts @@ -18,184 +18,28 @@ import { filterStatusOpen, } from '../../tasks/create_new_case'; import { - constructUrlWithUser, - getEnvAuth, + loginAndWaitForHostDetailsPage, loginWithUserAndWaitForPageWithoutDateRange, + logout, } from '../../tasks/login'; +import { + createUsersAndRoles, + deleteUsersAndRoles, + secAll, + secAllUser, + secReadCasesAllUser, + secReadCasesAll, +} from '../../tasks/privileges'; import { CASES_URL } from '../../urls/navigation'; - -interface User { - username: string; - password: string; - description?: string; - roles: string[]; -} - -interface UserInfo { - username: string; - full_name: string; - email: string; -} - -interface FeaturesPrivileges { - [featureId: string]: string[]; -} - -interface ElasticsearchIndices { - names: string[]; - privileges: string[]; -} - -interface ElasticSearchPrivilege { - cluster?: string[]; - indices?: ElasticsearchIndices[]; -} - -interface KibanaPrivilege { - spaces: string[]; - base?: string[]; - feature?: FeaturesPrivileges; -} - -interface Role { - name: string; - privileges: { - elasticsearch?: ElasticSearchPrivilege; - kibana?: KibanaPrivilege[]; - }; -} - -const secAll: Role = { - name: 'sec_all_role', - privileges: { - elasticsearch: { - indices: [ - { - names: ['*'], - privileges: ['all'], - }, - ], - }, - kibana: [ - { - feature: { - siem: ['all'], - securitySolutionCases: ['all'], - actions: ['all'], - actionsSimulators: ['all'], - }, - spaces: ['*'], - }, - ], - }, -}; - -const secAllUser: User = { - username: 'sec_all_user', - password: 'password', - roles: [secAll.name], -}; - -const secReadCasesAll: Role = { - name: 'sec_read_cases_all_role', - privileges: { - elasticsearch: { - indices: [ - { - names: ['*'], - privileges: ['all'], - }, - ], - }, - kibana: [ - { - feature: { - siem: ['read'], - securitySolutionCases: ['all'], - actions: ['all'], - actionsSimulators: ['all'], - }, - spaces: ['*'], - }, - ], - }, -}; - -const secReadCasesAllUser: User = { - username: 'sec_read_cases_all_user', - password: 'password', - roles: [secReadCasesAll.name], -}; - +import { openSourcerer } from '../../tasks/sourcerer'; const usersToCreate = [secAllUser, secReadCasesAllUser]; const rolesToCreate = [secAll, secReadCasesAll]; - -const getUserInfo = (user: User): UserInfo => ({ - username: user.username, - full_name: user.username.replace('_', ' '), - email: `${user.username}@elastic.co`, -}); - -const createUsersAndRoles = (users: User[], roles: Role[]) => { - const envUser = getEnvAuth(); - for (const role of roles) { - cy.log(`Creating role: ${JSON.stringify(role)}`); - cy.request({ - body: role.privileges, - headers: { 'kbn-xsrf': 'cypress-creds-via-config' }, - method: 'PUT', - url: constructUrlWithUser(envUser, `/api/security/role/${role.name}`), - }) - .its('status') - .should('eql', 204); - } - - for (const user of users) { - const userInfo = getUserInfo(user); - cy.log(`Creating user: ${JSON.stringify(user)}`); - cy.request({ - body: { - username: user.username, - password: user.password, - roles: user.roles, - full_name: userInfo.full_name, - email: userInfo.email, - }, - headers: { 'kbn-xsrf': 'cypress-creds-via-config' }, - method: 'POST', - url: constructUrlWithUser(envUser, `/internal/security/users/${user.username}`), - }) - .its('status') - .should('eql', 200); - } -}; - -const deleteUsersAndRoles = (users: User[], roles: Role[]) => { - const envUser = getEnvAuth(); - for (const user of users) { - cy.log(`Deleting user: ${JSON.stringify(user)}`); - cy.request({ - headers: { 'kbn-xsrf': 'cypress-creds-via-config' }, - method: 'DELETE', - url: constructUrlWithUser(envUser, `/internal/security/users/${user.username}`), - failOnStatusCode: false, - }) - .its('status') - .should('oneOf', [204, 404]); - } - - for (const role of roles) { - cy.log(`Deleting role: ${JSON.stringify(role)}`); - cy.request({ - headers: { 'kbn-xsrf': 'cypress-creds-via-config' }, - method: 'DELETE', - url: constructUrlWithUser(envUser, `/api/security/role/${role.name}`), - failOnStatusCode: false, - }) - .its('status') - .should('oneOf', [204, 404]); - } +// needed to generate index pattern +const visitSecuritySolution = () => { + loginAndWaitForHostDetailsPage(); + openSourcerer(); + logout(); }; const testCase: TestCaseWithoutTimeline = { @@ -205,11 +49,11 @@ const testCase: TestCaseWithoutTimeline = { reporter: 'elastic', owner: 'securitySolution', }; - describe('Cases privileges', () => { before(() => { cleanKibana(); createUsersAndRoles(usersToCreate, rolesToCreate); + visitSecuritySolution(); }); after(() => { diff --git a/x-pack/plugins/security_solution/cypress/integration/data_sources/sourcerer.spec.ts b/x-pack/plugins/security_solution/cypress/integration/data_sources/sourcerer.spec.ts index 26c366e981d44..bd7acc38c1021 100644 --- a/x-pack/plugins/security_solution/cypress/integration/data_sources/sourcerer.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/data_sources/sourcerer.spec.ts @@ -5,7 +5,10 @@ * 2.0. */ -import { loginAndWaitForPage } from '../../tasks/login'; +import { + loginAndWaitForPage, + loginWithUserAndWaitForPageWithoutDateRange, +} from '../../tasks/login'; import { HOSTS_URL } from '../../urls/navigation'; import { waitForAllHostsToBeLoaded } from '../../tasks/hosts/all_hosts'; @@ -28,20 +31,34 @@ import { openTimelineUsingToggle } from '../../tasks/security_main'; import { populateTimeline } from '../../tasks/timeline'; import { SERVER_SIDE_EVENT_COUNT } from '../../screens/timeline'; import { cleanKibana } from '../../tasks/common'; +import { createUsersAndRoles, secReadCasesAll, secReadCasesAllUser } from '../../tasks/privileges'; +import { TOASTER } from '../../screens/configure_cases'; +const usersToCreate = [secReadCasesAllUser]; +const rolesToCreate = [secReadCasesAll]; // Skipped at the moment as this has flake due to click handler issues. This has been raised with team members // and the code is being re-worked and then these tests will be unskipped -describe.skip('Sourcerer', () => { - before(() => { +describe('Sourcerer', () => { + beforeEach(() => { cleanKibana(); }); - - beforeEach(() => { - cy.clearLocalStorage(); - loginAndWaitForPage(HOSTS_URL); + describe('permissions', () => { + before(() => { + createUsersAndRoles(usersToCreate, rolesToCreate); + }); + it(`role(s) ${secReadCasesAllUser.roles.join()} shows error when user does not have permissions`, () => { + loginWithUserAndWaitForPageWithoutDateRange(HOSTS_URL, secReadCasesAllUser); + cy.get(TOASTER).should('have.text', 'Write role required to generate data'); + }); }); + // Originially written in December 2020, flakey from day1 + // has always been skipped with intentions to fix, see note at top of file + describe.skip('Default scope', () => { + beforeEach(() => { + cy.clearLocalStorage(); + loginAndWaitForPage(HOSTS_URL); + }); - describe('Default scope', () => { it('has SIEM index patterns selected on initial load', () => { openSourcerer(); isSourcererSelection(`auditbeat-*`); @@ -52,7 +69,7 @@ describe.skip('Sourcerer', () => { isSourcererOptions([`metrics-*`, `logs-*`]); }); - it('selected KIP gets added to sourcerer', () => { + it('selected DATA_VIEW gets added to sourcerer', () => { setSourcererOption(`metrics-*`); openSourcerer(); isSourcererSelection(`metrics-*`); @@ -75,8 +92,14 @@ describe.skip('Sourcerer', () => { isNotSourcererSelection(`metrics-*`); }); }); + // Originially written in December 2020, flakey from day1 + // has always been skipped with intentions to fix + describe.skip('Timeline scope', () => { + beforeEach(() => { + cy.clearLocalStorage(); + loginAndWaitForPage(HOSTS_URL); + }); - describe('Timeline scope', () => { const alertPatterns = ['.siem-signals-default']; const rawPatterns = ['auditbeat-*']; const allPatterns = [...alertPatterns, ...rawPatterns]; diff --git a/x-pack/plugins/security_solution/cypress/integration/detection_alerts/alerts_details.spec.ts b/x-pack/plugins/security_solution/cypress/integration/detection_alerts/alerts_details.spec.ts index 803ff4b4d0d80..033a12dd9de3e 100644 --- a/x-pack/plugins/security_solution/cypress/integration/detection_alerts/alerts_details.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/detection_alerts/alerts_details.spec.ts @@ -9,6 +9,7 @@ import { ALERT_FLYOUT, CELL_TEXT, JSON_TEXT, TABLE_ROWS } from '../../screens/al import { expandFirstAlert, + refreshAlerts, waitForAlertsIndexToBeCreated, waitForAlertsPanelToBeLoaded, } from '../../tasks/alerts'; @@ -32,6 +33,7 @@ describe('Alert details with unmapped fields', () => { createCustomRuleActivated(getUnmappedRule()); loginAndWaitForPageWithoutDateRange(ALERTS_URL); waitForAlertsPanelToBeLoaded(); + refreshAlerts(); expandFirstAlert(); }); diff --git a/x-pack/plugins/security_solution/cypress/integration/detection_alerts/attach_to_case.spec.ts b/x-pack/plugins/security_solution/cypress/integration/detection_alerts/attach_to_case.spec.ts index 49c2dd4b41717..e5b2c4eed3b00 100644 --- a/x-pack/plugins/security_solution/cypress/integration/detection_alerts/attach_to_case.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/detection_alerts/attach_to_case.spec.ts @@ -54,6 +54,7 @@ describe('Alerts timeline', () => { loadDetectionsPage(ROLES.platform_engineer); }); + // Skipping due to alerts not refreshing for platform_engineer despite being returned from API? it.skip('should allow a user with crud privileges to attach alerts to cases', () => { cy.get(TIMELINE_CONTEXT_MENU_BTN).first().click({ force: true }); cy.get(ATTACH_ALERT_TO_CASE_BUTTON).first().should('not.be.disabled'); diff --git a/x-pack/plugins/security_solution/cypress/integration/detection_rules/event_correlation_rule.spec.ts b/x-pack/plugins/security_solution/cypress/integration/detection_rules/event_correlation_rule.spec.ts index 10f556a11bf60..171d224cc32d3 100644 --- a/x-pack/plugins/security_solution/cypress/integration/detection_rules/event_correlation_rule.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/detection_rules/event_correlation_rule.spec.ts @@ -70,7 +70,7 @@ import { loginAndWaitForPageWithoutDateRange } from '../../tasks/login'; import { ALERTS_URL } from '../../urls/navigation'; -describe.skip('Detection rules, EQL', () => { +describe('Detection rules, EQL', () => { const expectedUrls = getEqlRule().referenceUrls.join(''); const expectedFalsePositives = getEqlRule().falsePositivesExamples.join(''); const expectedTags = getEqlRule().tags.join(''); @@ -169,7 +169,7 @@ describe.skip('Detection rules, EQL', () => { }); }); -describe.skip('Detection rules, sequence EQL', () => { +describe('Detection rules, sequence EQL', () => { const expectedNumberOfRules = 1; const expectedNumberOfSequenceAlerts = '1 alert'; diff --git a/x-pack/plugins/security_solution/cypress/integration/detection_rules/indicator_match_rule.spec.ts b/x-pack/plugins/security_solution/cypress/integration/detection_rules/indicator_match_rule.spec.ts index 02621ea49e906..378de8f0bc593 100644 --- a/x-pack/plugins/security_solution/cypress/integration/detection_rules/indicator_match_rule.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/detection_rules/indicator_match_rule.spec.ts @@ -114,7 +114,7 @@ import { loginAndWaitForPageWithoutDateRange } from '../../tasks/login'; import { goBackToAllRulesTable } from '../../tasks/rule_details'; import { ALERTS_URL, RULE_CREATION } from '../../urls/navigation'; -import { DEFAULT_THREAT_MATCH_QUERY } from '../../../common/constants'; +const DEFAULT_THREAT_MATCH_QUERY = '@timestamp >= "now-30d"'; describe('indicator match', () => { describe('Detection rules, Indicator Match', () => { diff --git a/x-pack/plugins/security_solution/cypress/integration/detection_rules/sorting.spec.ts b/x-pack/plugins/security_solution/cypress/integration/detection_rules/sorting.spec.ts index ef3d3a82d40bd..92f9e8180d50c 100644 --- a/x-pack/plugins/security_solution/cypress/integration/detection_rules/sorting.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/detection_rules/sorting.spec.ts @@ -34,7 +34,6 @@ import { waitForRuleToChangeStatus, } from '../../tasks/alerts_detection_rules'; import { loginAndWaitForPageWithoutDateRange } from '../../tasks/login'; -import { DEFAULT_RULE_REFRESH_INTERVAL_VALUE } from '../../../common/constants'; import { ALERTS_URL } from '../../urls/navigation'; import { createCustomRule } from '../../tasks/api_calls/rules'; @@ -46,6 +45,8 @@ import { getNewThresholdRule, } from '../../objects/rule'; +const DEFAULT_RULE_REFRESH_INTERVAL_VALUE = 60000; + describe('Alerts detection rules', () => { beforeEach(() => { cleanKibana(); diff --git a/x-pack/plugins/security_solution/cypress/integration/ml/ml_conditional_links.spec.ts b/x-pack/plugins/security_solution/cypress/integration/ml/ml_conditional_links.spec.ts index 89a0d5a660b97..f9d78ba12a5ea 100644 --- a/x-pack/plugins/security_solution/cypress/integration/ml/ml_conditional_links.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/ml/ml_conditional_links.spec.ts @@ -98,7 +98,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlNetworkSingleIpNullKqlQuery); cy.url().should( 'include', - 'app/security/network/ip/127.0.0.1/source?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))&sourcerer=(default:!(%27auditbeat-*%27))' + 'app/security/network/ip/127.0.0.1/source?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))&sourcerer=(default:(id:security-solution-default,selectedPatterns:!(%27auditbeat-*%27)))' ); }); @@ -106,7 +106,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlNetworkSingleIpKqlQuery); cy.url().should( 'include', - '/app/security/network/ip/127.0.0.1/source?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))&sourcerer=(default:!(%27auditbeat-*%27))' + '/app/security/network/ip/127.0.0.1/source?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))&sourcerer=(default:(id:security-solution-default,selectedPatterns:!(%27auditbeat-*%27)))' ); }); @@ -114,7 +114,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlNetworkMultipleIpNullKqlQuery); cy.url().should( 'include', - 'app/security/network/flows?query=(language:kuery,query:%27((source.ip:%20%22127.0.0.1%22%20or%20destination.ip:%20%22127.0.0.1%22)%20or%20(source.ip:%20%22127.0.0.2%22%20or%20destination.ip:%20%22127.0.0.2%22))%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))&sourcerer=(default:!(%27auditbeat-*%27))' + 'app/security/network/flows?query=(language:kuery,query:%27((source.ip:%20%22127.0.0.1%22%20or%20destination.ip:%20%22127.0.0.1%22)%20or%20(source.ip:%20%22127.0.0.2%22%20or%20destination.ip:%20%22127.0.0.2%22))%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))&sourcerer=(default:(id:security-solution-default,selectedPatterns:!(%27auditbeat-*%27)))' ); }); @@ -122,7 +122,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlNetworkMultipleIpKqlQuery); cy.url().should( 'include', - '/app/security/network/flows?query=(language:kuery,query:%27((source.ip:%20%22127.0.0.1%22%20or%20destination.ip:%20%22127.0.0.1%22)%20or%20(source.ip:%20%22127.0.0.2%22%20or%20destination.ip:%20%22127.0.0.2%22))%20and%20((process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22))%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))&sourcerer=(default:!(%27auditbeat-*%27))' + '/app/security/network/flows?query=(language:kuery,query:%27((source.ip:%20%22127.0.0.1%22%20or%20destination.ip:%20%22127.0.0.1%22)%20or%20(source.ip:%20%22127.0.0.2%22%20or%20destination.ip:%20%22127.0.0.2%22))%20and%20((process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22))%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))&sourcerer=(default:(id:security-solution-default,selectedPatterns:!(%27auditbeat-*%27)))' ); }); @@ -130,15 +130,16 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlNetworkNullKqlQuery); cy.url().should( 'include', - '/app/security/network/flows?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))&sourcerer=(default:!(%27auditbeat-*%27))' + '/app/security/network/flows?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))&sourcerer=(default:(id:security-solution-default,selectedPatterns:!(%27auditbeat-*%27)))' ); }); it('redirects from a $ip$ with a value for the query', () => { loginAndWaitForPageWithoutDateRange(mlNetworkKqlQuery); + cy.url().should( 'include', - '/app/security/network/flows?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))&sourcerer=(default:!(%27auditbeat-*%27))' + `/app/security/network/flows?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))&sourcerer=(default:(id:security-solution-default,selectedPatterns:!(%27auditbeat-*%27)))` ); }); @@ -146,7 +147,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlHostSingleHostNullKqlQuery); cy.url().should( 'include', - '/app/security/hosts/siem-windows/anomalies?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))&sourcerer=(default:!(%27auditbeat-*%27))' + '/app/security/hosts/siem-windows/anomalies?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))&sourcerer=(default:(id:security-solution-default,selectedPatterns:!(%27auditbeat-*%27)))' ); }); @@ -154,7 +155,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlHostSingleHostKqlQueryVariable); cy.url().should( 'include', - '/app/security/hosts/siem-windows/anomalies?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))&sourcerer=(default:!(%27auditbeat-*%27))' + '/app/security/hosts/siem-windows/anomalies?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))&sourcerer=(default:(id:security-solution-default,selectedPatterns:!(%27auditbeat-*%27)))' ); }); @@ -162,7 +163,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlHostSingleHostKqlQuery); cy.url().should( 'include', - '/app/security/hosts/siem-windows/anomalies?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))&sourcerer=(default:!(%27auditbeat-*%27))' + '/app/security/hosts/siem-windows/anomalies?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))&sourcerer=(default:(id:security-solution-default,selectedPatterns:!(%27auditbeat-*%27)))' ); }); @@ -170,7 +171,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlHostMultiHostNullKqlQuery); cy.url().should( 'include', - '/app/security/hosts/anomalies?query=(language:kuery,query:%27(host.name:%20%22siem-windows%22%20or%20host.name:%20%22siem-suricata%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))&sourcerer=(default:!(%27auditbeat-*%27))' + '/app/security/hosts/anomalies?query=(language:kuery,query:%27(host.name:%20%22siem-windows%22%20or%20host.name:%20%22siem-suricata%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))&sourcerer=(default:(id:security-solution-default,selectedPatterns:!(%27auditbeat-*%27)))' ); }); @@ -178,7 +179,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlHostMultiHostKqlQuery); cy.url().should( 'include', - '/app/security/hosts/anomalies?query=(language:kuery,query:%27(host.name:%20%22siem-windows%22%20or%20host.name:%20%22siem-suricata%22)%20and%20((process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22))%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))&sourcerer=(default:!(%27auditbeat-*%27))' + '/app/security/hosts/anomalies?query=(language:kuery,query:%27(host.name:%20%22siem-windows%22%20or%20host.name:%20%22siem-suricata%22)%20and%20((process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22))%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))&sourcerer=(default:(id:security-solution-default,selectedPatterns:!(%27auditbeat-*%27)))' ); }); @@ -186,7 +187,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlHostVariableHostNullKqlQuery); cy.url().should( 'include', - '/app/security/hosts/anomalies?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))&sourcerer=(default:!(%27auditbeat-*%27))' + '/app/security/hosts/anomalies?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))&sourcerer=(default:(id:security-solution-default,selectedPatterns:!(%27auditbeat-*%27)))' ); }); @@ -194,7 +195,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlHostVariableHostKqlQuery); cy.url().should( 'include', - '/app/security/hosts/anomalies?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))&sourcerer=(default:!(%27auditbeat-*%27))' + '/app/security/hosts/anomalies?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))&sourcerer=(default:(id:security-solution-default,selectedPatterns:!(%27auditbeat-*%27)))' ); }); }); diff --git a/x-pack/plugins/security_solution/cypress/integration/timelines/creation.spec.ts b/x-pack/plugins/security_solution/cypress/integration/timelines/creation.spec.ts index fb41aec91b6c4..cbff911e5d982 100644 --- a/x-pack/plugins/security_solution/cypress/integration/timelines/creation.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/timelines/creation.spec.ts @@ -121,7 +121,6 @@ describe('Create a timeline from a template', () => { loginAndWaitForPageWithoutDateRange(TIMELINE_TEMPLATES_URL); waitForTimelinesPanelToBeLoaded(); }); - it('Should have the same query and open the timeline modal', () => { selectCustomTemplates(); cy.wait('@timeline', { timeout: 100000 }); @@ -132,5 +131,6 @@ describe('Create a timeline from a template', () => { cy.get(TIMELINE_FLYOUT_WRAPPER).should('have.css', 'visibility', 'visible'); cy.get(TIMELINE_DESCRIPTION).should('have.text', getTimeline().description); cy.get(TIMELINE_QUERY).should('have.text', getTimeline().query); + closeTimeline(); }); }); diff --git a/x-pack/plugins/security_solution/cypress/integration/urls/state.spec.ts b/x-pack/plugins/security_solution/cypress/integration/urls/state.spec.ts index 73eb141f1ce3d..28fe1294e6f01 100644 --- a/x-pack/plugins/security_solution/cypress/integration/urls/state.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/urls/state.spec.ts @@ -182,11 +182,10 @@ describe('url state', () => { loginAndWaitForPageWithoutDateRange(ABSOLUTE_DATE_RANGE.url); kqlSearch('source.ip: "10.142.0.9" {enter}'); navigateFromHeaderTo(HOSTS); - cy.get(NETWORK).should( 'have.attr', 'href', - `/app/security/network?query=(language:kuery,query:'source.ip:%20%2210.142.0.9%22%20')&sourcerer=(default:!(\'auditbeat-*\'))&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2019-08-01T20:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2019-08-01T20:33:29.186Z')))` + `/app/security/network?query=(language:kuery,query:'source.ip:%20%2210.142.0.9%22%20')&sourcerer=(default:(id:security-solution-default,selectedPatterns:!('auditbeat-*')))&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2019-08-01T20:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2019-08-01T20:33:29.186Z')))` ); }); @@ -199,12 +198,12 @@ describe('url state', () => { cy.get(HOSTS).should( 'have.attr', 'href', - `/app/security/hosts?query=(language:kuery,query:'host.name:%20%22siem-kibana%22%20')&sourcerer=(default:!(\'auditbeat-*\'))&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')))` + `/app/security/hosts?query=(language:kuery,query:'host.name:%20%22siem-kibana%22%20')&sourcerer=(default:(id:security-solution-default,selectedPatterns:!('auditbeat-*')))&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')))` ); cy.get(NETWORK).should( 'have.attr', 'href', - `/app/security/network?query=(language:kuery,query:'host.name:%20%22siem-kibana%22%20')&sourcerer=(default:!(\'auditbeat-*\'))&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')))` + `/app/security/network?query=(language:kuery,query:'host.name:%20%22siem-kibana%22%20')&sourcerer=(default:(id:security-solution-default,selectedPatterns:!('auditbeat-*')))&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')))` ); cy.get(HOSTS_NAMES).first().should('have.text', 'siem-kibana'); @@ -215,21 +214,21 @@ describe('url state', () => { cy.get(ANOMALIES_TAB).should( 'have.attr', 'href', - "/app/security/hosts/siem-kibana/anomalies?sourcerer=(default:!('auditbeat-*'))&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')))&query=(language:kuery,query:'agent.type:%20%22auditbeat%22%20')" + "/app/security/hosts/siem-kibana/anomalies?sourcerer=(default:(id:security-solution-default,selectedPatterns:!('auditbeat-*')))&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')))&query=(language:kuery,query:'agent.type:%20%22auditbeat%22%20')" ); cy.get(BREADCRUMBS) .eq(1) .should( 'have.attr', 'href', - `/app/security/hosts?query=(language:kuery,query:'agent.type:%20%22auditbeat%22%20')&sourcerer=(default:!(\'auditbeat-*\'))&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')))` + `/app/security/hosts?query=(language:kuery,query:'agent.type:%20%22auditbeat%22%20')&sourcerer=(default:(id:security-solution-default,selectedPatterns:!('auditbeat-*')))&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')))` ); cy.get(BREADCRUMBS) .eq(2) .should( 'have.attr', 'href', - `/app/security/hosts/siem-kibana?query=(language:kuery,query:'agent.type:%20%22auditbeat%22%20')&sourcerer=(default:!(\'auditbeat-*\'))&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')))` + `/app/security/hosts/siem-kibana?query=(language:kuery,query:'agent.type:%20%22auditbeat%22%20')&sourcerer=(default:(id:security-solution-default,selectedPatterns:!('auditbeat-*')))&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')))` ); }); diff --git a/x-pack/plugins/security_solution/cypress/objects/rule.ts b/x-pack/plugins/security_solution/cypress/objects/rule.ts index ae04e20dfe86e..0a9eecf83c7fc 100644 --- a/x-pack/plugins/security_solution/cypress/objects/rule.ts +++ b/x-pack/plugins/security_solution/cypress/objects/rule.ts @@ -419,7 +419,63 @@ export const getEditedRule = (): CustomRule => ({ }); export const expectedExportedRule = (ruleResponse: Cypress.Response): string => { - const jsonrule = ruleResponse.body; - - return `{"id":"${jsonrule.id}","updated_at":"${jsonrule.updated_at}","updated_by":"elastic","created_at":"${jsonrule.created_at}","created_by":"elastic","name":"${jsonrule.name}","tags":[],"interval":"100m","enabled":false,"description":"${jsonrule.description}","risk_score":${jsonrule.risk_score},"severity":"${jsonrule.severity}","output_index":".siem-signals-default","author":[],"false_positives":[],"from":"now-50000h","rule_id":"rule_testing","max_signals":100,"risk_score_mapping":[],"severity_mapping":[],"threat":[],"to":"now","references":[],"version":1,"exceptions_list":[],"immutable":false,"type":"query","language":"kuery","index":["exceptions-*"],"query":"${jsonrule.query}","throttle":"no_actions","actions":[]}\n{"exported_rules_count":1,"missing_rules":[],"missing_rules_count":0,"exported_exception_list_count":0,"exported_exception_list_item_count":0,"missing_exception_list_item_count":0,"missing_exception_list_items":[],"missing_exception_lists":[],"missing_exception_lists_count":0}\n`; + const { + id, + updated_at: updatedAt, + updated_by: updatedBy, + created_at: createdAt, + description, + name, + risk_score: riskScore, + severity, + query, + } = ruleResponse.body; + const rule = { + id, + updated_at: updatedAt, + updated_by: updatedBy, + created_at: createdAt, + created_by: 'elastic', + name, + tags: [], + interval: '100m', + enabled: false, + description, + risk_score: riskScore, + severity, + output_index: '.siem-signals-default', + author: [], + false_positives: [], + from: 'now-50000h', + rule_id: 'rule_testing', + max_signals: 100, + risk_score_mapping: [], + severity_mapping: [], + threat: [], + to: 'now', + references: [], + version: 1, + exceptions_list: [], + immutable: false, + type: 'query', + language: 'kuery', + index: ['exceptions-*'], + query, + throttle: 'no_actions', + actions: [], + }; + const details = { + exported_count: 1, + exported_rules_count: 1, + missing_rules: [], + missing_rules_count: 0, + exported_exception_list_count: 0, + exported_exception_list_item_count: 0, + missing_exception_list_item_count: 0, + missing_exception_list_items: [], + missing_exception_lists: [], + missing_exception_lists_count: 0, + }; + + return `${JSON.stringify(rule)}\n${JSON.stringify(details)}\n`; }; diff --git a/x-pack/plugins/security_solution/cypress/objects/timeline.ts b/x-pack/plugins/security_solution/cypress/objects/timeline.ts index f3d9bc1b9ef1a..70b8c1b400d51 100644 --- a/x-pack/plugins/security_solution/cypress/objects/timeline.ts +++ b/x-pack/plugins/security_solution/cypress/objects/timeline.ts @@ -87,6 +87,7 @@ export const expectedExportedTimelineTemplate = ( }, }, }, + dataViewId: timelineTemplateBody.dataViewId, dateRange: { start: timelineTemplateBody.dateRange?.start, end: timelineTemplateBody.dateRange?.end, @@ -127,6 +128,7 @@ export const expectedExportedTimeline = (timelineResponse: Cypress.Response