diff --git a/.ci/end2end.groovy b/.ci/end2end.groovy index 8ad810717d86ed..8e9b041d32d3e8 100644 --- a/.ci/end2end.groovy +++ b/.ci/end2end.groovy @@ -13,7 +13,7 @@ pipeline { BASE_DIR = 'src/github.com/elastic/kibana' HOME = "${env.WORKSPACE}" APM_ITS = 'apm-integration-testing' - CYPRESS_DIR = 'x-pack/legacy/plugins/apm/e2e' + CYPRESS_DIR = 'x-pack/plugins/apm/e2e' PIPELINE_LOG_LEVEL = 'DEBUG' } options { @@ -39,7 +39,7 @@ pipeline { shallow: false, reference: "/var/lib/jenkins/.git-references/kibana.git") script { dir("${BASE_DIR}"){ - def regexps =[ "^x-pack/legacy/plugins/apm/.*" ] + def regexps =[ "^x-pack/plugins/apm/.*" ] env.APM_UPDATED = isGitRegionMatch(patterns: regexps) } } diff --git a/.ci/es-snapshots/Jenkinsfile_verify_es b/.ci/es-snapshots/Jenkinsfile_verify_es index 2655ca1b48c18b..75b686abe845f7 100644 --- a/.ci/es-snapshots/Jenkinsfile_verify_es +++ b/.ci/es-snapshots/Jenkinsfile_verify_es @@ -21,41 +21,46 @@ def SNAPSHOT_MANIFEST = "https://storage.googleapis.com/kibana-ci-es-snapshots-d kibanaPipeline(timeoutMinutes: 120) { catchErrors { - retryable.enable(2) - withEnv(["ES_SNAPSHOT_MANIFEST=${SNAPSHOT_MANIFEST}"]) { - parallel([ - 'kibana-intake-agent': workers.intake('kibana-intake', './test/scripts/jenkins_unit.sh'), - 'x-pack-intake-agent': workers.intake('x-pack-intake', './test/scripts/jenkins_xpack.sh'), - 'kibana-oss-agent': workers.functional('kibana-oss-tests', { kibanaPipeline.buildOss() }, [ - 'oss-ciGroup1': kibanaPipeline.ossCiGroupProcess(1), - 'oss-ciGroup2': kibanaPipeline.ossCiGroupProcess(2), - 'oss-ciGroup3': kibanaPipeline.ossCiGroupProcess(3), - 'oss-ciGroup4': kibanaPipeline.ossCiGroupProcess(4), - 'oss-ciGroup5': kibanaPipeline.ossCiGroupProcess(5), - 'oss-ciGroup6': kibanaPipeline.ossCiGroupProcess(6), - 'oss-ciGroup7': kibanaPipeline.ossCiGroupProcess(7), - 'oss-ciGroup8': kibanaPipeline.ossCiGroupProcess(8), - 'oss-ciGroup9': kibanaPipeline.ossCiGroupProcess(9), - 'oss-ciGroup10': kibanaPipeline.ossCiGroupProcess(10), - 'oss-ciGroup11': kibanaPipeline.ossCiGroupProcess(11), - 'oss-ciGroup12': kibanaPipeline.ossCiGroupProcess(12), - ]), - 'kibana-xpack-agent': workers.functional('kibana-xpack-tests', { kibanaPipeline.buildXpack() }, [ - 'xpack-ciGroup1': kibanaPipeline.xpackCiGroupProcess(1), - 'xpack-ciGroup2': kibanaPipeline.xpackCiGroupProcess(2), - 'xpack-ciGroup3': kibanaPipeline.xpackCiGroupProcess(3), - 'xpack-ciGroup4': kibanaPipeline.xpackCiGroupProcess(4), - 'xpack-ciGroup5': kibanaPipeline.xpackCiGroupProcess(5), - 'xpack-ciGroup6': kibanaPipeline.xpackCiGroupProcess(6), - 'xpack-ciGroup7': kibanaPipeline.xpackCiGroupProcess(7), - 'xpack-ciGroup8': kibanaPipeline.xpackCiGroupProcess(8), - 'xpack-ciGroup9': kibanaPipeline.xpackCiGroupProcess(9), - 'xpack-ciGroup10': kibanaPipeline.xpackCiGroupProcess(10), - ]), - ]) - } + slackNotifications.onFailure( + title: ":broken_heart: *<${env.BUILD_URL}|[${SNAPSHOT_VERSION}] ES Snapshot Verification Failure>*", + message: ":broken_heart: [${SNAPSHOT_VERSION}] ES Snapshot Verification Failure", + ) { + retryable.enable(2) + withEnv(["ES_SNAPSHOT_MANIFEST=${SNAPSHOT_MANIFEST}"]) { + parallel([ + 'kibana-intake-agent': workers.intake('kibana-intake', './test/scripts/jenkins_unit.sh'), + 'x-pack-intake-agent': workers.intake('x-pack-intake', './test/scripts/jenkins_xpack.sh'), + 'kibana-oss-agent': workers.functional('kibana-oss-tests', { kibanaPipeline.buildOss() }, [ + 'oss-ciGroup1': kibanaPipeline.ossCiGroupProcess(1), + 'oss-ciGroup2': kibanaPipeline.ossCiGroupProcess(2), + 'oss-ciGroup3': kibanaPipeline.ossCiGroupProcess(3), + 'oss-ciGroup4': kibanaPipeline.ossCiGroupProcess(4), + 'oss-ciGroup5': kibanaPipeline.ossCiGroupProcess(5), + 'oss-ciGroup6': kibanaPipeline.ossCiGroupProcess(6), + 'oss-ciGroup7': kibanaPipeline.ossCiGroupProcess(7), + 'oss-ciGroup8': kibanaPipeline.ossCiGroupProcess(8), + 'oss-ciGroup9': kibanaPipeline.ossCiGroupProcess(9), + 'oss-ciGroup10': kibanaPipeline.ossCiGroupProcess(10), + 'oss-ciGroup11': kibanaPipeline.ossCiGroupProcess(11), + 'oss-ciGroup12': kibanaPipeline.ossCiGroupProcess(12), + ]), + 'kibana-xpack-agent': workers.functional('kibana-xpack-tests', { kibanaPipeline.buildXpack() }, [ + 'xpack-ciGroup1': kibanaPipeline.xpackCiGroupProcess(1), + 'xpack-ciGroup2': kibanaPipeline.xpackCiGroupProcess(2), + 'xpack-ciGroup3': kibanaPipeline.xpackCiGroupProcess(3), + 'xpack-ciGroup4': kibanaPipeline.xpackCiGroupProcess(4), + 'xpack-ciGroup5': kibanaPipeline.xpackCiGroupProcess(5), + 'xpack-ciGroup6': kibanaPipeline.xpackCiGroupProcess(6), + 'xpack-ciGroup7': kibanaPipeline.xpackCiGroupProcess(7), + 'xpack-ciGroup8': kibanaPipeline.xpackCiGroupProcess(8), + 'xpack-ciGroup9': kibanaPipeline.xpackCiGroupProcess(9), + 'xpack-ciGroup10': kibanaPipeline.xpackCiGroupProcess(10), + ]), + ]) + } - promoteSnapshot(SNAPSHOT_VERSION, SNAPSHOT_ID) + promoteSnapshot(SNAPSHOT_VERSION, SNAPSHOT_ID) + } } kibanaPipeline.sendMail() diff --git a/.eslintignore b/.eslintignore index 4913192e81c1d9..53b3d807204390 100644 --- a/.eslintignore +++ b/.eslintignore @@ -25,7 +25,7 @@ target /src/plugins/vis_type_timelion/public/_generated_/** /src/plugins/vis_type_timelion/public/webpackShims/jquery.flot.* /x-pack/legacy/plugins/**/__tests__/fixtures/** -/x-pack/legacy/plugins/apm/e2e/cypress/**/snapshots.js +/x-pack/plugins/apm/e2e/cypress/**/snapshots.js /x-pack/legacy/plugins/canvas/canvas_plugin /x-pack/legacy/plugins/canvas/canvas_plugin_src/lib/flot-charts /x-pack/legacy/plugins/canvas/shareable_runtime/build diff --git a/.eslintrc.js b/.eslintrc.js index 8b33ec83347a85..9e3ab7cef8002a 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -151,6 +151,16 @@ module.exports = { }, }, + /** + * New Platform client-side + */ + { + files: ['{src,x-pack}/plugins/*/public/**/*.{js,ts,tsx}'], + rules: { + 'import/no-commonjs': 'error', + }, + }, + /** * Files that require Elastic license headers instead of Apache 2.0 header */ @@ -306,7 +316,7 @@ module.exports = { { files: [ 'x-pack/test/functional/apps/**/*.js', - 'x-pack/legacy/plugins/apm/**/*.js', + 'x-pack/plugins/apm/**/*.js', 'test/*/config.ts', 'test/*/config_open.ts', 'test/*/{tests,test_suites,apis,apps}/**/*', @@ -393,7 +403,7 @@ module.exports = { 'x-pack/**/*.test.js', 'x-pack/test_utils/**/*', 'x-pack/gulpfile.js', - 'x-pack/legacy/plugins/apm/public/utils/testHelpers.js', + 'x-pack/plugins/apm/public/utils/testHelpers.js', ], rules: { 'import/no-extraneous-dependencies': [ @@ -519,7 +529,7 @@ module.exports = { * APM overrides */ { - files: ['x-pack/legacy/plugins/apm/**/*.js'], + files: ['x-pack/plugins/apm/**/*.js'], rules: { 'no-unused-vars': ['error', { ignoreRestSiblings: true }], 'no-console': ['warn', { allow: ['error'] }], @@ -527,7 +537,7 @@ module.exports = { }, { plugins: ['react-hooks'], - files: ['x-pack/legacy/plugins/apm/**/*.{ts,tsx}'], + files: ['x-pack/plugins/apm/**/*.{ts,tsx}'], rules: { 'react-hooks/rules-of-hooks': 'error', // Checks rules of Hooks 'react-hooks/exhaustive-deps': ['error', { additionalHooks: '^useFetcher$' }], diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index a008fa7ea9239f..280cb6fbd1b1d6 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -8,8 +8,6 @@ /x-pack/plugins/graph/ @elastic/kibana-app /src/legacy/server/url_shortening/ @elastic/kibana-app /src/legacy/server/sample_data/ @elastic/kibana-app -/src/legacy/core_plugins/kibana/public/dashboard/ @elastic/kibana-app -/src/legacy/core_plugins/kibana/public/discover/ @elastic/kibana-app /src/legacy/core_plugins/kibana/public/local_application_service/ @elastic/kibana-app /src/legacy/core_plugins/kibana/public/dev_tools/ @elastic/kibana-app /src/plugins/dashboard/ @elastic/kibana-app @@ -68,7 +66,7 @@ /x-pack/plugins/drilldowns/ @elastic/kibana-app-arch # APM -/x-pack/legacy/plugins/apm/ @elastic/apm-ui +/x-pack/plugins/apm/ @elastic/apm-ui /x-pack/plugins/apm/ @elastic/apm-ui /x-pack/test/functional/apps/apm/ @elastic/apm-ui /src/legacy/core_plugins/apm_oss/ @elastic/apm-ui diff --git a/.github/paths-labeller.yml b/.github/paths-labeller.yml index 89e0af270c54dd..efdb041e2b37ab 100644 --- a/.github/paths-labeller.yml +++ b/.github/paths-labeller.yml @@ -10,7 +10,7 @@ - "src/plugins/bfetch/**/*.*" - "Team:apm" - "x-pack/plugins/apm/**/*.*" - - "x-pack/legacy/plugins/apm/**/*.*" + - "x-pack/plugins/apm/**/*.*" - "Team:uptime": - "x-pack/plugins/uptime/**/*.*" - "x-pack/legacy/plugins/uptime/**/*.*" diff --git a/.gitignore b/.gitignore index bd7a954f950e9f..13c7cd5fb2769d 100644 --- a/.gitignore +++ b/.gitignore @@ -44,6 +44,6 @@ package-lock.json *.sublime-* npm-debug.log* .tern-project -x-pack/legacy/plugins/apm/tsconfig.json +x-pack/plugins/apm/tsconfig.json apm.tsconfig.json -/x-pack/legacy/plugins/apm/e2e/snapshots.js +/x-pack/plugins/apm/e2e/snapshots.js diff --git a/config/kibana.yml b/config/kibana.yml index 0780841ca057ed..8725888159506e 100644 --- a/config/kibana.yml +++ b/config/kibana.yml @@ -40,7 +40,7 @@ # the username and password that the Kibana server uses to perform maintenance on the Kibana # index at startup. Your Kibana users still need to authenticate with Elasticsearch, which # is proxied through the Kibana server. -#elasticsearch.username: "kibana" +#elasticsearch.username: "kibana_system" #elasticsearch.password: "pass" # Enables SSL and paths to the PEM-format SSL certificate and SSL key files, respectively. diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.__spec.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.__spec.md deleted file mode 100644 index 43ff9a930b974d..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.__spec.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [$$spec](./kibana-plugin-plugins-data-public.field.__spec.md) - -## Field.$$spec property - -Signature: - -```typescript -$$spec: FieldSpec; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.aggregatable.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.aggregatable.md deleted file mode 100644 index fcfd7d73c8b0ce..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.aggregatable.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [aggregatable](./kibana-plugin-plugins-data-public.field.aggregatable.md) - -## Field.aggregatable property - -Signature: - -```typescript -aggregatable?: boolean; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.conflictdescriptions.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.conflictdescriptions.md deleted file mode 100644 index 21b6917c4aad41..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.conflictdescriptions.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [conflictDescriptions](./kibana-plugin-plugins-data-public.field.conflictdescriptions.md) - -## Field.conflictDescriptions property - -Signature: - -```typescript -conflictDescriptions?: Record; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.count.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.count.md deleted file mode 100644 index 4f51d88a3046ed..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.count.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [count](./kibana-plugin-plugins-data-public.field.count.md) - -## Field.count property - -Signature: - -```typescript -count?: number; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.displayname.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.displayname.md deleted file mode 100644 index 0846a7595cf907..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.displayname.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [displayName](./kibana-plugin-plugins-data-public.field.displayname.md) - -## Field.displayName property - -Signature: - -```typescript -displayName?: string; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.estypes.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.estypes.md deleted file mode 100644 index efe1bceb43361a..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.estypes.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [esTypes](./kibana-plugin-plugins-data-public.field.estypes.md) - -## Field.esTypes property - -Signature: - -```typescript -esTypes?: string[]; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.filterable.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.filterable.md deleted file mode 100644 index fd7be589e87a79..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.filterable.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [filterable](./kibana-plugin-plugins-data-public.field.filterable.md) - -## Field.filterable property - -Signature: - -```typescript -filterable?: boolean; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.format.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.format.md deleted file mode 100644 index 431e043d1fecc6..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.format.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [format](./kibana-plugin-plugins-data-public.field.format.md) - -## Field.format property - -Signature: - -```typescript -format: any; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.indexpattern.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.indexpattern.md deleted file mode 100644 index 59420747e0958e..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.indexpattern.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [indexPattern](./kibana-plugin-plugins-data-public.field.indexpattern.md) - -## Field.indexPattern property - -Signature: - -```typescript -indexPattern?: IndexPattern; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.lang.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.lang.md deleted file mode 100644 index d51857090356fe..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.lang.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [lang](./kibana-plugin-plugins-data-public.field.lang.md) - -## Field.lang property - -Signature: - -```typescript -lang?: string; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.md deleted file mode 100644 index 86ff2b2c28ae94..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.md +++ /dev/null @@ -1,41 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) - -## Field class - -Signature: - -```typescript -export declare class Field implements IFieldType -``` - -## Constructors - -| Constructor | Modifiers | Description | -| --- | --- | --- | -| [(constructor)(indexPattern, spec, shortDotsEnable)](./kibana-plugin-plugins-data-public.field._constructor_.md) | | Constructs a new instance of the Field class | - -## Properties - -| Property | Modifiers | Type | Description | -| --- | --- | --- | --- | -| [$$spec](./kibana-plugin-plugins-data-public.field.__spec.md) | | FieldSpec | | -| [aggregatable](./kibana-plugin-plugins-data-public.field.aggregatable.md) | | boolean | | -| [conflictDescriptions](./kibana-plugin-plugins-data-public.field.conflictdescriptions.md) | | Record<string, string[]> | | -| [count](./kibana-plugin-plugins-data-public.field.count.md) | | number | | -| [displayName](./kibana-plugin-plugins-data-public.field.displayname.md) | | string | | -| [esTypes](./kibana-plugin-plugins-data-public.field.estypes.md) | | string[] | | -| [filterable](./kibana-plugin-plugins-data-public.field.filterable.md) | | boolean | | -| [format](./kibana-plugin-plugins-data-public.field.format.md) | | any | | -| [indexPattern](./kibana-plugin-plugins-data-public.field.indexpattern.md) | | IndexPattern | | -| [lang](./kibana-plugin-plugins-data-public.field.lang.md) | | string | | -| [name](./kibana-plugin-plugins-data-public.field.name.md) | | string | | -| [script](./kibana-plugin-plugins-data-public.field.script.md) | | string | | -| [scripted](./kibana-plugin-plugins-data-public.field.scripted.md) | | boolean | | -| [searchable](./kibana-plugin-plugins-data-public.field.searchable.md) | | boolean | | -| [sortable](./kibana-plugin-plugins-data-public.field.sortable.md) | | boolean | | -| [subType](./kibana-plugin-plugins-data-public.field.subtype.md) | | IFieldSubType | | -| [type](./kibana-plugin-plugins-data-public.field.type.md) | | string | | -| [visualizable](./kibana-plugin-plugins-data-public.field.visualizable.md) | | boolean | | - diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.name.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.name.md deleted file mode 100644 index d2a9b9b86aefc9..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.name.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [name](./kibana-plugin-plugins-data-public.field.name.md) - -## Field.name property - -Signature: - -```typescript -name: string; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.script.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.script.md deleted file mode 100644 index 676ff9bdfc35a7..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.script.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [script](./kibana-plugin-plugins-data-public.field.script.md) - -## Field.script property - -Signature: - -```typescript -script?: string; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.scripted.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.scripted.md deleted file mode 100644 index 1f6c8105e3f618..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.scripted.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [scripted](./kibana-plugin-plugins-data-public.field.scripted.md) - -## Field.scripted property - -Signature: - -```typescript -scripted?: boolean; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.searchable.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.searchable.md deleted file mode 100644 index 186d344f503788..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.searchable.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [searchable](./kibana-plugin-plugins-data-public.field.searchable.md) - -## Field.searchable property - -Signature: - -```typescript -searchable?: boolean; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.sortable.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.sortable.md deleted file mode 100644 index 0cd4b14d0e1e5c..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.sortable.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [sortable](./kibana-plugin-plugins-data-public.field.sortable.md) - -## Field.sortable property - -Signature: - -```typescript -sortable?: boolean; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.subtype.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.subtype.md deleted file mode 100644 index bef3b2131fa475..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.subtype.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [subType](./kibana-plugin-plugins-data-public.field.subtype.md) - -## Field.subType property - -Signature: - -```typescript -subType?: IFieldSubType; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.type.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.type.md deleted file mode 100644 index 490615edcf097e..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.type.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [type](./kibana-plugin-plugins-data-public.field.type.md) - -## Field.type property - -Signature: - -```typescript -type: string; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.visualizable.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.visualizable.md deleted file mode 100644 index f32a5c456dc5db..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field.visualizable.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [visualizable](./kibana-plugin-plugins-data-public.field.visualizable.md) - -## Field.visualizable property - -Signature: - -```typescript -visualizable?: boolean; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.getindexpatternfieldlistcreator.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.getindexpatternfieldlistcreator.md new file mode 100644 index 00000000000000..60302286cbd728 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.getindexpatternfieldlistcreator.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [getIndexPatternFieldListCreator](./kibana-plugin-plugins-data-public.getindexpatternfieldlistcreator.md) + +## getIndexPatternFieldListCreator variable + +Signature: + +```typescript +getIndexPatternFieldListCreator: ({ fieldFormats, toastNotifications, }: FieldListDependencies) => CreateIndexPatternFieldList +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.add.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.add.md new file mode 100644 index 00000000000000..0f3469ae9c5505 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.add.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IIndexPatternFieldList](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.md) > [add](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.add.md) + +## IIndexPatternFieldList.add() method + +Signature: + +```typescript +add(field: FieldSpec): void; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| field | FieldSpec | | + +Returns: + +`void` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.getbyname.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.getbyname.md new file mode 100644 index 00000000000000..14b5aa7137dc2c --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.getbyname.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IIndexPatternFieldList](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.md) > [getByName](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.getbyname.md) + +## IIndexPatternFieldList.getByName() method + +Signature: + +```typescript +getByName(name: Field['name']): Field | undefined; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| name | Field['name'] | | + +Returns: + +`Field | undefined` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.getbytype.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.getbytype.md new file mode 100644 index 00000000000000..3c65b78e5291db --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.getbytype.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IIndexPatternFieldList](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.md) > [getByType](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.getbytype.md) + +## IIndexPatternFieldList.getByType() method + +Signature: + +```typescript +getByType(type: Field['type']): Field[]; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| type | Field['type'] | | + +Returns: + +`Field[]` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.md new file mode 100644 index 00000000000000..47d7c7491aa86f --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IIndexPatternFieldList](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.md) + +## IIndexPatternFieldList interface + +Signature: + +```typescript +export interface IIndexPatternFieldList extends Array +``` + +## Methods + +| Method | Description | +| --- | --- | +| [add(field)](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.add.md) | | +| [getByName(name)](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.getbyname.md) | | +| [getByType(type)](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.getbytype.md) | | +| [remove(field)](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.remove.md) | | +| [update(field)](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.update.md) | | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.remove.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.remove.md new file mode 100644 index 00000000000000..3b6bbb0691930c --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.remove.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IIndexPatternFieldList](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.md) > [remove](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.remove.md) + +## IIndexPatternFieldList.remove() method + +Signature: + +```typescript +remove(field: IFieldType): void; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| field | IFieldType | | + +Returns: + +`void` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.update.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.update.md new file mode 100644 index 00000000000000..121ffb65f26a52 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.iindexpatternfieldlist.update.md @@ -0,0 +1,22 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IIndexPatternFieldList](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.md) > [update](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.update.md) + +## IIndexPatternFieldList.update() method + +Signature: + +```typescript +update(field: FieldSpec): void; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| field | FieldSpec | | + +Returns: + +`void` + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.fields.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.fields.md index fcd682340eb539..9a93148e4a466f 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.fields.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.fields.md @@ -7,5 +7,5 @@ Signature: ```typescript -fields: IFieldList; +fields: IIndexPatternFieldList; ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.md index 35075e19dcaf6a..21a155ba977c96 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpattern.md @@ -21,7 +21,7 @@ export declare class IndexPattern implements IIndexPattern | Property | Modifiers | Type | Description | | --- | --- | --- | --- | | [fieldFormatMap](./kibana-plugin-plugins-data-public.indexpattern.fieldformatmap.md) | | any | | -| [fields](./kibana-plugin-plugins-data-public.indexpattern.fields.md) | | IFieldList | | +| [fields](./kibana-plugin-plugins-data-public.indexpattern.fields.md) | | IIndexPatternFieldList | | | [fieldsFetcher](./kibana-plugin-plugins-data-public.indexpattern.fieldsfetcher.md) | | any | | | [flattenHit](./kibana-plugin-plugins-data-public.indexpattern.flattenhit.md) | | any | | | [formatField](./kibana-plugin-plugins-data-public.indexpattern.formatfield.md) | | any | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.__spec.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.__spec.md new file mode 100644 index 00000000000000..f52a3324af36f7 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.__spec.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [$$spec](./kibana-plugin-plugins-data-public.indexpatternfield.__spec.md) + +## IndexPatternField.$$spec property + +Signature: + +```typescript +$$spec: FieldSpec; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field._constructor_.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield._constructor_.md similarity index 55% rename from docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field._constructor_.md rename to docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield._constructor_.md index c3b2ac8d30b5a9..8ee9acc684fb1c 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.field._constructor_.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield._constructor_.md @@ -1,15 +1,15 @@ -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [Field](./kibana-plugin-plugins-data-public.field.md) > [(constructor)](./kibana-plugin-plugins-data-public.field._constructor_.md) +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [(constructor)](./kibana-plugin-plugins-data-public.indexpatternfield._constructor_.md) -## Field.(constructor) +## IndexPatternField.(constructor) Constructs a new instance of the `Field` class Signature: ```typescript -constructor(indexPattern: IndexPattern, spec: FieldSpec | Field, shortDotsEnable?: boolean); +constructor(indexPattern: IndexPattern, spec: FieldSpec | Field, shortDotsEnable: boolean, { fieldFormats, toastNotifications }: FieldDependencies); ``` ## Parameters @@ -19,4 +19,5 @@ constructor(indexPattern: IndexPattern, spec: FieldSpec | Field, shortDotsEnable | indexPattern | IndexPattern | | | spec | FieldSpec | Field | | | shortDotsEnable | boolean | | +| { fieldFormats, toastNotifications } | FieldDependencies | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.aggregatable.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.aggregatable.md new file mode 100644 index 00000000000000..267c8f786b5dd2 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.aggregatable.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [aggregatable](./kibana-plugin-plugins-data-public.indexpatternfield.aggregatable.md) + +## IndexPatternField.aggregatable property + +Signature: + +```typescript +aggregatable?: boolean; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.conflictdescriptions.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.conflictdescriptions.md new file mode 100644 index 00000000000000..ca2552aeb1b425 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.conflictdescriptions.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [conflictDescriptions](./kibana-plugin-plugins-data-public.indexpatternfield.conflictdescriptions.md) + +## IndexPatternField.conflictDescriptions property + +Signature: + +```typescript +conflictDescriptions?: Record; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.count.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.count.md new file mode 100644 index 00000000000000..8e848276f21c4c --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.count.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [count](./kibana-plugin-plugins-data-public.indexpatternfield.count.md) + +## IndexPatternField.count property + +Signature: + +```typescript +count?: number; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.displayname.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.displayname.md new file mode 100644 index 00000000000000..ed9630f92fc975 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.displayname.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [displayName](./kibana-plugin-plugins-data-public.indexpatternfield.displayname.md) + +## IndexPatternField.displayName property + +Signature: + +```typescript +displayName?: string; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.estypes.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.estypes.md new file mode 100644 index 00000000000000..dec74df099d43a --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.estypes.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [esTypes](./kibana-plugin-plugins-data-public.indexpatternfield.estypes.md) + +## IndexPatternField.esTypes property + +Signature: + +```typescript +esTypes?: string[]; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.filterable.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.filterable.md new file mode 100644 index 00000000000000..4290c4a2f86b3b --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.filterable.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [filterable](./kibana-plugin-plugins-data-public.indexpatternfield.filterable.md) + +## IndexPatternField.filterable property + +Signature: + +```typescript +filterable?: boolean; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.format.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.format.md new file mode 100644 index 00000000000000..d5df8ed628cb08 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.format.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [format](./kibana-plugin-plugins-data-public.indexpatternfield.format.md) + +## IndexPatternField.format property + +Signature: + +```typescript +format: any; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.indexpattern.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.indexpattern.md new file mode 100644 index 00000000000000..d1a1ee0905c6e3 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.indexpattern.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [indexPattern](./kibana-plugin-plugins-data-public.indexpatternfield.indexpattern.md) + +## IndexPatternField.indexPattern property + +Signature: + +```typescript +indexPattern?: IndexPattern; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.lang.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.lang.md new file mode 100644 index 00000000000000..f731be8f613cfa --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.lang.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [lang](./kibana-plugin-plugins-data-public.indexpatternfield.lang.md) + +## IndexPatternField.lang property + +Signature: + +```typescript +lang?: string; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.md new file mode 100644 index 00000000000000..a62cee7b654fe7 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.md @@ -0,0 +1,41 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) + +## IndexPatternField class + +Signature: + +```typescript +export declare class Field implements IFieldType +``` + +## Constructors + +| Constructor | Modifiers | Description | +| --- | --- | --- | +| [(constructor)(indexPattern, spec, shortDotsEnable, { fieldFormats, toastNotifications })](./kibana-plugin-plugins-data-public.indexpatternfield._constructor_.md) | | Constructs a new instance of the Field class | + +## Properties + +| Property | Modifiers | Type | Description | +| --- | --- | --- | --- | +| [$$spec](./kibana-plugin-plugins-data-public.indexpatternfield.__spec.md) | | FieldSpec | | +| [aggregatable](./kibana-plugin-plugins-data-public.indexpatternfield.aggregatable.md) | | boolean | | +| [conflictDescriptions](./kibana-plugin-plugins-data-public.indexpatternfield.conflictdescriptions.md) | | Record<string, string[]> | | +| [count](./kibana-plugin-plugins-data-public.indexpatternfield.count.md) | | number | | +| [displayName](./kibana-plugin-plugins-data-public.indexpatternfield.displayname.md) | | string | | +| [esTypes](./kibana-plugin-plugins-data-public.indexpatternfield.estypes.md) | | string[] | | +| [filterable](./kibana-plugin-plugins-data-public.indexpatternfield.filterable.md) | | boolean | | +| [format](./kibana-plugin-plugins-data-public.indexpatternfield.format.md) | | any | | +| [indexPattern](./kibana-plugin-plugins-data-public.indexpatternfield.indexpattern.md) | | IndexPattern | | +| [lang](./kibana-plugin-plugins-data-public.indexpatternfield.lang.md) | | string | | +| [name](./kibana-plugin-plugins-data-public.indexpatternfield.name.md) | | string | | +| [script](./kibana-plugin-plugins-data-public.indexpatternfield.script.md) | | string | | +| [scripted](./kibana-plugin-plugins-data-public.indexpatternfield.scripted.md) | | boolean | | +| [searchable](./kibana-plugin-plugins-data-public.indexpatternfield.searchable.md) | | boolean | | +| [sortable](./kibana-plugin-plugins-data-public.indexpatternfield.sortable.md) | | boolean | | +| [subType](./kibana-plugin-plugins-data-public.indexpatternfield.subtype.md) | | IFieldSubType | | +| [type](./kibana-plugin-plugins-data-public.indexpatternfield.type.md) | | string | | +| [visualizable](./kibana-plugin-plugins-data-public.indexpatternfield.visualizable.md) | | boolean | | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.name.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.name.md new file mode 100644 index 00000000000000..cb24621e732093 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.name.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [name](./kibana-plugin-plugins-data-public.indexpatternfield.name.md) + +## IndexPatternField.name property + +Signature: + +```typescript +name: string; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.script.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.script.md new file mode 100644 index 00000000000000..132ba25a476374 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.script.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [script](./kibana-plugin-plugins-data-public.indexpatternfield.script.md) + +## IndexPatternField.script property + +Signature: + +```typescript +script?: string; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.scripted.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.scripted.md new file mode 100644 index 00000000000000..1dd6bc865a75d9 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.scripted.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [scripted](./kibana-plugin-plugins-data-public.indexpatternfield.scripted.md) + +## IndexPatternField.scripted property + +Signature: + +```typescript +scripted?: boolean; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.searchable.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.searchable.md new file mode 100644 index 00000000000000..42f984d851435b --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.searchable.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [searchable](./kibana-plugin-plugins-data-public.indexpatternfield.searchable.md) + +## IndexPatternField.searchable property + +Signature: + +```typescript +searchable?: boolean; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.sortable.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.sortable.md new file mode 100644 index 00000000000000..72d225185140be --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.sortable.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [sortable](./kibana-plugin-plugins-data-public.indexpatternfield.sortable.md) + +## IndexPatternField.sortable property + +Signature: + +```typescript +sortable?: boolean; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.subtype.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.subtype.md new file mode 100644 index 00000000000000..2d807f8a5739ce --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.subtype.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [subType](./kibana-plugin-plugins-data-public.indexpatternfield.subtype.md) + +## IndexPatternField.subType property + +Signature: + +```typescript +subType?: IFieldSubType; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.type.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.type.md new file mode 100644 index 00000000000000..c8483c9b83c9a1 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.type.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [type](./kibana-plugin-plugins-data-public.indexpatternfield.type.md) + +## IndexPatternField.type property + +Signature: + +```typescript +type: string; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.visualizable.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.visualizable.md new file mode 100644 index 00000000000000..dd661ae779c117 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.visualizable.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) > [visualizable](./kibana-plugin-plugins-data-public.indexpatternfield.visualizable.md) + +## IndexPatternField.visualizable property + +Signature: + +```typescript +visualizable?: boolean; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist._constructor_.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist._constructor_.md deleted file mode 100644 index 2207107db8b2b4..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist._constructor_.md +++ /dev/null @@ -1,22 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternFieldList](./kibana-plugin-plugins-data-public.indexpatternfieldlist.md) > [(constructor)](./kibana-plugin-plugins-data-public.indexpatternfieldlist._constructor_.md) - -## IndexPatternFieldList.(constructor) - -Constructs a new instance of the `FieldList` class - -Signature: - -```typescript -constructor(indexPattern: IndexPattern, specs?: FieldSpec[], shortDotsEnable?: boolean); -``` - -## Parameters - -| Parameter | Type | Description | -| --- | --- | --- | -| indexPattern | IndexPattern | | -| specs | FieldSpec[] | | -| shortDotsEnable | boolean | | - diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.add.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.add.md deleted file mode 100644 index dce2f38bbcf100..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.add.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternFieldList](./kibana-plugin-plugins-data-public.indexpatternfieldlist.md) > [add](./kibana-plugin-plugins-data-public.indexpatternfieldlist.add.md) - -## IndexPatternFieldList.add property - -Signature: - -```typescript -add: (field: Record) => void; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.getbyname.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.getbyname.md deleted file mode 100644 index bf6bc51b603012..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.getbyname.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternFieldList](./kibana-plugin-plugins-data-public.indexpatternfieldlist.md) > [getByName](./kibana-plugin-plugins-data-public.indexpatternfieldlist.getbyname.md) - -## IndexPatternFieldList.getByName property - -Signature: - -```typescript -getByName: (name: string) => Field | undefined; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.getbytype.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.getbytype.md deleted file mode 100644 index 86c5ae32940d48..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.getbytype.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternFieldList](./kibana-plugin-plugins-data-public.indexpatternfieldlist.md) > [getByType](./kibana-plugin-plugins-data-public.indexpatternfieldlist.getbytype.md) - -## IndexPatternFieldList.getByType property - -Signature: - -```typescript -getByType: (type: string) => any[]; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.md deleted file mode 100644 index 478b73f5f85813..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.md +++ /dev/null @@ -1,28 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternFieldList](./kibana-plugin-plugins-data-public.indexpatternfieldlist.md) - -## IndexPatternFieldList class - -Signature: - -```typescript -export declare class FieldList extends Array implements IFieldList -``` - -## Constructors - -| Constructor | Modifiers | Description | -| --- | --- | --- | -| [(constructor)(indexPattern, specs, shortDotsEnable)](./kibana-plugin-plugins-data-public.indexpatternfieldlist._constructor_.md) | | Constructs a new instance of the FieldList class | - -## Properties - -| Property | Modifiers | Type | Description | -| --- | --- | --- | --- | -| [add](./kibana-plugin-plugins-data-public.indexpatternfieldlist.add.md) | | (field: Record<string, any>) => void | | -| [getByName](./kibana-plugin-plugins-data-public.indexpatternfieldlist.getbyname.md) | | (name: string) => Field | undefined | | -| [getByType](./kibana-plugin-plugins-data-public.indexpatternfieldlist.getbytype.md) | | (type: string) => any[] | | -| [remove](./kibana-plugin-plugins-data-public.indexpatternfieldlist.remove.md) | | (field: IFieldType) => void | | -| [update](./kibana-plugin-plugins-data-public.indexpatternfieldlist.update.md) | | (field: Record<string, any>) => void | | - diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.remove.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.remove.md deleted file mode 100644 index 1f2e0883d272e0..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.remove.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternFieldList](./kibana-plugin-plugins-data-public.indexpatternfieldlist.md) > [remove](./kibana-plugin-plugins-data-public.indexpatternfieldlist.remove.md) - -## IndexPatternFieldList.remove property - -Signature: - -```typescript -remove: (field: IFieldType) => void; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.update.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.update.md deleted file mode 100644 index d5156ed41e493e..00000000000000 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfieldlist.update.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [IndexPatternFieldList](./kibana-plugin-plugins-data-public.indexpatternfieldlist.md) > [update](./kibana-plugin-plugins-data-public.indexpatternfieldlist.update.md) - -## IndexPatternFieldList.update property - -Signature: - -```typescript -update: (field: Record) => void; -``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md index 13e38ba5e6e5dc..8b58957b9044a8 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md @@ -9,11 +9,10 @@ | Class | Description | | --- | --- | | [AggParamType](./kibana-plugin-plugins-data-public.aggparamtype.md) | | -| [Field](./kibana-plugin-plugins-data-public.field.md) | | | [FieldFormat](./kibana-plugin-plugins-data-public.fieldformat.md) | | | [FilterManager](./kibana-plugin-plugins-data-public.filtermanager.md) | | | [IndexPattern](./kibana-plugin-plugins-data-public.indexpattern.md) | | -| [IndexPatternFieldList](./kibana-plugin-plugins-data-public.indexpatternfieldlist.md) | | +| [IndexPatternField](./kibana-plugin-plugins-data-public.indexpatternfield.md) | | | [IndexPatternSelect](./kibana-plugin-plugins-data-public.indexpatternselect.md) | | | [OptionedParamType](./kibana-plugin-plugins-data-public.optionedparamtype.md) | | | [Plugin](./kibana-plugin-plugins-data-public.plugin.md) | | @@ -61,6 +60,7 @@ | [IFieldSubType](./kibana-plugin-plugins-data-public.ifieldsubtype.md) | | | [IFieldType](./kibana-plugin-plugins-data-public.ifieldtype.md) | | | [IIndexPattern](./kibana-plugin-plugins-data-public.iindexpattern.md) | | +| [IIndexPatternFieldList](./kibana-plugin-plugins-data-public.iindexpatternfieldlist.md) | | | [IKibanaSearchRequest](./kibana-plugin-plugins-data-public.ikibanasearchrequest.md) | | | [IKibanaSearchResponse](./kibana-plugin-plugins-data-public.ikibanasearchresponse.md) | | | [IndexPatternAttributes](./kibana-plugin-plugins-data-public.indexpatternattributes.md) | Use data plugin interface instead | @@ -103,6 +103,7 @@ | [esQuery](./kibana-plugin-plugins-data-public.esquery.md) | | | [fieldFormats](./kibana-plugin-plugins-data-public.fieldformats.md) | | | [FilterBar](./kibana-plugin-plugins-data-public.filterbar.md) | | +| [getIndexPatternFieldListCreator](./kibana-plugin-plugins-data-public.getindexpatternfieldlistcreator.md) | | | [getKbnTypeNames](./kibana-plugin-plugins-data-public.getkbntypenames.md) | Get the esTypes known by all kbnFieldTypes {Array} | | [indexPatterns](./kibana-plugin-plugins-data-public.indexpatterns.md) | | | [QueryStringInput](./kibana-plugin-plugins-data-public.querystringinput.md) | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystringinput.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystringinput.md index d0d4cc491e1428..58690300b3bd62 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystringinput.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.querystringinput.md @@ -7,5 +7,5 @@ Signature: ```typescript -QueryStringInput: React.FC> +QueryStringInput: React.FC> ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchbar.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchbar.md index a0b879673e553c..0d5e0e42af27fa 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchbar.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchbar.md @@ -7,7 +7,7 @@ Signature: ```typescript -SearchBar: React.ComponentClass, "query" | "isLoading" | "filters" | "indexPatterns" | "refreshInterval" | "screenTitle" | "dataTestSubj" | "customSubmitButton" | "showQueryBar" | "showQueryInput" | "showFilterBar" | "showDatePicker" | "showAutoRefreshOnly" | "isRefreshPaused" | "dateRangeFrom" | "dateRangeTo" | "showSaveQuery" | "savedQuery" | "onQueryChange" | "onQuerySubmit" | "onSaved" | "onSavedQueryUpdated" | "onClearSavedQuery" | "onRefresh" | "timeHistory" | "onFiltersUpdated" | "onRefreshChange">, any> & { - WrappedComponent: React.ComponentType & ReactIntl.InjectedIntlProps>; +SearchBar: React.ComponentClass, "query" | "isLoading" | "filters" | "indexPatterns" | "refreshInterval" | "customSubmitButton" | "screenTitle" | "dataTestSubj" | "showQueryBar" | "showQueryInput" | "showFilterBar" | "showDatePicker" | "showAutoRefreshOnly" | "isRefreshPaused" | "dateRangeFrom" | "dateRangeTo" | "showSaveQuery" | "savedQuery" | "onQueryChange" | "onQuerySubmit" | "onSaved" | "onSavedQueryUpdated" | "onClearSavedQuery" | "onRefresh" | "timeHistory" | "onFiltersUpdated" | "onRefreshChange">, any> & { + WrappedComponent: React.ComponentType & ReactIntl.InjectedIntlProps>; } ``` diff --git a/docs/user/security/securing-kibana.asciidoc b/docs/user/security/securing-kibana.asciidoc index 24aacd6a476261..f4178bacb111e8 100644 --- a/docs/user/security/securing-kibana.asciidoc +++ b/docs/user/security/securing-kibana.asciidoc @@ -31,14 +31,14 @@ file: [source,yaml] ----------------------------------------------- -elasticsearch.username: "kibana" +elasticsearch.username: "kibana_system" elasticsearch.password: "kibanapassword" ----------------------------------------------- The {kib} server submits requests as this user to access the cluster monitoring APIs and the `.kibana` index. The server does _not_ need access to user indices. -The password for the built-in `kibana` user is typically set as part of the +The password for the built-in `kibana_system` user is typically set as part of the {security} configuration process on {es}. For more information, see {ref}/built-in-users.html[Built-in users]. -- diff --git a/examples/alerting_example/public/application.tsx b/examples/alerting_example/public/application.tsx index 6ff5a7d0880b84..23e9d194410028 100644 --- a/examples/alerting_example/public/application.tsx +++ b/examples/alerting_example/public/application.tsx @@ -27,6 +27,7 @@ import { IUiSettingsClient, DocLinksStart, ToastsSetup, + ApplicationStart, } from '../../../src/core/public'; import { DataPublicPluginStart } from '../../../src/plugins/data/public'; import { ChartsPluginStart } from '../../../src/plugins/charts/public'; @@ -48,6 +49,7 @@ export interface AlertingExampleComponentParams { uiSettings: IUiSettingsClient; docLinks: DocLinksStart; toastNotifications: ToastsSetup; + capabilities: ApplicationStart['capabilities']; } const AlertingExampleApp = (deps: AlertingExampleComponentParams) => { @@ -102,6 +104,7 @@ export const renderApp = ( http={http} uiSettings={uiSettings} docLinks={docLinks} + capabilities={application.capabilities} {...deps} />, element diff --git a/examples/alerting_example/public/components/create_alert.tsx b/examples/alerting_example/public/components/create_alert.tsx index 0541e0b18a2e12..a8e1f06cb39143 100644 --- a/examples/alerting_example/public/components/create_alert.tsx +++ b/examples/alerting_example/public/components/create_alert.tsx @@ -36,6 +36,7 @@ export const CreateAlert = ({ docLinks, data, toastNotifications, + capabilities, }: AlertingExampleComponentParams) => { const [alertFlyoutVisible, setAlertFlyoutVisibility] = useState(false); @@ -60,6 +61,7 @@ export const CreateAlert = ({ docLinks, charts, dataFieldsFormats: data.fieldFormats, + capabilities, }} > { mockClient.security.getUser.mockImplementation(() => ({ body: { - kibana: { + kibana_system: { metadata: { _reserved: true, }, @@ -138,7 +138,7 @@ describe('setPasswords', () => { })); await nativeRealm.setPasswords({ - 'password.kibana': 'bar', + 'password.kibana_system': 'bar', }); expect(mockClient.security.changePassword.mock.calls).toMatchInlineSnapshot(` @@ -149,7 +149,7 @@ Array [ "password": "bar", }, "refresh": "wait_for", - "username": "kibana", + "username": "kibana_system", }, ], Array [ @@ -188,7 +188,7 @@ describe('getReservedUsers', () => { it('returns array of reserved usernames', async () => { mockClient.security.getUser.mockImplementation(() => ({ body: { - kibana: { + kibana_system: { metadata: { _reserved: true, }, @@ -206,17 +206,17 @@ describe('getReservedUsers', () => { }, })); - expect(await nativeRealm.getReservedUsers()).toEqual(['kibana', 'logstash_system']); + expect(await nativeRealm.getReservedUsers()).toEqual(['kibana_system', 'logstash_system']); }); }); describe('setPassword', () => { it('sets password for provided user', async () => { - await nativeRealm.setPassword('kibana', 'foo'); + await nativeRealm.setPassword('kibana_system', 'foo'); expect(mockClient.security.changePassword).toHaveBeenCalledWith({ body: { password: 'foo' }, refresh: 'wait_for', - username: 'kibana', + username: 'kibana_system', }); }); @@ -226,7 +226,7 @@ describe('setPassword', () => { }); await expect( - nativeRealm.setPassword('kibana', 'foo') + nativeRealm.setPassword('kibana_system', 'foo') ).rejects.toThrowErrorMatchingInlineSnapshot(`"SomeError"`); }); }); diff --git a/packages/kbn-ui-shared-deps/package.json b/packages/kbn-ui-shared-deps/package.json index ec61e8519c960e..382b6614fc3ec0 100644 --- a/packages/kbn-ui-shared-deps/package.json +++ b/packages/kbn-ui-shared-deps/package.json @@ -9,7 +9,7 @@ "kbn:watch": "node scripts/build --watch" }, "dependencies": { - "@elastic/charts": "18.4.2", + "@elastic/charts": "19.2.0", "@elastic/eui": "22.3.0", "@kbn/i18n": "1.0.0", "abortcontroller-polyfill": "^1.4.0", diff --git a/packages/kbn-ui-shared-deps/webpack.config.js b/packages/kbn-ui-shared-deps/webpack.config.js index 52e7bb620b50b4..ca913d0f16417d 100644 --- a/packages/kbn-ui-shared-deps/webpack.config.js +++ b/packages/kbn-ui-shared-deps/webpack.config.js @@ -118,15 +118,19 @@ exports.getWebpackConfig = ({ dev = false } = {}) => ({ new webpack.DefinePlugin({ 'process.env.NODE_ENV': dev ? '"development"' : '"production"', }), - new CompressionPlugin({ - algorithm: 'brotliCompress', - filename: '[path].br', - test: /\.(js|css)$/, - }), - new CompressionPlugin({ - algorithm: 'gzip', - filename: '[path].gz', - test: /\.(js|css)$/, - }), + ...(dev + ? [] + : [ + new CompressionPlugin({ + algorithm: 'brotliCompress', + filename: '[path].br', + test: /\.(js|css)$/, + }), + new CompressionPlugin({ + algorithm: 'gzip', + filename: '[path].gz', + test: /\.(js|css)$/, + }), + ]), ], }); diff --git a/src/cli/serve/serve.js b/src/cli/serve/serve.js index 29d0fe16ee126a..471939121143a1 100644 --- a/src/cli/serve/serve.js +++ b/src/cli/serve/serve.js @@ -79,7 +79,7 @@ function applyConfigOverrides(rawConfig, opts, extraCliOptions) { set('optimize.watch', true); if (!has('elasticsearch.username')) { - set('elasticsearch.username', 'kibana'); + set('elasticsearch.username', 'kibana_system'); } if (!has('elasticsearch.password')) { diff --git a/src/core/public/application/application_service.tsx b/src/core/public/application/application_service.tsx index 0dd77072e9eafb..8442f1ecc6411a 100644 --- a/src/core/public/application/application_service.tsx +++ b/src/core/public/application/application_service.tsx @@ -26,6 +26,7 @@ import { InjectedMetadataSetup } from '../injected_metadata'; import { HttpSetup, HttpStart } from '../http'; import { OverlayStart } from '../overlays'; import { ContextSetup, IContextContainer } from '../context'; +import { PluginOpaqueId } from '../plugins'; import { AppRouter } from './ui'; import { Capabilities, CapabilitiesService } from './capabilities'; import { @@ -34,7 +35,6 @@ import { AppLeaveHandler, AppMount, AppMountDeprecated, - AppMounter, AppNavLinkStatus, AppStatus, AppUpdatableFields, @@ -145,6 +145,25 @@ export class ApplicationService { this.subscriptions.push(subscription); }; + const wrapMount = (plugin: PluginOpaqueId, app: App): AppMount => { + let handler: AppMount; + if (isAppMountDeprecated(app.mount)) { + handler = this.mountContext!.createHandler(plugin, app.mount); + if (process.env.NODE_ENV === 'development') { + // eslint-disable-next-line no-console + console.warn( + `App [${app.id}] is using deprecated mount context. Use core.getStartServices() instead.` + ); + } + } else { + handler = app.mount; + } + return async params => { + this.currentAppId$.next(app.id); + return handler(params); + }; + }; + return { registerMountContext: this.mountContext!.registerContext, register: (plugin, app: App) => { @@ -162,24 +181,6 @@ export class ApplicationService { throw new Error('Cannot register an application route that includes HTTP base path'); } - let handler: AppMount; - - if (isAppMountDeprecated(app.mount)) { - handler = this.mountContext!.createHandler(plugin, app.mount); - // eslint-disable-next-line no-console - console.warn( - `App [${app.id}] is using deprecated mount context. Use core.getStartServices() instead.` - ); - } else { - handler = app.mount; - } - - const mount: AppMounter = async params => { - const unmount = await handler(params); - this.currentAppId$.next(app.id); - return unmount; - }; - const { updater$, ...appProps } = app; this.apps.set(app.id, { ...appProps, @@ -193,7 +194,7 @@ export class ApplicationService { this.mounters.set(app.id, { appRoute: app.appRoute!, appBasePath: basePath.prepend(app.appRoute!), - mount, + mount: wrapMount(plugin, app), unmountBeforeMounting: false, }); }, diff --git a/src/core/public/application/integration_tests/application_service.test.tsx b/src/core/public/application/integration_tests/application_service.test.tsx index edf3583f384b83..60c36d3e330e0b 100644 --- a/src/core/public/application/integration_tests/application_service.test.tsx +++ b/src/core/public/application/integration_tests/application_service.test.tsx @@ -17,6 +17,7 @@ * under the License. */ +import { take } from 'rxjs/operators'; import { createRenderer } from './utils'; import { createMemoryHistory, MemoryHistory } from 'history'; import { ApplicationService } from '../application_service'; @@ -56,6 +57,69 @@ describe('ApplicationService', () => { service = new ApplicationService(); }); + describe('navigating to apps', () => { + describe('using history.push', () => { + it('emits currentAppId$ before mounting the app', async () => { + const { register } = service.setup(setupDeps); + + let resolveMount: () => void; + const promise = new Promise(resolve => { + resolveMount = resolve; + }); + + register(Symbol(), { + id: 'app1', + title: 'App1', + mount: async ({}: AppMountParameters) => { + await promise; + return () => undefined; + }, + }); + + const { currentAppId$, getComponent } = await service.start(startDeps); + update = createRenderer(getComponent()); + + await navigate('/app/app1'); + + expect(await currentAppId$.pipe(take(1)).toPromise()).toEqual('app1'); + + resolveMount!(); + + expect(await currentAppId$.pipe(take(1)).toPromise()).toEqual('app1'); + }); + }); + + describe('using navigateToApp', () => { + it('emits currentAppId$ before mounting the app', async () => { + const { register } = service.setup(setupDeps); + + let resolveMount: () => void; + const promise = new Promise(resolve => { + resolveMount = resolve; + }); + + register(Symbol(), { + id: 'app1', + title: 'App1', + mount: async ({}: AppMountParameters) => { + await promise; + return () => undefined; + }, + }); + + const { navigateToApp, currentAppId$ } = await service.start(startDeps); + + await navigateToApp('app1'); + + expect(await currentAppId$.pipe(take(1)).toPromise()).toEqual('app1'); + + resolveMount!(); + + expect(await currentAppId$.pipe(take(1)).toPromise()).toEqual('app1'); + }); + }); + }); + describe('leaving an application that registered an app leave handler', () => { it('navigates to the new app if action is default', async () => { startDeps.overlays.openConfirm.mockResolvedValue(true); diff --git a/src/core/public/chrome/chrome_service.test.ts b/src/core/public/chrome/chrome_service.test.ts index bf531aaa00facb..a765ed47ea712c 100644 --- a/src/core/public/chrome/chrome_service.test.ts +++ b/src/core/public/chrome/chrome_service.test.ts @@ -29,7 +29,6 @@ import { notificationServiceMock } from '../notifications/notifications_service. import { docLinksServiceMock } from '../doc_links/doc_links_service.mock'; import { ChromeService } from './chrome_service'; import { App } from '../application'; -import { uiSettingsServiceMock } from '../ui_settings/ui_settings_service.mock'; class FakeApp implements App { public title = `${this.id} App`; @@ -52,7 +51,6 @@ function defaultStartDeps(availableApps?: App[]) { http: httpServiceMock.createStartContract(), injectedMetadata: injectedMetadataServiceMock.createStartContract(), notifications: notificationServiceMock.createStartContract(), - uiSettings: uiSettingsServiceMock.createStartContract(), }; if (availableApps) { @@ -163,7 +161,7 @@ describe('start', () => { }); describe('visibility', () => { - it('updates/emits the visibility', async () => { + it('emits false when no application is mounted', async () => { const { chrome, service } = await start(); const promise = chrome .getIsVisible$() @@ -177,33 +175,37 @@ describe('start', () => { await expect(promise).resolves.toMatchInlineSnapshot(` Array [ - true, - true, false, - true, + false, + false, + false, ] `); }); - it('always emits false if embed query string is preset when set up', async () => { + it('emits false until manually overridden when in embed mode', async () => { window.history.pushState(undefined, '', '#/home?a=b&embed=true'); + const startDeps = defaultStartDeps([new FakeApp('alpha')]); + const { navigateToApp } = startDeps.application; + const { chrome, service } = await start({ startDeps }); - const { chrome, service } = await start(); const promise = chrome .getIsVisible$() .pipe(toArray()) .toPromise(); + await navigateToApp('alpha'); + chrome.setIsVisible(true); chrome.setIsVisible(false); - chrome.setIsVisible(true); + service.stop(); await expect(promise).resolves.toMatchInlineSnapshot(` Array [ false, false, - false, + true, false, ] `); @@ -228,7 +230,7 @@ describe('start', () => { await expect(promise).resolves.toMatchInlineSnapshot(` Array [ - true, + false, true, false, true, @@ -245,13 +247,13 @@ describe('start', () => { .pipe(toArray()) .toPromise(); - navigateToApp('alpha'); + await navigateToApp('alpha'); chrome.setIsVisible(true); service.stop(); await expect(promise).resolves.toMatchInlineSnapshot(` Array [ - true, + false, false, false, ] diff --git a/src/core/public/chrome/chrome_service.tsx b/src/core/public/chrome/chrome_service.tsx index 7c9b644b8b9849..3d9eeff09ecceb 100644 --- a/src/core/public/chrome/chrome_service.tsx +++ b/src/core/public/chrome/chrome_service.tsx @@ -38,7 +38,6 @@ import { LoadingIndicator, Header } from './ui'; import { DocLinksStart } from '../doc_links'; import { ChromeHelpExtensionMenuLink } from './ui/header/header_help_menu'; import { KIBANA_ASK_ELASTIC_LINK } from './constants'; -import { IUiSettingsClient } from '../ui_settings'; export { ChromeNavControls, ChromeRecentlyAccessed, ChromeDocTitle }; const IS_LOCKED_KEY = 'core.chrome.isLocked'; @@ -85,14 +84,12 @@ interface StartDeps { http: HttpStart; injectedMetadata: InjectedMetadataStart; notifications: NotificationsStart; - uiSettings: IUiSettingsClient; } /** @internal */ export class ChromeService { private isVisible$!: Observable; - private appHidden$!: Observable; - private toggleHidden$!: BehaviorSubject; + private isForceHidden$!: BehaviorSubject; private readonly stop$ = new ReplaySubject(1); private readonly navControls = new NavControlsService(); private readonly navLinks = new NavLinksService(); @@ -111,13 +108,12 @@ export class ChromeService { private initVisibility(application: StartDeps['application']) { // Start off the chrome service hidden if "embed" is in the hash query string. const isEmbedded = 'embed' in parse(location.hash.slice(1), true).query; + this.isForceHidden$ = new BehaviorSubject(isEmbedded); - this.toggleHidden$ = new BehaviorSubject(isEmbedded); - this.appHidden$ = merge( - // Default the app being hidden to the same value initial value as the chrome visibility - // in case the application service has not emitted an app ID yet, since we want to trigger - // combineLatest below regardless of having an application value yet. - of(isEmbedded), + const appHidden$ = merge( + // For the isVisible$ logic, having no mounted app is equivalent to having a hidden app + // in the sense that the chrome UI should not be displayed until a non-chromeless app is mounting or mounted + of(true), application.currentAppId$.pipe( flatMap(appId => application.applications$.pipe( @@ -128,8 +124,8 @@ export class ChromeService { ) ) ); - this.isVisible$ = combineLatest([this.appHidden$, this.toggleHidden$]).pipe( - map(([appHidden, toggleHidden]) => !(appHidden || toggleHidden)), + this.isVisible$ = combineLatest([appHidden$, this.isForceHidden$]).pipe( + map(([appHidden, forceHidden]) => !appHidden && !forceHidden), takeUntil(this.stop$) ); } @@ -140,7 +136,6 @@ export class ChromeService { http, injectedMetadata, notifications, - uiSettings, }: StartDeps): Promise { this.initVisibility(application); @@ -221,7 +216,7 @@ export class ChromeService { getIsVisible$: () => this.isVisible$, - setIsVisible: (isVisible: boolean) => this.toggleHidden$.next(!isVisible), + setIsVisible: (isVisible: boolean) => this.isForceHidden$.next(!isVisible), getApplicationClasses$: () => applicationClasses$.pipe( diff --git a/src/core/public/core_system.ts b/src/core/public/core_system.ts index e58114b69dcc1e..59f0142bb88902 100644 --- a/src/core/public/core_system.ts +++ b/src/core/public/core_system.ts @@ -240,7 +240,6 @@ export class CoreSystem { http, injectedMetadata, notifications, - uiSettings, }); application.registerMountContext(this.coreContext.coreId, 'core', () => ({ diff --git a/src/core/server/elasticsearch/__snapshots__/elasticsearch_config.test.ts.snap b/src/core/server/elasticsearch/__snapshots__/elasticsearch_config.test.ts.snap index e81336c8863f56..75627f311d9a58 100644 --- a/src/core/server/elasticsearch/__snapshots__/elasticsearch_config.test.ts.snap +++ b/src/core/server/elasticsearch/__snapshots__/elasticsearch_config.test.ts.snap @@ -1,3 +1,3 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`#username throws if equal to "elastic", only while running from source 1`] = `"[username]: value of \\"elastic\\" is forbidden. This is a superuser account that can obfuscate privilege-related issues. You should use the \\"kibana\\" user instead."`; +exports[`#username throws if equal to "elastic", only while running from source 1`] = `"[username]: value of \\"elastic\\" is forbidden. This is a superuser account that can obfuscate privilege-related issues. You should use the \\"kibana_system\\" user instead."`; diff --git a/src/core/server/elasticsearch/elasticsearch_config.test.ts b/src/core/server/elasticsearch/elasticsearch_config.test.ts index de3f57298f461f..cb4501a51e849d 100644 --- a/src/core/server/elasticsearch/elasticsearch_config.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_config.test.ts @@ -315,12 +315,21 @@ describe('deprecations', () => { const { messages } = applyElasticsearchDeprecations({ username: 'elastic' }); expect(messages).toMatchInlineSnapshot(` Array [ - "Setting [${CONFIG_PATH}.username] to \\"elastic\\" is deprecated. You should use the \\"kibana\\" user instead.", + "Setting [${CONFIG_PATH}.username] to \\"elastic\\" is deprecated. You should use the \\"kibana_system\\" user instead.", ] `); }); - it('does not log a warning if elasticsearch.username is set to something besides "elastic"', () => { + it('logs a warning if elasticsearch.username is set to "kibana"', () => { + const { messages } = applyElasticsearchDeprecations({ username: 'kibana' }); + expect(messages).toMatchInlineSnapshot(` + Array [ + "Setting [${CONFIG_PATH}.username] to \\"kibana\\" is deprecated. You should use the \\"kibana_system\\" user instead.", + ] + `); + }); + + it('does not log a warning if elasticsearch.username is set to something besides "elastic" or "kibana"', () => { const { messages } = applyElasticsearchDeprecations({ username: 'otheruser' }); expect(messages).toHaveLength(0); }); diff --git a/src/core/server/elasticsearch/elasticsearch_config.ts b/src/core/server/elasticsearch/elasticsearch_config.ts index d3012e361b3ed0..c87c94bcd0b6af 100644 --- a/src/core/server/elasticsearch/elasticsearch_config.ts +++ b/src/core/server/elasticsearch/elasticsearch_config.ts @@ -55,7 +55,7 @@ export const configSchema = schema.object({ if (rawConfig === 'elastic') { return ( 'value of "elastic" is forbidden. This is a superuser account that can obfuscate ' + - 'privilege-related issues. You should use the "kibana" user instead.' + 'privilege-related issues. You should use the "kibana_system" user instead.' ); } }, @@ -131,7 +131,11 @@ const deprecations: ConfigDeprecationProvider = () => [ } if (es.username === 'elastic') { log( - `Setting [${fromPath}.username] to "elastic" is deprecated. You should use the "kibana" user instead.` + `Setting [${fromPath}.username] to "elastic" is deprecated. You should use the "kibana_system" user instead.` + ); + } else if (es.username === 'kibana') { + log( + `Setting [${fromPath}.username] to "kibana" is deprecated. You should use the "kibana_system" user instead.` ); } if (es.ssl?.key !== undefined && es.ssl?.certificate === undefined) { diff --git a/src/core/server/http/integration_tests/core_services.test.ts b/src/core/server/http/integration_tests/core_services.test.ts index 5726486a0930a3..c7925f5b6d8217 100644 --- a/src/core/server/http/integration_tests/core_services.test.ts +++ b/src/core/server/http/integration_tests/core_services.test.ts @@ -43,7 +43,7 @@ describe('http service', () => { describe('auth', () => { let root: ReturnType; beforeEach(async () => { - root = kbnTestServer.createRoot(); + root = kbnTestServer.createRoot({ plugins: { initialize: false } }); }, 30000); afterEach(async () => { @@ -192,7 +192,7 @@ describe('http service', () => { let root: ReturnType; beforeEach(async () => { - root = kbnTestServer.createRoot(); + root = kbnTestServer.createRoot({ plugins: { initialize: false } }); }, 30000); afterEach(async () => { @@ -326,7 +326,7 @@ describe('http service', () => { describe('#basePath()', () => { let root: ReturnType; beforeEach(async () => { - root = kbnTestServer.createRoot(); + root = kbnTestServer.createRoot({ plugins: { initialize: false } }); }, 30000); afterEach(async () => await root.shutdown()); @@ -355,7 +355,7 @@ describe('http service', () => { describe('elasticsearch', () => { let root: ReturnType; beforeEach(async () => { - root = kbnTestServer.createRoot(); + root = kbnTestServer.createRoot({ plugins: { initialize: false } }); }, 30000); afterEach(async () => { diff --git a/src/legacy/core_plugins/interpreter/README.md b/src/legacy/core_plugins/interpreter/README.md deleted file mode 100644 index 6d90ce2d5e2ebd..00000000000000 --- a/src/legacy/core_plugins/interpreter/README.md +++ /dev/null @@ -1,2 +0,0 @@ -Interpreter legacy plugin has been migrated to the New Platform. Use -`expressions` New Platform plugin instead. diff --git a/src/legacy/core_plugins/interpreter/index.ts b/src/legacy/core_plugins/interpreter/index.ts deleted file mode 100644 index 9427a2f8a2d0f3..00000000000000 --- a/src/legacy/core_plugins/interpreter/index.ts +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { resolve } from 'path'; -import { Legacy } from '../../../../kibana'; -import { init } from './init'; - -// eslint-disable-next-line -export default function InterpreterPlugin(kibana: any) { - const config: Legacy.PluginSpecOptions = { - id: 'interpreter', - require: ['kibana', 'elasticsearch'], - publicDir: resolve(__dirname, 'public'), - uiExports: { - injectDefaultVars: server => ({ - serverBasePath: server.config().get('server.basePath'), - }), - }, - config: (Joi: any) => { - return Joi.object({ - enabled: Joi.boolean().default(true), - }).default(); - }, - init, - }; - - return new kibana.Plugin(config); -} diff --git a/src/legacy/core_plugins/interpreter/init.ts b/src/legacy/core_plugins/interpreter/init.ts deleted file mode 100644 index 46da1539afadb6..00000000000000 --- a/src/legacy/core_plugins/interpreter/init.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* eslint-disable max-classes-per-file */ - -// @ts-ignore -import { register, registryFactory, Registry, Fn } from '@kbn/interpreter/common'; - -import { Legacy } from '../../../../kibana'; - -export async function init(server: Legacy.Server /* options */) { - server.injectUiAppVars('canvas', () => { - const config = server.config(); - const basePath = config.get('server.basePath'); - const reportingBrowserType = (() => { - const configKey = 'xpack.reporting.capture.browser.type'; - if (!config.has(configKey)) { - return null; - } - return config.get(configKey); - })(); - - return { - kbnIndex: config.get('kibana.index'), - serverFunctions: (server.newPlatform.setup.plugins.expressions as any).__LEGACY - .registries() - .serverFunctions.toArray(), - basePath, - reportingBrowserType, - }; - }); - - // Expose server.plugins.interpreter.register(specs) and - // server.plugins.interpreter.registries() (a getter). - server.expose((server.newPlatform.setup.plugins.expressions as any).__LEGACY); -} diff --git a/src/legacy/core_plugins/interpreter/package.json b/src/legacy/core_plugins/interpreter/package.json deleted file mode 100644 index 3265dadd7fbfc2..00000000000000 --- a/src/legacy/core_plugins/interpreter/package.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "name": "interpreter", - "version": "kibana" -} diff --git a/src/legacy/core_plugins/interpreter/public/canvas/load_legacy_server_function_wrappers.ts b/src/legacy/core_plugins/interpreter/public/canvas/load_legacy_server_function_wrappers.ts deleted file mode 100644 index fed157846a1a15..00000000000000 --- a/src/legacy/core_plugins/interpreter/public/canvas/load_legacy_server_function_wrappers.ts +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This file needs to be deleted by 8.0 release. It is here to load available - * server side functions and create a wrappers around them on client side, to - * execute them from client side. This functionality is used only by Canvas - * and all server side functions are in Canvas plugin. - * - * In 8.0 there will be no server-side functions, plugins will register only - * client side functions and if they need those to execute something on the - * server side, it should be respective function's internal implementation detail. - */ - -import { npSetup } from 'ui/new_platform'; - -export const { loadLegacyServerFunctionWrappers } = npSetup.plugins.expressions.__LEGACY; diff --git a/src/legacy/core_plugins/interpreter/public/interpreter.ts b/src/legacy/core_plugins/interpreter/public/interpreter.ts deleted file mode 100644 index 319a2779010c31..00000000000000 --- a/src/legacy/core_plugins/interpreter/public/interpreter.ts +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import 'uiExports/interpreter'; -// @ts-ignore -import { register, registryFactory } from '@kbn/interpreter/common'; -import { npSetup } from 'ui/new_platform'; -import { registries } from './registries'; -import { Executor, ExpressionExecutor } from '../../../../plugins/expressions/public'; - -// Expose kbnInterpreter.register(specs) and kbnInterpreter.registries() globally so that plugins -// can register without a transpile step. -// TODO: This will be left behind in then legacy platform? -(global as any).kbnInterpreter = Object.assign( - (global as any).kbnInterpreter || {}, - registryFactory(registries) -); - -// TODO: This function will be left behind in the legacy platform. -let executorPromise: Promise | undefined; -export const getInterpreter = async () => { - if (!executorPromise) { - const executor = npSetup.plugins.expressions.__LEGACY.getExecutor(); - executorPromise = Promise.resolve(executor); - } - return await executorPromise; -}; - -// TODO: This function will be left behind in the legacy platform. -export const interpretAst: Executor['run'] = async (ast, context, handlers) => { - const { interpreter } = await getInterpreter(); - return await interpreter.interpretAst(ast, context, handlers); -}; diff --git a/src/legacy/core_plugins/interpreter/public/registries.karma_mock.ts b/src/legacy/core_plugins/interpreter/public/registries.karma_mock.ts deleted file mode 100644 index 0f37f33cc1b13d..00000000000000 --- a/src/legacy/core_plugins/interpreter/public/registries.karma_mock.ts +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import sinon from 'sinon'; - -export const functionsRegistry = {}; -export const renderersRegistry = {}; -export const typesRegistry = {}; -export const registries = { - browserFunctions: functionsRegistry, - renderers: renderersRegistry, - types: typesRegistry, - loadLegacyServerFunctionWrappers: () => Promise.resolve(), -}; - -const resetRegistry = (registry: any) => { - registry.wrapper = sinon.stub(); - registry.register = sinon.stub(); - registry.toJS = sinon.stub(); - registry.toArray = sinon.stub(); - registry.get = sinon.stub(); - registry.getProp = sinon.stub(); - registry.reset = sinon.stub(); -}; -const resetAll = () => Object.values(registries).forEach(resetRegistry); - -resetAll(); -afterEach(resetAll); diff --git a/src/legacy/core_plugins/interpreter/public/registries.ts b/src/legacy/core_plugins/interpreter/public/registries.ts deleted file mode 100644 index 63fd9089acf4a8..00000000000000 --- a/src/legacy/core_plugins/interpreter/public/registries.ts +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { npSetup } from 'ui/new_platform'; - -export const functionsRegistry = npSetup.plugins.expressions.__LEGACY.functions; -export const renderersRegistry = npSetup.plugins.expressions.__LEGACY.renderers; -export const typesRegistry = npSetup.plugins.expressions.__LEGACY.types; -export const registries = { - browserFunctions: functionsRegistry, - renderers: renderersRegistry, - types: typesRegistry, -}; diff --git a/src/legacy/core_plugins/kibana/index.js b/src/legacy/core_plugins/kibana/index.js index 48d86e3628e491..51577456135d16 100644 --- a/src/legacy/core_plugins/kibana/index.js +++ b/src/legacy/core_plugins/kibana/index.js @@ -53,7 +53,7 @@ export default function(kibana) { }, uiExports: { - hacks: ['plugins/kibana/discover/legacy', 'plugins/kibana/dev_tools'], + hacks: ['plugins/kibana/dev_tools'], app: { id: 'kibana', title: 'Kibana', diff --git a/src/legacy/core_plugins/kibana/public/discover/__tests__/doc_table/doc_table.js b/src/legacy/core_plugins/kibana/public/__tests__/discover/doc_table.js similarity index 96% rename from src/legacy/core_plugins/kibana/public/discover/__tests__/doc_table/doc_table.js rename to src/legacy/core_plugins/kibana/public/__tests__/discover/doc_table.js index 9e74df08233dad..edf65fdb56220d 100644 --- a/src/legacy/core_plugins/kibana/public/discover/__tests__/doc_table/doc_table.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/discover/doc_table.js @@ -16,18 +16,15 @@ * specific language governing permissions and limitations * under the License. */ - import angular from 'angular'; import expect from '@kbn/expect'; import _ from 'lodash'; import ngMock from 'ng_mock'; import 'ui/private'; -import { pluginInstance } from 'plugins/kibana/discover/legacy'; +import { pluginInstance } from './legacy'; import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; import hits from 'fixtures/real_hits'; -// Load the kibana app dependencies. - let $parentScope; let $scope; @@ -60,6 +57,7 @@ const destroy = function() { describe('docTable', function() { let $elem; + beforeEach(() => pluginInstance.initializeInnerAngular()); beforeEach(() => pluginInstance.initializeServices()); beforeEach(ngMock.module('app/discover')); diff --git a/src/legacy/core_plugins/kibana/public/discover/__tests__/directives/fixed_scroll.js b/src/legacy/core_plugins/kibana/public/__tests__/discover/fixed_scroll.js similarity index 89% rename from src/legacy/core_plugins/kibana/public/discover/__tests__/directives/fixed_scroll.js rename to src/legacy/core_plugins/kibana/public/__tests__/discover/fixed_scroll.js index 49a0df54079ea5..4a8736cc0d6a45 100644 --- a/src/legacy/core_plugins/kibana/public/discover/__tests__/directives/fixed_scroll.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/discover/fixed_scroll.js @@ -17,21 +17,33 @@ * under the License. */ +/* eslint-disable @kbn/eslint/no-restricted-paths */ + +import angular from 'angular'; import expect from '@kbn/expect'; -import { pluginInstance } from 'plugins/kibana/discover/legacy'; import ngMock from 'ng_mock'; import $ from 'jquery'; import sinon from 'sinon'; +import { PrivateProvider } from '../../../../../../plugins/kibana_legacy/public'; +import { FixedScrollProvider } from '../../../../../../plugins/discover/public/application/angular/directives/fixed_scroll'; +import { DebounceProviderTimeout } from '../../../../../../plugins/discover/public/application/angular/directives/debounce/debounce'; + +const testModuleName = 'fixedScroll'; + +angular + .module(testModuleName, []) + .provider('Private', PrivateProvider) + .service('debounce', ['$timeout', DebounceProviderTimeout]) + .directive('fixedScroll', FixedScrollProvider); + describe('FixedScroll directive', function() { const sandbox = sinon.createSandbox(); let compile; let flushPendingTasks; const trash = []; - beforeEach(() => pluginInstance.initializeServices()); - beforeEach(() => pluginInstance.initializeInnerAngular()); - beforeEach(ngMock.module('app/discover')); + beforeEach(ngMock.module(testModuleName)); beforeEach( ngMock.inject(function($compile, $rootScope, $timeout) { flushPendingTasks = function flushPendingTasks() { diff --git a/src/legacy/core_plugins/kibana/public/discover/legacy.ts b/src/legacy/core_plugins/kibana/public/__tests__/discover/legacy.ts similarity index 80% rename from src/legacy/core_plugins/kibana/public/discover/legacy.ts rename to src/legacy/core_plugins/kibana/public/__tests__/discover/legacy.ts index f08fd22c718504..ecda2a8c153951 100644 --- a/src/legacy/core_plugins/kibana/public/discover/legacy.ts +++ b/src/legacy/core_plugins/kibana/public/__tests__/discover/legacy.ts @@ -17,11 +17,11 @@ * under the License. */ -import { PluginInitializerContext } from 'kibana/public'; import { npSetup, npStart } from 'ui/new_platform'; -import { plugin } from './index'; +import { plugin } from '../../../../../../plugins/discover/public'; +import { coreMock } from '../../../../../../core/public/mocks'; +const context = coreMock.createPluginInitializerContext(); -// Legacy compatibility part - to be removed at cutover, replaced by a kibana.json file -export const pluginInstance = plugin({} as PluginInitializerContext); +export const pluginInstance = plugin(context); export const setup = pluginInstance.setup(npSetup.core, npSetup.plugins); export const start = pluginInstance.start(npStart.core, npStart.plugins); diff --git a/src/legacy/core_plugins/kibana/public/discover/__tests__/doc_table/lib/rows_headers.js b/src/legacy/core_plugins/kibana/public/__tests__/discover/row_headers.js similarity index 98% rename from src/legacy/core_plugins/kibana/public/discover/__tests__/doc_table/lib/rows_headers.js rename to src/legacy/core_plugins/kibana/public/__tests__/discover/row_headers.js index 9b63b8cd18f3e9..5450a4127b63c8 100644 --- a/src/legacy/core_plugins/kibana/public/discover/__tests__/doc_table/lib/rows_headers.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/discover/row_headers.js @@ -16,7 +16,6 @@ * specific language governing permissions and limitations * under the License. */ - import angular from 'angular'; import _ from 'lodash'; import sinon from 'sinon'; @@ -24,7 +23,7 @@ import expect from '@kbn/expect'; import ngMock from 'ng_mock'; import { getFakeRow, getFakeRowVals } from 'fixtures/fake_row'; import $ from 'jquery'; -import { pluginInstance } from 'plugins/kibana/discover/legacy'; +import { pluginInstance } from './legacy'; import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; describe('Doc Table', function() { @@ -218,7 +217,7 @@ describe('Doc Table', function() { }); /** this no longer works with the new plugin approach - it('should render even when the row source contains a field with the same name as a meta field', function () { + it('should render even when the row source contains a field with the same name as a meta field', function () { setTimeout(() => { //this should be overridden by later changes }, 100); diff --git a/src/legacy/core_plugins/kibana/public/discover/_index.scss b/src/legacy/core_plugins/kibana/public/discover/_index.scss deleted file mode 100644 index 386472a9f6e015..00000000000000 --- a/src/legacy/core_plugins/kibana/public/discover/_index.scss +++ /dev/null @@ -1,2 +0,0 @@ -// Discover plugin styles -@import 'np_ready/index'; diff --git a/src/legacy/core_plugins/kibana/public/discover/index.ts b/src/legacy/core_plugins/kibana/public/discover/index.ts deleted file mode 100644 index b449b70418d020..00000000000000 --- a/src/legacy/core_plugins/kibana/public/discover/index.ts +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { PluginInitializerContext } from 'kibana/public'; -import { DiscoverPlugin } from './plugin'; - -// Core will be looking for this when loading our plugin in the new platform -export const plugin = (context: PluginInitializerContext) => { - return new DiscoverPlugin(); -}; diff --git a/src/legacy/core_plugins/kibana/public/discover/plugin.ts b/src/legacy/core_plugins/kibana/public/discover/plugin.ts deleted file mode 100644 index 702331529b8794..00000000000000 --- a/src/legacy/core_plugins/kibana/public/discover/plugin.ts +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { BehaviorSubject } from 'rxjs'; -import { filter, map } from 'rxjs/operators'; -import { AppMountParameters, CoreSetup, CoreStart, Plugin } from 'kibana/public'; -import angular, { auto } from 'angular'; -import { UiActionsSetup, UiActionsStart } from 'src/plugins/ui_actions/public'; -import { - DataPublicPluginStart, - DataPublicPluginSetup, - esFilters, -} from '../../../../../plugins/data/public'; -import { registerFeature } from './np_ready/register_feature'; -import './kibana_services'; -import { EmbeddableStart, EmbeddableSetup } from '../../../../../plugins/embeddable/public'; -import { getInnerAngularModule, getInnerAngularModuleEmbeddable } from './get_inner_angular'; -import { getHistory, setAngularModule, setServices, setUrlTracker } from './kibana_services'; -import { NavigationPublicPluginStart as NavigationStart } from '../../../../../plugins/navigation/public'; -import { ChartsPluginStart } from '../../../../../plugins/charts/public'; -import { buildServices } from './build_services'; -import { SharePluginStart } from '../../../../../plugins/share/public'; -import { - KibanaLegacySetup, - AngularRenderedAppUpdater, -} from '../../../../../plugins/kibana_legacy/public'; -import { DiscoverSetup, DiscoverStart } from '../../../../../plugins/discover/public'; -import { HomePublicPluginSetup } from '../../../../../plugins/home/public'; -import { - VisualizationsStart, - VisualizationsSetup, -} from '../../../../../plugins/visualizations/public'; -import { createKbnUrlTracker } from '../../../../../plugins/kibana_utils/public'; - -export interface DiscoverSetupPlugins { - uiActions: UiActionsSetup; - embeddable: EmbeddableSetup; - kibanaLegacy: KibanaLegacySetup; - home: HomePublicPluginSetup; - visualizations: VisualizationsSetup; - data: DataPublicPluginSetup; - discover: DiscoverSetup; -} -export interface DiscoverStartPlugins { - uiActions: UiActionsStart; - embeddable: EmbeddableStart; - navigation: NavigationStart; - charts: ChartsPluginStart; - data: DataPublicPluginStart; - share: SharePluginStart; - inspector: any; - visualizations: VisualizationsStart; - discover: DiscoverStart; -} -const innerAngularName = 'app/discover'; -const embeddableAngularName = 'app/discoverEmbeddable'; - -/** - * Contains Discover, one of the oldest parts of Kibana - * There are 2 kinds of Angular bootstrapped for rendering, additionally to the main Angular - * Discover provides embeddables, those contain a slimmer Angular - */ -export class DiscoverPlugin implements Plugin { - private servicesInitialized: boolean = false; - private innerAngularInitialized: boolean = false; - private embeddableInjector: auto.IInjectorService | null = null; - private getEmbeddableInjector: (() => Promise) | null = null; - private appStateUpdater = new BehaviorSubject(() => ({})); - private stopUrlTracking: (() => void) | undefined = undefined; - - /** - * why are those functions public? they are needed for some mocha tests - * can be removed once all is Jest - */ - public initializeInnerAngular?: () => void; - public initializeServices?: () => Promise<{ core: CoreStart; plugins: DiscoverStartPlugins }>; - - setup(core: CoreSetup, plugins: DiscoverSetupPlugins) { - const { - appMounted, - appUnMounted, - stop: stopUrlTracker, - setActiveUrl: setTrackedUrl, - } = createKbnUrlTracker({ - // we pass getter here instead of plain `history`, - // so history is lazily created (when app is mounted) - // this prevents redundant `#` when not in discover app - getHistory, - baseUrl: core.http.basePath.prepend('/app/kibana'), - defaultSubUrl: '#/discover', - storageKey: `lastUrl:${core.http.basePath.get()}:discover`, - navLinkUpdater$: this.appStateUpdater, - toastNotifications: core.notifications.toasts, - stateParams: [ - { - kbnUrlKey: '_g', - stateUpdate$: plugins.data.query.state$.pipe( - filter( - ({ changes }) => !!(changes.globalFilters || changes.time || changes.refreshInterval) - ), - map(({ state }) => ({ - ...state, - filters: state.filters?.filter(esFilters.isFilterPinned), - })) - ), - }, - ], - }); - setUrlTracker({ setTrackedUrl }); - this.stopUrlTracking = () => { - stopUrlTracker(); - }; - - this.getEmbeddableInjector = this.getInjector.bind(this); - plugins.discover.docViews.setAngularInjectorGetter(this.getEmbeddableInjector); - plugins.kibanaLegacy.registerLegacyApp({ - id: 'discover', - title: 'Discover', - updater$: this.appStateUpdater.asObservable(), - navLinkId: 'kibana:discover', - order: -1004, - euiIconType: 'discoverApp', - mount: async (params: AppMountParameters) => { - if (!this.initializeServices) { - throw Error('Discover plugin method initializeServices is undefined'); - } - if (!this.initializeInnerAngular) { - throw Error('Discover plugin method initializeInnerAngular is undefined'); - } - appMounted(); - await this.initializeServices(); - await this.initializeInnerAngular(); - - // make sure the index pattern list is up to date - const [, { data: dataStart }] = await core.getStartServices(); - await dataStart.indexPatterns.clearCache(); - const { renderApp } = await import('./np_ready/application'); - const unmount = await renderApp(innerAngularName, params.element); - return () => { - unmount(); - appUnMounted(); - }; - }, - }); - registerFeature(plugins.home); - this.registerEmbeddable(core, plugins); - } - - start(core: CoreStart, plugins: DiscoverStartPlugins) { - // we need to register the application service at setup, but to render it - // there are some start dependencies necessary, for this reason - // initializeInnerAngular + initializeServices are assigned at start and used - // when the application/embeddable is mounted - this.initializeInnerAngular = async () => { - if (this.innerAngularInitialized) { - return; - } - // this is used by application mount and tests - const module = getInnerAngularModule(innerAngularName, core, plugins); - setAngularModule(module); - this.innerAngularInitialized = true; - }; - - this.initializeServices = async () => { - if (this.servicesInitialized) { - return { core, plugins }; - } - const services = await buildServices(core, plugins, getHistory); - setServices(services); - this.servicesInitialized = true; - - return { core, plugins }; - }; - } - - stop() { - if (this.stopUrlTracking) { - this.stopUrlTracking(); - } - } - - /** - * register embeddable with a slimmer embeddable version of inner angular - */ - private async registerEmbeddable( - core: CoreSetup, - plugins: DiscoverSetupPlugins - ) { - const { SearchEmbeddableFactory } = await import('./np_ready/embeddable'); - - if (!this.getEmbeddableInjector) { - throw Error('Discover plugin method getEmbeddableInjector is undefined'); - } - - const getStartServices = async () => { - const [coreStart, deps] = await core.getStartServices(); - return { - executeTriggerActions: deps.uiActions.executeTriggerActions, - isEditable: () => coreStart.application.capabilities.discover.save as boolean, - }; - }; - - const factory = new SearchEmbeddableFactory(getStartServices, this.getEmbeddableInjector); - plugins.embeddable.registerEmbeddableFactory(factory.type, factory); - } - - private async getInjector() { - if (!this.embeddableInjector) { - if (!this.initializeServices) { - throw Error('Discover plugin getEmbeddableInjector: initializeServices is undefined'); - } - const { core, plugins } = await this.initializeServices(); - getInnerAngularModuleEmbeddable(embeddableAngularName, core, plugins); - const mountpoint = document.createElement('div'); - this.embeddableInjector = angular.bootstrap(mountpoint, [embeddableAngularName]); - } - - return this.embeddableInjector; - } -} diff --git a/src/legacy/core_plugins/kibana/public/index.scss b/src/legacy/core_plugins/kibana/public/index.scss index 26805554370b96..6a2e65e3a9ff53 100644 --- a/src/legacy/core_plugins/kibana/public/index.scss +++ b/src/legacy/core_plugins/kibana/public/index.scss @@ -7,9 +7,6 @@ // Public UI styles @import 'src/legacy/ui/public/index'; -// Discover styles -@import 'discover/index'; - // Has to come after visualize because of some // bad cascading in the Editor layout @import '../../../../plugins/maps_legacy/public/index'; diff --git a/src/legacy/core_plugins/kibana/public/kibana.js b/src/legacy/core_plugins/kibana/public/kibana.js index ea0d5ad3790b13..ad67a74121cc94 100644 --- a/src/legacy/core_plugins/kibana/public/kibana.js +++ b/src/legacy/core_plugins/kibana/public/kibana.js @@ -42,7 +42,6 @@ import 'uiExports/shareContextMenuExtensions'; import 'uiExports/interpreter'; import 'ui/autoload/all'; -import './discover/legacy'; import './management'; import './dev_tools'; import { showAppRedirectNotification } from '../../../../plugins/kibana_legacy/public'; diff --git a/src/legacy/core_plugins/kibana/public/management/sections/index_patterns/create_index_pattern_wizard/__snapshots__/create_index_pattern_wizard.test.tsx.snap b/src/legacy/core_plugins/kibana/public/management/sections/index_patterns/create_index_pattern_wizard/__snapshots__/create_index_pattern_wizard.test.tsx.snap index ed65db10e0acb6..1545ab8cb9b1ce 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/index_patterns/create_index_pattern_wizard/__snapshots__/create_index_pattern_wizard.test.tsx.snap +++ b/src/legacy/core_plugins/kibana/public/management/sections/index_patterns/create_index_pattern_wizard/__snapshots__/create_index_pattern_wizard.test.tsx.snap @@ -149,6 +149,8 @@ exports[`CreateIndexPatternWizard renders time field step when step is set to 2 indexPatternsService={ Object { "clearCache": [MockFunction], + "createField": [MockFunction], + "createFieldList": [MockFunction], "ensureDefaultIndexPattern": [MockFunction], "get": [MockFunction], "make": [Function], diff --git a/src/legacy/core_plugins/kibana/public/management/sections/index_patterns/edit_index_pattern/create_edit_field/create_edit_field.tsx b/src/legacy/core_plugins/kibana/public/management/sections/index_patterns/edit_index_pattern/create_edit_field/create_edit_field.tsx index 564f115cf2c487..3b865f7d5e1eaf 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/index_patterns/edit_index_pattern/create_edit_field/create_edit_field.tsx +++ b/src/legacy/core_plugins/kibana/public/management/sections/index_patterns/edit_index_pattern/create_edit_field/create_edit_field.tsx @@ -24,8 +24,8 @@ import { FieldEditor } from 'ui/field_editor'; import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { HttpStart, DocLinksStart } from 'src/core/public'; +import { IndexPattern, DataPublicPluginStart } from 'src/plugins/data/public'; import { IndexHeader } from '../index_header'; -import { IndexPattern, IndexPatternField } from '../../../../../../../../../plugins/data/public'; import { ChromeDocTitle, NotificationsStart } from '../../../../../../../../../core/public'; import { TAB_SCRIPTED_FIELDS, TAB_INDEXED_FIELDS } from '../constants'; @@ -36,6 +36,7 @@ interface CreateEditFieldProps extends RouteComponentProps { fieldFormatEditors: any; getConfig: (name: string) => any; services: { + dataStart: DataPublicPluginStart; notifications: NotificationsStart; docTitle: ChromeDocTitle; getHttpStart: () => HttpStart; @@ -63,10 +64,14 @@ export const CreateEditField = withRouter( const field = mode === 'edit' && fieldName ? indexPattern.fields.getByName(fieldName) - : new IndexPatternField(indexPattern, { - scripted: true, - type: 'number', - }); + : services.dataStart.indexPatterns.createField( + indexPattern, + { + scripted: true, + type: 'number', + }, + false + ); const url = `/management/kibana/index_patterns/${indexPattern.id}`; diff --git a/src/legacy/core_plugins/kibana/public/management/sections/index_patterns/edit_index_pattern/index.js b/src/legacy/core_plugins/kibana/public/management/sections/index_patterns/edit_index_pattern/index.js index e2f387c0291a7a..ab1fa546e5ea83 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/index_patterns/edit_index_pattern/index.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/index_patterns/edit_index_pattern/index.js @@ -112,6 +112,7 @@ const renderCreateEditField = ($scope, $route, getConfig, fieldFormatEditors) => fieldFormatEditors={fieldFormatEditors} getConfig={getConfig} services={{ + dataStart: npStart.plugins.data, getHttpStart: () => npStart.core.http, notifications: npStart.core.notifications, docTitle: npStart.core.chrome.docTitle, diff --git a/src/legacy/ui/public/field_editor/field_editor.test.tsx b/src/legacy/ui/public/field_editor/field_editor.test.tsx index 5716305b514830..ced7aa27e50657 100644 --- a/src/legacy/ui/public/field_editor/field_editor.test.tsx +++ b/src/legacy/ui/public/field_editor/field_editor.test.tsx @@ -22,9 +22,9 @@ import React from 'react'; import { npStart } from 'ui/new_platform'; import { shallowWithI18nProvider } from 'test_utils/enzyme_helpers'; import { - Field, IndexPattern, - IndexPatternFieldList, + IndexPatternField, + IIndexPatternFieldList, FieldFormatInstanceType, } from 'src/plugins/data/public'; import { HttpStart } from '../../../../core/public'; @@ -76,10 +76,10 @@ jest.mock('./components/field_format_editor', () => ({ FieldFormatEditor: 'field-format-editor', })); -const fields: Field[] = [ +const fields: IndexPatternField[] = [ { name: 'foobar', - } as Field, + } as IndexPatternField, ]; // @ts-ignore @@ -114,7 +114,7 @@ describe('FieldEditor', () => { beforeEach(() => { indexPattern = ({ - fields: fields as IndexPatternFieldList, + fields: fields as IIndexPatternFieldList, } as unknown) as IndexPattern; npStart.plugins.data.fieldFormats.getDefaultType = jest.fn( @@ -133,7 +133,7 @@ describe('FieldEditor', () => { const component = shallowWithI18nProvider( ); @@ -149,18 +149,18 @@ describe('FieldEditor', () => { name: 'test', script: 'doc.test.value', }; - indexPattern.fields.push(testField as Field); + indexPattern.fields.push(testField as IndexPatternField); indexPattern.fields.getByName = name => { const flds = { [testField.name]: testField, }; - return flds[name] as Field; + return flds[name] as IndexPatternField; }; const component = shallowWithI18nProvider( ); @@ -177,18 +177,18 @@ describe('FieldEditor', () => { script: 'doc.test.value', lang: 'testlang', }; - indexPattern.fields.push((testField as unknown) as Field); + indexPattern.fields.push((testField as unknown) as IndexPatternField); indexPattern.fields.getByName = name => { const flds = { [testField.name]: testField, }; - return flds[name] as Field; + return flds[name] as IndexPatternField; }; const component = shallowWithI18nProvider( ); @@ -203,7 +203,7 @@ describe('FieldEditor', () => { const component = shallowWithI18nProvider( ); @@ -226,7 +226,7 @@ describe('FieldEditor', () => { const component = shallowWithI18nProvider( ); diff --git a/src/legacy/ui/public/field_editor/field_editor.tsx b/src/legacy/ui/public/field_editor/field_editor.tsx index aa62a53f2c32a1..7de70f5d956e88 100644 --- a/src/legacy/ui/public/field_editor/field_editor.tsx +++ b/src/legacy/ui/public/field_editor/field_editor.tsx @@ -55,13 +55,13 @@ import { import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { + IndexPatternField, + FieldFormatInstanceType, IndexPattern, IFieldType, KBN_FIELD_TYPES, ES_FIELD_TYPES, } from '../../../../plugins/data/public'; -import { FieldFormatInstanceType } from '../../../../plugins/data/common'; -import { Field } from '../../../../plugins/data/public'; import { ScriptingDisabledCallOut, ScriptingWarningCallOut, @@ -114,7 +114,7 @@ interface InitialFieldTypeFormat extends FieldTypeFormat { defaultFieldFormat: FieldFormatInstanceType; } -interface FieldClone extends Field { +interface FieldClone extends IndexPatternField { format: any; } @@ -139,7 +139,7 @@ export interface FieldEditorState { export interface FieldEdiorProps { indexPattern: IndexPattern; - field: Field; + field: IndexPatternField; helpers: { getConfig: (key: string) => any; getHttpStart: () => HttpStart; diff --git a/src/legacy/ui/public/styles/_legacy/components/_table.scss b/src/legacy/ui/public/styles/_legacy/components/_table.scss index c9472cbd2faa73..d0ac9d6f798628 100644 --- a/src/legacy/ui/public/styles/_legacy/components/_table.scss +++ b/src/legacy/ui/public/styles/_legacy/components/_table.scss @@ -1,4 +1,4 @@ -@import '../../../../../core_plugins/kibana/public/discover/np_ready/mixins'; +@import '../../../../../../plugins/discover/public/application/mixins'; .table { // Nesting diff --git a/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.tsx b/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.tsx index cf62de82bcf4b3..47f7aa16352053 100644 --- a/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.tsx +++ b/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.tsx @@ -24,7 +24,7 @@ import { parse } from 'query-string'; import React, { CSSProperties, useCallback, useEffect, useRef, useState } from 'react'; import { useUIAceKeyboardMode } from '../../../../../../../es_ui_shared/public'; // @ts-ignore -import mappings from '../../../../../lib/mappings/mappings'; +import { retrieveAutoCompleteInfo, clearSubscriptions } from '../../../../../lib/mappings/mappings'; import { ConsoleMenu } from '../../../../components'; import { useEditorReadContext, useServicesContext } from '../../../../contexts'; import { @@ -172,14 +172,14 @@ function EditorUI({ initialTextValue }: EditorProps) { setInputEditor(editor); setTextArea(editorRef.current!.querySelector('textarea')); - mappings.retrieveAutoCompleteInfo(settingsService, settingsService.getAutocomplete()); + retrieveAutoCompleteInfo(settingsService, settingsService.getAutocomplete()); const unsubscribeResizer = subscribeResizeChecker(editorRef.current!, editor); setupAutosave(); return () => { unsubscribeResizer(); - mappings.clearSubscriptions(); + clearSubscriptions(); window.removeEventListener('hashchange', onHashChange); }; }, [saveCurrentTextObject, initialTextValue, history, setInputEditor, settingsService]); diff --git a/src/plugins/console/public/application/containers/settings.tsx b/src/plugins/console/public/application/containers/settings.tsx index e34cfcac8096bb..81938a83435de9 100644 --- a/src/plugins/console/public/application/containers/settings.tsx +++ b/src/plugins/console/public/application/containers/settings.tsx @@ -21,7 +21,7 @@ import React from 'react'; import { AutocompleteOptions, DevToolsSettingsModal } from '../components'; // @ts-ignore -import mappings from '../../lib/mappings/mappings'; +import { retrieveAutoCompleteInfo } from '../../lib/mappings/mappings'; import { useServicesContext, useEditorActionContext } from '../contexts'; import { DevToolsSettings, Settings as SettingsService } from '../../services'; @@ -33,7 +33,7 @@ const getAutocompleteDiff = (newSettings: DevToolsSettings, prevSettings: DevToo }; const refreshAutocompleteSettings = (settings: SettingsService, selectedSettings: any) => { - mappings.retrieveAutoCompleteInfo(settings, selectedSettings); + retrieveAutoCompleteInfo(settings, selectedSettings); }; const fetchAutocompleteSettingsIfNeeded = ( @@ -61,10 +61,10 @@ const fetchAutocompleteSettingsIfNeeded = ( }, {} ); - mappings.retrieveAutoCompleteInfo(settings, changedSettings); + retrieveAutoCompleteInfo(settings, changedSettings); } else if (isPollingChanged && newSettings.polling) { // If the user has turned polling on, then we'll fetch all selected autocomplete settings. - mappings.retrieveAutoCompleteInfo(settings, settings.getAutocomplete()); + retrieveAutoCompleteInfo(settings, settings.getAutocomplete()); } } }; diff --git a/src/plugins/console/public/application/hooks/use_send_current_request_to_es/use_send_current_request_to_es.ts b/src/plugins/console/public/application/hooks/use_send_current_request_to_es/use_send_current_request_to_es.ts index dde793d9b9691e..f0ce61f1d34016 100644 --- a/src/plugins/console/public/application/hooks/use_send_current_request_to_es/use_send_current_request_to_es.ts +++ b/src/plugins/console/public/application/hooks/use_send_current_request_to_es/use_send_current_request_to_es.ts @@ -24,7 +24,7 @@ import { sendRequestToES } from './send_request_to_es'; import { track } from './track'; // @ts-ignore -import mappings from '../../../lib/mappings/mappings'; +import { retrieveAutoCompleteInfo } from '../../../lib/mappings/mappings'; export const useSendCurrentRequestToES = () => { const { @@ -73,7 +73,7 @@ export const useSendCurrentRequestToES = () => { // or templates may have changed, so we'll need to update this data. Assume that if // the user disables polling they're trying to optimize performance or otherwise // preserve resources, so they won't want this request sent either. - mappings.retrieveAutoCompleteInfo(settings, settings.getAutocomplete()); + retrieveAutoCompleteInfo(settings, settings.getAutocomplete()); } dispatch({ diff --git a/src/plugins/console/public/application/models/legacy_core_editor/__tests__/output_tokenization.test.js b/src/plugins/console/public/application/models/legacy_core_editor/__tests__/output_tokenization.test.js index 5c86b0a1d20924..1db9ca7bc0a865 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/__tests__/output_tokenization.test.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/__tests__/output_tokenization.test.js @@ -17,7 +17,7 @@ * under the License. */ import '../legacy_core_editor.test.mocks'; -const $ = require('jquery'); +import $ from 'jquery'; import RowParser from '../../../../lib/row_parser'; import ace from 'brace'; import { createReadOnlyAceEditor } from '../create_readonly'; diff --git a/src/plugins/console/public/application/models/legacy_core_editor/mode/input.js b/src/plugins/console/public/application/models/legacy_core_editor/mode/input.js index d763db7ae5d795..77b4ba8cea6ffc 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/mode/input.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/mode/input.js @@ -19,20 +19,21 @@ import ace from 'brace'; import { workerModule } from './worker'; +import { ScriptMode } from './script'; const oop = ace.acequire('ace/lib/oop'); const TextMode = ace.acequire('ace/mode/text').Mode; -const ScriptMode = require('./script').ScriptMode; + const MatchingBraceOutdent = ace.acequire('ace/mode/matching_brace_outdent').MatchingBraceOutdent; const CstyleBehaviour = ace.acequire('ace/mode/behaviour/cstyle').CstyleBehaviour; const CStyleFoldMode = ace.acequire('ace/mode/folding/cstyle').FoldMode; const WorkerClient = ace.acequire('ace/worker/worker_client').WorkerClient; const AceTokenizer = ace.acequire('ace/tokenizer').Tokenizer; -const HighlightRules = require('./input_highlight_rules').InputHighlightRules; +import { InputHighlightRules } from './input_highlight_rules'; export function Mode() { - this.$tokenizer = new AceTokenizer(new HighlightRules().getRules()); + this.$tokenizer = new AceTokenizer(new InputHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); diff --git a/src/plugins/console/public/application/models/legacy_core_editor/mode/input_highlight_rules.js b/src/plugins/console/public/application/models/legacy_core_editor/mode/input_highlight_rules.js index 29f192f4ea858e..1558cf0cb55544 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/mode/input_highlight_rules.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/mode/input_highlight_rules.js @@ -17,7 +17,7 @@ * under the License. */ -const ace = require('brace'); +import ace from 'brace'; import { addXJsonToRules } from '../../../../../../es_ui_shared/public'; export function addEOL(tokens, reg, nextIfEOL, normalNext) { diff --git a/src/plugins/console/public/application/models/legacy_core_editor/mode/output.js b/src/plugins/console/public/application/models/legacy_core_editor/mode/output.js index 40e3128e396a37..5ad34532d18610 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/mode/output.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/mode/output.js @@ -18,11 +18,11 @@ */ import ace from 'brace'; -require('./output_highlight_rules'); + +import { OutputJsonHighlightRules } from './output_highlight_rules'; const oop = ace.acequire('ace/lib/oop'); const JSONMode = ace.acequire('ace/mode/json').Mode; -const HighlightRules = require('./output_highlight_rules').OutputJsonHighlightRules; const MatchingBraceOutdent = ace.acequire('ace/mode/matching_brace_outdent').MatchingBraceOutdent; const CstyleBehaviour = ace.acequire('ace/mode/behaviour/cstyle').CstyleBehaviour; const CStyleFoldMode = ace.acequire('ace/mode/folding/cstyle').FoldMode; @@ -30,7 +30,7 @@ ace.acequire('ace/worker/worker_client'); const AceTokenizer = ace.acequire('ace/tokenizer').Tokenizer; export function Mode() { - this.$tokenizer = new AceTokenizer(new HighlightRules().getRules()); + this.$tokenizer = new AceTokenizer(new OutputJsonHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); diff --git a/src/plugins/console/public/application/models/legacy_core_editor/mode/output_highlight_rules.js b/src/plugins/console/public/application/models/legacy_core_editor/mode/output_highlight_rules.js index c9d538ab6ceb17..448fd847aeacda 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/mode/output_highlight_rules.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/mode/output_highlight_rules.js @@ -17,7 +17,7 @@ * under the License. */ -const ace = require('brace'); +import ace from 'brace'; import 'brace/mode/json'; import { addXJsonToRules } from '../../../../../../es_ui_shared/public'; diff --git a/src/plugins/console/public/application/models/legacy_core_editor/theme_sense_dark.js b/src/plugins/console/public/application/models/legacy_core_editor/theme_sense_dark.js index f79a171c650826..8a0eb9a03480bf 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/theme_sense_dark.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/theme_sense_dark.js @@ -18,7 +18,7 @@ */ /* eslint import/no-unresolved: 0 */ -const ace = require('brace'); +import ace from 'brace'; ace.define('ace/theme/sense-dark', ['require', 'exports', 'module'], function(require, exports) { exports.isDark = true; diff --git a/src/plugins/console/public/application/models/sense_editor/__tests__/integration.test.js b/src/plugins/console/public/application/models/sense_editor/__tests__/integration.test.js index c5a0c2ebddf718..edd09885c1ad2a 100644 --- a/src/plugins/console/public/application/models/sense_editor/__tests__/integration.test.js +++ b/src/plugins/console/public/application/models/sense_editor/__tests__/integration.test.js @@ -19,10 +19,10 @@ import '../sense_editor.test.mocks'; import { create } from '../create'; import _ from 'lodash'; -const $ = require('jquery'); +import $ from 'jquery'; -const kb = require('../../../../lib/kb/kb'); -const mappings = require('../../../../lib/mappings/mappings'); +import * as kb from '../../../../lib/kb/kb'; +import * as mappings from '../../../../lib/mappings/mappings'; describe('Integration', () => { let senseEditor; diff --git a/src/plugins/console/public/application/models/sense_editor/__tests__/sense_editor.test.js b/src/plugins/console/public/application/models/sense_editor/__tests__/sense_editor.test.js index 34b4cad7fbb6bb..219e6262ab346c 100644 --- a/src/plugins/console/public/application/models/sense_editor/__tests__/sense_editor.test.js +++ b/src/plugins/console/public/application/models/sense_editor/__tests__/sense_editor.test.js @@ -23,7 +23,7 @@ import _ from 'lodash'; import { create } from '../create'; import { collapseLiteralStrings } from '../../../../../../es_ui_shared/public'; -const editorInput1 = require('./editor_input1.txt'); +import editorInput1 from './editor_input1.txt'; describe('Editor', () => { let input; diff --git a/src/plugins/console/public/lib/autocomplete/__jest__/url_autocomplete.test.js b/src/plugins/console/public/lib/autocomplete/__jest__/url_autocomplete.test.js index 0758a756955662..ebde8c39cffbcb 100644 --- a/src/plugins/console/public/lib/autocomplete/__jest__/url_autocomplete.test.js +++ b/src/plugins/console/public/lib/autocomplete/__jest__/url_autocomplete.test.js @@ -17,7 +17,7 @@ * under the License. */ -const _ = require('lodash'); +import _ from 'lodash'; import { URL_PATH_END_MARKER, UrlPatternMatcher, diff --git a/src/plugins/console/public/lib/autocomplete/__jest__/url_params.test.js b/src/plugins/console/public/lib/autocomplete/__jest__/url_params.test.js index 72fce53c4f1fef..286aefcd133a09 100644 --- a/src/plugins/console/public/lib/autocomplete/__jest__/url_params.test.js +++ b/src/plugins/console/public/lib/autocomplete/__jest__/url_params.test.js @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -const _ = require('lodash'); +import _ from 'lodash'; import { UrlParams } from '../../autocomplete/url_params'; import { populateContext } from '../../autocomplete/engine'; diff --git a/src/plugins/console/public/lib/autocomplete/body_completer.js b/src/plugins/console/public/lib/autocomplete/body_completer.js index 1aa315c50b9bf1..9bb1f14a6266ae 100644 --- a/src/plugins/console/public/lib/autocomplete/body_completer.js +++ b/src/plugins/console/public/lib/autocomplete/body_completer.js @@ -17,7 +17,7 @@ * under the License. */ -const _ = require('lodash'); +import _ from 'lodash'; import { WalkingState, walkTokenPath, wrapComponentWithDefaults } from './engine'; import { ConstantComponent, diff --git a/src/plugins/console/public/lib/autocomplete/components/field_autocomplete_component.js b/src/plugins/console/public/lib/autocomplete/components/field_autocomplete_component.js index 0574ffbcfc3a97..80f65406cf5d30 100644 --- a/src/plugins/console/public/lib/autocomplete/components/field_autocomplete_component.js +++ b/src/plugins/console/public/lib/autocomplete/components/field_autocomplete_component.js @@ -17,11 +17,11 @@ * under the License. */ import _ from 'lodash'; -import mappings from '../../mappings/mappings'; +import { getFields } from '../../mappings/mappings'; import { ListComponent } from './list_component'; function FieldGenerator(context) { - return _.map(mappings.getFields(context.indices, context.types), function(field) { + return _.map(getFields(context.indices, context.types), function(field) { return { name: field.name, meta: field.type }; }); } diff --git a/src/plugins/console/public/lib/autocomplete/components/index_autocomplete_component.js b/src/plugins/console/public/lib/autocomplete/components/index_autocomplete_component.js index 03d67c9e27ee87..ec6f24253e78d0 100644 --- a/src/plugins/console/public/lib/autocomplete/components/index_autocomplete_component.js +++ b/src/plugins/console/public/lib/autocomplete/components/index_autocomplete_component.js @@ -17,14 +17,14 @@ * under the License. */ import _ from 'lodash'; -import mappings from '../../mappings/mappings'; +import { getIndices } from '../../mappings/mappings'; import { ListComponent } from './list_component'; function nonValidIndexType(token) { return !(token === '_all' || token[0] !== '_'); } export class IndexAutocompleteComponent extends ListComponent { constructor(name, parent, multiValued) { - super(name, mappings.getIndices, parent, multiValued); + super(name, getIndices, parent, multiValued); } validateTokens(tokens) { if (!this.multiValued && tokens.length > 1) { diff --git a/src/plugins/console/public/lib/autocomplete/components/template_autocomplete_component.js b/src/plugins/console/public/lib/autocomplete/components/template_autocomplete_component.js index cc62a2f9eeea6c..14141980d493d7 100644 --- a/src/plugins/console/public/lib/autocomplete/components/template_autocomplete_component.js +++ b/src/plugins/console/public/lib/autocomplete/components/template_autocomplete_component.js @@ -16,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ -import mappings from '../../mappings/mappings'; +import { getTemplates } from '../../mappings/mappings'; import { ListComponent } from './list_component'; export class TemplateAutocompleteComponent extends ListComponent { constructor(name, parent) { - super(name, mappings.getTemplates, parent, true, true); + super(name, getTemplates, parent, true, true); } getContextKey() { return 'template'; diff --git a/src/plugins/console/public/lib/autocomplete/components/type_autocomplete_component.js b/src/plugins/console/public/lib/autocomplete/components/type_autocomplete_component.js index 507817c1ed8c56..03d85eccaf3855 100644 --- a/src/plugins/console/public/lib/autocomplete/components/type_autocomplete_component.js +++ b/src/plugins/console/public/lib/autocomplete/components/type_autocomplete_component.js @@ -18,9 +18,9 @@ */ import _ from 'lodash'; import { ListComponent } from './list_component'; -import mappings from '../../mappings/mappings'; +import { getTypes } from '../../mappings/mappings'; function TypeGenerator(context) { - return mappings.getTypes(context.indices); + return getTypes(context.indices); } function nonValidIndexType(token) { return !(token === '_all' || token[0] !== '_'); diff --git a/src/plugins/console/public/lib/autocomplete/components/username_autocomplete_component.js b/src/plugins/console/public/lib/autocomplete/components/username_autocomplete_component.js index 26b7bd5c48c999..14b77d4e706255 100644 --- a/src/plugins/console/public/lib/autocomplete/components/username_autocomplete_component.js +++ b/src/plugins/console/public/lib/autocomplete/components/username_autocomplete_component.js @@ -17,14 +17,14 @@ * under the License. */ import _ from 'lodash'; -import mappings from '../../mappings/mappings'; +import { getIndices } from '../../mappings/mappings'; import { ListComponent } from './list_component'; function nonValidUsernameType(token) { return token[0] === '_'; } export class UsernameAutocompleteComponent extends ListComponent { constructor(name, parent, multiValued) { - super(name, mappings.getIndices, parent, multiValued); + super(name, getIndices, parent, multiValued); } validateTokens(tokens) { if (!this.multiValued && tokens.length > 1) { diff --git a/src/plugins/console/public/lib/autocomplete/engine.js b/src/plugins/console/public/lib/autocomplete/engine.js index 7b64d91c953742..ae943a74ffb3a4 100644 --- a/src/plugins/console/public/lib/autocomplete/engine.js +++ b/src/plugins/console/public/lib/autocomplete/engine.js @@ -17,7 +17,7 @@ * under the License. */ -const _ = require('lodash'); +import _ from 'lodash'; export function wrapComponentWithDefaults(component, defaults) { const originalGetTerms = component.getTerms; diff --git a/src/plugins/console/public/lib/autocomplete/url_params.js b/src/plugins/console/public/lib/autocomplete/url_params.js index 3f05b9ce85aab9..0519a2daade878 100644 --- a/src/plugins/console/public/lib/autocomplete/url_params.js +++ b/src/plugins/console/public/lib/autocomplete/url_params.js @@ -17,7 +17,7 @@ * under the License. */ -const _ = require('lodash'); +import _ from 'lodash'; import { ConstantComponent, ListComponent, SharedComponent } from './components'; export class ParamComponent extends ConstantComponent { diff --git a/src/plugins/console/public/lib/curl_parsing/__tests__/curl_parsing.test.js b/src/plugins/console/public/lib/curl_parsing/__tests__/curl_parsing.test.js index 49a54eaefa9efc..6a8caebfc68746 100644 --- a/src/plugins/console/public/lib/curl_parsing/__tests__/curl_parsing.test.js +++ b/src/plugins/console/public/lib/curl_parsing/__tests__/curl_parsing.test.js @@ -17,15 +17,15 @@ * under the License. */ -const _ = require('lodash'); -const curl = require('../curl'); +import _ from 'lodash'; +import { detectCURL, parseCURL } from '../curl'; import curlTests from './curl_parsing.txt'; describe('CURL', () => { const notCURLS = ['sldhfsljfhs', 's;kdjfsldkfj curl -XDELETE ""', '{ "hello": 1 }']; _.each(notCURLS, function(notCURL, i) { test('cURL Detection - broken strings ' + i, function() { - expect(curl.detectCURL(notCURL)).toEqual(false); + expect(detectCURL(notCURL)).toEqual(false); }); }); @@ -39,8 +39,8 @@ describe('CURL', () => { const response = fixture[2].trim(); test('cURL Detection - ' + name, function() { - expect(curl.detectCURL(curlText)).toBe(true); - const r = curl.parseCURL(curlText); + expect(detectCURL(curlText)).toBe(true); + const r = parseCURL(curlText); expect(r).toEqual(response); }); }); diff --git a/src/plugins/console/public/lib/kb/__tests__/kb.test.js b/src/plugins/console/public/lib/kb/__tests__/kb.test.js index c2c69314a172de..c80f5671449b36 100644 --- a/src/plugins/console/public/lib/kb/__tests__/kb.test.js +++ b/src/plugins/console/public/lib/kb/__tests__/kb.test.js @@ -21,8 +21,8 @@ import _ from 'lodash'; import { populateContext } from '../../autocomplete/engine'; import '../../../application/models/sense_editor/sense_editor.test.mocks'; -const kb = require('../../kb'); -const mappings = require('../../mappings/mappings'); +import * as kb from '../../kb'; +import * as mappings from '../../mappings/mappings'; describe('Knowledge base', () => { beforeEach(() => { diff --git a/src/plugins/console/public/lib/kb/api.js b/src/plugins/console/public/lib/kb/api.js index eeec87060b7704..c418a7cb414efc 100644 --- a/src/plugins/console/public/lib/kb/api.js +++ b/src/plugins/console/public/lib/kb/api.js @@ -17,7 +17,7 @@ * under the License. */ -const _ = require('lodash'); +import _ from 'lodash'; import { UrlPatternMatcher } from '../autocomplete/components'; import { UrlParams } from '../autocomplete/url_params'; import { diff --git a/src/plugins/console/public/lib/mappings/__tests__/mapping.test.js b/src/plugins/console/public/lib/mappings/__tests__/mapping.test.js index 27b3ce26b55883..292b1b4fb1bf58 100644 --- a/src/plugins/console/public/lib/mappings/__tests__/mapping.test.js +++ b/src/plugins/console/public/lib/mappings/__tests__/mapping.test.js @@ -17,7 +17,7 @@ * under the License. */ import '../../../application/models/sense_editor/sense_editor.test.mocks'; -const mappings = require('../mappings'); +import * as mappings from '../mappings'; describe('Mappings', () => { beforeEach(() => { diff --git a/src/plugins/console/public/lib/mappings/mappings.js b/src/plugins/console/public/lib/mappings/mappings.js index 330147118d42cc..b5bcc2b105996b 100644 --- a/src/plugins/console/public/lib/mappings/mappings.js +++ b/src/plugins/console/public/lib/mappings/mappings.js @@ -17,9 +17,9 @@ * under the License. */ -const $ = require('jquery'); -const _ = require('lodash'); -const es = require('../es/es'); +import $ from 'jquery'; +import _ from 'lodash'; +import * as es from '../es/es'; // NOTE: If this value ever changes to be a few seconds or less, it might introduce flakiness // due to timing issues in our app.js tests. @@ -32,7 +32,7 @@ let templates = []; const mappingObj = {}; -function expandAliases(indicesOrAliases) { +export function expandAliases(indicesOrAliases) { // takes a list of indices or aliases or a string which may be either and returns a list of indices // returns a list for multiple values or a string for a single. @@ -60,11 +60,11 @@ function expandAliases(indicesOrAliases) { return ret.length > 1 ? ret : ret[0]; } -function getTemplates() { +export function getTemplates() { return [...templates]; } -function getFields(indices, types) { +export function getFields(indices, types) { // get fields for indices and types. Both can be a list, a string or null (meaning all). let ret = []; indices = expandAliases(indices); @@ -103,7 +103,7 @@ function getFields(indices, types) { }); } -function getTypes(indices) { +export function getTypes(indices) { let ret = []; indices = expandAliases(indices); if (typeof indices === 'string') { @@ -129,7 +129,7 @@ function getTypes(indices) { return _.uniq(ret); } -function getIndices(includeAliases) { +export function getIndices(includeAliases) { const ret = []; $.each(perIndexTypes, function(index) { ret.push(index); @@ -200,7 +200,7 @@ function loadTemplates(templatesObject = {}) { templates = Object.keys(templatesObject); } -function loadMappings(mappings) { +export function loadMappings(mappings) { perIndexTypes = {}; $.each(mappings, function(index, indexMapping) { @@ -224,7 +224,7 @@ function loadMappings(mappings) { }); } -function loadAliases(aliases) { +export function loadAliases(aliases) { perAliasIndexes = {}; $.each(aliases || {}, function(index, omdexAliases) { // verify we have an index defined. useful when mapping loading is disabled @@ -246,7 +246,7 @@ function loadAliases(aliases) { perAliasIndexes._all = getIndices(false); } -function clear() { +export function clear() { perIndexTypes = {}; perAliasIndexes = {}; templates = []; @@ -285,7 +285,7 @@ function retrieveSettings(settingsKey, settingsToRetrieve) { // unchanged alone (both selected and unselected). // 3. Poll: Use saved. Fetch selected. Ignore unselected. -function clearSubscriptions() { +export function clearSubscriptions() { if (pollTimeoutId) { clearTimeout(pollTimeoutId); } @@ -296,7 +296,7 @@ function clearSubscriptions() { * @param settings Settings A way to retrieve the current settings * @param settingsToRetrieve any */ -function retrieveAutoCompleteInfo(settings, settingsToRetrieve) { +export function retrieveAutoCompleteInfo(settings, settingsToRetrieve) { clearSubscriptions(); const mappingPromise = retrieveSettings('fields', settingsToRetrieve); @@ -341,16 +341,3 @@ function retrieveAutoCompleteInfo(settings, settingsToRetrieve) { }, POLL_INTERVAL); }); } - -export default { - getFields, - getTemplates, - getIndices, - getTypes, - loadMappings, - loadAliases, - expandAliases, - clear, - retrieveAutoCompleteInfo, - clearSubscriptions, -}; diff --git a/src/plugins/console/public/lib/utils/__tests__/utils.test.js b/src/plugins/console/public/lib/utils/__tests__/utils.test.js index 6115be3c84ed93..3a2e6a54c1328f 100644 --- a/src/plugins/console/public/lib/utils/__tests__/utils.test.js +++ b/src/plugins/console/public/lib/utils/__tests__/utils.test.js @@ -17,7 +17,7 @@ * under the License. */ -const utils = require('../'); +import * as utils from '../'; describe('Utils class', () => { test('extract deprecation messages', function() { diff --git a/src/plugins/console/server/lib/spec_definitions/js/aggregations.ts b/src/plugins/console/server/lib/spec_definitions/js/aggregations.ts index 1170c9edd2366f..ce3155919bd1d0 100644 --- a/src/plugins/console/server/lib/spec_definitions/js/aggregations.ts +++ b/src/plugins/console/server/lib/spec_definitions/js/aggregations.ts @@ -148,7 +148,7 @@ const rules = { shard_size: 10, order: { __template: { - _term: 'asc', + _key: 'asc', }, _term: { __one_of: ['asc', 'desc'] }, _count: { __one_of: ['asc', 'desc'] }, diff --git a/src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx b/src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx index 8346fd900caef8..7e25d80c9d6191 100644 --- a/src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx +++ b/src/plugins/dashboard/public/application/embeddable/dashboard_container.tsx @@ -177,6 +177,7 @@ export class DashboardContainer extends Container; +interface FieldDependencies { + fieldFormats: FieldFormatsStart; + toastNotifications: ToastsStart; +} + export class Field implements IFieldType { name: string; type: string; @@ -52,7 +63,8 @@ export class Field implements IFieldType { constructor( indexPattern: IndexPattern, spec: FieldSpec | Field, - shortDotsEnable: boolean = false + shortDotsEnable: boolean, + { fieldFormats, toastNotifications }: FieldDependencies ) { // unwrap old instances of Field if (spec instanceof Field) spec = spec.$$spec; @@ -77,9 +89,8 @@ export class Field implements IFieldType { values: { name: spec.name, title: indexPattern.title }, defaultMessage: 'Field {name} in indexPattern {title} is using an unknown field type.', }); - const { toasts } = getNotifications(); - toasts.addDanger({ + toastNotifications.addDanger({ title, text, }); @@ -90,11 +101,9 @@ export class Field implements IFieldType { let format = spec.format; if (!FieldFormat.isInstanceOfFieldFormat(format)) { - const fieldFormatsService = getFieldFormats(); - format = indexPattern.fieldFormatMap[spec.name] || - fieldFormatsService.getDefaultInstance(spec.type, spec.esTypes); + fieldFormats.getDefaultInstance(spec.type, spec.esTypes); } const indexed = !!spec.indexed; diff --git a/src/plugins/data/public/index_patterns/fields/field_list.ts b/src/plugins/data/public/index_patterns/fields/field_list.ts index 9772370199b24a..0631e00a1fb622 100644 --- a/src/plugins/data/public/index_patterns/fields/field_list.ts +++ b/src/plugins/data/public/index_patterns/fields/field_list.ts @@ -18,13 +18,20 @@ */ import { findIndex } from 'lodash'; +import { ToastsStart } from 'kibana/public'; import { IndexPattern } from '../index_patterns'; import { IFieldType } from '../../../common'; import { Field, FieldSpec } from './field'; +import { FieldFormatsStart } from '../../field_formats'; type FieldMap = Map; -export interface IFieldList extends Array { +interface FieldListDependencies { + fieldFormats: FieldFormatsStart; + toastNotifications: ToastsStart; +} + +export interface IIndexPatternFieldList extends Array { getByName(name: Field['name']): Field | undefined; getByType(type: Field['type']): Field[]; add(field: FieldSpec): void; @@ -32,51 +39,70 @@ export interface IFieldList extends Array { update(field: FieldSpec): void; } -export class FieldList extends Array implements IFieldList { - private byName: FieldMap = new Map(); - private groups: Map = new Map(); - private indexPattern: IndexPattern; - private shortDotsEnable: boolean; - private setByName = (field: Field) => this.byName.set(field.name, field); - private setByGroup = (field: Field) => { - if (typeof this.groups.get(field.type) === 'undefined') { - this.groups.set(field.type, new Map()); - } - this.groups.get(field.type)!.set(field.name, field); - }; - private removeByGroup = (field: IFieldType) => this.groups.get(field.type)!.delete(field.name); +export type CreateIndexPatternFieldList = ( + indexPattern: IndexPattern, + specs?: FieldSpec[], + shortDotsEnable?: boolean +) => IIndexPatternFieldList; - constructor(indexPattern: IndexPattern, specs: FieldSpec[] = [], shortDotsEnable = false) { - super(); - this.indexPattern = indexPattern; - this.shortDotsEnable = shortDotsEnable; +export const getIndexPatternFieldListCreator = ({ + fieldFormats, + toastNotifications, +}: FieldListDependencies): CreateIndexPatternFieldList => (...fieldListParams) => { + class FieldList extends Array implements IIndexPatternFieldList { + private byName: FieldMap = new Map(); + private groups: Map = new Map(); + private indexPattern: IndexPattern; + private shortDotsEnable: boolean; + private setByName = (field: Field) => this.byName.set(field.name, field); + private setByGroup = (field: Field) => { + if (typeof this.groups.get(field.type) === 'undefined') { + this.groups.set(field.type, new Map()); + } + this.groups.get(field.type)!.set(field.name, field); + }; + private removeByGroup = (field: IFieldType) => this.groups.get(field.type)!.delete(field.name); - specs.map(field => this.add(field)); - } + constructor(indexPattern: IndexPattern, specs: FieldSpec[] = [], shortDotsEnable = false) { + super(); + this.indexPattern = indexPattern; + this.shortDotsEnable = shortDotsEnable; - getByName = (name: Field['name']) => this.byName.get(name); - getByType = (type: Field['type']) => [...(this.groups.get(type) || new Map()).values()]; - add = (field: FieldSpec) => { - const newField = new Field(this.indexPattern, field, this.shortDotsEnable); - this.push(newField); - this.setByName(newField); - this.setByGroup(newField); - }; + specs.map(field => this.add(field)); + } - remove = (field: IFieldType) => { - this.removeByGroup(field); - this.byName.delete(field.name); + getByName = (name: Field['name']) => this.byName.get(name); + getByType = (type: Field['type']) => [...(this.groups.get(type) || new Map()).values()]; + add = (field: FieldSpec) => { + const newField = new Field(this.indexPattern, field, this.shortDotsEnable, { + fieldFormats, + toastNotifications, + }); + this.push(newField); + this.setByName(newField); + this.setByGroup(newField); + }; - const fieldIndex = findIndex(this, { name: field.name }); - this.splice(fieldIndex, 1); - }; + remove = (field: IFieldType) => { + this.removeByGroup(field); + this.byName.delete(field.name); - update = (field: FieldSpec) => { - const newField = new Field(this.indexPattern, field, this.shortDotsEnable); - const index = this.findIndex(f => f.name === newField.name); - this.splice(index, 1, newField); - this.setByName(newField); - this.removeByGroup(newField); - this.setByGroup(newField); - }; -} + const fieldIndex = findIndex(this, { name: field.name }); + this.splice(fieldIndex, 1); + }; + + update = (field: FieldSpec) => { + const newField = new Field(this.indexPattern, field, this.shortDotsEnable, { + fieldFormats, + toastNotifications, + }); + const index = this.findIndex(f => f.name === newField.name); + this.splice(index, 1, newField); + this.setByName(newField); + this.removeByGroup(newField); + this.setByGroup(newField); + }; + } + + return new FieldList(...fieldListParams); +}; diff --git a/src/plugins/data/public/index_patterns/index.ts b/src/plugins/data/public/index_patterns/index.ts index dcf799184b01c4..e05db0e4d4cec0 100644 --- a/src/plugins/data/public/index_patterns/index.ts +++ b/src/plugins/data/public/index_patterns/index.ts @@ -29,7 +29,7 @@ export { export { getRoutes } from './utils'; export { flattenHitWrapper, formatHitProvider } from './index_patterns'; -export { Field, FieldList } from './fields'; +export { getIndexPatternFieldListCreator, Field, IIndexPatternFieldList } from './fields'; // TODO: figure out how to replace IndexPatterns in get_inner_angular. export { diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.ts b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.ts index 768029136879da..f39be78433710f 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.ts @@ -32,7 +32,7 @@ import { ES_FIELD_TYPES, KBN_FIELD_TYPES, IIndexPattern, IFieldType } from '../. import { findByTitle, getRoutes } from '../utils'; import { IndexPatternMissingIndices } from '../lib'; -import { Field, FieldList, IFieldList } from '../fields'; +import { Field, IIndexPatternFieldList, getIndexPatternFieldListCreator } from '../fields'; import { createFieldsFetcher } from './_fields_fetcher'; import { formatHitProvider } from './format_hit'; import { flattenHitWrapper } from './flatten_hit'; @@ -51,7 +51,7 @@ export class IndexPattern implements IIndexPattern { public type?: string; public fieldFormatMap: any; public typeMeta?: TypeMeta; - public fields: IFieldList; + public fields: IIndexPatternFieldList; public timeFieldName: string | undefined; public formatHit: any; public formatField: any; @@ -106,7 +106,12 @@ export class IndexPattern implements IIndexPattern { this.shortDotsEnable = this.getConfig('shortDots:enable'); this.metaFields = this.getConfig('metaFields'); - this.fields = new FieldList(this, [], this.shortDotsEnable); + this.createFieldList = getIndexPatternFieldListCreator({ + fieldFormats: getFieldFormats(), + toastNotifications: getNotifications().toasts, + }); + + this.fields = this.createFieldList(this, [], this.shortDotsEnable); this.fieldsFetcher = createFieldsFetcher(this, apiClient, this.getConfig('metaFields')); this.flattenHit = flattenHitWrapper(this, this.getConfig('metaFields')); this.formatHit = formatHitProvider( @@ -131,7 +136,7 @@ export class IndexPattern implements IIndexPattern { private initFields(input?: any) { const newValue = input || this.fields; - this.fields = new FieldList(this, newValue, this.shortDotsEnable); + this.fields = this.createFieldList(this, newValue, this.shortDotsEnable); } private isFieldRefreshRequired(): boolean { @@ -281,7 +286,11 @@ export class IndexPattern implements IIndexPattern { filterable: true, searchable: true, }, - false + false, + { + fieldFormats: getFieldFormats(), + toastNotifications: getNotifications().toasts, + } ) ); diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_patterns.test.ts b/src/plugins/data/public/index_patterns/index_patterns/index_patterns.test.ts index cf1f83d0e28cb8..fc0be270e9c506 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_patterns.test.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_patterns.test.ts @@ -19,12 +19,13 @@ // eslint-disable-next-line max-classes-per-file import { IndexPatternsService } from './index_patterns'; -import { - SavedObjectsClientContract, - HttpSetup, - SavedObjectsFindResponsePublic, - CoreStart, -} from 'kibana/public'; +import { SavedObjectsClientContract, SavedObjectsFindResponsePublic } from 'kibana/public'; +import { coreMock, httpServiceMock } from '../../../../../core/public/mocks'; +import { fieldFormatsServiceMock } from '../../field_formats/mocks'; + +const core = coreMock.createStart(); +const http = httpServiceMock.createStartContract(); +const fieldFormats = fieldFormatsServiceMock.createStartContract(); jest.mock('./index_pattern', () => { class IndexPattern { @@ -61,10 +62,7 @@ describe('IndexPatterns', () => { }) as Promise> ); - const core = {} as CoreStart; - const http = {} as HttpSetup; - - indexPatterns = new IndexPatternsService(core, savedObjectsClient, http); + indexPatterns = new IndexPatternsService(core, savedObjectsClient, http, fieldFormats); }); test('does cache gets for the same id', async () => { diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_patterns.ts b/src/plugins/data/public/index_patterns/index_patterns/index_patterns.ts index 73d5aeaf30710f..515f2e7cf95eec 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_patterns.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_patterns.ts @@ -32,6 +32,13 @@ import { createEnsureDefaultIndexPattern, EnsureDefaultIndexPattern, } from './ensure_default_index_pattern'; +import { + getIndexPatternFieldListCreator, + CreateIndexPatternFieldList, + Field, + FieldSpec, +} from '../fields'; +import { FieldFormatsStart } from '../../field_formats'; const indexPatternCache = createIndexPatternCache(); @@ -47,12 +54,33 @@ export class IndexPatternsService { private savedObjectsCache?: Array> | null; private apiClient: IndexPatternsApiClient; ensureDefaultIndexPattern: EnsureDefaultIndexPattern; - - constructor(core: CoreStart, savedObjectsClient: SavedObjectsClientContract, http: HttpStart) { + createFieldList: CreateIndexPatternFieldList; + createField: ( + indexPattern: IndexPattern, + spec: FieldSpec | Field, + shortDotsEnable: boolean + ) => Field; + + constructor( + core: CoreStart, + savedObjectsClient: SavedObjectsClientContract, + http: HttpStart, + fieldFormats: FieldFormatsStart + ) { this.apiClient = new IndexPatternsApiClient(http); this.config = core.uiSettings; this.savedObjectsClient = savedObjectsClient; this.ensureDefaultIndexPattern = createEnsureDefaultIndexPattern(core); + this.createFieldList = getIndexPatternFieldListCreator({ + fieldFormats, + toastNotifications: core.notifications.toasts, + }); + this.createField = (indexPattern, spec, shortDotsEnable) => { + return new Field(indexPattern, spec, shortDotsEnable, { + fieldFormats, + toastNotifications: core.notifications.toasts, + }); + }; } private async refreshSavedObjectsCache() { diff --git a/src/plugins/data/public/mocks.ts b/src/plugins/data/public/mocks.ts index ba1df89c413587..7307c93139d592 100644 --- a/src/plugins/data/public/mocks.ts +++ b/src/plugins/data/public/mocks.ts @@ -57,6 +57,8 @@ const createStartContract = (): Start => { SearchBar: jest.fn(), }, indexPatterns: ({ + createField: jest.fn(() => {}), + createFieldList: jest.fn(() => []), ensureDefaultIndexPattern: jest.fn(), make: () => ({ fieldsFetcher: { diff --git a/src/plugins/data/public/plugin.ts b/src/plugins/data/public/plugin.ts index d822e96d0a129f..08796216db1e06 100644 --- a/src/plugins/data/public/plugin.ts +++ b/src/plugins/data/public/plugin.ts @@ -160,7 +160,7 @@ export class DataPublicPlugin implements Plugin; - // (undocumented) - count?: number; - // (undocumented) - displayName?: string; - // (undocumented) - esTypes?: string[]; - // (undocumented) - filterable?: boolean; - // (undocumented) - format: any; - // (undocumented) - indexPattern?: IndexPattern; - // (undocumented) - lang?: string; - // (undocumented) - name: string; - // (undocumented) - script?: string; - // (undocumented) - scripted?: boolean; - // (undocumented) - searchable?: boolean; - // (undocumented) - sortable?: boolean; - // (undocumented) - subType?: IFieldSubType; - // (undocumented) - type: string; - // (undocumented) - visualizable?: boolean; -} - -export { Field } - -export { Field as IndexPatternField } - // Warning: (ae-missing-release-tag) "FieldFormat" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -658,6 +610,13 @@ export function getDefaultQuery(language?: QueryLanguage): { // @public (undocumented) export function getEsPreference(uiSettings: IUiSettingsClient_2, sessionId?: string): any; +// Warning: (ae-forgotten-export) The symbol "FieldListDependencies" needs to be exported by the entry point index.d.ts +// Warning: (ae-forgotten-export) The symbol "CreateIndexPatternFieldList" needs to be exported by the entry point index.d.ts +// Warning: (ae-missing-release-tag) "getIndexPatternFieldListCreator" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export const getIndexPatternFieldListCreator: ({ fieldFormats, toastNotifications, }: FieldListDependencies) => CreateIndexPatternFieldList; + // Warning: (ae-missing-release-tag) "getKbnTypeNames" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public @@ -829,6 +788,24 @@ export interface IIndexPattern { type?: string; } +// Warning: (ae-missing-release-tag) "IIndexPatternFieldList" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface IIndexPatternFieldList extends Array { + // Warning: (ae-forgotten-export) The symbol "FieldSpec" needs to be exported by the entry point index.d.ts + // + // (undocumented) + add(field: FieldSpec): void; + // (undocumented) + getByName(name: IndexPatternField['name']): IndexPatternField | undefined; + // (undocumented) + getByType(type: IndexPatternField['type']): IndexPatternField[]; + // (undocumented) + remove(field: IFieldType): void; + // (undocumented) + update(field: FieldSpec): void; +} + // Warning: (ae-missing-release-tag) "IKibanaSearchRequest" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) @@ -870,10 +847,8 @@ export class IndexPattern implements IIndexPattern { _fetchFields(): Promise; // (undocumented) fieldFormatMap: any; - // Warning: (ae-forgotten-export) The symbol "IFieldList" needs to be exported by the entry point index.d.ts - // // (undocumented) - fields: IFieldList; + fields: IIndexPatternFieldList; // (undocumented) fieldsFetcher: any; // (undocumented) @@ -901,17 +876,17 @@ export class IndexPattern implements IIndexPattern { }[]; }; // (undocumented) - getFieldByName(name: string): Field | void; + getFieldByName(name: string): IndexPatternField | void; // (undocumented) - getNonScriptedFields(): Field[]; + getNonScriptedFields(): IndexPatternField[]; // (undocumented) - getScriptedFields(): Field[]; + getScriptedFields(): IndexPatternField[]; // (undocumented) getSourceFiltering(): { excludes: any[]; }; // (undocumented) - getTimeField(): Field | undefined; + getTimeField(): IndexPatternField | undefined; // (undocumented) id?: string; // (undocumented) @@ -988,21 +963,48 @@ export interface IndexPatternAttributes { typeMeta: string; } -// Warning: (ae-missing-release-tag) "FieldList" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// Warning: (ae-missing-release-tag) "Field" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) -export class IndexPatternFieldList extends Array implements IFieldList { - constructor(indexPattern: IndexPattern, specs?: FieldSpec[], shortDotsEnable?: boolean); +export class IndexPatternField implements IFieldType { + // (undocumented) + $$spec: FieldSpec; + // Warning: (ae-forgotten-export) The symbol "FieldDependencies" needs to be exported by the entry point index.d.ts + constructor(indexPattern: IndexPattern, spec: FieldSpec | IndexPatternField, shortDotsEnable: boolean, { fieldFormats, toastNotifications }: FieldDependencies); + // (undocumented) + aggregatable?: boolean; + // (undocumented) + conflictDescriptions?: Record; + // (undocumented) + count?: number; // (undocumented) - add: (field: Record) => void; + displayName?: string; + // (undocumented) + esTypes?: string[]; + // (undocumented) + filterable?: boolean; + // (undocumented) + format: any; + // (undocumented) + indexPattern?: IndexPattern; // (undocumented) - getByName: (name: string) => Field | undefined; + lang?: string; // (undocumented) - getByType: (type: string) => any[]; + name: string; // (undocumented) - remove: (field: IFieldType) => void; + script?: string; // (undocumented) - update: (field: Record) => void; + scripted?: boolean; + // (undocumented) + searchable?: boolean; + // (undocumented) + sortable?: boolean; + // (undocumented) + subType?: IFieldSubType; + // (undocumented) + type: string; + // (undocumented) + visualizable?: boolean; } // Warning: (ae-missing-release-tag) "indexPatterns" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -1352,7 +1354,7 @@ export interface QueryState { // Warning: (ae-missing-release-tag) "QueryStringInput" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) -export const QueryStringInput: React.FC>; +export const QueryStringInput: React.FC>; // @public (undocumented) export type QuerySuggestion = QuerySuggestionBasic | QuerySuggestionField; @@ -1564,8 +1566,8 @@ export const search: { // Warning: (ae-missing-release-tag) "SearchBar" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) -export const SearchBar: React.ComponentClass, "query" | "isLoading" | "filters" | "indexPatterns" | "refreshInterval" | "screenTitle" | "dataTestSubj" | "customSubmitButton" | "showQueryBar" | "showQueryInput" | "showFilterBar" | "showDatePicker" | "showAutoRefreshOnly" | "isRefreshPaused" | "dateRangeFrom" | "dateRangeTo" | "showSaveQuery" | "savedQuery" | "onQueryChange" | "onQuerySubmit" | "onSaved" | "onSavedQueryUpdated" | "onClearSavedQuery" | "onRefresh" | "timeHistory" | "onFiltersUpdated" | "onRefreshChange">, any> & { - WrappedComponent: React.ComponentType & ReactIntl.InjectedIntlProps>; +export const SearchBar: React.ComponentClass, "query" | "isLoading" | "filters" | "indexPatterns" | "refreshInterval" | "customSubmitButton" | "screenTitle" | "dataTestSubj" | "showQueryBar" | "showQueryInput" | "showFilterBar" | "showDatePicker" | "showAutoRefreshOnly" | "isRefreshPaused" | "dateRangeFrom" | "dateRangeTo" | "showSaveQuery" | "savedQuery" | "onQueryChange" | "onQuerySubmit" | "onSaved" | "onSavedQueryUpdated" | "onClearSavedQuery" | "onRefresh" | "timeHistory" | "onFiltersUpdated" | "onRefreshChange">, any> & { + WrappedComponent: React.ComponentType & ReactIntl.InjectedIntlProps>; }; // Warning: (ae-forgotten-export) The symbol "SearchBarOwnProps" needs to be exported by the entry point index.d.ts diff --git a/src/plugins/data/public/search/aggs/agg_config.ts b/src/plugins/data/public/search/aggs/agg_config.ts index 973c69e3d4f5fa..86a2c3e0e82e40 100644 --- a/src/plugins/data/public/search/aggs/agg_config.ts +++ b/src/plugins/data/public/search/aggs/agg_config.ts @@ -19,7 +19,7 @@ import _ from 'lodash'; import { i18n } from '@kbn/i18n'; -import { Assign } from '@kbn/utility-types'; +import { Assign, Ensure } from '@kbn/utility-types'; import { ExpressionAstFunction, ExpressionAstArgument } from 'src/plugins/expressions/public'; import { IAggType } from './agg_type'; import { writeParams } from './agg_params'; @@ -31,17 +31,22 @@ import { FieldFormatsStart } from '../../field_formats'; type State = string | number | boolean | null | undefined | SerializableState; -interface SerializableState { +/** @internal **/ +export interface SerializableState { [key: string]: State | State[]; } -export interface AggConfigSerialized { - type: string; - enabled?: boolean; - id?: string; - params?: SerializableState; - schema?: string; -} +/** @internal **/ +export type AggConfigSerialized = Ensure< + { + type: string; + enabled?: boolean; + id?: string; + params?: SerializableState; + schema?: string; + }, + SerializableState +>; export interface AggConfigDependencies { fieldFormats: FieldFormatsStart; diff --git a/src/plugins/data/public/search/aggs/agg_types.ts b/src/plugins/data/public/search/aggs/agg_types.ts index da07f581c9274c..7c7d7609cc82f7 100644 --- a/src/plugins/data/public/search/aggs/agg_types.ts +++ b/src/plugins/data/public/search/aggs/agg_types.ts @@ -105,6 +105,29 @@ export const getAggTypes = ({ ], }); +/** Buckets: **/ +import { aggFilter } from './buckets/filter_fn'; +import { aggFilters } from './buckets/filters_fn'; +import { aggSignificantTerms } from './buckets/significant_terms_fn'; +import { aggIpRange } from './buckets/ip_range_fn'; +import { aggDateRange } from './buckets/date_range_fn'; +import { aggRange } from './buckets/range_fn'; +import { aggGeoTile } from './buckets/geo_tile_fn'; +import { aggGeoHash } from './buckets/geo_hash_fn'; +import { aggHistogram } from './buckets/histogram_fn'; +import { aggDateHistogram } from './buckets/date_histogram_fn'; import { aggTerms } from './buckets/terms_fn'; -export const getAggTypesFunctions = () => [aggTerms]; +export const getAggTypesFunctions = () => [ + aggFilter, + aggFilters, + aggSignificantTerms, + aggIpRange, + aggDateRange, + aggRange, + aggGeoTile, + aggGeoHash, + aggDateHistogram, + aggHistogram, + aggTerms, +]; diff --git a/src/plugins/data/public/search/aggs/buckets/date_histogram.ts b/src/plugins/data/public/search/aggs/buckets/date_histogram.ts index 3ecdc17cb57f3f..219bb5440c8dae 100644 --- a/src/plugins/data/public/search/aggs/buckets/date_histogram.ts +++ b/src/plugins/data/public/search/aggs/buckets/date_histogram.ts @@ -27,7 +27,7 @@ import { BucketAggType, IBucketAggConfig } from './bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; import { createFilterDateHistogram } from './create_filter/date_histogram'; import { intervalOptions } from './_interval_options'; -import { dateHistogramInterval } from '../../../../common'; +import { dateHistogramInterval, TimeRange } from '../../../../common'; import { writeParams } from '../agg_params'; import { isMetricAggType } from '../metrics/metric_agg_type'; @@ -35,6 +35,8 @@ import { FIELD_FORMAT_IDS, KBN_FIELD_TYPES } from '../../../../common'; import { TimefilterContract } from '../../../query'; import { QuerySetup } from '../../../query/query_service'; import { GetInternalStartServicesFn } from '../../../types'; +import { BaseAggParams } from '../types'; +import { ExtendedBounds } from './lib/extended_bounds'; const detectedTimezone = moment.tz.guess(); const tzOffset = moment().format('Z'); @@ -67,6 +69,19 @@ export function isDateHistogramBucketAggConfig(agg: any): agg is IBucketDateHist return Boolean(agg.buckets); } +export interface AggParamsDateHistogram extends BaseAggParams { + field?: string; + timeRange?: TimeRange; + useNormalizedEsInterval?: boolean; + scaleMetricValues?: boolean; + interval?: string; + time_zone?: string; + drop_partials?: boolean; + format?: string; + min_doc_count?: number; + extended_bounds?: ExtendedBounds; +} + export const getDateHistogramBucketAgg = ({ uiSettings, query, @@ -89,6 +104,7 @@ export const getDateHistogramBucketAgg = ({ } const field = agg.getFieldDisplayName(); + return i18n.translate('data.search.aggs.buckets.dateHistogramLabel', { defaultMessage: '{fieldName} per {intervalDescription}', values: { diff --git a/src/plugins/data/public/search/aggs/buckets/date_histogram_fn.test.ts b/src/plugins/data/public/search/aggs/buckets/date_histogram_fn.test.ts new file mode 100644 index 00000000000000..bd3c4f8dd58cfd --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/date_histogram_fn.test.ts @@ -0,0 +1,120 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { functionWrapper } from '../test_helpers'; +import { aggDateHistogram } from './date_histogram_fn'; + +describe('agg_expression_functions', () => { + describe('aggDateHistogram', () => { + const fn = functionWrapper(aggDateHistogram()); + + test('fills in defaults when only required args are provided', () => { + const actual = fn({}); + expect(actual).toMatchInlineSnapshot(` + Object { + "type": "agg_type", + "value": Object { + "enabled": true, + "id": undefined, + "params": Object { + "customLabel": undefined, + "drop_partials": undefined, + "extended_bounds": undefined, + "field": undefined, + "format": undefined, + "interval": undefined, + "json": undefined, + "min_doc_count": undefined, + "scaleMetricValues": undefined, + "timeRange": undefined, + "time_zone": undefined, + "useNormalizedEsInterval": undefined, + }, + "schema": undefined, + "type": "date_histogram", + }, + } + `); + }); + + test('includes optional params when they are provided', () => { + const actual = fn({ + field: 'field', + timeRange: JSON.stringify({ + from: 'from', + to: 'to', + }), + useNormalizedEsInterval: true, + scaleMetricValues: true, + interval: 'interval', + time_zone: 'time_zone', + drop_partials: false, + format: 'format', + min_doc_count: 1, + extended_bounds: JSON.stringify({ + min: 1, + max: 2, + }), + }); + + expect(actual.value).toMatchInlineSnapshot(` + Object { + "enabled": true, + "id": undefined, + "params": Object { + "customLabel": undefined, + "drop_partials": false, + "extended_bounds": Object { + "max": 2, + "min": 1, + }, + "field": "field", + "format": "format", + "interval": "interval", + "json": undefined, + "min_doc_count": 1, + "scaleMetricValues": true, + "timeRange": Object { + "from": "from", + "to": "to", + }, + "time_zone": "time_zone", + "useNormalizedEsInterval": true, + }, + "schema": undefined, + "type": "date_histogram", + } + `); + }); + + test('correctly parses json string argument', () => { + const actual = fn({ + json: '{ "foo": true }', + }); + + expect(actual.value.params.json).toEqual({ foo: true }); + + expect(() => { + fn({ + json: '/// intentionally malformed json ///', + }); + }).toThrowErrorMatchingInlineSnapshot(`"Unable to parse json argument string"`); + }); + }); +}); diff --git a/src/plugins/data/public/search/aggs/buckets/date_histogram_fn.ts b/src/plugins/data/public/search/aggs/buckets/date_histogram_fn.ts new file mode 100644 index 00000000000000..033b44da0880f6 --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/date_histogram_fn.ts @@ -0,0 +1,155 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; +import { Assign } from '@kbn/utility-types'; +import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; +import { getParsedValue } from '../utils/get_parsed_value'; + +const fnName = 'aggDateHistogram'; + +type Input = any; +type AggArgs = AggExpressionFunctionArgs; + +type Arguments = Assign; + +type Output = AggExpressionType; +type FunctionDefinition = ExpressionFunctionDefinition; + +export const aggDateHistogram = (): FunctionDefinition => ({ + name: fnName, + help: i18n.translate('data.search.aggs.function.buckets.dateHistogram.help', { + defaultMessage: 'Generates a serialized agg config for a Histogram agg', + }), + type: 'agg_type', + args: { + id: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateHistogram.id.help', { + defaultMessage: 'ID for this aggregation', + }), + }, + enabled: { + types: ['boolean'], + default: true, + help: i18n.translate('data.search.aggs.buckets.dateHistogram.enabled.help', { + defaultMessage: 'Specifies whether this aggregation should be enabled', + }), + }, + schema: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateHistogram.schema.help', { + defaultMessage: 'Schema to use for this aggregation', + }), + }, + field: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateHistogram.field.help', { + defaultMessage: 'Field to use for this aggregation', + }), + }, + useNormalizedEsInterval: { + types: ['boolean'], + help: i18n.translate('data.search.aggs.buckets.dateHistogram.useNormalizedEsInterval.help', { + defaultMessage: 'Specifies whether to use useNormalizedEsInterval for this aggregation', + }), + }, + time_zone: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateHistogram.timeZone.help', { + defaultMessage: 'Time zone to use for this aggregation', + }), + }, + format: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateHistogram.format.help', { + defaultMessage: 'Format to use for this aggregation', + }), + }, + scaleMetricValues: { + types: ['boolean'], + help: i18n.translate('data.search.aggs.buckets.dateHistogram.scaleMetricValues.help', { + defaultMessage: 'Specifies whether to use scaleMetricValues for this aggregation', + }), + }, + interval: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateHistogram.interval.help', { + defaultMessage: 'Interval to use for this aggregation', + }), + }, + timeRange: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateHistogram.timeRange.help', { + defaultMessage: 'Time Range to use for this aggregation', + }), + }, + min_doc_count: { + types: ['number'], + help: i18n.translate('data.search.aggs.buckets.dateHistogram.minDocCount.help', { + defaultMessage: 'Minimum document count to use for this aggregation', + }), + }, + drop_partials: { + types: ['boolean'], + help: i18n.translate('data.search.aggs.buckets.dateHistogram.dropPartials.help', { + defaultMessage: 'Specifies whether to use drop_partials for this aggregation', + }), + }, + extended_bounds: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateHistogram.extendedBounds.help', { + defaultMessage: + 'With extended_bounds setting, you now can "force" the histogram aggregation to start building buckets on a specific min value and also keep on building buckets up to a max value ', + }), + }, + json: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateHistogram.json.help', { + defaultMessage: 'Advanced json to include when the agg is sent to Elasticsearch', + }), + }, + customLabel: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateHistogram.customLabel.help', { + defaultMessage: 'Represents a custom label for this aggregation', + }), + }, + }, + fn: (input, args) => { + const { id, enabled, schema, ...rest } = args; + + return { + type: 'agg_type', + value: { + id, + enabled, + schema, + type: BUCKET_TYPES.DATE_HISTOGRAM, + params: { + ...rest, + timeRange: getParsedValue(args, 'timeRange'), + extended_bounds: getParsedValue(args, 'extended_bounds'), + json: getParsedValue(args, 'json'), + }, + }, + }; + }, +}); diff --git a/src/plugins/data/public/search/aggs/buckets/date_range.ts b/src/plugins/data/public/search/aggs/buckets/date_range.ts index 07d927e64a943d..504958854cad4d 100644 --- a/src/plugins/data/public/search/aggs/buckets/date_range.ts +++ b/src/plugins/data/public/search/aggs/buckets/date_range.ts @@ -29,6 +29,7 @@ import { convertDateRangeToString, DateRangeKey } from './lib/date_range'; import { KBN_FIELD_TYPES, FieldFormat, TEXT_CONTEXT_TYPE } from '../../../../common'; import { GetInternalStartServicesFn } from '../../../types'; +import { BaseAggParams } from '../types'; const dateRangeTitle = i18n.translate('data.search.aggs.buckets.dateRangeTitle', { defaultMessage: 'Date Range', @@ -39,6 +40,12 @@ export interface DateRangeBucketAggDependencies { getInternalStartServices: GetInternalStartServicesFn; } +export interface AggParamsDateRange extends BaseAggParams { + field?: string; + ranges?: DateRangeKey[]; + time_zone?: string; +} + export const getDateRangeBucketAgg = ({ uiSettings, getInternalStartServices, diff --git a/src/plugins/data/public/search/aggs/buckets/date_range_fn.test.ts b/src/plugins/data/public/search/aggs/buckets/date_range_fn.test.ts new file mode 100644 index 00000000000000..93bb791874e677 --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/date_range_fn.test.ts @@ -0,0 +1,101 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { functionWrapper } from '../test_helpers'; +import { aggDateRange } from './date_range_fn'; + +describe('agg_expression_functions', () => { + describe('aggDateRange', () => { + const fn = functionWrapper(aggDateRange()); + + test('fills in defaults when only required args are provided', () => { + const actual = fn({}); + expect(actual).toMatchInlineSnapshot(` + Object { + "type": "agg_type", + "value": Object { + "enabled": true, + "id": undefined, + "params": Object { + "customLabel": undefined, + "field": undefined, + "json": undefined, + "ranges": undefined, + "time_zone": undefined, + }, + "schema": undefined, + "type": "date_range", + }, + } + `); + }); + + test('includes optional params when they are provided', () => { + const actual = fn({ + field: 'date_field', + time_zone: 'UTC +3', + ranges: JSON.stringify([ + { from: 'now-1w/w', to: 'now' }, + { from: 1588163532470, to: 1588163532481 }, + ]), + }); + + expect(actual.value).toMatchInlineSnapshot(` + Object { + "enabled": true, + "id": undefined, + "params": Object { + "customLabel": undefined, + "field": "date_field", + "json": undefined, + "ranges": Array [ + Object { + "from": "now-1w/w", + "to": "now", + }, + Object { + "from": 1588163532470, + "to": 1588163532481, + }, + ], + "time_zone": "UTC +3", + }, + "schema": undefined, + "type": "date_range", + } + `); + }); + + test('correctly parses json string argument', () => { + const actual = fn({ + field: 'date_field', + json: '{ "foo": true }', + }); + + expect(actual.value.params.json).toEqual({ foo: true }); + + expect(() => { + fn({ + field: 'date_field', + json: '/// intentionally malformed json ///', + }); + }).toThrowErrorMatchingInlineSnapshot(`"Unable to parse json argument string"`); + }); + }); +}); diff --git a/src/plugins/data/public/search/aggs/buckets/date_range_fn.ts b/src/plugins/data/public/search/aggs/buckets/date_range_fn.ts new file mode 100644 index 00000000000000..1fe42ce63d8157 --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/date_range_fn.ts @@ -0,0 +1,111 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; +import { Assign } from '@kbn/utility-types'; +import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; +import { getParsedValue } from '../utils/get_parsed_value'; + +const fnName = 'aggDateRange'; + +type Input = any; +type AggArgs = AggExpressionFunctionArgs; + +type Arguments = Assign; + +type Output = AggExpressionType; +type FunctionDefinition = ExpressionFunctionDefinition; + +export const aggDateRange = (): FunctionDefinition => ({ + name: fnName, + help: i18n.translate('data.search.aggs.function.buckets.dateRange.help', { + defaultMessage: 'Generates a serialized agg config for a Date Range agg', + }), + type: 'agg_type', + args: { + id: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateRange.id.help', { + defaultMessage: 'ID for this aggregation', + }), + }, + enabled: { + types: ['boolean'], + default: true, + help: i18n.translate('data.search.aggs.buckets.dateRange.enabled.help', { + defaultMessage: 'Specifies whether this aggregation should be enabled', + }), + }, + schema: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateRange.schema.help', { + defaultMessage: 'Schema to use for this aggregation', + }), + }, + field: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateRange.field.help', { + defaultMessage: 'Field to use for this aggregation', + }), + }, + ranges: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateRange.ranges.help', { + defaultMessage: 'Serialized ranges to use for this aggregation.', + }), + }, + time_zone: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateRange.timeZone.help', { + defaultMessage: 'Time zone to use for this aggregation.', + }), + }, + json: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateRange.json.help', { + defaultMessage: 'Advanced json to include when the agg is sent to Elasticsearch', + }), + }, + customLabel: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.dateRange.customLabel.help', { + defaultMessage: 'Represents a custom label for this aggregation', + }), + }, + }, + fn: (input, args) => { + const { id, enabled, schema, ...rest } = args; + + return { + type: 'agg_type', + value: { + id, + enabled, + schema, + type: BUCKET_TYPES.DATE_RANGE, + params: { + ...rest, + json: getParsedValue(args, 'json'), + ranges: getParsedValue(args, 'ranges'), + }, + }, + }; + }, +}); diff --git a/src/plugins/data/public/search/aggs/buckets/filter.ts b/src/plugins/data/public/search/aggs/buckets/filter.ts index accbdf4dd783d9..69157edad4f680 100644 --- a/src/plugins/data/public/search/aggs/buckets/filter.ts +++ b/src/plugins/data/public/search/aggs/buckets/filter.ts @@ -21,6 +21,8 @@ import { i18n } from '@kbn/i18n'; import { BucketAggType } from './bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; import { GetInternalStartServicesFn } from '../../../types'; +import { GeoBoundingBox } from './lib/geo_point'; +import { BaseAggParams } from '../types'; const filterTitle = i18n.translate('data.search.aggs.buckets.filterTitle', { defaultMessage: 'Filter', @@ -30,6 +32,10 @@ export interface FilterBucketAggDependencies { getInternalStartServices: GetInternalStartServicesFn; } +export interface AggParamsFilter extends BaseAggParams { + geo_bounding_box?: GeoBoundingBox; +} + export const getFilterBucketAgg = ({ getInternalStartServices }: FilterBucketAggDependencies) => new BucketAggType( { diff --git a/src/plugins/data/public/search/aggs/buckets/filter_fn.test.ts b/src/plugins/data/public/search/aggs/buckets/filter_fn.test.ts new file mode 100644 index 00000000000000..c820a73b0a8944 --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/filter_fn.test.ts @@ -0,0 +1,85 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { functionWrapper } from '../test_helpers'; +import { aggFilter } from './filter_fn'; + +describe('agg_expression_functions', () => { + describe('aggFilter', () => { + const fn = functionWrapper(aggFilter()); + + test('fills in defaults when only required args are provided', () => { + const actual = fn({}); + expect(actual).toMatchInlineSnapshot(` + Object { + "type": "agg_type", + "value": Object { + "enabled": true, + "id": undefined, + "params": Object { + "customLabel": undefined, + "geo_bounding_box": undefined, + "json": undefined, + }, + "schema": undefined, + "type": "filter", + }, + } + `); + }); + + test('includes optional params when they are provided', () => { + const actual = fn({ + geo_bounding_box: JSON.stringify({ + wkt: 'BBOX (-74.1, -71.12, 40.73, 40.01)', + }), + }); + + expect(actual.value).toMatchInlineSnapshot(` + Object { + "enabled": true, + "id": undefined, + "params": Object { + "customLabel": undefined, + "geo_bounding_box": Object { + "wkt": "BBOX (-74.1, -71.12, 40.73, 40.01)", + }, + "json": undefined, + }, + "schema": undefined, + "type": "filter", + } + `); + }); + + test('correctly parses json string argument', () => { + const actual = fn({ + json: '{ "foo": true }', + }); + + expect(actual.value.params.json).toEqual({ foo: true }); + + expect(() => { + fn({ + json: '/// intentionally malformed json ///', + }); + }).toThrowErrorMatchingInlineSnapshot(`"Unable to parse json argument string"`); + }); + }); +}); diff --git a/src/plugins/data/public/search/aggs/buckets/filter_fn.ts b/src/plugins/data/public/search/aggs/buckets/filter_fn.ts new file mode 100644 index 00000000000000..4a7180fc86c714 --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/filter_fn.ts @@ -0,0 +1,99 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; +import { Assign } from '@kbn/utility-types'; +import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; +import { getParsedValue } from '../utils/get_parsed_value'; + +const fnName = 'aggFilter'; + +type Input = any; +type AggArgs = AggExpressionFunctionArgs; + +type Arguments = Assign; + +type Output = AggExpressionType; +type FunctionDefinition = ExpressionFunctionDefinition; + +export const aggFilter = (): FunctionDefinition => ({ + name: fnName, + help: i18n.translate('data.search.aggs.function.buckets.filter.help', { + defaultMessage: 'Generates a serialized agg config for a Filter agg', + }), + type: 'agg_type', + args: { + id: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.filter.id.help', { + defaultMessage: 'ID for this aggregation', + }), + }, + enabled: { + types: ['boolean'], + default: true, + help: i18n.translate('data.search.aggs.buckets.filter.enabled.help', { + defaultMessage: 'Specifies whether this aggregation should be enabled', + }), + }, + schema: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.filter.schema.help', { + defaultMessage: 'Schema to use for this aggregation', + }), + }, + geo_bounding_box: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.filter.geoBoundingBox.help', { + defaultMessage: 'Filter results based on a point location within a bounding box', + }), + }, + json: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.filter.json.help', { + defaultMessage: 'Advanced json to include when the agg is sent to Elasticsearch', + }), + }, + customLabel: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.filter.customLabel.help', { + defaultMessage: 'Represents a custom label for this aggregation', + }), + }, + }, + fn: (input, args) => { + const { id, enabled, schema, ...rest } = args; + + return { + type: 'agg_type', + value: { + id, + enabled, + schema, + type: BUCKET_TYPES.FILTER, + params: { + ...rest, + json: getParsedValue(args, 'json'), + geo_bounding_box: getParsedValue(args, 'geo_bounding_box'), + }, + }, + }; + }, +}); diff --git a/src/plugins/data/public/search/aggs/buckets/filters.ts b/src/plugins/data/public/search/aggs/buckets/filters.ts index fe013928bba65a..8654645d46a9b1 100644 --- a/src/plugins/data/public/search/aggs/buckets/filters.ts +++ b/src/plugins/data/public/search/aggs/buckets/filters.ts @@ -29,6 +29,7 @@ import { Storage } from '../../../../../../plugins/kibana_utils/public'; import { getEsQueryConfig, buildEsQuery, Query } from '../../../../common'; import { getQueryLog } from '../../../query'; import { GetInternalStartServicesFn } from '../../../types'; +import { BaseAggParams } from '../types'; const filtersTitle = i18n.translate('data.search.aggs.buckets.filtersTitle', { defaultMessage: 'Filters', @@ -47,6 +48,13 @@ export interface FiltersBucketAggDependencies { getInternalStartServices: GetInternalStartServicesFn; } +export interface AggParamsFilters extends Omit { + filters?: Array<{ + input: Query; + label: string; + }>; +} + export const getFiltersBucketAgg = ({ uiSettings, getInternalStartServices, diff --git a/src/plugins/data/public/search/aggs/buckets/filters_fn.test.ts b/src/plugins/data/public/search/aggs/buckets/filters_fn.test.ts new file mode 100644 index 00000000000000..99c4f7d8c2b659 --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/filters_fn.test.ts @@ -0,0 +1,91 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { functionWrapper } from '../test_helpers'; +import { aggFilters } from './filters_fn'; + +describe('agg_expression_functions', () => { + describe('aggFilters', () => { + const fn = functionWrapper(aggFilters()); + + test('fills in defaults when only required args are provided', () => { + const actual = fn({}); + expect(actual).toMatchInlineSnapshot(` + Object { + "type": "agg_type", + "value": Object { + "enabled": true, + "id": undefined, + "params": Object { + "filters": undefined, + "json": undefined, + }, + "schema": undefined, + "type": "filters", + }, + } + `); + }); + + test('includes optional params when they are provided', () => { + const actual = fn({ + filters: JSON.stringify([ + { + query: 'query', + language: 'lucene', + label: 'test', + }, + ]), + }); + + expect(actual.value).toMatchInlineSnapshot(` + Object { + "enabled": true, + "id": undefined, + "params": Object { + "filters": Array [ + Object { + "label": "test", + "language": "lucene", + "query": "query", + }, + ], + "json": undefined, + }, + "schema": undefined, + "type": "filters", + } + `); + }); + + test('correctly parses json string argument', () => { + const actual = fn({ + json: '{ "foo": true }', + }); + + expect(actual.value.params.json).toEqual({ foo: true }); + + expect(() => { + fn({ + json: '/// intentionally malformed json ///', + }); + }).toThrowErrorMatchingInlineSnapshot(`"Unable to parse json argument string"`); + }); + }); +}); diff --git a/src/plugins/data/public/search/aggs/buckets/filters_fn.ts b/src/plugins/data/public/search/aggs/buckets/filters_fn.ts new file mode 100644 index 00000000000000..6ffd5369d70876 --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/filters_fn.ts @@ -0,0 +1,93 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; +import { Assign } from '@kbn/utility-types'; +import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; +import { getParsedValue } from '../utils/get_parsed_value'; + +const fnName = 'aggFilters'; + +type Input = any; +type AggArgs = AggExpressionFunctionArgs; + +type Arguments = Assign; + +type Output = AggExpressionType; +type FunctionDefinition = ExpressionFunctionDefinition; + +export const aggFilters = (): FunctionDefinition => ({ + name: fnName, + help: i18n.translate('data.search.aggs.function.buckets.filters.help', { + defaultMessage: 'Generates a serialized agg config for a Filter agg', + }), + type: 'agg_type', + args: { + id: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.filters.id.help', { + defaultMessage: 'ID for this aggregation', + }), + }, + enabled: { + types: ['boolean'], + default: true, + help: i18n.translate('data.search.aggs.buckets.filters.enabled.help', { + defaultMessage: 'Specifies whether this aggregation should be enabled', + }), + }, + schema: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.filters.schema.help', { + defaultMessage: 'Schema to use for this aggregation', + }), + }, + filters: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.filters.filters.help', { + defaultMessage: 'Filters to use for this aggregation', + }), + }, + json: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.filters.json.help', { + defaultMessage: 'Advanced json to include when the agg is sent to Elasticsearch', + }), + }, + }, + fn: (input, args) => { + const { id, enabled, schema, ...rest } = args; + + return { + type: 'agg_type', + value: { + id, + enabled, + schema, + type: BUCKET_TYPES.FILTERS, + params: { + ...rest, + filters: getParsedValue(args, 'filters'), + json: getParsedValue(args, 'json'), + }, + }, + }; + }, +}); diff --git a/src/plugins/data/public/search/aggs/buckets/geo_hash.ts b/src/plugins/data/public/search/aggs/buckets/geo_hash.ts index eab10edad60f63..be339de5d7faea 100644 --- a/src/plugins/data/public/search/aggs/buckets/geo_hash.ts +++ b/src/plugins/data/public/search/aggs/buckets/geo_hash.ts @@ -22,6 +22,8 @@ import { BucketAggType, IBucketAggConfig } from './bucket_agg_type'; import { KBN_FIELD_TYPES } from '../../../../common'; import { BUCKET_TYPES } from './bucket_agg_types'; import { GetInternalStartServicesFn } from '../../../types'; +import { GeoBoundingBox } from './lib/geo_point'; +import { BaseAggParams } from '../types'; const defaultBoundingBox = { top_left: { lat: 1, lon: 1 }, @@ -38,6 +40,15 @@ export interface GeoHashBucketAggDependencies { getInternalStartServices: GetInternalStartServicesFn; } +export interface AggParamsGeoHash extends BaseAggParams { + field: string; + autoPrecision?: boolean; + precision?: number; + useGeocentroid?: boolean; + isFilteredByCollar?: boolean; + boundingBox?: GeoBoundingBox; +} + export const getGeoHashBucketAgg = ({ getInternalStartServices }: GeoHashBucketAggDependencies) => new BucketAggType( { diff --git a/src/plugins/data/public/search/aggs/buckets/geo_hash_fn.test.ts b/src/plugins/data/public/search/aggs/buckets/geo_hash_fn.test.ts new file mode 100644 index 00000000000000..07ab8e66f1defe --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/geo_hash_fn.test.ts @@ -0,0 +1,112 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { functionWrapper } from '../test_helpers'; +import { aggGeoHash } from './geo_hash_fn'; + +describe('agg_expression_functions', () => { + describe('aggGeoHash', () => { + const fn = functionWrapper(aggGeoHash()); + + test('fills in defaults when only required args are provided', () => { + const actual = fn({ + field: 'geo_field', + }); + expect(actual).toMatchInlineSnapshot(` + Object { + "type": "agg_type", + "value": Object { + "enabled": true, + "id": undefined, + "params": Object { + "autoPrecision": undefined, + "boundingBox": undefined, + "customLabel": undefined, + "field": "geo_field", + "isFilteredByCollar": undefined, + "json": undefined, + "precision": undefined, + "useGeocentroid": undefined, + }, + "schema": undefined, + "type": "geohash_grid", + }, + } + `); + }); + + test('includes optional params when they are provided', () => { + const actual = fn({ + field: 'geo_field', + autoPrecision: false, + precision: 10, + useGeocentroid: true, + isFilteredByCollar: false, + boundingBox: JSON.stringify({ + top_left: [-74.1, 40.73], + bottom_right: [-71.12, 40.01], + }), + }); + + expect(actual.value).toMatchInlineSnapshot(` + Object { + "enabled": true, + "id": undefined, + "params": Object { + "autoPrecision": false, + "boundingBox": Object { + "bottom_right": Array [ + -71.12, + 40.01, + ], + "top_left": Array [ + -74.1, + 40.73, + ], + }, + "customLabel": undefined, + "field": "geo_field", + "isFilteredByCollar": false, + "json": undefined, + "precision": 10, + "useGeocentroid": true, + }, + "schema": undefined, + "type": "geohash_grid", + } + `); + }); + + test('correctly parses json string argument', () => { + const actual = fn({ + field: 'geo_field', + json: '{ "foo": true }', + }); + + expect(actual.value.params.json).toEqual({ foo: true }); + + expect(() => { + fn({ + field: 'geo_field', + json: '/// intentionally malformed json ///', + }); + }).toThrowErrorMatchingInlineSnapshot(`"Unable to parse json argument string"`); + }); + }); +}); diff --git a/src/plugins/data/public/search/aggs/buckets/geo_hash_fn.ts b/src/plugins/data/public/search/aggs/buckets/geo_hash_fn.ts new file mode 100644 index 00000000000000..bbfa8575d486ce --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/geo_hash_fn.ts @@ -0,0 +1,129 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; +import { Assign } from '@kbn/utility-types'; +import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; +import { getParsedValue } from '../utils/get_parsed_value'; + +const fnName = 'aggGeoHash'; + +type Input = any; +type AggArgs = AggExpressionFunctionArgs; + +type Arguments = Assign; +type Output = AggExpressionType; +type FunctionDefinition = ExpressionFunctionDefinition; + +export const aggGeoHash = (): FunctionDefinition => ({ + name: fnName, + help: i18n.translate('data.search.aggs.function.buckets.geoHash.help', { + defaultMessage: 'Generates a serialized agg config for a Geo Hash agg', + }), + type: 'agg_type', + args: { + id: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.geoHash.id.help', { + defaultMessage: 'ID for this aggregation', + }), + }, + enabled: { + types: ['boolean'], + default: true, + help: i18n.translate('data.search.aggs.buckets.geoHash.enabled.help', { + defaultMessage: 'Specifies whether this aggregation should be enabled', + }), + }, + schema: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.geoHash.schema.help', { + defaultMessage: 'Schema to use for this aggregation', + }), + }, + field: { + types: ['string'], + required: true, + help: i18n.translate('data.search.aggs.buckets.geoHash.field.help', { + defaultMessage: 'Field to use for this aggregation', + }), + }, + useGeocentroid: { + types: ['boolean'], + help: i18n.translate('data.search.aggs.buckets.geoHash.useGeocentroid.help', { + defaultMessage: 'Specifies whether to use geocentroid for this aggregation', + }), + }, + autoPrecision: { + types: ['boolean'], + help: i18n.translate('data.search.aggs.buckets.geoHash.autoPrecision.help', { + defaultMessage: 'Specifies whether to use auto precision for this aggregation', + }), + }, + isFilteredByCollar: { + types: ['boolean'], + help: i18n.translate('data.search.aggs.buckets.geoHash.isFilteredByCollar.help', { + defaultMessage: 'Specifies whether to filter by collar', + }), + }, + boundingBox: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.geoHash.boundingBox.help', { + defaultMessage: 'Filter results based on a point location within a bounding box', + }), + }, + precision: { + types: ['number'], + help: i18n.translate('data.search.aggs.buckets.geoHash.precision.help', { + defaultMessage: 'Precision to use for this aggregation.', + }), + }, + json: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.geoHash.json.help', { + defaultMessage: 'Advanced json to include when the agg is sent to Elasticsearch', + }), + }, + customLabel: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.geoHash.customLabel.help', { + defaultMessage: 'Represents a custom label for this aggregation', + }), + }, + }, + fn: (input, args) => { + const { id, enabled, schema, ...rest } = args; + + return { + type: 'agg_type', + value: { + id, + enabled, + schema, + type: BUCKET_TYPES.GEOHASH_GRID, + params: { + ...rest, + boundingBox: getParsedValue(args, 'boundingBox'), + json: getParsedValue(args, 'json'), + }, + }, + }; + }, +}); diff --git a/src/plugins/data/public/search/aggs/buckets/geo_tile.ts b/src/plugins/data/public/search/aggs/buckets/geo_tile.ts index c981e8400f9a12..1212bba23a93aa 100644 --- a/src/plugins/data/public/search/aggs/buckets/geo_tile.ts +++ b/src/plugins/data/public/search/aggs/buckets/geo_tile.ts @@ -25,6 +25,7 @@ import { BUCKET_TYPES } from './bucket_agg_types'; import { KBN_FIELD_TYPES } from '../../../../common'; import { METRIC_TYPES } from '../metrics/metric_agg_types'; import { GetInternalStartServicesFn } from '../../../types'; +import { BaseAggParams } from '../types'; export interface GeoTitleBucketAggDependencies { getInternalStartServices: GetInternalStartServicesFn; @@ -34,6 +35,12 @@ const geotileGridTitle = i18n.translate('data.search.aggs.buckets.geotileGridTit defaultMessage: 'Geotile', }); +export interface AggParamsGeoTile extends BaseAggParams { + field: string; + useGeocentroid?: boolean; + precision?: number; +} + export const getGeoTitleBucketAgg = ({ getInternalStartServices }: GeoTitleBucketAggDependencies) => new BucketAggType( { diff --git a/src/plugins/data/public/search/aggs/buckets/geo_tile_fn.test.ts b/src/plugins/data/public/search/aggs/buckets/geo_tile_fn.test.ts new file mode 100644 index 00000000000000..bfaf47ede87343 --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/geo_tile_fn.test.ts @@ -0,0 +1,91 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { functionWrapper } from '../test_helpers'; +import { aggGeoTile } from './geo_tile_fn'; + +describe('agg_expression_functions', () => { + describe('aggGeoTile', () => { + const fn = functionWrapper(aggGeoTile()); + + test('fills in defaults when only required args are provided', () => { + const actual = fn({ + field: 'geo_field', + }); + expect(actual).toMatchInlineSnapshot(` + Object { + "type": "agg_type", + "value": Object { + "enabled": true, + "id": undefined, + "params": Object { + "customLabel": undefined, + "field": "geo_field", + "json": undefined, + "precision": undefined, + "useGeocentroid": undefined, + }, + "schema": undefined, + "type": "geotile_grid", + }, + } + `); + }); + + test('includes optional params when they are provided', () => { + const actual = fn({ + field: 'geo_field', + useGeocentroid: false, + precision: 10, + }); + + expect(actual.value).toMatchInlineSnapshot(` + Object { + "enabled": true, + "id": undefined, + "params": Object { + "customLabel": undefined, + "field": "geo_field", + "json": undefined, + "precision": 10, + "useGeocentroid": false, + }, + "schema": undefined, + "type": "geotile_grid", + } + `); + }); + + test('correctly parses json string argument', () => { + const actual = fn({ + field: 'geo_field', + json: '{ "foo": true }', + }); + + expect(actual.value.params.json).toEqual({ foo: true }); + + expect(() => { + fn({ + field: 'geo_field', + json: '/// intentionally malformed json ///', + }); + }).toThrowErrorMatchingInlineSnapshot(`"Unable to parse json argument string"`); + }); + }); +}); diff --git a/src/plugins/data/public/search/aggs/buckets/geo_tile_fn.ts b/src/plugins/data/public/search/aggs/buckets/geo_tile_fn.ts new file mode 100644 index 00000000000000..9c33ef45762af4 --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/geo_tile_fn.ts @@ -0,0 +1,108 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; +import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; +import { getParsedValue } from '../utils/get_parsed_value'; + +const fnName = 'aggGeoTile'; + +type Input = any; +type AggArgs = AggExpressionFunctionArgs; + +type Output = AggExpressionType; +type FunctionDefinition = ExpressionFunctionDefinition; + +export const aggGeoTile = (): FunctionDefinition => ({ + name: fnName, + help: i18n.translate('data.search.aggs.function.buckets.geoTile.help', { + defaultMessage: 'Generates a serialized agg config for a Geo Tile agg', + }), + type: 'agg_type', + args: { + id: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.geoTile.id.help', { + defaultMessage: 'ID for this aggregation', + }), + }, + enabled: { + types: ['boolean'], + default: true, + help: i18n.translate('data.search.aggs.buckets.geoTile.enabled.help', { + defaultMessage: 'Specifies whether this aggregation should be enabled', + }), + }, + schema: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.geoTile.schema.help', { + defaultMessage: 'Schema to use for this aggregation', + }), + }, + field: { + types: ['string'], + required: true, + help: i18n.translate('data.search.aggs.buckets.geoTile.field.help', { + defaultMessage: 'Field to use for this aggregation', + }), + }, + useGeocentroid: { + types: ['boolean'], + help: i18n.translate('data.search.aggs.buckets.geoTile.useGeocentroid.help', { + defaultMessage: 'Specifies whether to use geocentroid for this aggregation', + }), + }, + precision: { + types: ['number'], + help: i18n.translate('data.search.aggs.buckets.geoTile.precision.help', { + defaultMessage: 'Precision to use for this aggregation.', + }), + }, + json: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.geoTile.json.help', { + defaultMessage: 'Advanced json to include when the agg is sent to Elasticsearch', + }), + }, + customLabel: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.geoTile.customLabel.help', { + defaultMessage: 'Represents a custom label for this aggregation', + }), + }, + }, + fn: (input, args) => { + const { id, enabled, schema, ...rest } = args; + + return { + type: 'agg_type', + value: { + id, + enabled, + schema, + type: BUCKET_TYPES.GEOTILE_GRID, + params: { + ...rest, + json: getParsedValue(args, 'json'), + }, + }, + }; + }, +}); diff --git a/src/plugins/data/public/search/aggs/buckets/histogram.ts b/src/plugins/data/public/search/aggs/buckets/histogram.ts index f8e8720d24ea97..d04df4f8aac6ba 100644 --- a/src/plugins/data/public/search/aggs/buckets/histogram.ts +++ b/src/plugins/data/public/search/aggs/buckets/histogram.ts @@ -26,6 +26,8 @@ import { createFilterHistogram } from './create_filter/histogram'; import { BUCKET_TYPES } from './bucket_agg_types'; import { KBN_FIELD_TYPES } from '../../../../common'; import { GetInternalStartServicesFn } from '../../../types'; +import { BaseAggParams } from '../types'; +import { ExtendedBounds } from './lib/extended_bounds'; export interface AutoBounds { min: number; @@ -42,6 +44,15 @@ export interface IBucketHistogramAggConfig extends IBucketAggConfig { getAutoBounds: () => AutoBounds; } +export interface AggParamsHistogram extends BaseAggParams { + field: string; + interval: string; + intervalBase?: number; + min_doc_count?: boolean; + has_extended_bounds?: boolean; + extended_bounds?: ExtendedBounds; +} + export const getHistogramBucketAgg = ({ uiSettings, getInternalStartServices, diff --git a/src/plugins/data/public/search/aggs/buckets/histogram_fn.test.ts b/src/plugins/data/public/search/aggs/buckets/histogram_fn.test.ts new file mode 100644 index 00000000000000..34b6fa1a6dcd6d --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/histogram_fn.test.ts @@ -0,0 +1,109 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { functionWrapper } from '../test_helpers'; +import { aggHistogram } from './histogram_fn'; + +describe('agg_expression_functions', () => { + describe('aggHistogram', () => { + const fn = functionWrapper(aggHistogram()); + + test('fills in defaults when only required args are provided', () => { + const actual = fn({ + field: 'field', + interval: '10', + }); + expect(actual).toMatchInlineSnapshot(` + Object { + "type": "agg_type", + "value": Object { + "enabled": true, + "id": undefined, + "params": Object { + "customLabel": undefined, + "extended_bounds": undefined, + "field": "field", + "has_extended_bounds": undefined, + "interval": "10", + "intervalBase": undefined, + "json": undefined, + "min_doc_count": undefined, + }, + "schema": undefined, + "type": "histogram", + }, + } + `); + }); + + test('includes optional params when they are provided', () => { + const actual = fn({ + field: 'field', + interval: '10', + intervalBase: 1, + min_doc_count: false, + has_extended_bounds: false, + extended_bounds: JSON.stringify({ + min: 1, + max: 2, + }), + }); + + expect(actual.value).toMatchInlineSnapshot(` + Object { + "enabled": true, + "id": undefined, + "params": Object { + "customLabel": undefined, + "extended_bounds": Object { + "max": 2, + "min": 1, + }, + "field": "field", + "has_extended_bounds": false, + "interval": "10", + "intervalBase": 1, + "json": undefined, + "min_doc_count": false, + }, + "schema": undefined, + "type": "histogram", + } + `); + }); + + test('correctly parses json string argument', () => { + const actual = fn({ + field: 'field', + interval: '10', + json: '{ "foo": true }', + }); + + expect(actual.value.params.json).toEqual({ foo: true }); + + expect(() => { + fn({ + field: 'field', + interval: '10', + json: '/// intentionally malformed json ///', + }); + }).toThrowErrorMatchingInlineSnapshot(`"Unable to parse json argument string"`); + }); + }); +}); diff --git a/src/plugins/data/public/search/aggs/buckets/histogram_fn.ts b/src/plugins/data/public/search/aggs/buckets/histogram_fn.ts new file mode 100644 index 00000000000000..1e5a5a72c0ecbd --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/histogram_fn.ts @@ -0,0 +1,132 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; +import { Assign } from '@kbn/utility-types'; +import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; +import { getParsedValue } from '../utils/get_parsed_value'; + +const fnName = 'aggHistogram'; + +type Input = any; +type AggArgs = AggExpressionFunctionArgs; + +type Arguments = Assign; + +type Output = AggExpressionType; +type FunctionDefinition = ExpressionFunctionDefinition; + +export const aggHistogram = (): FunctionDefinition => ({ + name: fnName, + help: i18n.translate('data.search.aggs.function.buckets.histogram.help', { + defaultMessage: 'Generates a serialized agg config for a Histogram agg', + }), + type: 'agg_type', + args: { + id: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.histogram.id.help', { + defaultMessage: 'ID for this aggregation', + }), + }, + enabled: { + types: ['boolean'], + default: true, + help: i18n.translate('data.search.aggs.buckets.histogram.enabled.help', { + defaultMessage: 'Specifies whether this aggregation should be enabled', + }), + }, + schema: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.histogram.schema.help', { + defaultMessage: 'Schema to use for this aggregation', + }), + }, + field: { + types: ['string'], + required: true, + help: i18n.translate('data.search.aggs.buckets.histogram.field.help', { + defaultMessage: 'Field to use for this aggregation', + }), + }, + interval: { + types: ['string'], + required: true, + help: i18n.translate('data.search.aggs.buckets.histogram.interval.help', { + defaultMessage: 'Interval to use for this aggregation', + }), + }, + intervalBase: { + types: ['number'], + help: i18n.translate('data.search.aggs.buckets.histogram.intervalBase.help', { + defaultMessage: 'IntervalBase to use for this aggregation', + }), + }, + min_doc_count: { + types: ['boolean'], + help: i18n.translate('data.search.aggs.buckets.histogram.minDocCount.help', { + defaultMessage: 'Specifies whether to use min_doc_count for this aggregation', + }), + }, + has_extended_bounds: { + types: ['boolean'], + help: i18n.translate('data.search.aggs.buckets.histogram.hasExtendedBounds.help', { + defaultMessage: 'Specifies whether to use has_extended_bounds for this aggregation', + }), + }, + extended_bounds: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.histogram.extendedBounds.help', { + defaultMessage: + 'With extended_bounds setting, you now can "force" the histogram aggregation to start building buckets on a specific min value and also keep on building buckets up to a max value ', + }), + }, + json: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.histogram.json.help', { + defaultMessage: 'Advanced json to include when the agg is sent to Elasticsearch', + }), + }, + customLabel: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.histogram.customLabel.help', { + defaultMessage: 'Represents a custom label for this aggregation', + }), + }, + }, + fn: (input, args) => { + const { id, enabled, schema, ...rest } = args; + + return { + type: 'agg_type', + value: { + id, + enabled, + schema, + type: BUCKET_TYPES.HISTOGRAM, + params: { + ...rest, + extended_bounds: getParsedValue(args, 'extended_bounds'), + json: getParsedValue(args, 'json'), + }, + }, + }; + }, +}); diff --git a/src/plugins/data/public/search/aggs/buckets/index.ts b/src/plugins/data/public/search/aggs/buckets/index.ts index 3a402b1498a775..7036cc7785db7f 100644 --- a/src/plugins/data/public/search/aggs/buckets/index.ts +++ b/src/plugins/data/public/search/aggs/buckets/index.ts @@ -19,11 +19,18 @@ export * from './_interval_options'; export * from './bucket_agg_types'; +export * from './histogram'; export * from './date_histogram'; export * from './date_range'; +export * from './range'; +export * from './filter'; +export * from './filters'; +export * from './geo_tile'; +export * from './geo_hash'; export * from './ip_range'; export * from './lib/cidr_mask'; export * from './lib/date_range'; export * from './lib/ip_range'; export * from './migrate_include_exclude_format'; +export * from './significant_terms'; export * from './terms'; diff --git a/src/plugins/data/public/search/aggs/buckets/ip_range.ts b/src/plugins/data/public/search/aggs/buckets/ip_range.ts index bde347d6e673d1..029fd864154bea 100644 --- a/src/plugins/data/public/search/aggs/buckets/ip_range.ts +++ b/src/plugins/data/public/search/aggs/buckets/ip_range.ts @@ -23,18 +23,38 @@ import { BucketAggType } from './bucket_agg_type'; import { BUCKET_TYPES } from './bucket_agg_types'; import { createFilterIpRange } from './create_filter/ip_range'; -import { IpRangeKey, convertIPRangeToString } from './lib/ip_range'; +import { + convertIPRangeToString, + IpRangeKey, + RangeIpRangeAggKey, + CidrMaskIpRangeAggKey, +} from './lib/ip_range'; import { KBN_FIELD_TYPES, FieldFormat, TEXT_CONTEXT_TYPE } from '../../../../common'; import { GetInternalStartServicesFn } from '../../../types'; +import { BaseAggParams } from '../types'; const ipRangeTitle = i18n.translate('data.search.aggs.buckets.ipRangeTitle', { defaultMessage: 'IPv4 Range', }); +export enum IP_RANGE_TYPES { + FROM_TO = 'fromTo', + MASK = 'mask', +} + export interface IpRangeBucketAggDependencies { getInternalStartServices: GetInternalStartServicesFn; } +export interface AggParamsIpRange extends BaseAggParams { + field: string; + ipRangeType?: IP_RANGE_TYPES; + ranges?: Partial<{ + [IP_RANGE_TYPES.FROM_TO]: RangeIpRangeAggKey[]; + [IP_RANGE_TYPES.MASK]: CidrMaskIpRangeAggKey[]; + }>; +} + export const getIpRangeBucketAgg = ({ getInternalStartServices }: IpRangeBucketAggDependencies) => new BucketAggType( { @@ -42,7 +62,7 @@ export const getIpRangeBucketAgg = ({ getInternalStartServices }: IpRangeBucketA title: ipRangeTitle, createFilter: createFilterIpRange, getKey(bucket, key, agg): IpRangeKey { - if (agg.params.ipRangeType === 'mask') { + if (agg.params.ipRangeType === IP_RANGE_TYPES.MASK) { return { type: 'mask', mask: key }; } return { type: 'range', from: bucket.from, to: bucket.to }; @@ -74,7 +94,7 @@ export const getIpRangeBucketAgg = ({ getInternalStartServices }: IpRangeBucketA }, { name: 'ipRangeType', - default: 'fromTo', + default: IP_RANGE_TYPES.FROM_TO, write: noop, }, { @@ -90,7 +110,7 @@ export const getIpRangeBucketAgg = ({ getInternalStartServices }: IpRangeBucketA const ipRangeType = aggConfig.params.ipRangeType; let ranges = aggConfig.params.ranges[ipRangeType]; - if (ipRangeType === 'fromTo') { + if (ipRangeType === IP_RANGE_TYPES.FROM_TO) { ranges = map(ranges, (range: any) => omit(range, isNull)); } diff --git a/src/plugins/data/public/search/aggs/buckets/ip_range_fn.test.ts b/src/plugins/data/public/search/aggs/buckets/ip_range_fn.test.ts new file mode 100644 index 00000000000000..5940345b258904 --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/ip_range_fn.test.ts @@ -0,0 +1,102 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { functionWrapper } from '../test_helpers'; +import { IP_RANGE_TYPES } from './ip_range'; +import { aggIpRange } from './ip_range_fn'; + +describe('agg_expression_functions', () => { + describe('aggIpRange', () => { + const fn = functionWrapper(aggIpRange()); + + test('fills in defaults when only required args are provided', () => { + const actual = fn({ + field: 'ip_field', + }); + expect(actual).toMatchInlineSnapshot(` + Object { + "type": "agg_type", + "value": Object { + "enabled": true, + "id": undefined, + "params": Object { + "customLabel": undefined, + "field": "ip_field", + "ipRangeType": undefined, + "json": undefined, + "ranges": undefined, + }, + "schema": undefined, + "type": "ip_range", + }, + } + `); + }); + + test('includes optional params when they are provided', () => { + const actual = fn({ + field: 'ip_field', + ipRangeType: IP_RANGE_TYPES.MASK, + ranges: JSON.stringify({ + mask: [{ mask: '10.0.0.0/25' }], + }), + }); + + expect(actual.value).toMatchInlineSnapshot(` + Object { + "enabled": true, + "id": undefined, + "params": Object { + "customLabel": undefined, + "field": "ip_field", + "ipRangeType": "mask", + "json": undefined, + "ranges": Object { + "mask": Array [ + Object { + "mask": "10.0.0.0/25", + }, + ], + }, + }, + "schema": undefined, + "type": "ip_range", + } + `); + }); + + test('correctly parses json string argument', () => { + const actual = fn({ + field: 'ip_field', + ipRangeType: IP_RANGE_TYPES.MASK, + json: '{ "foo": true }', + }); + + expect(actual.value.params.json).toEqual({ foo: true }); + + expect(() => { + fn({ + field: 'ip_field', + ipRangeType: IP_RANGE_TYPES.FROM_TO, + json: '/// intentionally malformed json ///', + }); + }).toThrowErrorMatchingInlineSnapshot(`"Unable to parse json argument string"`); + }); + }); +}); diff --git a/src/plugins/data/public/search/aggs/buckets/ip_range_fn.ts b/src/plugins/data/public/search/aggs/buckets/ip_range_fn.ts new file mode 100644 index 00000000000000..554a8708d91642 --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/ip_range_fn.ts @@ -0,0 +1,114 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; +import { Assign } from '@kbn/utility-types'; +import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; +import { getParsedValue } from '../utils/get_parsed_value'; + +const fnName = 'aggIpRange'; + +type Input = any; +type AggArgs = AggExpressionFunctionArgs; + +type Arguments = Assign; + +type Output = AggExpressionType; +type FunctionDefinition = ExpressionFunctionDefinition; + +export const aggIpRange = (): FunctionDefinition => ({ + name: fnName, + help: i18n.translate('data.search.aggs.function.buckets.ipRange.help', { + defaultMessage: 'Generates a serialized agg config for a Ip Range agg', + }), + type: 'agg_type', + args: { + id: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.ipRange.id.help', { + defaultMessage: 'ID for this aggregation', + }), + }, + enabled: { + types: ['boolean'], + default: true, + help: i18n.translate('data.search.aggs.buckets.ipRange.enabled.help', { + defaultMessage: 'Specifies whether this aggregation should be enabled', + }), + }, + schema: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.ipRange.schema.help', { + defaultMessage: 'Schema to use for this aggregation', + }), + }, + field: { + types: ['string'], + required: true, + help: i18n.translate('data.search.aggs.buckets.ipRange.field.help', { + defaultMessage: 'Field to use for this aggregation', + }), + }, + ipRangeType: { + types: ['string'], + options: ['mask', 'fromTo'], + help: i18n.translate('data.search.aggs.buckets.ipRange.ipRangeType.help', { + defaultMessage: + 'IP range type to use for this aggregation. Takes one of the following values: mask, fromTo.', + }), + }, + ranges: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.ipRange.ranges.help', { + defaultMessage: 'Serialized ranges to use for this aggregation.', + }), + }, + json: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.ipRange.json.help', { + defaultMessage: 'Advanced json to include when the agg is sent to Elasticsearch', + }), + }, + customLabel: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.ipRange.customLabel.help', { + defaultMessage: 'Represents a custom label for this aggregation', + }), + }, + }, + fn: (input, args) => { + const { id, enabled, schema, ...rest } = args; + + return { + type: 'agg_type', + value: { + id, + enabled, + schema, + type: BUCKET_TYPES.IP_RANGE, + params: { + ...rest, + json: getParsedValue(args, 'json'), + ranges: getParsedValue(args, 'ranges'), + }, + }, + }; + }, +}); diff --git a/src/plugins/data/public/search/aggs/buckets/lib/date_range.ts b/src/plugins/data/public/search/aggs/buckets/lib/date_range.ts index 6eb9fe8414ec8f..d52bdff993a2b1 100644 --- a/src/plugins/data/public/search/aggs/buckets/lib/date_range.ts +++ b/src/plugins/data/public/search/aggs/buckets/lib/date_range.ts @@ -18,8 +18,8 @@ */ export interface DateRangeKey { - from: number; - to: number; + from: number | string; + to: number | string; } export function convertDateRangeToString({ from, to }: DateRangeKey, format: (val: any) => string) { diff --git a/src/plugins/discover/public/helpers/index.ts b/src/plugins/data/public/search/aggs/buckets/lib/extended_bounds.ts similarity index 92% rename from src/plugins/discover/public/helpers/index.ts rename to src/plugins/data/public/search/aggs/buckets/lib/extended_bounds.ts index 7196c96989e97d..7a249a9daca91f 100644 --- a/src/plugins/discover/public/helpers/index.ts +++ b/src/plugins/data/public/search/aggs/buckets/lib/extended_bounds.ts @@ -17,4 +17,7 @@ * under the License. */ -export { shortenDottedString } from './shorten_dotted_string'; +export interface ExtendedBounds { + min: number; + max: number; +} diff --git a/src/plugins/data/public/search/aggs/buckets/lib/geo_point.ts b/src/plugins/data/public/search/aggs/buckets/lib/geo_point.ts new file mode 100644 index 00000000000000..8ff4493e286cf2 --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/lib/geo_point.ts @@ -0,0 +1,86 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +type GeoPoint = + | { + lat: number; + lon: number; + } + | string + | [number, number]; + +interface GeoBox { + top: number; + left: number; + bottom: number; + right: number; +} + +/** GeoBoundingBox Accepted Formats: + * Lat Lon As Properties: + * "top_left" : { + * "lat" : 40.73, "lon" : -74.1 + * }, + * "bottom_right" : { + * "lat" : 40.01, "lon" : -71.12 + * } + * + * Lat Lon As Array: + * { + * "top_left" : [-74.1, 40.73], + * "bottom_right" : [-71.12, 40.01] + * } + * + * Lat Lon As String: + * { + * "top_left" : "40.73, -74.1", + * "bottom_right" : "40.01, -71.12" + * } + * + * Bounding Box as Well-Known Text (WKT): + * { + * "wkt" : "BBOX (-74.1, -71.12, 40.73, 40.01)" + * } + * + * Geohash: + * { + * "top_right" : "dr5r9ydj2y73", + * "bottom_left" : "drj7teegpus6" + * } + * + * Vertices: + * { + * "top" : 40.73, + * "left" : -74.1, + * "bottom" : 40.01, + * "right" : -71.12 + * } + * + * **/ +export type GeoBoundingBox = + | Partial<{ + top_left: GeoPoint; + top_right: GeoPoint; + bottom_right: GeoPoint; + bottom_left: GeoPoint; + }> + | { + wkt: string; + } + | GeoBox; diff --git a/src/plugins/data/public/search/aggs/buckets/lib/ip_range.ts b/src/plugins/data/public/search/aggs/buckets/lib/ip_range.ts index be1ac28934c7cd..57e5337d4c3654 100644 --- a/src/plugins/data/public/search/aggs/buckets/lib/ip_range.ts +++ b/src/plugins/data/public/search/aggs/buckets/lib/ip_range.ts @@ -17,9 +17,18 @@ * under the License. */ -export type IpRangeKey = - | { type: 'mask'; mask: string } - | { type: 'range'; from: string; to: string }; +export interface CidrMaskIpRangeAggKey { + type: 'mask'; + mask: string; +} + +export interface RangeIpRangeAggKey { + type: 'range'; + from: string; + to: string; +} + +export type IpRangeKey = CidrMaskIpRangeAggKey | RangeIpRangeAggKey; export const convertIPRangeToString = (range: IpRangeKey, format: (val: any) => string) => { if (range.type === 'mask') { diff --git a/src/plugins/data/public/search/aggs/buckets/range.ts b/src/plugins/data/public/search/aggs/buckets/range.ts index 2c1303814a88ab..02aad3bd5fed12 100644 --- a/src/plugins/data/public/search/aggs/buckets/range.ts +++ b/src/plugins/data/public/search/aggs/buckets/range.ts @@ -24,6 +24,7 @@ import { RangeKey } from './range_key'; import { createFilterRange } from './create_filter/range'; import { BUCKET_TYPES } from './bucket_agg_types'; import { GetInternalStartServicesFn } from '../../../types'; +import { BaseAggParams } from '../types'; const keyCaches = new WeakMap(); const formats = new WeakMap(); @@ -36,6 +37,14 @@ export interface RangeBucketAggDependencies { getInternalStartServices: GetInternalStartServicesFn; } +export interface AggParamsRange extends BaseAggParams { + field: string; + ranges?: Array<{ + from: number; + to: number; + }>; +} + export const getRangeBucketAgg = ({ getInternalStartServices }: RangeBucketAggDependencies) => new BucketAggType( { diff --git a/src/plugins/data/public/search/aggs/buckets/range_fn.test.ts b/src/plugins/data/public/search/aggs/buckets/range_fn.test.ts new file mode 100644 index 00000000000000..93ae4490196a82 --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/range_fn.test.ts @@ -0,0 +1,100 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { functionWrapper } from '../test_helpers'; +import { aggRange } from './range_fn'; + +describe('agg_expression_functions', () => { + describe('aggRange', () => { + const fn = functionWrapper(aggRange()); + + test('fills in defaults when only required args are provided', () => { + const actual = fn({ + field: 'number_field', + }); + expect(actual).toMatchInlineSnapshot(` + Object { + "type": "agg_type", + "value": Object { + "enabled": true, + "id": undefined, + "params": Object { + "customLabel": undefined, + "field": "number_field", + "json": undefined, + "ranges": undefined, + }, + "schema": undefined, + "type": "range", + }, + } + `); + }); + + test('includes optional params when they are provided', () => { + const actual = fn({ + field: 'number_field', + ranges: JSON.stringify([ + { from: 1, to: 2 }, + { from: 5, to: 100 }, + ]), + }); + + expect(actual.value).toMatchInlineSnapshot(` + Object { + "enabled": true, + "id": undefined, + "params": Object { + "customLabel": undefined, + "field": "number_field", + "json": undefined, + "ranges": Array [ + Object { + "from": 1, + "to": 2, + }, + Object { + "from": 5, + "to": 100, + }, + ], + }, + "schema": undefined, + "type": "range", + } + `); + }); + + test('correctly parses json string argument', () => { + const actual = fn({ + field: 'number_field', + json: '{ "foo": true }', + }); + + expect(actual.value.params.json).toEqual({ foo: true }); + + expect(() => { + fn({ + field: 'number_field', + json: '/// intentionally malformed json ///', + }); + }).toThrowErrorMatchingInlineSnapshot(`"Unable to parse json argument string"`); + }); + }); +}); diff --git a/src/plugins/data/public/search/aggs/buckets/range_fn.ts b/src/plugins/data/public/search/aggs/buckets/range_fn.ts new file mode 100644 index 00000000000000..48686e7061de96 --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/range_fn.ts @@ -0,0 +1,106 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; +import { Assign } from '@kbn/utility-types'; +import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; +import { getParsedValue } from '../utils/get_parsed_value'; + +const fnName = 'aggRange'; + +type Input = any; +type AggArgs = AggExpressionFunctionArgs; + +type Arguments = Assign; + +type Output = AggExpressionType; +type FunctionDefinition = ExpressionFunctionDefinition; + +export const aggRange = (): FunctionDefinition => ({ + name: fnName, + help: i18n.translate('data.search.aggs.function.buckets.range.help', { + defaultMessage: 'Generates a serialized agg config for a Range agg', + }), + type: 'agg_type', + args: { + id: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.range.id.help', { + defaultMessage: 'ID for this aggregation', + }), + }, + enabled: { + types: ['boolean'], + default: true, + help: i18n.translate('data.search.aggs.buckets.range.enabled.help', { + defaultMessage: 'Specifies whether this aggregation should be enabled', + }), + }, + schema: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.range.schema.help', { + defaultMessage: 'Schema to use for this aggregation', + }), + }, + field: { + types: ['string'], + required: true, + help: i18n.translate('data.search.aggs.buckets.range.field.help', { + defaultMessage: 'Field to use for this aggregation', + }), + }, + ranges: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.range.ranges.help', { + defaultMessage: 'Serialized ranges to use for this aggregation.', + }), + }, + json: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.range.json.help', { + defaultMessage: 'Advanced json to include when the agg is sent to Elasticsearch', + }), + }, + customLabel: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.range.customLabel.help', { + defaultMessage: 'Represents a custom label for this aggregation', + }), + }, + }, + fn: (input, args) => { + const { id, enabled, schema, ...rest } = args; + + return { + type: 'agg_type', + value: { + id, + enabled, + schema, + type: BUCKET_TYPES.RANGE, + params: { + ...rest, + json: getParsedValue(args, 'json'), + ranges: getParsedValue(args, 'ranges'), + }, + }, + }; + }, +}); diff --git a/src/plugins/data/public/search/aggs/buckets/significant_terms.ts b/src/plugins/data/public/search/aggs/buckets/significant_terms.ts index 49d797f3afbc9a..e6afc56dfd31c0 100644 --- a/src/plugins/data/public/search/aggs/buckets/significant_terms.ts +++ b/src/plugins/data/public/search/aggs/buckets/significant_terms.ts @@ -24,6 +24,7 @@ import { isStringType, migrateIncludeExcludeFormat } from './migrate_include_exc import { BUCKET_TYPES } from './bucket_agg_types'; import { KBN_FIELD_TYPES } from '../../../../common'; import { GetInternalStartServicesFn } from '../../../types'; +import { BaseAggParams } from '../types'; const significantTermsTitle = i18n.translate('data.search.aggs.buckets.significantTermsTitle', { defaultMessage: 'Significant Terms', @@ -33,6 +34,13 @@ export interface SignificantTermsBucketAggDependencies { getInternalStartServices: GetInternalStartServicesFn; } +export interface AggParamsSignificantTerms extends BaseAggParams { + field: string; + size?: number; + exclude?: string; + include?: string; +} + export const getSignificantTermsBucketAgg = ({ getInternalStartServices, }: SignificantTermsBucketAggDependencies) => diff --git a/src/plugins/data/public/search/aggs/buckets/significant_terms_fn.test.ts b/src/plugins/data/public/search/aggs/buckets/significant_terms_fn.test.ts new file mode 100644 index 00000000000000..71be4e9cfa9ac9 --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/significant_terms_fn.test.ts @@ -0,0 +1,96 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { functionWrapper } from '../test_helpers'; +import { aggSignificantTerms } from './significant_terms_fn'; + +describe('agg_expression_functions', () => { + describe('aggSignificantTerms', () => { + const fn = functionWrapper(aggSignificantTerms()); + + test('fills in defaults when only required args are provided', () => { + const actual = fn({ + field: 'machine.os.keyword', + }); + expect(actual).toMatchInlineSnapshot(` + Object { + "type": "agg_type", + "value": Object { + "enabled": true, + "id": undefined, + "params": Object { + "customLabel": undefined, + "exclude": undefined, + "field": "machine.os.keyword", + "include": undefined, + "json": undefined, + "size": undefined, + }, + "schema": undefined, + "type": "significant_terms", + }, + } + `); + }); + + test('includes optional params when they are provided', () => { + const actual = fn({ + id: '1', + enabled: false, + schema: 'whatever', + field: 'machine.os.keyword', + size: 6, + include: 'win', + exclude: 'ios', + }); + + expect(actual.value).toMatchInlineSnapshot(` + Object { + "enabled": false, + "id": "1", + "params": Object { + "customLabel": undefined, + "exclude": "ios", + "field": "machine.os.keyword", + "include": "win", + "json": undefined, + "size": 6, + }, + "schema": "whatever", + "type": "significant_terms", + } + `); + }); + + test('correctly parses json string argument', () => { + const actual = fn({ + field: 'machine.os.keyword', + json: '{ "foo": true }', + }); + + expect(actual.value.params.json).toEqual({ foo: true }); + expect(() => { + fn({ + field: 'machine.os.keyword', + json: '/// intentionally malformed json ///', + }); + }).toThrowErrorMatchingInlineSnapshot(`"Unable to parse json argument string"`); + }); + }); +}); diff --git a/src/plugins/data/public/search/aggs/buckets/significant_terms_fn.ts b/src/plugins/data/public/search/aggs/buckets/significant_terms_fn.ts new file mode 100644 index 00000000000000..83583070bddfed --- /dev/null +++ b/src/plugins/data/public/search/aggs/buckets/significant_terms_fn.ts @@ -0,0 +1,116 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; +import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; +import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; +import { getParsedValue } from '../utils/get_parsed_value'; + +const fnName = 'aggSignificantTerms'; + +type Input = any; +type AggArgs = AggExpressionFunctionArgs; + +type Arguments = AggArgs; + +type Output = AggExpressionType; +type FunctionDefinition = ExpressionFunctionDefinition; + +export const aggSignificantTerms = (): FunctionDefinition => ({ + name: fnName, + help: i18n.translate('data.search.aggs.function.buckets.significantTerms.help', { + defaultMessage: 'Generates a serialized agg config for a Significant Terms agg', + }), + type: 'agg_type', + args: { + id: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.significantTerms.id.help', { + defaultMessage: 'ID for this aggregation', + }), + }, + enabled: { + types: ['boolean'], + default: true, + help: i18n.translate('data.search.aggs.buckets.significantTerms.enabled.help', { + defaultMessage: 'Specifies whether this aggregation should be enabled', + }), + }, + schema: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.significantTerms.schema.help', { + defaultMessage: 'Schema to use for this aggregation', + }), + }, + field: { + types: ['string'], + required: true, + help: i18n.translate('data.search.aggs.buckets.significantTerms.field.help', { + defaultMessage: 'Field to use for this aggregation', + }), + }, + size: { + types: ['number'], + help: i18n.translate('data.search.aggs.buckets.significantTerms.size.help', { + defaultMessage: 'Max number of buckets to retrieve', + }), + }, + exclude: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.significantTerms.exclude.help', { + defaultMessage: 'Specific bucket values to exclude from results', + }), + }, + include: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.significantTerms.include.help', { + defaultMessage: 'Specific bucket values to include in results', + }), + }, + json: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.significantTerms.json.help', { + defaultMessage: 'Advanced json to include when the agg is sent to Elasticsearch', + }), + }, + customLabel: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.significantTerms.customLabel.help', { + defaultMessage: 'Represents a custom label for this aggregation', + }), + }, + }, + fn: (input, args) => { + const { id, enabled, schema, ...rest } = args; + + return { + type: 'agg_type', + value: { + id, + enabled, + schema, + type: BUCKET_TYPES.SIGNIFICANT_TERMS, + params: { + ...rest, + json: getParsedValue(args, 'json'), + }, + }, + }; + }, +}); diff --git a/src/plugins/data/public/search/aggs/buckets/terms.ts b/src/plugins/data/public/search/aggs/buckets/terms.ts index a12a1d7ac2d3d5..1bfc508dc38716 100644 --- a/src/plugins/data/public/search/aggs/buckets/terms.ts +++ b/src/plugins/data/public/search/aggs/buckets/terms.ts @@ -26,7 +26,7 @@ import { isStringOrNumberType, migrateIncludeExcludeFormat, } from './migrate_include_exclude_format'; -import { AggConfigSerialized, IAggConfigs } from '../types'; +import { AggConfigSerialized, BaseAggParams, IAggConfigs } from '../types'; import { Adapters } from '../../../../../inspector/public'; import { ISearchSource } from '../../search_source'; @@ -63,11 +63,11 @@ export interface TermsBucketAggDependencies { getInternalStartServices: GetInternalStartServicesFn; } -export interface AggParamsTerms { +export interface AggParamsTerms extends BaseAggParams { field: string; - order: 'asc' | 'desc'; orderBy: string; orderAgg?: AggConfigSerialized; + order?: 'asc' | 'desc'; size?: number; missingBucket?: boolean; missingBucketLabel?: string; @@ -76,7 +76,6 @@ export interface AggParamsTerms { // advanced exclude?: string; include?: string; - json?: string; } export const getTermsBucketAgg = ({ getInternalStartServices }: TermsBucketAggDependencies) => diff --git a/src/plugins/data/public/search/aggs/buckets/terms_fn.test.ts b/src/plugins/data/public/search/aggs/buckets/terms_fn.test.ts index f55f1de7960138..1384a9f17e4b69 100644 --- a/src/plugins/data/public/search/aggs/buckets/terms_fn.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/terms_fn.test.ts @@ -27,7 +27,6 @@ describe('agg_expression_functions', () => { test('fills in defaults when only required args are provided', () => { const actual = fn({ field: 'machine.os.keyword', - order: 'asc', orderBy: '1', }); expect(actual).toMatchInlineSnapshot(` @@ -37,18 +36,19 @@ describe('agg_expression_functions', () => { "enabled": true, "id": undefined, "params": Object { + "customLabel": undefined, "exclude": undefined, "field": "machine.os.keyword", "include": undefined, "json": undefined, - "missingBucket": false, - "missingBucketLabel": "Missing", - "order": "asc", + "missingBucket": undefined, + "missingBucketLabel": undefined, + "order": undefined, "orderAgg": undefined, "orderBy": "1", - "otherBucket": false, - "otherBucketLabel": "Other", - "size": 5, + "otherBucket": undefined, + "otherBucketLabel": undefined, + "size": undefined, }, "schema": undefined, "type": "terms", @@ -70,6 +70,7 @@ describe('agg_expression_functions', () => { missingBucketLabel: 'missing', otherBucket: true, otherBucketLabel: 'other', + include: 'win', exclude: 'ios', }); @@ -78,9 +79,10 @@ describe('agg_expression_functions', () => { "enabled": false, "id": "1", "params": Object { + "customLabel": undefined, "exclude": "ios", "field": "machine.os.keyword", - "include": undefined, + "include": "win", "json": undefined, "missingBucket": true, "missingBucketLabel": "missing", @@ -107,37 +109,39 @@ describe('agg_expression_functions', () => { expect(actual.value.params).toMatchInlineSnapshot(` Object { + "customLabel": undefined, "exclude": undefined, "field": "machine.os.keyword", "include": undefined, "json": undefined, - "missingBucket": false, - "missingBucketLabel": "Missing", + "missingBucket": undefined, + "missingBucketLabel": undefined, "order": "asc", "orderAgg": Object { "enabled": true, "id": undefined, "params": Object { + "customLabel": undefined, "exclude": undefined, "field": "name", "include": undefined, "json": undefined, - "missingBucket": false, - "missingBucketLabel": "Missing", + "missingBucket": undefined, + "missingBucketLabel": undefined, "order": "asc", "orderAgg": undefined, "orderBy": "1", - "otherBucket": false, - "otherBucketLabel": "Other", - "size": 5, + "otherBucket": undefined, + "otherBucketLabel": undefined, + "size": undefined, }, "schema": undefined, "type": "terms", }, "orderBy": "1", - "otherBucket": false, - "otherBucketLabel": "Other", - "size": 5, + "otherBucket": undefined, + "otherBucketLabel": undefined, + "size": undefined, } `); }); diff --git a/src/plugins/data/public/search/aggs/buckets/terms_fn.ts b/src/plugins/data/public/search/aggs/buckets/terms_fn.ts index 7980bfabe79fb1..49520863fe1cca 100644 --- a/src/plugins/data/public/search/aggs/buckets/terms_fn.ts +++ b/src/plugins/data/public/search/aggs/buckets/terms_fn.ts @@ -20,27 +20,25 @@ import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; import { ExpressionFunctionDefinition } from '../../../../../expressions/public'; -import { AggExpressionType, AggExpressionFunctionArgs } from '../'; +import { AggExpressionType, AggExpressionFunctionArgs, BUCKET_TYPES } from '../'; +import { getParsedValue } from '../utils/get_parsed_value'; -const aggName = 'terms'; const fnName = 'aggTerms'; type Input = any; -type AggArgs = AggExpressionFunctionArgs; +type AggArgs = AggExpressionFunctionArgs; + // Since the orderAgg param is an agg nested in a subexpression, we need to // overwrite the param type to expect a value of type AggExpressionType. -type Arguments = AggArgs & - Assign< - AggArgs, - { orderAgg?: AggArgs['orderAgg'] extends undefined ? undefined : AggExpressionType } - >; +type Arguments = Assign; + type Output = AggExpressionType; type FunctionDefinition = ExpressionFunctionDefinition; export const aggTerms = (): FunctionDefinition => ({ name: fnName, help: i18n.translate('data.search.aggs.function.buckets.terms.help', { - defaultMessage: 'Generates a serialized agg config for a terms agg', + defaultMessage: 'Generates a serialized agg config for a Terms agg', }), type: 'agg_type', args: { @@ -72,7 +70,7 @@ export const aggTerms = (): FunctionDefinition => ({ }, order: { types: ['string'], - required: true, + options: ['asc', 'desc'], help: i18n.translate('data.search.aggs.buckets.terms.order.help', { defaultMessage: 'Order in which to return the results: asc or desc', }), @@ -91,41 +89,30 @@ export const aggTerms = (): FunctionDefinition => ({ }, size: { types: ['number'], - default: 5, help: i18n.translate('data.search.aggs.buckets.terms.size.help', { defaultMessage: 'Max number of buckets to retrieve', }), }, missingBucket: { types: ['boolean'], - default: false, help: i18n.translate('data.search.aggs.buckets.terms.missingBucket.help', { defaultMessage: 'When set to true, groups together any buckets with missing fields', }), }, missingBucketLabel: { types: ['string'], - default: i18n.translate('data.search.aggs.buckets.terms.missingBucketLabel', { - defaultMessage: 'Missing', - description: `Default label used in charts when documents are missing a field. - Visible when you create a chart with a terms aggregation and enable "Show missing values"`, - }), help: i18n.translate('data.search.aggs.buckets.terms.missingBucketLabel.help', { defaultMessage: 'Default label used in charts when documents are missing a field.', }), }, otherBucket: { types: ['boolean'], - default: false, help: i18n.translate('data.search.aggs.buckets.terms.otherBucket.help', { defaultMessage: 'When set to true, groups together any buckets beyond the allowed size', }), }, otherBucketLabel: { types: ['string'], - default: i18n.translate('data.search.aggs.buckets.terms.otherBucketLabel', { - defaultMessage: 'Other', - }), help: i18n.translate('data.search.aggs.buckets.terms.otherBucketLabel.help', { defaultMessage: 'Default label used in charts for documents in the Other bucket', }), @@ -148,32 +135,27 @@ export const aggTerms = (): FunctionDefinition => ({ defaultMessage: 'Advanced json to include when the agg is sent to Elasticsearch', }), }, + customLabel: { + types: ['string'], + help: i18n.translate('data.search.aggs.buckets.terms.customLabel.help', { + defaultMessage: 'Represents a custom label for this aggregation', + }), + }, }, fn: (input, args) => { const { id, enabled, schema, ...rest } = args; - let json; - try { - json = args.json ? JSON.parse(args.json) : undefined; - } catch (e) { - throw new Error('Unable to parse json argument string'); - } - - // Need to spread this object to work around TS bug: - // https://github.com/microsoft/TypeScript/issues/15300#issuecomment-436793742 - const orderAgg = args.orderAgg?.value ? { ...args.orderAgg.value } : undefined; - return { type: 'agg_type', value: { id, enabled, schema, - type: aggName, + type: BUCKET_TYPES.TERMS, params: { ...rest, - orderAgg, - json, + orderAgg: args.orderAgg?.value, + json: getParsedValue(args, 'json'), }, }, }; diff --git a/src/plugins/data/public/search/aggs/types.ts b/src/plugins/data/public/search/aggs/types.ts index 1c5b5b458ce907..8ad264f59cc27a 100644 --- a/src/plugins/data/public/search/aggs/types.ts +++ b/src/plugins/data/public/search/aggs/types.ts @@ -21,11 +21,22 @@ import { IndexPattern } from '../../index_patterns'; import { AggConfigSerialized, AggConfigs, + AggParamsRange, + AggParamsIpRange, + AggParamsDateRange, + AggParamsFilter, + AggParamsFilters, + AggParamsSignificantTerms, + AggParamsGeoTile, + AggParamsGeoHash, AggParamsTerms, + AggParamsHistogram, + AggParamsDateHistogram, AggTypesRegistrySetup, AggTypesRegistryStart, CreateAggConfigParams, getCalculateAutoTimeExpression, + BUCKET_TYPES, } from './'; export { IAggConfig, AggConfigSerialized } from './agg_config'; @@ -55,6 +66,12 @@ export interface SearchAggsStart { types: AggTypesRegistryStart; } +/** @internal */ +export interface BaseAggParams { + json?: string; + customLabel?: string; +} + /** @internal */ export interface AggExpressionType { type: 'agg_type'; @@ -74,5 +91,15 @@ export type AggExpressionFunctionArgs< * @internal */ export interface AggParamsMapping { - terms: AggParamsTerms; + [BUCKET_TYPES.RANGE]: AggParamsRange; + [BUCKET_TYPES.IP_RANGE]: AggParamsIpRange; + [BUCKET_TYPES.DATE_RANGE]: AggParamsDateRange; + [BUCKET_TYPES.FILTER]: AggParamsFilter; + [BUCKET_TYPES.FILTERS]: AggParamsFilters; + [BUCKET_TYPES.SIGNIFICANT_TERMS]: AggParamsSignificantTerms; + [BUCKET_TYPES.GEOTILE_GRID]: AggParamsGeoTile; + [BUCKET_TYPES.GEOHASH_GRID]: AggParamsGeoHash; + [BUCKET_TYPES.HISTOGRAM]: AggParamsHistogram; + [BUCKET_TYPES.DATE_HISTOGRAM]: AggParamsDateHistogram; + [BUCKET_TYPES.TERMS]: AggParamsTerms; } diff --git a/src/plugins/discover/public/helpers/shorten_dotted_string.ts b/src/plugins/data/public/search/aggs/utils/get_parsed_value.ts similarity index 60% rename from src/plugins/discover/public/helpers/shorten_dotted_string.ts rename to src/plugins/data/public/search/aggs/utils/get_parsed_value.ts index 9d78a96784339b..48e752369d1d3c 100644 --- a/src/plugins/discover/public/helpers/shorten_dotted_string.ts +++ b/src/plugins/data/public/search/aggs/utils/get_parsed_value.ts @@ -17,10 +17,18 @@ * under the License. */ -const DOT_PREFIX_RE = /(.).+?\./g; - /** - * Convert a dot.notated.string into a short - * version (d.n.string) + * This method parses a JSON string and constructs the Object or object described by the string. + * If the given string is not valid JSON, you will get a syntax error. + * @param data { Object } - an object that contains the required for parsing field + * @param key { string} - name of the field to be parsed + * + * @internal */ -export const shortenDottedString = (input: string) => input.replace(DOT_PREFIX_RE, '$1.'); +export const getParsedValue = (data: any, key: string) => { + try { + return data[key] ? JSON.parse(data[key]) : undefined; + } catch (e) { + throw new Error(`Unable to parse ${key} argument string`); + } +}; diff --git a/src/plugins/dev_tools/public/application.tsx b/src/plugins/dev_tools/public/application.tsx index 2c21b451cb9f70..5ec5b8036e4fb4 100644 --- a/src/plugins/dev_tools/public/application.tsx +++ b/src/plugins/dev_tools/public/application.tsx @@ -16,7 +16,6 @@ * specific language governing permissions and limitations * under the License. */ - import { I18nProvider } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; import { EuiTab, EuiTabs, EuiToolTip } from '@elastic/eui'; @@ -26,17 +25,17 @@ import ReactDOM from 'react-dom'; import { useEffect, useRef } from 'react'; import { AppMountContext, AppMountDeprecated } from 'kibana/public'; -import { DevTool } from './plugin'; +import { DevToolApp } from './dev_tool'; interface DevToolsWrapperProps { - devTools: readonly DevTool[]; - activeDevTool: DevTool; + devTools: readonly DevToolApp[]; + activeDevTool: DevToolApp; appMountContext: AppMountContext; updateRoute: (newRoute: string) => void; } interface MountedDevToolDescriptor { - devTool: DevTool; + devTool: DevToolApp; mountpoint: HTMLElement; unmountHandler: () => void; } @@ -64,10 +63,10 @@ function DevToolsWrapper({ {devTools.map(currentDevTool => ( { - if (!currentDevTool.disabled) { + if (!currentDevTool.isDisabled()) { updateRoute(`/dev_tools/${currentDevTool.id}`); } }} @@ -151,7 +150,7 @@ export function renderApp( element: HTMLElement, appMountContext: AppMountContext, basePath: string, - devTools: readonly DevTool[] + devTools: readonly DevToolApp[] ) { if (redirectOnMissingCapabilities(appMountContext)) { return () => {}; @@ -162,21 +161,24 @@ export function renderApp( - {devTools.map(devTool => ( - ( - - )} - /> - ))} + {devTools + // Only create routes for devtools that are not disabled + .filter(devTool => !devTool.isDisabled()) + .map(devTool => ( + ( + + )} + /> + ))} diff --git a/src/plugins/dev_tools/public/dev_tool.ts b/src/plugins/dev_tools/public/dev_tool.ts new file mode 100644 index 00000000000000..943cca286a722f --- /dev/null +++ b/src/plugins/dev_tools/public/dev_tool.ts @@ -0,0 +1,106 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +import { App } from 'kibana/public'; + +/** + * Descriptor for a dev tool. A dev tool works similar to an application + * registered in the core application service. + */ +export type CreateDevToolArgs = Omit & { + disabled?: boolean; +}; + +export class DevToolApp { + /** + * The id of the dev tools. This will become part of the URL path + * (`dev_tools/${devTool.id}`. It has to be unique among registered + * dev tools. + */ + public readonly id: string; + /** + * The human readable name of the dev tool. Should be internationalized. + * This will be used as a label in the tab above the actual tool. + */ + public readonly title: string; + public readonly mount: App['mount']; + + /** + * Flag indicating to disable the tab of this dev tool. Navigating to a + * disabled dev tool will be treated as the navigation to an unknown route + * (redirect to the console). + */ + private disabled: boolean; + + /** + * Optional tooltip content of the tab. + */ + public readonly tooltipContent?: string; + /** + * Flag indicating whether the dev tool will do routing within the `dev_tools/${devTool.id}/` + * prefix. If it is set to true, the dev tool is responsible to redirect + * the user when navigating to unknown URLs within the prefix. If set + * to false only the root URL of the dev tool will be recognized as valid. + */ + public readonly enableRouting: boolean; + /** + * Number used to order the tabs. + */ + public readonly order: number; + + constructor( + id: string, + title: string, + mount: App['mount'], + enableRouting: boolean, + order: number, + toolTipContent = '', + disabled = false + ) { + this.id = id; + this.title = title; + this.mount = mount; + this.enableRouting = enableRouting; + this.order = order; + this.tooltipContent = toolTipContent; + this.disabled = disabled; + } + + public enable() { + this.disabled = false; + } + + public disable() { + this.disabled = true; + } + + public isDisabled(): boolean { + return this.disabled; + } +} + +export const createDevToolApp = ({ + id, + title, + mount, + enableRouting, + order, + tooltipContent, + disabled, +}: CreateDevToolArgs) => + new DevToolApp(id, title, mount, enableRouting, order, tooltipContent, disabled); diff --git a/src/plugins/dev_tools/public/plugin.ts b/src/plugins/dev_tools/public/plugin.ts index df61271baf879a..bedf92818315ae 100644 --- a/src/plugins/dev_tools/public/plugin.ts +++ b/src/plugins/dev_tools/public/plugin.ts @@ -17,9 +17,10 @@ * under the License. */ -import { App, CoreSetup, Plugin } from 'kibana/public'; +import { CoreSetup, Plugin } from 'kibana/public'; import { sortBy } from 'lodash'; import { KibanaLegacySetup } from '../../kibana_legacy/public'; +import { CreateDevToolArgs, DevToolApp, createDevToolApp } from './dev_tool'; import './index.scss'; @@ -34,7 +35,7 @@ export interface DevToolsSetup { * to switch between the tools. * @param devTool The dev tools descriptor */ - register: (devTool: DevTool) => void; + register: (devTool: CreateDevToolArgs) => DevToolApp; } export interface DevToolsStart { @@ -46,53 +47,13 @@ export interface DevToolsStart { * becomes an implementation detail. * @deprecated */ - getSortedDevTools: () => readonly DevTool[]; -} - -/** - * Descriptor for a dev tool. A dev tool works similar to an application - * registered in the core application service. - */ -export interface DevTool { - /** - * The id of the dev tools. This will become part of the URL path - * (`dev_tools/${devTool.id}`. It has to be unique among registered - * dev tools. - */ - id: string; - /** - * The human readable name of the dev tool. Should be internationalized. - * This will be used as a label in the tab above the actual tool. - */ - title: string; - mount: App['mount']; - /** - * Flag indicating to disable the tab of this dev tool. Navigating to a - * disabled dev tool will be treated as the navigation to an unknown route - * (redirect to the console). - */ - disabled?: boolean; - /** - * Optional tooltip content of the tab. - */ - tooltipContent?: string; - /** - * Flag indicating whether the dev tool will do routing within the `dev_tools/${devTool.id}/` - * prefix. If it is set to true, the dev tool is responsible to redirect - * the user when navigating to unknown URLs within the prefix. If set - * to false only the root URL of the dev tool will be recognized as valid. - */ - enableRouting: boolean; - /** - * Number used to order the tabs. - */ - order: number; + getSortedDevTools: () => readonly DevToolApp[]; } export class DevToolsPlugin implements Plugin { - private readonly devTools = new Map(); + private readonly devTools = new Map(); - private getSortedDevTools(): readonly DevTool[] { + private getSortedDevTools(): readonly DevToolApp[] { return sortBy([...this.devTools.values()], 'order'); } @@ -115,14 +76,16 @@ export class DevToolsPlugin implements Plugin { }); return { - register: (devTool: DevTool) => { - if (this.devTools.has(devTool.id)) { + register: (devToolArgs: CreateDevToolArgs) => { + if (this.devTools.has(devToolArgs.id)) { throw new Error( - `Dev tool with id [${devTool.id}] has already been registered. Use a unique id.` + `Dev tool with id [${devToolArgs.id}] has already been registered. Use a unique id.` ); } + const devTool = createDevToolApp(devToolArgs); this.devTools.set(devTool.id, devTool); + return devTool; }, }; } diff --git a/src/plugins/discover/kibana.json b/src/plugins/discover/kibana.json index 2d41293f263698..0b3a07e98624ef 100644 --- a/src/plugins/discover/kibana.json +++ b/src/plugins/discover/kibana.json @@ -2,5 +2,16 @@ "id": "discover", "version": "kibana", "server": true, - "ui": true + "ui": true, + "requiredPlugins": [ + "charts", + "data", + "embeddable", + "inspector", + "kibanaLegacy", + "navigation", + "uiActions", + "visualizations" + ], + "optionalPlugins": ["home", "share"] } diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/_discover.scss b/src/plugins/discover/public/application/_discover.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/_discover.scss rename to src/plugins/discover/public/application/_discover.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/_hacks.scss b/src/plugins/discover/public/application/_hacks.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/_hacks.scss rename to src/plugins/discover/public/application/_hacks.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/_mixins.scss b/src/plugins/discover/public/application/_mixins.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/_mixins.scss rename to src/plugins/discover/public/application/_mixins.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/_index.scss b/src/plugins/discover/public/application/angular/_index.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/_index.scss rename to src/plugins/discover/public/application/angular/_index.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context.html b/src/plugins/discover/public/application/angular/context.html similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context.html rename to src/plugins/discover/public/application/angular/context.html diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context.js b/src/plugins/discover/public/application/angular/context.js similarity index 98% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context.js rename to src/plugins/discover/public/application/angular/context.js index 032ec7af09a301..33bbc8cb2e6cf9 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context.js +++ b/src/plugins/discover/public/application/angular/context.js @@ -32,7 +32,7 @@ const k7Breadcrumbs = $route => { return [ ...getRootBreadcrumbs(), { - text: i18n.translate('kbn.context.breadcrumb', { + text: i18n.translate('discover.context.breadcrumb', { defaultMessage: 'Context of {indexPatternTitle}#{docId}', values: { indexPatternTitle: indexPattern.title, diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/NOTES.md b/src/plugins/discover/public/application/angular/context/NOTES.md similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/NOTES.md rename to src/plugins/discover/public/application/angular/context/NOTES.md diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/_index.scss b/src/plugins/discover/public/application/angular/context/_index.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/_index.scss rename to src/plugins/discover/public/application/angular/context/_index.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/_stubs.js b/src/plugins/discover/public/application/angular/context/api/_stubs.js similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/_stubs.js rename to src/plugins/discover/public/application/angular/context/api/_stubs.js diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/anchor.js b/src/plugins/discover/public/application/angular/context/api/anchor.js similarity index 95% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/anchor.js rename to src/plugins/discover/public/application/angular/context/api/anchor.js index 4338d3e1dbdbd7..4df5ba989f7985 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/anchor.js +++ b/src/plugins/discover/public/application/angular/context/api/anchor.js @@ -46,7 +46,7 @@ export function fetchAnchorProvider(indexPatterns, searchSource) { if (_.get(response, ['hits', 'total'], 0) < 1) { throw new Error( - i18n.translate('kbn.context.failedToLoadAnchorDocumentErrorDescription', { + i18n.translate('discover.context.failedToLoadAnchorDocumentErrorDescription', { defaultMessage: 'Failed to load anchor document.', }) ); diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/anchor.test.js b/src/plugins/discover/public/application/angular/context/api/anchor.test.js similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/anchor.test.js rename to src/plugins/discover/public/application/angular/context/api/anchor.test.js diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/context.predecessors.test.js b/src/plugins/discover/public/application/angular/context/api/context.predecessors.test.js similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/context.predecessors.test.js rename to src/plugins/discover/public/application/angular/context/api/context.predecessors.test.js diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/context.successors.test.js b/src/plugins/discover/public/application/angular/context/api/context.successors.test.js similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/context.successors.test.js rename to src/plugins/discover/public/application/angular/context/api/context.successors.test.js diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/context.ts b/src/plugins/discover/public/application/angular/context/api/context.ts similarity index 97% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/context.ts rename to src/plugins/discover/public/application/angular/context/api/context.ts index 2760eec38755e2..0bca820f9a7238 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/context.ts +++ b/src/plugins/discover/public/application/angular/context/api/context.ts @@ -17,17 +17,13 @@ * under the License. */ +import { Filter, IndexPatternsContract, IndexPattern } from 'src/plugins/data/public'; import { reverseSortDir, SortDirection } from './utils/sorting'; import { extractNanos, convertIsoToMillis } from './utils/date_conversion'; import { fetchHitsInInterval } from './utils/fetch_hits_in_interval'; import { generateIntervals } from './utils/generate_intervals'; import { getEsQuerySearchAfter } from './utils/get_es_query_search_after'; import { getEsQuerySort } from './utils/get_es_query_sort'; -import { - Filter, - IndexPatternsContract, - IndexPattern, -} from '../../../../../../../../../plugins/data/public'; import { getServices } from '../../../../kibana_services'; export type SurrDocType = 'successors' | 'predecessors'; diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/__tests__/date_conversion.test.ts b/src/plugins/discover/public/application/angular/context/api/utils/date_conversion.test.ts similarity index 96% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/__tests__/date_conversion.test.ts rename to src/plugins/discover/public/application/angular/context/api/utils/date_conversion.test.ts index b9ec105cc0e7bd..223b1747182966 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/__tests__/date_conversion.test.ts +++ b/src/plugins/discover/public/application/angular/context/api/utils/date_conversion.test.ts @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -import { extractNanos } from '../date_conversion'; +import { extractNanos } from './date_conversion'; describe('function extractNanos', function() { test('extract nanos of 2014-01-01', function() { diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/date_conversion.ts b/src/plugins/discover/public/application/angular/context/api/utils/date_conversion.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/date_conversion.ts rename to src/plugins/discover/public/application/angular/context/api/utils/date_conversion.ts diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/fetch_hits_in_interval.ts b/src/plugins/discover/public/application/angular/context/api/utils/fetch_hits_in_interval.ts similarity index 95% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/fetch_hits_in_interval.ts rename to src/plugins/discover/public/application/angular/context/api/utils/fetch_hits_in_interval.ts index 8eed5d33ab004b..437898201863f2 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/fetch_hits_in_interval.ts +++ b/src/plugins/discover/public/application/angular/context/api/utils/fetch_hits_in_interval.ts @@ -16,11 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -import { - ISearchSource, - EsQuerySortValue, - SortDirection, -} from '../../../../../../../../../../plugins/data/public'; +import { ISearchSource, EsQuerySortValue, SortDirection } from '../../../../../../../data/public'; import { convertTimeValueToIso } from './date_conversion'; import { EsHitRecordList } from '../context'; import { IntervalValue } from './generate_intervals'; diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/generate_intervals.ts b/src/plugins/discover/public/application/angular/context/api/utils/generate_intervals.ts similarity index 95% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/generate_intervals.ts rename to src/plugins/discover/public/application/angular/context/api/utils/generate_intervals.ts index b14180d32b4f24..1497f54aa5079a 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/generate_intervals.ts +++ b/src/plugins/discover/public/application/angular/context/api/utils/generate_intervals.ts @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -import { SortDirection } from '../../../../../../../../../../plugins/data/public'; +import { SortDirection } from '../../../../../../../data/public'; export type IntervalValue = number | null; diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/get_es_query_search_after.ts b/src/plugins/discover/public/application/angular/context/api/utils/get_es_query_search_after.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/get_es_query_search_after.ts rename to src/plugins/discover/public/application/angular/context/api/utils/get_es_query_search_after.ts diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/get_es_query_sort.ts b/src/plugins/discover/public/application/angular/context/api/utils/get_es_query_sort.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/get_es_query_sort.ts rename to src/plugins/discover/public/application/angular/context/api/utils/get_es_query_sort.ts diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/__tests__/sorting.test.ts b/src/plugins/discover/public/application/angular/context/api/utils/sorting.test.ts similarity index 94% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/__tests__/sorting.test.ts rename to src/plugins/discover/public/application/angular/context/api/utils/sorting.test.ts index eeae2aa2c5d0ae..350a0a8ede8d5f 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/__tests__/sorting.test.ts +++ b/src/plugins/discover/public/application/angular/context/api/utils/sorting.test.ts @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -import { reverseSortDir, SortDirection } from '../sorting'; +import { reverseSortDir, SortDirection } from './sorting'; describe('function reverseSortDir', function() { test('reverse a given sort direction', function() { diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/sorting.ts b/src/plugins/discover/public/application/angular/context/api/utils/sorting.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/api/utils/sorting.ts rename to src/plugins/discover/public/application/angular/context/api/utils/sorting.ts diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/_action_bar.scss b/src/plugins/discover/public/application/angular/context/components/action_bar/_action_bar.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/_action_bar.scss rename to src/plugins/discover/public/application/angular/context/components/action_bar/_action_bar.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/_index.scss b/src/plugins/discover/public/application/angular/context/components/action_bar/_index.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/_index.scss rename to src/plugins/discover/public/application/angular/context/components/action_bar/_index.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/action_bar.test.tsx b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.test.tsx similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/action_bar.test.tsx rename to src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.test.tsx diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/action_bar.tsx b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.tsx similarity index 93% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/action_bar.tsx rename to src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.tsx index 8fcfcba08955c3..97a29ab21c5818 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/action_bar.tsx +++ b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.tsx @@ -111,7 +111,7 @@ export function ActionBar({ }} flush="right" > - + @@ -119,10 +119,10 @@ export function ActionBar({ {isSuccessor ? ( ) : ( )} diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/action_bar_directive.ts b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar_directive.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/action_bar_directive.ts rename to src/plugins/discover/public/application/angular/context/components/action_bar/action_bar_directive.ts diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/action_bar_warning.tsx b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar_warning.tsx similarity index 90% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/action_bar_warning.tsx rename to src/plugins/discover/public/application/angular/context/components/action_bar/action_bar_warning.tsx index 6b922bb05a2434..db757881ad819c 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/action_bar_warning.tsx +++ b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar_warning.tsx @@ -31,12 +31,12 @@ export function ActionBarWarning({ docCount, type }: { docCount: number; type: S title={ docCount === 0 ? ( ) : ( @@ -55,12 +55,12 @@ export function ActionBarWarning({ docCount, type }: { docCount: number; type: S title={ docCount === 0 ? ( ) : ( diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/index.ts b/src/plugins/discover/public/application/angular/context/components/action_bar/index.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/components/action_bar/index.ts rename to src/plugins/discover/public/application/angular/context/components/action_bar/index.ts diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/helpers/call_after_bindings_workaround.js b/src/plugins/discover/public/application/angular/context/helpers/call_after_bindings_workaround.js similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/helpers/call_after_bindings_workaround.js rename to src/plugins/discover/public/application/angular/context/helpers/call_after_bindings_workaround.js diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query/actions.js b/src/plugins/discover/public/application/angular/context/query/actions.js similarity index 95% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query/actions.js rename to src/plugins/discover/public/application/angular/context/query/actions.js index efc230d2cd4aef..1b1fa7138bfda7 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query/actions.js +++ b/src/plugins/discover/public/application/angular/context/query/actions.js @@ -26,7 +26,7 @@ import { fetchAnchorProvider } from '../api/anchor'; import { fetchContextProvider } from '../api/context'; import { getQueryParameterActions } from '../query_parameters'; import { FAILURE_REASONS, LOADING_STATUS } from './constants'; -import { MarkdownSimple } from '../../../../../../../../../plugins/kibana_react/public'; +import { MarkdownSimple } from '../../../../../../kibana_react/public'; export function QueryActionsProvider(Promise) { const { filterManager, indexPatterns, data } = getServices(); @@ -80,7 +80,7 @@ export function QueryActionsProvider(Promise) { error => { setFailedStatus(state)('anchor', { error }); getServices().toastNotifications.addDanger({ - title: i18n.translate('kbn.context.unableToLoadAnchorDocumentDescription', { + title: i18n.translate('discover.context.unableToLoadAnchorDocumentDescription', { defaultMessage: 'Unable to load the anchor document', }), text: {error.message}, @@ -133,7 +133,7 @@ export function QueryActionsProvider(Promise) { error => { setFailedStatus(state)(type, { error }); getServices().toastNotifications.addDanger({ - title: i18n.translate('kbn.context.unableToLoadDocumentDescription', { + title: i18n.translate('discover.context.unableToLoadDocumentDescription', { defaultMessage: 'Unable to load documents', }), text: {error.message}, diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query/constants.js b/src/plugins/discover/public/application/angular/context/query/constants.js similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query/constants.js rename to src/plugins/discover/public/application/angular/context/query/constants.js diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query/index.js b/src/plugins/discover/public/application/angular/context/query/index.js similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query/index.js rename to src/plugins/discover/public/application/angular/context/query/index.js diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query/state.js b/src/plugins/discover/public/application/angular/context/query/state.js similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query/state.js rename to src/plugins/discover/public/application/angular/context/query/state.js diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query_parameters/actions.js b/src/plugins/discover/public/application/angular/context/query_parameters/actions.js similarity index 96% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query_parameters/actions.js rename to src/plugins/discover/public/application/angular/context/query_parameters/actions.js index 5c1700e7763610..4f86dea08fe848 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query_parameters/actions.js +++ b/src/plugins/discover/public/application/angular/context/query_parameters/actions.js @@ -18,7 +18,7 @@ */ import _ from 'lodash'; -import { esFilters } from '../../../../../../../../../plugins/data/public'; +import { esFilters } from '../../../../../../data/public'; import { MAX_CONTEXT_SIZE, MIN_CONTEXT_SIZE, QUERY_PARAMETER_KEYS } from './constants'; diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query_parameters/actions.test.ts b/src/plugins/discover/public/application/angular/context/query_parameters/actions.test.ts similarity index 97% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query_parameters/actions.test.ts rename to src/plugins/discover/public/application/angular/context/query_parameters/actions.test.ts index 35fbd33fb4bc97..00747fcc812279 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query_parameters/actions.test.ts +++ b/src/plugins/discover/public/application/angular/context/query_parameters/actions.test.ts @@ -19,8 +19,8 @@ // @ts-ignore import { getQueryParameterActions } from './actions'; -import { FilterManager } from '../../../../../../../../../plugins/data/public'; -import { coreMock } from '../../../../../../../../../core/public/mocks'; +import { FilterManager } from '../../../../../../data/public'; +import { coreMock } from '../../../../../../../core/public/mocks'; const setupMock = coreMock.createSetup(); let state: { diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query_parameters/constants.ts b/src/plugins/discover/public/application/angular/context/query_parameters/constants.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query_parameters/constants.ts rename to src/plugins/discover/public/application/angular/context/query_parameters/constants.ts diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query_parameters/index.js b/src/plugins/discover/public/application/angular/context/query_parameters/index.js similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query_parameters/index.js rename to src/plugins/discover/public/application/angular/context/query_parameters/index.js diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query_parameters/state.ts b/src/plugins/discover/public/application/angular/context/query_parameters/state.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context/query_parameters/state.ts rename to src/plugins/discover/public/application/angular/context/query_parameters/state.ts diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context_app.html b/src/plugins/discover/public/application/angular/context_app.html similarity index 78% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context_app.html rename to src/plugins/discover/public/application/angular/context_app.html index 8bbb746fa45f87..1f2d6a073150b2 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context_app.html +++ b/src/plugins/discover/public/application/angular/context_app.html @@ -21,7 +21,7 @@ @@ -30,7 +30,7 @@
@@ -92,7 +92,7 @@ >
diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context_app.js b/src/plugins/discover/public/application/angular/context_app.js similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context_app.js rename to src/plugins/discover/public/application/angular/context_app.js diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context_state.test.ts b/src/plugins/discover/public/application/angular/context_state.test.ts similarity index 97% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context_state.test.ts rename to src/plugins/discover/public/application/angular/context_state.test.ts index 1fa71ed11643a6..83bf1b1d7e3d51 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context_state.test.ts +++ b/src/plugins/discover/public/application/angular/context_state.test.ts @@ -19,8 +19,8 @@ import { getState } from './context_state'; import { createBrowserHistory, History } from 'history'; -import { FilterManager, Filter } from '../../../../../../../plugins/data/public'; -import { coreMock } from '../../../../../../../core/public/mocks'; +import { FilterManager, Filter } from '../../../../data/public'; +import { coreMock } from '../../../../../core/public/mocks'; const setupMock = coreMock.createSetup(); describe('Test Discover Context State', () => { diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context_state.ts b/src/plugins/discover/public/application/angular/context_state.ts similarity index 98% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context_state.ts rename to src/plugins/discover/public/application/angular/context_state.ts index b46995d44d826d..7a92a6ace125b3 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/context_state.ts +++ b/src/plugins/discover/public/application/angular/context_state.ts @@ -23,8 +23,8 @@ import { createKbnUrlStateStorage, syncStates, BaseStateContainer, -} from '../../../../../../../plugins/kibana_utils/public'; -import { esFilters, FilterManager, Filter, Query } from '../../../../../../../plugins/data/public'; +} from '../../../../kibana_utils/public'; +import { esFilters, FilterManager, Filter, Query } from '../../../../data/public'; export interface AppState { /** diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/__snapshots__/no_results.test.js.snap b/src/plugins/discover/public/application/angular/directives/__snapshots__/no_results.test.js.snap similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/__snapshots__/no_results.test.js.snap rename to src/plugins/discover/public/application/angular/directives/__snapshots__/no_results.test.js.snap diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/_histogram.scss b/src/plugins/discover/public/application/angular/directives/_histogram.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/_histogram.scss rename to src/plugins/discover/public/application/angular/directives/_histogram.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/_index.scss b/src/plugins/discover/public/application/angular/directives/_index.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/_index.scss rename to src/plugins/discover/public/application/angular/directives/_index.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/_no_results.scss b/src/plugins/discover/public/application/angular/directives/_no_results.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/_no_results.scss rename to src/plugins/discover/public/application/angular/directives/_no_results.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/_collapsible_sidebar.scss b/src/plugins/discover/public/application/angular/directives/collapsible_sidebar/_collapsible_sidebar.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/_collapsible_sidebar.scss rename to src/plugins/discover/public/application/angular/directives/collapsible_sidebar/_collapsible_sidebar.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/_depth.scss b/src/plugins/discover/public/application/angular/directives/collapsible_sidebar/_depth.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/_depth.scss rename to src/plugins/discover/public/application/angular/directives/collapsible_sidebar/_depth.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/_index.scss b/src/plugins/discover/public/application/angular/directives/collapsible_sidebar/_index.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/_index.scss rename to src/plugins/discover/public/application/angular/directives/collapsible_sidebar/_index.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/collapsible_sidebar.ts b/src/plugins/discover/public/application/angular/directives/collapsible_sidebar/collapsible_sidebar.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/collapsible_sidebar/collapsible_sidebar.ts rename to src/plugins/discover/public/application/angular/directives/collapsible_sidebar/collapsible_sidebar.ts diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/debounce/debounce.js b/src/plugins/discover/public/application/angular/directives/debounce/debounce.js similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/debounce/debounce.js rename to src/plugins/discover/public/application/angular/directives/debounce/debounce.js diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/debounce/__tests__/debounce.js b/src/plugins/discover/public/application/angular/directives/debounce/debounce.test.ts similarity index 73% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/debounce/__tests__/debounce.js rename to src/plugins/discover/public/application/angular/directives/debounce/debounce.test.ts index 43fa5ffbf299a2..bc08d8566d48a4 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/debounce/__tests__/debounce.js +++ b/src/plugins/discover/public/application/angular/directives/debounce/debounce.test.ts @@ -17,42 +17,56 @@ * under the License. */ -import sinon from 'sinon'; -import expect from '@kbn/expect'; -import ngMock from 'ng_mock'; -import { DebounceProvider } from '../index'; -import { pluginInstance } from 'plugins/kibana/discover/legacy'; - -let debounce; -let debounceFromProvider; -let $timeout; - -function init() { - pluginInstance.initializeServices(); - pluginInstance.initializeInnerAngular(); - ngMock.module('app/discover'); - - ngMock.inject(function($injector, _$timeout_, Private) { - $timeout = _$timeout_; - - debounce = $injector.get('debounce'); - debounceFromProvider = Private(DebounceProvider); - }); -} +import sinon, { SinonSpy } from 'sinon'; +import angular, { auto, ITimeoutService } from 'angular'; +import 'angular-mocks'; +import 'angular-sanitize'; +import 'angular-route'; + +// @ts-ignore +import { DebounceProvider } from './index'; +import { coreMock } from '../../../../../../../core/public/mocks'; +import { initializeInnerAngularModule } from '../../../../get_inner_angular'; +import { navigationPluginMock } from '../../../../../../navigation/public/mocks'; +import { dataPluginMock } from '../../../../../../data/public/mocks'; +import { initAngularBootstrap } from '../../../../../../kibana_legacy/public'; describe('debounce service', function() { - let spy; - beforeEach(function() { + let debounce: (fn: () => void, timeout: number, options?: any) => any; + let debounceFromProvider: (fn: () => void, timeout: number, options?: any) => any; + let $timeout: ITimeoutService; + let spy: SinonSpy; + + beforeEach(() => { spy = sinon.spy(); - init(); + + initAngularBootstrap(); + + initializeInnerAngularModule( + 'app/discover', + coreMock.createStart(), + navigationPluginMock.createStartContract(), + dataPluginMock.createStartContract() + ); + + angular.mock.module('app/discover'); + + angular.mock.inject( + ($injector: auto.IInjectorService, _$timeout_: ITimeoutService, Private: any) => { + $timeout = _$timeout_; + + debounce = $injector.get('debounce'); + debounceFromProvider = Private(DebounceProvider); + } + ); }); it('should have a cancel method', function() { const bouncer = debounce(() => {}, 100); const bouncerFromProvider = debounceFromProvider(() => {}, 100); - expect(bouncer).to.have.property('cancel'); - expect(bouncerFromProvider).to.have.property('cancel'); + expect(bouncer).toHaveProperty('cancel'); + expect(bouncerFromProvider).toHaveProperty('cancel'); }); describe('delayed execution', function() { diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/debounce/index.js b/src/plugins/discover/public/application/angular/directives/debounce/index.js similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/debounce/index.js rename to src/plugins/discover/public/application/angular/directives/debounce/index.js diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/fixed_scroll.js b/src/plugins/discover/public/application/angular/directives/fixed_scroll.js similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/fixed_scroll.js rename to src/plugins/discover/public/application/angular/directives/fixed_scroll.js diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/histogram.tsx b/src/plugins/discover/public/application/angular/directives/histogram.tsx similarity index 97% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/histogram.tsx rename to src/plugins/discover/public/application/angular/directives/histogram.tsx index 8c55622e4c6041..d856be58958f16 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/histogram.tsx +++ b/src/plugins/discover/public/application/angular/directives/histogram.tsx @@ -39,6 +39,7 @@ import { TooltipType, ElementClickListener, XYChartElementEvent, + BrushEndListener, } from '@elastic/charts'; import { i18n } from '@kbn/i18n'; @@ -143,13 +144,12 @@ export class DiscoverHistogram extends Component { - const range = { - from: min, - to: max, - }; - - this.props.timefilterUpdateHandler(range); + public onBrushEnd: BrushEndListener = ({ x }) => { + if (!x) { + return; + } + const [from, to] = x; + this.props.timefilterUpdateHandler({ from, to }); }; public onElementClick = (xInterval: number): ElementClickListener => ([elementData]) => { @@ -175,7 +175,7 @@ export class DiscoverHistogram extends Component

@@ -114,14 +114,14 @@ export class DiscoverNoResults extends Component {

@@ -155,7 +155,7 @@ export class DiscoverNoResults extends Component { @@ -168,7 +168,7 @@ export class DiscoverNoResults extends Component { @@ -181,7 +181,7 @@ export class DiscoverNoResults extends Component { @@ -194,7 +194,7 @@ export class DiscoverNoResults extends Component { @@ -210,14 +210,14 @@ export class DiscoverNoResults extends Component {

@@ -256,7 +256,7 @@ export class DiscoverNoResults extends Component { } diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/no_results.test.js b/src/plugins/discover/public/application/angular/directives/no_results.test.js similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/no_results.test.js rename to src/plugins/discover/public/application/angular/directives/no_results.test.js diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/render_complete.ts b/src/plugins/discover/public/application/angular/directives/render_complete.ts similarity index 92% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/render_complete.ts rename to src/plugins/discover/public/application/angular/directives/render_complete.ts index 7757deb806a18e..635cf68f12fcbb 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/render_complete.ts +++ b/src/plugins/discover/public/application/angular/directives/render_complete.ts @@ -17,7 +17,7 @@ * under the License. */ import { IScope } from 'angular'; -import { RenderCompleteHelper } from '../../../../../../../../plugins/kibana_utils/public'; +import { RenderCompleteHelper } from '../../../../../kibana_utils/public'; export function createRenderCompleteDirective() { return { diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/uninitialized.tsx b/src/plugins/discover/public/application/angular/directives/uninitialized.tsx similarity index 92% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/uninitialized.tsx rename to src/plugins/discover/public/application/angular/directives/uninitialized.tsx index b308607bbfbb07..d04aea09331159 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/directives/uninitialized.tsx +++ b/src/plugins/discover/public/application/angular/directives/uninitialized.tsx @@ -37,7 +37,7 @@ export const DiscoverUninitialized = ({ onRefresh }: Props) => { title={

@@ -45,7 +45,7 @@ export const DiscoverUninitialized = ({ onRefresh }: Props) => { body={

@@ -53,7 +53,7 @@ export const DiscoverUninitialized = ({ onRefresh }: Props) => { actions={ diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover.html b/src/plugins/discover/public/application/angular/discover.html similarity index 89% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover.html rename to src/plugins/discover/public/application/angular/discover.html index 1221b01657e45f..b4db89b9275b46 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover.html +++ b/src/plugins/discover/public/application/angular/discover.html @@ -61,7 +61,7 @@

{{screenTitle}}

@@ -83,7 +83,7 @@

{{screenTitle}}

@@ -93,7 +93,7 @@

{{screenTitle}}

{{(hits || 0) | number:0}} @@ -104,12 +104,12 @@

{{screenTitle}}

id="reload_saved_search" ng-click="resetQuery()" > - {{::'kbn.discover.reloadSavedSearchButton' | i18n: {defaultMessage: 'Reset search'} }} + {{::'discover.reloadSavedSearchButton' | i18n: {defaultMessage: 'Reset search'} }}
@@ -117,7 +117,7 @@

{{screenTitle}}

@@ -141,7 +141,7 @@

{{screenTitle}}

> {{screenTitle}} >

{{screenTitle}} class="dscTable__footer" > {{screenTitle}}
diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover.js b/src/plugins/discover/public/application/angular/discover.js similarity index 93% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover.js rename to src/plugins/discover/public/application/angular/discover.js index c1de704d1c00a6..2afd0322f87014 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover.js +++ b/src/plugins/discover/public/application/angular/discover.js @@ -26,11 +26,8 @@ import dateMath from '@elastic/datemath'; import { i18n } from '@kbn/i18n'; import { getState, splitState } from './discover_state'; -import { RequestAdapter } from '../../../../../../../plugins/inspector/public'; -import { - SavedObjectSaveModal, - showSaveModal, -} from '../../../../../../../plugins/saved_objects/public'; +import { RequestAdapter } from '../../../../inspector/public'; +import { SavedObjectSaveModal, showSaveModal } from '../../../../saved_objects/public'; import { getSortArray, getSortForSearchSource } from './doc_table'; import * as columnActions from './doc_table/actions/columns'; @@ -75,9 +72,9 @@ import { syncQueryStateWithUrl, getDefaultQuery, search, -} from '../../../../../../../plugins/data/public'; +} from '../../../../data/public'; import { getIndexPatternId } from '../helpers/get_index_pattern_id'; -import { addFatalError } from '../../../../../../../plugins/kibana_legacy/public'; +import { addFatalError } from '../../../../kibana_legacy/public'; const fetchStatuses = { UNINITIALIZED: 'uninitialized', @@ -99,10 +96,10 @@ app.config($routeProvider => { } return { - text: i18n.translate('kbn.discover.badge.readOnly.text', { + text: i18n.translate('discover.badge.readOnly.text', { defaultMessage: 'Read only', }), - tooltip: i18n.translate('kbn.discover.badge.readOnly.tooltip', { + tooltip: i18n.translate('discover.badge.readOnly.tooltip', { defaultMessage: 'Unable to save searches', }), iconType: 'glasses', @@ -333,10 +330,10 @@ function discoverController( const getTopNavLinks = () => { const newSearch = { id: 'new', - label: i18n.translate('kbn.discover.localMenu.localMenu.newSearchTitle', { + label: i18n.translate('discover.localMenu.localMenu.newSearchTitle', { defaultMessage: 'New', }), - description: i18n.translate('kbn.discover.localMenu.newSearchDescription', { + description: i18n.translate('discover.localMenu.newSearchDescription', { defaultMessage: 'New Search', }), run: function() { @@ -349,10 +346,10 @@ function discoverController( const saveSearch = { id: 'save', - label: i18n.translate('kbn.discover.localMenu.saveTitle', { + label: i18n.translate('discover.localMenu.saveTitle', { defaultMessage: 'Save', }), - description: i18n.translate('kbn.discover.localMenu.saveSearchDescription', { + description: i18n.translate('discover.localMenu.saveSearchDescription', { defaultMessage: 'Save Search', }), testId: 'discoverSaveButton', @@ -389,7 +386,7 @@ function discoverController( title={savedSearch.title} showCopyOnSave={!!savedSearch.id} objectType="search" - description={i18n.translate('kbn.discover.localMenu.saveSaveSearchDescription', { + description={i18n.translate('discover.localMenu.saveSaveSearchDescription', { defaultMessage: 'Save your Discover search so you can use it in visualizations and dashboards', })} @@ -402,10 +399,10 @@ function discoverController( const openSearch = { id: 'open', - label: i18n.translate('kbn.discover.localMenu.openTitle', { + label: i18n.translate('discover.localMenu.openTitle', { defaultMessage: 'Open', }), - description: i18n.translate('kbn.discover.localMenu.openSavedSearchDescription', { + description: i18n.translate('discover.localMenu.openSavedSearchDescription', { defaultMessage: 'Open Saved Search', }), testId: 'discoverOpenButton', @@ -419,10 +416,10 @@ function discoverController( const shareSearch = { id: 'share', - label: i18n.translate('kbn.discover.localMenu.shareTitle', { + label: i18n.translate('discover.localMenu.shareTitle', { defaultMessage: 'Share', }), - description: i18n.translate('kbn.discover.localMenu.shareSearchDescription', { + description: i18n.translate('discover.localMenu.shareSearchDescription', { defaultMessage: 'Share Search', }), testId: 'shareTopNavButton', @@ -446,10 +443,10 @@ function discoverController( const inspectSearch = { id: 'inspect', - label: i18n.translate('kbn.discover.localMenu.inspectTitle', { + label: i18n.translate('discover.localMenu.inspectTitle', { defaultMessage: 'Inspect', }), - description: i18n.translate('kbn.discover.localMenu.openInspectorForSearchDescription', { + description: i18n.translate('discover.localMenu.openInspectorForSearchDescription', { defaultMessage: 'Open Inspector for search', }), testId: 'openInspectorButton', @@ -492,7 +489,7 @@ function discoverController( const pageTitleSuffix = savedSearch.id && savedSearch.title ? `: ${savedSearch.title}` : ''; chrome.docTitle.change(`Discover${pageTitleSuffix}`); - const discoverBreadcrumbsTitle = i18n.translate('kbn.discover.discoverBreadcrumbTitle', { + const discoverBreadcrumbsTitle = i18n.translate('discover.discoverBreadcrumbTitle', { defaultMessage: 'Discover', }); @@ -606,16 +603,16 @@ function discoverController( $scope.state.sort = getSortArray($scope.state.sort, $scope.indexPattern); $scope.getBucketIntervalToolTipText = () => { - return i18n.translate('kbn.discover.bucketIntervalTooltip', { + return 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: $scope.bucketInterval.scale > 1 - ? i18n.translate('kbn.discover.bucketIntervalTooltip.tooLargeBucketsText', { + ? i18n.translate('discover.bucketIntervalTooltip.tooLargeBucketsText', { defaultMessage: 'buckets that are too large', }) - : i18n.translate('kbn.discover.bucketIntervalTooltip.tooManyBucketsText', { + : i18n.translate('discover.bucketIntervalTooltip.tooManyBucketsText', { defaultMessage: 'too many buckets', }), bucketIntervalDescription: $scope.bucketInterval.description, @@ -748,7 +745,7 @@ function discoverController( $scope.$evalAsync(() => { if (id) { toastNotifications.addSuccess({ - title: i18n.translate('kbn.discover.notifications.savedSearchTitle', { + title: i18n.translate('discover.notifications.savedSearchTitle', { defaultMessage: `Search '{savedSearchTitle}' was saved`, values: { savedSearchTitle: savedSearch.title, @@ -769,7 +766,7 @@ function discoverController( return { id }; } catch (saveError) { toastNotifications.addDanger({ - title: i18n.translate('kbn.discover.notifications.notSavedSearchTitle', { + title: i18n.translate('discover.notifications.notSavedSearchTitle', { defaultMessage: `Search '{savedSearchTitle}' was not saved.`, values: { savedSearchTitle: savedSearch.title, @@ -812,7 +809,7 @@ function discoverController( $scope.fetchError = fetchError; } else { toastNotifications.addError(error, { - title: i18n.translate('kbn.discover.errorLoadingData', { + title: i18n.translate('discover.errorLoadingData', { defaultMessage: 'Error loading data', }), toastMessage: error.shortMessage || error.body?.message, @@ -903,10 +900,10 @@ function discoverController( function logInspectorRequest() { inspectorAdapters.requests.reset(); - const title = i18n.translate('kbn.discover.inspectorRequestDataTitle', { + const title = i18n.translate('discover.inspectorRequestDataTitle', { defaultMessage: 'data', }); - const description = i18n.translate('kbn.discover.inspectorRequestDescription', { + const description = i18n.translate('discover.inspectorRequestDescription', { defaultMessage: 'This request queries Elasticsearch to fetch the data for the search.', }); inspectorRequest = inspectorAdapters.requests.start(title, { description }); @@ -1049,7 +1046,7 @@ function discoverController( } function getIndexPatternWarning(index) { - return i18n.translate('kbn.discover.valueIsNotConfiguredIndexPatternIDWarningTitle', { + return i18n.translate('discover.valueIsNotConfiguredIndexPatternIDWarningTitle', { defaultMessage: '{stateVal} is not a configured index pattern ID', values: { stateVal: `"${index}"`, @@ -1076,7 +1073,7 @@ function discoverController( if (ownIndexPattern) { toastNotifications.addWarning({ title: warningTitle, - text: i18n.translate('kbn.discover.showingSavedIndexPatternWarningDescription', { + text: i18n.translate('discover.showingSavedIndexPatternWarningDescription', { defaultMessage: 'Showing the saved index pattern: "{ownIndexPatternTitle}" ({ownIndexPatternId})', values: { @@ -1090,7 +1087,7 @@ function discoverController( toastNotifications.addWarning({ title: warningTitle, - text: i18n.translate('kbn.discover.showingDefaultIndexPatternWarningDescription', { + text: i18n.translate('discover.showingDefaultIndexPatternWarningDescription', { defaultMessage: 'Showing the default index pattern: "{loadedIndexPatternTitle}" ({loadedIndexPatternId})', values: { diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover_state.test.ts b/src/plugins/discover/public/application/angular/discover_state.test.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover_state.test.ts rename to src/plugins/discover/public/application/angular/discover_state.test.ts diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover_state.ts b/src/plugins/discover/public/application/angular/discover_state.ts similarity index 96% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover_state.ts rename to src/plugins/discover/public/application/angular/discover_state.ts index 2a036f0ac60ad3..46500d9fdf85e2 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/discover_state.ts +++ b/src/plugins/discover/public/application/angular/discover_state.ts @@ -24,9 +24,9 @@ import { syncState, ReduxLikeStateContainer, IKbnUrlStateStorage, -} from '../../../../../../../plugins/kibana_utils/public'; -import { esFilters, Filter, Query } from '../../../../../../../plugins/data/public'; -import { migrateLegacyQuery } from '../../../../../../../plugins/kibana_legacy/public'; +} from '../../../../kibana_utils/public'; +import { esFilters, Filter, Query } from '../../../../data/public'; +import { migrateLegacyQuery } from '../../../../kibana_legacy/public'; export interface AppState { /** diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc.html b/src/plugins/discover/public/application/angular/doc.html similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc.html rename to src/plugins/discover/public/application/angular/doc.html diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc.ts b/src/plugins/discover/public/application/angular/doc.ts similarity index 91% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc.ts rename to src/plugins/discover/public/application/angular/doc.ts index 092e3c79b1007c..2d0d45e5003fbd 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc.ts +++ b/src/plugins/discover/public/application/angular/doc.ts @@ -49,7 +49,9 @@ app.config(($routeProvider: any) => { }) // the new route, es 7 deprecated types, es 8 removed them .when('/discover/doc/:indexPattern/:index', { - controller: ($scope: LazyScope, $route: any, es: any) => { + // have to be written as function expression, because it's not compiled in dev mode + // eslint-disable-next-line object-shorthand + controller: function($scope: LazyScope, $route: any, es: any) { timefilter.disableAutoRefreshSelector(); timefilter.disableTimeRangeSelector(); $scope.esClient = es; diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/_doc_table.scss b/src/plugins/discover/public/application/angular/doc_table/_doc_table.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/_doc_table.scss rename to src/plugins/discover/public/application/angular/doc_table/_doc_table.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/_index.scss b/src/plugins/discover/public/application/angular/doc_table/_index.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/_index.scss rename to src/plugins/discover/public/application/angular/doc_table/_index.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/actions/columns.ts b/src/plugins/discover/public/application/angular/doc_table/actions/columns.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/actions/columns.ts rename to src/plugins/discover/public/application/angular/doc_table/actions/columns.ts diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/_index.scss b/src/plugins/discover/public/application/angular/doc_table/components/_index.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/_index.scss rename to src/plugins/discover/public/application/angular/doc_table/components/_index.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/_table_header.scss b/src/plugins/discover/public/application/angular/doc_table/components/_table_header.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/_table_header.scss rename to src/plugins/discover/public/application/angular/doc_table/components/_table_header.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/__snapshots__/tool_bar_pager_buttons.test.tsx.snap b/src/plugins/discover/public/application/angular/doc_table/components/pager/__snapshots__/tool_bar_pager_buttons.test.tsx.snap similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/__snapshots__/tool_bar_pager_buttons.test.tsx.snap rename to src/plugins/discover/public/application/angular/doc_table/components/pager/__snapshots__/tool_bar_pager_buttons.test.tsx.snap diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/__snapshots__/tool_bar_pager_text.test.tsx.snap b/src/plugins/discover/public/application/angular/doc_table/components/pager/__snapshots__/tool_bar_pager_text.test.tsx.snap similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/__snapshots__/tool_bar_pager_text.test.tsx.snap rename to src/plugins/discover/public/application/angular/doc_table/components/pager/__snapshots__/tool_bar_pager_text.test.tsx.snap diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/index.ts b/src/plugins/discover/public/application/angular/doc_table/components/pager/index.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/index.ts rename to src/plugins/discover/public/application/angular/doc_table/components/pager/index.ts diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/tool_bar_pager_buttons.test.tsx b/src/plugins/discover/public/application/angular/doc_table/components/pager/tool_bar_pager_buttons.test.tsx similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/tool_bar_pager_buttons.test.tsx rename to src/plugins/discover/public/application/angular/doc_table/components/pager/tool_bar_pager_buttons.test.tsx diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/tool_bar_pager_buttons.tsx b/src/plugins/discover/public/application/angular/doc_table/components/pager/tool_bar_pager_buttons.tsx similarity index 92% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/tool_bar_pager_buttons.tsx rename to src/plugins/discover/public/application/angular/doc_table/components/pager/tool_bar_pager_buttons.tsx index 6f1cf81e2c541b..e95153d85b0641 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/tool_bar_pager_buttons.tsx +++ b/src/plugins/discover/public/application/angular/doc_table/components/pager/tool_bar_pager_buttons.tsx @@ -35,7 +35,7 @@ export function ToolBarPagerButtons(props: Props) { disabled={!props.hasPreviousPage} data-test-subj="btnPrevPage" aria-label={i18n.translate( - 'kbn.discover.docTable.pager.toolbarPagerButtons.previousButtonAriaLabel', + 'discover.docTable.pager.toolbarPagerButtons.previousButtonAriaLabel', { defaultMessage: 'Previous page in table', } @@ -49,7 +49,7 @@ export function ToolBarPagerButtons(props: Props) { disabled={!props.hasNextPage} data-test-subj="btnNextPage" aria-label={i18n.translate( - 'kbn.discover.docTable.pager.toolbarPagerButtons.nextButtonAriaLabel', + 'discover.docTable.pager.toolbarPagerButtons.nextButtonAriaLabel', { defaultMessage: 'Next page in table', } diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/tool_bar_pager_text.test.tsx b/src/plugins/discover/public/application/angular/doc_table/components/pager/tool_bar_pager_text.test.tsx similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/tool_bar_pager_text.test.tsx rename to src/plugins/discover/public/application/angular/doc_table/components/pager/tool_bar_pager_text.test.tsx diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/tool_bar_pager_text.tsx b/src/plugins/discover/public/application/angular/doc_table/components/pager/tool_bar_pager_text.tsx similarity index 95% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/tool_bar_pager_text.tsx rename to src/plugins/discover/public/application/angular/doc_table/components/pager/tool_bar_pager_text.tsx index 84338d817c86b5..46e3cd9511eb59 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/pager/tool_bar_pager_text.tsx +++ b/src/plugins/discover/public/application/angular/doc_table/components/pager/tool_bar_pager_text.tsx @@ -30,7 +30,7 @@ export function ToolBarPagerText({ startItem, endItem, totalItems }: Props) {
diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_header.ts b/src/plugins/discover/public/application/angular/doc_table/components/table_header.ts similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_header.ts rename to src/plugins/discover/public/application/angular/doc_table/components/table_header.ts diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_header/__snapshots__/table_header.test.tsx.snap b/src/plugins/discover/public/application/angular/doc_table/components/table_header/__snapshots__/table_header.test.tsx.snap similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_header/__snapshots__/table_header.test.tsx.snap rename to src/plugins/discover/public/application/angular/doc_table/components/table_header/__snapshots__/table_header.test.tsx.snap diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_header/helpers.tsx b/src/plugins/discover/public/application/angular/doc_table/components/table_header/helpers.tsx similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_header/helpers.tsx rename to src/plugins/discover/public/application/angular/doc_table/components/table_header/helpers.tsx diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_header/table_header.test.tsx b/src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header.test.tsx similarity index 99% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_header/table_header.test.tsx rename to src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header.test.tsx index 89f73022627c50..b201bea26503ea 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_header/table_header.test.tsx +++ b/src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header.test.tsx @@ -25,8 +25,6 @@ import { findTestSubject } from '@elastic/eui/lib/test'; import { SortOrder } from './helpers'; import { IndexPattern, IFieldType } from '../../../../../kibana_services'; -jest.mock('ui/new_platform'); - function getMockIndexPattern() { return ({ id: 'test', diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_header/table_header.tsx b/src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header.tsx similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_header/table_header.tsx rename to src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header.tsx diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_header/table_header_column.tsx b/src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header_column.tsx similarity index 88% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_header/table_header_column.tsx rename to src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header_column.tsx index d1a9a5146fb8a5..4c09ff8701f30a 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_header/table_header_column.tsx +++ b/src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header_column.tsx @@ -80,21 +80,21 @@ export function TableHeaderColumn({ const getSortButtonAriaLabel = () => { const sortAscendingMessage = i18n.translate( - 'kbn.docTable.tableHeader.sortByColumnAscendingAriaLabel', + 'discover.docTable.tableHeader.sortByColumnAscendingAriaLabel', { defaultMessage: 'Sort {columnName} ascending', values: { columnName: name }, } ); const sortDescendingMessage = i18n.translate( - 'kbn.docTable.tableHeader.sortByColumnDescendingAriaLabel', + 'discover.docTable.tableHeader.sortByColumnDescendingAriaLabel', { defaultMessage: 'Sort {columnName} descending', values: { columnName: name }, } ); const stopSortingMessage = i18n.translate( - 'kbn.docTable.tableHeader.sortByColumnUnsortedAriaLabel', + 'discover.docTable.tableHeader.sortByColumnUnsortedAriaLabel', { defaultMessage: 'Stop sorting on {columnName}', values: { columnName: name }, @@ -126,42 +126,42 @@ export function TableHeaderColumn({ // Remove Button { active: isRemoveable && typeof onRemoveColumn === 'function', - ariaLabel: i18n.translate('kbn.docTable.tableHeader.removeColumnButtonAriaLabel', { + ariaLabel: i18n.translate('discover.docTable.tableHeader.removeColumnButtonAriaLabel', { defaultMessage: 'Remove {columnName} column', values: { columnName: name }, }), className: 'fa fa-remove kbnDocTableHeader__move', onClick: () => onRemoveColumn && onRemoveColumn(name), testSubject: `docTableRemoveHeader-${name}`, - tooltip: i18n.translate('kbn.docTable.tableHeader.removeColumnButtonTooltip', { + tooltip: i18n.translate('discover.docTable.tableHeader.removeColumnButtonTooltip', { defaultMessage: 'Remove Column', }), }, // Move Left Button { active: colLeftIdx >= 0 && typeof onMoveColumn === 'function', - ariaLabel: i18n.translate('kbn.docTable.tableHeader.moveColumnLeftButtonAriaLabel', { + ariaLabel: i18n.translate('discover.docTable.tableHeader.moveColumnLeftButtonAriaLabel', { defaultMessage: 'Move {columnName} column to the left', values: { columnName: name }, }), className: 'fa fa-angle-double-left kbnDocTableHeader__move', onClick: () => onMoveColumn && onMoveColumn(name, colLeftIdx), testSubject: `docTableMoveLeftHeader-${name}`, - tooltip: i18n.translate('kbn.docTable.tableHeader.moveColumnLeftButtonTooltip', { + tooltip: i18n.translate('discover.docTable.tableHeader.moveColumnLeftButtonTooltip', { defaultMessage: 'Move column to the left', }), }, // Move Right Button { active: colRightIdx >= 0 && typeof onMoveColumn === 'function', - ariaLabel: i18n.translate('kbn.docTable.tableHeader.moveColumnRightButtonAriaLabel', { + ariaLabel: i18n.translate('discover.docTable.tableHeader.moveColumnRightButtonAriaLabel', { defaultMessage: 'Move {columnName} column to the right', values: { columnName: name }, }), className: 'fa fa-angle-double-right kbnDocTableHeader__move', onClick: () => onMoveColumn && onMoveColumn(name, colRightIdx), testSubject: `docTableMoveRightHeader-${name}`, - tooltip: i18n.translate('kbn.docTable.tableHeader.moveColumnRightButtonTooltip', { + tooltip: i18n.translate('discover.docTable.tableHeader.moveColumnRightButtonTooltip', { defaultMessage: 'Move column to the right', }), }, diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row.ts b/src/plugins/discover/public/application/angular/doc_table/components/table_row.ts similarity index 96% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row.ts rename to src/plugins/discover/public/application/angular/doc_table/components/table_row.ts index 698bfe7416d420..3b48c4c79365e2 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row.ts +++ b/src/plugins/discover/public/application/angular/doc_table/components/table_row.ts @@ -23,15 +23,15 @@ import $ from 'jquery'; import rison from 'rison-node'; import '../../doc_viewer'; // @ts-ignore -import { noWhiteSpace } from '../../../../../../common/utils/no_white_space'; +import { noWhiteSpace } from '../../../../../../../legacy/core_plugins/kibana/common/utils/no_white_space'; import openRowHtml from './table_row/open.html'; import detailsHtml from './table_row/details.html'; -import { dispatchRenderComplete } from '../../../../../../../../../plugins/kibana_utils/public'; +import { dispatchRenderComplete } from '../../../../../../kibana_utils/public'; import cellTemplateHtml from '../components/table_row/cell.html'; import truncateByHeightTemplateHtml from '../components/table_row/truncate_by_height.html'; -import { esFilters } from '../../../../../../../../../plugins/data/public'; +import { esFilters } from '../../../../../../data/public'; import { getServices } from '../../../../kibana_services'; // guesstimate at the minimum number of chars wide cells in the table should be diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/_cell.scss b/src/plugins/discover/public/application/angular/doc_table/components/table_row/_cell.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/_cell.scss rename to src/plugins/discover/public/application/angular/doc_table/components/table_row/_cell.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/_details.scss b/src/plugins/discover/public/application/angular/doc_table/components/table_row/_details.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/_details.scss rename to src/plugins/discover/public/application/angular/doc_table/components/table_row/_details.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/_index.scss b/src/plugins/discover/public/application/angular/doc_table/components/table_row/_index.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/_index.scss rename to src/plugins/discover/public/application/angular/doc_table/components/table_row/_index.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/_open.scss b/src/plugins/discover/public/application/angular/doc_table/components/table_row/_open.scss similarity index 100% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/_open.scss rename to src/plugins/discover/public/application/angular/doc_table/components/table_row/_open.scss diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/cell.html b/src/plugins/discover/public/application/angular/doc_table/components/table_row/cell.html similarity index 66% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/cell.html rename to src/plugins/discover/public/application/angular/doc_table/components/table_row/cell.html index 0704016a52bbdd..e8c4fceeca7ffd 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/cell.html +++ b/src/plugins/discover/public/application/angular/doc_table/components/table_row/cell.html @@ -18,17 +18,17 @@ data-column="<%- column %>" tooltip-append-to-body="1" data-test-subj="docTableCellFilter" - tooltip="{{ ::'kbn.docTable.tableRow.filterForValueButtonTooltip' | i18n: {defaultMessage: 'Filter for value'} }}" + tooltip="{{ ::'discover.docTable.tableRow.filterForValueButtonTooltip' | i18n: {defaultMessage: 'Filter for value'} }}" tooltip-placement="bottom" - aria-label="{{ ::'kbn.docTable.tableRow.filterForValueButtonAriaLabel' | i18n: {defaultMessage: 'Filter for value'} }}" + aria-label="{{ ::'discover.docTable.tableRow.filterForValueButtonAriaLabel' | i18n: {defaultMessage: 'Filter for value'} }}" > diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/details.html b/src/plugins/discover/public/application/angular/doc_table/components/table_row/details.html similarity index 89% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/details.html rename to src/plugins/discover/public/application/angular/doc_table/components/table_row/details.html index d149a9023816a8..37ae08246d1d3f 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/details.html +++ b/src/plugins/discover/public/application/angular/doc_table/components/table_row/details.html @@ -8,7 +8,7 @@

@@ -22,7 +22,7 @@ data-test-subj="docTableRowAction" ng-href="{{ getContextAppHref() }}" ng-if="indexPattern.isTimeBased()" - i18n-id="kbn.docTable.tableRow.viewSurroundingDocumentsLinkText" + i18n-id="discover.docTable.tableRow.viewSurroundingDocumentsLinkText" i18n-default-message="View surrounding documents" >
@@ -31,7 +31,7 @@ class="euiLink" data-test-subj="docTableRowAction" ng-href="#/discover/doc/{{indexPattern.id}}/{{row._index}}?id={{uriEncodedId}}" - i18n-id="kbn.docTable.tableRow.viewSingleDocumentLinkText" + i18n-id="discover.docTable.tableRow.viewSingleDocumentLinkText" i18n-default-message="View single document" > diff --git a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/open.html b/src/plugins/discover/public/application/angular/doc_table/components/table_row/open.html similarity index 72% rename from src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/open.html rename to src/plugins/discover/public/application/angular/doc_table/components/table_row/open.html index d6c4b858d2b476..6a14b6fc703489 100644 --- a/src/legacy/core_plugins/kibana/public/discover/np_ready/angular/doc_table/components/table_row/open.html +++ b/src/plugins/discover/public/application/angular/doc_table/components/table_row/open.html @@ -2,7 +2,7 @@ + + +`; + +exports[`DownNoExpressionSelect component should shallow renders against props 1`] = ` + + } + data-test-subj="xpack.uptime.alerts.monitorStatus.numTimesExpression" + description="matching monitors are down >" + id="ping-count" + value="5 times" +/> +`; diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/__tests__/__snapshots__/time_expression_select.test.tsx.snap b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/__tests__/__snapshots__/time_expression_select.test.tsx.snap new file mode 100644 index 00000000000000..cbbaccbab34e4e --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/__tests__/__snapshots__/time_expression_select.test.tsx.snap @@ -0,0 +1,160 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`TimeExpressionSelect component should renders against props 1`] = ` +
+
+
+
+ +
+
+
+
+
+
+ +
+
+
+
+`; + +exports[`TimeExpressionSelect component should shallow renders against props 1`] = ` + + + + } + data-test-subj="xpack.uptime.alerts.monitorStatus.timerangeValueExpression" + description="within" + id="timerange" + value="last 15" + /> + + + + +
+ +
+
+ + [Function] + + + } + data-test-subj="xpack.uptime.alerts.monitorStatus.timerangeUnitExpression" + description="" + id="timerange-unit" + value="minutes" + /> +
+
+`; diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/__tests__/down_number_select.test.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/__tests__/down_number_select.test.tsx new file mode 100644 index 00000000000000..13db9f2f809094 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/__tests__/down_number_select.test.tsx @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { renderWithIntl, shallowWithIntl } from 'test_utils/enzyme_helpers'; +import { DownNoExpressionSelect } from '../down_number_select'; + +describe('DownNoExpressionSelect component', () => { + const filters = + '"{"bool":{"filter":[{"bool":{"should":[{"match":{"observer.geo.name":"US-West"}}],"minimum_should_match":1}},' + + '{"bool":{"should":[{"match":{"url.port":443}}],"minimum_should_match":1}}]}}"'; + + it('should shallow renders against props', function() { + const component = shallowWithIntl( + + ); + expect(component).toMatchSnapshot(); + }); + + it('should renders against props', function() { + const component = renderWithIntl( + + ); + expect(component).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/__tests__/time_expression_select.test.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/__tests__/time_expression_select.test.tsx new file mode 100644 index 00000000000000..37df7dfdaaec1c --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/__tests__/time_expression_select.test.tsx @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { renderWithIntl, shallowWithIntl } from 'test_utils/enzyme_helpers'; +import { TimeExpressionSelect } from '../time_expression_select'; + +describe('TimeExpressionSelect component', () => { + it('should shallow renders against props', function() { + const component = shallowWithIntl(); + expect(component).toMatchSnapshot(); + }); + + it('should renders against props', function() { + const component = renderWithIntl(); + expect(component).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/down_number_select.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/down_number_select.tsx new file mode 100644 index 00000000000000..7f68aef8e179c4 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/down_number_select.tsx @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useEffect, useState } from 'react'; +import { AlertExpressionPopover } from '../alert_expression_popover'; +import * as labels from '../translations'; +import { AlertFieldNumber } from '../alert_field_number'; + +interface Props { + setAlertParams: (key: string, value: any) => void; + filters: string; +} + +export const DownNoExpressionSelect: React.FC = ({ filters, setAlertParams }) => { + const [numTimes, setNumTimes] = useState(5); + + useEffect(() => { + setAlertParams('numTimes', numTimes); + }, [numTimes, setAlertParams]); + + return ( + + } + data-test-subj="xpack.uptime.alerts.monitorStatus.numTimesExpression" + description={filters ? labels.MATCHING_MONITORS_DOWN : labels.ANY_MONITOR_DOWN} + id="ping-count" + value={`${numTimes} times`} + /> + ); +}; diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/filters_expression_select.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/filters_expression_select.tsx new file mode 100644 index 00000000000000..8298f202b94584 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/filters_expression_select.tsx @@ -0,0 +1,163 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useEffect, useState } from 'react'; +import { useSelector } from 'react-redux'; +import { EuiButtonIcon, EuiExpression, EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui'; +import { FilterPopover } from '../../filter_group/filter_popover'; +import { overviewFiltersSelector } from '../../../../state/selectors'; +import { useFilterUpdate } from '../../../../hooks/use_filter_update'; +import { filterLabels } from '../../filter_group/translations'; +import { alertFilterLabels } from './translations'; + +interface Props { + newFilters: string[]; + onRemoveFilter: (val: string) => void; + setAlertParams: (key: string, value: any) => void; +} + +export const FiltersExpressionsSelect: React.FC = ({ + setAlertParams, + newFilters, + onRemoveFilter, +}) => { + const { tags, ports, schemes, locations } = useSelector(overviewFiltersSelector); + + const [updatedFieldValues, setUpdatedFieldValues] = useState<{ + fieldName: string; + values: string[]; + }>({ fieldName: '', values: [] }); + + const currentFilters = useFilterUpdate(updatedFieldValues.fieldName, updatedFieldValues.values); + + useEffect(() => { + if (updatedFieldValues.fieldName === 'observer.geo.name') { + setAlertParams('locations', updatedFieldValues.values); + } + }, [setAlertParams, updatedFieldValues]); + + useEffect(() => { + setAlertParams('locations', []); + + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + const selectedTags = currentFilters.get('tags'); + const selectedPorts = currentFilters.get('url.port'); + const selectedScheme = currentFilters.get('monitor.type'); + const selectedLocation = currentFilters.get('observer.geo.name'); + + const getSelectedItems = (fieldName: string) => currentFilters.get(fieldName) || []; + + const onFilterFieldChange = (fieldName: string, values: string[]) => { + setUpdatedFieldValues({ fieldName, values }); + }; + + const monitorFilters = [ + { + onFilterFieldChange, + loading: false, + fieldName: 'url.port', + id: 'filter_port', + disabled: ports?.length === 0, + items: ports?.map((p: number) => p.toString()) ?? [], + selectedItems: getSelectedItems('url.port'), + title: filterLabels.PORT, + description: selectedPorts ? alertFilterLabels.USING_PORT : alertFilterLabels.USING, + value: selectedPorts?.join(',') ?? alertFilterLabels.ANY_PORT, + }, + { + onFilterFieldChange, + loading: false, + fieldName: 'tags', + id: 'filter_tags', + disabled: tags?.length === 0, + items: tags ?? [], + selectedItems: getSelectedItems('tags'), + title: filterLabels.TAGS, + description: selectedTags ? alertFilterLabels.WITH_TAG : alertFilterLabels.WITH, + value: selectedTags?.join(',') ?? alertFilterLabels.ANY_TAG, + }, + { + onFilterFieldChange, + loading: false, + fieldName: 'monitor.type', + id: 'filter_scheme', + disabled: schemes?.length === 0, + items: schemes ?? [], + selectedItems: getSelectedItems('monitor.type'), + title: filterLabels.SCHEME, + description: selectedScheme ? alertFilterLabels.OF_TYPE : alertFilterLabels.OF, + value: selectedScheme?.join(',') ?? alertFilterLabels.ANY_TYPE, + }, + { + onFilterFieldChange, + loading: false, + fieldName: 'observer.geo.name', + id: 'filter_location', + disabled: locations?.length === 0, + items: locations ?? [], + selectedItems: getSelectedItems('observer.geo.name'), + title: filterLabels.SCHEME, + description: selectedLocation ? alertFilterLabels.FROM_LOCATION : alertFilterLabels.FROM, + value: selectedLocation?.join(',') ?? alertFilterLabels.ANY_LOCATION, + }, + ]; + + const [isOpen, setIsOpen] = useState({ + filter_port: false, + filter_tags: false, + filter_scheme: false, + filter_location: false, + }); + + const filtersToDisplay = monitorFilters.filter( + curr => curr.selectedItems.length > 0 || newFilters?.includes(curr.fieldName) + ); + + return ( + <> + {filtersToDisplay.map(({ description, value, ...item }) => ( + + + setIsOpen({ ...isOpen, [item.id]: !isOpen[item.id] })} + /> + } + forceOpen={isOpen[item.id]} + setForceOpen={() => { + setIsOpen({ ...isOpen, [item.id]: !isOpen[item.id] }); + }} + /> + + + { + onRemoveFilter(item.fieldName); + onFilterFieldChange(item.fieldName, []); + }} + /> + + + + + ))} + + + + ); +}; diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/index.ts b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/index.ts new file mode 100644 index 00000000000000..acc19dfbc8f8b5 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/index.ts @@ -0,0 +1,9 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export { DownNoExpressionSelect } from './down_number_select'; +export { FiltersExpressionsSelect } from './filters_expression_select'; +export { TimeExpressionSelect } from './time_expression_select'; diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/time_expression_select.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/time_expression_select.tsx new file mode 100644 index 00000000000000..8cab4315967d36 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/time_expression_select.tsx @@ -0,0 +1,118 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useEffect, useState } from 'react'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiFlexGroup, EuiFlexItem, EuiSelectable, EuiTitle } from '@elastic/eui'; +import { AlertExpressionPopover } from '../alert_expression_popover'; +import * as labels from '../translations'; +import { AlertFieldNumber } from '../alert_field_number'; +import { timeExpLabels } from './translations'; + +interface Props { + setAlertParams: (key: string, value: any) => void; +} + +const TimeRangeOptions = [ + { + 'aria-label': labels.SECONDS_TIME_RANGE, + 'data-test-subj': 'xpack.uptime.alerts.monitorStatus.timerangeUnitSelectable.secondsOption', + key: 's', + label: labels.SECONDS, + }, + { + 'aria-label': labels.MINUTES_TIME_RANGE, + 'data-test-subj': 'xpack.uptime.alerts.monitorStatus.timerangeUnitSelectable.minutesOption', + checked: 'on', + key: 'm', + label: labels.MINUTES, + }, + { + 'aria-label': labels.HOURS_TIME_RANGE, + 'data-test-subj': 'xpack.uptime.alerts.monitorStatus.timerangeUnitSelectable.hoursOption', + key: 'h', + label: labels.HOURS, + }, + { + 'aria-label': labels.DAYS_TIME_RANGE, + 'data-test-subj': 'xpack.uptime.alerts.monitorStatus.timerangeUnitSelectable.daysOption', + key: 'd', + label: labels.DAYS, + }, +]; + +export const TimeExpressionSelect: React.FC = ({ setAlertParams }) => { + const [numUnits, setNumUnits] = useState(15); + + const [timerangeUnitOptions, setTimerangeUnitOptions] = useState(TimeRangeOptions); + + useEffect(() => { + const timerangeUnit = timerangeUnitOptions.find(({ checked }) => checked === 'on')?.key ?? 'm'; + setAlertParams('timerange', { from: `now-${numUnits}${timerangeUnit}`, to: 'now' }); + }, [numUnits, timerangeUnitOptions, setAlertParams]); + + return ( + + + + } + data-test-subj="xpack.uptime.alerts.monitorStatus.timerangeValueExpression" + description="within" + id="timerange" + value={`last ${numUnits}`} + /> + + + + +
+ +
+
+ { + if (newOptions.reduce((acc, { checked }) => acc || checked === 'on', false)) { + setTimerangeUnitOptions(newOptions); + } + }} + singleSelection={true} + listProps={{ + showIcons: true, + }} + > + {list => list} + + + } + data-test-subj="xpack.uptime.alerts.monitorStatus.timerangeUnitExpression" + description="" + id="timerange-unit" + value={ + timerangeUnitOptions.find(({ checked }) => checked === 'on')?.label.toLowerCase() ?? '' + } + /> +
+
+ ); +}; diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/translations.ts b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/translations.ts new file mode 100644 index 00000000000000..5fefc9f3ae35b5 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/alerts/monitor_expressions/translations.ts @@ -0,0 +1,72 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; + +export const alertFilterLabels = { + USING: i18n.translate('xpack.uptime.alerts.monitorStatus.filters.using', { + defaultMessage: 'Using', + }), + + USING_PORT: i18n.translate('xpack.uptime.alerts.monitorStatus.filters.usingPort', { + defaultMessage: 'Using port', + }), + + ANY_PORT: i18n.translate('xpack.uptime.alerts.monitorStatus.filters.anyPort', { + defaultMessage: 'any port', + }), + + WITH: i18n.translate('xpack.uptime.alerts.monitorStatus.filters.with', { + defaultMessage: 'Using', + }), + + WITH_TAG: i18n.translate('xpack.uptime.alerts.monitorStatus.filters.withTag', { + defaultMessage: 'With tag', + }), + + ANY_TAG: i18n.translate('xpack.uptime.alerts.monitorStatus.filters.anyTag', { + defaultMessage: 'any tag', + }), + + OF: i18n.translate('xpack.uptime.alerts.monitorStatus.filters.of', { + defaultMessage: 'Of', + }), + + OF_TYPE: i18n.translate('xpack.uptime.alerts.monitorStatus.filters.ofType', { + defaultMessage: 'Of type', + }), + + ANY_TYPE: i18n.translate('xpack.uptime.alerts.monitorStatus.filters.anyType', { + defaultMessage: 'any type', + }), + + FROM: i18n.translate('xpack.uptime.alerts.monitorStatus.filters.from', { + defaultMessage: 'From', + }), + + FROM_LOCATION: i18n.translate('xpack.uptime.alerts.monitorStatus.filters.fromLocation', { + defaultMessage: 'From location', + }), + + ANY_LOCATION: i18n.translate('xpack.uptime.alerts.monitorStatus.filters.anyLocation', { + defaultMessage: 'any location', + }), +}; + +export const timeExpLabels = { + OPEN_TIME_POPOVER: i18n.translate( + 'xpack.uptime.alerts.monitorStatus.timerangeUnitExpression.ariaLabel', + { + defaultMessage: 'Open the popover for time range unit select field', + } + ), + SELECT_TIME_RANGE_ARIA: i18n.translate( + 'xpack.uptime.alerts.monitorStatus.timerangeUnitSelectable', + { + defaultMessage: 'Selectable field for the time range units alerts should use', + } + ), +}; diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/settings_message_expression_popover.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/settings_message_expression_popover.tsx new file mode 100644 index 00000000000000..8d9de08751eeef --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/alerts/settings_message_expression_popover.tsx @@ -0,0 +1,72 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiExpression, EuiPopover } from '@elastic/eui'; +import { Link } from 'react-router-dom'; +import React, { useState } from 'react'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { SETTINGS_ROUTE } from '../../../../common/constants'; + +interface SettingsMessageExpressionPopoverProps { + 'aria-label': string; + description: string; + id: string; + setAlertFlyoutVisible: (value: boolean) => void; + value: string; +} + +export const SettingsMessageExpressionPopover: React.FC = ({ + 'aria-label': ariaLabel, + description, + setAlertFlyoutVisible, + value, + id, +}) => { + const [isOpen, setIsOpen] = useState(false); + return ( + setIsOpen(!isOpen)} + value={value} + /> + } + isOpen={isOpen} + closePopover={() => setIsOpen(false)} + > + + { + setAlertFlyoutVisible(false); + }} + onKeyUp={e => { + if (e.key === 'Enter') { + setAlertFlyoutVisible(false); + } + }} + > + settings page + + + ), + }} + /> + + ); +}; diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/toggle_alert_flyout_button.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/toggle_alert_flyout_button.tsx index 92fc015a276d3f..cba96cd2fe5b12 100644 --- a/x-pack/plugins/uptime/public/components/overview/alerts/toggle_alert_flyout_button.tsx +++ b/x-pack/plugins/uptime/public/components/overview/alerts/toggle_alert_flyout_button.tsx @@ -4,27 +4,128 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiButtonEmpty, EuiContextMenuItem, EuiContextMenuPanel, EuiPopover } from '@elastic/eui'; +import { + EuiButtonEmpty, + EuiContextMenu, + EuiContextMenuPanelDescriptor, + EuiContextMenuPanelItemDescriptor, + EuiLink, + EuiPopover, +} from '@elastic/eui'; import React, { useState } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; -import { i18n } from '@kbn/i18n'; import { useKibana } from '../../../../../../../src/plugins/kibana_react/public'; +import { CLIENT_ALERT_TYPES } from '../../../../common/constants'; +import { ToggleFlyoutTranslations } from './translations'; +import { ToggleAlertFlyoutButtonProps } from './alerts_containers'; -interface Props { - setAlertFlyoutVisible: (value: boolean) => void; +interface ComponentProps { + setAlertFlyoutVisible: (value: boolean | string) => void; } -export const ToggleAlertFlyoutButtonComponent = ({ setAlertFlyoutVisible }: Props) => { +type Props = ComponentProps & ToggleAlertFlyoutButtonProps; + +const ALERT_CONTEXT_MAIN_PANEL_ID = 0; +const ALERT_CONTEXT_SELECT_TYPE_PANEL_ID = 1; + +export const ToggleAlertFlyoutButtonComponent: React.FC = ({ + alertOptions, + setAlertFlyoutVisible, +}) => { const [isOpen, setIsOpen] = useState(false); const kibana = useKibana(); + const monitorStatusAlertContextMenuItem: EuiContextMenuPanelItemDescriptor = { + 'aria-label': ToggleFlyoutTranslations.toggleMonitorStatusAriaLabel, + 'data-test-subj': 'xpack.uptime.toggleAlertFlyout', + name: ToggleFlyoutTranslations.toggleMonitorStatusContent, + onClick: () => { + setAlertFlyoutVisible(CLIENT_ALERT_TYPES.MONITOR_STATUS); + setIsOpen(false); + }, + }; + + const tlsAlertContextMenuItem: EuiContextMenuPanelItemDescriptor = { + 'aria-label': ToggleFlyoutTranslations.toggleTlsAriaLabel, + 'data-test-subj': 'xpack.uptime.toggleTlsAlertFlyout', + name: ToggleFlyoutTranslations.toggleTlsContent, + onClick: () => { + setAlertFlyoutVisible(CLIENT_ALERT_TYPES.TLS); + setIsOpen(false); + }, + }; + + const managementContextItem: EuiContextMenuPanelItemDescriptor = { + 'aria-label': ToggleFlyoutTranslations.navigateToAlertingUIAriaLabel, + 'data-test-subj': 'xpack.uptime.navigateToAlertingUi', + name: ( + + + + ), + icon: 'tableOfContents', + }; + + let selectionItems: EuiContextMenuPanelItemDescriptor[] = []; + if (!alertOptions) { + selectionItems = [monitorStatusAlertContextMenuItem, tlsAlertContextMenuItem]; + } else { + alertOptions.forEach(option => { + if (option === CLIENT_ALERT_TYPES.MONITOR_STATUS) + selectionItems.push(monitorStatusAlertContextMenuItem); + else if (option === CLIENT_ALERT_TYPES.TLS) selectionItems.push(tlsAlertContextMenuItem); + }); + } + + if (selectionItems.length === 1) { + selectionItems[0].icon = 'bell'; + } + + let panels: EuiContextMenuPanelDescriptor[]; + if (selectionItems.length === 1) { + panels = [ + { + id: ALERT_CONTEXT_MAIN_PANEL_ID, + title: 'main panel', + items: [...selectionItems, managementContextItem], + }, + ]; + } else { + panels = [ + { + id: ALERT_CONTEXT_MAIN_PANEL_ID, + title: 'main panel', + items: [ + { + 'aria-label': ToggleFlyoutTranslations.openAlertContextPanelAriaLabel, + 'data-test-subj': 'xpack.uptime.openAlertContextPanel', + name: ToggleFlyoutTranslations.openAlertContextPanelLabel, + icon: 'bell', + panel: ALERT_CONTEXT_SELECT_TYPE_PANEL_ID, + }, + managementContextItem, + ], + }, + { + id: ALERT_CONTEXT_SELECT_TYPE_PANEL_ID, + title: 'create alerts', + items: selectionItems, + }, + ]; + } return ( - { - setAlertFlyoutVisible(true); - setIsOpen(false); - }} - > - - , - - - , - ]} - /> + ); }; diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/translations.ts b/x-pack/plugins/uptime/public/components/overview/alerts/translations.ts new file mode 100644 index 00000000000000..637fe0a108958b --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/alerts/translations.ts @@ -0,0 +1,192 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; + +export const SECONDS_TIME_RANGE = i18n.translate( + 'xpack.uptime.alerts.timerangeUnitSelectable.secondsOption.ariaLabel', + { + defaultMessage: '"Seconds" time range select item', + } +); + +export const SECONDS = i18n.translate('xpack.uptime.alerts.monitorStatus.timerangeOption.seconds', { + defaultMessage: 'seconds', +}); + +export const MINUTES_TIME_RANGE = i18n.translate( + 'xpack.uptime.alerts.timerangeUnitSelectable.minutesOption.ariaLabel', + { + defaultMessage: '"Minutes" time range select item', + } +); + +export const MINUTES = i18n.translate('xpack.uptime.alerts.monitorStatus.timerangeOption.minutes', { + defaultMessage: 'minutes', +}); + +export const HOURS_TIME_RANGE = i18n.translate( + 'xpack.uptime.alerts.timerangeUnitSelectable.hoursOption.ariaLabel', + { + defaultMessage: '"Hours" time range select item', + } +); + +export const HOURS = i18n.translate('xpack.uptime.alerts.monitorStatus.timerangeOption.hours', { + defaultMessage: 'hours', +}); + +export const DAYS_TIME_RANGE = i18n.translate( + 'xpack.uptime.alerts.timerangeUnitSelectable.daysOption.ariaLabel', + { + defaultMessage: '"Days" time range select item', + } +); + +export const DAYS = i18n.translate('xpack.uptime.alerts.monitorStatus.timerangeOption.days', { + defaultMessage: 'days', +}); + +export const ALERT_KUERY_BAR_ARIA = i18n.translate( + 'xpack.uptime.alerts.monitorStatus.filterBar.ariaLabel', + { + defaultMessage: 'Input that allows filtering criteria for the monitor status alert', + } +); + +export const OPEN_THE_POPOVER_DOWN_COUNT = i18n.translate( + 'xpack.uptime.alerts.monitorStatus.numTimesExpression.ariaLabel', + { + defaultMessage: 'Open the popover for down count input', + } +); + +export const ENTER_NUMBER_OF_DOWN_COUNTS = i18n.translate( + 'xpack.uptime.alerts.monitorStatus.numTimesField.ariaLabel', + { + defaultMessage: 'Enter number of down counts required to trigger the alert', + } +); + +export const MATCHING_MONITORS_DOWN = i18n.translate( + 'xpack.uptime.alerts.monitorStatus.numTimesExpression.matchingMonitors.description', + { + defaultMessage: 'matching monitors are down >', + } +); + +export const ANY_MONITOR_DOWN = i18n.translate( + 'xpack.uptime.alerts.monitorStatus.numTimesExpression.anyMonitors.description', + { + defaultMessage: 'any monitor is down >', + } +); + +export const OPEN_THE_POPOVER_TIME_RANGE_VALUE = i18n.translate( + 'xpack.uptime.alerts.monitorStatus.timerangeValueExpression.ariaLabel', + { + defaultMessage: 'Open the popover for time range value field', + } +); + +export const ENTER_NUMBER_OF_TIME_UNITS = i18n.translate( + 'xpack.uptime.alerts.monitorStatus.timerangeValueField.ariaLabel', + { + defaultMessage: `Enter the number of time units for the alert's range`, + } +); + +export const ADD_FILTER = i18n.translate('xpack.uptime.alerts.monitorStatus.addFilter', { + defaultMessage: `Add filter`, +}); + +export const LOCATION = i18n.translate('xpack.uptime.alerts.monitorStatus.addFilter.location', { + defaultMessage: `Location`, +}); + +export const TAG = i18n.translate('xpack.uptime.alerts.monitorStatus.addFilter.tag', { + defaultMessage: `Tag`, +}); + +export const PORT = i18n.translate('xpack.uptime.alerts.monitorStatus.addFilter.port', { + defaultMessage: `Port`, +}); + +export const TYPE = i18n.translate('xpack.uptime.alerts.monitorStatus.addFilter.type', { + defaultMessage: `Type`, +}); + +export const TlsTranslations = { + criteriaAriaLabel: i18n.translate('xpack.uptime.alerts.tls.criteriaExpression.ariaLabel', { + defaultMessage: + 'An expression displaying the criteria for monitor that are watched by this alert', + }), + criteriaDescription: i18n.translate('xpack.uptime.alerts.tls.criteriaExpression.description', { + defaultMessage: 'when', + description: + 'The context of this `when` is in the conditional sense, like "when there are three cookies, eat them all".', + }), + criteriaValue: i18n.translate('xpack.uptime.alerts.tls.criteriaExpression.value', { + defaultMessage: 'any monitor', + }), + expirationAriaLabel: i18n.translate('xpack.uptime.alerts.tls.expirationExpression.ariaLabel', { + defaultMessage: + 'An expression displaying the threshold that will trigger the TLS alert for certificate expiration', + }), + expirationDescription: i18n.translate( + 'xpack.uptime.alerts.tls.expirationExpression.description', + { + defaultMessage: 'has a certificate expiring within', + } + ), + expirationValue: (value?: number) => + i18n.translate('xpack.uptime.alerts.tls.expirationExpression.value', { + defaultMessage: '{value} days', + values: { value }, + }), + ageAriaLabel: i18n.translate('xpack.uptime.alerts.tls.ageExpression.ariaLabel', { + defaultMessage: + 'An expressing displaying the threshold that will trigger the TLS alert for old certificates', + }), + ageDescription: i18n.translate('xpack.uptime.alerts.tls.ageExpression.description', { + defaultMessage: 'or older than', + }), + ageValue: (value?: number) => + i18n.translate('xpack.uptime.alerts.tls.ageExpression.value', { + defaultMessage: '{value} days', + values: { value }, + }), +}; + +export const ToggleFlyoutTranslations = { + toggleButtonAriaLabel: i18n.translate('xpack.uptime.alertsPopover.toggleButton.ariaLabel', { + defaultMessage: 'Open alert context menu', + }), + openAlertContextPanelAriaLabel: i18n.translate('xpack.uptime.openAlertContextPanel.ariaLabel', { + defaultMessage: 'Open the alert context panel so you can choose an alert type', + }), + openAlertContextPanelLabel: i18n.translate('xpack.uptime.openAlertContextPanel.label', { + defaultMessage: 'Create alert', + }), + toggleTlsAriaLabel: i18n.translate('xpack.uptime.toggleTlsAlertButton.ariaLabel', { + defaultMessage: 'Open TLS alert flyout', + }), + toggleTlsContent: i18n.translate('xpack.uptime.toggleTlsAlertButton.content', { + defaultMessage: 'TLS alert', + }), + toggleMonitorStatusAriaLabel: i18n.translate('xpack.uptime.toggleAlertFlyout.ariaLabel', { + defaultMessage: 'Open add alert flyout', + }), + toggleMonitorStatusContent: i18n.translate('xpack.uptime.toggleAlertButton.content', { + defaultMessage: 'Monitor status alert', + }), + navigateToAlertingUIAriaLabel: i18n.translate('xpack.uptime.navigateToAlertingUi', { + defaultMessage: 'Leave Uptime and go to Alerting Management page', + }), + navigateToAlertingButtonContent: i18n.translate('xpack.uptime.navigateToAlertingButton.content', { + defaultMessage: 'Manage alerts', + }), +}; diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/uptime_alerts_context_provider.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/uptime_alerts_context_provider.tsx index 262e1552e3660d..d1c6f076d67495 100644 --- a/x-pack/plugins/uptime/public/components/overview/alerts/uptime_alerts_context_provider.tsx +++ b/x-pack/plugins/uptime/public/components/overview/alerts/uptime_alerts_context_provider.tsx @@ -18,6 +18,7 @@ export const UptimeAlertsContextProvider: React.FC = ({ children }) => { triggers_actions_ui: { actionTypeRegistry, alertTypeRegistry }, uiSettings, docLinks, + application: { capabilities }, }, } = useKibana(); @@ -32,6 +33,7 @@ export const UptimeAlertsContextProvider: React.FC = ({ children }) => { http, toastNotifications: notifications?.toasts, uiSettings, + capabilities, }} > {children} diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/uptime_alerts_flyout_wrapper.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/uptime_alerts_flyout_wrapper.tsx index 9b1d3a73dc6614..de4e67cfe8edce 100644 --- a/x-pack/plugins/uptime/public/components/overview/alerts/uptime_alerts_flyout_wrapper.tsx +++ b/x-pack/plugins/uptime/public/components/overview/alerts/uptime_alerts_flyout_wrapper.tsx @@ -10,14 +10,12 @@ import { AlertAdd } from '../../../../../../plugins/triggers_actions_ui/public'; interface Props { alertFlyoutVisible: boolean; alertTypeId?: string; - canChangeTrigger?: boolean; setAlertFlyoutVisibility: React.Dispatch>; } export const UptimeAlertsFlyoutWrapperComponent = ({ alertFlyoutVisible, alertTypeId, - canChangeTrigger, setAlertFlyoutVisibility, }: Props) => ( ); diff --git a/x-pack/plugins/uptime/public/components/overview/filter_group/__tests__/__snapshots__/filter_popover.test.tsx.snap b/x-pack/plugins/uptime/public/components/overview/filter_group/__tests__/__snapshots__/filter_popover.test.tsx.snap index 31a7e12dbdc291..c7ffc36532b71c 100644 --- a/x-pack/plugins/uptime/public/components/overview/filter_group/__tests__/__snapshots__/filter_popover.test.tsx.snap +++ b/x-pack/plugins/uptime/public/components/overview/filter_group/__tests__/__snapshots__/filter_popover.test.tsx.snap @@ -21,7 +21,7 @@ exports[`FilterPopover component does not show item list when loading 1`] = ` ownFocus={true} panelPaddingSize="m" withTitle={true} - zIndex={1000} + zIndex={10000} > void; } export const FilterGroupComponent: React.FC = ({ - currentFilter, overviewFilters, loading, - onFilterUpdate, }) => { const { locations, ports, schemes, tags } = overviewFilters; - let filterKueries: Map; - try { - filterKueries = new Map(JSON.parse(currentFilter)); - } catch { - filterKueries = new Map(); - } + const [updatedFieldValues, setUpdatedFieldValues] = useState<{ + fieldName: string; + values: string[]; + }>({ fieldName: '', values: [] }); - /** - * Handle an added or removed value to filter against for an uptime field. - * @param fieldName the name of the field to filter against - * @param values the list of values to use when filter a field - */ - const onFilterFieldChange = (fieldName: string, values: string[]) => { - // add new term to filter map, toggle it off if already present - const updatedFilterMap = new Map(filterKueries); - updatedFilterMap.set(fieldName, values); - Array.from(updatedFilterMap.keys()).forEach(key => { - const value = updatedFilterMap.get(key); - if (value && value.length === 0) { - updatedFilterMap.delete(key); - } - }); + const currentFilters = useFilterUpdate(updatedFieldValues.fieldName, updatedFieldValues.values); - // store the new set of filters - const persistedFilters = Array.from(updatedFilterMap); - onFilterUpdate(persistedFilters.length === 0 ? '' : JSON.stringify(persistedFilters)); + const onFilterFieldChange = (fieldName: string, values: string[]) => { + setUpdatedFieldValues({ fieldName, values }); }; - const getSelectedItems = (fieldName: string) => filterKueries.get(fieldName) || []; + const getSelectedItems = (fieldName: string) => currentFilters.get(fieldName) || []; const filterPopoverProps: FilterPopoverProps[] = [ { @@ -64,9 +43,7 @@ export const FilterGroupComponent: React.FC = ({ id: 'location', items: locations, selectedItems: getSelectedItems('observer.geo.name'), - title: i18n.translate('xpack.uptime.filterBar.options.location.name', { - defaultMessage: 'Location', - }), + title: filterLabels.LOCATION, }, { loading, @@ -76,7 +53,7 @@ export const FilterGroupComponent: React.FC = ({ disabled: ports.length === 0, items: ports.map((p: number) => p.toString()), selectedItems: getSelectedItems('url.port'), - title: i18n.translate('xpack.uptime.filterBar.options.portLabel', { defaultMessage: 'Port' }), + title: filterLabels.PORT, }, { loading, @@ -86,9 +63,7 @@ export const FilterGroupComponent: React.FC = ({ disabled: schemes.length === 0, items: schemes, selectedItems: getSelectedItems('monitor.type'), - title: i18n.translate('xpack.uptime.filterBar.options.schemeLabel', { - defaultMessage: 'Scheme', - }), + title: filterLabels.SCHEME, }, { loading, @@ -98,30 +73,12 @@ export const FilterGroupComponent: React.FC = ({ disabled: tags.length === 0, items: tags, selectedItems: getSelectedItems('tags'), - title: i18n.translate('xpack.uptime.filterBar.options.tagsLabel', { - defaultMessage: 'Tags', - }), + title: filterLabels.TAGS, }, ]; return ( - - {filterPopoverProps.map(item => ( ))} diff --git a/x-pack/plugins/uptime/public/components/overview/filter_group/filter_group_container.tsx b/x-pack/plugins/uptime/public/components/overview/filter_group/filter_group_container.tsx index 3612604fdf1162..67cb89745269e9 100644 --- a/x-pack/plugins/uptime/public/components/overview/filter_group/filter_group_container.tsx +++ b/x-pack/plugins/uptime/public/components/overview/filter_group/filter_group_container.tsx @@ -5,56 +5,41 @@ */ import React, { useContext, useEffect } from 'react'; -import { connect } from 'react-redux'; -import { useUrlParams } from '../../../hooks'; +import { useDispatch, useSelector } from 'react-redux'; +import { useGetUrlParams } from '../../../hooks'; import { parseFiltersMap } from './parse_filter_map'; -import { AppState } from '../../../state'; -import { fetchOverviewFilters, GetOverviewFiltersPayload } from '../../../state/actions'; +import { fetchOverviewFilters } from '../../../state/actions'; import { FilterGroupComponent } from './index'; -import { OverviewFilters } from '../../../../common/runtime_types/overview_filters'; import { UptimeRefreshContext } from '../../../contexts'; +import { filterGroupDataSelector } from '../../../state/selectors'; -interface OwnProps { +interface Props { esFilters?: string; } -interface StoreProps { - esKuery: string; - lastRefresh: number; - loading: boolean; - overviewFilters: OverviewFilters; -} - -interface DispatchProps { - loadFilterGroup: typeof fetchOverviewFilters; -} +export const FilterGroup: React.FC = ({ esFilters }: Props) => { + const { lastRefresh } = useContext(UptimeRefreshContext); -type Props = OwnProps & StoreProps & DispatchProps; + const { esKuery, filters: overviewFilters, loading } = useSelector(filterGroupDataSelector); -export const Container: React.FC = ({ - esKuery, - esFilters, - loading, - loadFilterGroup, - overviewFilters, -}: Props) => { - const { lastRefresh } = useContext(UptimeRefreshContext); + const { dateRangeStart, dateRangeEnd, statusFilter, filters: urlFilters } = useGetUrlParams(); - const [getUrlParams, updateUrl] = useUrlParams(); - const { dateRangeStart, dateRangeEnd, statusFilter, filters: urlFilters } = getUrlParams(); + const dispatch = useDispatch(); useEffect(() => { const filterSelections = parseFiltersMap(urlFilters); - loadFilterGroup({ - dateRangeStart, - dateRangeEnd, - locations: filterSelections.locations ?? [], - ports: filterSelections.ports ?? [], - schemes: filterSelections.schemes ?? [], - search: esKuery, - statusFilter, - tags: filterSelections.tags ?? [], - }); + dispatch( + fetchOverviewFilters({ + dateRangeStart, + dateRangeEnd, + locations: filterSelections.locations ?? [], + ports: filterSelections.ports ?? [], + schemes: filterSelections.schemes ?? [], + search: esKuery, + statusFilter, + tags: filterSelections.tags ?? [], + }) + ); }, [ lastRefresh, dateRangeStart, @@ -63,42 +48,8 @@ export const Container: React.FC = ({ esFilters, statusFilter, urlFilters, - loadFilterGroup, + dispatch, ]); - // update filters in the URL from filter group - const onFilterUpdate = (filtersKuery: string) => { - if (urlFilters !== filtersKuery) { - updateUrl({ filters: filtersKuery, pagination: '' }); - } - }; - - return ( - - ); + return ; }; - -const mapStateToProps = ({ - overviewFilters: { loading, filters }, - ui: { esKuery, lastRefresh }, -}: AppState): StoreProps => ({ - esKuery, - overviewFilters: filters, - lastRefresh, - loading, -}); - -const mapDispatchToProps = (dispatch: any): DispatchProps => ({ - loadFilterGroup: (payload: GetOverviewFiltersPayload) => dispatch(fetchOverviewFilters(payload)), -}); - -export const FilterGroup = connect( - // @ts-ignore connect is expecting null | undefined for some reason - mapStateToProps, - mapDispatchToProps -)(Container); diff --git a/x-pack/plugins/uptime/public/components/overview/filter_group/filter_popover.tsx b/x-pack/plugins/uptime/public/components/overview/filter_group/filter_popover.tsx index ac65063ee897d3..18d40b83be3696 100644 --- a/x-pack/plugins/uptime/public/components/overview/filter_group/filter_popover.tsx +++ b/x-pack/plugins/uptime/public/components/overview/filter_group/filter_popover.tsx @@ -20,6 +20,9 @@ export interface FilterPopoverProps { onFilterFieldChange: (fieldName: string, values: string[]) => void; selectedItems: string[]; title: string; + btnContent?: JSX.Element; + forceOpen?: boolean; + setForceOpen?: (val: boolean) => void; } const isItemSelected = (selectedItems: string[], item: string): 'on' | undefined => @@ -34,6 +37,9 @@ export const FilterPopover = ({ onFilterFieldChange, selectedItems, title, + btnContent, + forceOpen, + setForceOpen, }: FilterPopoverProps) => { const [isOpen, setIsOpen] = useState(false); const [itemsToDisplay, setItemsToDisplay] = useState([]); @@ -52,28 +58,33 @@ export const FilterPopover = ({ return ( 0} - numFilters={items.length} - numActiveFilters={tempSelectedItems.length} - onClick={() => { - setIsOpen(!isOpen); - onFilterFieldChange(fieldName, tempSelectedItems); - }} - title={title} - /> + btnContent ?? ( + 0} + numFilters={items.length} + numActiveFilters={tempSelectedItems.length} + onClick={() => { + setIsOpen(!isOpen); + onFilterFieldChange(fieldName, tempSelectedItems); + }} + title={title} + /> + ) } closePopover={() => { setIsOpen(false); onFilterFieldChange(fieldName, tempSelectedItems); + if (setForceOpen) { + setForceOpen(false); + } }} data-test-subj={`filter-popover_${id}`} id={id} - isOpen={isOpen} + isOpen={isOpen || forceOpen} ownFocus={true} withTitle - zIndex={1000} + zIndex={10000} > + + + + Up + + + + +`; + +exports[`FilterStatusButton shallow renders without errors for valid props 1`] = ` diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/__tests__/__snapshots__/monitor_list.test.tsx.snap b/x-pack/plugins/uptime/public/components/overview/monitor_list/__tests__/__snapshots__/monitor_list.test.tsx.snap index 0d6638e7070d64..7772b886f7a4f9 100644 --- a/x-pack/plugins/uptime/public/components/overview/monitor_list/__tests__/__snapshots__/monitor_list.test.tsx.snap +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/__tests__/__snapshots__/monitor_list.test.tsx.snap @@ -533,22 +533,26 @@ exports[`MonitorList component renders loading state 1`] = ` `; exports[`MonitorList component renders the monitor list 1`] = ` -.c1 { +.c2 { padding-left: 17px; } -.c3 { +.c4 { padding-top: 12px; } -.c2 { +.c0 { + margin-left: auto; +} + +.c3 { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } @media (max-width:574px) { - .c0 { + .c1 { min-width: 230px; } } @@ -557,28 +561,101 @@ exports[`MonitorList component renders the monitor list 1`] = ` class="euiPanel euiPanel--paddingMedium" >
- Monitor status + Monitors
+
+ + + +
+
+ @@ -726,7 +803,7 @@ exports[`MonitorList component renders the monitor list 1`] = ` class="euiTableCellContent euiTableCellContent--overflowingContent" >
+ + +
+`; + +exports[`StatusFilterComponent shallow renders without errors for valid props 1`] = ` + + + +`; diff --git a/x-pack/plugins/uptime/public/components/overview/filter_group/__tests__/filter_status_button.test.tsx b/x-pack/plugins/uptime/public/components/overview/monitor_list/__tests__/filter_status_button.test.tsx similarity index 73% rename from x-pack/plugins/uptime/public/components/overview/filter_group/__tests__/filter_status_button.test.tsx rename to x-pack/plugins/uptime/public/components/overview/monitor_list/__tests__/filter_status_button.test.tsx index 2ad4d971cf3b04..58c305f0d15a08 100644 --- a/x-pack/plugins/uptime/public/components/overview/filter_group/__tests__/filter_status_button.test.tsx +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/__tests__/filter_status_button.test.tsx @@ -6,7 +6,7 @@ import React from 'react'; import { FilterStatusButton, FilterStatusButtonProps } from '../filter_status_button'; -import { shallowWithRouter } from '../../../../lib'; +import { renderWithRouter, shallowWithRouter } from '../../../../lib'; describe('FilterStatusButton', () => { let props: FilterStatusButtonProps; @@ -16,11 +16,17 @@ describe('FilterStatusButton', () => { dataTestSubj: 'foo', value: 'up', withNext: true, + isActive: true, }; }); - it('renders without errors for valid props', () => { + it('shallow renders without errors for valid props', () => { const wrapper = shallowWithRouter(); expect(wrapper).toMatchSnapshot(); }); + + it('renders without errors for valid props', () => { + const wrapper = renderWithRouter(); + expect(wrapper).toMatchSnapshot(); + }); }); diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/__tests__/status_filter.test.tsx b/x-pack/plugins/uptime/public/components/overview/monitor_list/__tests__/status_filter.test.tsx new file mode 100644 index 00000000000000..a1288513eb7856 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/__tests__/status_filter.test.tsx @@ -0,0 +1,64 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { mountWithRouter, renderWithRouter, shallowWithRouter } from '../../../../lib'; +import { createMemoryHistory } from 'history'; +import { StatusFilter } from '../status_filter'; +import { FilterStatusButton } from '../filter_status_button'; + +describe('StatusFilterComponent', () => { + beforeEach(() => {}); + + const getStatusBtns = (status: string) => { + const history = createMemoryHistory({ + initialEntries: [`/?g=%22%22&statusFilter=${status}`], + }); + + const wrapper = mountWithRouter(, history); + const filterBtns = wrapper.find(FilterStatusButton); + + const allBtn = filterBtns.at(0); + const upBtn = filterBtns.at(1); + const downBtn = filterBtns.at(2); + + return { allBtn, upBtn, downBtn, wrapper }; + }; + + it('shallow renders without errors for valid props', () => { + const wrapper = shallowWithRouter(); + expect(wrapper).toMatchSnapshot(); + }); + + it('renders without errors for valid props', () => { + const wrapper = renderWithRouter(); + expect(wrapper).toMatchSnapshot(); + }); + + it('checks if it properly validates url state when filter is up', () => { + const { allBtn, upBtn, downBtn } = getStatusBtns('up'); + + expect(allBtn.props().isActive).toBe(false); + expect(upBtn.props().isActive).toBe(true); + expect(downBtn.props().isActive).toBe(false); + }); + + it('checks if it properly validates url state when filter is down', () => { + const { allBtn, upBtn, downBtn } = getStatusBtns('down'); + + expect(allBtn.props().isActive).toBe(false); + expect(upBtn.props().isActive).toBe(false); + expect(downBtn.props().isActive).toBe(true); + }); + + it('checks if it properly validates url state when filter is all', () => { + const { allBtn, upBtn, downBtn } = getStatusBtns(''); + + expect(allBtn.props().isActive).toBe(true); + expect(upBtn.props().isActive).toBe(false); + expect(downBtn.props().isActive).toBe(false); + }); +}); diff --git a/x-pack/plugins/uptime/public/components/overview/filter_group/filter_status_button.tsx b/x-pack/plugins/uptime/public/components/overview/monitor_list/filter_status_button.tsx similarity index 83% rename from x-pack/plugins/uptime/public/components/overview/filter_group/filter_status_button.tsx rename to x-pack/plugins/uptime/public/components/overview/monitor_list/filter_status_button.tsx index abbe72530fd80a..6e63c21d08ca96 100644 --- a/x-pack/plugins/uptime/public/components/overview/filter_group/filter_status_button.tsx +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/filter_status_button.tsx @@ -9,26 +9,31 @@ import React from 'react'; import { useUrlParams } from '../../../hooks'; export interface FilterStatusButtonProps { - content: string; + content: string | JSX.Element; dataTestSubj: string; isDisabled?: boolean; - value: string; + isActive: boolean; + value: 'up' | 'down' | ''; withNext: boolean; + color?: string; } export const FilterStatusButton = ({ content, dataTestSubj, isDisabled, + isActive, value, + color, withNext, }: FilterStatusButtonProps) => { const [getUrlParams, setUrlParams] = useUrlParams(); const { statusFilter: urlValue } = getUrlParams(); return ( { const nextFilter = { statusFilter: urlValue === value ? '' : value, pagination: '' }; diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list.tsx b/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list.tsx index 616d8fbd76043f..de53c52cd7f758 100644 --- a/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list.tsx +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/monitor_list.tsx @@ -13,12 +13,9 @@ import { EuiLink, EuiPanel, EuiSpacer, - EuiTitle, } from '@elastic/eui'; -import { FormattedMessage } from '@kbn/i18n/react'; import React, { useState, useEffect } from 'react'; import styled from 'styled-components'; -import { Link } from 'react-router-dom'; import { HistogramPoint, FetchMonitorStatesQueryArgs } from '../../../../common/runtime_types'; import { MonitorSummary } from '../../../../common/runtime_types'; import { MonitorListStatusColumn } from './monitor_list_status_column'; @@ -32,8 +29,8 @@ import { MonitorListDrawer } from './monitor_list_drawer/list_drawer_container'; import { MonitorListProps } from './monitor_list_container'; import { MonitorList } from '../../../state/reducers/monitor_list'; import { useUrlParams } from '../../../hooks'; -import { CERTIFICATES_ROUTE } from '../../../../common/constants'; import { CertStatusColumn } from './cert_status_column'; +import { MonitorListHeader } from './monitor_list_header'; interface Props extends MonitorListProps { lastRefresh: number; @@ -190,31 +187,7 @@ export const MonitorListComponent: React.FC = ({ return ( - - - -
- -
-
-
- - -
- - - -
-
-
-
- + { + return ( + + + +
+ +
+
+
+ + + + + +
+ + + +
+
+
+
+ ); +}; diff --git a/x-pack/plugins/uptime/public/components/overview/monitor_list/status_filter.tsx b/x-pack/plugins/uptime/public/components/overview/monitor_list/status_filter.tsx new file mode 100644 index 00000000000000..43a7ffcea08679 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/monitor_list/status_filter.tsx @@ -0,0 +1,55 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { i18n } from '@kbn/i18n'; +import { EuiFilterGroup, EuiTextColor } from '@elastic/eui'; +import { FilterStatusButton } from './filter_status_button'; +import { useGetUrlParams } from '../../../hooks'; + +export const StatusFilter: React.FC = () => { + const { statusFilter } = useGetUrlParams(); + + // Empty string for all filter button value, since we dont store it in url, so keeping it in sync + const ALL = ''; + + return ( + + + + {i18n.translate('xpack.uptime.filterBar.filterUpLabel', { + defaultMessage: 'Up', + })} + + } + dataTestSubj="xpack.uptime.filterBar.filterStatusUp" + value="up" + withNext={true} + isActive={statusFilter === 'up'} + /> + + + ); +}; diff --git a/x-pack/plugins/uptime/public/components/overview/overview_container.tsx b/x-pack/plugins/uptime/public/components/overview/overview_container.tsx index d64e489c480768..320536bc63b3c9 100644 --- a/x-pack/plugins/uptime/public/components/overview/overview_container.tsx +++ b/x-pack/plugins/uptime/public/components/overview/overview_container.tsx @@ -4,20 +4,25 @@ * you may not use this file except in compliance with the Elastic License. */ -import { connect } from 'react-redux'; +import { useDispatch, useSelector } from 'react-redux'; +import React, { useCallback } from 'react'; +import { DataPublicPluginSetup } from 'src/plugins/data/public'; import { OverviewPageComponent } from '../../pages/overview'; import { selectIndexPattern } from '../../state/selectors'; -import { AppState } from '../../state'; import { setEsKueryString } from '../../state/actions'; -interface DispatchProps { - setEsKueryFilters: typeof setEsKueryString; +export interface OverviewPageProps { + autocomplete: DataPublicPluginSetup['autocomplete']; } -const mapDispatchToProps = (dispatch: any): DispatchProps => ({ - setEsKueryFilters: (esFilters: string) => dispatch(setEsKueryString(esFilters)), -}); - -const mapStateToProps = (state: AppState) => ({ ...selectIndexPattern(state) }); - -export const OverviewPage = connect(mapStateToProps, mapDispatchToProps)(OverviewPageComponent); +export const OverviewPage: React.FC = props => { + const dispatch = useDispatch(); + const setEsKueryFilters = useCallback( + (esFilters: string) => dispatch(setEsKueryString(esFilters)), + [dispatch] + ); + const indexPattern = useSelector(selectIndexPattern); + return ( + + ); +}; diff --git a/x-pack/plugins/uptime/public/components/overview/snapshot/snapshot_container.tsx b/x-pack/plugins/uptime/public/components/overview/snapshot/snapshot_container.tsx index 09d30e049175c0..0fd52f0a0be4fa 100644 --- a/x-pack/plugins/uptime/public/components/overview/snapshot/snapshot_container.tsx +++ b/x-pack/plugins/uptime/public/components/overview/snapshot/snapshot_container.tsx @@ -19,16 +19,14 @@ interface Props { } export const Snapshot: React.FC = ({ height }: Props) => { - const { dateRangeStart, dateRangeEnd, statusFilter } = useGetUrlParams(); + const { dateRangeStart, dateRangeEnd } = useGetUrlParams(); const { count, lastRefresh, loading, esKuery } = useSelector(snapshotDataSelector); const dispatch = useDispatch(); useEffect(() => { - dispatch( - getSnapshotCountAction({ dateRangeStart, dateRangeEnd, filters: esKuery, statusFilter }) - ); - }, [dateRangeStart, dateRangeEnd, esKuery, lastRefresh, statusFilter, dispatch]); + dispatch(getSnapshotCountAction({ dateRangeStart, dateRangeEnd, filters: esKuery })); + }, [dateRangeStart, dateRangeEnd, esKuery, lastRefresh, dispatch]); return ; }; diff --git a/x-pack/plugins/uptime/public/hooks/use_filter_update.ts b/x-pack/plugins/uptime/public/hooks/use_filter_update.ts new file mode 100644 index 00000000000000..97ef6b0e67ad2e --- /dev/null +++ b/x-pack/plugins/uptime/public/hooks/use_filter_update.ts @@ -0,0 +1,56 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { useEffect } from 'react'; +import { useUrlParams } from './use_url_params'; + +/** + * Handle an added or removed value to filter against for an uptime field. + * @param fieldName the name of the field to filter against + * @param values the list of values to use when filter a field + */ + +export const useFilterUpdate = (fieldName?: string, values?: string[]) => { + const [getUrlParams, updateUrl] = useUrlParams(); + + const { filters: currentFilters } = getUrlParams(); + + // update filters in the URL from filter group + const onFilterUpdate = (filtersKuery: string) => { + if (currentFilters !== filtersKuery) { + updateUrl({ filters: filtersKuery, pagination: '' }); + } + }; + + let filterKueries: Map; + try { + filterKueries = new Map(JSON.parse(currentFilters)); + } catch { + filterKueries = new Map(); + } + + useEffect(() => { + if (fieldName) { + // add new term to filter map, toggle it off if already present + const updatedFilterMap = new Map(filterKueries); + updatedFilterMap.set(fieldName, values); + Array.from(updatedFilterMap.keys()).forEach(key => { + const value = updatedFilterMap.get(key); + if (value && value.length === 0) { + updatedFilterMap.delete(key); + } + }); + + // store the new set of filters + const persistedFilters = Array.from(updatedFilterMap); + onFilterUpdate(persistedFilters.length === 0 ? '' : JSON.stringify(persistedFilters)); + } + + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [fieldName, values]); + + return filterKueries; +}; diff --git a/x-pack/plugins/uptime/public/lib/alert_types/__tests__/monitor_status.test.ts b/x-pack/plugins/uptime/public/lib/alert_types/__tests__/monitor_status.test.ts index 81402c00e484ec..0d18facaa5bbb2 100644 --- a/x-pack/plugins/uptime/public/lib/alert_types/__tests__/monitor_status.test.ts +++ b/x-pack/plugins/uptime/public/lib/alert_types/__tests__/monitor_status.test.ts @@ -174,7 +174,7 @@ describe('monitor status alert type', () => { {{context.downMonitorsWithGeo}}", "iconClass": "uptimeApp", "id": "xpack.uptime.alerts.monitorStatus", - "name": "Uptime monitor status", + "name": , "validate": [Function], } `); diff --git a/x-pack/plugins/uptime/public/lib/alert_types/index.ts b/x-pack/plugins/uptime/public/lib/alert_types/index.ts index f7ab254ffe675f..9a0151e95748c5 100644 --- a/x-pack/plugins/uptime/public/lib/alert_types/index.ts +++ b/x-pack/plugins/uptime/public/lib/alert_types/index.ts @@ -6,7 +6,11 @@ import { AlertTypeModel } from '../../../../triggers_actions_ui/public'; import { initMonitorStatusAlertType } from './monitor_status'; +import { initTlsAlertType } from './tls'; export type AlertTypeInitializer = (dependenies: { autocomplete: any }) => AlertTypeModel; -export const alertTypeInitializers: AlertTypeInitializer[] = [initMonitorStatusAlertType]; +export const alertTypeInitializers: AlertTypeInitializer[] = [ + initMonitorStatusAlertType, + initTlsAlertType, +]; diff --git a/x-pack/plugins/uptime/public/lib/alert_types/monitor_status.tsx b/x-pack/plugins/uptime/public/lib/alert_types/monitor_status.tsx index e7695fb1cbb56c..66e61fbf73b649 100644 --- a/x-pack/plugins/uptime/public/lib/alert_types/monitor_status.tsx +++ b/x-pack/plugins/uptime/public/lib/alert_types/monitor_status.tsx @@ -12,6 +12,9 @@ import { AlertTypeModel } from '../../../../triggers_actions_ui/public'; import { AlertTypeInitializer } from '.'; import { StatusCheckExecutorParamsType } from '../../../common/runtime_types'; import { AlertMonitorStatus } from '../../components/overview/alerts/alerts_containers'; +import { MonitorStatusTitle } from './monitor_status_title'; +import { CLIENT_ALERT_TYPES } from '../../../common/constants'; +import { MonitorStatusTranslations } from './translations'; export const validate = (alertParams: any) => { const errors: Record = {}; @@ -52,15 +55,15 @@ export const validate = (alertParams: any) => { return { errors }; }; +const { defaultActionMessage } = MonitorStatusTranslations; + export const initMonitorStatusAlertType: AlertTypeInitializer = ({ autocomplete, }): AlertTypeModel => ({ - id: 'xpack.uptime.alerts.monitorStatus', - name: 'Uptime monitor status', + id: CLIENT_ALERT_TYPES.MONITOR_STATUS, + name: , iconClass: 'uptimeApp', - alertParamsExpression: params => { - return ; - }, + alertParamsExpression: params => , validate, - defaultActionMessage: `{{context.message}}\nLast triggered at: {{state.lastTriggeredAt}}\n{{context.downMonitorsWithGeo}}`, + defaultActionMessage, }); diff --git a/x-pack/plugins/uptime/public/lib/alert_types/monitor_status_title.tsx b/x-pack/plugins/uptime/public/lib/alert_types/monitor_status_title.tsx new file mode 100644 index 00000000000000..3fe497f9e88bc3 --- /dev/null +++ b/x-pack/plugins/uptime/public/lib/alert_types/monitor_status_title.tsx @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { useSelector } from 'react-redux'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiFlexGroup, EuiFlexItem, EuiLoadingSpinner, EuiText } from '@elastic/eui'; +import { snapshotDataSelector } from '../../state/selectors'; + +export const MonitorStatusTitle = () => { + const { count, loading } = useSelector(snapshotDataSelector); + return ( + + + {' '} + + + {!loading ? ( + + {count.total} monitors + + ) : ( + + )} + + + ); +}; diff --git a/x-pack/plugins/uptime/public/lib/alert_types/tls.tsx b/x-pack/plugins/uptime/public/lib/alert_types/tls.tsx new file mode 100644 index 00000000000000..0a5c09acbb69fe --- /dev/null +++ b/x-pack/plugins/uptime/public/lib/alert_types/tls.tsx @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { AlertTypeModel } from '../../../../triggers_actions_ui/public'; +import { CLIENT_ALERT_TYPES } from '../../../common/constants'; +import { TlsTranslations } from './translations'; +import { AlertTypeInitializer } from '.'; +import { AlertTls } from '../../components/overview/alerts/alerts_containers/alert_tls'; + +const { name, defaultActionMessage } = TlsTranslations; + +export const initTlsAlertType: AlertTypeInitializer = (): AlertTypeModel => ({ + id: CLIENT_ALERT_TYPES.TLS, + iconClass: 'uptimeApp', + alertParamsExpression: () => , + name, + validate: () => ({ errors: {} }), + defaultActionMessage, +}); diff --git a/x-pack/plugins/uptime/public/lib/alert_types/translations.ts b/x-pack/plugins/uptime/public/lib/alert_types/translations.ts new file mode 100644 index 00000000000000..cdf3cd107b00f9 --- /dev/null +++ b/x-pack/plugins/uptime/public/lib/alert_types/translations.ts @@ -0,0 +1,52 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; + +export const MonitorStatusTranslations = { + defaultActionMessage: i18n.translate('xpack.uptime.alerts.monitorStatus.defaultActionMessage', { + defaultMessage: '{contextMessage}\nLast triggered at: {lastTriggered}\n{downMonitors}', + values: { + contextMessage: '{{context.message}}', + lastTriggered: '{{state.lastTriggeredAt}}', + downMonitors: '{{context.downMonitorsWithGeo}}', + }, + }), + name: i18n.translate('xpack.uptime.alerts.monitorStatus.clientName', { + defaultMessage: 'Uptime monitor status', + }), +}; + +export const TlsTranslations = { + defaultActionMessage: i18n.translate('xpack.uptime.alerts.tls.defaultActionMessage', { + defaultMessage: `Detected {count} TLS certificates expiring or becoming too old. + +{expiringConditionalOpen} +Expiring cert count: {expiringCount} +Expiring Certificates: {expiringCommonNameAndDate} +{expiringConditionalClose} + +{agingConditionalOpen} +Aging cert count: {agingCount} +Aging Certificates: {agingCommonNameAndDate} +{agingConditionalClose} +`, + values: { + count: '{{state.count}}', + expiringCount: '{{state.expiringCount}}', + expiringCommonNameAndDate: '{{state.expiringCommonNameAndDate}}', + expiringConditionalOpen: '{{#state.hasExpired}}', + expiringConditionalClose: '{{/state.hasExpired}}', + agingCount: '{{state.agingCount}}', + agingCommonNameAndDate: '{{state.agingCommonNameAndDate}}', + agingConditionalOpen: '{{#state.hasAging}}', + agingConditionalClose: '{{/state.hasAging}}', + }, + }), + name: i18n.translate('xpack.uptime.alerts.tls.clientName', { + defaultMessage: 'Uptime TLS', + }), +}; diff --git a/x-pack/plugins/uptime/public/pages/certificates.tsx b/x-pack/plugins/uptime/public/pages/certificates.tsx index d6c1b8e2b4568c..92a41adcf01cdf 100644 --- a/x-pack/plugins/uptime/public/pages/certificates.tsx +++ b/x-pack/plugins/uptime/public/pages/certificates.tsx @@ -19,13 +19,14 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { useTrackPageview } from '../../../observability/public'; import { PageHeader } from './page_header'; import { useBreadcrumbs } from '../hooks/use_breadcrumbs'; -import { OVERVIEW_ROUTE, SETTINGS_ROUTE } from '../../common/constants'; +import { OVERVIEW_ROUTE, SETTINGS_ROUTE, CLIENT_ALERT_TYPES } from '../../common/constants'; import { getDynamicSettings } from '../state/actions/dynamic_settings'; import { UptimeRefreshContext } from '../contexts'; import * as labels from './translations'; import { UptimePage, useUptimeTelemetry } from '../hooks'; import { certificatesSelector, getCertificatesAction } from '../state/certificates/certificates'; import { CertificateList, CertificateSearch, CertSort } from '../components/certificates'; +import { ToggleAlertFlyoutButton } from '../components/overview/alerts/alerts_containers'; const DEFAULT_PAGE_SIZE = 10; const LOCAL_STORAGE_KEY = 'xpack.uptime.certList.pageSize'; @@ -83,6 +84,9 @@ export const CertificatesPage: React.FC = () => { + + + diff --git a/x-pack/plugins/uptime/public/pages/overview.tsx b/x-pack/plugins/uptime/public/pages/overview.tsx index fefd804cbfabf0..65f64aa7352a9e 100644 --- a/x-pack/plugins/uptime/public/pages/overview.tsx +++ b/x-pack/plugins/uptime/public/pages/overview.tsx @@ -11,22 +11,20 @@ import { i18n } from '@kbn/i18n'; import { useUptimeTelemetry, UptimePage, useGetUrlParams } from '../hooks'; import { stringifyUrlParams } from '../lib/helper/stringify_url_params'; import { PageHeader } from './page_header'; -import { DataPublicPluginSetup, IIndexPattern } from '../../../../../src/plugins/data/public'; +import { IIndexPattern } from '../../../../../src/plugins/data/public'; import { useUpdateKueryString } from '../hooks'; import { useBreadcrumbs } from '../hooks/use_breadcrumbs'; import { useTrackPageview } from '../../../observability/public'; import { MonitorList } from '../components/overview/monitor_list/monitor_list_container'; import { EmptyState, FilterGroup, KueryBar, ParsingErrorCallout } from '../components/overview'; import { StatusPanel } from '../components/overview/status_panel'; +import { OverviewPageProps } from '../components/overview/overview_container'; -interface OverviewPageProps { - autocomplete: DataPublicPluginSetup['autocomplete']; +interface Props extends OverviewPageProps { indexPattern: IIndexPattern | null; setEsKueryFilters: (esFilters: string) => void; } -type Props = OverviewPageProps; - const EuiFlexItemStyled = styled(EuiFlexItem)` && { min-width: 598px; diff --git a/x-pack/plugins/uptime/public/state/actions/snapshot.ts b/x-pack/plugins/uptime/public/state/actions/snapshot.ts index e819a553e61f5a..cbb7095eabb6c2 100644 --- a/x-pack/plugins/uptime/public/state/actions/snapshot.ts +++ b/x-pack/plugins/uptime/public/state/actions/snapshot.ts @@ -11,7 +11,6 @@ export interface GetSnapshotPayload { dateRangeStart: string; dateRangeEnd: string; filters?: string; - statusFilter?: string; } export const getSnapshotCountAction = createAction('GET_SNAPSHOT_COUNT'); diff --git a/x-pack/plugins/uptime/public/state/actions/ui.ts b/x-pack/plugins/uptime/public/state/actions/ui.ts index 4885f974dbbd49..80e8796843ac2e 100644 --- a/x-pack/plugins/uptime/public/state/actions/ui.ts +++ b/x-pack/plugins/uptime/public/state/actions/ui.ts @@ -12,7 +12,9 @@ export interface PopoverState { export type UiPayload = PopoverState & string & number & Map; -export const setAlertFlyoutVisible = createAction('TOGGLE ALERT FLYOUT'); +export const setAlertFlyoutVisible = createAction('TOGGLE ALERT FLYOUT'); + +export const setAlertFlyoutType = createAction('SET ALERT FLYOUT TYPE'); export const setBasePath = createAction('SET BASE PATH'); diff --git a/x-pack/plugins/uptime/public/state/api/__tests__/snapshot.test.ts b/x-pack/plugins/uptime/public/state/api/__tests__/snapshot.test.ts index ff9fcd05732571..89f3373dacdd38 100644 --- a/x-pack/plugins/uptime/public/state/api/__tests__/snapshot.test.ts +++ b/x-pack/plugins/uptime/public/state/api/__tests__/snapshot.test.ts @@ -30,14 +30,12 @@ describe('snapshot API', () => { dateRangeStart: 'now-15m', dateRangeEnd: 'now', filters: 'monitor.id:"auto-http-0X21EE76EAC459873F"', - statusFilter: 'up', }); expect(fetchMock).toHaveBeenCalledWith('/api/uptime/snapshot/count', { query: { dateRangeEnd: 'now', dateRangeStart: 'now-15m', filters: 'monitor.id:"auto-http-0X21EE76EAC459873F"', - statusFilter: 'up', }, }); expect(resp).toEqual({ up: 3, down: 12, total: 15 }); @@ -50,7 +48,6 @@ describe('snapshot API', () => { dateRangeStart: 'now-15m', dateRangeEnd: 'now', filters: 'monitor.id: baz', - statusFilter: 'up', }); expect(result).toMatchSnapshot(); diff --git a/x-pack/plugins/uptime/public/state/api/ml_anomaly.ts b/x-pack/plugins/uptime/public/state/api/ml_anomaly.ts index c4ecb769abefce..ff2ad8ba0745ff 100644 --- a/x-pack/plugins/uptime/public/state/api/ml_anomaly.ts +++ b/x-pack/plugins/uptime/public/state/api/ml_anomaly.ts @@ -57,7 +57,7 @@ export const createMLJob = async ({ useDedicatedIndex: false, startDatafeed: true, start: moment() - .subtract(24, 'h') + .subtract(2, 'w') .valueOf(), indexPatternName: heartbeatIndices, query: { diff --git a/x-pack/plugins/uptime/public/state/api/ping.ts b/x-pack/plugins/uptime/public/state/api/ping.ts index 6de27879a49f58..a2937c9c794ddf 100644 --- a/x-pack/plugins/uptime/public/state/api/ping.ts +++ b/x-pack/plugins/uptime/public/state/api/ping.ts @@ -24,14 +24,12 @@ export const fetchPingHistogram: APIFn monitorId, dateStart, dateEnd, - statusFilter, filters, }) => { const queryParams = { dateStart, dateEnd, monitorId, - statusFilter, filters, }; diff --git a/x-pack/plugins/uptime/public/state/reducers/__tests__/snapshot.test.ts b/x-pack/plugins/uptime/public/state/reducers/__tests__/snapshot.test.ts index 3650422571ce81..40e365f0a13a71 100644 --- a/x-pack/plugins/uptime/public/state/reducers/__tests__/snapshot.test.ts +++ b/x-pack/plugins/uptime/public/state/reducers/__tests__/snapshot.test.ts @@ -17,7 +17,6 @@ describe('snapshot reducer', () => { dateRangeStart: 'now-15m', dateRangeEnd: 'now', filters: 'foo: bar', - statusFilter: 'up', }); expect( snapshotReducer( diff --git a/x-pack/plugins/uptime/public/state/reducers/ui.ts b/x-pack/plugins/uptime/public/state/reducers/ui.ts index c533f293fc940a..82c2bfe2c0cec2 100644 --- a/x-pack/plugins/uptime/public/state/reducers/ui.ts +++ b/x-pack/plugins/uptime/public/state/reducers/ui.ts @@ -12,11 +12,13 @@ import { setEsKueryString, triggerAppRefresh, UiPayload, + setAlertFlyoutType, setAlertFlyoutVisible, } from '../actions'; export interface UiState { alertFlyoutVisible: boolean; + alertFlyoutType?: string; basePath: string; esKuery: string; integrationsPopoverOpen: PopoverState | null; @@ -57,6 +59,11 @@ export const uiReducer = handleActions( ...state, esKuery: action.payload as string, }), + + [String(setAlertFlyoutType)]: (state, action: Action) => ({ + ...state, + alertFlyoutType: action.payload, + }), }, initialState ); diff --git a/x-pack/plugins/uptime/public/state/selectors/index.ts b/x-pack/plugins/uptime/public/state/selectors/index.ts index 15fc8b8a7b1735..2b7eabe727ad1a 100644 --- a/x-pack/plugins/uptime/public/state/selectors/index.ts +++ b/x-pack/plugins/uptime/public/state/selectors/index.ts @@ -91,6 +91,8 @@ export const selectDurationLines = ({ monitorDuration }: AppState) => { export const selectAlertFlyoutVisibility = ({ ui: { alertFlyoutVisible } }: AppState) => alertFlyoutVisible; +export const selectAlertFlyoutType = ({ ui: { alertFlyoutType } }: AppState) => alertFlyoutType; + export const selectMonitorStatusAlert = ({ indexPattern, overviewFilters, ui }: AppState) => ({ filters: ui.esKuery, indexPattern: indexPattern.index_pattern, @@ -105,3 +107,16 @@ export const monitorListSelector = ({ monitorList, ui: { lastRefresh } }: AppSta monitorList, lastRefresh, }); + +export const overviewFiltersSelector = ({ overviewFilters }: AppState) => { + return overviewFilters.filters; +}; + +export const filterGroupDataSelector = ({ + overviewFilters: { loading, filters }, + ui: { esKuery }, +}: AppState) => ({ + esKuery, + filters, + loading, +}); diff --git a/x-pack/plugins/uptime/public/uptime_app.tsx b/x-pack/plugins/uptime/public/uptime_app.tsx index 0d18f959230d11..836d942d92165e 100644 --- a/x-pack/plugins/uptime/public/uptime_app.tsx +++ b/x-pack/plugins/uptime/public/uptime_app.tsx @@ -105,10 +105,7 @@ const Application = (props: UptimeAppProps) => {
- +
diff --git a/x-pack/plugins/uptime/server/lib/alerts/__tests__/common.test.ts b/x-pack/plugins/uptime/server/lib/alerts/__tests__/common.test.ts new file mode 100644 index 00000000000000..cd06370816cccc --- /dev/null +++ b/x-pack/plugins/uptime/server/lib/alerts/__tests__/common.test.ts @@ -0,0 +1,180 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { updateState } from '../common'; + +describe('updateState', () => { + let spy: jest.SpyInstance; + beforeEach(() => { + spy = jest.spyOn(Date.prototype, 'toISOString'); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + it('sets initial state values', () => { + spy.mockImplementation(() => 'foo date string'); + const result = updateState({}, false); + expect(spy).toHaveBeenCalledTimes(1); + expect(result).toMatchInlineSnapshot(` + Object { + "currentTriggerStarted": undefined, + "firstCheckedAt": "foo date string", + "firstTriggeredAt": undefined, + "isTriggered": false, + "lastCheckedAt": "foo date string", + "lastResolvedAt": undefined, + "lastTriggeredAt": undefined, + } + `); + }); + + it('updates the correct field in subsequent calls', () => { + spy + .mockImplementationOnce(() => 'first date string') + .mockImplementationOnce(() => 'second date string'); + const firstState = updateState({}, false); + const secondState = updateState(firstState, true); + expect(spy).toHaveBeenCalledTimes(2); + expect(firstState).toMatchInlineSnapshot(` + Object { + "currentTriggerStarted": undefined, + "firstCheckedAt": "first date string", + "firstTriggeredAt": undefined, + "isTriggered": false, + "lastCheckedAt": "first date string", + "lastResolvedAt": undefined, + "lastTriggeredAt": undefined, + } + `); + expect(secondState).toMatchInlineSnapshot(` + Object { + "currentTriggerStarted": "second date string", + "firstCheckedAt": "first date string", + "firstTriggeredAt": "second date string", + "isTriggered": true, + "lastCheckedAt": "second date string", + "lastResolvedAt": undefined, + "lastTriggeredAt": "second date string", + } + `); + }); + + it('correctly marks resolution times', () => { + spy + .mockImplementationOnce(() => 'first date string') + .mockImplementationOnce(() => 'second date string') + .mockImplementationOnce(() => 'third date string'); + const firstState = updateState({}, true); + const secondState = updateState(firstState, true); + const thirdState = updateState(secondState, false); + expect(spy).toHaveBeenCalledTimes(3); + expect(firstState).toMatchInlineSnapshot(` + Object { + "currentTriggerStarted": "first date string", + "firstCheckedAt": "first date string", + "firstTriggeredAt": "first date string", + "isTriggered": true, + "lastCheckedAt": "first date string", + "lastResolvedAt": undefined, + "lastTriggeredAt": "first date string", + } + `); + expect(secondState).toMatchInlineSnapshot(` + Object { + "currentTriggerStarted": "first date string", + "firstCheckedAt": "first date string", + "firstTriggeredAt": "first date string", + "isTriggered": true, + "lastCheckedAt": "second date string", + "lastResolvedAt": undefined, + "lastTriggeredAt": "second date string", + } + `); + expect(thirdState).toMatchInlineSnapshot(` + Object { + "currentTriggerStarted": undefined, + "firstCheckedAt": "first date string", + "firstTriggeredAt": "first date string", + "isTriggered": false, + "lastCheckedAt": "third date string", + "lastResolvedAt": "third date string", + "lastTriggeredAt": "second date string", + } + `); + }); + + it('correctly marks state fields across multiple triggers/resolutions', () => { + spy + .mockImplementationOnce(() => 'first date string') + .mockImplementationOnce(() => 'second date string') + .mockImplementationOnce(() => 'third date string') + .mockImplementationOnce(() => 'fourth date string') + .mockImplementationOnce(() => 'fifth date string'); + const firstState = updateState({}, false); + const secondState = updateState(firstState, true); + const thirdState = updateState(secondState, false); + const fourthState = updateState(thirdState, true); + const fifthState = updateState(fourthState, false); + expect(spy).toHaveBeenCalledTimes(5); + expect(firstState).toMatchInlineSnapshot(` + Object { + "currentTriggerStarted": undefined, + "firstCheckedAt": "first date string", + "firstTriggeredAt": undefined, + "isTriggered": false, + "lastCheckedAt": "first date string", + "lastResolvedAt": undefined, + "lastTriggeredAt": undefined, + } + `); + expect(secondState).toMatchInlineSnapshot(` + Object { + "currentTriggerStarted": "second date string", + "firstCheckedAt": "first date string", + "firstTriggeredAt": "second date string", + "isTriggered": true, + "lastCheckedAt": "second date string", + "lastResolvedAt": undefined, + "lastTriggeredAt": "second date string", + } + `); + expect(thirdState).toMatchInlineSnapshot(` + Object { + "currentTriggerStarted": undefined, + "firstCheckedAt": "first date string", + "firstTriggeredAt": "second date string", + "isTriggered": false, + "lastCheckedAt": "third date string", + "lastResolvedAt": "third date string", + "lastTriggeredAt": "second date string", + } + `); + expect(fourthState).toMatchInlineSnapshot(` + Object { + "currentTriggerStarted": "fourth date string", + "firstCheckedAt": "first date string", + "firstTriggeredAt": "second date string", + "isTriggered": true, + "lastCheckedAt": "fourth date string", + "lastResolvedAt": "third date string", + "lastTriggeredAt": "fourth date string", + } + `); + expect(fifthState).toMatchInlineSnapshot(` + Object { + "currentTriggerStarted": undefined, + "firstCheckedAt": "first date string", + "firstTriggeredAt": "second date string", + "isTriggered": false, + "lastCheckedAt": "fifth date string", + "lastResolvedAt": "fifth date string", + "lastTriggeredAt": "fourth date string", + } + `); + }); +}); diff --git a/x-pack/plugins/uptime/server/lib/alerts/__tests__/status_check.test.ts b/x-pack/plugins/uptime/server/lib/alerts/__tests__/status_check.test.ts index 24da3f3fa4d067..1cc0f1da820c1d 100644 --- a/x-pack/plugins/uptime/server/lib/alerts/__tests__/status_check.test.ts +++ b/x-pack/plugins/uptime/server/lib/alerts/__tests__/status_check.test.ts @@ -7,7 +7,6 @@ import { contextMessage, uniqueMonitorIds, - updateState, statusCheckAlertFactory, fullListByIdAndLocation, } from '../status_check'; @@ -337,179 +336,6 @@ describe('status check alert', () => { }); }); - describe('updateState', () => { - let spy: jest.SpyInstance; - beforeEach(() => { - spy = jest.spyOn(Date.prototype, 'toISOString'); - }); - - afterEach(() => { - jest.clearAllMocks(); - }); - - it('sets initial state values', () => { - spy.mockImplementation(() => 'foo date string'); - const result = updateState({}, false); - expect(spy).toHaveBeenCalledTimes(1); - expect(result).toMatchInlineSnapshot(` - Object { - "currentTriggerStarted": undefined, - "firstCheckedAt": "foo date string", - "firstTriggeredAt": undefined, - "isTriggered": false, - "lastCheckedAt": "foo date string", - "lastResolvedAt": undefined, - "lastTriggeredAt": undefined, - } - `); - }); - - it('updates the correct field in subsequent calls', () => { - spy - .mockImplementationOnce(() => 'first date string') - .mockImplementationOnce(() => 'second date string'); - const firstState = updateState({}, false); - const secondState = updateState(firstState, true); - expect(spy).toHaveBeenCalledTimes(2); - expect(firstState).toMatchInlineSnapshot(` - Object { - "currentTriggerStarted": undefined, - "firstCheckedAt": "first date string", - "firstTriggeredAt": undefined, - "isTriggered": false, - "lastCheckedAt": "first date string", - "lastResolvedAt": undefined, - "lastTriggeredAt": undefined, - } - `); - expect(secondState).toMatchInlineSnapshot(` - Object { - "currentTriggerStarted": "second date string", - "firstCheckedAt": "first date string", - "firstTriggeredAt": "second date string", - "isTriggered": true, - "lastCheckedAt": "second date string", - "lastResolvedAt": undefined, - "lastTriggeredAt": "second date string", - } - `); - }); - - it('correctly marks resolution times', () => { - spy - .mockImplementationOnce(() => 'first date string') - .mockImplementationOnce(() => 'second date string') - .mockImplementationOnce(() => 'third date string'); - const firstState = updateState({}, true); - const secondState = updateState(firstState, true); - const thirdState = updateState(secondState, false); - expect(spy).toHaveBeenCalledTimes(3); - expect(firstState).toMatchInlineSnapshot(` - Object { - "currentTriggerStarted": "first date string", - "firstCheckedAt": "first date string", - "firstTriggeredAt": "first date string", - "isTriggered": true, - "lastCheckedAt": "first date string", - "lastResolvedAt": undefined, - "lastTriggeredAt": "first date string", - } - `); - expect(secondState).toMatchInlineSnapshot(` - Object { - "currentTriggerStarted": "first date string", - "firstCheckedAt": "first date string", - "firstTriggeredAt": "first date string", - "isTriggered": true, - "lastCheckedAt": "second date string", - "lastResolvedAt": undefined, - "lastTriggeredAt": "second date string", - } - `); - expect(thirdState).toMatchInlineSnapshot(` - Object { - "currentTriggerStarted": undefined, - "firstCheckedAt": "first date string", - "firstTriggeredAt": "first date string", - "isTriggered": false, - "lastCheckedAt": "third date string", - "lastResolvedAt": "third date string", - "lastTriggeredAt": "second date string", - } - `); - }); - - it('correctly marks state fields across multiple triggers/resolutions', () => { - spy - .mockImplementationOnce(() => 'first date string') - .mockImplementationOnce(() => 'second date string') - .mockImplementationOnce(() => 'third date string') - .mockImplementationOnce(() => 'fourth date string') - .mockImplementationOnce(() => 'fifth date string'); - const firstState = updateState({}, false); - const secondState = updateState(firstState, true); - const thirdState = updateState(secondState, false); - const fourthState = updateState(thirdState, true); - const fifthState = updateState(fourthState, false); - expect(spy).toHaveBeenCalledTimes(5); - expect(firstState).toMatchInlineSnapshot(` - Object { - "currentTriggerStarted": undefined, - "firstCheckedAt": "first date string", - "firstTriggeredAt": undefined, - "isTriggered": false, - "lastCheckedAt": "first date string", - "lastResolvedAt": undefined, - "lastTriggeredAt": undefined, - } - `); - expect(secondState).toMatchInlineSnapshot(` - Object { - "currentTriggerStarted": "second date string", - "firstCheckedAt": "first date string", - "firstTriggeredAt": "second date string", - "isTriggered": true, - "lastCheckedAt": "second date string", - "lastResolvedAt": undefined, - "lastTriggeredAt": "second date string", - } - `); - expect(thirdState).toMatchInlineSnapshot(` - Object { - "currentTriggerStarted": undefined, - "firstCheckedAt": "first date string", - "firstTriggeredAt": "second date string", - "isTriggered": false, - "lastCheckedAt": "third date string", - "lastResolvedAt": "third date string", - "lastTriggeredAt": "second date string", - } - `); - expect(fourthState).toMatchInlineSnapshot(` - Object { - "currentTriggerStarted": "fourth date string", - "firstCheckedAt": "first date string", - "firstTriggeredAt": "second date string", - "isTriggered": true, - "lastCheckedAt": "fourth date string", - "lastResolvedAt": "third date string", - "lastTriggeredAt": "fourth date string", - } - `); - expect(fifthState).toMatchInlineSnapshot(` - Object { - "currentTriggerStarted": undefined, - "firstCheckedAt": "first date string", - "firstTriggeredAt": "second date string", - "isTriggered": false, - "lastCheckedAt": "fifth date string", - "lastResolvedAt": "fifth date string", - "lastTriggeredAt": "fourth date string", - } - `); - }); - }); - describe('uniqueMonitorIds', () => { let items: GetMonitorStatusResult[]; beforeEach(() => { diff --git a/x-pack/plugins/uptime/server/lib/alerts/__tests__/tls.test.ts b/x-pack/plugins/uptime/server/lib/alerts/__tests__/tls.test.ts new file mode 100644 index 00000000000000..2b74d608417cc2 --- /dev/null +++ b/x-pack/plugins/uptime/server/lib/alerts/__tests__/tls.test.ts @@ -0,0 +1,147 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import moment from 'moment'; +import { getCertSummary } from '../tls'; +import { Cert } from '../../../../common/runtime_types'; + +describe('tls alert', () => { + describe('getCertSummary', () => { + let mockCerts: Cert[]; + let diffSpy: jest.SpyInstance; + + beforeEach(() => { + diffSpy = jest.spyOn(moment.prototype, 'diff'); + mockCerts = [ + { + not_after: '2020-07-16T03:15:39.000Z', + not_before: '2019-07-24T03:15:39.000Z', + common_name: 'Common-One', + monitors: [{ name: 'monitor-one', id: 'monitor1' }], + sha256: 'abc', + }, + { + not_after: '2020-07-18T03:15:39.000Z', + not_before: '2019-07-20T03:15:39.000Z', + common_name: 'Common-Two', + monitors: [{ name: 'monitor-two', id: 'monitor2' }], + sha256: 'bcd', + }, + { + not_after: '2020-07-19T03:15:39.000Z', + not_before: '2019-07-22T03:15:39.000Z', + common_name: 'Common-Three', + monitors: [{ name: 'monitor-three', id: 'monitor3' }], + sha256: 'cde', + }, + { + not_after: '2020-07-25T03:15:39.000Z', + not_before: '2019-07-25T03:15:39.000Z', + common_name: 'Common-Four', + monitors: [{ name: 'monitor-four', id: 'monitor4' }], + sha256: 'def', + }, + ]; + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + it('sorts expiring certs appropriately when creating summary', () => { + diffSpy + .mockReturnValueOnce(900) + .mockReturnValueOnce(901) + .mockReturnValueOnce(902); + const result = getCertSummary( + mockCerts, + new Date('2020-07-20T05:00:00.000Z').valueOf(), + new Date('2019-03-01T00:00:00.000Z').valueOf() + ); + expect(result).toMatchInlineSnapshot(` + Object { + "agingCommonNameAndDate": "", + "agingCount": 0, + "count": 4, + "expiringCommonNameAndDate": "Common-One, expired on 2020-07-16T03:15:39.000Z 900 days ago.; Common-Two, expired on 2020-07-18T03:15:39.000Z 901 days ago.; Common-Three, expired on 2020-07-19T03:15:39.000Z 902 days ago.", + "expiringCount": 3, + "hasAging": null, + "hasExpired": true, + } + `); + }); + + it('sorts aging certs appropriate when creating summary', () => { + diffSpy + .mockReturnValueOnce(702) + .mockReturnValueOnce(701) + .mockReturnValueOnce(700); + const result = getCertSummary( + mockCerts, + new Date('2020-07-01T12:00:00.000Z').valueOf(), + new Date('2019-09-01T03:00:00.000Z').valueOf() + ); + expect(result).toMatchInlineSnapshot(` + Object { + "agingCommonNameAndDate": "Common-Two, valid since 2019-07-20T03:15:39.000Z, 702 days ago.; Common-Three, valid since 2019-07-22T03:15:39.000Z, 701 days ago.; Common-One, valid since 2019-07-24T03:15:39.000Z, 700 days ago.", + "agingCount": 4, + "count": 4, + "expiringCommonNameAndDate": "", + "expiringCount": 0, + "hasAging": true, + "hasExpired": null, + } + `); + }); + + it('handles negative diff values appropriately for aging certs', () => { + diffSpy + .mockReturnValueOnce(700) + .mockReturnValueOnce(-90) + .mockReturnValueOnce(-80); + const result = getCertSummary( + mockCerts, + new Date('2020-07-01T12:00:00.000Z').valueOf(), + new Date('2019-09-01T03:00:00.000Z').valueOf() + ); + expect(result).toMatchInlineSnapshot(` + Object { + "agingCommonNameAndDate": "Common-Two, valid since 2019-07-20T03:15:39.000Z, 700 days ago.; Common-Three, invalid until 2019-07-22T03:15:39.000Z, 90 days from now.; Common-One, invalid until 2019-07-24T03:15:39.000Z, 80 days from now.", + "agingCount": 4, + "count": 4, + "expiringCommonNameAndDate": "", + "expiringCount": 0, + "hasAging": true, + "hasExpired": null, + } + `); + }); + + it('handles negative diff values appropriately for expiring certs', () => { + diffSpy + // negative days are in the future, positive days are in the past + .mockReturnValueOnce(-96) + .mockReturnValueOnce(-94) + .mockReturnValueOnce(2); + const result = getCertSummary( + mockCerts, + new Date('2020-07-20T05:00:00.000Z').valueOf(), + new Date('2019-03-01T00:00:00.000Z').valueOf() + ); + expect(result).toMatchInlineSnapshot(` + Object { + "agingCommonNameAndDate": "", + "agingCount": 0, + "count": 4, + "expiringCommonNameAndDate": "Common-One, expires on 2020-07-16T03:15:39.000Z in 96 days.; Common-Two, expires on 2020-07-18T03:15:39.000Z in 94 days.; Common-Three, expired on 2020-07-19T03:15:39.000Z 2 days ago.", + "expiringCount": 3, + "hasAging": null, + "hasExpired": true, + } + `); + }); + }); +}); diff --git a/x-pack/plugins/uptime/server/lib/alerts/common.ts b/x-pack/plugins/uptime/server/lib/alerts/common.ts new file mode 100644 index 00000000000000..f33cd9052d2295 --- /dev/null +++ b/x-pack/plugins/uptime/server/lib/alerts/common.ts @@ -0,0 +1,56 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { isRight } from 'fp-ts/lib/Either'; +import { UptimeCommonState, UptimeCommonStateType } from '../../../common/runtime_types'; + +export type UpdateUptimeAlertState = ( + state: Record, + isTriggeredNow: boolean +) => UptimeCommonState; + +export const updateState: UpdateUptimeAlertState = (state, isTriggeredNow) => { + const now = new Date().toISOString(); + const decoded = UptimeCommonStateType.decode(state); + if (!isRight(decoded)) { + const triggerVal = isTriggeredNow ? now : undefined; + return { + currentTriggerStarted: triggerVal, + firstCheckedAt: now, + firstTriggeredAt: triggerVal, + isTriggered: isTriggeredNow, + lastTriggeredAt: triggerVal, + lastCheckedAt: now, + lastResolvedAt: undefined, + }; + } + const { + currentTriggerStarted, + firstCheckedAt, + firstTriggeredAt, + lastTriggeredAt, + // this is the stale trigger status, we're naming it `wasTriggered` + // to differentiate it from the `isTriggeredNow` param + isTriggered: wasTriggered, + lastResolvedAt, + } = decoded.right; + + let cts: string | undefined; + if (isTriggeredNow && !currentTriggerStarted) { + cts = now; + } else if (isTriggeredNow) { + cts = currentTriggerStarted; + } + return { + currentTriggerStarted: cts, + firstCheckedAt: firstCheckedAt ?? now, + firstTriggeredAt: isTriggeredNow && !firstTriggeredAt ? now : firstTriggeredAt, + lastCheckedAt: now, + lastTriggeredAt: isTriggeredNow ? now : lastTriggeredAt, + lastResolvedAt: !isTriggeredNow && wasTriggered ? now : lastResolvedAt, + isTriggered: isTriggeredNow, + }; +}; diff --git a/x-pack/plugins/uptime/server/lib/alerts/index.ts b/x-pack/plugins/uptime/server/lib/alerts/index.ts index 0e61fd70e0024b..661df39ece6286 100644 --- a/x-pack/plugins/uptime/server/lib/alerts/index.ts +++ b/x-pack/plugins/uptime/server/lib/alerts/index.ts @@ -6,5 +6,9 @@ import { UptimeAlertTypeFactory } from './types'; import { statusCheckAlertFactory } from './status_check'; +import { tlsAlertFactory } from './tls'; -export const uptimeAlertTypeFactories: UptimeAlertTypeFactory[] = [statusCheckAlertFactory]; +export const uptimeAlertTypeFactories: UptimeAlertTypeFactory[] = [ + statusCheckAlertFactory, + tlsAlertFactory, +]; diff --git a/x-pack/plugins/uptime/server/lib/alerts/status_check.ts b/x-pack/plugins/uptime/server/lib/alerts/status_check.ts index f9df559a3977ba..0eaa12e8f4372b 100644 --- a/x-pack/plugins/uptime/server/lib/alerts/status_check.ts +++ b/x-pack/plugins/uptime/server/lib/alerts/status_check.ts @@ -11,13 +11,11 @@ import { i18n } from '@kbn/i18n'; import { AlertExecutorOptions } from '../../../../alerting/server'; import { UptimeAlertTypeFactory } from './types'; import { GetMonitorStatusResult } from '../requests'; -import { - StatusCheckExecutorParamsType, - StatusCheckAlertStateType, - StatusCheckAlertState, -} from '../../../common/runtime_types'; +import { StatusCheckExecutorParamsType } from '../../../common/runtime_types'; import { ACTION_GROUP_DEFINITIONS } from '../../../common/constants'; import { savedObjectsAdapter } from '../saved_objects'; +import { updateState } from './common'; +import { commonStateTranslations } from './translations'; const { MONITOR_STATUS } = ACTION_GROUP_DEFINITIONS; @@ -34,7 +32,7 @@ export const uniqueMonitorIds = (items: GetMonitorStatusResult[]): Set = /** * Generates a message to include in contexts of alerts. * @param monitors the list of monitors to include in the message - * @param max + * @param max the maximum number of items the summary should contain */ export const contextMessage = (monitorIds: string[], max: number): string => { const MIN = 2; @@ -122,58 +120,11 @@ export const fullListByIdAndLocation = ( ); }; -export const updateState = ( - state: Record, - isTriggeredNow: boolean -): StatusCheckAlertState => { - const now = new Date().toISOString(); - const decoded = StatusCheckAlertStateType.decode(state); - if (!isRight(decoded)) { - const triggerVal = isTriggeredNow ? now : undefined; - return { - currentTriggerStarted: triggerVal, - firstCheckedAt: now, - firstTriggeredAt: triggerVal, - isTriggered: isTriggeredNow, - lastTriggeredAt: triggerVal, - lastCheckedAt: now, - lastResolvedAt: undefined, - }; - } - const { - currentTriggerStarted, - firstCheckedAt, - firstTriggeredAt, - lastTriggeredAt, - // this is the stale trigger status, we're naming it `wasTriggered` - // to differentiate it from the `isTriggeredNow` param - isTriggered: wasTriggered, - lastResolvedAt, - } = decoded.right; - - let cts: string | undefined; - if (isTriggeredNow && !currentTriggerStarted) { - cts = now; - } else if (isTriggeredNow) { - cts = currentTriggerStarted; - } - - return { - currentTriggerStarted: cts, - firstCheckedAt: firstCheckedAt ?? now, - firstTriggeredAt: isTriggeredNow && !firstTriggeredAt ? now : firstTriggeredAt, - lastCheckedAt: now, - lastTriggeredAt: isTriggeredNow ? now : lastTriggeredAt, - lastResolvedAt: !isTriggeredNow && wasTriggered ? now : lastResolvedAt, - isTriggered: isTriggeredNow, - }; -}; - // Right now the maximum number of monitors shown in the message is hardcoded here. // we might want to make this a parameter in the future const DEFAULT_MAX_MESSAGE_ROWS = 3; -export const statusCheckAlertFactory: UptimeAlertTypeFactory = (server, libs) => ({ +export const statusCheckAlertFactory: UptimeAlertTypeFactory = (_server, libs) => ({ id: 'xpack.uptime.alerts.monitorStatus', name: i18n.translate('xpack.uptime.alerts.monitorStatus', { defaultMessage: 'Uptime monitor status', @@ -218,72 +169,7 @@ export const statusCheckAlertFactory: UptimeAlertTypeFactory = (server, libs) => ), }, ], - state: [ - { - name: 'firstCheckedAt', - description: i18n.translate( - 'xpack.uptime.alerts.monitorStatus.actionVariables.state.firstCheckedAt', - { - defaultMessage: 'Timestamp indicating when this alert first checked', - } - ), - }, - { - name: 'firstTriggeredAt', - description: i18n.translate( - 'xpack.uptime.alerts.monitorStatus.actionVariables.state.firstTriggeredAt', - { - defaultMessage: 'Timestamp indicating when the alert first triggered', - } - ), - }, - { - name: 'currentTriggerStarted', - description: i18n.translate( - 'xpack.uptime.alerts.monitorStatus.actionVariables.state.currentTriggerStarted', - { - defaultMessage: - 'Timestamp indicating when the current trigger state began, if alert is triggered', - } - ), - }, - { - name: 'isTriggered', - description: i18n.translate( - 'xpack.uptime.alerts.monitorStatus.actionVariables.state.isTriggered', - { - defaultMessage: `Flag indicating if the alert is currently triggering`, - } - ), - }, - { - name: 'lastCheckedAt', - description: i18n.translate( - 'xpack.uptime.alerts.monitorStatus.actionVariables.state.lastCheckedAt', - { - defaultMessage: `Timestamp indicating the alert's most recent check time`, - } - ), - }, - { - name: 'lastResolvedAt', - description: i18n.translate( - 'xpack.uptime.alerts.monitorStatus.actionVariables.state.lastResolvedAt', - { - defaultMessage: `Timestamp indicating the most recent resolution time for this alert`, - } - ), - }, - { - name: 'lastTriggeredAt', - description: i18n.translate( - 'xpack.uptime.alerts.monitorStatus.actionVariables.state.lastTriggeredAt', - { - defaultMessage: `Timestamp indicating the alert's most recent trigger time`, - } - ), - }, - ], + state: [...commonStateTranslations], }, async executor(options: AlertExecutorOptions) { const { params: rawParams } = options; diff --git a/x-pack/plugins/uptime/server/lib/alerts/tls.ts b/x-pack/plugins/uptime/server/lib/alerts/tls.ts new file mode 100644 index 00000000000000..518e3ed93b4249 --- /dev/null +++ b/x-pack/plugins/uptime/server/lib/alerts/tls.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import moment from 'moment'; +import { schema } from '@kbn/config-schema'; +import { UptimeAlertTypeFactory } from './types'; +import { savedObjectsAdapter } from '../saved_objects'; +import { updateState } from './common'; +import { ACTION_GROUP_DEFINITIONS, DYNAMIC_SETTINGS_DEFAULTS } from '../../../common/constants'; +import { Cert, CertResult } from '../../../common/runtime_types'; +import { commonStateTranslations, tlsTranslations } from './translations'; + +const { TLS } = ACTION_GROUP_DEFINITIONS; + +const DEFAULT_FROM = 'now-1d'; +const DEFAULT_TO = 'now'; +const DEFAULT_INDEX = 0; +const DEFAULT_SIZE = 20; + +interface TlsAlertState { + count: number; + agingCount: number; + agingCommonNameAndDate: string; + expiringCount: number; + expiringCommonNameAndDate: string; + hasAging: true | null; + hasExpired: true | null; +} + +const sortCerts = (a: string, b: string) => new Date(a).valueOf() - new Date(b).valueOf(); + +const mapCertsToSummaryString = ( + certs: Cert[], + certLimitMessage: (cert: Cert) => string, + maxSummaryItems: number +): string => + certs + .slice(0, maxSummaryItems) + .map(cert => `${cert.common_name}, ${certLimitMessage(cert)}`) + .reduce((prev, cur) => (prev === '' ? cur : prev.concat(`; ${cur}`)), ''); + +const getValidAfter = ({ not_after: date }: Cert) => { + if (!date) return 'Error, missing `certificate_not_valid_after` date.'; + const relativeDate = moment().diff(date, 'days'); + return relativeDate >= 0 + ? tlsTranslations.validAfterExpiredString(date, relativeDate) + : tlsTranslations.validAfterExpiringString(date, Math.abs(relativeDate)); +}; + +const getValidBefore = ({ not_before: date }: Cert): string => { + if (!date) return 'Error, missing `certificate_not_valid_before` date.'; + const relativeDate = moment().diff(date, 'days'); + return relativeDate >= 0 + ? tlsTranslations.validBeforeExpiredString(date, relativeDate) + : tlsTranslations.validBeforeExpiringString(date, Math.abs(relativeDate)); +}; + +export const getCertSummary = ( + certs: Cert[], + expirationThreshold: number, + ageThreshold: number, + maxSummaryItems: number = 3 +): TlsAlertState => { + certs.sort((a, b) => sortCerts(a.not_after ?? '', b.not_after ?? '')); + const expiring = certs.filter( + cert => new Date(cert.not_after ?? '').valueOf() < expirationThreshold + ); + + certs.sort((a, b) => sortCerts(a.not_before ?? '', b.not_before ?? '')); + const aging = certs.filter(cert => new Date(cert.not_before ?? '').valueOf() < ageThreshold); + + return { + count: certs.length, + agingCount: aging.length, + agingCommonNameAndDate: mapCertsToSummaryString(aging, getValidBefore, maxSummaryItems), + expiringCommonNameAndDate: mapCertsToSummaryString(expiring, getValidAfter, maxSummaryItems), + expiringCount: expiring.length, + hasAging: aging.length > 0 ? true : null, + hasExpired: expiring.length > 0 ? true : null, + }; +}; + +export const tlsAlertFactory: UptimeAlertTypeFactory = (_server, libs) => ({ + id: 'xpack.uptime.alerts.tls', + name: tlsTranslations.alertFactoryName, + validate: { + params: schema.object({}), + }, + defaultActionGroupId: TLS.id, + actionGroups: [ + { + id: TLS.id, + name: TLS.name, + }, + ], + actionVariables: { + context: [], + state: [...tlsTranslations.actionVariables, ...commonStateTranslations], + }, + async executor(options) { + const { + services: { alertInstanceFactory, callCluster, savedObjectsClient }, + state, + } = options; + const dynamicSettings = await savedObjectsAdapter.getUptimeDynamicSettings(savedObjectsClient); + + const { certs, total }: CertResult = await libs.requests.getCerts({ + callES: callCluster, + dynamicSettings, + from: DEFAULT_FROM, + to: DEFAULT_TO, + index: DEFAULT_INDEX, + size: DEFAULT_SIZE, + notValidAfter: `now+${dynamicSettings.certThresholds?.expiration ?? + DYNAMIC_SETTINGS_DEFAULTS.certThresholds?.expiration}d`, + notValidBefore: `now-${dynamicSettings.certThresholds?.age ?? + DYNAMIC_SETTINGS_DEFAULTS.certThresholds?.age}d`, + sortBy: 'common_name', + direction: 'desc', + }); + + const foundCerts = total > 0; + + if (foundCerts) { + const absoluteExpirationThreshold = moment() + .add( + dynamicSettings.certThresholds?.expiration ?? + DYNAMIC_SETTINGS_DEFAULTS.certThresholds?.expiration, + 'd' + ) + .valueOf(); + const absoluteAgeThreshold = moment() + .subtract( + dynamicSettings.certThresholds?.age ?? DYNAMIC_SETTINGS_DEFAULTS.certThresholds?.age, + 'd' + ) + .valueOf(); + const alertInstance = alertInstanceFactory(TLS.id); + const summary = getCertSummary(certs, absoluteExpirationThreshold, absoluteAgeThreshold); + alertInstance.replaceState({ + ...updateState(state, foundCerts), + ...summary, + }); + alertInstance.scheduleActions(TLS.id); + } + + return updateState(state, foundCerts); + }, +}); diff --git a/x-pack/plugins/uptime/server/lib/alerts/translations.ts b/x-pack/plugins/uptime/server/lib/alerts/translations.ts new file mode 100644 index 00000000000000..e41930aad5af0b --- /dev/null +++ b/x-pack/plugins/uptime/server/lib/alerts/translations.ts @@ -0,0 +1,150 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; + +export const commonStateTranslations = [ + { + name: 'firstCheckedAt', + description: i18n.translate( + 'xpack.uptime.alerts.monitorStatus.actionVariables.state.firstCheckedAt', + { + defaultMessage: 'Timestamp indicating when this alert first checked', + } + ), + }, + { + name: 'firstTriggeredAt', + description: i18n.translate( + 'xpack.uptime.alerts.monitorStatus.actionVariables.state.firstTriggeredAt', + { + defaultMessage: 'Timestamp indicating when the alert first triggered', + } + ), + }, + { + name: 'currentTriggerStarted', + description: i18n.translate( + 'xpack.uptime.alerts.monitorStatus.actionVariables.state.currentTriggerStarted', + { + defaultMessage: + 'Timestamp indicating when the current trigger state began, if alert is triggered', + } + ), + }, + { + name: 'isTriggered', + description: i18n.translate( + 'xpack.uptime.alerts.monitorStatus.actionVariables.state.isTriggered', + { + defaultMessage: `Flag indicating if the alert is currently triggering`, + } + ), + }, + { + name: 'lastCheckedAt', + description: i18n.translate( + 'xpack.uptime.alerts.monitorStatus.actionVariables.state.lastCheckedAt', + { + defaultMessage: `Timestamp indicating the alert's most recent check time`, + } + ), + }, + { + name: 'lastResolvedAt', + description: i18n.translate( + 'xpack.uptime.alerts.monitorStatus.actionVariables.state.lastResolvedAt', + { + defaultMessage: `Timestamp indicating the most recent resolution time for this alert`, + } + ), + }, + { + name: 'lastTriggeredAt', + description: i18n.translate( + 'xpack.uptime.alerts.monitorStatus.actionVariables.state.lastTriggeredAt', + { + defaultMessage: `Timestamp indicating the alert's most recent trigger time`, + } + ), + }, +]; + +export const tlsTranslations = { + alertFactoryName: i18n.translate('xpack.uptime.alerts.tls', { + defaultMessage: 'Uptime TLS', + }), + actionVariables: [ + { + name: 'count', + description: i18n.translate('xpack.uptime.alerts.tls.actionVariables.state.count', { + defaultMessage: 'The number of certs detected by the alert executor', + }), + }, + { + name: 'expiringCount', + description: i18n.translate('xpack.uptime.alerts.tls.actionVariables.state.expiringCount', { + defaultMessage: 'The number of expiring certs detected by the alert.', + }), + }, + { + name: 'expiringCommonNameAndDate', + description: i18n.translate( + 'xpack.uptime.alerts.tls.actionVariables.state.expiringCommonNameAndDate', + { + defaultMessage: 'The common names and expiration date/time of the detected certs', + } + ), + }, + { + name: 'agingCount', + description: i18n.translate('xpack.uptime.alerts.tls.actionVariables.state.agingCount', { + defaultMessage: 'The number of detected certs that are becoming too old.', + }), + }, + { + name: 'agingCommonNameAndDate', + description: i18n.translate( + 'xpack.uptime.alerts.tls.actionVariables.state.agingCommonNameAndDate', + { + defaultMessage: 'The common names and expiration date/time of the detected certs.', + } + ), + }, + ], + validAfterExpiredString: (date: string, relativeDate: number) => + i18n.translate('xpack.uptime.alerts.tls.validAfterExpiredString', { + defaultMessage: `expired on {date} {relativeDate} days ago.`, + values: { + date, + relativeDate, + }, + }), + validAfterExpiringString: (date: string, relativeDate: number) => + i18n.translate('xpack.uptime.alerts.tls.validAfterExpiringString', { + defaultMessage: `expires on {date} in {relativeDate} days.`, + values: { + date, + relativeDate, + }, + }), + validBeforeExpiredString: (date: string, relativeDate: number) => + i18n.translate('xpack.uptime.alerts.tls.validBeforeExpiredString', { + defaultMessage: 'valid since {date}, {relativeDate} days ago.', + values: { + date, + relativeDate, + }, + }), + validBeforeExpiringString: (date: string, relativeDate: number) => + i18n.translate('xpack.uptime.alerts.tls.validBeforeExpiringString', { + defaultMessage: 'invalid until {date}, {relativeDate} days from now.', + values: { + date, + relativeDate, + }, + }), +}; diff --git a/x-pack/plugins/uptime/server/lib/requests/__tests__/__snapshots__/get_ping_histogram.test.ts.snap b/x-pack/plugins/uptime/server/lib/requests/__tests__/__snapshots__/get_ping_histogram.test.ts.snap index 0dafa5144c25a2..37dec410664eff 100644 --- a/x-pack/plugins/uptime/server/lib/requests/__tests__/__snapshots__/get_ping_histogram.test.ts.snap +++ b/x-pack/plugins/uptime/server/lib/requests/__tests__/__snapshots__/get_ping_histogram.test.ts.snap @@ -31,19 +31,19 @@ Object { "histogram": Array [ Object { "downCount": 1, - "upCount": 0, + "upCount": 2, "x": 1, "y": 1, }, Object { "downCount": 2, - "upCount": 0, + "upCount": 2, "x": 2, "y": 1, }, Object { "downCount": 1, - "upCount": 0, + "upCount": 3, "x": 3, "y": 1, }, @@ -52,46 +52,6 @@ Object { } `; -exports[`getPingHistogram returns a down-filtered array for when filtered by down status 1`] = ` -Object { - "histogram": Array [ - Object { - "downCount": 1, - "upCount": 0, - "x": 1, - "y": 1, - }, - Object { - "downCount": undefined, - "upCount": 0, - "x": 2, - "y": 1, - }, - ], - "interval": "1d", -} -`; - -exports[`getPingHistogram returns a down-filtered array for when filtered by up status 1`] = ` -Object { - "histogram": Array [ - Object { - "downCount": 0, - "upCount": 2, - "x": 1, - "y": 1, - }, - Object { - "downCount": 0, - "upCount": 2, - "x": 2, - "y": 1, - }, - ], - "interval": "1s", -} -`; - exports[`getPingHistogram returns a single bucket if array has 1 1`] = ` Object { "histogram": Array [ diff --git a/x-pack/plugins/uptime/server/lib/requests/__tests__/get_ping_histogram.test.ts b/x-pack/plugins/uptime/server/lib/requests/__tests__/get_ping_histogram.test.ts index e456670a5e68de..9042186145eb71 100644 --- a/x-pack/plugins/uptime/server/lib/requests/__tests__/get_ping_histogram.test.ts +++ b/x-pack/plugins/uptime/server/lib/requests/__tests__/get_ping_histogram.test.ts @@ -145,7 +145,6 @@ describe('getPingHistogram', () => { to: '5678', filters: JSON.stringify(searchFilter), monitorId: undefined, - statusFilter: 'down', }); expect(mockEsClient).toHaveBeenCalledTimes(1); @@ -205,44 +204,4 @@ describe('getPingHistogram', () => { expect(mockEsClient).toHaveBeenCalledTimes(1); expect(result).toMatchSnapshot(); }); - - it('returns a down-filtered array for when filtered by down status', async () => { - expect.assertions(2); - const mockEsClient = jest.fn(); - standardMockResponse.aggregations.timeseries.interval = '1d'; - mockEsClient.mockReturnValue(standardMockResponse); - const result = await getPingHistogram({ - callES: mockEsClient, - dynamicSettings: DYNAMIC_SETTINGS_DEFAULTS, - from: '1234', - to: '5678', - filters: '', - monitorId: undefined, - statusFilter: 'down', - }); - - expect(mockEsClient).toHaveBeenCalledTimes(1); - expect(result).toMatchSnapshot(); - }); - - it('returns a down-filtered array for when filtered by up status', async () => { - expect.assertions(2); - const mockEsClient = jest.fn(); - - standardMockResponse.aggregations.timeseries.interval = '1s'; - mockEsClient.mockReturnValue(standardMockResponse); - - const result = await getPingHistogram({ - callES: mockEsClient, - dynamicSettings: DYNAMIC_SETTINGS_DEFAULTS, - from: '1234', - to: '5678', - filters: '', - monitorId: undefined, - statusFilter: 'up', - }); - - expect(mockEsClient).toHaveBeenCalledTimes(1); - expect(result).toMatchSnapshot(); - }); }); diff --git a/x-pack/plugins/uptime/server/lib/requests/get_certs.ts b/x-pack/plugins/uptime/server/lib/requests/get_certs.ts index 6820cd69376d18..57a59936ddf7c6 100644 --- a/x-pack/plugins/uptime/server/lib/requests/get_certs.ts +++ b/x-pack/plugins/uptime/server/lib/requests/get_certs.ts @@ -20,8 +20,10 @@ export const getCerts: UMElasticsearchQueryFn = asyn index, from, to, - search, size, + search, + notValidBefore, + notValidAfter, sortBy, direction, }) => { @@ -91,6 +93,10 @@ export const getCerts: UMElasticsearchQueryFn = asyn }, }; + if (!params.body.query.bool.should) { + params.body.query.bool.should = []; + } + if (search) { params.body.query.bool.minimum_should_match = 1; params.body.query.bool.should = [ @@ -110,6 +116,35 @@ export const getCerts: UMElasticsearchQueryFn = asyn ]; } + if (notValidBefore || notValidAfter) { + const validityFilters: any = { + bool: { + should: [], + }, + }; + if (notValidBefore) { + validityFilters.bool.should.push({ + range: { + 'tls.certificate_not_valid_before': { + lte: notValidBefore, + }, + }, + }); + } + if (notValidAfter) { + validityFilters.bool.should.push({ + range: { + 'tls.certificate_not_valid_after': { + lte: notValidAfter, + }, + }, + }); + } + + params.body.query.bool.filter.push(validityFilters); + } + + // console.log(JSON.stringify(params, null, 2)); const result = await callES('search', params); const certs = (result?.hits?.hits ?? []).map((hit: any) => { diff --git a/x-pack/plugins/uptime/server/lib/requests/get_ping_histogram.ts b/x-pack/plugins/uptime/server/lib/requests/get_ping_histogram.ts index 299913c8dff086..d33e98c7ba8e74 100644 --- a/x-pack/plugins/uptime/server/lib/requests/get_ping_histogram.ts +++ b/x-pack/plugins/uptime/server/lib/requests/get_ping_histogram.ts @@ -18,14 +18,12 @@ export interface GetPingHistogramParams { filters?: string | null; /** @member monitorId optional limit to monitorId */ monitorId?: string | null; - /** @member statusFilter special filter targeting the latest status of each monitor */ - statusFilter?: string | null; } export const getPingHistogram: UMElasticsearchQueryFn< GetPingHistogramParams, HistogramResult -> = async ({ callES, dynamicSettings, from, to, filters, monitorId, statusFilter }) => { +> = async ({ callES, dynamicSettings, from, to, filters, monitorId }) => { const boolFilters = filters ? JSON.parse(filters) : null; const additionalFilters = []; if (monitorId) { @@ -81,8 +79,8 @@ export const getPingHistogram: UMElasticsearchQueryFn< const upCount: number = bucket.up.doc_count; return { x, - downCount: statusFilter && statusFilter !== 'down' ? 0 : downCount, - upCount: statusFilter && statusFilter !== 'up' ? 0 : upCount, + downCount, + upCount, y: 1, }; }); diff --git a/x-pack/plugins/uptime/server/lib/requests/get_snapshot_counts.ts b/x-pack/plugins/uptime/server/lib/requests/get_snapshot_counts.ts index b57bc87d454183..92295a38cffb4f 100644 --- a/x-pack/plugins/uptime/server/lib/requests/get_snapshot_counts.ts +++ b/x-pack/plugins/uptime/server/lib/requests/get_snapshot_counts.ts @@ -13,7 +13,6 @@ export interface GetSnapshotCountParams { dateRangeStart: string; dateRangeEnd: string; filters?: string | null; - statusFilter?: string; } export const getSnapshotCount: UMElasticsearchQueryFn = async ({ @@ -22,12 +21,7 @@ export const getSnapshotCount: UMElasticsearchQueryFn => { - if (!(statusFilter === 'up' || statusFilter === 'down' || statusFilter === undefined)) { - throw new Error(`Invalid status filter value '${statusFilter}'`); - } - const context = new QueryContext( callES, heartbeatIndices, @@ -35,18 +29,13 @@ export const getSnapshotCount: UMElasticsearchQueryFn => { @@ -55,7 +44,13 @@ const statusCount = async (context: QueryContext): Promise => { body: statusCountBody(await context.dateAndCustomFilters()), }); - return res.aggregations.counts.value; + return ( + res.aggregations?.counts?.value ?? { + total: 0, + up: 0, + down: 0, + } + ); }; const statusCountBody = (filters: any): any => { diff --git a/x-pack/plugins/uptime/server/lib/requests/search/find_potential_matches.ts b/x-pack/plugins/uptime/server/lib/requests/search/find_potential_matches.ts index e60c52660915a1..a3e7324086073f 100644 --- a/x-pack/plugins/uptime/server/lib/requests/search/find_potential_matches.ts +++ b/x-pack/plugins/uptime/server/lib/requests/search/find_potential_matches.ts @@ -47,7 +47,7 @@ export const findPotentialMatches = async ( return { monitorIds, checkGroups, - searchAfter: queryResult.aggregations.monitors.after_key, + searchAfter: queryResult.aggregations?.monitors?.after_key, }; }; diff --git a/x-pack/plugins/uptime/server/rest_api/pings/get_ping_histogram.ts b/x-pack/plugins/uptime/server/rest_api/pings/get_ping_histogram.ts index 41078f735920b8..a5899978890696 100644 --- a/x-pack/plugins/uptime/server/rest_api/pings/get_ping_histogram.ts +++ b/x-pack/plugins/uptime/server/rest_api/pings/get_ping_histogram.ts @@ -17,12 +17,11 @@ export const createGetPingHistogramRoute: UMRestApiRouteFactory = (libs: UMServe dateStart: schema.string(), dateEnd: schema.string(), monitorId: schema.maybe(schema.string()), - statusFilter: schema.maybe(schema.string()), filters: schema.maybe(schema.string()), }), }, handler: async ({ callES, dynamicSettings }, _context, request, response): Promise => { - const { dateStart, dateEnd, statusFilter, monitorId, filters } = request.query; + const { dateStart, dateEnd, monitorId, filters } = request.query; const result = await libs.requests.getPingHistogram({ callES, @@ -30,7 +29,6 @@ export const createGetPingHistogramRoute: UMRestApiRouteFactory = (libs: UMServe from: dateStart, to: dateEnd, monitorId, - statusFilter, filters, }); diff --git a/x-pack/plugins/uptime/server/rest_api/snapshot/get_snapshot_count.ts b/x-pack/plugins/uptime/server/rest_api/snapshot/get_snapshot_count.ts index 7809e102a499f8..9502335e4e5a8f 100644 --- a/x-pack/plugins/uptime/server/rest_api/snapshot/get_snapshot_count.ts +++ b/x-pack/plugins/uptime/server/rest_api/snapshot/get_snapshot_count.ts @@ -17,18 +17,16 @@ export const createGetSnapshotCount: UMRestApiRouteFactory = (libs: UMServerLibs dateRangeStart: schema.string(), dateRangeEnd: schema.string(), filters: schema.maybe(schema.string()), - statusFilter: schema.maybe(schema.string()), }), }, handler: async ({ callES, dynamicSettings }, _context, request, response): Promise => { - const { dateRangeStart, dateRangeEnd, filters, statusFilter } = request.query; + const { dateRangeStart, dateRangeEnd, filters } = request.query; const result = await libs.requests.getSnapshotCount({ callES, dynamicSettings, dateRangeStart, dateRangeEnd, filters, - statusFilter, }); return response.ok({ body: { diff --git a/x-pack/run_functional_tests.sh b/x-pack/run_functional_tests.sh new file mode 100755 index 00000000000000..e94f283ea03942 --- /dev/null +++ b/x-pack/run_functional_tests.sh @@ -0,0 +1,3 @@ +export TEST_KIBANA_URL="http://elastic:mlqa_admin@localhost:5601" +export TEST_ES_URL="http://elastic:mlqa_admin@localhost:9200" +node ../scripts/functional_test_runner --include-tag walterra diff --git a/x-pack/test/api_integration/apis/fleet/agents/acks.ts b/x-pack/test/api_integration/apis/fleet/agents/acks.ts index adde6dd184b817..084f2b7a656dc3 100644 --- a/x-pack/test/api_integration/apis/fleet/agents/acks.ts +++ b/x-pack/test/api_integration/apis/fleet/agents/acks.ts @@ -106,7 +106,7 @@ export default function(providerContext: FtrProviderContext) { item.action_id === '48cebde1-c906-4893-b89f-595d943b72a2' ); expect(expectedEvents.length).to.eql(2); - const expectedEvent = expectedEvents.find( + const { id, ...expectedEvent } = expectedEvents.find( (item: Record) => item.action_id === '48cebde1-c906-4893-b89f-595d943b72a1' ); expect(expectedEvent).to.eql({ diff --git a/x-pack/test/api_integration/apis/infra/metadata.ts b/x-pack/test/api_integration/apis/infra/metadata.ts index 5187cc5e3ec26a..d3551a139bf173 100644 --- a/x-pack/test/api_integration/apis/infra/metadata.ts +++ b/x-pack/test/api_integration/apis/infra/metadata.ts @@ -29,11 +29,6 @@ const timeRange800withAws = { to: DATES[`8.0.0`].logs_and_metrics_with_aws.max, }; -const timeRange800 = { - from: DATES['8.0.0'].logs_and_metrics.min, - to: DATES[`8.0.0`].logs_and_metrics.max, -}; - export default function({ getService }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const supertest = getService('supertest'); @@ -269,42 +264,6 @@ export default function({ getService }: FtrProviderContext) { } }); }); - describe('APM metrics', () => { - const archiveName = 'infra/8.0.0/metrics_and_apm'; - before(() => esArchiver.load(archiveName)); - after(() => esArchiver.unload(archiveName)); - - it('host without APM data', async () => { - const metadata = await fetchMetadata({ - sourceId: 'default', - nodeId: 'gke-observability-8--observability-8--bc1afd95-f0zc', - nodeType: 'host', - timeRange: timeRange800, - }); - if (metadata) { - expect( - metadata.features.some(f => f.name === 'apm.transaction' && f.source === 'apm') - ).to.be(false); - } else { - throw new Error('Metadata should never be empty'); - } - }); - it('pod with APM data', async () => { - const metadata = await fetchMetadata({ - sourceId: 'default', - nodeId: 'c1031331-9ae0-11e9-9a96-42010a84004d', - nodeType: 'pod', - timeRange: timeRange800, - }); - if (metadata) { - expect( - metadata.features.some(f => f.name === 'apm.transaction' && f.source === 'apm') - ).to.be(true); - } else { - throw new Error('Metadata should never be empty'); - } - }); - }); }); }); } diff --git a/x-pack/test/api_integration/apis/infra/metrics_alerting.ts b/x-pack/test/api_integration/apis/infra/metrics_alerting.ts index 5c43e8938a8c12..b4ae29a2f3f856 100644 --- a/x-pack/test/api_integration/apis/infra/metrics_alerting.ts +++ b/x-pack/test/api_integration/apis/infra/metrics_alerting.ts @@ -57,21 +57,6 @@ export default function({ getService }: FtrProviderContext) { expect(result.hits).to.be.ok(); expect(result.aggregations).to.be.ok(); }); - it('should work with a filterQuery in KQL format', async () => { - const searchBody = getElasticsearchMetricQuery( - getSearchParams('avg'), - '@timestamp', - undefined, - '"agent.hostname":"foo"' - ); - const result = await client.search({ - index, - body: searchBody, - }); - expect(result.error).to.not.be.ok(); - expect(result.hits).to.be.ok(); - expect(result.aggregations).to.be.ok(); - }); }); describe('querying with a groupBy parameter', () => { for (const aggType of aggs) { diff --git a/x-pack/test/api_integration/apis/uptime/rest/fixtures/snapshot_filtered_by_down.json b/x-pack/test/api_integration/apis/uptime/rest/fixtures/snapshot_filtered_by_down.json deleted file mode 100644 index 27ba69411f88df..00000000000000 --- a/x-pack/test/api_integration/apis/uptime/rest/fixtures/snapshot_filtered_by_down.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "total": 7, - "up": 0, - "down": 7 -} \ No newline at end of file diff --git a/x-pack/test/api_integration/apis/uptime/rest/fixtures/snapshot_filtered_by_up.json b/x-pack/test/api_integration/apis/uptime/rest/fixtures/snapshot_filtered_by_up.json deleted file mode 100644 index 33e60a4340a139..00000000000000 --- a/x-pack/test/api_integration/apis/uptime/rest/fixtures/snapshot_filtered_by_up.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "total": 10, - "up": 10, - "down": 0 -} \ No newline at end of file diff --git a/x-pack/test/api_integration/apis/uptime/rest/index.ts b/x-pack/test/api_integration/apis/uptime/rest/index.ts index f77c14e960ab23..2084c1a572058e 100644 --- a/x-pack/test/api_integration/apis/uptime/rest/index.ts +++ b/x-pack/test/api_integration/apis/uptime/rest/index.ts @@ -46,6 +46,7 @@ export default function({ getService, loadTestFile }: FtrProviderContext) { loadTestFile(require.resolve('./monitor_states_generated')); loadTestFile(require.resolve('./telemetry_collectors')); }); + describe('with real-world data', () => { beforeEach('load heartbeat data', async () => await esArchiver.load('uptime/full_heartbeat')); afterEach('unload', async () => await esArchiver.unload('uptime/full_heartbeat')); diff --git a/x-pack/test/api_integration/apis/uptime/rest/snapshot.ts b/x-pack/test/api_integration/apis/uptime/rest/snapshot.ts index 9a8951741948e3..0d708446503698 100644 --- a/x-pack/test/api_integration/apis/uptime/rest/snapshot.ts +++ b/x-pack/test/api_integration/apis/uptime/rest/snapshot.ts @@ -80,23 +80,6 @@ export default function({ getService }: FtrProviderContext) { expectFixtureEql(apiResponse.body, 'snapshot'); }); - - it('will fetch a monitor snapshot filtered by down status', async () => { - const statusFilter = 'down'; - const apiResponse = await supertest.get( - `/api/uptime/snapshot/count?dateRangeStart=${dateRange.start}&dateRangeEnd=${dateRange.end}&statusFilter=${statusFilter}` - ); - - expectFixtureEql(apiResponse.body, 'snapshot_filtered_by_down'); - }); - - it('will fetch a monitor snapshot filtered by up status', async () => { - const statusFilter = 'up'; - const apiResponse = await supertest.get( - `/api/uptime/snapshot/count?dateRangeStart=${dateRange.start}&dateRangeEnd=${dateRange.end}&statusFilter=${statusFilter}` - ); - expectFixtureEql(apiResponse.body, 'snapshot_filtered_by_up'); - }); }); }); }); diff --git a/x-pack/test/functional/apps/infra/home_page.ts b/x-pack/test/functional/apps/infra/home_page.ts index ed8bec570ab60a..28d7956e353e14 100644 --- a/x-pack/test/functional/apps/infra/home_page.ts +++ b/x-pack/test/functional/apps/infra/home_page.ts @@ -33,6 +33,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { before(async () => { await esArchiver.load('infra/metrics_and_logs'); await pageObjects.common.navigateToApp('infraOps'); + await pageObjects.infraHome.waitForLoading(); }); after(async () => await esArchiver.unload('infra/metrics_and_logs')); diff --git a/x-pack/test/functional/apps/security/users.js b/x-pack/test/functional/apps/security/users.js index 04d59334a01c47..bfc6950faecc64 100644 --- a/x-pack/test/functional/apps/security/users.js +++ b/x-pack/test/functional/apps/security/users.js @@ -18,15 +18,22 @@ export default function({ getService, getPageObjects }) { await PageObjects.security.clickElasticsearchUsers(); }); - it('should show the default elastic and kibana users', async function() { + it('should show the default elastic and kibana_system users', async function() { const users = indexBy(await PageObjects.security.getElasticsearchUsers(), 'username'); log.info('actualUsers = %j', users); log.info('config = %j', config.get('servers.elasticsearch.hostname')); if (config.get('servers.elasticsearch.hostname') === 'localhost') { expect(users.elastic.roles).to.eql(['superuser']); expect(users.elastic.reserved).to.be(true); + expect(users.elastic.deprecated).to.be(false); + + expect(users.kibana_system.roles).to.eql(['kibana_system']); + expect(users.kibana_system.reserved).to.be(true); + expect(users.kibana_system.deprecated).to.be(false); + expect(users.kibana.roles).to.eql(['kibana_system']); expect(users.kibana.reserved).to.be(true); + expect(users.kibana.deprecated).to.be(true); } else { expect(users.anonymous.roles).to.eql(['anonymous']); expect(users.anonymous.reserved).to.be(true); diff --git a/x-pack/test/functional/apps/transform/creation_index_pattern.ts b/x-pack/test/functional/apps/transform/creation_index_pattern.ts index 0e61635fb70e4f..150b2a9a15147b 100644 --- a/x-pack/test/functional/apps/transform/creation_index_pattern.ts +++ b/x-pack/test/functional/apps/transform/creation_index_pattern.ts @@ -58,6 +58,7 @@ export default function({ getService }: FtrProviderContext) { return `user-${this.transformId}`; }, expected: { + pivotAdvancedEditorValueArr: ['{', ' "group_by": {', ' "category.keyword": {'], pivotAdvancedEditorValue: { group_by: { 'category.keyword': { @@ -117,6 +118,7 @@ export default function({ getService }: FtrProviderContext) { return `user-${this.transformId}`; }, expected: { + pivotAdvancedEditorValueArr: ['{', ' "group_by": {', ' "geoip.country_iso_code": {'], pivotAdvancedEditorValue: { group_by: { 'geoip.country_iso_code': { @@ -233,7 +235,7 @@ export default function({ getService }: FtrProviderContext) { it('displays the advanced configuration', async () => { await transform.wizard.enabledAdvancedPivotEditor(); await transform.wizard.assertAdvancedPivotEditorContent( - testData.expected.pivotAdvancedEditorValue + testData.expected.pivotAdvancedEditorValueArr ); }); diff --git a/x-pack/test/functional/apps/uptime/overview.ts b/x-pack/test/functional/apps/uptime/overview.ts index d0dfca64634f6f..98d432668a2851 100644 --- a/x-pack/test/functional/apps/uptime/overview.ts +++ b/x-pack/test/functional/apps/uptime/overview.ts @@ -10,11 +10,16 @@ import { FtrProviderContext } from '../../ftr_provider_context'; export default ({ getPageObjects, getService }: FtrProviderContext) => { const { uptime } = getPageObjects(['uptime']); const retry = getService('retry'); + const esArchiver = getService('esArchiver'); describe('overview page', function() { const DEFAULT_DATE_START = 'Sep 10, 2019 @ 12:40:08.078'; const DEFAULT_DATE_END = 'Sep 11, 2019 @ 19:40:08.078'; + before(async () => { + await esArchiver.loadIfNeeded('uptime/full_heartbeat'); + }); + beforeEach(async () => { await uptime.goToRoot(); await uptime.setDateRange(DEFAULT_DATE_START, DEFAULT_DATE_END); @@ -159,20 +164,20 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { }); describe('snapshot counts', () => { - it('updates the snapshot count when status filter is set to down', async () => { + it('should not update when status filter is set to down', async () => { await uptime.setStatusFilter('down'); await retry.tryForTime(12000, async () => { const counts = await uptime.getSnapshotCount(); - expect(counts).to.eql({ up: '0', down: '7' }); + expect(counts).to.eql({ up: '93', down: '7' }); }); }); - it('updates the snapshot count when status filter is set to up', async () => { + it('should not update when status filter is set to up', async () => { await uptime.setStatusFilter('up'); await retry.tryForTime(12000, async () => { const counts = await uptime.getSnapshotCount(); - expect(counts).to.eql({ up: '93', down: '0' }); + expect(counts).to.eql({ up: '93', down: '7' }); }); }); diff --git a/x-pack/test/functional/page_objects/infra_home_page.ts b/x-pack/test/functional/page_objects/infra_home_page.ts index 998a60500aca29..51dad594f21f57 100644 --- a/x-pack/test/functional/page_objects/infra_home_page.ts +++ b/x-pack/test/functional/page_objects/infra_home_page.ts @@ -74,5 +74,9 @@ export function InfraHomePageProvider({ getService }: FtrProviderContext) { await testSubjects.click('configureSourceButton'); await testSubjects.exists('sourceConfigurationFlyout'); }, + + async waitForLoading() { + await testSubjects.missingOrFail('loadingMessage', { timeout: 20000 }); + }, }; } diff --git a/x-pack/test/functional/page_objects/security_page.js b/x-pack/test/functional/page_objects/security_page.js index 84eb0cc378771c..08895de815b396 100644 --- a/x-pack/test/functional/page_objects/security_page.js +++ b/x-pack/test/functional/page_objects/security_page.js @@ -235,6 +235,7 @@ export function SecurityPageProvider({ getService, getPageObjects }) { const rolesElement = await user.findByTestSubject('userRowRoles'); // findAll is substantially faster than `find.descendantExistsByCssSelector for negative cases const isUserReserved = (await user.findAllByTestSubject('userReserved', 1)).length > 0; + const isUserDeprecated = (await user.findAllByTestSubject('userDeprecated', 1)).length > 0; return { username: await usernameElement.getVisibleText(), @@ -242,6 +243,7 @@ export function SecurityPageProvider({ getService, getPageObjects }) { email: await emailElement.getVisibleText(), roles: (await rolesElement.getVisibleText()).split('\n').map(role => role.trim()), reserved: isUserReserved, + deprecated: isUserDeprecated, }; }); } diff --git a/x-pack/test/functional/page_objects/uptime_page.ts b/x-pack/test/functional/page_objects/uptime_page.ts index 53c89eadeced74..1155b6a5cb2968 100644 --- a/x-pack/test/functional/page_objects/uptime_page.ts +++ b/x-pack/test/functional/page_objects/uptime_page.ts @@ -9,7 +9,7 @@ import { FtrProviderContext } from '../ftr_provider_context'; export function UptimePageProvider({ getPageObjects, getService }: FtrProviderContext) { const pageObjects = getPageObjects(['common', 'timePicker']); - const { alerts, common: commonService, monitor, navigation } = getService('uptime'); + const { common: commonService, monitor, navigation } = getService('uptime'); const retry = getService('retry'); return new (class UptimePage { @@ -97,42 +97,9 @@ export function UptimePageProvider({ getPageObjects, getService }: FtrProviderCo return await commonService.getSnapshotCount(); } - public async openAlertFlyoutAndCreateMonitorStatusAlert({ - alertInterval, - alertName, - alertNumTimes, - alertTags, - alertThrottleInterval, - alertTimerangeSelection, - alertType, - filters, - }: { - alertName: string; - alertTags: string[]; - alertInterval: string; - alertThrottleInterval: string; - alertNumTimes: string; - alertTimerangeSelection: string; - alertType?: string; - filters?: string; - }) { + public async setAlertKueryBarText(filters: string) { const { setKueryBarText } = commonService; - await alerts.openFlyout(); - if (alertType) { - await alerts.openMonitorStatusAlertType(alertType); - } - await alerts.setAlertName(alertName); - await alerts.setAlertTags(alertTags); - await alerts.setAlertInterval(alertInterval); - await alerts.setAlertThrottleInterval(alertThrottleInterval); - if (filters) { - await setKueryBarText('xpack.uptime.alerts.monitorStatus.filterBar', filters); - } - await alerts.setAlertStatusNumTimes(alertNumTimes); - await alerts.setAlertTimerangeSelection(alertTimerangeSelection); - await alerts.setMonitorStatusSelectableToHours(); - await alerts.setLocationsSelectable(); - await alerts.clickSaveAlertButtion(); + await setKueryBarText('xpack.uptime.alerts.monitorStatus.filterBar', filters); } public async setMonitorListPageSize(size: number): Promise { diff --git a/x-pack/test/functional/services/transform_ui/wizard.ts b/x-pack/test/functional/services/transform_ui/wizard.ts index e63af493438d67..4b136746eb525e 100644 --- a/x-pack/test/functional/services/transform_ui/wizard.ts +++ b/x-pack/test/functional/services/transform_ui/wizard.ts @@ -274,10 +274,15 @@ export function TransformWizardProvider({ getService }: FtrProviderContext) { await this.assertAggregationEntryExists(index, expectedLabel); }, - async assertAdvancedPivotEditorContent(expectedValue: Record) { + async assertAdvancedPivotEditorContent(expectedValue: string[]) { const advancedEditorString = await aceEditor.getValue('transformAdvancedPivotEditor'); - const advancedEditorValue = JSON.parse(advancedEditorString); - expect(advancedEditorValue).to.eql(expectedValue); + // Not all lines may be visible in the editor and thus aceEditor may not return all lines. + // This means we might not get back valid JSON so we only test against the first few lines + // and see if the string matches. + + // const advancedEditorValue = JSON.parse(advancedEditorString); + // expect(advancedEditorValue).to.eql(expectedValue); + expect(advancedEditorString.split('\n').splice(0, 3)).to.eql(expectedValue); }, async assertAdvancedPivotEditorSwitchExists() { diff --git a/x-pack/test/functional/services/uptime/alerts.ts b/x-pack/test/functional/services/uptime/alerts.ts index 3a8193ff3d3278..dc10fcccaa6cef 100644 --- a/x-pack/test/functional/services/uptime/alerts.ts +++ b/x-pack/test/functional/services/uptime/alerts.ts @@ -13,6 +13,7 @@ export function UptimeAlertsProvider({ getService }: FtrProviderContext) { return { async openFlyout() { await testSubjects.click('xpack.uptime.alertsPopover.toggleButton', 5000); + await testSubjects.click('xpack.uptime.openAlertContextPanel', 5000); await testSubjects.click('xpack.uptime.toggleAlertFlyout', 5000); }, async openMonitorStatusAlertType(alertType: string) { @@ -76,19 +77,37 @@ export function UptimeAlertsProvider({ getService }: FtrProviderContext) { ['xpack.uptime.alerts.monitorStatus.timerangeUnitSelectable.hoursOption'] ); }, - async setLocationsSelectable() { - await testSubjects.click( - 'xpack.uptime.alerts.monitorStatus.locationsSelectionExpression', - 5000 - ); - await testSubjects.click('xpack.uptime.alerts.monitorStatus.locationsSelectionSwitch', 5000); - await testSubjects.click( - 'xpack.uptime.alerts.monitorStatus.locationsSelectionSelectable', - 5000 - ); + async clickAddFilter() { + await testSubjects.click('uptimeCreateAlertAddFilter'); + }, + async clickAddFilterLocation() { + await this.clickAddFilter(); + await testSubjects.click('uptimeAlertAddFilter.observer.geo.name'); + }, + async clickAddFilterPort() { + await this.clickAddFilter(); + await testSubjects.click('uptimeAlertAddFilter.url.port'); + }, + async clickAddFilterType() { + await this.clickAddFilter(); + await testSubjects.click('uptimeAlertAddFilter.monitor.type'); + }, + async clickLocationExpression(filter: string) { + await testSubjects.click('uptimeCreateStatusAlert.filter_location'); + await testSubjects.click(`filter-popover-item_${filter}`); + return browser.pressKeys(browser.keys.ESCAPE); + }, + async clickPortExpression(filter: string) { + await testSubjects.click('uptimeCreateStatusAlert.filter_port'); + await testSubjects.click(`filter-popover-item_${filter}`); + return browser.pressKeys(browser.keys.ESCAPE); + }, + async clickTypeExpression(filter: string) { + await testSubjects.click('uptimeCreateStatusAlert.filter_scheme'); + await testSubjects.click(`filter-popover-item_${filter}`); return browser.pressKeys(browser.keys.ESCAPE); }, - async clickSaveAlertButtion() { + async clickSaveAlertButton() { return testSubjects.click('saveAlertButton'); }, }; diff --git a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/connectors.ts b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/connectors.ts index 1facc05bc186d2..88d52578f692ed 100644 --- a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/connectors.ts +++ b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/connectors.ts @@ -56,7 +56,6 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { { name: connectorName, actionType: 'Slack', - referencedByCount: '0', }, ]); }); @@ -100,7 +99,6 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { { name: updatedConnectorName, actionType: 'Slack', - referencedByCount: '0', }, ]); }); diff --git a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts index 7970c9b24427e1..9d547876d9b3b5 100644 --- a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts +++ b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts @@ -75,29 +75,28 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { const alertType = await pageObjects.alertDetailsUI.getAlertType(); expect(alertType).to.be(`Always Firing`); - const { actionType, actionCount } = await pageObjects.alertDetailsUI.getActionsLabels(); + const { actionType } = await pageObjects.alertDetailsUI.getActionsLabels(); expect(actionType).to.be(`Slack`); - expect(actionCount).to.be(`+1`); }); it('should disable the alert', async () => { - const enableSwitch = await testSubjects.find('enableSwitch'); + const disableSwitch = await testSubjects.find('disableSwitch'); - const isChecked = await enableSwitch.getAttribute('aria-checked'); - expect(isChecked).to.eql('true'); + const isChecked = await disableSwitch.getAttribute('aria-checked'); + expect(isChecked).to.eql('false'); - await enableSwitch.click(); + await disableSwitch.click(); - const enabledSwitchAfterDisabling = await testSubjects.find('enableSwitch'); - const isCheckedAfterDisabling = await enabledSwitchAfterDisabling.getAttribute( + const disableSwitchAfterDisabling = await testSubjects.find('disableSwitch'); + const isCheckedAfterDisabling = await disableSwitchAfterDisabling.getAttribute( 'aria-checked' ); - expect(isCheckedAfterDisabling).to.eql('false'); + expect(isCheckedAfterDisabling).to.eql('true'); }); it('shouldnt allow you to mute a disabled alert', async () => { - const disabledEnableSwitch = await testSubjects.find('enableSwitch'); - expect(await disabledEnableSwitch.getAttribute('aria-checked')).to.eql('false'); + const disabledDisableSwitch = await testSubjects.find('disableSwitch'); + expect(await disabledDisableSwitch.getAttribute('aria-checked')).to.eql('true'); const muteSwitch = await testSubjects.find('muteSwitch'); expect(await muteSwitch.getAttribute('aria-checked')).to.eql('false'); @@ -112,18 +111,18 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { }); it('should reenable a disabled the alert', async () => { - const enableSwitch = await testSubjects.find('enableSwitch'); + const disableSwitch = await testSubjects.find('disableSwitch'); - const isChecked = await enableSwitch.getAttribute('aria-checked'); - expect(isChecked).to.eql('false'); + const isChecked = await disableSwitch.getAttribute('aria-checked'); + expect(isChecked).to.eql('true'); - await enableSwitch.click(); + await disableSwitch.click(); - const enabledSwitchAfterReenabling = await testSubjects.find('enableSwitch'); - const isCheckedAfterDisabling = await enabledSwitchAfterReenabling.getAttribute( + const disableSwitchAfterReenabling = await testSubjects.find('disableSwitch'); + const isCheckedAfterDisabling = await disableSwitchAfterReenabling.getAttribute( 'aria-checked' ); - expect(isCheckedAfterDisabling).to.eql('true'); + expect(isCheckedAfterDisabling).to.eql('false'); }); it('should mute the alert', async () => { diff --git a/x-pack/test/functional_with_es_ssl/apps/uptime/alert_flyout.ts b/x-pack/test/functional_with_es_ssl/apps/uptime/alert_flyout.ts index 3e5a8c57c4c7e6..fb4f34d65f9b00 100644 --- a/x-pack/test/functional_with_es_ssl/apps/uptime/alert_flyout.ts +++ b/x-pack/test/functional_with_es_ssl/apps/uptime/alert_flyout.ts @@ -14,20 +14,67 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { const pageObjects = getPageObjects(['common', 'uptime']); const supertest = getService('supertest'); const retry = getService('retry'); + let alerts: any; - it('posts an alert, verfies its presence, and deletes the alert', async () => { + before(async () => { + alerts = getService('uptime').alerts; + }); + + it('can open alert flyout', async () => { await pageObjects.uptime.goToUptimeOverviewAndLoadData(DEFAULT_DATE_START, DEFAULT_DATE_END); + await alerts.openFlyout(); + }); - await pageObjects.uptime.openAlertFlyoutAndCreateMonitorStatusAlert({ - alertInterval: '11', - alertName: 'uptime-test', - alertNumTimes: '3', - alertTags: ['uptime', 'another'], - alertThrottleInterval: '30', - alertTimerangeSelection: '1', - filters: 'monitor.id: "0001-up"', - }); + it('can set alert name', async () => { + await alerts.setAlertName('uptime-test'); + }); + + it('can set alert tags', async () => { + await alerts.setAlertTags(['uptime', 'another']); + }); + + it('can set alert interval', async () => { + await alerts.setAlertInterval('11'); + }); + + it('can set alert throttle interval', async () => { + await alerts.setAlertThrottleInterval('30'); + }); + + it('can set alert status number of time', async () => { + await alerts.setAlertStatusNumTimes('3'); + }); + it('can set alert time range', async () => { + await alerts.setAlertTimerangeSelection('1'); + }); + it('can set monitor hours', async () => { + await alerts.setMonitorStatusSelectableToHours(); + }); + + it('can set kuery bar filters', async () => { + await pageObjects.uptime.setAlertKueryBarText('monitor.id: "0001-up"'); + }); + + it('can select location filter', async () => { + await alerts.clickAddFilterLocation(); + await alerts.clickLocationExpression('mpls'); + }); + + it('can select port filter', async () => { + await alerts.clickAddFilterPort(); + await alerts.clickPortExpression('5678'); + }); + + it('can select type/scheme filter', async () => { + await alerts.clickAddFilterType(); + await alerts.clickTypeExpression('http'); + }); + + it('can save alert', async () => { + await alerts.clickSaveAlertButton(); + }); + it('posts an alert, verifies its presence, and deletes the alert', async () => { // The creation of the alert could take some time, so the first few times we query after // the previous line resolves, the API may not be done creating the alert yet, so we // put the fetch code in a retry block with a timeout. @@ -67,7 +114,10 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { expect(timerange.to).to.be('now'); expect(locations).to.eql(['mpls']); expect(filters).to.eql( - '{"bool":{"should":[{"match_phrase":{"monitor.id":"0001-up"}}],"minimum_should_match":1}}' + '{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"monitor.id":"0001-up"}}],' + + '"minimum_should_match":1}},{"bool":{"filter":[{"bool":{"should":[{"match":{"observer.geo.name":"mpls"}}],' + + '"minimum_should_match":1}},{"bool":{"filter":[{"bool":{"should":[{"match":{"url.port":5678}}],' + + '"minimum_should_match":1}},{"bool":{"should":[{"match":{"monitor.type":"http"}}],"minimum_should_match":1}}]}}]}}]}}' ); } finally { await supertest diff --git a/x-pack/test/functional_with_es_ssl/page_objects/alert_details.ts b/x-pack/test/functional_with_es_ssl/page_objects/alert_details.ts index 48ad59586f7935..bd824430687659 100644 --- a/x-pack/test/functional_with_es_ssl/page_objects/alert_details.ts +++ b/x-pack/test/functional_with_es_ssl/page_objects/alert_details.ts @@ -23,7 +23,6 @@ export function AlertDetailsPageProvider({ getService }: FtrProviderContext) { async getActionsLabels() { return { actionType: await testSubjects.getVisibleText('actionTypeLabel'), - actionCount: await testSubjects.getVisibleText('actionCountLabel'), }; }, async getAlertInstancesList() { @@ -71,12 +70,10 @@ export function AlertDetailsPageProvider({ getService }: FtrProviderContext) { const muteAlertInstanceButton = await testSubjects.find( `muteAlertInstanceButton_${instance}` ); - log.debug(`checked:${await muteAlertInstanceButton.getAttribute('checked')}`); - expect(await muteAlertInstanceButton.getAttribute('checked')).to.eql( - isMuted ? 'true' : null + log.debug(`checked:${await muteAlertInstanceButton.getAttribute('aria-checked')}`); + expect(await muteAlertInstanceButton.getAttribute('aria-checked')).to.eql( + isMuted ? 'true' : 'false' ); - - expect(await testSubjects.exists(`mutedAlertInstanceLabel_${instance}`)).to.eql(isMuted); }); }, async ensureAlertInstanceExistance(instance: string, shouldExist: boolean) { diff --git a/x-pack/test/functional_with_es_ssl/page_objects/triggers_actions_ui_page.ts b/x-pack/test/functional_with_es_ssl/page_objects/triggers_actions_ui_page.ts index 2a50c0117eae93..ca7f064e206900 100644 --- a/x-pack/test/functional_with_es_ssl/page_objects/triggers_actions_ui_page.ts +++ b/x-pack/test/functional_with_es_ssl/page_objects/triggers_actions_ui_page.ts @@ -69,10 +69,6 @@ export function TriggersActionsPageProvider({ getService }: FtrProviderContext) .findTestSubject('connectorsTableCell-actionType') .find('.euiTableCellContent') .text(), - referencedByCount: $(row) - .findTestSubject('connectorsTableCell-referencedByCount') - .find('.euiTableCellContent') - .text(), }; }); }, diff --git a/x-pack/test/reporting/services/reporting_api.js b/x-pack/test/reporting/services/reporting_api.js index e81f02c8a8ae48..82fe6aea08ac31 100644 --- a/x-pack/test/reporting/services/reporting_api.js +++ b/x-pack/test/reporting/services/reporting_api.js @@ -97,7 +97,6 @@ export function ReportingAPIProvider({ getService }) { }, expectRecentPdfAppStats(stats, app, count) { - expect(stats.reporting.last_day.printable_pdf.app[app]).to.be(count); expect(stats.reporting.last_7_days.printable_pdf.app[app]).to.be(count); }, @@ -106,7 +105,6 @@ export function ReportingAPIProvider({ getService }) { }, expectRecentPdfLayoutStats(stats, layout, count) { - expect(stats.reporting.last_day.printable_pdf.layout[layout]).to.be(count); expect(stats.reporting.last_7_days.printable_pdf.layout[layout]).to.be(count); }, @@ -115,7 +113,6 @@ export function ReportingAPIProvider({ getService }) { }, expectRecentJobTypeTotalStats(stats, jobType, count) { - expect(stats.reporting.last_day[jobType].total).to.be(count); expect(stats.reporting.last_7_days[jobType].total).to.be(count); }, diff --git a/yarn.lock b/yarn.lock index 941143e76483e1..b28c5a32123482 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1262,10 +1262,10 @@ dependencies: "@elastic/apm-rum-core" "^5.2.0" -"@elastic/charts@18.4.2": - version "18.4.2" - resolved "https://registry.yarnpkg.com/@elastic/charts/-/charts-18.4.2.tgz#7d3c40dca8a7a701fb7227382191b84d36d8b32a" - integrity sha512-fmEDRUeFEtVWGurafhp/5bHBypOjdXiRXY074tCqnez43hA2iA4v1KrZL8tPFlMePgc/kpZf9wb8aEwxlfWumw== +"@elastic/charts@19.2.0": + version "19.2.0" + resolved "https://registry.yarnpkg.com/@elastic/charts/-/charts-19.2.0.tgz#45db8c80e4699e5088a1771f190171c1144c5242" + integrity sha512-uhk73OQPaxg7l54gfr+kv+c6jiEngewwH408OySzJbnH23z/5sIpLSziZhV33I6bs/LKDXQSqamC9Jh6Xcwk1A== dependencies: classnames "^2.2.6" d3-array "^1.2.4"