,
{ uiActions }: UiActionExamplesSetupDependencies
diff --git a/package.json b/package.json
index e16d88689dc3b..e6015c88f95a0 100644
--- a/package.json
+++ b/package.json
@@ -584,7 +584,7 @@
"@types/pdfmake": "^0.1.15",
"@types/pegjs": "^0.10.1",
"@types/pngjs": "^3.4.0",
- "@types/prettier": "^2.1.5",
+ "@types/prettier": "^2.3.2",
"@types/pretty-ms": "^5.0.0",
"@types/prop-types": "^15.7.3",
"@types/rbush": "^3.0.0",
@@ -705,7 +705,7 @@
"eslint-plugin-no-unsanitized": "^3.0.2",
"eslint-plugin-node": "^11.0.0",
"eslint-plugin-prefer-object-spread": "^1.2.1",
- "eslint-plugin-prettier": "^3.1.4",
+ "eslint-plugin-prettier": "^3.4.1",
"eslint-plugin-react": "^7.20.3",
"eslint-plugin-react-hooks": "^4.2.0",
"eslint-plugin-react-perf": "^3.2.3",
@@ -782,7 +782,7 @@
"postcss": "^7.0.32",
"postcss-loader": "^3.0.0",
"postcss-prefix-selector": "^1.7.2",
- "prettier": "^2.2.0",
+ "prettier": "^2.4.0",
"pretty-ms": "5.0.0",
"q": "^1.5.1",
"react-test-renderer": "^16.12.0",
diff --git a/packages/kbn-analytics/src/application_usage_tracker.ts b/packages/kbn-analytics/src/application_usage_tracker.ts
index b1cc47334541a..751fb9203fe62 100644
--- a/packages/kbn-analytics/src/application_usage_tracker.ts
+++ b/packages/kbn-analytics/src/application_usage_tracker.ts
@@ -132,9 +132,9 @@ export class ApplicationUsageTracker {
}
public pauseTrackingAll() {
- this.currentApplicationKeys = Object.values(
- this.trackedApplicationViews
- ).map(({ appId, viewId }) => this.createKey(appId, viewId));
+ this.currentApplicationKeys = Object.values(this.trackedApplicationViews).map(
+ ({ appId, viewId }) => this.createKey(appId, viewId)
+ );
this.flushTrackedViews();
}
diff --git a/packages/kbn-config-schema/src/types/object_type.ts b/packages/kbn-config-schema/src/types/object_type.ts
index 284ea6fddb35b..784b17a92c397 100644
--- a/packages/kbn-config-schema/src/types/object_type.ts
+++ b/packages/kbn-config-schema/src/types/object_type.ts
@@ -35,8 +35,9 @@ type RequiredProperties = Pick<
// Because of https://github.com/Microsoft/TypeScript/issues/14041
// this might not have perfect _rendering_ output, but it will be typed.
export type ObjectResultType = Readonly<
- { [K in keyof OptionalProperties
]?: TypeOf
} &
- { [K in keyof RequiredProperties
]: TypeOf
}
+ { [K in keyof OptionalProperties
]?: TypeOf
} & {
+ [K in keyof RequiredProperties
]: TypeOf
;
+ }
>;
type DefinedProperties = Pick<
@@ -46,8 +47,9 @@ type DefinedProperties = Pick<
}[keyof Base]
>;
-type ExtendedProps
= Omit
&
- { [K in keyof DefinedProperties]: NP[K] };
+type ExtendedProps = Omit
& {
+ [K in keyof DefinedProperties]: NP[K];
+};
type ExtendedObjectType = ObjectType<
ExtendedProps
diff --git a/packages/kbn-config/src/deprecation/deprecation_factory.ts b/packages/kbn-config/src/deprecation/deprecation_factory.ts
index 6d7669cef04f2..119b9b11237dc 100644
--- a/packages/kbn-config/src/deprecation/deprecation_factory.ts
+++ b/packages/kbn-config/src/deprecation/deprecation_factory.ts
@@ -125,31 +125,25 @@ const _unused = (
};
};
-const rename = (
- oldKey: string,
- newKey: string,
- details?: Partial
-): ConfigDeprecation => (config, rootPath, addDeprecation) =>
- _rename(config, rootPath, addDeprecation, oldKey, newKey, details);
+const rename =
+ (oldKey: string, newKey: string, details?: Partial): ConfigDeprecation =>
+ (config, rootPath, addDeprecation) =>
+ _rename(config, rootPath, addDeprecation, oldKey, newKey, details);
-const renameFromRoot = (
- oldKey: string,
- newKey: string,
- details?: Partial
-): ConfigDeprecation => (config, rootPath, addDeprecation) =>
- _rename(config, '', addDeprecation, oldKey, newKey, details);
+const renameFromRoot =
+ (oldKey: string, newKey: string, details?: Partial): ConfigDeprecation =>
+ (config, rootPath, addDeprecation) =>
+ _rename(config, '', addDeprecation, oldKey, newKey, details);
-const unused = (
- unusedKey: string,
- details?: Partial
-): ConfigDeprecation => (config, rootPath, addDeprecation) =>
- _unused(config, rootPath, addDeprecation, unusedKey, details);
+const unused =
+ (unusedKey: string, details?: Partial): ConfigDeprecation =>
+ (config, rootPath, addDeprecation) =>
+ _unused(config, rootPath, addDeprecation, unusedKey, details);
-const unusedFromRoot = (
- unusedKey: string,
- details?: Partial
-): ConfigDeprecation => (config, rootPath, addDeprecation) =>
- _unused(config, '', addDeprecation, unusedKey, details);
+const unusedFromRoot =
+ (unusedKey: string, details?: Partial): ConfigDeprecation =>
+ (config, rootPath, addDeprecation) =>
+ _unused(config, '', addDeprecation, unusedKey, details);
const getPath = (rootPath: string, subPath: string) =>
rootPath !== '' ? `${rootPath}.${subPath}` : subPath;
diff --git a/packages/kbn-docs-utils/src/api_docs/build_api_docs_cli.ts b/packages/kbn-docs-utils/src/api_docs/build_api_docs_cli.ts
index 5b973977c86d9..a45c9035baa31 100644
--- a/packages/kbn-docs-utils/src/api_docs/build_api_docs_cli.ts
+++ b/packages/kbn-docs-utils/src/api_docs/build_api_docs_cli.ts
@@ -74,15 +74,11 @@ export function runBuildApiDocsCli() {
}
const collectReferences = flags.references as boolean;
- const {
- pluginApiMap,
- missingApiItems,
- unReferencedDeprecations,
- referencedDeprecations,
- } = getPluginApiMap(project, plugins, log, {
- collectReferences,
- pluginFilter: pluginFilter as string[],
- });
+ const { pluginApiMap, missingApiItems, unReferencedDeprecations, referencedDeprecations } =
+ getPluginApiMap(project, plugins, log, {
+ collectReferences,
+ pluginFilter: pluginFilter as string[],
+ });
const reporter = CiStatsReporter.fromEnv(log);
plugins.forEach((plugin) => {
diff --git a/packages/kbn-docs-utils/src/api_docs/tests/__fixtures__/src/plugin_a/public/fns.ts b/packages/kbn-docs-utils/src/api_docs/tests/__fixtures__/src/plugin_a/public/fns.ts
index c2a932f7d9134..8bcf2bb7ab185 100644
--- a/packages/kbn-docs-utils/src/api_docs/tests/__fixtures__/src/plugin_a/public/fns.ts
+++ b/packages/kbn-docs-utils/src/api_docs/tests/__fixtures__/src/plugin_a/public/fns.ts
@@ -60,11 +60,15 @@ export const arrowFn = (
* @returns I have no idea.
*
*/
-export const crazyFunction = (
- obj: { hi: string },
- { fn1, fn2 }: { fn1: (foo: { param: string }) => number; fn2: () => void },
- { str }: { str: string }
-) => () => () => fn1({ param: str });
+export const crazyFunction =
+ (
+ obj: { hi: string },
+ { fn1, fn2 }: { fn1: (foo: { param: string }) => number; fn2: () => void },
+ { str }: { str: string }
+ ) =>
+ () =>
+ () =>
+ fn1({ param: str });
export const fnWithNonExportedRef = (a: ImNotExportedFromIndex) => a;
diff --git a/packages/kbn-es-query/src/es_query/from_filters.test.ts b/packages/kbn-es-query/src/es_query/from_filters.test.ts
index e3a56b5a9d63d..0e376fe3f299e 100644
--- a/packages/kbn-es-query/src/es_query/from_filters.test.ts
+++ b/packages/kbn-es-query/src/es_query/from_filters.test.ts
@@ -60,7 +60,7 @@ describe('build query', () => {
});
test('should remove falsy filters', () => {
- const filters = ([null, undefined] as unknown) as Filter[];
+ const filters = [null, undefined] as unknown as Filter[];
const result = buildQueryFromFilters(filters, indexPattern, false);
expect(result.must_not).toEqual([]);
diff --git a/packages/kbn-es-query/src/es_query/from_lucene.test.ts b/packages/kbn-es-query/src/es_query/from_lucene.test.ts
index e4ca435ae8862..bed8333c762de 100644
--- a/packages/kbn-es-query/src/es_query/from_lucene.test.ts
+++ b/packages/kbn-es-query/src/es_query/from_lucene.test.ts
@@ -26,10 +26,10 @@ describe('build query', () => {
});
test("should transform an array of lucene queries into ES queries combined in the bool's must clause", () => {
- const queries = ([
+ const queries = [
{ query: 'foo:bar', language: 'lucene' },
{ query: 'bar:baz', language: 'lucene' },
- ] as unknown) as Query[];
+ ] as unknown as Query[];
const expectedESQueries = queries.map((query) => {
return decorateQuery(luceneStringToDsl(query.query), {});
});
@@ -40,7 +40,7 @@ describe('build query', () => {
});
test('should also accept queries in ES query DSL format, simply passing them through', () => {
- const queries = ([{ query: { match_all: {} }, language: 'lucene' }] as unknown) as Query[];
+ const queries = [{ query: { match_all: {} }, language: 'lucene' }] as unknown as Query[];
const result = buildQueryFromLucene(queries, {});
expect(result.must).toEqual([queries[0].query]);
@@ -48,10 +48,10 @@ describe('build query', () => {
});
test("should accept a date format in the decorated queries and combine that into the bool's must clause", () => {
- const queries = ([
+ const queries = [
{ query: 'foo:bar', language: 'lucene' },
{ query: 'bar:baz', language: 'lucene' },
- ] as unknown) as Query[];
+ ] as unknown as Query[];
const dateFormatTZ = 'America/Phoenix';
const expectedESQueries = queries.map((query) => {
return decorateQuery(luceneStringToDsl(query.query), {}, dateFormatTZ);
diff --git a/packages/kbn-es-query/src/es_query/migrate_filter.test.ts b/packages/kbn-es-query/src/es_query/migrate_filter.test.ts
index ed01ce22e2edc..77118e2cbdb1c 100644
--- a/packages/kbn-es-query/src/es_query/migrate_filter.test.ts
+++ b/packages/kbn-es-query/src/es_query/migrate_filter.test.ts
@@ -11,7 +11,7 @@ import { migrateFilter, DeprecatedMatchPhraseFilter } from './migrate_filter';
import { PhraseFilter, MatchAllFilter } from '../filters';
describe('migrateFilter', function () {
- const oldMatchPhraseFilter = ({
+ const oldMatchPhraseFilter = {
query: {
match: {
fieldFoo: {
@@ -21,9 +21,9 @@ describe('migrateFilter', function () {
},
},
meta: {},
- } as unknown) as DeprecatedMatchPhraseFilter;
+ } as unknown as DeprecatedMatchPhraseFilter;
- const newMatchPhraseFilter = ({
+ const newMatchPhraseFilter = {
query: {
match_phrase: {
fieldFoo: {
@@ -32,7 +32,7 @@ describe('migrateFilter', function () {
},
},
meta: {},
- } as unknown) as PhraseFilter;
+ } as unknown as PhraseFilter;
it('should migrate match filters of type phrase', function () {
const migratedFilter = migrateFilter(oldMatchPhraseFilter, undefined);
diff --git a/packages/kbn-es-query/src/filters/build_filters/range_filter.test.ts b/packages/kbn-es-query/src/filters/build_filters/range_filter.test.ts
index 32909fcc8cf9a..8895b766e2335 100644
--- a/packages/kbn-es-query/src/filters/build_filters/range_filter.test.ts
+++ b/packages/kbn-es-query/src/filters/build_filters/range_filter.test.ts
@@ -203,9 +203,9 @@ describe('Range filter builder', () => {
});
describe('getRangeFilterField', function () {
- const indexPattern: IndexPatternBase = ({
+ const indexPattern: IndexPatternBase = {
fields,
- } as unknown) as IndexPatternBase;
+ } as unknown as IndexPatternBase;
test('should return the name of the field a range query is targeting', () => {
const field = indexPattern.fields.find((patternField) => patternField.name === 'bytes');
diff --git a/packages/kbn-es-query/src/kuery/ast/ast.test.ts b/packages/kbn-es-query/src/kuery/ast/ast.test.ts
index 459ace026796c..edb9150ea00d5 100644
--- a/packages/kbn-es-query/src/kuery/ast/ast.test.ts
+++ b/packages/kbn-es-query/src/kuery/ast/ast.test.ts
@@ -371,7 +371,7 @@ describe('kuery AST API', () => {
indexPattern
);
- expect(toElasticsearchQuery((null as unknown) as KueryNode, undefined)).toEqual(expected);
+ expect(toElasticsearchQuery(null as unknown as KueryNode, undefined)).toEqual(expected);
const noTypeNode = nodeTypes.function.buildNode('exists', 'foo');
diff --git a/packages/kbn-es-query/src/kuery/ast/ast.ts b/packages/kbn-es-query/src/kuery/ast/ast.ts
index 7145eb5043c60..c1b4380ecbfe3 100644
--- a/packages/kbn-es-query/src/kuery/ast/ast.ts
+++ b/packages/kbn-es-query/src/kuery/ast/ast.ts
@@ -75,6 +75,6 @@ export const toElasticsearchQuery = (
}
// TODO: the return type of this function might be incorrect and it works only because of this casting
- const nodeType = (nodeTypes[node.type] as unknown) as any;
+ const nodeType = nodeTypes[node.type] as unknown as any;
return nodeType.toElasticsearchQuery(node, indexPattern, config, context);
};
diff --git a/packages/kbn-es-query/src/kuery/functions/is.ts b/packages/kbn-es-query/src/kuery/functions/is.ts
index 4dc0a66d3d9fa..596dd91df22b3 100644
--- a/packages/kbn-es-query/src/kuery/functions/is.ts
+++ b/packages/kbn-es-query/src/kuery/functions/is.ts
@@ -76,7 +76,7 @@ export function toElasticsearchQuery(
return {
multi_match: {
type,
- query: (value as unknown) as string,
+ query: value as unknown as string,
lenient: true,
},
};
@@ -90,7 +90,7 @@ export function toElasticsearchQuery(
// keep things familiar for now.
if (fields && fields.length === 0) {
fields.push({
- name: (ast.toElasticsearchQuery(fullFieldNameArg) as unknown) as string,
+ name: ast.toElasticsearchQuery(fullFieldNameArg) as unknown as string,
scripted: false,
type: '',
});
diff --git a/packages/kbn-es-query/src/kuery/functions/nested.ts b/packages/kbn-es-query/src/kuery/functions/nested.ts
index 3a3be4c10eade..e59f7a6acc07d 100644
--- a/packages/kbn-es-query/src/kuery/functions/nested.ts
+++ b/packages/kbn-es-query/src/kuery/functions/nested.ts
@@ -26,7 +26,7 @@ export function toElasticsearchQuery(
context: Record = {}
): estypes.QueryDslQueryContainer {
const [path, child] = node.arguments;
- const stringPath = (ast.toElasticsearchQuery(path) as unknown) as string;
+ const stringPath = ast.toElasticsearchQuery(path) as unknown as string;
const fullPath = context?.nested?.path ? `${context.nested.path}.${stringPath}` : stringPath;
return {
diff --git a/packages/kbn-es-query/src/kuery/functions/range.ts b/packages/kbn-es-query/src/kuery/functions/range.ts
index 6b5810bb7518f..51f686925518d 100644
--- a/packages/kbn-es-query/src/kuery/functions/range.ts
+++ b/packages/kbn-es-query/src/kuery/functions/range.ts
@@ -57,7 +57,7 @@ export function toElasticsearchQuery(
// keep things familiar for now.
if (fields && fields.length === 0) {
fields.push({
- name: (ast.toElasticsearchQuery(fullFieldNameArg) as unknown) as string,
+ name: ast.toElasticsearchQuery(fullFieldNameArg) as unknown as string,
scripted: false,
type: '',
});
diff --git a/packages/kbn-es-query/src/kuery/functions/utils/get_fields.test.ts b/packages/kbn-es-query/src/kuery/functions/utils/get_fields.test.ts
index 4125b0a572566..2a63614fadd04 100644
--- a/packages/kbn-es-query/src/kuery/functions/utils/get_fields.test.ts
+++ b/packages/kbn-es-query/src/kuery/functions/utils/get_fields.test.ts
@@ -18,9 +18,9 @@ describe('getFields', () => {
let indexPattern: IndexPatternBase;
beforeEach(() => {
- indexPattern = ({
+ indexPattern = {
fields,
- } as unknown) as IndexPatternBase;
+ } as unknown as IndexPatternBase;
});
describe('field names without a wildcard', () => {
@@ -41,14 +41,14 @@ describe('getFields', () => {
});
test('should not match a wildcard in a literal node', () => {
- const indexPatternWithWildField: IndexPatternBase = ({
+ const indexPatternWithWildField: IndexPatternBase = {
title: 'wildIndex',
fields: [
{
name: 'foo*',
},
],
- } as unknown) as IndexPatternBase;
+ } as unknown as IndexPatternBase;
const fieldNameNode = nodeTypes.literal.buildNode('foo*');
const results = getFields(fieldNameNode, indexPatternWithWildField);
diff --git a/packages/kbn-i18n/src/core/pseudo_locale.ts b/packages/kbn-i18n/src/core/pseudo_locale.ts
index daa1b76391f76..10fd086169b6c 100644
--- a/packages/kbn-i18n/src/core/pseudo_locale.ts
+++ b/packages/kbn-i18n/src/core/pseudo_locale.ts
@@ -9,7 +9,8 @@
/**
* Matches every single [A-Za-z] character, ``, `](markdown-link-address)` and `@I18N@valid_variable_name@I18N@`
*/
-const CHARS_FOR_PSEUDO_LOCALIZATION_REGEX = /[A-Za-z]|(\]\([\s\S]*?\))|(<([^"<>]|("[^"]*?"))*?>)|(@I18N@\w*?@I18N@)/g;
+const CHARS_FOR_PSEUDO_LOCALIZATION_REGEX =
+ /[A-Za-z]|(\]\([\s\S]*?\))|(<([^"<>]|("[^"]*?"))*?>)|(@I18N@\w*?@I18N@)/g;
const PSEUDO_ACCENTS_LOCALE = 'en-xa';
export function isPseudoLocale(locale: string) {
diff --git a/packages/kbn-io-ts-utils/src/merge_rt/index.ts b/packages/kbn-io-ts-utils/src/merge_rt/index.ts
index c582767fb5101..b2c3ea03938d8 100644
--- a/packages/kbn-io-ts-utils/src/merge_rt/index.ts
+++ b/packages/kbn-io-ts-utils/src/merge_rt/index.ts
@@ -14,10 +14,9 @@ type PlainObject = Record;
type DeepMerge = U extends PlainObject
? T extends PlainObject
- ? Omit &
- {
- [key in keyof U]: T extends { [k in key]: any } ? DeepMerge : U[key];
- }
+ ? Omit & {
+ [key in keyof U]: T extends { [k in key]: any } ? DeepMerge : U[key];
+ }
: U
: U;
diff --git a/packages/kbn-legacy-logging/src/legacy_logging_server.ts b/packages/kbn-legacy-logging/src/legacy_logging_server.ts
index 3ece0f6f1ee47..c02eb2803515a 100644
--- a/packages/kbn-legacy-logging/src/legacy_logging_server.ts
+++ b/packages/kbn-legacy-logging/src/legacy_logging_server.ts
@@ -96,7 +96,7 @@ export class LegacyLoggingServer {
},
});
- setupLogging((this as unknown) as Server, loggingConfig, 2147483647);
+ setupLogging(this as unknown as Server, loggingConfig, 2147483647);
}
public register({ plugin: { register }, options }: PluginRegisterParams): Promise {
diff --git a/packages/kbn-optimizer/src/common/array_helpers.ts b/packages/kbn-optimizer/src/common/array_helpers.ts
index b486f1a14c971..1dbce46f2e8a7 100644
--- a/packages/kbn-optimizer/src/common/array_helpers.ts
+++ b/packages/kbn-optimizer/src/common/array_helpers.ts
@@ -22,28 +22,30 @@ type Comparator = (a: T, b: T) => number;
* - If the values for a getter are equal the next getter is
* used to compare the items.
*/
-export const ascending = (...getters: Array>): Comparator => (a, b) => {
- for (const getter of getters) {
- const valA = getter(a);
- const valB = getter(b);
+export const ascending =
+ (...getters: Array>): Comparator =>
+ (a, b) => {
+ for (const getter of getters) {
+ const valA = getter(a);
+ const valB = getter(b);
- if (valA === valB) {
- continue;
- }
- if (valA === undefined) {
- return -1;
- }
- if (valB === undefined) {
- return 1;
- }
+ if (valA === valB) {
+ continue;
+ }
+ if (valA === undefined) {
+ return -1;
+ }
+ if (valB === undefined) {
+ return 1;
+ }
- return typeof valA === 'string' || typeof valB === 'string'
- ? String(valA).localeCompare(String(valB))
- : valA - valB;
- }
+ return typeof valA === 'string' || typeof valB === 'string'
+ ? String(valA).localeCompare(String(valB))
+ : valA - valB;
+ }
- return 0;
-};
+ return 0;
+ };
/**
* create a sort comparator that sorts values in descending
diff --git a/packages/kbn-optimizer/src/common/bundle.ts b/packages/kbn-optimizer/src/common/bundle.ts
index 08946deec0b47..7feaa960b79e7 100644
--- a/packages/kbn-optimizer/src/common/bundle.ts
+++ b/packages/kbn-optimizer/src/common/bundle.ts
@@ -179,76 +179,74 @@ export function parseBundles(json: string) {
throw new Error('must be an array');
}
- return specs.map(
- (spec: UnknownVals): Bundle => {
- if (!(spec && typeof spec === 'object')) {
- throw new Error('`bundles[]` must be an object');
- }
+ return specs.map((spec: UnknownVals): Bundle => {
+ if (!(spec && typeof spec === 'object')) {
+ throw new Error('`bundles[]` must be an object');
+ }
- const { type } = spec;
- if (!includes(VALID_BUNDLE_TYPES, type)) {
- throw new Error('`bundles[]` must have a valid `type`');
- }
+ const { type } = spec;
+ if (!includes(VALID_BUNDLE_TYPES, type)) {
+ throw new Error('`bundles[]` must have a valid `type`');
+ }
- const { id } = spec;
- if (!(typeof id === 'string')) {
- throw new Error('`bundles[]` must have a string `id` property');
- }
+ const { id } = spec;
+ if (!(typeof id === 'string')) {
+ throw new Error('`bundles[]` must have a string `id` property');
+ }
- const { publicDirNames } = spec;
- if (!Array.isArray(publicDirNames) || !publicDirNames.every((d) => typeof d === 'string')) {
- throw new Error('`bundles[]` must have an array of strings `publicDirNames` property');
- }
+ const { publicDirNames } = spec;
+ if (!Array.isArray(publicDirNames) || !publicDirNames.every((d) => typeof d === 'string')) {
+ throw new Error('`bundles[]` must have an array of strings `publicDirNames` property');
+ }
- const { contextDir } = spec;
- if (!(typeof contextDir === 'string' && Path.isAbsolute(contextDir))) {
- throw new Error('`bundles[]` must have an absolute path `contextDir` property');
- }
+ const { contextDir } = spec;
+ if (!(typeof contextDir === 'string' && Path.isAbsolute(contextDir))) {
+ throw new Error('`bundles[]` must have an absolute path `contextDir` property');
+ }
- const { sourceRoot } = spec;
- if (!(typeof sourceRoot === 'string' && Path.isAbsolute(sourceRoot))) {
- throw new Error('`bundles[]` must have an absolute path `sourceRoot` property');
- }
+ const { sourceRoot } = spec;
+ if (!(typeof sourceRoot === 'string' && Path.isAbsolute(sourceRoot))) {
+ throw new Error('`bundles[]` must have an absolute path `sourceRoot` property');
+ }
- const { outputDir } = spec;
- if (!(typeof outputDir === 'string' && Path.isAbsolute(outputDir))) {
- throw new Error('`bundles[]` must have an absolute path `outputDir` property');
- }
+ const { outputDir } = spec;
+ if (!(typeof outputDir === 'string' && Path.isAbsolute(outputDir))) {
+ throw new Error('`bundles[]` must have an absolute path `outputDir` property');
+ }
- const { manifestPath } = spec;
- if (manifestPath !== undefined) {
- if (!(typeof manifestPath === 'string' && Path.isAbsolute(manifestPath))) {
- throw new Error('`bundles[]` must have an absolute path `manifestPath` property');
- }
+ const { manifestPath } = spec;
+ if (manifestPath !== undefined) {
+ if (!(typeof manifestPath === 'string' && Path.isAbsolute(manifestPath))) {
+ throw new Error('`bundles[]` must have an absolute path `manifestPath` property');
}
+ }
- const { banner } = spec;
- if (banner !== undefined) {
- if (!(typeof banner === 'string')) {
- throw new Error('`bundles[]` must have a string `banner` property');
- }
+ const { banner } = spec;
+ if (banner !== undefined) {
+ if (!(typeof banner === 'string')) {
+ throw new Error('`bundles[]` must have a string `banner` property');
}
+ }
- const { pageLoadAssetSizeLimit } = spec;
- if (pageLoadAssetSizeLimit !== undefined) {
- if (!(typeof pageLoadAssetSizeLimit === 'number')) {
- throw new Error('`bundles[]` must have a numeric `pageLoadAssetSizeLimit` property');
- }
+ const { pageLoadAssetSizeLimit } = spec;
+ if (pageLoadAssetSizeLimit !== undefined) {
+ if (!(typeof pageLoadAssetSizeLimit === 'number')) {
+ throw new Error('`bundles[]` must have a numeric `pageLoadAssetSizeLimit` property');
}
-
- return new Bundle({
- type,
- id,
- publicDirNames,
- contextDir,
- sourceRoot,
- outputDir,
- banner,
- manifestPath,
- pageLoadAssetSizeLimit,
- });
}
- );
+
+ return new Bundle({
+ type,
+ id,
+ publicDirNames,
+ contextDir,
+ sourceRoot,
+ outputDir,
+ banner,
+ manifestPath,
+ pageLoadAssetSizeLimit,
+ });
+ });
} catch (error) {
throw new Error(`unable to parse bundles: ${error.message}`);
}
diff --git a/packages/kbn-optimizer/src/common/bundle_refs.ts b/packages/kbn-optimizer/src/common/bundle_refs.ts
index 91fc21780930e..49628fcf05588 100644
--- a/packages/kbn-optimizer/src/common/bundle_refs.ts
+++ b/packages/kbn-optimizer/src/common/bundle_refs.ts
@@ -58,46 +58,44 @@ export class BundleRefs {
}
return new BundleRefs(
- spec.map(
- (refSpec: UnknownVals): BundleRef => {
- if (typeof refSpec !== 'object' || !refSpec) {
- throw new Error('`bundleRefs[]` must be an object');
- }
-
- const { bundleId } = refSpec;
- if (typeof bundleId !== 'string') {
- throw new Error('`bundleRefs[].bundleId` must be a string');
- }
-
- const { contextDir } = refSpec;
- if (typeof contextDir !== 'string' || !Path.isAbsolute(contextDir)) {
- throw new Error('`bundleRefs[].contextDir` must be an absolute directory');
- }
-
- const { contextPrefix } = refSpec;
- if (typeof contextPrefix !== 'string' || !Path.isAbsolute(contextPrefix)) {
- throw new Error('`bundleRefs[].contextPrefix` must be an absolute directory');
- }
-
- const { entry } = refSpec;
- if (typeof entry !== 'string') {
- throw new Error('`bundleRefs[].entry` must be a string');
- }
-
- const { exportId } = refSpec;
- if (typeof exportId !== 'string') {
- throw new Error('`bundleRefs[].exportId` must be a string');
- }
-
- return {
- bundleId,
- contextDir,
- contextPrefix,
- entry,
- exportId,
- };
+ spec.map((refSpec: UnknownVals): BundleRef => {
+ if (typeof refSpec !== 'object' || !refSpec) {
+ throw new Error('`bundleRefs[]` must be an object');
}
- )
+
+ const { bundleId } = refSpec;
+ if (typeof bundleId !== 'string') {
+ throw new Error('`bundleRefs[].bundleId` must be a string');
+ }
+
+ const { contextDir } = refSpec;
+ if (typeof contextDir !== 'string' || !Path.isAbsolute(contextDir)) {
+ throw new Error('`bundleRefs[].contextDir` must be an absolute directory');
+ }
+
+ const { contextPrefix } = refSpec;
+ if (typeof contextPrefix !== 'string' || !Path.isAbsolute(contextPrefix)) {
+ throw new Error('`bundleRefs[].contextPrefix` must be an absolute directory');
+ }
+
+ const { entry } = refSpec;
+ if (typeof entry !== 'string') {
+ throw new Error('`bundleRefs[].entry` must be a string');
+ }
+
+ const { exportId } = refSpec;
+ if (typeof exportId !== 'string') {
+ throw new Error('`bundleRefs[].exportId` must be a string');
+ }
+
+ return {
+ bundleId,
+ contextDir,
+ contextPrefix,
+ entry,
+ exportId,
+ };
+ })
);
}
diff --git a/packages/kbn-optimizer/src/integration_tests/watch_bundles_for_changes.test.ts b/packages/kbn-optimizer/src/integration_tests/watch_bundles_for_changes.test.ts
index 5bfca96d9679d..2c5668766ed5e 100644
--- a/packages/kbn-optimizer/src/integration_tests/watch_bundles_for_changes.test.ts
+++ b/packages/kbn-optimizer/src/integration_tests/watch_bundles_for_changes.test.ts
@@ -109,7 +109,7 @@ it('notifies of changes and completes once all bundles have changed', async () =
);
expect(MockWatchPack.mock.instances).toHaveLength(1);
- const [watcher] = (MockWatchPack.mock.instances as any) as Array>;
+ const [watcher] = MockWatchPack.mock.instances as any as Array>;
expect(watcher.on).toHaveBeenCalledTimes(1);
expect(watcher.on).toHaveBeenCalledWith('change', expect.any(Function));
const [, changeListener] = watcher.on.mock.calls[0];
diff --git a/packages/kbn-optimizer/src/optimizer/optimizer_config.test.ts b/packages/kbn-optimizer/src/optimizer/optimizer_config.test.ts
index 39a7e0ab0e622..dff389f2e0de2 100644
--- a/packages/kbn-optimizer/src/optimizer/optimizer_config.test.ts
+++ b/packages/kbn-optimizer/src/optimizer/optimizer_config.test.ts
@@ -380,10 +380,12 @@ describe('OptimizerConfig::parseOptions()', () => {
* and just making sure that the arguments are coming from where we expect
*/
describe('OptimizerConfig::create()', () => {
- const assignBundlesToWorkers: jest.Mock = jest.requireMock('./assign_bundles_to_workers.ts')
- .assignBundlesToWorkers;
- const findKibanaPlatformPlugins: jest.Mock = jest.requireMock('./kibana_platform_plugins.ts')
- .findKibanaPlatformPlugins;
+ const assignBundlesToWorkers: jest.Mock = jest.requireMock(
+ './assign_bundles_to_workers.ts'
+ ).assignBundlesToWorkers;
+ const findKibanaPlatformPlugins: jest.Mock = jest.requireMock(
+ './kibana_platform_plugins.ts'
+ ).findKibanaPlatformPlugins;
const getPluginBundles: jest.Mock = jest.requireMock('./get_plugin_bundles.ts').getPluginBundles;
const filterById: jest.Mock = jest.requireMock('./filter_by_id.ts').filterById;
const focusBundles: jest.Mock = jest.requireMock('./focus_bundles').focusBundles;
@@ -404,24 +406,26 @@ describe('OptimizerConfig::create()', () => {
focusBundles.mockReturnValue(Symbol('focused bundles'));
readLimits.mockReturnValue(Symbol('limits'));
- jest.spyOn(OptimizerConfig, 'parseOptions').mockImplementation((): {
- [key in keyof ParsedOptions]: any;
- } => ({
- cache: Symbol('parsed cache'),
- dist: Symbol('parsed dist'),
- maxWorkerCount: Symbol('parsed max worker count'),
- pluginPaths: Symbol('parsed plugin paths'),
- pluginScanDirs: Symbol('parsed plugin scan dirs'),
- repoRoot: Symbol('parsed repo root'),
- outputRoot: Symbol('parsed output root'),
- watch: Symbol('parsed watch'),
- themeTags: Symbol('theme tags'),
- inspectWorkers: Symbol('parsed inspect workers'),
- profileWebpack: Symbol('parsed profile webpack'),
- filters: [],
- focus: [],
- includeCoreBundle: false,
- }));
+ jest.spyOn(OptimizerConfig, 'parseOptions').mockImplementation(
+ (): {
+ [key in keyof ParsedOptions]: any;
+ } => ({
+ cache: Symbol('parsed cache'),
+ dist: Symbol('parsed dist'),
+ maxWorkerCount: Symbol('parsed max worker count'),
+ pluginPaths: Symbol('parsed plugin paths'),
+ pluginScanDirs: Symbol('parsed plugin scan dirs'),
+ repoRoot: Symbol('parsed repo root'),
+ outputRoot: Symbol('parsed output root'),
+ watch: Symbol('parsed watch'),
+ themeTags: Symbol('theme tags'),
+ inspectWorkers: Symbol('parsed inspect workers'),
+ profileWebpack: Symbol('parsed profile webpack'),
+ filters: [],
+ focus: [],
+ includeCoreBundle: false,
+ })
+ );
});
it('passes parsed options to findKibanaPlatformPlugins, getBundles, and assignBundlesToWorkers', () => {
diff --git a/packages/kbn-optimizer/src/worker/bundle_refs_plugin.ts b/packages/kbn-optimizer/src/worker/bundle_refs_plugin.ts
index 5396d11726f7a..18b219336a92d 100644
--- a/packages/kbn-optimizer/src/worker/bundle_refs_plugin.ts
+++ b/packages/kbn-optimizer/src/worker/bundle_refs_plugin.ts
@@ -65,21 +65,22 @@ export class BundleRefsPlugin {
// entry then create a BundleRefModule instead of a NormalModule.
compilationParams.normalModuleFactory.hooks.factory.tap(
'BundleRefsPlugin/normalModuleFactory/factory',
- (wrappedFactory: ModuleFactory): ModuleFactory => (data, callback) => {
- const context = data.context;
- const dep = data.dependencies[0];
-
- this.maybeReplaceImport(context, dep.request).then(
- (module) => {
- if (!module) {
- wrappedFactory(data, callback);
- } else {
- callback(undefined, module);
- }
- },
- (error) => callback(error)
- );
- }
+ (wrappedFactory: ModuleFactory): ModuleFactory =>
+ (data, callback) => {
+ const context = data.context;
+ const dep = data.dependencies[0];
+
+ this.maybeReplaceImport(context, dep.request).then(
+ (module) => {
+ if (!module) {
+ wrappedFactory(data, callback);
+ } else {
+ callback(undefined, module);
+ }
+ },
+ (error) => callback(error)
+ );
+ }
);
});
diff --git a/packages/kbn-securitysolution-autocomplete/src/field/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/field/index.test.tsx
index 08f55cef89b66..626c791315c3e 100644
--- a/packages/kbn-securitysolution-autocomplete/src/field/index.test.tsx
+++ b/packages/kbn-securitysolution-autocomplete/src/field/index.test.tsx
@@ -123,9 +123,11 @@ describe('field', () => {
/>
);
- ((wrapper.find(EuiComboBox).props() as unknown) as {
- onChange: (a: EuiComboBoxOptionOption[]) => void;
- }).onChange([{ label: 'machine.os' }]);
+ (
+ wrapper.find(EuiComboBox).props() as unknown as {
+ onChange: (a: EuiComboBoxOptionOption[]) => void;
+ }
+ ).onChange([{ label: 'machine.os' }]);
expect(mockOnChange).toHaveBeenCalledWith([
{
diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.test.tsx
index 6fcf8ddf74b03..941eaf5322000 100644
--- a/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.test.tsx
+++ b/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.test.tsx
@@ -202,9 +202,11 @@ describe('AutocompleteFieldListsComponent', () => {
/>
);
- ((wrapper.find(EuiComboBox).props() as unknown) as {
- onChange: (a: EuiComboBoxOptionOption[]) => void;
- }).onChange([{ label: 'some name' }]);
+ (
+ wrapper.find(EuiComboBox).props() as unknown as {
+ onChange: (a: EuiComboBoxOptionOption[]) => void;
+ }
+ ).onChange([{ label: 'some name' }]);
await waitFor(() => {
expect(mockOnChange).toHaveBeenCalledWith({
diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.tsx
index 093643c3a5469..cef46b9bcaa21 100644
--- a/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.tsx
+++ b/packages/kbn-securitysolution-autocomplete/src/field_value_lists/index.tsx
@@ -51,10 +51,10 @@ export const AutocompleteFieldListsComponent: React.FC name, []);
- const optionsMemo = useMemo(() => filterFieldToList(lists, selectedField), [
- lists,
- selectedField,
- ]);
+ const optionsMemo = useMemo(
+ () => filterFieldToList(lists, selectedField),
+ [lists, selectedField]
+ );
const selectedOptionsMemo = useMemo(() => {
if (selectedValue != null) {
const list = lists.filter(({ id }) => id === selectedValue);
diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.test.tsx
index c0690774965c3..195259b89eb63 100644
--- a/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.test.tsx
+++ b/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.test.tsx
@@ -188,9 +188,11 @@ describe('AutocompleteFieldMatchComponent', () => {
/>
);
- ((wrapper.find(EuiComboBox).props() as unknown) as {
- onCreateOption: (a: string) => void;
- }).onCreateOption('127.0.0.1');
+ (
+ wrapper.find(EuiComboBox).props() as unknown as {
+ onCreateOption: (a: string) => void;
+ }
+ ).onCreateOption('127.0.0.1');
expect(mockOnChange).toHaveBeenCalledWith('127.0.0.1');
});
@@ -216,9 +218,11 @@ describe('AutocompleteFieldMatchComponent', () => {
/>
);
- ((wrapper.find(EuiComboBox).props() as unknown) as {
- onChange: (a: EuiComboBoxOptionOption[]) => void;
- }).onChange([{ label: 'value 1' }]);
+ (
+ wrapper.find(EuiComboBox).props() as unknown as {
+ onChange: (a: EuiComboBoxOptionOption[]) => void;
+ }
+ ).onChange([{ label: 'value 1' }]);
expect(mockOnChange).toHaveBeenCalledWith('value 1');
});
@@ -243,9 +247,11 @@ describe('AutocompleteFieldMatchComponent', () => {
/>
);
act(() => {
- ((wrapper.find(EuiComboBox).props() as unknown) as {
- onSearchChange: (a: string) => void;
- }).onSearchChange('value 1');
+ (
+ wrapper.find(EuiComboBox).props() as unknown as {
+ onSearchChange: (a: string) => void;
+ }
+ ).onSearchChange('value 1');
});
expect(useFieldValueAutocomplete).toHaveBeenCalledWith({
@@ -331,9 +337,11 @@ describe('AutocompleteFieldMatchComponent', () => {
/>
);
- ((wrapper.find(EuiSuperSelect).props() as unknown) as {
- onChange: (a: string) => void;
- }).onChange('true');
+ (
+ wrapper.find(EuiSuperSelect).props() as unknown as {
+ onChange: (a: string) => void;
+ }
+ ).onChange('true');
expect(mockOnChange).toHaveBeenCalledWith('true');
});
@@ -359,9 +367,11 @@ describe('AutocompleteFieldMatchComponent', () => {
/>
);
- ((wrapper.find(EuiSuperSelect).props() as unknown) as {
- onChange: (a: string) => void;
- }).onChange('false');
+ (
+ wrapper.find(EuiSuperSelect).props() as unknown as {
+ onChange: (a: string) => void;
+ }
+ ).onChange('false');
expect(mockOnChange).toHaveBeenCalledWith('false');
});
diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.tsx
index 9088517adbe58..b45d508ffdb20 100644
--- a/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.tsx
+++ b/packages/kbn-securitysolution-autocomplete/src/field_value_match/index.tsx
@@ -187,10 +187,10 @@ export const AutocompleteFieldMatchComponent: React.FC isLoading || isLoadingSuggestions, [
- isLoading,
- isLoadingSuggestions,
- ]);
+ const isLoadingState = useMemo(
+ (): boolean => isLoading || isLoadingSuggestions,
+ [isLoading, isLoadingSuggestions]
+ );
useEffect((): void => {
setError(undefined);
diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.test.tsx
index 389761c9a6dfc..3246e0febede2 100644
--- a/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.test.tsx
+++ b/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.test.tsx
@@ -189,9 +189,11 @@ describe('AutocompleteFieldMatchAnyComponent', () => {
/>
);
- ((wrapper.find(EuiComboBox).props() as unknown) as {
- onCreateOption: (a: string) => void;
- }).onCreateOption('127.0.0.1');
+ (
+ wrapper.find(EuiComboBox).props() as unknown as {
+ onCreateOption: (a: string) => void;
+ }
+ ).onCreateOption('127.0.0.1');
expect(mockOnChange).toHaveBeenCalledWith(['127.0.0.1']);
});
@@ -221,9 +223,11 @@ describe('AutocompleteFieldMatchAnyComponent', () => {
/>
);
- ((wrapper.find(EuiComboBox).props() as unknown) as {
- onChange: (a: EuiComboBoxOptionOption[]) => void;
- }).onChange([{ label: 'value 1' }]);
+ (
+ wrapper.find(EuiComboBox).props() as unknown as {
+ onChange: (a: EuiComboBoxOptionOption[]) => void;
+ }
+ ).onChange([{ label: 'value 1' }]);
expect(mockOnChange).toHaveBeenCalledWith(['value 1']);
});
@@ -250,9 +254,11 @@ describe('AutocompleteFieldMatchAnyComponent', () => {
/>
);
act(() => {
- ((wrapper.find(EuiComboBox).props() as unknown) as {
- onSearchChange: (a: string) => void;
- }).onSearchChange('value 1');
+ (
+ wrapper.find(EuiComboBox).props() as unknown as {
+ onSearchChange: (a: string) => void;
+ }
+ ).onSearchChange('value 1');
});
expect(useFieldValueAutocomplete).toHaveBeenCalledWith({
autocompleteService: autocompleteStartMock,
diff --git a/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.tsx b/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.tsx
index bfcafd199dc32..8aa8d6ad5ff70 100644
--- a/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.tsx
+++ b/packages/kbn-securitysolution-autocomplete/src/field_value_match_any/index.tsx
@@ -145,10 +145,10 @@ export const AutocompleteFieldMatchAnyComponent: React.FC isLoading || isLoadingSuggestions, [
- isLoading,
- isLoadingSuggestions,
- ]);
+ const isLoadingState = useMemo(
+ (): boolean => isLoading || isLoadingSuggestions,
+ [isLoading, isLoadingSuggestions]
+ );
const defaultInput = useMemo((): JSX.Element => {
return (
diff --git a/packages/kbn-securitysolution-autocomplete/src/fields/index.mock.ts b/packages/kbn-securitysolution-autocomplete/src/fields/index.mock.ts
index a79325e25343f..d2f74a17561a4 100644
--- a/packages/kbn-securitysolution-autocomplete/src/fields/index.mock.ts
+++ b/packages/kbn-securitysolution-autocomplete/src/fields/index.mock.ts
@@ -11,7 +11,7 @@ import { IndexPatternFieldBase } from '@kbn/es-query';
// Copied from "src/plugins/data/common/index_patterns/fields/fields.mocks.ts" but with the types changed to "IndexPatternFieldBase" since that type is compatible.
// TODO: This should move out once those mocks are directly useable or in their own package, https://github.com/elastic/kibana/issues/100715
-export const fields: IndexPatternFieldBase[] = ([
+export const fields: IndexPatternFieldBase[] = [
{
name: 'bytes',
type: 'number',
@@ -309,6 +309,6 @@ export const fields: IndexPatternFieldBase[] = ([
readFromDocValues: false,
subType: { nested: { path: 'nestedField.nestedChild' } },
},
-] as unknown) as IndexPatternFieldBase[];
+] as unknown as IndexPatternFieldBase[];
export const getField = (name: string) => fields.find((field) => field.name === name);
diff --git a/packages/kbn-securitysolution-autocomplete/src/operator/index.test.tsx b/packages/kbn-securitysolution-autocomplete/src/operator/index.test.tsx
index e2af384215c25..6d1622f0fa95f 100644
--- a/packages/kbn-securitysolution-autocomplete/src/operator/index.test.tsx
+++ b/packages/kbn-securitysolution-autocomplete/src/operator/index.test.tsx
@@ -210,9 +210,11 @@ describe('operator', () => {
/>
);
- ((wrapper.find(EuiComboBox).props() as unknown) as {
- onChange: (a: EuiComboBoxOptionOption[]) => void;
- }).onChange([{ label: 'is not' }]);
+ (
+ wrapper.find(EuiComboBox).props() as unknown as {
+ onChange: (a: EuiComboBoxOptionOption[]) => void;
+ }
+ ).onChange([{ label: 'is not' }]);
expect(mockOnChange).toHaveBeenCalledWith([
{ message: 'is not', operator: 'excluded', type: 'match', value: 'is_not' },
diff --git a/packages/kbn-securitysolution-autocomplete/src/operator/index.tsx b/packages/kbn-securitysolution-autocomplete/src/operator/index.tsx
index dc12de7c398c3..c791ef4ccb91f 100644
--- a/packages/kbn-securitysolution-autocomplete/src/operator/index.tsx
+++ b/packages/kbn-securitysolution-autocomplete/src/operator/index.tsx
@@ -50,9 +50,10 @@ export const OperatorComponent: React.FC = ({
: getOperators(selectedField),
[operatorOptions, selectedField]
);
- const selectedOptionsMemo = useMemo((): OperatorOption[] => (operator ? [operator] : []), [
- operator,
- ]);
+ const selectedOptionsMemo = useMemo(
+ (): OperatorOption[] => (operator ? [operator] : []),
+ [operator]
+ );
const { comboOptions, labels, selectedComboOptions } = useMemo(
(): GetGenericComboBoxPropsReturn =>
getGenericComboBoxProps({
diff --git a/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.test.ts b/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.test.ts
index c3c9702823ecb..a35ed9d85122f 100644
--- a/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.test.ts
+++ b/packages/kbn-securitysolution-autocomplete/src/param_is_valid/index.test.ts
@@ -15,17 +15,21 @@ describe('params_is_valid', () => {
beforeEach(() => {
// Disable momentJS deprecation warning and it looks like it is not typed either so
// we have to disable the type as well and cannot extend it easily.
- ((moment as unknown) as {
- suppressDeprecationWarnings: boolean;
- }).suppressDeprecationWarnings = true;
+ (
+ moment as unknown as {
+ suppressDeprecationWarnings: boolean;
+ }
+ ).suppressDeprecationWarnings = true;
});
afterEach(() => {
// Re-enable momentJS deprecation warning and it looks like it is not typed either so
// we have to disable the type as well and cannot extend it easily.
- ((moment as unknown) as {
- suppressDeprecationWarnings: boolean;
- }).suppressDeprecationWarnings = false;
+ (
+ moment as unknown as {
+ suppressDeprecationWarnings: boolean;
+ }
+ ).suppressDeprecationWarnings = false;
});
test('returns no errors if no field has been selected', () => {
diff --git a/packages/kbn-securitysolution-es-utils/src/encode_hit_version/index.ts b/packages/kbn-securitysolution-es-utils/src/encode_hit_version/index.ts
index 29b5a18f7c303..fc44d605888dc 100644
--- a/packages/kbn-securitysolution-es-utils/src/encode_hit_version/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/encode_hit_version/index.ts
@@ -16,7 +16,7 @@
*/
export const encodeHitVersion = (hit: T): string | undefined => {
// Have to do this "as cast" here as these two types aren't included in the SearchResponse hit type
- const { _seq_no: seqNo, _primary_term: primaryTerm } = (hit as unknown) as {
+ const { _seq_no: seqNo, _primary_term: primaryTerm } = hit as unknown as {
_seq_no: number;
_primary_term: number;
};
diff --git a/packages/kbn-securitysolution-es-utils/src/transform_error/index.test.ts b/packages/kbn-securitysolution-es-utils/src/transform_error/index.test.ts
index e0f520f1ebfd4..2b4bbf34c7c8a 100644
--- a/packages/kbn-securitysolution-es-utils/src/transform_error/index.test.ts
+++ b/packages/kbn-securitysolution-es-utils/src/transform_error/index.test.ts
@@ -88,7 +88,7 @@ describe('transformError', () => {
reason: 'detailed explanation',
},
},
- meta: ({} as unknown) as errors.ResponseError['meta'],
+ meta: {} as unknown as errors.ResponseError['meta'],
statusCode: 400,
};
const transformed = transformError(error);
diff --git a/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.ts b/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.ts
index da6fd414abc57..c4b53abfa88f4 100644
--- a/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.ts
+++ b/packages/kbn-securitysolution-hook-utils/src/with_optional_signal/index.ts
@@ -18,9 +18,9 @@ export type OptionalSignalArgs = Omit & Partial(fn: (args: Args) => Result) => (
- args: OptionalSignalArgs
-): Result => {
- const signal = args.signal != null ? args.signal : new AbortController().signal;
- return fn({ ...args, signal } as Args);
-};
+export const withOptionalSignal =
+ (fn: (args: Args) => Result) =>
+ (args: OptionalSignalArgs): Result => {
+ const signal = args.signal != null ? args.signal : new AbortController().signal;
+ return fn({ ...args, signal } as Args);
+ };
diff --git a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.test.ts b/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.test.ts
index 16fd1647e5bfc..6e2e671dbb029 100644
--- a/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.test.ts
+++ b/packages/kbn-securitysolution-io-ts-alerting-types/src/threat_mapping/index.test.ts
@@ -54,13 +54,13 @@ describe('threat_mapping', () => {
});
test('it should fail validation with a non string', () => {
- const payload = ([
+ const payload = [
{
field: 5,
type: 'mapping',
value: 'field.one',
},
- ] as unknown) as ThreatMappingEntries[];
+ ] as unknown as ThreatMappingEntries[];
const decoded = threatMappingEntries.decode(payload);
const checked = exactCheck(payload, decoded);
const message = pipe(checked, foldLeftRight);
@@ -70,13 +70,13 @@ describe('threat_mapping', () => {
});
test('it should fail validation with a wrong type', () => {
- const payload = ([
+ const payload = [
{
field: 'field.one',
type: 'invalid',
value: 'field.one',
},
- ] as unknown) as ThreatMappingEntries[];
+ ] as unknown as ThreatMappingEntries[];
const decoded = threatMappingEntries.decode(payload);
const checked = exactCheck(payload, decoded);
const message = pipe(checked, foldLeftRight);
@@ -155,7 +155,7 @@ describe('threat_mapping', () => {
});
test('it should fail validate with an extra inner entry with the wrong data type', () => {
- const payload = ([
+ const payload = [
{
entries: [
{
@@ -165,7 +165,7 @@ describe('threat_mapping', () => {
},
],
},
- ] as unknown) as ThreatMapping;
+ ] as unknown as ThreatMapping;
const decoded = threat_mapping.decode(payload);
const checked = exactCheck(payload, decoded);
diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.test.ts
index 4af9be0a7f0e6..1272eeed6ee1e 100644
--- a/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.test.ts
+++ b/packages/kbn-securitysolution-io-ts-list-types/src/common/comment/index.test.ts
@@ -193,7 +193,7 @@ describe('Comment', () => {
});
test('it fails validation when array includes non Comment types', () => {
- const payload = ([1] as unknown) as CommentsArray;
+ const payload = [1] as unknown as CommentsArray;
const decoded = commentsArray.decode(payload);
const message = pipe(decoded, foldLeftRight);
@@ -224,7 +224,7 @@ describe('Comment', () => {
});
test('it fails validation when array includes non Comment types', () => {
- const payload = ([1] as unknown) as CommentsArrayOrUndefined;
+ const payload = [1] as unknown as CommentsArrayOrUndefined;
const decoded = commentsArray.decode(payload);
const message = pipe(decoded, foldLeftRight);
diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.test.ts
index 3baf0054221db..1f5aa2118be40 100644
--- a/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.test.ts
+++ b/packages/kbn-securitysolution-io-ts-list-types/src/common/create_comment/index.test.ts
@@ -90,7 +90,7 @@ describe('CreateComment', () => {
});
test('it fails validation when array includes non comments types', () => {
- const payload = ([1] as unknown) as CreateCommentsArray;
+ const payload = [1] as unknown as CreateCommentsArray;
const decoded = createCommentsArray.decode(payload);
const message = pipe(decoded, foldLeftRight);
@@ -121,7 +121,7 @@ describe('CreateComment', () => {
});
test('it fails validation when array includes non comments types', () => {
- const payload = ([1] as unknown) as CreateCommentsArrayOrUndefined;
+ const payload = [1] as unknown as CreateCommentsArrayOrUndefined;
const decoded = createCommentsArray.decode(payload);
const message = pipe(decoded, foldLeftRight);
diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.test.ts
index 88dcc1ced8607..83e75a924f436 100644
--- a/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.test.ts
+++ b/packages/kbn-securitysolution-io-ts-list-types/src/common/lists/index.test.ts
@@ -81,7 +81,7 @@ describe('Lists', () => {
});
test('it should not validate when unexpected type found in array', () => {
- const payload = ([1] as unknown) as ListArray;
+ const payload = [1] as unknown as ListArray;
const decoded = listArray.decode(payload);
const message = pipe(decoded, foldLeftRight);
@@ -112,7 +112,7 @@ describe('Lists', () => {
});
test('it should not allow an item that is not of type "list" in array', () => {
- const payload = ([1] as unknown) as ListArrayOrUndefined;
+ const payload = [1] as unknown as ListArrayOrUndefined;
const decoded = listArrayOrUndefined.decode(payload);
const message = pipe(decoded, foldLeftRight);
diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.test.ts b/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.test.ts
index 8dd0301c54dd8..7ddbdf31ca317 100644
--- a/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.test.ts
+++ b/packages/kbn-securitysolution-io-ts-list-types/src/common/update_comment/index.test.ts
@@ -105,7 +105,7 @@ describe('CommentsUpdate', () => {
});
test('it should fail validation when array includes non comments types', () => {
- const payload = ([1] as unknown) as UpdateCommentsArray;
+ const payload = [1] as unknown as UpdateCommentsArray;
const decoded = updateCommentsArray.decode(payload);
const message = pipe(decoded, foldLeftRight);
@@ -136,7 +136,7 @@ describe('CommentsUpdate', () => {
});
test('it should fail validation when array includes non comments types', () => {
- const payload = ([1] as unknown) as UpdateCommentsArrayOrUndefined;
+ const payload = [1] as unknown as UpdateCommentsArrayOrUndefined;
const decoded = updateCommentsArray.decode(payload);
const message = pipe(decoded, foldLeftRight);
diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.mock.ts
index 4ed62887ef9ba..5b88de0c85c02 100644
--- a/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.mock.ts
+++ b/packages/kbn-securitysolution-io-ts-list-types/src/request/create_exception_list_item_schema/index.mock.ts
@@ -51,11 +51,12 @@ export const getCreateExceptionListItemMinimalSchemaMock = (): CreateExceptionLi
/**
* Useful for end to end testing
*/
-export const getCreateExceptionListItemMinimalSchemaMockWithoutId = (): CreateExceptionListItemSchema => ({
- description: DESCRIPTION,
- entries: ENTRIES,
- list_id: LIST_ID,
- name: NAME,
- os_types: OS_TYPES,
- type: ITEM_TYPE,
-});
+export const getCreateExceptionListItemMinimalSchemaMockWithoutId =
+ (): CreateExceptionListItemSchema => ({
+ description: DESCRIPTION,
+ entries: ENTRIES,
+ list_id: LIST_ID,
+ name: NAME,
+ os_types: OS_TYPES,
+ type: ITEM_TYPE,
+ });
diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.mock.ts
index f6548a2c5f4fe..8f64dccf6d577 100644
--- a/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.mock.ts
+++ b/packages/kbn-securitysolution-io-ts-list-types/src/request/find_exception_list_item_schema/index.mock.ts
@@ -30,22 +30,24 @@ export const getFindExceptionListItemSchemaMultipleMock = (): FindExceptionListI
sort_order: undefined,
});
-export const getFindExceptionListItemSchemaDecodedMock = (): FindExceptionListItemSchemaDecoded => ({
- filter: [FILTER],
- list_id: [LIST_ID],
- namespace_type: [NAMESPACE_TYPE],
- page: 1,
- per_page: 25,
- sort_field: undefined,
- sort_order: undefined,
-});
+export const getFindExceptionListItemSchemaDecodedMock =
+ (): FindExceptionListItemSchemaDecoded => ({
+ filter: [FILTER],
+ list_id: [LIST_ID],
+ namespace_type: [NAMESPACE_TYPE],
+ page: 1,
+ per_page: 25,
+ sort_field: undefined,
+ sort_order: undefined,
+ });
-export const getFindExceptionListItemSchemaDecodedMultipleMock = (): FindExceptionListItemSchemaDecoded => ({
- filter: ['name:Sofia Kovalevskaya', 'name:Hypatia', 'name:Sophie Germain'],
- list_id: ['list-1', 'list-2', 'list-3'],
- namespace_type: ['single', 'single', 'agnostic'],
- page: 1,
- per_page: 25,
- sort_field: undefined,
- sort_order: undefined,
-});
+export const getFindExceptionListItemSchemaDecodedMultipleMock =
+ (): FindExceptionListItemSchemaDecoded => ({
+ filter: ['name:Sofia Kovalevskaya', 'name:Hypatia', 'name:Sophie Germain'],
+ list_id: ['list-1', 'list-2', 'list-3'],
+ namespace_type: ['single', 'single', 'agnostic'],
+ page: 1,
+ per_page: 25,
+ sort_field: undefined,
+ sort_order: undefined,
+ });
diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.mock.ts
index 2348584000475..c06a5439d11d8 100644
--- a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.mock.ts
+++ b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_item_schema/index.mock.ts
@@ -53,17 +53,18 @@ export const getExceptionListItemSchemaMock = (
* This is useful for end to end tests where we remove the auto generated parts for comparisons
* such as created_at, updated_at, and id.
*/
-export const getExceptionListItemResponseMockWithoutAutoGeneratedValues = (): Partial => ({
- comments: [],
- created_by: ELASTIC_USER,
- description: DESCRIPTION,
- entries: ENTRIES,
- item_id: ITEM_ID,
- list_id: LIST_ID,
- name: NAME,
- namespace_type: 'single',
- os_types: OS_TYPES,
- tags: [],
- type: ITEM_TYPE,
- updated_by: ELASTIC_USER,
-});
+export const getExceptionListItemResponseMockWithoutAutoGeneratedValues =
+ (): Partial => ({
+ comments: [],
+ created_by: ELASTIC_USER,
+ description: DESCRIPTION,
+ entries: ENTRIES,
+ item_id: ITEM_ID,
+ list_id: LIST_ID,
+ name: NAME,
+ namespace_type: 'single',
+ os_types: OS_TYPES,
+ tags: [],
+ type: ITEM_TYPE,
+ updated_by: ELASTIC_USER,
+ });
diff --git a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.mock.ts b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.mock.ts
index c77fb35a40b60..c73b5a55d0c2c 100644
--- a/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.mock.ts
+++ b/packages/kbn-securitysolution-io-ts-list-types/src/response/exception_list_schema/index.mock.ts
@@ -62,16 +62,17 @@ export const getTrustedAppsListSchemaMock = (): ExceptionListSchema => {
* This is useful for end to end tests where we remove the auto generated parts for comparisons
* such as created_at, updated_at, and id.
*/
-export const getExceptionResponseMockWithoutAutoGeneratedValues = (): Partial => ({
- created_by: ELASTIC_USER,
- description: DESCRIPTION,
- immutable: IMMUTABLE,
- list_id: LIST_ID,
- name: NAME,
- namespace_type: 'single',
- os_types: [],
- tags: [],
- type: ENDPOINT_TYPE,
- updated_by: ELASTIC_USER,
- version: VERSION,
-});
+export const getExceptionResponseMockWithoutAutoGeneratedValues =
+ (): Partial => ({
+ created_by: ELASTIC_USER,
+ description: DESCRIPTION,
+ immutable: IMMUTABLE,
+ list_id: LIST_ID,
+ name: NAME,
+ namespace_type: 'single',
+ os_types: [],
+ tags: [],
+ type: ENDPOINT_TYPE,
+ updated_by: ELASTIC_USER,
+ version: VERSION,
+ });
diff --git a/packages/kbn-securitysolution-io-ts-utils/src/format_errors/index.test.ts b/packages/kbn-securitysolution-io-ts-utils/src/format_errors/index.test.ts
index f47f8f87f6a7e..17a551b098765 100644
--- a/packages/kbn-securitysolution-io-ts-utils/src/format_errors/index.test.ts
+++ b/packages/kbn-securitysolution-io-ts-utils/src/format_errors/index.test.ts
@@ -60,7 +60,7 @@ describe('utils', () => {
});
test('will use message before context if it is set', () => {
- const context: t.Context = ([{ key: 'some string key' }] as unknown) as t.Context;
+ const context: t.Context = [{ key: 'some string key' }] as unknown as t.Context;
const validationError1: t.ValidationError = {
value: 'Some existing error 1',
context,
@@ -72,7 +72,7 @@ describe('utils', () => {
});
test('will use context entry of a single string', () => {
- const context: t.Context = ([{ key: 'some string key' }] as unknown) as t.Context;
+ const context: t.Context = [{ key: 'some string key' }] as unknown as t.Context;
const validationError1: t.ValidationError = {
value: 'Some existing error 1',
context,
@@ -83,10 +83,10 @@ describe('utils', () => {
});
test('will use two context entries of two strings', () => {
- const context: t.Context = ([
+ const context: t.Context = [
{ key: 'some string key 1' },
{ key: 'some string key 2' },
- ] as unknown) as t.Context;
+ ] as unknown as t.Context;
const validationError1: t.ValidationError = {
value: 'Some existing error 1',
context,
@@ -99,10 +99,7 @@ describe('utils', () => {
});
test('will filter out and not use any strings of numbers', () => {
- const context: t.Context = ([
- { key: '5' },
- { key: 'some string key 2' },
- ] as unknown) as t.Context;
+ const context: t.Context = [{ key: '5' }, { key: 'some string key 2' }] as unknown as t.Context;
const validationError1: t.ValidationError = {
value: 'Some existing error 1',
context,
@@ -115,10 +112,10 @@ describe('utils', () => {
});
test('will filter out and not use null', () => {
- const context: t.Context = ([
+ const context: t.Context = [
{ key: null },
{ key: 'some string key 2' },
- ] as unknown) as t.Context;
+ ] as unknown as t.Context;
const validationError1: t.ValidationError = {
value: 'Some existing error 1',
context,
@@ -131,10 +128,7 @@ describe('utils', () => {
});
test('will filter out and not use empty strings', () => {
- const context: t.Context = ([
- { key: '' },
- { key: 'some string key 2' },
- ] as unknown) as t.Context;
+ const context: t.Context = [{ key: '' }, { key: 'some string key 2' }] as unknown as t.Context;
const validationError1: t.ValidationError = {
value: 'Some existing error 1',
context,
@@ -147,10 +141,10 @@ describe('utils', () => {
});
test('will use a name context if it cannot find a keyContext', () => {
- const context: t.Context = ([
+ const context: t.Context = [
{ key: '' },
{ key: '', type: { name: 'someName' } },
- ] as unknown) as t.Context;
+ ] as unknown as t.Context;
const validationError1: t.ValidationError = {
value: 'Some existing error 1',
context,
@@ -161,7 +155,7 @@ describe('utils', () => {
});
test('will return an empty string if name does not exist but type does', () => {
- const context: t.Context = ([{ key: '' }, { key: '', type: {} }] as unknown) as t.Context;
+ const context: t.Context = [{ key: '' }, { key: '', type: {} }] as unknown as t.Context;
const validationError1: t.ValidationError = {
value: 'Some existing error 1',
context,
@@ -172,10 +166,7 @@ describe('utils', () => {
});
test('will stringify an error value', () => {
- const context: t.Context = ([
- { key: '' },
- { key: 'some string key 2' },
- ] as unknown) as t.Context;
+ const context: t.Context = [{ key: '' }, { key: 'some string key 2' }] as unknown as t.Context;
const validationError1: t.ValidationError = {
value: { foo: 'some error' },
context,
diff --git a/packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.ts b/packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.ts
index 722a7918c4127..c0a5325377dc0 100644
--- a/packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.ts
+++ b/packages/kbn-securitysolution-list-hooks/src/use_exception_lists/index.ts
@@ -72,7 +72,12 @@ export const useExceptionLists = ({
abortCtrlRef.current = new AbortController();
- const { page, per_page: perPage, total, data } = await fetchExceptionLists({
+ const {
+ page,
+ per_page: perPage,
+ total,
+ data,
+ } = await fetchExceptionLists({
filters,
http,
namespaceTypes: namespaceTypesAsString,
diff --git a/packages/kbn-server-route-repository/src/typings.ts b/packages/kbn-server-route-repository/src/typings.ts
index c27f67c71e88b..dde957f469901 100644
--- a/packages/kbn-server-route-repository/src/typings.ts
+++ b/packages/kbn-server-route-repository/src/typings.ts
@@ -70,16 +70,15 @@ export interface ServerRouteRepository<
): ServerRouteRepository<
TRouteHandlerResources,
TRouteCreateOptions,
- TRouteState &
- {
- [key in TEndpoint]: ServerRoute<
- TEndpoint,
- TRouteParamsRT,
- TRouteHandlerResources,
- TReturnType,
- TRouteCreateOptions
- >;
- }
+ TRouteState & {
+ [key in TEndpoint]: ServerRoute<
+ TEndpoint,
+ TRouteParamsRT,
+ TRouteHandlerResources,
+ TReturnType,
+ TRouteCreateOptions
+ >;
+ }
>;
merge<
TServerRouteRepository extends ServerRouteRepository<
@@ -104,27 +103,24 @@ export interface ServerRouteRepository<
>;
}
-type ClientRequestParamsOfType<
- TRouteParamsRT extends RouteParamsRT
-> = TRouteParamsRT extends t.Mixed
- ? MaybeOptional<{
- params: t.OutputOf;
- }>
- : {};
+type ClientRequestParamsOfType =
+ TRouteParamsRT extends t.Mixed
+ ? MaybeOptional<{
+ params: t.OutputOf;
+ }>
+ : {};
-type DecodedRequestParamsOfType<
- TRouteParamsRT extends RouteParamsRT
-> = TRouteParamsRT extends t.Mixed
- ? MaybeOptional<{
- params: t.TypeOf;
- }>
- : {};
+type DecodedRequestParamsOfType =
+ TRouteParamsRT extends t.Mixed
+ ? MaybeOptional<{
+ params: t.TypeOf;
+ }>
+ : {};
-export type EndpointOf<
- TServerRouteRepository extends ServerRouteRepository
-> = TServerRouteRepository extends ServerRouteRepository
- ? keyof TRouteState
- : never;
+export type EndpointOf> =
+ TServerRouteRepository extends ServerRouteRepository
+ ? keyof TRouteState
+ : never;
export type ReturnOf<
TServerRouteRepository extends ServerRouteRepository,
diff --git a/packages/kbn-test/src/es/test_es_cluster.ts b/packages/kbn-test/src/es/test_es_cluster.ts
index 2d6edce269684..0d31ffdb99cc2 100644
--- a/packages/kbn-test/src/es/test_es_cluster.ts
+++ b/packages/kbn-test/src/es/test_es_cluster.ts
@@ -55,11 +55,10 @@ export interface ICluster {
getHostUrls: () => string[];
}
-export type EsTestCluster<
- Options extends CreateTestEsClusterOptions = CreateTestEsClusterOptions
-> = Options['nodes'] extends TestEsClusterNodesOptions[]
- ? ICluster
- : ICluster & { getUrl: () => string }; // Only allow use of `getUrl` if `nodes` option isn't provided.
+export type EsTestCluster =
+ Options['nodes'] extends TestEsClusterNodesOptions[]
+ ? ICluster
+ : ICluster & { getUrl: () => string }; // Only allow use of `getUrl` if `nodes` option isn't provided.
export interface CreateTestEsClusterOptions {
basePath?: string;
diff --git a/packages/kbn-test/src/functional_test_runner/lib/providers/provider_collection.ts b/packages/kbn-test/src/functional_test_runner/lib/providers/provider_collection.ts
index 2d05d5bba5ff6..69a5973168f0c 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/providers/provider_collection.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/providers/provider_collection.ts
@@ -67,7 +67,7 @@ export class ProviderCollection {
};
if (provider.prototype instanceof GenericFtrService) {
- const Constructor = (provider as any) as new (ctx: any) => any;
+ const Constructor = provider as any as new (ctx: any) => any;
return new Constructor(ctx);
}
diff --git a/packages/kbn-test/src/functional_test_runner/lib/snapshots/decorate_snapshot_ui.test.ts b/packages/kbn-test/src/functional_test_runner/lib/snapshots/decorate_snapshot_ui.test.ts
index 707aba5932172..c199dfc092789 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/snapshots/decorate_snapshot_ui.test.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/snapshots/decorate_snapshot_ui.test.ts
@@ -34,11 +34,11 @@ const registerTest = ({
title?: string;
passed?: boolean;
}) => {
- const test = ({
+ const test = {
file: __filename,
fullTitle: () => title,
isPassed: () => passed,
- } as unknown) as Test;
+ } as unknown as Test;
parent.tests.push(test);
test.parent = parent;
diff --git a/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.test.ts b/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.test.ts
index ac715da7d2a09..e87f316a100a7 100644
--- a/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.test.ts
+++ b/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.test.ts
@@ -51,12 +51,12 @@ describe('SuiteTracker', () => {
let MOCKS: Record;
const createMock = (overrides = {}) => {
- return ({
+ return {
file: resolve(REPO_ROOT, MOCK_TEST_PATH),
title: 'A Test',
suiteTag: MOCK_TEST_PATH,
...overrides,
- } as unknown) as Suite;
+ } as unknown as Suite;
};
const runLifecycleWithMocks = async (mocks: Suite[], fn: (objs: any) => any = () => {}) => {
diff --git a/packages/kbn-test/src/jest/utils/enzyme_helpers.tsx b/packages/kbn-test/src/jest/utils/enzyme_helpers.tsx
index 686a201761dcd..0aa93dc51446c 100644
--- a/packages/kbn-test/src/jest/utils/enzyme_helpers.tsx
+++ b/packages/kbn-test/src/jest/utils/enzyme_helpers.tsx
@@ -19,11 +19,13 @@ import React, { ReactElement, ValidationMap } from 'react';
import { act as reactAct } from 'react-dom/test-utils';
// Use fake component to extract `intl` property to use in tests.
-const { intl } = (mount(
-
-
-
-).find('IntlProvider') as ReactWrapper<{}, {}, __IntlProvider>)
+const { intl } = (
+ mount(
+
+
+
+ ).find('IntlProvider') as ReactWrapper<{}, {}, __IntlProvider>
+)
.instance()
.getChildContext();
diff --git a/packages/kbn-test/src/jest/utils/redux_helpers.tsx b/packages/kbn-test/src/jest/utils/redux_helpers.tsx
index 906cad2444b2e..3bbdfb965f323 100644
--- a/packages/kbn-test/src/jest/utils/redux_helpers.tsx
+++ b/packages/kbn-test/src/jest/utils/redux_helpers.tsx
@@ -9,8 +9,9 @@
import React, { ComponentType } from 'react';
import { Provider } from 'react-redux';
-export const WithStore = (store: any) => (WrappedComponent: ComponentType) => (props: any) => (
-
-
-
-);
+export const WithStore = (store: any) => (WrappedComponent: ComponentType) => (props: any) =>
+ (
+
+
+
+ );
diff --git a/packages/kbn-test/src/jest/utils/router_helpers.tsx b/packages/kbn-test/src/jest/utils/router_helpers.tsx
index 85ef27488a4ce..7c40e50bf646a 100644
--- a/packages/kbn-test/src/jest/utils/router_helpers.tsx
+++ b/packages/kbn-test/src/jest/utils/router_helpers.tsx
@@ -30,42 +30,45 @@ const locationDescriptorToRoutePath = (
return stringifyPath(paths);
};
-export const WithMemoryRouter = (
- initialEntries: LocationDescriptor[] = ['/'],
- initialIndex: number = 0
-) => (WrappedComponent: ComponentType) => (props: any) => (
-
-
-
-);
+export const WithMemoryRouter =
+ (initialEntries: LocationDescriptor[] = ['/'], initialIndex: number = 0) =>
+ (WrappedComponent: ComponentType) =>
+ (props: any) =>
+ (
+
+
+
+ );
-export const WithRoute = (
- componentRoutePath: LocationDescriptor | LocationDescriptor[] = ['/'],
- onRouter = (router: any) => {}
-) => (WrappedComponent: ComponentType) => {
- // Create a class component that will catch the router
- // and forward it to our "onRouter()" handler.
- const CatchRouter = withRouter(
- class extends Component {
- componentDidMount() {
- const { match, location, history } = this.props;
- const router = { route: { match, location }, history };
- onRouter(router);
- }
+export const WithRoute =
+ (
+ componentRoutePath: LocationDescriptor | LocationDescriptor[] = ['/'],
+ onRouter = (router: any) => {}
+ ) =>
+ (WrappedComponent: ComponentType) => {
+ // Create a class component that will catch the router
+ // and forward it to our "onRouter()" handler.
+ const CatchRouter = withRouter(
+ class extends Component {
+ componentDidMount() {
+ const { match, location, history } = this.props;
+ const router = { route: { match, location }, history };
+ onRouter(router);
+ }
- render() {
- return ;
+ render() {
+ return ;
+ }
}
- }
- );
+ );
- return (props: any) => (
- }
- />
- );
-};
+ return (props: any) => (
+ }
+ />
+ );
+ };
interface Router {
history: Partial;
diff --git a/packages/kbn-test/types/ftr_globals/snapshots.d.ts b/packages/kbn-test/types/ftr_globals/snapshots.d.ts
index ba7a4c114370f..d244e6cc90bbf 100644
--- a/packages/kbn-test/types/ftr_globals/snapshots.d.ts
+++ b/packages/kbn-test/types/ftr_globals/snapshots.d.ts
@@ -6,9 +6,7 @@
* Side Public License, v 1.
*/
-declare const expectSnapshot: (
- received: any
-) => {
+declare const expectSnapshot: (received: any) => {
toMatch: () => void;
toMatchInline: (_actual?: any) => void;
};
diff --git a/packages/kbn-tinymath/test/functions/degtorad.test.js b/packages/kbn-tinymath/test/functions/degtorad.test.js
index 857447ab7051b..0988db251743d 100644
--- a/packages/kbn-tinymath/test/functions/degtorad.test.js
+++ b/packages/kbn-tinymath/test/functions/degtorad.test.js
@@ -16,10 +16,7 @@ describe('Degrees to Radians', () => {
it('arrays', () => {
expect(degtorad([0, 90, 180, 360])).toEqual([
- 0,
- 1.5707963267948966,
- 3.141592653589793,
- 6.283185307179586,
+ 0, 1.5707963267948966, 3.141592653589793, 6.283185307179586,
]);
});
});
diff --git a/packages/kbn-tinymath/test/functions/radtodeg.test.js b/packages/kbn-tinymath/test/functions/radtodeg.test.js
index 03a10f59d60c7..e2059df464f2a 100644
--- a/packages/kbn-tinymath/test/functions/radtodeg.test.js
+++ b/packages/kbn-tinymath/test/functions/radtodeg.test.js
@@ -16,10 +16,7 @@ describe('Radians to Degrees', () => {
it('arrays', () => {
expect(radtodeg([0, 1.5707963267948966, 3.141592653589793, 6.283185307179586])).toEqual([
- 0,
- 90,
- 180,
- 360,
+ 0, 90, 180, 360,
]);
});
});
diff --git a/packages/kbn-typed-react-router-config/src/types/index.ts b/packages/kbn-typed-react-router-config/src/types/index.ts
index e6c70001ef4b6..9c19c8dca323b 100644
--- a/packages/kbn-typed-react-router-config/src/types/index.ts
+++ b/packages/kbn-typed-react-router-config/src/types/index.ts
@@ -252,10 +252,9 @@ type AppendPath<
TPath extends string
> = NormalizePath<`${TPrefix}${NormalizePath<`/${TPath}`>}`>;
-type MaybeUnion, U extends Record> = Omit &
- {
- [key in keyof U]: key extends keyof T ? T[key] | U[key] : U[key];
- };
+type MaybeUnion, U extends Record> = Omit & {
+ [key in keyof U]: key extends keyof T ? T[key] | U[key] : U[key];
+};
type MapRoute = TRoute extends Route
? MaybeUnion<
diff --git a/packages/kbn-utility-types/src/jest/index.ts b/packages/kbn-utility-types/src/jest/index.ts
index f6d14f23b504d..e146e19d10f17 100644
--- a/packages/kbn-utility-types/src/jest/index.ts
+++ b/packages/kbn-utility-types/src/jest/index.ts
@@ -10,7 +10,6 @@ export type DeeplyMockedKeys = {
[P in keyof T]: T[P] extends (...args: any[]) => any
? jest.MockInstance, Parameters>
: DeeplyMockedKeys;
-} &
- T;
+} & T;
export type MockedKeys = { [P in keyof T]: jest.Mocked };
diff --git a/src/cli_encryption_keys/encryption_config.js b/src/cli_encryption_keys/encryption_config.js
index 3f68ab9ef9187..4ad46d65c08c8 100644
--- a/src/cli_encryption_keys/encryption_config.js
+++ b/src/cli_encryption_keys/encryption_config.js
@@ -23,18 +23,15 @@ export class EncryptionConfig {
];
#encryptionMeta = {
'xpack.encryptedSavedObjects.encryptionKey': {
- docs:
- 'https://www.elastic.co/guide/en/kibana/current/xpack-security-secure-saved-objects.html#xpack-security-secure-saved-objects',
+ docs: 'https://www.elastic.co/guide/en/kibana/current/xpack-security-secure-saved-objects.html#xpack-security-secure-saved-objects',
description: 'Used to encrypt stored objects such as dashboards and visualizations',
},
'xpack.reporting.encryptionKey': {
- docs:
- 'https://www.elastic.co/guide/en/kibana/current/reporting-settings-kb.html#general-reporting-settings',
+ docs: 'https://www.elastic.co/guide/en/kibana/current/reporting-settings-kb.html#general-reporting-settings',
description: 'Used to encrypt saved reports',
},
'xpack.security.encryptionKey': {
- docs:
- 'https://www.elastic.co/guide/en/kibana/current/security-settings-kb.html#security-session-and-cookie-settings',
+ docs: 'https://www.elastic.co/guide/en/kibana/current/security-settings-kb.html#security-session-and-cookie-settings',
description: 'Used to encrypt session information',
},
};
diff --git a/src/core/public/apm_system.ts b/src/core/public/apm_system.ts
index f5af7011e632e..1a653636c54d4 100644
--- a/src/core/public/apm_system.ts
+++ b/src/core/public/apm_system.ts
@@ -11,7 +11,8 @@ import { modifyUrl } from '@kbn/std';
import type { InternalApplicationStart } from './application';
/** "GET protocol://hostname:port/pathname" */
-const HTTP_REQUEST_TRANSACTION_NAME_REGEX = /^(GET|POST|PUT|HEAD|PATCH|DELETE|OPTIONS|CONNECT|TRACE)\s(.*)$/;
+const HTTP_REQUEST_TRANSACTION_NAME_REGEX =
+ /^(GET|POST|PUT|HEAD|PATCH|DELETE|OPTIONS|CONNECT|TRACE)\s(.*)$/;
/**
* This is the entry point used to boot the frontend when serving a application
diff --git a/src/core/public/application/scoped_history.ts b/src/core/public/application/scoped_history.ts
index b932465f800cd..2ab60e66b860f 100644
--- a/src/core/public/application/scoped_history.ts
+++ b/src/core/public/application/scoped_history.ts
@@ -32,7 +32,8 @@ import {
* @public
*/
export class ScopedHistory
- implements History {
+ implements History
+{
/**
* Tracks whether or not the user has left this history's scope. All methods throw errors if called after scope has
* been left.
diff --git a/src/core/public/chrome/ui/header/header_action_menu.test.tsx b/src/core/public/chrome/ui/header/header_action_menu.test.tsx
index 201be8848bac8..e75b3b978bc11 100644
--- a/src/core/public/chrome/ui/header/header_action_menu.test.tsx
+++ b/src/core/public/chrome/ui/header/header_action_menu.test.tsx
@@ -41,17 +41,17 @@ describe('HeaderActionMenu', () => {
});
};
- const createMountPoint = (id: string, content: string = id): MountPoint => (
- root
- ): MockedUnmount => {
- const container = document.createElement('DIV');
- // eslint-disable-next-line no-unsanitized/property
- container.innerHTML = content;
- root.appendChild(container);
- const unmount = jest.fn(() => container.remove());
- unmounts[id] = unmount;
- return unmount;
- };
+ const createMountPoint =
+ (id: string, content: string = id): MountPoint =>
+ (root): MockedUnmount => {
+ const container = document.createElement('DIV');
+ // eslint-disable-next-line no-unsanitized/property
+ container.innerHTML = content;
+ root.appendChild(container);
+ const unmount = jest.fn(() => container.remove());
+ unmounts[id] = unmount;
+ return unmount;
+ };
it('mounts the current value of the provided observable', async () => {
component = mount();
diff --git a/src/core/public/notifications/toasts/error_toast.test.tsx b/src/core/public/notifications/toasts/error_toast.test.tsx
index 2fac3019db933..e0f917fb7f078 100644
--- a/src/core/public/notifications/toasts/error_toast.test.tsx
+++ b/src/core/public/notifications/toasts/error_toast.test.tsx
@@ -29,7 +29,9 @@ function render(props: ErrorToastProps = {}) {
error={props.error || new Error('error message')}
title={props.title || 'An error occured'}
toastMessage={props.toastMessage || 'This is the toast message'}
- i18nContext={() => ({ children }) => {children}}
+ i18nContext={() =>
+ ({ children }) =>
+ {children}}
/>
);
}
diff --git a/src/core/public/overlays/banners/user_banner_service.test.ts b/src/core/public/overlays/banners/user_banner_service.test.ts
index a13d7b0ca8e67..ff46a03886d7e 100644
--- a/src/core/public/overlays/banners/user_banner_service.test.ts
+++ b/src/core/public/overlays/banners/user_banner_service.test.ts
@@ -72,7 +72,7 @@ describe('OverlayBannersService', () => {
startService();
expect(banners.replace).toHaveBeenCalledTimes(0);
- const update$ = (uiSettings.getUpdate$() as any) as Subject<{
+ const update$ = uiSettings.getUpdate$() as any as Subject<{
key: string;
}>;
@@ -87,7 +87,7 @@ describe('OverlayBannersService', () => {
it('removes banner when changed to empty string', () => {
startService('remove me!');
- const update$ = (uiSettings.getUpdate$() as any) as Subject<{
+ const update$ = uiSettings.getUpdate$() as any as Subject<{
key: string;
}>;
@@ -98,7 +98,7 @@ describe('OverlayBannersService', () => {
it('removes banner when changed to undefined', () => {
startService('remove me!');
- const update$ = (uiSettings.getUpdate$() as any) as Subject<{
+ const update$ = uiSettings.getUpdate$() as any as Subject<{
key: string;
}>;
@@ -111,7 +111,7 @@ describe('OverlayBannersService', () => {
startService('initial banner!');
expect(banners.replace).toHaveBeenCalledTimes(1);
- const update$ = (uiSettings.getUpdate$() as any) as Subject<{
+ const update$ = uiSettings.getUpdate$() as any as Subject<{
key: string;
}>;
diff --git a/src/core/public/plugins/plugin_context.ts b/src/core/public/plugins/plugin_context.ts
index 49c895aa80fc4..3461f570333d5 100644
--- a/src/core/public/plugins/plugin_context.ts
+++ b/src/core/public/plugins/plugin_context.ts
@@ -56,7 +56,7 @@ export function createPluginInitializerContext(
env: coreContext.env,
config: {
get() {
- return (pluginConfig as unknown) as T;
+ return pluginConfig as unknown as T;
},
},
};
diff --git a/src/core/public/plugins/plugin_reader.ts b/src/core/public/plugins/plugin_reader.ts
index db3085930888a..24508075975db 100644
--- a/src/core/public/plugins/plugin_reader.ts
+++ b/src/core/public/plugins/plugin_reader.ts
@@ -29,7 +29,7 @@ export interface CoreWindow {
* Reads the plugin's bundle declared in the global context.
*/
export function read(name: string) {
- const coreWindow = (window as unknown) as CoreWindow;
+ const coreWindow = window as unknown as CoreWindow;
const exportId = `plugin/${name}/public`;
if (!coreWindow.__kbnBundles__.has(exportId)) {
diff --git a/src/core/public/plugins/plugins_service.test.mocks.ts b/src/core/public/plugins/plugins_service.test.mocks.ts
index 1f85482569dbc..1858008e28016 100644
--- a/src/core/public/plugins/plugins_service.test.mocks.ts
+++ b/src/core/public/plugins/plugins_service.test.mocks.ts
@@ -14,12 +14,11 @@ export type MockedPluginInitializer = jest.Mock<
any
>;
-export const mockPluginInitializerProvider: jest.Mock<
- MockedPluginInitializer,
- [PluginName]
-> = jest.fn().mockImplementation(() => () => {
- throw new Error('No provider specified');
-});
+export const mockPluginInitializerProvider: jest.Mock = jest
+ .fn()
+ .mockImplementation(() => () => {
+ throw new Error('No provider specified');
+ });
jest.mock('./plugin_reader', () => ({
read: mockPluginInitializerProvider,
diff --git a/src/core/public/plugins/plugins_service.test.ts b/src/core/public/plugins/plugins_service.test.ts
index d85f8538e3a69..6bed958009419 100644
--- a/src/core/public/plugins/plugins_service.test.ts
+++ b/src/core/public/plugins/plugins_service.test.ts
@@ -117,7 +117,7 @@ describe('PluginsService', () => {
};
// Reset these for each test.
- mockPluginInitializers = new Map(([
+ mockPluginInitializers = new Map([
[
'pluginA',
jest.fn(() => ({
@@ -146,7 +146,7 @@ describe('PluginsService', () => {
stop: jest.fn(),
})),
],
- ] as unknown) as [[PluginName, any]]);
+ ] as unknown as [[PluginName, any]]);
});
describe('#getOpaqueIds()', () => {
diff --git a/src/core/public/utils/crypto/sha256.ts b/src/core/public/utils/crypto/sha256.ts
index 009f0ee69a9e8..c36099279d8fc 100644
--- a/src/core/public/utils/crypto/sha256.ts
+++ b/src/core/public/utils/crypto/sha256.ts
@@ -39,70 +39,14 @@
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
const K = [
- 0x428a2f98,
- 0x71374491,
- 0xb5c0fbcf,
- 0xe9b5dba5,
- 0x3956c25b,
- 0x59f111f1,
- 0x923f82a4,
- 0xab1c5ed5,
- 0xd807aa98,
- 0x12835b01,
- 0x243185be,
- 0x550c7dc3,
- 0x72be5d74,
- 0x80deb1fe,
- 0x9bdc06a7,
- 0xc19bf174,
- 0xe49b69c1,
- 0xefbe4786,
- 0x0fc19dc6,
- 0x240ca1cc,
- 0x2de92c6f,
- 0x4a7484aa,
- 0x5cb0a9dc,
- 0x76f988da,
- 0x983e5152,
- 0xa831c66d,
- 0xb00327c8,
- 0xbf597fc7,
- 0xc6e00bf3,
- 0xd5a79147,
- 0x06ca6351,
- 0x14292967,
- 0x27b70a85,
- 0x2e1b2138,
- 0x4d2c6dfc,
- 0x53380d13,
- 0x650a7354,
- 0x766a0abb,
- 0x81c2c92e,
- 0x92722c85,
- 0xa2bfe8a1,
- 0xa81a664b,
- 0xc24b8b70,
- 0xc76c51a3,
- 0xd192e819,
- 0xd6990624,
- 0xf40e3585,
- 0x106aa070,
- 0x19a4c116,
- 0x1e376c08,
- 0x2748774c,
- 0x34b0bcb5,
- 0x391c0cb3,
- 0x4ed8aa4a,
- 0x5b9cca4f,
- 0x682e6ff3,
- 0x748f82ee,
- 0x78a5636f,
- 0x84c87814,
- 0x8cc70208,
- 0x90befffa,
- 0xa4506ceb,
- 0xbef9a3f7,
- 0xc67178f2,
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];
const W = new Array(64);
diff --git a/src/core/public/utils/mount.tsx b/src/core/public/utils/mount.tsx
index 43d96c7f712cd..fc23202e2c71d 100644
--- a/src/core/public/utils/mount.tsx
+++ b/src/core/public/utils/mount.tsx
@@ -30,7 +30,9 @@ export const MountWrapper: React.FunctionComponent<{ mount: MountPoint; classNam
*
* @param node to get a mount for
*/
-export const mountReactNode = (node: React.ReactNode): MountPoint => (element: HTMLElement) => {
- render({node}, element);
- return () => unmountComponentAtNode(element);
-};
+export const mountReactNode =
+ (node: React.ReactNode): MountPoint =>
+ (element: HTMLElement) => {
+ render({node}, element);
+ return () => unmountComponentAtNode(element);
+ };
diff --git a/src/core/server/capabilities/resolve_capabilities.ts b/src/core/server/capabilities/resolve_capabilities.ts
index 89da7b6c30a19..34d7894543b03 100644
--- a/src/core/server/capabilities/resolve_capabilities.ts
+++ b/src/core/server/capabilities/resolve_capabilities.ts
@@ -16,22 +16,24 @@ export type CapabilitiesResolver = (
useDefaultCapabilities: boolean
) => Promise;
-export const getCapabilitiesResolver = (
- capabilities: () => Capabilities,
- switchers: () => CapabilitiesSwitcher[]
-): CapabilitiesResolver => async (
- request: KibanaRequest,
- applications: string[],
- useDefaultCapabilities: boolean
-): Promise => {
- return resolveCapabilities(
- capabilities(),
- switchers(),
- request,
- applications,
- useDefaultCapabilities
- );
-};
+export const getCapabilitiesResolver =
+ (
+ capabilities: () => Capabilities,
+ switchers: () => CapabilitiesSwitcher[]
+ ): CapabilitiesResolver =>
+ async (
+ request: KibanaRequest,
+ applications: string[],
+ useDefaultCapabilities: boolean
+ ): Promise => {
+ return resolveCapabilities(
+ capabilities(),
+ switchers(),
+ request,
+ applications,
+ useDefaultCapabilities
+ );
+ };
export const resolveCapabilities = async (
capabilities: Capabilities,
diff --git a/src/core/server/config/test_utils.ts b/src/core/server/config/test_utils.ts
index ab06ff50012b7..e3f9ca7eb29f2 100644
--- a/src/core/server/config/test_utils.ts
+++ b/src/core/server/config/test_utils.ts
@@ -22,7 +22,9 @@ function collectDeprecations(
deprecation,
path,
})),
- () => ({ message }) => deprecationMessages.push(message)
+ () =>
+ ({ message }) =>
+ deprecationMessages.push(message)
);
return {
messages: deprecationMessages,
diff --git a/src/core/server/context/container/context.mock.ts b/src/core/server/context/container/context.mock.ts
index 2a43006301c03..9996d609fc074 100644
--- a/src/core/server/context/container/context.mock.ts
+++ b/src/core/server/context/container/context.mock.ts
@@ -16,8 +16,10 @@ const createContextMock = (mockContext: any = {}) => {
registerContext: jest.fn(),
createHandler: jest.fn(),
};
- contextMock.createHandler.mockImplementation((pluginId, handler) => (...args) =>
- Promise.resolve(handler(mockContext, ...args))
+ contextMock.createHandler.mockImplementation(
+ (pluginId, handler) =>
+ (...args) =>
+ Promise.resolve(handler(mockContext, ...args))
);
return contextMock;
};
diff --git a/src/core/server/context/container/context.ts b/src/core/server/context/container/context.ts
index f3d91e268bd1c..2650c21853604 100644
--- a/src/core/server/context/container/context.ts
+++ b/src/core/server/context/container/context.ts
@@ -288,15 +288,14 @@ export class ContextContainer implements IContextContainer {
}
/** Sorts context provider pairs by core pairs first. */
-const sortByCoreFirst = (
- coreId: symbol
-): ((left: [any, { source: symbol }], right: [any, { source: symbol }]) => number) => (
- [leftName, leftProvider],
- [rightName, rightProvider]
-) => {
- if (leftProvider.source === coreId) {
- return rightProvider.source === coreId ? 0 : -1;
- } else {
- return rightProvider.source === coreId ? 1 : 0;
- }
-};
+const sortByCoreFirst =
+ (
+ coreId: symbol
+ ): ((left: [any, { source: symbol }], right: [any, { source: symbol }]) => number) =>
+ ([leftName, leftProvider], [rightName, rightProvider]) => {
+ if (leftProvider.source === coreId) {
+ return rightProvider.source === coreId ? 0 : -1;
+ } else {
+ return rightProvider.source === coreId ? 1 : 0;
+ }
+ };
diff --git a/src/core/server/core_app/core_app.test.ts b/src/core/server/core_app/core_app.test.ts
index e5c3a592a72c7..c13116577af71 100644
--- a/src/core/server/core_app/core_app.test.ts
+++ b/src/core/server/core_app/core_app.test.ts
@@ -132,7 +132,7 @@ describe('CoreApp', () => {
const [[, handler]] = prebootHTTPResourcesRegistrar.register.mock.calls;
const mockResponseFactory = httpResourcesMock.createResponseFactory();
handler(
- ({} as unknown) as RequestHandlerContext,
+ {} as unknown as RequestHandlerContext,
httpServerMock.createKibanaRequest(),
mockResponseFactory
);
diff --git a/src/core/server/core_usage_data/core_usage_data_service.ts b/src/core/server/core_usage_data/core_usage_data_service.ts
index ce9013d9437d6..72b70824d305d 100644
--- a/src/core/server/core_usage_data/core_usage_data_service.ts
+++ b/src/core/server/core_usage_data/core_usage_data_service.ts
@@ -88,7 +88,8 @@ const isCustomIndex = (index: string) => {
};
export class CoreUsageDataService
- implements CoreService {
+ implements CoreService
+{
private logger: Logger;
private elasticsearchConfig?: ElasticsearchConfigType;
private configService: CoreContext['configService'];
diff --git a/src/core/server/core_usage_data/core_usage_stats_client.mock.ts b/src/core/server/core_usage_data/core_usage_stats_client.mock.ts
index 438424f76d057..ac5855c3a4ba0 100644
--- a/src/core/server/core_usage_data/core_usage_stats_client.mock.ts
+++ b/src/core/server/core_usage_data/core_usage_stats_client.mock.ts
@@ -9,7 +9,7 @@
import { CoreUsageStatsClient } from '.';
const createUsageStatsClientMock = () =>
- (({
+ ({
getUsageStats: jest.fn().mockResolvedValue({}),
incrementSavedObjectsBulkCreate: jest.fn().mockResolvedValue(null),
incrementSavedObjectsBulkGet: jest.fn().mockResolvedValue(null),
@@ -26,7 +26,7 @@ const createUsageStatsClientMock = () =>
incrementSavedObjectsExport: jest.fn().mockResolvedValue(null),
incrementLegacyDashboardsImport: jest.fn().mockResolvedValue(null),
incrementLegacyDashboardsExport: jest.fn().mockResolvedValue(null),
- } as unknown) as jest.Mocked);
+ } as unknown as jest.Mocked);
export const coreUsageStatsClientMock = {
create: createUsageStatsClientMock,
diff --git a/src/core/server/deprecations/deprecations_factory.test.ts b/src/core/server/deprecations/deprecations_factory.test.ts
index 73beb84f57fa6..85ef521538b15 100644
--- a/src/core/server/deprecations/deprecations_factory.test.ts
+++ b/src/core/server/deprecations/deprecations_factory.test.ts
@@ -55,10 +55,10 @@ describe('DeprecationsFactory', () => {
});
describe('getAllDeprecations', () => {
- const mockDependencies = ({
+ const mockDependencies = {
esClient: jest.fn(),
savedObjectsClient: jest.fn(),
- } as unknown) as GetDeprecationsContext;
+ } as unknown as GetDeprecationsContext;
it('returns a flattened array of deprecations', async () => {
const deprecationsFactory = new DeprecationsFactory({ logger });
@@ -184,10 +184,10 @@ describe('DeprecationsFactory', () => {
});
describe('getDeprecations', () => {
- const mockDependencies = ({
+ const mockDependencies = {
esClient: jest.fn(),
savedObjectsClient: jest.fn(),
- } as unknown) as GetDeprecationsContext;
+ } as unknown as GetDeprecationsContext;
it('returns a flattened array of DeprecationInfo', async () => {
const deprecationsFactory = new DeprecationsFactory({ logger });
diff --git a/src/core/server/deprecations/deprecations_registry.test.ts b/src/core/server/deprecations/deprecations_registry.test.ts
index 82b09beaa5123..0e4f48b18a0a9 100644
--- a/src/core/server/deprecations/deprecations_registry.test.ts
+++ b/src/core/server/deprecations/deprecations_registry.test.ts
@@ -14,9 +14,9 @@ describe('DeprecationsRegistry', () => {
describe('registerDeprecations', () => {
it('throws if getDeprecations is not a function', async () => {
const deprecationsRegistry = new DeprecationsRegistry();
- const deprecationsConfig = ({
+ const deprecationsConfig = {
getDeprecations: null,
- } as unknown) as RegisterDeprecationsConfig;
+ } as unknown as RegisterDeprecationsConfig;
expect(() => deprecationsRegistry.registerDeprecations(deprecationsConfig)).toThrowError(
/getDeprecations must be a function/
);
@@ -46,7 +46,7 @@ describe('DeprecationsRegistry', () => {
describe('getDeprecations', () => {
it('returns all settled deprecations', async () => {
const deprecationsRegistry = new DeprecationsRegistry();
- const mockContext = ({} as unknown) as GetDeprecationsContext;
+ const mockContext = {} as unknown as GetDeprecationsContext;
const mockError = new Error();
const deprecationsConfigA = { getDeprecations: jest.fn().mockResolvedValue('hi') };
const deprecationsConfigB = { getDeprecations: jest.fn().mockRejectedValue(mockError) };
@@ -67,7 +67,7 @@ describe('DeprecationsRegistry', () => {
it('passes dependencies to registered getDeprecations function', async () => {
const deprecationsRegistry = new DeprecationsRegistry();
- const mockContext = ({} as unknown) as GetDeprecationsContext;
+ const mockContext = {} as unknown as GetDeprecationsContext;
const deprecationsConfig = { getDeprecations: jest.fn().mockResolvedValue('hi') };
deprecationsRegistry.registerDeprecations(deprecationsConfig);
const deprecations = await deprecationsRegistry.getDeprecations(mockContext);
diff --git a/src/core/server/deprecations/deprecations_service.test.ts b/src/core/server/deprecations/deprecations_service.test.ts
index bc0dbcef4a5b6..0067cff1d2306 100644
--- a/src/core/server/deprecations/deprecations_service.test.ts
+++ b/src/core/server/deprecations/deprecations_service.test.ts
@@ -93,9 +93,10 @@ describe('DeprecationsService', () => {
expect(deprecationsFactory.getRegistry).toBeCalledTimes(1);
expect(deprecationsFactory.getRegistry).toBeCalledWith('testDomain');
expect(deprecationsRegistry.registerDeprecations).toBeCalledTimes(1);
- const configDeprecations = await deprecationsRegistry.registerDeprecations.mock.calls[0][0].getDeprecations(
- getDeprecationsContext
- );
+ const configDeprecations =
+ await deprecationsRegistry.registerDeprecations.mock.calls[0][0].getDeprecations(
+ getDeprecationsContext
+ );
expect(configDeprecations).toMatchInlineSnapshot(`
Array [
Object {
@@ -136,9 +137,10 @@ describe('DeprecationsService', () => {
deprecationsFactory.getRegistry.mockReturnValue(deprecationsRegistry);
deprecationsService['registerConfigDeprecationsInfo'](deprecationsFactory);
- const configDeprecations = await deprecationsRegistry.registerDeprecations.mock.calls[0][0].getDeprecations(
- getDeprecationsContext
- );
+ const configDeprecations =
+ await deprecationsRegistry.registerDeprecations.mock.calls[0][0].getDeprecations(
+ getDeprecationsContext
+ );
expect(configDeprecations[0].level).toBe('warning');
});
});
diff --git a/src/core/server/deprecations/deprecations_service.ts b/src/core/server/deprecations/deprecations_service.ts
index bc981c21ba975..cfc0aae443d1b 100644
--- a/src/core/server/deprecations/deprecations_service.ts
+++ b/src/core/server/deprecations/deprecations_service.ts
@@ -126,7 +126,8 @@ export interface DeprecationsSetupDeps {
/** @internal */
export class DeprecationsService
- implements CoreService {
+ implements CoreService
+{
private readonly logger: Logger;
private readonly deprecationsFactory: DeprecationsFactory;
diff --git a/src/core/server/elasticsearch/client/configure_client.test.ts b/src/core/server/elasticsearch/client/configure_client.test.ts
index 4e2c9c22f42f8..35fcb5819d015 100644
--- a/src/core/server/elasticsearch/client/configure_client.test.ts
+++ b/src/core/server/elasticsearch/client/configure_client.test.ts
@@ -25,10 +25,10 @@ import { configureClient } from './configure_client';
const createFakeConfig = (
parts: Partial = {}
): ElasticsearchClientConfig => {
- return ({
+ return {
type: 'fake-config',
...parts,
- } as unknown) as ElasticsearchClientConfig;
+ } as unknown as ElasticsearchClientConfig;
};
const createFakeClient = () => {
diff --git a/src/core/server/elasticsearch/client/configure_client.ts b/src/core/server/elasticsearch/client/configure_client.ts
index efd22365d44f3..93c404593af3f 100644
--- a/src/core/server/elasticsearch/client/configure_client.ts
+++ b/src/core/server/elasticsearch/client/configure_client.ts
@@ -102,9 +102,12 @@ function getResponseMessage(event: RequestEvent): string {
* Returns stringified debug information from an Elasticsearch request event
* useful for logging in case of an unexpected failure.
*/
-export function getRequestDebugMeta(
- event: RequestEvent
-): { url: string; body: string; statusCode: number | null; method: string } {
+export function getRequestDebugMeta(event: RequestEvent): {
+ url: string;
+ body: string;
+ statusCode: number | null;
+ method: string;
+} {
const params = event.meta.request.params;
// definition is wrong, `params.querystring` can be either a string or an object
const querystring = convertQueryString(params.querystring);
diff --git a/src/core/server/elasticsearch/client/mocks.ts b/src/core/server/elasticsearch/client/mocks.ts
index 5e2bf784b2a1d..7c4cde1ae424d 100644
--- a/src/core/server/elasticsearch/client/mocks.ts
+++ b/src/core/server/elasticsearch/client/mocks.ts
@@ -92,7 +92,7 @@ const createInternalClientMock = (
export type ElasticsearchClientMock = DeeplyMockedKeys;
const createClientMock = (res?: MockedTransportRequestPromise): ElasticsearchClientMock =>
- (createInternalClientMock(res) as unknown) as ElasticsearchClientMock;
+ createInternalClientMock(res) as unknown as ElasticsearchClientMock;
export interface ScopedClusterClientMock {
asInternalUser: ElasticsearchClientMock;
diff --git a/src/core/server/elasticsearch/elasticsearch_service.ts b/src/core/server/elasticsearch/elasticsearch_service.ts
index eebd732749285..09c96696b7985 100644
--- a/src/core/server/elasticsearch/elasticsearch_service.ts
+++ b/src/core/server/elasticsearch/elasticsearch_service.ts
@@ -38,7 +38,8 @@ export interface SetupDeps {
/** @internal */
export class ElasticsearchService
- implements CoreService {
+ implements CoreService
+{
private readonly log: Logger;
private readonly config$: Observable;
private stop$ = new Subject();
diff --git a/src/core/server/elasticsearch/integration_tests/client.test.ts b/src/core/server/elasticsearch/integration_tests/client.test.ts
index 83b20761df1ae..f3c9cf27d3b29 100644
--- a/src/core/server/elasticsearch/integration_tests/client.test.ts
+++ b/src/core/server/elasticsearch/integration_tests/client.test.ts
@@ -38,24 +38,27 @@ describe('elasticsearch clients', () => {
it('does not return deprecation warning when x-elastic-product-origin header is set', async () => {
// Header should be automatically set by Core
- const resp1 = await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings(
- { index: '.kibana' }
- );
+ const resp1 =
+ await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings({
+ index: '.kibana',
+ });
expect(resp1.headers).not.toHaveProperty('warning');
// Also test setting it explicitly
- const resp2 = await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings(
- { index: '.kibana' },
- { headers: { 'x-elastic-product-origin': 'kibana' } }
- );
+ const resp2 =
+ await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings(
+ { index: '.kibana' },
+ { headers: { 'x-elastic-product-origin': 'kibana' } }
+ );
expect(resp2.headers).not.toHaveProperty('warning');
});
it('returns deprecation warning when x-elastic-product-orign header is not set', async () => {
- const resp = await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings(
- { index: '.kibana' },
- { headers: { 'x-elastic-product-origin': null } }
- );
+ const resp =
+ await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings(
+ { index: '.kibana' },
+ { headers: { 'x-elastic-product-origin': null } }
+ );
expect(resp.headers).toHaveProperty('warning');
expect(resp.headers!.warning).toMatch('system indices');
diff --git a/src/core/server/environment/resolve_uuid.test.ts b/src/core/server/environment/resolve_uuid.test.ts
index 40db2d697906b..3ee65e8ac99cf 100644
--- a/src/core/server/environment/resolve_uuid.test.ts
+++ b/src/core/server/environment/resolve_uuid.test.ts
@@ -35,7 +35,7 @@ const mockReadFile = ({
uuid: string;
error: any;
}>) => {
- ((readFile as unknown) as jest.Mock).mockImplementation(() => {
+ (readFile as unknown as jest.Mock).mockImplementation(() => {
if (error) {
return Promise.reject(error);
} else {
@@ -45,7 +45,7 @@ const mockReadFile = ({
};
const mockWriteFile = (error?: object) => {
- ((writeFile as unknown) as jest.Mock).mockImplementation(() => {
+ (writeFile as unknown as jest.Mock).mockImplementation(() => {
if (error) {
return Promise.reject(error);
} else {
diff --git a/src/core/server/execution_context/execution_context_service.ts b/src/core/server/execution_context/execution_context_service.ts
index d8ff5fca7847d..6e2b809e23043 100644
--- a/src/core/server/execution_context/execution_context_service.ts
+++ b/src/core/server/execution_context/execution_context_service.ts
@@ -69,7 +69,8 @@ export interface ExecutionContextSetup {
export type ExecutionContextStart = ExecutionContextSetup;
export class ExecutionContextService
- implements CoreService {
+ implements CoreService
+{
private readonly log: Logger;
private readonly contextStore: AsyncLocalStorage;
private readonly requestIdStore: AsyncLocalStorage<{ requestId: string }>;
diff --git a/src/core/server/http/http_service.mock.ts b/src/core/server/http/http_service.mock.ts
index 4cb1bc9867d2c..894ff38e12a35 100644
--- a/src/core/server/http/http_service.mock.ts
+++ b/src/core/server/http/http_service.mock.ts
@@ -108,7 +108,7 @@ const createPrebootContractMock = () => {
const createInternalSetupContractMock = () => {
const mock: InternalHttpServiceSetupMock = {
// we can mock other hapi server methods when we need it
- server: ({
+ server: {
name: 'http-server-test',
version: 'kibana',
route: jest.fn(),
@@ -116,7 +116,7 @@ const createInternalSetupContractMock = () => {
stop: jest.fn(),
config: jest.fn().mockReturnValue(configMock.create()),
// @ts-expect-error somehow it thinks that `Server` isn't a `Construtable`
- } as unknown) as jest.MockedClass,
+ } as unknown as jest.MockedClass,
createCookieSessionStorageFactory: jest.fn(),
registerOnPreRouting: jest.fn(),
registerOnPreAuth: jest.fn(),
diff --git a/src/core/server/http/http_service.ts b/src/core/server/http/http_service.ts
index 538a4c065e997..98ae0f8b81aa6 100644
--- a/src/core/server/http/http_service.ts
+++ b/src/core/server/http/http_service.ts
@@ -51,7 +51,8 @@ interface SetupDeps {
/** @internal */
export class HttpService
- implements CoreService {
+ implements CoreService
+{
private readonly prebootServer: HttpServer;
private isPrebootServerStopped = false;
private readonly httpServer: HttpServer;
diff --git a/src/core/server/http/integration_tests/lifecycle.test.ts b/src/core/server/http/integration_tests/lifecycle.test.ts
index 098dfbebfa7b5..1db0b3c131522 100644
--- a/src/core/server/http/integration_tests/lifecycle.test.ts
+++ b/src/core/server/http/integration_tests/lifecycle.test.ts
@@ -51,9 +51,11 @@ interface StorageData {
describe('OnPreRouting', () => {
it('supports registering a request interceptor', async () => {
- const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreRouting,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/', validate: false }, (context, req, res) => res.ok({ body: 'ok' }));
@@ -76,9 +78,11 @@ describe('OnPreRouting', () => {
});
it('supports request forwarding to specified url', async () => {
- const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreRouting,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/initial', validate: false }, (context, req, res) =>
@@ -110,9 +114,11 @@ describe('OnPreRouting', () => {
});
it('provides original request url', async () => {
- const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreRouting,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/login', validate: false }, (context, req, res) => {
@@ -135,9 +141,11 @@ describe('OnPreRouting', () => {
});
it('provides original request url if rewritten several times', async () => {
- const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreRouting,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/reroute-2', validate: false }, (context, req, res) => {
@@ -161,9 +169,11 @@ describe('OnPreRouting', () => {
});
it('does not provide request url if interceptor does not rewrite url', async () => {
- const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreRouting,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/login', validate: false }, (context, req, res) => {
@@ -184,9 +194,11 @@ describe('OnPreRouting', () => {
});
it('supports redirection from the interceptor', async () => {
- const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreRouting,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
const redirectUrl = '/redirectUrl';
@@ -207,9 +219,11 @@ describe('OnPreRouting', () => {
});
it('supports rejecting request and adjusting response headers', async () => {
- const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreRouting,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/', validate: false }, (context, req, res) => res.ok());
@@ -229,9 +243,11 @@ describe('OnPreRouting', () => {
});
it('does not expose error details if interceptor throws', async () => {
- const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreRouting,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/', validate: false }, (context, req, res) => res.ok());
@@ -254,9 +270,11 @@ describe('OnPreRouting', () => {
});
it('returns internal error if interceptor returns unexpected result', async () => {
- const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreRouting,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/', validate: false }, (context, req, res) => res.ok());
@@ -277,9 +295,11 @@ describe('OnPreRouting', () => {
});
it(`doesn't share request object between interceptors`, async () => {
- const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreRouting,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
registerOnPreRouting((req, res, t) => {
@@ -1172,9 +1192,11 @@ describe('Auth', () => {
describe('OnPreResponse', () => {
it('supports registering response interceptors', async () => {
- const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreResponse,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/', validate: false }, (context, req, res) => res.ok({ body: 'ok' }));
@@ -1197,9 +1219,11 @@ describe('OnPreResponse', () => {
});
it('supports additional headers attachments', async () => {
- const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreResponse,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/', validate: false }, (context, req, res) =>
@@ -1226,9 +1250,11 @@ describe('OnPreResponse', () => {
});
it('logs a warning if interceptor rewrites response header', async () => {
- const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreResponse,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/', validate: false }, (context, req, res) =>
@@ -1255,9 +1281,11 @@ describe('OnPreResponse', () => {
});
it("doesn't expose error details if interceptor throws", async () => {
- const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreResponse,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/', validate: false }, (context, req, res) => res.ok(undefined));
@@ -1279,9 +1307,11 @@ describe('OnPreResponse', () => {
});
it('returns internal error if interceptor returns unexpected result', async () => {
- const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreResponse,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/', validate: false }, (context, req, res) => res.ok());
@@ -1301,9 +1331,11 @@ describe('OnPreResponse', () => {
});
it('cannot change response statusCode', async () => {
- const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreResponse,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
registerOnPreResponse((req, res, t) => {
@@ -1319,9 +1351,11 @@ describe('OnPreResponse', () => {
});
it('has no access to request body', async () => {
- const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreResponse,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
let requestBody = null;
registerOnPreResponse((req, res, t) => {
@@ -1354,9 +1388,11 @@ describe('OnPreResponse', () => {
});
it('supports rendering a different response body', async () => {
- const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreResponse,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/', validate: false }, (context, req, res) => {
@@ -1380,9 +1416,11 @@ describe('OnPreResponse', () => {
});
it('supports rendering a different response body + headers', async () => {
- const { registerOnPreResponse, server: innerServer, createRouter } = await server.setup(
- setupDeps
- );
+ const {
+ registerOnPreResponse,
+ server: innerServer,
+ createRouter,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/', validate: false }, (context, req, res) => {
diff --git a/src/core/server/http/integration_tests/request.test.ts b/src/core/server/http/integration_tests/request.test.ts
index 0a30bfac85f5d..a2560c2c39fad 100644
--- a/src/core/server/http/integration_tests/request.test.ts
+++ b/src/core/server/http/integration_tests/request.test.ts
@@ -245,9 +245,11 @@ describe('KibanaRequest', () => {
});
it('does not complete before response has been sent', async () => {
- const { server: innerServer, createRouter, registerOnPreAuth } = await server.setup(
- setupDeps
- );
+ const {
+ server: innerServer,
+ createRouter,
+ registerOnPreAuth,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
const nextSpy = jest.fn();
diff --git a/src/core/server/http/integration_tests/router.test.ts b/src/core/server/http/integration_tests/router.test.ts
index a3e872ee3ea87..80676b6be6c63 100644
--- a/src/core/server/http/integration_tests/router.test.ts
+++ b/src/core/server/http/integration_tests/router.test.ts
@@ -64,9 +64,12 @@ describe('Options', () => {
});
it('Authenticated user has access to a route', async () => {
- const { server: innerServer, createRouter, registerAuth, auth } = await server.setup(
- setupDeps
- );
+ const {
+ server: innerServer,
+ createRouter,
+ registerAuth,
+ auth,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
registerAuth((req, res, toolkit) => {
@@ -91,9 +94,12 @@ describe('Options', () => {
});
it('User with no credentials can access a route', async () => {
- const { server: innerServer, createRouter, registerAuth, auth } = await server.setup(
- setupDeps
- );
+ const {
+ server: innerServer,
+ createRouter,
+ registerAuth,
+ auth,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
registerAuth((req, res, toolkit) => toolkit.notHandled());
@@ -117,9 +123,12 @@ describe('Options', () => {
});
it('User with invalid credentials can access a route', async () => {
- const { server: innerServer, createRouter, registerAuth, auth } = await server.setup(
- setupDeps
- );
+ const {
+ server: innerServer,
+ createRouter,
+ registerAuth,
+ auth,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
registerAuth((req, res, toolkit) => res.unauthorized());
@@ -143,9 +152,12 @@ describe('Options', () => {
});
it('does not redirect user and allows access to a resource', async () => {
- const { server: innerServer, createRouter, registerAuth, auth } = await server.setup(
- setupDeps
- );
+ const {
+ server: innerServer,
+ createRouter,
+ registerAuth,
+ auth,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
registerAuth((req, res, toolkit) =>
@@ -197,9 +209,12 @@ describe('Options', () => {
});
it('Authenticated user has access to a route', async () => {
- const { server: innerServer, createRouter, registerAuth, auth } = await server.setup(
- setupDeps
- );
+ const {
+ server: innerServer,
+ createRouter,
+ registerAuth,
+ auth,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
registerAuth((req, res, toolkit) => {
@@ -277,9 +292,12 @@ describe('Options', () => {
describe('false', () => {
it('does not try to authenticate a user', async () => {
- const { server: innerServer, createRouter, registerAuth, auth } = await server.setup(
- setupDeps
- );
+ const {
+ server: innerServer,
+ createRouter,
+ registerAuth,
+ auth,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
const authHook = jest.fn();
@@ -1844,9 +1862,11 @@ describe('ETag', () => {
describe('registerRouterAfterListening', () => {
it('allows a router to be registered before server has started listening', async () => {
- const { server: innerServer, createRouter, registerRouterAfterListening } = await server.setup(
- setupDeps
- );
+ const {
+ server: innerServer,
+ createRouter,
+ registerRouterAfterListening,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/', validate: false }, (context, req, res) => {
@@ -1869,9 +1889,11 @@ describe('registerRouterAfterListening', () => {
});
it('allows a router to be registered after server has started listening', async () => {
- const { server: innerServer, createRouter, registerRouterAfterListening } = await server.setup(
- setupDeps
- );
+ const {
+ server: innerServer,
+ createRouter,
+ registerRouterAfterListening,
+ } = await server.setup(setupDeps);
const router = createRouter('/');
router.get({ path: '/', validate: false }, (context, req, res) => {
diff --git a/src/core/server/http/logging/get_payload_size.test.ts b/src/core/server/http/logging/get_payload_size.test.ts
index 30cb547dd98b7..36ef2e9c8e5a0 100644
--- a/src/core/server/http/logging/get_payload_size.test.ts
+++ b/src/core/server/http/logging/get_payload_size.test.ts
@@ -226,11 +226,11 @@ describe('getPayloadSize', () => {
test('always provides content-length header if available', () => {
const headers = { 'content-length': '123' };
const result = getResponsePayloadBytes(
- ({
+ {
headers,
variety: 'plain',
source: 'abc',
- } as unknown) as Response,
+ } as unknown as Response,
logger
);
expect(result).toBe(123);
@@ -238,19 +238,19 @@ describe('getPayloadSize', () => {
test('uses first value when hapi header is an array', () => {
const headers = { 'content-length': ['123', '456'] };
- const result = getResponsePayloadBytes(({ headers } as unknown) as Response, logger);
+ const result = getResponsePayloadBytes({ headers } as unknown as Response, logger);
expect(result).toBe(123);
});
test('returns undefined if length is NaN', () => {
const headers = { 'content-length': 'oops' };
- const result = getResponsePayloadBytes(({ headers } as unknown) as Response, logger);
+ const result = getResponsePayloadBytes({ headers } as unknown as Response, logger);
expect(result).toBeUndefined();
});
});
test('defaults to undefined', () => {
- const result = getResponsePayloadBytes(({} as unknown) as Response, logger);
+ const result = getResponsePayloadBytes({} as unknown as Response, logger);
expect(result).toBeUndefined();
});
@@ -262,10 +262,10 @@ describe('getPayloadSize', () => {
},
};
const result = getResponsePayloadBytes(
- ({
+ {
variety: 'plain',
source: payload.circular,
- } as unknown) as Response,
+ } as unknown as Response,
logger
);
expect(result).toBeUndefined();
@@ -279,10 +279,10 @@ describe('getPayloadSize', () => {
},
};
getResponsePayloadBytes(
- ({
+ {
variety: 'plain',
source: payload.circular,
- } as unknown) as Response,
+ } as unknown as Response,
logger
);
expect(logger.warn.mock.calls[0][0]).toMatchInlineSnapshot(
diff --git a/src/core/server/http/logging/get_response_log.test.ts b/src/core/server/http/logging/get_response_log.test.ts
index 5f749220138d7..df91ae9c1a98b 100644
--- a/src/core/server/http/logging/get_response_log.test.ts
+++ b/src/core/server/http/logging/get_response_log.test.ts
@@ -40,7 +40,7 @@ function createMockHapiRequest({
query = {},
response = { headers: {}, statusCode: 200 },
}: RequestFixtureOptions = {}): Request {
- return ({
+ return {
auth,
body,
headers,
@@ -50,7 +50,7 @@ function createMockHapiRequest({
path,
query,
response,
- } as unknown) as Request;
+ } as unknown as Request;
}
describe('getEcsResponseLog', () => {
diff --git a/src/core/server/http/router/error_wrapper.test.ts b/src/core/server/http/router/error_wrapper.test.ts
index 53ee3bff61d9d..a25e9bb1df9bc 100644
--- a/src/core/server/http/router/error_wrapper.test.ts
+++ b/src/core/server/http/router/error_wrapper.test.ts
@@ -11,9 +11,11 @@ import { KibanaResponse, KibanaResponseFactory, kibanaResponseFactory } from './
import { wrapErrors } from './error_wrapper';
import { KibanaRequest, RequestHandler, RequestHandlerContext } from 'kibana/server';
-const createHandler = (handler: () => any): RequestHandler => () => {
- return handler();
-};
+const createHandler =
+ (handler: () => any): RequestHandler =>
+ () => {
+ return handler();
+ };
describe('wrapErrors', () => {
let context: RequestHandlerContext;
diff --git a/src/core/server/http/router/request.ts b/src/core/server/http/router/request.ts
index b9bf5693ab758..d16158bb0fb08 100644
--- a/src/core/server/http/router/request.ts
+++ b/src/core/server/http/router/request.ts
@@ -237,13 +237,18 @@ export class KibanaRequest<
private getRouteInfo(request: Request): KibanaRequestRoute {
const method = request.method as Method;
- const { parse, maxBytes, allow, output, timeout: payloadTimeout } =
- request.route.settings.payload || {};
+ const {
+ parse,
+ maxBytes,
+ allow,
+ output,
+ timeout: payloadTimeout,
+ } = request.route.settings.payload || {};
// net.Socket#timeout isn't documented, yet, and isn't part of the types... https://github.com/nodejs/node/pull/34543
// the socket is also undefined when using @hapi/shot, or when a "fake request" is used
const socketTimeout = (request.raw.req.socket as any)?.timeout;
- const options = ({
+ const options = {
authRequired: this.getAuthRequired(request),
// TypeScript note: Casting to `RouterOptions` to fix the following error:
//
@@ -268,7 +273,7 @@ export class KibanaRequest<
accepts: allow,
output: output as typeof validBodyOutput[number], // We do not support all the HAPI-supported outputs and TS complains
},
- } as unknown) as KibanaRequestRouteOptions; // TS does not understand this is OK so I'm enforced to do this enforced casting
+ } as unknown as KibanaRequestRouteOptions; // TS does not understand this is OK so I'm enforced to do this enforced casting
return {
path: request.path,
diff --git a/src/core/server/http/router/response.ts b/src/core/server/http/router/response.ts
index 6cea7fcf4c949..331a1ab38f069 100644
--- a/src/core/server/http/router/response.ts
+++ b/src/core/server/http/router/response.ts
@@ -45,7 +45,8 @@ export function isKibanaResponse(response: Record): response is IKi
* @internal
*/
export class KibanaResponse
- implements IKibanaResponse {
+ implements IKibanaResponse
+{
constructor(
public readonly status: number,
public readonly payload?: T,
diff --git a/src/core/server/http/router/router.ts b/src/core/server/http/router/router.ts
index 75fcc1bb0e083..d2d8dfa2cc72f 100644
--- a/src/core/server/http/router/router.ts
+++ b/src/core/server/http/router/router.ts
@@ -203,7 +203,8 @@ function validOptions(
* @internal
*/
export class Router
- implements IRouter {
+ implements IRouter
+{
public routes: Array> = [];
public get: IRouter['get'];
public post: IRouter['post'];
@@ -216,25 +217,27 @@ export class Router
) {
- const buildMethod = (method: Method) => (
- route: RouteConfig
,
- handler: RequestHandler
- ) => {
- const routeSchemas = routeSchemasFromRouteConfig(route, method);
-
- this.routes.push({
- handler: async (req, responseToolkit) =>
- await this.handle({
- routeSchemas,
- request: req,
- responseToolkit,
- handler: this.enhanceWithContext(handler),
- }),
- method,
- path: getRouteFullPath(this.routerPath, route.path),
- options: validOptions(method, route),
- });
- };
+ const buildMethod =
+ (method: Method) =>
+ (
+ route: RouteConfig
,
+ handler: RequestHandler
+ ) => {
+ const routeSchemas = routeSchemasFromRouteConfig(route, method);
+
+ this.routes.push({
+ handler: async (req, responseToolkit) =>
+ await this.handle({
+ routeSchemas,
+ request: req,
+ responseToolkit,
+ handler: this.enhanceWithContext(handler),
+ }),
+ method,
+ path: getRouteFullPath(this.routerPath, route.path),
+ options: validOptions(method, route),
+ });
+ };
this.get = buildMethod('get');
this.post = buildMethod('post');
diff --git a/src/core/server/logging/appenders/rewrite/policies/meta/meta_policy.test.ts b/src/core/server/logging/appenders/rewrite/policies/meta/meta_policy.test.ts
index faa026363ed40..f03c5bd9d1f8f 100644
--- a/src/core/server/logging/appenders/rewrite/policies/meta/meta_policy.test.ts
+++ b/src/core/server/logging/appenders/rewrite/policies/meta/meta_policy.test.ts
@@ -93,10 +93,10 @@ describe('MetaRewritePolicy', () => {
it('does not touch anything outside of LogMeta', () => {
const policy = createPolicy('update', [{ path: 'a', value: 'bar' }]);
const message = Symbol();
- expect(
- policy.rewrite(({ message, meta: { a: 'foo' } } as unknown) as LogRecord).message
- ).toBe(message);
- expect(policy.rewrite(({ message, meta: { a: 'foo' } } as unknown) as LogRecord))
+ expect(policy.rewrite({ message, meta: { a: 'foo' } } as unknown as LogRecord).message).toBe(
+ message
+ );
+ expect(policy.rewrite({ message, meta: { a: 'foo' } } as unknown as LogRecord))
.toMatchInlineSnapshot(`
Object {
"message": Symbol(),
@@ -147,9 +147,9 @@ describe('MetaRewritePolicy', () => {
const policy = createPolicy('remove', [{ path: 'message' }]);
const message = Symbol();
expect(
- policy.rewrite(({ message, meta: { message: 'foo' } } as unknown) as LogRecord).message
+ policy.rewrite({ message, meta: { message: 'foo' } } as unknown as LogRecord).message
).toBe(message);
- expect(policy.rewrite(({ message, meta: { message: 'foo' } } as unknown) as LogRecord))
+ expect(policy.rewrite({ message, meta: { message: 'foo' } } as unknown as LogRecord))
.toMatchInlineSnapshot(`
Object {
"message": Symbol(),
diff --git a/src/core/server/logging/logging_system.mock.ts b/src/core/server/logging/logging_system.mock.ts
index c74c7d962ff77..1ca778afa31a5 100644
--- a/src/core/server/logging/logging_system.mock.ts
+++ b/src/core/server/logging/logging_system.mock.ts
@@ -42,7 +42,7 @@ const collectLoggingSystemMock = (loggerFactory: LoggerFactory) => {
};
const clearLoggingSystemMock = (loggerFactory: LoggerFactory) => {
- const mockedLoggerFactory = (loggerFactory as unknown) as jest.Mocked;
+ const mockedLoggerFactory = loggerFactory as unknown as jest.Mocked;
mockedLoggerFactory.get.mockClear();
mockedLoggerFactory.asLoggerFactory.mockClear();
mockedLoggerFactory.upgrade.mockClear();
diff --git a/src/core/server/logging/logging_system.test.ts b/src/core/server/logging/logging_system.test.ts
index 8eed2aecb21d6..dd546d4e7eaca 100644
--- a/src/core/server/logging/logging_system.test.ts
+++ b/src/core/server/logging/logging_system.test.ts
@@ -24,7 +24,7 @@ const timestamp = new Date(Date.UTC(2012, 1, 1, 14, 33, 22, 11));
let mockConsoleLog: jest.SpyInstance;
import { createWriteStream } from 'fs';
-const mockCreateWriteStream = (createWriteStream as unknown) as jest.Mock;
+const mockCreateWriteStream = createWriteStream as unknown as jest.Mock;
import { LoggingSystem, config } from '.';
diff --git a/src/core/server/metrics/event_loop_delays/event_loop_delays_monitor.mocks.ts b/src/core/server/metrics/event_loop_delays/event_loop_delays_monitor.mocks.ts
index ee96668cf3e7c..691bfc5030c93 100644
--- a/src/core/server/metrics/event_loop_delays/event_loop_delays_monitor.mocks.ts
+++ b/src/core/server/metrics/event_loop_delays/event_loop_delays_monitor.mocks.ts
@@ -32,13 +32,13 @@ function createMockHistogram(overwrites: Partial = {}): Inter
function createMockEventLoopDelaysMonitor() {
const mockCollect = jest.fn();
- const MockEventLoopDelaysMonitor: jest.MockedClass<
- typeof EventLoopDelaysMonitor
- > = jest.fn().mockReturnValue({
- collect: mockCollect,
- reset: jest.fn(),
- stop: jest.fn(),
- });
+ const MockEventLoopDelaysMonitor: jest.MockedClass = jest
+ .fn()
+ .mockReturnValue({
+ collect: mockCollect,
+ reset: jest.fn(),
+ stop: jest.fn(),
+ });
mockCollect.mockReturnValue(createMockHistogram());
diff --git a/src/core/server/metrics/logging/get_ops_metrics_log.test.ts b/src/core/server/metrics/logging/get_ops_metrics_log.test.ts
index 2d7a6bebf255e..cba188c94c74e 100644
--- a/src/core/server/metrics/logging/get_ops_metrics_log.test.ts
+++ b/src/core/server/metrics/logging/get_ops_metrics_log.test.ts
@@ -37,7 +37,7 @@ function createMockOpsMetrics(testMetrics: Partial): OpsMetrics {
...testMetrics,
};
}
-const testMetrics = ({
+const testMetrics = {
process: {
memory: { heap: { used_in_bytes: 100 } },
uptime_in_millis: 1500,
@@ -50,7 +50,7 @@ const testMetrics = ({
'15m': 30,
},
},
-} as unknown) as Partial;
+} as unknown as Partial;
describe('getEcsOpsMetricsLog', () => {
it('provides correctly formatted message', () => {
@@ -67,11 +67,11 @@ describe('getEcsOpsMetricsLog', () => {
it('excludes values from the message if unavailable', () => {
const baseMetrics = createBaseOpsMetrics();
- const missingMetrics = ({
+ const missingMetrics = {
...baseMetrics,
process: {},
os: {},
- } as unknown) as OpsMetrics;
+ } as unknown as OpsMetrics;
const logMeta = getEcsOpsMetricsLog(missingMetrics);
expect(logMeta.message).toMatchInlineSnapshot(`""`);
});
diff --git a/src/core/server/metrics/metrics_service.ts b/src/core/server/metrics/metrics_service.ts
index 78e4dd98f93d6..8e9604b50fb57 100644
--- a/src/core/server/metrics/metrics_service.ts
+++ b/src/core/server/metrics/metrics_service.ts
@@ -23,7 +23,8 @@ interface MetricsServiceSetupDeps {
/** @internal */
export class MetricsService
- implements CoreService {
+ implements CoreService
+{
private readonly logger: Logger;
private readonly opsMetricsLogger: Logger;
private metricsCollector?: OpsMetricsCollector;
diff --git a/src/core/server/plugins/discovery/plugins_discovery.test.ts b/src/core/server/plugins/discovery/plugins_discovery.test.ts
index 15e53b0a34f7b..958e051d0476d 100644
--- a/src/core/server/plugins/discovery/plugins_discovery.test.ts
+++ b/src/core/server/plugins/discovery/plugins_discovery.test.ts
@@ -417,9 +417,8 @@ describe('plugins discovery system', () => {
[`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/plugin`]: Plugins.valid('plugin3'),
[`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/plugin`]: Plugins.valid('plugin4'),
[`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/sub5/plugin`]: Plugins.valid('plugin5'),
- [`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/sub5/sub6/plugin`]: Plugins.valid(
- 'plugin6'
- ),
+ [`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/sub5/sub6/plugin`]:
+ Plugins.valid('plugin6'),
},
{ createCwd: false }
);
diff --git a/src/core/server/plugins/discovery/scan_plugin_search_paths.test.ts b/src/core/server/plugins/discovery/scan_plugin_search_paths.test.ts
index 8c5e1f256aaa0..548c479975ddf 100644
--- a/src/core/server/plugins/discovery/scan_plugin_search_paths.test.ts
+++ b/src/core/server/plugins/discovery/scan_plugin_search_paths.test.ts
@@ -196,9 +196,8 @@ describe('scanPluginSearchPaths', () => {
[`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/plugin`]: Plugins.valid('plugin3'),
[`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/plugin`]: Plugins.valid('plugin4'),
[`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/sub5/plugin`]: Plugins.valid('plugin5'),
- [`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/sub5/sub6/plugin`]: Plugins.valid(
- 'plugin6'
- ),
+ [`${KIBANA_ROOT}/src/plugins/sub1/sub2/sub3/sub4/sub5/sub6/plugin`]:
+ Plugins.valid('plugin6'),
},
{ createCwd: false }
);
diff --git a/src/core/server/saved_objects/import/import_saved_objects.test.ts b/src/core/server/saved_objects/import/import_saved_objects.test.ts
index 792858b53b5ea..cf30d6c803933 100644
--- a/src/core/server/saved_objects/import/import_saved_objects.test.ts
+++ b/src/core/server/saved_objects/import/import_saved_objects.test.ts
@@ -69,7 +69,7 @@ describe('#importSavedObjectsFromStream', () => {
let readStream: Readable;
const objectLimit = 10;
- const overwrite = (Symbol() as unknown) as boolean;
+ const overwrite = Symbol() as unknown as boolean;
let savedObjectsClient: jest.Mocked;
let typeRegistry: jest.Mocked;
const namespace = 'some-namespace';
diff --git a/src/core/server/saved_objects/import/lib/check_conflicts.test.ts b/src/core/server/saved_objects/import/lib/check_conflicts.test.ts
index 3370dda05f68b..6ab37b0122e4b 100644
--- a/src/core/server/saved_objects/import/lib/check_conflicts.test.ts
+++ b/src/core/server/saved_objects/import/lib/check_conflicts.test.ts
@@ -23,7 +23,7 @@ const createObject = (type: string, id: string): SavedObjectType => ({
type,
id,
attributes: { title: 'some-title' },
- references: (Symbol() as unknown) as SavedObjectReference[],
+ references: Symbol() as unknown as SavedObjectReference[],
});
const getResultMock = {
diff --git a/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts b/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts
index 011e5500b8d9c..03d94492e7ec8 100644
--- a/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts
+++ b/src/core/server/saved_objects/import/lib/check_origin_conflicts.test.ts
@@ -34,7 +34,7 @@ const createObject = (
type,
id,
attributes: { title: `Title for ${type}:${id}` },
- references: (Symbol() as unknown) as SavedObjectReference[],
+ references: Symbol() as unknown as SavedObjectReference[],
...(originId && { originId }),
...(updatedAt && { updated_at: updatedAt }),
});
diff --git a/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts b/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts
index 8c5d05b253f11..38372e8fad6fd 100644
--- a/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts
+++ b/src/core/server/saved_objects/import/lib/create_saved_objects.test.ts
@@ -120,7 +120,7 @@ describe('#createSavedObjects', () => {
}),
conflict: (type: string, id: string) => {
const error = SavedObjectsErrorHelpers.createConflictError(type, id).output.payload;
- return ({ type, id, error } as unknown) as SavedObject;
+ return { type, id, error } as unknown as SavedObject;
},
unresolvableConflict: (type: string, id: string) => {
const conflictMock = getResultMock.conflict(type, id);
@@ -253,7 +253,7 @@ describe('#createSavedObjects', () => {
expectBulkCreateArgs.objects(1, argObjs);
};
const testBulkCreateOptions = async (namespace?: string) => {
- const overwrite = (Symbol() as unknown) as boolean;
+ const overwrite = Symbol() as unknown as boolean;
const options = setupParams({ objects: objs, namespace, overwrite });
setupMockResults(options);
diff --git a/src/core/server/saved_objects/import/lib/regenerate_ids.test.ts b/src/core/server/saved_objects/import/lib/regenerate_ids.test.ts
index e70476205f03c..2696a52e0554f 100644
--- a/src/core/server/saved_objects/import/lib/regenerate_ids.test.ts
+++ b/src/core/server/saved_objects/import/lib/regenerate_ids.test.ts
@@ -11,11 +11,11 @@ import { regenerateIds } from './regenerate_ids';
import { SavedObject } from '../../types';
describe('#regenerateIds', () => {
- const objects = ([
+ const objects = [
{ type: 'foo', id: '1' },
{ type: 'bar', id: '2' },
{ type: 'baz', id: '3' },
- ] as any) as SavedObject[];
+ ] as any as SavedObject[];
test('returns expected values', () => {
mockUuidv4
diff --git a/src/core/server/saved_objects/import/resolve_import_errors.test.ts b/src/core/server/saved_objects/import/resolve_import_errors.test.ts
index 3d4e95cf709db..d7d7544baafcb 100644
--- a/src/core/server/saved_objects/import/resolve_import_errors.test.ts
+++ b/src/core/server/saved_objects/import/resolve_import_errors.test.ts
@@ -259,7 +259,7 @@ describe('#importSavedObjectsFromStream', () => {
});
test('checks conflicts', async () => {
- const createNewCopies = (Symbol() as unknown) as boolean;
+ const createNewCopies = Symbol() as unknown as boolean;
const retries = [createRetry()];
const options = setupOptions({ retries, createNewCopies });
const collectedObjects = [createObject()];
@@ -282,7 +282,7 @@ describe('#importSavedObjectsFromStream', () => {
test('gets import ID map for retries', async () => {
const retries = [createRetry()];
- const createNewCopies = (Symbol() as unknown) as boolean;
+ const createNewCopies = Symbol() as unknown as boolean;
const options = setupOptions({ retries, createNewCopies });
const filteredObjects = [createObject()];
getMockFn(checkConflicts).mockResolvedValue({
diff --git a/src/core/server/saved_objects/migrations/mocks.ts b/src/core/server/saved_objects/migrations/mocks.ts
index ef806aa5f0fca..4bd4e2a1e52fd 100644
--- a/src/core/server/saved_objects/migrations/mocks.ts
+++ b/src/core/server/saved_objects/migrations/mocks.ts
@@ -9,17 +9,18 @@
import { SavedObjectMigrationContext } from './types';
import { SavedObjectsMigrationLogger } from './core';
-export const createSavedObjectsMigrationLoggerMock = (): jest.Mocked => {
- const mock = {
- debug: jest.fn(),
- info: jest.fn(),
- warning: jest.fn(),
- warn: jest.fn(),
- error: jest.fn(),
- };
+export const createSavedObjectsMigrationLoggerMock =
+ (): jest.Mocked => {
+ const mock = {
+ debug: jest.fn(),
+ info: jest.fn(),
+ warning: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ };
- return mock;
-};
+ return mock;
+ };
const createContextMock = ({
migrationVersion = '8.0.0',
diff --git a/src/core/server/saved_objects/migrationsv2/actions/bulk_overwrite_transformed_documents.ts b/src/core/server/saved_objects/migrationsv2/actions/bulk_overwrite_transformed_documents.ts
index 82f642b928058..9353ede9be6ac 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/bulk_overwrite_transformed_documents.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/bulk_overwrite_transformed_documents.ts
@@ -56,68 +56,70 @@ export interface BulkOverwriteTransformedDocumentsParams {
* Write the up-to-date transformed documents to the index, overwriting any
* documents that are still on their outdated version.
*/
-export const bulkOverwriteTransformedDocuments = ({
- client,
- index,
- transformedDocs,
- refresh = false,
-}: BulkOverwriteTransformedDocumentsParams): TaskEither.TaskEither<
- | RetryableEsClientError
- | TargetIndexHadWriteBlock
- | IndexNotFound
- | RequestEntityTooLargeException,
- 'bulk_index_succeeded'
-> => () => {
- const body = transformedDocs.flatMap((doc) => {
- return createBulkOperationBody(doc, index);
- });
+export const bulkOverwriteTransformedDocuments =
+ ({
+ client,
+ index,
+ transformedDocs,
+ refresh = false,
+ }: BulkOverwriteTransformedDocumentsParams): TaskEither.TaskEither<
+ | RetryableEsClientError
+ | TargetIndexHadWriteBlock
+ | IndexNotFound
+ | RequestEntityTooLargeException,
+ 'bulk_index_succeeded'
+ > =>
+ () => {
+ const body = transformedDocs.flatMap((doc) => {
+ return createBulkOperationBody(doc, index);
+ });
- return client
- .bulk({
- // Because we only add aliases in the MARK_VERSION_INDEX_READY step we
- // can't bulkIndex to an alias with require_alias=true. This means if
- // users tamper during this operation (delete indices or restore a
- // snapshot), we could end up auto-creating an index without the correct
- // mappings. Such tampering could lead to many other problems and is
- // probably unlikely so for now we'll accept this risk and wait till
- // system indices puts in place a hard control.
- require_alias: false,
- wait_for_active_shards: WAIT_FOR_ALL_SHARDS_TO_BE_ACTIVE,
- refresh,
- filter_path: ['items.*.error'],
- body,
- })
- .then((res) => {
- // Filter out version_conflict_engine_exception since these just mean
- // that another instance already updated these documents
- const errors = (res.body.items ?? [])
- .filter((item) => item.index?.error)
- .map((item) => item.index!.error!)
- .filter(({ type }) => type !== 'version_conflict_engine_exception');
+ return client
+ .bulk({
+ // Because we only add aliases in the MARK_VERSION_INDEX_READY step we
+ // can't bulkIndex to an alias with require_alias=true. This means if
+ // users tamper during this operation (delete indices or restore a
+ // snapshot), we could end up auto-creating an index without the correct
+ // mappings. Such tampering could lead to many other problems and is
+ // probably unlikely so for now we'll accept this risk and wait till
+ // system indices puts in place a hard control.
+ require_alias: false,
+ wait_for_active_shards: WAIT_FOR_ALL_SHARDS_TO_BE_ACTIVE,
+ refresh,
+ filter_path: ['items.*.error'],
+ body,
+ })
+ .then((res) => {
+ // Filter out version_conflict_engine_exception since these just mean
+ // that another instance already updated these documents
+ const errors = (res.body.items ?? [])
+ .filter((item) => item.index?.error)
+ .map((item) => item.index!.error!)
+ .filter(({ type }) => type !== 'version_conflict_engine_exception');
- if (errors.length === 0) {
- return Either.right('bulk_index_succeeded' as const);
- } else {
- if (errors.every(isWriteBlockException)) {
- return Either.left({
- type: 'target_index_had_write_block' as const,
- });
+ if (errors.length === 0) {
+ return Either.right('bulk_index_succeeded' as const);
+ } else {
+ if (errors.every(isWriteBlockException)) {
+ return Either.left({
+ type: 'target_index_had_write_block' as const,
+ });
+ }
+ if (errors.every(isIndexNotFoundException)) {
+ return Either.left({
+ type: 'index_not_found_exception' as const,
+ index,
+ });
+ }
+ throw new Error(JSON.stringify(errors));
}
- if (errors.every(isIndexNotFoundException)) {
- return Either.left({
- type: 'index_not_found_exception' as const,
- index,
- });
+ })
+ .catch((error) => {
+ if (error instanceof esErrors.ResponseError && error.statusCode === 413) {
+ return Either.left({ type: 'request_entity_too_large_exception' as const });
+ } else {
+ throw error;
}
- throw new Error(JSON.stringify(errors));
- }
- })
- .catch((error) => {
- if (error instanceof esErrors.ResponseError && error.statusCode === 413) {
- return Either.left({ type: 'request_entity_too_large_exception' as const });
- } else {
- throw error;
- }
- })
- .catch(catchRetryableEsClientErrors);
-};
+ })
+ .catch(catchRetryableEsClientErrors);
+ };
diff --git a/src/core/server/saved_objects/migrationsv2/actions/calculate_exclude_filters.ts b/src/core/server/saved_objects/migrationsv2/actions/calculate_exclude_filters.ts
index 9d57db079e33e..9ba098d01870f 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/calculate_exclude_filters.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/calculate_exclude_filters.ts
@@ -28,80 +28,82 @@ export interface CalculatedExcludeFilter {
errorsByType: Record;
}
-export const calculateExcludeFilters = ({
- client,
- excludeFromUpgradeFilterHooks,
- hookTimeoutMs = 30_000, // default to 30s, exposed for testing
-}: CalculateExcludeFiltersParams): TaskEither.TaskEither<
- RetryableEsClientError,
- CalculatedExcludeFilter
-> => () => {
- return Promise.all<
- | Either.Right
- | Either.Left<{ soType: string; error: Error | RetryableEsClientError }>
- >(
- Object.entries(excludeFromUpgradeFilterHooks).map(([soType, hook]) =>
- withTimeout({
- promise: Promise.resolve(
- hook({ readonlyEsClient: { search: client.search.bind(client) } })
- ),
- timeoutMs: hookTimeoutMs,
- })
- .then((result) =>
- result.timedout
- ? Either.left({
+export const calculateExcludeFilters =
+ ({
+ client,
+ excludeFromUpgradeFilterHooks,
+ hookTimeoutMs = 30_000, // default to 30s, exposed for testing
+ }: CalculateExcludeFiltersParams): TaskEither.TaskEither<
+ RetryableEsClientError,
+ CalculatedExcludeFilter
+ > =>
+ () => {
+ return Promise.all<
+ | Either.Right
+ | Either.Left<{ soType: string; error: Error | RetryableEsClientError }>
+ >(
+ Object.entries(excludeFromUpgradeFilterHooks).map(([soType, hook]) =>
+ withTimeout({
+ promise: Promise.resolve(
+ hook({ readonlyEsClient: { search: client.search.bind(client) } })
+ ),
+ timeoutMs: hookTimeoutMs,
+ })
+ .then((result) =>
+ result.timedout
+ ? Either.left({
+ soType,
+ error: new Error(
+ `excludeFromUpgrade hook timed out after ${hookTimeoutMs / 1000} seconds.`
+ ),
+ })
+ : Either.right(result.value)
+ )
+ .catch((error) => {
+ const retryableError = catchRetryableEsClientErrors(error);
+ if (Either.isLeft(retryableError)) {
+ return Either.left({ soType, error: retryableError.left });
+ } else {
+ // Really should never happen, only here to satisfy TypeScript
+ return Either.left({
soType,
error: new Error(
- `excludeFromUpgrade hook timed out after ${hookTimeoutMs / 1000} seconds.`
+ `Unexpected return value from catchRetryableEsClientErrors: "${retryableError.toString()}"`
),
- })
- : Either.right(result.value)
- )
- .catch((error) => {
- const retryableError = catchRetryableEsClientErrors(error);
- if (Either.isLeft(retryableError)) {
- return Either.left({ soType, error: retryableError.left });
- } else {
- // Really should never happen, only here to satisfy TypeScript
- return Either.left({
- soType,
- error: new Error(
- `Unexpected return value from catchRetryableEsClientErrors: "${retryableError.toString()}"`
- ),
- });
- }
- })
- .catch((error: Error) => Either.left({ soType, error }))
- )
- ).then((results) => {
- const retryableError = results.find(
- (r) =>
- Either.isLeft(r) &&
- !(r.left.error instanceof Error) &&
- r.left.error.type === 'retryable_es_client_error'
- ) as Either.Left<{ soType: string; error: RetryableEsClientError }> | undefined;
- if (retryableError) {
- return Either.left(retryableError.left.error);
- }
+ });
+ }
+ })
+ .catch((error: Error) => Either.left({ soType, error }))
+ )
+ ).then((results) => {
+ const retryableError = results.find(
+ (r) =>
+ Either.isLeft(r) &&
+ !(r.left.error instanceof Error) &&
+ r.left.error.type === 'retryable_es_client_error'
+ ) as Either.Left<{ soType: string; error: RetryableEsClientError }> | undefined;
+ if (retryableError) {
+ return Either.left(retryableError.left.error);
+ }
- const errorsByType: Array<[string, Error]> = [];
- const filters: estypes.QueryDslQueryContainer[] = [];
+ const errorsByType: Array<[string, Error]> = [];
+ const filters: estypes.QueryDslQueryContainer[] = [];
- // Loop through all results and collect successes and errors
- results.forEach((r) =>
- Either.isRight(r)
- ? filters.push(r.right)
- : Either.isLeft(r) && errorsByType.push([r.left.soType, r.left.error as Error])
- );
+ // Loop through all results and collect successes and errors
+ results.forEach((r) =>
+ Either.isRight(r)
+ ? filters.push(r.right)
+ : Either.isLeft(r) && errorsByType.push([r.left.soType, r.left.error as Error])
+ );
- // Composite filter from all calculated filters that successfully executed
- const excludeFilter: estypes.QueryDslQueryContainer = {
- bool: { must_not: filters },
- };
+ // Composite filter from all calculated filters that successfully executed
+ const excludeFilter: estypes.QueryDslQueryContainer = {
+ bool: { must_not: filters },
+ };
- return Either.right({
- excludeFilter,
- errorsByType: Object.fromEntries(errorsByType),
+ return Either.right({
+ excludeFilter,
+ errorsByType: Object.fromEntries(errorsByType),
+ });
});
- });
-};
+ };
diff --git a/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.ts b/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.ts
index e3d72fbdf866f..1db47f0083467 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.ts
@@ -35,32 +35,31 @@ export interface UnknownDocsFound {
unknownDocs: CheckForUnknownDocsFoundDoc[];
}
-export const checkForUnknownDocs = ({
- client,
- indexName,
- unusedTypesQuery,
- knownTypes,
-}: CheckForUnknownDocsParams): TaskEither.TaskEither<
- RetryableEsClientError,
- UnknownDocsFound
-> => () => {
- const query = createUnknownDocQuery(unusedTypesQuery, knownTypes);
+export const checkForUnknownDocs =
+ ({
+ client,
+ indexName,
+ unusedTypesQuery,
+ knownTypes,
+ }: CheckForUnknownDocsParams): TaskEither.TaskEither =>
+ () => {
+ const query = createUnknownDocQuery(unusedTypesQuery, knownTypes);
- return client
- .search({
- index: indexName,
- body: {
- query,
- },
- })
- .then((response) => {
- const { hits } = response.body.hits;
- return Either.right({
- unknownDocs: hits.map((hit) => ({ id: hit._id, type: hit._source?.type ?? 'unknown' })),
- });
- })
- .catch(catchRetryableEsClientErrors);
-};
+ return client
+ .search({
+ index: indexName,
+ body: {
+ query,
+ },
+ })
+ .then((response) => {
+ const { hits } = response.body.hits;
+ return Either.right({
+ unknownDocs: hits.map((hit) => ({ id: hit._id, type: hit._source?.type ?? 'unknown' })),
+ });
+ })
+ .catch(catchRetryableEsClientErrors);
+ };
const createUnknownDocQuery = (
unusedTypesQuery: estypes.QueryDslQueryContainer,
diff --git a/src/core/server/saved_objects/migrationsv2/actions/close_pit.ts b/src/core/server/saved_objects/migrationsv2/actions/close_pit.ts
index d421950c839e2..9dd7f1d22386f 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/close_pit.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/close_pit.ts
@@ -23,19 +23,18 @@ export interface ClosePitParams {
* Closes PIT.
* See https://www.elastic.co/guide/en/elasticsearch/reference/current/point-in-time-api.html
* */
-export const closePit = ({
- client,
- pitId,
-}: ClosePitParams): TaskEither.TaskEither => () => {
- return client
- .closePointInTime({
- body: { id: pitId },
- })
- .then((response) => {
- if (!response.body.succeeded) {
- throw new Error(`Failed to close PointInTime with id: ${pitId}`);
- }
- return Either.right({});
- })
- .catch(catchRetryableEsClientErrors);
-};
+export const closePit =
+ ({ client, pitId }: ClosePitParams): TaskEither.TaskEither =>
+ () => {
+ return client
+ .closePointInTime({
+ body: { id: pitId },
+ })
+ .then((response) => {
+ if (!response.body.succeeded) {
+ throw new Error(`Failed to close PointInTime with id: ${pitId}`);
+ }
+ return Either.right({});
+ })
+ .catch(catchRetryableEsClientErrors);
+ };
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 8e5042a5ff8fe..d5269233344c3 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/create_index.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/create_index.ts
@@ -55,74 +55,72 @@ export const createIndex = ({
mappings,
aliases = [],
}: CreateIndexParams): TaskEither.TaskEither => {
- const createIndexTask: TaskEither.TaskEither<
- RetryableEsClientError,
- AcknowledgeResponse
- > = () => {
- const aliasesObject = aliasArrayToRecord(aliases);
+ const createIndexTask: TaskEither.TaskEither =
+ () => {
+ const aliasesObject = aliasArrayToRecord(aliases);
- return client.indices
- .create(
- {
- index: indexName,
- // wait until all shards are available before creating the index
- // (since number_of_shards=1 this does not have any effect atm)
- wait_for_active_shards: WAIT_FOR_ALL_SHARDS_TO_BE_ACTIVE,
- // Wait up to 60s for the cluster state to update and all shards to be
- // started
- timeout: DEFAULT_TIMEOUT,
- body: {
- mappings,
- aliases: aliasesObject,
- settings: {
- index: {
- // ES rule of thumb: shards should be several GB to 10's of GB, so
- // Kibana is unlikely to cross that limit.
- number_of_shards: 1,
- auto_expand_replicas: INDEX_AUTO_EXPAND_REPLICAS,
- // Set an explicit refresh interval so that we don't inherit the
- // value from incorrectly configured index templates (not required
- // after we adopt system indices)
- refresh_interval: '1s',
- // Bump priority so that recovery happens before newer indices
- priority: 10,
+ return client.indices
+ .create(
+ {
+ index: indexName,
+ // wait until all shards are available before creating the index
+ // (since number_of_shards=1 this does not have any effect atm)
+ wait_for_active_shards: WAIT_FOR_ALL_SHARDS_TO_BE_ACTIVE,
+ // Wait up to 60s for the cluster state to update and all shards to be
+ // started
+ timeout: DEFAULT_TIMEOUT,
+ body: {
+ mappings,
+ aliases: aliasesObject,
+ settings: {
+ index: {
+ // ES rule of thumb: shards should be several GB to 10's of GB, so
+ // Kibana is unlikely to cross that limit.
+ number_of_shards: 1,
+ auto_expand_replicas: INDEX_AUTO_EXPAND_REPLICAS,
+ // Set an explicit refresh interval so that we don't inherit the
+ // value from incorrectly configured index templates (not required
+ // after we adopt system indices)
+ refresh_interval: '1s',
+ // Bump priority so that recovery happens before newer indices
+ priority: 10,
+ },
},
},
},
- },
- { maxRetries: 0 /** handle retry ourselves for now */ }
- )
- .then((res) => {
- /**
- * - acknowledged=false, we timed out before the cluster state was
- * updated on all nodes with the newly created index, but it
- * probably will be created sometime soon.
- * - shards_acknowledged=false, we timed out before all shards were
- * started
- * - acknowledged=true, shards_acknowledged=true, index creation complete
- */
- return Either.right({
- acknowledged: res.body.acknowledged,
- shardsAcknowledged: res.body.shards_acknowledged,
- });
- })
- .catch((error) => {
- if (error?.body?.error?.type === 'resource_already_exists_exception') {
+ { maxRetries: 0 /** handle retry ourselves for now */ }
+ )
+ .then((res) => {
/**
- * If the target index already exists it means a previous create
- * operation had already been started. However, we can't be sure
- * that all shards were started so return shardsAcknowledged: false
+ * - acknowledged=false, we timed out before the cluster state was
+ * updated on all nodes with the newly created index, but it
+ * probably will be created sometime soon.
+ * - shards_acknowledged=false, we timed out before all shards were
+ * started
+ * - acknowledged=true, shards_acknowledged=true, index creation complete
*/
return Either.right({
- acknowledged: true,
- shardsAcknowledged: false,
+ acknowledged: res.body.acknowledged,
+ shardsAcknowledged: res.body.shards_acknowledged,
});
- } else {
- throw error;
- }
- })
- .catch(catchRetryableEsClientErrors);
- };
+ })
+ .catch((error) => {
+ if (error?.body?.error?.type === 'resource_already_exists_exception') {
+ /**
+ * If the target index already exists it means a previous create
+ * operation had already been started. However, we can't be sure
+ * that all shards were started so return shardsAcknowledged: false
+ */
+ return Either.right({
+ acknowledged: true,
+ shardsAcknowledged: false,
+ });
+ } else {
+ throw error;
+ }
+ })
+ .catch(catchRetryableEsClientErrors);
+ };
return pipe(
createIndexTask,
diff --git a/src/core/server/saved_objects/migrationsv2/actions/fetch_indices.ts b/src/core/server/saved_objects/migrationsv2/actions/fetch_indices.ts
index 3847252eb6db1..1256b2d858906 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/fetch_indices.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/fetch_indices.ts
@@ -28,10 +28,11 @@ export interface FetchIndicesParams {
* Fetches information about the given indices including aliases, mappings and
* settings.
*/
-export const fetchIndices = ({
- client,
- indices,
-}: FetchIndicesParams): TaskEither.TaskEither =>
+export const fetchIndices =
+ ({
+ client,
+ indices,
+ }: FetchIndicesParams): TaskEither.TaskEither =>
// @ts-expect-error @elastic/elasticsearch IndexState.alias and IndexState.mappings should be required
() => {
return client.indices
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 0ae6464f2623d..936746ddc6930 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
@@ -82,13 +82,13 @@ describe('migration actions', () => {
properties: {},
},
})();
- const sourceDocs = ([
+ const sourceDocs = [
{ _source: { title: 'doc 1' } },
{ _source: { title: 'doc 2' } },
{ _source: { title: 'doc 3' } },
{ _source: { title: 'saved object 4', type: 'another_unused_type' } },
{ _source: { title: 'f-agent-event 5', type: 'f_agent_event' } },
- ] as unknown) as SavedObjectsRawDoc[];
+ ] as unknown as SavedObjectsRawDoc[];
await bulkOverwriteTransformedDocuments({
client,
index: 'existing_index_with_docs',
@@ -182,12 +182,12 @@ describe('migration actions', () => {
expect.assertions(1);
const task = setWriteBlock({ client, index: 'new_index_without_write_block' });
await task();
- const sourceDocs = ([
+ const sourceDocs = [
{ _source: { title: 'doc 1' } },
{ _source: { title: 'doc 2' } },
{ _source: { title: 'doc 3' } },
{ _source: { title: 'doc 4' } },
- ] as unknown) as SavedObjectsRawDoc[];
+ ] as unknown as SavedObjectsRawDoc[];
const res = (await bulkOverwriteTransformedDocuments({
client,
@@ -452,11 +452,13 @@ describe('migration actions', () => {
}
`);
- const results = ((await searchForOutdatedDocuments(client, {
- batchSize: 1000,
- targetIndex: 'reindex_target',
- outdatedDocumentsQuery: undefined,
- })()) as Either.Right).right.outdatedDocuments;
+ const results = (
+ (await searchForOutdatedDocuments(client, {
+ batchSize: 1000,
+ targetIndex: 'reindex_target',
+ outdatedDocumentsQuery: undefined,
+ })()) as Either.Right
+ ).right.outdatedDocuments;
expect(results.map((doc) => doc._source.title).sort()).toMatchInlineSnapshot(`
Array [
"doc 1",
@@ -490,11 +492,13 @@ describe('migration actions', () => {
}
`);
- const results = ((await searchForOutdatedDocuments(client, {
- batchSize: 1000,
- targetIndex: 'reindex_target_excluded_docs',
- outdatedDocumentsQuery: undefined,
- })()) as Either.Right).right.outdatedDocuments;
+ const results = (
+ (await searchForOutdatedDocuments(client, {
+ batchSize: 1000,
+ targetIndex: 'reindex_target_excluded_docs',
+ outdatedDocumentsQuery: undefined,
+ })()) as Either.Right
+ ).right.outdatedDocuments;
expect(results.map((doc) => doc._source.title).sort()).toMatchInlineSnapshot(`
Array [
"doc 1",
@@ -520,11 +524,13 @@ describe('migration actions', () => {
"right": "reindex_succeeded",
}
`);
- const results = ((await searchForOutdatedDocuments(client, {
- batchSize: 1000,
- targetIndex: 'reindex_target_2',
- outdatedDocumentsQuery: undefined,
- })()) as Either.Right).right.outdatedDocuments;
+ const results = (
+ (await searchForOutdatedDocuments(client, {
+ batchSize: 1000,
+ targetIndex: 'reindex_target_2',
+ outdatedDocumentsQuery: undefined,
+ })()) as Either.Right
+ ).right.outdatedDocuments;
expect(results.map((doc) => doc._source.title).sort()).toMatchInlineSnapshot(`
Array [
"doc 1_updated",
@@ -572,11 +578,13 @@ describe('migration actions', () => {
`);
// Assert that documents weren't overridden by the second, unscripted reindex
- const results = ((await searchForOutdatedDocuments(client, {
- batchSize: 1000,
- targetIndex: 'reindex_target_3',
- outdatedDocumentsQuery: undefined,
- })()) as Either.Right).right.outdatedDocuments;
+ const results = (
+ (await searchForOutdatedDocuments(client, {
+ batchSize: 1000,
+ targetIndex: 'reindex_target_3',
+ outdatedDocumentsQuery: undefined,
+ })()) as Either.Right
+ ).right.outdatedDocuments;
expect(results.map((doc) => doc._source.title).sort()).toMatchInlineSnapshot(`
Array [
"doc 1_updated",
@@ -592,11 +600,13 @@ describe('migration actions', () => {
// Simulate a reindex that only adds some of the documents from the
// source index into the target index
await createIndex({ client, indexName: 'reindex_target_4', mappings: { properties: {} } })();
- const sourceDocs = ((await searchForOutdatedDocuments(client, {
- batchSize: 1000,
- targetIndex: 'existing_index_with_docs',
- outdatedDocumentsQuery: undefined,
- })()) as Either.Right).right.outdatedDocuments
+ const sourceDocs = (
+ (await searchForOutdatedDocuments(client, {
+ batchSize: 1000,
+ targetIndex: 'existing_index_with_docs',
+ outdatedDocumentsQuery: undefined,
+ })()) as Either.Right
+ ).right.outdatedDocuments
.slice(0, 2)
.map(({ _id, _source }) => ({
_id,
@@ -627,11 +637,13 @@ describe('migration actions', () => {
`);
// Assert that existing documents weren't overridden, but that missing
// documents were added by the reindex
- const results = ((await searchForOutdatedDocuments(client, {
- batchSize: 1000,
- targetIndex: 'reindex_target_4',
- outdatedDocumentsQuery: undefined,
- })()) as Either.Right).right.outdatedDocuments;
+ const results = (
+ (await searchForOutdatedDocuments(client, {
+ batchSize: 1000,
+ targetIndex: 'reindex_target_4',
+ outdatedDocumentsQuery: undefined,
+ })()) as Either.Right
+ ).right.outdatedDocuments;
expect(results.map((doc) => doc._source.title).sort()).toMatchInlineSnapshot(`
Array [
"doc 1",
@@ -1106,8 +1118,9 @@ describe('migration actions', () => {
outdatedDocuments: originalDocs,
});
- const resultsWithProcessDocs = ((await transformTask()) as Either.Right)
- .right.processedDocs;
+ const resultsWithProcessDocs = (
+ (await transformTask()) as Either.Right
+ ).right.processedDocs;
expect(resultsWithProcessDocs.length).toEqual(2);
const foo2 = resultsWithProcessDocs.find((h) => h._id === 'foo:2');
expect(foo2?._source?.value).toBe(3);
@@ -1130,7 +1143,8 @@ describe('migration actions', () => {
// We can't do a snapshot match because the response includes an index
// id which ES assigns dynamically
await expect(task()).rejects.toMatchObject({
- message: /pickupUpdatedMappings task failed with the following failures:\n\[\{\"index\":\"existing_index_with_write_block\"/,
+ message:
+ /pickupUpdatedMappings task failed with the following failures:\n\[\{\"index\":\"existing_index_with_write_block\"/,
});
});
it('rejects if there is an error', async () => {
@@ -1202,12 +1216,12 @@ describe('migration actions', () => {
properties: {},
},
})();
- const sourceDocs = ([
+ const sourceDocs = [
{ _source: { title: 'doc 1' } },
{ _source: { title: 'doc 2' } },
{ _source: { title: 'doc 3' } },
{ _source: { title: 'doc 4' } },
- ] as unknown) as SavedObjectsRawDoc[];
+ ] as unknown as SavedObjectsRawDoc[];
await bulkOverwriteTransformedDocuments({
client,
index: 'existing_index_without_mappings',
@@ -1216,13 +1230,15 @@ describe('migration actions', () => {
})();
// Assert that we can't search over the unmapped fields of the document
- const originalSearchResults = ((await searchForOutdatedDocuments(client, {
- batchSize: 1000,
- targetIndex: 'existing_index_without_mappings',
- outdatedDocumentsQuery: {
- match: { title: { query: 'doc' } },
- },
- })()) as Either.Right).right.outdatedDocuments;
+ const originalSearchResults = (
+ (await searchForOutdatedDocuments(client, {
+ batchSize: 1000,
+ targetIndex: 'existing_index_without_mappings',
+ outdatedDocumentsQuery: {
+ match: { title: { query: 'doc' } },
+ },
+ })()) as Either.Right
+ ).right.outdatedDocuments;
expect(originalSearchResults.length).toBe(0);
// Update and pickup mappings so that the title field is searchable
@@ -1240,13 +1256,15 @@ describe('migration actions', () => {
await waitForPickupUpdatedMappingsTask({ client, taskId, timeout: '60s' })();
// Repeat the search expecting to be able to find the existing documents
- const pickedUpSearchResults = ((await searchForOutdatedDocuments(client, {
- batchSize: 1000,
- targetIndex: 'existing_index_without_mappings',
- outdatedDocumentsQuery: {
- match: { title: { query: 'doc' } },
- },
- })()) as Either.Right).right.outdatedDocuments;
+ const pickedUpSearchResults = (
+ (await searchForOutdatedDocuments(client, {
+ batchSize: 1000,
+ targetIndex: 'existing_index_without_mappings',
+ outdatedDocumentsQuery: {
+ match: { title: { query: 'doc' } },
+ },
+ })()) as Either.Right
+ ).right.outdatedDocuments;
expect(pickedUpSearchResults.length).toBe(4);
});
});
@@ -1461,11 +1479,11 @@ describe('migration actions', () => {
describe('bulkOverwriteTransformedDocuments', () => {
it('resolves right when documents do not yet exist in the index', async () => {
- const newDocs = ([
+ const newDocs = [
{ _source: { title: 'doc 5' } },
{ _source: { title: 'doc 6' } },
{ _source: { title: 'doc 7' } },
- ] as unknown) as SavedObjectsRawDoc[];
+ ] as unknown as SavedObjectsRawDoc[];
const task = bulkOverwriteTransformedDocuments({
client,
index: 'existing_index_with_docs',
@@ -1481,18 +1499,20 @@ describe('migration actions', () => {
`);
});
it('resolves right even if there were some version_conflict_engine_exception', async () => {
- const existingDocs = ((await searchForOutdatedDocuments(client, {
- batchSize: 1000,
- targetIndex: 'existing_index_with_docs',
- outdatedDocumentsQuery: undefined,
- })()) as Either.Right).right.outdatedDocuments;
+ const existingDocs = (
+ (await searchForOutdatedDocuments(client, {
+ batchSize: 1000,
+ targetIndex: 'existing_index_with_docs',
+ outdatedDocumentsQuery: undefined,
+ })()) as Either.Right
+ ).right.outdatedDocuments;
const task = bulkOverwriteTransformedDocuments({
client,
index: 'existing_index_with_docs',
transformedDocs: [
...existingDocs,
- ({ _source: { title: 'doc 8' } } as unknown) as SavedObjectsRawDoc,
+ { _source: { title: 'doc 8' } } as unknown as SavedObjectsRawDoc,
],
refresh: 'wait_for',
});
@@ -1504,11 +1524,11 @@ describe('migration actions', () => {
`);
});
it('resolves left target_index_had_write_block if there are write_block errors', async () => {
- const newDocs = ([
+ const newDocs = [
{ _source: { title: 'doc 5' } },
{ _source: { title: 'doc 6' } },
{ _source: { title: 'doc 7' } },
- ] as unknown) as SavedObjectsRawDoc[];
+ ] as unknown as SavedObjectsRawDoc[];
await expect(
bulkOverwriteTransformedDocuments({
client,
diff --git a/src/core/server/saved_objects/migrationsv2/actions/open_pit.ts b/src/core/server/saved_objects/migrationsv2/actions/open_pit.ts
index e740dc00ac27e..43c84a2b26613 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/open_pit.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/open_pit.ts
@@ -29,15 +29,17 @@ export const pitKeepAlive = '10m';
* Creates a lightweight view of data when the request has been initiated.
* See https://www.elastic.co/guide/en/elasticsearch/reference/current/point-in-time-api.html
* */
-export const openPit = ({
- client,
- index,
-}: OpenPitParams): TaskEither.TaskEither => () => {
- return client
- .openPointInTime({
- index,
- keep_alive: pitKeepAlive,
- })
- .then((response) => Either.right({ pitId: response.body.id }))
- .catch(catchRetryableEsClientErrors);
-};
+export const openPit =
+ ({
+ client,
+ index,
+ }: OpenPitParams): TaskEither.TaskEither =>
+ () => {
+ return client
+ .openPointInTime({
+ index,
+ keep_alive: pitKeepAlive,
+ })
+ .then((response) => Either.right({ pitId: response.body.id }))
+ .catch(catchRetryableEsClientErrors);
+ };
diff --git a/src/core/server/saved_objects/migrationsv2/actions/pickup_updated_mappings.ts b/src/core/server/saved_objects/migrationsv2/actions/pickup_updated_mappings.ts
index 8cc609e5277bc..2db6b1833c6dd 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/pickup_updated_mappings.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/pickup_updated_mappings.ts
@@ -31,27 +31,29 @@ export interface UpdateByQueryResponse {
* This action uses `conflicts: 'proceed'` allowing several Kibana instances
* to run this in parallel.
*/
-export const pickupUpdatedMappings = (
- client: ElasticsearchClient,
- index: string
-): TaskEither.TaskEither => () => {
- return client
- .updateByQuery({
- // Ignore version conflicts that can occur from parallel update by query operations
- conflicts: 'proceed',
- // Return an error when targeting missing or closed indices
- allow_no_indices: false,
- index,
- // How many documents to update per batch
- scroll_size: BATCH_SIZE,
- // force a refresh so that we can query the updated index immediately
- // after the operation completes
- refresh: true,
- // Create a task and return task id instead of blocking until complete
- wait_for_completion: false,
- })
- .then(({ body: { task: taskId } }) => {
- return Either.right({ taskId: String(taskId!) });
- })
- .catch(catchRetryableEsClientErrors);
-};
+export const pickupUpdatedMappings =
+ (
+ client: ElasticsearchClient,
+ index: string
+ ): TaskEither.TaskEither =>
+ () => {
+ return client
+ .updateByQuery({
+ // Ignore version conflicts that can occur from parallel update by query operations
+ conflicts: 'proceed',
+ // Return an error when targeting missing or closed indices
+ allow_no_indices: false,
+ index,
+ // How many documents to update per batch
+ scroll_size: BATCH_SIZE,
+ // force a refresh so that we can query the updated index immediately
+ // after the operation completes
+ refresh: true,
+ // Create a task and return task id instead of blocking until complete
+ wait_for_completion: false,
+ })
+ .then(({ body: { task: taskId } }) => {
+ return Either.right({ taskId: String(taskId!) });
+ })
+ .catch(catchRetryableEsClientErrors);
+ };
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 b101e7db0141c..c8e7d61dce811 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
@@ -37,56 +37,58 @@ export interface ReadWithPitParams {
/*
* Requests documents from the index using PIT mechanism.
* */
-export const readWithPit = ({
- client,
- pitId,
- query,
- batchSize,
- searchAfter,
- seqNoPrimaryTerm,
-}: ReadWithPitParams): TaskEither.TaskEither => () => {
- return client
- .search({
- seq_no_primary_term: seqNoPrimaryTerm,
- body: {
- // Sort fields are required to use searchAfter
- sort: {
- // the most efficient option as order is not important for the migration
- _shard_doc: { order: 'asc' },
+export const readWithPit =
+ ({
+ client,
+ pitId,
+ query,
+ batchSize,
+ searchAfter,
+ seqNoPrimaryTerm,
+ }: ReadWithPitParams): TaskEither.TaskEither =>
+ () => {
+ return client
+ .search({
+ seq_no_primary_term: seqNoPrimaryTerm,
+ body: {
+ // Sort fields are required to use searchAfter
+ sort: {
+ // the most efficient option as order is not important for the migration
+ _shard_doc: { order: 'asc' },
+ },
+ pit: { id: pitId, keep_alive: pitKeepAlive },
+ size: batchSize,
+ search_after: searchAfter,
+ /**
+ * We want to know how many documents we need to process so we can log the progress.
+ * But we also want to increase the performance of these requests,
+ * so we ask ES to report the total count only on the first request (when searchAfter does not exist)
+ */
+ track_total_hits: typeof searchAfter === 'undefined',
+ query,
},
- pit: { id: pitId, keep_alive: pitKeepAlive },
- size: batchSize,
- search_after: searchAfter,
- /**
- * We want to know how many documents we need to process so we can log the progress.
- * But we also want to increase the performance of these requests,
- * so we ask ES to report the total count only on the first request (when searchAfter does not exist)
- */
- track_total_hits: typeof searchAfter === 'undefined',
- query,
- },
- })
- .then((response) => {
- const totalHits =
- typeof response.body.hits.total === 'number'
- ? response.body.hits.total // This format is to be removed in 8.0
- : response.body.hits.total?.value;
- const hits = response.body.hits.hits;
+ })
+ .then((response) => {
+ const totalHits =
+ typeof response.body.hits.total === 'number'
+ ? response.body.hits.total // This format is to be removed in 8.0
+ : response.body.hits.total?.value;
+ const hits = response.body.hits.hits;
+
+ if (hits.length > 0) {
+ return Either.right({
+ // @ts-expect-error @elastic/elasticsearch _source is optional
+ outdatedDocuments: hits as SavedObjectsRawDoc[],
+ lastHitSortValue: hits[hits.length - 1].sort as number[],
+ totalHits,
+ });
+ }
- if (hits.length > 0) {
return Either.right({
- // @ts-expect-error @elastic/elasticsearch _source is optional
- outdatedDocuments: hits as SavedObjectsRawDoc[],
- lastHitSortValue: hits[hits.length - 1].sort as number[],
+ outdatedDocuments: [],
+ lastHitSortValue: undefined,
totalHits,
});
- }
-
- return Either.right({
- outdatedDocuments: [],
- lastHitSortValue: undefined,
- totalHits,
- });
- })
- .catch(catchRetryableEsClientErrors);
-};
+ })
+ .catch(catchRetryableEsClientErrors);
+ };
diff --git a/src/core/server/saved_objects/migrationsv2/actions/refresh_index.ts b/src/core/server/saved_objects/migrationsv2/actions/refresh_index.ts
index e7bcbfb7d2d53..371247789af24 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/refresh_index.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/refresh_index.ts
@@ -22,19 +22,18 @@ export interface RefreshIndexParams {
/**
* Wait for Elasticsearch to reindex all the changes.
*/
-export const refreshIndex = ({
- client,
- targetIndex,
-}: RefreshIndexParams): TaskEither.TaskEither<
- RetryableEsClientError,
- { refreshed: boolean }
-> => () => {
- return client.indices
- .refresh({
- index: targetIndex,
- })
- .then(() => {
- return Either.right({ refreshed: true });
- })
- .catch(catchRetryableEsClientErrors);
-};
+export const refreshIndex =
+ ({
+ client,
+ targetIndex,
+ }: RefreshIndexParams): TaskEither.TaskEither =>
+ () => {
+ return client.indices
+ .refresh({
+ index: targetIndex,
+ })
+ .then(() => {
+ return Either.right({ refreshed: true });
+ })
+ .catch(catchRetryableEsClientErrors);
+ };
diff --git a/src/core/server/saved_objects/migrationsv2/actions/reindex.ts b/src/core/server/saved_objects/migrationsv2/actions/reindex.ts
index e9cfb4b61dace..92134d2755ac3 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/reindex.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/reindex.ts
@@ -42,49 +42,51 @@ export interface ReindexParams {
* this in parallel. By using `op_type: 'create', conflicts: 'proceed'` there
* will be only one write per reindexed document.
*/
-export const reindex = ({
- client,
- sourceIndex,
- targetIndex,
- reindexScript,
- requireAlias,
- unusedTypesQuery,
-}: ReindexParams): TaskEither.TaskEither => () => {
- return client
- .reindex({
- // Require targetIndex to be an alias. Prevents a new index from being
- // created if targetIndex doesn't exist.
- require_alias: requireAlias,
- body: {
- // Ignore version conflicts from existing documents
- conflicts: 'proceed',
- source: {
- index: sourceIndex,
- // Set reindex batch size
- size: BATCH_SIZE,
- // Exclude saved object types
- query: unusedTypesQuery,
+export const reindex =
+ ({
+ client,
+ sourceIndex,
+ targetIndex,
+ reindexScript,
+ requireAlias,
+ unusedTypesQuery,
+ }: ReindexParams): TaskEither.TaskEither =>
+ () => {
+ return client
+ .reindex({
+ // Require targetIndex to be an alias. Prevents a new index from being
+ // created if targetIndex doesn't exist.
+ require_alias: requireAlias,
+ body: {
+ // Ignore version conflicts from existing documents
+ conflicts: 'proceed',
+ source: {
+ index: sourceIndex,
+ // Set reindex batch size
+ size: BATCH_SIZE,
+ // Exclude saved object types
+ query: unusedTypesQuery,
+ },
+ dest: {
+ index: targetIndex,
+ // Don't override existing documents, only create if missing
+ op_type: 'create',
+ },
+ script: Option.fold(
+ () => undefined,
+ (script) => ({
+ source: script,
+ lang: 'painless',
+ })
+ )(reindexScript),
},
- dest: {
- index: targetIndex,
- // Don't override existing documents, only create if missing
- op_type: 'create',
- },
- script: Option.fold(
- () => undefined,
- (script) => ({
- source: script,
- lang: 'painless',
- })
- )(reindexScript),
- },
- // force a refresh so that we can query the target index
- refresh: true,
- // Create a task and return task id instead of blocking until complete
- wait_for_completion: false,
- })
- .then(({ body: { task: taskId } }) => {
- return Either.right({ taskId: String(taskId) });
- })
- .catch(catchRetryableEsClientErrors);
-};
+ // force a refresh so that we can query the target index
+ refresh: true,
+ // Create a task and return task id instead of blocking until complete
+ wait_for_completion: false,
+ })
+ .then(({ body: { task: taskId } }) => {
+ return Either.right({ taskId: String(taskId) });
+ })
+ .catch(catchRetryableEsClientErrors);
+ };
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 b5bf64d5c29f7..77445654d3cc3 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
@@ -22,39 +22,41 @@ export interface RemoveWriteBlockParams {
/**
* Removes a write block from an index
*/
-export const removeWriteBlock = ({
- client,
- index,
-}: RemoveWriteBlockParams): TaskEither.TaskEither<
- RetryableEsClientError,
- 'remove_write_block_succeeded'
-> => () => {
- return client.indices
- .putSettings<{
- acknowledged: boolean;
- shards_acknowledged: boolean;
- }>(
- {
- index,
- // Don't change any existing settings
- preserve_existing: true,
- body: {
- settings: {
- blocks: {
- write: false,
+export const removeWriteBlock =
+ ({
+ client,
+ index,
+ }: RemoveWriteBlockParams): TaskEither.TaskEither<
+ RetryableEsClientError,
+ 'remove_write_block_succeeded'
+ > =>
+ () => {
+ return client.indices
+ .putSettings<{
+ acknowledged: boolean;
+ shards_acknowledged: boolean;
+ }>(
+ {
+ index,
+ // Don't change any existing settings
+ preserve_existing: true,
+ body: {
+ settings: {
+ blocks: {
+ write: false,
+ },
},
},
},
- },
- { maxRetries: 0 /** handle retry ourselves for now */ }
- )
- .then((res) => {
- return res.body.acknowledged === true
- ? Either.right('remove_write_block_succeeded' as const)
- : Either.left({
- type: 'retryable_es_client_error' as const,
- message: 'remove_write_block_failed',
- });
- })
- .catch(catchRetryableEsClientErrors);
-};
+ { maxRetries: 0 /** handle retry ourselves for now */ }
+ )
+ .then((res) => {
+ return res.body.acknowledged === true
+ ? Either.right('remove_write_block_succeeded' as const)
+ : Either.left({
+ type: 'retryable_es_client_error' as const,
+ message: 'remove_write_block_failed',
+ });
+ })
+ .catch(catchRetryableEsClientErrors);
+ };
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 c27170a78245b..5a6cb3a3d048d 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
@@ -34,44 +34,46 @@ export interface SearchForOutdatedDocumentsOptions {
*
* Used for testing only
*/
-export const searchForOutdatedDocuments = (
- client: ElasticsearchClient,
- options: SearchForOutdatedDocumentsOptions
-): TaskEither.TaskEither => () => {
- return client
- .search({
- index: options.targetIndex,
- // Return the _seq_no and _primary_term so we can use optimistic
- // concurrency control for updates
- seq_no_primary_term: true,
- size: options.batchSize,
- body: {
- query: options.outdatedDocumentsQuery,
- // Optimize search performance by sorting by the "natural" index order
- sort: ['_doc'],
- },
- // Return an error when targeting missing or closed indices
- allow_no_indices: false,
- // Don't return partial results if timeouts or shard failures are
- // encountered. This is important because 0 search hits is interpreted as
- // there being no more outdated documents left that require
- // transformation. Although the default is `false`, we set this
- // explicitly to avoid users overriding the
- // search.default_allow_partial_results cluster setting to true.
- allow_partial_search_results: false,
- // Improve performance by not calculating the total number of hits
- // matching the query.
- track_total_hits: false,
- // Reduce the response payload size by only returning the data we care about
- filter_path: [
- 'hits.hits._id',
- 'hits.hits._source',
- 'hits.hits._seq_no',
- 'hits.hits._primary_term',
- ],
- })
- .then((res) =>
- Either.right({ outdatedDocuments: (res.body.hits?.hits as SavedObjectsRawDoc[]) ?? [] })
- )
- .catch(catchRetryableEsClientErrors);
-};
+export const searchForOutdatedDocuments =
+ (
+ client: ElasticsearchClient,
+ options: SearchForOutdatedDocumentsOptions
+ ): TaskEither.TaskEither =>
+ () => {
+ return client
+ .search({
+ index: options.targetIndex,
+ // Return the _seq_no and _primary_term so we can use optimistic
+ // concurrency control for updates
+ seq_no_primary_term: true,
+ size: options.batchSize,
+ body: {
+ query: options.outdatedDocumentsQuery,
+ // Optimize search performance by sorting by the "natural" index order
+ sort: ['_doc'],
+ },
+ // Return an error when targeting missing or closed indices
+ allow_no_indices: false,
+ // Don't return partial results if timeouts or shard failures are
+ // encountered. This is important because 0 search hits is interpreted as
+ // there being no more outdated documents left that require
+ // transformation. Although the default is `false`, we set this
+ // explicitly to avoid users overriding the
+ // search.default_allow_partial_results cluster setting to true.
+ allow_partial_search_results: false,
+ // Improve performance by not calculating the total number of hits
+ // matching the query.
+ track_total_hits: false,
+ // Reduce the response payload size by only returning the data we care about
+ filter_path: [
+ 'hits.hits._id',
+ 'hits.hits._source',
+ 'hits.hits._seq_no',
+ 'hits.hits._primary_term',
+ ],
+ })
+ .then((res) =>
+ Either.right({ outdatedDocuments: (res.body.hits?.hits as SavedObjectsRawDoc[]) ?? [] })
+ )
+ .catch(catchRetryableEsClientErrors);
+ };
diff --git a/src/core/server/saved_objects/migrationsv2/actions/set_write_block.ts b/src/core/server/saved_objects/migrationsv2/actions/set_write_block.ts
index 5aed316306cf9..db519d0246511 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/set_write_block.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/set_write_block.ts
@@ -31,43 +31,45 @@ export interface SetWriteBlockParams {
* include `shards_acknowledged: true` but once the block is in place,
* subsequent calls return `shards_acknowledged: false`
*/
-export const setWriteBlock = ({
- client,
- index,
-}: SetWriteBlockParams): TaskEither.TaskEither<
- IndexNotFound | RetryableEsClientError,
- 'set_write_block_succeeded'
-> => () => {
- return (
- client.indices
- .addBlock<{
- acknowledged: boolean;
- shards_acknowledged: boolean;
- }>(
- {
- index,
- block: 'write',
- },
- { maxRetries: 0 /** handle retry ourselves for now */ }
- )
- // not typed yet
- .then((res: any) => {
- return res.body.acknowledged === true
- ? Either.right('set_write_block_succeeded' as const)
- : Either.left({
- type: 'retryable_es_client_error' as const,
- message: 'set_write_block_failed',
- });
- })
- .catch((e: ElasticsearchClientError) => {
- if (e instanceof EsErrors.ResponseError) {
- if (e.body?.error?.type === 'index_not_found_exception') {
- return Either.left({ type: 'index_not_found_exception' as const, index });
+export const setWriteBlock =
+ ({
+ client,
+ index,
+ }: SetWriteBlockParams): TaskEither.TaskEither<
+ IndexNotFound | RetryableEsClientError,
+ 'set_write_block_succeeded'
+ > =>
+ () => {
+ return (
+ client.indices
+ .addBlock<{
+ acknowledged: boolean;
+ shards_acknowledged: boolean;
+ }>(
+ {
+ index,
+ block: 'write',
+ },
+ { maxRetries: 0 /** handle retry ourselves for now */ }
+ )
+ // not typed yet
+ .then((res: any) => {
+ return res.body.acknowledged === true
+ ? Either.right('set_write_block_succeeded' as const)
+ : Either.left({
+ type: 'retryable_es_client_error' as const,
+ message: 'set_write_block_failed',
+ });
+ })
+ .catch((e: ElasticsearchClientError) => {
+ if (e instanceof EsErrors.ResponseError) {
+ if (e.body?.error?.type === 'index_not_found_exception') {
+ return Either.left({ type: 'index_not_found_exception' as const, index });
+ }
}
- }
- throw e;
- })
- .catch(catchRetryableEsClientErrors)
- );
-};
+ throw e;
+ })
+ .catch(catchRetryableEsClientErrors)
+ );
+ };
//
diff --git a/src/core/server/saved_objects/migrationsv2/actions/update_aliases.ts b/src/core/server/saved_objects/migrationsv2/actions/update_aliases.ts
index ffb8002f09212..5f1903f010a41 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/update_aliases.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/update_aliases.ts
@@ -39,60 +39,62 @@ export interface UpdateAliasesParams {
/**
* Calls the Update index alias API `_alias` with the provided alias actions.
*/
-export const updateAliases = ({
- client,
- aliasActions,
-}: UpdateAliasesParams): TaskEither.TaskEither<
- IndexNotFound | AliasNotFound | RemoveIndexNotAConcreteIndex | RetryableEsClientError,
- 'update_aliases_succeeded'
-> => () => {
- return client.indices
- .updateAliases(
- {
- body: {
- actions: aliasActions,
+export const updateAliases =
+ ({
+ client,
+ aliasActions,
+ }: UpdateAliasesParams): TaskEither.TaskEither<
+ IndexNotFound | AliasNotFound | RemoveIndexNotAConcreteIndex | RetryableEsClientError,
+ 'update_aliases_succeeded'
+ > =>
+ () => {
+ return client.indices
+ .updateAliases(
+ {
+ body: {
+ actions: aliasActions,
+ },
},
- },
- { maxRetries: 0 }
- )
- .then(() => {
- // Ignore `acknowledged: false`. When the coordinating node accepts
- // the new cluster state update but not all nodes have applied the
- // update within the timeout `acknowledged` will be false. However,
- // retrying this update will always immediately result in `acknowledged:
- // true` even if there are still nodes which are falling behind with
- // cluster state updates.
- // The only impact for using `updateAliases` to mark the version index
- // as ready is that it could take longer for other Kibana instances to
- // see that the version index is ready so they are more likely to
- // perform unecessary duplicate work.
- return Either.right('update_aliases_succeeded' as const);
- })
- .catch((err: EsErrors.ElasticsearchClientError) => {
- if (err instanceof EsErrors.ResponseError) {
- if (err?.body?.error?.type === 'index_not_found_exception') {
- return Either.left({
- type: 'index_not_found_exception' as const,
- index: err.body.error.index,
- });
- } else if (
- err?.body?.error?.type === 'illegal_argument_exception' &&
- err?.body?.error?.reason?.match(
- /The provided expression \[.+\] matches an alias, specify the corresponding concrete indices instead./
- )
- ) {
- return Either.left({ type: 'remove_index_not_a_concrete_index' as const });
- } else if (
- err?.body?.error?.type === 'aliases_not_found_exception' ||
- (err?.body?.error?.type === 'resource_not_found_exception' &&
- err?.body?.error?.reason?.match(/required alias \[.+\] does not exist/))
- ) {
- return Either.left({
- type: 'alias_not_found_exception' as const,
- });
+ { maxRetries: 0 }
+ )
+ .then(() => {
+ // Ignore `acknowledged: false`. When the coordinating node accepts
+ // the new cluster state update but not all nodes have applied the
+ // update within the timeout `acknowledged` will be false. However,
+ // retrying this update will always immediately result in `acknowledged:
+ // true` even if there are still nodes which are falling behind with
+ // cluster state updates.
+ // The only impact for using `updateAliases` to mark the version index
+ // as ready is that it could take longer for other Kibana instances to
+ // see that the version index is ready so they are more likely to
+ // perform unecessary duplicate work.
+ return Either.right('update_aliases_succeeded' as const);
+ })
+ .catch((err: EsErrors.ElasticsearchClientError) => {
+ if (err instanceof EsErrors.ResponseError) {
+ if (err?.body?.error?.type === 'index_not_found_exception') {
+ return Either.left({
+ type: 'index_not_found_exception' as const,
+ index: err.body.error.index,
+ });
+ } else if (
+ err?.body?.error?.type === 'illegal_argument_exception' &&
+ err?.body?.error?.reason?.match(
+ /The provided expression \[.+\] matches an alias, specify the corresponding concrete indices instead./
+ )
+ ) {
+ return Either.left({ type: 'remove_index_not_a_concrete_index' as const });
+ } else if (
+ err?.body?.error?.type === 'aliases_not_found_exception' ||
+ (err?.body?.error?.type === 'resource_not_found_exception' &&
+ err?.body?.error?.reason?.match(/required alias \[.+\] does not exist/))
+ ) {
+ return Either.left({
+ type: 'alias_not_found_exception' as const,
+ });
+ }
}
- }
- throw err;
- })
- .catch(catchRetryableEsClientErrors);
-};
+ throw err;
+ })
+ .catch(catchRetryableEsClientErrors);
+ };
diff --git a/src/core/server/saved_objects/migrationsv2/actions/update_and_pickup_mappings.ts b/src/core/server/saved_objects/migrationsv2/actions/update_and_pickup_mappings.ts
index 8c742005a01ce..52065ba60cb84 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/update_and_pickup_mappings.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/update_and_pickup_mappings.ts
@@ -41,35 +41,33 @@ export const updateAndPickupMappings = ({
RetryableEsClientError,
UpdateAndPickupMappingsResponse
> => {
- const putMappingTask: TaskEither.TaskEither<
- RetryableEsClientError,
- 'update_mappings_succeeded'
- > = () => {
- return client.indices
- .putMapping({
- index,
- timeout: DEFAULT_TIMEOUT,
- body: mappings,
- })
- .then((res) => {
- // Ignore `acknowledged: false`. When the coordinating node accepts
- // the new cluster state update but not all nodes have applied the
- // update within the timeout `acknowledged` will be false. However,
- // retrying this update will always immediately result in `acknowledged:
- // true` even if there are still nodes which are falling behind with
- // cluster state updates.
- // For updateAndPickupMappings this means that there is the potential
- // that some existing document's fields won't be picked up if the node
- // on which the Kibana shard is running has fallen behind with cluster
- // state updates and the mapping update wasn't applied before we run
- // `pickupUpdatedMappings`. ES tries to limit this risk by blocking
- // index operations (including update_by_query used by
- // updateAndPickupMappings) if there are pending mappings changes. But
- // not all mapping changes will prevent this.
- return Either.right('update_mappings_succeeded' as const);
- })
- .catch(catchRetryableEsClientErrors);
- };
+ const putMappingTask: TaskEither.TaskEither =
+ () => {
+ return client.indices
+ .putMapping({
+ index,
+ timeout: DEFAULT_TIMEOUT,
+ body: mappings,
+ })
+ .then((res) => {
+ // Ignore `acknowledged: false`. When the coordinating node accepts
+ // the new cluster state update but not all nodes have applied the
+ // update within the timeout `acknowledged` will be false. However,
+ // retrying this update will always immediately result in `acknowledged:
+ // true` even if there are still nodes which are falling behind with
+ // cluster state updates.
+ // For updateAndPickupMappings this means that there is the potential
+ // that some existing document's fields won't be picked up if the node
+ // on which the Kibana shard is running has fallen behind with cluster
+ // state updates and the mapping update wasn't applied before we run
+ // `pickupUpdatedMappings`. ES tries to limit this risk by blocking
+ // index operations (including update_by_query used by
+ // updateAndPickupMappings) if there are pending mappings changes. But
+ // not all mapping changes will prevent this.
+ return Either.right('update_mappings_succeeded' as const);
+ })
+ .catch(catchRetryableEsClientErrors);
+ };
return pipe(
putMappingTask,
diff --git a/src/core/server/saved_objects/migrationsv2/actions/verify_reindex.ts b/src/core/server/saved_objects/migrationsv2/actions/verify_reindex.ts
index 4db599d8fbadf..a344bf5a97ff3 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/verify_reindex.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/verify_reindex.ts
@@ -21,32 +21,34 @@ export interface VerifyReindexParams {
targetIndex: string;
}
-export const verifyReindex = ({
- client,
- sourceIndex,
- targetIndex,
-}: VerifyReindexParams): TaskEither.TaskEither<
- RetryableEsClientError | { type: 'verify_reindex_failed' },
- 'verify_reindex_succeeded'
-> => () => {
- const count = (index: string) =>
- client
- .count<{ count: number }>({
- index,
- // Return an error when targeting missing or closed indices
- allow_no_indices: false,
- })
- .then((res) => {
- return res.body.count;
- });
+export const verifyReindex =
+ ({
+ client,
+ sourceIndex,
+ targetIndex,
+ }: VerifyReindexParams): TaskEither.TaskEither<
+ RetryableEsClientError | { type: 'verify_reindex_failed' },
+ 'verify_reindex_succeeded'
+ > =>
+ () => {
+ const count = (index: string) =>
+ client
+ .count<{ count: number }>({
+ index,
+ // Return an error when targeting missing or closed indices
+ allow_no_indices: false,
+ })
+ .then((res) => {
+ return res.body.count;
+ });
- return Promise.all([count(sourceIndex), count(targetIndex)])
- .then(([sourceCount, targetCount]) => {
- if (targetCount >= sourceCount) {
- return Either.right('verify_reindex_succeeded' as const);
- } else {
- return Either.left({ type: 'verify_reindex_failed' as const });
- }
- })
- .catch(catchRetryableEsClientErrors);
-};
+ return Promise.all([count(sourceIndex), count(targetIndex)])
+ .then(([sourceCount, targetCount]) => {
+ if (targetCount >= sourceCount) {
+ return Either.right('verify_reindex_succeeded' as const);
+ } else {
+ return Either.left({ type: 'verify_reindex_failed' as const });
+ }
+ })
+ .catch(catchRetryableEsClientErrors);
+ };
diff --git a/src/core/server/saved_objects/migrationsv2/actions/wait_for_index_status_yellow.ts b/src/core/server/saved_objects/migrationsv2/actions/wait_for_index_status_yellow.ts
index 57e49b8d51cd0..2880dfaff0d48 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/wait_for_index_status_yellow.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/wait_for_index_status_yellow.ts
@@ -32,15 +32,17 @@ export interface WaitForIndexStatusYellowParams {
* yellow at any point in the future. So ultimately data-redundancy is up to
* users to maintain.
*/
-export const waitForIndexStatusYellow = ({
- client,
- index,
- timeout = DEFAULT_TIMEOUT,
-}: WaitForIndexStatusYellowParams): TaskEither.TaskEither => () => {
- return client.cluster
- .health({ index, wait_for_status: 'yellow', timeout })
- .then(() => {
- return Either.right({});
- })
- .catch(catchRetryableEsClientErrors);
-};
+export const waitForIndexStatusYellow =
+ ({
+ client,
+ index,
+ timeout = DEFAULT_TIMEOUT,
+ }: WaitForIndexStatusYellowParams): TaskEither.TaskEither =>
+ () => {
+ return client.cluster
+ .health({ index, wait_for_status: 'yellow', timeout })
+ .then(() => {
+ return Either.right({});
+ })
+ .catch(catchRetryableEsClientErrors);
+ };
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 0cdaa88c535ab..af0ed3613bd6b 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
@@ -65,30 +65,32 @@ export interface WaitForTaskParams {
*
* TODO: delete completed tasks
*/
-export const waitForTask = ({
- client,
- taskId,
- timeout,
-}: WaitForTaskParams): TaskEither.TaskEither<
- RetryableEsClientError | WaitForTaskCompletionTimeout,
- WaitForTaskResponse
-> => () => {
- return client.tasks
- .get({
- task_id: taskId,
- wait_for_completion: true,
- timeout,
- })
- .then((res) => {
- const body = res.body;
- const failures = body.response?.failures ?? [];
- return Either.right({
- completed: body.completed,
- error: Option.fromNullable(body.error),
- failures: failures.length > 0 ? Option.some(failures) : Option.none,
- description: body.task.description,
- });
- })
- .catch(catchWaitForTaskCompletionTimeout)
- .catch(catchRetryableEsClientErrors);
-};
+export const waitForTask =
+ ({
+ client,
+ taskId,
+ timeout,
+ }: WaitForTaskParams): TaskEither.TaskEither<
+ RetryableEsClientError | WaitForTaskCompletionTimeout,
+ WaitForTaskResponse
+ > =>
+ () => {
+ return client.tasks
+ .get({
+ task_id: taskId,
+ wait_for_completion: true,
+ timeout,
+ })
+ .then((res) => {
+ const body = res.body;
+ const failures = body.response?.failures ?? [];
+ return Either.right({
+ completed: body.completed,
+ error: Option.fromNullable(body.error),
+ failures: failures.length > 0 ? Option.some(failures) : Option.none,
+ description: body.task.description,
+ });
+ })
+ .catch(catchWaitForTaskCompletionTimeout)
+ .catch(catchRetryableEsClientErrors);
+ };
diff --git a/src/core/server/saved_objects/migrationsv2/initial_state.test.ts b/src/core/server/saved_objects/migrationsv2/initial_state.test.ts
index 26ba129cbeab4..601eb7cf1ce36 100644
--- a/src/core/server/saved_objects/migrationsv2/initial_state.test.ts
+++ b/src/core/server/saved_objects/migrationsv2/initial_state.test.ts
@@ -19,11 +19,11 @@ describe('createInitialState', () => {
typeRegistry = new SavedObjectTypeRegistry();
});
- const migrationsConfig = ({
+ const migrationsConfig = {
retryAttempts: 15,
batchSize: 1000,
maxBatchSizeBytes: ByteSizeValue.parse('100mb'),
- } as unknown) as SavedObjectsMigrationConfigType;
+ } as unknown as SavedObjectsMigrationConfigType;
it('creates the initial state for the model based on the passed in parameters', () => {
expect(
createInitialState({
diff --git a/src/core/server/saved_objects/migrationsv2/model/model.test.ts b/src/core/server/saved_objects/migrationsv2/model/model.test.ts
index 1d017116bf3fd..033a18b488841 100644
--- a/src/core/server/saved_objects/migrationsv2/model/model.test.ts
+++ b/src/core/server/saved_objects/migrationsv2/model/model.test.ts
@@ -556,9 +556,8 @@ describe('migrations v2 model', () => {
legacyIndex: '',
};
test('LEGACY_CREATE_REINDEX_TARGET -> LEGACY_REINDEX', () => {
- const res: ResponseType<'LEGACY_CREATE_REINDEX_TARGET'> = Either.right(
- 'create_index_succeeded'
- );
+ const res: ResponseType<'LEGACY_CREATE_REINDEX_TARGET'> =
+ Either.right('create_index_succeeded');
const newState = model(legacyCreateReindexTargetState, res);
expect(newState.controlState).toEqual('LEGACY_REINDEX');
expect(newState.retryCount).toEqual(0);
@@ -1143,9 +1142,8 @@ describe('migrations v2 model', () => {
progress: createInitialProgress(),
};
test('REINDEX_SOURCE_TO_TEMP_INDEX_BULK -> REINDEX_SOURCE_TO_TEMP_READ if action succeeded', () => {
- const res: ResponseType<'REINDEX_SOURCE_TO_TEMP_INDEX_BULK'> = Either.right(
- 'bulk_index_succeeded'
- );
+ const res: ResponseType<'REINDEX_SOURCE_TO_TEMP_INDEX_BULK'> =
+ Either.right('bulk_index_succeeded');
const newState = model(reindexSourceToTempIndexBulkState, res);
expect(newState.controlState).toEqual('REINDEX_SOURCE_TO_TEMP_READ');
expect(newState.retryCount).toEqual(0);
@@ -1563,9 +1561,8 @@ describe('migrations v2 model', () => {
};
test('TRANSFORMED_DOCUMENTS_BULK_INDEX -> TRANSFORMED_DOCUMENTS_BULK_INDEX and increments currentBatch if more batches are left', () => {
- const res: ResponseType<'TRANSFORMED_DOCUMENTS_BULK_INDEX'> = Either.right(
- 'bulk_index_succeeded'
- );
+ const res: ResponseType<'TRANSFORMED_DOCUMENTS_BULK_INDEX'> =
+ Either.right('bulk_index_succeeded');
const newState = model(
transformedDocumentsBulkIndexState,
res
@@ -1575,9 +1572,8 @@ describe('migrations v2 model', () => {
});
test('TRANSFORMED_DOCUMENTS_BULK_INDEX -> OUTDATED_DOCUMENTS_SEARCH_READ if all batches were written', () => {
- const res: ResponseType<'TRANSFORMED_DOCUMENTS_BULK_INDEX'> = Either.right(
- 'bulk_index_succeeded'
- );
+ const res: ResponseType<'TRANSFORMED_DOCUMENTS_BULK_INDEX'> =
+ Either.right('bulk_index_succeeded');
const newState = model(
{ ...transformedDocumentsBulkIndexState, ...{ currentBatch: 1 } },
res
diff --git a/src/core/server/saved_objects/routes/create.ts b/src/core/server/saved_objects/routes/create.ts
index 0e321aa7031f2..3e287e91fec80 100644
--- a/src/core/server/saved_objects/routes/create.ts
+++ b/src/core/server/saved_objects/routes/create.ts
@@ -47,13 +47,8 @@ export const registerCreateRoute = (router: IRouter, { coreUsageData }: RouteDep
catchAndReturnBoomErrors(async (context, req, res) => {
const { type, id } = req.params;
const { overwrite } = req.query;
- const {
- attributes,
- migrationVersion,
- coreMigrationVersion,
- references,
- initialNamespaces,
- } = req.body;
+ const { attributes, migrationVersion, coreMigrationVersion, references, initialNamespaces } =
+ req.body;
const usageStatsClient = coreUsageData.getClient();
usageStatsClient.incrementSavedObjectsCreate({ request: req }).catch(() => {});
diff --git a/src/core/server/saved_objects/routes/utils.test.ts b/src/core/server/saved_objects/routes/utils.test.ts
index 2127352e4c60e..51dd5d0918fd4 100644
--- a/src/core/server/saved_objects/routes/utils.test.ts
+++ b/src/core/server/saved_objects/routes/utils.test.ts
@@ -174,9 +174,11 @@ describe('catchAndReturnBoomErrors', () => {
let request: KibanaRequest;
let response: KibanaResponseFactory;
- const createHandler = (handler: () => any): RequestHandler => () => {
- return handler();
- };
+ const createHandler =
+ (handler: () => any): RequestHandler =>
+ () => {
+ return handler();
+ };
beforeEach(() => {
context = {} as any;
diff --git a/src/core/server/saved_objects/saved_objects_config.ts b/src/core/server/saved_objects/saved_objects_config.ts
index e7bbd706762f5..0c27f170f590b 100644
--- a/src/core/server/saved_objects/saved_objects_config.ts
+++ b/src/core/server/saved_objects/saved_objects_config.ts
@@ -39,11 +39,12 @@ const migrationDeprecations: ConfigDeprecationProvider = () => [
},
];
-export const savedObjectsMigrationConfig: ServiceConfigDescriptor = {
- path: 'migrations',
- schema: migrationSchema,
- deprecations: migrationDeprecations,
-};
+export const savedObjectsMigrationConfig: ServiceConfigDescriptor =
+ {
+ path: 'migrations',
+ schema: migrationSchema,
+ deprecations: migrationDeprecations,
+ };
const soSchema = schema.object({
maxImportPayloadBytes: schema.byteSize({ defaultValue: 26_214_400 }),
diff --git a/src/core/server/saved_objects/saved_objects_service.mock.ts b/src/core/server/saved_objects/saved_objects_service.mock.ts
index b26e9ff4db00e..cd7310e226f63 100644
--- a/src/core/server/saved_objects/saved_objects_service.mock.ts
+++ b/src/core/server/saved_objects/saved_objects_service.mock.ts
@@ -49,9 +49,8 @@ const createStartContractMock = (typeRegistry?: jest.Mocked) => {
- const internalStartContract: jest.Mocked = createStartContractMock(
- typeRegistry
- );
+ const internalStartContract: jest.Mocked =
+ createStartContractMock(typeRegistry);
return internalStartContract;
};
diff --git a/src/core/server/saved_objects/saved_objects_service.test.ts b/src/core/server/saved_objects/saved_objects_service.test.ts
index 6477d1a3dfbeb..1d860d2c5a695 100644
--- a/src/core/server/saved_objects/saved_objects_service.test.ts
+++ b/src/core/server/saved_objects/saved_objects_service.test.ts
@@ -97,7 +97,8 @@ describe('SavedObjectsService', () => {
deprecationsSetup.getRegistry.mockReturnValue(mockRegistry);
const deprecations = Symbol('deprecations');
- const mockedGetSavedObjectsDeprecationsProvider = getSavedObjectsDeprecationsProvider as jest.Mock;
+ const mockedGetSavedObjectsDeprecationsProvider =
+ getSavedObjectsDeprecationsProvider as jest.Mock;
mockedGetSavedObjectsDeprecationsProvider.mockReturnValue(deprecations);
await soService.setup(createSetupDeps());
@@ -233,8 +234,10 @@ describe('SavedObjectsService', () => {
await soService.setup(setupDeps);
soService.start(createStartDeps());
expect(migratorInstanceMock.runMigrations).toHaveBeenCalledTimes(0);
- ((setupDeps.elasticsearch
- .esNodesCompatibility$ as any) as BehaviorSubject).next({
+ (
+ setupDeps.elasticsearch
+ .esNodesCompatibility$ as any as BehaviorSubject
+ ).next({
isCompatible: true,
incompatibleNodes: [],
warningNodes: [],
@@ -311,9 +314,9 @@ describe('SavedObjectsService', () => {
expect(coreStart.elasticsearch.client.asScoped).toHaveBeenCalledWith(req);
- const [
- [, , , , , includedHiddenTypes],
- ] = (SavedObjectsRepository.createRepository as jest.Mocked).mock.calls;
+ const [[, , , , , includedHiddenTypes]] = (
+ SavedObjectsRepository.createRepository as jest.Mocked
+ ).mock.calls;
expect(includedHiddenTypes).toEqual([]);
});
@@ -329,9 +332,9 @@ describe('SavedObjectsService', () => {
const req = httpServerMock.createKibanaRequest();
createScopedRepository(req, ['someHiddenType']);
- const [
- [, , , , , includedHiddenTypes],
- ] = (SavedObjectsRepository.createRepository as jest.Mocked).mock.calls;
+ const [[, , , , , includedHiddenTypes]] = (
+ SavedObjectsRepository.createRepository as jest.Mocked
+ ).mock.calls;
expect(includedHiddenTypes).toEqual(['someHiddenType']);
});
@@ -348,9 +351,9 @@ describe('SavedObjectsService', () => {
createInternalRepository();
- const [
- [, , , client, , includedHiddenTypes],
- ] = (SavedObjectsRepository.createRepository as jest.Mocked).mock.calls;
+ const [[, , , client, , includedHiddenTypes]] = (
+ SavedObjectsRepository.createRepository as jest.Mocked
+ ).mock.calls;
expect(coreStart.elasticsearch.client.asInternalUser).toBe(client);
expect(includedHiddenTypes).toEqual([]);
@@ -365,9 +368,9 @@ describe('SavedObjectsService', () => {
createInternalRepository(['someHiddenType']);
- const [
- [, , , , , includedHiddenTypes],
- ] = (SavedObjectsRepository.createRepository as jest.Mocked).mock.calls;
+ const [[, , , , , includedHiddenTypes]] = (
+ SavedObjectsRepository.createRepository as jest.Mocked
+ ).mock.calls;
expect(includedHiddenTypes).toEqual(['someHiddenType']);
});
diff --git a/src/core/server/saved_objects/saved_objects_service.ts b/src/core/server/saved_objects/saved_objects_service.ts
index ee56744249c5b..534718bd683b8 100644
--- a/src/core/server/saved_objects/saved_objects_service.ts
+++ b/src/core/server/saved_objects/saved_objects_service.ts
@@ -269,7 +269,8 @@ export interface SavedObjectsStartDeps {
}
export class SavedObjectsService
- implements CoreService