[7.x][DX] Upgrade prettier to v2.4.0 (#112359) (#112524)

Signed-off-by: Tyler Smalley <tyler.smalley@elastic.co>
This commit is contained in:
Tyler Smalley 2021-09-19 22:34:46 -07:00 committed by GitHub
parent 039a0d4ed7
commit c16480e849
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2933 changed files with 28726 additions and 30633 deletions

View file

@ -27,7 +27,6 @@ async function getDeprecations({ esClient, savedObjectsClient }: GetDeprecations
const deprecations: DeprecationsDetails[] = [];
const count = await getFooCount(savedObjectsClient);
if (count > 0) {
// Example of a manual correctiveAction
deprecations.push({
title: i18n.translate('xpack.foo.deprecations.title', {
defaultMessage: `Foo's are deprecated`

View file

@ -19,7 +19,7 @@ export interface OpsMetrics
| [collected\_at](./kibana-plugin-core-server.opsmetrics.collected_at.md) | <code>Date</code> | Time metrics were recorded at. |
| [concurrent\_connections](./kibana-plugin-core-server.opsmetrics.concurrent_connections.md) | <code>OpsServerMetrics['concurrent_connections']</code> | number of current concurrent connections to the server |
| [os](./kibana-plugin-core-server.opsmetrics.os.md) | <code>OpsOsMetrics</code> | OS related metrics |
| [process](./kibana-plugin-core-server.opsmetrics.process.md) | <code>OpsProcessMetrics</code> | Process related metrics. Deprecated in favor of processes field. |
| [process](./kibana-plugin-core-server.opsmetrics.process.md) | <code>OpsProcessMetrics</code> | Process related metrics. |
| [processes](./kibana-plugin-core-server.opsmetrics.processes.md) | <code>OpsProcessMetrics[]</code> | Process related metrics. Reports an array of objects for each kibana pid. |
| [requests](./kibana-plugin-core-server.opsmetrics.requests.md) | <code>OpsServerMetrics['requests']</code> | server requests stats |
| [response\_times](./kibana-plugin-core-server.opsmetrics.response_times.md) | <code>OpsServerMetrics['response_times']</code> | server response time stats |

View file

@ -6,9 +6,10 @@
> Warning: This API is now obsolete.
>
> use the processes field instead.
>
Process related metrics. Deprecated in favor of processes field.
Process related metrics.
<b>Signature:</b>

View file

@ -20,17 +20,16 @@ export interface BfetchDeps {
explorer: ExplorerService;
}
export const mount = (
coreSetup: CoreSetup<BfetchExplorerStartPlugins>,
explorer: ExplorerService
) => async ({ appBasePath, element }: AppMountParameters) => {
const [core, plugins] = await coreSetup.getStartServices();
const deps: BfetchDeps = { appBasePath, core, plugins, explorer };
const reactElement = (
<KibanaContextProvider services={deps}>
<App />
</KibanaContextProvider>
);
render(reactElement, element);
return () => unmountComponentAtNode(element);
};
export const mount =
(coreSetup: CoreSetup<BfetchExplorerStartPlugins>, explorer: ExplorerService) =>
async ({ appBasePath, element }: AppMountParameters) => {
const [core, plugins] = await coreSetup.getStartServices();
const deps: BfetchDeps = { appBasePath, core, plugins, explorer };
const reactElement = (
<KibanaContextProvider services={deps}>
<App />
</KibanaContextProvider>
);
render(reactElement, element);
return () => unmountComponentAtNode(element);
};

View file

@ -33,7 +33,8 @@ export class DashboardEmbeddableExamples implements Plugin<void, void, {}, Start
return renderApp(
{
basename: params.appBasePath,
DashboardContainerByValueRenderer: depsStart.dashboard.getDashboardContainerByValueRenderer(),
DashboardContainerByValueRenderer:
depsStart.dashboard.getDashboardContainerByValueRenderer(),
},
params.element
);

View file

@ -52,7 +52,8 @@ function getHasMatch(search?: string, savedAttributes?: BookSavedObjectAttribute
export class BookEmbeddable
extends Embeddable<BookEmbeddableInput, BookEmbeddableOutput>
implements ReferenceOrValueEmbeddable<BookByValueInput, BookByReferenceInput> {
implements ReferenceOrValueEmbeddable<BookByValueInput, BookByReferenceInput>
{
public readonly type = BOOK_EMBEDDABLE;
private subscription: Subscription;
private node?: HTMLElement;

View file

@ -52,7 +52,8 @@ export class BookEmbeddableFactoryDefinition
BookEmbeddableOutput,
BookEmbeddable,
BookSavedObjectAttributes
> {
>
{
public readonly type = BOOK_EMBEDDABLE;
public savedObjectMetaData = {
name: 'Book',
@ -116,10 +117,8 @@ export class BookEmbeddableFactoryDefinition
private async unwrapMethod(savedObjectId: string): Promise<BookSavedObjectAttributes> {
const { savedObjectsClient } = await this.getStartServices();
const savedObject: SimpleSavedObject<BookSavedObjectAttributes> = await savedObjectsClient.get<BookSavedObjectAttributes>(
this.type,
savedObjectId
);
const savedObject: SimpleSavedObject<BookSavedObjectAttributes> =
await savedObjectsClient.get<BookSavedObjectAttributes>(this.type, savedObjectId);
return { ...savedObject.attributes };
}

View file

@ -22,7 +22,8 @@ interface StartServices {
export type ListContainerFactory = EmbeddableFactory<ContainerInput, ContainerOutput>;
export class ListContainerFactoryDefinition
implements EmbeddableFactoryDefinition<ContainerInput, ContainerOutput> {
implements EmbeddableFactoryDefinition<ContainerInput, ContainerOutput>
{
public readonly type = LIST_CONTAINER;
public readonly isContainerType = true;

View file

@ -26,7 +26,8 @@ export type SimpleEmbeddableInput = EmbeddableInput & {
export type SimpleEmbeddableFactory = EmbeddableFactory;
export class SimpleEmbeddableFactoryDefinition
implements EmbeddableFactoryDefinition<SimpleEmbeddableInput> {
implements EmbeddableFactoryDefinition<SimpleEmbeddableInput>
{
public readonly type = SIMPLE_EMBEDDABLE;
// we need to provide migration function every time we change the interface of our state

View file

@ -27,7 +27,8 @@ export type MultiTaskTodoEmbeddableFactory = EmbeddableFactory<
export class MultiTaskTodoEmbeddableFactoryDefinition
implements
EmbeddableFactoryDefinition<MultiTaskTodoInput, MultiTaskTodoOutput, MultiTaskTodoEmbeddable> {
EmbeddableFactoryDefinition<MultiTaskTodoInput, MultiTaskTodoOutput, MultiTaskTodoEmbeddable>
{
public readonly type = MULTI_TASK_TODO_EMBEDDABLE;
public async isEditable() {

View file

@ -88,65 +88,74 @@ export class EmbeddableExamplesPlugin
EmbeddableExamplesStart,
EmbeddableExamplesSetupDependencies,
EmbeddableExamplesStartDependencies
> {
>
{
private exampleEmbeddableFactories: Partial<ExampleEmbeddableFactories> = {};
public setup(
core: CoreSetup<EmbeddableExamplesStartDependencies>,
deps: EmbeddableExamplesSetupDependencies
) {
this.exampleEmbeddableFactories.getHelloWorldEmbeddableFactory = deps.embeddable.registerEmbeddableFactory(
HELLO_WORLD_EMBEDDABLE,
new HelloWorldEmbeddableFactoryDefinition()
);
this.exampleEmbeddableFactories.getHelloWorldEmbeddableFactory =
deps.embeddable.registerEmbeddableFactory(
HELLO_WORLD_EMBEDDABLE,
new HelloWorldEmbeddableFactoryDefinition()
);
this.exampleEmbeddableFactories.getMigrationsEmbeddableFactory = deps.embeddable.registerEmbeddableFactory(
SIMPLE_EMBEDDABLE,
new SimpleEmbeddableFactoryDefinition()
);
this.exampleEmbeddableFactories.getMigrationsEmbeddableFactory =
deps.embeddable.registerEmbeddableFactory(
SIMPLE_EMBEDDABLE,
new SimpleEmbeddableFactoryDefinition()
);
this.exampleEmbeddableFactories.getMultiTaskTodoEmbeddableFactory = deps.embeddable.registerEmbeddableFactory(
MULTI_TASK_TODO_EMBEDDABLE,
new MultiTaskTodoEmbeddableFactoryDefinition()
);
this.exampleEmbeddableFactories.getMultiTaskTodoEmbeddableFactory =
deps.embeddable.registerEmbeddableFactory(
MULTI_TASK_TODO_EMBEDDABLE,
new MultiTaskTodoEmbeddableFactoryDefinition()
);
this.exampleEmbeddableFactories.getSearchableListContainerEmbeddableFactory = deps.embeddable.registerEmbeddableFactory(
SEARCHABLE_LIST_CONTAINER,
new SearchableListContainerFactoryDefinition(async () => ({
embeddableServices: (await core.getStartServices())[1].embeddable,
}))
);
this.exampleEmbeddableFactories.getSearchableListContainerEmbeddableFactory =
deps.embeddable.registerEmbeddableFactory(
SEARCHABLE_LIST_CONTAINER,
new SearchableListContainerFactoryDefinition(async () => ({
embeddableServices: (await core.getStartServices())[1].embeddable,
}))
);
this.exampleEmbeddableFactories.getListContainerEmbeddableFactory = deps.embeddable.registerEmbeddableFactory(
LIST_CONTAINER,
new ListContainerFactoryDefinition(async () => ({
embeddableServices: (await core.getStartServices())[1].embeddable,
}))
);
this.exampleEmbeddableFactories.getListContainerEmbeddableFactory =
deps.embeddable.registerEmbeddableFactory(
LIST_CONTAINER,
new ListContainerFactoryDefinition(async () => ({
embeddableServices: (await core.getStartServices())[1].embeddable,
}))
);
this.exampleEmbeddableFactories.getTodoEmbeddableFactory = deps.embeddable.registerEmbeddableFactory(
TODO_EMBEDDABLE,
new TodoEmbeddableFactoryDefinition(async () => ({
openModal: (await core.getStartServices())[0].overlays.openModal,
}))
);
this.exampleEmbeddableFactories.getTodoEmbeddableFactory =
deps.embeddable.registerEmbeddableFactory(
TODO_EMBEDDABLE,
new TodoEmbeddableFactoryDefinition(async () => ({
openModal: (await core.getStartServices())[0].overlays.openModal,
}))
);
this.exampleEmbeddableFactories.getTodoRefEmbeddableFactory = deps.embeddable.registerEmbeddableFactory(
TODO_REF_EMBEDDABLE,
new TodoRefEmbeddableFactoryDefinition(async () => ({
savedObjectsClient: (await core.getStartServices())[0].savedObjects.client,
getEmbeddableFactory: (await core.getStartServices())[1].embeddable.getEmbeddableFactory,
}))
);
this.exampleEmbeddableFactories.getBookEmbeddableFactory = deps.embeddable.registerEmbeddableFactory(
BOOK_EMBEDDABLE,
new BookEmbeddableFactoryDefinition(async () => ({
getAttributeService: (await core.getStartServices())[1].embeddable.getAttributeService,
openModal: (await core.getStartServices())[0].overlays.openModal,
savedObjectsClient: (await core.getStartServices())[0].savedObjects.client,
overlays: (await core.getStartServices())[0].overlays,
}))
);
this.exampleEmbeddableFactories.getTodoRefEmbeddableFactory =
deps.embeddable.registerEmbeddableFactory(
TODO_REF_EMBEDDABLE,
new TodoRefEmbeddableFactoryDefinition(async () => ({
savedObjectsClient: (await core.getStartServices())[0].savedObjects.client,
getEmbeddableFactory: (await core.getStartServices())[1].embeddable.getEmbeddableFactory,
}))
);
this.exampleEmbeddableFactories.getBookEmbeddableFactory =
deps.embeddable.registerEmbeddableFactory(
BOOK_EMBEDDABLE,
new BookEmbeddableFactoryDefinition(async () => ({
getAttributeService: (await core.getStartServices())[1].embeddable.getAttributeService,
openModal: (await core.getStartServices())[0].overlays.openModal,
savedObjectsClient: (await core.getStartServices())[0].savedObjects.client,
overlays: (await core.getStartServices())[0].overlays,
}))
);
const editBookAction = createEditBookAction(async () => ({
getAttributeService: (await core.getStartServices())[1].embeddable.getAttributeService,

View file

@ -28,7 +28,8 @@ export type SearchableListContainerFactory = EmbeddableFactory<
ContainerOutput
>;
export class SearchableListContainerFactoryDefinition
implements EmbeddableFactoryDefinition<SearchableContainerInput, ContainerOutput> {
implements EmbeddableFactoryDefinition<SearchableContainerInput, ContainerOutput>
{
public readonly type = SEARCHABLE_LIST_CONTAINER;
public readonly isContainerType = true;

View file

@ -44,7 +44,8 @@ interface StartServices {
export type TodoEmbeddableFactory = EmbeddableFactory<TodoInput, TodoOutput, TodoEmbeddable>;
export class TodoEmbeddableFactoryDefinition
implements EmbeddableFactoryDefinition<TodoInput, TodoOutput, TodoEmbeddable> {
implements EmbeddableFactoryDefinition<TodoInput, TodoOutput, TodoEmbeddable>
{
public readonly type = TODO_EMBEDDABLE;
constructor(private getStartServices: () => Promise<StartServices>) {}

View file

@ -42,7 +42,8 @@ export class TodoRefEmbeddableFactoryDefinition
TodoRefOutput,
TodoRefEmbeddable,
TodoSavedObjectAttributes
> {
>
{
public readonly type = TODO_REF_EMBEDDABLE;
public readonly savedObjectMetaData = {
name: 'Todo',

View file

@ -17,7 +17,8 @@ export interface EmbeddableExamplesSetupDependencies {
}
export class EmbeddableExamplesPlugin
implements Plugin<void, void, EmbeddableExamplesSetupDependencies> {
implements Plugin<void, void, EmbeddableExamplesSetupDependencies>
{
public setup(core: CoreSetup, { embeddable }: EmbeddableExamplesSetupDependencies) {
core.savedObjects.registerType(todoSavedObject);
core.savedObjects.registerType(bookSavedObject);

View file

@ -40,8 +40,7 @@ export class IndexPatternFieldEditorPlugin implements Plugin<void, void, SetupDe
links: [
{
label: 'README',
href:
'https://github.com/elastic/kibana/blob/master/src/plugins/index_pattern_field_editor/README.md',
href: 'https://github.com/elastic/kibana/blob/master/src/plugins/index_pattern_field_editor/README.md',
iconType: 'logoGithub',
size: 's',
target: '_blank',

View file

@ -50,6 +50,6 @@ export class HelloLocatorDefinition implements LocatorDefinition<HelloLocatorPar
};
public readonly migrations = {
'0.0.2': (migrateV1ToV2 as unknown) as MigrateFunction,
'0.0.2': migrateV1ToV2 as unknown as MigrateFunction,
};
}

View file

@ -23,7 +23,8 @@ export interface LocatorExamplesSetup {
}
export class LocatorExamplesPlugin
implements Plugin<LocatorExamplesSetup, void, SetupDeps, StartDeps> {
implements Plugin<LocatorExamplesSetup, void, SetupDeps, StartDeps>
{
public setup(core: CoreSetup<StartDeps>, plugins: SetupDeps) {
const locator = plugins.share.url.locators.create(new HelloLocatorDefinition());

View file

@ -47,8 +47,7 @@ export class LocatorExplorerPlugin implements Plugin<void, void, SetupDeps, Star
links: [
{
label: 'README',
href:
'https://github.com/elastic/kibana/blob/master/src/plugins/share/common/url_service/locators/README.md',
href: 'https://github.com/elastic/kibana/blob/master/src/plugins/share/common/url_service/locators/README.md',
iconType: 'logoGithub',
size: 's',
target: '_blank',

View file

@ -47,16 +47,14 @@ function RoutingExplorer({
listItems={[
{
label: 'IRouter API docs',
href:
'https://github.com/elastic/kibana/blob/master/docs/development/core/server/kibana-plugin-core-server.irouter.md',
href: 'https://github.com/elastic/kibana/blob/master/docs/development/core/server/kibana-plugin-core-server.irouter.md',
iconType: 'logoGithub',
target: '_blank',
size: 's',
},
{
label: 'HttpHandler (core.http.fetch) API docs',
href:
'https://github.com/elastic/kibana/blob/master/docs/development/core/public/kibana-plugin-core-public.httphandler.md',
href: 'https://github.com/elastic/kibana/blob/master/docs/development/core/public/kibana-plugin-core-public.httphandler.md',
iconType: 'logoGithub',
target: '_blank',
size: 's',

View file

@ -41,16 +41,14 @@ export class RoutingExamplePlugin implements Plugin<{}, {}, SetupDeps, {}> {
links: [
{
label: 'IRouter',
href:
'https://github.com/elastic/kibana/blob/master/docs/development/core/server/kibana-plugin-core-server.irouter.md',
href: 'https://github.com/elastic/kibana/blob/master/docs/development/core/server/kibana-plugin-core-server.irouter.md',
iconType: 'logoGithub',
target: '_blank',
size: 's',
},
{
label: 'HttpHandler (core.http.fetch)',
href:
'https://github.com/elastic/kibana/blob/master/docs/development/core/public/kibana-plugin-core-public.httphandler.md',
href: 'https://github.com/elastic/kibana/blob/master/docs/development/core/public/kibana-plugin-core-public.httphandler.md',
iconType: 'logoGithub',
target: '_blank',
size: 's',

View file

@ -30,7 +30,8 @@ export class SearchExamplesPlugin
SearchExamplesPluginStart,
AppPluginSetupDependencies,
AppPluginStartDependencies
> {
>
{
public setup(
core: CoreSetup<AppPluginStartDependencies>,
{ developerExamples, share }: AppPluginSetupDependencies

View file

@ -542,14 +542,8 @@ function SearchInspector({
function useAppState({ data }: { data: DataPublicPluginStart }) {
const stateContainer = useMemo(() => {
const {
filters,
time,
searchSessionId,
numericFieldName,
indexPatternId,
query,
} = getInitialStateFromUrl();
const { filters, time, searchSessionId, numericFieldName, indexPatternId, query } =
getInitialStateFromUrl();
if (filters) {
data.query.filterManager.setFilters(filters);

View file

@ -15,7 +15,7 @@ export const fibonacciStrategyProvider = (): ISearchStrategy<
FibonacciResponse
> => {
const responseMap = new Map<string, [number[], number, number]>();
return ({
return {
search: (request: FibonacciRequest) => {
const id = request.id ?? uuid();
const [sequence, total, started] = responseMap.get(id) ?? [
@ -48,5 +48,5 @@ export const fibonacciStrategyProvider = (): ISearchStrategy<
cancel: async (id: string) => {
responseMap.delete(id);
},
} as unknown) as ISearchStrategy<FibonacciRequest, FibonacciResponse>;
} as unknown as ISearchStrategy<FibonacciRequest, FibonacciResponse>;
};

View file

@ -33,7 +33,8 @@ export class SearchExamplesPlugin
SearchExamplesPluginStart,
SearchExamplesPluginSetupDeps,
SearchExamplesPluginStartDeps
> {
>
{
private readonly logger: Logger;
constructor(initializerContext: PluginInitializerContext) {

View file

@ -88,16 +88,14 @@ export class StateContainersExamplesPlugin implements Plugin {
links: [
{
label: 'State containers README',
href:
'https://github.com/elastic/kibana/tree/master/src/plugins/kibana_utils/docs/state_containers',
href: 'https://github.com/elastic/kibana/tree/master/src/plugins/kibana_utils/docs/state_containers',
iconType: 'logoGithub',
size: 's',
target: '_blank',
},
{
label: 'State sync utils README',
href:
'https://github.com/elastic/kibana/tree/master/src/plugins/kibana_utils/docs/state_sync',
href: 'https://github.com/elastic/kibana/tree/master/src/plugins/kibana_utils/docs/state_sync',
iconType: 'logoGithub',
size: 's',
target: '_blank',

View file

@ -21,7 +21,8 @@ export interface UiActionExamplesStartDependencies {
export class UiActionExamplesPlugin
implements
Plugin<void, void, UiActionExamplesSetupDependencies, UiActionExamplesStartDependencies> {
Plugin<void, void, UiActionExamplesSetupDependencies, UiActionExamplesStartDependencies>
{
public setup(
core: CoreSetup<UiActionExamplesStartDependencies>,
{ uiActions }: UiActionExamplesSetupDependencies

View file

@ -586,7 +586,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",
@ -707,7 +707,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",
@ -784,7 +784,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",

View file

@ -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();
}

View file

@ -35,8 +35,9 @@ type RequiredProperties<Base extends Props> = 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<P extends Props> = Readonly<
{ [K in keyof OptionalProperties<P>]?: TypeOf<P[K]> } &
{ [K in keyof RequiredProperties<P>]: TypeOf<P[K]> }
{ [K in keyof OptionalProperties<P>]?: TypeOf<P[K]> } & {
[K in keyof RequiredProperties<P>]: TypeOf<P[K]>;
}
>;
type DefinedProperties<Base extends NullableProps> = Pick<
@ -46,8 +47,9 @@ type DefinedProperties<Base extends NullableProps> = Pick<
}[keyof Base]
>;
type ExtendedProps<P extends Props, NP extends NullableProps> = Omit<P, keyof NP> &
{ [K in keyof DefinedProperties<NP>]: NP[K] };
type ExtendedProps<P extends Props, NP extends NullableProps> = Omit<P, keyof NP> & {
[K in keyof DefinedProperties<NP>]: NP[K];
};
type ExtendedObjectType<P extends Props, NP extends NullableProps> = ObjectType<
ExtendedProps<P, NP>

View file

@ -125,31 +125,25 @@ const _unused = (
};
};
const rename = (
oldKey: string,
newKey: string,
details?: Partial<DeprecatedConfigDetails>
): ConfigDeprecation => (config, rootPath, addDeprecation) =>
_rename(config, rootPath, addDeprecation, oldKey, newKey, details);
const rename =
(oldKey: string, newKey: string, details?: Partial<DeprecatedConfigDetails>): ConfigDeprecation =>
(config, rootPath, addDeprecation) =>
_rename(config, rootPath, addDeprecation, oldKey, newKey, details);
const renameFromRoot = (
oldKey: string,
newKey: string,
details?: Partial<DeprecatedConfigDetails>
): ConfigDeprecation => (config, rootPath, addDeprecation) =>
_rename(config, '', addDeprecation, oldKey, newKey, details);
const renameFromRoot =
(oldKey: string, newKey: string, details?: Partial<DeprecatedConfigDetails>): ConfigDeprecation =>
(config, rootPath, addDeprecation) =>
_rename(config, '', addDeprecation, oldKey, newKey, details);
const unused = (
unusedKey: string,
details?: Partial<DeprecatedConfigDetails>
): ConfigDeprecation => (config, rootPath, addDeprecation) =>
_unused(config, rootPath, addDeprecation, unusedKey, details);
const unused =
(unusedKey: string, details?: Partial<DeprecatedConfigDetails>): ConfigDeprecation =>
(config, rootPath, addDeprecation) =>
_unused(config, rootPath, addDeprecation, unusedKey, details);
const unusedFromRoot = (
unusedKey: string,
details?: Partial<DeprecatedConfigDetails>
): ConfigDeprecation => (config, rootPath, addDeprecation) =>
_unused(config, '', addDeprecation, unusedKey, details);
const unusedFromRoot =
(unusedKey: string, details?: Partial<DeprecatedConfigDetails>): ConfigDeprecation =>
(config, rootPath, addDeprecation) =>
_unused(config, '', addDeprecation, unusedKey, details);
const getPath = (rootPath: string, subPath: string) =>
rootPath !== '' ? `${rootPath}.${subPath}` : subPath;

View file

@ -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) => {

View file

@ -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;

View file

@ -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([]);

View file

@ -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);

View file

@ -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);

View file

@ -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');

View file

@ -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');

View file

@ -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);
};

View file

@ -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: '',
});

View file

@ -26,7 +26,7 @@ export function toElasticsearchQuery(
context: Record<string, any> = {}
): 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 {

View file

@ -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: '',
});

View file

@ -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);

View file

@ -9,7 +9,8 @@
/**
* Matches every single [A-Za-z] character, `<tag attr="any > text">`, `](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) {

View file

@ -14,10 +14,9 @@ type PlainObject = Record<string | number | symbol, any>;
type DeepMerge<T, U> = U extends PlainObject
? T extends PlainObject
? Omit<T, keyof U> &
{
[key in keyof U]: T extends { [k in key]: any } ? DeepMerge<T[key], U[key]> : U[key];
}
? Omit<T, keyof U> & {
[key in keyof U]: T extends { [k in key]: any } ? DeepMerge<T[key], U[key]> : U[key];
}
: U
: U;

View file

@ -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<void> {

View file

@ -22,28 +22,30 @@ type Comparator<T> = (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 = <T>(...getters: Array<SortPropGetter<T>>): Comparator<T> => (a, b) => {
for (const getter of getters) {
const valA = getter(a);
const valB = getter(b);
export const ascending =
<T>(...getters: Array<SortPropGetter<T>>): Comparator<T> =>
(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

View file

@ -179,76 +179,74 @@ export function parseBundles(json: string) {
throw new Error('must be an array');
}
return specs.map(
(spec: UnknownVals<BundleSpec>): 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 { 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 { 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 { 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 { 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');
}
}
return new Bundle({
type,
id,
publicDirNames,
contextDir,
sourceRoot,
outputDir,
banner,
manifestPath,
pageLoadAssetSizeLimit,
});
return specs.map((spec: UnknownVals<BundleSpec>): 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 { 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 { 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 { 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 { 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');
}
}
return new Bundle({
type,
id,
publicDirNames,
contextDir,
sourceRoot,
outputDir,
banner,
manifestPath,
pageLoadAssetSizeLimit,
});
});
} catch (error) {
throw new Error(`unable to parse bundles: ${error.message}`);
}

View file

@ -58,46 +58,44 @@ export class BundleRefs {
}
return new BundleRefs(
spec.map(
(refSpec: UnknownVals<BundleRef>): 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>): 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,
};
})
);
}

View file

@ -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<jest.Mocked<ActualWatchpack>>;
const [watcher] = MockWatchPack.mock.instances as any as Array<jest.Mocked<ActualWatchpack>>;
expect(watcher.on).toHaveBeenCalledTimes(1);
expect(watcher.on).toHaveBeenCalledWith('change', expect.any(Function));
const [, changeListener] = watcher.on.mock.calls[0];

View file

@ -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', () => {

View file

@ -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];
(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)
);
}
this.maybeReplaceImport(context, dep.request).then(
(module) => {
if (!module) {
wrappedFactory(data, callback);
} else {
callback(undefined, module);
}
},
(error) => callback(error)
);
}
);
});

View file

@ -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([
{

View file

@ -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({

View file

@ -51,10 +51,10 @@ export const AutocompleteFieldListsComponent: React.FC<AutocompleteFieldListsPro
const { loading, result, start } = useFindLists();
const getLabel = useCallback(({ name }) => 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);

View file

@ -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');
});

View file

@ -187,10 +187,10 @@ export const AutocompleteFieldMatchComponent: React.FC<AutocompleteFieldMatchPro
}
}, [isLoading, selectedField, isLoadingSuggestions, placeholder]);
const isLoadingState = useMemo((): boolean => isLoading || isLoadingSuggestions, [
isLoading,
isLoadingSuggestions,
]);
const isLoadingState = useMemo(
(): boolean => isLoading || isLoadingSuggestions,
[isLoading, isLoadingSuggestions]
);
useEffect((): void => {
setError(undefined);

View file

@ -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,

View file

@ -145,10 +145,10 @@ export const AutocompleteFieldMatchAnyComponent: React.FC<AutocompleteFieldMatch
[isLoading, isLoadingSuggestions, placeholder]
);
const isLoadingState = useMemo((): boolean => isLoading || isLoadingSuggestions, [
isLoading,
isLoadingSuggestions,
]);
const isLoadingState = useMemo(
(): boolean => isLoading || isLoadingSuggestions,
[isLoading, isLoadingSuggestions]
);
const defaultInput = useMemo((): JSX.Element => {
return (

View file

@ -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);

View file

@ -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' },

View file

@ -50,9 +50,10 @@ export const OperatorComponent: React.FC<OperatorState> = ({
: 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<OperatorOption>({

View file

@ -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', () => {

View file

@ -16,7 +16,7 @@
*/
export const encodeHitVersion = <T>(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;
};

View file

@ -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);

View file

@ -18,9 +18,9 @@ export type OptionalSignalArgs<Args> = Omit<Args, 'signal'> & Partial<SignalArgs
*
* @returns An async function where the AbortSignal argument is optional
*/
export const withOptionalSignal = <Args extends SignalArgs, Result>(fn: (args: Args) => Result) => (
args: OptionalSignalArgs<Args>
): Result => {
const signal = args.signal != null ? args.signal : new AbortController().signal;
return fn({ ...args, signal } as Args);
};
export const withOptionalSignal =
<Args extends SignalArgs, Result>(fn: (args: Args) => Result) =>
(args: OptionalSignalArgs<Args>): Result => {
const signal = args.signal != null ? args.signal : new AbortController().signal;
return fn({ ...args, signal } as Args);
};

View file

@ -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);

View file

@ -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);

View file

@ -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);

View file

@ -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);

View file

@ -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);

View file

@ -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,
});

View file

@ -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,
});

View file

@ -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<ExceptionListItemSchema> => ({
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<ExceptionListItemSchema> => ({
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,
});

View file

@ -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<ExceptionListSchema> => ({
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<ExceptionListSchema> => ({
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,
});

View file

@ -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,

View file

@ -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,

View file

@ -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<TRouteParamsRT>;
}>
: {};
type ClientRequestParamsOfType<TRouteParamsRT extends RouteParamsRT> =
TRouteParamsRT extends t.Mixed
? MaybeOptional<{
params: t.OutputOf<TRouteParamsRT>;
}>
: {};
type DecodedRequestParamsOfType<
TRouteParamsRT extends RouteParamsRT
> = TRouteParamsRT extends t.Mixed
? MaybeOptional<{
params: t.TypeOf<TRouteParamsRT>;
}>
: {};
type DecodedRequestParamsOfType<TRouteParamsRT extends RouteParamsRT> =
TRouteParamsRT extends t.Mixed
? MaybeOptional<{
params: t.TypeOf<TRouteParamsRT>;
}>
: {};
export type EndpointOf<
TServerRouteRepository extends ServerRouteRepository<any, any, any>
> = TServerRouteRepository extends ServerRouteRepository<any, any, infer TRouteState>
? keyof TRouteState
: never;
export type EndpointOf<TServerRouteRepository extends ServerRouteRepository<any, any, any>> =
TServerRouteRepository extends ServerRouteRepository<any, any, infer TRouteState>
? keyof TRouteState
: never;
export type ReturnOf<
TServerRouteRepository extends ServerRouteRepository<any, any, any>,

View file

@ -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 extends CreateTestEsClusterOptions = CreateTestEsClusterOptions> =
Options['nodes'] extends TestEsClusterNodesOptions[]
? ICluster
: ICluster & { getUrl: () => string }; // Only allow use of `getUrl` if `nodes` option isn't provided.
export interface CreateTestEsClusterOptions {
basePath?: string;

View file

@ -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);
}

View file

@ -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;

View file

@ -51,12 +51,12 @@ describe('SuiteTracker', () => {
let MOCKS: Record<string, Suite>;
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 = () => {}) => {

View file

@ -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(
<I18nProvider>
<br />
</I18nProvider>
).find('IntlProvider') as ReactWrapper<{}, {}, __IntlProvider>)
const { intl } = (
mount(
<I18nProvider>
<br />
</I18nProvider>
).find('IntlProvider') as ReactWrapper<{}, {}, __IntlProvider>
)
.instance()
.getChildContext();

View file

@ -9,8 +9,9 @@
import React, { ComponentType } from 'react';
import { Provider } from 'react-redux';
export const WithStore = (store: any) => (WrappedComponent: ComponentType) => (props: any) => (
<Provider store={store}>
<WrappedComponent {...props} />
</Provider>
);
export const WithStore = (store: any) => (WrappedComponent: ComponentType) => (props: any) =>
(
<Provider store={store}>
<WrappedComponent {...props} />
</Provider>
);

View file

@ -30,42 +30,45 @@ const locationDescriptorToRoutePath = (
return stringifyPath(paths);
};
export const WithMemoryRouter = (
initialEntries: LocationDescriptor[] = ['/'],
initialIndex: number = 0
) => (WrappedComponent: ComponentType) => (props: any) => (
<MemoryRouter initialEntries={initialEntries} initialIndex={initialIndex}>
<WrappedComponent {...props} />
</MemoryRouter>
);
export const WithMemoryRouter =
(initialEntries: LocationDescriptor[] = ['/'], initialIndex: number = 0) =>
(WrappedComponent: ComponentType) =>
(props: any) =>
(
<MemoryRouter initialEntries={initialEntries} initialIndex={initialIndex}>
<WrappedComponent {...props} />
</MemoryRouter>
);
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<any> {
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<any> {
componentDidMount() {
const { match, location, history } = this.props;
const router = { route: { match, location }, history };
onRouter(router);
}
render() {
return <WrappedComponent {...this.props} />;
}
}
);
render() {
return <WrappedComponent {...this.props} />;
}
}
);
return (props: any) => (
<Route
path={locationDescriptorToRoutePath(componentRoutePath)}
render={(routerProps) => <CatchRouter {...routerProps} {...props} />}
/>
);
};
return (props: any) => (
<Route
path={locationDescriptorToRoutePath(componentRoutePath)}
render={(routerProps) => <CatchRouter {...routerProps} {...props} />}
/>
);
};
interface Router {
history: Partial<History>;

View file

@ -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;
};

View file

@ -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,
]);
});
});

View file

@ -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,
]);
});
});

View file

@ -252,10 +252,9 @@ type AppendPath<
TPath extends string
> = NormalizePath<`${TPrefix}${NormalizePath<`/${TPath}`>}`>;
type MaybeUnion<T extends Record<string, any>, U extends Record<string, any>> = Omit<T, keyof U> &
{
[key in keyof U]: key extends keyof T ? T[key] | U[key] : U[key];
};
type MaybeUnion<T extends Record<string, any>, U extends Record<string, any>> = Omit<T, keyof U> & {
[key in keyof U]: key extends keyof T ? T[key] | U[key] : U[key];
};
type MapRoute<TRoute extends Route, TParents extends Route[] = []> = TRoute extends Route
? MaybeUnion<

View file

@ -10,7 +10,6 @@ export type DeeplyMockedKeys<T> = {
[P in keyof T]: T[P] extends (...args: any[]) => any
? jest.MockInstance<ReturnType<T[P]>, Parameters<T[P]>>
: DeeplyMockedKeys<T[P]>;
} &
T;
} & T;
export type MockedKeys<T> = { [P in keyof T]: jest.Mocked<T[P]> };

View file

@ -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',
},
};

View file

@ -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

View file

@ -32,7 +32,8 @@ import {
* @public
*/
export class ScopedHistory<HistoryLocationState = unknown>
implements History<HistoryLocationState> {
implements History<HistoryLocationState>
{
/**
* Tracks whether or not the user has left this history's scope. All methods throw errors if called after scope has
* been left.

View file

@ -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(<HeaderActionMenu actionMenu$={menuMount$} />);

View file

@ -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 }) => <React.Fragment>{children}</React.Fragment>}
i18nContext={() =>
({ children }) =>
<React.Fragment>{children}</React.Fragment>}
/>
);
}

View file

@ -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;
}>;

View file

@ -56,7 +56,7 @@ export function createPluginInitializerContext(
env: coreContext.env,
config: {
get<T>() {
return (pluginConfig as unknown) as T;
return pluginConfig as unknown as T;
},
},
};

View file

@ -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)) {

View file

@ -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<MockedPluginInitializer, [PluginName]> = jest
.fn()
.mockImplementation(() => () => {
throw new Error('No provider specified');
});
jest.mock('./plugin_reader', () => ({
read: mockPluginInitializerProvider,

View file

@ -117,7 +117,7 @@ describe('PluginsService', () => {
};
// Reset these for each test.
mockPluginInitializers = new Map<PluginName, MockedPluginInitializer>(([
mockPluginInitializers = new Map<PluginName, MockedPluginInitializer>([
[
'pluginA',
jest.fn(() => ({
@ -146,7 +146,7 @@ describe('PluginsService', () => {
stop: jest.fn(),
})),
],
] as unknown) as [[PluginName, any]]);
] as unknown as [[PluginName, any]]);
});
describe('#getOpaqueIds()', () => {

Some files were not shown because too many files have changed in this diff Show more