diff --git a/oas_docs/output/kibana.serverless.yaml b/oas_docs/output/kibana.serverless.yaml index b84a7fa1d1b93..6f37e5db5f53e 100644 --- a/oas_docs/output/kibana.serverless.yaml +++ b/oas_docs/output/kibana.serverless.yaml @@ -64815,6 +64815,7 @@ paths: append: {} attachment: {} bytes: {} + cef: {} circle: {} community_id: {} convert: {} @@ -64861,6 +64862,7 @@ paths: - append - attachment - bytes + - cef - circle - community_id - convert @@ -69766,6 +69768,7 @@ paths: append: {} attachment: {} bytes: {} + cef: {} circle: {} community_id: {} convert: {} @@ -69812,6 +69815,7 @@ paths: - append - attachment - bytes + - cef - circle - community_id - convert @@ -74458,6 +74462,7 @@ paths: append: {} attachment: {} bytes: {} + cef: {} circle: {} community_id: {} convert: {} @@ -74504,6 +74509,7 @@ paths: - append - attachment - bytes + - cef - circle - community_id - convert @@ -79221,6 +79227,7 @@ paths: append: {} attachment: {} bytes: {} + cef: {} circle: {} community_id: {} convert: {} @@ -79267,6 +79274,7 @@ paths: - append - attachment - bytes + - cef - circle - community_id - convert @@ -84247,6 +84255,7 @@ paths: append: {} attachment: {} bytes: {} + cef: {} circle: {} community_id: {} convert: {} @@ -84293,6 +84302,7 @@ paths: - append - attachment - bytes + - cef - circle - community_id - convert @@ -88869,6 +88879,7 @@ paths: append: {} attachment: {} bytes: {} + cef: {} circle: {} community_id: {} convert: {} @@ -88915,6 +88926,7 @@ paths: - append - attachment - bytes + - cef - circle - community_id - convert diff --git a/oas_docs/output/kibana.yaml b/oas_docs/output/kibana.yaml index 092d5aa694e77..f497a9941a887 100644 --- a/oas_docs/output/kibana.yaml +++ b/oas_docs/output/kibana.yaml @@ -69269,6 +69269,7 @@ paths: append: {} attachment: {} bytes: {} + cef: {} circle: {} community_id: {} convert: {} @@ -69315,6 +69316,7 @@ paths: - append - attachment - bytes + - cef - circle - community_id - convert @@ -74220,6 +74222,7 @@ paths: append: {} attachment: {} bytes: {} + cef: {} circle: {} community_id: {} convert: {} @@ -74266,6 +74269,7 @@ paths: - append - attachment - bytes + - cef - circle - community_id - convert @@ -78912,6 +78916,7 @@ paths: append: {} attachment: {} bytes: {} + cef: {} circle: {} community_id: {} convert: {} @@ -78958,6 +78963,7 @@ paths: - append - attachment - bytes + - cef - circle - community_id - convert @@ -83675,6 +83681,7 @@ paths: append: {} attachment: {} bytes: {} + cef: {} circle: {} community_id: {} convert: {} @@ -83721,6 +83728,7 @@ paths: - append - attachment - bytes + - cef - circle - community_id - convert @@ -88701,6 +88709,7 @@ paths: append: {} attachment: {} bytes: {} + cef: {} circle: {} community_id: {} convert: {} @@ -88747,6 +88756,7 @@ paths: - append - attachment - bytes + - cef - circle - community_id - convert @@ -93323,6 +93333,7 @@ paths: append: {} attachment: {} bytes: {} + cef: {} circle: {} community_id: {} convert: {} @@ -93369,6 +93380,7 @@ paths: - append - attachment - bytes + - cef - circle - community_id - convert diff --git a/package.json b/package.json index c027c56c30f90..77530eeba5734 100644 --- a/package.json +++ b/package.json @@ -130,7 +130,7 @@ "@elastic/datemath": "5.0.3", "@elastic/ebt": "1.4.1", "@elastic/ecs": "9.2.0", - "@elastic/elasticsearch": "9.2.0", + "@elastic/elasticsearch": "9.3.1", "@elastic/ems-client": "8.6.3", "@elastic/eui": "113.0.0", "@elastic/eui-theme-borealis": "6.0.0", diff --git a/src/core/packages/saved-objects/migration-server-internal/src/actions/check_for_unknown_docs.ts b/src/core/packages/saved-objects/migration-server-internal/src/actions/check_for_unknown_docs.ts index baaace7b8d352..23cd500a1eb63 100644 --- a/src/core/packages/saved-objects/migration-server-internal/src/actions/check_for_unknown_docs.ts +++ b/src/core/packages/saved-objects/migration-server-internal/src/actions/check_for_unknown_docs.ts @@ -119,7 +119,7 @@ export const checkForUnknownDocs = UnknownDocsFound | {} > => () => { - const excludeQuery = addExcludedTypesToBoolQuery(knownTypes, excludeOnUpgradeQuery.bool); + const excludeQuery = addExcludedTypesToBoolQuery(knownTypes, excludeOnUpgradeQuery?.bool); return getAggregatedTypesDocuments(client, indexName, excludeQuery) .then((unknownDocs) => { if (unknownDocs.length) { diff --git a/src/core/packages/saved-objects/migration-server-internal/src/model/helpers.test.ts b/src/core/packages/saved-objects/migration-server-internal/src/model/helpers.test.ts index 788d218b02d5a..7af7e64e63edc 100644 --- a/src/core/packages/saved-objects/migration-server-internal/src/model/helpers.test.ts +++ b/src/core/packages/saved-objects/migration-server-internal/src/model/helpers.test.ts @@ -432,9 +432,9 @@ describe('createBulkIndexOperationTuple', () => { _source: { type: 'cases', title: 'no originId' }, }; const [operation] = createBulkIndexOperationTuple(document); - expect(operation.index).toBeDefined(); - expect((operation.index as any).if_seq_no).toBe(10); - expect((operation.index as any).if_primary_term).toBe(20); + expect(operation!.index).toBeDefined(); + expect((operation!.index as any).if_seq_no).toBe(10); + expect((operation!.index as any).if_primary_term).toBe(20); }); it('includes if_seq_no and if_primary_term when originId === _id', () => { @@ -445,9 +445,9 @@ describe('createBulkIndexOperationTuple', () => { _source: { type: 'cases', title: 'originId equals _id', originId: 'doc2' }, }; const [operation] = createBulkIndexOperationTuple(document); - expect(operation.index).toBeDefined(); - expect((operation.index as any).if_seq_no).toBe(11); - expect((operation.index as any).if_primary_term).toBe(21); + expect(operation!.index).toBeDefined(); + expect((operation!.index as any).if_seq_no).toBe(11); + expect((operation!.index as any).if_primary_term).toBe(21); }); it('does NOT include if_seq_no and if_primary_term when originId !== _id', () => { @@ -458,9 +458,9 @@ describe('createBulkIndexOperationTuple', () => { _source: { type: 'cases', title: 'originId not equal _id', originId: 'other-id' }, }; const [operation] = createBulkIndexOperationTuple(document); - expect(operation.index).toBeDefined(); - expect((operation.index as any).if_seq_no).toBeUndefined(); - expect((operation.index as any).if_primary_term).toBeUndefined(); + expect(operation!.index).toBeDefined(); + expect((operation!.index as any).if_seq_no).toBeUndefined(); + expect((operation!.index as any).if_primary_term).toBeUndefined(); }); }); diff --git a/src/core/packages/saved-objects/migration-server-internal/src/model/model.ts b/src/core/packages/saved-objects/migration-server-internal/src/model/model.ts index 26759d4f20e15..e8ec809138739 100644 --- a/src/core/packages/saved-objects/migration-server-internal/src/model/model.ts +++ b/src/core/packages/saved-objects/migration-server-internal/src/model/model.ts @@ -795,7 +795,7 @@ export const model = (currentState: State, resW: ResponseType): excludeOnUpgradeQuery = addMustClausesToBoolQuery( [{ exists: { field: 'type' } }], - excludeOnUpgradeQuery.bool + excludeOnUpgradeQuery?.bool ); } diff --git a/src/platform/packages/private/kbn-index-editor/src/services/bulk_update_service.test.ts b/src/platform/packages/private/kbn-index-editor/src/services/bulk_update_service.test.ts index ed8b2eae2fcd5..3e9884471f1fd 100644 --- a/src/platform/packages/private/kbn-index-editor/src/services/bulk_update_service.test.ts +++ b/src/platform/packages/private/kbn-index-editor/src/services/bulk_update_service.test.ts @@ -61,14 +61,14 @@ describe('Bulk update', () => { expect(operations.length).toBe(4); // Validate presence of delete operations for non-placeholder ids only - const deletes = operations.filter((op) => op.delete); - const deleteIds = deletes.map((d) => d.delete?._id).sort(); + const deletes = operations.filter((op) => op!.delete); + const deleteIds = deletes.map((d) => d!.delete!._id).sort(); expect(deleteIds).toEqual(['abc123', 'to-del']); // Validate there is an index operation and that the document merges values - const indexIdx = operations.findIndex((op) => op.index); + const indexIdx = operations.findIndex((op) => op!.index); expect(indexIdx).toBeGreaterThanOrEqual(0); - const doc = operations[indexIdx + 1]; + const doc = operations[indexIdx + 1]!; expect(doc).toEqual({ b: 2, c: 3 }); }); diff --git a/src/platform/packages/shared/kbn-alerting-types/search_strategy_types.ts b/src/platform/packages/shared/kbn-alerting-types/search_strategy_types.ts index 082bcacbe5802..e70f6cb9aedf3 100644 --- a/src/platform/packages/shared/kbn-alerting-types/search_strategy_types.ts +++ b/src/platform/packages/shared/kbn-alerting-types/search_strategy_types.ts @@ -20,7 +20,7 @@ export type RuleRegistrySearchRequest = IEsSearchRequest & { ruleTypeIds: string[]; consumers?: string[]; fields?: QueryDslFieldAndFormat[]; - query?: Pick; + query?: Pick, 'bool' | 'ids'>; sort?: SortCombinations[]; pagination?: RuleRegistrySearchRequestPagination; runtimeMappings?: MappingRuntimeFields; diff --git a/src/platform/packages/shared/kbn-alerts-ui-shared/src/common/apis/search_alerts/search_alerts.ts b/src/platform/packages/shared/kbn-alerts-ui-shared/src/common/apis/search_alerts/search_alerts.ts index 2465e44d6b1d9..aceb5674095a4 100644 --- a/src/platform/packages/shared/kbn-alerts-ui-shared/src/common/apis/search_alerts/search_alerts.ts +++ b/src/platform/packages/shared/kbn-alerts-ui-shared/src/common/apis/search_alerts/search_alerts.ts @@ -47,7 +47,7 @@ export interface SearchAlertsParams { /** * ES query to perform on the affected alert indices */ - query: Pick; + query: Partial, 'bool' | 'ids'>>; /** * The alert document fields to include in the response */ diff --git a/src/platform/packages/shared/kbn-es-query/src/es_query/from_kuery.ts b/src/platform/packages/shared/kbn-es-query/src/es_query/from_kuery.ts index e1d8f3e6562ad..0c1636c6e305b 100644 --- a/src/platform/packages/shared/kbn-es-query/src/es_query/from_kuery.ts +++ b/src/platform/packages/shared/kbn-es-query/src/es_query/from_kuery.ts @@ -55,6 +55,6 @@ function buildQuery( should: [], must_not: [], }, - kueryQuery.bool + kueryQuery?.bool ); } diff --git a/src/platform/packages/shared/kbn-es-query/src/es_query/lucene_string_to_dsl.ts b/src/platform/packages/shared/kbn-es-query/src/es_query/lucene_string_to_dsl.ts index 3a89f4af0b2de..eb0667d4781d0 100644 --- a/src/platform/packages/shared/kbn-es-query/src/es_query/lucene_string_to_dsl.ts +++ b/src/platform/packages/shared/kbn-es-query/src/es_query/lucene_string_to_dsl.ts @@ -18,8 +18,8 @@ import { isString } from 'lodash'; * @public */ export function luceneStringToDsl( - query: string | estypes.QueryDslQueryContainer -): estypes.QueryDslQueryContainer { + query: string | NonNullable +): NonNullable { if (isString(query)) { if (query.trim() === '') { return { match_all: {} }; diff --git a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrase_filter.ts b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrase_filter.ts index f853abdfb508a..40bf4a50d80c8 100644 --- a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrase_filter.ts +++ b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/phrase_filter.ts @@ -30,8 +30,8 @@ export type PhraseFilterMeta = FilterMeta & { export type PhraseFilter = Filter & { meta: PhraseFilterMeta; query: { - match_phrase?: estypes.QueryDslQueryContainer['match_phrase']; - match?: estypes.QueryDslQueryContainer['match']; + match_phrase?: NonNullable['match_phrase']; + match?: NonNullable['match']; }; }; diff --git a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/range_filter.ts b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/range_filter.ts index 08924e3719b63..4755146b092d2 100644 --- a/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/range_filter.ts +++ b/src/platform/packages/shared/kbn-es-query/src/filters/build_filters/range_filter.ts @@ -75,7 +75,7 @@ export type ScriptedRangeFilter = Filter & { export type MatchAllRangeFilter = Filter & { meta: RangeFilterMeta; query: { - match_all: estypes.QueryDslQueryContainer['match_all']; + match_all: NonNullable['match_all']; }; }; diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/ast/ast.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/ast/ast.ts index e466d8be4b507..4802d499f64ea 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/ast/ast.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/ast/ast.ts @@ -43,7 +43,7 @@ export const fromLiteralExpression = ( }; export const fromKueryExpression = ( - expression: string | estypes.QueryDslQueryContainer, + expression: string | NonNullable, parseOptions: Partial = {} ): KueryNode => { try { diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/and.test.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/and.test.ts index a521b9c2445a8..0a5d6d85f3f5d 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/and.test.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/and.test.ts @@ -49,11 +49,11 @@ describe('kuery functions', () => { const result = and.toElasticsearchQuery(node, indexPattern); expect(result).toHaveProperty('bool'); - expect(Object.keys(result).length).toBe(1); - expect(result.bool).toHaveProperty('filter'); - expect(Object.keys(result.bool!).length).toBe(1); + expect(Object.keys(result!).length).toBe(1); + expect(result!.bool).toHaveProperty('filter'); + expect(Object.keys(result!.bool!).length).toBe(1); - expect(result.bool!.filter).toEqual( + expect(result!.bool!.filter).toEqual( [childNode1, childNode2].map((childNode) => ast.toElasticsearchQuery(childNode, indexPattern) ) @@ -70,11 +70,11 @@ describe('kuery functions', () => { }); expect(result).toHaveProperty('bool'); - expect(Object.keys(result).length).toBe(1); - expect(result.bool).toHaveProperty('must'); - expect(Object.keys(result.bool!).length).toBe(1); + expect(Object.keys(result!).length).toBe(1); + expect(result!.bool).toHaveProperty('must'); + expect(Object.keys(result!.bool!).length).toBe(1); - expect(result.bool!.must).toEqual( + expect(result!.bool!.must).toEqual( [childNode1, childNode2].map((childNode) => ast.toElasticsearchQuery(childNode, indexPattern) ) diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/is.test.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/is.test.ts index b97803ab77d8b..048b8f16070be 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/is.test.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/is.test.ts @@ -116,7 +116,7 @@ describe('kuery functions', () => { const result = is.toElasticsearchQuery(node, indexPattern); expect(result).toHaveProperty('bool'); - expect((result.bool!.should! as estypes.QueryDslQueryContainer[]).length).toBe( + expect((result!.bool!.should! as estypes.QueryDslQueryContainer[]).length).toBe( indexPattern.fields.length ); }); @@ -270,7 +270,7 @@ describe('kuery functions', () => { ) as KqlIsFunctionNode; const result = is.toElasticsearchQuery(node, indexPattern); - expect((result.bool!.should as estypes.QueryDslQueryContainer[])[0]).toHaveProperty( + expect((result!.bool!.should as estypes.QueryDslQueryContainer[])[0]).toHaveProperty( 'script' ); }); diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/nested.test.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/nested.test.ts index e1be923b944d8..c3523502e40e9 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/nested.test.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/nested.test.ts @@ -49,10 +49,10 @@ describe('kuery functions', () => { const result = nested.toElasticsearchQuery(node, indexPattern); expect(result).toHaveProperty('nested'); - expect(Object.keys(result).length).toBe(1); + expect(Object.keys(result!).length).toBe(1); - expect(result.nested?.path).toBe('nestedField'); - expect(result.nested?.score_mode).toBe('none'); + expect(result!.nested?.path).toBe('nestedField'); + expect(result!.nested?.score_mode).toBe('none'); }); test('should pass the nested path to subqueries so the full field name can be used', () => { @@ -66,7 +66,7 @@ describe('kuery functions', () => { nodeTypes.function.buildNode('is', 'nestedField.child', 'foo') ); - expect(result.nested!.query).toEqual(expectedSubQuery); + expect(result!.nested!.query).toEqual(expectedSubQuery); }); }); diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/not.test.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/not.test.ts index a66cff663cb55..89293d5d24b1b 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/not.test.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/not.test.ts @@ -44,12 +44,12 @@ describe('kuery functions', () => { const result = not.toElasticsearchQuery(node, indexPattern); expect(result).toHaveProperty('bool'); - expect(Object.keys(result).length).toBe(1); + expect(Object.keys(result!).length).toBe(1); - expect(result.bool).toHaveProperty('must_not'); - expect(Object.keys(result.bool!).length).toBe(1); + expect(result!.bool).toHaveProperty('must_not'); + expect(Object.keys(result!.bool!).length).toBe(1); - expect(result.bool!.must_not).toEqual(ast.toElasticsearchQuery(childNode, indexPattern)); + expect(result!.bool!.must_not).toEqual(ast.toElasticsearchQuery(childNode, indexPattern)); }); }); diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/or.test.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/or.test.ts index d087451915f27..bd66135e3ee60 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/or.test.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/or.test.ts @@ -51,9 +51,9 @@ describe('kuery functions', () => { const result = or.toElasticsearchQuery(node, indexPattern); expect(result).toHaveProperty('bool'); - expect(Object.keys(result).length).toBe(1); - expect(result.bool).toHaveProperty('should'); - expect(result.bool!.should).toEqual( + expect(Object.keys(result!).length).toBe(1); + expect(result!.bool).toHaveProperty('should'); + expect(result!.bool!.should).toEqual( [childNode1, childNode2].map((childNode) => ast.toElasticsearchQuery(childNode, indexPattern) ) @@ -67,7 +67,7 @@ describe('kuery functions', () => { ]) as KqlOrFunctionNode; const result = or.toElasticsearchQuery(node, indexPattern); - expect(result.bool).toHaveProperty('minimum_should_match', 1); + expect(result!.bool).toHaveProperty('minimum_should_match', 1); }); }); diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/range.test.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/range.test.ts index df931366a67ab..8282a70121a71 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/functions/range.test.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/functions/range.test.ts @@ -139,7 +139,7 @@ describe('kuery functions', () => { ) as KqlRangeFunctionNode; const result = range.toElasticsearchQuery(node, indexPattern); - expect((result.bool!.should as estypes.QueryDslQueryContainer[])[0]).toHaveProperty( + expect((result!.bool!.should as estypes.QueryDslQueryContainer[])[0]).toHaveProperty( 'script' ); }); diff --git a/src/platform/packages/shared/kbn-es-query/src/kuery/index.ts b/src/platform/packages/shared/kbn-es-query/src/kuery/index.ts index c470071d56a95..770c1903b4927 100644 --- a/src/platform/packages/shared/kbn-es-query/src/kuery/index.ts +++ b/src/platform/packages/shared/kbn-es-query/src/kuery/index.ts @@ -18,7 +18,7 @@ import { toElasticsearchQuery as astToElasticsearchQuery } from './ast'; * about how we craft the queries (e.g. scripted fields) */ export const toElasticsearchQuery = (...params: Parameters) => { - return astToElasticsearchQuery(...params) as estypes.QueryDslQueryContainer; + return astToElasticsearchQuery(...params) as NonNullable; }; export { KQLSyntaxError } from './kuery_syntax_error'; diff --git a/src/platform/packages/shared/kbn-grouping/src/containers/query/types.ts b/src/platform/packages/shared/kbn-grouping/src/containers/query/types.ts index 97ea0ededdc5b..236a495458591 100644 --- a/src/platform/packages/shared/kbn-grouping/src/containers/query/types.ts +++ b/src/platform/packages/shared/kbn-grouping/src/containers/query/types.ts @@ -66,7 +66,7 @@ export interface GroupingRuntimeField extends MappingRuntimeField { type GroupingMappingRuntimeFields = Record<'groupByField', GroupingRuntimeField>; -export interface GroupingQuery extends estypes.QueryDslQueryContainer { +export type GroupingQuery = estypes.QueryDslQueryContainer & { aggs: MainAggregation; query: { bool: { @@ -76,4 +76,4 @@ export interface GroupingQuery extends estypes.QueryDslQueryContainer { runtime_mappings: MappingRuntimeFields & GroupingMappingRuntimeFields; size: number; _source: boolean; -} +}; diff --git a/src/platform/packages/shared/kbn-synthtrace/src/lib/logs/custom_logsdb_index_templates.ts b/src/platform/packages/shared/kbn-synthtrace/src/lib/logs/custom_logsdb_index_templates.ts index 748246e5e0ed4..ed7a7cc254506 100644 --- a/src/platform/packages/shared/kbn-synthtrace/src/lib/logs/custom_logsdb_index_templates.ts +++ b/src/platform/packages/shared/kbn-synthtrace/src/lib/logs/custom_logsdb_index_templates.ts @@ -68,7 +68,6 @@ export const indexTemplates: { settings: { default_pipeline: 'logs@default-pipeline', }, - // @ts-expect-error data_stream_options: { failure_store: { enabled: false, @@ -93,7 +92,6 @@ export const indexTemplates: { settings: { default_pipeline: 'synth.fs@pipeline', }, - // @ts-expect-error data_stream_options: { failure_store: { enabled: true, diff --git a/src/platform/plugins/private/vis_types/vega/public/data_model/es_query_parser.ts b/src/platform/plugins/private/vis_types/vega/public/data_model/es_query_parser.ts index a1262a03ad0cc..88e726ea49e7e 100644 --- a/src/platform/plugins/private/vis_types/vega/public/data_model/es_query_parser.ts +++ b/src/platform/plugins/private/vis_types/vega/public/data_model/es_query_parser.ts @@ -181,7 +181,7 @@ export class EsQueryParser { // Use dashboard context const newQuery = cloneDeep(this._filters); if (timefield) { - newQuery.bool!.must!.push(body.query); + newQuery.bool!.must!.push(body.query as estypes.QueryDslQueryContainer); } body.query = newQuery; } diff --git a/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_data_telemetry/get_data_telemetry.ts b/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_data_telemetry/get_data_telemetry.ts index cce37543fce0a..1d5963811914f 100644 --- a/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_data_telemetry/get_data_telemetry.ts +++ b/src/platform/plugins/shared/telemetry/server/telemetry_collection/get_data_telemetry/get_data_telemetry.ts @@ -205,16 +205,11 @@ export async function getDataTelemetry(esClient: ElasticsearchClient) { '*.mappings.properties.data_stream.properties.dataset.value', ], }; - const indicesStatsParams: { - index: string | string[] | undefined; - level: 'cluster' | 'indices' | 'shards' | undefined; - metric: string[]; - filter_path: string[]; - } = { + const indicesStatsParams = { // GET /_stats/docs,store?level=indices&filter_path=indices.*.total index, - level: 'indices', - metric: ['docs', 'store'], + level: 'indices' as const, + metric: ['docs', 'store'] as ('docs' | 'store')[], filter_path: ['indices.*.total'], }; const [indexMappings, indexStats] = await Promise.all([ @@ -240,7 +235,7 @@ export async function getDataTelemetry(esClient: ElasticsearchClient) { indexMappings[name]?.mappings?.properties?.data_stream?.properties?.type?.value, }; - const stats = (indexStats?.indices || {})[name]; + const stats = (indexStats?.indices ?? {})[name]; if (stats) { return { ...baseIndexInfo, diff --git a/x-pack/platform/packages/private/ml/category_validator/src/examples.ts b/x-pack/platform/packages/private/ml/category_validator/src/examples.ts index dd7f914dfba56..f09d7a30289ec 100644 --- a/x-pack/platform/packages/private/ml/category_validator/src/examples.ts +++ b/x-pack/platform/packages/private/ml/category_validator/src/examples.ts @@ -73,16 +73,20 @@ export function categorizationExamplesProvider(client: IScopedClusterClient) { }, }, }; - if (query.bool === undefined) { - query.bool = {}; - } - if (query.bool.filter === undefined) { - query.bool.filter = range; + if (!query || typeof query !== 'object') { + query = { bool: { filter: range } }; } else { - if (Array.isArray(query.bool.filter)) { - query.bool.filter.push(range); + if (query.bool === undefined) { + query.bool = {}; + } + if (query.bool.filter === undefined) { + query.bool.filter = range; } else { - query.bool.filter.range = range; + if (Array.isArray(query.bool.filter)) { + query.bool.filter.push(range); + } else { + query.bool.filter = [query.bool.filter, range] as estypes.QueryDslBoolQuery['filter']; + } } } } diff --git a/x-pack/platform/packages/private/ml/query_utils/src/add_exclude_frozen_to_query.test.ts b/x-pack/platform/packages/private/ml/query_utils/src/add_exclude_frozen_to_query.test.ts index 9c2e5cf0a38c7..4a7e8adb372e1 100644 --- a/x-pack/platform/packages/private/ml/query_utils/src/add_exclude_frozen_to_query.test.ts +++ b/x-pack/platform/packages/private/ml/query_utils/src/add_exclude_frozen_to_query.test.ts @@ -5,6 +5,7 @@ * 2.0. */ +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { addExcludeFrozenToQuery } from './add_exclude_frozen_to_query'; describe('addExcludeFrozenToQuery', () => { @@ -19,7 +20,7 @@ describe('addExcludeFrozenToQuery', () => { }, ], }, - }) + } as unknown as QueryDslQueryContainer) ).toMatchObject({ bool: { must: [{ match_all: {} }], @@ -39,7 +40,7 @@ describe('addExcludeFrozenToQuery', () => { }, }, }, - }) + } as unknown as QueryDslQueryContainer) ).toMatchObject({ bool: { must: [], @@ -56,7 +57,7 @@ describe('addExcludeFrozenToQuery', () => { must: [], must_not: [{ term: { category: { value: 'clothing' } } }], }, - }) + } as unknown as QueryDslQueryContainer) ).toMatchObject({ bool: { must: [], diff --git a/x-pack/platform/packages/private/ml/query_utils/src/build_base_filter_criteria.ts b/x-pack/platform/packages/private/ml/query_utils/src/build_base_filter_criteria.ts index ee7fed9383ba9..773c90e593e74 100644 --- a/x-pack/platform/packages/private/ml/query_utils/src/build_base_filter_criteria.ts +++ b/x-pack/platform/packages/private/ml/query_utils/src/build_base_filter_criteria.ts @@ -27,7 +27,7 @@ export function buildBaseFilterCriteria( latestMs?: number | string, query?: Query['query'], timeFormat = 'epoch_millis' -): estypes.QueryDslQueryContainer[] { +): NonNullable[] { const filterCriteria = []; if (timeFieldName && earliestMs && latestMs) { diff --git a/x-pack/platform/packages/private/ml/query_utils/src/get_default_dsl_query.ts b/x-pack/platform/packages/private/ml/query_utils/src/get_default_dsl_query.ts index d62cc97f92c48..1bb56c5d01021 100644 --- a/x-pack/platform/packages/private/ml/query_utils/src/get_default_dsl_query.ts +++ b/x-pack/platform/packages/private/ml/query_utils/src/get_default_dsl_query.ts @@ -9,7 +9,7 @@ import { cloneDeep } from 'lodash'; import type { estypes } from '@elastic/elasticsearch'; -const DEFAULT_DSL_QUERY: estypes.QueryDslQueryContainer = { +const DEFAULT_DSL_QUERY: NonNullable = { bool: { must: [ { @@ -22,6 +22,6 @@ const DEFAULT_DSL_QUERY: estypes.QueryDslQueryContainer = { /** * Default DSL query which matches all the results */ -export function getDefaultDSLQuery(): estypes.QueryDslQueryContainer { +export function getDefaultDSLQuery(): NonNullable { return cloneDeep(DEFAULT_DSL_QUERY); } diff --git a/x-pack/platform/packages/shared/kbn-streamlang/src/transpilers/ingest_pipeline/processors/math_processor.test.ts b/x-pack/platform/packages/shared/kbn-streamlang/src/transpilers/ingest_pipeline/processors/math_processor.test.ts index 44c179795590f..7f314cd2141cf 100644 --- a/x-pack/platform/packages/shared/kbn-streamlang/src/transpilers/ingest_pipeline/processors/math_processor.test.ts +++ b/x-pack/platform/packages/shared/kbn-streamlang/src/transpilers/ingest_pipeline/processors/math_processor.test.ts @@ -18,7 +18,7 @@ describe('processMathProcessor', () => { to: 'result', }; const result = processMathProcessor(processor); - expect(result).toEqual({ + expect(result!).toEqual({ script: { lang: 'painless', source: "ctx['result'] = (2 + 2);", @@ -34,7 +34,7 @@ describe('processMathProcessor', () => { to: 'total', }; const result = processMathProcessor(processor); - expect(result).toEqual({ + expect(result!).toEqual({ script: { lang: 'painless', source: "ctx['total'] = ($('price', null) * $('quantity', null));", @@ -54,7 +54,7 @@ describe('processMathProcessor', () => { for (const { expr, expected } of expressions) { const processor: MathProcessor = { action: 'math', expression: expr, to: 'result' }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( `ctx['result'] = ${expected};` ); } @@ -69,7 +69,7 @@ describe('processMathProcessor', () => { to: 'attributes.total', }; const result = processMathProcessor(processor); - expect(result).toEqual({ + expect(result!).toEqual({ script: { lang: 'painless', source: @@ -86,7 +86,7 @@ describe('processMathProcessor', () => { to: 'order.item.total', }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( "ctx['order.item.total'] = ($('order.item.price', null) * $('order.item.qty', null));" ); }); @@ -100,7 +100,7 @@ describe('processMathProcessor', () => { to: 'ln_value', }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( "ctx['ln_value'] = Math.log($('value', null));" ); }); @@ -112,7 +112,7 @@ describe('processMathProcessor', () => { to: 'result', }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( "ctx['result'] = Math.log(100);" ); }); @@ -124,7 +124,7 @@ describe('processMathProcessor', () => { to: 'result', }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( "ctx['result'] = Math.log(($('a', null) * $('b', null)));" ); }); @@ -138,7 +138,7 @@ describe('processMathProcessor', () => { to: 'is_cheap', }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( "ctx['is_cheap'] = ($('price', null) < 100);" ); }); @@ -150,7 +150,7 @@ describe('processMathProcessor', () => { to: 'is_expensive', }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( "ctx['is_expensive'] = ($('price', null) > 100);" ); }); @@ -162,7 +162,7 @@ describe('processMathProcessor', () => { to: 'is_active', }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( "ctx['is_active'] = ($('status', null) == 1);" ); }); @@ -174,7 +174,7 @@ describe('processMathProcessor', () => { to: 'is_not_zero', }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( "ctx['is_not_zero'] = ($('status', null) != 0);" ); }); @@ -186,7 +186,7 @@ describe('processMathProcessor', () => { to: 'in_budget', }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( "ctx['in_budget'] = ($('price', null) <= 50);" ); }); @@ -198,7 +198,7 @@ describe('processMathProcessor', () => { to: 'passed', }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( "ctx['passed'] = ($('score', null) >= 60);" ); }); @@ -210,7 +210,7 @@ describe('processMathProcessor', () => { to: 'is_expensive', }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( "ctx['is_expensive'] = ($('price', null) > 100);" ); }); @@ -225,7 +225,7 @@ describe('processMathProcessor', () => { ignore_missing: true, }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( "if ($('value', null) != null) { ctx['result'] = ($('value', null) * 2); }" ); }); @@ -238,7 +238,7 @@ describe('processMathProcessor', () => { ignore_missing: true, }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( "if ($('price', null) != null && $('quantity', null) != null && $('tax', null) != null) { ctx['total'] = (($('price', null) * $('quantity', null)) + $('tax', null)); }" ); }); @@ -251,7 +251,7 @@ describe('processMathProcessor', () => { ignore_missing: true, }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( "if ($('attributes.price', null) != null && $('attributes.qty', null) != null) { ctx['total'] = ($('attributes.price', null) * $('attributes.qty', null)); }" ); }); @@ -264,7 +264,7 @@ describe('processMathProcessor', () => { ignore_missing: false, }; const result = processMathProcessor(processor); - expect((result.script as Record).source).toBe( + expect((result!.script as Record).source).toBe( "ctx['total'] = ($('price', null) * $('quantity', null));" ); }); @@ -282,9 +282,9 @@ describe('processMathProcessor', () => { if: compiledIf, }; const result = processMathProcessor(processor); - expect(result.script).toHaveProperty('if'); - expect((result.script as Record).if).toBe(compiledIf); - expect((result.script as Record).if).toContain('active'); + expect(result!.script).toHaveProperty('if'); + expect((result!.script as Record).if).toBe(compiledIf); + expect((result!.script as Record).if).toContain('active'); }); }); @@ -297,7 +297,7 @@ describe('processMathProcessor', () => { tag: 'calc_total', }; const result = processMathProcessor(processor); - expect((result.script as Record).tag).toBe('calc_total'); + expect((result!.script as Record).tag).toBe('calc_total'); }); it('should include ignore_failure when true', () => { @@ -308,7 +308,7 @@ describe('processMathProcessor', () => { ignore_failure: true, }; const result = processMathProcessor(processor); - expect((result.script as Record).ignore_failure).toBe(true); + expect((result!.script as Record).ignore_failure).toBe(true); }); it('should always include description', () => { @@ -318,7 +318,7 @@ describe('processMathProcessor', () => { to: 'sum', }; const result = processMathProcessor(processor); - expect((result.script as Record).description).toBe('Math processor: a + b'); + expect((result!.script as Record).description).toBe('Math processor: a + b'); }); }); @@ -334,7 +334,7 @@ describe('processMathProcessor', () => { ])('should generate error-throwing script for: %s', (expression, funcName) => { const processor: MathProcessor = { action: 'math', expression, to: 'result' }; const result = processMathProcessor(processor); - const source = (result.script as Record).source as string; + const source = (result!.script as Record).source as string; expect(source).toContain('throw new IllegalArgumentException("'); expect(source).toContain(funcName); expect(source).toContain('not supported'); @@ -347,7 +347,7 @@ describe('processMathProcessor', () => { to: 'result', }; const result = processMathProcessor(processor); - const source = (result.script as Record).source as string; + const source = (result!.script as Record).source as string; expect(source).toContain('throw new IllegalArgumentException("'); expect(source).toContain('Unknown function'); }); @@ -359,7 +359,7 @@ describe('processMathProcessor', () => { to: 'result', }; const result = processMathProcessor(processor); - const source = (result.script as Record).source as string; + const source = (result!.script as Record).source as string; expect(source).toContain('throw new IllegalArgumentException("'); expect(source).toContain('Failed to parse expression'); }); diff --git a/x-pack/platform/packages/shared/kbn-streamlang/src/transpilers/ingest_pipeline/processors/post_processing.ts b/x-pack/platform/packages/shared/kbn-streamlang/src/transpilers/ingest_pipeline/processors/post_processing.ts index e014c8bf9d040..00e90f95dc05a 100644 --- a/x-pack/platform/packages/shared/kbn-streamlang/src/transpilers/ingest_pipeline/processors/post_processing.ts +++ b/x-pack/platform/packages/shared/kbn-streamlang/src/transpilers/ingest_pipeline/processors/post_processing.ts @@ -10,7 +10,7 @@ import type { IngestProcessorContainer } from '@elastic/elasticsearch/lib/api/ty // This can be used to apply any post-processing directly to the ingest pipeline processors. export const applyPostProcessing = (processors: IngestProcessorContainer[]) => { return processors.map((processor) => { - if ('grok' in processor && processor.grok) { + if (processor?.grok) { return { grok: { ...processor.grok, diff --git a/x-pack/platform/packages/shared/kbn-streamlang/types/processors/manual_ingest_pipeline_processors.ts b/x-pack/platform/packages/shared/kbn-streamlang/types/processors/manual_ingest_pipeline_processors.ts index 37e2cf638fd5a..cbbdd8d043ed0 100644 --- a/x-pack/platform/packages/shared/kbn-streamlang/types/processors/manual_ingest_pipeline_processors.ts +++ b/x-pack/platform/packages/shared/kbn-streamlang/types/processors/manual_ingest_pipeline_processors.ts @@ -7,7 +7,7 @@ import type { IngestProcessorContainer } from '@elastic/elasticsearch/lib/api/types'; -export type ElasticsearchProcessorType = keyof IngestProcessorContainer; +export type ElasticsearchProcessorType = keyof NonNullable; const ensureFullProcessorTypeList = ( types: ElasticsearchProcessorType extends T[number] @@ -19,6 +19,7 @@ export const elasticsearchProcessorTypes = ensureFullProcessorTypeList([ 'append', 'attachment', 'bytes', + 'cef', 'circle', 'community_id', 'convert', diff --git a/x-pack/platform/packages/shared/kbn-streams-schema/src/ingest_pipeline_processors.ts b/x-pack/platform/packages/shared/kbn-streams-schema/src/ingest_pipeline_processors.ts index 37e2cf638fd5a..cbbdd8d043ed0 100644 --- a/x-pack/platform/packages/shared/kbn-streams-schema/src/ingest_pipeline_processors.ts +++ b/x-pack/platform/packages/shared/kbn-streams-schema/src/ingest_pipeline_processors.ts @@ -7,7 +7,7 @@ import type { IngestProcessorContainer } from '@elastic/elasticsearch/lib/api/types'; -export type ElasticsearchProcessorType = keyof IngestProcessorContainer; +export type ElasticsearchProcessorType = keyof NonNullable; const ensureFullProcessorTypeList = ( types: ElasticsearchProcessorType extends T[number] @@ -19,6 +19,7 @@ export const elasticsearchProcessorTypes = ensureFullProcessorTypeList([ 'append', 'attachment', 'bytes', + 'cef', 'circle', 'community_id', 'convert', diff --git a/x-pack/platform/packages/shared/logs-overview/src/services/categorize_logs_service/queries.ts b/x-pack/platform/packages/shared/logs-overview/src/services/categorize_logs_service/queries.ts index 08e9ada2a6c94..c3cae57bd4c09 100644 --- a/x-pack/platform/packages/shared/logs-overview/src/services/categorize_logs_service/queries.ts +++ b/x-pack/platform/packages/shared/logs-overview/src/services/categorize_logs_service/queries.ts @@ -127,7 +127,6 @@ export const createCategorizationRequestParams = ({ }, }, change: { - // @ts-expect-error the official types don't support the change_point aggregation change_point: { buckets_path: 'histogram>_count', }, diff --git a/x-pack/platform/packages/shared/ml/aiops_common/create_default_query.ts b/x-pack/platform/packages/shared/ml/aiops_common/create_default_query.ts index 39cfafff4097b..65d23ac041e02 100644 --- a/x-pack/platform/packages/shared/ml/aiops_common/create_default_query.ts +++ b/x-pack/platform/packages/shared/ml/aiops_common/create_default_query.ts @@ -23,26 +23,27 @@ export function createDefaultQuery( query.bool = Object.create(null) as QueryDslBoolQuery; } - if (query.bool.must === undefined) { - query.bool.must = []; + const bool = query.bool; + if (bool.must === undefined) { + bool.must = []; if (query.match_all !== undefined) { - query.bool.must.push({ match_all: query.match_all }); + bool.must.push({ match_all: query.match_all }); delete query.match_all; } if (query.query_string !== undefined) { - query.bool.must.push({ query_string: query.query_string }); + bool.must.push({ query_string: query.query_string }); delete query.query_string; } } if (query.multi_match !== undefined) { - query.bool.should = { + bool.should = { multi_match: query.multi_match, }; delete query.multi_match; } if (timeRange !== undefined) { - (query.bool.must as QueryDslQueryContainer[]).push({ + (bool.must as QueryDslQueryContainer[]).push({ range: { [timeField]: { gte: timeRange.from, diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_significant_term_p_values.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_significant_term_p_values.ts index f0d22ba4f462e..4003037e16b02 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_significant_term_p_values.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_significant_term_p_values.ts @@ -41,7 +41,7 @@ export const getSignificantTermRequest = ( let filter: estypes.QueryDslQueryContainer[] = []; if (query.bool && Array.isArray(query.bool.filter)) { - filter = query.bool.filter.filter((d) => Object.keys(d)[0] !== 'range'); + filter = query.bool.filter.filter((d) => Object.keys(d || {})[0] !== 'range'); query.bool.filter = [ ...filter, diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_top_terms.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_top_terms.ts index 27538128df51b..7dd67433da559 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_top_terms.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/fetch_top_terms.ts @@ -41,7 +41,7 @@ export const getTopTermRequest = ( let filter: estypes.QueryDslQueryContainer[] = []; if (query.bool && Array.isArray(query.bool.filter)) { - filter = query.bool.filter.filter((d) => Object.keys(d)[0] !== 'range'); + filter = query.bool.filter.filter((d) => Object.keys(d || {})[0] !== 'range'); query.bool.filter = [ ...filter, diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_histogram_query.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_histogram_query.ts index 3f1d3c0b36cb6..39458659f2c56 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_histogram_query.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_histogram_query.ts @@ -20,7 +20,9 @@ export function getHistogramQuery( }); if (histogramQuery.bool && Array.isArray(histogramQuery.bool.filter)) { - const existingFilter = histogramQuery.bool.filter.filter((d) => Object.keys(d)[0] !== 'range'); + const existingFilter = histogramQuery.bool.filter.filter( + (d) => Object.keys(d || {})[0] !== 'range' + ); histogramQuery.bool.filter = [ ...existingFilter, diff --git a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_query_with_params.ts b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_query_with_params.ts index e63d54df7820f..be357fe6f72bf 100644 --- a/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_query_with_params.ts +++ b/x-pack/platform/packages/shared/ml/aiops_log_rate_analysis/queries/get_query_with_params.ts @@ -28,13 +28,13 @@ export const getQueryWithParams = ({ termFilters, filter, skipRangeQuery = false, -}: QueryParams): estypes.QueryDslQueryContainer => { +}: QueryParams): NonNullable => { const searchQuery = JSON.parse(params.searchQuery) as estypes.QueryDslQueryContainer; return { bool: { filter: [ // Add `searchQuery` if it's not a `match_all` query - ...(searchQuery.match_all === undefined ? [searchQuery] : []), + ...(searchQuery?.match_all === undefined ? [searchQuery] : []), // Add a range query based on `start/end` for the `timeFieldName`, check for skip flag. ...(!skipRangeQuery ? [getRangeQuery(params.start, params.end, params.timeFieldName)] : []), diff --git a/x-pack/platform/packages/shared/response-ops/alerts-table/hooks/use_bulk_actions.ts b/x-pack/platform/packages/shared/response-ops/alerts-table/hooks/use_bulk_actions.ts index cd9139f05af39..39fe32a9c20da 100644 --- a/x-pack/platform/packages/shared/response-ops/alerts-table/hooks/use_bulk_actions.ts +++ b/x-pack/platform/packages/shared/response-ops/alerts-table/hooks/use_bulk_actions.ts @@ -41,7 +41,7 @@ import { MUTE_SELECTED, UNMUTE_SELECTED } from '../translations'; interface BulkActionsProps { ruleTypeIds?: string[]; - query: Pick; + query: Partial, 'bool' | 'ids'>>; alertsCount: number; casesConfig?: PublicAlertsDataGridProps['casesConfiguration']; additionalBulkActions?: PublicAlertsDataGridProps['additionalBulkActions']; diff --git a/x-pack/platform/packages/shared/response-ops/alerts-table/hooks/use_bulk_untrack_alerts_by_query.tsx b/x-pack/platform/packages/shared/response-ops/alerts-table/hooks/use_bulk_untrack_alerts_by_query.tsx index b946c7ac3576b..0e0215c930b76 100644 --- a/x-pack/platform/packages/shared/response-ops/alerts-table/hooks/use_bulk_untrack_alerts_by_query.tsx +++ b/x-pack/platform/packages/shared/response-ops/alerts-table/hooks/use_bulk_untrack_alerts_by_query.tsx @@ -25,7 +25,10 @@ export const useBulkUntrackAlertsByQuery = ({ return useMutation< string, string, - { query: Pick; ruleTypeIds: string[] } + { + query: Partial, 'bool' | 'ids'>>; + ruleTypeIds: string[]; + } >( mutationKeys.bulkUntrackAlertsByQuery(), ({ query, ruleTypeIds }) => { diff --git a/x-pack/platform/packages/shared/response-ops/alerts-table/types.ts b/x-pack/platform/packages/shared/response-ops/alerts-table/types.ts index 206bd7c4cd7c9..c257b25de1a67 100644 --- a/x-pack/platform/packages/shared/response-ops/alerts-table/types.ts +++ b/x-pack/platform/packages/shared/response-ops/alerts-table/types.ts @@ -217,7 +217,7 @@ export interface AlertsTableProps; + query: Pick, 'bool' | 'ids'>; /** * The sort configuration. * @@ -592,7 +592,7 @@ export interface AlertsDataGridProps void; onResetColumns: () => void; onColumnResize?: EuiDataGridOnColumnResizeHandler; - query: Pick; + query: Pick, 'bool' | 'ids'>; showInspectButton?: boolean; toolbarVisibility?: EuiDataGridToolBarVisibilityOptions; /** diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_page.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_page.tsx index 02d4b73c774a3..3ac1461af94e1 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_page.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/data_drift/data_drift_page.tsx @@ -192,7 +192,7 @@ export const DataDriftPage: FC = ({ initialSettings }) => { const setSearchParams = useCallback( (searchParams: { - searchQuery: estypes.QueryDslQueryContainer; + searchQuery: NonNullable; searchString: Query['query']; queryLanguage: SearchQueryLanguage; filters: Filter[]; diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/hooks/esql/use_data_visualizer_esql_data.tsx b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/hooks/esql/use_data_visualizer_esql_data.tsx index c68005e22add7..7f58e83bd8a4f 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/hooks/esql/use_data_visualizer_esql_data.tsx +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/hooks/esql/use_data_visualizer_esql_data.tsx @@ -231,6 +231,9 @@ export const useESQLDataVisualizerData = ( } // Ensure that we don't query frozen data + if (!filter) { + filter = { bool: {} }; + } if (filter.bool === undefined) { filter.bool = Object.create(null); } diff --git a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/utils/saved_search_utils.ts b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/utils/saved_search_utils.ts index 70c32d7365817..644878cbd15ce 100644 --- a/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/utils/saved_search_utils.ts +++ b/x-pack/platform/plugins/private/data_visualizer/public/application/index_data_visualizer/utils/saved_search_utils.ts @@ -73,10 +73,10 @@ export function getEsQueryFromSavedSearch({ cloneDeep(savedSearchSource.getSearchRequestBody()?.query) ?? getDefaultDSLQuery(); const timeField = savedSearchSource.getField('index')?.timeFieldName; - if (Array.isArray(savedQuery.bool.filter) && timeField !== undefined) { + if (savedQuery?.bool && Array.isArray(savedQuery.bool.filter) && timeField !== undefined) { savedQuery.bool.filter = savedQuery.bool.filter.filter( (c: QueryDslQueryContainer) => - !(Object.hasOwn(c, 'range') && Object.hasOwn(c.range ?? {}, timeField)) + c != null && !(Object.hasOwn(c, 'range') && Object.hasOwn(c.range ?? {}, timeField)) ); } diff --git a/x-pack/platform/plugins/private/rollup/server/collectors/helpers.ts b/x-pack/platform/plugins/private/rollup/server/collectors/helpers.ts index e1a8006a26eea..2752a87954118 100644 --- a/x-pack/platform/plugins/private/rollup/server/collectors/helpers.ts +++ b/x-pack/platform/plugins/private/rollup/server/collectors/helpers.ts @@ -73,7 +73,7 @@ const getSavedObjectsList = async ({ sort: [{ updated_at: 'asc' }], query: { bool: { - filter, + filter: filter as estypes.QueryDslQueryContainer, }, }, ignore_unavailable: true, diff --git a/x-pack/platform/plugins/shared/aiops/public/application/utils/search_utils.ts b/x-pack/platform/plugins/shared/aiops/public/application/utils/search_utils.ts index 25e511521c42f..ce2a3752048e8 100644 --- a/x-pack/platform/plugins/shared/aiops/public/application/utils/search_utils.ts +++ b/x-pack/platform/plugins/shared/aiops/public/application/utils/search_utils.ts @@ -65,10 +65,10 @@ export function getEsQueryFromSavedSearch({ cloneDeep(savedSearch.searchSource.getSearchRequestBody()?.query) ?? getDefaultDSLQuery(); const timeField = savedSearch.searchSource.getField('index')?.timeFieldName; - if (Array.isArray(savedQuery.bool.filter) && timeField !== undefined) { + if (savedQuery?.bool && Array.isArray(savedQuery.bool.filter) && timeField !== undefined) { savedQuery.bool.filter = savedQuery.bool.filter.filter( (c: QueryDslQueryContainer) => - !(Object.hasOwn(c, 'range') && Object.hasOwn(c.range ?? {}, timeField)) + c != null && !(Object.hasOwn(c, 'range') && Object.hasOwn(c.range ?? {}, timeField)) ); } return { diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_page.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_page.tsx index 4222bdb17e032..c8a6a1890529c 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_page.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_categorization/log_categorization_page.tsx @@ -120,7 +120,7 @@ export const LogCategorizationPage: FC = () => { const setSearchParams = useCallback( (searchParams: { - searchQuery: estypes.QueryDslQueryContainer; + searchQuery: NonNullable; searchString: Query['query']; queryLanguage: SearchQueryLanguage; filters: Filter[]; diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content.tsx index 38e10d585f755..7289676e762ba 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_content/log_rate_analysis_content.tsx @@ -40,8 +40,8 @@ import { import { useAiopsAppContext } from '../../../hooks/use_aiops_app_context'; import { LogRateAnalysisAttachmentsMenu } from './log_rate_analysis_attachments_menu'; -export const DEFAULT_SEARCH_QUERY: estypes.QueryDslQueryContainer = { match_all: {} }; -const DEFAULT_SEARCH_BAR_QUERY: estypes.QueryDslQueryContainer = { +export const DEFAULT_SEARCH_QUERY: NonNullable = { match_all: {} }; +const DEFAULT_SEARCH_BAR_QUERY: NonNullable = { bool: { filter: [], must: [ diff --git a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_page.tsx b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_page.tsx index c499cc0c87467..5d6be2820f924 100644 --- a/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_page.tsx +++ b/x-pack/platform/plugins/shared/aiops/public/components/log_rate_analysis/log_rate_analysis_page.tsx @@ -96,7 +96,7 @@ export const LogRateAnalysisPage: FC = ({ const setSearchParams = useCallback( (searchParams: { - searchQuery: estypes.QueryDslQueryContainer; + searchQuery: NonNullable; searchString: Query['query']; queryLanguage: SearchQueryLanguage; filters: Filter[]; diff --git a/x-pack/platform/plugins/shared/aiops/public/get_document_stats.ts b/x-pack/platform/plugins/shared/aiops/public/get_document_stats.ts index 08dd730528d08..5bed7e6760c40 100644 --- a/x-pack/platform/plugins/shared/aiops/public/get_document_stats.ts +++ b/x-pack/platform/plugins/shared/aiops/public/get_document_stats.ts @@ -84,7 +84,6 @@ export const getDocumentCountStatsRequest = ( ...(changePoints ? { change_point_request: { - // @ts-expect-error missing from ES spec change_point: { buckets_path: 'eventRate>_count', }, diff --git a/x-pack/platform/plugins/shared/aiops/public/hooks/use_data.ts b/x-pack/platform/plugins/shared/aiops/public/hooks/use_data.ts index a73ced70d4c8a..7122dcf166761 100644 --- a/x-pack/platform/plugins/shared/aiops/public/hooks/use_data.ts +++ b/x-pack/platform/plugins/shared/aiops/public/hooks/use_data.ts @@ -31,7 +31,7 @@ const DEFAULT_BAR_TARGET = 75; export const useData = ( selectedDataView: DataView, contextId: string, - searchQuery: estypes.QueryDslQueryContainer, + searchQuery: NonNullable, onUpdate?: (params: Dictionary) => void, selectedSignificantItem?: SignificantItem, selectedGroup: GroupTableItem | null = null, diff --git a/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/alert_conflict_resolver.ts b/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/alert_conflict_resolver.ts index 654936ede407b..3a98dce459437 100644 --- a/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/alert_conflict_resolver.ts +++ b/x-pack/platform/plugins/shared/alerting/server/alerts_client/lib/alert_conflict_resolver.ts @@ -156,7 +156,7 @@ async function refreshFieldsInDocs( freshResponses: MgetResponseItem[] ) { for (const [conflictRequest, freshResponse] of zip(conflictRequests, freshResponses)) { - if (!conflictRequest?.op.index || !freshResponse) continue; + if (!conflictRequest?.op?.index || !freshResponse) continue; // @ts-expect-error @elastic/elasticsearch _source is not in the type! const freshDoc = freshResponse._source; @@ -191,7 +191,7 @@ async function refreshFieldsInDocs( /** Update the OCC info in the conflict request with the fresh info. */ async function updateOCC(conflictRequests: NormalizedBulkRequest[], freshDocs: MgetResponseItem[]) { for (const [req, freshDoc] of zip(conflictRequests, freshDocs)) { - if (!req?.op.index || !freshDoc) continue; + if (!req?.op?.index || !freshDoc) continue; // @ts-expect-error @elastic/elasticsearch _seq_no is not in the type! const seqNo: number | undefined = freshDoc._seq_no; @@ -214,7 +214,7 @@ async function getFreshDocs( const docs: Array<{ _id: string; _index: string }> = []; conflictRequests.forEach((req) => { - const [id, index] = [req.op.index?._id, req.op.index?._index]; + const [id, index] = [req.op?.index?._id, req.op?.index?._index]; if (!id || !index) return; docs.push({ _id: id, _index: index }); @@ -262,7 +262,7 @@ function normalizeRequest(bulkRequest: BulkRequest) { let index = 0; while (index < bulkRequest.operations.length) { // the "op" data - const op = bulkRequest.operations[index] as BulkOperationContainer; + const op = bulkRequest.operations[index] as NonNullable; // now the "doc" data, if there is any (none for delete) if (op.create || op.index || op.update) { diff --git a/x-pack/platform/plugins/shared/alerting/server/application/rule/methods/aggregate/validation/validate_rule_aggregation_fields.test.ts b/x-pack/platform/plugins/shared/alerting/server/application/rule/methods/aggregate/validation/validate_rule_aggregation_fields.test.ts index 0f5a94e2230de..182b5dc78a939 100644 --- a/x-pack/platform/plugins/shared/alerting/server/application/rule/methods/aggregate/validation/validate_rule_aggregation_fields.test.ts +++ b/x-pack/platform/plugins/shared/alerting/server/application/rule/methods/aggregate/validation/validate_rule_aggregation_fields.test.ts @@ -5,6 +5,7 @@ * 2.0. */ +import type { AggregationsAggregationContainer } from '@elastic/elasticsearch/lib/api/types'; import { getRuleTagsAggregation } from '../../../../../../common'; import { defaultRuleAggregationFactory } from '..'; @@ -91,7 +92,7 @@ describe('validateAggregationTerms', () => { }, }, }, - }); + } as unknown as Record); }).not.toThrowError(); }); @@ -263,7 +264,7 @@ describe('validateAggregationTerms', () => { field: 'alert.attributes.executionStatus.status', }, }, - }); + } as unknown as Record); }).toThrowErrorMatchingInlineSnapshot(`"Invalid aggregation type: max"`); }); diff --git a/x-pack/platform/plugins/shared/cases/public/components/case_view/components/case_view_alerts.tsx b/x-pack/platform/plugins/shared/cases/public/components/case_view/components/case_view_alerts.tsx index 6344b117c28b3..0950e3452cfda 100644 --- a/x-pack/platform/plugins/shared/cases/public/components/case_view/components/case_view_alerts.tsx +++ b/x-pack/platform/plugins/shared/cases/public/components/case_view/components/case_view_alerts.tsx @@ -5,6 +5,7 @@ * 2.0. */ +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import { EuiFlexGroup, EuiFlexItem, EuiProgress } from '@elastic/eui'; import type { Alert } from '@kbn/alerting-types'; import { AlertsTable as DefaultAlertsTable } from '@kbn/response-ops-alerts-table'; @@ -35,7 +36,7 @@ export const CaseViewAlerts = ({ services as SetRequired; const alertIds = getManualAlertIds(caseData.comments); const alertIdsQuery = useMemo( - () => ({ + (): NonNullable => ({ ids: { values: alertIds, }, @@ -53,7 +54,7 @@ export const CaseViewAlerts = ({ [onAlertsTableLoaded] ); - if (alertIdsQuery.ids.values.length === 0) { + if (alertIdsQuery.ids?.values?.length === 0) { return ( diff --git a/x-pack/platform/plugins/shared/cases/server/cases_analytics/cases_index/constants.ts b/x-pack/platform/plugins/shared/cases/server/cases_analytics/cases_index/constants.ts index 8c594ca84d116..756e4909106db 100644 --- a/x-pack/platform/plugins/shared/cases/server/cases_analytics/cases_index/constants.ts +++ b/x-pack/platform/plugins/shared/cases/server/cases_analytics/cases_index/constants.ts @@ -59,7 +59,7 @@ export const getCasesSynchronizationSourceQuery = ( owner: Owner ): QueryDslQueryContainer => ({ bool: { - filter: getCasesSourceQuery(spaceId, owner).bool?.filter, + filter: getCasesSourceQuery(spaceId, owner)?.bool?.filter ?? [], must: [ { bool: { diff --git a/x-pack/platform/plugins/shared/cases/server/cases_analytics/comments_index/constants.ts b/x-pack/platform/plugins/shared/cases/server/cases_analytics/comments_index/constants.ts index 6f870738f5b83..bee923aedbb4b 100644 --- a/x-pack/platform/plugins/shared/cases/server/cases_analytics/comments_index/constants.ts +++ b/x-pack/platform/plugins/shared/cases/server/cases_analytics/comments_index/constants.ts @@ -64,7 +64,7 @@ export const getCommentsSynchronizationSourceQuery = ( owner: Owner ): QueryDslQueryContainer => ({ bool: { - filter: getCommentsSourceQuery(spaceId, owner).bool?.filter, + filter: getCommentsSourceQuery(spaceId, owner)?.bool?.filter ?? [], must: [ { bool: { diff --git a/x-pack/platform/plugins/shared/cases/server/client/metrics/alerts/aggregations/hosts.ts b/x-pack/platform/plugins/shared/cases/server/client/metrics/alerts/aggregations/hosts.ts index 179a9aa25c978..1b1c81bc3f5c8 100644 --- a/x-pack/platform/plugins/shared/cases/server/client/metrics/alerts/aggregations/hosts.ts +++ b/x-pack/platform/plugins/shared/cases/server/client/metrics/alerts/aggregations/hosts.ts @@ -34,32 +34,28 @@ const hostId = 'host.id'; export class AlertHosts implements AggregationBuilder { constructor(private readonly uniqueValuesLimit: number = 10) {} - build() { - const topHits: estypes.AggregationsAggregationContainer = { - aggs: { - top_fields: { - top_hits: { - docvalue_fields: [hostName], - sort: [ - { - '@timestamp': { - order: 'desc', - }, - }, - ], - size: 1, - }, - }, - }, - }; - + build(): Record { return { hosts_frequency: { terms: { field: hostId, size: this.uniqueValuesLimit, }, - ...topHits, + aggs: { + top_fields: { + top_hits: { + docvalue_fields: [hostName], + sort: [ + { + '@timestamp': { + order: 'desc', + }, + }, + ], + size: 1, + }, + }, + }, }, hosts_total: { cardinality: { diff --git a/x-pack/platform/plugins/shared/ml/common/types/results.ts b/x-pack/platform/plugins/shared/ml/common/types/results.ts index 888f5e19ac4c0..37b76de5728d5 100644 --- a/x-pack/platform/plugins/shared/ml/common/types/results.ts +++ b/x-pack/platform/plugins/shared/ml/common/types/results.ts @@ -44,7 +44,7 @@ export interface DatafeedResultsChartDataParams { end: number; } -export const defaultSearchQuery: estypes.QueryDslQueryContainer = { +export const defaultSearchQuery: NonNullable = { bool: { must: [ { diff --git a/x-pack/platform/plugins/shared/ml/common/types/trained_models.ts b/x-pack/platform/plugins/shared/ml/common/types/trained_models.ts index 86ce75c6f822e..4ebb1520ef287 100644 --- a/x-pack/platform/plugins/shared/ml/common/types/trained_models.ts +++ b/x-pack/platform/plugins/shared/ml/common/types/trained_models.ts @@ -396,7 +396,10 @@ export type TrainedModelItem = ExistingModelBase & { stats: Stats }; /** Trained DFA model */ export type DFAModelItem = Omit & { origin_job_exists?: boolean; - inference_config?: Pick; + inference_config?: Pick< + NonNullable, + 'classification' | 'regression' + >; metadata?: estypes.MlTrainedModelConfig['metadata'] & { analytics_config: DataFrameAnalyticsConfig; input: unknown; diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/state.ts b/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/state.ts index 26bfe934eb46b..1d997f2c29c26 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/state.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/state.ts @@ -61,9 +61,8 @@ export const getInitialState = (model: DFAModelItem): MlInferenceState => { if (modelType !== undefined) { targetField = model.inference_config ? `ml.inference.${ - model.inference_config[ - modelType as keyof Exclude - ]!.results_field + model.inference_config[modelType as keyof NonNullable]! + .results_field }` : undefined; } @@ -74,6 +73,7 @@ export const getInitialState = (model: DFAModelItem): MlInferenceState => { error: false, fieldMap: undefined, ignoreFailure: false, + // @ts-expect-error - ExactlyOne in the ES types makes it really hard to comply without force-casting. inferenceConfig: model.inference_config, modelId: model.model_id, onFailure: getDefaultOnFailureConfiguration(), diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/validation.ts b/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/validation.ts index d8431af734b80..5499f6a504302 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/validation.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/components/ml_inference/validation.ts @@ -143,7 +143,7 @@ export const validatePipelineProcessors = ( } const inferenceProcessor = processors?.find( - (processor) => processor.inference && processor.inference.model_id + (processor) => processor?.inference && processor.inference.model_id ); if (inferenceProcessor === undefined) { diff --git a/x-pack/platform/plugins/shared/ml/public/application/components/shared/review_and_create_pipeline.tsx b/x-pack/platform/plugins/shared/ml/public/application/components/shared/review_and_create_pipeline.tsx index 44ffc94742ac4..f69377c52ae93 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/components/shared/review_and_create_pipeline.tsx +++ b/x-pack/platform/plugins/shared/ml/public/application/components/shared/review_and_create_pipeline.tsx @@ -35,7 +35,7 @@ function getFieldFromPipelineConfig(config: estypes.IngestPipeline) { const { processors } = config; let field = ''; if (processors?.length) { - field = Object.keys(processors[0].inference?.field_map ?? {})[0]; + field = Object.keys(processors[0]?.inference?.field_map ?? {})[0]; } return field; } diff --git a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts index 53bb2d3ceb4d1..307e3d995df7d 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts @@ -386,7 +386,7 @@ export function getFormStateFromJobConfig( resultState.destinationIndex = analyticsJobConfig?.dest.index ?? ''; } - const analysisConfig = analyticsJobConfig.analysis[jobType]; + const analysisConfig = analyticsJobConfig.analysis?.[jobType]; for (const key in analysisConfig) { if (Object.hasOwn(analysisConfig, key)) { diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts index 4620d52731b52..caffa1cc2b609 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts @@ -509,7 +509,7 @@ export class JobCreator { } public get query(): object { - return this._datafeed_config.query; + return this._datafeed_config.query!; } public set query(query: object) { diff --git a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/utils/new_job_utils.ts b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/utils/new_job_utils.ts index 031db77e22787..53338cf5c0c80 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/utils/new_job_utils.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/jobs/new_job/utils/new_job_utils.ts @@ -62,7 +62,7 @@ export function createQueries( kibanaConfig: IUiSettingsClient ) { let query = getDefaultQuery(); - let combinedQuery: estypes.QueryDslQueryContainer = getDefaultDatafeedQuery(); + let combinedQuery = getDefaultDatafeedQuery(); query = data.query; const filter = data.filter; @@ -82,6 +82,7 @@ export function createQueries( // a bool.should // in this case, move it to a bool.should if (combinedQuery.multi_match !== undefined) { + // @ts-expect-error - ExactlyOne in the ES types makes it really hard to comply without force-casting. combinedQuery.bool.should = { multi_match: combinedQuery.multi_match, }; diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/get_inference_properties_from_pipeline_config.ts b/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/get_inference_properties_from_pipeline_config.ts index 9af0461260bb1..c665872a5d6ed 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/get_inference_properties_from_pipeline_config.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/create_pipeline_for_model/get_inference_properties_from_pipeline_config.ts @@ -78,7 +78,7 @@ export function getInferencePropertiesFromPipelineConfig( }; pipelineConfig.processors?.forEach((processor) => { - const { inference } = processor; + const { inference } = processor || {}; if (inference) { propertiesToReturn.inferenceObj = inference; // Get the input field diff --git a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/inference_base.ts b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/inference_base.ts index 25ab8ea5c03e2..65a9f12f9c006 100644 --- a/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/inference_base.ts +++ b/x-pack/platform/plugins/shared/ml/public/application/model_management/test_models/models/inference_base.ts @@ -20,7 +20,7 @@ import type { ITelemetryClient } from '../../../services/telemetry/types'; export type InferenceType = | SupportedPytorchTasksType - | keyof estypes.AggregationsInferenceConfigContainer; + | keyof NonNullable; export type InferenceOptions = | estypes.MlRegressionInferenceOptions @@ -370,17 +370,16 @@ export abstract class InferenceBase { })); } - private getDefaultInferenceConfig(): estypes.MlInferenceConfigUpdateContainer[keyof estypes.MlInferenceConfigUpdateContainer] { + private getDefaultInferenceConfig(): NonNullable[InferenceType] { return this.model.inference_config![ this.inferenceType as keyof estypes.MlInferenceConfigUpdateContainer ]; } protected getNumTopClassesConfig(defaultOverride = 5) { - const options: estypes.MlInferenceConfigUpdateContainer[keyof estypes.MlInferenceConfigUpdateContainer] = - this.getDefaultInferenceConfig(); + const options = this.getDefaultInferenceConfig(); - if (options && 'num_top_classes' in options && (options?.num_top_classes ?? 0 > 0)) { + if (options && 'num_top_classes' in options && (options.num_top_classes ?? 0) > 0) { return {}; } diff --git a/x-pack/platform/plugins/shared/ml/server/models/model_management/models_provider.ts b/x-pack/platform/plugins/shared/ml/server/models/model_management/models_provider.ts index 7cf4d64a730e6..3d28454db8719 100644 --- a/x-pack/platform/plugins/shared/ml/server/models/model_management/models_provider.ts +++ b/x-pack/platform/plugins/shared/ml/server/models/model_management/models_provider.ts @@ -519,10 +519,10 @@ export class ModelsProvider { const id = processor.inference?.model_id; if (modelIdsMap.has(id)) { const obj = modelIdsMap.get(id); - if (obj === null) { - modelIdsMap.set(id, { [pipelineName]: pipelineDefinition }); + if (obj == null) { + modelIdsMap.set(id, { [pipelineName]: pipelineDefinition as PipelineDefinition }); } else { - obj![pipelineName] = pipelineDefinition; + obj[pipelineName] = pipelineDefinition as PipelineDefinition; } } } diff --git a/x-pack/platform/plugins/shared/ml/server/routes/anomaly_detectors.ts b/x-pack/platform/plugins/shared/ml/server/routes/anomaly_detectors.ts index 8266dbdea8c62..daf93d2b4b9be 100644 --- a/x-pack/platform/plugins/shared/ml/server/routes/anomaly_detectors.ts +++ b/x-pack/platform/plugins/shared/ml/server/routes/anomaly_detectors.ts @@ -553,7 +553,7 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) { try { const body = await mlClient.getCategories({ job_id: request.params.jobId, - category_id: request.params.categoryId, + category_id: Number(request.params.categoryId), }); return response.ok({ body, diff --git a/x-pack/platform/plugins/shared/rule_registry/common/types.ts b/x-pack/platform/plugins/shared/rule_registry/common/types.ts index 9898eb7dc6a84..9cb58edfbcbab 100644 --- a/x-pack/platform/plugins/shared/rule_registry/common/types.ts +++ b/x-pack/platform/plugins/shared/rule_registry/common/types.ts @@ -394,7 +394,7 @@ type AssertAssignable = T; // Used to check that the validation schema is aligned with the type from ES declare type _ = AssertAssignable< - keyof Omit, + keyof Omit, 'script' | 'script_score'>, t.TypeOf >; diff --git a/x-pack/platform/plugins/shared/rule_registry/server/search_strategy/search_strategy.ts b/x-pack/platform/plugins/shared/rule_registry/server/search_strategy/search_strategy.ts index 59644ce13f6f3..bde845fc2d16c 100644 --- a/x-pack/platform/plugins/shared/rule_registry/server/search_strategy/search_strategy.ts +++ b/x-pack/platform/plugins/shared/rule_registry/server/search_strategy/search_strategy.ts @@ -115,9 +115,9 @@ export const ruleRegistrySearchStrategyProvider = ( } const filter = request.query?.bool?.filter - ? Array.isArray(request.query?.bool?.filter) - ? request.query?.bool?.filter - : [request.query?.bool?.filter] + ? Array.isArray(request.query.bool.filter) + ? request.query.bool.filter + : [request.query.bool.filter] : []; if (authzFilter) { @@ -157,7 +157,7 @@ export const ruleRegistrySearchStrategyProvider = ( const query = { ...(request.query?.ids != null - ? { ids: request.query?.ids } + ? { ids: request.query.ids } : { bool: { ...request.query?.bool, diff --git a/x-pack/platform/plugins/shared/security/server/session_management/session_index.ts b/x-pack/platform/plugins/shared/security/server/session_management/session_index.ts index 08542e66683ff..f4f27d9cbe736 100644 --- a/x-pack/platform/plugins/shared/security/server/session_management/session_index.ts +++ b/x-pack/platform/plugins/shared/security/server/session_management/session_index.ts @@ -9,7 +9,7 @@ import { errors } from '@elastic/elasticsearch'; import type { AggregateName, AggregationsMultiTermsAggregate, - BulkOperationContainer, + BulkDeleteOperation, IndicesCreateRequest, MsearchRequestItem, SearchHit, @@ -1104,9 +1104,7 @@ export class SessionIndex { * @param deleteOperations Bulk delete operations. * @returns Returns `true` if the bulk delete affected any session document. */ - private async bulkDeleteSessions( - deleteOperations: Array>> - ) { + private async bulkDeleteSessions(deleteOperations: Array<{ delete: BulkDeleteOperation }>) { if (deleteOperations.length === 0) { return false; } diff --git a/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/inference/inference.test.ts b/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/inference/inference.test.ts index 8b7969775db56..3c261f4d57de4 100644 --- a/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/inference/inference.test.ts +++ b/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/inference/inference.test.ts @@ -234,7 +234,7 @@ describe('InferenceConnector', () => { }, { asStream: false } ); - expect(response).toEqual(mockResponse.text_embedding); + expect(response).toEqual([]); }); it('errors during API calls are properly handled', async () => { diff --git a/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/inference/inference.ts b/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/inference/inference.ts index f70a58bcefcf4..69e236397aa29 100644 --- a/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/inference/inference.ts +++ b/x-pack/platform/plugins/shared/stack_connectors/server/connector_types/inference/inference.ts @@ -285,7 +285,10 @@ export class InferenceConnector extends SubActionConnector { false, signal ); - return response.rerank!.map(({ relevance_score: score, ...rest }) => ({ score, ...rest })); + return (response?.rerank ?? []).map(({ relevance_score: score, ...rest }) => ({ + score, + ...rest, + })); } /** @@ -302,7 +305,7 @@ export class InferenceConnector extends SubActionConnector { false, signal ); - return response.sparse_embedding!; + return response?.sparse_embedding ?? []; } /** @@ -327,7 +330,7 @@ export class InferenceConnector extends SubActionConnector { false, signal ); - return response.text_embedding!; + return response?.text_embedding ?? []; } /** @@ -368,7 +371,7 @@ export class InferenceConnector extends SubActionConnector { false, signal ); - return response.completion!; + return response?.completion ?? []; } /** diff --git a/x-pack/platform/plugins/shared/streams/server/lib/significant_events/read_significant_events_from_alerts_indices.ts b/x-pack/platform/plugins/shared/streams/server/lib/significant_events/read_significant_events_from_alerts_indices.ts index 160ca6e74c6ab..c366bc6fcd110 100644 --- a/x-pack/platform/plugins/shared/streams/server/lib/significant_events/read_significant_events_from_alerts_indices.ts +++ b/x-pack/platform/plugins/shared/streams/server/lib/significant_events/read_significant_events_from_alerts_indices.ts @@ -113,7 +113,6 @@ export async function readSignificantEventsFromAlertsIndices( }, }, change_points: { - // @ts-expect-error change_point: { buckets_path: 'occurrences>_count', }, diff --git a/x-pack/platform/plugins/shared/streams/server/lib/streams/state_management/execution_plan/translate_classic_stream_pipeline_actions.ts b/x-pack/platform/plugins/shared/streams/server/lib/streams/state_management/execution_plan/translate_classic_stream_pipeline_actions.ts index 977d670d07fc5..02d9eef017d44 100644 --- a/x-pack/platform/plugins/shared/streams/server/lib/streams/state_management/execution_plan/translate_classic_stream_pipeline_actions.ts +++ b/x-pack/platform/plugins/shared/streams/server/lib/streams/state_management/execution_plan/translate_classic_stream_pipeline_actions.ts @@ -165,18 +165,18 @@ async function updateExistingStreamsManagedPipeline({ }) { let processors = pipeline.processors ?? []; const existingPipelineProcessors = processors - .filter((processor) => processor.pipeline !== undefined) - .map((processor) => processor.pipeline?.name); + .filter((processor) => processor?.pipeline !== undefined) + .map((processor) => processor!.pipeline!.name); for (const action of actions) { if (action.type === 'append_processor_to_ingest_pipeline') { - if (!existingPipelineProcessors.includes(action.processor.pipeline?.name)) { + if (!existingPipelineProcessors.includes(action.processor?.pipeline?.name ?? '')) { processors.push(action.processor); } } else { processors = processors.filter( (processor) => - processor.pipeline === undefined || processor.pipeline.name !== action.referencePipeline + processor?.pipeline === undefined || processor.pipeline.name !== action.referencePipeline ); } } @@ -215,18 +215,18 @@ async function updateExistingUserManagedPipeline({ let processors = targetPipeline?.processors ?? []; const existingPipelineProcessors = processors - .filter((processor) => processor.pipeline !== undefined) - .map((processor) => processor.pipeline?.name); + .filter((processor) => processor?.pipeline !== undefined) + .map((processor) => processor!.pipeline!.name); for (const action of actions) { if (action.type === 'append_processor_to_ingest_pipeline') { - if (!existingPipelineProcessors.includes(action.processor.pipeline?.name)) { + if (!existingPipelineProcessors.includes(action.processor?.pipeline?.name ?? '')) { processors.push(action.processor); } } else { processors = processors.filter( (processor) => - processor.pipeline === undefined || processor.pipeline.name !== action.referencePipeline + processor?.pipeline === undefined || processor.pipeline.name !== action.referencePipeline ); } } @@ -261,7 +261,7 @@ async function findPipelineToModify( } const streamProcessor = pipeline.processors?.find( - (processor) => processor.pipeline && processor.pipeline.name.includes('@stream.') + (processor) => processor?.pipeline && processor.pipeline.name.includes('@stream.') ); if (streamProcessor) { @@ -272,7 +272,7 @@ async function findPipelineToModify( } const customProcessor = pipeline.processors?.findLast( - (processor) => processor.pipeline && processor.pipeline.name.endsWith('@custom') + (processor) => processor?.pipeline && processor.pipeline.name.endsWith('@custom') ); if (customProcessor) { diff --git a/x-pack/platform/plugins/shared/streams/server/routes/internal/streams/processing/simulation_condition_noops.test.ts b/x-pack/platform/plugins/shared/streams/server/routes/internal/streams/processing/simulation_condition_noops.test.ts index ada47730ce812..16ea1948716de 100644 --- a/x-pack/platform/plugins/shared/streams/server/routes/internal/streams/processing/simulation_condition_noops.test.ts +++ b/x-pack/platform/plugins/shared/streams/server/routes/internal/streams/processing/simulation_condition_noops.test.ts @@ -28,12 +28,12 @@ describe('buildSimulationProcessorsWithConditionNoops', () => { expect(processors).toHaveLength(2); expect(processors[0]).toHaveProperty('set'); - expect(processors[0].set?.tag).toBe('cond-1'); - expect(processors[0].set?.field).toBe('_streams_condition_noop'); - expect(typeof processors[0].set?.if).toBe('string'); + expect(processors[0]!.set?.tag).toBe('cond-1'); + expect(processors[0]!.set?.field).toBe('_streams_condition_noop'); + expect(typeof processors[0]!.set?.if).toBe('string'); expect(processors[1]).toHaveProperty('remove'); - expect(processors[1].remove?.tag).toBe('cond-1:noop-cleanup'); - expect(processors[1].remove?.field).toBe('_streams_condition_noop'); + expect(processors[1]!.remove?.tag).toBe('cond-1:noop-cleanup'); + expect(processors[1]!.remove?.field).toBe('_streams_condition_noop'); }); it('injects condition no-op before its descendants and keeps descendant processor tags', () => { @@ -60,11 +60,11 @@ describe('buildSimulationProcessorsWithConditionNoops', () => { const processors = buildSimulationProcessorsWithConditionNoops(dsl); expect(processors).toHaveLength(3); - expect(processors[0].set?.tag).toBe('cond-1'); - expect(processors[1].remove?.tag).toBe('cond-1:noop-cleanup'); - expect(processors[1].remove?.field).toBe('_streams_condition_noop'); - expect(processors[2].set?.tag).toBe('proc-1'); - expect(typeof processors[2].set?.if).toBe('string'); + expect(processors[0]!.set?.tag).toBe('cond-1'); + expect(processors[1]!.remove?.tag).toBe('cond-1:noop-cleanup'); + expect(processors[1]!.remove?.field).toBe('_streams_condition_noop'); + expect(processors[2]!.set?.tag).toBe('proc-1'); + expect(typeof processors[2]!.set?.if).toBe('string'); }); it('composes nested condition no-ops with parent conditions', () => { @@ -100,15 +100,15 @@ describe('buildSimulationProcessorsWithConditionNoops', () => { const processors = buildSimulationProcessorsWithConditionNoops(dsl); expect(processors).toHaveLength(5); - expect(processors[0].set?.tag).toBe('cond-parent'); - expect(processors[1].remove?.tag).toBe('cond-parent:noop-cleanup'); - expect(processors[1].remove?.field).toBe('_streams_condition_noop'); - expect(processors[2].set?.tag).toBe('cond-child'); - expect(processors[3].remove?.tag).toBe('cond-child:noop-cleanup'); - expect(processors[3].remove?.field).toBe('_streams_condition_noop'); - expect(processors[4].set?.tag).toBe('proc-1'); + expect(processors[0]!.set?.tag).toBe('cond-parent'); + expect(processors[1]!.remove?.tag).toBe('cond-parent:noop-cleanup'); + expect(processors[1]!.remove?.field).toBe('_streams_condition_noop'); + expect(processors[2]!.set?.tag).toBe('cond-child'); + expect(processors[3]!.remove?.tag).toBe('cond-child:noop-cleanup'); + expect(processors[3]!.remove?.field).toBe('_streams_condition_noop'); + expect(processors[4]!.set?.tag).toBe('proc-1'); - const childSetIf = processors[2].set?.if; + const childSetIf = processors[2]!.set?.if; expect(childSetIf).toBe(conditionToPainless({ and: [parentCondition, childCondition] })); }); }); diff --git a/x-pack/platform/plugins/shared/streams/server/routes/internal/streams/processing/simulation_condition_noops.ts b/x-pack/platform/plugins/shared/streams/server/routes/internal/streams/processing/simulation_condition_noops.ts index e370cb81dbdf3..ca75f85ed80e4 100644 --- a/x-pack/platform/plugins/shared/streams/server/routes/internal/streams/processing/simulation_condition_noops.ts +++ b/x-pack/platform/plugins/shared/streams/server/routes/internal/streams/processing/simulation_condition_noops.ts @@ -23,7 +23,7 @@ function createConditionNoopProcessor({ }: { conditionId: string; condition: Condition; -}): IngestProcessorContainer[] { +}): NonNullable[] { let painlessIf: string; try { painlessIf = conditionToPainless(condition); @@ -68,8 +68,8 @@ function buildSimulationProcessorsFromSteps({ }: { steps: StreamlangStep[]; parentCondition?: Condition; -}): IngestProcessorContainer[] { - const processors: IngestProcessorContainer[] = []; +}): NonNullable[] { + const processors: NonNullable[] = []; for (const step of steps) { if (isConditionBlock(step)) { @@ -113,7 +113,7 @@ function buildSimulationProcessorsFromSteps({ const transpiled = transpileIngestPipeline( { steps: [stepWithCombinedWhere] } as StreamlangDSL, { ignoreMalformed: true, traceCustomIdentifiers: true } - ).processors; + ).processors as NonNullable[]; processors.push(...transpiled); } @@ -136,6 +136,6 @@ function buildSimulationProcessorsFromSteps({ */ export function buildSimulationProcessorsWithConditionNoops( processing: StreamlangDSL -): IngestProcessorContainer[] { +): NonNullable[] { return buildSimulationProcessorsFromSteps({ steps: processing.steps }); } diff --git a/x-pack/platform/plugins/shared/streams/server/routes/internal/streams/processing/simulation_handler.ts b/x-pack/platform/plugins/shared/streams/server/routes/internal/streams/processing/simulation_handler.ts index 0b13cd99b8bac..f128853a0ab68 100644 --- a/x-pack/platform/plugins/shared/streams/server/routes/internal/streams/processing/simulation_handler.ts +++ b/x-pack/platform/plugins/shared/streams/server/routes/internal/streams/processing/simulation_handler.ts @@ -230,7 +230,7 @@ const prepareSimulationProcessors = (processing: StreamlangDSL): IngestProcessor field: '_errors', value: { message: '{{{ _ingest.on_failure_message }}}', - processor_id: processorConfig.tag, + processor_id: processorConfig?.tag, type: 'generic_processor_failure', }, }, @@ -584,16 +584,17 @@ const computePipelineSimulationResult = ( }; const initProcessorMetricsMap = ( - processors: IngestProcessorContainer[] + processors: NonNullable[] ): Record => { // Gather unique IDs because the manual ingest pipeline proccessor (for example) will share the same // ID across it's nested processors. const ids = new Set(); for (const processor of processors) { - const type = Object.keys(processor)[0] as keyof IngestProcessorContainer; - const config = processor[type] as Record; - const tag = config.tag; + const type = Object.keys(processor)[0] as keyof NonNullable; + const config = processor[type]; + + const tag = config?.tag; if (typeof tag === 'string') { ids.add(tag); diff --git a/x-pack/platform/plugins/shared/task_manager/server/queries/query_clauses.ts b/x-pack/platform/plugins/shared/task_manager/server/queries/query_clauses.ts index 6f09ec56a16e5..453f11ed2ee21 100644 --- a/x-pack/platform/plugins/shared/task_manager/server/queries/query_clauses.ts +++ b/x-pack/platform/plugins/shared/task_manager/server/queries/query_clauses.ts @@ -35,9 +35,9 @@ export interface ScriptClause { }; } -export type PinnedQuery = Pick; +export type PinnedQuery = Pick, 'pinned'>; -type BoolClause = Pick; +type BoolClause = Pick, 'bool'>; export function matchesClauses(...clauses: Array): BoolClause { return { bool: Object.assign( diff --git a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/hooks/use_load_alert_summary.ts b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/hooks/use_load_alert_summary.ts index 5f80af1e1a7eb..bcbddc154d51e 100644 --- a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/hooks/use_load_alert_summary.ts +++ b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/hooks/use_load_alert_summary.ts @@ -17,7 +17,7 @@ interface UseLoadAlertSummaryProps { ruleTypeIds?: string[]; consumers?: string[]; timeRange: AlertSummaryTimeRange; - filter?: estypes.QueryDslQueryContainer; + filter?: NonNullable; } interface AlertSummary { @@ -108,7 +108,7 @@ async function fetchAlertSummary({ consumers?: string[]; signal: AbortSignal; timeRange: AlertSummaryTimeRange; - filter?: estypes.QueryDslQueryContainer; + filter?: Pick, 'bool' | 'ids'>; }): Promise { const res = ruleTypeIds.length ? await http.post>(`${BASE_RAC_ALERTS_API_PATH}/_alert_summary`, { diff --git a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/sections/alert_summary_widget/types.ts b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/sections/alert_summary_widget/types.ts index d16df1d7e401a..f2fa81a9dc649 100644 --- a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/sections/alert_summary_widget/types.ts +++ b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/sections/alert_summary_widget/types.ts @@ -50,7 +50,7 @@ export interface DependencyProps { export interface AlertSummaryWidgetProps { ruleTypeIds?: string[]; consumers?: string[]; - filter?: estypes.QueryDslQueryContainer; + filter?: NonNullable; fullSize?: boolean; onClick?: (status?: PublicAlertStatus) => void; timeRange: AlertSummaryTimeRange; diff --git a/x-pack/platform/test/api_integration/apis/management/index_management/lib/indices.helpers.ts b/x-pack/platform/test/api_integration/apis/management/index_management/lib/indices.helpers.ts index f6a7456adac0b..a239a89edba05 100644 --- a/x-pack/platform/test/api_integration/apis/management/index_management/lib/indices.helpers.ts +++ b/x-pack/platform/test/api_integration/apis/management/index_management/lib/indices.helpers.ts @@ -5,6 +5,7 @@ * 2.0. */ +import type { IndicesStatsRequest } from '@elastic/elasticsearch/lib/api/types'; import { getRandomString } from './random'; import type { FtrProviderContext } from '../../../../ftr_provider_context'; @@ -28,7 +29,7 @@ export function indicesHelpers(getService: FtrProviderContext['getService']) { const catIndex = (index?: string, h?: any) => es.cat.indices({ index, format: 'json', h }, { meta: true }); - const indexStats = (index: string, metric: string) => + const indexStats = (index: string, metric: IndicesStatsRequest['metric']) => es.indices.stats({ index, metric }, { meta: true }); return { createIndex, deleteAllIndices, catIndex, indexStats }; diff --git a/x-pack/platform/test/api_integration_deployment_agnostic/apis/streams/classic.ts b/x-pack/platform/test/api_integration_deployment_agnostic/apis/streams/classic.ts index 332464b3d5f01..222e6d7b4c0de 100644 --- a/x-pack/platform/test/api_integration_deployment_agnostic/apis/streams/classic.ts +++ b/x-pack/platform/test/api_integration_deployment_agnostic/apis/streams/classic.ts @@ -713,7 +713,7 @@ export default function ({ getService }: DeploymentAgnosticFtrProviderContext) { }); const pipeline = pipelineResponse[`${TEMPLATE_NAME}-pipeline`]; expect(pipeline._meta?.managed_by).to.eql('streams'); - expect(pipeline.processors?.[0].pipeline?.name).to.eql('mytest-first@stream.processing'); + expect(pipeline?.processors?.[0]?.pipeline?.name).to.eql('mytest-first@stream.processing'); }); it('Executes processing using the newly created ingest pipeline', async () => { @@ -768,7 +768,7 @@ export default function ({ getService }: DeploymentAgnosticFtrProviderContext) { id: `${TEMPLATE_NAME}-pipeline`, }); const pipeline = pipelineResponse[`${TEMPLATE_NAME}-pipeline`]; - expect(pipeline.processors?.map((processor) => processor.pipeline?.name)).to.eql([ + expect(pipeline.processors?.map((proc) => proc?.pipeline?.name)).to.eql([ 'mytest-first@stream.processing', 'mytest-second@stream.processing', ]); @@ -793,7 +793,8 @@ export default function ({ getService }: DeploymentAgnosticFtrProviderContext) { id: `${TEMPLATE_NAME}-pipeline`, }); const pipeline = pipelineResponse[`${TEMPLATE_NAME}-pipeline`]; - expect(pipeline.processors?.[0].pipeline?.name).to.eql('mytest-second@stream.processing'); + + expect(pipeline?.processors?.[0]?.pipeline?.name).to.eql('mytest-second@stream.processing'); }); it('clears the pipeline when processing is removed from the second stream', async () => { diff --git a/x-pack/platform/test/functional/services/ml/data_frame_analytics_creation.ts b/x-pack/platform/test/functional/services/ml/data_frame_analytics_creation.ts index 3596d315bb2e1..c1c2609140a1d 100644 --- a/x-pack/platform/test/functional/services/ml/data_frame_analytics_creation.ts +++ b/x-pack/platform/test/functional/services/ml/data_frame_analytics_creation.ts @@ -726,7 +726,7 @@ export function MachineLearningDataFrameAnalyticsCreationProvider( }, async assertInitialCloneJobConfigStep(job: DataFrameAnalyticsConfig) { - const jobType = Object.keys(job.analysis)[0]; + const jobType = Object.keys(job.analysis!)[0]; const jobTypeAttribute = `mlAnalyticsCreation-${jobType}-option`; await this.assertJobTypeSelection(jobTypeAttribute); if (isClassificationAnalysis(job.analysis) || isRegressionAnalysis(job.analysis)) { @@ -741,7 +741,7 @@ export function MachineLearningDataFrameAnalyticsCreationProvider( async assertInitialCloneJobAdditionalOptionsStep( analysis: DataFrameAnalyticsConfig['analysis'] ) { - const jobType = Object.keys(analysis)[0]; + const jobType = Object.keys(analysis!)[0]; if (isClassificationAnalysis(analysis) || isRegressionAnalysis(analysis)) { // @ts-ignore await this.assertPredictionFieldNameValue(analysis[jobType].prediction_field_name); diff --git a/x-pack/platform/test/functional/services/ml/stack_management_jobs.ts b/x-pack/platform/test/functional/services/ml/stack_management_jobs.ts index 4d022a20edd06..51173c8d7ea42 100644 --- a/x-pack/platform/test/functional/services/ml/stack_management_jobs.ts +++ b/x-pack/platform/test/functional/services/ml/stack_management_jobs.ts @@ -476,8 +476,8 @@ export function MachineLearningStackManagementJobsProvider( expectedJob.id, `Expected job id to be '${expectedJob.id}' (got '${sortedActualJobs[i].id}')` ); - const expectedType = Object.keys(expectedJob.analysis)[0]; - const actualType = Object.keys(sortedActualJobs[i].analysis)[0]; + const expectedType = Object.keys(expectedJob.analysis!)[0]; + const actualType = Object.keys(sortedActualJobs[i].analysis!)[0]; expect(actualType).to.eql( expectedType, `Expected job type to be '${expectedType}' (got '${actualType}')` diff --git a/x-pack/platform/test/serverless/api_integration/services/index_management/svl_indices.helpers.ts b/x-pack/platform/test/serverless/api_integration/services/index_management/svl_indices.helpers.ts index fefb574b24cc7..c717073cfbc53 100644 --- a/x-pack/platform/test/serverless/api_integration/services/index_management/svl_indices.helpers.ts +++ b/x-pack/platform/test/serverless/api_integration/services/index_management/svl_indices.helpers.ts @@ -5,6 +5,7 @@ * 2.0. */ +import type { IndicesStatsRequest } from '@elastic/elasticsearch/lib/api/types'; import { getRandomString } from './svl_random'; import type { FtrProviderContext } from '../../ftr_provider_context'; @@ -28,7 +29,7 @@ export function SvlIndicesHelpers({ getService }: FtrProviderContext) { const catIndex = (index?: string, h?: any) => es.cat.indices({ index, format: 'json', h }, { meta: true }); - const indexStats = (index: string, metric: string) => + const indexStats = (index: string, metric: IndicesStatsRequest['metric']) => es.indices.stats({ index, metric }, { meta: true }); return { createIndex, deleteAllIndices, catIndex, indexStats }; diff --git a/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/series_editor/columns/report_definition_field.tsx b/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/series_editor/columns/report_definition_field.tsx index f776f705901dc..1574b6dc315b3 100644 --- a/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/series_editor/columns/report_definition_field.tsx +++ b/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/series_editor/columns/report_definition_field.tsx @@ -67,7 +67,7 @@ export function ReportDefinitionField({ if (!values.includes(ALL_VALUES_SELECTED)) { const valueFilter = buildPhrasesFilter(fieldT, values, dataView)[0]; if (valueFilter.query) { - filtersN.push(valueFilter.query); + filtersN.push(valueFilter.query as ESFilter); } } } diff --git a/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/utils.ts b/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/utils.ts index 10e9c0a29e52e..956e5385c002b 100644 --- a/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/utils.ts +++ b/x-pack/solutions/observability/plugins/infra/server/routes/infra/lib/utils.ts @@ -13,7 +13,7 @@ interface BoolQuery { } const isValidFilter = (query: any): query is BoolQuery => { - const boolClause = (query as estypes.QueryDslQueryContainer).bool; + const boolClause = (query as estypes.QueryDslQueryContainer)?.bool; if (!boolClause || Object.keys(boolClause).length === 0) { return false; diff --git a/x-pack/solutions/observability/plugins/observability/public/pages/alert_details/hooks/related_alerts/get_build_related_alerts_query.ts b/x-pack/solutions/observability/plugins/observability/public/pages/alert_details/hooks/related_alerts/get_build_related_alerts_query.ts index e411e1d3a8f96..13044d5bdf2d7 100644 --- a/x-pack/solutions/observability/plugins/observability/public/pages/alert_details/hooks/related_alerts/get_build_related_alerts_query.ts +++ b/x-pack/solutions/observability/plugins/observability/public/pages/alert_details/hooks/related_alerts/get_build_related_alerts_query.ts @@ -29,7 +29,7 @@ interface Props { export function getBuildRelatedAlertsQuery({ alert, filterProximal, -}: Props): QueryDslQueryContainer { +}: Props): NonNullable { const groups = alert.fields[ALERT_GROUP]; const shouldGroups: QueryDslQueryContainer[] = []; groups?.forEach(({ field, value }) => { diff --git a/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/metric_query.test.ts b/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/metric_query.test.ts index 33dc8f8074140..9eaed2ab107c1 100644 --- a/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/metric_query.test.ts +++ b/x-pack/solutions/observability/plugins/observability/server/lib/rules/custom_threshold/lib/metric_query.test.ts @@ -70,12 +70,12 @@ describe("The Metric Threshold Alert's getElasticsearchMetricQuery", () => { ); test('includes a range filter', () => { expect( - searchBody.query.bool.filter.find((filter) => Object.hasOwn(filter, 'range')) + searchBody.query!.bool!.filter!.find((filter) => Object.hasOwn(filter!, 'range')) ).toBeTruthy(); }); test('includes a metric field filter', () => { - expect(searchBody.aggs.groupings.aggs.currentPeriod).toMatchObject( + expect(searchBody.aggs!.groupings!.aggs!.currentPeriod).toMatchObject( expect.objectContaining({ aggs: { // eslint-disable-next-line @typescript-eslint/naming-convention @@ -128,12 +128,12 @@ describe("The Metric Threshold Alert's getElasticsearchMetricQuery", () => { ); test('includes a range filter', () => { expect( - searchBody.query.bool.filter.find((filter) => Object.hasOwn(filter, 'range')) + searchBody.query!.bool!.filter!.find((filter) => Object.hasOwn(filter!, 'range')) ).toBeTruthy(); }); test('includes a metric field filter', () => { - expect(searchBody.query.bool.filter).toMatchObject( + expect(searchBody.query!.bool!.filter).toMatchObject( expect.arrayContaining([ { range: { mockedTimeFieldName: expect.any(Object) } }, { @@ -164,7 +164,7 @@ describe("The Metric Threshold Alert's getElasticsearchMetricQuery", () => { }, ]) ); - expect(searchBody.aggs.groupings.aggs).toMatchObject( + expect(searchBody.aggs!.groupings!.aggs).toMatchObject( expect.objectContaining({ currentPeriod: { filters: { @@ -241,12 +241,12 @@ describe("The Metric Threshold Alert's getElasticsearchMetricQuery", () => { ); test('includes a range filter', () => { expect( - searchBody.query.bool.filter.find((filter) => Object.hasOwn(filter, 'range')) + searchBody.query!.bool!.filter!.find((filter) => Object.hasOwn(filter!, 'range')) ).toBeTruthy(); }); test('includes a metric field filter', () => { - expect(searchBody.query.bool.filter).toMatchObject( + expect(searchBody.query!.bool!.filter!).toMatchObject( expect.arrayContaining([ { range: { mockedTimeFieldName: expect.any(Object) } }, { match_phrase: { 'service.name': 'synth-node-2' } }, diff --git a/x-pack/solutions/observability/plugins/observability/server/utils/get_parsed_filtered_query.ts b/x-pack/solutions/observability/plugins/observability/server/utils/get_parsed_filtered_query.ts index fbde8dd466a53..ebeb92465032a 100644 --- a/x-pack/solutions/observability/plugins/observability/server/utils/get_parsed_filtered_query.ts +++ b/x-pack/solutions/observability/plugins/observability/server/utils/get_parsed_filtered_query.ts @@ -5,14 +5,15 @@ * 2.0. */ +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import Boom from '@hapi/boom'; import type { BoolQuery, EsQueryConfig, Filter } from '@kbn/es-query'; import { buildEsQuery, fromKueryExpression, toElasticsearchQuery } from '@kbn/es-query'; import type { SearchConfigurationType } from '../../common/custom_threshold_rule/types'; -export const getParsedFilterQuery: (filter: string | undefined) => Array> = ( - filter -) => { +export const getParsedFilterQuery: ( + filter: string | undefined +) => NonNullable[] = (filter) => { if (!filter) return []; try { diff --git a/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_anomaly_detection_jobs/kql_to_influencer_query.ts b/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_anomaly_detection_jobs/kql_to_influencer_query.ts index 52d57d08dd391..5c8ac996da468 100644 --- a/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_anomaly_detection_jobs/kql_to_influencer_query.ts +++ b/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_anomaly_detection_jobs/kql_to_influencer_query.ts @@ -37,19 +37,19 @@ export function kqlToInfluencerQuery( * target the nested `influencers` path. */ function rewriteDslToInfluencerQuery(dsl: QueryDslQueryContainer): QueryDslQueryContainer { - if (dsl.bool) { + if (dsl?.bool) { const rewritten: QueryDslQueryContainer = { bool: {} }; - if (dsl.bool.filter) { + if (dsl?.bool.filter) { rewritten.bool!.filter = toArray(dsl.bool.filter).map(rewriteDslToInfluencerQuery); } - if (dsl.bool.must) { + if (dsl?.bool.must) { rewritten.bool!.must = toArray(dsl.bool.must).map(rewriteDslToInfluencerQuery); } - if (dsl.bool.should) { + if (dsl?.bool.should) { rewritten.bool!.should = toArray(dsl.bool.should).map(rewriteDslToInfluencerQuery); rewritten.bool!.minimum_should_match = dsl.bool.minimum_should_match; } - if (dsl.bool.must_not) { + if (dsl?.bool.must_not) { rewritten.bool!.must_not = toArray(dsl.bool.must_not).map(rewriteDslToInfluencerQuery); } return rewritten; @@ -87,25 +87,25 @@ function rewriteDslToInfluencerQuery(dsl: QueryDslQueryContainer): QueryDslQuery function extractFieldAndValue( dsl: QueryDslQueryContainer ): { field: string; value?: string; isWildcard?: boolean } | undefined { - if (dsl.match) { + if (dsl?.match) { const [field] = Object.keys(dsl.match); const clause = (dsl.match as Record)[field]; return { field, value: String(typeof clause === 'object' ? (clause as any).query : clause) }; } - if (dsl.match_phrase) { + if (dsl?.match_phrase) { const [field] = Object.keys(dsl.match_phrase); const clause = (dsl.match_phrase as Record)[field]; return { field, value: String(typeof clause === 'object' ? (clause as any).query : clause) }; } - if (dsl.term) { + if (dsl?.term) { const [field] = Object.keys(dsl.term); const clause = (dsl.term as Record)[field]; return { field, value: String(typeof clause === 'object' ? (clause as any).value : clause) }; } - if (dsl.exists) { + if (dsl?.exists) { return { field: dsl.exists.field as string }; } - if (dsl.wildcard) { + if (dsl?.wildcard) { const [field] = Object.keys(dsl.wildcard); const clause = (dsl.wildcard as Record)[field]; return { @@ -114,7 +114,7 @@ function extractFieldAndValue( isWildcard: true, }; } - if (dsl.query_string) { + if (dsl?.query_string) { const qs = dsl.query_string; const field = Array.isArray(qs.fields) ? qs.fields[0] : undefined; if (field && qs.query) { diff --git a/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_log_change_points/handler.ts b/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_log_change_points/handler.ts index 1f5f23d3e7b54..5633a7719f1b2 100644 --- a/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_log_change_points/handler.ts +++ b/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_log_change_points/handler.ts @@ -5,7 +5,6 @@ * 2.0. */ -import type { AggregationsAggregationContainer } from '@elastic/elasticsearch/lib/api/types'; import type { IScopedClusterClient } from '@kbn/core/server'; import { orderBy } from 'lodash'; import { getTotalHits } from '../../utils/get_total_hits'; @@ -75,8 +74,7 @@ async function getLogChangePoint({ change_point: { buckets_path: 'time_series>_count', }, - // elasticsearch@9.0.0 change_point aggregation is missing in the types: https://github.com/elastic/elasticsearch-specification/issues/3671 - } as AggregationsAggregationContainer, + }, }, }, }, diff --git a/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_metric_change_points/handler.ts b/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_metric_change_points/handler.ts index 98a985acf986c..b776593b530c3 100644 --- a/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_metric_change_points/handler.ts +++ b/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_metric_change_points/handler.ts @@ -40,7 +40,7 @@ function getMetricAggregation(aggregation: AggregationConfig | undefined): { [aggregation.type]: { field: aggregation.field, }, - } as Record, { field: string }>, + }, buckets_path: 'metric', }; } @@ -130,8 +130,7 @@ async function getMetricChangePoints({ change_point: { buckets_path: 'time_series>value', }, - // elasticsearch@9.0.0 change_point aggregation is missing in the types: https://github.com/elastic/elasticsearch-specification/issues/3671 - } as AggregationsAggregationContainer, + }, }, }, }; @@ -153,7 +152,7 @@ async function getMetricChangePoints({ ], }, }, - aggs: aggregations as Record, + aggs: aggregations, }); const buckets = (response.aggregations as { groups?: { buckets?: Bucket[] } })?.groups?.buckets; diff --git a/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_trace_change_points/handler.ts b/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_trace_change_points/handler.ts index 008013e0aa215..355340b49eb2d 100644 --- a/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_trace_change_points/handler.ts +++ b/x-pack/solutions/observability/plugins/observability_agent_builder/server/tools/get_trace_change_points/handler.ts @@ -6,7 +6,6 @@ */ import type { CoreSetup, KibanaRequest, Logger } from '@kbn/core/server'; import type { ChangePointType } from '@kbn/es-types/src'; -import type { AggregationsAggregationContainer } from '@elastic/elasticsearch/lib/api/types'; import { intervalToSeconds } from '@kbn/apm-data-access-plugin/common/utils/get_preferred_bucket_size_and_data_source'; import type { ObservabilityAgentBuilderPluginSetupDependencies, @@ -56,8 +55,7 @@ function getChangePointsAggs(bucketsPath: string) { change_point: { buckets_path: bucketsPath, }, - // elasticsearch@9.0.0 change_point aggregation is missing in the types: https://github.com/elastic/elasticsearch-specification/issues/3671 - } as AggregationsAggregationContainer; + }; return changePointAggs; } diff --git a/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_log_changes.ts b/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_log_changes.ts index 0ab1ea82775e0..26caff9120f3d 100644 --- a/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_log_changes.ts +++ b/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_log_changes.ts @@ -5,10 +5,7 @@ * 2.0. */ -import type { - AggregationsAggregationContainer, - AggregationsAutoDateHistogramAggregation, -} from '@elastic/elasticsearch/lib/api/types'; +import type { AggregationsAutoDateHistogramAggregation } from '@elastic/elasticsearch/lib/api/types'; import type { QueryDslQueryContainer } from '@kbn/data-views-plugin/common/types'; import type { ChangePointType } from '@kbn/es-types/src'; import type { AggregateOf } from '@kbn/es-types/src/search'; @@ -72,8 +69,7 @@ export async function getLogChanges({ change_point: { buckets_path: 'over_time>_count', }, - // elasticsearch@9.0.0 change_point aggregation is missing in the types: https://github.com/elastic/elasticsearch-specification/issues/3671 - } as AggregationsAggregationContainer, + }, }, }, }, diff --git a/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_metric_changes.ts b/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_metric_changes.ts index 8362d7fb1e9fc..19038d2dca86d 100644 --- a/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_metric_changes.ts +++ b/x-pack/solutions/observability/plugins/observability_ai_assistant_app/server/functions/changes/get_metric_changes.ts @@ -107,7 +107,7 @@ export async function getMetricChanges({ over_time: { auto_date_histogram: dateHistogram, aggs: { - metric: metricAgg, + metric: metricAgg as AggregationsAggregationContainer, value: { bucket_script: { buckets_path: { @@ -122,8 +122,7 @@ export async function getMetricChanges({ change_point: { buckets_path: 'over_time>value', }, - // elasticsearch@9.0.0 change_point aggregation is missing in the types: https://github.com/elastic/elasticsearch-specification/issues/3671 - } as AggregationsAggregationContainer, + }, }; const response = await client.search('get_metric_changes', { @@ -157,9 +156,9 @@ export async function getMetricChanges({ return { key, - over_time: group.over_time.buckets.map((bucket) => { + over_time: group.over_time?.buckets?.map((bucket) => { return { - x: new Date(bucket.key_as_string).getTime(), + x: new Date(bucket.key_as_string!).getTime(), y: bucket.value?.value as number | null, }; }), diff --git a/x-pack/solutions/observability/plugins/slo/public/embeddable/slo/alerts/components/slo_alerts_table.tsx b/x-pack/solutions/observability/plugins/slo/public/embeddable/slo/alerts/components/slo_alerts_table.tsx index 361f8da1acae1..b954619b6563d 100644 --- a/x-pack/solutions/observability/plugins/slo/public/embeddable/slo/alerts/components/slo_alerts_table.tsx +++ b/x-pack/solutions/observability/plugins/slo/public/embeddable/slo/alerts/components/slo_alerts_table.tsx @@ -15,13 +15,11 @@ import { } from '@kbn/rule-data-utils'; import type { TimeRange } from '@kbn/es-query'; import { ALL_VALUE } from '@kbn/slo-schema'; -import type { - AlertsTableProps, - AlertsTableImperativeApi, -} from '@kbn/response-ops-alerts-table/types'; +import type { AlertsTableImperativeApi } from '@kbn/response-ops-alerts-table/types'; import { ObservabilityAlertsTable } from '@kbn/observability-plugin/public'; import type { EuiDataGridColumn } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { SloItem } from '../types'; import type { SloEmbeddableDeps } from '../types'; @@ -116,7 +114,7 @@ export const useSloAlertsQuery = ( showAllGroupByInstances?: boolean ) => { return useMemo(() => { - const query: AlertsTableProps['query'] = { + const query: NonNullable = { bool: { filter: [ { diff --git a/x-pack/solutions/observability/plugins/slo/server/assets/ingest_templates/summary_pipeline_template.test.ts b/x-pack/solutions/observability/plugins/slo/server/assets/ingest_templates/summary_pipeline_template.test.ts index 1fecffb7a1149..2ef8c1b771bc1 100644 --- a/x-pack/solutions/observability/plugins/slo/server/assets/ingest_templates/summary_pipeline_template.test.ts +++ b/x-pack/solutions/observability/plugins/slo/server/assets/ingest_templates/summary_pipeline_template.test.ts @@ -60,10 +60,10 @@ describe('getSummaryPipelineTemplate', () => { const template = getSummaryPipelineTemplate(slo, 'default', basePath); const hasTimesliceTarget = template.processors?.some( - (p) => 'set' in p && p.set?.field === 'slo.objective.timesliceTarget' + (p) => p?.set?.field === 'slo.objective.timesliceTarget' ); const hasTimesliceWindow = template.processors?.some( - (p) => 'set' in p && p.set?.field === 'slo.objective.timesliceWindow' + (p) => p?.set?.field === 'slo.objective.timesliceWindow' ); expect(hasTimesliceTarget).toBe(true); diff --git a/x-pack/solutions/observability/plugins/slo/server/assets/transform_templates/slo_transform_template.ts b/x-pack/solutions/observability/plugins/slo/server/assets/transform_templates/slo_transform_template.ts index 98e1e0ad2c9e4..2c7c64dfe1064 100644 --- a/x-pack/solutions/observability/plugins/slo/server/assets/transform_templates/slo_transform_template.ts +++ b/x-pack/solutions/observability/plugins/slo/server/assets/transform_templates/slo_transform_template.ts @@ -71,7 +71,7 @@ const buildGroupingFilters = (slo: SLODefinition): QueryDslQueryContainer[] => { const buildSourceWithFilters = (source: TransformSource, slo: SLODefinition): TransformSource => { const groupingFilters = buildGroupingFilters(slo); - const sourceFilters = [source.query?.bool?.filter].flat() || []; + const sourceFilters = [source.query?.bool?.filter].flat().filter(Boolean); return { ...source, query: { @@ -80,6 +80,6 @@ const buildSourceWithFilters = (source: TransformSource, slo: SLODefinition): Tr ...source.query?.bool, filter: [...sourceFilters, ...groupingFilters] as QueryDslQueryContainer[], }, - }, + } as QueryDslQueryContainer, }; }; diff --git a/x-pack/solutions/observability/plugins/slo/server/services/tasks/stale_instances_cleanup_task/cleanup_stale_instances.ts b/x-pack/solutions/observability/plugins/slo/server/services/tasks/stale_instances_cleanup_task/cleanup_stale_instances.ts index a84535e5c1bf4..61ab59e458326 100644 --- a/x-pack/solutions/observability/plugins/slo/server/services/tasks/stale_instances_cleanup_task/cleanup_stale_instances.ts +++ b/x-pack/solutions/observability/plugins/slo/server/services/tasks/stale_instances_cleanup_task/cleanup_stale_instances.ts @@ -6,6 +6,7 @@ */ import { errors } from '@elastic/elasticsearch'; +import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types'; import type { ElasticsearchClient, Logger, SavedObjectsClient } from '@kbn/core/server'; import { DEFAULT_STALE_SLO_THRESHOLD_HOURS, @@ -239,7 +240,11 @@ async function hasDocumentsToDelete( ): Promise { const { esClient, abortController } = dependencies; const response = await esClient.count( - { index: SUMMARY_DESTINATION_INDEX_PATTERN, terminate_after: 1, query }, + { + index: SUMMARY_DESTINATION_INDEX_PATTERN, + terminate_after: 1, + query: query as QueryDslQueryContainer, + }, { signal: abortController.signal } ); @@ -259,7 +264,7 @@ async function executeDeleteByQuery( slices: 'auto', max_docs: MAX_DOCS_PER_DELETE, requests_per_second: REQUESTS_PER_SECOND, - query, + query: query as QueryDslQueryContainer, }, { signal: abortController.signal } ); diff --git a/x-pack/solutions/observability/plugins/ux/public/components/app/rum_dashboard/panels/web_application_select.tsx b/x-pack/solutions/observability/plugins/ux/public/components/app/rum_dashboard/panels/web_application_select.tsx index c598138b69cbf..f63131af7866f 100644 --- a/x-pack/solutions/observability/plugins/ux/public/components/app/rum_dashboard/panels/web_application_select.tsx +++ b/x-pack/solutions/observability/plugins/ux/public/components/app/rum_dashboard/panels/web_application_select.tsx @@ -30,8 +30,11 @@ export function WebApplicationSelect() { { name: 'UxApplicationServices' } ); - const rumServiceNames = - data?.aggregations?.services?.buckets.map(({ key }) => key as string) ?? []; + interface ServicesAggregation { + services?: { buckets?: Array<{ key: string }> }; + } + const servicesAgg = (data?.aggregations as ServicesAggregation | undefined)?.services; + const rumServiceNames = servicesAgg?.buckets?.map((bucket: { key: string }) => bucket.key) ?? []; return ; } diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/core_web_vitals_query.ts b/x-pack/solutions/observability/plugins/ux/public/services/data/core_web_vitals_query.ts index 0b5ee5a0f42a9..2392e6ca1173f 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/core_web_vitals_query.ts +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/core_web_vitals_query.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { ESSearchResponse } from '@kbn/es-types'; +import type { ESSearchResponse, ESSearchRequest } from '@kbn/es-types'; import type { UXMetrics } from '@kbn/observability-shared-plugin/public'; import { TBT_FIELD, @@ -19,7 +19,9 @@ import { getRumPageLoadTransactionsProjection } from './projections'; export const DEFAULT_RANKS = [100, 0, 0]; -export const getRanksPercentages = (ranks?: Record) => { +export const getRanksPercentages = ( + ranks?: Record | Array<{ value?: number }> +) => { if (!Array.isArray(ranks)) return null; const ranksVal = ranks?.map(({ value }) => value?.toFixed(0) ?? 0) ?? []; return [ @@ -29,6 +31,24 @@ export const getRanksPercentages = (ranks?: Record) => { ]; }; +interface PercentileAggregation { + values?: Record; +} + +interface PercentileRanksAggregation { + values?: Array<{ value?: number }>; +} + +interface CoreWebVitalsAggregations { + lcp?: PercentileAggregation; + cls?: PercentileAggregation; + tbt?: PercentileAggregation; + fcp?: PercentileAggregation; + lcpRanks?: PercentileRanksAggregation; + clsRanks?: PercentileRanksAggregation; + coreVitalPages?: { doc_count?: number }; +} + export function transformCoreWebVitalsResponse( response?: ESSearchResponse< T, @@ -38,7 +58,8 @@ export function transformCoreWebVitalsResponse( percentile = PERCENTILE_DEFAULT ): UXMetrics | undefined { if (!response) return response; - const { lcp, cls, tbt, fcp, lcpRanks, clsRanks, coreVitalPages } = response.aggregations ?? {}; + const aggs = (response.aggregations ?? {}) as CoreWebVitalsAggregations; + const { lcp, cls, tbt, fcp, lcpRanks, clsRanks, coreVitalPages } = aggs; const pkey = percentile.toFixed(1); @@ -46,15 +67,15 @@ export function transformCoreWebVitalsResponse( coreVitalPages: coreVitalPages?.doc_count ?? 0, /* Because cls is required in the type UXMetrics, and defined as number | null, * we need to default to null in the case where cls is undefined in order to satisfy the UXMetrics type */ - cls: cls?.values[pkey] ?? null, - lcp: lcp?.values[pkey], - tbt: tbt?.values[pkey] ?? 0, - fcp: fcp?.values[pkey], + cls: cls?.values?.[pkey] ?? null, + lcp: lcp?.values?.[pkey], + tbt: tbt?.values?.[pkey] ?? 0, + fcp: fcp?.values?.[pkey], - lcpRanks: lcp?.values[pkey] + lcpRanks: lcp?.values?.[pkey] ? getRanksPercentages(lcpRanks?.values) ?? DEFAULT_RANKS : DEFAULT_RANKS, - clsRanks: cls?.values[pkey] + clsRanks: cls?.values?.[pkey] ? getRanksPercentages(clsRanks?.values) ?? DEFAULT_RANKS : DEFAULT_RANKS, }; @@ -68,7 +89,7 @@ export function coreWebVitalsQuery( urlQuery?: string, uiFilters?: UxUIFilters, percentile = PERCENTILE_DEFAULT -) { +): Omit { const setup: SetupUX = { uiFilters: uiFilters ?? {} }; const projection = getRumPageLoadTransactionsProjection({ @@ -77,7 +98,7 @@ export function coreWebVitalsQuery( start, end, }); - const params = mergeProjection(projection, { + const params: ESSearchRequest = mergeProjection(projection, { size: 0, query: { bool: { diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/inp_query.ts b/x-pack/solutions/observability/plugins/ux/public/services/data/inp_query.ts index 1a6b69572cd53..5979da6de5ccf 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/inp_query.ts +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/inp_query.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { ESSearchResponse } from '@kbn/es-types'; +import type { ESSearchResponse, ESSearchRequest } from '@kbn/es-types'; import type { UXMetrics } from '@kbn/observability-shared-plugin/public/types'; import { DEFAULT_RANKS, getRanksPercentages } from './core_web_vitals_query'; import { INP_FIELD } from '../../../common/elasticsearch_fieldnames'; @@ -13,19 +13,25 @@ import type { SetupUX, UxUIFilters } from '../../../typings/ui_filters'; import { mergeProjection } from '../../../common/utils/merge_projection'; import { getRumPageExitTransactionsProjection } from './projections'; +interface InPAggregations { + inp?: { values?: Record }; + inpRanks?: { values?: Array<{ value?: number }> }; +} + export function transformINPResponse( response?: ESSearchResponse, { restTotalHitsAsInt: false }>, percentile = PERCENTILE_DEFAULT ): UXMetrics | undefined { if (!response) return response; - const { inp, inpRanks } = response.aggregations ?? {}; + const aggs = (response.aggregations ?? {}) as InPAggregations; + const { inp, inpRanks } = aggs; const pkey = percentile.toFixed(1); return { - hasINP: response.hits.total.value > 0, - inp: inp?.values[pkey], - inpRanks: inp?.values[pkey] + hasINP: (response.hits?.total?.value ?? 0) > 0, + inp: inp?.values?.[pkey], + inpRanks: inp?.values?.[pkey] ? getRanksPercentages(inpRanks?.values) ?? DEFAULT_RANKS : DEFAULT_RANKS, }; @@ -39,7 +45,7 @@ export function inpQuery( urlQuery?: string, uiFilters?: UxUIFilters, percentile = PERCENTILE_DEFAULT -) { +): Omit { const setup: SetupUX = { uiFilters: uiFilters ?? {} }; const projection = getRumPageExitTransactionsProjection({ diff --git a/x-pack/solutions/observability/plugins/ux/public/services/data/service_name_query.ts b/x-pack/solutions/observability/plugins/ux/public/services/data/service_name_query.ts index 85e2cb42e6cb2..f6efb4023fb3e 100644 --- a/x-pack/solutions/observability/plugins/ux/public/services/data/service_name_query.ts +++ b/x-pack/solutions/observability/plugins/ux/public/services/data/service_name_query.ts @@ -5,12 +5,17 @@ * 2.0. */ +import type { ESSearchRequest } from '@kbn/es-types'; import { SERVICE_NAME } from '../../../common/elasticsearch_fieldnames'; import { mergeProjection } from '../../../common/utils/merge_projection'; import type { SetupUX, UxUIFilters } from '../../../typings/ui_filters'; import { getRumPageLoadTransactionsProjection } from './projections'; -export function serviceNameQuery(start: number, end: number, uiFilters?: UxUIFilters) { +export function serviceNameQuery( + start: number, + end: number, + uiFilters?: UxUIFilters +): Omit { const setup: SetupUX = { uiFilters: uiFilters ? uiFilters : {} }; const projection = getRumPageLoadTransactionsProjection({ setup, diff --git a/x-pack/solutions/search/packages/kbn-search-queries/src/generate_query.ts b/x-pack/solutions/search/packages/kbn-search-queries/src/generate_query.ts index 69b7b502bd961..cb2eae2bf4ab0 100644 --- a/x-pack/solutions/search/packages/kbn-search-queries/src/generate_query.ts +++ b/x-pack/solutions/search/packages/kbn-search-queries/src/generate_query.ts @@ -92,7 +92,7 @@ export function generateSearchQuery( const hasExistingSparseMatch = acc.queryMatches.find( (x) => x?.text_expansion?.[elserField.field] && - x?.sparse_vector?.inference_id === elserField?.model_id + x?.text_expansion?.[elserField.field]?.model_id === elserField?.model_id ); if (hasExistingSparseMatch) { @@ -237,7 +237,9 @@ export function generateSearchQuery( }); const highlightSemanticFields = allMatches - .map((match) => ('semantic' in match && match.semantic ? match.semantic.field : null)) + .map((match) => + match && 'semantic' in match && match.semantic ? match.semantic.field : null + ) .filter((field): field is string => !!field) .filter((field) => isFieldInSourceFields(field, sourceFields)); diff --git a/x-pack/solutions/search/plugins/enterprise_search/common/ml_inference_pipeline/index.ts b/x-pack/solutions/search/plugins/enterprise_search/common/ml_inference_pipeline/index.ts index 6ead350214608..b04d8ca5e5806 100644 --- a/x-pack/solutions/search/plugins/enterprise_search/common/ml_inference_pipeline/index.ts +++ b/x-pack/solutions/search/plugins/enterprise_search/common/ml_inference_pipeline/index.ts @@ -166,8 +166,8 @@ export const parseMlInferenceParametersFromPipeline = ( pipeline: IngestPipeline ): CreateMLInferencePipeline | null => { const inferenceProcessors = pipeline?.processors - ?.filter((p) => p.inference) - .map((p) => p.inference) as IngestInferenceProcessor[]; + ?.filter((p) => p?.inference) + .map((p) => p!.inference) as IngestInferenceProcessor[]; if (!inferenceProcessors || inferenceProcessors.length === 0) { return null; } diff --git a/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/delete_ml_inference_pipeline.ts b/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/delete_ml_inference_pipeline.ts index ba3cd3410604b..bfeee3d3c41b6 100644 --- a/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/delete_ml_inference_pipeline.ts +++ b/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/delete_ml_inference_pipeline.ts @@ -73,7 +73,7 @@ const findUsageInOtherManagedPipelines = async ( return Object.entries(pipelines).find( ([name, pipeline]) => name !== getInferencePipelineNameFromIndexName(indexName) && - pipeline.processors?.find((processor) => processor.pipeline?.name === pipelineName) + pipeline.processors?.find((processor) => processor?.pipeline?.name === pipelineName) )?.[0]; // Managed pipeline name } catch (error) { // only suppress Not Found error diff --git a/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/detach_ml_inference_pipeline.ts b/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/detach_ml_inference_pipeline.ts index d31748d94e1f2..b001c36c6c461 100644 --- a/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/detach_ml_inference_pipeline.ts +++ b/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/detach_ml_inference_pipeline.ts @@ -34,7 +34,7 @@ export const detachMlInferencePipeline = async ( // remove sub-pipeline from parent pipeline if (parentPipeline.processors !== undefined) { const updatedProcessors = parentPipeline.processors.filter( - (p) => !(p.pipeline !== undefined && p.pipeline.name === pipelineName) + (p) => !(p?.pipeline !== undefined && p.pipeline.name === pipelineName) ); // only update if we changed something if (updatedProcessors.length !== parentPipeline.processors.length) { diff --git a/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/get_ml_inference_pipeline_processors.ts b/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/get_ml_inference_pipeline_processors.ts index 21d47e903d414..7f49cf8f33595 100644 --- a/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/get_ml_inference_pipeline_processors.ts +++ b/x-pack/solutions/search/plugins/enterprise_search/server/lib/indices/pipelines/ml_inference/pipeline_processors/get_ml_inference_pipeline_processors.ts @@ -49,7 +49,7 @@ export const getMlInferencePipelineProcessorNamesFromPipelines = ( } = pipelines; return mlInferencePipelineProcessors - .map((obj) => obj.pipeline?.name) + .map((obj) => obj?.pipeline?.name) .filter((name): name is string => name !== undefined); }; @@ -67,7 +67,7 @@ export const getProcessorPipelineMap = ( Object.entries(pipelines).forEach(([name, pipeline]) => pipeline?.processors?.forEach((processor) => { - if (processor.pipeline?.name !== undefined) { + if (processor?.pipeline?.name !== undefined) { addPipelineToProcessorMap(processor.pipeline.name, name); } }) @@ -92,15 +92,15 @@ export const fetchPipelineProcessorInferenceData = async ( mlInferencePipelineProcessorConfigs[pipelineProcessorName].processors || []; // Get the inference processors; there is one per configured field, but they share the same model ID - const inferenceProcessors = subProcessors.filter((processor) => - Object.hasOwn(processor, 'inference') + const inferenceProcessors = subProcessors.filter( + (processor) => processor && Object.hasOwn(processor, 'inference') ); const trainedModelName = inferenceProcessors[0]?.inference?.model_id; if (trainedModelName) { // Extract source fields from field mappings const sourceFields = inferenceProcessors.flatMap((processor) => - Object.keys(processor.inference?.field_map ?? {}) + Object.keys(processor?.inference?.field_map ?? {}) ); pipelineProcessorData.push({ diff --git a/x-pack/solutions/search/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.test.ts b/x-pack/solutions/search/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.test.ts index 1b9c29d1280db..8f6336a5f4166 100644 --- a/x-pack/solutions/search/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.test.ts +++ b/x-pack/solutions/search/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.test.ts @@ -5,7 +5,6 @@ * 2.0. */ -import type { IngestProcessorContainer } from '@elastic/elasticsearch/lib/api/types'; import type { ElasticsearchClient } from '@kbn/core/server'; import type { MlTrainedModels } from '@kbn/ml-plugin/server'; @@ -103,24 +102,12 @@ describe('getMlInferencePipelines', () => { mockTrainedModelsProvider as unknown as MlTrainedModels ); - expect( - (actualPipelines.pipeline1.processors as IngestProcessorContainer[])[1].inference?.model_id - ).toEqual('model1'); - expect( - (actualPipelines.pipeline2.processors as IngestProcessorContainer[])[1].inference?.model_id - ).toEqual('model2'); - expect( - (actualPipelines.pipeline3.processors as IngestProcessorContainer[])[1].inference?.model_id - ).toEqual(''); // Redacted model ID - expect( - (actualPipelines.pipeline4.processors as IngestProcessorContainer[])[1].inference?.model_id - ).toEqual(''); - expect( - (actualPipelines.pipeline4.processors as IngestProcessorContainer[])[2].inference?.model_id - ).toEqual('model2'); - expect( - (actualPipelines.pipeline4.processors as IngestProcessorContainer[])[3].inference?.model_id - ).toEqual(''); + expect(actualPipelines.pipeline1.processors?.[1]?.inference?.model_id).toEqual('model1'); + expect(actualPipelines.pipeline2.processors?.[1]?.inference?.model_id).toEqual('model2'); + expect(actualPipelines.pipeline3.processors?.[1]?.inference?.model_id).toEqual(''); // Redacted model ID + expect(actualPipelines.pipeline4.processors?.[1]?.inference?.model_id).toEqual(''); + expect(actualPipelines.pipeline4.processors?.[2]?.inference?.model_id).toEqual('model2'); + expect(actualPipelines.pipeline4.processors?.[3]?.inference?.model_id).toEqual(''); expect(mockClient.ingest.getPipeline).toHaveBeenCalledWith({ id: 'ml-inference-*' }); expect(mockTrainedModelsProvider.getTrainedModels).toHaveBeenCalledWith({}); }); diff --git a/x-pack/solutions/search/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.ts b/x-pack/solutions/search/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.ts index 77d957592ed95..be9bea14769f5 100644 --- a/x-pack/solutions/search/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.ts +++ b/x-pack/solutions/search/plugins/enterprise_search/server/lib/pipelines/ml_inference/get_ml_inference_pipelines.ts @@ -72,7 +72,7 @@ function redactModelIdIfInaccessible( processor: IngestProcessorContainer, accessibleModelIds: string[] ): IngestProcessorContainer { - if (!processor.inference || accessibleModelIds.includes(processor.inference.model_id)) { + if (!processor?.inference || accessibleModelIds.includes(processor.inference.model_id)) { return processor; } diff --git a/x-pack/solutions/search/plugins/enterprise_search/server/utils/create_ml_inference_pipeline.ts b/x-pack/solutions/search/plugins/enterprise_search/server/utils/create_ml_inference_pipeline.ts index cc8bfc3a554cf..a18082ad4252e 100644 --- a/x-pack/solutions/search/plugins/enterprise_search/server/utils/create_ml_inference_pipeline.ts +++ b/x-pack/solutions/search/plugins/enterprise_search/server/utils/create_ml_inference_pipeline.ts @@ -49,7 +49,7 @@ export const addSubPipelineToIndexSpecificMlPipeline = async ( // Check if the sub-pipeline reference is already in the list of processors, // if so, don't modify it const existingSubPipeline = parentPipeline.processors.find( - (p) => p.pipeline?.name === pipelineName + (p) => p?.pipeline?.name === pipelineName ); if (existingSubPipeline) { return Promise.resolve({ diff --git a/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/components/graph_investigation/graph_investigation.tsx b/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/components/graph_investigation/graph_investigation.tsx index 434f3c566e7b9..51e449504a6ee 100644 --- a/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/components/graph_investigation/graph_investigation.tsx +++ b/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/components/graph_investigation/graph_investigation.tsx @@ -333,7 +333,7 @@ export const GraphInvestigation = memo( [kquery], [...searchFilters], getEsQueryConfig(uiSettings as Parameters[0]) - ); + ) as EsQuery; } catch (err) { notifications?.toasts.addError(err, { title: i18n.translate( diff --git a/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/configurations/configurations.handlers.mock.ts b/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/configurations/configurations.handlers.mock.ts index 1ae31b4facd05..e580e2dd1e3a8 100644 --- a/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/configurations/configurations.handlers.mock.ts +++ b/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/configurations/configurations.handlers.mock.ts @@ -226,7 +226,8 @@ export const searchFindingsHandler = (findings: CspFinding[]) => if (hasRuleSectionQuerySearchTerm) { const filteredFindings = findings.filter((finding) => { - const termValue = (filter[0].bool?.should as estypes.QueryDslQueryContainer[])?.[0]?.term?.[ + const termValue = (filter[0]?.bool?.should as estypes.QueryDslQueryContainer[])?.[0] + ?.term?.[ 'rule.section' // @ts-expect-error FieldValue is now very broad (can be anything) ]?.value; diff --git a/x-pack/solutions/security/plugins/security_solution/common/endpoint/utils/endpoint_metadata_filter.test.ts b/x-pack/solutions/security/plugins/security_solution/common/endpoint/utils/endpoint_metadata_filter.test.ts index c7191985d3087..db28aad68bcf7 100644 --- a/x-pack/solutions/security/plugins/security_solution/common/endpoint/utils/endpoint_metadata_filter.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/common/endpoint/utils/endpoint_metadata_filter.test.ts @@ -208,8 +208,8 @@ describe('buildBaseEndpointMetadataFilter', () => { it('should always include ignored agent IDs filter', () => { const result = buildBaseEndpointMetadataFilter(['policy-1']); - expect(result.bool).toBeDefined(); - expect(result.bool!.must_not).toEqual({ + expect(result!.bool).toBeDefined(); + expect(result!.bool!.must_not).toEqual({ terms: { 'agent.id': [ '00000000-0000-0000-0000-000000000000', @@ -222,8 +222,8 @@ describe('buildBaseEndpointMetadataFilter', () => { it('should always include base existence and active filters', () => { const result = buildBaseEndpointMetadataFilter(); - expect(result.bool).toBeDefined(); - const baseFilters = result.bool!.filter; + expect(result!.bool).toBeDefined(); + const baseFilters = result!.bool!.filter; expect(baseFilters).toContainEqual({ exists: { field: 'united.endpoint.agent.id' } }); expect(baseFilters).toContainEqual({ exists: { field: 'united.agent.agent.id' } }); expect(baseFilters).toContainEqual({ diff --git a/x-pack/solutions/security/plugins/security_solution/public/attack_discovery/pages/results/attack_discovery_panel/tabs/alerts_tab/ease/table.tsx b/x-pack/solutions/security/plugins/security_solution/public/attack_discovery/pages/results/attack_discovery_panel/tabs/alerts_tab/ease/table.tsx index dfcdb7e4c85f2..53934679d1588 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/attack_discovery/pages/results/attack_discovery_panel/tabs/alerts_tab/ease/table.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/attack_discovery/pages/results/attack_discovery_panel/tabs/alerts_tab/ease/table.tsx @@ -46,7 +46,7 @@ export interface TableProps { /** * Query that contains the id of the alerts to display in the table */ - query: Pick; + query: Partial, 'bool' | 'ids'>>; } /** diff --git a/x-pack/solutions/security/plugins/security_solution/public/attack_discovery/pages/results/attack_discovery_panel/tabs/alerts_tab/ease/wrapper.tsx b/x-pack/solutions/security/plugins/security_solution/public/attack_discovery/pages/results/attack_discovery_panel/tabs/alerts_tab/ease/wrapper.tsx index 06c6de9a4bd62..66d4f0b022846 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/attack_discovery/pages/results/attack_discovery_panel/tabs/alerts_tab/ease/wrapper.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/attack_discovery/pages/results/attack_discovery_panel/tabs/alerts_tab/ease/wrapper.tsx @@ -32,7 +32,7 @@ interface EaseAlertsTabProps { /** * Query that contains the id of the alerts to display in the table */ - query: Pick; + query: Partial, 'bool' | 'ids'>>; } /** diff --git a/x-pack/solutions/security/plugins/security_solution/public/attack_discovery/pages/settings_flyout/alerts_preview/index.tsx b/x-pack/solutions/security/plugins/security_solution/public/attack_discovery/pages/settings_flyout/alerts_preview/index.tsx index 6cce1fee1cc40..3db6862c8913c 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/attack_discovery/pages/settings_flyout/alerts_preview/index.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/attack_discovery/pages/settings_flyout/alerts_preview/index.tsx @@ -14,7 +14,7 @@ import { TableId } from '@kbn/securitysolution-data-table'; import { AlertsTable } from '../../../../detections/components/alerts_table'; interface Props { - query: Pick; + query: Partial, 'bool' | 'ids'>>; size: number; } diff --git a/x-pack/solutions/security/plugins/security_solution/public/cases/components/ease/table.tsx b/x-pack/solutions/security/plugins/security_solution/public/cases/components/ease/table.tsx index 1df42230a2517..7d8a2e0ff0999 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/cases/components/ease/table.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/cases/components/ease/table.tsx @@ -53,7 +53,7 @@ export interface TableProps { /** * Query that contains the id of the alerts to display in the table */ - query: Pick; + query: Partial, 'bool' | 'ids'>>; } /** diff --git a/x-pack/solutions/security/plugins/security_solution/public/cases/components/ease/wrapper.tsx b/x-pack/solutions/security/plugins/security_solution/public/cases/components/ease/wrapper.tsx index 32bd011899cfa..cf0e76c285d54 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/cases/components/ease/wrapper.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/cases/components/ease/wrapper.tsx @@ -37,7 +37,7 @@ interface EaseAlertsTableProps { /** * Query that contains the id of the alerts to display in the table */ - query: Pick; + query: Partial, 'bool' | 'ids'>>; } /** diff --git a/x-pack/solutions/security/plugins/security_solution/public/detections/hooks/trigger_actions_alert_table/use_bulk_actions.tsx b/x-pack/solutions/security/plugins/security_solution/public/detections/hooks/trigger_actions_alert_table/use_bulk_actions.tsx index 2019b48a5f5f5..51bd554bcf2dd 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detections/hooks/trigger_actions_alert_table/use_bulk_actions.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detections/hooks/trigger_actions_alert_table/use_bulk_actions.tsx @@ -28,7 +28,9 @@ import type { inputsModel } from '../../../common/store'; import { inputsSelectors } from '../../../common/store'; // check to see if the query is a known "empty" shape -export function isKnownEmptyQuery(query: QueryDslQueryContainer) { +export function isKnownEmptyQuery( + query: Pick, 'bool' | 'ids'> +) { const queries = [ // the default query used by the job wizards { bool: { must: [{ match_all: {} }] } }, @@ -47,7 +49,9 @@ export function isKnownEmptyQuery(query: QueryDslQueryContainer) { return false; } -function getFiltersForDSLQuery(datafeedQuery: QueryDslQueryContainer): Filter[] { +function getFiltersForDSLQuery( + datafeedQuery: Pick, 'bool' | 'ids'> +): Filter[] { if (isKnownEmptyQuery(datafeedQuery)) { return []; } diff --git a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/get_threshold_bucket_filters.ts b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/get_threshold_bucket_filters.ts index d39baa34f2664..6ce468a526e42 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/get_threshold_bucket_filters.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/lib/detection_engine/rule_types/threshold/get_threshold_bucket_filters.ts @@ -35,13 +35,12 @@ export const getThresholdBucketFilters = async ({ }, ], }, - } as ESFilter; + } as NonNullable; // Terms to filter out events older than `lastSignalTimestamp`. bucket.terms.forEach((term) => { - if (term.field != null) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - (filter.bool!.filter as ESFilter[]).push({ + if (term.field != null && filter.bool?.filter != null) { + (filter.bool.filter as ESFilter[]).push({ term: { [term.field]: `${term.value}`, }, diff --git a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_n_flow/query.top_n_flow_network.dsl.ts b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_n_flow/query.top_n_flow_network.dsl.ts index 6c57c67eda0cf..f0ebd8994d954 100644 --- a/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_n_flow/query.top_n_flow_network.dsl.ts +++ b/x-pack/solutions/security/plugins/security_solution/server/search_strategy/security_solution/factory/network/top_n_flow/query.top_n_flow_network.dsl.ts @@ -22,13 +22,13 @@ import { createQueryFilterClauses } from '../../../../../utils/build_query'; import { getOppositeField } from '../helpers'; import { getQueryOrder } from './helpers'; -interface AggregationsAggregationWithFieldsContainer extends AggregationsAggregationContainer { +type AggregationsAggregationWithFieldsContainer = AggregationsAggregationContainer & { aggregations?: Record; aggs?: Record; top_hits?: AggregationsTopHitsAggregation & { fields?: Array; // fields is missing in the official types but it is used in the query }; -} +}; export const buildTopNFlowQuery = ({ defaultIndex, diff --git a/yarn.lock b/yarn.lock index 1e7d5aede0318..56a1bbde1a015 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2408,12 +2408,12 @@ "@elastic/transport" "^8.3.1" tslib "^2.4.0" -"@elastic/elasticsearch@9.2.0": - version "9.2.0" - resolved "https://registry.yarnpkg.com/@elastic/elasticsearch/-/elasticsearch-9.2.0.tgz#33e028d0272838838da686738377c46e3c753ce7" - integrity sha512-M59qmMOZOk8pTcI9Ns2ow18PlyMbYrpcXqYwkChjiyXSmmqoCTvFXkC2bGQLxrrQkXaPbYR7aZqWD9b5F1405A== +"@elastic/elasticsearch@9.3.1": + version "9.3.1" + resolved "https://registry.yarnpkg.com/@elastic/elasticsearch/-/elasticsearch-9.3.1.tgz#471eec6b9456d538781ce974ae6da65c6ee6de48" + integrity sha512-4oujxiqHWLMNRE5ClPR9O7CyWvnyCRCtAHlNItKbMIdP9Fo8YTn43WZaps0qzeYne4iaTwjjdjWmGlL4CrIz2w== dependencies: - "@elastic/transport" "^9.2.0" + "@elastic/transport" "^9.3.3" apache-arrow "18.x - 21.x" tslib "^2.4.0" @@ -2722,10 +2722,10 @@ tslib "^2.8.1" undici "^6.21.1" -"@elastic/transport@^9.2.0": - version "9.3.0" - resolved "https://registry.yarnpkg.com/@elastic/transport/-/transport-9.3.0.tgz#aabfd2043254d389fd03ddbe58d373ffe58483bf" - integrity sha512-GtfjGjxhJBdLYYhdRxd7/tWBQ9JsntZNDFZiSJp9fymrup9Kj7IojucojwxpC+7QN9yQzeTUU7M67x6uPnAGpg== +"@elastic/transport@^9.3.3": + version "9.3.3" + resolved "https://registry.yarnpkg.com/@elastic/transport/-/transport-9.3.3.tgz#808ffed0aeaf99f869cb38cdac7ba896eb7da7d0" + integrity sha512-0QeEKScXdpwE8pCU/F4aDv5OO7rgh/WNmVScDhrfHS6vNLjRa0/403hzcvmyqt2ULhfDuN6hNLgnI6mtvKuO/Q== dependencies: "@opentelemetry/api" "1.x" "@opentelemetry/core" "2.x" @@ -2734,7 +2734,7 @@ ms "^2.1.3" secure-json-parse "^4.0.0" tslib "^2.8.1" - undici "^7.16.0" + undici "^7.19.1" "@emnapi/runtime@^1.5.0": version "1.6.0" @@ -33631,10 +33631,10 @@ undici@6.23.0, undici@^6.21.1, undici@^6.21.2, undici@^6.21.3: resolved "https://registry.yarnpkg.com/undici/-/undici-6.23.0.tgz#7953087744d9095a96f115de3140ca3828aff3a4" integrity sha512-VfQPToRA5FZs/qJxLIinmU59u0r7LXqoJkCzinq3ckNJp3vKEh7jTWN589YQ5+aoAC/TGRLyJLCPKcLQbM8r9g== -undici@^7.11.0, undici@^7.16.0: - version "7.18.2" - resolved "https://registry.yarnpkg.com/undici/-/undici-7.18.2.tgz#6cf724ef799a67d94fd55adf66b1e184176efcdf" - integrity sha512-y+8YjDFzWdQlSE9N5nzKMT3g4a5UBX1HKowfdXh0uvAnTaqqwqB92Jt4UXBAeKekDs5IaDKyJFR4X1gYVCgXcw== +undici@^7.11.0, undici@^7.19.1: + version "7.22.0" + resolved "https://registry.yarnpkg.com/undici/-/undici-7.22.0.tgz#7a82590a5908e504a47d85c60b0f89ca14240e60" + integrity sha512-RqslV2Us5BrllB+JeiZnK4peryVTndy9Dnqq62S3yYRRTj0tFQCwEniUy2167skdGOy3vqRzEvl1Dm4sV2ReDg== unherit@^1.0.4: version "1.1.0"