From 5c9e635b3bc392a984eec546149628ec2fd406e9 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Tue, 8 Jun 2021 15:06:06 +0200 Subject: [PATCH] Update @elastic/elasticsearch to 8.0.0-canary13 (#98266) * bump @elastic/elasticsearch to canary.7 * address errors in core * address errors in data plugin * address errors in Alerting team plugins * remove outdated messages in Lens * remove unnecessary comments in ML * address errors in Observability plugin * address errors in reporting plugin * address errors in Rule registry plugin * fix errors in Security plugins * fix errors in ES-UI plugin * remove unnecessary union. * update core tests * fix kbn-es-archiver * update to canary 8 * bump to v9 * use new typings * fix new errors in core * fix errors in core typeings * fix type errors in data plugin * fix type errors in telemetray plugin * fix data plugin tests * fix search examples type error * fix errors in discover plugin * fix errors in index_pattern_management * fix type errors in vis_type_* * fix errors in typings/elasticsearch * fix type errors in actions plugin * fix type errors in alerting and apm plugins * fix type errors in canvas and cases * fix errors in event_log * fix type errors in ILM and ingest_pipelines * fix errors in lens plugin * fix errors in lists plugin * fix errors in logstash * fix errors in metrics_entities * fix errors in o11y * fix errors in watcher * fix errors in uptime * fix errors in upgrade_assistant * fix errors in task_manager * fix errors in stack_alerts * fix errors in security_solution * fix errors in rule_registry * fix errors in snapshot_restore * fix remaining errors * fix search intergration tests * adjust assetion * bump version to canary.10 * adapt code to new naming schema * use mapping types provided by the client library * Revert "adjust assetion" This reverts commit 19b8fe0464c7df8f198f1c004fc4d8d69a16f75d. * fix so intergration tests * fix http integration tests * bump version to canary 11 * fix login test * fix http integration test * fix apm test * update docs * fixing some ml types * fix new errors in data plugin * fix new errors in alerting plugin * fix new errors in lists plugin * fix new errors in reporting * fix or mute errors in rule_registry plugin * more ML type fixes * bump to canary 12 * fix errors after merge conflict * additional ML fixes * bump to canary 13 * fix errors in apm plugin * fix errors in fleet plugin * fix errors in infra plugin * fix errors in monitoring plugin * fix errors in osquery plugin * fix errors in security solution plugins * fix errors in transform plugin * Update type imports for ES * fix errors in x-pack plugins * fix errors in tests * update docs * fix errors in x-pack/test * update error description * fix errors after master merge * update comment in infra plugin * fix new errors on xpack tests/ Co-authored-by: James Gowdy Co-authored-by: Dario Gieselaar # Conflicts: # package.json # src/core/server/saved_objects/migrationsv2/integration_tests/migration.test.ts # test/common/services/saved_object_info.ts # x-pack/plugins/snapshot_restore/server/routes/api/repositories.ts # x-pack/plugins/snapshot_restore/server/routes/api/snapshots.ts # yarn.lock --- ...gin-core-public.savedobjectsfindoptions.md | 2 +- ...ublic.savedobjectsfindoptions.sortorder.md | 2 +- .../core/server/kibana-plugin-core-server.md | 2 - ...edobjectscomplexfieldmapping.doc_values.md | 11 ---- ...savedobjectscomplexfieldmapping.dynamic.md | 15 ------ ...savedobjectscomplexfieldmapping.enabled.md | 11 ---- ...-server.savedobjectscomplexfieldmapping.md | 24 --------- ...edobjectscomplexfieldmapping.properties.md | 11 ---- ...er.savedobjectscomplexfieldmapping.type.md | 11 ---- ...savedobjectscorefieldmapping.doc_values.md | 11 ---- ...ver.savedobjectscorefieldmapping.fields.md | 16 ------ ...rver.savedobjectscorefieldmapping.index.md | 11 ---- ...ore-server.savedobjectscorefieldmapping.md | 24 --------- ...savedobjectscorefieldmapping.null_value.md | 11 ---- ...erver.savedobjectscorefieldmapping.type.md | 11 ---- ...in-core-server.savedobjectsfieldmapping.md | 4 +- ...gin-core-server.savedobjectsfindoptions.md | 2 +- ...erver.savedobjectsfindoptions.sortorder.md | 2 +- ...gin-plugins-data-public.ifieldtype.lang.md | 2 +- ...a-plugin-plugins-data-public.ifieldtype.md | 2 +- ...gins-data-public.indexpatternfield.lang.md | 4 +- ...n-plugins-data-public.indexpatternfield.md | 2 +- ...ns-data-public.indexpatternfield.tojson.md | 4 +- ...plugin-plugins-data-public.phrasefilter.md | 2 +- ...-plugin-plugins-data-public.rangefilter.md | 2 +- ...-plugin-plugins-data-public.reason.lang.md | 2 +- ...ibana-plugin-plugins-data-public.reason.md | 2 +- ...gin-plugins-data-server.ifieldtype.lang.md | 2 +- ...a-plugin-plugins-data-server.ifieldtype.md | 2 +- ...ta-server.indexpattern.addscriptedfield.md | 1 + ...erver.indexpattern.getnonscriptedfields.md | 1 + ...a-server.indexpattern.getscriptedfields.md | 1 + ...server.indexpattern.removescriptedfield.md | 1 + .../public/search_sessions/app.tsx | 2 +- package.json | 2 +- .../src/lib/indices/create_index_stream.ts | 2 +- .../src/lib/indices/delete_index.ts | 2 +- .../src/lib/indices/kibana_index.ts | 4 +- src/core/public/public.api.md | 4 +- .../version_check/ensure_es_version.ts | 2 +- .../integration_tests/core_services.test.ts | 2 +- src/core/server/index.ts | 2 - src/core/server/saved_objects/index.ts | 2 - .../server/saved_objects/mappings/index.ts | 2 - .../mappings/lib/get_property.test.ts | 2 +- .../mappings/lib/get_property.ts | 4 +- .../lib/get_root_properties_objects.test.ts | 16 +++--- .../lib/get_root_properties_objects.ts | 8 +-- .../server/saved_objects/mappings/types.ts | 54 +++++-------------- .../core/build_active_mappings.test.ts | 8 +-- .../migrations/core/build_index_map.test.ts | 18 +++---- .../migrations/core/elastic_index.test.ts | 10 ++-- .../migrations/core/elastic_index.ts | 3 +- .../migrations/core/index_migrator.test.ts | 2 +- .../migrations/core/migration_context.test.ts | 4 +- .../migrations/kibana/kibana_migrator.test.ts | 8 ++- .../migrationsv2/actions/create_index.ts | 4 +- .../actions/integration_tests/actions.test.ts | 23 +++----- .../migrationsv2/actions/read_with_pit.ts | 2 +- .../migrationsv2/actions/reindex.ts | 2 +- .../actions/remove_write_block.ts | 2 +- .../actions/search_for_outdated_documents.ts | 2 +- .../actions/wait_for_reindex_task.ts | 2 +- .../migrationsv2/actions/wait_for_task.ts | 3 +- .../integration_tests/migration.test.ts | 5 +- .../saved_objects/migrationsv2/model.test.ts | 4 +- .../saved_objects/migrationsv2/types.ts | 6 +-- .../saved_objects_type_registry.ts | 2 +- .../lib/aggregations/validation.test.ts | 10 ++-- .../service/lib/aggregations/validation.ts | 25 +++++---- .../lib/aggregations/validation_utils.test.ts | 7 ++- .../service/lib/filter_utils.test.ts | 4 +- .../saved_objects/service/lib/repository.ts | 13 ++--- .../service/lib/search_dsl/search_dsl.ts | 2 +- .../lib/search_dsl/sorting_params.test.ts | 2 +- .../service/lib/search_dsl/sorting_params.ts | 4 +- .../service/lib/update_objects_spaces.ts | 6 +-- src/core/server/saved_objects/types.ts | 4 +- src/core/server/server.api.md | 40 ++------------ .../common/es_query/filters/phrase_filter.ts | 4 +- .../common/es_query/filters/range_filter.ts | 4 +- .../index_pattern_field.test.ts.snap | 4 +- .../fields/index_pattern_field.test.ts | 2 +- .../common/index_patterns/fields/types.ts | 4 +- .../data/common/index_patterns/types.ts | 6 +-- .../data/common/search/aggs/agg_configs.ts | 8 +-- .../common/search/aggs/utils/time_splits.ts | 45 ++++++++-------- .../data/common/search/search_source/types.ts | 4 +- .../kql_query_suggestion/field.test.ts | 1 + src/plugins/data/public/public.api.md | 16 +++--- .../search/errors/painless_error.test.tsx | 1 + .../data/public/search/errors/types.ts | 4 +- .../search_interceptor.test.ts | 1 + .../shard_failure_types.ts | 4 +- .../autocomplete/value_suggestions_route.ts | 2 +- .../field_capabilities/field_caps_response.ts | 2 +- .../data/server/search/routes/call_msearch.ts | 7 ++- .../data/server/search/routes/msearch.test.ts | 2 +- .../eql_search/eql_search_strategy.ts | 3 +- .../ese_search/ese_search_strategy.test.ts | 2 +- .../ese_search/ese_search_strategy.ts | 2 +- src/plugins/data/server/server.api.md | 12 ++--- .../doc_table/create_doc_table_react.tsx | 2 +- .../components/doc/use_es_doc_search.ts | 2 +- .../confirmation_modal.test.tsx | 1 + .../components/table/table.test.tsx | 1 + .../scripted_field_table.test.tsx | 2 + .../scripted_fields_table.tsx | 2 +- .../scripted_fields_table/types.ts | 4 +- .../components/field_editor/field_editor.tsx | 13 ++--- .../public/scripting_languages/index.ts | 6 +-- .../get_local_stats.test.ts | 4 +- .../telemetry_collection/get_local_stats.ts | 2 +- .../telemetry_collection/get_nodes_usage.ts | 2 +- .../common/fields_utils.test.ts | 2 +- .../vis_type_vega/public/data_model/types.ts | 2 +- .../apis/saved_objects/migrations.ts | 12 ++--- .../apis/search/verify_error.ts | 2 +- typings/elasticsearch/index.d.ts | 4 +- typings/elasticsearch/search.d.ts | 28 ++++++---- .../plugins/actions/server/actions_client.ts | 2 +- .../create_alert_history_index_template.ts | 1 + .../actions/server/saved_objects/index.ts | 7 +-- .../server/alerts_client/alerts_client.ts | 2 +- .../alerting/server/saved_objects/index.ts | 5 +- .../create-functional-tests-archive/index.ts | 4 +- .../chart_preview/get_transaction_duration.ts | 4 +- ...egister_transaction_duration_alert_type.ts | 4 +- ...transaction_duration_anomaly_alert_type.ts | 4 +- .../collect_data_telemetry/tasks.ts | 4 +- .../create_internal_es_client/index.ts | 12 ++--- .../metrics/by_agent/shared/memory/index.ts | 4 +- .../fetch_service_paths_from_trace_ids.ts | 2 +- .../lib/service_map/get_service_anomalies.ts | 6 ++- .../get_service_map_service_node_info.ts | 4 +- .../create_agent_config_index.ts | 3 +- .../custom_link/create_custom_link_index.ts | 4 +- .../settings/custom_link/list_custom_links.ts | 4 +- .../apm/server/lib/traces/get_trace_items.ts | 4 +- .../get_transaction_group_stats.ts | 5 +- .../distribution/get_buckets/index.ts | 6 +-- .../transactions/get_anomaly_data/fetcher.ts | 4 +- .../plugins/apm/server/projections/metrics.ts | 4 +- .../apm/server/projections/transactions.ts | 4 +- .../plugins/apm/server/projections/typings.ts | 2 +- x-pack/plugins/apm/server/utils/queries.ts | 6 ++- x-pack/plugins/canvas/types/strategy.ts | 4 +- .../cases/server/services/cases/index.ts | 6 ++- .../server/es/cluster_client_adapter.ts | 2 +- .../server/routes/data_streams/handlers.ts | 2 +- .../fleet/server/services/agents/crud.ts | 6 +-- .../fleet/server/services/agents/helpers.ts | 2 +- .../server/services/agents/reassign.test.ts | 2 +- .../server/services/agents/unenroll.test.ts | 30 +++++------ .../services/api_keys/enrollment_api_key.ts | 1 - .../elasticsearch/template/install.test.ts | 1 + .../epm/elasticsearch/template/install.ts | 1 + .../epm/elasticsearch/template/template.ts | 3 +- .../api/index/register_add_policy_route.ts | 1 - .../templates/register_add_policy_route.ts | 1 + .../resolved_log_source_configuration.ts | 6 +-- .../components/expression_chart.test.tsx | 2 + .../log_analysis/api/validate_datasets.ts | 2 +- .../logs/log_analysis/api/validate_indices.ts | 2 +- .../log_analysis/log_analysis_module_types.ts | 6 +-- .../log_entry_categories/module_descriptor.ts | 4 +- .../use_log_entry_categories_module.tsx | 2 +- .../log_entry_rate/module_descriptor.ts | 4 +- .../use_log_entry_rate_module.tsx | 2 +- .../lib/create_uptime_link.test.ts | 1 + .../framework/kibana_framework_adapter.ts | 2 +- .../log_threshold_executor.test.ts | 4 +- .../log_threshold/log_threshold_executor.ts | 10 ++-- .../log_entries_domain/log_entries_domain.ts | 2 +- .../queries/log_entry_datasets.ts | 2 +- .../lib/log_analysis/log_entry_anomalies.ts | 2 +- .../log_entry_categories_analysis.ts | 2 +- .../queries/log_entry_category_examples.ts | 2 +- .../queries/log_entry_examples.ts | 2 +- .../log_analysis/validation/datasets.ts | 2 +- .../routes/log_sources/configuration.ts | 2 + .../server/routes/metrics_sources/index.ts | 2 + .../log_entries/queries/log_entries.ts | 4 +- .../services/log_entries/queries/log_entry.ts | 4 +- .../common/lib/pipeline_serialization.ts | 6 ++- .../server/routes/api/simulate.ts | 4 +- .../public/indexpattern_datasource/mocks.ts | 6 +-- .../server/routes/existing_fields.test.ts | 2 +- .../lens/server/routes/existing_fields.ts | 7 ++- .../plugins/lens/server/routes/field_stats.ts | 13 ++--- .../server/services/items/find_list_item.ts | 4 +- .../lists/server/services/lists/find_list.ts | 4 +- .../services/utils/get_search_after_scroll.ts | 2 +- .../utils/get_sort_with_tie_breaker.ts | 2 +- .../utils/transform_elastic_to_list_item.ts | 2 +- .../server/models/cluster/cluster.test.ts | 2 +- .../logstash/server/models/cluster/cluster.ts | 2 +- x-pack/plugins/maps/server/mvt/get_tile.ts | 2 +- .../server/routes/post_transforms.ts | 4 +- .../server/services/install_transforms.ts | 2 +- .../services/metrics_entities_client_types.ts | 2 +- .../server/services/post_transforms.ts | 2 +- .../types/anomaly_detection_jobs/datafeed.ts | 13 ++--- .../anomaly_detection_jobs/datafeed_stats.ts | 2 +- .../types/anomaly_detection_jobs/job.ts | 16 +++--- .../types/anomaly_detection_jobs/job_stats.ts | 21 +++----- .../anomaly_detection_jobs/model_snapshot.ts | 16 +----- .../ml/common/types/data_frame_analytics.ts | 2 +- x-pack/plugins/ml/common/types/es_client.ts | 8 +-- x-pack/plugins/ml/common/types/fields.ts | 4 +- x-pack/plugins/ml/common/util/job_utils.ts | 4 +- .../ml/common/util/runtime_field_utils.ts | 2 +- .../components/data_grid/common.ts | 2 +- .../application/components/data_grid/types.ts | 2 +- .../chart_loader.ts | 1 - .../common/get_index_data.ts | 2 +- .../form_options_validation.ts | 2 +- .../hooks/use_index_data.ts | 6 ++- .../job_creator/advanced_job_creator.ts | 9 ++-- .../new_job/common/job_creator/job_creator.ts | 1 + .../util/filter_runtime_mappings.test.ts | 4 +- .../categorization_examples_loader.ts | 1 - .../common/results_loader/results_loader.ts | 1 - .../advanced_detector_modal.tsx | 4 +- .../estimate_bucket_span.ts | 1 - .../metric_selection_summary.tsx | 1 - .../multi_metric_view/metric_selection.tsx | 2 - .../metric_selection_summary.tsx | 2 - .../population_view/metric_selection.tsx | 2 - .../metric_selection_summary.tsx | 2 - .../single_metric_view/metric_selection.tsx | 1 - .../metric_selection_summary.tsx | 1 - .../components/time_range_step/time_range.tsx | 1 - .../new_job/recognize/components/edit_job.tsx | 8 +-- .../new_job/recognize/components/job_item.tsx | 11 ++-- .../ml/server/lib/ml_client/ml_client.ts | 6 ++- x-pack/plugins/ml/server/lib/query_utils.ts | 2 +- .../models/calendar/calendar_manager.ts | 2 +- .../server/models/calendar/event_manager.ts | 2 +- .../data_frame_analytics/analytics_manager.ts | 37 ++++++++++++- .../models/fields_service/fields_service.ts | 2 - .../ml/server/models/filter/filter_manager.ts | 36 +++++++------ .../ml/server/models/job_service/datafeeds.ts | 6 +-- .../ml/server/models/job_service/jobs.ts | 6 --- .../job_service/new_job_caps/field_service.ts | 6 ++- .../models/job_service/new_job_caps/rollup.ts | 4 +- .../models/job_validation/job_validation.ts | 1 - .../ml/server/routes/anomaly_detectors.ts | 16 +++--- .../ml/server/routes/data_frame_analytics.ts | 3 ++ x-pack/plugins/ml/server/routes/datafeeds.ts | 2 +- .../ml/server/routes/trained_models.ts | 1 + .../lib/alerts/fetch_available_ccs.test.ts | 4 +- .../server/lib/annotations/mappings.ts | 4 +- .../server/utils/create_or_update_index.ts | 10 ++-- .../observability/server/utils/queries.ts | 10 ++-- .../common/search_strategy/osquery/index.ts | 2 +- .../plugins/osquery/public/agents/helpers.ts | 8 +-- x-pack/plugins/osquery/public/agents/types.ts | 4 +- .../results/query.action_results.dsl.ts | 2 +- .../reporting/server/lib/store/mapping.ts | 2 +- .../rollup/server/collectors/helpers.ts | 1 - .../common/mapping_from_field_map.ts | 4 +- x-pack/plugins/rule_registry/common/types.ts | 4 +- .../elasticsearch/index_management_gateway.ts | 1 + .../elasticsearch/resources/ilm_policy.ts | 2 +- .../elasticsearch/resources/index_template.ts | 3 +- .../event_log/log/event_query_builder.ts | 4 +- .../server/event_log/log/public_api.ts | 2 +- .../server/rule_data_client/index.ts | 4 +- .../server/rule_data_plugin_service/index.ts | 4 +- .../authorization/privileges/get_builtin.ts | 5 +- .../server/routes/authorization/roles/put.ts | 1 - .../session_management/session_index.ts | 4 +- .../data_generators/fleet_agent_generator.ts | 9 ++-- .../common/endpoint/index_data.ts | 4 +- .../common/search_strategy/common/index.ts | 2 +- .../security_solution/hosts/details/index.ts | 2 +- .../security_solution/index.ts | 2 +- .../routes/metadata/query_builders.ts | 6 +-- .../get_index_versions_by_index.test.ts | 2 +- .../migrations/migration_cleanup.ts | 2 +- .../detection_engine/reference_rules/query.ts | 4 +- .../signals/build_events_query.ts | 11 ++-- .../signals/filters/filter_events.ts | 2 +- .../filters/filter_events_against_list.ts | 6 +-- .../detection_engine/signals/filters/types.ts | 6 +-- .../signals/search_after_bulk_create.ts | 4 +- .../signals/signal_rule_alert_type.test.ts | 4 +- .../signals/single_search_after.ts | 9 ++-- .../threat_mapping/create_threat_signals.ts | 2 +- .../signals/threat_mapping/get_threat_list.ts | 4 +- .../signals/threat_mapping/types.ts | 2 +- .../lib/detection_engine/signals/types.ts | 4 +- .../lib/detection_engine/signals/utils.ts | 5 +- .../hosts/authentications/dsl/query.dsl.ts | 2 +- .../authentications/dsl/query_entities.dsl.ts | 5 +- .../hosts/overview/query.overview_host.dsl.ts | 2 +- .../hosts/uncommon_processes/dsl/query.dsl.ts | 6 +-- .../server/routes/api/policy.ts | 7 +-- .../server/routes/api/restore.ts | 4 +- .../server/routes/api/snapshots.ts | 2 +- .../spaces/server/saved_objects/mappings.ts | 2 +- .../common/build_sorted_events_query.ts | 2 +- .../alert_types/es_query/expression.tsx | 2 +- .../alert_types/es_query/action_context.ts | 2 +- .../server/alert_types/es_query/alert_type.ts | 2 +- .../monitoring/workload_statistics.test.ts | 6 +-- .../server/monitoring/workload_statistics.ts | 13 ++--- .../mark_available_tasks_as_claimed.ts | 6 +-- .../server/queries/query_clauses.ts | 22 ++++---- .../server/saved_objects/index.ts | 4 +- .../task_manager/server/task_store.test.ts | 2 +- .../plugins/task_manager/server/task_store.ts | 8 +-- .../telemetry_collection/get_license.ts | 2 +- .../get_stats_with_xpack.test.ts | 2 +- .../common/api_schemas/type_guards.ts | 2 +- .../public/app/hooks/use_index_data.ts | 2 +- .../components/filter_term_form.tsx | 4 +- .../server/routes/api/field_histograms.ts | 1 - .../transform/server/routes/api/transforms.ts | 8 ++- .../server/lib/es_migration_apis.test.ts | 1 + .../lib/reindexing/index_settings.test.ts | 4 ++ .../server/lib/reindexing/index_settings.ts | 8 +++ .../lib/reindexing/reindex_service.test.ts | 4 +- .../server/lib/reindexing/reindex_service.ts | 4 +- .../server/lib/reindexing/types.ts | 13 ++--- .../server/routes/update_index_settings.ts | 2 +- .../lib/requests/get_journey_details.ts | 6 +-- .../lib/requests/get_journey_failed_steps.ts | 4 +- .../lib/requests/get_journey_screenshot.ts | 4 +- .../server/lib/requests/get_journey_steps.ts | 4 +- .../server/lib/requests/get_latest_monitor.ts | 4 +- .../lib/requests/get_monitor_duration.ts | 4 +- .../server/lib/requests/get_monitor_status.ts | 4 +- .../server/lib/requests/get_network_events.ts | 4 +- .../uptime/server/lib/requests/get_pings.ts | 4 +- .../fetch_all_from_scroll.ts | 10 ++-- .../routes/api/indices/register_get_route.ts | 6 ++- .../api/watches/register_delete_route.ts | 7 ++- x-pack/test/accessibility/apps/ml.ts | 1 - .../api_integration/apis/lens/telemetry.ts | 2 - .../apis/ml/calendars/create_calendars.ts | 6 +-- .../apis/ml/calendars/delete_calendars.ts | 1 - .../apis/ml/calendars/get_calendars.ts | 6 --- .../apis/ml/calendars/helpers.ts | 2 +- .../apis/ml/calendars/update_calendars.ts | 2 - .../apis/ml/jobs/jobs_summary.ts | 4 +- .../api_integration/apis/security/roles.ts | 1 - .../upgrade_assistant/upgrade_assistant.ts | 1 + .../tests/alerts/rule_registry.ts | 2 +- .../service_overview/dependencies/es_utils.ts | 3 +- .../case_api_integration/common/lib/utils.ts | 12 ++--- .../tests/delete_signals_migrations.ts | 1 + .../detection_engine_api_integration/utils.ts | 2 - .../tests/encrypted_saved_objects_api.ts | 2 - .../apis/enrollment_api_keys/crud.ts | 1 - .../apps/ml/permissions/full_ml_access.ts | 1 - .../apps/ml/permissions/read_ml_access.ts | 1 - .../apps/ml/settings/calendar_edit.ts | 1 - x-pack/test/functional/services/ml/api.ts | 8 +-- .../apps/ml/alert_flyout.ts | 4 +- x-pack/test/lists_api_integration/utils.ts | 1 - .../task_manager/task_management.ts | 3 +- .../saved_object_test_plugin/server/plugin.ts | 2 +- .../tests/anonymous/login.ts | 13 ++--- yarn.lock | 19 ++++--- 366 files changed, 834 insertions(+), 1042 deletions(-) delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.doc_values.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.dynamic.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.enabled.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.properties.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.type.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.doc_values.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.fields.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.index.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.type.md diff --git a/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.md b/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.md index 7be45c6c173b4..706408f81f02a 100644 --- a/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.md +++ b/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.md @@ -30,7 +30,7 @@ export interface SavedObjectsFindOptions | [searchAfter](./kibana-plugin-core-public.savedobjectsfindoptions.searchafter.md) | estypes.Id[] | Use the sort values from the previous page to retrieve the next page of results. | | [searchFields](./kibana-plugin-core-public.savedobjectsfindoptions.searchfields.md) | string[] | The fields to perform the parsed query against. See Elasticsearch Simple Query String fields argument for more information | | [sortField](./kibana-plugin-core-public.savedobjectsfindoptions.sortfield.md) | string | | -| [sortOrder](./kibana-plugin-core-public.savedobjectsfindoptions.sortorder.md) | estypes.SortOrder | | +| [sortOrder](./kibana-plugin-core-public.savedobjectsfindoptions.sortorder.md) | estypes.SearchSortOrder | | | [type](./kibana-plugin-core-public.savedobjectsfindoptions.type.md) | string | string[] | | | [typeToNamespacesMap](./kibana-plugin-core-public.savedobjectsfindoptions.typetonamespacesmap.md) | Map<string, string[] | undefined> | This map defines each type to search for, and the namespace(s) to search for the type in; this is only intended to be used by a saved object client wrapper. If this is defined, it supersedes the type and namespaces fields when building the Elasticsearch query. Any types that are not included in this map will be excluded entirely. If a type is included but its value is undefined, the operation will search for that type in the Default namespace. | diff --git a/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.sortorder.md b/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.sortorder.md index 36f99e51ea8c6..506fb9041e353 100644 --- a/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.sortorder.md +++ b/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.sortorder.md @@ -7,5 +7,5 @@ Signature: ```typescript -sortOrder?: estypes.SortOrder; +sortOrder?: estypes.SearchSortOrder; ``` diff --git a/docs/development/core/server/kibana-plugin-core-server.md b/docs/development/core/server/kibana-plugin-core-server.md index 32a2f3312708c..604cdea1a7fbe 100644 --- a/docs/development/core/server/kibana-plugin-core-server.md +++ b/docs/development/core/server/kibana-plugin-core-server.md @@ -159,8 +159,6 @@ The plugin integrates with the core system via lifecycle events: `setup` | [SavedObjectsCollectMultiNamespaceReferencesObject](./kibana-plugin-core-server.savedobjectscollectmultinamespacereferencesobject.md) | An object to collect references for. It must be a multi-namespace type (in other words, the object type must be registered with the namespaceType: 'multiple' or namespaceType: 'multiple-isolated' option).Note: if options.purpose is 'updateObjectsSpaces', it must be a shareable type (in other words, the object type must be registered with the namespaceType: 'multiple'). | | [SavedObjectsCollectMultiNamespaceReferencesOptions](./kibana-plugin-core-server.savedobjectscollectmultinamespacereferencesoptions.md) | Options for collecting references. | | [SavedObjectsCollectMultiNamespaceReferencesResponse](./kibana-plugin-core-server.savedobjectscollectmultinamespacereferencesresponse.md) | The response when object references are collected. | -| [SavedObjectsComplexFieldMapping](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.md) | See [SavedObjectsFieldMapping](./kibana-plugin-core-server.savedobjectsfieldmapping.md) for documentation. | -| [SavedObjectsCoreFieldMapping](./kibana-plugin-core-server.savedobjectscorefieldmapping.md) | See [SavedObjectsFieldMapping](./kibana-plugin-core-server.savedobjectsfieldmapping.md) for documentation. | | [SavedObjectsCreateOptions](./kibana-plugin-core-server.savedobjectscreateoptions.md) | | | [SavedObjectsCreatePointInTimeFinderDependencies](./kibana-plugin-core-server.savedobjectscreatepointintimefinderdependencies.md) | | | [SavedObjectsDeleteByNamespaceOptions](./kibana-plugin-core-server.savedobjectsdeletebynamespaceoptions.md) | | diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.doc_values.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.doc_values.md deleted file mode 100644 index 3f2d81cc97c7c..0000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.doc_values.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsComplexFieldMapping](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.md) > [doc\_values](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.doc_values.md) - -## SavedObjectsComplexFieldMapping.doc\_values property - -Signature: - -```typescript -doc_values?: boolean; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.dynamic.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.dynamic.md deleted file mode 100644 index b01da3c62fda6..0000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.dynamic.md +++ /dev/null @@ -1,15 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsComplexFieldMapping](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.md) > [dynamic](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.dynamic.md) - -## SavedObjectsComplexFieldMapping.dynamic property - -The dynamic property of the mapping, either `false` or `'strict'`. If unspecified `dynamic: 'strict'` will be inherited from the top-level index mappings. - -Note: To limit the number of mapping fields Saved Object types should \*never\* use `dynamic: true`. - -Signature: - -```typescript -dynamic?: false | 'strict'; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.enabled.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.enabled.md deleted file mode 100644 index 08513aa2a849b..0000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.enabled.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsComplexFieldMapping](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.md) > [enabled](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.enabled.md) - -## SavedObjectsComplexFieldMapping.enabled property - -Signature: - -```typescript -enabled?: boolean; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.md deleted file mode 100644 index fc262cad54f18..0000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.md +++ /dev/null @@ -1,24 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsComplexFieldMapping](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.md) - -## SavedObjectsComplexFieldMapping interface - -See [SavedObjectsFieldMapping](./kibana-plugin-core-server.savedobjectsfieldmapping.md) for documentation. - -Signature: - -```typescript -export interface SavedObjectsComplexFieldMapping -``` - -## Properties - -| Property | Type | Description | -| --- | --- | --- | -| [doc\_values](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.doc_values.md) | boolean | | -| [dynamic](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.dynamic.md) | false | 'strict' | The dynamic property of the mapping, either false or 'strict'. If unspecified dynamic: 'strict' will be inherited from the top-level index mappings.Note: To limit the number of mapping fields Saved Object types should \*never\* use dynamic: true. | -| [enabled](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.enabled.md) | boolean | | -| [properties](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.properties.md) | SavedObjectsMappingProperties | | -| [type](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.type.md) | string | | - diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.properties.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.properties.md deleted file mode 100644 index 613a36a09ba1e..0000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.properties.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsComplexFieldMapping](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.md) > [properties](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.properties.md) - -## SavedObjectsComplexFieldMapping.properties property - -Signature: - -```typescript -properties: SavedObjectsMappingProperties; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.type.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.type.md deleted file mode 100644 index 8aaa524dad43a..0000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscomplexfieldmapping.type.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsComplexFieldMapping](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.md) > [type](./kibana-plugin-core-server.savedobjectscomplexfieldmapping.type.md) - -## SavedObjectsComplexFieldMapping.type property - -Signature: - -```typescript -type?: string; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.doc_values.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.doc_values.md deleted file mode 100644 index 2a79eafd85a6c..0000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.doc_values.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsCoreFieldMapping](./kibana-plugin-core-server.savedobjectscorefieldmapping.md) > [doc\_values](./kibana-plugin-core-server.savedobjectscorefieldmapping.doc_values.md) - -## SavedObjectsCoreFieldMapping.doc\_values property - -Signature: - -```typescript -doc_values?: boolean; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.fields.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.fields.md deleted file mode 100644 index 4f88b635ca2f7..0000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.fields.md +++ /dev/null @@ -1,16 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsCoreFieldMapping](./kibana-plugin-core-server.savedobjectscorefieldmapping.md) > [fields](./kibana-plugin-core-server.savedobjectscorefieldmapping.fields.md) - -## SavedObjectsCoreFieldMapping.fields property - -Signature: - -```typescript -fields?: { - [subfield: string]: { - type: string; - ignore_above?: number; - }; - }; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.index.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.index.md deleted file mode 100644 index e3cf685e310d2..0000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.index.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsCoreFieldMapping](./kibana-plugin-core-server.savedobjectscorefieldmapping.md) > [index](./kibana-plugin-core-server.savedobjectscorefieldmapping.index.md) - -## SavedObjectsCoreFieldMapping.index property - -Signature: - -```typescript -index?: boolean; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.md deleted file mode 100644 index e9b9c2bcf51b5..0000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.md +++ /dev/null @@ -1,24 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsCoreFieldMapping](./kibana-plugin-core-server.savedobjectscorefieldmapping.md) - -## SavedObjectsCoreFieldMapping interface - -See [SavedObjectsFieldMapping](./kibana-plugin-core-server.savedobjectsfieldmapping.md) for documentation. - -Signature: - -```typescript -export interface SavedObjectsCoreFieldMapping -``` - -## Properties - -| Property | Type | Description | -| --- | --- | --- | -| [doc\_values](./kibana-plugin-core-server.savedobjectscorefieldmapping.doc_values.md) | boolean | | -| [fields](./kibana-plugin-core-server.savedobjectscorefieldmapping.fields.md) | {
[subfield: string]: {
type: string;
ignore_above?: number;
};
} | | -| [index](./kibana-plugin-core-server.savedobjectscorefieldmapping.index.md) | boolean | | -| [null\_value](./kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md) | number | boolean | string | | -| [type](./kibana-plugin-core-server.savedobjectscorefieldmapping.type.md) | string | | - diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md deleted file mode 100644 index 627ea3695383a..0000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsCoreFieldMapping](./kibana-plugin-core-server.savedobjectscorefieldmapping.md) > [null\_value](./kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md) - -## SavedObjectsCoreFieldMapping.null\_value property - -Signature: - -```typescript -null_value?: number | boolean | string; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.type.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.type.md deleted file mode 100644 index 94d395d7983e5..0000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.type.md +++ /dev/null @@ -1,11 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsCoreFieldMapping](./kibana-plugin-core-server.savedobjectscorefieldmapping.md) > [type](./kibana-plugin-core-server.savedobjectscorefieldmapping.type.md) - -## SavedObjectsCoreFieldMapping.type property - -Signature: - -```typescript -type: string; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsfieldmapping.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfieldmapping.md index 925ca4be92e66..85b52bacafa25 100644 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectsfieldmapping.md +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfieldmapping.md @@ -11,5 +11,7 @@ Please refer to [elasticsearch documentation](https://www.elastic.co/guide/en/el Signature: ```typescript -export declare type SavedObjectsFieldMapping = SavedObjectsCoreFieldMapping | SavedObjectsComplexFieldMapping; +export declare type SavedObjectsFieldMapping = estypes.MappingProperty & { + dynamic?: false | 'strict'; +}; ``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.md index a92b1f48d08eb..d3696ee71049a 100644 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.md +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.md @@ -30,7 +30,7 @@ export interface SavedObjectsFindOptions | [searchAfter](./kibana-plugin-core-server.savedobjectsfindoptions.searchafter.md) | estypes.Id[] | Use the sort values from the previous page to retrieve the next page of results. | | [searchFields](./kibana-plugin-core-server.savedobjectsfindoptions.searchfields.md) | string[] | The fields to perform the parsed query against. See Elasticsearch Simple Query String fields argument for more information | | [sortField](./kibana-plugin-core-server.savedobjectsfindoptions.sortfield.md) | string | | -| [sortOrder](./kibana-plugin-core-server.savedobjectsfindoptions.sortorder.md) | estypes.SortOrder | | +| [sortOrder](./kibana-plugin-core-server.savedobjectsfindoptions.sortorder.md) | estypes.SearchSortOrder | | | [type](./kibana-plugin-core-server.savedobjectsfindoptions.type.md) | string | string[] | | | [typeToNamespacesMap](./kibana-plugin-core-server.savedobjectsfindoptions.typetonamespacesmap.md) | Map<string, string[] | undefined> | This map defines each type to search for, and the namespace(s) to search for the type in; this is only intended to be used by a saved object client wrapper. If this is defined, it supersedes the type and namespaces fields when building the Elasticsearch query. Any types that are not included in this map will be excluded entirely. If a type is included but its value is undefined, the operation will search for that type in the Default namespace. | diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.sortorder.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.sortorder.md index e1c657e3a5171..dca5a7d8c7583 100644 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.sortorder.md +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.sortorder.md @@ -7,5 +7,5 @@ Signature: ```typescript -sortOrder?: estypes.SortOrder; +sortOrder?: estypes.SearchSortOrder; ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.lang.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.lang.md index a994fc458cfb6..f99e7ba8b967e 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.lang.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.lang.md @@ -7,5 +7,5 @@ Signature: ```typescript -lang?: string; +lang?: estypes.ScriptLanguage; ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.md index 4e3dea5549b56..29377ff8fd392 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.ifieldtype.md @@ -26,7 +26,7 @@ export interface IFieldType | [esTypes](./kibana-plugin-plugins-data-public.ifieldtype.estypes.md) | string[] | | | [filterable](./kibana-plugin-plugins-data-public.ifieldtype.filterable.md) | boolean | | | [format](./kibana-plugin-plugins-data-public.ifieldtype.format.md) | any | | -| [lang](./kibana-plugin-plugins-data-public.ifieldtype.lang.md) | string | | +| [lang](./kibana-plugin-plugins-data-public.ifieldtype.lang.md) | estypes.ScriptLanguage | | | [name](./kibana-plugin-plugins-data-public.ifieldtype.name.md) | string | | | [readFromDocValues](./kibana-plugin-plugins-data-public.ifieldtype.readfromdocvalues.md) | boolean | | | [script](./kibana-plugin-plugins-data-public.ifieldtype.script.md) | string | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.lang.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.lang.md index b81218eb08886..3666e503e2722 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.lang.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.lang.md @@ -9,7 +9,7 @@ Script field language Signature: ```typescript -get lang(): string | undefined; +get lang(): "painless" | "expression" | "mustache" | "java" | undefined; -set lang(lang: string | undefined); +set lang(lang: "painless" | "expression" | "mustache" | "java" | undefined); ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.md index 05c807b1cd845..8cd1a476cf32f 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.md @@ -28,7 +28,7 @@ export declare class IndexPatternField implements IFieldType | [esTypes](./kibana-plugin-plugins-data-public.indexpatternfield.estypes.md) | | string[] | undefined | | | [filterable](./kibana-plugin-plugins-data-public.indexpatternfield.filterable.md) | | boolean | | | [isMapped](./kibana-plugin-plugins-data-public.indexpatternfield.ismapped.md) | | boolean | undefined | Is the field part of the index mapping? | -| [lang](./kibana-plugin-plugins-data-public.indexpatternfield.lang.md) | | string | undefined | Script field language | +| [lang](./kibana-plugin-plugins-data-public.indexpatternfield.lang.md) | | "painless" | "expression" | "mustache" | "java" | undefined | Script field language | | [name](./kibana-plugin-plugins-data-public.indexpatternfield.name.md) | | string | | | [readFromDocValues](./kibana-plugin-plugins-data-public.indexpatternfield.readfromdocvalues.md) | | boolean | | | [runtimeField](./kibana-plugin-plugins-data-public.indexpatternfield.runtimefield.md) | | RuntimeField | undefined | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.tojson.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.tojson.md index f0600dd20658a..8882fa05ce0c2 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.tojson.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.indexpatternfield.tojson.md @@ -10,7 +10,7 @@ toJSON(): { count: number; script: string | undefined; - lang: string | undefined; + lang: "painless" | "expression" | "mustache" | "java" | undefined; conflictDescriptions: Record | undefined; name: string; type: string; @@ -28,7 +28,7 @@ toJSON(): { `{ count: number; script: string | undefined; - lang: string | undefined; + lang: "painless" | "expression" | "mustache" | "java" | undefined; conflictDescriptions: Record | undefined; name: string; type: string; diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.phrasefilter.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.phrasefilter.md index 090b78a7078cc..8d0447d58634c 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.phrasefilter.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.phrasefilter.md @@ -12,7 +12,7 @@ export declare type PhraseFilter = Filter & { script?: { script: { source?: any; - lang?: string; + lang?: estypes.ScriptLanguage; params: any; }; }; diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.rangefilter.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.rangefilter.md index fbe04f5e0a2a9..1cb627ec3a8f9 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.rangefilter.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.rangefilter.md @@ -12,7 +12,7 @@ export declare type RangeFilter = Filter & EsRangeFilter & { script?: { script: { params: any; - lang: string; + lang: estypes.ScriptLanguage; source: any; }; }; diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.lang.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.lang.md index 095142cf0f05b..757d8f34a0c3a 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.lang.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.lang.md @@ -7,5 +7,5 @@ Signature: ```typescript -lang?: string; +lang?: estypes.ScriptLanguage; ``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.md index a1a76f2d2a295..fb39333cf245e 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.reason.md @@ -15,7 +15,7 @@ export interface Reason | Property | Type | Description | | --- | --- | --- | | [caused\_by](./kibana-plugin-plugins-data-public.reason.caused_by.md) | {
type: string;
reason: string;
} | | -| [lang](./kibana-plugin-plugins-data-public.reason.lang.md) | string | | +| [lang](./kibana-plugin-plugins-data-public.reason.lang.md) | estypes.ScriptLanguage | | | [position](./kibana-plugin-plugins-data-public.reason.position.md) | {
offset: number;
start: number;
end: number;
} | | | [reason](./kibana-plugin-plugins-data-public.reason.reason.md) | string | | | [script\_stack](./kibana-plugin-plugins-data-public.reason.script_stack.md) | string[] | | diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.lang.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.lang.md index d033804cb6fcb..3d5a757cb8f18 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.lang.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.lang.md @@ -7,5 +7,5 @@ Signature: ```typescript -lang?: string; +lang?: estypes.ScriptLanguage; ``` diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.md index 5ac48d26a85d6..bbc4cc2135d40 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.ifieldtype.md @@ -26,7 +26,7 @@ export interface IFieldType | [esTypes](./kibana-plugin-plugins-data-server.ifieldtype.estypes.md) | string[] | | | [filterable](./kibana-plugin-plugins-data-server.ifieldtype.filterable.md) | boolean | | | [format](./kibana-plugin-plugins-data-server.ifieldtype.format.md) | any | | -| [lang](./kibana-plugin-plugins-data-server.ifieldtype.lang.md) | string | | +| [lang](./kibana-plugin-plugins-data-server.ifieldtype.lang.md) | estypes.ScriptLanguage | | | [name](./kibana-plugin-plugins-data-server.ifieldtype.name.md) | string | | | [readFromDocValues](./kibana-plugin-plugins-data-server.ifieldtype.readfromdocvalues.md) | boolean | | | [script](./kibana-plugin-plugins-data-server.ifieldtype.script.md) | string | | diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md index 981f28a51ae09..33f1ac5e31660 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.addscriptedfield.md @@ -6,6 +6,7 @@ > Warning: This API is now obsolete. > +> use runtime field instead > Add scripted field to field list diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getnonscriptedfields.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getnonscriptedfields.md index cff2c5de98de6..e791dfc7c3738 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getnonscriptedfields.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getnonscriptedfields.md @@ -6,6 +6,7 @@ > Warning: This API is now obsolete. > +> use runtime field instead > Signature: diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getscriptedfields.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getscriptedfields.md index 62b8f1b62ac78..95f9f31309674 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getscriptedfields.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.getscriptedfields.md @@ -6,6 +6,7 @@ > Warning: This API is now obsolete. > +> use runtime field instead > Signature: diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.removescriptedfield.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.removescriptedfield.md index f6beed7389e43..b351eba2ace4f 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.removescriptedfield.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.indexpattern.removescriptedfield.md @@ -6,6 +6,7 @@ > Warning: This API is now obsolete. > +> use runtime field instead > Remove scripted field from field list diff --git a/examples/search_examples/public/search_sessions/app.tsx b/examples/search_examples/public/search_sessions/app.tsx index a768600db24ee..7fdf91537c977 100644 --- a/examples/search_examples/public/search_sessions/app.tsx +++ b/examples/search_examples/public/search_sessions/app.tsx @@ -702,7 +702,7 @@ function doSearch( const startTs = performance.now(); // Submit the search request using the `data.search` service. - // @ts-expect-error request.params is incompatible. Filter is not assignable to QueryContainer + // @ts-expect-error request.params is incompatible. Filter is not assignable to QueryDslQueryContainer return data.search .search(req, { sessionId }) .pipe( diff --git a/package.json b/package.json index 32c4420276821..091f8a003b948 100644 --- a/package.json +++ b/package.json @@ -98,7 +98,7 @@ "@elastic/apm-rum-react": "^1.2.5", "@elastic/charts": "29.2.0", "@elastic/datemath": "link:bazel-bin/packages/elastic-datemath", - "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@7.13.0-canary.1", + "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@7.14.0-canary.6", "@elastic/ems-client": "7.13.0", "@elastic/eui": "33.0.0", "@elastic/filesaver": "1.1.2", diff --git a/packages/kbn-es-archiver/src/lib/indices/create_index_stream.ts b/packages/kbn-es-archiver/src/lib/indices/create_index_stream.ts index b8d9237bc3207..f4399eff262e4 100644 --- a/packages/kbn-es-archiver/src/lib/indices/create_index_stream.ts +++ b/packages/kbn-es-archiver/src/lib/indices/create_index_stream.ts @@ -19,7 +19,7 @@ import { deleteIndex } from './delete_index'; import { ES_CLIENT_HEADERS } from '../../client_headers'; interface DocRecord { - value: estypes.IndexState & { + value: estypes.IndicesIndexState & { index: string; type: string; }; diff --git a/packages/kbn-es-archiver/src/lib/indices/delete_index.ts b/packages/kbn-es-archiver/src/lib/indices/delete_index.ts index 2a42d52e2ca80..d3d6f85d7a360 100644 --- a/packages/kbn-es-archiver/src/lib/indices/delete_index.ts +++ b/packages/kbn-es-archiver/src/lib/indices/delete_index.ts @@ -126,7 +126,7 @@ export async function waitForSnapshotCompletion( const { body: repositoryMap } = await client.snapshot.getRepository({} as any); for (const repository of Object.keys(repositoryMap)) { const allInProgress = await getInProgressSnapshots(repository); - const found = allInProgress.find((s: any) => s.indices.includes(index)); + const found = allInProgress?.find((s: any) => s.indices.includes(index)); if (!found) { continue; diff --git a/packages/kbn-es-archiver/src/lib/indices/kibana_index.ts b/packages/kbn-es-archiver/src/lib/indices/kibana_index.ts index f95bf956e2e25..29c0a03ab61fc 100644 --- a/packages/kbn-es-archiver/src/lib/indices/kibana_index.ts +++ b/packages/kbn-es-archiver/src/lib/indices/kibana_index.ts @@ -36,7 +36,7 @@ export async function deleteKibanaIndices({ await client.indices.putSettings( { index: indexNames, - body: { index: { blocks: { read_only: false } } }, + body: { settings: { blocks: { read_only: false } } }, }, { headers: ES_CLIENT_HEADERS, @@ -126,7 +126,7 @@ export async function cleanKibanaIndices({ }, }, }, - } as estypes.QueryContainer, + } as estypes.QueryDslQueryContainer, }, }, { diff --git a/src/core/public/public.api.md b/src/core/public/public.api.md index 667863d29623e..8df1bae24388f 100644 --- a/src/core/public/public.api.md +++ b/src/core/public/public.api.md @@ -1249,7 +1249,7 @@ export interface SavedObjectsCreateOptions { // @public (undocumented) export interface SavedObjectsFindOptions { // @alpha - aggs?: Record; + aggs?: Record; defaultSearchOperator?: 'AND' | 'OR'; fields?: string[]; // Warning: (ae-forgotten-export) The symbol "KueryNode" needs to be exported by the entry point index.d.ts @@ -1275,7 +1275,7 @@ export interface SavedObjectsFindOptions { // (undocumented) sortField?: string; // (undocumented) - sortOrder?: estypes.SortOrder; + sortOrder?: estypes.SearchSortOrder; // (undocumented) type: string | string[]; typeToNamespacesMap?: Map; diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.ts index 43cd52f1b5721..e1f18f8ad836a 100644 --- a/src/core/server/elasticsearch/version_check/ensure_es_version.ts +++ b/src/core/server/elasticsearch/version_check/ensure_es_version.ts @@ -31,7 +31,7 @@ export interface PollEsNodesVersionOptions { interface NodeInfo { version: string; ip: string; - http: { + http?: { publish_address: string; }; name: string; diff --git a/src/core/server/http/integration_tests/core_services.test.ts b/src/core/server/http/integration_tests/core_services.test.ts index 5433f0d3c3e31..99b63fc73687a 100644 --- a/src/core/server/http/integration_tests/core_services.test.ts +++ b/src/core/server/http/integration_tests/core_services.test.ts @@ -405,7 +405,7 @@ describe('http service', () => { const { body } = await kbnTestServer.request.get(root, '/new-platform/').expect(400); - expect(body.message).toEqual('[error_type]: error_reason'); + expect(body.message).toMatch('[error_type]: error_reason'); }); }); }); diff --git a/src/core/server/index.ts b/src/core/server/index.ts index 2e495657d3410..ef1ee69ff529b 100644 --- a/src/core/server/index.ts +++ b/src/core/server/index.ts @@ -339,8 +339,6 @@ export type { SavedObjectsDeleteByNamespaceOptions, SavedObjectsIncrementCounterOptions, SavedObjectsIncrementCounterField, - SavedObjectsComplexFieldMapping, - SavedObjectsCoreFieldMapping, SavedObjectsFieldMapping, SavedObjectsTypeMappingDefinition, SavedObjectsMappingProperties, diff --git a/src/core/server/saved_objects/index.ts b/src/core/server/saved_objects/index.ts index 2af25e0cdef3f..b1b1584d7de88 100644 --- a/src/core/server/saved_objects/index.ts +++ b/src/core/server/saved_objects/index.ts @@ -72,8 +72,6 @@ export type { } from './service/lib/repository'; export type { - SavedObjectsCoreFieldMapping, - SavedObjectsComplexFieldMapping, SavedObjectsFieldMapping, SavedObjectsMappingProperties, SavedObjectsTypeMappingDefinition, diff --git a/src/core/server/saved_objects/mappings/index.ts b/src/core/server/saved_objects/mappings/index.ts index bf1029e9f3b81..5da185ace79c6 100644 --- a/src/core/server/saved_objects/mappings/index.ts +++ b/src/core/server/saved_objects/mappings/index.ts @@ -8,8 +8,6 @@ export { getTypes, getProperty, getRootProperties, getRootPropertiesObjects } from './lib'; export type { - SavedObjectsComplexFieldMapping, - SavedObjectsCoreFieldMapping, SavedObjectsTypeMappingDefinition, SavedObjectsTypeMappingDefinitions, SavedObjectsMappingProperties, diff --git a/src/core/server/saved_objects/mappings/lib/get_property.test.ts b/src/core/server/saved_objects/mappings/lib/get_property.test.ts index dab712bbb87ad..8732b5e07d3fa 100644 --- a/src/core/server/saved_objects/mappings/lib/get_property.test.ts +++ b/src/core/server/saved_objects/mappings/lib/get_property.test.ts @@ -34,7 +34,7 @@ const MAPPINGS = { }, }, }, -}; +} as const; function runTest(key: string | string[], mapping: IndexMapping | SavedObjectsFieldMapping) { expect(typeof key === 'string' || Array.isArray(key)).toBeTruthy(); diff --git a/src/core/server/saved_objects/mappings/lib/get_property.ts b/src/core/server/saved_objects/mappings/lib/get_property.ts index c2daa1e70a898..2a9993bc175ca 100644 --- a/src/core/server/saved_objects/mappings/lib/get_property.ts +++ b/src/core/server/saved_objects/mappings/lib/get_property.ts @@ -7,7 +7,7 @@ */ import { toPath } from 'lodash'; -import { SavedObjectsCoreFieldMapping, SavedObjectsFieldMapping, IndexMapping } from '../types'; +import { SavedObjectsFieldMapping, IndexMapping } from '../types'; function getPropertyMappingFromObjectMapping( mapping: IndexMapping | SavedObjectsFieldMapping, @@ -15,7 +15,7 @@ function getPropertyMappingFromObjectMapping( ): SavedObjectsFieldMapping | undefined { const props = (mapping && (mapping as IndexMapping).properties) || - (mapping && (mapping as SavedObjectsCoreFieldMapping).fields); + (mapping && (mapping as SavedObjectsFieldMapping).fields); if (!props) { return undefined; diff --git a/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.test.ts b/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.test.ts index 2daca3a1fdd83..cbc6808418bc0 100644 --- a/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.test.ts +++ b/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.test.ts @@ -15,7 +15,7 @@ test(`returns single object with properties`, () => { properties: {}, }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({ @@ -32,7 +32,7 @@ test(`returns single object with type === 'object'`, () => { type: 'object', }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({ @@ -75,7 +75,7 @@ test(`returns two objects with type === 'object'`, () => { type: 'object', }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({ @@ -95,7 +95,7 @@ test(`excludes objects without properties and type of keyword`, () => { type: 'keyword', }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({}); @@ -111,7 +111,7 @@ test(`excludes two objects without properties and type of keyword`, () => { type: 'keyword', }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({}); @@ -127,7 +127,7 @@ test(`includes one object with properties and excludes one object without proper type: 'keyword', }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({ @@ -147,7 +147,7 @@ test(`includes one object with type === 'object' and excludes one object without type: 'keyword', }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({ @@ -170,7 +170,7 @@ test('excludes references and migrationVersion which are part of the blacklist', type: 'object', }, }, - }; + } as const; const result = getRootPropertiesObjects(mappings); expect(result).toEqual({ foo: { diff --git a/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.ts b/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.ts index 3a25865c03b26..54ea4eafc186f 100644 --- a/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.ts +++ b/src/core/server/saved_objects/mappings/lib/get_root_properties_objects.ts @@ -6,11 +6,7 @@ * Side Public License, v 1. */ -import { - SavedObjectsComplexFieldMapping, - IndexMapping, - SavedObjectsMappingProperties, -} from '../types'; +import { SavedObjectsFieldMapping, IndexMapping, SavedObjectsMappingProperties } from '../types'; import { getRootProperties } from './get_root_properties'; /** @@ -36,7 +32,7 @@ export function getRootPropertiesObjects(mappings: IndexMapping) { // we consider the existence of the properties or type of object to designate that this is an object datatype if ( !omittedRootProps.includes(key) && - ((value as SavedObjectsComplexFieldMapping).properties || value.type === 'object') + ((value as SavedObjectsFieldMapping).properties || value.type === 'object') ) { acc[key] = value; } diff --git a/src/core/server/saved_objects/mappings/types.ts b/src/core/server/saved_objects/mappings/types.ts index 25fb61de93518..e2ad2a91fd000 100644 --- a/src/core/server/saved_objects/mappings/types.ts +++ b/src/core/server/saved_objects/mappings/types.ts @@ -6,6 +6,7 @@ * Side Public License, v 1. */ +import type { estypes } from '@elastic/elasticsearch'; /** * Describe a saved object type mapping. * @@ -96,9 +97,17 @@ export interface SavedObjectsMappingProperties { * * @public */ -export type SavedObjectsFieldMapping = - | SavedObjectsCoreFieldMapping - | SavedObjectsComplexFieldMapping; +export type SavedObjectsFieldMapping = estypes.MappingProperty & { + /** + * The dynamic property of the mapping, either `false` or `'strict'`. If + * unspecified `dynamic: 'strict'` will be inherited from the top-level + * index mappings. + * + * Note: To limit the number of mapping fields Saved Object types should + * *never* use `dynamic: true`. + */ + dynamic?: false | 'strict'; +}; /** @internal */ export interface IndexMapping { @@ -114,42 +123,3 @@ export interface IndexMappingMeta { // the md5 hash of that mapping's value when the index was created. migrationMappingPropertyHashes?: { [k: string]: string }; } - -/** - * See {@link SavedObjectsFieldMapping} for documentation. - * - * @public - */ -export interface SavedObjectsCoreFieldMapping { - type: string; - null_value?: number | boolean | string; - index?: boolean; - doc_values?: boolean; - fields?: { - [subfield: string]: { - type: string; - ignore_above?: number; - }; - }; -} - -/** - * See {@link SavedObjectsFieldMapping} for documentation. - * - * @public - */ -export interface SavedObjectsComplexFieldMapping { - /** - * The dynamic property of the mapping, either `false` or `'strict'`. If - * unspecified `dynamic: 'strict'` will be inherited from the top-level - * index mappings. - * - * Note: To limit the number of mapping fields Saved Object types should - * *never* use `dynamic: true`. - */ - dynamic?: false | 'strict'; - enabled?: boolean; - doc_values?: boolean; - type?: string; - properties: SavedObjectsMappingProperties; -} diff --git a/src/core/server/saved_objects/migrations/core/build_active_mappings.test.ts b/src/core/server/saved_objects/migrations/core/build_active_mappings.test.ts index 5465da2f620ad..a39fff20abbe7 100644 --- a/src/core/server/saved_objects/migrations/core/build_active_mappings.test.ts +++ b/src/core/server/saved_objects/migrations/core/build_active_mappings.test.ts @@ -19,19 +19,19 @@ describe('buildActiveMappings', () => { const properties = { aaa: { type: 'text' }, bbb: { type: 'long' }, - }; + } as const; expect(buildActiveMappings(properties)).toMatchSnapshot(); }); test('disallows duplicate mappings', () => { - const properties = { type: { type: 'long' } }; + const properties = { type: { type: 'long' } } as const; expect(() => buildActiveMappings(properties)).toThrow(/Cannot redefine core mapping \"type\"/); }); test('disallows mappings with leading underscore', () => { - const properties = { _hm: { type: 'keyword' } }; + const properties = { _hm: { type: 'keyword' } } as const; expect(() => buildActiveMappings(properties)).toThrow( /Invalid mapping \"_hm\"\. Mappings cannot start with _/ @@ -60,7 +60,7 @@ describe('buildActiveMappings', () => { aaa: { type: 'keyword', fields: { a: { type: 'keyword' }, b: { type: 'text' } } }, bbb: { fields: { b: { type: 'text' }, a: { type: 'keyword' } }, type: 'keyword' }, ccc: { fields: { b: { type: 'text' }, a: { type: 'text' } }, type: 'keyword' }, - }; + } as const; const mappings = buildActiveMappings(properties); const hashes = mappings._meta!.migrationMappingPropertyHashes!; diff --git a/src/core/server/saved_objects/migrations/core/build_index_map.test.ts b/src/core/server/saved_objects/migrations/core/build_index_map.test.ts index c7a3251e33ab1..731b7f8c029c2 100644 --- a/src/core/server/saved_objects/migrations/core/build_index_map.test.ts +++ b/src/core/server/saved_objects/migrations/core/build_index_map.test.ts @@ -36,7 +36,7 @@ test('mappings without index pattern goes to default index', () => { type1: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, @@ -48,7 +48,7 @@ test('mappings without index pattern goes to default index', () => { type1: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, @@ -69,7 +69,7 @@ test(`mappings with custom index pattern doesn't go to default index`, () => { type1: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, @@ -81,7 +81,7 @@ test(`mappings with custom index pattern doesn't go to default index`, () => { type1: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, @@ -103,7 +103,7 @@ test('creating a script gets added to the index pattern', () => { type1: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, @@ -116,7 +116,7 @@ test('creating a script gets added to the index pattern', () => { type1: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, @@ -144,18 +144,18 @@ test('throws when two scripts are defined for an index pattern', () => { type1: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, type2: { properties: { field1: { - type: 'string', + type: 'text', }, }, }, - }; + } as const; expect(() => createIndexMap({ kibanaIndexName: defaultIndex, diff --git a/src/core/server/saved_objects/migrations/core/elastic_index.test.ts b/src/core/server/saved_objects/migrations/core/elastic_index.test.ts index 1d2ec6abc0dd1..c9c24cc85a452 100644 --- a/src/core/server/saved_objects/migrations/core/elastic_index.test.ts +++ b/src/core/server/saved_objects/migrations/core/elastic_index.test.ts @@ -40,10 +40,10 @@ describe('ElasticIndex', () => { return elasticsearchClientMock.createSuccessTransportRequestPromise({ [index]: { aliases: { foo: index }, - mappings: { dynamic: 'strict', properties: { a: 'b' } }, + mappings: { dynamic: 'strict', properties: { a: 'b' } as any }, settings: {}, }, - } as estypes.GetIndexResponse); + } as estypes.IndicesGetResponse); }); const info = await Index.fetchInfo(client, '.baz'); @@ -164,7 +164,7 @@ describe('ElasticIndex', () => { client.tasks.get.mockResolvedValue( elasticsearchClientMock.createSuccessTransportRequestPromise({ completed: true, - } as estypes.GetTaskResponse) + } as estypes.TaskGetResponse) ); const info = { @@ -175,7 +175,7 @@ describe('ElasticIndex', () => { dynamic: 'strict' as const, properties: { foo: { type: 'keyword' } }, }, - }; + } as const; await Index.convertToAlias( client, @@ -248,7 +248,7 @@ describe('ElasticIndex', () => { reason: 'all shards failed', failed_shards: [], }, - } as estypes.GetTaskResponse) + } as estypes.TaskGetResponse) ); const info = { diff --git a/src/core/server/saved_objects/migrations/core/elastic_index.ts b/src/core/server/saved_objects/migrations/core/elastic_index.ts index 76fdd5e73d804..296a4cee07c11 100644 --- a/src/core/server/saved_objects/migrations/core/elastic_index.ts +++ b/src/core/server/saved_objects/migrations/core/elastic_index.ts @@ -32,7 +32,7 @@ export interface FullIndexInfo { // saved objects which are no longer used. These saved objects will still be // kept in the outdated index for backup purposes, but won't be available in // the upgraded index. -export const excludeUnusedTypesQuery: estypes.QueryContainer = { +export const excludeUnusedTypesQuery: estypes.QueryDslQueryContainer = { bool: { must_not: [ // https://github.com/elastic/kibana/issues/91869 @@ -401,7 +401,6 @@ async function reindex( task_id: String(task), }); - // @ts-expect-error @elastic/elasticsearch GetTaskResponse doesn't contain `error` property const e = body.error; if (e) { throw new Error(`Re-index failed [${e.type}] ${e.reason} :: ${JSON.stringify(e)}`); diff --git a/src/core/server/saved_objects/migrations/core/index_migrator.test.ts b/src/core/server/saved_objects/migrations/core/index_migrator.test.ts index fcc03f363139b..64d4fa3609e90 100644 --- a/src/core/server/saved_objects/migrations/core/index_migrator.test.ts +++ b/src/core/server/saved_objects/migrations/core/index_migrator.test.ts @@ -450,7 +450,7 @@ function withIndex( client.tasks.get.mockReturnValue( elasticsearchClientMock.createSuccessTransportRequestPromise({ completed: true, - } as estypes.GetTaskResponse) + } as estypes.TaskGetResponse) ); client.search.mockReturnValue( elasticsearchClientMock.createSuccessTransportRequestPromise(searchResult(0) as any) diff --git a/src/core/server/saved_objects/migrations/core/migration_context.test.ts b/src/core/server/saved_objects/migrations/core/migration_context.test.ts index 5f2e8a37ec427..240b41266abb6 100644 --- a/src/core/server/saved_objects/migrations/core/migration_context.test.ts +++ b/src/core/server/saved_objects/migrations/core/migration_context.test.ts @@ -31,7 +31,7 @@ describe('disableUnknownTypeMappingFields', () => { }, }, }, - }; + } as const; const activeMappings = { _meta: { migrationMappingPropertyHashes: { @@ -46,7 +46,7 @@ describe('disableUnknownTypeMappingFields', () => { }, }, }, - }; + } as const; const targetMappings = disableUnknownTypeMappingFields(activeMappings, sourceMappings); it('disables complex field mappings from unknown types in the source mappings', () => { diff --git a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts index 37cea5d2de3d2..d0cc52f2dd9bd 100644 --- a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts +++ b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts @@ -320,7 +320,11 @@ const mockV2MigrationOptions = () => { ) ); options.client.indices.addBlock.mockReturnValue( - elasticsearchClientMock.createSuccessTransportRequestPromise({ acknowledged: true }) + elasticsearchClientMock.createSuccessTransportRequestPromise({ + acknowledged: true, + shards_acknowledged: true, + indices: [], + }) ); options.client.reindex.mockReturnValue( elasticsearchClientMock.createSuccessTransportRequestPromise({ @@ -333,7 +337,7 @@ const mockV2MigrationOptions = () => { error: undefined, failures: [], task: { description: 'task description' } as any, - } as estypes.GetTaskResponse) + } as estypes.TaskGetResponse) ); options.client.search = jest diff --git a/src/core/server/saved_objects/migrationsv2/actions/create_index.ts b/src/core/server/saved_objects/migrationsv2/actions/create_index.ts index 47ee44e762db7..8e5042a5ff8fe 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/create_index.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/create_index.ts @@ -24,8 +24,8 @@ import { } from './constants'; import { waitForIndexStatusYellow } from './wait_for_index_status_yellow'; -function aliasArrayToRecord(aliases: string[]): Record { - const result: Record = {}; +function aliasArrayToRecord(aliases: string[]): Record { + const result: Record = {}; for (const alias of aliases) { result[alias] = {}; } diff --git a/src/core/server/saved_objects/migrationsv2/actions/integration_tests/actions.test.ts b/src/core/server/saved_objects/migrationsv2/actions/integration_tests/actions.test.ts index b508a6198bfb3..3fa4d59e383bf 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/integration_tests/actions.test.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/integration_tests/actions.test.ts @@ -242,9 +242,7 @@ describe('migration actions', () => { it('rejects if there is a non-retryable error', async () => { expect.assertions(1); const task = removeWriteBlock({ client, index: 'no_such_index' }); - await expect(task()).rejects.toMatchInlineSnapshot( - `[ResponseError: index_not_found_exception]` - ); + await expect(task()).rejects.toThrow('index_not_found_exception'); }); }); @@ -264,7 +262,7 @@ describe('migration actions', () => { // Allocate 1 replica so that this index stays yellow number_of_replicas: '1', // Disable all shard allocation so that the index status is red - index: { routing: { allocation: { enable: 'none' } } }, + routing: { allocation: { enable: 'none' } }, }, }, }, @@ -284,7 +282,7 @@ describe('migration actions', () => { index: 'red_then_yellow_index', body: { // Enable all shard allocation so that the index status turns yellow - index: { routing: { allocation: { enable: 'all' } } }, + settings: { routing: { allocation: { enable: 'all' } } }, }, }); @@ -354,7 +352,7 @@ describe('migration actions', () => { index: 'clone_red_then_yellow_index', body: { // Enable all shard allocation so that the index status goes yellow - index: { routing: { allocation: { enable: 'all' } } }, + settings: { routing: { allocation: { enable: 'all' } } }, }, }); indexYellow = true; @@ -859,9 +857,7 @@ describe('migration actions', () => { sourceIndex: 'no_such_index', targetIndex: 'existing_index_2', }); - await expect(task()).rejects.toMatchInlineSnapshot( - `[ResponseError: index_not_found_exception]` - ); + await expect(task()).rejects.toThrow('index_not_found_exception'); task = verifyReindex({ client, @@ -1142,10 +1138,7 @@ describe('migration actions', () => { timeout: '10s', }); - await expect(task()).rejects.toMatchInlineSnapshot(` - [Error: pickupUpdatedMappings task failed with the following error: - {"type":"index_not_found_exception","reason":"no such index [no_such_index]","resource.type":"index_or_alias","resource.id":"no_such_index","index_uuid":"_na_","index":"no_such_index"}] - `); + await expect(task()).rejects.toThrow('index_not_found_exception'); }); it('resolves left wait_for_task_completion_timeout when the task does not complete within the timeout', async () => { const res = (await pickupUpdatedMappings( @@ -1433,7 +1426,7 @@ describe('migration actions', () => { index: 'red_then_yellow_index', body: { // Disable all shard allocation so that the index status is red - index: { routing: { allocation: { enable: 'all' } } }, + settings: { routing: { allocation: { enable: 'all' } } }, }, }); indexYellow = true; @@ -1455,7 +1448,7 @@ describe('migration actions', () => { // failure await expect( createIndex({ client, indexName: 'existing_index_2_alias', mappings: undefined as any })() - ).rejects.toMatchInlineSnapshot(`[ResponseError: invalid_index_name_exception]`); + ).rejects.toThrow('invalid_index_name_exception'); }); }); diff --git a/src/core/server/saved_objects/migrationsv2/actions/read_with_pit.ts b/src/core/server/saved_objects/migrationsv2/actions/read_with_pit.ts index 16f1df05f26b3..b101e7db0141c 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/read_with_pit.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/read_with_pit.ts @@ -28,7 +28,7 @@ export interface ReadWithPit { export interface ReadWithPitParams { client: ElasticsearchClient; pitId: string; - query: estypes.QueryContainer; + query: estypes.QueryDslQueryContainer; batchSize: number; searchAfter?: number[]; seqNoPrimaryTerm?: boolean; diff --git a/src/core/server/saved_objects/migrationsv2/actions/reindex.ts b/src/core/server/saved_objects/migrationsv2/actions/reindex.ts index ca8d3b594703c..e9cfb4b61dace 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/reindex.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/reindex.ts @@ -32,7 +32,7 @@ export interface ReindexParams { * are no longer used. These saved objects will still be kept in the outdated * index for backup purposes, but won't be available in the upgraded index. */ - unusedTypesQuery: estypes.QueryContainer; + unusedTypesQuery: estypes.QueryDslQueryContainer; } /** * Reindex documents from the `sourceIndex` into the `targetIndex`. Returns a diff --git a/src/core/server/saved_objects/migrationsv2/actions/remove_write_block.ts b/src/core/server/saved_objects/migrationsv2/actions/remove_write_block.ts index c55e4a235fbf1..b5bf64d5c29f7 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/remove_write_block.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/remove_write_block.ts @@ -39,7 +39,7 @@ export const removeWriteBlock = ({ // Don't change any existing settings preserve_existing: true, body: { - index: { + settings: { blocks: { write: false, }, diff --git a/src/core/server/saved_objects/migrationsv2/actions/search_for_outdated_documents.ts b/src/core/server/saved_objects/migrationsv2/actions/search_for_outdated_documents.ts index 7406cd35b1593..c27170a78245b 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/search_for_outdated_documents.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/search_for_outdated_documents.ts @@ -24,7 +24,7 @@ export interface SearchResponse { export interface SearchForOutdatedDocumentsOptions { batchSize: number; targetIndex: string; - outdatedDocumentsQuery?: estypes.QueryContainer; + outdatedDocumentsQuery?: estypes.QueryDslQueryContainer; } /** diff --git a/src/core/server/saved_objects/migrationsv2/actions/wait_for_reindex_task.ts b/src/core/server/saved_objects/migrationsv2/actions/wait_for_reindex_task.ts index fcadb5e80298a..18cf3350292b5 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/wait_for_reindex_task.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/wait_for_reindex_task.ts @@ -42,7 +42,7 @@ export const waitForReindexTask = flow( if (res.error.value.type === 'index_not_found_exception') { return TaskEither.left({ type: 'index_not_found_exception' as const, - index: res.error.value.index, + index: res.error.value.index!, }); } else { throw new Error('Reindex failed with the following error:\n' + JSON.stringify(res.error)); diff --git a/src/core/server/saved_objects/migrationsv2/actions/wait_for_task.ts b/src/core/server/saved_objects/migrationsv2/actions/wait_for_task.ts index 4e3631797e34b..0cdaa88c535ab 100644 --- a/src/core/server/saved_objects/migrationsv2/actions/wait_for_task.ts +++ b/src/core/server/saved_objects/migrationsv2/actions/wait_for_task.ts @@ -16,7 +16,7 @@ import { } from './catch_retryable_es_client_errors'; /** @internal */ export interface WaitForTaskResponse { - error: Option.Option<{ type: string; reason: string; index: string }>; + error: Option.Option<{ type: string; reason: string; index?: string }>; completed: boolean; failures: Option.Option; description?: string; @@ -84,7 +84,6 @@ export const waitForTask = ({ const failures = body.response?.failures ?? []; return Either.right({ completed: body.completed, - // @ts-expect-error @elastic/elasticsearch GetTaskResponse doesn't declare `error` property error: Option.fromNullable(body.error), failures: failures.length > 0 ? Option.some(failures) : Option.none, description: body.task.description, diff --git a/src/core/server/saved_objects/migrationsv2/integration_tests/migration.test.ts b/src/core/server/saved_objects/migrationsv2/integration_tests/migration.test.ts index 695811d4c46f2..e82f2b222bb43 100644 --- a/src/core/server/saved_objects/migrationsv2/integration_tests/migration.test.ts +++ b/src/core/server/saved_objects/migrationsv2/integration_tests/migration.test.ts @@ -157,7 +157,10 @@ describe('migration v2', () => { const response = body[migratedIndex]; expect(response).toBeDefined(); - expect(Object.keys(response.aliases).sort()).toEqual(['.kibana', `.kibana_${kibanaVersion}`]); + expect(Object.keys(response.aliases!).sort()).toEqual([ + '.kibana', + `.kibana_${kibanaVersion}`, + ]); }); it('copies all the document of the previous index to the new one', async () => { diff --git a/src/core/server/saved_objects/migrationsv2/model.test.ts b/src/core/server/saved_objects/migrationsv2/model.test.ts index 186cb24b4a34a..86dc590aabdad 100644 --- a/src/core/server/saved_objects/migrationsv2/model.test.ts +++ b/src/core/server/saved_objects/migrationsv2/model.test.ts @@ -244,7 +244,7 @@ describe('migrations v2 model', () => { disabled_saved_object_type: '7997cf5a56cc02bdc9c93361bde732b0', }, }, - }; + } as const; test('INIT -> OUTDATED_DOCUMENTS_SEARCH_OPEN_PIT if .kibana is already pointing to the target index', () => { const res: ResponseType<'INIT'> = Either.right({ @@ -683,7 +683,7 @@ describe('migrations v2 model', () => { disabled_saved_object_type: '7997cf5a56cc02bdc9c93361bde732b0', }, }, - }; + } as const; const waitForYellowSourceState: WaitForYellowSourceState = { ...baseState, diff --git a/src/core/server/saved_objects/migrationsv2/types.ts b/src/core/server/saved_objects/migrationsv2/types.ts index adcd2ad32fd24..1151e8337d3d5 100644 --- a/src/core/server/saved_objects/migrationsv2/types.ts +++ b/src/core/server/saved_objects/migrationsv2/types.ts @@ -53,7 +53,7 @@ export interface BaseState extends ControlState { readonly tempIndexMappings: IndexMapping; /** Script to apply to a legacy index before it can be used as a migration source */ readonly preMigrationScript: Option.Option; - readonly outdatedDocumentsQuery: estypes.QueryContainer; + readonly outdatedDocumentsQuery: estypes.QueryDslQueryContainer; readonly retryCount: number; readonly retryDelay: number; /** @@ -112,7 +112,7 @@ export interface BaseState extends ControlState { * are no longer used. These saved objects will still be kept in the outdated * index for backup purposes, but won't be available in the upgraded index. */ - readonly unusedTypesQuery: estypes.QueryContainer; + readonly unusedTypesQuery: estypes.QueryDslQueryContainer; } export interface InitState extends BaseState { @@ -132,7 +132,7 @@ export interface PostInitState extends BaseState { /** The target index is the index to which the migration writes */ readonly targetIndex: string; readonly versionIndexReadyActions: Option.Option; - readonly outdatedDocumentsQuery: estypes.QueryContainer; + readonly outdatedDocumentsQuery: estypes.QueryDslQueryContainer; } export interface DoneState extends PostInitState { diff --git a/src/core/server/saved_objects/saved_objects_type_registry.ts b/src/core/server/saved_objects/saved_objects_type_registry.ts index a63837132b652..ba5960c59239d 100644 --- a/src/core/server/saved_objects/saved_objects_type_registry.ts +++ b/src/core/server/saved_objects/saved_objects_type_registry.ts @@ -33,7 +33,7 @@ export class SavedObjectTypeRegistry { throw new Error(`Type '${type.name}' is already registered`); } validateType(type); - this.types.set(type.name, deepFreeze(type)); + this.types.set(type.name, deepFreeze(type) as SavedObjectsType); } /** diff --git a/src/core/server/saved_objects/service/lib/aggregations/validation.test.ts b/src/core/server/saved_objects/service/lib/aggregations/validation.test.ts index 57421db76f5b6..53f1b5c9d78c5 100644 --- a/src/core/server/saved_objects/service/lib/aggregations/validation.test.ts +++ b/src/core/server/saved_objects/service/lib/aggregations/validation.test.ts @@ -9,7 +9,7 @@ import type { estypes } from '@elastic/elasticsearch'; import { validateAndConvertAggregations } from './validation'; -type AggsMap = Record; +type AggsMap = Record; const mockMappings = { properties: { @@ -19,7 +19,9 @@ const mockMappings = { references: { type: 'nested', properties: { - id: 'keyword', + id: { + type: 'keyword', + }, }, }, foo: { @@ -31,7 +33,7 @@ const mockMappings = { type: 'text', }, bytes: { - type: 'number', + type: 'integer', }, }, }, @@ -73,7 +75,7 @@ const mockMappings = { }, }, }, -}; +} as const; describe('validateAndConvertAggregations', () => { it('validates a simple aggregations', () => { diff --git a/src/core/server/saved_objects/service/lib/aggregations/validation.ts b/src/core/server/saved_objects/service/lib/aggregations/validation.ts index cd41a23f4a28b..5ef89f297a796 100644 --- a/src/core/server/saved_objects/service/lib/aggregations/validation.ts +++ b/src/core/server/saved_objects/service/lib/aggregations/validation.ts @@ -37,9 +37,9 @@ interface ValidationContext { */ export const validateAndConvertAggregations = ( allowedTypes: string[], - aggs: Record, + aggs: Record, indexMapping: IndexMapping -): Record => { +): Record => { return validateAggregations(aggs, { allowedTypes, indexMapping, @@ -53,16 +53,15 @@ export const validateAndConvertAggregations = ( * Or a nested record of aggregation (`SearchRequest.body.aggs.myAggregation.aggs`) */ const validateAggregations = ( - aggregations: Record, + aggregations: Record, context: ValidationContext ) => { - return Object.entries(aggregations).reduce>( - (memo, [aggrName, aggrContainer]) => { - memo[aggrName] = validateAggregation(aggrContainer, childContext(context, aggrName)); - return memo; - }, - {} - ); + return Object.entries(aggregations).reduce< + Record + >((memo, [aggrName, aggrContainer]) => { + memo[aggrName] = validateAggregation(aggrContainer, childContext(context, aggrName)); + return memo; + }, {}); }; /** @@ -70,7 +69,7 @@ const validateAggregations = ( * from a nested aggregation record, including its potential nested aggregations. */ const validateAggregation = ( - aggregation: estypes.AggregationContainer, + aggregation: estypes.AggregationsAggregationContainer, context: ValidationContext ) => { const container = validateAggregationContainer(aggregation, context); @@ -93,10 +92,10 @@ const validateAggregation = ( * (ignoring its nested aggregations) */ const validateAggregationContainer = ( - container: estypes.AggregationContainer, + container: estypes.AggregationsAggregationContainer, context: ValidationContext ) => { - return Object.entries(container).reduce( + return Object.entries(container).reduce( (memo, [aggName, aggregation]) => { if (aggregationKeys.includes(aggName)) { return memo; diff --git a/src/core/server/saved_objects/service/lib/aggregations/validation_utils.test.ts b/src/core/server/saved_objects/service/lib/aggregations/validation_utils.test.ts index 25c3aea474ece..0425e46b4477e 100644 --- a/src/core/server/saved_objects/service/lib/aggregations/validation_utils.test.ts +++ b/src/core/server/saved_objects/service/lib/aggregations/validation_utils.test.ts @@ -6,7 +6,6 @@ * Side Public License, v 1. */ -import { IndexMapping } from '../../../mappings'; import { isRootLevelAttribute, rewriteRootLevelAttribute, @@ -14,7 +13,7 @@ import { rewriteObjectTypeAttribute, } from './validation_utils'; -const mockMappings: IndexMapping = { +const mockMappings = { properties: { updated_at: { type: 'date', @@ -28,7 +27,7 @@ const mockMappings: IndexMapping = { type: 'text', }, bytes: { - type: 'number', + type: 'integer', }, }, }, @@ -70,7 +69,7 @@ const mockMappings: IndexMapping = { }, }, }, -}; +} as const; describe('isRootLevelAttribute', () => { it('returns true when referring to a path to a valid root level field', () => { diff --git a/src/core/server/saved_objects/service/lib/filter_utils.test.ts b/src/core/server/saved_objects/service/lib/filter_utils.test.ts index 2ef5219ccfff1..e6934398862dc 100644 --- a/src/core/server/saved_objects/service/lib/filter_utils.test.ts +++ b/src/core/server/saved_objects/service/lib/filter_utils.test.ts @@ -31,7 +31,7 @@ const mockMappings = { type: 'text', }, bytes: { - type: 'number', + type: 'integer', }, }, }, @@ -90,7 +90,7 @@ const mockMappings = { }, }, }, -}; +} as const; describe('Filter Utils', () => { describe('#validateConvertFilterToKueryNode', () => { diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts index c626a2b2acfb5..6b51bd57248a1 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -672,7 +672,6 @@ export class SavedObjectsRepository { } const deleteDocNotFound = body.result === 'not_found'; - // @ts-expect-error 'error' does not exist on type 'DeleteResponse' const deleteIndexNotFound = body.error && body.error.type === 'index_not_found_exception'; if (deleteDocNotFound || deleteIndexNotFound) { // see "404s from missing index" above @@ -897,7 +896,7 @@ export class SavedObjectsRepository { per_page: perPage, total: body.hits.total, saved_objects: body.hits.hits.map( - (hit: estypes.Hit): SavedObjectsFindResult => ({ + (hit: estypes.SearchHit): SavedObjectsFindResult => ({ // @ts-expect-error @elastic/elasticsearch declared Id as string | number ...this._rawToSavedObject(hit), score: hit._score!, @@ -1835,13 +1834,9 @@ export class SavedObjectsRepository { ...(preference ? { preference } : {}), }; - const { body, statusCode } = await this.client.openPointInTime( - // @ts-expect-error @elastic/elasticsearch OpenPointInTimeRequest.index expected to accept string[] - esOptions, - { - ignore: [404], - } - ); + const { body, statusCode } = await this.client.openPointInTime(esOptions, { + ignore: [404], + }); if (statusCode === 404) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(); } diff --git a/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts b/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts index 64b3dd428fb8b..3196a59ca39ee 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts @@ -26,7 +26,7 @@ interface GetSearchDslOptions { rootSearchFields?: string[]; searchAfter?: estypes.Id[]; sortField?: string; - sortOrder?: estypes.SortOrder; + sortOrder?: estypes.SearchSortOrder; namespaces?: string[]; pit?: SavedObjectsPitParams; typeToNamespacesMap?: Map; diff --git a/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.test.ts b/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.test.ts index 1376f0d50a9da..e2a21cc03ce3b 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.test.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.test.ts @@ -50,7 +50,7 @@ const MAPPINGS = { }, }, }, -}; +} as const; describe('searchDsl/getSortParams', () => { describe('type, no sortField', () => { diff --git a/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.ts b/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.ts index 64849c308f3f0..592110a5413ec 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.ts @@ -16,8 +16,8 @@ export function getSortingParams( mappings: IndexMapping, type: string | string[], sortField?: string, - sortOrder?: estypes.SortOrder -): { sort?: estypes.SortContainer[] } { + sortOrder?: estypes.SearchSortOrder +): { sort?: estypes.SearchSortContainer[] } { if (!sortField) { return {}; } diff --git a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts index 079549265385c..3131d0240f96b 100644 --- a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts +++ b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import type { BulkOperationContainer, MultiGetOperation } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import intersection from 'lodash/intersection'; import type { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry'; @@ -173,7 +173,7 @@ export async function updateObjectsSpaces({ }; }); - const bulkGetDocs = expectedBulkGetResults.reduce((acc, x) => { + const bulkGetDocs = expectedBulkGetResults.reduce((acc, x) => { if (isRight(x) && x.value.esRequestIndex !== undefined) { acc.push({ _id: serializer.generateRawId(undefined, x.value.type, x.value.id), @@ -192,7 +192,7 @@ export async function updateObjectsSpaces({ const time = new Date().toISOString(); let bulkOperationRequestIndexCounter = 0; - const bulkOperationParams: BulkOperationContainer[] = []; + const bulkOperationParams: estypes.BulkOperationContainer[] = []; const expectedBulkOperationResults: Either[] = expectedBulkGetResults.map( (expectedBulkGetResult) => { if (isLeft(expectedBulkGetResult)) { diff --git a/src/core/server/saved_objects/types.ts b/src/core/server/saved_objects/types.ts index d3bfdcc6923dc..964ba671b5964 100644 --- a/src/core/server/saved_objects/types.ts +++ b/src/core/server/saved_objects/types.ts @@ -80,7 +80,7 @@ export interface SavedObjectsFindOptions { page?: number; perPage?: number; sortField?: string; - sortOrder?: estypes.SortOrder; + sortOrder?: estypes.SearchSortOrder; /** * An array of fields to include in the results * @example @@ -137,7 +137,7 @@ export interface SavedObjectsFindOptions { * * @alpha */ - aggs?: Record; + aggs?: Record; namespaces?: string[]; /** * This map defines each type to search for, and the namespace(s) to search for the type in; this is only intended to be used by a saved diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index 379e4147ae024..acec03902bf6a 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -2361,38 +2361,6 @@ export interface SavedObjectsCollectMultiNamespaceReferencesResponse { objects: SavedObjectReferenceWithContext[]; } -// @public -export interface SavedObjectsComplexFieldMapping { - // (undocumented) - doc_values?: boolean; - dynamic?: false | 'strict'; - // (undocumented) - enabled?: boolean; - // (undocumented) - properties: SavedObjectsMappingProperties; - // (undocumented) - type?: string; -} - -// @public -export interface SavedObjectsCoreFieldMapping { - // (undocumented) - doc_values?: boolean; - // (undocumented) - fields?: { - [subfield: string]: { - type: string; - ignore_above?: number; - }; - }; - // (undocumented) - index?: boolean; - // (undocumented) - null_value?: number | boolean | string; - // (undocumented) - type: string; -} - // @public (undocumented) export interface SavedObjectsCreateOptions extends SavedObjectsBaseOptions { coreMigrationVersion?: string; @@ -2554,12 +2522,14 @@ export interface SavedObjectsExportTransformContext { } // @public -export type SavedObjectsFieldMapping = SavedObjectsCoreFieldMapping | SavedObjectsComplexFieldMapping; +export type SavedObjectsFieldMapping = estypes.MappingProperty & { + dynamic?: false | 'strict'; +}; // @public (undocumented) export interface SavedObjectsFindOptions { // @alpha - aggs?: Record; + aggs?: Record; defaultSearchOperator?: 'AND' | 'OR'; fields?: string[]; // Warning: (ae-forgotten-export) The symbol "KueryNode" needs to be exported by the entry point index.d.ts @@ -2583,7 +2553,7 @@ export interface SavedObjectsFindOptions { // (undocumented) sortField?: string; // (undocumented) - sortOrder?: estypes.SortOrder; + sortOrder?: estypes.SearchSortOrder; // (undocumented) type: string | string[]; typeToNamespacesMap?: Map; diff --git a/src/plugins/data/common/es_query/filters/phrase_filter.ts b/src/plugins/data/common/es_query/filters/phrase_filter.ts index 2a7f2458a27de..85562435e68d0 100644 --- a/src/plugins/data/common/es_query/filters/phrase_filter.ts +++ b/src/plugins/data/common/es_query/filters/phrase_filter.ts @@ -5,7 +5,7 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - +import type { estypes } from '@elastic/elasticsearch'; import { get, isPlainObject } from 'lodash'; import { Filter, FilterMeta } from './meta_filter'; import { IIndexPattern, IFieldType } from '../../index_patterns'; @@ -23,7 +23,7 @@ export type PhraseFilter = Filter & { script?: { script: { source?: any; - lang?: string; + lang?: estypes.ScriptLanguage; params: any; }; }; diff --git a/src/plugins/data/common/es_query/filters/range_filter.ts b/src/plugins/data/common/es_query/filters/range_filter.ts index fb8426655583e..a082b93c0a79a 100644 --- a/src/plugins/data/common/es_query/filters/range_filter.ts +++ b/src/plugins/data/common/es_query/filters/range_filter.ts @@ -5,7 +5,7 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - +import type { estypes } from '@elastic/elasticsearch'; import { map, reduce, mapValues, get, keys, pickBy } from 'lodash'; import { Filter, FilterMeta } from './meta_filter'; import { IIndexPattern, IFieldType } from '../../index_patterns'; @@ -63,7 +63,7 @@ export type RangeFilter = Filter & script?: { script: { params: any; - lang: string; + lang: estypes.ScriptLanguage; source: any; }; }; diff --git a/src/plugins/data/common/index_patterns/fields/__snapshots__/index_pattern_field.test.ts.snap b/src/plugins/data/common/index_patterns/fields/__snapshots__/index_pattern_field.test.ts.snap index 6b1d01e5ba142..681aba41a609c 100644 --- a/src/plugins/data/common/index_patterns/fields/__snapshots__/index_pattern_field.test.ts.snap +++ b/src/plugins/data/common/index_patterns/fields/__snapshots__/index_pattern_field.test.ts.snap @@ -16,7 +16,7 @@ Object { "esTypes": Array [ "keyword", ], - "lang": "lang", + "lang": "java", "name": "name", "readFromDocValues": false, "script": "script", @@ -58,7 +58,7 @@ Object { }, }, "isMapped": undefined, - "lang": "lang", + "lang": "java", "name": "name", "readFromDocValues": false, "runtimeField": Object { diff --git a/src/plugins/data/common/index_patterns/fields/index_pattern_field.test.ts b/src/plugins/data/common/index_patterns/fields/index_pattern_field.test.ts index 48342a9e02a2b..73f015ca5517c 100644 --- a/src/plugins/data/common/index_patterns/fields/index_pattern_field.test.ts +++ b/src/plugins/data/common/index_patterns/fields/index_pattern_field.test.ts @@ -24,7 +24,7 @@ describe('Field', function () { name: 'name', type: 'string', script: 'script', - lang: 'lang', + lang: 'java' as const, count: 1, esTypes: ['text'], // note, this will get replaced by the runtime field type aggregatable: true, diff --git a/src/plugins/data/common/index_patterns/fields/types.ts b/src/plugins/data/common/index_patterns/fields/types.ts index 565dd6d926948..0fb7a46c2cf73 100644 --- a/src/plugins/data/common/index_patterns/fields/types.ts +++ b/src/plugins/data/common/index_patterns/fields/types.ts @@ -5,7 +5,7 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - +import type { estypes } from '@elastic/elasticsearch'; import { FieldSpec, IFieldSubType, IndexPattern } from '../..'; /** @@ -16,7 +16,7 @@ export interface IFieldType { name: string; type: string; script?: string; - lang?: string; + lang?: estypes.ScriptLanguage; count?: number; // esTypes might be undefined on old index patterns that have not been refreshed since we added // this prop. It is also undefined on scripted fields. diff --git a/src/plugins/data/common/index_patterns/types.ts b/src/plugins/data/common/index_patterns/types.ts index f7aeb91017740..d014e2785bd41 100644 --- a/src/plugins/data/common/index_patterns/types.ts +++ b/src/plugins/data/common/index_patterns/types.ts @@ -5,7 +5,7 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - +import type { estypes } from '@elastic/elasticsearch'; import { ToastInputFields, ErrorToastOptions } from 'src/core/public/notifications'; // eslint-disable-next-line import type { SavedObject } from 'src/core/server'; @@ -178,7 +178,7 @@ export type FieldSpecConflictDescriptions = Record; export interface FieldSpecExportFmt { count?: number; script?: string; - lang?: string; + lang?: estypes.ScriptLanguage; conflictDescriptions?: FieldSpecConflictDescriptions; name: string; type: KBN_FIELD_TYPES; @@ -208,7 +208,7 @@ export interface FieldSpec { * Scripted field langauge * Painless is the only valid scripted field language */ - lang?: string; + lang?: estypes.ScriptLanguage; conflictDescriptions?: Record; format?: SerializedFieldFormat; name: string; diff --git a/src/plugins/data/common/search/aggs/agg_configs.ts b/src/plugins/data/common/search/aggs/agg_configs.ts index 6f8a8d38a4a28..8593a0b0ed0fa 100644 --- a/src/plugins/data/common/search/aggs/agg_configs.ts +++ b/src/plugins/data/common/search/aggs/agg_configs.ts @@ -10,7 +10,7 @@ import moment from 'moment'; import _, { cloneDeep } from 'lodash'; import { i18n } from '@kbn/i18n'; import { Assign } from '@kbn/utility-types'; -import { Aggregate, Bucket } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { IEsSearchResponse, @@ -57,7 +57,9 @@ export interface AggConfigsOptions { export type CreateAggConfigParams = Assign; -export type GenericBucket = Bucket & { [property: string]: Aggregate }; +export type GenericBucket = estypes.AggregationsBucket & { + [property: string]: estypes.AggregationsAggregate; +}; /** * @name AggConfigs @@ -412,7 +414,7 @@ export class AggConfigs { const transformedRawResponse = cloneDeep(response.rawResponse); if (!transformedRawResponse.aggregations) { transformedRawResponse.aggregations = { - doc_count: response.rawResponse.hits?.total as Aggregate, + doc_count: response.rawResponse.hits?.total as estypes.AggregationsAggregate, }; } const aggCursor = transformedRawResponse.aggregations!; diff --git a/src/plugins/data/common/search/aggs/utils/time_splits.ts b/src/plugins/data/common/search/aggs/utils/time_splits.ts index 4ac47efaea347..75c1c091e0756 100644 --- a/src/plugins/data/common/search/aggs/utils/time_splits.ts +++ b/src/plugins/data/common/search/aggs/utils/time_splits.ts @@ -8,12 +8,7 @@ import moment from 'moment'; import _, { isArray } from 'lodash'; -import { - Aggregate, - FiltersAggregate, - FiltersBucketItem, - MultiBucketAggregate, -} from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { AggGroupNames } from '../agg_groups'; import { GenericBucket, AggConfigs, getTime, AggConfig } from '../../../../common'; @@ -156,12 +151,15 @@ import { IBucketAggConfig } from '../buckets'; } // ... * ``` - * - * + * + * * @param aggConfigs The agg configs instance * @param aggCursor The root aggregations object from the response which will be mutated in place */ -export function mergeTimeShifts(aggConfigs: AggConfigs, aggCursor: Record) { +export function mergeTimeShifts( + aggConfigs: AggConfigs, + aggCursor: Record +) { const timeShifts = aggConfigs.getTimeShifts(); const hasMultipleTimeShifts = Object.keys(timeShifts).length > 1; const requestAggs = aggConfigs.getRequestAggs(); @@ -200,7 +198,7 @@ export function mergeTimeShifts(aggConfigs: AggConfigs, aggCursor: Record @@ -212,7 +210,7 @@ export function mergeTimeShifts(aggConfigs: AggConfigs, aggCursor: Record bucketAgg.type.orderBuckets(bucketAgg, a, b)); } else if (baseBuckets && buckets && !isArray(baseBuckets)) { @@ -249,7 +247,10 @@ export function mergeTimeShifts(aggConfigs: AggConfigs, aggCursor: Record, aggIndex: number): undefined => { + const transformTimeShift = ( + cursor: Record, + aggIndex: number + ): undefined => { const shouldSplit = aggConfigs.aggs[aggIndex].type.splitForTimeShift( aggConfigs.aggs[aggIndex], aggConfigs @@ -257,10 +258,8 @@ export function mergeTimeShifts(aggConfigs: AggConfigs, aggCursor: Record; + const timeShiftedBuckets = (cursor.time_offset_split as estypes.AggregationsFiltersAggregate) + .buckets as Record; const subTree = {}; Object.entries(timeShifts).forEach(([key, shift]) => { mergeAggLevel( @@ -301,7 +300,7 @@ export function mergeTimeShifts(aggConfigs: AggConfigs, aggCursor: Record { querySuggestionsArgs, mockKueryNode({ prefix, suffix }) ); + // @ts-expect-error indexPatternResponse is not properly typed json const filterableFields = indexPatternResponse.fields.filter(indexPatternsUtils.isFilterable); expect(suggestions.length).toBe(filterableFields.length); diff --git a/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md index 434785839408e..6c791d01f2774 100644 --- a/src/plugins/data/public/public.api.md +++ b/src/plugins/data/public/public.api.md @@ -7,13 +7,11 @@ import { $Values } from '@kbn/utility-types'; import { Action } from 'history'; import { Adapters as Adapters_2 } from 'src/plugins/inspector/common'; -import { Aggregate } from '@elastic/elasticsearch/api/types'; import { ApiResponse } from '@elastic/elasticsearch/lib/Transport'; import { ApplicationStart } from 'kibana/public'; import { Assign } from '@kbn/utility-types'; import { BfetchPublicSetup } from 'src/plugins/bfetch/public'; import Boom from '@hapi/boom'; -import { Bucket } from '@elastic/elasticsearch/api/types'; import { ConfigDeprecationProvider } from '@kbn/config'; import { CoreSetup } from 'src/core/public'; import { CoreSetup as CoreSetup_2 } from 'kibana/public'; @@ -1245,7 +1243,7 @@ export interface IFieldType { // (undocumented) format?: any; // (undocumented) - lang?: string; + lang?: estypes.ScriptLanguage; // (undocumented) name: string; // (undocumented) @@ -1530,8 +1528,8 @@ export class IndexPatternField implements IFieldType { // (undocumented) get filterable(): boolean; get isMapped(): boolean | undefined; - get lang(): string | undefined; - set lang(lang: string | undefined); + get lang(): "painless" | "expression" | "mustache" | "java" | undefined; + set lang(lang: "painless" | "expression" | "mustache" | "java" | undefined); // (undocumented) get name(): string; // (undocumented) @@ -1555,7 +1553,7 @@ export class IndexPatternField implements IFieldType { toJSON(): { count: number; script: string | undefined; - lang: string | undefined; + lang: "painless" | "expression" | "mustache" | "java" | undefined; conflictDescriptions: Record | undefined; name: string; type: string; @@ -2002,7 +2000,7 @@ export type PhraseFilter = Filter & { script?: { script: { source?: any; - lang?: string; + lang?: estypes.ScriptLanguage; params: any; }; }; @@ -2220,7 +2218,7 @@ export type RangeFilter = Filter & EsRangeFilter & { script?: { script: { params: any; - lang: string; + lang: estypes.ScriptLanguage; source: any; }; }; @@ -2266,7 +2264,7 @@ export interface Reason { reason: string; }; // (undocumented) - lang?: string; + lang?: estypes.ScriptLanguage; // (undocumented) position?: { offset: number; diff --git a/src/plugins/data/public/search/errors/painless_error.test.tsx b/src/plugins/data/public/search/errors/painless_error.test.tsx index f07f078ea03a3..833573786594b 100644 --- a/src/plugins/data/public/search/errors/painless_error.test.tsx +++ b/src/plugins/data/public/search/errors/painless_error.test.tsx @@ -23,6 +23,7 @@ describe('PainlessError', () => { const e = new PainlessError({ statusCode: 400, message: 'search_phase_execution_exception', + // @ts-expect-error searchPhaseException is not properly typed json attributes: searchPhaseException.error, }); const component = mount(e.getErrorMessage(startMock.application)); diff --git a/src/plugins/data/public/search/errors/types.ts b/src/plugins/data/public/search/errors/types.ts index 445293fe47ea3..13c5d0c242ed0 100644 --- a/src/plugins/data/public/search/errors/types.ts +++ b/src/plugins/data/public/search/errors/types.ts @@ -5,7 +5,7 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - +import type { estypes } from '@elastic/elasticsearch'; import { KibanaServerError } from '../../../../kibana_utils/common'; export interface FailedShard { @@ -24,7 +24,7 @@ export interface Reason { start: number; end: number; }; - lang?: string; + lang?: estypes.ScriptLanguage; script?: string; caused_by?: { type: string; diff --git a/src/plugins/data/public/search/search_interceptor/search_interceptor.test.ts b/src/plugins/data/public/search/search_interceptor/search_interceptor.test.ts index dfbc912453d6e..fe66d4b6e9937 100644 --- a/src/plugins/data/public/search/search_interceptor/search_interceptor.test.ts +++ b/src/plugins/data/public/search/search_interceptor/search_interceptor.test.ts @@ -135,6 +135,7 @@ describe('SearchInterceptor', () => { new PainlessError({ statusCode: 400, message: 'search_phase_execution_exception', + // @ts-expect-error searchPhaseException is not properly typed json attributes: searchPhaseException.error, }) ); diff --git a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_types.ts b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_types.ts index c34a47dc1c6dd..83e4abf55d525 100644 --- a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_types.ts +++ b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_types.ts @@ -5,7 +5,7 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - +import type { estypes } from '@elastic/elasticsearch'; export interface ShardFailureRequest { docvalue_fields: string[]; _source: unknown; @@ -24,7 +24,7 @@ export interface ShardFailure { type: string; }; reason: string; - lang?: string; + lang?: estypes.ScriptLanguage; script?: string; script_stack?: string[]; type: string; diff --git a/src/plugins/data/server/autocomplete/value_suggestions_route.ts b/src/plugins/data/server/autocomplete/value_suggestions_route.ts index 5917f8009c472..7c5d5ccff29ea 100644 --- a/src/plugins/data/server/autocomplete/value_suggestions_route.ts +++ b/src/plugins/data/server/autocomplete/value_suggestions_route.ts @@ -78,7 +78,7 @@ async function getBody( { timeout, terminate_after }: Record, field: IFieldType | string, query: string, - filters: estypes.QueryContainer[] = [] + filters: estypes.QueryDslQueryContainer[] = [] ) { const isFieldObject = (f: any): f is IFieldType => Boolean(f && f.name); diff --git a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts index c4c1ffa3cf9f9..6db9254b81528 100644 --- a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts +++ b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts @@ -69,7 +69,7 @@ import { FieldDescriptor } from '../../../fetcher'; * @return {Array} */ export function readFieldCapsResponse( - fieldCapsResponse: estypes.FieldCapabilitiesResponse + fieldCapsResponse: estypes.FieldCapsResponse ): FieldDescriptor[] { const capsByNameThenType = fieldCapsResponse.fields; diff --git a/src/plugins/data/server/search/routes/call_msearch.ts b/src/plugins/data/server/search/routes/call_msearch.ts index 0c238adf831bd..4a7db9517c688 100644 --- a/src/plugins/data/server/search/routes/call_msearch.ts +++ b/src/plugins/data/server/search/routes/call_msearch.ts @@ -8,7 +8,8 @@ import { Observable } from 'rxjs'; import { first } from 'rxjs/operators'; -import { IUiSettingsClient, IScopedClusterClient, SharedGlobalConfig } from 'src/core/server'; +import type { IUiSettingsClient, IScopedClusterClient, SharedGlobalConfig } from 'src/core/server'; +import type { estypes } from '@elastic/elasticsearch'; import type { MsearchRequestBody, MsearchResponse } from '../../../common/search/search_source'; import { getKbnServerError } from '../../../../kibana_utils/server'; @@ -78,7 +79,9 @@ export function getCallMsearch(dependencies: CallMsearchDependencies) { body: { ...response, body: { - responses: response.body.responses?.map((r) => shimHitsTotal(r)), + responses: response.body.responses?.map((r) => + shimHitsTotal(r as estypes.SearchResponse) + ), }, }, }; diff --git a/src/plugins/data/server/search/routes/msearch.test.ts b/src/plugins/data/server/search/routes/msearch.test.ts index 6ae8612cceb1e..303f83582f737 100644 --- a/src/plugins/data/server/search/routes/msearch.test.ts +++ b/src/plugins/data/server/search/routes/msearch.test.ts @@ -116,7 +116,7 @@ describe('msearch route', () => { const error: any = mockResponse.customError.mock.calls[0][0]; expect(error.statusCode).toBe(400); - expect(error.body.message).toBe('json_e_o_f_exception'); + expect(error.body.message).toMatch(/json_e_o_f_exception/); expect(error.body.attributes).toBe(jsonEofException.error); }); diff --git a/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts b/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts index 0e3acedfe12f6..91de0fca3674c 100644 --- a/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts +++ b/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts @@ -54,7 +54,8 @@ export const eqlSearchStrategyProvider = ( }; const promise = id ? client.get({ ...params, id }, request.options) - : client.search(params as EqlSearchStrategyRequest['params'], request.options); + : // @ts-expect-error EqlRequestParams | undefined is not assignable to EqlRequestParams + client.search(params as EqlSearchStrategyRequest['params'], request.options); const response = await shimAbortSignal(promise, options.abortSignal); return toEqlKibanaSearchResponse(response as ApiResponse); }; diff --git a/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.test.ts b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.test.ts index 216318339622f..56b26a7ebe02c 100644 --- a/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.test.ts +++ b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.test.ts @@ -293,7 +293,7 @@ describe('ES search strategy', () => { expect(mockGetCaller).toBeCalled(); const request = mockGetCaller.mock.calls[0][0]; - expect(request).toEqual({ id, body: { keep_alive: keepAlive } }); + expect(request).toEqual({ id, keep_alive: keepAlive }); }); it('throws normalized error on ElasticsearchClientError', async () => { diff --git a/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts index ab6162f756ea8..d6af00ada80fa 100644 --- a/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts +++ b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts @@ -177,7 +177,7 @@ export const enhancedEsSearchStrategyProvider = ( const client = useInternalUser ? esClient.asInternalUser : esClient.asCurrentUser; await client.asyncSearch.get({ id, - body: { keep_alive: keepAlive }, + keep_alive: keepAlive, }); } catch (e) { throw getKbnServerError(e); diff --git a/src/plugins/data/server/server.api.md b/src/plugins/data/server/server.api.md index 694963534cf44..315439e56a40b 100644 --- a/src/plugins/data/server/server.api.md +++ b/src/plugins/data/server/server.api.md @@ -6,10 +6,8 @@ import { $Values } from '@kbn/utility-types'; import { Adapters } from 'src/plugins/inspector/common'; -import { Aggregate } from '@elastic/elasticsearch/api/types'; import { Assign } from '@kbn/utility-types'; import { BfetchServerSetup } from 'src/plugins/bfetch/server'; -import { Bucket } from '@elastic/elasticsearch/api/types'; import { ConfigDeprecationProvider } from '@kbn/config'; import { CoreSetup } from 'src/core/server'; import { CoreSetup as CoreSetup_2 } from 'kibana/server'; @@ -713,7 +711,7 @@ export interface IFieldType { // (undocumented) format?: any; // (undocumented) - lang?: string; + lang?: estypes.ScriptLanguage; // (undocumented) name: string; // (undocumented) @@ -1430,22 +1428,22 @@ export const shimAbortSignal: (promise: TransportRequestPromise, signal?: export function shimHitsTotal(response: estypes.SearchResponse, { legacyHitsTotal }?: ISearchOptions): { hits: { total: any; - hits: estypes.Hit[]; + hits: estypes.SearchHit[]; max_score?: number | undefined; }; took: number; timed_out: boolean; _shards: estypes.ShardStatistics; - aggregations?: Record | undefined; + aggregations?: Record | undefined; _clusters?: estypes.ClusterStatistics | undefined; documents?: unknown[] | undefined; fields?: Record | undefined; max_score?: number | undefined; num_reduce_phases?: number | undefined; - profile?: estypes.Profile | undefined; + profile?: estypes.SearchProfile | undefined; pit_id?: string | undefined; _scroll_id?: string | undefined; - suggest?: Record[]> | undefined; + suggest?: Record[]> | undefined; terminated_early?: boolean | undefined; }; diff --git a/src/plugins/discover/public/application/angular/doc_table/create_doc_table_react.tsx b/src/plugins/discover/public/application/angular/doc_table/create_doc_table_react.tsx index 1135d79b6b69e..681418c1bd7cf 100644 --- a/src/plugins/discover/public/application/angular/doc_table/create_doc_table_react.tsx +++ b/src/plugins/discover/public/application/angular/doc_table/create_doc_table_react.tsx @@ -21,7 +21,7 @@ export interface DocTableLegacyProps { searchDescription?: string; searchTitle?: string; onFilter: (field: IndexPatternField | string, value: string, type: '+' | '-') => void; - rows: estypes.Hit[]; + rows: estypes.SearchHit[]; indexPattern: IIndexPattern; minimumVisibleRows?: number; onAddColumn?: (column: string) => void; diff --git a/src/plugins/discover/public/application/components/doc/use_es_doc_search.ts b/src/plugins/discover/public/application/components/doc/use_es_doc_search.ts index 6b8e912bbffba..7a3320d43c8b5 100644 --- a/src/plugins/discover/public/application/components/doc/use_es_doc_search.ts +++ b/src/plugins/discover/public/application/components/doc/use_es_doc_search.ts @@ -33,7 +33,7 @@ export function buildSearchBody( useNewFieldsApi: boolean ): RequestBody | undefined { const computedFields = indexPattern.getComputedFields(); - const runtimeFields = computedFields.runtimeFields as estypes.RuntimeFields; + const runtimeFields = computedFields.runtimeFields as estypes.MappingRuntimeFields; const request: RequestBody = { body: { query: { diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/confirmation_modal/confirmation_modal.test.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/confirmation_modal/confirmation_modal.test.tsx index 96f78a088fff4..bacab18d28509 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/confirmation_modal/confirmation_modal.test.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/confirmation_modal/confirmation_modal.test.tsx @@ -15,6 +15,7 @@ describe('DeleteScritpedFieldConfirmationModal', () => { test('should render normally', () => { const component = shallow( {}} hideDeleteConfirmationModal={() => {}} diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/table/table.test.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/table/table.test.tsx index 83ac96f6c1695..5a9f4eb871181 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/table/table.test.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/components/table/table.test.tsx @@ -15,6 +15,7 @@ import { IIndexPattern } from 'src/plugins/data/public'; const getIndexPatternMock = (mockedFields: any = {}) => ({ ...mockedFields } as IIndexPattern); +// @ts-expect-error invalid lang type const items: ScriptedFieldItem[] = [{ name: '1', lang: 'Elastic', script: '' }]; describe('Table', () => { diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_field_table.test.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_field_table.test.tsx index 08a5f22723628..e6aa87172ca0b 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_field_table.test.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_field_table.test.tsx @@ -155,6 +155,7 @@ describe('ScriptedFieldsTable', () => { ); await component.update(); // Fire `componentWillMount()` + // @ts-expect-error lang is not valid component.instance().startDeleteField({ name: 'ScriptedField', lang: '', script: '' }); await component.update(); @@ -179,6 +180,7 @@ describe('ScriptedFieldsTable', () => { ); await component.update(); // Fire `componentWillMount()` + // @ts-expect-error lang is not valid component.instance().startDeleteField({ name: 'ScriptedField', lang: '', script: '' }); await component.update(); diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx index 77ba2f734d3fe..7fd5170b669f7 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx @@ -65,7 +65,7 @@ export class ScriptedFieldsTable extends Component< const supportedLangs = getSupportedScriptingLanguages(); for (const field of fields) { - const lang: string = field.lang; + const lang = field.lang; if (deprecatedLangs.includes(lang) || !supportedLangs.includes(lang)) { deprecatedLangsInUse.push(lang); } diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/types.ts b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/types.ts index 3348f5eb052eb..5c6adc824d225 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/types.ts +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/types.ts @@ -5,10 +5,10 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - +import type { estypes } from '@elastic/elasticsearch'; /** @internal **/ export interface ScriptedFieldItem { name: string; - lang: string; + lang: estypes.ScriptLanguage; script: string; } diff --git a/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx b/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx index f0da57a5f9b6f..b05ddaed064cd 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx @@ -5,7 +5,7 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - +import type { estypes } from '@elastic/elasticsearch'; import React, { PureComponent, Fragment } from 'react'; import { intersection, union, get } from 'lodash'; @@ -100,7 +100,7 @@ export interface FieldEditorState { isReady: boolean; isCreating: boolean; isDeprecatedLang: boolean; - scriptingLangs: string[]; + scriptingLangs: estypes.ScriptLanguage[]; fieldTypes: string[]; fieldTypeFormats: FieldTypeFormat[]; existingFieldNames: string[]; @@ -131,8 +131,8 @@ export class FieldEditor extends PureComponent { + onLangChange = (lang: estypes.ScriptLanguage) => { const { spec } = this.state; const fieldTypes = get(FIELD_TYPES_BY_LANG, lang, DEFAULT_FIELD_TYPES); spec.lang = lang; @@ -373,7 +374,7 @@ export class FieldEditor extends PureComponent { - this.onLangChange(e.target.value); + this.onLangChange(e.target.value as estypes.ScriptLanguage); }} /> diff --git a/src/plugins/index_pattern_management/public/scripting_languages/index.ts b/src/plugins/index_pattern_management/public/scripting_languages/index.ts index c6b2f3c4b6b27..aeb38c8172be0 100644 --- a/src/plugins/index_pattern_management/public/scripting_languages/index.ts +++ b/src/plugins/index_pattern_management/public/scripting_languages/index.ts @@ -5,15 +5,15 @@ * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ - +import type { estypes } from '@elastic/elasticsearch'; import { i18n } from '@kbn/i18n'; import { HttpStart, NotificationsStart } from 'src/core/public'; -export function getSupportedScriptingLanguages(): string[] { +export function getSupportedScriptingLanguages(): estypes.ScriptLanguage[] { return ['painless']; } -export function getDeprecatedScriptingLanguages(): string[] { +export function getDeprecatedScriptingLanguages(): estypes.ScriptLanguage[] { return []; } diff --git a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts index 7fd6ca4080d6a..bacfa5e77107f 100644 --- a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts +++ b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts @@ -188,7 +188,7 @@ describe('get_local_stats', () => { describe('handleLocalStats', () => { it('returns expected object without xpack or kibana data', () => { const result = handleLocalStats( - clusterInfo as estypes.RootNodeInfoResponse, + clusterInfo as estypes.InfoResponse, clusterStatsWithNodesUsage, void 0, void 0, @@ -205,7 +205,7 @@ describe('get_local_stats', () => { it('returns expected object with xpack', () => { const result = handleLocalStats( - clusterInfo as estypes.RootNodeInfoResponse, + clusterInfo as estypes.InfoResponse, clusterStatsWithNodesUsage, void 0, void 0, diff --git a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts index 7fdcb50b704af..7860949e098aa 100644 --- a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts +++ b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts @@ -28,7 +28,7 @@ import { getDataTelemetry, DATA_TELEMETRY_ID, DataTelemetryPayload } from './get */ export function handleLocalStats( // eslint-disable-next-line @typescript-eslint/naming-convention - { cluster_name, cluster_uuid, version }: estypes.RootNodeInfoResponse, + { cluster_name, cluster_uuid, version }: estypes.InfoResponse, { _nodes, cluster_name: clusterName, ...clusterStats }: ClusterStats, kibana: KibanaUsageStats | undefined, dataTelemetry: DataTelemetryPayload | undefined, diff --git a/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts b/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts index c35b8a3d24498..0d58d80ed5965 100644 --- a/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts +++ b/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts @@ -14,7 +14,7 @@ import { TIMEOUT } from './constants'; * Data returned by GET /_nodes/usage, but flattened as an array of {@link estypes.NodeUsageInformation} * with the node ID set in the field `node_id`. */ -export interface NodeUsage extends estypes.NodeUsageInformation { +export interface NodeUsage extends estypes.NodesUsageNodeUsage { /** * The Node ID as reported by ES */ diff --git a/src/plugins/vis_type_timeseries/common/fields_utils.test.ts b/src/plugins/vis_type_timeseries/common/fields_utils.test.ts index 9550697e22851..f056c38b0c0c3 100644 --- a/src/plugins/vis_type_timeseries/common/fields_utils.test.ts +++ b/src/plugins/vis_type_timeseries/common/fields_utils.test.ts @@ -12,7 +12,7 @@ import type { FieldSpec } from '../../data/common'; describe('fields_utils', () => { describe('toSanitizedFieldType', () => { const mockedField = { - lang: 'lang', + lang: 'painless', conflictDescriptions: {}, aggregatable: true, name: 'name', diff --git a/src/plugins/vis_type_vega/public/data_model/types.ts b/src/plugins/vis_type_vega/public/data_model/types.ts index 255bd9774f9df..9e3cf0a5421c1 100644 --- a/src/plugins/vis_type_vega/public/data_model/types.ts +++ b/src/plugins/vis_type_vega/public/data_model/types.ts @@ -17,7 +17,7 @@ import { EmsFileParser } from './ems_file_parser'; import { UrlParser } from './url_parser'; interface Body { - aggs?: Record; + aggs?: Record; query?: Query; timeout?: string; } diff --git a/test/api_integration/apis/saved_objects/migrations.ts b/test/api_integration/apis/saved_objects/migrations.ts index d009a66e9df55..0877998ca6c1f 100644 --- a/test/api_integration/apis/saved_objects/migrations.ts +++ b/test/api_integration/apis/saved_objects/migrations.ts @@ -87,7 +87,7 @@ export default ({ getService }: FtrProviderContext) => { const mappingProperties = { foo: { properties: { name: { type: 'text' } } }, bar: { properties: { mynum: { type: 'integer' } } }, - }; + } as const; const savedObjectTypes: SavedObjectsType[] = [ { @@ -221,7 +221,7 @@ export default ({ getService }: FtrProviderContext) => { const mappingProperties = { foo: { properties: { name: { type: 'text' } } }, bar: { properties: { mynum: { type: 'integer' } } }, - }; + } as const; let savedObjectTypes: SavedObjectsType[] = [ { @@ -357,7 +357,7 @@ export default ({ getService }: FtrProviderContext) => { const mappingProperties = { 'fleet-agent-event': { properties: { name: { type: 'text' } } }, bar: { properties: { mynum: { type: 'integer' } } }, - }; + } as const; let savedObjectTypes: SavedObjectsType[] = [ FLEET_AGENT_EVENT_TYPE, @@ -417,7 +417,7 @@ export default ({ getService }: FtrProviderContext) => { const mappingProperties = { foo: { properties: { name: { type: 'text' } } }, - }; + } as const; const savedObjectTypes: SavedObjectsType[] = [ { @@ -510,7 +510,7 @@ export default ({ getService }: FtrProviderContext) => { foo: { properties: { name: { type: 'text' } } }, bar: { properties: { nomnom: { type: 'integer' } } }, baz: { properties: { title: { type: 'keyword' } } }, - }; + } as const; const savedObjectTypes: SavedObjectsType[] = [ { @@ -677,7 +677,7 @@ async function createIndex({ coreMigrationVersion: { type: 'keyword', }, - }; + } as const; await esClient.indices.create({ index, body: { mappings: { dynamic: 'strict', properties } }, diff --git a/test/api_integration/apis/search/verify_error.ts b/test/api_integration/apis/search/verify_error.ts index d6b729f59d8d4..1973fe4e4ab36 100644 --- a/test/api_integration/apis/search/verify_error.ts +++ b/test/api_integration/apis/search/verify_error.ts @@ -16,7 +16,7 @@ export const verifyErrorResponse = ( ) => { expect(r.statusCode).to.be(expectedCode); if (message) { - expect(r.message).to.be(message); + expect(r.message).to.include.string(message); } if (shouldHaveAttrs) { expect(r).to.have.property('attributes'); diff --git a/typings/elasticsearch/index.d.ts b/typings/elasticsearch/index.d.ts index 7eaf762d353ac..1951434890c50 100644 --- a/typings/elasticsearch/index.d.ts +++ b/typings/elasticsearch/index.d.ts @@ -8,9 +8,9 @@ import { estypes } from '@elastic/elasticsearch'; import { InferSearchResponseOf, AggregateOf as AggregationResultOf, SearchHit } from './search'; -export type ESFilter = estypes.QueryContainer; +export type ESFilter = estypes.QueryDslQueryContainer; export type ESSearchRequest = estypes.SearchRequest; -export type AggregationOptionsByType = Required; +export type AggregationOptionsByType = Required; // Typings for Elasticsearch queries and aggregations. These are intended to be // moved to the Elasticsearch JS client at some point (see #77720.) diff --git a/typings/elasticsearch/search.d.ts b/typings/elasticsearch/search.d.ts index d75f31d388176..36a684fb097a5 100644 --- a/typings/elasticsearch/search.d.ts +++ b/typings/elasticsearch/search.d.ts @@ -28,14 +28,14 @@ type KeysOfSources = T extends [infer U, ...infer V] : {}; type CompositeKeysOf< - TAggregationContainer extends estypes.AggregationContainer + TAggregationContainer extends estypes.AggregationsAggregationContainer > = TAggregationContainer extends { composite: { sources: [...infer TSource] }; } ? KeysOfSources : unknown; -type Source = estypes.SourceFilter | boolean | estypes.Fields; +type Source = estypes.SearchSourceFilter | boolean | estypes.Fields; type ValueTypeOfField = T extends Record ? ValuesType @@ -50,13 +50,13 @@ type ValueTypeOfField = T extends Record type MaybeArray = T | T[]; type Fields = Exclude['body']['fields'], undefined>; -type DocValueFields = MaybeArray; +type DocValueFields = MaybeArray; export type SearchHit< TSource extends any = unknown, TFields extends Fields | undefined = undefined, TDocValueFields extends DocValueFields | undefined = undefined -> = Omit & +> = Omit & (TSource extends false ? {} : { _source: TSource }) & (TFields extends Fields ? { @@ -82,11 +82,17 @@ type HitsOf< > >; -type AggregationTypeName = Exclude; +type AggregationTypeName = Exclude< + keyof estypes.AggregationsAggregationContainer, + 'aggs' | 'aggregations' +>; -type AggregationMap = Partial>; +type AggregationMap = Partial>; -type TopLevelAggregationRequest = Pick; +type TopLevelAggregationRequest = Pick< + estypes.AggregationsAggregationContainer, + 'aggs' | 'aggregations' +>; type MaybeKeyed< TAggregationContainer, @@ -97,7 +103,7 @@ type MaybeKeyed< : { buckets: TBucket[] }; export type AggregateOf< - TAggregationContainer extends estypes.AggregationContainer, + TAggregationContainer extends estypes.AggregationsAggregationContainer, TDocument > = (Record & { adjacency_matrix: { @@ -518,9 +524,9 @@ export type AggregateOf< relation: 'eq' | 'gte'; }; max_score: number | null; - hits: TAggregationContainer extends { top_hits: estypes.TopHitsAggregation } + hits: TAggregationContainer extends { top_hits: estypes.AggregationsTopHitsAggregation } ? HitsOf - : estypes.HitsMetadata; + : estypes.SearchHitsMetadata; }; }; top_metrics: { @@ -542,7 +548,7 @@ export type AggregateOf< })[ValidAggregationKeysOf & AggregationTypeName]; type AggregateOfMap = { - [TAggregationName in keyof TAggregationMap]: TAggregationMap[TAggregationName] extends estypes.AggregationContainer + [TAggregationName in keyof TAggregationMap]: TAggregationMap[TAggregationName] extends estypes.AggregationsAggregationContainer ? AggregateOf : never; // using never means we effectively ignore optional keys, using {} creates a union type of { ... } | {} }; diff --git a/x-pack/plugins/actions/server/actions_client.ts b/x-pack/plugins/actions/server/actions_client.ts index c655141415b54..449d218ed5ae0 100644 --- a/x-pack/plugins/actions/server/actions_client.ts +++ b/x-pack/plugins/actions/server/actions_client.ts @@ -515,7 +515,7 @@ async function injectExtraFindData( scopedClusterClient: IScopedClusterClient, actionResults: ActionResult[] ): Promise { - const aggs: Record = {}; + const aggs: Record = {}; for (const actionResult of actionResults) { aggs[actionResult.id] = { filter: { diff --git a/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.ts b/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.ts index fe9874fb1d671..28b904361e677 100644 --- a/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.ts +++ b/x-pack/plugins/actions/server/preconfigured_connectors/alert_history_es_index/create_alert_history_index_template.ts @@ -56,6 +56,7 @@ async function createIndexTemplate({ await client.indices.putIndexTemplate({ name: templateName, body: template, + // @ts-expect-error doesn't exist in @elastic/elasticsearch create: true, }); } catch (err) { diff --git a/x-pack/plugins/actions/server/saved_objects/index.ts b/x-pack/plugins/actions/server/saved_objects/index.ts index 9360bc919a2d5..9d8c364007959 100644 --- a/x-pack/plugins/actions/server/saved_objects/index.ts +++ b/x-pack/plugins/actions/server/saved_objects/index.ts @@ -5,10 +5,11 @@ * 2.0. */ -import { +import type { SavedObject, SavedObjectsExportTransformContext, SavedObjectsServiceSetup, + SavedObjectsTypeMappingDefinition, } from 'kibana/server'; import { EncryptedSavedObjectsPluginSetup } from '../../../encrypted_saved_objects/server'; import mappings from './mappings.json'; @@ -31,7 +32,7 @@ export function setupSavedObjects( name: ACTION_SAVED_OBJECT_TYPE, hidden: true, namespaceType: 'single', - mappings: mappings.action, + mappings: mappings.action as SavedObjectsTypeMappingDefinition, migrations: getMigrations(encryptedSavedObjects), management: { defaultSearchField: 'name', @@ -67,7 +68,7 @@ export function setupSavedObjects( name: ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, hidden: true, namespaceType: 'single', - mappings: mappings.action_task_params, + mappings: mappings.action_task_params as SavedObjectsTypeMappingDefinition, }); encryptedSavedObjects.registerType({ type: ACTION_TASK_PARAMS_SAVED_OBJECT_TYPE, diff --git a/x-pack/plugins/alerting/server/alerts_client/alerts_client.ts b/x-pack/plugins/alerting/server/alerts_client/alerts_client.ts index b8df0c3d8de09..c81fa7927ef7d 100644 --- a/x-pack/plugins/alerting/server/alerts_client/alerts_client.ts +++ b/x-pack/plugins/alerting/server/alerts_client/alerts_client.ts @@ -109,7 +109,7 @@ export interface FindOptions extends IndexType { defaultSearchOperator?: 'AND' | 'OR'; searchFields?: string[]; sortField?: string; - sortOrder?: estypes.SortOrder; + sortOrder?: estypes.SearchSortOrder; hasReference?: { type: string; id: string; diff --git a/x-pack/plugins/alerting/server/saved_objects/index.ts b/x-pack/plugins/alerting/server/saved_objects/index.ts index c339183eeedcd..1ad0f972b2ec0 100644 --- a/x-pack/plugins/alerting/server/saved_objects/index.ts +++ b/x-pack/plugins/alerting/server/saved_objects/index.ts @@ -5,10 +5,11 @@ * 2.0. */ -import { +import type { SavedObject, SavedObjectsExportTransformContext, SavedObjectsServiceSetup, + SavedObjectsTypeMappingDefinition, } from 'kibana/server'; import mappings from './mappings.json'; import { getMigrations } from './migrations'; @@ -51,7 +52,7 @@ export function setupSavedObjects( hidden: true, namespaceType: 'single', migrations: getMigrations(encryptedSavedObjects), - mappings: mappings.alert, + mappings: mappings.alert as SavedObjectsTypeMappingDefinition, ...(config.enableImportExport ? { management: { diff --git a/x-pack/plugins/apm/scripts/create-functional-tests-archive/index.ts b/x-pack/plugins/apm/scripts/create-functional-tests-archive/index.ts index 7f62fd3998060..18cb641bd4e65 100644 --- a/x-pack/plugins/apm/scripts/create-functional-tests-archive/index.ts +++ b/x-pack/plugins/apm/scripts/create-functional-tests-archive/index.ts @@ -10,7 +10,7 @@ import { execSync } from 'child_process'; import moment from 'moment'; import path from 'path'; import fs from 'fs'; -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { getEsClient } from '../shared/get_es_client'; import { parseIndexUrl } from '../shared/parse_index_url'; @@ -117,7 +117,7 @@ async function run() { const query = { bool: { - should: should.map(({ bool }) => ({ bool })) as QueryContainer[], + should: should.map(({ bool }) => ({ bool })) as QueryDslQueryContainer[], minimum_should_match: 1, }, }; diff --git a/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_duration.ts b/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_duration.ts index 508b9419344cd..091982598d6a3 100644 --- a/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_duration.ts +++ b/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_duration.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { PROCESSOR_EVENT, SERVICE_NAME, @@ -45,7 +45,7 @@ export function getTransactionDurationChartPreview({ : []), ...rangeQuery(start, end), ...environmentQuery(environment), - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }; diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts index f77cc3ee930b1..3e870eb3e32c6 100644 --- a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts +++ b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts @@ -7,7 +7,7 @@ import { schema } from '@kbn/config-schema'; import { take } from 'rxjs/operators'; -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { ALERT_EVALUATION_THRESHOLD, ALERT_EVALUATION_VALUE, @@ -109,7 +109,7 @@ export function registerTransactionDurationAlertType({ }, }, ...environmentQuery(alertParams.environment), - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }, aggs: { diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.ts b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.ts index 399fb9a216ef5..4cc2324f47b9d 100644 --- a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.ts +++ b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.ts @@ -8,7 +8,7 @@ import { schema } from '@kbn/config-schema'; import { compact } from 'lodash'; import { ESSearchResponse } from 'typings/elasticsearch'; -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { ALERT_EVALUATION_THRESHOLD, ALERT_EVALUATION_VALUE, @@ -157,7 +157,7 @@ export function registerTransactionDurationAnomalyAlertType({ }, ] : []), - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }, aggs: { diff --git a/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts b/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts index e2a39b521466a..3d5b4b754e4aa 100644 --- a/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts +++ b/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts @@ -5,7 +5,7 @@ * 2.0. */ import { flatten, merge, sortBy, sum, pickBy } from 'lodash'; -import { CompositeAggregationSource } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { asMutableArray } from '../../../../common/utils/as_mutable_array'; import { ProcessorEvent } from '../../../../common/processor_event'; import { TelemetryTask } from '.'; @@ -59,7 +59,7 @@ export const tasks: TelemetryTask[] = [ // the transaction count for that time range. executor: async ({ indices, search }) => { async function getBucketCountFromPaginatedQuery( - sources: CompositeAggregationSource[], + sources: estypes.AggregationsCompositeAggregationSource[], prevResult?: { transaction_count: number; expected_metric_document_count: number; diff --git a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts index 9d7434d127ead..1544538de74a6 100644 --- a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts +++ b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts @@ -6,11 +6,7 @@ */ import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport'; -import { - CreateIndexRequest, - DeleteRequest, - IndexRequest, -} from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { unwrapEsResponse } from '../../../../../../observability/server'; import { APMRouteHandlerResources } from '../../../../routes/typings'; import { @@ -24,7 +20,7 @@ import { } from '../call_async_with_debug'; import { cancelEsRequestOnAbort } from '../cancel_es_request_on_abort'; -export type APMIndexDocumentParams = IndexRequest; +export type APMIndexDocumentParams = estypes.IndexRequest; export type APMInternalClient = ReturnType; @@ -78,14 +74,14 @@ export function createInternalESClient({ params, }); }, - delete: (params: DeleteRequest): Promise<{ result: string }> => { + delete: (params: estypes.DeleteRequest): Promise<{ result: string }> => { return callEs({ requestType: 'delete', cb: () => asInternalUser.delete(params), params, }); }, - indicesCreate: (params: CreateIndexRequest) => { + indicesCreate: (params: estypes.IndicesCreateRequest) => { return callEs({ requestType: 'indices.create', cb: () => asInternalUser.indices.create(params), diff --git a/x-pack/plugins/apm/server/lib/metrics/by_agent/shared/memory/index.ts b/x-pack/plugins/apm/server/lib/metrics/by_agent/shared/memory/index.ts index c58fb170bd2b0..0ec2f2c2fcfb2 100644 --- a/x-pack/plugins/apm/server/lib/metrics/by_agent/shared/memory/index.ts +++ b/x-pack/plugins/apm/server/lib/metrics/by_agent/shared/memory/index.ts @@ -46,7 +46,7 @@ const chartBase: ChartBase = { export const percentSystemMemoryUsedScript = { lang: 'expression', source: `1 - doc['${METRIC_SYSTEM_FREE_MEMORY}'] / doc['${METRIC_SYSTEM_TOTAL_MEMORY}']`, -}; +} as const; export const percentCgroupMemoryUsedScript = { lang: 'painless', @@ -68,7 +68,7 @@ export const percentCgroupMemoryUsedScript = { return used / total; `, -}; +} as const; export async function getMemoryChartData({ environment, diff --git a/x-pack/plugins/apm/server/lib/service_map/fetch_service_paths_from_trace_ids.ts b/x-pack/plugins/apm/server/lib/service_map/fetch_service_paths_from_trace_ids.ts index 64de74fb9023b..6047b97651e6a 100644 --- a/x-pack/plugins/apm/server/lib/service_map/fetch_service_paths_from_trace_ids.ts +++ b/x-pack/plugins/apm/server/lib/service_map/fetch_service_paths_from_trace_ids.ts @@ -211,7 +211,7 @@ export async function fetchServicePathsFromTraceIds( }, }, }, - }, + } as const, }, }; diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts b/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts index bcddbff34a8f6..129a0ee73b8cb 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts +++ b/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts @@ -64,7 +64,7 @@ export async function getServiceAnomalies({ by_field_value: [TRANSACTION_REQUEST, TRANSACTION_PAGE_LOAD], }, }, - ] as estypes.QueryContainer[], + ] as estypes.QueryDslQueryContainer[], }, }, aggs: { @@ -74,7 +74,9 @@ export async function getServiceAnomalies({ sources: [ { serviceName: { terms: { field: 'partition_field_value' } } }, { jobId: { terms: { field: 'job_id' } } }, - ] as Array>, + ] as Array< + Record + >, }, aggs: { metrics: { diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.ts b/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.ts index c1dfed377a763..9850c36c573dd 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.ts +++ b/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.ts @@ -224,7 +224,9 @@ function getMemoryStats({ script, }: { additionalFilters: ESFilter[]; - script: typeof percentCgroupMemoryUsedScript; + script: + | typeof percentCgroupMemoryUsedScript + | typeof percentSystemMemoryUsedScript; }) => { return withApmSpan('get_avg_memory_for_service_map_node', async () => { const response = await apmEventClient.search({ diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/create_agent_config_index.ts b/x-pack/plugins/apm/server/lib/settings/agent_configuration/create_agent_config_index.ts index 7ec850717dab1..f43938891f1f0 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/create_agent_config_index.ts +++ b/x-pack/plugins/apm/server/lib/settings/agent_configuration/create_agent_config_index.ts @@ -36,10 +36,11 @@ const mappings: Mappings = { dynamic_templates: [ { // force string to keyword (instead of default of text + keyword) + // @ts-expect-error @elastic/elasticsearch expects here mapping: MappingPropertyBase strings: { match_mapping_type: 'string', mapping: { - type: 'keyword', + type: 'keyword' as const, ignore_above: 1024, }, }, diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/create_custom_link_index.ts b/x-pack/plugins/apm/server/lib/settings/custom_link/create_custom_link_index.ts index 3965e363499fc..085bb2b4be40d 100644 --- a/x-pack/plugins/apm/server/lib/settings/custom_link/create_custom_link_index.ts +++ b/x-pack/plugins/apm/server/lib/settings/custom_link/create_custom_link_index.ts @@ -6,7 +6,7 @@ */ import { ElasticsearchClient, Logger } from 'src/core/server'; -import { PropertyBase } from '@elastic/elasticsearch/api/types'; +import { estypes } from '@elastic/elasticsearch'; import { createOrUpdateIndex, Mappings, @@ -47,7 +47,7 @@ const mappings: Mappings = { }, }, // FIXME: PropertyBase type is missing .fields - } as PropertyBase, + } as estypes.MappingPropertyBase, url: { type: 'keyword', }, diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.ts b/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.ts index f6b41f462c99f..0eac2e08d0901 100644 --- a/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.ts +++ b/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.ts @@ -6,7 +6,7 @@ */ import * as t from 'io-ts'; -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { CustomLink, CustomLinkES, @@ -32,7 +32,7 @@ export function listCustomLinks({ should: [ { term: { [key]: value } }, { bool: { must_not: [{ exists: { field: key } }] } }, - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }; }); diff --git a/x-pack/plugins/apm/server/lib/traces/get_trace_items.ts b/x-pack/plugins/apm/server/lib/traces/get_trace_items.ts index a946fa66a3b92..157f09978eaec 100644 --- a/x-pack/plugins/apm/server/lib/traces/get_trace_items.ts +++ b/x-pack/plugins/apm/server/lib/traces/get_trace_items.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { ProcessorEvent } from '../../../common/processor_event'; import { TRACE_ID, @@ -76,7 +76,7 @@ export async function getTraceItems( filter: [ { term: { [TRACE_ID]: traceId } }, ...rangeQuery(start, end), - ] as QueryContainer[], + ] as QueryDslQueryContainer[], should: { exists: { field: PARENT_ID }, }, diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/get_transaction_group_stats.ts b/x-pack/plugins/apm/server/lib/transaction_groups/get_transaction_group_stats.ts index 86be82faee578..8156d52d984df 100644 --- a/x-pack/plugins/apm/server/lib/transaction_groups/get_transaction_group_stats.ts +++ b/x-pack/plugins/apm/server/lib/transaction_groups/get_transaction_group_stats.ts @@ -23,7 +23,10 @@ type BucketKey = string | Record; function mergeRequestWithAggs< TRequestBase extends TransactionGroupRequestBase, - TAggregationMap extends Record + TAggregationMap extends Record< + string, + estypes.AggregationsAggregationContainer + > >(request: TRequestBase, aggs: TAggregationMap) { return merge({}, request, { body: { diff --git a/x-pack/plugins/apm/server/lib/transactions/distribution/get_buckets/index.ts b/x-pack/plugins/apm/server/lib/transactions/distribution/get_buckets/index.ts index 966bf4ab3c58b..3e995913aebb9 100644 --- a/x-pack/plugins/apm/server/lib/transactions/distribution/get_buckets/index.ts +++ b/x-pack/plugins/apm/server/lib/transactions/distribution/get_buckets/index.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { withApmSpan } from '../../../../utils/with_apm_span'; import { SERVICE_NAME, @@ -86,7 +86,7 @@ export async function getBuckets({ ...rangeQuery(start, end), ...environmentQuery(environment), ...kqlQuery(kuery), - ] as QueryContainer[]; + ] as QueryDslQueryContainer[]; async function getSamplesForDistributionBuckets() { const response = await withApmSpan( @@ -106,7 +106,7 @@ export async function getBuckets({ should: [ { term: { [TRACE_ID]: traceId } }, { term: { [TRANSACTION_ID]: transactionId } }, - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }, aggs: { diff --git a/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/fetcher.ts b/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/fetcher.ts index 8b068fd6bd2fb..b105f3b5c0a30 100644 --- a/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/fetcher.ts +++ b/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/fetcher.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { ESSearchResponse } from '../../../../../../../typings/elasticsearch'; import { PromiseReturnType } from '../../../../../observability/typings/common'; import { rangeQuery } from '../../../../server/utils/queries'; @@ -44,7 +44,7 @@ export function anomalySeriesFetcher({ { term: { partition_field_value: serviceName } }, { term: { by_field_value: transactionType } }, ...rangeQuery(start, end, 'timestamp'), - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }, aggs: { diff --git a/x-pack/plugins/apm/server/projections/metrics.ts b/x-pack/plugins/apm/server/projections/metrics.ts index 68056f091c873..9a757893337e5 100644 --- a/x-pack/plugins/apm/server/projections/metrics.ts +++ b/x-pack/plugins/apm/server/projections/metrics.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { Setup, SetupTimeRange } from '../../server/lib/helpers/setup_request'; import { SERVICE_NAME, @@ -52,7 +52,7 @@ export function getMetricsProjection({ ...rangeQuery(start, end), ...environmentQuery(environment), ...kqlQuery(kuery), - ] as QueryContainer[]; + ] as QueryDslQueryContainer[]; return { apm: { diff --git a/x-pack/plugins/apm/server/projections/transactions.ts b/x-pack/plugins/apm/server/projections/transactions.ts index dd16b0b910abf..3e830403debb0 100644 --- a/x-pack/plugins/apm/server/projections/transactions.ts +++ b/x-pack/plugins/apm/server/projections/transactions.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { Setup, SetupTimeRange } from '../../server/lib/helpers/setup_request'; import { SERVICE_NAME, @@ -62,7 +62,7 @@ export function getTransactionsProjection({ ...rangeQuery(start, end), ...environmentQuery(environment), ...kqlQuery(kuery), - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }; return { diff --git a/x-pack/plugins/apm/server/projections/typings.ts b/x-pack/plugins/apm/server/projections/typings.ts index bb90aa0bf5eb4..60a3317af1864 100644 --- a/x-pack/plugins/apm/server/projections/typings.ts +++ b/x-pack/plugins/apm/server/projections/typings.ts @@ -16,7 +16,7 @@ export type Projection = Omit & { aggs?: { [key: string]: { terms: AggregationOptionsByType['terms'] & { field: string }; - aggs?: Record; + aggs?: Record; }; }; }; diff --git a/x-pack/plugins/apm/server/utils/queries.ts b/x-pack/plugins/apm/server/utils/queries.ts index 7255e7ed75a63..f21ef9de0283f 100644 --- a/x-pack/plugins/apm/server/utils/queries.ts +++ b/x-pack/plugins/apm/server/utils/queries.ts @@ -13,9 +13,11 @@ import { } from '../../common/environment_filter_values'; export { kqlQuery, rangeQuery } from '../../../observability/server'; -type QueryContainer = ESFilter; +type QueryDslQueryContainer = ESFilter; -export function environmentQuery(environment?: string): QueryContainer[] { +export function environmentQuery( + environment?: string +): QueryDslQueryContainer[] { if (!environment || environment === ENVIRONMENT_ALL.value) { return []; } diff --git a/x-pack/plugins/canvas/types/strategy.ts b/x-pack/plugins/canvas/types/strategy.ts index 1c94059f0c9ca..d7115a3e4372f 100644 --- a/x-pack/plugins/canvas/types/strategy.ts +++ b/x-pack/plugins/canvas/types/strategy.ts @@ -6,7 +6,7 @@ */ import { ApiResponse } from '@elastic/elasticsearch/lib/Transport'; -import { QuerySqlResponse } from '@elastic/elasticsearch/api/types'; +import { estypes } from '@elastic/elasticsearch'; import { IKibanaSearchRequest } from 'src/plugins/data/common'; import { ExpressionValueFilter } from '.'; export interface EssqlSearchStrategyRequest extends IKibanaSearchRequest { @@ -27,5 +27,5 @@ export interface EssqlSearchStrategyResponse { }>; rows: any[]; - rawResponse: ApiResponse; + rawResponse: ApiResponse; } diff --git a/x-pack/plugins/cases/server/services/cases/index.ts b/x-pack/plugins/cases/server/services/cases/index.ts index 196314a0ecbfb..5618f6c83ff06 100644 --- a/x-pack/plugins/cases/server/services/cases/index.ts +++ b/x-pack/plugins/cases/server/services/cases/index.ts @@ -16,7 +16,7 @@ import { SavedObjectsFindResult, } from 'kibana/server'; -import { AggregationContainer } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { nodeBuilder, KueryNode } from '../../../../../../src/plugins/data/common'; import { SecurityPluginSetup } from '../../../../security/server'; @@ -218,7 +218,9 @@ export class CasesService { private readonly authentication?: SecurityPluginSetup['authc'] ) {} - private buildCaseIdsAggs = (size: number = 100): Record => ({ + private buildCaseIdsAggs = ( + size: number = 100 + ): Record => ({ references: { nested: { path: `${CASE_COMMENT_SAVED_OBJECT}.references`, diff --git a/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts b/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts index dd6ac6350d6e3..e42e24e4b47d4 100644 --- a/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts +++ b/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts @@ -240,7 +240,7 @@ export class ClusterClientAdapter { +): maybeDocument is estypes.MgetHit { return '_id' in maybeDocument && '_source' in maybeDocument; } -export type ESAgentDocumentResult = estypes.MultiGetHit; +export type ESAgentDocumentResult = estypes.MgetHit; export async function getAgentDocuments( esClient: ElasticsearchClient, agentIds: string[] diff --git a/x-pack/plugins/fleet/server/services/agents/helpers.ts b/x-pack/plugins/fleet/server/services/agents/helpers.ts index c4273a57ddffd..822a2a9df98d5 100644 --- a/x-pack/plugins/fleet/server/services/agents/helpers.ts +++ b/x-pack/plugins/fleet/server/services/agents/helpers.ts @@ -11,7 +11,7 @@ import type { SearchHit } from '../../../../../../typings/elasticsearch'; import type { Agent, AgentSOAttributes, FleetServerAgent } from '../../types'; type FleetServerAgentESResponse = - | estypes.MultiGetHit + | estypes.MgetHit | estypes.SearchResponse['hits']['hits'][0] | SearchHit; diff --git a/x-pack/plugins/fleet/server/services/agents/reassign.test.ts b/x-pack/plugins/fleet/server/services/agents/reassign.test.ts index 63085b7729c4b..a87432c639249 100644 --- a/x-pack/plugins/fleet/server/services/agents/reassign.test.ts +++ b/x-pack/plugins/fleet/server/services/agents/reassign.test.ts @@ -85,7 +85,7 @@ describe('reassignAgents (plural)', () => { // calls ES update with correct values const calledWith = esClient.bulk.mock.calls[0][0]; // only 1 are regular and bulk write two line per update - expect(calledWith.body.length).toBe(2); + expect(calledWith.body?.length).toBe(2); // @ts-expect-error expect(calledWith.body[0].update._id).toEqual(agentInRegularDoc._id); }); diff --git a/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts b/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts index 33f12dc52dc00..3621bc5025ab3 100644 --- a/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts +++ b/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts @@ -94,11 +94,11 @@ describe('unenrollAgents (plural)', () => { // calls ES update with correct values const calledWith = esClient.bulk.mock.calls[1][0]; const ids = calledWith?.body - .filter((i: any) => i.update !== undefined) + ?.filter((i: any) => i.update !== undefined) .map((i: any) => i.update._id); - const docs = calledWith?.body.filter((i: any) => i.doc).map((i: any) => i.doc); + const docs = calledWith?.body?.filter((i: any) => i.doc).map((i: any) => i.doc); expect(ids).toEqual(idsToUnenroll); - for (const doc of docs) { + for (const doc of docs!) { expect(doc).toHaveProperty('unenrollment_started_at'); } }); @@ -112,11 +112,11 @@ describe('unenrollAgents (plural)', () => { const onlyRegular = [agentInRegularDoc._id, agentInRegularDoc2._id]; const calledWith = esClient.bulk.mock.calls[1][0]; const ids = calledWith?.body - .filter((i: any) => i.update !== undefined) + ?.filter((i: any) => i.update !== undefined) .map((i: any) => i.update._id); - const docs = calledWith?.body.filter((i: any) => i.doc).map((i: any) => i.doc); + const docs = calledWith?.body?.filter((i: any) => i.doc).map((i: any) => i.doc); expect(ids).toEqual(onlyRegular); - for (const doc of docs) { + for (const doc of docs!) { expect(doc).toHaveProperty('unenrollment_started_at'); } }); @@ -150,11 +150,11 @@ describe('unenrollAgents (plural)', () => { const onlyRegular = [agentInRegularDoc._id, agentInRegularDoc2._id]; const calledWith = esClient.bulk.mock.calls[0][0]; const ids = calledWith?.body - .filter((i: any) => i.update !== undefined) + ?.filter((i: any) => i.update !== undefined) .map((i: any) => i.update._id); - const docs = calledWith?.body.filter((i: any) => i.doc).map((i: any) => i.doc); + const docs = calledWith?.body?.filter((i: any) => i.doc).map((i: any) => i.doc); expect(ids).toEqual(onlyRegular); - for (const doc of docs) { + for (const doc of docs!) { expect(doc).toHaveProperty('unenrolled_at'); } }); @@ -167,11 +167,11 @@ describe('unenrollAgents (plural)', () => { // calls ES update with correct values const calledWith = esClient.bulk.mock.calls[1][0]; const ids = calledWith?.body - .filter((i: any) => i.update !== undefined) + ?.filter((i: any) => i.update !== undefined) .map((i: any) => i.update._id); - const docs = calledWith?.body.filter((i: any) => i.doc).map((i: any) => i.doc); + const docs = calledWith?.body?.filter((i: any) => i.doc).map((i: any) => i.doc); expect(ids).toEqual(idsToUnenroll); - for (const doc of docs) { + for (const doc of docs!) { expect(doc).toHaveProperty('unenrollment_started_at'); } }); @@ -205,11 +205,11 @@ describe('unenrollAgents (plural)', () => { // calls ES update with correct values const calledWith = esClient.bulk.mock.calls[0][0]; const ids = calledWith?.body - .filter((i: any) => i.update !== undefined) + ?.filter((i: any) => i.update !== undefined) .map((i: any) => i.update._id); - const docs = calledWith?.body.filter((i: any) => i.doc).map((i: any) => i.doc); + const docs = calledWith?.body?.filter((i: any) => i.doc).map((i: any) => i.doc); expect(ids).toEqual(idsToUnenroll); - for (const doc of docs) { + for (const doc of docs!) { expect(doc).toHaveProperty('unenrolled_at'); } }); diff --git a/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts b/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts index 511a0abecbc18..f9aab997f063c 100644 --- a/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts +++ b/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts @@ -197,7 +197,6 @@ export async function generateEnrollmentAPIKey( .createApiKey({ body: { name, - // @ts-expect-error Metadata in api keys metadata: { managed_by: 'fleet', managed: true, diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts index 8c58238588b2f..552e486552a78 100644 --- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts +++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts @@ -142,6 +142,7 @@ describe('EPM install', () => { it('tests installPackage remove the aliases property if the property existed', async () => { const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser; + // @ts-expect-error not full interface esClient.indices.getIndexTemplate.mockImplementation(() => elasticsearchServiceMock.createSuccessTransportRequestPromise({ index_templates: [ diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts index 9e8277eb6171f..d202dab54f5bd 100644 --- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts +++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts @@ -183,6 +183,7 @@ function putComponentTemplate( }; return { + // @ts-expect-error body expected to be ClusterPutComponentTemplateRequest clusterPromise: esClient.cluster.putComponentTemplate(esClientParams, { ignore: [404] }), name, }; diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts index 5dd2755390ecb..07d0df021c827 100644 --- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts +++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts @@ -527,7 +527,6 @@ const updateExistingDataStream = async ({ await esClient.indices.putMapping({ index: dataStreamName, body: mappings, - // @ts-expect-error @elastic/elasticsearch doesn't declare it on PutMappingRequest write_index_only: true, }); // if update fails, rollover data stream @@ -549,7 +548,7 @@ const updateExistingDataStream = async ({ try { await esClient.indices.putSettings({ index: dataStreamName, - body: { index: { default_pipeline: settings.index.default_pipeline } }, + body: { settings: { default_pipeline: settings.index.default_pipeline } }, }); } catch (err) { throw new Error(`could not update index template settings for ${dataStreamName}`); diff --git a/x-pack/plugins/index_lifecycle_management/server/routes/api/index/register_add_policy_route.ts b/x-pack/plugins/index_lifecycle_management/server/routes/api/index/register_add_policy_route.ts index 77f14decc5642..a18459d5d21b9 100644 --- a/x-pack/plugins/index_lifecycle_management/server/routes/api/index/register_add_policy_route.ts +++ b/x-pack/plugins/index_lifecycle_management/server/routes/api/index/register_add_policy_route.ts @@ -24,7 +24,6 @@ async function addLifecyclePolicy( }, }; - // @ts-expect-error @elastic/elasticsearch UpdateIndexSettingsRequest does not support index property return client.indices.putSettings({ index: indexName, body }); } diff --git a/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_add_policy_route.ts b/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_add_policy_route.ts index 4d467a807109a..823b36e63a873 100644 --- a/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_add_policy_route.ts +++ b/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_add_policy_route.ts @@ -80,6 +80,7 @@ async function updateIndexTemplate( if (isLegacy) { return client.indices.putTemplate({ name: templateName, body: indexTemplate }); } + // @ts-expect-error Type 'IndexSettings' is not assignable to type 'IndicesIndexSettings'. return client.indices.putIndexTemplate({ name: templateName, body: indexTemplate }); } diff --git a/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts b/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts index 77c7947ce22c3..ee831d9a98eb9 100644 --- a/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts +++ b/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts @@ -22,7 +22,7 @@ export interface ResolvedLogSourceConfiguration { tiebreakerField: string; messageField: string[]; fields: IndexPattern['fields']; - runtimeMappings: estypes.RuntimeFields; + runtimeMappings: estypes.MappingRuntimeFields; columns: LogSourceColumnConfiguration[]; } @@ -103,12 +103,12 @@ const resolveKibanaIndexPatternReference = async ( }; // this might take other sources of runtime fields into account in the future -const resolveRuntimeMappings = (indexPattern: IndexPattern): estypes.RuntimeFields => { +const resolveRuntimeMappings = (indexPattern: IndexPattern): estypes.MappingRuntimeFields => { const { runtimeFields } = indexPattern.getComputedFields(); const runtimeMappingsFromIndexPattern = (Object.entries(runtimeFields) as ObjectEntries< typeof runtimeFields - >).reduce( + >).reduce( (accumulatedMappings, [runtimeFieldName, runtimeFieldSpec]) => ({ ...accumulatedMappings, [runtimeFieldName]: { diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.test.tsx b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.test.tsx index caf8e32814fe5..2df741b746640 100644 --- a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.test.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.test.tsx @@ -54,6 +54,8 @@ describe('ExpressionChart', () => { metricAlias: 'metricbeat-*', inventoryDefaultView: 'host', metricsExplorerDefaultView: 'host', + + // @ts-expect-error not full interface fields: { timestamp: '@timestamp', container: 'container.id', diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts index 9eadc3035588d..9de6e574ecb5b 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts @@ -19,7 +19,7 @@ interface RequestArgs { timestampField: string; startTime: number; endTime: number; - runtimeMappings: estypes.RuntimeFields; + runtimeMappings: estypes.MappingRuntimeFields; } export const callValidateDatasetsAPI = async (requestArgs: RequestArgs, fetch: HttpHandler) => { diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts index f9eb7609e00f3..a211fecc807fa 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts @@ -20,7 +20,7 @@ import { decodeOrThrow } from '../../../../../common/runtime_types'; interface RequestArgs { indices: string[]; fields: ValidationIndicesFieldSpecification[]; - runtimeMappings: estypes.RuntimeFields; + runtimeMappings: estypes.MappingRuntimeFields; } export const callValidateIndicesAPI = async (requestArgs: RequestArgs, fetch: HttpHandler) => { diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts index 36371b080ee45..4ae99b95cfff8 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts @@ -47,7 +47,7 @@ export interface ModuleDescriptor { validateSetupIndices: ( indices: string[], timestampField: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, fetch: HttpHandler ) => Promise; validateSetupDatasets: ( @@ -55,7 +55,7 @@ export interface ModuleDescriptor { timestampField: string, startTime: number, endTime: number, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, fetch: HttpHandler ) => Promise; } @@ -65,5 +65,5 @@ export interface ModuleSourceConfiguration { sourceId: string; spaceId: string; timestampField: string; - runtimeMappings: estypes.RuntimeFields; + runtimeMappings: estypes.MappingRuntimeFields; } diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts index 981b7b496b435..af2bd1802042a 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts @@ -136,7 +136,7 @@ const cleanUpModule = async (spaceId: string, sourceId: string, fetch: HttpHandl const validateSetupIndices = async ( indices: string[], timestampField: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, fetch: HttpHandler ) => { return await callValidateIndicesAPI( @@ -167,7 +167,7 @@ const validateSetupDatasets = async ( timestampField: string, startTime: number, endTime: number, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, fetch: HttpHandler ) => { return await callValidateDatasetsAPI( diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx index a2ad5cd4f56c4..86e8e75dc3d41 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx @@ -26,7 +26,7 @@ export const useLogEntryCategoriesModule = ({ sourceId: string; spaceId: string; timestampField: string; - runtimeMappings: estypes.RuntimeFields; + runtimeMappings: estypes.MappingRuntimeFields; }) => { const sourceConfiguration: ModuleSourceConfiguration = useMemo( () => ({ diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts index 345f221f11c1f..9704afd80e9ea 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts @@ -128,7 +128,7 @@ const cleanUpModule = async (spaceId: string, sourceId: string, fetch: HttpHandl const validateSetupIndices = async ( indices: string[], timestampField: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, fetch: HttpHandler ) => { return await callValidateIndicesAPI( @@ -155,7 +155,7 @@ const validateSetupDatasets = async ( timestampField: string, startTime: number, endTime: number, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, fetch: HttpHandler ) => { return await callValidateDatasetsAPI( diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx index b451cad1c8753..0df5d9b446dbe 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx @@ -25,7 +25,7 @@ export const useLogEntryRateModule = ({ sourceId: string; spaceId: string; timestampField: string; - runtimeMappings: estypes.RuntimeFields; + runtimeMappings: estypes.MappingRuntimeFields; }) => { const sourceConfiguration: ModuleSourceConfiguration = useMemo( () => ({ diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_uptime_link.test.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_uptime_link.test.ts index dbe45a387891c..1e80545756a4c 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_uptime_link.test.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_uptime_link.test.ts @@ -10,6 +10,7 @@ import { InfraWaffleMapOptions, InfraFormatterType } from '../../../../lib/lib'; import { SnapshotMetricType } from '../../../../../common/inventory_models/types'; const options: InfraWaffleMapOptions = { + // @ts-expect-error not full interface fields: { container: 'container.id', pod: 'kubernetes.pod.uid', diff --git a/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts index dab36a9cb131d..cce1ab51c484a 100644 --- a/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts @@ -161,7 +161,7 @@ export class KibanaFramework { apiResult = elasticsearch.client.asCurrentUser.msearch({ ...params, ...frozenIndicesParams, - } as estypes.MultiSearchRequest); + } as estypes.MsearchRequest); break; case 'fieldCaps': apiResult = elasticsearch.client.asCurrentUser.fieldCaps({ diff --git a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts index 1c1edb3ea8328..ffabd7ba65f03 100644 --- a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts +++ b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts @@ -24,7 +24,7 @@ import { GroupedSearchQueryResponse, } from '../../../../common/alerting/logs/log_threshold/types'; import { alertsMock } from '../../../../../alerting/server/mocks'; -import { estypes } from '@elastic/elasticsearch'; +import type { estypes } from '@elastic/elasticsearch'; // Mocks // const numericField = { @@ -70,7 +70,7 @@ const baseAlertParams: Pick = { const TIMESTAMP_FIELD = '@timestamp'; const FILEBEAT_INDEX = 'filebeat-*'; -const runtimeMappings: estypes.RuntimeFields = { +const runtimeMappings: estypes.MappingRuntimeFields = { runtime_field: { type: 'keyword', script: { diff --git a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts index 3e910e5dfbf46..a537801202217 100644 --- a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts @@ -113,7 +113,7 @@ async function executeAlert( alertParams: CountAlertParams, timestampField: string, indexPattern: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, esClient: ElasticsearchClient, alertInstanceFactory: LogThresholdAlertServices['alertInstanceFactory'] ) { @@ -144,7 +144,7 @@ async function executeRatioAlert( alertParams: RatioAlertParams, timestampField: string, indexPattern: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, esClient: ElasticsearchClient, alertInstanceFactory: LogThresholdAlertServices['alertInstanceFactory'] ) { @@ -198,7 +198,7 @@ const getESQuery = ( alertParams: Omit & { criteria: CountCriteria }, timestampField: string, indexPattern: string, - runtimeMappings: estypes.RuntimeFields + runtimeMappings: estypes.MappingRuntimeFields ) => { return hasGroupBy(alertParams) ? getGroupedESQuery(alertParams, timestampField, indexPattern, runtimeMappings) @@ -433,7 +433,7 @@ export const getGroupedESQuery = ( params: Pick & { criteria: CountCriteria }, timestampField: string, index: string, - runtimeMappings: estypes.RuntimeFields + runtimeMappings: estypes.MappingRuntimeFields ): estypes.SearchRequest | undefined => { const { groupBy } = params; @@ -493,7 +493,7 @@ export const getUngroupedESQuery = ( params: Pick & { criteria: CountCriteria }, timestampField: string, index: string, - runtimeMappings: estypes.RuntimeFields + runtimeMappings: estypes.MappingRuntimeFields ): object => { const { rangeFilter, mustFilters, mustNotFilters } = buildFiltersFromCriteria( params, diff --git a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts index 387143ef9f9c4..ad8650bbb0fb6 100644 --- a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts +++ b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts @@ -277,7 +277,7 @@ export class InfraLogEntriesDomain { indexName: string, startTime: number, endTime: number, - runtimeMappings: estypes.RuntimeFields + runtimeMappings: estypes.MappingRuntimeFields ) { let datasetBuckets: LogEntryDatasetBucket[] = []; let afterLatestBatchKey: CompositeDatasetKey | undefined; diff --git a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts index 18e04aaf063d4..3431f3bfb0c8c 100644 --- a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts +++ b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts @@ -15,7 +15,7 @@ export const createLogEntryDatasetsQuery = ( timestampField: string, startTime: number, endTime: number, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, size: number, afterKey?: CompositeDatasetKey ) => ({ diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts index 716ab400c0123..3210f01116f76 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts @@ -387,7 +387,7 @@ export async function fetchLogEntryExamples( context: InfraPluginRequestHandlerContext & { infra: Required }, sourceId: string, indices: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, timestampField: string, tiebreakerField: string, startTime: number, diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts index ee2441d591134..7739f39cb5624 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts @@ -404,7 +404,7 @@ async function fetchTopLogEntryCategoryHistograms( async function fetchLogEntryCategoryExamples( requestContext: { core: { elasticsearch: { client: { asCurrentUser: ElasticsearchClient } } } }, indices: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, timestampField: string, tiebreakerField: string, startTime: number, diff --git a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts index f06dcd43a9156..0fef7dedfff0b 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts @@ -12,7 +12,7 @@ import { defaultRequestParameters } from './common'; export const createLogEntryCategoryExamplesQuery = ( indices: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, timestampField: string, tiebreakerField: string, startTime: number, diff --git a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts index 1e8cbe247dd50..ee339c9c6eb7e 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts @@ -13,7 +13,7 @@ import { defaultRequestParameters } from './common'; export const createLogEntryExamplesQuery = ( indices: string, - runtimeMappings: estypes.RuntimeFields, + runtimeMappings: estypes.MappingRuntimeFields, timestampField: string, tiebreakerField: string, startTime: number, diff --git a/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts b/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts index 950ecc98619ee..ef789c1b41349 100644 --- a/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts +++ b/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts @@ -43,7 +43,7 @@ export const initValidateLogAnalysisDatasetsRoute = ({ indexName, startTime, endTime, - runtimeMappings as estypes.RuntimeFields + runtimeMappings as estypes.MappingRuntimeFields ); return { diff --git a/x-pack/plugins/infra/server/routes/log_sources/configuration.ts b/x-pack/plugins/infra/server/routes/log_sources/configuration.ts index f0d7b18d91a5d..4d5c68ecfe8ee 100644 --- a/x-pack/plugins/infra/server/routes/log_sources/configuration.ts +++ b/x-pack/plugins/infra/server/routes/log_sources/configuration.ts @@ -85,11 +85,13 @@ export const initLogSourceConfigurationRoutes = ({ framework, sources }: InfraBa ? sources.updateSourceConfiguration( requestContext.core.savedObjects.client, sourceId, + // @ts-expect-error doesn't expect fields.container to be optional patchedSourceConfigurationProperties ) : sources.createSourceConfiguration( requestContext.core.savedObjects.client, sourceId, + // @ts-expect-error doesn't expect fields.container to be optional patchedSourceConfigurationProperties )); diff --git a/x-pack/plugins/infra/server/routes/metrics_sources/index.ts b/x-pack/plugins/infra/server/routes/metrics_sources/index.ts index 0123e4678697c..6e7877789a6d9 100644 --- a/x-pack/plugins/infra/server/routes/metrics_sources/index.ts +++ b/x-pack/plugins/infra/server/routes/metrics_sources/index.ts @@ -88,11 +88,13 @@ export const initMetricsSourceConfigurationRoutes = (libs: InfraBackendLibs) => ? sources.updateSourceConfiguration( requestContext.core.savedObjects.client, sourceId, + // @ts-expect-error doesn't expect fields.container to be optional patchedSourceConfigurationProperties ) : sources.createSourceConfiguration( requestContext.core.savedObjects.client, sourceId, + // @ts-expect-error doesn't expect fields.container to be optional patchedSourceConfigurationProperties )); diff --git a/x-pack/plugins/infra/server/services/log_entries/queries/log_entries.ts b/x-pack/plugins/infra/server/services/log_entries/queries/log_entries.ts index 6df17dbfd7bfd..9022195dce85d 100644 --- a/x-pack/plugins/infra/server/services/log_entries/queries/log_entries.ts +++ b/x-pack/plugins/infra/server/services/log_entries/queries/log_entries.ts @@ -29,7 +29,7 @@ export const createGetLogEntriesQuery = ( timestampField: string, tiebreakerField: string, fields: string[], - runtimeMappings?: estypes.RuntimeFields, + runtimeMappings?: estypes.MappingRuntimeFields, query?: JsonObject, highlightTerm?: string ): estypes.AsyncSearchSubmitRequest => { @@ -52,8 +52,8 @@ export const createGetLogEntriesQuery = ( ], }, }, - // @ts-expect-error @elastic/elasticsearch doesn't declare body.fields on AsyncSearchSubmitRequest fields, + // @ts-expect-error @elastic/elasticsearch doesn't declare "runtime_mappings" property runtime_mappings: runtimeMappings, _source: false, ...createSortClause(sortDirection, timestampField, tiebreakerField), diff --git a/x-pack/plugins/infra/server/services/log_entries/queries/log_entry.ts b/x-pack/plugins/infra/server/services/log_entries/queries/log_entry.ts index 6bef317d96ada..8da2f1d685db3 100644 --- a/x-pack/plugins/infra/server/services/log_entries/queries/log_entry.ts +++ b/x-pack/plugins/infra/server/services/log_entries/queries/log_entry.ts @@ -18,7 +18,7 @@ export const createGetLogEntryQuery = ( logEntryId: string, timestampField: string, tiebreakerField: string, - runtimeMappings?: estypes.RuntimeFields + runtimeMappings?: estypes.MappingRuntimeFields ): estypes.AsyncSearchSubmitRequest => ({ index: logEntryIndex, terminate_after: 1, @@ -31,8 +31,8 @@ export const createGetLogEntryQuery = ( values: [logEntryId], }, }, - // @ts-expect-error @elastic/elasticsearch doesn't declare body.fields on AsyncSearchSubmitRequest fields: ['*'], + // @ts-expect-error @elastic/elasticsearch doesn't declare "runtime_mappings" property runtime_mappings: runtimeMappings, sort: [{ [timestampField]: 'desc' }, { [tiebreakerField]: 'desc' }], _source: false, diff --git a/x-pack/plugins/ingest_pipelines/common/lib/pipeline_serialization.ts b/x-pack/plugins/ingest_pipelines/common/lib/pipeline_serialization.ts index 5360e2713aee1..d2669e7c0012b 100644 --- a/x-pack/plugins/ingest_pipelines/common/lib/pipeline_serialization.ts +++ b/x-pack/plugins/ingest_pipelines/common/lib/pipeline_serialization.ts @@ -5,10 +5,12 @@ * 2.0. */ -import { Pipeline as ESPipeline } from '@elastic/elasticsearch/api/types'; +import { estypes } from '@elastic/elasticsearch'; import { Pipeline, Processor } from '../types'; -export function deserializePipelines(pipelinesByName: { [key: string]: ESPipeline }): Pipeline[] { +export function deserializePipelines(pipelinesByName: { + [key: string]: estypes.IngestPipeline; +}): Pipeline[] { const pipelineNames: string[] = Object.keys(pipelinesByName); const deserializedPipelines = pipelineNames.map((name: string) => { diff --git a/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts b/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts index f697a38e21561..c133b9237102a 100644 --- a/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts +++ b/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { SimulatePipelineDocument } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema } from '@kbn/config-schema'; import { API_BASE_PATH } from '../../../common/constants'; @@ -38,7 +38,7 @@ export const registerSimulateRoute = ({ verbose, body: { pipeline, - docs: documents as SimulatePipelineDocument[], + docs: documents as estypes.IngestSimulatePipelineDocument[], }, }); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/mocks.ts b/x-pack/plugins/lens/public/indexpattern_datasource/mocks.ts index e71b26b9d4cd9..4545e42b2ff99 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/mocks.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/mocks.ts @@ -71,7 +71,7 @@ export const createMockedIndexPatternWithoutType = ( searchable: true, aggregatable: true, scripted: true, - lang: 'painless', + lang: 'painless' as const, script: '1234', }, ].filter(({ type }) => type !== typeToFilter); @@ -145,7 +145,7 @@ export const createMockedIndexPattern = (): IndexPattern => { searchable: true, aggregatable: true, scripted: true, - lang: 'painless', + lang: 'painless' as const, script: '1234', }, ]; @@ -183,7 +183,7 @@ export const createMockedRestrictedIndexPattern = () => { searchable: true, scripted: true, esTypes: ['keyword'], - lang: 'painless', + lang: 'painless' as const, script: '1234', }, ]; diff --git a/x-pack/plugins/lens/server/routes/existing_fields.test.ts b/x-pack/plugins/lens/server/routes/existing_fields.test.ts index 57d8ebf678d61..703b946149e26 100644 --- a/x-pack/plugins/lens/server/routes/existing_fields.test.ts +++ b/x-pack/plugins/lens/server/routes/existing_fields.test.ts @@ -79,7 +79,7 @@ describe('existingFields', () => { const result = existingFields( [ { - // @ts-expect-error _mymeta is not defined on estypes.Hit + // @ts-expect-error _mymeta is not defined on estypes.SearchHit _mymeta: 'abc', ...searchResults({ bar: ['scriptvalue'] }), }, diff --git a/x-pack/plugins/lens/server/routes/existing_fields.ts b/x-pack/plugins/lens/server/routes/existing_fields.ts index d775113d83ff7..f35b0a7f23179 100644 --- a/x-pack/plugins/lens/server/routes/existing_fields.ts +++ b/x-pack/plugins/lens/server/routes/existing_fields.ts @@ -28,7 +28,7 @@ export interface Field { name: string; isScript: boolean; isMeta: boolean; - lang?: string; + lang?: estypes.ScriptLanguage; script?: string; runtimeField?: RuntimeField; } @@ -201,10 +201,9 @@ async function fetchIndexPatternStats({ _source: false, runtime_mappings: runtimeFields.reduce((acc, field) => { if (!field.runtimeField) return acc; - // @ts-expect-error @elastic/elasticsearch StoredScript.language is required acc[field.name] = field.runtimeField; return acc; - }, {} as Record), + }, {} as Record), script_fields: scriptedFields.reduce((acc, field) => { acc[field.name] = { script: { @@ -233,7 +232,7 @@ async function fetchIndexPatternStats({ /** * Exported only for unit tests. */ -export function existingFields(docs: estypes.Hit[], fields: Field[]): string[] { +export function existingFields(docs: estypes.SearchHit[], fields: Field[]): string[] { const missingFields = new Set(fields); for (const doc of docs) { diff --git a/x-pack/plugins/lens/server/routes/field_stats.ts b/x-pack/plugins/lens/server/routes/field_stats.ts index 6b7e197a4d561..ef1043ddd3583 100644 --- a/x-pack/plugins/lens/server/routes/field_stats.ts +++ b/x-pack/plugins/lens/server/routes/field_stats.ts @@ -79,14 +79,13 @@ export async function initFieldsRoute(setup: CoreSetup) { }, }; - const search = async (aggs: Record) => { + const search = async (aggs: Record) => { const { body: result } = await requestClient.search({ index: indexPattern.title, track_total_hits: true, body: { query, aggs, - // @ts-expect-error @elastic/elasticsearch StoredScript.language is required runtime_mappings: field.runtimeField ? { [fieldName]: field.runtimeField } : {}, }, size: 0, @@ -136,7 +135,9 @@ export async function initFieldsRoute(setup: CoreSetup) { } export async function getNumberHistogram( - aggSearchWithBody: (aggs: Record) => Promise, + aggSearchWithBody: ( + aggs: Record + ) => Promise, field: IFieldType, useTopHits = true ): Promise { @@ -245,7 +246,7 @@ export async function getNumberHistogram( } export async function getStringSamples( - aggSearchWithBody: (aggs: Record) => unknown, + aggSearchWithBody: (aggs: Record) => unknown, field: IFieldType, size = 10 ): Promise { @@ -285,7 +286,7 @@ export async function getStringSamples( // This one is not sampled so that it returns the full date range export async function getDateHistogram( - aggSearchWithBody: (aggs: Record) => unknown, + aggSearchWithBody: (aggs: Record) => unknown, field: IFieldType, range: { fromDate: string; toDate: string } ): Promise { @@ -332,7 +333,7 @@ function getFieldRef(field: IFieldType) { return field.scripted ? { script: { - lang: field.lang as string, + lang: field.lang!, source: field.script as string, }, } diff --git a/x-pack/plugins/lists/server/services/items/find_list_item.ts b/x-pack/plugins/lists/server/services/items/find_list_item.ts index 803cc34ed2a12..29bfdf8bf1d13 100644 --- a/x-pack/plugins/lists/server/services/items/find_list_item.ts +++ b/x-pack/plugins/lists/server/services/items/find_list_item.ts @@ -76,7 +76,7 @@ export const findListItem = async ({ const { body: respose } = await esClient.count({ body: { - // @ts-expect-error GetQueryFilterReturn is not assignable to QueryContainer + // @ts-expect-error GetQueryFilterReturn is not assignable to QueryDslQueryContainer query, }, ignore_unavailable: true, @@ -89,7 +89,7 @@ export const findListItem = async ({ // to explicitly define the type . const { body: response } = await esClient.search({ body: { - // @ts-expect-error GetQueryFilterReturn is not assignable to QueryContainer + // @ts-expect-error GetQueryFilterReturn is not assignable to QueryDslQueryContainer query, search_after: scroll.searchAfter, sort: getSortWithTieBreaker({ sortField, sortOrder }), diff --git a/x-pack/plugins/lists/server/services/lists/find_list.ts b/x-pack/plugins/lists/server/services/lists/find_list.ts index 1c7a5fe60b995..ae28428d80a5c 100644 --- a/x-pack/plugins/lists/server/services/lists/find_list.ts +++ b/x-pack/plugins/lists/server/services/lists/find_list.ts @@ -65,7 +65,7 @@ export const findList = async ({ const { body: totalCount } = await esClient.count({ body: { - // @ts-expect-error GetQueryFilterReturn is not compatible with QueryContainer + // @ts-expect-error GetQueryFilterReturn is not compatible with QueryDslQueryContainer query, }, ignore_unavailable: true, @@ -78,7 +78,7 @@ export const findList = async ({ // to explicitly define the type . const { body: response } = await esClient.search({ body: { - // @ts-expect-error GetQueryFilterReturn is not compatible with QueryContainer + // @ts-expect-error GetQueryFilterReturn is not compatible with QueryDslQueryContainer query, search_after: scroll.searchAfter, sort: getSortWithTieBreaker({ sortField, sortOrder }), diff --git a/x-pack/plugins/lists/server/services/utils/get_search_after_scroll.ts b/x-pack/plugins/lists/server/services/utils/get_search_after_scroll.ts index 4ddd3f1c73315..e34b3080dd33b 100644 --- a/x-pack/plugins/lists/server/services/utils/get_search_after_scroll.ts +++ b/x-pack/plugins/lists/server/services/utils/get_search_after_scroll.ts @@ -46,7 +46,7 @@ export const getSearchAfterScroll = async ({ const { body: response } = await esClient.search>({ body: { _source: getSourceWithTieBreaker({ sortField }), - // @ts-expect-error Filter is not assignale to QueryContainer + // @ts-expect-error Filter is not assignale to QueryDslQueryContainer query, search_after: newSearchAfter, sort: getSortWithTieBreaker({ sortField, sortOrder }), diff --git a/x-pack/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts b/x-pack/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts index dbcec20d3d8a8..8a513483f5b5e 100644 --- a/x-pack/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts +++ b/x-pack/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts @@ -13,7 +13,7 @@ export const getSortWithTieBreaker = ({ }: { sortField: SortFieldOrUndefined; sortOrder: SortOrderOrUndefined; -}): estypes.SortCombinations[] => { +}): estypes.SearchSortCombinations[] => { const ascOrDesc = sortOrder ?? ('asc' as const); if (sortField != null) { return [{ [sortField]: ascOrDesc, tie_breaker_id: 'asc' as const }]; diff --git a/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts b/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts index 585eeeb118110..79db56f9a7fe9 100644 --- a/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts +++ b/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts @@ -20,7 +20,7 @@ export interface TransformElasticToListItemOptions { } export interface TransformElasticHitToListItemOptions { - hits: Array>; + hits: Array>; type: Type; } diff --git a/x-pack/plugins/logstash/server/models/cluster/cluster.test.ts b/x-pack/plugins/logstash/server/models/cluster/cluster.test.ts index 1e1afc33394f3..10c1d1ba24ae0 100755 --- a/x-pack/plugins/logstash/server/models/cluster/cluster.test.ts +++ b/x-pack/plugins/logstash/server/models/cluster/cluster.test.ts @@ -13,7 +13,7 @@ describe('cluster', () => { describe('fromUpstreamJSON factory method', () => { const upstreamJSON = { cluster_uuid: 'S-S4NNZDRV-g9c-JrIhx6A', - } as estypes.RootNodeInfoResponse; + } as estypes.InfoResponse; it('returns correct Cluster instance', () => { const cluster = Cluster.fromUpstreamJSON(upstreamJSON); diff --git a/x-pack/plugins/logstash/server/models/cluster/cluster.ts b/x-pack/plugins/logstash/server/models/cluster/cluster.ts index 88789a2d29c89..2982284879c47 100755 --- a/x-pack/plugins/logstash/server/models/cluster/cluster.ts +++ b/x-pack/plugins/logstash/server/models/cluster/cluster.ts @@ -24,7 +24,7 @@ export class Cluster { } // generate Pipeline object from elasticsearch response - static fromUpstreamJSON(upstreamCluster: estypes.RootNodeInfoResponse) { + static fromUpstreamJSON(upstreamCluster: estypes.InfoResponse) { const uuid = upstreamCluster.cluster_uuid; return new Cluster({ uuid }); } diff --git a/x-pack/plugins/maps/server/mvt/get_tile.ts b/x-pack/plugins/maps/server/mvt/get_tile.ts index 95b8e043e0ce4..776d316440a56 100644 --- a/x-pack/plugins/maps/server/mvt/get_tile.ts +++ b/x-pack/plugins/maps/server/mvt/get_tile.ts @@ -218,7 +218,7 @@ export async function getTile({ // Todo: pass in epochMillies-fields const featureCollection = hitsToGeoJson( - // @ts-expect-error hitsToGeoJson should be refactored to accept estypes.Hit + // @ts-expect-error hitsToGeoJson should be refactored to accept estypes.SearchHit documentsResponse.rawResponse.hits.hits, (hit: Record) => { return flattenHit(geometryFieldName, hit); diff --git a/x-pack/plugins/metrics_entities/server/routes/post_transforms.ts b/x-pack/plugins/metrics_entities/server/routes/post_transforms.ts index d5b5648757e8b..f5a46ec04611d 100644 --- a/x-pack/plugins/metrics_entities/server/routes/post_transforms.ts +++ b/x-pack/plugins/metrics_entities/server/routes/post_transforms.ts @@ -37,9 +37,9 @@ export const postTransforms = (router: IRouter): void => { auto_start: autoStart = false, settings: { max_page_search_size: maxPageSearchSize = 500, - docs_per_second: docsPerSecond = null, + docs_per_second: docsPerSecond = undefined, } = { - docsPerSecond: null, + docsPerSecond: undefined, maxPageSearchSize: 500, }, frequency = '1m', diff --git a/x-pack/plugins/metrics_entities/server/services/install_transforms.ts b/x-pack/plugins/metrics_entities/server/services/install_transforms.ts index d0a81955ca184..eec4f8d555356 100644 --- a/x-pack/plugins/metrics_entities/server/services/install_transforms.ts +++ b/x-pack/plugins/metrics_entities/server/services/install_transforms.ts @@ -27,7 +27,7 @@ interface CreateTransformOptions { frequency: string; logger: Logger; query: object; - docsPerSecond: number | null; + docsPerSecond: number | undefined; maxPageSearchSize: number; sync: { time: { diff --git a/x-pack/plugins/metrics_entities/server/services/metrics_entities_client_types.ts b/x-pack/plugins/metrics_entities/server/services/metrics_entities_client_types.ts index 1ae9f0d7a2f53..def26c5342ef9 100644 --- a/x-pack/plugins/metrics_entities/server/services/metrics_entities_client_types.ts +++ b/x-pack/plugins/metrics_entities/server/services/metrics_entities_client_types.ts @@ -21,7 +21,7 @@ export interface PostTransformsOptions { autoStart: boolean; frequency: string; indices: string[]; - docsPerSecond: number | null; + docsPerSecond: number | undefined; maxPageSearchSize: number; prefix: string; query: object; diff --git a/x-pack/plugins/metrics_entities/server/services/post_transforms.ts b/x-pack/plugins/metrics_entities/server/services/post_transforms.ts index 1850047ae1e9d..f14f53d78f10e 100644 --- a/x-pack/plugins/metrics_entities/server/services/post_transforms.ts +++ b/x-pack/plugins/metrics_entities/server/services/post_transforms.ts @@ -20,7 +20,7 @@ interface PostTransformsOptions { autoStart: boolean; frequency: string; indices: string[]; - docsPerSecond: number | null; + docsPerSecond: number | undefined; kibanaVersion: string; maxPageSearchSize: number; query: object; diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed.ts index 440f4c6e55fb8..e1a3f6044587b 100644 --- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed.ts +++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed.ts @@ -9,15 +9,10 @@ import { estypes } from '@elastic/elasticsearch'; export type DatafeedId = string; -export type Datafeed = estypes.Datafeed; +export type Datafeed = estypes.MlDatafeed; -export type ChunkingConfig = estypes.ChunkingConfig; +export type ChunkingConfig = estypes.MlChunkingConfig; -export type Aggregation = Record; +export type Aggregation = Record; -// export type IndicesOptions = estypes.IndicesOptions; -export interface IndicesOptions { - allow_no_indices?: boolean; - expand_wildcards?: estypes.ExpandWildcards; - ignore_unavailable?: boolean; -} +export type IndicesOptions = estypes.MlDatafeedIndicesOptions; diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts index dd0d3a5001f84..4e23d97c0d145 100644 --- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts +++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts @@ -7,4 +7,4 @@ import { estypes } from '@elastic/elasticsearch'; -export type DatafeedStats = estypes.DatafeedStats; +export type DatafeedStats = estypes.MlDatafeedStats; diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts index 68544e7cb828f..2ef1d824180ad 100644 --- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts +++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts @@ -10,23 +10,23 @@ import { estypes } from '@elastic/elasticsearch'; export type JobId = string; export type BucketSpan = string; -export type Job = estypes.Job; +export type Job = estypes.MlJob; -export type AnalysisConfig = estypes.AnalysisConfig; +export type AnalysisConfig = estypes.MlAnalysisConfig; -export type Detector = estypes.Detector; +export type Detector = estypes.MlDetector; -export type AnalysisLimits = estypes.AnalysisLimits; +export type AnalysisLimits = estypes.MlAnalysisLimits; -export type DataDescription = estypes.DataDescription; +export type DataDescription = estypes.MlDataDescription; -export type ModelPlotConfig = estypes.ModelPlotConfig; +export type ModelPlotConfig = estypes.MlModelPlotConfig; -export type CustomRule = estypes.DetectionRule; +export type CustomRule = estypes.MlDetectionRule; export interface PerPartitionCategorization { enabled?: boolean; stop_on_warn?: boolean; } -export type CustomSettings = estypes.CustomSettings; +export type CustomSettings = estypes.MlCustomSettings; diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts index a53f1f2486699..5fc8b423a5ac2 100644 --- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts +++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts @@ -7,23 +7,14 @@ import { estypes } from '@elastic/elasticsearch'; -export type JobStats = estypes.JobStats & { - model_size_stats: ModelSizeStats; - timing_stats: TimingStats; -}; +export type JobStats = estypes.MlJobStats; -export type DataCounts = estypes.DataCounts; +export type DataCounts = estypes.MlDataCounts; -export type ModelSizeStats = estypes.ModelSizeStats & { - model_bytes_exceeded: number; - model_bytes_memory_limit: number; - peak_model_bytes?: number; -}; +export type ModelSizeStats = estypes.MlModelSizeStats; -export type TimingStats = estypes.TimingStats & { - total_bucket_processing_time_ms: number; -}; +export type TimingStats = estypes.MlTimingStats; -export type ForecastsStats = estypes.JobForecastStatistics; +export type ForecastsStats = estypes.MlJobForecastStatistics; -export type Node = estypes.DiscoveryNode; +export type Node = estypes.MlDiscoveryNode; diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/model_snapshot.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/model_snapshot.ts index f844c42f4ca6e..0bb2162994c37 100644 --- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/model_snapshot.ts +++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/model_snapshot.ts @@ -5,18 +5,6 @@ * 2.0. */ -import { JobId } from './job'; -import { ModelSizeStats } from './job_stats'; +import { estypes } from '@elastic/elasticsearch'; -export interface ModelSnapshot { - job_id: JobId; - min_version: string; - timestamp: number; - description: string; - snapshot_id: string; - snapshot_doc_count: number; - model_size_stats: ModelSizeStats; - latest_record_time_stamp: number; - latest_result_time_stamp: number; - retain: boolean; -} +export type ModelSnapshot = estypes.MlModelSnapshot; diff --git a/x-pack/plugins/ml/common/types/data_frame_analytics.ts b/x-pack/plugins/ml/common/types/data_frame_analytics.ts index ff5069e7d59ad..3305eeaaf4794 100644 --- a/x-pack/plugins/ml/common/types/data_frame_analytics.ts +++ b/x-pack/plugins/ml/common/types/data_frame_analytics.ts @@ -76,7 +76,7 @@ export interface DataFrameAnalyticsConfig { }; source: { index: IndexName | IndexName[]; - query?: estypes.QueryContainer; + query?: estypes.QueryDslQueryContainer; runtime_mappings?: RuntimeMappings; }; analysis: AnalysisConfig; diff --git a/x-pack/plugins/ml/common/types/es_client.ts b/x-pack/plugins/ml/common/types/es_client.ts index 249b3c150a082..67adda6b24c18 100644 --- a/x-pack/plugins/ml/common/types/es_client.ts +++ b/x-pack/plugins/ml/common/types/es_client.ts @@ -13,13 +13,15 @@ import type { JsonObject } from '../../../../../src/plugins/kibana_utils/common' import { isPopulatedObject } from '../util/object_utils'; -export function isMultiBucketAggregate(arg: unknown): arg is estypes.MultiBucketAggregate { +export function isMultiBucketAggregate( + arg: unknown +): arg is estypes.AggregationsMultiBucketAggregate { return isPopulatedObject(arg, ['buckets']); } export const ES_CLIENT_TOTAL_HITS_RELATION: Record< - Uppercase, - estypes.TotalHitsRelation + Uppercase, + estypes.SearchTotalHitsRelation > = { EQ: 'eq', GTE: 'gte', diff --git a/x-pack/plugins/ml/common/types/fields.ts b/x-pack/plugins/ml/common/types/fields.ts index cf017192353e9..33a4a94e539b8 100644 --- a/x-pack/plugins/ml/common/types/fields.ts +++ b/x-pack/plugins/ml/common/types/fields.ts @@ -28,7 +28,7 @@ export interface Field { aggregatable?: boolean; aggIds?: AggId[]; aggs?: Aggregation[]; - runtimeField?: estypes.RuntimeField; + runtimeField?: estypes.MappingRuntimeField; } export interface Aggregation { @@ -112,4 +112,4 @@ export interface AggCardinality { export type RollupFields = Record]>; -export type RuntimeMappings = estypes.RuntimeFields; +export type RuntimeMappings = estypes.MappingRuntimeFields; diff --git a/x-pack/plugins/ml/common/util/job_utils.ts b/x-pack/plugins/ml/common/util/job_utils.ts index e7608af553f60..2cb803af38579 100644 --- a/x-pack/plugins/ml/common/util/job_utils.ts +++ b/x-pack/plugins/ml/common/util/job_utils.ts @@ -78,7 +78,7 @@ export function isMappableJob(job: CombinedJob, detectorIndex: number): boolean * if composite is defined. * @param buckets */ -export function hasValidComposite(buckets: estypes.AggregationContainer) { +export function hasValidComposite(buckets: estypes.AggregationsAggregationContainer) { if ( isPopulatedObject(buckets, ['composite']) && isPopulatedObject(buckets.composite, ['sources']) && @@ -157,7 +157,7 @@ export function isSourceDataChartableForDetector(job: CombinedJob, detectorIndex } // if fieldName is an aggregated field under nested terms using bucket_script const aggregations = - getAggregations(aggs[aggBucketsName]) ?? {}; + getAggregations(aggs[aggBucketsName]) ?? {}; const foundField = findAggField(aggregations, dtr.field_name, false); if (foundField?.bucket_script !== undefined) { return false; diff --git a/x-pack/plugins/ml/common/util/runtime_field_utils.ts b/x-pack/plugins/ml/common/util/runtime_field_utils.ts index 7be2a3ec8c9e1..1fcf8e2e72b15 100644 --- a/x-pack/plugins/ml/common/util/runtime_field_utils.ts +++ b/x-pack/plugins/ml/common/util/runtime_field_utils.ts @@ -11,7 +11,7 @@ import type { RuntimeMappings } from '../types/fields'; type RuntimeType = typeof RUNTIME_FIELD_TYPES[number]; -export function isRuntimeField(arg: unknown): arg is estypes.RuntimeField { +export function isRuntimeField(arg: unknown): arg is estypes.MappingRuntimeField { return ( ((isPopulatedObject(arg, ['type']) && Object.keys(arg).length === 1) || (isPopulatedObject(arg, ['type', 'script']) && diff --git a/x-pack/plugins/ml/public/application/components/data_grid/common.ts b/x-pack/plugins/ml/public/application/components/data_grid/common.ts index 24a3cfb70d18d..a64594e86a757 100644 --- a/x-pack/plugins/ml/public/application/components/data_grid/common.ts +++ b/x-pack/plugins/ml/public/application/components/data_grid/common.ts @@ -181,7 +181,7 @@ export const getDataGridSchemasFromFieldTypes = (fieldTypes: FieldTypes, results export const NON_AGGREGATABLE = 'non-aggregatable'; export const getDataGridSchemaFromESFieldType = ( - fieldType: ES_FIELD_TYPES | undefined | estypes.RuntimeField['type'] + fieldType: ES_FIELD_TYPES | undefined | estypes.MappingRuntimeField['type'] ): string | undefined => { // Built-in values are ['boolean', 'currency', 'datetime', 'numeric', 'json'] // To fall back to the default string schema it needs to be undefined. diff --git a/x-pack/plugins/ml/public/application/components/data_grid/types.ts b/x-pack/plugins/ml/public/application/components/data_grid/types.ts index 865e09e72b40c..9dcd6abb432b3 100644 --- a/x-pack/plugins/ml/public/application/components/data_grid/types.ts +++ b/x-pack/plugins/ml/public/application/components/data_grid/types.ts @@ -27,7 +27,7 @@ export type DataGridItem = Record; // `undefined` is used to indicate a non-initialized state. export type ChartsVisible = boolean | undefined; -export type RowCountRelation = estypes.TotalHitsRelation | undefined; +export type RowCountRelation = estypes.SearchTotalHitsRelation | undefined; export type IndexPagination = Pick; diff --git a/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/chart_loader.ts b/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/chart_loader.ts index 15979751f40d6..a9217d884fd32 100644 --- a/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/chart_loader.ts +++ b/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/chart_loader.ts @@ -31,7 +31,6 @@ export function chartLoaderProvider(mlResultsService: MlResultsService) { job.data_counts.latest_record_timestamp, intervalMs, job.datafeed_config.runtime_mappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options job.datafeed_config.indices_options ); if (resp.error !== undefined) { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts index 88f403cdf0c44..920f56b376747 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts @@ -67,7 +67,7 @@ export const getIndexData = async ( setRowCount(typeof resp.hits.total === 'number' ? resp.hits.total : resp.hits.total.value); setRowCountRelation( typeof resp.hits.total === 'number' - ? ('eq' as estypes.TotalHitsRelation) + ? ('eq' as estypes.SearchTotalHitsRelation) : resp.hits.total.relation ); setTableItems( diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts index 79986e8ddb098..72853ec23fd36 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts @@ -18,7 +18,7 @@ export const CATEGORICAL_TYPES = new Set(['ip', 'keyword']); // Regression supports numeric fields. Classification supports categorical, numeric, and boolean. export const shouldAddAsDepVarOption = ( fieldId: string, - fieldType: ES_FIELD_TYPES | estypes.RuntimeField['type'], + fieldType: ES_FIELD_TYPES | estypes.MappingRuntimeField['type'], jobType: AnalyticsJobType ) => { if (fieldId === EVENT_RATE_FIELD_ID) return false; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts index f3b51acf093ad..ddf88ce79ab5b 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts @@ -45,7 +45,9 @@ interface MLEuiDataGridColumn extends EuiDataGridColumn { function getRuntimeFieldColumns(runtimeMappings: RuntimeMappings) { return Object.keys(runtimeMappings).map((id) => { const field = runtimeMappings[id]; - const schema = getDataGridSchemaFromESFieldType(field.type as estypes.RuntimeField['type']); + const schema = getDataGridSchemaFromESFieldType( + field.type as estypes.MappingRuntimeField['type'] + ); return { id, schema, isExpandable: schema !== 'boolean', isRuntimeFieldColumn: true }; }); } @@ -194,7 +196,7 @@ export const useIndexData = ( setRowCount(typeof resp.hits.total === 'number' ? resp.hits.total : resp.hits.total.value); setRowCountRelation( typeof resp.hits.total === 'number' - ? ('eq' as estypes.TotalHitsRelation) + ? ('eq' as estypes.SearchTotalHitsRelation) : resp.hits.total.relation ); setTableItems(docs); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts index 45b26226def8f..35847839b02a0 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts @@ -29,7 +29,7 @@ export interface RichDetector { byField: SplitField; overField: SplitField; partitionField: SplitField; - excludeFrequent: estypes.ExcludeFrequent | null; + excludeFrequent: estypes.MlExcludeFrequent | null; description: string | null; customRules: CustomRule[] | null; useNull: boolean | null; @@ -58,7 +58,7 @@ export class AdvancedJobCreator extends JobCreator { byField: SplitField, overField: SplitField, partitionField: SplitField, - excludeFrequent: estypes.ExcludeFrequent | null, + excludeFrequent: estypes.MlExcludeFrequent | null, description: string | null, useNull: boolean | null ) { @@ -87,7 +87,7 @@ export class AdvancedJobCreator extends JobCreator { byField: SplitField, overField: SplitField, partitionField: SplitField, - excludeFrequent: estypes.ExcludeFrequent | null, + excludeFrequent: estypes.MlExcludeFrequent | null, description: string | null, index: number, useNull: boolean | null @@ -120,7 +120,7 @@ export class AdvancedJobCreator extends JobCreator { byField: SplitField, overField: SplitField, partitionField: SplitField, - excludeFrequent: estypes.ExcludeFrequent | null, + excludeFrequent: estypes.MlExcludeFrequent | null, description: string | null, customRules: CustomRule[] | null, useNull: boolean | null @@ -193,7 +193,6 @@ export class AdvancedJobCreator extends JobCreator { timeFieldName: this.timeFieldName, query: this.query, runtimeMappings: this.datafeedConfig.runtime_mappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options indicesOptions: this.datafeedConfig.indices_options, }); this.setTimeRange(start.epoch, end.epoch); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts index fe0329851758c..d4a410bcda24c 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts @@ -226,6 +226,7 @@ export class JobCreator { } public get groups(): string[] { + // @ts-expect-error @elastic-elasticsearch FIXME groups is optional return this._job_config.groups; } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/filter_runtime_mappings.test.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/filter_runtime_mappings.test.ts index 7f1ee2349c2c1..f81362ad83288 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/filter_runtime_mappings.test.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/filter_runtime_mappings.test.ts @@ -54,19 +54,19 @@ function getDatafeed(): Datafeed { runtime_mappings: { responsetime_big: { type: 'double', - // @ts-expect-error @elastic/elasticsearch StoredScript.language is required script: { source: "emit(doc['responsetime'].value * 100.0)", }, }, airline_lower: { type: 'keyword', - // @ts-expect-error @elastic/elasticsearch StoredScript.language is required script: { source: "emit(doc['airline'].value.toLowerCase())", }, }, }, + chunking_config: { mode: 'auto' }, + delayed_data_check_config: { enabled: false }, }; } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/categorization_examples_loader.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/categorization_examples_loader.ts index b51cd9b99792b..641eda3dbf3e8 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/categorization_examples_loader.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/categorization_examples_loader.ts @@ -52,7 +52,6 @@ export class CategorizationExamplesLoader { this._jobCreator.end, analyzer, this._jobCreator.runtimeMappings ?? undefined, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options this._jobCreator.datafeedConfig.indices_options ); return resp; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts index 6d5fa26af7024..a01581f7526c5 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts @@ -257,7 +257,6 @@ export class ResultsLoader { const fieldValues = await this._chartLoader.loadFieldExampleValues( this._jobCreator.splitField, this._jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options this._jobCreator.datafeedConfig.indices_options ); if (fieldValues.length > 0) { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx index 2b1a35bcb8c46..237af335ffa51 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx @@ -173,7 +173,7 @@ export const AdvancedDetectorModal: FC = ({ partitionField, excludeFrequent: excludeFrequentOption.label !== '' - ? (excludeFrequentOption.label as estypes.ExcludeFrequent) + ? (excludeFrequentOption.label as estypes.MlExcludeFrequent) : null, description: descriptionOption !== '' ? descriptionOption : null, customRules: null, @@ -349,7 +349,7 @@ function createFieldOption(field: Field | null): EuiComboBoxOptionOption { } function createExcludeFrequentOption( - excludeFrequent: estypes.ExcludeFrequent | null + excludeFrequent: estypes.MlExcludeFrequent | null ): EuiComboBoxOptionOption { if (excludeFrequent === null) { return emptyOption; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts index 113bde6fbf93d..85083146c1378 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts @@ -42,7 +42,6 @@ export function useEstimateBucketSpan() { splitField: undefined, timeField: mlContext.currentIndexPattern.timeFieldName, runtimeMappings: jobCreator.runtimeMappings ?? undefined, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options indicesOptions: jobCreator.datafeedConfig.indices_options, }; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/metric_selection_summary.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/metric_selection_summary.tsx index c553da93a4bc0..9d84854245216 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/metric_selection_summary.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/metric_selection_summary.tsx @@ -56,7 +56,6 @@ export const CategorizationDetectorsSummary: FC = () => { jobCreator.end, chartInterval.getInterval().asMilliseconds(), jobCreator.runtimeMappings ?? undefined, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); setEventRateChartData(resp); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx index 6cbf96fcb04e8..58252feca4b53 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx @@ -114,7 +114,6 @@ export const MultiMetricDetectors: FC = ({ setIsValid }) => { .loadFieldExampleValues( splitField, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ) .then(setFieldValues) @@ -146,7 +145,6 @@ export const MultiMetricDetectors: FC = ({ setIsValid }) => { fieldValues.length > 0 ? fieldValues[0] : null, cs.intervalMs, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); setLineChartsData(resp); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection_summary.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection_summary.tsx index dc76fc0178112..a4c344d16482b 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection_summary.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection_summary.tsx @@ -44,7 +44,6 @@ export const MultiMetricDetectorsSummary: FC = () => { const tempFieldValues = await chartLoader.loadFieldExampleValues( jobCreator.splitField, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); setFieldValues(tempFieldValues); @@ -79,7 +78,6 @@ export const MultiMetricDetectorsSummary: FC = () => { fieldValues.length > 0 ? fieldValues[0] : null, cs.intervalMs, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); setLineChartsData(resp); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx index c5efd4b226d5c..1be487d5b7eec 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx @@ -161,7 +161,6 @@ export const PopulationDetectors: FC = ({ setIsValid }) => { jobCreator.splitField, cs.intervalMs, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); @@ -185,7 +184,6 @@ export const PopulationDetectors: FC = ({ setIsValid }) => { fields: await chartLoader.loadFieldExampleValues( field, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ), }; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx index 31b436944a5b0..55a9d37d1115c 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx @@ -79,7 +79,6 @@ export const PopulationDetectorsSummary: FC = () => { jobCreator.splitField, cs.intervalMs, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); @@ -103,7 +102,6 @@ export const PopulationDetectorsSummary: FC = () => { fields: await chartLoader.loadFieldExampleValues( field, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ), }; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection.tsx index b2a97d8e0589a..d41234bbedd81 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection.tsx @@ -94,7 +94,6 @@ export const SingleMetricDetectors: FC = ({ setIsValid }) => { null, cs.intervalMs, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); if (resp[DTR_IDX] !== undefined) { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection_summary.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection_summary.tsx index 5e64f4ef18984..ced94b2095f72 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection_summary.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/single_metric_view/metric_selection_summary.tsx @@ -60,7 +60,6 @@ export const SingleMetricDetectorsSummary: FC = () => { null, cs.intervalMs, jobCreator.runtimeMappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); if (resp[DTR_IDX] !== undefined) { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/time_range_step/time_range.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/time_range_step/time_range.tsx index 7e7b919f677ab..66c92d5c80851 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/time_range_step/time_range.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/time_range_step/time_range.tsx @@ -49,7 +49,6 @@ export const TimeRangeStep: FC = ({ setCurrentStep, isCurrentStep }) jobCreator.end, chartInterval.getInterval().asMilliseconds(), jobCreator.runtimeMappings ?? undefined, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options jobCreator.datafeedConfig.indices_options ); setEventRateChartData(resp); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx index 6ce808ed36b15..d2780691e551d 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx @@ -51,9 +51,9 @@ export const EditJob: FC = ({ job, jobOverride, existingGroupIds, ); const handleValidation = () => { - const jobGroupsValidationResult = formState.jobGroups - .map((group) => groupValidator(group)) - .filter((result) => result !== null); + const jobGroupsValidationResult = + formState.jobGroups ?? + [].map((group) => groupValidator(group)).filter((result) => result !== null); setValidationResult({ jobGroups: jobGroupsValidationResult, @@ -92,7 +92,7 @@ export const EditJob: FC = ({ job, jobOverride, existingGroupIds, { setFormState({ jobGroups: value, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx index 311e291cf2519..b97c16e02d900 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx @@ -87,11 +87,12 @@ export const JobItem: FC = memo( - {jobGroups.map((group) => ( - - {group} - - ))} + {jobGroups ?? + [].map((group) => ( + + {group} + + ))} {setupResult && setupResult.error && ( diff --git a/x-pack/plugins/ml/server/lib/ml_client/ml_client.ts b/x-pack/plugins/ml/server/lib/ml_client/ml_client.ts index 6e76a536feb25..0a9c76893dd0b 100644 --- a/x-pack/plugins/ml/server/lib/ml_client/ml_client.ts +++ b/x-pack/plugins/ml/server/lib/ml_client/ml_client.ts @@ -242,6 +242,7 @@ export function getMlClient( }>(...p); const jobs = await jobSavedObjectService.filterJobsForSpace( 'data-frame-analytics', + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete body.data_frame_analytics, 'id' ); @@ -494,12 +495,13 @@ function getDFAJobIdsFromRequest([params]: MlGetDFAParams): string[] { } function getADJobIdsFromRequest([params]: MlGetADParams): string[] { - const ids = params?.job_id?.split(','); + const ids = typeof params?.job_id === 'string' ? params?.job_id.split(',') : params?.job_id; return ids || []; } function getDatafeedIdsFromRequest([params]: MlGetDatafeedParams): string[] { - const ids = params?.datafeed_id?.split(','); + const ids = + typeof params?.datafeed_id === 'string' ? params?.datafeed_id.split(',') : params?.datafeed_id; return ids || []; } diff --git a/x-pack/plugins/ml/server/lib/query_utils.ts b/x-pack/plugins/ml/server/lib/query_utils.ts index dd4dc01498dbb..e801130643345 100644 --- a/x-pack/plugins/ml/server/lib/query_utils.ts +++ b/x-pack/plugins/ml/server/lib/query_utils.ts @@ -44,7 +44,7 @@ export function buildBaseFilterCriteria( export function buildSamplerAggregation( aggs: any, samplerShardSize: number -): Record { +): Record { if (samplerShardSize < 1) { return aggs; } diff --git a/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts b/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts index 458a34346bed9..791ba6d79ab5a 100644 --- a/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts +++ b/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts @@ -10,7 +10,7 @@ import { difference } from 'lodash'; import { EventManager } from './event_manager'; import type { MlClient } from '../../lib/ml_client'; -type ScheduledEvent = estypes.ScheduledEvent; +type ScheduledEvent = estypes.MlCalendarEvent; interface BasicCalendar { job_ids: string[]; diff --git a/x-pack/plugins/ml/server/models/calendar/event_manager.ts b/x-pack/plugins/ml/server/models/calendar/event_manager.ts index c870d67524135..d30297eab5c15 100644 --- a/x-pack/plugins/ml/server/models/calendar/event_manager.ts +++ b/x-pack/plugins/ml/server/models/calendar/event_manager.ts @@ -9,7 +9,7 @@ import { estypes } from '@elastic/elasticsearch'; import { GLOBAL_CALENDAR } from '../../../common/constants/calendars'; import type { MlClient } from '../../lib/ml_client'; -type ScheduledEvent = estypes.ScheduledEvent; +type ScheduledEvent = estypes.MlCalendarEvent; export class EventManager { private _mlClient: MlClient; diff --git a/x-pack/plugins/ml/server/models/data_frame_analytics/analytics_manager.ts b/x-pack/plugins/ml/server/models/data_frame_analytics/analytics_manager.ts index a9c1d95d933a9..41b8e6dfe96c4 100644 --- a/x-pack/plugins/ml/server/models/data_frame_analytics/analytics_manager.ts +++ b/x-pack/plugins/ml/server/models/data_frame_analytics/analytics_manager.ts @@ -67,6 +67,7 @@ export class AnalyticsManager { async setInferenceModels() { try { const models = await this.getAnalyticsModels(); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete this.inferenceModels = models; } catch (error) { // eslint-disable-next-line @@ -77,6 +78,7 @@ export class AnalyticsManager { async setJobStats() { try { const jobStats = await this.getAnalyticsStats(); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete this.jobStats = jobStats; } catch (error) { // eslint-disable-next-line @@ -133,8 +135,10 @@ export class AnalyticsManager { if (analyticsId !== undefined) { const jobStats = this.findJobStats(analyticsId); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete jobData = { ...jobData, stats: { ...jobStats } }; } else { + // @ts-expect-error @elastic-elasticsearch Data frame types incompletes jobData = jobData.map((job: any) => { const jobStats = this.findJobStats(job.id); return { ...job, stats: { ...jobStats } }; @@ -270,6 +274,7 @@ export class AnalyticsManager { // fetch model data and create model elements let data = await this.getAnalyticsModelData(modelId); const modelNodeId = `${data.model_id}-${JOB_MAP_NODE_TYPES.TRAINED_MODEL}`; + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete const sourceJobId = data?.metadata?.analytics_config?.id; let nextLinkId: string | undefined; let nextType: JobMapNodeTypes | undefined; @@ -288,17 +293,22 @@ export class AnalyticsManager { // fetch source job data and create elements if (sourceJobId !== undefined) { try { + // @ts-expect-error @elastic-elasticsearch Data frame types incompletes data = await this.getAnalyticsData(sourceJobId); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete nextLinkId = data?.source?.index[0]; nextType = JOB_MAP_NODE_TYPES.INDEX; + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete previousNodeId = `${data.id}-${JOB_MAP_NODE_TYPES.ANALYTICS}`; resultElements.push({ data: { id: previousNodeId, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete label: data.id, type: JOB_MAP_NODE_TYPES.ANALYTICS, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete analysisType: getAnalysisType(data?.analysis), }, }); @@ -332,16 +342,20 @@ export class AnalyticsManager { const modelElements = []; const details: any = {}; const data = await this.getAnalyticsData(jobId); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete const nextLinkId = data?.source?.index[0]; const nextType: JobMapNodeTypes = JOB_MAP_NODE_TYPES.INDEX; + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete const previousNodeId = `${data.id}-${JOB_MAP_NODE_TYPES.ANALYTICS}`; resultElements.push({ data: { id: previousNodeId, + // @ts-expect-error @elastic-elasticsearch Data frame types incompletes label: data.id, type: JOB_MAP_NODE_TYPES.ANALYTICS, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete analysisType: getAnalysisType(data?.analysis), isRoot: true, }, @@ -530,20 +544,27 @@ export class AnalyticsManager { const jobs = await this.getAnalyticsData(); const comparator = rootTransform !== undefined ? rootTransform : rootIndexPattern; + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete for (let i = 0; i < jobs.length; i++) { if ( + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete jobs[i]?.source?.index[0] === comparator && + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete this.isDuplicateElement(jobs[i].id, result.elements) === false ) { + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete const nodeId = `${jobs[i].id}-${JOB_MAP_NODE_TYPES.ANALYTICS}`; result.elements.push({ data: { id: nodeId, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete label: jobs[i].id, type: JOB_MAP_NODE_TYPES.ANALYTICS, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete analysisType: getAnalysisType(jobs[i]?.analysis), }, }); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete result.details[nodeId] = jobs[i]; const source = `${comparator}-${JOB_MAP_NODE_TYPES.INDEX}`; result.elements.push({ @@ -555,6 +576,7 @@ export class AnalyticsManager { }); // Get inference model for analytics job and create model node ({ modelElement, modelDetails, edgeElement } = this.getAnalyticsModelElements( + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete jobs[i].id )); if (isAnalyticsMapNodeElement(modelElement)) { @@ -590,10 +612,14 @@ export class AnalyticsManager { if (analyticsId !== undefined) { const jobData = await this.getAnalyticsData(analyticsId); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete const currentJobNodeId = `${jobData.id}-${JOB_MAP_NODE_TYPES.ANALYTICS}`; + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete rootIndex = Array.isArray(jobData?.dest?.index) - ? jobData?.dest?.index[0] - : jobData?.dest?.index; + ? // @ts-expect-error @elastic-elasticsearch Data frame types incomplete + jobData?.dest?.index[0] + : // @ts-expect-error @elastic-elasticsearch Data frame types incomplete + jobData?.dest?.index; rootIndexNodeId = `${rootIndex}-${JOB_MAP_NODE_TYPES.INDEX}`; // Fetch inference model for incoming job id and add node and edge @@ -632,21 +658,28 @@ export class AnalyticsManager { rootIndexNodeId = `${rootIndex}-${JOB_MAP_NODE_TYPES.INDEX}`; } + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete for (let i = 0; i < jobs.length; i++) { if ( + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete jobs[i]?.source?.index[0] === rootIndex && + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete this.isDuplicateElement(jobs[i].id, result.elements) === false ) { // Create node for associated job + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete const nodeId = `${jobs[i].id}-${JOB_MAP_NODE_TYPES.ANALYTICS}`; result.elements.push({ data: { id: nodeId, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete label: jobs[i].id, type: JOB_MAP_NODE_TYPES.ANALYTICS, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete analysisType: getAnalysisType(jobs[i]?.analysis), }, }); + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete result.details[nodeId] = jobs[i]; result.elements.push({ diff --git a/x-pack/plugins/ml/server/models/fields_service/fields_service.ts b/x-pack/plugins/ml/server/models/fields_service/fields_service.ts index cfe0bcc532630..e608bfeb622d8 100644 --- a/x-pack/plugins/ml/server/models/fields_service/fields_service.ts +++ b/x-pack/plugins/ml/server/models/fields_service/fields_service.ts @@ -185,7 +185,6 @@ export function fieldsServiceProvider({ asCurrentUser }: IScopedClusterClient) { } = await asCurrentUser.search({ index, body, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options ...(datafeedConfig?.indices_options ?? {}), }); @@ -407,7 +406,6 @@ export function fieldsServiceProvider({ asCurrentUser }: IScopedClusterClient) { } = await asCurrentUser.search({ index, body, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options ...(datafeedConfig?.indices_options ?? {}), }); diff --git a/x-pack/plugins/ml/server/models/filter/filter_manager.ts b/x-pack/plugins/ml/server/models/filter/filter_manager.ts index 1429324a6d9c8..f48b71dedf3ee 100644 --- a/x-pack/plugins/ml/server/models/filter/filter_manager.ts +++ b/x-pack/plugins/ml/server/models/filter/filter_manager.ts @@ -79,16 +79,16 @@ export class FilterManager { if ( results[FILTERS] && - (results[FILTERS].body as estypes.GetFiltersResponse).filters.length + (results[FILTERS].body as estypes.MlGetFiltersResponse).filters.length ) { let filtersInUse: FiltersInUse = {}; - if (results[JOBS] && (results[JOBS].body as estypes.GetJobsResponse).jobs) { + if (results[JOBS] && (results[JOBS].body as estypes.MlGetJobsResponse).jobs) { filtersInUse = this.buildFiltersInUse( - (results[JOBS].body as estypes.GetJobsResponse).jobs + (results[JOBS].body as estypes.MlGetJobsResponse).jobs ); } - const filter = (results[FILTERS].body as estypes.GetFiltersResponse).filters[0]; + const filter = (results[FILTERS].body as estypes.MlGetFiltersResponse).filters[0]; return { ...filter, used_by: filtersInUse[filter.filter_id], @@ -121,8 +121,10 @@ export class FilterManager { // Build a map of filter_ids against jobs and detectors using that filter. let filtersInUse: FiltersInUse = {}; - if (results[JOBS] && (results[JOBS].body as estypes.GetJobsResponse).jobs) { - filtersInUse = this.buildFiltersInUse((results[JOBS].body as estypes.GetJobsResponse).jobs); + if (results[JOBS] && (results[JOBS].body as estypes.MlGetJobsResponse).jobs) { + filtersInUse = this.buildFiltersInUse( + (results[JOBS].body as estypes.MlGetJobsResponse).jobs + ); } // For each filter, return just @@ -131,16 +133,18 @@ export class FilterManager { // item_count // jobs using the filter const filterStats: FilterStats[] = []; - if (results[FILTERS] && (results[FILTERS].body as estypes.GetFiltersResponse).filters) { - (results[FILTERS].body as estypes.GetFiltersResponse).filters.forEach((filter: Filter) => { - const stats: FilterStats = { - filter_id: filter.filter_id, - description: filter.description, - item_count: filter.items.length, - used_by: filtersInUse[filter.filter_id], - }; - filterStats.push(stats); - }); + if (results[FILTERS] && (results[FILTERS].body as estypes.MlGetFiltersResponse).filters) { + (results[FILTERS].body as estypes.MlGetFiltersResponse).filters.forEach( + (filter: Filter) => { + const stats: FilterStats = { + filter_id: filter.filter_id, + description: filter.description, + item_count: filter.items.length, + used_by: filtersInUse[filter.filter_id], + }; + filterStats.push(stats); + } + ); } return filterStats; diff --git a/x-pack/plugins/ml/server/models/job_service/datafeeds.ts b/x-pack/plugins/ml/server/models/job_service/datafeeds.ts index 72255e168249a..5dfe1b5934fe9 100644 --- a/x-pack/plugins/ml/server/models/job_service/datafeeds.ts +++ b/x-pack/plugins/ml/server/models/job_service/datafeeds.ts @@ -28,8 +28,8 @@ export interface MlDatafeedsStatsResponse { interface Results { [id: string]: { - started?: estypes.StartDatafeedResponse['started']; - stopped?: estypes.StopDatafeedResponse['stopped']; + started?: estypes.MlStartDatafeedResponse['started']; + stopped?: estypes.MlStopDatafeedResponse['stopped']; error?: any; }; } @@ -246,7 +246,6 @@ export function datafeedsProvider(client: IScopedClusterClient, mlClient: MlClie job.data_description.time_field, query, datafeed.runtime_mappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options datafeed.indices_options ); @@ -378,7 +377,6 @@ export function datafeedsProvider(client: IScopedClusterClient, mlClient: MlClie const data = { index: datafeed.indices, body, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options ...(datafeed.indices_options ?? {}), }; diff --git a/x-pack/plugins/ml/server/models/job_service/jobs.ts b/x-pack/plugins/ml/server/models/job_service/jobs.ts index a838db443bebc..b7f8ce569641e 100644 --- a/x-pack/plugins/ml/server/models/job_service/jobs.ts +++ b/x-pack/plugins/ml/server/models/job_service/jobs.ts @@ -195,7 +195,6 @@ export function jobsProvider( processed_record_count: job.data_counts?.processed_record_count, earliestStartTimestampMs: getEarliestDatafeedStartTime( dataCounts?.latest_record_timestamp, - // @ts-expect-error @elastic/elasticsearch data counts missing is missing latest_bucket_timestamp dataCounts?.latest_bucket_timestamp, parseTimeIntervalForJob(job.analysis_config?.bucket_span) ), @@ -211,7 +210,6 @@ export function jobsProvider( earliestTimestampMs: dataCounts?.earliest_record_timestamp, latestResultsTimestampMs: getLatestDataOrBucketTimestamp( dataCounts?.latest_record_timestamp, - // @ts-expect-error @elastic/elasticsearch data counts missing is missing latest_bucket_timestamp dataCounts?.latest_bucket_timestamp ), isSingleMetricViewerJob: errorMessage === undefined, @@ -254,7 +252,6 @@ export function jobsProvider( if (dataCounts !== undefined) { timeRange.to = getLatestDataOrBucketTimestamp( dataCounts.latest_record_timestamp as number, - // @ts-expect-error @elastic/elasticsearch data counts missing is missing latest_bucket_timestamp dataCounts.latest_bucket_timestamp as number ); timeRange.from = dataCounts.earliest_record_timestamp; @@ -398,7 +395,6 @@ export function jobsProvider( if (jobStatsResults && jobStatsResults.jobs) { const jobStats = jobStatsResults.jobs.find((js) => js.job_id === tempJob.job_id); if (jobStats !== undefined) { - // @ts-expect-error @elastic-elasticsearch JobStats type is incomplete tempJob = { ...tempJob, ...jobStats }; if (jobStats.node) { tempJob.node = jobStats.node; @@ -411,7 +407,6 @@ export function jobsProvider( const latestBucketTimestamp = latestBucketTimestampByJob && latestBucketTimestampByJob[tempJob.job_id]; if (latestBucketTimestamp) { - // @ts-expect-error @elastic/elasticsearch data counts missing is missing latest_bucket_timestamp tempJob.data_counts.latest_bucket_timestamp = latestBucketTimestamp; } } @@ -467,7 +462,6 @@ export function jobsProvider( const jobIds: string[] = []; try { const { body } = await asInternalUser.tasks.list({ - // @ts-expect-error @elastic-elasticsearch expects it to be a string actions, detailed, }); diff --git a/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts index 49c09742985d4..fad388f791f08 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts @@ -114,7 +114,7 @@ class FieldsService { this._savedObjectsClient ); const rollupConfigs: - | estypes.RollupCapabilitiesJob[] + | estypes.RollupGetRollupCapabilitiesRollupCapabilitySummary[] | null = await rollupService.getRollupJobs(); // if a rollup index has been specified, yet there are no @@ -137,7 +137,9 @@ class FieldsService { } } -function combineAllRollupFields(rollupConfigs: estypes.RollupCapabilitiesJob[]): RollupFields { +function combineAllRollupFields( + rollupConfigs: estypes.RollupGetRollupCapabilitiesRollupCapabilitySummary[] +): RollupFields { const rollupFields: RollupFields = {}; rollupConfigs.forEach((conf) => { Object.keys(conf.fields).forEach((fieldName) => { diff --git a/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts index d83f7afb4cdf6..5f5ae16ed9733 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts @@ -27,7 +27,9 @@ export async function rollupServiceProvider( const rollupIndexPatternObject = await loadRollupIndexPattern(indexPattern, savedObjectsClient); let jobIndexPatterns: string[] = [indexPattern]; - async function getRollupJobs(): Promise { + async function getRollupJobs(): Promise< + estypes.RollupGetRollupCapabilitiesRollupCapabilitySummary[] | null + > { if (rollupIndexPatternObject !== null) { const parsedTypeMetaData = JSON.parse(rollupIndexPatternObject.attributes.typeMeta); const rollUpIndex: string = parsedTypeMetaData.params.rollup_index; diff --git a/x-pack/plugins/ml/server/models/job_validation/job_validation.ts b/x-pack/plugins/ml/server/models/job_validation/job_validation.ts index 00a51d1e4e153..80eba7b864051 100644 --- a/x-pack/plugins/ml/server/models/job_validation/job_validation.ts +++ b/x-pack/plugins/ml/server/models/job_validation/job_validation.ts @@ -69,7 +69,6 @@ export async function validateJob( timeField, job.datafeed_config.query, job.datafeed_config.runtime_mappings, - // @ts-expect-error @elastic/elasticsearch Datafeed is missing indices_options job.datafeed_config.indices_options ); diff --git a/x-pack/plugins/ml/server/routes/anomaly_detectors.ts b/x-pack/plugins/ml/server/routes/anomaly_detectors.ts index 5205ea7353ac6..c5be5e1c9ef2d 100644 --- a/x-pack/plugins/ml/server/routes/anomaly_detectors.ts +++ b/x-pack/plugins/ml/server/routes/anomaly_detectors.ts @@ -284,7 +284,7 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) { }, routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { try { - const options: estypes.CloseJobRequest = { + const options: estypes.MlCloseJobRequest = { job_id: request.params.jobId, }; const force = request.query.force; @@ -323,7 +323,7 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) { }, routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { try { - const options: estypes.DeleteJobRequest = { + const options: estypes.MlDeleteJobRequest = { job_id: request.params.jobId, wait_for_completion: false, }; @@ -517,13 +517,11 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) { try { const { body } = await mlClient.getOverallBuckets({ job_id: request.params.jobId, - body: { - top_n: request.body.topN, - bucket_span: request.body.bucketSpan, - start: request.body.start !== undefined ? String(request.body.start) : undefined, - end: request.body.end !== undefined ? String(request.body.end) : undefined, - overall_score: request.body.overall_score ?? 0, - }, + top_n: request.body.topN, + bucket_span: request.body.bucketSpan, + start: request.body.start !== undefined ? String(request.body.start) : undefined, + end: request.body.end !== undefined ? String(request.body.end) : undefined, + overall_score: request.body.overall_score ?? 0, }); return response.ok({ body, diff --git a/x-pack/plugins/ml/server/routes/data_frame_analytics.ts b/x-pack/plugins/ml/server/routes/data_frame_analytics.ts index f6dc21538ffa0..2ed4fd6fcd31a 100644 --- a/x-pack/plugins/ml/server/routes/data_frame_analytics.ts +++ b/x-pack/plugins/ml/server/routes/data_frame_analytics.ts @@ -265,6 +265,7 @@ export function dataFrameAnalyticsRoutes({ router, mlLicense, routeGuard }: Rout const { body } = await mlClient.putDataFrameAnalytics( { id: analyticsId, + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete body: request.body, }, getAuthorizationHeader(request) @@ -301,6 +302,7 @@ export function dataFrameAnalyticsRoutes({ router, mlLicense, routeGuard }: Rout try { const { body } = await mlClient.evaluateDataFrame( { + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete body: request.body, }, getAuthorizationHeader(request) @@ -338,6 +340,7 @@ export function dataFrameAnalyticsRoutes({ router, mlLicense, routeGuard }: Rout try { const { body } = await mlClient.explainDataFrameAnalytics( { + // @ts-expect-error @elastic-elasticsearch Data frame types incomplete body: request.body, }, getAuthorizationHeader(request) diff --git a/x-pack/plugins/ml/server/routes/datafeeds.ts b/x-pack/plugins/ml/server/routes/datafeeds.ts index 2013af3ee8735..9f908bf61a35d 100644 --- a/x-pack/plugins/ml/server/routes/datafeeds.ts +++ b/x-pack/plugins/ml/server/routes/datafeeds.ts @@ -247,7 +247,7 @@ export function dataFeedRoutes({ router, routeGuard }: RouteInitialization) { }, routeGuard.fullLicenseAPIGuard(async ({ mlClient, request, response }) => { try { - const options: estypes.DeleteDatafeedRequest = { + const options: estypes.MlDeleteDatafeedRequest = { datafeed_id: request.params.datafeedId, }; const force = request.query.force; diff --git a/x-pack/plugins/ml/server/routes/trained_models.ts b/x-pack/plugins/ml/server/routes/trained_models.ts index c4b2d63b05d13..106010d0f7550 100644 --- a/x-pack/plugins/ml/server/routes/trained_models.ts +++ b/x-pack/plugins/ml/server/routes/trained_models.ts @@ -39,6 +39,7 @@ export function trainedModelsRoutes({ router, routeGuard }: RouteInitialization) const { modelId } = request.params; const { with_pipelines: withPipelines, ...query } = request.query; const { body } = await mlClient.getTrainedModels({ + // @ts-expect-error @elastic-elasticsearch not sure why this is an error, size is a number size: 1000, ...query, ...(modelId ? { model_id: modelId } : {}), diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_available_ccs.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_available_ccs.test.ts index 603c66d2d05f2..ca8270590da54 100644 --- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_available_ccs.test.ts +++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_available_ccs.test.ts @@ -26,7 +26,7 @@ describe('fetchAvailableCcs', () => { elasticsearchClientMock.createSuccessTransportRequestPromise({ [connectedRemote]: { connected: true, - } as estypes.RemoteInfo, + } as estypes.ClusterRemoteInfoClusterRemoteInfo, }) ); @@ -41,7 +41,7 @@ describe('fetchAvailableCcs', () => { elasticsearchClientMock.createSuccessTransportRequestPromise({ [disconnectedRemote]: { connected: false, - } as estypes.RemoteInfo, + } as estypes.ClusterRemoteInfoClusterRemoteInfo, }) ); diff --git a/x-pack/plugins/observability/server/lib/annotations/mappings.ts b/x-pack/plugins/observability/server/lib/annotations/mappings.ts index da72afdbecb33..3313c411b5889 100644 --- a/x-pack/plugins/observability/server/lib/annotations/mappings.ts +++ b/x-pack/plugins/observability/server/lib/annotations/mappings.ts @@ -6,7 +6,7 @@ */ export const mappings = { - dynamic: 'strict' as const, + dynamic: 'strict', properties: { annotation: { properties: { @@ -45,4 +45,4 @@ export const mappings = { }, }, }, -}; +} as const; diff --git a/x-pack/plugins/observability/server/utils/create_or_update_index.ts b/x-pack/plugins/observability/server/utils/create_or_update_index.ts index 19b14ef8b2437..7451314ad248c 100644 --- a/x-pack/plugins/observability/server/utils/create_or_update_index.ts +++ b/x-pack/plugins/observability/server/utils/create_or_update_index.ts @@ -4,12 +4,12 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { CreateIndexRequest, PutMappingRequest } from '@elastic/elasticsearch/api/types'; +import { estypes } from '@elastic/elasticsearch'; import pRetry from 'p-retry'; import { Logger, ElasticsearchClient } from 'src/core/server'; -export type Mappings = Required['body']['mappings'] & - Required['body']; +export type Mappings = Required['body']['mappings'] & + Required['body']; export async function createOrUpdateIndex({ index, @@ -71,7 +71,7 @@ function createNewIndex({ }: { index: string; client: ElasticsearchClient; - mappings: Required['body']['mappings']; + mappings: Required['body']['mappings']; }) { return client.indices.create({ index, @@ -90,7 +90,7 @@ function updateExistingIndex({ }: { index: string; client: ElasticsearchClient; - mappings: PutMappingRequest['body']; + mappings: estypes.IndicesPutMappingRequest['body']; }) { return client.indices.putMapping({ index, diff --git a/x-pack/plugins/observability/server/utils/queries.ts b/x-pack/plugins/observability/server/utils/queries.ts index b7412120365c6..2ee3291e7fb62 100644 --- a/x-pack/plugins/observability/server/utils/queries.ts +++ b/x-pack/plugins/observability/server/utils/queries.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { ALERT_STATUS } from '@kbn/rule-data-utils/target/technical_field_names'; import { esKuery } from '../../../../../src/plugins/data/server'; import { AlertStatus } from '../../common/typings'; @@ -18,7 +18,11 @@ export function alertStatusQuery(status: AlertStatus) { return [{ term: { [ALERT_STATUS]: status } }]; } -export function rangeQuery(start?: number, end?: number, field = '@timestamp'): QueryContainer[] { +export function rangeQuery( + start?: number, + end?: number, + field = '@timestamp' +): estypes.QueryDslQueryContainer[] { return [ { range: { @@ -32,7 +36,7 @@ export function rangeQuery(start?: number, end?: number, field = '@timestamp'): ]; } -export function kqlQuery(kql?: string): QueryContainer[] { +export function kqlQuery(kql?: string): estypes.QueryDslQueryContainer[] { if (!kql) { return []; } diff --git a/x-pack/plugins/osquery/common/search_strategy/osquery/index.ts b/x-pack/plugins/osquery/common/search_strategy/osquery/index.ts index d07af8c878c51..fb3bd92abb4c9 100644 --- a/x-pack/plugins/osquery/common/search_strategy/osquery/index.ts +++ b/x-pack/plugins/osquery/common/search_strategy/osquery/index.ts @@ -37,7 +37,7 @@ export type FactoryQueryTypes = OsqueryQueries; export interface RequestBasicOptions extends IEsSearchRequest { filterQuery: ESQuery | string | undefined; - aggregations?: Record; + aggregations?: Record; docValueFields?: DocValueFields[]; factoryQueryType?: FactoryQueryTypes; } diff --git a/x-pack/plugins/osquery/public/agents/helpers.ts b/x-pack/plugins/osquery/public/agents/helpers.ts index a79933db0ceb0..df966a01f1de1 100644 --- a/x-pack/plugins/osquery/public/agents/helpers.ts +++ b/x-pack/plugins/osquery/public/agents/helpers.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Aggregate, TermsAggregate } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { euiPaletteColorBlindBehindText } from '@elastic/eui'; import { PaginationInputPaginated, @@ -40,11 +40,11 @@ export const getNumOverlapped = ( }); return sum; }; -export const processAggregations = (aggs: Record) => { +export const processAggregations = (aggs: Record) => { const platforms: Group[] = []; const overlap: Overlap = {}; - const platformTerms = aggs.platforms as TermsAggregate; - const policyTerms = aggs.policies as TermsAggregate; + const platformTerms = aggs.platforms as estypes.AggregationsTermsAggregate; + const policyTerms = aggs.policies as estypes.AggregationsTermsAggregate; const policies = policyTerms?.buckets.map((o) => ({ name: o.key, id: o.key, size: o.doc_count })) ?? []; diff --git a/x-pack/plugins/osquery/public/agents/types.ts b/x-pack/plugins/osquery/public/agents/types.ts index 302b2686d511e..bfe59c91d007d 100644 --- a/x-pack/plugins/osquery/public/agents/types.ts +++ b/x-pack/plugins/osquery/public/agents/types.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { TermsAggregate } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { EuiComboBoxOptionOption } from '@elastic/eui'; import { Agent } from '../../common/shared_imports'; @@ -15,7 +15,7 @@ interface BaseDataPoint { } export type AggregationDataPoint = BaseDataPoint & { - [key: string]: TermsAggregate; + [key: string]: estypes.AggregationsTermsAggregate; }; export interface Group { diff --git a/x-pack/plugins/osquery/server/search_strategy/osquery/factory/actions/results/query.action_results.dsl.ts b/x-pack/plugins/osquery/server/search_strategy/osquery/factory/actions/results/query.action_results.dsl.ts index e8a8fbd63a84d..d74067bff0251 100644 --- a/x-pack/plugins/osquery/server/search_strategy/osquery/factory/actions/results/query.action_results.dsl.ts +++ b/x-pack/plugins/osquery/server/search_strategy/osquery/factory/actions/results/query.action_results.dsl.ts @@ -52,7 +52,7 @@ export const buildActionResultsQuery = ({ lang: 'painless', source: "if (doc['error.keyword'].size()==0) { return 'success' } else { return 'error' }", - }, + } as const, }, }, }, diff --git a/x-pack/plugins/reporting/server/lib/store/mapping.ts b/x-pack/plugins/reporting/server/lib/store/mapping.ts index e663c7e23b146..1a4567b4aee92 100644 --- a/x-pack/plugins/reporting/server/lib/store/mapping.ts +++ b/x-pack/plugins/reporting/server/lib/store/mapping.ts @@ -63,4 +63,4 @@ export const mapping = { content: { type: 'object', enabled: false }, }, }, -}; +} as const; diff --git a/x-pack/plugins/rollup/server/collectors/helpers.ts b/x-pack/plugins/rollup/server/collectors/helpers.ts index 3ec457bc6191e..1d1a8755aa568 100644 --- a/x-pack/plugins/rollup/server/collectors/helpers.ts +++ b/x-pack/plugins/rollup/server/collectors/helpers.ts @@ -81,7 +81,6 @@ const getSavedObjectsList = async ({ ignore_unavailable: true, index: kibanaIndex, size: ES_MAX_RESULT_WINDOW_DEFAULT_VALUE, - // @ts-expect-error@elastic/elasticsearch _source does not exist in type SearchRequest _source: filterPath, }); return esResponse; diff --git a/x-pack/plugins/rule_registry/common/mapping_from_field_map.ts b/x-pack/plugins/rule_registry/common/mapping_from_field_map.ts index 17eb5ae8967af..74681a6aad4ee 100644 --- a/x-pack/plugins/rule_registry/common/mapping_from_field_map.ts +++ b/x-pack/plugins/rule_registry/common/mapping_from_field_map.ts @@ -5,11 +5,11 @@ * 2.0. */ -import { TypeMapping } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { set } from '@elastic/safer-lodash-set'; import { FieldMap } from './field_map/types'; -export function mappingFromFieldMap(fieldMap: FieldMap): TypeMapping { +export function mappingFromFieldMap(fieldMap: FieldMap): estypes.MappingTypeMapping { const mappings = { dynamic: 'strict' as const, properties: {}, diff --git a/x-pack/plugins/rule_registry/common/types.ts b/x-pack/plugins/rule_registry/common/types.ts index 299d2c300ab49..858b1a5af431f 100644 --- a/x-pack/plugins/rule_registry/common/types.ts +++ b/x-pack/plugins/rule_registry/common/types.ts @@ -7,7 +7,7 @@ import { estypes } from '@elastic/elasticsearch'; -export type PutIndexTemplateRequest = estypes.PutIndexTemplateRequest & { +export type PutIndexTemplateRequest = estypes.IndicesPutIndexTemplateRequest & { body?: { composed_of?: string[] }; }; @@ -16,6 +16,6 @@ export interface ClusterPutComponentTemplateBody { settings: { number_of_shards: number; }; - mappings: estypes.TypeMapping; + mappings: estypes.MappingTypeMapping; }; } diff --git a/x-pack/plugins/rule_registry/server/event_log/elasticsearch/index_management_gateway.ts b/x-pack/plugins/rule_registry/server/event_log/elasticsearch/index_management_gateway.ts index 96b5860e143ee..cb04a442d0b34 100644 --- a/x-pack/plugins/rule_registry/server/event_log/elasticsearch/index_management_gateway.ts +++ b/x-pack/plugins/rule_registry/server/event_log/elasticsearch/index_management_gateway.ts @@ -93,6 +93,7 @@ export class IndexManagementGateway { this.logger.debug(`Updating index template; name="${templateName}"`); try { + // @ts-expect-error settings is optional const { settings, ...templateWithoutSettings } = template; const es = await this.elasticsearch; diff --git a/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/ilm_policy.ts b/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/ilm_policy.ts index 00fc9131523ac..7663ea27fb0df 100644 --- a/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/ilm_policy.ts +++ b/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/ilm_policy.ts @@ -8,7 +8,7 @@ import { estypes } from '@elastic/elasticsearch'; export interface IlmPolicy { - policy: estypes.Policy; + policy: estypes.IlmPolicy; } export const defaultIlmPolicy: IlmPolicy = { diff --git a/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/index_template.ts b/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/index_template.ts index caf71dadf6e1e..0045bce3ed873 100644 --- a/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/index_template.ts +++ b/x-pack/plugins/rule_registry/server/event_log/elasticsearch/resources/index_template.ts @@ -9,7 +9,7 @@ import { estypes } from '@elastic/elasticsearch'; import { IndexNames } from './index_names'; import { IndexMappings } from './index_mappings'; -export type IndexTemplate = estypes.PutIndexTemplateRequest['body']; +export type IndexTemplate = estypes.IndicesPutTemplateRequest['body']; export const createIndexTemplate = ( names: IndexNames, @@ -39,6 +39,7 @@ export const createIndexTemplate = ( order: 'desc', }, }, + // @ts-expect-error IndexMappings is not assignale to estypes.MappingTypeMapping mappings: { ...mappings, _meta: { diff --git a/x-pack/plugins/rule_registry/server/event_log/log/event_query_builder.ts b/x-pack/plugins/rule_registry/server/event_log/log/event_query_builder.ts index 48228ce5352b7..bf9aca74f7800 100644 --- a/x-pack/plugins/rule_registry/server/event_log/log/event_query_builder.ts +++ b/x-pack/plugins/rule_registry/server/event_log/log/event_query_builder.ts @@ -78,8 +78,8 @@ export class EventQueryBuilder implements IEventQueryBuilder { return new EventQuery({ indexReader, request }); } - private buildFilter(): estypes.QueryContainer[] { - const result: estypes.QueryContainer[] = []; + private buildFilter(): estypes.QueryDslQueryContainer[] { + const result: estypes.QueryDslQueryContainer[] = []; if (this.loggerName) { result.push({ diff --git a/x-pack/plugins/rule_registry/server/event_log/log/public_api.ts b/x-pack/plugins/rule_registry/server/event_log/log/public_api.ts index 7807dd9ca6b36..7dcaee9d382b1 100644 --- a/x-pack/plugins/rule_registry/server/event_log/log/public_api.ts +++ b/x-pack/plugins/rule_registry/server/event_log/log/public_api.ts @@ -101,7 +101,7 @@ export interface IEventQueryBuilder { buildQuery(): IEventQuery; } -export type SortingParams = estypes.Sort; +export type SortingParams = estypes.SearchSort; export interface PaginationParams { page: number; diff --git a/x-pack/plugins/rule_registry/server/rule_data_client/index.ts b/x-pack/plugins/rule_registry/server/rule_data_client/index.ts index 43122ba49519a..cd7467c903e52 100644 --- a/x-pack/plugins/rule_registry/server/rule_data_client/index.ts +++ b/x-pack/plugins/rule_registry/server/rule_data_client/index.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { TypeMapping } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { ResponseError } from '@elastic/elasticsearch/lib/errors'; import { IndexPatternsFetcher } from '../../../../../src/plugins/data/server'; import { @@ -125,7 +125,7 @@ export class RuleDataClient implements IRuleDataClient { path: `/_index_template/_simulate_index/${concreteIndexName}`, }); - const mappings: TypeMapping = simulateResponse.template.mappings; + const mappings: estypes.MappingTypeMapping = simulateResponse.template.mappings; await clusterClient.indices.putMapping({ index: `${alias}*`, body: mappings }); } diff --git a/x-pack/plugins/rule_registry/server/rule_data_plugin_service/index.ts b/x-pack/plugins/rule_registry/server/rule_data_plugin_service/index.ts index 159e9b8152597..22435ef8c0203 100644 --- a/x-pack/plugins/rule_registry/server/rule_data_plugin_service/index.ts +++ b/x-pack/plugins/rule_registry/server/rule_data_plugin_service/index.ts @@ -110,7 +110,7 @@ export class RuleDataPluginService { return clusterClient.indices.putIndexTemplate(template); } - private async _createOrUpdateLifecyclePolicy(policy: estypes.PutLifecycleRequest) { + private async _createOrUpdateLifecyclePolicy(policy: estypes.IlmPutLifecycleRequest) { this.assertWriteEnabled(); const clusterClient = await this.getClusterClient(); @@ -130,7 +130,7 @@ export class RuleDataPluginService { return this._createOrUpdateIndexTemplate(template); } - async createOrUpdateLifecyclePolicy(policy: estypes.PutLifecycleRequest) { + async createOrUpdateLifecyclePolicy(policy: estypes.IlmPutLifecycleRequest) { await this.wait(); return this._createOrUpdateLifecyclePolicy(policy); } diff --git a/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts b/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts index e3a586062ae4c..29849497e02ec 100644 --- a/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts +++ b/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts @@ -17,7 +17,10 @@ export function defineGetBuiltinPrivilegesRoutes({ router }: RouteDefinitionPara // Exclude the `none` privilege, as it doesn't make sense as an option within the Kibana UI privileges.cluster = privileges.cluster.filter((privilege) => privilege !== 'none'); - privileges.index = privileges.index.filter((privilege) => privilege !== 'none'); + const indexPriviledges = Array.isArray(privileges.index) + ? privileges.index + : [privileges.index]; + privileges.index = indexPriviledges.filter((privilege) => privilege !== 'none'); return response.ok({ body: privileges }); } diff --git a/x-pack/plugins/security/server/routes/authorization/roles/put.ts b/x-pack/plugins/security/server/routes/authorization/roles/put.ts index 09bcb6b8c505c..5a0934721e20c 100644 --- a/x-pack/plugins/security/server/routes/authorization/roles/put.ts +++ b/x-pack/plugins/security/server/routes/authorization/roles/put.ts @@ -72,7 +72,6 @@ export function definePutRolesRoutes({ const body = transformPutPayloadToElasticsearchRole( request.body, authz.applicationName, - // @ts-expect-error @elastic/elasticsearch `XPackRole` type doesn't define `applications`. rawRoles[name] ? rawRoles[name].applications : [] ); diff --git a/x-pack/plugins/security/server/session_management/session_index.ts b/x-pack/plugins/security/server/session_management/session_index.ts index d7a4c3e2520bf..9093d5d2e0db2 100644 --- a/x-pack/plugins/security/server/session_management/session_index.ts +++ b/x-pack/plugins/security/server/session_management/session_index.ts @@ -52,7 +52,7 @@ export function getSessionIndexTemplate(indexName: string) { }, }, mappings: { - dynamic: 'strict' as 'strict', + dynamic: 'strict', properties: { usernameHash: { type: 'keyword' }, provider: { properties: { name: { type: 'keyword' }, type: { type: 'keyword' } } }, @@ -61,7 +61,7 @@ export function getSessionIndexTemplate(indexName: string) { accessAgreementAcknowledged: { type: 'boolean' }, content: { type: 'binary' }, }, - }, + } as const, }); } diff --git a/x-pack/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts b/x-pack/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts index 6e508a099003a..58e7539b1f617 100644 --- a/x-pack/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts +++ b/x-pack/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts @@ -51,13 +51,16 @@ export class FleetAgentGenerator extends BaseDataGenerator { * @param [overrides] any partial value to the full document */ generateEsHit( - overrides: DeepPartial> = {} - ): estypes.Hit { + overrides: DeepPartial> = {} + ): estypes.SearchHit { const hostname = this.randomHostname(); const now = new Date().toISOString(); const osFamily = this.randomOSFamily(); - return merge, DeepPartial>>( + return merge< + estypes.SearchHit, + DeepPartial> + >( { _index: AGENTS_INDEX, _id: this.randomUUID(), diff --git a/x-pack/plugins/security_solution/common/endpoint/index_data.ts b/x-pack/plugins/security_solution/common/endpoint/index_data.ts index 021b9bcb1eccc..4996d90288ca9 100644 --- a/x-pack/plugins/security_solution/common/endpoint/index_data.ts +++ b/x-pack/plugins/security_solution/common/endpoint/index_data.ts @@ -121,7 +121,7 @@ async function indexHostDocs({ const kibanaVersion = await fetchKibanaVersion(kbnClient); let hostMetadata: HostMetadata; let wasAgentEnrolled = false; - let enrolledAgent: undefined | estypes.Hit; + let enrolledAgent: undefined | estypes.SearchHit; for (let j = 0; j < numDocs; j++) { generator.updateHostData(); @@ -373,7 +373,7 @@ const indexFleetAgentForHost = async ( endpointHost: HostMetadata, agentPolicyId: string, kibanaVersion: string = '8.0.0' -): Promise> => { +): Promise> => { const agentDoc = fleetAgentGenerator.generateEsHit({ _source: { local_metadata: { diff --git a/x-pack/plugins/security_solution/common/search_strategy/common/index.ts b/x-pack/plugins/security_solution/common/search_strategy/common/index.ts index e27e9b5173fd5..4fcfbdac3c1b4 100644 --- a/x-pack/plugins/security_solution/common/search_strategy/common/index.ts +++ b/x-pack/plugins/security_solution/common/search_strategy/common/index.ts @@ -70,7 +70,7 @@ export interface PaginationInputPaginated { querySize: number; } -export type DocValueFields = estypes.DocValueField; +export type DocValueFields = estypes.SearchDocValueField; export interface Explanation { value: number; diff --git a/x-pack/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts b/x-pack/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts index 34b32115a089d..e8578b4c07063 100644 --- a/x-pack/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts +++ b/x-pack/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts @@ -25,5 +25,5 @@ export interface HostDetailsRequestOptions extends Partial { }); it('properly transforms the response', async () => { + // @ts-expect-error mocking only what we need esClient.indices.getMapping.mockResolvedValue({ body: { - // @ts-expect-error mocking only what we need index1: { mappings: { _meta: { version: 3 } } }, }, }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/migration_cleanup.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/migration_cleanup.ts index 9c40778d46704..00446a204ca89 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/migration_cleanup.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/migrations/migration_cleanup.ts @@ -86,7 +86,7 @@ export const applyMigrationCleanupPolicy = async ({ await esClient.indices.putSettings({ index, body: { - index: { + settings: { lifecycle: { name: getMigrationCleanupPolicyName(alias), }, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/reference_rules/query.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/reference_rules/query.ts index 3911dcabc34de..04bfa78f883f0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/reference_rules/query.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/reference_rules/query.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema } from '@kbn/config-schema'; import { Logger } from '@kbn/logging'; import { ESSearchRequest } from 'typings/elasticsearch'; @@ -60,7 +60,7 @@ export const createQueryAlertType = (ruleDataClient: RuleDataClient, logger: Log indexPattern, { query: customQuery, language: 'kuery' }, [] - ) as QueryContainer; + ) as estypes.QueryDslQueryContainer; const query: ESSearchRequest = { body: { query: esQuery, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.ts index 0414439580361..7b27d22d9b387 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.ts @@ -5,7 +5,6 @@ * 2.0. */ import type { estypes } from '@elastic/elasticsearch'; -import { SortResults } from '@elastic/elasticsearch/api/types'; import { isEmpty } from 'lodash'; import { SortOrderOrUndefined, @@ -13,14 +12,14 @@ import { } from '../../../../common/detection_engine/schemas/common/schemas'; interface BuildEventsSearchQuery { - aggregations?: Record; + aggregations?: Record; index: string[]; from: string; to: string; - filter: estypes.QueryContainer; + filter: estypes.QueryDslQueryContainer; size: number; sortOrder?: SortOrderOrUndefined; - searchAfterSortIds: SortResults | undefined; + searchAfterSortIds: estypes.SearchSortResults | undefined; timestampOverride: TimestampOverrideOrUndefined; } @@ -43,7 +42,7 @@ export const buildEventsSearchQuery = ({ format: 'strict_date_optional_time', })); - const rangeFilter: estypes.QueryContainer[] = + const rangeFilter: estypes.QueryDslQueryContainer[] = timestampOverride != null ? [ { @@ -93,7 +92,7 @@ export const buildEventsSearchQuery = ({ }, ]; - const filterWithTime: estypes.QueryContainer[] = [ + const filterWithTime: estypes.QueryDslQueryContainer[] = [ filter, { bool: { filter: [{ bool: { should: [...rangeFilter], minimum_should_match: 1 } }] } }, ]; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events.ts index a50d40e33a717..da664f65c2d50 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events.ts @@ -16,7 +16,7 @@ import { FilterEventsOptions } from './types'; export const filterEvents = ({ events, fieldAndSetTuples, -}: FilterEventsOptions): Array> => { +}: FilterEventsOptions): Array> => { return events.filter((item) => { return fieldAndSetTuples .map((tuple) => { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events_against_list.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events_against_list.ts index 5907cbdfb7fdd..fffe971753f87 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events_against_list.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/filter_events_against_list.ts @@ -58,9 +58,9 @@ export const filterEventsAgainstList = async ({ return listItem.entries.every((entry) => entriesList.is(entry)); }); - const res = await valueListExceptionItems.reduce>>>( + const res = await valueListExceptionItems.reduce>>>( async ( - filteredAccum: Promise>>, + filteredAccum: Promise>>, exceptionItem: ExceptionListItemSchema ) => { const events = await filteredAccum; @@ -78,7 +78,7 @@ export const filterEventsAgainstList = async ({ ); return filteredEvents; }, - Promise.resolve>>(eventSearchResult.hits.hits) + Promise.resolve>>(eventSearchResult.hits.hits) ); return { diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/types.ts index 1252ca3f5faa5..160506b965bf0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filters/types.ts @@ -20,7 +20,7 @@ export interface FilterEventsAgainstListOptions { } export interface CreateSetToFilterAgainstOptions { - events: Array>; + events: Array>; field: string; listId: string; listType: Type; @@ -30,12 +30,12 @@ export interface CreateSetToFilterAgainstOptions { } export interface FilterEventsOptions { - events: Array>; + events: Array>; fieldAndSetTuples: FieldSet[]; } export interface CreateFieldAndSetTuplesOptions { - events: Array>; + events: Array>; exceptionItem: ExceptionListItemSchema; listClient: ListClient; logger: Logger; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts index 08f8abe384d0f..b0dcc1810a639 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts @@ -6,7 +6,7 @@ */ import { identity } from 'lodash'; -import { SortResults } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { singleSearchAfter } from './single_search_after'; import { singleBulkCreate } from './single_bulk_create'; import { filterEventsAgainstList } from './filters/filter_events_against_list'; @@ -44,7 +44,7 @@ export const searchAfterAndBulkCreate = async ({ let toReturn = createSearchAfterReturnType(); // sortId tells us where to start our next consecutive search_after query - let sortIds: SortResults | undefined; + let sortIds: estypes.SearchSortResults | undefined; let hasSortId = true; // default to true so we execute the search on initial run // signalsCreatedCount keeps track of how many signals we have created, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.test.ts index 66f7d41df94ab..823d694f36514 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.test.ts @@ -157,7 +157,7 @@ describe('signal_rule_alert_type', () => { (mlExecutor as jest.Mock).mockClear(); (mlExecutor as jest.Mock).mockResolvedValue(executorReturnValue); (parseScheduleDates as jest.Mock).mockReturnValue(moment(100)); - const value: Partial> = { + const value: Partial> = { statusCode: 200, body: { indices: ['index1', 'index2', 'index3', 'index4'], @@ -174,7 +174,7 @@ describe('signal_rule_alert_type', () => { }, }; alertServices.scopedClusterClient.asCurrentUser.fieldCaps.mockResolvedValue( - value as ApiResponse + value as ApiResponse ); const ruleAlert = getAlertMock(getQueryRuleParams()); alertServices.savedObjectsClient.get.mockResolvedValue({ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts index ae22964eced92..6436da40088b3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts @@ -6,7 +6,6 @@ */ import type { estypes } from '@elastic/elasticsearch'; import { performance } from 'perf_hooks'; -import { SearchRequest, SortResults } from '@elastic/elasticsearch/api/types'; import { AlertInstanceContext, AlertInstanceState, @@ -23,8 +22,8 @@ import { } from '../../../../common/detection_engine/schemas/common/schemas'; interface SingleSearchAfterParams { - aggregations?: Record; - searchAfterSortIds: SortResults | undefined; + aggregations?: Record; + searchAfterSortIds: estypes.SearchSortResults | undefined; index: string[]; from: string; to: string; @@ -32,7 +31,7 @@ interface SingleSearchAfterParams { logger: Logger; pageSize: number; sortOrder?: SortOrderOrUndefined; - filter: estypes.QueryContainer; + filter: estypes.QueryDslQueryContainer; timestampOverride: TimestampOverrideOrUndefined; buildRuleMessage: BuildRuleMessage; } @@ -73,7 +72,7 @@ export const singleSearchAfter = async ({ const { body: nextSearchAfterResult, } = await services.scopedClusterClient.asCurrentUser.search( - searchAfterQuery as SearchRequest + searchAfterQuery as estypes.SearchRequest ); const end = performance.now(); const searchErrors = createErrorsFromShard({ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/create_threat_signals.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/create_threat_signals.ts index ade85db0e4ba6..b3e0e376c7794 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/create_threat_signals.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/create_threat_signals.ts @@ -154,7 +154,7 @@ export const createThreatSignals = async ({ language: threatLanguage, threatFilters, index: threatIndex, - // @ts-expect-error@elastic/elasticsearch SortResults might contain null + // @ts-expect-error@elastic/elasticsearch SearchSortResults might contain null searchAfter: threatList.hits.hits[threatList.hits.hits.length - 1].sort, sortField: undefined, sortOrder: undefined, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/get_threat_list.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/get_threat_list.ts index c3d3d6c6a99e1..3ff23e27547b4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/get_threat_list.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/get_threat_list.ts @@ -54,7 +54,7 @@ export const getThreatList = async ({ ); const { body: response } = await esClient.search({ body: { - // @ts-expect-error ESBoolQuery is not assignale to QueryContainer + // @ts-expect-error ESBoolQuery is not assignale to QueryDslQueryContainer query: queryFilter, fields: [ { @@ -125,7 +125,7 @@ export const getThreatListCount = async ({ ); const { body: response } = await esClient.count({ body: { - // @ts-expect-error ESBoolQuery is not assignale to QueryContainer + // @ts-expect-error ESBoolQuery is not assignale to QueryDslQueryContainer query: queryFilter, }, ignore_unavailable: true, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/types.ts index 094c4d74d8ac7..acb64f826f3f2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/threat_mapping/types.ts @@ -167,7 +167,7 @@ export interface ThreatListDoc { * This is an ECS document being returned, but the user could return or use non-ecs based * documents potentially. */ -export type ThreatListItem = estypes.Hit; +export type ThreatListItem = estypes.SearchHit; export interface ThreatIndicator { [key: string]: unknown; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts index 8f34e58ebc85b..4205c2d6d8b2c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts @@ -153,9 +153,9 @@ export interface GetResponse { } export type SignalSearchResponse = estypes.SearchResponse; -export type SignalSourceHit = estypes.Hit; +export type SignalSourceHit = estypes.SearchHit; export type WrappedSignalHit = BaseHit; -export type BaseSignalHit = estypes.Hit; +export type BaseSignalHit = estypes.SearchHit; export type EqlSignalSearchResponse = EqlSearchResponse; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts index dde9986e8bdf5..1de76f64fabec 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts @@ -13,7 +13,6 @@ import type { estypes } from '@elastic/elasticsearch'; import { chunk, isEmpty, partition } from 'lodash'; import { ApiResponse, Context } from '@elastic/elasticsearch/lib/Transport'; -import { SortResults } from '@elastic/elasticsearch/api/types'; import type { ListArray, ExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types'; import { MAX_EXCEPTION_LIST_SIZE } from '@kbn/securitysolution-list-constants'; import { hasLargeValueList } from '@kbn/securitysolution-list-utils'; @@ -875,10 +874,10 @@ export const isMachineLearningParams = (params: RuleParams): params is MachineLe * Ref: https://github.com/elastic/elasticsearch/issues/28806#issuecomment-369303620 * * return stringified Long.MAX_VALUE if we receive Number.MAX_SAFE_INTEGER - * @param sortIds SortResults | undefined + * @param sortIds estypes.SearchSortResults | undefined * @returns SortResults */ -export const getSafeSortIds = (sortIds: SortResults | undefined) => { +export const getSafeSortIds = (sortIds: estypes.SearchSortResults | undefined) => { return sortIds?.map((sortId) => { // haven't determined when we would receive a null value for a sort id // but in case we do, default to sending the stringified Java max_int diff --git a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query.dsl.ts b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query.dsl.ts index e960067713bda..325d45e04b2b0 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query.dsl.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query.dsl.ts @@ -75,7 +75,7 @@ export const buildQuery = ({ order: [ { 'successes.doc_count': 'desc' as const }, { 'failures.doc_count': 'desc' as const }, - ] as estypes.TermsAggregationOrder, + ] as estypes.AggregationsTermsAggregationOrder, }, aggs: { failures: { diff --git a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query_entities.dsl.ts b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query_entities.dsl.ts index 51d80152d65c0..d320130115588 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query_entities.dsl.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/authentications/dsl/query_entities.dsl.ts @@ -52,7 +52,10 @@ export const buildQueryEntities = ({ terms: { size: querySize, field: 'user.name', - order: [{ successes: 'desc' }, { failures: 'desc' }] as estypes.TermsAggregationOrder, + order: [ + { successes: 'desc' }, + { failures: 'desc' }, + ] as estypes.AggregationsTermsAggregationOrder, }, aggs: { failures: { diff --git a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/overview/query.overview_host.dsl.ts b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/overview/query.overview_host.dsl.ts index 897ae633076a2..a0ae368ac0fe2 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/overview/query.overview_host.dsl.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/overview/query.overview_host.dsl.ts @@ -293,6 +293,6 @@ export const buildOverviewHostQuery = ({ }, } as const; - // @ts-expect-error @elastic-elasticsearch readonly [] is not assignable to mutable QueryContainer[] + // @ts-expect-error @elastic-elasticsearch readonly [] is not assignable to mutable QueryDslQueryContainer[] return dslQuery; }; diff --git a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/dsl/query.dsl.ts b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/dsl/query.dsl.ts index 1df0d60d54a88..5d4f45c68160a 100644 --- a/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/dsl/query.dsl.ts +++ b/x-pack/plugins/security_solution/server/search_strategy/security_solution/factory/hosts/uncommon_processes/dsl/query.dsl.ts @@ -68,7 +68,7 @@ export const buildQuery = ({ { _key: 'asc' as const, }, - ] as estypes.TermsAggregationOrder, + ] as estypes.AggregationsTermsAggregationOrder, }, aggregations: { process: { @@ -120,7 +120,7 @@ export const buildQuery = ({ 'event.action': 'executed', }, }, - ] as estypes.QueryContainer[], + ] as estypes.QueryDslQueryContainer[], }, }, { @@ -146,7 +146,7 @@ export const buildQuery = ({ 'event.action': 'process_started', }, }, - ] as estypes.QueryContainer[], + ] as estypes.QueryDslQueryContainer[], }, }, { diff --git a/x-pack/plugins/snapshot_restore/server/routes/api/policy.ts b/x-pack/plugins/snapshot_restore/server/routes/api/policy.ts index 77264c4bffc9a..52e4e7011f0d4 100644 --- a/x-pack/plugins/snapshot_restore/server/routes/api/policy.ts +++ b/x-pack/plugins/snapshot_restore/server/routes/api/policy.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { PutSnapshotLifecycleRequest } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema, TypeOf } from '@kbn/config-schema'; import { SlmPolicyEs, PolicyIndicesResponse } from '../../../common/types'; @@ -103,7 +103,7 @@ export function registerPolicyRoutes({ const response = await clusterClient.asCurrentUser.slm.putLifecycle({ policy_id: name, // TODO: bring {@link SlmPolicyEs['policy']} in line with {@link PutSnapshotLifecycleRequest['body']} - body: (serializePolicy(policy) as unknown) as PutSnapshotLifecycleRequest['body'], + body: (serializePolicy(policy) as unknown) as estypes.SlmPutLifecycleRequest['body'], }); return res.ok({ body: response.body }); @@ -133,7 +133,7 @@ export function registerPolicyRoutes({ const response = await clusterClient.asCurrentUser.slm.putLifecycle({ policy_id: name, // TODO: bring {@link SlmPolicyEs['policy']} in line with {@link PutSnapshotLifecycleRequest['body']} - body: (serializePolicy(policy) as unknown) as PutSnapshotLifecycleRequest['body'], + body: (serializePolicy(policy) as unknown) as estypes.SlmPutLifecycleRequest['body'], }); return res.ok({ body: response.body }); @@ -205,6 +205,7 @@ export function registerPolicyRoutes({ name: '*', expand_wildcards: 'all', }); + // @ts-expect-error Type 'ResolveIndexAliasItem[]' is not comparable to type 'IndexAndAliasFromEs[]'. const resolvedIndicesResponse = response.body as ResolveIndexResponseFromES; const body: PolicyIndicesResponse = { diff --git a/x-pack/plugins/snapshot_restore/server/routes/api/restore.ts b/x-pack/plugins/snapshot_restore/server/routes/api/restore.ts index b7281fee04c53..eb77c5e2d833f 100644 --- a/x-pack/plugins/snapshot_restore/server/routes/api/restore.ts +++ b/x-pack/plugins/snapshot_restore/server/routes/api/restore.ts @@ -6,7 +6,7 @@ */ import { schema, TypeOf } from '@kbn/config-schema'; -import { RestoreRequest } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { SnapshotRestore, SnapshotRestoreShardEs } from '../../../common/types'; import { serializeRestoreSettings } from '../../../common/lib'; @@ -108,7 +108,7 @@ export function registerRestoreRoutes({ repository, snapshot, // TODO: Bring {@link RestoreSettingsEs} in line with {@link RestoreRequest['body']} - body: serializeRestoreSettings(restoreSettings) as RestoreRequest['body'], + body: serializeRestoreSettings(restoreSettings) as estypes.SnapshotRestoreRequest['body'], }); return res.ok({ body: response.body }); diff --git a/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.ts b/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.ts index 49c7ec2ef3d8f..38fbc08b19c48 100644 --- a/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.ts +++ b/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.ts @@ -73,7 +73,7 @@ export function registerSnapshotsRoutes({ ignore_unavailable: true, // Allow request to succeed even if some snapshots are unavailable. }); - const { snapshots: fetchedSnapshots } = response.body; + const { snapshots: fetchedSnapshots = [] } = response.body; // Decorate each snapshot with the repository with which it's associated. diff --git a/x-pack/plugins/spaces/server/saved_objects/mappings.ts b/x-pack/plugins/spaces/server/saved_objects/mappings.ts index 2b1763f1de583..82a134bfdbf62 100644 --- a/x-pack/plugins/spaces/server/saved_objects/mappings.ts +++ b/x-pack/plugins/spaces/server/saved_objects/mappings.ts @@ -38,7 +38,7 @@ export const SpacesSavedObjectMappings = deepFreeze({ type: 'boolean', }, }, -}); +} as const); export const UsageStatsMappings = deepFreeze({ dynamic: false as false, // we aren't querying or aggregating over this data, so we don't need to specify any fields diff --git a/x-pack/plugins/stack_alerts/common/build_sorted_events_query.ts b/x-pack/plugins/stack_alerts/common/build_sorted_events_query.ts index 34851073bd8a2..455307cb73a09 100644 --- a/x-pack/plugins/stack_alerts/common/build_sorted_events_query.ts +++ b/x-pack/plugins/stack_alerts/common/build_sorted_events_query.ts @@ -8,7 +8,7 @@ import { estypes } from '@elastic/elasticsearch'; import type { ESSearchRequest } from '../../../../typings/elasticsearch'; interface BuildSortedEventsQueryOpts { - aggs?: Record; + aggs?: Record; track_total_hits: boolean | number; index: estypes.Indices; size: number; diff --git a/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.tsx b/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.tsx index f89f1133d0248..5111f427cd0d8 100644 --- a/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.tsx +++ b/x-pack/plugins/stack_alerts/public/alert_types/es_query/expression.tsx @@ -41,7 +41,7 @@ import { buildSortedEventsQuery } from '../../../common/build_sorted_events_quer import { EsQueryAlertParams } from './types'; import { IndexSelectPopover } from '../components/index_select_popover'; -function totalHitsToNumber(total: estypes.HitsMetadata['total']): number { +function totalHitsToNumber(total: estypes.SearchHitsMetadata['total']): number { return typeof total === 'number' ? total : total.value; } diff --git a/x-pack/plugins/stack_alerts/server/alert_types/es_query/action_context.ts b/x-pack/plugins/stack_alerts/server/alert_types/es_query/action_context.ts index bc5d5c41c5cce..84a4569d9b860 100644 --- a/x-pack/plugins/stack_alerts/server/alert_types/es_query/action_context.ts +++ b/x-pack/plugins/stack_alerts/server/alert_types/es_query/action_context.ts @@ -29,7 +29,7 @@ export interface EsQueryAlertActionContext extends AlertInstanceContext { // threshold conditions conditions: string; // query matches - hits: estypes.Hit[]; + hits: estypes.SearchHit[]; } export function addMessages( diff --git a/x-pack/plugins/stack_alerts/server/alert_types/es_query/alert_type.ts b/x-pack/plugins/stack_alerts/server/alert_types/es_query/alert_type.ts index ece193e07d776..b81bc19d5c731 100644 --- a/x-pack/plugins/stack_alerts/server/alert_types/es_query/alert_type.ts +++ b/x-pack/plugins/stack_alerts/server/alert_types/es_query/alert_type.ts @@ -220,7 +220,7 @@ export function getAlertType( `alert ${ES_QUERY_ID}:${alertId} "${name}" result - ${JSON.stringify(searchResult)}` ); - const numMatches = (searchResult.hits.total as estypes.TotalHits).value; + const numMatches = (searchResult.hits.total as estypes.SearchTotalHits).value; // apply the alert condition const conditionMet = compareFn(numMatches, params.threshold); diff --git a/x-pack/plugins/task_manager/server/monitoring/workload_statistics.test.ts b/x-pack/plugins/task_manager/server/monitoring/workload_statistics.test.ts index a4913fca19ee8..f3ee21bc7d770 100644 --- a/x-pack/plugins/task_manager/server/monitoring/workload_statistics.test.ts +++ b/x-pack/plugins/task_manager/server/monitoring/workload_statistics.test.ts @@ -61,7 +61,7 @@ describe('Workload Statistics Aggregator', () => { doc_count_error_upper_bound: 0, sum_other_doc_count: 0, }, - // The `FiltersAggregate` doesn't cover the case of a nested `AggregationContainer`, in which `FiltersAggregate` + // The `FiltersAggregate` doesn't cover the case of a nested `AggregationsAggregationContainer`, in which `FiltersAggregate` // would not have a `buckets` property, but rather a keyed property that's inferred from the request. // @ts-expect-error idleTasks: { @@ -238,7 +238,7 @@ describe('Workload Statistics Aggregator', () => { }, ], }, - // The `FiltersAggregate` doesn't cover the case of a nested `AggregationContainer`, in which `FiltersAggregate` + // The `FiltersAggregate` doesn't cover the case of a nested `AggregationsAggregationContainer`, in which `FiltersAggregate` // would not have a `buckets` property, but rather a keyed property that's inferred from the request. // @ts-expect-error idleTasks: { @@ -944,7 +944,7 @@ function setTaskTypeCount( ...rest.hits, total: { value: buckets.reduce((sum, bucket) => sum + bucket.doc_count, 0), - relation: 'eq' as estypes.TotalHitsRelation, + relation: 'eq' as estypes.SearchTotalHitsRelation, }, }, aggregations: { diff --git a/x-pack/plugins/task_manager/server/monitoring/workload_statistics.ts b/x-pack/plugins/task_manager/server/monitoring/workload_statistics.ts index 548539b0db329..e251ce07679ff 100644 --- a/x-pack/plugins/task_manager/server/monitoring/workload_statistics.ts +++ b/x-pack/plugins/task_manager/server/monitoring/workload_statistics.ts @@ -86,7 +86,6 @@ export interface WorkloadAggregation { // The type of a bucket in the scheduleDensity range aggregation type ScheduleDensityResult = AggregationResultOf< - // @ts-expect-error AggregationRange reqires from: number WorkloadAggregation['aggs']['idleTasks']['aggs']['scheduleDensity'], {} >['buckets'][0]; @@ -137,9 +136,7 @@ export function createWorkloadAggregator( field: 'task.runAt', ranges: [ { - // @ts-expect-error @elastic/elasticsearch The `AggregationRange` type only supports `double` for `from` and `to` but it can be a string too for time based ranges from: `now`, - // @ts-expect-error @elastic/elasticsearch The `AggregationRange` type only supports `double` for `from` and `to` but it can be a string too for time based ranges to: `now+${asInterval(scheduleDensityBuckets * pollInterval)}`, }, ], @@ -355,7 +352,7 @@ export function summarizeWorkloadStat( } function hasAggregations( - aggregations?: Record + aggregations?: Record ): aggregations is WorkloadAggregationResponse { return !!( aggregations?.taskType && @@ -368,9 +365,9 @@ export interface WorkloadAggregationResponse { taskType: TaskTypeAggregation; schedule: ScheduleAggregation; idleTasks: IdleTasksAggregation; - [otherAggs: string]: estypes.Aggregate; + [otherAggs: string]: estypes.AggregationsAggregate; } -export interface TaskTypeAggregation extends estypes.FiltersAggregate { +export interface TaskTypeAggregation extends estypes.AggregationsFiltersAggregate { buckets: Array<{ doc_count: number; key: string | number; @@ -386,7 +383,7 @@ export interface TaskTypeAggregation extends estypes.FiltersAggregate { doc_count_error_upper_bound?: number | undefined; sum_other_doc_count?: number | undefined; } -export interface ScheduleAggregation extends estypes.FiltersAggregate { +export interface ScheduleAggregation extends estypes.AggregationsFiltersAggregate { buckets: Array<{ doc_count: number; key: string | number; @@ -411,7 +408,7 @@ export type ScheduleDensityHistogram = DateRangeBucket & { >; }; }; -export interface IdleTasksAggregation extends estypes.FiltersAggregate { +export interface IdleTasksAggregation extends estypes.AggregationsFiltersAggregate { doc_count: number; scheduleDensity: { buckets: ScheduleDensityHistogram[]; diff --git a/x-pack/plugins/task_manager/server/queries/mark_available_tasks_as_claimed.ts b/x-pack/plugins/task_manager/server/queries/mark_available_tasks_as_claimed.ts index 2437e893abf37..1793ede8161df 100644 --- a/x-pack/plugins/task_manager/server/queries/mark_available_tasks_as_claimed.ts +++ b/x-pack/plugins/task_manager/server/queries/mark_available_tasks_as_claimed.ts @@ -30,7 +30,7 @@ export function taskWithLessThanMaxAttempts(type: string, maxAttempts: number): }; } -export function tasksOfType(taskTypes: string[]): estypes.QueryContainer { +export function tasksOfType(taskTypes: string[]): estypes.QueryDslQueryContainer { return { bool: { should: [...taskTypes].map((type) => ({ term: { 'task.taskType': type } })), @@ -40,7 +40,7 @@ export function tasksOfType(taskTypes: string[]): estypes.QueryContainer { export function tasksClaimedByOwner( taskManagerId: string, - ...taskFilters: estypes.QueryContainer[] + ...taskFilters: estypes.QueryDslQueryContainer[] ) { return mustBeAllOf( { @@ -104,7 +104,7 @@ if (doc['task.runAt'].size()!=0) { }; export const SortByRunAtAndRetryAt = (SortByRunAtAndRetryAtScript as unknown) as Record< string, - estypes.Sort + estypes.SearchSort >; export const updateFieldsAndMarkAsFailed = ( diff --git a/x-pack/plugins/task_manager/server/queries/query_clauses.ts b/x-pack/plugins/task_manager/server/queries/query_clauses.ts index 97c41295eece3..5f7cc8ed2bdb3 100644 --- a/x-pack/plugins/task_manager/server/queries/query_clauses.ts +++ b/x-pack/plugins/task_manager/server/queries/query_clauses.ts @@ -8,10 +8,10 @@ import { estypes } from '@elastic/elasticsearch'; export interface MustCondition { - bool: Pick; + bool: Pick; } export interface MustNotCondition { - bool: Pick; + bool: Pick; } export interface ScriptBasedSortClause { @@ -24,7 +24,7 @@ export interface ScriptBasedSortClause { export interface ScriptClause { source: string; - lang: string; + lang: estypes.ScriptLanguage; params?: { [field: string]: | string @@ -35,16 +35,16 @@ export interface ScriptClause { }; } -export type PinnedQuery = Pick; +export type PinnedQuery = Pick; -type BoolClause = Pick; +type BoolClause = Pick; export function matchesClauses(...clauses: BoolClause[]): BoolClause { return { bool: Object.assign({}, ...clauses.map((clause) => clause.bool)), }; } -export function shouldBeOneOf(...should: estypes.QueryContainer[]) { +export function shouldBeOneOf(...should: estypes.QueryDslQueryContainer[]) { return { bool: { should, @@ -52,7 +52,7 @@ export function shouldBeOneOf(...should: estypes.QueryContainer[]) { }; } -export function mustBeAllOf(...must: estypes.QueryContainer[]) { +export function mustBeAllOf(...must: estypes.QueryDslQueryContainer[]) { return { bool: { must, @@ -60,7 +60,7 @@ export function mustBeAllOf(...must: estypes.QueryContainer[]) { }; } -export function filterDownBy(...filter: estypes.QueryContainer[]) { +export function filterDownBy(...filter: estypes.QueryDslQueryContainer[]) { return { bool: { filter, @@ -69,9 +69,9 @@ export function filterDownBy(...filter: estypes.QueryContainer[]) { } export function asPinnedQuery( - ids: estypes.PinnedQuery['ids'], - organic: estypes.PinnedQuery['organic'] -): Pick { + ids: estypes.QueryDslPinnedQuery['ids'], + organic: estypes.QueryDslPinnedQuery['organic'] +): Pick { return { pinned: { ids, diff --git a/x-pack/plugins/task_manager/server/saved_objects/index.ts b/x-pack/plugins/task_manager/server/saved_objects/index.ts index 33b57b62b31aa..c032e8d658a40 100644 --- a/x-pack/plugins/task_manager/server/saved_objects/index.ts +++ b/x-pack/plugins/task_manager/server/saved_objects/index.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { SavedObjectsServiceSetup } from 'kibana/server'; +import type { SavedObjectsServiceSetup, SavedObjectsTypeMappingDefinition } from 'kibana/server'; import mappings from './mappings.json'; import { migrations } from './migrations'; import { TaskManagerConfig } from '../config.js'; @@ -19,7 +19,7 @@ export function setupSavedObjects( namespaceType: 'agnostic', hidden: true, convertToAliasScript: `ctx._id = ctx._source.type + ':' + ctx._id; ctx._source.remove("kibana")`, - mappings: mappings.task, + mappings: mappings.task as SavedObjectsTypeMappingDefinition, migrations, indexPattern: config.index, }); diff --git a/x-pack/plugins/task_manager/server/task_store.test.ts b/x-pack/plugins/task_manager/server/task_store.test.ts index 2d2bd81af96e5..f3b4014c9c919 100644 --- a/x-pack/plugins/task_manager/server/task_store.test.ts +++ b/x-pack/plugins/task_manager/server/task_store.test.ts @@ -208,7 +208,7 @@ describe('TaskStore', () => { }); }); - async function testFetch(opts?: SearchOpts, hits: Array> = []) { + async function testFetch(opts?: SearchOpts, hits: Array> = []) { esClient.search.mockResolvedValue(asApiResponse({ hits: { hits, total: hits.length } })); const result = await store.fetch(opts); diff --git a/x-pack/plugins/task_manager/server/task_store.ts b/x-pack/plugins/task_manager/server/task_store.ts index 0eeccd0af75f7..ce01660134683 100644 --- a/x-pack/plugins/task_manager/server/task_store.ts +++ b/x-pack/plugins/task_manager/server/task_store.ts @@ -46,14 +46,14 @@ export interface StoreOpts { export interface SearchOpts { search_after?: Array; size?: number; - sort?: estypes.Sort; - query?: estypes.QueryContainer; + sort?: estypes.SearchSort; + query?: estypes.QueryDslQueryContainer; seq_no_primary_term?: boolean; } export interface AggregationOpts { - aggs: Record; - query?: estypes.QueryContainer; + aggs: Record; + query?: estypes.QueryDslQueryContainer; size?: number; } diff --git a/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_license.ts b/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_license.ts index 3db9f06bd8bf6..ad7d5439f8765 100644 --- a/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_license.ts +++ b/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_license.ts @@ -7,7 +7,7 @@ import type { estypes } from '@elastic/elasticsearch'; import { ElasticsearchClient } from 'src/core/server'; -export type ESLicense = estypes.LicenseInformation; +export type ESLicense = estypes.LicenseGetLicenseInformation; let cachedLicense: ESLicense | undefined; diff --git a/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.test.ts b/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.test.ts index 86d1554a4fd57..75b9c736de901 100644 --- a/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.test.ts +++ b/x-pack/plugins/telemetry_collection_xpack/server/telemetry_collection/get_stats_with_xpack.test.ts @@ -91,7 +91,7 @@ function mockEsClient() { cluster_uuid: 'test', cluster_name: 'test', version: { number: '8.0.0' } as estypes.ElasticsearchVersionInfo, - } as estypes.RootNodeInfoResponse, + } as estypes.InfoResponse, } ); diff --git a/x-pack/plugins/transform/common/api_schemas/type_guards.ts b/x-pack/plugins/transform/common/api_schemas/type_guards.ts index 4b66de9be20d2..1f27f1798c8e7 100644 --- a/x-pack/plugins/transform/common/api_schemas/type_guards.ts +++ b/x-pack/plugins/transform/common/api_schemas/type_guards.ts @@ -74,7 +74,7 @@ export const isEsSearchResponseWithAggregations = ( export const isMultiBucketAggregate = ( arg: unknown -): arg is estypes.MultiBucketAggregate => { +): arg is estypes.AggregationsMultiBucketAggregate => { return isPopulatedObject(arg, ['buckets']); }; diff --git a/x-pack/plugins/transform/public/app/hooks/use_index_data.ts b/x-pack/plugins/transform/public/app/hooks/use_index_data.ts index bd1ecd79f4d12..55a304207a1c7 100644 --- a/x-pack/plugins/transform/public/app/hooks/use_index_data.ts +++ b/x-pack/plugins/transform/public/app/hooks/use_index_data.ts @@ -206,7 +206,7 @@ export const useIndexData = ( setRowCount(typeof resp.hits.total === 'number' ? resp.hits.total : resp.hits.total.value); setRowCountRelation( typeof resp.hits.total === 'number' - ? ('eq' as estypes.TotalHitsRelation) + ? ('eq' as estypes.SearchTotalHitsRelation) : resp.hits.total.relation ); setTableItems(docs); diff --git a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_term_form.tsx b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_term_form.tsx index 358bb9dcafa96..da7100a31167a 100644 --- a/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_term_form.tsx +++ b/x-pack/plugins/transform/public/app/sections/create_transform/components/step_define/common/filter_agg/components/filter_term_form.tsx @@ -69,7 +69,9 @@ export const FilterTermForm: FilterAggConfigTerm['aggTypeConfig']['FilterAggForm if ( !( isEsSearchResponseWithAggregations(response) && - isMultiBucketAggregate(response.aggregations.field_values) + isMultiBucketAggregate( + response.aggregations.field_values + ) ) ) { toastNotifications.addWarning( diff --git a/x-pack/plugins/transform/server/routes/api/field_histograms.ts b/x-pack/plugins/transform/server/routes/api/field_histograms.ts index bb2a1b278a5c2..bfe2f47078569 100644 --- a/x-pack/plugins/transform/server/routes/api/field_histograms.ts +++ b/x-pack/plugins/transform/server/routes/api/field_histograms.ts @@ -41,7 +41,6 @@ export function registerFieldHistogramsRoutes({ router, license }: RouteDependen query, fields, samplerShardSize, - // @ts-expect-error script is not compatible with StoredScript from @elastic/elasticsearch: string is not supported runtimeMappings ); diff --git a/x-pack/plugins/transform/server/routes/api/transforms.ts b/x-pack/plugins/transform/server/routes/api/transforms.ts index 80f80d6f1d71b..ea2bb28776ac2 100644 --- a/x-pack/plugins/transform/server/routes/api/transforms.ts +++ b/x-pack/plugins/transform/server/routes/api/transforms.ts @@ -6,6 +6,7 @@ */ import { schema } from '@kbn/config-schema'; +import type { estypes } from '@elastic/elasticsearch'; import { ElasticsearchClient, @@ -252,7 +253,7 @@ export function registerTransformsRoutes(routeDependencies: RouteDependencies) { const { body, } = await ctx.core.elasticsearch.client.asCurrentUser.transform.updateTransform({ - // @ts-expect-error query doesn't satisfy QueryContainer from @elastic/elasticsearch + // @ts-expect-error query doesn't satisfy QueryDslQueryContainer from @elastic/elasticsearch body: req.body, transform_id: transformId, }); @@ -570,7 +571,10 @@ const previewTransformHandler: RequestHandler< return acc; }, {} as Record); - body.generated_dest_index.mappings.properties = fields; + body.generated_dest_index.mappings!.properties = fields as Record< + string, + estypes.MappingProperty + >; } return res.ok({ body }); } catch (e) { diff --git a/x-pack/plugins/upgrade_assistant/server/lib/es_migration_apis.test.ts b/x-pack/plugins/upgrade_assistant/server/lib/es_migration_apis.test.ts index 2620fe31d6277..d78af9162e924 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/es_migration_apis.test.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/es_migration_apis.test.ts @@ -35,6 +35,7 @@ describe('getUpgradeAssistantStatus', () => { asApiResponse(deprecationsResponse) ); + // @ts-expect-error not full interface of response esClient.asCurrentUser.indices.resolveIndex.mockResolvedValue(asApiResponse(resolvedIndices)); it('calls /_migration/deprecations', async () => { diff --git a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.test.ts b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.test.ts index 5e994f76f927c..30093a9fb6e50 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.test.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.test.ts @@ -40,6 +40,7 @@ describe('transformFlatSettings', () => { 'index.number_of_shards': '5', // Blacklisted settings + // @ts-expect-error @elastic/elasticsearch doesn't declare it 'index.allocation.existing_shards_allocator': 'gateway_allocator', 'index.blocks.write': 'true', 'index.creation_date': '1547052614626', @@ -89,6 +90,7 @@ describe('transformFlatSettings', () => { 'index.number_of_shards': '5', // Deprecated settings + // @ts-expect-error @elastic/elasticsearch doesn't declare it 'index.soft_deletes.enabled': 'true', 'index.translog.retention.size': '5b', }, @@ -112,6 +114,7 @@ describe('transformFlatSettings', () => { 'index.number_of_shards': '5', // Deprecated settings + // @ts-expect-error @elastic/elasticsearch doesn't declare it 'index.soft_deletes.enabled': 'true', 'index.translog.retention.age': '5d', }, @@ -216,6 +219,7 @@ describe('transformFlatSettings', () => { getReindexWarnings({ settings: { // Deprecated settings + // @ts-expect-error @elastic/elasticsearch doesn't declare it 'index.force_memory_term_dictionary': '1024', 'index.max_adjacency_matrix_filters': 'true', 'index.soft_deletes.enabled': 'true', diff --git a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.ts b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.ts index 5ee067f3640f3..0fb531b286854 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/index_settings.ts @@ -104,11 +104,14 @@ export const getDeprecatedSettingWarning = ( }); // Translog settings are only marked as deprecated if soft deletes is enabled + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting if (settings['index.soft_deletes.enabled'] === 'true') { + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting if (settings['index.translog.retention.size']) { deprecatedSettingsInUse.push('index.translog.retention.size'); } + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting if (settings['index.translog.retention.age']) { deprecatedSettingsInUse.push('index.translog.retention.age'); } @@ -183,12 +186,17 @@ const removeDeprecatedSettings = (settings: FlatSettings['settings']) => { const updatedSettings = { ...settings }; // Translog settings are only marked as deprecated if soft deletes is enabled + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting if (updatedSettings['index.soft_deletes.enabled'] === 'true') { + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting if (updatedSettings['index.translog.retention.size']) { + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting delete updatedSettings['index.translog.retention.size']; } + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting if (settings['index.translog.retention.age']) { + // @ts-expect-error @elastic/elasticsearch doesn't declare such a setting delete updatedSettings['index.translog.retention.age']; } } diff --git a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts index ae0a6f97e29d5..7a5bf1c187698 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.test.ts @@ -793,7 +793,7 @@ describe('reindexService', () => { expect(updatedOp.attributes.lastCompletedStep).toEqual(ReindexStep.readonly); expect(clusterClient.asCurrentUser.indices.putSettings).toHaveBeenCalledWith({ index: 'myIndex', - body: { index: { blocks: { write: true } } }, + body: { settings: { blocks: { write: true } } }, }); }); @@ -885,7 +885,7 @@ describe('reindexService', () => { // Original index should have been set back to allow reads. expect(clusterClient.asCurrentUser.indices.putSettings).toHaveBeenCalledWith({ index: 'myIndex', - body: { index: { blocks: { write: false } } }, + body: { settings: { blocks: { write: false } } }, }); }); }); diff --git a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.ts b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.ts index d01275645965e..a8f0708045951 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/reindex_service.ts @@ -226,7 +226,7 @@ export const reindexServiceFactory = ( if (reindexOp.attributes.lastCompletedStep >= ReindexStep.readonly) { await esClient.indices.putSettings({ index: reindexOp.attributes.indexName, - body: { index: { blocks: { write: false } } }, + body: { settings: { blocks: { write: false } } }, }); } @@ -290,7 +290,7 @@ export const reindexServiceFactory = ( const { indexName } = reindexOp.attributes; const { body: putReadonly } = await esClient.indices.putSettings({ index: indexName, - body: { index: { blocks: { write: true } } }, + body: { settings: { blocks: { write: true } } }, }); if (!putReadonly.acknowledged) { diff --git a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/types.ts b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/types.ts index 569316e276e43..ddff137772ae8 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/reindexing/types.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/reindexing/types.ts @@ -4,6 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ +import type { estypes } from '@elastic/elasticsearch'; interface Mapping { type?: string; @@ -19,10 +20,8 @@ interface MetaProperties { } export interface FlatSettings { - settings: { - [key: string]: string; - }; - mappings: { + settings: estypes.IndicesIndexState['settings']; + mappings?: { properties?: MappingProperties; _meta?: MetaProperties; }; @@ -30,10 +29,8 @@ export interface FlatSettings { // Specific to 7.x-8 upgrade export interface FlatSettingsWithTypeName { - settings: { - [key: string]: string; - }; - mappings: { + settings: estypes.IndicesIndexState['settings']; + mappings?: { [typeName: string]: { properties?: MappingProperties; _meta?: MetaProperties; diff --git a/x-pack/plugins/upgrade_assistant/server/routes/update_index_settings.ts b/x-pack/plugins/upgrade_assistant/server/routes/update_index_settings.ts index 4bdf3c7f56cac..b90ff4281644b 100644 --- a/x-pack/plugins/upgrade_assistant/server/routes/update_index_settings.ts +++ b/x-pack/plugins/upgrade_assistant/server/routes/update_index_settings.ts @@ -45,7 +45,7 @@ export function registerUpdateSettingsRoute({ router }: RouteDependencies) { const { body: settingsResponse } = await client.asCurrentUser.indices.putSettings({ index: indexName, body: { - index: settingsToDelete, + settings: settingsToDelete, }, }); diff --git a/x-pack/plugins/uptime/server/lib/requests/get_journey_details.ts b/x-pack/plugins/uptime/server/lib/requests/get_journey_details.ts index 560653950c6f8..6081cc3a7b7c8 100644 --- a/x-pack/plugins/uptime/server/lib/requests/get_journey_details.ts +++ b/x-pack/plugins/uptime/server/lib/requests/get_journey_details.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { UMElasticsearchQueryFn } from '../adapters/framework'; import { SyntheticsJourneyApiResponse } from '../../../common/runtime_types'; @@ -31,7 +31,7 @@ export const getJourneyDetails: UMElasticsearchQueryFn< 'synthetics.type': 'journey/start', }, }, - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }, size: 1, @@ -56,7 +56,7 @@ export const getJourneyDetails: UMElasticsearchQueryFn< 'synthetics.type': 'journey/start', }, }, - ] as QueryContainer[], + ] as QueryDslQueryContainer[], }, }, _source: ['@timestamp', 'monitor.check_group'], diff --git a/x-pack/plugins/uptime/server/lib/requests/get_journey_failed_steps.ts b/x-pack/plugins/uptime/server/lib/requests/get_journey_failed_steps.ts index 5c4e263468947..d14a723d27628 100644 --- a/x-pack/plugins/uptime/server/lib/requests/get_journey_failed_steps.ts +++ b/x-pack/plugins/uptime/server/lib/requests/get_journey_failed_steps.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { QueryContainer } from '@elastic/elasticsearch/api/types'; +import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types'; import { SearchHit } from '../../../../../../typings/elasticsearch'; import { asMutableArray } from '../../../common/utils/as_mutable_array'; import { UMElasticsearchQueryFn } from '../adapters/framework'; @@ -38,7 +38,7 @@ export const getJourneyFailedSteps: UMElasticsearchQueryFn = a { range: { '@timestamp': { gte: from, lte: to } } }, ...(monitorId ? [{ term: { 'monitor.id': monitorId } }] : []), ...(status ? [{ term: { 'monitor.status': status } }] : []), - ] as QueryContainer[], + ] as QueryDslQueryContainer[], ...REMOVE_NON_SUMMARY_BROWSER_CHECKS, }, }, diff --git a/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts b/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts index f686d978ec710..621fdf0d15861 100644 --- a/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts +++ b/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/fetch_all_from_scroll.ts @@ -5,16 +5,16 @@ * 2.0. */ -import { ScrollResponse, Hit } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { IScopedClusterClient } from 'kibana/server'; import { get } from 'lodash'; import { ES_SCROLL_SETTINGS } from '../../../common/constants'; export function fetchAllFromScroll( - searchResults: ScrollResponse, + searchResults: estypes.ScrollResponse, dataClient: IScopedClusterClient, - hits: Hit[] = [] -): Promise { + hits: estypes.SearchHit[] = [] +): Promise { const newHits = get(searchResults, 'hits.hits', []); const scrollId = get(searchResults, '_scroll_id'); @@ -25,7 +25,7 @@ export function fetchAllFromScroll( .scroll({ body: { scroll: ES_SCROLL_SETTINGS.KEEPALIVE, - scroll_id: scrollId, + scroll_id: scrollId!, }, }) .then(({ body: innerResponse }) => { diff --git a/x-pack/plugins/watcher/server/routes/api/indices/register_get_route.ts b/x-pack/plugins/watcher/server/routes/api/indices/register_get_route.ts index 915871185af85..f69ee60f9cd73 100644 --- a/x-pack/plugins/watcher/server/routes/api/indices/register_get_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/indices/register_get_route.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { MultiBucketAggregate } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema } from '@kbn/config-schema'; import { IScopedClusterClient } from 'kibana/server'; import { reduce, size } from 'lodash'; @@ -64,7 +64,9 @@ async function getIndices(dataClient: IScopedClusterClient, pattern: string, lim if (response.statusCode === 404 || !response.body.aggregations) { return []; } - const indices = response.body.aggregations.indices as MultiBucketAggregate<{ key: unknown }>; + const indices = response.body.aggregations.indices as estypes.AggregationsMultiBucketAggregate<{ + key: unknown; + }>; return indices.buckets ? indices.buckets.map((bucket) => bucket.key) : []; } diff --git a/x-pack/plugins/watcher/server/routes/api/watches/register_delete_route.ts b/x-pack/plugins/watcher/server/routes/api/watches/register_delete_route.ts index e47d451c227e5..b7c09361774ab 100644 --- a/x-pack/plugins/watcher/server/routes/api/watches/register_delete_route.ts +++ b/x-pack/plugins/watcher/server/routes/api/watches/register_delete_route.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { DeleteWatchResponse } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { schema } from '@kbn/config-schema'; import { IScopedClusterClient } from 'kibana/server'; import { RouteDependencies } from '../../../types'; @@ -14,7 +14,10 @@ const bodySchema = schema.object({ watchIds: schema.arrayOf(schema.string()), }); -type DeleteWatchPromiseArray = Promise<{ success?: DeleteWatchResponse; error?: any }>; +type DeleteWatchPromiseArray = Promise<{ + success?: estypes.WatcherDeleteWatchResponse; + error?: any; +}>; function deleteWatches(dataClient: IScopedClusterClient, watchIds: string[]) { const deletePromises = watchIds.map((watchId) => { diff --git a/x-pack/test/accessibility/apps/ml.ts b/x-pack/test/accessibility/apps/ml.ts index 41f8d5e56f8e6..5436f74a2b8f9 100644 --- a/x-pack/test/accessibility/apps/ml.ts +++ b/x-pack/test/accessibility/apps/ml.ts @@ -114,7 +114,6 @@ export default function ({ getService }: FtrProviderContext) { description: 'Test calendar', }); await ml.api.createCalendarEvents(calendarId, [ - // @ts-expect-error not full interface { description: eventDescription, start_time: '1513641600000', diff --git a/x-pack/test/api_integration/apis/lens/telemetry.ts b/x-pack/test/api_integration/apis/lens/telemetry.ts index 5d00a097d32a7..5e8e12998af7e 100644 --- a/x-pack/test/api_integration/apis/lens/telemetry.ts +++ b/x-pack/test/api_integration/apis/lens/telemetry.ts @@ -41,7 +41,6 @@ export default ({ getService }: FtrProviderContext) => { beforeEach(async () => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:lens-ui-telemetry', wait_for_completion: true, refresh: true, @@ -52,7 +51,6 @@ export default ({ getService }: FtrProviderContext) => { afterEach(async () => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:lens-ui-telemetry', wait_for_completion: true, refresh: true, diff --git a/x-pack/test/api_integration/apis/ml/calendars/create_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/create_calendars.ts index 01b87e6059a29..fac62237aa74e 100644 --- a/x-pack/test/api_integration/apis/ml/calendars/create_calendars.ts +++ b/x-pack/test/api_integration/apis/ml/calendars/create_calendars.ts @@ -52,11 +52,7 @@ export default ({ getService }: FtrProviderContext) => { expect(createdCalendar.description).to.eql(requestBody.description); expect(createdCalendar.job_ids).to.eql(requestBody.job_ids); - await ml.api.waitForEventsToExistInCalendar( - calendarId, - // @ts-expect-error not full interface - requestBody.events - ); + await ml.api.waitForEventsToExistInCalendar(calendarId, requestBody.events); }); it('should not create new calendar for user without required permission', async () => { diff --git a/x-pack/test/api_integration/apis/ml/calendars/delete_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/delete_calendars.ts index dfbffad9dafdd..a2e1709731aa7 100644 --- a/x-pack/test/api_integration/apis/ml/calendars/delete_calendars.ts +++ b/x-pack/test/api_integration/apis/ml/calendars/delete_calendars.ts @@ -34,7 +34,6 @@ export default ({ getService }: FtrProviderContext) => { beforeEach(async () => { await ml.api.createCalendar(calendarId, testCalendar); - // @ts-expect-error not full interface await ml.api.createCalendarEvents(calendarId, testEvents); }); diff --git a/x-pack/test/api_integration/apis/ml/calendars/get_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/get_calendars.ts index 175c678317e6c..243a40abe97a4 100644 --- a/x-pack/test/api_integration/apis/ml/calendars/get_calendars.ts +++ b/x-pack/test/api_integration/apis/ml/calendars/get_calendars.ts @@ -35,7 +35,6 @@ export default ({ getService }: FtrProviderContext) => { beforeEach(async () => { for (const testCalendar of testCalendars) { await ml.api.createCalendar(testCalendar.calendar_id, testCalendar); - // @ts-expect-error not full interface await ml.api.createCalendarEvents(testCalendar.calendar_id, testEvents); } }); @@ -55,7 +54,6 @@ export default ({ getService }: FtrProviderContext) => { expect(body).to.have.length(testCalendars.length); expect(body[0].events).to.have.length(testEvents.length); - // @ts-expect-error not full interface ml.api.assertAllEventsExistInCalendar(testEvents, body[0]); }); @@ -68,7 +66,6 @@ export default ({ getService }: FtrProviderContext) => { expect(body).to.have.length(testCalendars.length); expect(body[0].events).to.have.length(testEvents.length); - // @ts-expect-error not full interface ml.api.assertAllEventsExistInCalendar(testEvents, body[0]); }); @@ -92,7 +89,6 @@ export default ({ getService }: FtrProviderContext) => { beforeEach(async () => { await ml.api.createCalendar(calendarId, testCalendar); - // @ts-expect-error not full interface await ml.api.createCalendarEvents(calendarId, testEvents); }); @@ -110,7 +106,6 @@ export default ({ getService }: FtrProviderContext) => { expect(body.job_ids).to.eql(testCalendar.job_ids); expect(body.description).to.eql(testCalendar.description); expect(body.events).to.have.length(testEvents.length); - // @ts-expect-error not full interface ml.api.assertAllEventsExistInCalendar(testEvents, body); }); @@ -124,7 +119,6 @@ export default ({ getService }: FtrProviderContext) => { expect(body.job_ids).to.eql(testCalendar.job_ids); expect(body.description).to.eql(testCalendar.description); expect(body.events).to.have.length(testEvents.length); - // @ts-expect-error not full interface ml.api.assertAllEventsExistInCalendar(testEvents, body); }); diff --git a/x-pack/test/api_integration/apis/ml/calendars/helpers.ts b/x-pack/test/api_integration/apis/ml/calendars/helpers.ts index f80c985c2676e..4667eb25437b1 100644 --- a/x-pack/test/api_integration/apis/ml/calendars/helpers.ts +++ b/x-pack/test/api_integration/apis/ml/calendars/helpers.ts @@ -8,7 +8,7 @@ import { estypes } from '@elastic/elasticsearch'; import { Calendar } from '../../../../../plugins/ml/server/models/calendar'; -type ScheduledEvent = estypes.ScheduledEvent; +type ScheduledEvent = estypes.MlCalendarEvent; export const assertAllEventsExistInCalendar = ( eventsToCheck: ScheduledEvent[], diff --git a/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts b/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts index 4798a3407be11..1ca9a66319943 100644 --- a/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts +++ b/x-pack/test/api_integration/apis/ml/calendars/update_calendars.ts @@ -42,7 +42,6 @@ export default ({ getService }: FtrProviderContext) => { beforeEach(async () => { await ml.api.createCalendar(calendarId, originalCalendar); - // @ts-expect-error not full interface await ml.api.createCalendarEvents(calendarId, originalEvents); }); @@ -71,7 +70,6 @@ export default ({ getService }: FtrProviderContext) => { expect(updatedEvents).to.have.length(updateCalendarRequestBody.events.length); await ml.api.waitForEventsToExistInCalendar( updatedCalendar.calendar_id, - // @ts-expect-error not full interface updateCalendarRequestBody.events ); }); diff --git a/x-pack/test/api_integration/apis/ml/jobs/jobs_summary.ts b/x-pack/test/api_integration/apis/ml/jobs/jobs_summary.ts index a0c00770f84dc..4e3be92a54b6a 100644 --- a/x-pack/test/api_integration/apis/ml/jobs/jobs_summary.ts +++ b/x-pack/test/api_integration/apis/ml/jobs/jobs_summary.ts @@ -183,10 +183,10 @@ export default ({ getService }: FtrProviderContext) => { return body; } - function getGroups(jobs: Array<{ groups: string[] }>) { + function getGroups(jobs: Array<{ groups?: string[] }>) { const groupIds: string[] = []; jobs.forEach((job) => { - const groups = job.groups; + const groups = job.groups || []; groups.forEach((group) => { if (groupIds.indexOf(group) === -1) { groupIds.push(group); diff --git a/x-pack/test/api_integration/apis/security/roles.ts b/x-pack/test/api_integration/apis/security/roles.ts index 09b2d2eef9fbe..440bb4ca32f18 100644 --- a/x-pack/test/api_integration/apis/security/roles.ts +++ b/x-pack/test/api_integration/apis/security/roles.ts @@ -312,7 +312,6 @@ export default function ({ getService }: FtrProviderContext) { metadata: { foo: 'test-metadata', }, - // @ts-expect-error @elastic/elasticsearch PutRoleRequest.body doesn't declare `transient_metadata` property transient_metadata: { enabled: true, }, diff --git a/x-pack/test/api_integration/apis/upgrade_assistant/upgrade_assistant.ts b/x-pack/test/api_integration/apis/upgrade_assistant/upgrade_assistant.ts index 7041427fb74d7..0eb0b98e29ffe 100644 --- a/x-pack/test/api_integration/apis/upgrade_assistant/upgrade_assistant.ts +++ b/x-pack/test/api_integration/apis/upgrade_assistant/upgrade_assistant.ts @@ -93,6 +93,7 @@ export default function ({ getService }: FtrProviderContext) { index: indexName, }); + // @ts-expect-error @elastic/elasticsearch supports flatten 'index.*' keys only const updatedIndexSettings = indexSettingsResponse[indexName].settings.index; // Verify number_of_shards and number_of_replicas are unchanged diff --git a/x-pack/test/apm_api_integration/tests/alerts/rule_registry.ts b/x-pack/test/apm_api_integration/tests/alerts/rule_registry.ts index e9392a611b5b7..1f8d1144349dd 100644 --- a/x-pack/test/apm_api_integration/tests/alerts/rule_registry.ts +++ b/x-pack/test/apm_api_integration/tests/alerts/rule_registry.ts @@ -603,7 +603,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { expect(errorOrUndefined).not.to.be(undefined); - expect(errorOrUndefined).to.be(`ResponseError: index_not_found_exception`); + expect(errorOrUndefined).to.contain('index_not_found_exception'); }); }); } diff --git a/x-pack/test/apm_api_integration/tests/service_overview/dependencies/es_utils.ts b/x-pack/test/apm_api_integration/tests/service_overview/dependencies/es_utils.ts index dbbc8ebc87958..b1663ea714056 100644 --- a/x-pack/test/apm_api_integration/tests/service_overview/dependencies/es_utils.ts +++ b/x-pack/test/apm_api_integration/tests/service_overview/dependencies/es_utils.ts @@ -5,6 +5,7 @@ * 2.0. */ +import { MappingTypeMapping } from '@elastic/elasticsearch/api/types'; import uuid from 'uuid'; export function createServiceDependencyDocs({ @@ -125,7 +126,7 @@ export function createServiceDependencyDocs({ ]; } -export const apmDependenciesMapping = { +export const apmDependenciesMapping: MappingTypeMapping = { properties: { '@timestamp': { type: 'date', diff --git a/x-pack/test/case_api_integration/common/lib/utils.ts b/x-pack/test/case_api_integration/common/lib/utils.ts index c66aeb67b3a5f..9ed5d84e54621 100644 --- a/x-pack/test/case_api_integration/common/lib/utils.ts +++ b/x-pack/test/case_api_integration/common/lib/utils.ts @@ -72,7 +72,7 @@ export const getSignalsWithES = async ({ es: KibanaClient; indices: string | string[]; ids: string | string[]; -}): Promise>>> => { +}): Promise>>> => { const signals: ApiResponse> = await es.search({ index: indices, body: { @@ -94,13 +94,13 @@ export const getSignalsWithES = async ({ return signals.body.hits.hits.reduce((acc, hit) => { let indexMap = acc.get(hit._index); if (indexMap === undefined) { - indexMap = new Map>([[hit._id, hit]]); + indexMap = new Map>([[hit._id, hit]]); } else { indexMap.set(hit._id, hit); } acc.set(hit._index, indexMap); return acc; - }, new Map>>()); + }, new Map>>()); }; interface SetStatusCasesParams { @@ -473,7 +473,6 @@ export const deleteAllCaseItems = async (es: KibanaClient) => { export const deleteCasesUserActions = async (es: KibanaClient): Promise => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:cases-user-actions', wait_for_completion: true, refresh: true, @@ -485,7 +484,6 @@ export const deleteCasesUserActions = async (es: KibanaClient): Promise => export const deleteCasesByESQuery = async (es: KibanaClient): Promise => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:cases', wait_for_completion: true, refresh: true, @@ -501,7 +499,6 @@ export const deleteCasesByESQuery = async (es: KibanaClient): Promise => { export const deleteSubCases = async (es: KibanaClient): Promise => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:cases-sub-case', wait_for_completion: true, refresh: true, @@ -513,7 +510,6 @@ export const deleteSubCases = async (es: KibanaClient): Promise => { export const deleteComments = async (es: KibanaClient): Promise => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:cases-comments', wait_for_completion: true, refresh: true, @@ -525,7 +521,6 @@ export const deleteComments = async (es: KibanaClient): Promise => { export const deleteConfiguration = async (es: KibanaClient): Promise => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:cases-configure', wait_for_completion: true, refresh: true, @@ -537,7 +532,6 @@ export const deleteConfiguration = async (es: KibanaClient): Promise => { export const deleteMappings = async (es: KibanaClient): Promise => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:cases-connector-mappings', wait_for_completion: true, refresh: true, diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_signals_migrations.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_signals_migrations.ts index 9bb3e776f4553..8c4ad5a2e8117 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_signals_migrations.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/delete_signals_migrations.ts @@ -96,6 +96,7 @@ export default ({ getService }: FtrProviderContext): void => { .expect(200); const { body } = await es.indices.getSettings({ index: createdMigration.index }); + // @ts-expect-error @elastic/elasticsearch supports flatten 'index.*' keys only const indexSettings = body[createdMigration.index].settings.index; expect(indexSettings.lifecycle.name).to.eql( `${DEFAULT_SIGNALS_INDEX}-default-migration-cleanup` diff --git a/x-pack/test/detection_engine_api_integration/utils.ts b/x-pack/test/detection_engine_api_integration/utils.ts index 9c5beebd64b3d..7456040a436a4 100644 --- a/x-pack/test/detection_engine_api_integration/utils.ts +++ b/x-pack/test/detection_engine_api_integration/utils.ts @@ -412,7 +412,6 @@ export const downgradeImmutableRule = async (es: KibanaClient, ruleId: string): export const deleteAllTimelines = async (es: KibanaClient): Promise => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:siem-ui-timeline', wait_for_completion: true, refresh: true, @@ -429,7 +428,6 @@ export const deleteAllRulesStatuses = async (es: KibanaClient): Promise => return countDownES(async () => { return es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:siem-detection-engine-rule-status', wait_for_completion: true, refresh: true, diff --git a/x-pack/test/encrypted_saved_objects_api_integration/tests/encrypted_saved_objects_api.ts b/x-pack/test/encrypted_saved_objects_api_integration/tests/encrypted_saved_objects_api.ts index 66dc10f3132cc..7128d9397f0ea 100644 --- a/x-pack/test/encrypted_saved_objects_api_integration/tests/encrypted_saved_objects_api.ts +++ b/x-pack/test/encrypted_saved_objects_api_integration/tests/encrypted_saved_objects_api.ts @@ -443,7 +443,6 @@ export default function ({ getService }: FtrProviderContext) { afterEach(async () => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch `DeleteByQueryRequest` type doesn't define `q`. q: `type:${SAVED_OBJECT_WITH_SECRET_TYPE} OR type:${HIDDEN_SAVED_OBJECT_WITH_SECRET_TYPE} OR type:${SAVED_OBJECT_WITH_SECRET_AND_MULTIPLE_SPACES_TYPE} OR type:${SAVED_OBJECT_WITHOUT_SECRET_TYPE}`, refresh: true, body: {}, @@ -493,7 +492,6 @@ export default function ({ getService }: FtrProviderContext) { afterEach(async () => { await es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch `DeleteByQueryRequest` type doesn't define `q`. q: `type:${SAVED_OBJECT_WITH_SECRET_TYPE} OR type:${HIDDEN_SAVED_OBJECT_WITH_SECRET_TYPE} OR type:${SAVED_OBJECT_WITH_SECRET_AND_MULTIPLE_SPACES_TYPE} OR type:${SAVED_OBJECT_WITHOUT_SECRET_TYPE}`, refresh: true, body: {}, diff --git a/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts b/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts index 25fb71ae42807..b38458f7334c4 100644 --- a/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts +++ b/x-pack/test/fleet_api_integration/apis/enrollment_api_keys/crud.ts @@ -177,7 +177,6 @@ export default function (providerContext: FtrProviderContext) { id: apiResponse.item.api_key_id, }); - // @ts-expect-error Metadata not yet in the client type expect(apiKeyRes.api_keys[0].metadata).eql({ policy_id: 'policy1', managed_by: 'fleet', diff --git a/x-pack/test/functional/apps/ml/permissions/full_ml_access.ts b/x-pack/test/functional/apps/ml/permissions/full_ml_access.ts index a203b078774c7..87f74363413d3 100644 --- a/x-pack/test/functional/apps/ml/permissions/full_ml_access.ts +++ b/x-pack/test/functional/apps/ml/permissions/full_ml_access.ts @@ -136,7 +136,6 @@ export default function ({ getService }: FtrProviderContext) { description: 'Test calendar', }); await ml.api.createCalendarEvents(calendarId, [ - // @ts-expect-error not full interface { description: eventDescription, start_time: '1513641600000', diff --git a/x-pack/test/functional/apps/ml/permissions/read_ml_access.ts b/x-pack/test/functional/apps/ml/permissions/read_ml_access.ts index 55cfb035d0cfe..5e6e179a7bdcc 100644 --- a/x-pack/test/functional/apps/ml/permissions/read_ml_access.ts +++ b/x-pack/test/functional/apps/ml/permissions/read_ml_access.ts @@ -137,7 +137,6 @@ export default function ({ getService }: FtrProviderContext) { description: 'Test calendar', }); await ml.api.createCalendarEvents(calendarId, [ - // @ts-expect-error not full interface { description: eventDescription, start_time: '1513641600000', diff --git a/x-pack/test/functional/apps/ml/settings/calendar_edit.ts b/x-pack/test/functional/apps/ml/settings/calendar_edit.ts index 1237cd8d71b8c..a643c4eb34299 100644 --- a/x-pack/test/functional/apps/ml/settings/calendar_edit.ts +++ b/x-pack/test/functional/apps/ml/settings/calendar_edit.ts @@ -35,7 +35,6 @@ export default function ({ getService }: FtrProviderContext) { job_ids: jobConfigs.map((c) => c.job_id), description: 'Test calendar', }); - // @ts-expect-error not full interface await ml.api.createCalendarEvents(calendarId, testEvents); await ml.testResources.setKibanaTimeZoneToUTC(); diff --git a/x-pack/test/functional/services/ml/api.ts b/x-pack/test/functional/services/ml/api.ts index 4623b4f4e41ae..9a96b1ec372dc 100644 --- a/x-pack/test/functional/services/ml/api.ts +++ b/x-pack/test/functional/services/ml/api.ts @@ -384,7 +384,7 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { }); }, - async createCalendarEvents(calendarId: string, events: estypes.ScheduledEvent[]) { + async createCalendarEvents(calendarId: string, events: estypes.MlCalendarEvent[]) { log.debug(`Creating events for calendar with id '${calendarId}'...`); await esSupertest.post(`/_ml/calendars/${calendarId}/events`).send({ events }).expect(200); await this.waitForEventsToExistInCalendar(calendarId, events); @@ -396,7 +396,7 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { }, assertAllEventsExistInCalendar: ( - eventsToCheck: estypes.ScheduledEvent[], + eventsToCheck: estypes.MlCalendarEvent[], calendar: Calendar ): boolean => { const updatedCalendarEvents = calendar.events; @@ -409,7 +409,7 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { (updatedEvent) => updatedEvent.description === eventToCheck.description && // updatedEvent are fetched with suptertest which converts start_time and end_time to number - // sometimes eventToCheck declared manually with types incompatible with estypes.ScheduledEvent + // sometimes eventToCheck declared manually with types incompatible with estypes.MlCalendarEvent String(updatedEvent.start_time) === String(eventToCheck.start_time) && String(updatedEvent.end_time) === String(eventToCheck.end_time) ) < 0 @@ -429,7 +429,7 @@ export function MachineLearningAPIProvider({ getService }: FtrProviderContext) { async waitForEventsToExistInCalendar( calendarId: string, - eventsToCheck: estypes.ScheduledEvent[], + eventsToCheck: estypes.MlCalendarEvent[], errorMsg?: string ) { await retry.waitForWithTimeout(`'${calendarId}' events to exist`, 5 * 1000, async () => { diff --git a/x-pack/test/functional_with_es_ssl/apps/ml/alert_flyout.ts b/x-pack/test/functional_with_es_ssl/apps/ml/alert_flyout.ts index 1a8395a1b49df..2c80f4b2ebd91 100644 --- a/x-pack/test/functional_with_es_ssl/apps/ml/alert_flyout.ts +++ b/x-pack/test/functional_with_es_ssl/apps/ml/alert_flyout.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { Datafeed } from '@elastic/elasticsearch/api/types'; +import type { estypes } from '@elastic/elasticsearch'; import { FtrProviderContext } from '../../ftr_provider_context'; import { DATAFEED_STATE } from '../../../../plugins/ml/common/constants/states'; @@ -56,7 +56,7 @@ function createTestJobAndDatafeed() { }, query_delay: '120s', indices: ['ft_ecommerce'], - } as unknown) as Datafeed, + } as unknown) as estypes.MlDatafeed, }; } diff --git a/x-pack/test/lists_api_integration/utils.ts b/x-pack/test/lists_api_integration/utils.ts index 2467e613ca2f5..90103ec8b856c 100644 --- a/x-pack/test/lists_api_integration/utils.ts +++ b/x-pack/test/lists_api_integration/utils.ts @@ -161,7 +161,6 @@ export const deleteAllExceptions = async (es: KibanaClient): Promise => { return countDownES(async () => { return es.deleteByQuery({ index: '.kibana', - // @ts-expect-error @elastic/elasticsearch DeleteByQueryRequest doesn't accept q parameter q: 'type:exception-list or type:exception-list-agnostic', wait_for_completion: true, refresh: true, diff --git a/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts b/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts index 26333ecabd505..b8ba9c93fe8b0 100644 --- a/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts +++ b/x-pack/test/plugin_api_integration/test_suites/task_manager/task_management.ts @@ -7,6 +7,7 @@ import _ from 'lodash'; import expect from '@kbn/expect'; +import type { estypes } from '@elastic/elasticsearch'; import url from 'url'; import supertestAsPromised from 'supertest-as-promised'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -87,7 +88,7 @@ export default function ({ getService }: FtrProviderContext) { params: taskManagerIndexMapping.params, state: taskManagerIndexMapping.state, runAt: taskManagerIndexMapping.runAt, - }, + } as Record, }, }, }); diff --git a/x-pack/test/saved_object_api_integration/common/fixtures/saved_object_test_plugin/server/plugin.ts b/x-pack/test/saved_object_api_integration/common/fixtures/saved_object_test_plugin/server/plugin.ts index e29bbc0db56b6..36bbbb4bb8755 100644 --- a/x-pack/test/saved_object_api_integration/common/fixtures/saved_object_test_plugin/server/plugin.ts +++ b/x-pack/test/saved_object_api_integration/common/fixtures/saved_object_test_plugin/server/plugin.ts @@ -22,7 +22,7 @@ export class Plugin { properties: { title: { type: 'text' }, }, - }; + } as const; core.savedObjects.registerType({ name: 'isolatedtype', diff --git a/x-pack/test/security_api_integration/tests/anonymous/login.ts b/x-pack/test/security_api_integration/tests/anonymous/login.ts index 30d5d3ea33120..05f3adf2b8cb6 100644 --- a/x-pack/test/security_api_integration/tests/anonymous/login.ts +++ b/x-pack/test/security_api_integration/tests/anonymous/login.ts @@ -162,12 +162,13 @@ export default function ({ getService }: FtrProviderContext) { .set('kbn-xsrf', 'xxx') .set('Authorization', 'Basic ZHVtbXlfaGFja2VyOnBhc3M=') .set('Cookie', sessionCookie.cookieString()) - .expect(401, { - statusCode: 401, - error: 'Unauthorized', - message: - '[security_exception]: unable to authenticate user [dummy_hacker] for REST request [/_security/_authenticate]', - }); + .expect(401); + + expect(apiResponse.body.statusCode).to.be(401); + expect(apiResponse.body.error).to.be('Unauthorized'); + expect(apiResponse.body.message).to.include.string( + '[security_exception] Reason: unable to authenticate user [dummy_hacker] for REST request [/_security/_authenticate]' + ); expect(apiResponse.headers['set-cookie']).to.be(undefined); }); diff --git a/yarn.lock b/yarn.lock index df3852fdd5220..56b3c417945b8 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1410,16 +1410,15 @@ dependencies: "@elastic/ecs-helpers" "^1.1.0" -"@elastic/elasticsearch@npm:@elastic/elasticsearch-canary@7.13.0-canary.1": - version "7.13.0-canary.1" - resolved "https://registry.yarnpkg.com/@elastic/elasticsearch-canary/-/elasticsearch-canary-7.13.0-canary.1.tgz#53a8ddbaeaba77dc163aad972e56d6741c98858a" - integrity sha512-RqJxZyouL/lTN4EgBvN9xQKq0zUIzSUAks91q/UvM41XyATTeTa2e9+zxrK07JCi0R6l/xAlHrLglf1/LiJOyg== +"@elastic/elasticsearch@npm:@elastic/elasticsearch-canary@7.14.0-canary.6": + version "7.14.0-canary.6" + resolved "https://registry.yarnpkg.com/@elastic/elasticsearch-canary/-/elasticsearch-canary-7.14.0-canary.6.tgz#29ae3f53708e94d7efbd9d1a228f6b9f83f03645" + integrity sha512-Se4ClajPQn5T3h6vil4Jvje+ic29kD3boM1AfOEWhNieGz48JMJSxNX31OiaD0Q7MsVLVKd6Xx0rXqzgMXDd1A== dependencies: debug "^4.3.1" hpagent "^0.1.1" ms "^2.1.3" - pump "^3.0.0" - secure-json-parse "^2.3.1" + secure-json-parse "^2.4.0" "@elastic/ems-client@7.13.0": version "7.13.0" @@ -24712,10 +24711,10 @@ scss-tokenizer@^0.2.3: js-base64 "^2.1.8" source-map "^0.4.2" -secure-json-parse@^2.3.1: - version "2.3.1" - resolved "https://registry.yarnpkg.com/secure-json-parse/-/secure-json-parse-2.3.1.tgz#908aa5e806e223ff8d179d37ad95c2433f5f147d" - integrity sha512-5uGhQLHSC9tVa7RGPkSwxbZVsJCZvIODOadAimCXkU1aCa1fWdszj2DktcutK8A7dD58PoRdxTYiy0jFl6qjnw== +secure-json-parse@^2.4.0: + version "2.4.0" + resolved "https://registry.yarnpkg.com/secure-json-parse/-/secure-json-parse-2.4.0.tgz#5aaeaaef85c7a417f76271a4f5b0cc3315ddca85" + integrity sha512-Q5Z/97nbON5t/L/sH6mY2EacfjVGwrCcSi5D3btRO2GZ8pf1K1UN7Z9H5J57hjVU2Qzxr1xO+FmBhOvEkzCMmg== seed-random@~2.2.0: version "2.2.0"