diff --git a/.eslintrc.js b/.eslintrc.js index 86ac92de9042d..aeaf6e04fdc01 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -50,7 +50,7 @@ const ELASTIC_LICENSE_HEADER = ` `; const allMochaRulesOff = {}; -Object.keys(require('eslint-plugin-mocha').rules).forEach(k => { +Object.keys(require('eslint-plugin-mocha').rules).forEach((k) => { allMochaRulesOff['mocha/' + k] = 'off'; }); diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a9a2f609e0913..1053cc2f65396 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -490,6 +490,14 @@ module.exports = { }; ``` +APM [Real User Monitoring agent](https://www.elastic.co/guide/en/apm/agent/rum-js/current/index.html) is not available in the Kibana distributables, +however the agent can be enabled by setting `ELASTIC_APM_ACTIVE` to `true`. +flags +``` +ELASTIC_APM_ACTIVE=true yarn start +// activates both Node.js and RUM agent +``` + Once the agent is active, it will trace all incoming HTTP requests to Kibana, monitor for errors, and collect process-level metrics. The collected data will be sent to the APM Server and is viewable in the APM UI in Kibana. diff --git a/Gruntfile.js b/Gruntfile.js index c33a576d4340f..0216ab12f7cc5 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -19,7 +19,7 @@ require('./src/setup_node_env'); -module.exports = function(grunt) { +module.exports = function (grunt) { // set the config once before calling load-grunt-config // and once during so that we have access to it via // grunt.config.get() within the config files diff --git a/docs/development/core/public/kibana-plugin-core-public.applicationstart.geturlforapp.md b/docs/development/core/public/kibana-plugin-core-public.applicationstart.geturlforapp.md index f36351c8b8f06..055ad9f37e654 100644 --- a/docs/development/core/public/kibana-plugin-core-public.applicationstart.geturlforapp.md +++ b/docs/development/core/public/kibana-plugin-core-public.applicationstart.geturlforapp.md @@ -6,7 +6,7 @@ Returns an URL to a given app, including the global base path. By default, the URL is relative (/basePath/app/my-app). Use the `absolute` option to generate an absolute url (http://host:port/basePath/app/my-app) -Note that when generating absolute urls, the protocol, host and port are determined from the browser location. +Note that when generating absolute urls, the origin (protocol, host and port) are determined from the browser's location. Signature: diff --git a/docs/development/core/public/kibana-plugin-core-public.applicationstart.md b/docs/development/core/public/kibana-plugin-core-public.applicationstart.md index a93bc61bac527..6f45bab3ebd2d 100644 --- a/docs/development/core/public/kibana-plugin-core-public.applicationstart.md +++ b/docs/development/core/public/kibana-plugin-core-public.applicationstart.md @@ -22,7 +22,8 @@ export interface ApplicationStart | Method | Description | | --- | --- | -| [getUrlForApp(appId, options)](./kibana-plugin-core-public.applicationstart.geturlforapp.md) | Returns an URL to a given app, including the global base path. By default, the URL is relative (/basePath/app/my-app). Use the absolute option to generate an absolute url (http://host:port/basePath/app/my-app)Note that when generating absolute urls, the protocol, host and port are determined from the browser location. | +| [getUrlForApp(appId, options)](./kibana-plugin-core-public.applicationstart.geturlforapp.md) | Returns an URL to a given app, including the global base path. By default, the URL is relative (/basePath/app/my-app). Use the absolute option to generate an absolute url (http://host:port/basePath/app/my-app)Note that when generating absolute urls, the origin (protocol, host and port) are determined from the browser's location. | | [navigateToApp(appId, options)](./kibana-plugin-core-public.applicationstart.navigatetoapp.md) | Navigate to a given app | +| [navigateToUrl(url)](./kibana-plugin-core-public.applicationstart.navigatetourl.md) | Navigate to given url, which can either be an absolute url or a relative path, in a SPA friendly way when possible.If all these criteria are true for the given url: - (only for absolute URLs) The origin of the URL matches the origin of the browser's current location - The pathname of the URL starts with the current basePath (eg. /mybasepath/s/my-space) - The pathname segment after the basePath matches any known application route (eg. /app// or any application's appRoute configuration)Then a SPA navigation will be performed using navigateToApp using the corresponding application and path. Otherwise, fallback to a full page reload to navigate to the url using window.location.assign | | [registerMountContext(contextName, provider)](./kibana-plugin-core-public.applicationstart.registermountcontext.md) | Register a context provider for application mounting. Will only be available to applications that depend on the plugin that registered this context. Deprecated, use [CoreSetup.getStartServices](./kibana-plugin-core-public.coresetup.getstartservices.md). | diff --git a/docs/development/core/public/kibana-plugin-core-public.applicationstart.navigatetourl.md b/docs/development/core/public/kibana-plugin-core-public.applicationstart.navigatetourl.md new file mode 100644 index 0000000000000..86b86776b0b12 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.applicationstart.navigatetourl.md @@ -0,0 +1,45 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [ApplicationStart](./kibana-plugin-core-public.applicationstart.md) > [navigateToUrl](./kibana-plugin-core-public.applicationstart.navigatetourl.md) + +## ApplicationStart.navigateToUrl() method + +Navigate to given url, which can either be an absolute url or a relative path, in a SPA friendly way when possible. + +If all these criteria are true for the given url: - (only for absolute URLs) The origin of the URL matches the origin of the browser's current location - The pathname of the URL starts with the current basePath (eg. /mybasepath/s/my-space) - The pathname segment after the basePath matches any known application route (eg. /app// or any application's `appRoute` configuration) + +Then a SPA navigation will be performed using `navigateToApp` using the corresponding application and path. Otherwise, fallback to a full page reload to navigate to the url using `window.location.assign` + +Signature: + +```typescript +navigateToUrl(url: string): Promise; +``` + +## Parameters + +| Parameter | Type | Description | +| --- | --- | --- | +| url | string | an absolute url, or a relative path, to navigate to. | + +Returns: + +`Promise` + +## Example + + +```ts +// current url: `https://kibana:8080/base-path/s/my-space/app/dashboard` + +// will call `application.navigateToApp('discover', { path: '/some-path?foo=bar'})` +application.navigateToUrl('https://kibana:8080/base-path/s/my-space/app/discover/some-path?foo=bar') +application.navigateToUrl('/base-path/s/my-space/app/discover/some-path?foo=bar') + +// will perform a full page reload using `window.location.assign` +application.navigateToUrl('https://elsewhere:8080/base-path/s/my-space/app/discover/some-path') // origin does not match +application.navigateToUrl('/app/discover/some-path') // does not include the current basePath +application.navigateToUrl('/base-path/s/my-space/app/unknown-app/some-path') // unknown application + +``` + diff --git a/examples/alerting_example/public/alert_types/always_firing.tsx b/examples/alerting_example/public/alert_types/always_firing.tsx index b7add1f6d43ce..130519308d3c3 100644 --- a/examples/alerting_example/public/alert_types/always_firing.tsx +++ b/examples/alerting_example/public/alert_types/always_firing.tsx @@ -71,7 +71,7 @@ export const AlwaysFiringExpression: React.FunctionComponent { + onChange={(event) => { setAlertParams('instances', event.target.valueAsNumber); }} /> diff --git a/examples/alerting_example/public/alert_types/astros.tsx b/examples/alerting_example/public/alert_types/astros.tsx index 3411c6722ccd6..2e263e454fa0c 100644 --- a/examples/alerting_example/public/alert_types/astros.tsx +++ b/examples/alerting_example/public/alert_types/astros.tsx @@ -51,7 +51,7 @@ interface PeopleinSpaceParamsProps { } function isValueInEnum(enumeratin: Record, value: any): boolean { - return !!Object.values(enumeratin).find(enumVal => enumVal === value); + return !!Object.values(enumeratin).find((enumVal) => enumVal === value); } export function getAlertType(): AlertTypeModel { @@ -139,7 +139,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent - errs.map(e => ( + errs.map((e) => (

{field}:`: ${errs}`

@@ -189,7 +189,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent { + onChange={(event) => { setAlertParams('craft', event.target.value); setCraftTrigger({ craft: event.target.value, @@ -238,7 +238,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent { + onChange={(event) => { setAlertParams('op', event.target.value); setOuterSpaceCapacity({ ...outerSpaceCapacityTrigger, @@ -258,7 +258,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent { + onChange={(event) => { setAlertParams('outerSpaceCapacity', event.target.valueAsNumber); setOuterSpaceCapacity({ ...outerSpaceCapacityTrigger, diff --git a/examples/alerting_example/server/alert_types/astros.ts b/examples/alerting_example/server/alert_types/astros.ts index d22bc6164fa52..d25edc1e01b3f 100644 --- a/examples/alerting_example/server/alert_types/astros.ts +++ b/examples/alerting_example/server/alert_types/astros.ts @@ -68,10 +68,7 @@ export const alertType: AlertType = { if (getOperator(op)(peopleInCraft.length, outerSpaceCapacity)) { peopleInCraft.forEach(({ craft, name }) => { - services - .alertInstanceFactory(name) - .replaceState({ craft }) - .scheduleActions('default'); + services.alertInstanceFactory(name).replaceState({ craft }).scheduleActions('default'); }); } diff --git a/examples/bfetch_explorer/public/components/count_until/index.tsx b/examples/bfetch_explorer/public/components/count_until/index.tsx index ce48ce9dfe61f..73cbcf4cbdb1c 100644 --- a/examples/bfetch_explorer/public/components/count_until/index.tsx +++ b/examples/bfetch_explorer/public/components/count_until/index.tsx @@ -82,7 +82,7 @@ export const CountUntil: React.FC = ({ fetchStreaming }) => { setData(Number(e.target.value))} + onChange={(e) => setData(Number(e.target.value))} /> diff --git a/examples/bfetch_explorer/public/components/double_integers/index.tsx b/examples/bfetch_explorer/public/components/double_integers/index.tsx index d8fbe33ec73be..58940c23b1a6c 100644 --- a/examples/bfetch_explorer/public/components/double_integers/index.tsx +++ b/examples/bfetch_explorer/public/components/double_integers/index.tsx @@ -49,18 +49,18 @@ export const DoubleIntegers: React.FC = ({ double }) => { setShowingResults(true); const nums = numbers .split('\n') - .map(num => num.trim()) + .map((num) => num.trim()) .filter(Boolean) .map(Number); counter.set(nums.length); - nums.forEach(num => { + nums.forEach((num) => { double({ num }).then( - result => { + (result) => { if (!isMounted()) return; counter.dec(); pushResult({ num, result }); }, - error => { + (error) => { if (!isMounted()) return; counter.dec(); pushResult({ num, error }); @@ -94,7 +94,7 @@ export const DoubleIntegers: React.FC = ({ double }) => { fullWidth placeholder="Enter numbers in milliseconds separated by new line" value={numbers} - onChange={e => setNumbers(e.target.value)} + onChange={(e) => setNumbers(e.target.value)} /> diff --git a/examples/bfetch_explorer/public/containers/app/index.tsx b/examples/bfetch_explorer/public/containers/app/index.tsx index a448c9e4f3a6a..13dee8ad9e61f 100644 --- a/examples/bfetch_explorer/public/containers/app/index.tsx +++ b/examples/bfetch_explorer/public/containers/app/index.tsx @@ -30,7 +30,7 @@ export const App: React.FC = () => { const routeElements: React.ReactElement[] = []; for (const { items } of routes) { for (const { id, component } of items) { - routeElements.push( component} />); + routeElements.push( component} />); } } diff --git a/examples/bfetch_explorer/public/containers/app/sidebar/index.tsx b/examples/bfetch_explorer/public/containers/app/sidebar/index.tsx index cc50698e05908..029076adea666 100644 --- a/examples/bfetch_explorer/public/containers/app/sidebar/index.tsx +++ b/examples/bfetch_explorer/public/containers/app/sidebar/index.tsx @@ -39,7 +39,7 @@ export const Sidebar: React.FC = () => { id, name: title, isSelected: true, - items: items.map(route => ({ + items: items.map((route) => ({ id: route.id, name: route.title, onClick: () => history.push(`/${route.id}`), diff --git a/examples/bfetch_explorer/server/plugin.ts b/examples/bfetch_explorer/server/plugin.ts index bf3b7f50ca6c8..2bfb63edefa3d 100644 --- a/examples/bfetch_explorer/server/plugin.ts +++ b/examples/bfetch_explorer/server/plugin.ts @@ -54,7 +54,7 @@ export class BfetchExplorerPlugin implements Plugin { // Validate inputs. if (num < 0) throw new Error('Invalid number'); // Wait number of specified milliseconds. - await new Promise(r => setTimeout(r, num)); + await new Promise((r) => setTimeout(r, num)); // Double the number and send it back. return { num: 2 * num }; }, diff --git a/examples/demo_search/server/async_demo_search_strategy.ts b/examples/demo_search/server/async_demo_search_strategy.ts index d2d40891a5d93..7ed5062acba48 100644 --- a/examples/demo_search/server/async_demo_search_strategy.ts +++ b/examples/demo_search/server/async_demo_search_strategy.ts @@ -40,7 +40,7 @@ const totalMap = new Map(); export const asyncDemoSearchStrategyProvider: TSearchStrategyProvider = () => { return { - search: async request => { + search: async (request) => { const id = request.id ?? generateId(); const loaded = (loadedMap.get(id) ?? 0) + 1; @@ -52,7 +52,7 @@ export const asyncDemoSearchStrategyProvider: TSearchStrategyProvider { + cancel: async (id) => { loadedMap.delete(id); totalMap.delete(id); }, diff --git a/examples/demo_search/server/demo_search_strategy.ts b/examples/demo_search/server/demo_search_strategy.ts index 5b0883be1fc51..a1fd0e45dbc8e 100644 --- a/examples/demo_search/server/demo_search_strategy.ts +++ b/examples/demo_search/server/demo_search_strategy.ts @@ -22,7 +22,7 @@ import { DEMO_SEARCH_STRATEGY } from '../common'; export const demoSearchStrategyProvider: TSearchStrategyProvider = () => { return { - search: request => { + search: (request) => { return Promise.resolve({ greeting: request.mood === 'happy' diff --git a/examples/embeddable_examples/public/list_container/list_container_component.tsx b/examples/embeddable_examples/public/list_container/list_container_component.tsx index da27889a27603..ae4de1c765154 100644 --- a/examples/embeddable_examples/public/list_container/list_container_component.tsx +++ b/examples/embeddable_examples/public/list_container/list_container_component.tsx @@ -40,7 +40,7 @@ function renderList( embeddableServices: EmbeddableStart ) { let number = 0; - const list = Object.values(panels).map(panel => { + const list = Object.values(panels).map((panel) => { const child = embeddable.getChild(panel.explicitInput.id); number++; return ( diff --git a/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_component.tsx b/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_component.tsx index b2882c97ef501..c059a884f08a2 100644 --- a/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_component.tsx +++ b/examples/embeddable_examples/public/multi_task_todo/multi_task_todo_component.tsx @@ -55,7 +55,7 @@ function wrapSearchTerms(task: string, search?: string) { } function renderTasks(tasks: MultiTaskTodoInput['tasks'], search?: string) { - return tasks.map(task => ( + return tasks.map((task) => ( task.match(search)); + const match = tasks.find((task) => task.match(search)); if (match) return true; return false; diff --git a/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_component.tsx b/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_component.tsx index 49dbce74788bf..f5fe01734bfa5 100644 --- a/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_component.tsx +++ b/examples/embeddable_examples/public/searchable_list_container/searchable_list_container_component.tsx @@ -65,12 +65,12 @@ export class SearchableListContainerComponentInner extends Component { + props.embeddable.getChildIds().forEach((id) => { checked[id] = false; const output = props.embeddable.getChild(id).getOutput(); hasMatch[id] = hasHasMatchOutput(output) && output.hasMatch; }); - props.embeddable.getChildIds().forEach(id => (checked[id] = false)); + props.embeddable.getChildIds().forEach((id) => (checked[id] = false)); this.state = { checked, hasMatch, @@ -78,13 +78,13 @@ export class SearchableListContainerComponentInner extends Component { + this.props.embeddable.getChildIds().forEach((id) => { this.subscriptions[id] = this.props.embeddable .getChild(id) .getOutput$() - .subscribe(output => { + .subscribe((output) => { if (hasHasMatchOutput(output)) { - this.setState(prevState => ({ + this.setState((prevState) => ({ hasMatch: { ...prevState.hasMatch, [id]: output.hasMatch, @@ -96,7 +96,7 @@ export class SearchableListContainerComponentInner extends Component sub.unsubscribe()); + Object.values(this.subscriptions).forEach((sub) => sub.unsubscribe()); } private updateSearch = (search: string) => { @@ -104,7 +104,7 @@ export class SearchableListContainerComponentInner extends Component { - Object.values(this.props.input.panels).map(panel => { + Object.values(this.props.input.panels).map((panel) => { if (this.state.checked[panel.explicitInput.id]) { this.props.embeddable.removeEmbeddable(panel.explicitInput.id); this.subscriptions[panel.explicitInput.id].unsubscribe(); @@ -115,7 +115,7 @@ export class SearchableListContainerComponentInner extends Component { const { input, embeddable } = this.props; const checked: { [key: string]: boolean } = {}; - Object.values(input.panels).map(panel => { + Object.values(input.panels).map((panel) => { const child = embeddable.getChild(panel.explicitInput.id); const output = child.getOutput(); if (hasHasMatchOutput(output) && output.hasMatch) { @@ -126,7 +126,7 @@ export class SearchableListContainerComponentInner extends Component { - this.setState(prevState => ({ checked: { ...prevState.checked, [id]: isChecked } })); + this.setState((prevState) => ({ checked: { ...prevState.checked, [id]: isChecked } })); }; public renderControls() { @@ -156,7 +156,7 @@ export class SearchableListContainerComponentInner extends Component this.updateSearch(ev.target.value)} + onChange={(ev) => this.updateSearch(ev.target.value)} /> @@ -183,7 +183,7 @@ export class SearchableListContainerComponentInner extends Component { + const list = Object.values(input.panels).map((panel) => { const childEmbeddable = embeddable.getChild(panel.explicitInput.id); id++; return childEmbeddable ? ( @@ -195,7 +195,7 @@ export class SearchableListContainerComponentInner extends Component this.toggleCheck(e.target.checked, childEmbeddable.id)} + onChange={(e) => this.toggleCheck(e.target.checked, childEmbeddable.id)} /> diff --git a/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx b/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx index bc577ca36d793..a46c3ce9ed8e9 100644 --- a/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx +++ b/examples/embeddable_examples/public/todo/todo_embeddable_factory.tsx @@ -34,7 +34,7 @@ function TaskInput({ onSave }: { onSave: (task: string) => void }) { data-test-subj="taskInputField" value={task} placeholder="Enter task here" - onChange={e => setTask(e.target.value)} + onChange={(e) => setTask(e.target.value)} /> onSave(task)}> Save @@ -69,7 +69,7 @@ export class TodoEmbeddableFactory */ public getExplicitInput = async () => { const { openModal } = await this.getStartServices(); - return new Promise<{ task: string }>(resolve => { + return new Promise<{ task: string }>((resolve) => { const onSave = (task: string) => resolve({ task }); const overlay = openModal( toMountPoint( diff --git a/examples/embeddable_explorer/public/app.tsx b/examples/embeddable_explorer/public/app.tsx index e18012b4b3d80..3fc7fbb3b89ef 100644 --- a/examples/embeddable_explorer/public/app.tsx +++ b/examples/embeddable_explorer/public/app.tsx @@ -51,7 +51,7 @@ type NavProps = RouteComponentProps & { }; const Nav = withRouter(({ history, navigateToApp, pages }: NavProps) => { - const navItems = pages.map(page => ({ + const navItems = pages.map((page) => ({ id: page.id, name: page.title, onClick: () => history.push(`/${page.id}`), @@ -122,7 +122,7 @@ const EmbeddableExplorerApp = ({ ]; const routes = pages.map((page, i) => ( - page.component} /> + page.component} /> )); return ( diff --git a/examples/embeddable_explorer/public/embeddable_panel_example.tsx b/examples/embeddable_explorer/public/embeddable_panel_example.tsx index 54cd7c5b5b2c0..98f30632ebf43 100644 --- a/examples/embeddable_explorer/public/embeddable_panel_example.tsx +++ b/examples/embeddable_explorer/public/embeddable_panel_example.tsx @@ -84,7 +84,7 @@ export function EmbeddablePanelExample({ embeddableServices }: Props) { const factory = embeddableServices.getEmbeddableFactory(SEARCHABLE_LIST_CONTAINER); const promise = factory?.create(searchableInput); if (promise) { - promise.then(e => { + promise.then((e) => { if (ref.current) { setEmbeddable(e); } diff --git a/examples/embeddable_explorer/public/todo_embeddable_example.tsx b/examples/embeddable_explorer/public/todo_embeddable_example.tsx index 2af6c713593c6..f43a81c3e7651 100644 --- a/examples/embeddable_explorer/public/todo_embeddable_example.tsx +++ b/examples/embeddable_explorer/public/todo_embeddable_example.tsx @@ -82,7 +82,7 @@ export class TodoEmbeddableExample extends React.Component { icon: 'broom', title: 'Trash', }) - .then(embeddable => { + .then((embeddable) => { this.embeddable = embeddable; this.setState({ loading: false }); }); @@ -135,7 +135,7 @@ export class TodoEmbeddableExample extends React.Component { this.setState({ title: ev.target.value })} + onChange={(ev) => this.setState({ title: ev.target.value })} /> @@ -143,7 +143,7 @@ export class TodoEmbeddableExample extends React.Component { this.setState({ icon: ev.target.value })} + onChange={(ev) => this.setState({ icon: ev.target.value })} /> @@ -153,7 +153,7 @@ export class TodoEmbeddableExample extends React.Component { fullWidth resize="horizontal" data-test-subj="taskTodo" - onChange={ev => this.setState({ task: ev.target.value })} + onChange={(ev) => this.setState({ task: ev.target.value })} /> diff --git a/examples/search_explorer/public/application.tsx b/examples/search_explorer/public/application.tsx index ea6d65d9e2113..a7072936f268d 100644 --- a/examples/search_explorer/public/application.tsx +++ b/examples/search_explorer/public/application.tsx @@ -51,7 +51,7 @@ type NavProps = RouteComponentProps & { }; const Nav = withRouter(({ history, navigateToApp, pages }: NavProps) => { - const navItems = pages.map(page => ({ + const navItems = pages.map((page) => ({ id: page.id, name: page.title, onClick: () => history.push(`/${page.id}`), @@ -103,7 +103,7 @@ const SearchApp = ({ basename, data, application }: SearchBarComponentParams) => ]; const routes = pages.map((page, i) => ( - buildPage(page)} /> + buildPage(page)} /> )); return ( diff --git a/examples/search_explorer/public/async_demo_strategy.tsx b/examples/search_explorer/public/async_demo_strategy.tsx index 40ddcc1f48fe7..9cea556c32d54 100644 --- a/examples/search_explorer/public/async_demo_strategy.tsx +++ b/examples/search_explorer/public/async_demo_strategy.tsx @@ -73,7 +73,7 @@ export class AsyncDemoStrategy extends React.Component { this.setState({ fibonacciNumbers: parseFloat(e.target.value) })} + onChange={(e) => this.setState({ fibonacciNumbers: parseFloat(e.target.value) })} /> diff --git a/examples/search_explorer/public/demo_strategy.tsx b/examples/search_explorer/public/demo_strategy.tsx index 7c6c21d2b7aed..3de6827818e14 100644 --- a/examples/search_explorer/public/demo_strategy.tsx +++ b/examples/search_explorer/public/demo_strategy.tsx @@ -81,7 +81,7 @@ export class DemoStrategy extends React.Component { this.setState({ name: e.target.value })} + onChange={(e) => this.setState({ name: e.target.value })} /> @@ -90,7 +90,7 @@ export class DemoStrategy extends React.Component { this.setState({ mood: e.target.value })} + onChange={(e) => this.setState({ mood: e.target.value })} /> diff --git a/examples/search_explorer/public/do_search.tsx b/examples/search_explorer/public/do_search.tsx index a6b6b9b57db4a..deadb06b16f5f 100644 --- a/examples/search_explorer/public/do_search.tsx +++ b/examples/search_explorer/public/do_search.tsx @@ -61,10 +61,10 @@ export class DoSearch extends React.Component { this.abortController = new AbortController(); this.props.search(this.abortController.signal).subscribe( - response => { + (response) => { this.setState({ response, error: undefined }); }, - error => { + (error) => { this.setState({ error, searching: false, response: undefined }); }, () => { diff --git a/examples/search_explorer/public/es_strategy.tsx b/examples/search_explorer/public/es_strategy.tsx index aaf9dada90341..bc6223c478bf5 100644 --- a/examples/search_explorer/public/es_strategy.tsx +++ b/examples/search_explorer/public/es_strategy.tsx @@ -92,7 +92,7 @@ export class EsSearchTest extends React.Component { this.setState({ index: e.target.value, changes: true })} + onChange={(e) => this.setState({ index: e.target.value, changes: true })} /> @@ -101,7 +101,7 @@ export class EsSearchTest extends React.Component { this.setState({ query: e.target.value, changes: true })} + onChange={(e) => this.setState({ query: e.target.value, changes: true })} /> diff --git a/examples/search_explorer/public/guide_section.tsx b/examples/search_explorer/public/guide_section.tsx index 1562e33b14c2f..c13c11dc5864c 100644 --- a/examples/search_explorer/public/guide_section.tsx +++ b/examples/search_explorer/public/guide_section.tsx @@ -59,7 +59,7 @@ export class GuideSection extends React.Component { } if (props.codeSections) { - props.codeSections.forEach(section => { + props.codeSections.forEach((section) => { this.tabs.push({ name: section.title, displayName: section.title, @@ -79,7 +79,7 @@ export class GuideSection extends React.Component { }; renderTabs() { - return this.tabs.map(tab => ( + return this.tabs.map((tab) => ( this.onSelectedTabChanged(tab.name)} isSelected={tab.name === this.state.selectedTab} @@ -98,7 +98,7 @@ export class GuideSection extends React.Component { if (!this.props.codeSections) { return undefined; } - const section = this.props.codeSections.find(s => s.title === this.state.selectedTab); + const section = this.props.codeSections.find((s) => s.title === this.state.selectedTab); if (!section) { throw new Error('No section named ' + this.state.selectedTab); diff --git a/examples/state_containers_examples/public/todo/todo.tsx b/examples/state_containers_examples/public/todo/todo.tsx index 597c2b19be0f6..b6f4f6550026b 100644 --- a/examples/state_containers_examples/public/todo/todo.tsx +++ b/examples/state_containers_examples/public/todo/todo.tsx @@ -61,7 +61,7 @@ const defaultGlobalState: GlobalState = { text: '' }; const globalStateContainer = createStateContainer( defaultGlobalState, { - setText: state => text => ({ ...state, text }), + setText: (state) => (text) => ({ ...state, text }), } ); @@ -81,7 +81,7 @@ const TodoApp: React.FC = ({ filter }) => { const { text } = GlobalStateHelpers.useState(); const { edit: editTodo, delete: deleteTodo, add: addTodo } = useTransitions(); const todos = useState().todos; - const filteredTodos = todos.filter(todo => { + const filteredTodos = todos.filter((todo) => { if (!filter) return true; if (filter === 'completed') return todo.completed; if (filter === 'not-completed') return !todo.completed; @@ -111,13 +111,13 @@ const TodoApp: React.FC = ({ filter }) => {
    - {filteredTodos.map(todo => ( + {filteredTodos.map((todo) => (
  • { + onChange={(e) => { editTodo({ ...todo, completed: e.target.checked, @@ -139,7 +139,7 @@ const TodoApp: React.FC = ({ filter }) => { ))}
{ + onSubmit={(e) => { const inputRef = (e.target as HTMLFormElement).elements.namedItem( 'newTodo' ) as HTMLInputElement; @@ -147,7 +147,7 @@ const TodoApp: React.FC = ({ filter }) => { addTodo({ text: inputRef.value, completed: false, - id: todos.map(todo => todo.id).reduce((a, b) => Math.max(a, b), 0) + 1, + id: todos.map((todo) => todo.id).reduce((a, b) => Math.max(a, b), 0) + 1, }); inputRef.value = ''; e.preventDefault(); @@ -157,7 +157,7 @@ const TodoApp: React.FC = ({ filter }) => {
- setText(e.target.value)} /> + setText(e.target.value)} />
); @@ -173,7 +173,7 @@ export const TodoAppPage: React.FC<{ appTitle: string; appBasePath: string; isInitialRoute: () => boolean; -}> = props => { +}> = (props) => { const initialAppUrl = React.useRef(window.location.href); const [useHashedUrl, setUseHashedUrl] = React.useState(false); @@ -181,7 +181,7 @@ export const TodoAppPage: React.FC<{ * Replicates what src/legacy/ui/public/chrome/api/nav.ts did * Persists the url in sessionStorage and tries to restore it on "componentDidMount" */ - useUrlTracker(`lastUrlTracker:${props.appInstanceId}`, props.history, urlToRestore => { + useUrlTracker(`lastUrlTracker:${props.appInstanceId}`, props.history, (urlToRestore) => { // shouldRestoreUrl: // App decides if it should restore url or not // In this specific case, restore only if navigated to initial route diff --git a/examples/state_containers_examples/public/with_data_services/components/app.tsx b/examples/state_containers_examples/public/with_data_services/components/app.tsx index c820929d8a61d..baf627fd62a32 100644 --- a/examples/state_containers_examples/public/with_data_services/components/app.tsx +++ b/examples/state_containers_examples/public/with_data_services/components/app.tsx @@ -135,7 +135,7 @@ const App = ({ appStateContainer.set({ ...appState, name: e.target.value })} + onChange={(e) => appStateContainer.set({ ...appState, name: e.target.value })} aria-label="My name" /> @@ -217,7 +217,7 @@ function useAppStateSyncing( stateContainer: { ...appStateContainer, // stateSync utils requires explicit handling of default state ("null") - set: state => state && appStateContainer.set(state), + set: (state) => state && appStateContainer.set(state), }, }); diff --git a/examples/ui_actions_explorer/public/actions/actions.tsx b/examples/ui_actions_explorer/public/actions/actions.tsx index 64a820ab6d194..4ef8d5bf4d9c6 100644 --- a/examples/ui_actions_explorer/public/actions/actions.tsx +++ b/examples/ui_actions_explorer/public/actions/actions.tsx @@ -47,14 +47,14 @@ export interface PhoneContext { export const makePhoneCallAction = createAction({ type: ACTION_CALL_PHONE_NUMBER, getDisplayName: () => 'Call phone number', - execute: async context => alert(`Pretend calling ${context.phone}...`), + execute: async (context) => alert(`Pretend calling ${context.phone}...`), }); export const lookUpWeatherAction = createAction({ type: ACTION_TRAVEL_GUIDE, getIconType: () => 'popout', getDisplayName: () => 'View travel guide', - execute: async context => { + execute: async (context) => { window.open(`https://www.worldtravelguide.net/?s=${context.country}`, '_blank'); }, }); @@ -67,7 +67,7 @@ export const viewInMapsAction = createAction({ type: ACTION_VIEW_IN_MAPS, getIconType: () => 'popout', getDisplayName: () => 'View in maps', - execute: async context => { + execute: async (context) => { window.open(`https://www.google.com/maps/place/${context.country}`, '_blank'); }, }); @@ -90,7 +90,7 @@ function EditUserModal({ const [name, setName] = useState(user.name); return ( - setName(e.target.value)} /> + setName(e.target.value)} /> { update({ ...user, name }); diff --git a/examples/ui_actions_explorer/public/app.tsx b/examples/ui_actions_explorer/public/app.tsx index f08b8bb29bdd3..1b0667962a3c2 100644 --- a/examples/ui_actions_explorer/public/app.tsx +++ b/examples/ui_actions_explorer/public/app.tsx @@ -72,7 +72,7 @@ const ActionsExplorer = ({ uiActionsApi, openModal }: Props) => { from. Using the UI Action and Trigger API makes your plugin extensible by other plugins. Any actions attached to the `HELLO_WORLD_TRIGGER_ID` will show up here!

- setName(e.target.value)} /> + setName(e.target.value)} /> { diff --git a/examples/ui_actions_explorer/public/trigger_context_example.tsx b/examples/ui_actions_explorer/public/trigger_context_example.tsx index 4b88652103966..05a9895d3fac4 100644 --- a/examples/ui_actions_explorer/public/trigger_context_example.tsx +++ b/examples/ui_actions_explorer/public/trigger_context_example.tsx @@ -105,7 +105,7 @@ export function TriggerContextExample({ uiActionsApi }: Props) { ]; const updateUser = (newUser: User, oldName: string) => { - const index = rows.findIndex(u => u.name === oldName); + const index = rows.findIndex((u) => u.name === oldName); const newRows = [...rows]; newRows.splice(index, 1, createRowData(newUser, uiActionsApi, updateUser)); setRows(newRows); diff --git a/examples/url_generators_examples/public/app.tsx b/examples/url_generators_examples/public/app.tsx index c39cd876ea9b1..82f36fa13ea71 100644 --- a/examples/url_generators_examples/public/app.tsx +++ b/examples/url_generators_examples/public/app.tsx @@ -67,7 +67,7 @@ export const Routes: React.FC<{}> = () => { export const LinksExample: React.FC<{ appBasePath: string; -}> = props => { +}> = (props) => { const history = React.useMemo( () => createBrowserHistory({ diff --git a/examples/url_generators_examples/public/url_generator.ts b/examples/url_generators_examples/public/url_generator.ts index f21b1c9295e66..c74ade8bf743d 100644 --- a/examples/url_generators_examples/public/url_generator.ts +++ b/examples/url_generators_examples/public/url_generator.ts @@ -38,7 +38,7 @@ export const createHelloPageLinkGenerator = ( getStartServices: () => Promise<{ appBasePath: string }> ): UrlGeneratorsDefinition => ({ id: HELLO_URL_GENERATOR, - createUrl: async state => { + createUrl: async (state) => { const startServices = await getStartServices(); const appBasePath = startServices.appBasePath; const parsedUrl = url.parse(window.location.href); @@ -72,7 +72,7 @@ export type LegacyHelloLinkGeneratorState = UrlGeneratorState< export const helloPageLinkGeneratorV1: UrlGeneratorsDefinition = { id: HELLO_URL_GENERATOR_V1, isDeprecated: true, - migrate: async state => { + migrate: async (state) => { return { id: HELLO_URL_GENERATOR, state: { firstName: state.name, lastName: '' } }; }, }; diff --git a/examples/url_generators_explorer/public/app.tsx b/examples/url_generators_explorer/public/app.tsx index 77e804ae08c5f..50dd2e075c528 100644 --- a/examples/url_generators_explorer/public/app.tsx +++ b/examples/url_generators_explorer/public/app.tsx @@ -81,7 +81,7 @@ const ActionsExplorer = ({ getLinkGenerator }: Props) => { const updateLinks = async () => { const updatedLinks = await Promise.all( - persistedLinks.map(async savedLink => { + persistedLinks.map(async (savedLink) => { const generator = getLinkGenerator(savedLink.id); const link = await generator.createUrl(savedLink.state); return { @@ -109,11 +109,11 @@ const ActionsExplorer = ({ getLinkGenerator }: Props) => { { + onChange={(e) => { setFirstName(e.target.value); }} /> - setLastName(e.target.value)} /> + setLastName(e.target.value)} /> setPersistedLinks([ @@ -142,7 +142,7 @@ const ActionsExplorer = ({ getLinkGenerator }: Props) => { {buildingLinks ? (
loading...
) : ( - migratedLinks.map(link => ( + migratedLinks.map((link) => ( dateMath.parse('now', { forceNow: '2000-01-01T00:00:00.000Z' }); expect(fn).to.throwError(); }); - it('should throw an Error if passed a moment', function() { + it('should throw an Error if passed a moment', function () { expect(() => dateMath.parse('now', { forceNow: moment() })).to.throwError(); }); - it('should throw an Error if passed an invalid date', function() { + it('should throw an Error if passed an invalid date', function () { expect(() => dateMath.parse('now', { forceNow: new Date('foobar') })).to.throwError(); }); }); }); - describe('objects and strings', function() { + describe('objects and strings', function () { let mmnt; let date; let string; let now; - beforeEach(function() { + beforeEach(function () { clock = sinon.useFakeTimers(unix); now = moment(); mmnt = moment(anchor); @@ -99,61 +99,61 @@ describe('dateMath', function() { string = mmnt.format(format); }); - afterEach(function() { + afterEach(function () { clock.restore(); }); - it('should return the same moment if passed a moment', function() { + it('should return the same moment if passed a moment', function () { expect(dateMath.parse(mmnt)).to.eql(mmnt); }); - it('should return a moment if passed a date', function() { + it('should return a moment if passed a date', function () { expect(dateMath.parse(date).format(format)).to.eql(mmnt.format(format)); }); - it('should return a moment if passed an ISO8601 string', function() { + it('should return a moment if passed an ISO8601 string', function () { expect(dateMath.parse(string).format(format)).to.eql(mmnt.format(format)); }); - it('should return the current time when parsing now', function() { + it('should return the current time when parsing now', function () { expect(dateMath.parse('now').format(format)).to.eql(now.format(format)); }); - it('should use the forceNow parameter when parsing now', function() { + it('should use the forceNow parameter when parsing now', function () { expect(dateMath.parse('now', { forceNow: anchoredDate }).valueOf()).to.eql(unix); }); }); - describe('subtraction', function() { + describe('subtraction', function () { let now; let anchored; - beforeEach(function() { + beforeEach(function () { clock = sinon.useFakeTimers(unix); now = moment(); anchored = moment(anchor); }); - afterEach(function() { + afterEach(function () { clock.restore(); }); - [5, 12, 247].forEach(len => { - spans.forEach(span => { + [5, 12, 247].forEach((len) => { + spans.forEach((span) => { const nowEx = `now-${len}${span}`; const thenEx = `${anchor}||-${len}${span}`; - it('should return ' + len + span + ' ago', function() { + it('should return ' + len + span + ' ago', function () { const parsed = dateMath.parse(nowEx).format(format); expect(parsed).to.eql(now.subtract(len, span).format(format)); }); - it('should return ' + len + span + ' before ' + anchor, function() { + it('should return ' + len + span + ' before ' + anchor, function () { const parsed = dateMath.parse(thenEx).format(format); expect(parsed).to.eql(anchored.subtract(len, span).format(format)); }); - it('should return ' + len + span + ' before forceNow', function() { + it('should return ' + len + span + ' before forceNow', function () { const parsed = dateMath.parse(nowEx, { forceNow: anchoredDate }).valueOf(); expect(parsed).to.eql(anchored.subtract(len, span).valueOf()); }); @@ -161,36 +161,36 @@ describe('dateMath', function() { }); }); - describe('addition', function() { + describe('addition', function () { let now; let anchored; - beforeEach(function() { + beforeEach(function () { clock = sinon.useFakeTimers(unix); now = moment(); anchored = moment(anchor); }); - afterEach(function() { + afterEach(function () { clock.restore(); }); - [5, 12, 247].forEach(len => { - spans.forEach(span => { + [5, 12, 247].forEach((len) => { + spans.forEach((span) => { const nowEx = `now+${len}${span}`; const thenEx = `${anchor}||+${len}${span}`; - it('should return ' + len + span + ' from now', function() { + it('should return ' + len + span + ' from now', function () { expect(dateMath.parse(nowEx).format(format)).to.eql(now.add(len, span).format(format)); }); - it('should return ' + len + span + ' after ' + anchor, function() { + it('should return ' + len + span + ' after ' + anchor, function () { expect(dateMath.parse(thenEx).format(format)).to.eql( anchored.add(len, span).format(format) ); }); - it('should return ' + len + span + ' after forceNow', function() { + it('should return ' + len + span + ' after forceNow', function () { expect(dateMath.parse(nowEx, { forceNow: anchoredDate }).valueOf()).to.eql( anchored.add(len, span).valueOf() ); @@ -199,40 +199,40 @@ describe('dateMath', function() { }); }); - describe('rounding', function() { + describe('rounding', function () { let now; let anchored; - beforeEach(function() { + beforeEach(function () { clock = sinon.useFakeTimers(unix); now = moment(); anchored = moment(anchor); }); - afterEach(function() { + afterEach(function () { clock.restore(); }); - spans.forEach(span => { - it(`should round now to the beginning of the ${span}`, function() { + spans.forEach((span) => { + it(`should round now to the beginning of the ${span}`, function () { expect(dateMath.parse('now/' + span).format(format)).to.eql( now.startOf(span).format(format) ); }); - it(`should round now to the beginning of forceNow's ${span}`, function() { + it(`should round now to the beginning of forceNow's ${span}`, function () { expect(dateMath.parse('now/' + span, { forceNow: anchoredDate }).valueOf()).to.eql( anchored.startOf(span).valueOf() ); }); - it(`should round now to the end of the ${span}`, function() { + it(`should round now to the end of the ${span}`, function () { expect(dateMath.parse('now/' + span, { roundUp: true }).format(format)).to.eql( now.endOf(span).format(format) ); }); - it(`should round now to the end of forceNow's ${span}`, function() { + it(`should round now to the end of forceNow's ${span}`, function () { expect( dateMath.parse('now/' + span, { roundUp: true, forceNow: anchoredDate }).valueOf() ).to.eql(anchored.endOf(span).valueOf()); @@ -240,61 +240,46 @@ describe('dateMath', function() { }); }); - describe('math and rounding', function() { + describe('math and rounding', function () { let now; let anchored; - beforeEach(function() { + beforeEach(function () { clock = sinon.useFakeTimers(unix); now = moment(); anchored = moment(anchor); }); - afterEach(function() { + afterEach(function () { clock.restore(); }); - it('should round to the nearest second with 0 value', function() { + it('should round to the nearest second with 0 value', function () { const val = dateMath.parse('now-0s/s').format(format); expect(val).to.eql(now.startOf('s').format(format)); }); - it('should subtract 17s, rounded to the nearest second', function() { + it('should subtract 17s, rounded to the nearest second', function () { const val = dateMath.parse('now-17s/s').format(format); - expect(val).to.eql( - now - .startOf('s') - .subtract(17, 's') - .format(format) - ); + expect(val).to.eql(now.startOf('s').subtract(17, 's').format(format)); }); - it('should add 555ms, rounded to the nearest millisecond', function() { + it('should add 555ms, rounded to the nearest millisecond', function () { const val = dateMath.parse('now+555ms/ms').format(format); - expect(val).to.eql( - now - .add(555, 'ms') - .startOf('ms') - .format(format) - ); + expect(val).to.eql(now.add(555, 'ms').startOf('ms').format(format)); }); - it('should subtract 555ms, rounded to the nearest second', function() { + it('should subtract 555ms, rounded to the nearest second', function () { const val = dateMath.parse('now-555ms/s').format(format); - expect(val).to.eql( - now - .subtract(555, 'ms') - .startOf('s') - .format(format) - ); + expect(val).to.eql(now.subtract(555, 'ms').startOf('s').format(format)); }); - it('should round weeks to Sunday by default', function() { + it('should round weeks to Sunday by default', function () { const val = dateMath.parse('now-1w/w'); expect(val.isoWeekday()).to.eql(7); }); - it('should round weeks based on the passed moment locale start of week setting', function() { + it('should round weeks based on the passed moment locale start of week setting', function () { const m = momentClone(); // Define a locale, that has Tuesday as beginning of the week m.defineLocale('x-test', { @@ -304,7 +289,7 @@ describe('dateMath', function() { expect(val.isoWeekday()).to.eql(2); }); - it('should round up weeks based on the passed moment locale start of week setting', function() { + it('should round up weeks based on the passed moment locale start of week setting', function () { const m = momentClone(); // Define a locale, that has Tuesday as beginning of the week m.defineLocale('x-test', { @@ -319,7 +304,7 @@ describe('dateMath', function() { expect(val.isoWeekday()).to.eql(3 - 1); }); - it('should round relative to forceNow', function() { + it('should round relative to forceNow', function () { const val = dateMath.parse('now-0s/s', { forceNow: anchoredDate }).valueOf(); expect(val).to.eql(anchored.startOf('s').valueOf()); }); @@ -329,15 +314,15 @@ describe('dateMath', function() { }); }); - describe('used momentjs instance', function() { - it('should use the default moment instance if parameter not specified', function() { + describe('used momentjs instance', function () { + it('should use the default moment instance if parameter not specified', function () { const momentSpy = sinon.spy(moment, 'isMoment'); dateMath.parse('now'); expect(momentSpy.called).to.be(true); momentSpy.restore(); }); - it('should not use default moment instance if parameter is specified', function() { + it('should not use default moment instance if parameter is specified', function () { const m = momentClone(); const momentSpy = sinon.spy(moment, 'isMoment'); const cloneSpy = sinon.spy(m, 'isMoment'); @@ -348,7 +333,7 @@ describe('dateMath', function() { cloneSpy.restore(); }); - it('should work with multiple different instances', function() { + it('should work with multiple different instances', function () { const m1 = momentClone(); const m2 = momentClone(); const m1Spy = sinon.spy(m1, 'isMoment'); @@ -365,7 +350,7 @@ describe('dateMath', function() { m2Spy.restore(); }); - it('should use global instance after passing an instance', function() { + it('should use global instance after passing an instance', function () { const m = momentClone(); const momentSpy = sinon.spy(moment, 'isMoment'); const cloneSpy = sinon.spy(m, 'isMoment'); @@ -382,12 +367,12 @@ describe('dateMath', function() { }); }); - describe('units', function() { - it('should have units descending for unitsDesc', function() { + describe('units', function () { + it('should have units descending for unitsDesc', function () { expect(dateMath.unitsDesc).to.eql(['y', 'M', 'w', 'd', 'h', 'm', 's', 'ms']); }); - it('should have units ascending for unitsAsc', function() { + it('should have units ascending for unitsAsc', function () { expect(dateMath.unitsAsc).to.eql(['ms', 's', 'm', 'h', 'd', 'w', 'M', 'y']); }); }); diff --git a/packages/elastic-datemath/src/index.js b/packages/elastic-datemath/src/index.js index afedad3ef6f72..52ce12ddf7027 100644 --- a/packages/elastic-datemath/src/index.js +++ b/packages/elastic-datemath/src/index.js @@ -34,9 +34,9 @@ const units = Object.keys(unitsMap).sort((a, b) => unitsMap[b].weight - unitsMap const unitsDesc = [...units]; const unitsAsc = [...units].reverse(); -const isDate = d => Object.prototype.toString.call(d) === '[object Date]'; +const isDate = (d) => Object.prototype.toString.call(d) === '[object Date]'; -const isValidDate = d => isDate(d) && !isNaN(d.valueOf()); +const isValidDate = (d) => isDate(d) && !isNaN(d.valueOf()); /* * This is a simplified version of elasticsearch's date parser. diff --git a/packages/eslint-config-kibana/package.json b/packages/eslint-config-kibana/package.json index 34b1b0fec376f..d9aef63c0115c 100644 --- a/packages/eslint-config-kibana/package.json +++ b/packages/eslint-config-kibana/package.json @@ -15,8 +15,8 @@ }, "homepage": "https://github.com/elastic/eslint-config-kibana#readme", "peerDependencies": { - "@typescript-eslint/eslint-plugin": "^2.15.0", - "@typescript-eslint/parser": "^2.15.0", + "@typescript-eslint/eslint-plugin": "^2.33.0", + "@typescript-eslint/parser": "^2.33.0", "babel-eslint": "^10.0.3", "eslint": "^6.8.0", "eslint-plugin-babel": "^5.3.0", diff --git a/packages/kbn-analytics/scripts/build.js b/packages/kbn-analytics/scripts/build.js index bb28c1460c9c2..448d1ca9332f2 100644 --- a/packages/kbn-analytics/scripts/build.js +++ b/packages/kbn-analytics/scripts/build.js @@ -31,7 +31,7 @@ const padRight = (width, str) => run( async ({ log, flags }) => { - await withProcRunner(log, async proc => { + await withProcRunner(log, async (proc) => { log.info('Deleting old output'); await del(BUILD_DIR); @@ -43,7 +43,7 @@ run( log.info(`Starting babel and typescript${flags.watch ? ' in watch mode' : ''}`); await Promise.all([ - ...['web', 'node'].map(subTask => + ...['web', 'node'].map((subTask) => proc.run(padRight(10, `babel:${subTask}`), { cmd: 'babel', args: [ diff --git a/packages/kbn-analytics/src/report.ts b/packages/kbn-analytics/src/report.ts index 58891e48aa3a6..d9303d2d3af1d 100644 --- a/packages/kbn-analytics/src/report.ts +++ b/packages/kbn-analytics/src/report.ts @@ -86,7 +86,7 @@ export class ReportManager { }; } assignReports(newMetrics: Metric | Metric[]) { - wrapArray(newMetrics).forEach(newMetric => this.assignReport(this.report, newMetric)); + wrapArray(newMetrics).forEach((newMetric) => this.assignReport(this.report, newMetric)); return { report: this.report }; } static createMetricKey(metric: Metric): string { diff --git a/packages/kbn-analytics/src/reporter.ts b/packages/kbn-analytics/src/reporter.ts index cbcdf6af63052..b20ddc0e58ba7 100644 --- a/packages/kbn-analytics/src/reporter.ts +++ b/packages/kbn-analytics/src/reporter.ts @@ -115,7 +115,7 @@ export class Reporter { eventNames: string | string[], count?: number ) => { - const metrics = wrapArray(eventNames).map(eventName => { + const metrics = wrapArray(eventNames).map((eventName) => { this.log(`${type} Metric -> (${appName}:${eventName}):`); const report = createUiStatsMetric({ type, appName, eventName, count }); this.log(report); diff --git a/packages/kbn-babel-code-parser/src/code_parser.js b/packages/kbn-babel-code-parser/src/code_parser.js index 9431eb639e2e5..91927780363ac 100644 --- a/packages/kbn-babel-code-parser/src/code_parser.js +++ b/packages/kbn-babel-code-parser/src/code_parser.js @@ -79,7 +79,7 @@ export async function parseEntries(cwd, entries, strategy, results, wasParsed = const sanitizedCwd = cwd || process.cwd(); // Test each entry against canRequire function - const entriesQueue = entries.map(entry => canRequire(entry)); + const entriesQueue = entries.map((entry) => canRequire(entry)); while (entriesQueue.length) { // Get the first element in the queue as diff --git a/packages/kbn-babel-code-parser/src/strategies.js b/packages/kbn-babel-code-parser/src/strategies.js index f116abde9e0e6..2369692ad434b 100644 --- a/packages/kbn-babel-code-parser/src/strategies.js +++ b/packages/kbn-babel-code-parser/src/strategies.js @@ -59,7 +59,7 @@ export async function dependenciesParseStrategy( // Get dependencies from a single file and filter // out node native modules from the result const dependencies = (await parseSingleFile(mainEntry, dependenciesVisitorsGenerator)).filter( - dep => !builtinModules.includes(dep) + (dep) => !builtinModules.includes(dep) ); // Return the list of all the new entries found into diff --git a/packages/kbn-babel-code-parser/src/strategies.test.js b/packages/kbn-babel-code-parser/src/strategies.test.js index dc2c599e81c39..e61c784cdcd54 100644 --- a/packages/kbn-babel-code-parser/src/strategies.test.js +++ b/packages/kbn-babel-code-parser/src/strategies.test.js @@ -84,7 +84,7 @@ describe('Code Parser Strategies', () => { cb(null, `require('./relative_dep')`); }); - canRequire.mockImplementation(entry => { + canRequire.mockImplementation((entry) => { if (entry === `${mockCwd}dep1/relative_dep`) { return `${entry}/index.js`; } diff --git a/packages/kbn-babel-code-parser/src/visitors.js b/packages/kbn-babel-code-parser/src/visitors.js index 30014941d2a27..b159848d424fa 100644 --- a/packages/kbn-babel-code-parser/src/visitors.js +++ b/packages/kbn-babel-code-parser/src/visitors.js @@ -21,7 +21,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) { // raw values on require + require.resolve CallExpression: ({ node }) => { // AST check for require expressions - const isRequire = node => { + const isRequire = (node) => { return matches({ callee: { type: 'Identifier', @@ -31,7 +31,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) { }; // AST check for require.resolve expressions - const isRequireResolve = node => { + const isRequireResolve = (node) => { return matches({ callee: { type: 'MemberExpression', @@ -66,7 +66,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) { // raw values on import ImportDeclaration: ({ node }) => { // AST check for supported import expressions - const isImport = node => { + const isImport = (node) => { return matches({ type: 'ImportDeclaration', source: { @@ -85,7 +85,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) { // raw values on export from ExportNamedDeclaration: ({ node }) => { // AST check for supported export from expressions - const isExportFrom = node => { + const isExportFrom = (node) => { return matches({ type: 'ExportNamedDeclaration', source: { @@ -104,7 +104,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) { // raw values on export * from ExportAllDeclaration: ({ node }) => { // AST check for supported export * from expressions - const isExportAllFrom = node => { + const isExportAllFrom = (node) => { return matches({ type: 'ExportAllDeclaration', source: { diff --git a/packages/kbn-babel-code-parser/src/visitors.test.js b/packages/kbn-babel-code-parser/src/visitors.test.js index 6a29d144a4dee..d2704fa9dfb72 100644 --- a/packages/kbn-babel-code-parser/src/visitors.test.js +++ b/packages/kbn-babel-code-parser/src/visitors.test.js @@ -21,7 +21,7 @@ import * as parser from '@babel/parser'; import traverse from '@babel/traverse'; import { dependenciesVisitorsGenerator } from './visitors'; -const visitorsApplier = code => { +const visitorsApplier = (code) => { const result = []; traverse( parser.parse(code, { diff --git a/packages/kbn-config-schema/src/errors/schema_error.test.ts b/packages/kbn-config-schema/src/errors/schema_error.test.ts index 0f632b781e9a6..d5cbb5a718a6a 100644 --- a/packages/kbn-config-schema/src/errors/schema_error.test.ts +++ b/packages/kbn-config-schema/src/errors/schema_error.test.ts @@ -26,8 +26,8 @@ import { SchemaError } from '.'; export const cleanStack = (stack: string) => stack .split('\n') - .filter(line => !line.includes('node_modules/') && !line.includes('internal/')) - .map(line => { + .filter((line) => !line.includes('node_modules/') && !line.includes('internal/')) + .map((line) => { const parts = /.*\((.*)\).?/.exec(line) || []; if (parts.length === 0) { diff --git a/packages/kbn-config-schema/src/errors/validation_error.ts b/packages/kbn-config-schema/src/errors/validation_error.ts index 2a4f887bc4349..0c86b61ba1e2a 100644 --- a/packages/kbn-config-schema/src/errors/validation_error.ts +++ b/packages/kbn-config-schema/src/errors/validation_error.ts @@ -26,12 +26,12 @@ export class ValidationError extends SchemaError { let message = error.message; if (error instanceof SchemaTypesError) { const indentLevel = level || 0; - const childErrorMessages = error.errors.map(childError => + const childErrorMessages = error.errors.map((childError) => ValidationError.extractMessage(childError, namespace, indentLevel + 1) ); message = `${message}\n${childErrorMessages - .map(childErrorMessage => `${' '.repeat(indentLevel)}- ${childErrorMessage}`) + .map((childErrorMessage) => `${' '.repeat(indentLevel)}- ${childErrorMessage}`) .join('\n')}`; } diff --git a/packages/kbn-config-schema/src/internals/index.ts b/packages/kbn-config-schema/src/internals/index.ts index f84e14d2f741d..f3756aaf90793 100644 --- a/packages/kbn-config-schema/src/internals/index.ts +++ b/packages/kbn-config-schema/src/internals/index.ts @@ -42,9 +42,7 @@ function isMap(o: any): o is Map { const anyCustomRule: Rules = { name: 'custom', params: { - validator: Joi.func() - .maxArity(1) - .required(), + validator: Joi.func().maxArity(1).required(), }, validate(params, value, state, options) { let validationResultMessage; diff --git a/packages/kbn-config-schema/src/typeguards/is_config_schema.test.ts b/packages/kbn-config-schema/src/typeguards/is_config_schema.test.ts index e0ef3835ca0a3..485251055d2b8 100644 --- a/packages/kbn-config-schema/src/typeguards/is_config_schema.test.ts +++ b/packages/kbn-config-schema/src/typeguards/is_config_schema.test.ts @@ -47,7 +47,7 @@ describe('isConfigSchema', () => { expect(isConfigSchema(undefined)).toBe(false); expect(isConfigSchema([1, 2, 3])).toBe(false); expect(isConfigSchema({ foo: 'bar' })).toBe(false); - expect(isConfigSchema(function() {})).toBe(false); + expect(isConfigSchema(function () {})).toBe(false); }); it('returns true as long as `__isKbnConfigSchemaType` is true', () => { diff --git a/packages/kbn-config-schema/src/types/array_type.ts b/packages/kbn-config-schema/src/types/array_type.ts index 0df0d44a37951..2fe1fa24222a1 100644 --- a/packages/kbn-config-schema/src/types/array_type.ts +++ b/packages/kbn-config-schema/src/types/array_type.ts @@ -28,10 +28,7 @@ export type ArrayOptions = TypeOptions & { export class ArrayType extends Type { constructor(type: Type, options: ArrayOptions = {}) { - let schema = internals - .array() - .items(type.getSchema().optional()) - .sparse(false); + let schema = internals.array().items(type.getSchema().optional()).sparse(false); if (options.minSize !== undefined) { schema = schema.min(options.minSize); diff --git a/packages/kbn-config-schema/src/types/string_type.ts b/packages/kbn-config-schema/src/types/string_type.ts index 7f49440b8d7e2..cb780bcbbc6bd 100644 --- a/packages/kbn-config-schema/src/types/string_type.ts +++ b/packages/kbn-config-schema/src/types/string_type.ts @@ -36,14 +36,14 @@ export class StringType extends Type { let schema = options.hostname === true ? internals.string().hostname() - : internals.any().custom(value => { + : internals.any().custom((value) => { if (typeof value !== 'string') { return `expected value of type [string] but got [${typeDetect(value)}]`; } }); if (options.minLength !== undefined) { - schema = schema.custom(value => { + schema = schema.custom((value) => { if (value.length < options.minLength!) { return `value has length [${value.length}] but it must have a minimum length of [${options.minLength}].`; } @@ -51,7 +51,7 @@ export class StringType extends Type { } if (options.maxLength !== undefined) { - schema = schema.custom(value => { + schema = schema.custom((value) => { if (value.length > options.maxLength!) { return `value has length [${value.length}] but it must have a maximum length of [${options.maxLength}].`; } diff --git a/packages/kbn-config-schema/src/types/union_type.ts b/packages/kbn-config-schema/src/types/union_type.ts index f4de829204e80..80fa8443e75d0 100644 --- a/packages/kbn-config-schema/src/types/union_type.ts +++ b/packages/kbn-config-schema/src/types/union_type.ts @@ -24,7 +24,7 @@ import { Type, TypeOptions } from './type'; export class UnionType>, T> extends Type { constructor(types: RTS, options?: TypeOptions) { - const schema = internals.alternatives(types.map(type => type.getSchema())); + const schema = internals.alternatives(types.map((type) => type.getSchema())); super(schema, options); } diff --git a/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts b/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts index 4e91289610432..b38a27fdc1b48 100644 --- a/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts +++ b/packages/kbn-dev-utils/src/ci_stats_reporter/ci_stats_reporter.ts @@ -145,7 +145,7 @@ export class CiStatsReporter { `failed to reach kibana-ci-stats service [reason=${reason}], retrying in ${attempt} seconds` ); - await new Promise(resolve => setTimeout(resolve, attempt * 1000)); + await new Promise((resolve) => setTimeout(resolve, attempt * 1000)); } } } diff --git a/packages/kbn-dev-utils/src/kbn_client/kbn_client_requester.ts b/packages/kbn-dev-utils/src/kbn_client/kbn_client_requester.ts index 4244006f4a3a3..ea4159de55749 100644 --- a/packages/kbn-dev-utils/src/kbn_client/kbn_client_requester.ts +++ b/packages/kbn-dev-utils/src/kbn_client/kbn_client_requester.ts @@ -66,7 +66,7 @@ export interface ReqOptions { } const delay = (ms: number) => - new Promise(resolve => { + new Promise((resolve) => { setTimeout(resolve, ms); }); diff --git a/packages/kbn-dev-utils/src/proc_runner/observe_readable.ts b/packages/kbn-dev-utils/src/proc_runner/observe_readable.ts index 1a292aff303af..4951bef91c446 100644 --- a/packages/kbn-dev-utils/src/proc_runner/observe_readable.ts +++ b/packages/kbn-dev-utils/src/proc_runner/observe_readable.ts @@ -33,7 +33,7 @@ export function observeReadable(readable: Readable): Rx.Observable { Rx.fromEvent(readable, 'error').pipe( first(), - mergeMap(err => Rx.throwError(err)) + mergeMap((err) => Rx.throwError(err)) ) ); } diff --git a/packages/kbn-dev-utils/src/proc_runner/proc.ts b/packages/kbn-dev-utils/src/proc_runner/proc.ts index c899293191f2a..59512cbb133b3 100644 --- a/packages/kbn-dev-utils/src/proc_runner/proc.ts +++ b/packages/kbn-dev-utils/src/proc_runner/proc.ts @@ -118,7 +118,7 @@ export function startProc(name: string, options: ProcOptions, log: ToolingLog) { // observe first error event Rx.fromEvent(childProcess, 'error').pipe( take(1), - mergeMap(err => Rx.throwError(err)) + mergeMap((err) => Rx.throwError(err)) ) ).pipe(share()); @@ -126,7 +126,7 @@ export function startProc(name: string, options: ProcOptions, log: ToolingLog) { observeLines(childProcess.stdout), observeLines(childProcess.stderr) ).pipe( - tap(line => log.write(` ${chalk.gray('proc')} [${chalk.gray(name)}] ${line}`)), + tap((line) => log.write(` ${chalk.gray('proc')} [${chalk.gray(name)}] ${line}`)), share() ); diff --git a/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts b/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts index 1759ca2840c5b..c879b4595b451 100644 --- a/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts +++ b/packages/kbn-dev-utils/src/proc_runner/proc_runner.ts @@ -50,7 +50,7 @@ export class ProcRunner { constructor(private log: ToolingLog) { this.signalUnsubscribe = exitHook(() => { - this.teardown().catch(error => { + this.teardown().catch((error) => { log.error(`ProcRunner teardown error: ${error.stack}`); }); }); @@ -105,9 +105,9 @@ export class ProcRunner { // wait for process to log matching line await Rx.race( proc.lines$.pipe( - filter(line => wait.test(line)), + filter((line) => wait.test(line)), first(), - catchError(err => { + catchError((err) => { if (err.name !== 'EmptyError') { throw createCliError(`[${name}] exited without matching pattern: ${wait}`); } else { @@ -159,7 +159,7 @@ export class ProcRunner { * @return {Promise} */ async waitForAllToStop() { - await Promise.all(this.procs.map(proc => proc.outcomePromise)); + await Promise.all(this.procs.map((proc) => proc.outcomePromise)); } /** @@ -181,19 +181,19 @@ export class ProcRunner { this.log.warning( '%d processes left running, stop them with procs.stop(name):', this.procs.length, - this.procs.map(proc => proc.name) + this.procs.map((proc) => proc.name) ); } await Promise.all( - this.procs.map(async proc => { + this.procs.map(async (proc) => { await proc.stop(signal === 'exit' ? 'SIGKILL' : signal); }) ); } private getProc(name: string) { - return this.procs.find(proc => { + return this.procs.find((proc) => { return proc.name === name; }); } @@ -209,14 +209,14 @@ export class ProcRunner { // tie into proc outcome$, remove from _procs on compete proc.outcome$.subscribe({ - next: code => { + next: (code) => { const duration = moment.duration(Date.now() - startMs); this.log.info('[%s] exited with %s after %s', name, code, duration.humanize()); }, complete: () => { remove(); }, - error: error => { + error: (error) => { if (this.closing) { this.log.error(error); } diff --git a/packages/kbn-dev-utils/src/proc_runner/with_proc_runner.test.ts b/packages/kbn-dev-utils/src/proc_runner/with_proc_runner.test.ts index e37bdcc40ca1c..89127069f4b8d 100644 --- a/packages/kbn-dev-utils/src/proc_runner/with_proc_runner.test.ts +++ b/packages/kbn-dev-utils/src/proc_runner/with_proc_runner.test.ts @@ -22,14 +22,14 @@ import { withProcRunner } from './with_proc_runner'; import { ProcRunner } from './proc_runner'; it('passes proc runner to a function', async () => { - await withProcRunner(new ToolingLog(), async proc => { + await withProcRunner(new ToolingLog(), async (proc) => { expect(proc).toBeInstanceOf(ProcRunner); }); }); it('calls procRunner.teardown() if function returns synchronously', async () => { let teardownSpy; - await withProcRunner(new ToolingLog(), async proc => { + await withProcRunner(new ToolingLog(), async (proc) => { teardownSpy = jest.spyOn(proc, 'teardown'); }); @@ -41,7 +41,7 @@ it('calls procRunner.teardown() if function throw synchronous error, and rejects let teardownSpy; await expect( - withProcRunner(new ToolingLog(), async proc => { + withProcRunner(new ToolingLog(), async (proc) => { teardownSpy = jest.spyOn(proc, 'teardown'); throw error; }) @@ -53,8 +53,8 @@ it('calls procRunner.teardown() if function throw synchronous error, and rejects it('waits for promise to resolve before tearing down proc', async () => { let teardownSpy; - await withProcRunner(new ToolingLog(), async proc => { - await new Promise(resolve => setTimeout(resolve, 500)); + await withProcRunner(new ToolingLog(), async (proc) => { + await new Promise((resolve) => setTimeout(resolve, 500)); teardownSpy = jest.spyOn(proc, 'teardown'); }); @@ -67,8 +67,8 @@ it('waits for promise to reject before tearing down proc and rejecting with the let teardownSpy; await expect( - withProcRunner(new ToolingLog(), async proc => { - await new Promise(resolve => setTimeout(resolve, 500)); + withProcRunner(new ToolingLog(), async (proc) => { + await new Promise((resolve) => setTimeout(resolve, 500)); teardownSpy = jest.spyOn(proc, 'teardown'); throw error; }) diff --git a/packages/kbn-dev-utils/src/run/fail.ts b/packages/kbn-dev-utils/src/run/fail.ts index a2501fc9513bf..f10ef1d52ef04 100644 --- a/packages/kbn-dev-utils/src/run/fail.ts +++ b/packages/kbn-dev-utils/src/run/fail.ts @@ -61,7 +61,7 @@ export function combineErrors(errors: Array) { .filter(isFailError) .reduce((acc, error) => Math.max(acc, error.exitCode), 1); - const showHelp = errors.some(error => isFailError(error) && error.showHelp); + const showHelp = errors.some((error) => isFailError(error) && error.showHelp); const message = errors.reduce((acc, error) => { if (isFailError(error)) { diff --git a/packages/kbn-dev-utils/src/run/run.ts b/packages/kbn-dev-utils/src/run/run.ts index 35477e988d837..894db0d3fdadb 100644 --- a/packages/kbn-dev-utils/src/run/run.ts +++ b/packages/kbn-dev-utils/src/run/run.ts @@ -62,7 +62,7 @@ export async function run(fn: RunFn, options: Options = {}) { writeTo: process.stdout, }); - process.on('unhandledRejection', error => { + process.on('unhandledRejection', (error) => { log.error('UNHANDLED PROMISE REJECTION'); log.error( error instanceof Error @@ -110,7 +110,7 @@ export async function run(fn: RunFn, options: Options = {}) { } try { - await withProcRunner(log, async procRunner => { + await withProcRunner(log, async (procRunner) => { await fn({ log, flags, diff --git a/packages/kbn-dev-utils/src/tooling_log/tooling_log.test.ts b/packages/kbn-dev-utils/src/tooling_log/tooling_log.test.ts index 21f02325cac66..4a0f5ca5f8a5f 100644 --- a/packages/kbn-dev-utils/src/tooling_log/tooling_log.test.ts +++ b/packages/kbn-dev-utils/src/tooling_log/tooling_log.test.ts @@ -80,29 +80,31 @@ describe('#indent()', () => { }); }); -(['verbose', 'debug', 'info', 'success', 'warning', 'error', 'write'] as const).forEach(method => { - describe(`#${method}()`, () => { - it(`sends a msg of type "${method}" to each writer with indent and arguments`, () => { - const log = new ToolingLog(); - const writeA = jest.fn(); - const writeB = jest.fn(); - - log.setWriters([{ write: writeA }, { write: writeB }]); - - if (method === 'error') { - const error = new Error('error message'); - error.stack = '... stack trace ...'; - log.error(error); - log.error('string message'); - } else { - log[method]('foo', 'bar', 'baz'); - } - - expect(writeA.mock.calls).toMatchSnapshot(); - expect(writeA.mock.calls).toEqual(writeB.mock.calls); +(['verbose', 'debug', 'info', 'success', 'warning', 'error', 'write'] as const).forEach( + (method) => { + describe(`#${method}()`, () => { + it(`sends a msg of type "${method}" to each writer with indent and arguments`, () => { + const log = new ToolingLog(); + const writeA = jest.fn(); + const writeB = jest.fn(); + + log.setWriters([{ write: writeA }, { write: writeB }]); + + if (method === 'error') { + const error = new Error('error message'); + error.stack = '... stack trace ...'; + log.error(error); + log.error('string message'); + } else { + log[method]('foo', 'bar', 'baz'); + } + + expect(writeA.mock.calls).toMatchSnapshot(); + expect(writeA.mock.calls).toEqual(writeB.mock.calls); + }); }); - }); -}); + } +); describe('#getWritten$()', () => { async function testWrittenMsgs(writers: Writer[]) { @@ -110,10 +112,7 @@ describe('#getWritten$()', () => { log.setWriters(writers); const done$ = new Rx.Subject(); - const promise = log - .getWritten$() - .pipe(takeUntil(done$), toArray()) - .toPromise(); + const promise = log.getWritten$().pipe(takeUntil(done$), toArray()).toPromise(); log.debug('foo'); log.info('bar'); diff --git a/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts b/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts index 46026bdc369d4..7e79077032156 100644 --- a/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts +++ b/packages/kbn-dev-utils/src/tooling_log/tooling_log_collecting_writer.ts @@ -26,7 +26,7 @@ export class ToolingLogCollectingWriter extends ToolingLogTextWriter { super({ level: 'verbose', writeTo: { - write: msg => { + write: (msg) => { // trim trailing new line this.messages.push(msg.slice(0, -1)); }, diff --git a/packages/kbn-es/src/artifact.js b/packages/kbn-es/src/artifact.js index 83dcd1cf36d2e..7d4c7a3fd2c33 100644 --- a/packages/kbn-es/src/artifact.js +++ b/packages/kbn-es/src/artifact.js @@ -60,7 +60,7 @@ async function retry(log, fn) { } log.warning('...failure, retrying in 5 seconds:', error.message); - await new Promise(resolve => setTimeout(resolve, 5000)); + await new Promise((resolve) => setTimeout(resolve, 5000)); log.info('...retrying'); return await doAttempt(attempt + 1); } @@ -120,7 +120,7 @@ async function getArtifactSpecForSnapshot(urlVersion, license, log) { const arch = process.arch === 'arm64' ? 'aarch64' : 'x86_64'; const archive = manifest.archives.find( - archive => + (archive) => archive.version === desiredVersion && archive.platform === platform && archive.license === desiredLicense && diff --git a/packages/kbn-es/src/artifact.test.js b/packages/kbn-es/src/artifact.test.js index 02e4d5318f63f..bbcf664006046 100644 --- a/packages/kbn-es/src/artifact.test.js +++ b/packages/kbn-es/src/artifact.test.js @@ -52,14 +52,14 @@ const createArchive = (params = {}) => { }; }; -const mockFetch = mock => +const mockFetch = (mock) => fetch.mockReturnValue(Promise.resolve(new Response(JSON.stringify(mock)))); const previousEnvVars = {}; const ENV_VARS_TO_RESET = ['ES_SNAPSHOT_MANIFEST', 'KBN_ES_SNAPSHOT_USE_UNVERIFIED']; beforeAll(() => { - ENV_VARS_TO_RESET.forEach(key => { + ENV_VARS_TO_RESET.forEach((key) => { if (key in process.env) { previousEnvVars[key] = process.env[key]; delete process.env[key]; @@ -68,7 +68,7 @@ beforeAll(() => { }); afterAll(() => { - Object.keys(previousEnvVars).forEach(key => { + Object.keys(previousEnvVars).forEach((key) => { process.env[key] = previousEnvVars[key]; }); }); diff --git a/packages/kbn-es/src/cli.js b/packages/kbn-es/src/cli.js index ed81e01ccf8ab..61019d27bf383 100644 --- a/packages/kbn-es/src/cli.js +++ b/packages/kbn-es/src/cli.js @@ -26,7 +26,7 @@ const { log } = require('./utils'); function help() { const availableCommands = Object.keys(commands).map( - name => `${name} - ${commands[name].description}` + (name) => `${name} - ${commands[name].description}` ); console.log(dedent` diff --git a/packages/kbn-es/src/cluster.js b/packages/kbn-es/src/cluster.js index ceb4a5b6aece1..68bcc37c65600 100644 --- a/packages/kbn-es/src/cluster.js +++ b/packages/kbn-es/src/cluster.js @@ -40,8 +40,8 @@ const readFile = util.promisify(fs.readFile); // listen to data on stream until map returns anything but undefined const first = (stream, map) => - new Promise(resolve => { - const onData = data => { + new Promise((resolve) => { + const onData = (data) => { const result = map(data); if (result !== undefined) { resolve(result); @@ -180,7 +180,7 @@ exports.Cluster = class Cluster { await Promise.race([ // wait for native realm to be setup and es to be started Promise.all([ - first(this._process.stdout, data => { + first(this._process.stdout, (data) => { if (/started/.test(data)) { return true; } @@ -207,7 +207,7 @@ exports.Cluster = class Cluster { this._exec(installPath, options); // log native realm setup errors so they aren't uncaught - this._nativeRealmSetup.catch(error => { + this._nativeRealmSetup.catch((error) => { this._log.error(error); this.stop(); }); @@ -287,7 +287,7 @@ exports.Cluster = class Cluster { }); // parse log output to find http port - const httpPort = first(this._process.stdout, data => { + const httpPort = first(this._process.stdout, (data) => { const match = data.toString('utf8').match(/HttpServer.+publish_address {[0-9.]+:([0-9]+)/); if (match) { @@ -296,7 +296,7 @@ exports.Cluster = class Cluster { }); // once the http port is available setup the native realm - this._nativeRealmSetup = httpPort.then(async port => { + this._nativeRealmSetup = httpPort.then(async (port) => { const caCert = await this._caCertPromise; const nativeRealm = new NativeRealm({ port, @@ -309,19 +309,19 @@ exports.Cluster = class Cluster { }); // parse and forward es stdout to the log - this._process.stdout.on('data', data => { + this._process.stdout.on('data', (data) => { const lines = parseEsLog(data.toString()); - lines.forEach(line => { + lines.forEach((line) => { this._log.info(line.formattedMessage); }); }); // forward es stderr to the log - this._process.stderr.on('data', data => this._log.error(chalk.red(data.toString()))); + this._process.stderr.on('data', (data) => this._log.error(chalk.red(data.toString()))); // observe the exit code of the process and reflect in _outcome promies - const exitCode = new Promise(resolve => this._process.once('exit', resolve)); - this._outcome = exitCode.then(code => { + const exitCode = new Promise((resolve) => this._process.once('exit', resolve)); + this._outcome = exitCode.then((code) => { if (this._stopCalled) { return; } diff --git a/packages/kbn-es/src/errors.js b/packages/kbn-es/src/errors.js index 099b5214bcbdb..7b39251f1327c 100644 --- a/packages/kbn-es/src/errors.js +++ b/packages/kbn-es/src/errors.js @@ -17,12 +17,12 @@ * under the License. */ -exports.createCliError = function(message) { +exports.createCliError = function (message) { const error = new Error(message); error.isCliError = true; return error; }; -exports.isCliError = function(error) { +exports.isCliError = function (error) { return error && error.isCliError; }; diff --git a/packages/kbn-es/src/install/source.js b/packages/kbn-es/src/install/source.js index e78e9f1ff4b25..bfeff736f8cdc 100644 --- a/packages/kbn-es/src/install/source.js +++ b/packages/kbn-es/src/install/source.js @@ -99,15 +99,11 @@ async function sourceInfo(cwd, license, log = defaultLog) { etag.update(sha); // for changed files, use last modified times in hash calculation - status.files.forEach(file => { + status.files.forEach((file) => { etag.update(fs.statSync(path.join(cwd, file.path)).mtime.toString()); }); - const cwdHash = crypto - .createHash('md5') - .update(cwd) - .digest('hex') - .substr(0, 8); + const cwdHash = crypto.createHash('md5').update(cwd).digest('hex').substr(0, 8); const basename = `${branch}-${task}-${cwdHash}`; const filename = `${basename}.${ext}`; diff --git a/packages/kbn-es/src/integration_tests/__fixtures__/es_bin.js b/packages/kbn-es/src/integration_tests/__fixtures__/es_bin.js index d374abe5db068..b860664443d1a 100644 --- a/packages/kbn-es/src/integration_tests/__fixtures__/es_bin.js +++ b/packages/kbn-es/src/integration_tests/__fixtures__/es_bin.js @@ -71,7 +71,7 @@ const delayServerClose = () => { server.on('request', delayServerClose); server.on('listening', delayServerClose); -server.listen(0, '127.0.0.1', function() { +server.listen(0, '127.0.0.1', function () { const { port, address: hostname } = server.address(); serverUrl = new URL( formatUrl({ diff --git a/packages/kbn-es/src/integration_tests/cluster.test.js b/packages/kbn-es/src/integration_tests/cluster.test.js index dfbc04477bd40..0ae0ac0aac27a 100644 --- a/packages/kbn-es/src/integration_tests/cluster.test.js +++ b/packages/kbn-es/src/integration_tests/cluster.test.js @@ -37,7 +37,7 @@ jest.mock('../utils/extract_config_files', () => ({ const log = new ToolingLog(); function sleep(ms) { - return new Promise(resolve => setTimeout(resolve, ms)); + return new Promise((resolve) => setTimeout(resolve, ms)); } async function ensureNoResolve(promise) { @@ -77,7 +77,7 @@ function mockEsBin({ exitCode, start }) { beforeEach(() => { jest.resetAllMocks(); - extractConfigFiles.mockImplementation(config => config); + extractConfigFiles.mockImplementation((config) => config); }); describe('#installSource()', () => { @@ -85,7 +85,7 @@ describe('#installSource()', () => { let resolveInstallSource; installSource.mockImplementationOnce( () => - new Promise(resolve => { + new Promise((resolve) => { resolveInstallSource = () => { resolve({ installPath: 'foo' }); }; @@ -124,7 +124,7 @@ describe('#installSnapshot()', () => { let resolveInstallSnapshot; installSnapshot.mockImplementationOnce( () => - new Promise(resolve => { + new Promise((resolve) => { resolveInstallSnapshot = () => { resolve({ installPath: 'foo' }); }; @@ -163,7 +163,7 @@ describe('#installArchive(path)', () => { let resolveInstallArchive; installArchive.mockImplementationOnce( () => - new Promise(resolve => { + new Promise((resolve) => { resolveInstallArchive = () => { resolve({ installPath: 'foo' }); }; diff --git a/packages/kbn-es/src/settings.ts b/packages/kbn-es/src/settings.ts index 58eedff207b4d..bf7160b9fee7b 100644 --- a/packages/kbn-es/src/settings.ts +++ b/packages/kbn-es/src/settings.ts @@ -25,7 +25,7 @@ const SECURE_SETTINGS_LIST = [ ]; function isSecureSetting(settingName: string) { - return SECURE_SETTINGS_LIST.some(secureSettingNameRegex => + return SECURE_SETTINGS_LIST.some((secureSettingNameRegex) => secureSettingNameRegex.test(settingName) ); } diff --git a/packages/kbn-es/src/utils/build_snapshot.js b/packages/kbn-es/src/utils/build_snapshot.js index 3173df700e303..ce0dc88ac1d7c 100644 --- a/packages/kbn-es/src/utils/build_snapshot.js +++ b/packages/kbn-es/src/utils/build_snapshot.js @@ -25,7 +25,7 @@ const { createCliError } = require('../errors'); const { findMostRecentlyChanged } = require('../utils'); const { GRADLE_BIN } = require('../paths'); -const onceEvent = (emitter, event) => new Promise(resolve => emitter.once(event, resolve)); +const onceEvent = (emitter, event) => new Promise((resolve) => emitter.once(event, resolve)); /** * Creates archive from source @@ -59,13 +59,13 @@ exports.buildSnapshot = async ({ license, sourcePath, log, platform = os.platfor const stdout = readline.createInterface({ input: build.stdout }); const stderr = readline.createInterface({ input: build.stderr }); - stdout.on('line', line => log.debug(line)); - stderr.on('line', line => log.error(line)); + stdout.on('line', (line) => log.debug(line)); + stderr.on('line', (line) => log.error(line)); const [exitCode] = await Promise.all([ Promise.race([ onceEvent(build, 'exit'), - onceEvent(build, 'error').then(error => { + onceEvent(build, 'error').then((error) => { throw createCliError(`Error spawning gradle: ${error.message}`); }), ]), diff --git a/packages/kbn-es/src/utils/decompress.js b/packages/kbn-es/src/utils/decompress.js index b4299594c5062..1fdb647b1dc0d 100644 --- a/packages/kbn-es/src/utils/decompress.js +++ b/packages/kbn-es/src/utils/decompress.js @@ -50,15 +50,12 @@ function decompressZip(input, output) { resolve(); }); - zipfile.on('error', err => { + zipfile.on('error', (err) => { reject(err); }); - zipfile.on('entry', entry => { - const zipPath = entry.fileName - .split(/\/|\\/) - .slice(1) - .join(path.sep); + zipfile.on('entry', (entry) => { + const zipPath = entry.fileName.split(/\/|\\/).slice(1).join(path.sep); const fileName = path.resolve(output, zipPath); if (/\/$/.test(entry.fileName)) { @@ -83,7 +80,7 @@ function decompressZip(input, output) { }); } -exports.decompress = async function(input, output) { +exports.decompress = async function (input, output) { const ext = path.extname(input); switch (path.extname(input)) { diff --git a/packages/kbn-es/src/utils/extract_config_files.js b/packages/kbn-es/src/utils/extract_config_files.js index a8a44a149e9b3..d535528cef239 100644 --- a/packages/kbn-es/src/utils/extract_config_files.js +++ b/packages/kbn-es/src/utils/extract_config_files.js @@ -32,7 +32,7 @@ exports.extractConfigFiles = function extractConfigFiles(config, dest, options = const originalConfig = typeof config === 'string' ? [config] : config; const localConfig = []; - originalConfig.forEach(prop => { + originalConfig.forEach((prop) => { const [key, value] = prop.split('='); if (isFile(value)) { diff --git a/packages/kbn-es/src/utils/find_most_recently_changed.js b/packages/kbn-es/src/utils/find_most_recently_changed.js index 0fcd87978c357..3ba8865e88d92 100644 --- a/packages/kbn-es/src/utils/find_most_recently_changed.js +++ b/packages/kbn-es/src/utils/find_most_recently_changed.js @@ -32,7 +32,7 @@ exports.findMostRecentlyChanged = function findMostRecentlyChanged(pattern) { throw new TypeError(`Pattern must be absolute, got ${pattern}`); } - const ctime = path => fs.statSync(path).ctime.getTime(); + const ctime = (path) => fs.statSync(path).ctime.getTime(); return glob .sync(pattern) diff --git a/packages/kbn-es/src/utils/find_most_recently_changed.test.js b/packages/kbn-es/src/utils/find_most_recently_changed.test.js index ed90576990c72..ee032686bc621 100644 --- a/packages/kbn-es/src/utils/find_most_recently_changed.test.js +++ b/packages/kbn-es/src/utils/find_most_recently_changed.test.js @@ -18,7 +18,7 @@ */ jest.mock('fs', () => ({ - statSync: jest.fn().mockImplementation(path => { + statSync: jest.fn().mockImplementation((path) => { if (path.includes('oldest')) { return { ctime: new Date(2018, 2, 1), diff --git a/packages/kbn-es/src/utils/native_realm.js b/packages/kbn-es/src/utils/native_realm.js index f3f5f7bbdf431..573944a8cc6d0 100644 --- a/packages/kbn-es/src/utils/native_realm.js +++ b/packages/kbn-es/src/utils/native_realm.js @@ -77,7 +77,7 @@ exports.NativeRealm = class NativeRealm { const reservedUsers = await this.getReservedUsers(); await Promise.all( - reservedUsers.map(async user => { + reservedUsers.map(async (user) => { await this.setPassword(user, options[`password.${user}`]); }) ); @@ -87,7 +87,7 @@ exports.NativeRealm = class NativeRealm { return await this._autoRetry(async () => { const resp = await this._client.security.getUser(); const usernames = Object.keys(resp.body).filter( - user => resp.body[user].metadata._reserved === true + (user) => resp.body[user].metadata._reserved === true ); if (!usernames?.length) { @@ -125,7 +125,7 @@ exports.NativeRealm = class NativeRealm { const sec = 1.5 * attempt; this._log.warning(`assuming ES isn't initialized completely, trying again in ${sec} seconds`); - await new Promise(resolve => setTimeout(resolve, sec * 1000)); + await new Promise((resolve) => setTimeout(resolve, sec * 1000)); return await this._autoRetry(fn, attempt + 1); } } diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_is_path_request.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_is_path_request.js index e26660f76a550..8472aaf0fc029 100644 --- a/packages/kbn-eslint-import-resolver-kibana/lib/get_is_path_request.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_is_path_request.js @@ -31,6 +31,6 @@ // const PATH_IMPORT_RE = /^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/; -exports.getIsPathRequest = function(source) { +exports.getIsPathRequest = function (source) { return PATH_IMPORT_RE.test(source); }; diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_kibana_path.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_kibana_path.js index 93c0f907d628d..3856281d15320 100755 --- a/packages/kbn-eslint-import-resolver-kibana/lib/get_kibana_path.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_kibana_path.js @@ -26,7 +26,7 @@ const DEFAULT_PLUGIN_PATH = '../..'; /* * Resolves the path to Kibana, either from default setting or config */ -exports.getKibanaPath = function(config, projectRoot) { +exports.getKibanaPath = function (config, projectRoot) { const inConfig = config != null && config.kibanaPath; // We only allow `.` in the config as we need it for Kibana itself diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_path_type.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_path_type.js index 3fb5b5dab7776..445a3cad385fc 100644 --- a/packages/kbn-eslint-import-resolver-kibana/lib/get_path_type.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_path_type.js @@ -49,10 +49,10 @@ function getPathType(path) { return type; } -exports.isDirectory = function(path) { +exports.isDirectory = function (path) { return getPathType(path) === DIR; }; -exports.isFile = function(path) { +exports.isFile = function (path) { return getPathType(path) === FILE; }; diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_plugins.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_plugins.js index 319b959883a8a..84481783b22fc 100755 --- a/packages/kbn-eslint-import-resolver-kibana/lib/get_plugins.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_plugins.js @@ -21,8 +21,8 @@ const { dirname, resolve } = require('path'); const glob = require('glob-all'); -exports.getPlugins = function(config, kibanaPath, projectRoot) { - const resolveToRoot = path => resolve(projectRoot, path); +exports.getPlugins = function (config, kibanaPath, projectRoot) { + const resolveToRoot = (path) => resolve(projectRoot, path); const pluginDirs = [ ...(config.pluginDirs || []).map(resolveToRoot), @@ -39,11 +39,11 @@ exports.getPlugins = function(config, kibanaPath, projectRoot) { ]; const globPatterns = [ - ...pluginDirs.map(dir => resolve(dir, '*/package.json')), - ...pluginPaths.map(path => resolve(path, 'package.json')), + ...pluginDirs.map((dir) => resolve(dir, '*/package.json')), + ...pluginPaths.map((path) => resolve(path, 'package.json')), ]; - const pluginsFromMap = Object.keys(config.pluginMap || {}).map(name => { + const pluginsFromMap = Object.keys(config.pluginMap || {}).map((name) => { const directory = resolveToRoot(config.pluginMap[name]); return { name, @@ -53,7 +53,7 @@ exports.getPlugins = function(config, kibanaPath, projectRoot) { }); return pluginsFromMap.concat( - glob.sync(globPatterns).map(pkgJsonPath => { + glob.sync(globPatterns).map((pkgJsonPath) => { const path = dirname(pkgJsonPath); const pkg = require(pkgJsonPath); // eslint-disable-line import/no-dynamic-require return { diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_project_root.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_project_root.js index 5c70d63bf147b..fed40298d513f 100755 --- a/packages/kbn-eslint-import-resolver-kibana/lib/get_project_root.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_project_root.js @@ -55,7 +55,7 @@ function getRootPackageDir(dirRoot, dir, rootPackageName) { } } -exports.getProjectRoot = function(file, config) { +exports.getProjectRoot = function (file, config) { const { root, dir } = parse(resolve(file)); const { rootPackageName } = config; diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js b/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js index da0b799b338ed..6cb2f3d2901d3 100755 --- a/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/get_webpack_config.js @@ -22,7 +22,7 @@ const { resolve } = require('path'); const { debug } = require('./debug'); const { getPlugins } = require('./get_plugins'); -exports.getWebpackConfig = function(kibanaPath, projectRoot, config) { +exports.getWebpackConfig = function (kibanaPath, projectRoot, config) { const fromKibana = (...path) => resolve(kibanaPath, ...path); const alias = { @@ -39,7 +39,7 @@ exports.getWebpackConfig = function(kibanaPath, projectRoot, config) { test_utils: fromKibana('src/test_utils/public'), }; - getPlugins(config, kibanaPath, projectRoot).forEach(plugin => { + getPlugins(config, kibanaPath, projectRoot).forEach((plugin) => { alias[`plugins/${plugin.name}`] = plugin.publicDirectory; }); diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/is_probably_webpack_shim.js b/packages/kbn-eslint-import-resolver-kibana/lib/is_probably_webpack_shim.js index 2af7d1c2f5349..9eb3234fca7b4 100644 --- a/packages/kbn-eslint-import-resolver-kibana/lib/is_probably_webpack_shim.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/is_probably_webpack_shim.js @@ -32,8 +32,8 @@ function readShimNames(shimDirectory) { } return readdirSync(shimDirectory) - .filter(name => !name.startsWith('.') && !name.startsWith('_')) - .map(name => (name.endsWith('.js') ? name.slice(0, -3) : name)); + .filter((name) => !name.startsWith('.') && !name.startsWith('_')) + .map((name) => (name.endsWith('.js') ? name.slice(0, -3) : name)); } function findRelativeWebpackShims(directory) { @@ -53,7 +53,7 @@ function findRelativeWebpackShims(directory) { return allShims; } -exports.isProbablyWebpackShim = function(source, file) { +exports.isProbablyWebpackShim = function (source, file) { const shims = findRelativeWebpackShims(dirname(file)); - return shims.some(shim => source === shim || source.startsWith(shim + '/')); + return shims.some((shim) => source === shim || source.startsWith(shim + '/')); }; diff --git a/packages/kbn-eslint-import-resolver-kibana/lib/resolve_webpack_alias.js b/packages/kbn-eslint-import-resolver-kibana/lib/resolve_webpack_alias.js index a7bb391f9b1c6..00b07f469bd9c 100644 --- a/packages/kbn-eslint-import-resolver-kibana/lib/resolve_webpack_alias.js +++ b/packages/kbn-eslint-import-resolver-kibana/lib/resolve_webpack_alias.js @@ -25,7 +25,7 @@ * @param {Array<[alias,path]>} aliasEntries * @return {string|undefined} */ -exports.resolveWebpackAlias = function(source, aliasEntries) { +exports.resolveWebpackAlias = function (source, aliasEntries) { for (const [alias, path] of aliasEntries) { if (source === alias) { return path; diff --git a/packages/kbn-eslint-plugin-eslint/lib.js b/packages/kbn-eslint-plugin-eslint/lib.js index 56684746c479f..a7431be00e054 100644 --- a/packages/kbn-eslint-plugin-eslint/lib.js +++ b/packages/kbn-eslint-plugin-eslint/lib.js @@ -31,7 +31,7 @@ exports.normalizeWhitespace = function normalizeWhitespace(string) { return string.replace(/\s+/g, ' '); }; -exports.init = function(context, program, initStep) { +exports.init = function (context, program, initStep) { try { return initStep(); } catch (error) { diff --git a/packages/kbn-eslint-plugin-eslint/rules/disallow_license_headers.js b/packages/kbn-eslint-plugin-eslint/rules/disallow_license_headers.js index 0567307d18968..6b5564f1f8004 100644 --- a/packages/kbn-eslint-plugin-eslint/rules/disallow_license_headers.js +++ b/packages/kbn-eslint-plugin-eslint/rules/disallow_license_headers.js @@ -39,7 +39,7 @@ module.exports = { }, ], }, - create: context => { + create: (context) => { return { Program(program) { const licenses = init(context, program, () => { @@ -70,8 +70,8 @@ module.exports = { sourceCode .getAllComments() - .filter(node => licenses.includes(normalizeWhitespace(node.value))) - .forEach(node => { + .filter((node) => licenses.includes(normalizeWhitespace(node.value))) + .forEach((node) => { context.report({ node, message: 'This license header is not allowed in this file.', diff --git a/packages/kbn-eslint-plugin-eslint/rules/module_migration.js b/packages/kbn-eslint-plugin-eslint/rules/module_migration.js index 8119d338ee536..6027a939f1a65 100644 --- a/packages/kbn-eslint-plugin-eslint/rules/module_migration.js +++ b/packages/kbn-eslint-plugin-eslint/rules/module_migration.js @@ -22,7 +22,7 @@ const KIBANA_ROOT = path.resolve(__dirname, '../../..'); function checkModuleNameNode(context, mappings, node) { const mapping = mappings.find( - mapping => mapping.from === node.value || node.value.startsWith(`${mapping.from}/`) + (mapping) => mapping.from === node.value || node.value.startsWith(`${mapping.from}/`) ); if (!mapping) { @@ -105,7 +105,7 @@ module.exports = { }, ], }, - create: context => { + create: (context) => { const mappings = context.options[0]; return { diff --git a/packages/kbn-eslint-plugin-eslint/rules/require_license_header.js b/packages/kbn-eslint-plugin-eslint/rules/require_license_header.js index f3c9fcef1985e..915ac3ed7922e 100644 --- a/packages/kbn-eslint-plugin-eslint/rules/require_license_header.js +++ b/packages/kbn-eslint-plugin-eslint/rules/require_license_header.js @@ -40,10 +40,10 @@ module.exports = { }, ], }, - create: context => { + create: (context) => { return { Program(program) { - const license = init(context, program, function() { + const license = init(context, program, function () { const options = context.options[0] || {}; const license = options.license; @@ -69,7 +69,7 @@ module.exports = { const sourceCode = context.getSourceCode(); const comment = sourceCode .getAllComments() - .find(node => normalizeWhitespace(node.value) === license.nodeValue); + .find((node) => normalizeWhitespace(node.value) === license.nodeValue); // no licence comment if (!comment) { diff --git a/packages/kbn-i18n/scripts/build.js b/packages/kbn-i18n/scripts/build.js index 0764451c74575..62e1a35f00399 100644 --- a/packages/kbn-i18n/scripts/build.js +++ b/packages/kbn-i18n/scripts/build.js @@ -31,7 +31,7 @@ const padRight = (width, str) => run( async ({ log, flags }) => { - await withProcRunner(log, async proc => { + await withProcRunner(log, async (proc) => { log.info('Deleting old output'); await del(BUILD_DIR); @@ -43,7 +43,7 @@ run( log.info(`Starting babel and typescript${flags.watch ? ' in watch mode' : ''}`); await Promise.all([ - ...['web', 'node'].map(subTask => + ...['web', 'node'].map((subTask) => proc.run(padRight(10, `babel:${subTask}`), { cmd: 'babel', args: [ diff --git a/packages/kbn-i18n/src/angular/filter.test.ts b/packages/kbn-i18n/src/angular/filter.test.ts index 78bc279689357..5336926a64139 100644 --- a/packages/kbn-i18n/src/angular/filter.test.ts +++ b/packages/kbn-i18n/src/angular/filter.test.ts @@ -28,17 +28,14 @@ import * as i18n from '../core/i18n'; import { i18nFilter as angularI18nFilter } from './filter'; import { I18nProvider, I18nServiceType } from './provider'; -angular - .module('app', []) - .provider('i18n', I18nProvider) - .filter('i18n', angularI18nFilter); +angular.module('app', []).provider('i18n', I18nProvider).filter('i18n', angularI18nFilter); describe('i18nFilter', () => { let filter: I18nServiceType; beforeEach(angular.mock.module('app')); beforeEach( - angular.mock.inject(i18nFilter => { + angular.mock.inject((i18nFilter) => { filter = i18nFilter; }) ); diff --git a/packages/kbn-i18n/src/loader.ts b/packages/kbn-i18n/src/loader.ts index 21f540f588f46..8231ed36928d8 100644 --- a/packages/kbn-i18n/src/loader.ts +++ b/packages/kbn-i18n/src/loader.ts @@ -127,7 +127,7 @@ export function getRegisteredLocales() { */ export async function getTranslationsByLocale(locale: string): Promise { const files = translationsRegistry[locale] || []; - const notLoadedFiles = files.filter(file => !loadedFiles[file]); + const notLoadedFiles = files.filter((file) => !loadedFiles[file]); if (notLoadedFiles.length) { await loadAndCacheFiles(notLoadedFiles); diff --git a/packages/kbn-i18n/src/react/pseudo_locale_wrapper.tsx b/packages/kbn-i18n/src/react/pseudo_locale_wrapper.tsx index db879fbae6ff1..3271ae7c98d2f 100644 --- a/packages/kbn-i18n/src/react/pseudo_locale_wrapper.tsx +++ b/packages/kbn-i18n/src/react/pseudo_locale_wrapper.tsx @@ -37,7 +37,7 @@ function translateFormattedMessageUsingPseudoLocale(message: string) { if (formattedMessageDelimiter !== null) { return message .split(formattedMessageDelimiter[0]) - .map(part => (part.startsWith('ELEMENT-') ? part : translateUsingPseudoLocale(part))) + .map((part) => (part.startsWith('ELEMENT-') ? part : translateUsingPseudoLocale(part))) .join(formattedMessageDelimiter[0]); } diff --git a/packages/kbn-interpreter/src/common/lib/arg.js b/packages/kbn-interpreter/src/common/lib/arg.js index 0aa2b52e35acb..2ab74e5035866 100644 --- a/packages/kbn-interpreter/src/common/lib/arg.js +++ b/packages/kbn-interpreter/src/common/lib/arg.js @@ -30,7 +30,7 @@ export function Arg(config) { this.multi = config.multi == null ? false : config.multi; this.resolve = config.resolve == null ? true : config.resolve; this.options = config.options || []; - this.accepts = type => { + this.accepts = (type) => { if (!this.types.length) return true; return includes(config.types, type); }; diff --git a/packages/kbn-interpreter/src/common/lib/ast.js b/packages/kbn-interpreter/src/common/lib/ast.js index 61cfe94ac955c..98123f475cd92 100644 --- a/packages/kbn-interpreter/src/common/lib/ast.js +++ b/packages/kbn-interpreter/src/common/lib/ast.js @@ -55,7 +55,7 @@ function getExpressionArgs(block, level = 0) { const argKeys = Object.keys(args); const MAX_LINE_LENGTH = 80; // length before wrapping arguments - return argKeys.map(argKey => + return argKeys.map((argKey) => args[argKey].reduce((acc, arg) => { const argString = getArgumentString(arg, argKey, level); const lineLength = acc.split('\n').pop().length; @@ -86,7 +86,7 @@ function getExpression(chain, level = 0) { const separator = level > 0 ? ' | ' : '\n| '; return chain - .map(chainObj => { + .map((chainObj) => { const type = getType(chainObj); if (type === 'function') { diff --git a/packages/kbn-interpreter/src/common/lib/fn.js b/packages/kbn-interpreter/src/common/lib/fn.js index c6b2fcbe67799..5561c08f9c7d0 100644 --- a/packages/kbn-interpreter/src/common/lib/fn.js +++ b/packages/kbn-interpreter/src/common/lib/fn.js @@ -39,7 +39,7 @@ export function Fn(config) { this.context = config.context || {}; - this.accepts = type => { + this.accepts = (type) => { if (!this.context.types) return true; // If you don't tell us about context, we'll assume you don't care what you get return includes(this.context.types, type); // Otherwise, check it }; diff --git a/packages/kbn-interpreter/src/common/lib/get_by_alias.js b/packages/kbn-interpreter/src/common/lib/get_by_alias.js index d7bb1bbf9e79d..04c435216b946 100644 --- a/packages/kbn-interpreter/src/common/lib/get_by_alias.js +++ b/packages/kbn-interpreter/src/common/lib/get_by_alias.js @@ -26,7 +26,7 @@ export function getByAlias(specs, name) { const lowerCaseName = name.toLowerCase(); return Object.values(specs).find(({ name, aliases }) => { if (name.toLowerCase() === lowerCaseName) return true; - return (aliases || []).some(alias => { + return (aliases || []).some((alias) => { return alias.toLowerCase() === lowerCaseName; }); }); diff --git a/packages/kbn-interpreter/src/common/lib/registry.js b/packages/kbn-interpreter/src/common/lib/registry.js index 3b22704b9e9c8..25b122f400711 100644 --- a/packages/kbn-interpreter/src/common/lib/registry.js +++ b/packages/kbn-interpreter/src/common/lib/registry.js @@ -48,7 +48,7 @@ export class Registry { } toArray() { - return Object.keys(this._indexed).map(key => this.get(key)); + return Object.keys(this._indexed).map((key) => this.get(key)); } get(name) { diff --git a/packages/kbn-interpreter/src/common/registries.js b/packages/kbn-interpreter/src/common/registries.js index 2c68f5647ca73..9d73433bb2d26 100644 --- a/packages/kbn-interpreter/src/common/registries.js +++ b/packages/kbn-interpreter/src/common/registries.js @@ -24,7 +24,7 @@ * @param {*} newRegistries - The new set of registries */ export function addRegistries(registries, newRegistries) { - Object.keys(newRegistries).forEach(registryName => { + Object.keys(newRegistries).forEach((registryName) => { if (registries[registryName]) { throw new Error(`There is already a registry named "${registryName}".`); } @@ -41,7 +41,7 @@ export function addRegistries(registries, newRegistries) { * @param {*} specs - The specs to be regsitered (e.g. { types: [], browserFunctions: [] }) */ export function register(registries, specs) { - Object.keys(specs).forEach(registryName => { + Object.keys(specs).forEach((registryName) => { if (!registries[registryName]) { throw new Error(`There is no registry named "${registryName}".`); } @@ -49,7 +49,7 @@ export function register(registries, specs) { if (!registries[registryName].register) { throw new Error(`Registry "${registryName}" must have a register function.`); } - specs[registryName].forEach(f => registries[registryName].register(f)); + specs[registryName].forEach((f) => registries[registryName].register(f)); }); return registries; diff --git a/packages/kbn-interpreter/tasks/build/cli.js b/packages/kbn-interpreter/tasks/build/cli.js index 86df21ee566ac..970e0f8847882 100644 --- a/packages/kbn-interpreter/tasks/build/cli.js +++ b/packages/kbn-interpreter/tasks/build/cli.js @@ -56,7 +56,7 @@ if (flags.help) { process.exit(); } -withProcRunner(log, async proc => { +withProcRunner(log, async (proc) => { log.info('Deleting old output'); await del(BUILD_DIR); @@ -87,7 +87,7 @@ withProcRunner(log, async proc => { ]); log.success('Complete'); -}).catch(error => { +}).catch((error) => { log.error(error); process.exit(1); }); diff --git a/packages/kbn-optimizer/src/cli.ts b/packages/kbn-optimizer/src/cli.ts index a2fbe969e34d8..0916f12a7110d 100644 --- a/packages/kbn-optimizer/src/cli.ts +++ b/packages/kbn-optimizer/src/cli.ts @@ -77,8 +77,8 @@ run( const extraPluginScanDirs = ([] as string[]) .concat((flags['scan-dir'] as string | string[]) || []) - .map(p => Path.resolve(p)); - if (!extraPluginScanDirs.every(s => typeof s === 'string')) { + .map((p) => Path.resolve(p)); + if (!extraPluginScanDirs.every((s) => typeof s === 'string')) { throw createFlagError('expected --scan-dir to be a string'); } diff --git a/packages/kbn-optimizer/src/common/array_helpers.test.ts b/packages/kbn-optimizer/src/common/array_helpers.test.ts index 9d45217486ee8..ab5f4b694333e 100644 --- a/packages/kbn-optimizer/src/common/array_helpers.test.ts +++ b/packages/kbn-optimizer/src/common/array_helpers.test.ts @@ -53,11 +53,7 @@ describe('ascending/descending', () => { ].sort(() => 0.5 - Math.random()); it('sorts items using getters', () => { - expect( - Array.from(values) - .sort(ascending(a, b, c)) - .map(print) - ).toMatchInlineSnapshot(` + expect(Array.from(values).sort(ascending(a, b, c)).map(print)).toMatchInlineSnapshot(` Array [ "1/2/3", "3/2/1", @@ -81,11 +77,7 @@ describe('ascending/descending', () => { ] `); - expect( - Array.from(values) - .sort(descending(a, b, c)) - .map(print) - ).toMatchInlineSnapshot(` + expect(Array.from(values).sort(descending(a, b, c)).map(print)).toMatchInlineSnapshot(` Array [ "9/9/9", "8/foo/8", diff --git a/packages/kbn-optimizer/src/common/bundle.ts b/packages/kbn-optimizer/src/common/bundle.ts index 7581b90d60af2..9e2ad186ba40c 100644 --- a/packages/kbn-optimizer/src/common/bundle.ts +++ b/packages/kbn-optimizer/src/common/bundle.ts @@ -80,7 +80,7 @@ export class Bundle { return { spec: this.toSpec(), mtimes: entriesToObject( - files.map(p => [p, mtimes.get(p)] as const).sort(ascending(e => e[0])) + files.map((p) => [p, mtimes.get(p)] as const).sort(ascending((e) => e[0])) ), }; } diff --git a/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax.ts b/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax.ts index ba19bdc9c3be7..aba4451622dcd 100644 --- a/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax.ts +++ b/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax.ts @@ -130,7 +130,7 @@ export const checks: DisallowedSyntaxCheck[] = [ { name: '[es2018] object spread properties', nodeType: 'ObjectExpression', - test: (n: estree.ObjectExpression) => n.properties.some(p => p.type === 'SpreadElement'), + test: (n: estree.ObjectExpression) => n.properties.some((p) => p.type === 'SpreadElement'), }, // https://github.com/estree/estree/blob/master/es2018.md#template-literals { @@ -142,7 +142,7 @@ export const checks: DisallowedSyntaxCheck[] = [ { name: '[es2018] rest properties', nodeType: 'ObjectPattern', - test: (n: estree.ObjectPattern) => n.properties.some(p => p.type === 'RestElement'), + test: (n: estree.ObjectPattern) => n.properties.some((p) => p.type === 'RestElement'), }, /** diff --git a/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax_plugin.ts b/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax_plugin.ts index 7377462eb267b..8fb7559f3e22f 100644 --- a/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax_plugin.ts +++ b/packages/kbn-optimizer/src/common/disallowed_syntax_plugin/disallowed_syntax_plugin.ts @@ -26,8 +26,8 @@ import { parseFilePath } from '../parse_path'; export class DisallowedSyntaxPlugin { apply(compiler: webpack.Compiler) { - compiler.hooks.normalModuleFactory.tap(DisallowedSyntaxPlugin.name, factory => { - factory.hooks.parser.for('javascript/auto').tap(DisallowedSyntaxPlugin.name, parser => { + compiler.hooks.normalModuleFactory.tap(DisallowedSyntaxPlugin.name, (factory) => { + factory.hooks.parser.for('javascript/auto').tap(DisallowedSyntaxPlugin.name, (parser) => { parser.hooks.program.tap(DisallowedSyntaxPlugin.name, (program: acorn.Node) => { const module = parser.state?.current; if (!module || !module.resource) { @@ -43,7 +43,7 @@ export class DisallowedSyntaxPlugin { const failedChecks = new Set(); - AcornWalk.full(program, node => { + AcornWalk.full(program, (node) => { const checks = checksByNodeType.get(node.type as any); if (!checks) { return; @@ -63,7 +63,7 @@ export class DisallowedSyntaxPlugin { // throw an error to trigger a parse failure, causing this module to be reported as invalid throw new Error( `disallowed syntax found in file ${resource}:\n - ${Array.from(failedChecks) - .map(c => c.name) + .map((c) => c.name) .join('\n - ')}` ); }); diff --git a/packages/kbn-optimizer/src/common/event_stream_helpers.test.ts b/packages/kbn-optimizer/src/common/event_stream_helpers.test.ts index f6f6841532799..7458fa13eccb3 100644 --- a/packages/kbn-optimizer/src/common/event_stream_helpers.test.ts +++ b/packages/kbn-optimizer/src/common/event_stream_helpers.test.ts @@ -233,6 +233,6 @@ it('stops an infinite stream when unsubscribed', async () => { // ensure summarizer still only called 10 times after a timeout expect(summarize).toHaveBeenCalledTimes(10); - await new Promise(resolve => setTimeout(resolve, 1000)); + await new Promise((resolve) => setTimeout(resolve, 1000)); expect(summarize).toHaveBeenCalledTimes(10); }); diff --git a/packages/kbn-optimizer/src/common/event_stream_helpers.ts b/packages/kbn-optimizer/src/common/event_stream_helpers.ts index d07af32f88897..d93cba5653abd 100644 --- a/packages/kbn-optimizer/src/common/event_stream_helpers.ts +++ b/packages/kbn-optimizer/src/common/event_stream_helpers.ts @@ -40,7 +40,7 @@ export const summarizeEventStream = ( initialState: State, summarize: Summarizer ) => { - return new Rx.Observable>(subscriber => { + return new Rx.Observable>((subscriber) => { const eventBuffer: Event[] = []; let processingEventBuffer = false; @@ -93,7 +93,7 @@ export const summarizeEventStream = ( subscriber.add( event$.subscribe( injectEvent, - error => { + (error) => { subscriber.error(error); }, () => { diff --git a/packages/kbn-optimizer/src/common/index.ts b/packages/kbn-optimizer/src/common/index.ts index 376b9ed350908..c51905be04565 100644 --- a/packages/kbn-optimizer/src/common/index.ts +++ b/packages/kbn-optimizer/src/common/index.ts @@ -21,7 +21,6 @@ export * from './bundle'; export * from './bundle_cache'; export * from './worker_config'; export * from './worker_messages'; -export * from './parent_messages'; export * from './compiler_messages'; export * from './ts_helpers'; export * from './rxjs_helpers'; diff --git a/packages/kbn-optimizer/src/common/parse_path.test.ts b/packages/kbn-optimizer/src/common/parse_path.test.ts index 61be44348cfae..48749a08fb285 100644 --- a/packages/kbn-optimizer/src/common/parse_path.test.ts +++ b/packages/kbn-optimizer/src/common/parse_path.test.ts @@ -32,13 +32,13 @@ const FILES = [ ]; describe('parseFilePath()', () => { - it.each([...FILES, ...AMBIGUOUS])('parses %s', path => { + it.each([...FILES, ...AMBIGUOUS])('parses %s', (path) => { expect(parseFilePath(path)).toMatchSnapshot(); }); }); describe('parseDirPath()', () => { - it.each([...DIRS, ...AMBIGUOUS])('parses %s', path => { + it.each([...DIRS, ...AMBIGUOUS])('parses %s', (path) => { expect(parseDirPath(path)).toMatchSnapshot(); }); }); diff --git a/packages/kbn-optimizer/src/common/rxjs_helpers.test.ts b/packages/kbn-optimizer/src/common/rxjs_helpers.test.ts index 72be71e6bf7ec..dda66c999b8f1 100644 --- a/packages/kbn-optimizer/src/common/rxjs_helpers.test.ts +++ b/packages/kbn-optimizer/src/common/rxjs_helpers.test.ts @@ -29,9 +29,9 @@ describe('pipeClosure()', () => { let counter = 0; const foo$ = Rx.of(1, 2, 3).pipe( - pipeClosure(source$ => { + pipeClosure((source$) => { const multiplier = ++counter; - return source$.pipe(map(i => i * multiplier)); + return source$.pipe(map((i) => i * multiplier)); }), toArray() ); @@ -71,7 +71,7 @@ describe('maybe()', () => { describe('maybeMap()', () => { it('calls map fn and filters out undefined values returned', async () => { const foo$ = Rx.of(1, 2, 3, 4, 5).pipe( - maybeMap(i => (i % 2 ? i : undefined)), + maybeMap((i) => (i % 2 ? i : undefined)), toArray() ); @@ -94,7 +94,7 @@ describe('debounceTimeBuffer()', () => { foo$ .pipe( debounceTimeBuffer(100), - map(items => items.reduce((sum, n) => sum + n)) + map((items) => items.reduce((sum, n) => sum + n)) ) .subscribe(dest); @@ -128,7 +128,7 @@ describe('debounceTimeBuffer()', () => { foo$ .pipe( debounceTimeBuffer(100), - map(items => items.reduce((sum, n) => sum + n)) + map((items) => items.reduce((sum, n) => sum + n)) ) .subscribe(dest); diff --git a/packages/kbn-optimizer/src/common/rxjs_helpers.ts b/packages/kbn-optimizer/src/common/rxjs_helpers.ts index f37bebb49efe9..c6385c22518aa 100644 --- a/packages/kbn-optimizer/src/common/rxjs_helpers.ts +++ b/packages/kbn-optimizer/src/common/rxjs_helpers.ts @@ -39,7 +39,7 @@ export const pipeClosure = (fn: Operator): Operator => { * supporting TypeScript */ export const maybe = (): Operator => { - return mergeMap(item => (item === undefined ? Rx.EMPTY : [item])); + return mergeMap((item) => (item === undefined ? Rx.EMPTY : [item])); }; /** @@ -64,7 +64,7 @@ export const debounceTimeBuffer = (ms: number) => pipeClosure((source$: Rx.Observable) => { const buffer: T[] = []; return source$.pipe( - tap(item => buffer.push(item)), + tap((item) => buffer.push(item)), debounceTime(ms), map(() => { const items = Array.from(buffer); diff --git a/packages/kbn-optimizer/src/common/worker_messages.ts b/packages/kbn-optimizer/src/common/worker_messages.ts index 0435f5b4c4011..d3c03f483d7e8 100644 --- a/packages/kbn-optimizer/src/common/worker_messages.ts +++ b/packages/kbn-optimizer/src/common/worker_messages.ts @@ -24,17 +24,13 @@ import { CompilerErrorMsg, } from './compiler_messages'; -export type InternalWorkerMsg = - | WorkerPingMsg +export type WorkerMsg = | CompilerRunningMsg | CompilerIssueMsg | CompilerSuccessMsg | CompilerErrorMsg | WorkerErrorMsg; -// ping messages are internal, they don't apper in public message streams -export type WorkerMsg = Exclude; - /** * Message sent when the worker encounters an error that it can't * recover from, no more messages will be sent and the worker @@ -46,10 +42,6 @@ export interface WorkerErrorMsg { errorStack?: string; } -export interface WorkerPingMsg { - type: 'ping'; -} - const WORKER_STATE_TYPES: ReadonlyArray = [ 'running', 'compiler issue', @@ -58,19 +50,10 @@ const WORKER_STATE_TYPES: ReadonlyArray = [ 'worker error', ]; -export const isWorkerPing = (value: any): value is WorkerPingMsg => - typeof value === 'object' && value && value.type === 'ping'; - export const isWorkerMsg = (value: any): value is WorkerMsg => typeof value === 'object' && value && WORKER_STATE_TYPES.includes(value.type); export class WorkerMsgs { - ping(): WorkerPingMsg { - return { - type: 'ping', - }; - } - error(error: Error): WorkerErrorMsg { return { type: 'worker error', diff --git a/packages/kbn-optimizer/src/integration_tests/basic_optimization.test.ts b/packages/kbn-optimizer/src/integration_tests/basic_optimization.test.ts index ff9addbb3172e..4776153935be5 100644 --- a/packages/kbn-optimizer/src/integration_tests/basic_optimization.test.ts +++ b/packages/kbn-optimizer/src/integration_tests/basic_optimization.test.ts @@ -85,39 +85,39 @@ it('builds expected bundles, saves bundle counts to metadata', async () => { } }; - const initializingStates = msgs.filter(msg => msg.state.phase === 'initializing'); + const initializingStates = msgs.filter((msg) => msg.state.phase === 'initializing'); assert('produce at least one initializing event', initializingStates.length >= 1); const bundleCacheStates = msgs.filter( - msg => + (msg) => (msg.event?.type === 'bundle cached' || msg.event?.type === 'bundle not cached') && msg.state.phase === 'initializing' ); assert('produce two bundle cache events while initializing', bundleCacheStates.length === 2); - const initializedStates = msgs.filter(msg => msg.state.phase === 'initialized'); + const initializedStates = msgs.filter((msg) => msg.state.phase === 'initialized'); assert('produce at least one initialized event', initializedStates.length >= 1); - const workerStarted = msgs.filter(msg => msg.event?.type === 'worker started'); + const workerStarted = msgs.filter((msg) => msg.event?.type === 'worker started'); assert('produce one worker started event', workerStarted.length === 1); - const runningStates = msgs.filter(msg => msg.state.phase === 'running'); + const runningStates = msgs.filter((msg) => msg.state.phase === 'running'); assert( 'produce two or three "running" states', runningStates.length === 2 || runningStates.length === 3 ); - const bundleNotCachedEvents = msgs.filter(msg => msg.event?.type === 'bundle not cached'); + const bundleNotCachedEvents = msgs.filter((msg) => msg.event?.type === 'bundle not cached'); assert('produce two "bundle not cached" events', bundleNotCachedEvents.length === 2); - const successStates = msgs.filter(msg => msg.state.phase === 'success'); + const successStates = msgs.filter((msg) => msg.state.phase === 'success'); assert( 'produce one or two "compiler success" states', successStates.length === 1 || successStates.length === 2 ); const otherStates = msgs.filter( - msg => + (msg) => msg.state.phase !== 'initializing' && msg.state.phase !== 'success' && msg.state.phase !== 'running' && @@ -126,7 +126,7 @@ it('builds expected bundles, saves bundle counts to metadata', async () => { ); assert('produce zero unexpected states', otherStates.length === 0, otherStates); - const foo = config.bundles.find(b => b.id === 'foo')!; + const foo = config.bundles.find((b) => b.id === 'foo')!; expect(foo).toBeTruthy(); foo.cache.refresh(); expect(foo.cache.getModuleCount()).toBe(4); @@ -139,7 +139,7 @@ it('builds expected bundles, saves bundle counts to metadata', async () => { ] `); - const bar = config.bundles.find(b => b.id === 'bar')!; + const bar = config.bundles.find((b) => b.id === 'bar')!; expect(bar).toBeTruthy(); bar.cache.refresh(); expect(bar.cache.getModuleCount()).toBe( @@ -173,7 +173,7 @@ it('uses cache on second run and exist cleanly', async () => { const msgs = await runOptimizer(config) .pipe( - tap(state => { + tap((state) => { if (state.event?.type === 'worker stdio') { // eslint-disable-next-line no-console console.log('worker', state.event.stream, state.event.chunk.toString('utf8')); @@ -183,7 +183,7 @@ it('uses cache on second run and exist cleanly', async () => { ) .toPromise(); - expect(msgs.map(m => m.state.phase)).toMatchInlineSnapshot(` + expect(msgs.map((m) => m.state.phase)).toMatchInlineSnapshot(` Array [ "initializing", "initializing", @@ -202,9 +202,7 @@ it('prepares assets for distribution', async () => { dist: true, }); - await runOptimizer(config) - .pipe(logOptimizerState(log, config), toArray()) - .toPromise(); + await runOptimizer(config).pipe(logOptimizerState(log, config), toArray()).toPromise(); expectFileMatchesSnapshotWithCompression('plugins/foo/target/public/foo.plugin.js', 'foo bundle'); expectFileMatchesSnapshotWithCompression( diff --git a/packages/kbn-optimizer/src/integration_tests/bundle_cache.test.ts b/packages/kbn-optimizer/src/integration_tests/bundle_cache.test.ts index 1bfd8d3fd073a..14ff320173d60 100644 --- a/packages/kbn-optimizer/src/integration_tests/bundle_cache.test.ts +++ b/packages/kbn-optimizer/src/integration_tests/bundle_cache.test.ts @@ -35,7 +35,7 @@ const MOCK_REPO_DIR = Path.resolve(TMP_DIR, 'mock_repo'); expect.addSnapshotSerializer({ print: () => '', - test: v => v instanceof Bundle, + test: (v) => v instanceof Bundle, }); expect.addSnapshotSerializer(createAbsolutePathSerializer(MOCK_REPO_DIR)); 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 c02a857883a98..91d0f308e0ef6 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 @@ -96,7 +96,7 @@ it('notifies of changes and completes once all bundles have changed', async () = // first we change foo and bar, and after 1 second get that change comes though if (i === 1) { expect(event.bundles).toHaveLength(2); - const [bar, foo] = event.bundles.sort(ascending(b => b.id)); + const [bar, foo] = event.bundles.sort(ascending((b) => b.id)); expect(bar).toHaveProperty('id', 'bar'); expect(foo).toHaveProperty('id', 'foo'); } @@ -110,7 +110,7 @@ it('notifies of changes and completes once all bundles have changed', async () = // finally we change box and car together if (i === 5) { expect(event.bundles).toHaveLength(2); - const [bar, foo] = event.bundles.sort(ascending(b => b.id)); + const [bar, foo] = event.bundles.sort(ascending((b) => b.id)); expect(bar).toHaveProperty('id', 'box'); expect(foo).toHaveProperty('id', 'car'); } diff --git a/packages/kbn-optimizer/src/log_optimizer_state.ts b/packages/kbn-optimizer/src/log_optimizer_state.ts index 5217581d1b413..cbec159bd27a0 100644 --- a/packages/kbn-optimizer/src/log_optimizer_state.ts +++ b/packages/kbn-optimizer/src/log_optimizer_state.ts @@ -33,7 +33,7 @@ export function logOptimizerState(log: ToolingLog, config: OptimizerConfig) { let loggedInit = false; return update$.pipe( - tap(update => { + tap((update) => { const { event, state } = update; if (event?.type === 'worker stdio') { diff --git a/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.test.ts b/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.test.ts index dd4d5c294dfc8..4671276797049 100644 --- a/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.test.ts +++ b/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.test.ts @@ -35,7 +35,7 @@ const summarizeBundles = (w: Assignments) => const readConfigs = (workers: Assignments[]) => workers.map( - (w, i) => `worker ${i} (${summarizeBundles(w)}) => ${w.bundles.map(b => b.id).join(',')}` + (w, i) => `worker ${i} (${summarizeBundles(w)}) => ${w.bundles.map((b) => b.id).join(',')}` ); const assertReturnVal = (workers: Assignments[]) => { diff --git a/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.ts b/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.ts index 001783b167c7a..e1bcb22230bf9 100644 --- a/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.ts +++ b/packages/kbn-optimizer/src/optimizer/assign_bundles_to_workers.ts @@ -70,16 +70,16 @@ export function assignBundlesToWorkers(bundles: Bundle[], maxWorkerCount: number * counts and sort them by [moduleCount, id] */ const bundlesWithCountsDesc = bundles - .filter(b => b.cache.getModuleCount() !== undefined) + .filter((b) => b.cache.getModuleCount() !== undefined) .sort( descending( - b => b.cache.getModuleCount(), - b => b.id + (b) => b.cache.getModuleCount(), + (b) => b.id ) ); const bundlesWithoutModuleCounts = bundles - .filter(b => b.cache.getModuleCount() === undefined) - .sort(descending(b => b.id)); + .filter((b) => b.cache.getModuleCount() === undefined) + .sort(descending((b) => b.id)); /** * assign largest bundles to the smallest worker until it is @@ -87,7 +87,7 @@ export function assignBundlesToWorkers(bundles: Bundle[], maxWorkerCount: number * with module counts are assigned */ while (bundlesWithCountsDesc.length) { - const [smallestWorker, nextSmallestWorker] = workers.sort(ascending(w => w.moduleCount)); + const [smallestWorker, nextSmallestWorker] = workers.sort(ascending((w) => w.moduleCount)); while (!nextSmallestWorker || smallestWorker.moduleCount <= nextSmallestWorker.moduleCount) { const bundle = bundlesWithCountsDesc.shift(); @@ -104,7 +104,7 @@ export function assignBundlesToWorkers(bundles: Bundle[], maxWorkerCount: number * assign bundles without module counts to workers round-robin * starting with the smallest workers */ - workers.sort(ascending(w => w.moduleCount)); + workers.sort(ascending((w) => w.moduleCount)); while (bundlesWithoutModuleCounts.length) { for (const worker of workers) { const bundle = bundlesWithoutModuleCounts.shift(); diff --git a/packages/kbn-optimizer/src/optimizer/cache_keys.test.ts b/packages/kbn-optimizer/src/optimizer/cache_keys.test.ts index 7351a3787f760..d5b0b8491f727 100644 --- a/packages/kbn-optimizer/src/optimizer/cache_keys.test.ts +++ b/packages/kbn-optimizer/src/optimizer/cache_keys.test.ts @@ -35,7 +35,7 @@ jest.mock('./get_changes.ts', () => ({ })); jest.mock('./get_mtimes.ts', () => ({ - getMtimes: async (paths: string[]) => new Map(paths.map(path => [path, 12345])), + getMtimes: async (paths: string[]) => new Map(paths.map((path) => [path, 12345])), })); jest.mock('execa'); diff --git a/packages/kbn-optimizer/src/optimizer/cache_keys.ts b/packages/kbn-optimizer/src/optimizer/cache_keys.ts index 11288afa28969..e024af125312d 100644 --- a/packages/kbn-optimizer/src/optimizer/cache_keys.ts +++ b/packages/kbn-optimizer/src/optimizer/cache_keys.ts @@ -182,7 +182,7 @@ export async function getOptimizerCacheKey(config: OptimizerConfig) { }; const mtimes = await getMtimes(modifiedPaths); - for (const [path, mtime] of Array.from(mtimes.entries()).sort(ascending(e => e[0]))) { + for (const [path, mtime] of Array.from(mtimes.entries()).sort(ascending((e) => e[0]))) { if (typeof mtime === 'number') { cacheKeys.modifiedTimes[path] = mtime; } diff --git a/packages/kbn-optimizer/src/optimizer/get_mtimes.ts b/packages/kbn-optimizer/src/optimizer/get_mtimes.ts index 9ac156cb5b8de..07777c323637a 100644 --- a/packages/kbn-optimizer/src/optimizer/get_mtimes.ts +++ b/packages/kbn-optimizer/src/optimizer/get_mtimes.ts @@ -33,15 +33,15 @@ export async function getMtimes(paths: Iterable) { // map paths to [path, mtimeMs] entries with concurrency of // 100 at a time, ignoring missing paths mergeMap( - path => + (path) => stat$(path).pipe( - map(stat => [path, stat.mtimeMs] as const), + map((stat) => [path, stat.mtimeMs] as const), catchError((error: any) => (error?.code === 'ENOENT' ? Rx.EMPTY : Rx.throwError(error))) ), 100 ), toArray(), - map(entries => new Map(entries)) + map((entries) => new Map(entries)) ) .toPromise(); } diff --git a/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.test.ts b/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.test.ts index 36dc0ca64c6ca..2174c488ad6cc 100644 --- a/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.test.ts +++ b/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.test.ts @@ -44,7 +44,7 @@ it('returns a bundle for core and each plugin', () => { }, ], '/repo' - ).map(b => b.toSpec()) + ).map((b) => b.toSpec()) ).toMatchInlineSnapshot(` Array [ Object { diff --git a/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.ts b/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.ts index 4741cc3c30af7..b75a8a6edc264 100644 --- a/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.ts +++ b/packages/kbn-optimizer/src/optimizer/get_plugin_bundles.ts @@ -25,9 +25,9 @@ import { KibanaPlatformPlugin } from './kibana_platform_plugins'; export function getPluginBundles(plugins: KibanaPlatformPlugin[], repoRoot: string) { return plugins - .filter(p => p.isUiPlugin) + .filter((p) => p.isUiPlugin) .map( - p => + (p) => new Bundle({ type: 'plugin', id: p.id, diff --git a/packages/kbn-optimizer/src/optimizer/handle_optimizer_completion.ts b/packages/kbn-optimizer/src/optimizer/handle_optimizer_completion.ts index b4b02649259a2..8b39b5fe8d3b6 100644 --- a/packages/kbn-optimizer/src/optimizer/handle_optimizer_completion.ts +++ b/packages/kbn-optimizer/src/optimizer/handle_optimizer_completion.ts @@ -32,7 +32,7 @@ export function handleOptimizerCompletion(config: OptimizerConfig) { return update$.pipe( tap({ - next: update => { + next: (update) => { prevState = update.state; }, complete: () => { diff --git a/packages/kbn-optimizer/src/optimizer/kibana_platform_plugins.ts b/packages/kbn-optimizer/src/optimizer/kibana_platform_plugins.ts index 2165878e92ff4..992feab6cd364 100644 --- a/packages/kbn-optimizer/src/optimizer/kibana_platform_plugins.ts +++ b/packages/kbn-optimizer/src/optimizer/kibana_platform_plugins.ts @@ -36,15 +36,15 @@ export function findKibanaPlatformPlugins(scanDirs: string[], paths: string[]) { .sync( Array.from( new Set([ - ...scanDirs.map(dir => `${dir}/*/kibana.json`), - ...paths.map(path => `${path}/kibana.json`), + ...scanDirs.map((dir) => `${dir}/*/kibana.json`), + ...paths.map((path) => `${path}/kibana.json`), ]) ), { absolute: true, } ) - .map(path => + .map((path) => // absolute paths returned from globby are using normalize or something so the path separators are `/` even on windows, Path.resolve solves this readKibanaPlatformPlugin(Path.resolve(path)) ); diff --git a/packages/kbn-optimizer/src/optimizer/observe_worker.ts b/packages/kbn-optimizer/src/optimizer/observe_worker.ts index 90c53f1ef9e87..f5c944cefb76f 100644 --- a/packages/kbn-optimizer/src/optimizer/observe_worker.ts +++ b/packages/kbn-optimizer/src/optimizer/observe_worker.ts @@ -22,14 +22,12 @@ import { Readable } from 'stream'; import { inspect } from 'util'; import * as Rx from 'rxjs'; -import { map, filter, takeUntil } from 'rxjs/operators'; +import { map, takeUntil } from 'rxjs/operators'; -import { isWorkerMsg, isWorkerPing, WorkerConfig, WorkerMsg, Bundle, ParentMsgs } from '../common'; +import { isWorkerMsg, WorkerConfig, WorkerMsg, Bundle } from '../common'; import { OptimizerConfig } from './optimizer_config'; -const parentMsgs = new ParentMsgs(); - export interface WorkerStdio { type: 'worker stdio'; stream: 'stdout' | 'stderr'; @@ -49,7 +47,7 @@ interface ProcResource extends Rx.Unsubscribable { const isNumeric = (input: any) => String(input).match(/^[0-9]+$/); let inspectPortCounter = 9230; -const inspectFlagIndex = process.execArgv.findIndex(flag => flag.startsWith('--inspect')); +const inspectFlagIndex = process.execArgv.findIndex((flag) => flag.startsWith('--inspect')); let inspectFlag: string | undefined; if (inspectFlagIndex !== -1) { const argv = process.execArgv[inspectFlagIndex]; @@ -76,7 +74,7 @@ function usingWorkerProc( ) { return Rx.using( (): ProcResource => { - const args = [JSON.stringify(workerConfig), JSON.stringify(bundles.map(b => b.toSpec()))]; + const args = [JSON.stringify(workerConfig), JSON.stringify(bundles.map((b) => b.toSpec()))]; const proc = fork(require.resolve('../worker/run_worker'), args, { stdio: ['ignore', 'pipe', 'pipe', 'ipc'], @@ -96,7 +94,7 @@ function usingWorkerProc( }; }, - resource => { + (resource) => { const { proc } = resource as ProcResource; return fn(proc); } @@ -109,7 +107,7 @@ function observeStdio$(stream: Readable, name: WorkerStdio['stream']) { Rx.race( Rx.fromEvent(stream, 'end'), Rx.fromEvent(stream, 'error').pipe( - map(error => { + map((error) => { throw error; }) ) @@ -136,7 +134,7 @@ export function observeWorker( workerConfig: WorkerConfig, bundles: Bundle[] ): Rx.Observable { - return usingWorkerProc(config, workerConfig, bundles, proc => { + return usingWorkerProc(config, workerConfig, bundles, (proc) => { let lastMsg: WorkerMsg; return Rx.merge( @@ -148,16 +146,6 @@ export function observeWorker( observeStdio$(proc.stderr, 'stderr'), Rx.fromEvent<[unknown]>(proc, 'message') .pipe( - // filter out ping messages so they don't end up in the general message stream - filter(([msg]) => { - if (!isWorkerPing(msg)) { - return true; - } - - proc.send(parentMsgs.pong()); - return false; - }), - // validate the messages from the process map(([msg]) => { if (!isWorkerMsg(msg)) { @@ -173,7 +161,7 @@ export function observeWorker( Rx.race( // throw into stream on error events Rx.fromEvent(proc, 'error').pipe( - map(error => { + map((error) => { throw new Error(`worker failed to spawn: ${error.message}`); }) ), diff --git a/packages/kbn-optimizer/src/optimizer/optimizer_config.ts b/packages/kbn-optimizer/src/optimizer/optimizer_config.ts index d6336cf867470..4ed241f3b9b2e 100644 --- a/packages/kbn-optimizer/src/optimizer/optimizer_config.ts +++ b/packages/kbn-optimizer/src/optimizer/optimizer_config.ts @@ -106,7 +106,7 @@ export class OptimizerConfig { ...(examples ? [Path.resolve('examples'), Path.resolve('x-pack/examples')] : []), Path.resolve(repoRoot, '../kibana-extra'), ]; - if (!pluginScanDirs.every(p => Path.isAbsolute(p))) { + if (!pluginScanDirs.every((p) => Path.isAbsolute(p))) { throw new TypeError('pluginScanDirs must all be absolute paths'); } @@ -118,7 +118,7 @@ export class OptimizerConfig { } const pluginPaths = options.pluginPaths || []; - if (!pluginPaths.every(s => Path.isAbsolute(s))) { + if (!pluginPaths.every((s) => Path.isAbsolute(s))) { throw new TypeError('pluginPaths must all be absolute paths'); } diff --git a/packages/kbn-optimizer/src/optimizer/optimizer_state.ts b/packages/kbn-optimizer/src/optimizer/optimizer_state.ts index ac2a9b8ce1f8b..1572f459e6ee5 100644 --- a/packages/kbn-optimizer/src/optimizer/optimizer_state.ts +++ b/packages/kbn-optimizer/src/optimizer/optimizer_state.ts @@ -80,7 +80,7 @@ function createOptimizerState( * calculate the total state, given a set of compiler messages */ function getStatePhase(states: CompilerMsg[]) { - const types = states.map(s => s.type); + const types = states.map((s) => s.type); if (types.includes('running')) { return 'running'; @@ -90,7 +90,7 @@ function getStatePhase(states: CompilerMsg[]) { return 'issue'; } - if (types.every(s => s === 'compiler success')) { + if (types.every((s) => s === 'compiler success')) { return 'success'; } @@ -173,7 +173,7 @@ export function createOptimizerStateSummarizer( event.type === 'running' ) { const compilerStates: CompilerMsg[] = [ - ...state.compilerStates.filter(c => c.bundleId !== event.bundleId), + ...state.compilerStates.filter((c) => c.bundleId !== event.bundleId), event, ]; return createOptimizerState(state, { diff --git a/packages/kbn-optimizer/src/optimizer/run_workers.ts b/packages/kbn-optimizer/src/optimizer/run_workers.ts index e91b0d25fd72b..1f277f011004d 100644 --- a/packages/kbn-optimizer/src/optimizer/run_workers.ts +++ b/packages/kbn-optimizer/src/optimizer/run_workers.ts @@ -50,15 +50,15 @@ export function runWorkers( return Rx.concat( // first batch of bundles are based on how up-to-date the cache is bundleCache$.pipe( - maybeMap(event => (event.type === 'bundle not cached' ? event.bundle : undefined)), + maybeMap((event) => (event.type === 'bundle not cached' ? event.bundle : undefined)), toArray() ), // subsequent batches are defined by changeEvent$ - changeEvent$.pipe(maybeMap(c => (c.type === 'changes' ? c.bundles : undefined))) + changeEvent$.pipe(maybeMap((c) => (c.type === 'changes' ? c.bundles : undefined))) ).pipe( - mergeMap(bundles => + mergeMap((bundles) => Rx.from(assignBundlesToWorkers(bundles, config.maxWorkerCount)).pipe( - mergeMap(assignment => + mergeMap((assignment) => observeWorker(config, config.getWorkerConfig(optimizerCacheKey), assignment.bundles) ) ) diff --git a/packages/kbn-optimizer/src/optimizer/watch_bundles_for_changes.ts b/packages/kbn-optimizer/src/optimizer/watch_bundles_for_changes.ts index 9149c483786fc..fdac4e0204fbe 100644 --- a/packages/kbn-optimizer/src/optimizer/watch_bundles_for_changes.ts +++ b/packages/kbn-optimizer/src/optimizer/watch_bundles_for_changes.ts @@ -38,7 +38,7 @@ function recursiveGetNextChange$( return !bundles.length ? Rx.EMPTY : watcher.getNextChange$(bundles, startTime).pipe( - mergeMap(event => { + mergeMap((event) => { if (event.type === 'changes detected') { return Rx.of(event); } @@ -48,7 +48,7 @@ function recursiveGetNextChange$( recursiveGetNextChange$( watcher, - bundles.filter(b => !event.bundles.includes(b)), + bundles.filter((b) => !event.bundles.includes(b)), Date.now() ) ); @@ -74,11 +74,11 @@ export function watchBundlesForChanges$( initialStartTime: number ) { return bundleCacheEvent$.pipe( - maybeMap(event => (event.type === 'bundle cached' ? event.bundle : undefined)), + maybeMap((event) => (event.type === 'bundle cached' ? event.bundle : undefined)), toArray(), - mergeMap(bundles => + mergeMap((bundles) => bundles.length - ? Watcher.using(watcher => recursiveGetNextChange$(watcher, bundles, initialStartTime)) + ? Watcher.using((watcher) => recursiveGetNextChange$(watcher, bundles, initialStartTime)) : Rx.EMPTY ) ); diff --git a/packages/kbn-optimizer/src/optimizer/watcher.ts b/packages/kbn-optimizer/src/optimizer/watcher.ts index 343f391921383..54c548755af5c 100644 --- a/packages/kbn-optimizer/src/optimizer/watcher.ts +++ b/packages/kbn-optimizer/src/optimizer/watcher.ts @@ -43,7 +43,7 @@ export class Watcher { static using(fn: (watcher: Watcher) => Rx.Observable) { return Rx.using( () => new Watcher(), - resource => fn(resource as Watcher) + (resource) => fn(resource as Watcher) ); } @@ -69,14 +69,14 @@ export class Watcher { // debounce and bufffer change events for 1 second to create // final change notification this.change$.pipe( - map(event => event[0]), + map((event) => event[0]), debounceTimeBuffer(1000), map( (changes): Changes => ({ type: 'changes', - bundles: bundles.filter(bundle => { + bundles: bundles.filter((bundle) => { const referencedFiles = bundle.cache.getReferencedFiles(); - return changes.some(change => referencedFiles?.includes(change)); + return changes.some((change) => referencedFiles?.includes(change)); }), }) ), diff --git a/packages/kbn-optimizer/src/report_optimizer_stats.ts b/packages/kbn-optimizer/src/report_optimizer_stats.ts index 06161fb2567b9..5f3153bff5175 100644 --- a/packages/kbn-optimizer/src/report_optimizer_stats.ts +++ b/packages/kbn-optimizer/src/report_optimizer_stats.ts @@ -29,14 +29,14 @@ export function reportOptimizerStats(reporter: CiStatsReporter, config: Optimize let lastState: OptimizerState | undefined; return update$.pipe( materialize(), - mergeMap(async n => { + mergeMap(async (n) => { if (n.kind === 'N' && n.value?.state) { lastState = n.value?.state; } if (n.kind === 'C' && lastState) { await reporter.metrics( - config.bundles.map(bundle => { + config.bundles.map((bundle) => { // make the cache read from the cache file since it was likely updated by the worker bundle.cache.refresh(); diff --git a/packages/kbn-optimizer/src/worker/observe_parent_offline.test.ts b/packages/kbn-optimizer/src/worker/observe_parent_offline.test.ts deleted file mode 100644 index 2c1b86b380c60..0000000000000 --- a/packages/kbn-optimizer/src/worker/observe_parent_offline.test.ts +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { EventEmitter } from 'events'; -import { inspect } from 'util'; - -import * as Rx from 'rxjs'; -import { tap, takeUntil } from 'rxjs/operators'; - -import { observeParentOffline, Process } from './observe_parent_offline'; -import { WorkerMsgs, ParentMsgs, isWorkerPing } from '../common'; - -jest.useFakeTimers(); - -beforeEach(() => { - jest.clearAllTimers(); -}); - -const workerMsgs = new WorkerMsgs(); -const parentMsgs = new ParentMsgs(); -class MockProcess extends EventEmitter implements Process { - connected?: boolean; - send?: jest.Mock; - - constructor(options: { connected?: boolean; send?: jest.Mock | false } = {}) { - super(); - - this.connected = options.connected ?? true; - this.send = options.send === false ? undefined : options.send ?? jest.fn(); - } -} - -async function record(observable: Rx.Observable): Promise { - const notes: string[] = []; - - await observable - .pipe( - tap({ - next(value) { - notes.push(`next: ${inspect(value)}`); - }, - error(error) { - notes.push(`error: ${inspect(error)}`); - }, - complete() { - notes.push(`complete`); - }, - }) - ) - .toPromise(); - - return notes; -} - -async function waitForTick() { - await new Promise(resolve => { - process.nextTick(resolve); - }); -} - -describe('emits and completes when parent exists because:', () => { - test('process.connected is false', async () => { - const mockProc = new MockProcess({ - connected: false, - }); - - const promise = record(observeParentOffline(mockProc, workerMsgs)); - jest.advanceTimersToNextTimer(); - expect(await promise).toMatchInlineSnapshot(` - Array [ - "next: 'parent offline (disconnected)'", - "complete", - ] - `); - }); - - test('process.send is falsey', async () => { - const mockProc = new MockProcess({ - send: false, - }); - - const promise = record(observeParentOffline(mockProc, workerMsgs)); - jest.advanceTimersToNextTimer(); - expect(await promise).toMatchInlineSnapshot(` - Array [ - "next: 'parent offline (disconnected)'", - "complete", - ] - `); - }); - - test('process.send throws "ERR_IPC_CHANNEL_CLOSED"', async () => { - const mockProc = new MockProcess({ - send: jest.fn(() => { - const error = new Error(); - (error as any).code = 'ERR_IPC_CHANNEL_CLOSED'; - throw error; - }), - }); - - const promise = record(observeParentOffline(mockProc, workerMsgs)); - jest.advanceTimersToNextTimer(); - expect(await promise).toMatchInlineSnapshot(` - Array [ - "next: 'parent offline (ipc channel exception)'", - "complete", - ] - `); - }); - - test('ping timeout', async () => { - const mockProc = new MockProcess({}); - - const promise = record(observeParentOffline(mockProc, workerMsgs)); - jest.advanceTimersByTime(10000); - expect(await promise).toMatchInlineSnapshot(` - Array [ - "next: 'parent offline (ping timeout)'", - "complete", - ] - `); - }); -}); - -test('it emits nothing if parent responds with pongs', async () => { - const send = jest.fn((msg: any) => { - if (isWorkerPing(msg)) { - process.nextTick(() => { - mockProc.emit('message', parentMsgs.pong(), undefined); - }); - } - }); - - const mockProc = new MockProcess({ send }); - const unsub$ = new Rx.Subject(); - const promise = record(observeParentOffline(mockProc, workerMsgs).pipe(takeUntil(unsub$))); - - jest.advanceTimersByTime(5000); - await waitForTick(); - jest.advanceTimersByTime(5000); - await waitForTick(); - unsub$.next(); - - expect(await promise).toMatchInlineSnapshot(` - Array [ - "complete", - ] - `); - expect(send).toHaveBeenCalledTimes(2); -}); diff --git a/packages/kbn-optimizer/src/worker/observe_parent_offline.ts b/packages/kbn-optimizer/src/worker/observe_parent_offline.ts deleted file mode 100644 index ff24a0e64a399..0000000000000 --- a/packages/kbn-optimizer/src/worker/observe_parent_offline.ts +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { EventEmitter } from 'events'; - -import * as Rx from 'rxjs'; -import { mergeMap, take, first, map, catchError } from 'rxjs/operators'; - -import { isParentPong, WorkerMsgs } from '../common'; - -const sleep = (ms: number) => Rx.timer(ms).pipe(take(1)); - -export interface Process extends EventEmitter { - connected?: boolean; - send?: (msg: any) => void; -} - -/** - * Returns an observable that will emit a value when the parent - * process goes offline. It accomplishes this by merging several - * signals: - * - * 1. process "disconnect" event - * 2. process.connected or process.send are falsy - * 3. a ping was sent to the parent process but it didn't respond - * with a pong within 5 seconds - * 4. a ping was sent to the parent process but the process.send - * call errored with an 'ERR_IPC_CHANNEL_CLOSED' exception - */ -export function observeParentOffline(process: Process, workerMsgs: WorkerMsgs) { - return sleep(5000).pipe( - mergeMap(() => { - if (!process.connected || !process.send) { - return Rx.of('parent offline (disconnected)'); - } - - process.send(workerMsgs.ping()); - - const pong$ = Rx.fromEvent<[any]>(process, 'message').pipe( - first(([msg]) => isParentPong(msg)), - map(() => { - throw new Error('parent still online'); - }) - ); - - // give the parent some time to respond, if the ping - // wins the race the parent is considered online - const timeout$ = sleep(5000).pipe(map(() => 'parent offline (ping timeout)')); - - return Rx.race(pong$, timeout$); - }), - - /** - * resubscribe to the source observable (triggering the timer, - * ping, wait for response) if the source observable does not - * observe the parent being offline yet. - * - * Scheduling the interval this way prevents the ping timeout - * from overlaping with the interval by only scheduling the - * next ping once the previous ping has completed - */ - catchError((error, resubscribe) => { - if (error.code === 'ERR_IPC_CHANNEL_CLOSED') { - return Rx.of('parent offline (ipc channel exception)'); - } - - if (error.message === 'parent still online') { - return resubscribe; - } - - throw error; - }) - ); -} diff --git a/packages/kbn-optimizer/src/worker/run_compilers.ts b/packages/kbn-optimizer/src/worker/run_compilers.ts index 0dfce4b5addba..4ab289d031d72 100644 --- a/packages/kbn-optimizer/src/worker/run_compilers.ts +++ b/packages/kbn-optimizer/src/worker/run_compilers.ts @@ -65,8 +65,8 @@ const observeCompiler = ( * Called by webpack as a single run compilation is starting */ const started$ = Rx.merge( - Rx.fromEventPattern(cb => beforeRun.tap(PLUGIN_NAME, cb)), - Rx.fromEventPattern(cb => watchRun.tap(PLUGIN_NAME, cb)) + Rx.fromEventPattern((cb) => beforeRun.tap(PLUGIN_NAME, cb)), + Rx.fromEventPattern((cb) => watchRun.tap(PLUGIN_NAME, cb)) ).pipe(mapTo(compilerMsgs.running())); /** @@ -74,8 +74,8 @@ const observeCompiler = ( * needAdditionalPass property is set then another compilation * is about to be started, so we shouldn't send complete quite yet */ - const complete$ = Rx.fromEventPattern(cb => done.tap(PLUGIN_NAME, cb)).pipe( - maybeMap(stats => { + const complete$ = Rx.fromEventPattern((cb) => done.tap(PLUGIN_NAME, cb)).pipe( + maybeMap((stats) => { // @ts-ignore not included in types, but it is real https://github.com/webpack/webpack/blob/ab4fa8ddb3f433d286653cd6af7e3aad51168649/lib/Watching.js#L58 if (stats.compilation.needAdditionalPass) { return undefined; @@ -134,7 +134,7 @@ const observeCompiler = ( ); } - const files = Array.from(referencedFiles).sort(ascending(p => p)); + const files = Array.from(referencedFiles).sort(ascending((p) => p)); const mtimes = new Map( files.map((path): [string, number | undefined] => { try { @@ -167,8 +167,10 @@ const observeCompiler = ( * prevets assets from being emitted, and prevents watching * from continuing. */ - const error$ = Rx.fromEventPattern(cb => compiler.hooks.failed.tap(PLUGIN_NAME, cb)).pipe( - map(error => { + const error$ = Rx.fromEventPattern((cb) => + compiler.hooks.failed.tap(PLUGIN_NAME, cb) + ).pipe( + map((error) => { throw compilerMsgs.error(error); }) ); @@ -184,7 +186,7 @@ const observeCompiler = ( * Run webpack compilers */ export const runCompilers = (workerConfig: WorkerConfig, bundles: Bundle[]) => { - const multiCompiler = webpack(bundles.map(def => getWebpackConfig(def, workerConfig))); + const multiCompiler = webpack(bundles.map((def) => getWebpackConfig(def, workerConfig))); return Rx.merge( /** diff --git a/packages/kbn-optimizer/src/worker/run_worker.ts b/packages/kbn-optimizer/src/worker/run_worker.ts index 0a9adc2a3db55..f83c69477f471 100644 --- a/packages/kbn-optimizer/src/worker/run_worker.ts +++ b/packages/kbn-optimizer/src/worker/run_worker.ts @@ -18,12 +18,10 @@ */ import * as Rx from 'rxjs'; -import { takeUntil } from 'rxjs/operators'; import { parseBundles, parseWorkerConfig, WorkerMsg, isWorkerMsg, WorkerMsgs } from '../common'; import { runCompilers } from './run_compilers'; -import { observeParentOffline } from './observe_parent_offline'; /** ** @@ -66,6 +64,15 @@ const exit = (code: number) => { }, 5000).unref(); }; +// check for connected parent on an unref'd timer rather than listening +// to "disconnect" since that listner prevents the process from exiting +setInterval(() => { + if (!process.connected) { + // parent is gone + process.exit(0); + } +}, 1000).unref(); + Rx.defer(() => { const workerConfig = parseWorkerConfig(process.argv[2]); const bundles = parseBundles(process.argv[3]); @@ -74,22 +81,20 @@ Rx.defer(() => { process.env.BROWSERSLIST_ENV = workerConfig.browserslistEnv; return runCompilers(workerConfig, bundles); -}) - .pipe(takeUntil(observeParentOffline(process, workerMsgs))) - .subscribe( - msg => { - send(msg); - }, - error => { - if (isWorkerMsg(error)) { - send(error); - } else { - send(workerMsgs.error(error)); - } - - exit(1); - }, - () => { - exit(0); +}).subscribe( + (msg) => { + send(msg); + }, + (error) => { + if (isWorkerMsg(error)) { + send(error); + } else { + send(workerMsgs.error(error)); } - ); + + exit(1); + }, + () => { + exit(0); + } +); diff --git a/packages/kbn-optimizer/src/worker/theme_loader.ts b/packages/kbn-optimizer/src/worker/theme_loader.ts index 6d6686a5bde1b..5d02462ef1bb8 100644 --- a/packages/kbn-optimizer/src/worker/theme_loader.ts +++ b/packages/kbn-optimizer/src/worker/theme_loader.ts @@ -21,7 +21,7 @@ import webpack from 'webpack'; import { stringifyRequest } from 'loader-utils'; // eslint-disable-next-line import/no-default-export -export default function(this: webpack.loader.LoaderContext) { +export default function (this: webpack.loader.LoaderContext) { return ` if (window.__kbnDarkMode__) { require(${stringifyRequest(this, `${this.resourcePath}?dark`)}) diff --git a/packages/kbn-optimizer/src/worker/webpack.config.ts b/packages/kbn-optimizer/src/worker/webpack.config.ts index 49bcc6e7e704c..0c9a5b0a75687 100644 --- a/packages/kbn-optimizer/src/worker/webpack.config.ts +++ b/packages/kbn-optimizer/src/worker/webpack.config.ts @@ -64,7 +64,7 @@ function dynamicExternals(bundle: Bundle, context: string, request: string) { // ignore requests that don't include a /{dirname}/public for one of our // "static" bundles as a cheap way to avoid doing path resolution // for paths that couldn't possibly resolve to what we're looking for - const reqToStaticBundle = STATIC_BUNDLE_PLUGINS.some(p => + const reqToStaticBundle = STATIC_BUNDLE_PLUGINS.some((p) => request.includes(`/${p.dirname}/public`) ); if (!reqToStaticBundle) { @@ -100,7 +100,7 @@ export function getWebpackConfig(bundle: Bundle, worker: WorkerConfig) { output: { path: bundle.outputDir, filename: `[name].${bundle.type}.js`, - devtoolModuleFilenameTemplate: info => + devtoolModuleFilenameTemplate: (info) => `/${bundle.type}:${bundle.id}/${Path.relative( bundle.sourceRoot, info.absoluteResourcePath @@ -121,7 +121,7 @@ export function getWebpackConfig(bundle: Bundle, worker: WorkerConfig) { externals: [ UiSharedDeps.externals, - function(context, request, cb) { + function (context, request, cb) { try { cb(undefined, dynamicExternals(bundle, context, request)); } catch (error) { diff --git a/packages/kbn-plugin-generator/index.js b/packages/kbn-plugin-generator/index.js index 5f20569886d88..e61037e42d63f 100644 --- a/packages/kbn-plugin-generator/index.js +++ b/packages/kbn-plugin-generator/index.js @@ -61,7 +61,7 @@ exports.run = function run(argv) { name, targetPath, }, - }).catch(error => { + }).catch((error) => { console.error(chalk`{red fatal error}!`); console.error(error.stack); process.exit(1); diff --git a/packages/kbn-plugin-generator/sao_template/sao.js b/packages/kbn-plugin-generator/sao_template/sao.js index 9073ce865a963..7fc29b1e6bd0a 100755 --- a/packages/kbn-plugin-generator/sao_template/sao.js +++ b/packages/kbn-plugin-generator/sao_template/sao.js @@ -59,7 +59,7 @@ async function eslintPlugin(dir) { } } -module.exports = function({ name, targetPath }) { +module.exports = function ({ name, targetPath }) { return { prompts: { customPath: { @@ -99,7 +99,7 @@ module.exports = function({ name, targetPath }) { }, generateTranslations: { type: 'confirm', - when: answers => { + when: (answers) => { // only for 3rd party plugins return !answers.customPath && answers.generateApp; }, @@ -112,7 +112,7 @@ module.exports = function({ name, targetPath }) { generateScss: { type: 'confirm', message: 'Should SCSS be used?', - when: answers => answers.generateApp, + when: (answers) => answers.generateApp, default: true, }, generateEslint: { @@ -135,7 +135,7 @@ module.exports = function({ name, targetPath }) { 'eslintrc.js': '.eslintrc.js', 'i18nrc.json': '.i18nrc.json', }, - data: answers => { + data: (answers) => { const pathToPlugin = answers.customPath ? resolve(answers.customPath, camelCase(name), 'public') : resolve(targetPath, 'public'); diff --git a/packages/kbn-plugin-helpers/src/cli.ts b/packages/kbn-plugin-helpers/src/cli.ts index ee1bca0fe3ac2..b894f854a484f 100644 --- a/packages/kbn-plugin-helpers/src/cli.ts +++ b/packages/kbn-plugin-helpers/src/cli.ts @@ -35,7 +35,7 @@ enableCollectingUnknownOptions( .description('Start kibana and have it include this plugin') .on('--help', docs('start')) .action( - createCommanderAction('start', command => ({ + createCommanderAction('start', (command) => ({ flags: command.unknownOptions, })) ) @@ -75,7 +75,7 @@ program .option('-p, --plugins ', "Manually specify which plugins' test bundles to run") .on('--help', docs('test/karma')) .action( - createCommanderAction('testKarma', command => ({ + createCommanderAction('testKarma', (command) => ({ dev: Boolean(command.dev), plugins: command.plugins, })) diff --git a/packages/kbn-plugin-helpers/src/lib/docs.ts b/packages/kbn-plugin-helpers/src/lib/docs.ts index 68c095209e817..fb05fd0c5c2ce 100644 --- a/packages/kbn-plugin-helpers/src/lib/docs.ts +++ b/packages/kbn-plugin-helpers/src/lib/docs.ts @@ -28,7 +28,7 @@ function indent(txt: string, n: number) { export function docs(name: string) { const md = readFileSync(resolve(__dirname, '../../src/tasks', name, 'README.md'), 'utf8'); - return function() { + return function () { /* eslint-disable-next-line no-console */ console.log(`\n Docs:\n\n${indent(md, 4)}\n\n`); }; diff --git a/packages/kbn-plugin-helpers/src/lib/enable_collecting_unknown_options.ts b/packages/kbn-plugin-helpers/src/lib/enable_collecting_unknown_options.ts index 77fa7f2fcae84..0d692aed06305 100644 --- a/packages/kbn-plugin-helpers/src/lib/enable_collecting_unknown_options.ts +++ b/packages/kbn-plugin-helpers/src/lib/enable_collecting_unknown_options.ts @@ -22,7 +22,7 @@ import { Command } from 'commander'; export function enableCollectingUnknownOptions(command: Command) { const origParse = command.parseOptions; command.allowUnknownOption(); - command.parseOptions = function(argv: string[]) { + command.parseOptions = function (argv: string[]) { const opts = origParse.call(this, argv); this.unknownOptions = opts.unknown; return opts; diff --git a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/build_action_test_plugin/index.js b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/build_action_test_plugin/index.js index c2d2ade568761..052d224b662e2 100644 --- a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/build_action_test_plugin/index.js +++ b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/build_action_test_plugin/index.js @@ -17,7 +17,7 @@ * under the License. */ -module.exports = kibana => +module.exports = (kibana) => new kibana.Plugin({ uiExports: { hacks: ['plugins/test_plugin/hack.js'], diff --git a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_build_test_plugin/index.js b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_build_test_plugin/index.js index c2d2ade568761..052d224b662e2 100644 --- a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_build_test_plugin/index.js +++ b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_build_test_plugin/index.js @@ -17,7 +17,7 @@ * under the License. */ -module.exports = kibana => +module.exports = (kibana) => new kibana.Plugin({ uiExports: { hacks: ['plugins/test_plugin/hack.js'], diff --git a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_package_test_plugin/index.js b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_package_test_plugin/index.js index c2d2ade568761..052d224b662e2 100644 --- a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_package_test_plugin/index.js +++ b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/__fixtures__/create_package_test_plugin/index.js @@ -17,7 +17,7 @@ * under the License. */ -module.exports = kibana => +module.exports = (kibana) => new kibana.Plugin({ uiExports: { hacks: ['plugins/test_plugin/hack.js'], diff --git a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/build_action.test.js b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/build_action.test.js index f596576fe7466..d9f20129e85f9 100644 --- a/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/build_action.test.js +++ b/packages/kbn-plugin-helpers/src/tasks/build/integration_tests/build_action.test.js @@ -91,7 +91,7 @@ describe('calling create_build', () => { expect(mockBuild.mock.calls).toHaveLength(1); const { files } = nameArgs(mockBuild.mock.calls[0]); - plugin.buildSourcePatterns.forEach(file => expect(files).toContain(file)); + plugin.buildSourcePatterns.forEach((file) => expect(files).toContain(file)); }); it('uses only files passed in', async () => { @@ -104,7 +104,7 @@ describe('calling create_build', () => { expect(mockBuild.mock.calls).toHaveLength(1); const { files } = nameArgs(mockBuild.mock.calls[0]); - options.files.forEach(file => expect(files).toContain(file)); + options.files.forEach((file) => expect(files).toContain(file)); }); it('rejects returned promise when build fails', async () => { diff --git a/packages/kbn-plugin-helpers/src/tasks/build/rewrite_package_json.ts b/packages/kbn-plugin-helpers/src/tasks/build/rewrite_package_json.ts index 255b2e6ef9992..aaecd11ad82af 100644 --- a/packages/kbn-plugin-helpers/src/tasks/build/rewrite_package_json.ts +++ b/packages/kbn-plugin-helpers/src/tasks/build/rewrite_package_json.ts @@ -26,7 +26,7 @@ export function rewritePackageJson( buildVersion: string, kibanaVersion: string ) { - return Through2Map.obj(function(file: File) { + return Through2Map.obj(function (file: File) { if (file.basename === 'package.json' && file.dirname === buildSource) { const pkg = JSON.parse(file.contents!.toString('utf8')); diff --git a/packages/kbn-plugin-helpers/src/tasks/start/start_task.ts b/packages/kbn-plugin-helpers/src/tasks/start/start_task.ts index 75affb6da8c6f..5018fd7598180 100644 --- a/packages/kbn-plugin-helpers/src/tasks/start/start_task.ts +++ b/packages/kbn-plugin-helpers/src/tasks/start/start_task.ts @@ -35,7 +35,7 @@ export function startTask({ plugin, options }: TaskContext) { let args = nodeOptions.concat([script, '--dev', '--plugin-path', plugin.root]); if (Array.isArray(plugin.includePlugins)) { - plugin.includePlugins.forEach(path => { + plugin.includePlugins.forEach((path) => { args = args.concat(['--plugin-path', path]); }); } diff --git a/packages/kbn-pm/dist/index.js b/packages/kbn-pm/dist/index.js index 1b670eb8cd816..baaac3d8d4a86 100644 --- a/packages/kbn-pm/dist/index.js +++ b/packages/kbn-pm/dist/index.js @@ -4859,7 +4859,7 @@ class ProcRunner { this.closing = false; this.procs = []; this.signalUnsubscribe = exit_hook_1.default(() => { - this.teardown().catch(error => { + this.teardown().catch((error) => { log.error(`ProcRunner teardown error: ${error.stack}`); }); }); @@ -4898,7 +4898,7 @@ class ProcRunner { try { if (wait instanceof RegExp) { // wait for process to log matching line - await Rx.race(proc.lines$.pipe(operators_1.filter(line => wait.test(line)), operators_1.first(), operators_1.catchError(err => { + await Rx.race(proc.lines$.pipe(operators_1.filter((line) => wait.test(line)), operators_1.first(), operators_1.catchError((err) => { if (err.name !== 'EmptyError') { throw errors_1.createCliError(`[${name}] exited without matching pattern: ${wait}`); } @@ -4943,7 +4943,7 @@ class ProcRunner { * @return {Promise} */ async waitForAllToStop() { - await Promise.all(this.procs.map(proc => proc.outcomePromise)); + await Promise.all(this.procs.map((proc) => proc.outcomePromise)); } /** * Close the ProcRunner and stop all running @@ -4959,14 +4959,14 @@ class ProcRunner { this.closing = true; this.signalUnsubscribe(); if (!signal && this.procs.length > 0) { - this.log.warning('%d processes left running, stop them with procs.stop(name):', this.procs.length, this.procs.map(proc => proc.name)); + this.log.warning('%d processes left running, stop them with procs.stop(name):', this.procs.length, this.procs.map((proc) => proc.name)); } await Promise.all(this.procs.map(async (proc) => { await proc.stop(signal === 'exit' ? 'SIGKILL' : signal); })); } getProc(name) { - return this.procs.find(proc => { + return this.procs.find((proc) => { return proc.name === name; }); } @@ -4979,14 +4979,14 @@ class ProcRunner { }; // tie into proc outcome$, remove from _procs on compete proc.outcome$.subscribe({ - next: code => { + next: (code) => { const duration = moment_1.default.duration(Date.now() - startMs); this.log.info('[%s] exited with %s after %s', name, code, duration.humanize()); }, complete: () => { remove(); }, - error: error => { + error: (error) => { if (this.closing) { this.log.error(error); } @@ -33599,8 +33599,8 @@ function startProc(name, options, log) { return code; })), // observe first error event - Rx.fromEvent(childProcess, 'error').pipe(operators_1.take(1), operators_1.mergeMap(err => Rx.throwError(err)))).pipe(operators_1.share()); - const lines$ = Rx.merge(observe_lines_1.observeLines(childProcess.stdout), observe_lines_1.observeLines(childProcess.stderr)).pipe(operators_1.tap(line => log.write(` ${chalk_1.default.gray('proc')} [${chalk_1.default.gray(name)}] ${line}`)), operators_1.share()); + Rx.fromEvent(childProcess, 'error').pipe(operators_1.take(1), operators_1.mergeMap((err) => Rx.throwError(err)))).pipe(operators_1.share()); + const lines$ = Rx.merge(observe_lines_1.observeLines(childProcess.stdout), observe_lines_1.observeLines(childProcess.stderr)).pipe(operators_1.tap((line) => log.write(` ${chalk_1.default.gray('proc')} [${chalk_1.default.gray(name)}] ${line}`)), operators_1.share()); const outcomePromise = Rx.merge(lines$.pipe(operators_1.ignoreElements()), outcome$).toPromise(); async function stop(signal) { if (stopCalled) { @@ -36584,7 +36584,7 @@ const operators_1 = __webpack_require__(270); * - fails on the first "error" event */ function observeReadable(readable) { - return Rx.race(Rx.fromEvent(readable, 'end').pipe(operators_1.first(), operators_1.ignoreElements()), Rx.fromEvent(readable, 'error').pipe(operators_1.first(), operators_1.mergeMap(err => Rx.throwError(err)))); + return Rx.race(Rx.fromEvent(readable, 'end').pipe(operators_1.first(), operators_1.ignoreElements()), Rx.fromEvent(readable, 'error').pipe(operators_1.first(), operators_1.mergeMap((err) => Rx.throwError(err)))); } exports.observeReadable = observeReadable; @@ -36894,7 +36894,7 @@ class ToolingLogCollectingWriter extends tooling_log_text_writer_1.ToolingLogTex super({ level: 'verbose', writeTo: { - write: msg => { + write: (msg) => { // trim trailing new line this.messages.push(msg.slice(0, -1)); }, @@ -39475,7 +39475,7 @@ async function run(fn, options = {}) { level: tooling_log_1.pickLevelFromFlags(flags), writeTo: process.stdout, }); - process.on('unhandledRejection', error => { + process.on('unhandledRejection', (error) => { log.error('UNHANDLED PROMISE REJECTION'); log.error(error instanceof Error ? error @@ -39589,7 +39589,7 @@ function combineErrors(errors) { const exitCode = errors .filter(isFailError) .reduce((acc, error) => Math.max(acc, error.exitCode), 1); - const showHelp = errors.some(error => isFailError(error) && error.showHelp); + const showHelp = errors.some((error) => isFailError(error) && error.showHelp); const message = errors.reduce((acc, error) => { if (isFailError(error)) { return acc + '\n' + error.message; @@ -40091,7 +40091,7 @@ exports.uriencode = (strings, ...values) => { return queue.reduce((acc, string, i) => `${acc}${encodeURIComponent(values[i])}${string}`, leadingString); }; const DEFAULT_MAX_ATTEMPTS = 5; -const delay = (ms) => new Promise(resolve => { +const delay = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); }); class KbnClientRequester { @@ -43984,7 +43984,7 @@ class CiStatsReporter { const reason = ((_d = (_c = error) === null || _c === void 0 ? void 0 : _c.response) === null || _d === void 0 ? void 0 : _d.status) ? `${error.response.status} response` : 'no response'; this.log.warning(`failed to reach kibana-ci-stats service [reason=${reason}], retrying in ${attempt} seconds`); - await new Promise(resolve => setTimeout(resolve, attempt * 1000)); + await new Promise((resolve) => setTimeout(resolve, attempt * 1000)); } } } diff --git a/packages/kbn-pm/package.json b/packages/kbn-pm/package.json index be56fad8aa0ce..234877e9ae626 100644 --- a/packages/kbn-pm/package.json +++ b/packages/kbn-pm/package.json @@ -54,7 +54,7 @@ "multimatch": "^4.0.0", "ncp": "^2.0.0", "ora": "^1.4.0", - "prettier": "^1.19.1", + "prettier": "^2.0.5", "read-pkg": "^5.2.0", "rxjs": "^6.5.3", "spawn-sync": "^1.0.15", diff --git a/packages/kbn-pm/src/cli.ts b/packages/kbn-pm/src/cli.ts index c2f49356957f7..94f348e1835ed 100644 --- a/packages/kbn-pm/src/cli.ts +++ b/packages/kbn-pm/src/cli.ts @@ -28,8 +28,8 @@ import { log } from './utils/log'; function help() { const availableCommands = Object.keys(commands) - .map(commandName => commands[commandName]) - .map(command => `${command.name} - ${command.description}`); + .map((commandName) => commands[commandName]) + .map((command) => `${command.name} - ${command.description}`); log.write(dedent` usage: kbn [] diff --git a/packages/kbn-pm/src/commands/bootstrap.ts b/packages/kbn-pm/src/commands/bootstrap.ts index d0aa220f25f66..6146aeab21db4 100644 --- a/packages/kbn-pm/src/commands/bootstrap.ts +++ b/packages/kbn-pm/src/commands/bootstrap.ts @@ -69,7 +69,7 @@ export const BootstrapCommand: ICommand = { log.write(chalk.bold('\nLinking executables completed, running `kbn:bootstrap` scripts\n')); const checksums = options.cache ? await getAllChecksums(kbn, log) : false; - await parallelizeBatches(batchedProjects, async project => { + await parallelizeBatches(batchedProjects, async (project) => { if (project.hasScript('kbn:bootstrap')) { const cacheFile = new BootstrapCacheFile(kbn, project, checksums); if (cacheFile.isValid()) { diff --git a/packages/kbn-pm/src/commands/run.ts b/packages/kbn-pm/src/commands/run.ts index 2f4d9e8453d09..989bfef19c380 100644 --- a/packages/kbn-pm/src/commands/run.ts +++ b/packages/kbn-pm/src/commands/run.ts @@ -43,7 +43,7 @@ export const RunCommand: ICommand = { chalk.bold(`\nRunning script [${chalk.green(scriptName)}] in batched topological order\n`) ); - await parallelizeBatches(batchedProjects, async pkg => { + await parallelizeBatches(batchedProjects, async (pkg) => { if (pkg.hasScript(scriptName)) { await pkg.runScriptStreaming(scriptName, scriptArgs); } diff --git a/packages/kbn-pm/src/commands/watch.ts b/packages/kbn-pm/src/commands/watch.ts index b5c493372b04f..2e18b02a1c860 100644 --- a/packages/kbn-pm/src/commands/watch.ts +++ b/packages/kbn-pm/src/commands/watch.ts @@ -83,7 +83,7 @@ export const WatchCommand: ICommand = { batchedProjects.push([projects.get(kibanaProjectName)!]); } - await parallelizeBatches(batchedProjects, async pkg => { + await parallelizeBatches(batchedProjects, async (pkg) => { const completionHint = await waitUntilWatchIsReady( pkg.runScriptStreaming(watchScriptName).stdout ); diff --git a/packages/kbn-pm/src/production/build_production_projects.ts b/packages/kbn-pm/src/production/build_production_projects.ts index 0d4be8b016077..689bf51cd7bdf 100644 --- a/packages/kbn-pm/src/production/build_production_projects.ts +++ b/packages/kbn-pm/src/production/build_production_projects.ts @@ -46,7 +46,7 @@ export async function buildProductionProjects({ const projectGraph = buildProjectGraph(projects); const batchedProjects = topologicallyBatchProjects(projects, projectGraph); - const projectNames = [...projects.values()].map(project => project.name); + const projectNames = [...projects.values()].map((project) => project.name); log.write(`Preparing production build for [${projectNames.join(', ')}]`); for (const batch of batchedProjects) { @@ -82,7 +82,7 @@ async function getProductionProjects(rootPath: string, onlyOSS?: boolean) { productionProjects.delete('kibana'); if (onlyOSS) { - productionProjects.forEach(project => { + productionProjects.forEach((project) => { if (project.getBuildConfig().oss === false) { productionProjects.delete(project.json.name); } diff --git a/packages/kbn-pm/src/run.ts b/packages/kbn-pm/src/run.ts index 44bf5a91ee1b1..c3879c701d785 100644 --- a/packages/kbn-pm/src/run.ts +++ b/packages/kbn-pm/src/run.ts @@ -71,7 +71,7 @@ export async function runCommand(command: ICommand, config: Omit 0) { - const metaOutput = keys.map(key => { + const metaOutput = keys.map((key) => { const value = e.meta[key]; return `${key}: ${value}`; }); diff --git a/packages/kbn-pm/src/utils/bootstrap_cache_file.ts b/packages/kbn-pm/src/utils/bootstrap_cache_file.ts index 7d87179f34605..282483e10ccf2 100644 --- a/packages/kbn-pm/src/utils/bootstrap_cache_file.ts +++ b/packages/kbn-pm/src/utils/bootstrap_cache_file.ts @@ -39,7 +39,7 @@ export class BootstrapCacheFile { // sort deps by name so that the key is stable .sort((a, b) => a.name.localeCompare(b.name)) // get the cacheKey for each project, return undefined if the cache key couldn't be determined - .map(p => { + .map((p) => { const cacheKey = checksums.get(p.name); if (cacheKey) { return `${p.name}:${cacheKey}`; @@ -47,7 +47,7 @@ export class BootstrapCacheFile { }); // if any of the relevant cache keys are undefined then the projectCacheKey must be too - this.expectedValue = projectAndDepCacheKeys.some(k => !k) + this.expectedValue = projectAndDepCacheKeys.some((k) => !k) ? undefined : [ `# this is only human readable for debugging, please don't try to parse this`, diff --git a/packages/kbn-pm/src/utils/fs.ts b/packages/kbn-pm/src/utils/fs.ts index 9484c3a61e608..44fc59bdeba96 100644 --- a/packages/kbn-pm/src/utils/fs.ts +++ b/packages/kbn-pm/src/utils/fs.ts @@ -49,7 +49,7 @@ async function statTest(path: string, block: (stats: fs.Stats) => boolean) { * @param path */ export async function isSymlink(path: string) { - return await statTest(path, stats => stats.isSymbolicLink()); + return await statTest(path, (stats) => stats.isSymbolicLink()); } /** @@ -57,7 +57,7 @@ export async function isSymlink(path: string) { * @param path */ export async function isDirectory(path: string) { - return await statTest(path, stats => stats.isDirectory()); + return await statTest(path, (stats) => stats.isDirectory()); } /** @@ -65,7 +65,7 @@ export async function isDirectory(path: string) { * @param path */ export async function isFile(path: string) { - return await statTest(path, stats => stats.isFile()); + return await statTest(path, (stats) => stats.isFile()); } /** diff --git a/packages/kbn-pm/src/utils/kibana.ts b/packages/kbn-pm/src/utils/kibana.ts index 58af98b2a92db..7fca4bd01822b 100644 --- a/packages/kbn-pm/src/utils/kibana.ts +++ b/packages/kbn-pm/src/utils/kibana.ts @@ -103,11 +103,11 @@ export class Kibana { const allProjects = this.getAllProjects(); const filteredProjects: ProjectMap = new Map(); - const pkgJsonPaths = Array.from(allProjects.values()).map(p => p.packageJsonLocation); + const pkgJsonPaths = Array.from(allProjects.values()).map((p) => p.packageJsonLocation); const filteredPkgJsonGlobs = getProjectPaths({ ...options, rootPath: this.kibanaProject.path, - }).map(g => Path.resolve(g, 'package.json')); + }).map((g) => Path.resolve(g, 'package.json')); const matchingPkgJsonPaths = multimatch(pkgJsonPaths, filteredPkgJsonGlobs); for (const project of allProjects.values()) { diff --git a/packages/kbn-pm/src/utils/link_project_executables.test.ts b/packages/kbn-pm/src/utils/link_project_executables.test.ts index a6334ec850860..a19e1fd66f334 100644 --- a/packages/kbn-pm/src/utils/link_project_executables.test.ts +++ b/packages/kbn-pm/src/utils/link_project_executables.test.ts @@ -70,7 +70,7 @@ const projectGraph = buildProjectGraph(projectsByName); function getFsMockCalls() { const fs = require('./fs'); const fsMockCalls: { [key: string]: any[][] } = {}; - Object.keys(fs).map(key => { + Object.keys(fs).map((key) => { if (jest.isMockFunction(fs[key])) { fsMockCalls[key] = fs[key].mock.calls; } diff --git a/packages/kbn-pm/src/utils/link_project_executables.ts b/packages/kbn-pm/src/utils/link_project_executables.ts index 25fb11f17f782..b403dfb2ecf2e 100644 --- a/packages/kbn-pm/src/utils/link_project_executables.ts +++ b/packages/kbn-pm/src/utils/link_project_executables.ts @@ -55,9 +55,7 @@ export async function linkProjectExecutables( const dest = resolve(binsDir, name); // Get relative project path with normalized path separators. - const projectRelativePath = relative(project.path, srcPath) - .split(sep) - .join('/'); + const projectRelativePath = relative(project.path, srcPath).split(sep).join('/'); log.write(chalk`{dim [${project.name}]} ${name} -> {dim ${projectRelativePath}}`); diff --git a/packages/kbn-pm/src/utils/parallelize.test.ts b/packages/kbn-pm/src/utils/parallelize.test.ts index fa23ecbb8c1e7..e85b40e0c67d8 100644 --- a/packages/kbn-pm/src/utils/parallelize.test.ts +++ b/packages/kbn-pm/src/utils/parallelize.test.ts @@ -22,7 +22,7 @@ import { parallelizeBatches } from './parallelize'; // As promises resolve async, we use this helper to wait for all promises that // have been resolved to complete (aka call `then`). const tick = () => - new Promise(resolve => { + new Promise((resolve) => { setTimeout(resolve, 0); }); @@ -32,7 +32,7 @@ test('parallelizes batches', async () => { const baz = createPromiseWithResolve(); const batches = [[foo, bar], [baz]]; - const parallelize = parallelizeBatches(batches, async obj => { + const parallelize = parallelizeBatches(batches, async (obj) => { obj.called = true; await obj.promise; }); @@ -82,7 +82,7 @@ test('schedules at most 4 calls at the same time (concurrency)', async () => { const foobar = createPromiseWithResolve(); const batches = [[foo, bar, baz, quux, foobar]]; - const parallelize = parallelizeBatches(batches, async obj => { + const parallelize = parallelizeBatches(batches, async (obj) => { obj.called = true; await obj.promise; }); @@ -113,7 +113,7 @@ test('rejects if any promise rejects', async () => { const baz = createPromiseWithResolve(); const batches = [[foo, bar], [baz]]; - const parallelize = parallelizeBatches(batches, async obj => { + const parallelize = parallelizeBatches(batches, async (obj) => { await obj.promise; }); diff --git a/packages/kbn-pm/src/utils/project.ts b/packages/kbn-pm/src/utils/project.ts index 7b0bbed5c3f46..91a3a5365b60e 100644 --- a/packages/kbn-pm/src/utils/project.ts +++ b/packages/kbn-pm/src/utils/project.ts @@ -229,10 +229,10 @@ export class Project { // check for any cross-project dependency for (const name of Object.keys(workspacesInfo)) { const workspace = workspacesInfo[name]; - workspace.workspaceDependencies.forEach(w => unusedWorkspaces.delete(w)); + workspace.workspaceDependencies.forEach((w) => unusedWorkspaces.delete(w)); } - unusedWorkspaces.forEach(name => { + unusedWorkspaces.forEach((name) => { const { dependencies, devDependencies } = this.json; const nodeModulesPath = Path.resolve(this.nodeModulesLocation, name); const isDependency = dependencies && dependencies.hasOwnProperty(name); diff --git a/packages/kbn-pm/src/utils/project_checksums.ts b/packages/kbn-pm/src/utils/project_checksums.ts index 7d939e715d411..46dde1b32c158 100644 --- a/packages/kbn-pm/src/utils/project_checksums.ts +++ b/packages/kbn-pm/src/utils/project_checksums.ts @@ -49,8 +49,8 @@ async function getChangesForProjects(projects: ProjectMap, kbn: Kibana, log: Too '--exclude-standard', '--', ...Array.from(projects.values()) - .filter(p => kbn.isPartOfRepo(p)) - .map(p => p.path), + .filter((p) => kbn.isPartOfRepo(p)) + .map((p) => p.path), ], { cwd: kbn.getAbsolute(), @@ -265,7 +265,7 @@ export async function getAllChecksums(kbn: Kibana, log: ToolingLog) { const cacheKeys: ChecksumMap = new Map(); await Promise.all( - Array.from(projects.values()).map(async project => { + Array.from(projects.values()).map(async (project) => { cacheKeys.set( project.name, await getChecksum(project, changesByProject.get(project), yarnLock, kbn, log) diff --git a/packages/kbn-pm/src/utils/projects.test.ts b/packages/kbn-pm/src/utils/projects.test.ts index ba093b9d5eba1..068c72286872a 100644 --- a/packages/kbn-pm/src/utils/projects.test.ts +++ b/packages/kbn-pm/src/utils/projects.test.ts @@ -208,7 +208,7 @@ describe('#topologicallyBatchProjects', () => { test('batches projects topologically based on their project dependencies', async () => { const batches = topologicallyBatchProjects(projects, graph); - const expectedBatches = batches.map(batch => batch.map(project => project.name)); + const expectedBatches = batches.map((batch) => batch.map((project) => project.name)); expect(expectedBatches).toMatchSnapshot(); }); @@ -219,7 +219,7 @@ describe('#topologicallyBatchProjects', () => { const batches = topologicallyBatchProjects(projects, graph); - const expectedBatches = batches.map(batch => batch.map(project => project.name)); + const expectedBatches = batches.map((batch) => batch.map((project) => project.name)); expect(expectedBatches).toMatchSnapshot(); }); @@ -228,7 +228,7 @@ describe('#topologicallyBatchProjects', () => { test('batches projects topologically based on their project dependencies and workspaces', async () => { const batches = topologicallyBatchProjects(projects, graph, { batchByWorkspace: true }); - const expectedBatches = batches.map(batch => batch.map(project => project.name)); + const expectedBatches = batches.map((batch) => batch.map((project) => project.name)); expect(expectedBatches).toEqual([['kibana'], ['bar', 'foo'], ['baz', 'zorge'], ['quux']]); }); diff --git a/packages/kbn-pm/src/utils/projects.ts b/packages/kbn-pm/src/utils/projects.ts index a6f174b1fc5a1..1c3bf0fa3091a 100644 --- a/packages/kbn-pm/src/utils/projects.ts +++ b/packages/kbn-pm/src/utils/projects.ts @@ -137,7 +137,9 @@ export function topologicallyBatchProjects( const batches = []; if (batchByWorkspace) { - const workspaceRootProject = Array.from(projectsToBatch.values()).find(p => p.isWorkspaceRoot); + const workspaceRootProject = Array.from(projectsToBatch.values()).find( + (p) => p.isWorkspaceRoot + ); if (!workspaceRootProject) { throw new CliError(`There was no yarn workspace root found.`); @@ -167,7 +169,7 @@ export function topologicallyBatchProjects( const batch = []; for (const projectName of projectsLeftToBatch) { const projectDeps = projectGraph.get(projectName)!; - const needsDependenciesBatched = projectDeps.some(dep => projectsLeftToBatch.has(dep.name)); + const needsDependenciesBatched = projectDeps.some((dep) => projectsLeftToBatch.has(dep.name)); if (!needsDependenciesBatched) { batch.push(projectsToBatch.get(projectName)!); @@ -188,7 +190,7 @@ export function topologicallyBatchProjects( batches.push(batch); - batch.forEach(project => projectsLeftToBatch.delete(project.name)); + batch.forEach((project) => projectsLeftToBatch.delete(project.name)); } return batches; @@ -211,7 +213,7 @@ export function includeTransitiveProjects( ? project.productionDependencies : project.allDependencies; - Object.keys(dependencies).forEach(dep => { + Object.keys(dependencies).forEach((dep) => { if (allProjects.has(dep)) { toProcess.push(allProjects.get(dep)!); } diff --git a/packages/kbn-pm/src/utils/watch.ts b/packages/kbn-pm/src/utils/watch.ts index 0ec8b50d83905..1998c5199fb73 100644 --- a/packages/kbn-pm/src/utils/watch.ts +++ b/packages/kbn-pm/src/utils/watch.ts @@ -56,20 +56,20 @@ function getWatchHandlers( }: IWatchOptions ) { const typescriptHandler = buildOutput$.pipe( - first(data => data.includes('$ tsc')), + first((data) => data.includes('$ tsc')), map(() => buildOutput$.pipe( - first(data => data.includes('Compilation complete.')), + first((data) => data.includes('Compilation complete.')), mapTo('tsc') ) ) ); const webpackHandler = buildOutput$.pipe( - first(data => data.includes('$ webpack')), + first((data) => data.includes('$ webpack')), map(() => buildOutput$.pipe( - first(data => data.includes('Chunk Names')), + first((data) => data.includes('Chunk Names')), mapTo('webpack') ) ) @@ -100,7 +100,7 @@ export function waitUntilWatchIsReady(stream: NodeJS.EventEmitter, opts: IWatchO return Rx.race(getWatchHandlers(buildOutput$, opts)) .pipe( - mergeMap(whenReady => whenReady), + mergeMap((whenReady) => whenReady), finalize(() => { stream.removeListener('data', onDataListener); stream.removeListener('end', onEndListener); diff --git a/packages/kbn-pm/src/utils/workspaces.ts b/packages/kbn-pm/src/utils/workspaces.ts index 22fa8636aea90..830a713e84ad4 100644 --- a/packages/kbn-pm/src/utils/workspaces.ts +++ b/packages/kbn-pm/src/utils/workspaces.ts @@ -48,7 +48,7 @@ export async function workspacePackagePaths(rootPath: string): Promise for (const pattern of workspacesPathsPatterns) { if (pattern.startsWith('!')) { const pathToRemove = path.join(rootPath, pattern.slice(1), 'package.json'); - workspaceProjectsPaths = workspaceProjectsPaths.filter(p => p !== pathToRemove); + workspaceProjectsPaths = workspaceProjectsPaths.filter((p) => p !== pathToRemove); } } diff --git a/packages/kbn-spec-to-console/bin/spec_to_console.js b/packages/kbn-spec-to-console/bin/spec_to_console.js index 20b42c67f3b89..432890a9cb903 100644 --- a/packages/kbn-spec-to-console/bin/spec_to_console.js +++ b/packages/kbn-spec-to-console/bin/spec_to_console.js @@ -46,7 +46,7 @@ console.log(); console.log(files); console.log(); -files.forEach(file => { +files.forEach((file) => { const spec = JSON.parse(fs.readFileSync(file)); const convertedSpec = convert(spec); if (!Object.keys(convertedSpec).length) { diff --git a/packages/kbn-spec-to-console/lib/convert.js b/packages/kbn-spec-to-console/lib/convert.js index 9648ef0b85a4f..bd0dbb429cff3 100644 --- a/packages/kbn-spec-to-console/lib/convert.js +++ b/packages/kbn-spec-to-console/lib/convert.js @@ -22,7 +22,7 @@ const convertMethods = require('./convert/methods'); const convertPaths = require('./convert/paths'); const convertParts = require('./convert/parts'); -module.exports = spec => { +module.exports = (spec) => { const result = {}; /** * TODO: @@ -34,7 +34,7 @@ module.exports = spec => { * from being used in autocompletion. It would be really nice if we could use this information * instead of just not including it. */ - Object.keys(spec).forEach(api => { + Object.keys(spec).forEach((api) => { const source = spec[api]; if (!source.url) { @@ -42,7 +42,7 @@ module.exports = spec => { } if (source.url.path) { - if (source.url.paths.every(path => Boolean(path.deprecated))) { + if (source.url.paths.every((path) => Boolean(path.deprecated))) { return; } } @@ -61,10 +61,10 @@ module.exports = spec => { if (source.url.paths) { // We filter out all deprecated url patterns here. - const paths = source.url.paths.filter(path => !path.deprecated); + const paths = source.url.paths.filter((path) => !path.deprecated); patterns = convertPaths(paths); - paths.forEach(pathsObject => { - pathsObject.methods.forEach(method => methodSet.add(method)); + paths.forEach((pathsObject) => { + pathsObject.methods.forEach((method) => methodSet.add(method)); if (pathsObject.parts) { for (const partName of Object.keys(pathsObject.parts)) { urlComponents[partName] = pathsObject.parts[partName]; @@ -79,7 +79,7 @@ module.exports = spec => { if (Object.keys(urlComponents).length) { const components = convertParts(urlComponents); const hasComponents = - Object.keys(components).filter(c => { + Object.keys(components).filter((c) => { return Boolean(components[c]); }).length > 0; if (hasComponents) { diff --git a/packages/kbn-spec-to-console/lib/convert/methods.js b/packages/kbn-spec-to-console/lib/convert/methods.js index b4ab8f467ae1f..89d193dd38071 100644 --- a/packages/kbn-spec-to-console/lib/convert/methods.js +++ b/packages/kbn-spec-to-console/lib/convert/methods.js @@ -17,6 +17,6 @@ * under the License. */ -module.exports = methods => { +module.exports = (methods) => { return methods; }; diff --git a/packages/kbn-spec-to-console/lib/convert/params.js b/packages/kbn-spec-to-console/lib/convert/params.js index 0d1747ae4f685..00169b12322ed 100644 --- a/packages/kbn-spec-to-console/lib/convert/params.js +++ b/packages/kbn-spec-to-console/lib/convert/params.js @@ -17,9 +17,9 @@ * under the License. */ -module.exports = params => { +module.exports = (params) => { const result = {}; - Object.keys(params).forEach(param => { + Object.keys(params).forEach((param) => { const { type, description = '', options = [] } = params[param]; const [, defaultValue] = description.match(/\(default: (.*)\)/) || []; switch (type) { @@ -35,7 +35,7 @@ module.exports = params => { case 'enum': // This is to clean up entries like: "d (Days)". We only want the "d" part. if (param === 'time') { - result[param] = options.map(option => option.split(' ')[0]); + result[param] = options.map((option) => option.split(' ')[0]); } else { result[param] = options; } diff --git a/packages/kbn-spec-to-console/lib/convert/parts.js b/packages/kbn-spec-to-console/lib/convert/parts.js index 040d04a0c1dc4..96cd3c94e796d 100644 --- a/packages/kbn-spec-to-console/lib/convert/parts.js +++ b/packages/kbn-spec-to-console/lib/convert/parts.js @@ -19,9 +19,9 @@ const replacePattern = require('../replace_pattern'); -module.exports = parts => { +module.exports = (parts) => { const result = {}; - Object.keys(parts).forEach(part => { + Object.keys(parts).forEach((part) => { const key = replacePattern(part, { exact: true }); const options = parts[part].options; if (options && options.length) { diff --git a/packages/kbn-spec-to-console/lib/convert/paths.js b/packages/kbn-spec-to-console/lib/convert/paths.js index 6c65bf48b9b06..af8897c2782f2 100644 --- a/packages/kbn-spec-to-console/lib/convert/paths.js +++ b/packages/kbn-spec-to-console/lib/convert/paths.js @@ -19,8 +19,8 @@ const replacePattern = require('../replace_pattern'); -module.exports = patterns => { - return patterns.map(patternObject => { +module.exports = (patterns) => { + return patterns.map((patternObject) => { return replacePattern(patternObject.path, { brackets: true }); }); }; diff --git a/packages/kbn-spec-to-console/lib/replace_pattern.js b/packages/kbn-spec-to-console/lib/replace_pattern.js index 29d16be3cc70f..4da75db78086d 100644 --- a/packages/kbn-spec-to-console/lib/replace_pattern.js +++ b/packages/kbn-spec-to-console/lib/replace_pattern.js @@ -21,7 +21,7 @@ const map = require('./static/map_interpolation'); module.exports = (pattern, { brackets, exact } = {}) => { let newPattern = pattern; - Object.keys(map).forEach(key => { + Object.keys(map).forEach((key) => { const replaceFrom = brackets ? `{${key}}` : key; const replaceTo = brackets ? `{${map[key]}}` : map[key]; if (exact) { diff --git a/packages/kbn-spec-to-console/package.json b/packages/kbn-spec-to-console/package.json index a6b3e8f96f7db..ebbf244eb2e10 100644 --- a/packages/kbn-spec-to-console/package.json +++ b/packages/kbn-spec-to-console/package.json @@ -18,7 +18,7 @@ "homepage": "https://github.com/jbudz/spec-to-console#readme", "devDependencies": { "jest": "^24.9.0", - "prettier": "^1.19.1" + "prettier": "^2.0.5" }, "dependencies": { "commander": "^3.0.0", diff --git a/packages/kbn-storybook/index.js b/packages/kbn-storybook/index.js index b595de8ea1c07..c7dae20902f1a 100644 --- a/packages/kbn-storybook/index.js +++ b/packages/kbn-storybook/index.js @@ -27,7 +27,7 @@ const { generateStorybookEntry } = require('./lib/storybook_entry'); const { REPO_ROOT, ASSET_DIR, CURRENT_CONFIG } = require('./lib/constants'); const { buildDll } = require('./lib/dll'); -exports.runStorybookCli = config => { +exports.runStorybookCli = (config) => { const { name, storyGlobs } = config; run( async ({ flags, log, procRunner }) => { diff --git a/packages/kbn-storybook/lib/storybook_entry.js b/packages/kbn-storybook/lib/storybook_entry.js index dececef47f40e..9eb1b0a458c6a 100644 --- a/packages/kbn-storybook/lib/storybook_entry.js +++ b/packages/kbn-storybook/lib/storybook_entry.js @@ -37,7 +37,7 @@ const STORE_ENTRY_DIR = dirname(STORY_ENTRY_PATH); exports.generateStorybookEntry = ({ log, storyGlobs }) => { const globs = ['built_assets/css/**/*.light.css', ...storyGlobs]; log.info('Storybook globs:\n', globs); - const norm = p => normalize(relative(STORE_ENTRY_DIR, p)); + const norm = (p) => normalize(relative(STORE_ENTRY_DIR, p)); return Rx.defer(() => glob(globs, { @@ -46,20 +46,20 @@ exports.generateStorybookEntry = ({ log, storyGlobs }) => { onlyFiles: true, }) ).pipe( - map(paths => { + map((paths) => { log.info('Discovered Storybook entry points:\n', paths); return new Set(paths.map(norm)); }), mergeMap( - paths => - new Rx.Observable(observer => { + (paths) => + new Rx.Observable((observer) => { observer.next(paths); const chokidar = watch(globs, { cwd: REPO_ROOT }) - .on('add', path => { + .on('add', (path) => { observer.next(paths.add(norm(resolve(REPO_ROOT, path)))); }) - .on('unlink', path => { + .on('unlink', (path) => { observer.next(paths.delete(norm(resolve(REPO_ROOT, path)))); }); diff --git a/packages/kbn-storybook/storybook_config/middleware.js b/packages/kbn-storybook/storybook_config/middleware.js index 046758948b2cf..9410bb66030d9 100644 --- a/packages/kbn-storybook/storybook_config/middleware.js +++ b/packages/kbn-storybook/storybook_config/middleware.js @@ -21,6 +21,6 @@ const serve = require('serve-static'); const path = require('path'); // Extend the Storybook Middleware to include a route to access Legacy UI assets -module.exports = function(router) { +module.exports = function (router) { router.get('/ui', serve(path.resolve(__dirname, '../../../src/core/server/core_app/assets'))); }; diff --git a/packages/kbn-storybook/storybook_config/mocks/noop.js b/packages/kbn-storybook/storybook_config/mocks/noop.js index aaddfb2ed8ac3..e78d222eaa560 100755 --- a/packages/kbn-storybook/storybook_config/mocks/noop.js +++ b/packages/kbn-storybook/storybook_config/mocks/noop.js @@ -17,4 +17,4 @@ * under the License. */ -export default function() {} +export default function () {} diff --git a/packages/kbn-storybook/storybook_config/webpack.config.js b/packages/kbn-storybook/storybook_config/webpack.config.js index 779d8a4153644..2dd051882bb4b 100644 --- a/packages/kbn-storybook/storybook_config/webpack.config.js +++ b/packages/kbn-storybook/storybook_config/webpack.config.js @@ -29,7 +29,7 @@ const { currentConfig } = require('../../../built_assets/storybook/current.confi module.exports = async ({ config }) => { // Find and alter the CSS rule to replace the Kibana public path string with a path // to the route we've added in middleware.js - const cssRule = config.module.rules.find(rule => rule.test.source.includes('.css$')); + const cssRule = config.module.rules.find((rule) => rule.test.source.includes('.css$')); cssRule.use.push({ loader: 'string-replace-loader', options: { diff --git a/packages/kbn-test-subj-selector/__tests__/index.js b/packages/kbn-test-subj-selector/__tests__/index.js index e18405b99ae52..23165cefec94a 100755 --- a/packages/kbn-test-subj-selector/__tests__/index.js +++ b/packages/kbn-test-subj-selector/__tests__/index.js @@ -20,8 +20,8 @@ const testSubjSelector = require('../'); const expect = require('@kbn/expect'); -describe('testSubjSelector()', function() { - it('converts subjectSelectors to cssSelectors', function() { +describe('testSubjSelector()', function () { + it('converts subjectSelectors to cssSelectors', function () { expect(testSubjSelector('foo bar')).to.eql('[data-test-subj="foo bar"]'); expect(testSubjSelector('foo > bar')).to.eql('[data-test-subj="foo"] [data-test-subj="bar"]'); expect(testSubjSelector('foo > bar baz')).to.eql( diff --git a/packages/kbn-test-subj-selector/index.js b/packages/kbn-test-subj-selector/index.js index 3984c15c00fef..2be59d78dc5ef 100755 --- a/packages/kbn-test-subj-selector/index.js +++ b/packages/kbn-test-subj-selector/index.js @@ -42,12 +42,7 @@ module.exports = function testSubjSelector(selector) { while (terms.length) { const term = terms.shift(); // split each term by joins/& and map to css selectors - cssSelectors.push( - term - .split('&') - .map(termToCssSelector) - .join('') - ); + cssSelectors.push(term.split('&').map(termToCssSelector).join('')); } return cssSelectors.join(' '); diff --git a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts index 0c824754b1237..7cbeb18a5ebd4 100644 --- a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts +++ b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.test.ts @@ -25,12 +25,8 @@ import { createPatch } from 'diff'; // turns out Jest can't encode xml diffs in their JUnit reports... expect.addSnapshotSerializer({ - test: v => typeof v === 'string' && (v.includes('<') || v.includes('>')), - print: v => - v - .replace(//g, '›') - .replace(/^\s+$/gm, ''), + test: (v) => typeof v === 'string' && (v.includes('<') || v.includes('>')), + print: (v) => v.replace(//g, '›').replace(/^\s+$/gm, ''), }); jest.mock('fs', () => { diff --git a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts index 32ea5fa0f9033..6bc7556db8a47 100644 --- a/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts +++ b/packages/kbn-test/src/failed_tests_reporter/add_messages_to_report.ts @@ -49,7 +49,7 @@ export async function addMessagesToReport(options: { for (const testCase of makeFailedTestCaseIter(report)) { const { classname, name } = testCase.$; const messageList = messages - .filter(u => u.classname === classname && u.name === name) + .filter((u) => u.classname === classname && u.name === name) .reduce((acc, u) => `${acc}\n - ${u.message}`, ''); if (!messageList) { @@ -76,7 +76,7 @@ export async function addMessagesToReport(options: { const xml = builder .buildObject(report) .split('\n') - .map(line => (line.trim() === '' ? '' : line)) + .map((line) => (line.trim() === '' ? '' : line)) .join('\n'); if (dryRun) { diff --git a/packages/kbn-test/src/failed_tests_reporter/github_api.ts b/packages/kbn-test/src/failed_tests_reporter/github_api.ts index 7da79b5b67e63..a0e3bcafdf196 100644 --- a/packages/kbn-test/src/failed_tests_reporter/github_api.ts +++ b/packages/kbn-test/src/failed_tests_reporter/github_api.ts @@ -233,7 +233,7 @@ export class GithubApi { this.log.error(`Unable to reach github, waiting ${waitMs}ms to retry`); } - await new Promise(resolve => setTimeout(resolve, waitMs)); + await new Promise((resolve) => setTimeout(resolve, waitMs)); return await this.request( { ...options, diff --git a/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts b/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts index 9324f9eb42aa5..b298c08f162bf 100644 --- a/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts +++ b/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts @@ -100,7 +100,7 @@ export function runFailedTestsReporterCli() { } let existingIssue: GithubIssueMini | undefined = await githubApi.findFailedTestIssue( - i => + (i) => getIssueMetadata(i.body, 'test.class') === failure.classname && getIssueMetadata(i.body, 'test.name') === failure.name ); diff --git a/packages/kbn-test/src/functional_test_runner/__tests__/integration/basic.js b/packages/kbn-test/src/functional_test_runner/__tests__/integration/basic.js index 3c8daf4154236..133f4d2feb53e 100644 --- a/packages/kbn-test/src/functional_test_runner/__tests__/integration/basic.js +++ b/packages/kbn-test/src/functional_test_runner/__tests__/integration/basic.js @@ -26,7 +26,7 @@ import { REPO_ROOT } from '@kbn/dev-utils'; const SCRIPT = resolve(REPO_ROOT, 'scripts/functional_test_runner.js'); const BASIC_CONFIG = require.resolve('../fixtures/simple_project/config.js'); -describe('basic config file with a single app and test', function() { +describe('basic config file with a single app and test', function () { this.timeout(60 * 1000); it('runs and prints expected output', () => { diff --git a/packages/kbn-test/src/functional_test_runner/__tests__/integration/failure_hooks.js b/packages/kbn-test/src/functional_test_runner/__tests__/integration/failure_hooks.js index d6e7b1ac58aa4..12e28d2702c5a 100644 --- a/packages/kbn-test/src/functional_test_runner/__tests__/integration/failure_hooks.js +++ b/packages/kbn-test/src/functional_test_runner/__tests__/integration/failure_hooks.js @@ -27,7 +27,7 @@ import { REPO_ROOT } from '@kbn/dev-utils'; const SCRIPT = resolve(REPO_ROOT, 'scripts/functional_test_runner.js'); const FAILURE_HOOKS_CONFIG = require.resolve('../fixtures/failure_hooks/config.js'); -describe('failure hooks', function() { +describe('failure hooks', function () { this.timeout(60 * 1000); it('runs and prints expected output', () => { diff --git a/packages/kbn-test/src/functional_test_runner/cli.ts b/packages/kbn-test/src/functional_test_runner/cli.ts index 276a51c3a6a99..fd5ee5ad3ae44 100644 --- a/packages/kbn-test/src/functional_test_runner/cli.ts +++ b/packages/kbn-test/src/functional_test_runner/cli.ts @@ -87,7 +87,7 @@ export function runFtrCli() { } }; - process.on('unhandledRejection', err => + process.on('unhandledRejection', (err) => teardown( err instanceof Error ? err : new Error(`non-Error type rejection value: ${inspect(err)}`) ) diff --git a/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts b/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts index 3a66ba22ccf3d..03d4d7643607f 100644 --- a/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts +++ b/packages/kbn-test/src/functional_test_runner/functional_test_runner.ts @@ -89,7 +89,7 @@ export class FunctionalTestRunner { // promise-like objects which never resolve, essentially disabling them // allowing us to load the test files and populate the mocha suites const readStubbedProviderSpec = (type: string, providers: any) => - readProviderSpec(type, providers).map(p => ({ + readProviderSpec(type, providers).map((p) => ({ ...p, fn: () => ({ then: () => {}, diff --git a/packages/kbn-test/src/functional_test_runner/lib/config/config.ts b/packages/kbn-test/src/functional_test_runner/lib/config/config.ts index ad9247523797a..e38520f00e45b 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/config/config.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/config/config.ts @@ -114,7 +114,7 @@ export class Config { throw new Error(`Unknown config key "${key}"`); } - return cloneDeep(get(this[$values], key, defaultValue), v => { + return cloneDeep(get(this[$values], key, defaultValue), (v) => { if (typeof v === 'function') { return v; } @@ -122,7 +122,7 @@ export class Config { } public getAll() { - return cloneDeep(this[$values], v => { + return cloneDeep(this[$values], (v) => { if (typeof v === 'function') { return v; } diff --git a/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts b/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts index f4b91d154cbb8..29ec28175a851 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/config/schema.ts @@ -30,12 +30,8 @@ const INSPECTING = const urlPartsSchema = () => Joi.object() .keys({ - protocol: Joi.string() - .valid('http', 'https') - .default('http'), - hostname: Joi.string() - .hostname() - .default('localhost'), + protocol: Joi.string().valid('http', 'https').default('http'), + hostname: Joi.string().hostname().default('localhost'), port: Joi.number(), auth: Joi.string().regex(/^[^:]+:.+$/, 'username and password separated by a colon'), username: Joi.string(), @@ -66,33 +62,21 @@ export const schema = Joi.object() suiteFiles: Joi.object() .keys({ - include: Joi.array() - .items(Joi.string()) - .default([]), - exclude: Joi.array() - .items(Joi.string()) - .default([]), + include: Joi.array().items(Joi.string()).default([]), + exclude: Joi.array().items(Joi.string()).default([]), }) .default(), suiteTags: Joi.object() .keys({ - include: Joi.array() - .items(Joi.string()) - .default([]), - exclude: Joi.array() - .items(Joi.string()) - .default([]), + include: Joi.array().items(Joi.string()).default([]), + exclude: Joi.array().items(Joi.string()).default([]), }) .default(), - services: Joi.object() - .pattern(ID_PATTERN, Joi.func().required()) - .default(), + services: Joi.object().pattern(ID_PATTERN, Joi.func().required()).default(), - pageObjects: Joi.object() - .pattern(ID_PATTERN, Joi.func().required()) - .default(), + pageObjects: Joi.object().pattern(ID_PATTERN, Joi.func().required()).default(), timeouts: Joi.object() .keys({ @@ -135,9 +119,7 @@ export const schema = Joi.object() browser: Joi.object() .keys({ - type: Joi.string() - .valid('chrome', 'firefox', 'ie', 'msedge') - .default('chrome'), + type: Joi.string().valid('chrome', 'firefox', 'ie', 'msedge').default('chrome'), logPollingMs: Joi.number().default(100), }) @@ -210,9 +192,7 @@ export const schema = Joi.object() .default(), // definition of apps that work with `common.navigateToApp()` - apps: Joi.object() - .pattern(ID_PATTERN, appUrlPartsSchema()) - .default(), + apps: Joi.object().pattern(ID_PATTERN, appUrlPartsSchema()).default(), // settings for the esArchiver module esArchiver: Joi.object() diff --git a/packages/kbn-test/src/functional_test_runner/lib/failure_metadata.ts b/packages/kbn-test/src/functional_test_runner/lib/failure_metadata.ts index be033e063fb9d..fdf8b3c0ddfa8 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/failure_metadata.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/failure_metadata.ts @@ -39,7 +39,7 @@ export class FailureMetadata { ); } - lifecycle.beforeEachRunnable.add(runnable => { + lifecycle.beforeEachRunnable.add((runnable) => { this.currentRunnable = runnable; }); } @@ -57,7 +57,7 @@ export class FailureMetadata { } addMessages(messages: string[]) { - this.add(current => ({ + this.add((current) => ({ messages: [...(Array.isArray(current.messages) ? current.messages : []), ...messages], })); } @@ -76,7 +76,7 @@ export class FailureMetadata { const slash = prefix.endsWith('/') ? '' : '/'; const urlPath = Path.relative(REPO_ROOT, repoPath) .split(Path.sep) - .map(c => encodeURIComponent(c)) + .map((c) => encodeURIComponent(c)) .join('/'); if (urlPath.startsWith('..')) { @@ -91,7 +91,7 @@ export class FailureMetadata { url, }; - this.add(current => ({ + this.add((current) => ({ screenshots: [...(Array.isArray(current.screenshots) ? current.screenshots : []), screenshot], })); diff --git a/packages/kbn-test/src/functional_test_runner/lib/lifecycle_event.ts b/packages/kbn-test/src/functional_test_runner/lib/lifecycle_event.ts index 22b7363454361..ce242d44009f2 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/lifecycle_event.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/lifecycle_event.ts @@ -57,7 +57,7 @@ export class LifecycleEvent { } try { - await Promise.all(this.handlers.map(async fn => await fn(...args))); + await Promise.all(this.handlers.map(async (fn) => await fn(...args))); } finally { this.afterSubj.next(undefined); if (this.options.singular) { diff --git a/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.test.ts b/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.test.ts index 94dd76884f2ca..d17c5503c42f8 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.test.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/lifecycle_phase.test.ts @@ -104,7 +104,7 @@ describe('without randomness', () => { const handler = jest.fn(async () => { order.push('handler start'); - await new Promise(resolve => setTimeout(resolve, 100)); + await new Promise((resolve) => setTimeout(resolve, 100)); order.push('handler done'); }); phase.add(handler); @@ -124,10 +124,10 @@ describe('without randomness', () => { const phase = new LifecyclePhase({ singular: true }); const beforeNotifs: Array> = []; - phase.before$.pipe(materialize()).subscribe(n => beforeNotifs.push(n)); + phase.before$.pipe(materialize()).subscribe((n) => beforeNotifs.push(n)); const afterNotifs: Array> = []; - phase.after$.pipe(materialize()).subscribe(n => afterNotifs.push(n)); + phase.after$.pipe(materialize()).subscribe((n) => afterNotifs.push(n)); await phase.trigger(); expect(beforeNotifs).toMatchInlineSnapshot(` diff --git a/packages/kbn-test/src/functional_test_runner/lib/load_tracer.ts b/packages/kbn-test/src/functional_test_runner/lib/load_tracer.ts index 26a0e9617a7c7..588e32b5d274c 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/load_tracer.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/load_tracer.ts @@ -22,7 +22,7 @@ const globalLoadPath: Array<{ ident: string; description: string }> = []; function getPath(startAt = 0) { return globalLoadPath .slice(startAt) - .map(step => step.description) + .map((step) => step.description) .join(' -> '); } @@ -49,7 +49,7 @@ function addPathToMessage(message: string, startAt?: number) { * @return {Any} the value produced by load() */ export function loadTracer(ident: any, description: string, load: () => Promise | void) { - const isCircular = globalLoadPath.find(step => step.ident === ident); + const isCircular = globalLoadPath.find((step) => step.ident === ident); if (isCircular) { throw new Error(addPathToMessage(`Circular reference to "${description}"`)); } diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/assignment_proxy.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/assignment_proxy.js index 5c08d566d3d73..ecf8f7af87ed8 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/assignment_proxy.js +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/assignment_proxy.js @@ -31,7 +31,7 @@ export function createAssignmentProxy(object, interceptor) { get(target, property) { if (property === 'revertProxiedAssignments') { - return function() { + return function () { for (const [property, value] of originalValues) { object[property] = value; } diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/decorate_mocha_ui.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/decorate_mocha_ui.js index 1cac852a7e713..5d3d8fe7d759b 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/decorate_mocha_ui.js +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/decorate_mocha_ui.js @@ -57,12 +57,12 @@ export function decorateMochaUi(lifecycle, context) { throw new Error(`Unexpected arguments to ${name}(${argumentsList.join(', ')})`); } - argumentsList[1] = function() { + argumentsList[1] = function () { before(async () => { await lifecycle.beforeTestSuite.trigger(this); }); - this.tags = tags => { + this.tags = (tags) => { this._tags = [].concat(this._tags || [], tags); }; diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.js index 302d43fac3e61..f7aaabd5a4495 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.js +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.js @@ -30,7 +30,7 @@ export function filterSuitesByTags({ log, mocha, include, exclude }) { mocha.excludedTests = []; // collect all the tests from some suite, including it's children - const collectTests = suite => + const collectTests = (suite) => suite.suites.reduce((acc, s) => acc.concat(collectTests(s)), suite.tests); // if include tags were provided, filter the tree once to @@ -38,8 +38,10 @@ export function filterSuitesByTags({ log, mocha, include, exclude }) { if (include.length) { log.info('Only running suites (and their sub-suites) if they include the tag(s):', include); - const isIncluded = suite => (!suite._tags ? false : suite._tags.some(t => include.includes(t))); - const isChildIncluded = suite => suite.suites.some(s => isIncluded(s) || isChildIncluded(s)); + const isIncluded = (suite) => + !suite._tags ? false : suite._tags.some((t) => include.includes(t)); + const isChildIncluded = (suite) => + suite.suites.some((s) => isIncluded(s) || isChildIncluded(s)); (function recurse(parentSuite) { const children = parentSuite.suites; @@ -73,7 +75,7 @@ export function filterSuitesByTags({ log, mocha, include, exclude }) { if (exclude.length) { log.info('Filtering out any suites that include the tag(s):', exclude); - const isNotExcluded = suite => !suite._tags || !suite._tags.some(t => exclude.includes(t)); + const isNotExcluded = (suite) => !suite._tags || !suite._tags.some((t) => exclude.includes(t)); (function recurse(parentSuite) { const children = parentSuite.suites; diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.test.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.test.js index 9901f62ae71cf..6ecfadfd25d6d 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.test.js +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/filter_suites_by_tags.test.js @@ -26,21 +26,21 @@ import Test from 'mocha/lib/test'; import { filterSuitesByTags } from './filter_suites_by_tags'; function setup({ include, exclude }) { - return new Promise(resolve => { + return new Promise((resolve) => { const history = []; const mocha = new Mocha({ reporter: class { constructor(runner) { - runner.on('hook', hook => { + runner.on('hook', (hook) => { history.push(`hook: ${hook.fullTitle()}`); }); - runner.on('pass', test => { + runner.on('pass', (test) => { history.push(`test: ${test.fullTitle()}`); }); - runner.on('suite', suite => { + runner.on('suite', (suite) => { history.push(`suite: ${suite.fullTitle()}`); }); } diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/load_test_files.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/load_test_files.js index 6ee65b1b7e394..5c23be6361866 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/load_test_files.js +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/load_test_files.js @@ -32,7 +32,7 @@ import { decorateMochaUi } from './decorate_mocha_ui'; * @return {undefined} - mutates mocha, no return value */ export const loadTestFiles = ({ mocha, log, lifecycle, providers, paths, updateBaselines }) => { - const innerLoadTestFile = path => { + const innerLoadTestFile = (path) => { if (typeof path !== 'string' || !isAbsolute(path)) { throw new TypeError('loadTestFile() only accepts absolute paths'); } diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/reporter/reporter.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/reporter/reporter.js index 0e8c1bc121e15..90bea1c3aa293 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/reporter/reporter.js +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/reporter/reporter.js @@ -54,7 +54,7 @@ export function MochaReporterProvider({ getService }) { if (config.get('junit.enabled') && config.get('junit.reportName')) { setupJUnitReportGeneration(runner, { reportName: config.get('junit.reportName'), - getTestMetadata: t => failureMetadata.get(t), + getTestMetadata: (t) => failureMetadata.get(t), }); } } @@ -76,7 +76,7 @@ export function MochaReporterProvider({ getService }) { new ToolingLogTextWriter({ level: 'debug', writeTo: { - write: line => { + write: (line) => { // if the current runnable is a beforeEach hook then // `runner.suite` is set to the suite that defined the // hook, rather than the suite executing, so instead we @@ -104,7 +104,7 @@ export function MochaReporterProvider({ getService }) { log.write(''); }; - onHookStart = hook => { + onHookStart = (hook) => { log.write(`-> ${colors.suite(hook.title)}`); log.indent(2); }; @@ -113,7 +113,7 @@ export function MochaReporterProvider({ getService }) { log.indent(-2); }; - onSuiteStart = suite => { + onSuiteStart = (suite) => { if (!suite.root) { log.write('-: ' + colors.suite(suite.title)); } @@ -127,28 +127,28 @@ export function MochaReporterProvider({ getService }) { } }; - onTestStart = test => { + onTestStart = (test) => { log.write(`-> ${test.title}`); log.indent(2); }; - onTestEnd = test => { + onTestEnd = (test) => { snapshotLogsForRunnable(test); log.indent(-2); }; - onPending = test => { + onPending = (test) => { log.write('-> ' + colors.pending(test.title)); log.indent(2); }; - onPass = test => { + onPass = (test) => { const time = colors.speed(test.speed, ` (${ms(test.duration)})`); const pass = colors.pass(`${symbols.ok} pass`); log.write(`- ${pass} ${time} "${test.fullTitle()}"`); }; - onFail = runnable => { + onFail = (runnable) => { // NOTE: this is super gross // // - I started by trying to extract the Base.list() logic from mocha @@ -173,8 +173,8 @@ export function MochaReporterProvider({ getService }) { // drop the first two lines, (empty + test title) .slice(2) // move leading colors behind leading spaces - .map(line => line.replace(/^((?:\[.+m)+)(\s+)/, '$2$1')) - .map(line => ` ${line}`) + .map((line) => line.replace(/^((?:\[.+m)+)(\s+)/, '$2$1')) + .map((line) => ` ${line}`) .join('\n') ); diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/run_tests.ts b/packages/kbn-test/src/functional_test_runner/lib/mocha/run_tests.ts index 654f588fda858..a23a5fb1407a0 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/run_tests.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/run_tests.ts @@ -39,7 +39,7 @@ export async function runTests(lifecycle: Lifecycle, mocha: Mocha) { if (!runComplete) runner.abort(); }); - return new Promise(resolve => { + return new Promise((resolve) => { const respond = () => resolve(runner.failures); // if there are no tests, mocha.run() is sync diff --git a/packages/kbn-test/src/functional_test_runner/lib/mocha/setup_mocha.js b/packages/kbn-test/src/functional_test_runner/lib/mocha/setup_mocha.js index 61851cece0e8f..3ac7a50cd28ea 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/mocha/setup_mocha.js +++ b/packages/kbn-test/src/functional_test_runner/lib/mocha/setup_mocha.js @@ -42,7 +42,7 @@ export async function setupMocha(lifecycle, log, config, providers) { }); // global beforeEach hook in root suite triggers before all others - mocha.suite.beforeEach('global before each', async function() { + mocha.suite.beforeEach('global before each', async function () { await lifecycle.beforeEachTest.trigger(this.currentTest); }); @@ -62,15 +62,15 @@ export async function setupMocha(lifecycle, log, config, providers) { filterSuitesByTags({ log, mocha, - include: config.get('suiteFiles.include').map(file => relative(REPO_ROOT, file)), - exclude: config.get('suiteFiles.exclude').map(file => relative(REPO_ROOT, file)), + include: config.get('suiteFiles.include').map((file) => relative(REPO_ROOT, file)), + exclude: config.get('suiteFiles.exclude').map((file) => relative(REPO_ROOT, file)), }); filterSuitesByTags({ log, mocha, - include: config.get('suiteTags.include').map(tag => tag.replace(/-\d+$/, '')), - exclude: config.get('suiteTags.exclude').map(tag => tag.replace(/-\d+$/, '')), + include: config.get('suiteTags.include').map((tag) => tag.replace(/-\d+$/, '')), + exclude: config.get('suiteTags.exclude').map((tag) => tag.replace(/-\d+$/, '')), }); return mocha; diff --git a/packages/kbn-test/src/functional_test_runner/lib/providers/async_instance.ts b/packages/kbn-test/src/functional_test_runner/lib/providers/async_instance.ts index 7bb1b2bc153c1..2d5644fbad290 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/providers/async_instance.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/providers/async_instance.ts @@ -34,7 +34,7 @@ export const createAsyncInstance = ( ): AsyncInstance => { let instance: T | symbol = INITIALIZING; - const initPromise = promiseForValue.then(v => (instance = v)); + const initPromise = promiseForValue.then((v) => (instance = v)); const loadingTarget = { init() { return initPromise; 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 f9ad86be634fc..c58747e07dcf4 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 @@ -37,7 +37,7 @@ export class ProviderCollection { public getPageObjects = (names: string[]) => { const pageObjects: Record = {}; - names.forEach(name => (pageObjects[name] = this.getPageObject(name))); + names.forEach((name) => (pageObjects[name] = this.getPageObject(name))); return pageObjects; }; @@ -78,7 +78,7 @@ export class ProviderCollection { } private findProvider(type: string, name: string) { - return this.providers.find(p => p.type === type && p.name === name); + return this.providers.find((p) => p.type === type && p.name === name); } private getProvider(type: string, name: string) { diff --git a/packages/kbn-test/src/functional_test_runner/lib/providers/read_provider_spec.ts b/packages/kbn-test/src/functional_test_runner/lib/providers/read_provider_spec.ts index be8e25f102b09..a29b220bc603b 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/providers/read_provider_spec.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/providers/read_provider_spec.ts @@ -21,7 +21,7 @@ export type Providers = ReturnType; export type Provider = Providers extends Array ? X : unknown; export function readProviderSpec(type: string, providers: Record any>) { - return Object.keys(providers).map(name => { + return Object.keys(providers).map((name) => { return { type, name, diff --git a/packages/kbn-test/src/functional_test_runner/lib/providers/verbose_instance.ts b/packages/kbn-test/src/functional_test_runner/lib/providers/verbose_instance.ts index 93a87f3496b54..1967e98306d42 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/providers/verbose_instance.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/providers/verbose_instance.ts @@ -23,7 +23,7 @@ import { ToolingLog } from '@kbn/dev-utils'; function printArgs(args: any[]): string { return args - .map(arg => { + .map((arg) => { if (typeof arg === 'string' || typeof arg === 'number' || arg instanceof Date) { return inspect(arg); } @@ -42,7 +42,7 @@ export function createVerboseInstance( name: string, instance: { [k: string]: any; [i: number]: any } ) { - if (!log.getWriters().some(l => (l as any).level.flags.verbose)) { + if (!log.getWriters().some((l) => (l as any).level.flags.verbose)) { return instance; } @@ -54,7 +54,7 @@ export function createVerboseInstance( return value; } - return function(this: any, ...args: any[]) { + return function (this: any, ...args: any[]) { log.verbose(`${name}.${prop}(${printArgs(args)})`); log.indent(2); 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 b6c2c0a6d511d..f879408bf2beb 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 @@ -145,8 +145,8 @@ describe('SuiteTracker', () => { const { suiteTracker } = await runLifecycleWithMocks([root, parent, withTests]); const suites = suiteTracker.getAllFinishedSuites(); - const finishedRoot = suites.find(s => s.title === 'root'); - const finishedWithTests = suites.find(s => s.title !== 'root'); + const finishedRoot = suites.find((s) => s.title === 'root'); + const finishedWithTests = suites.find((s) => s.title !== 'root'); expect(finishedRoot).toBeTruthy(); expect(finishedRoot?.hasTests).toBeFalsy(); diff --git a/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.ts b/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.ts index 8967251ea78de..b346be2d58dad 100644 --- a/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.ts +++ b/packages/kbn-test/src/functional_test_runner/lib/suite_tracker.ts @@ -70,7 +70,7 @@ export class SuiteTracker { const config = relative(REPO_ROOT, configPathAbsolute); - lifecycle.beforeTestSuite.add(suite => { + lifecycle.beforeTestSuite.add((suite) => { const tracked = this.getTracked(suite); tracked.startTime = new Date(); }); @@ -92,7 +92,7 @@ export class SuiteTracker { lifecycle.testFailure.add(handleFailure); lifecycle.testHookFailure.add(handleFailure); - lifecycle.afterTestSuite.add(suite => { + lifecycle.afterTestSuite.add((suite) => { const tracked = this.getTracked(suite); tracked.endTime = new Date(); diff --git a/packages/kbn-test/src/functional_tests/cli/run_tests/args.js b/packages/kbn-test/src/functional_tests/cli/run_tests/args.js index 7d2414305de8e..94d510915d8e5 100644 --- a/packages/kbn-test/src/functional_tests/cli/run_tests/args.js +++ b/packages/kbn-test/src/functional_tests/cli/run_tests/args.js @@ -73,8 +73,8 @@ const options = { export function displayHelp() { const helpOptions = Object.keys(options) - .filter(name => name !== '_') - .map(name => { + .filter((name) => name !== '_') + .map((name) => { const option = options[name]; return { ...option, @@ -82,7 +82,7 @@ export function displayHelp() { default: option.defaultHelp || '', }; }) - .map(option => { + .map((option) => { return `--${option.usage.padEnd(28)} ${option.desc} ${option.default}`; }) .join(`\n `); @@ -149,7 +149,7 @@ export function processOptions(userOptions, defaultConfigPaths) { return { ...userOptions, - configs: configs.map(c => resolve(c)), + configs: configs.map((c) => resolve(c)), createLogger, extraKbnOpts: userOptions._, }; diff --git a/packages/kbn-test/src/functional_tests/cli/run_tests/cli.js b/packages/kbn-test/src/functional_tests/cli/run_tests/cli.js index 27335739d290e..cf49fc77e479f 100644 --- a/packages/kbn-test/src/functional_tests/cli/run_tests/cli.js +++ b/packages/kbn-test/src/functional_tests/cli/run_tests/cli.js @@ -30,7 +30,7 @@ import { processOptions, displayHelp } from './args'; * if no config option is passed */ export async function runTestsCli(defaultConfigPaths) { - await runCli(displayHelp, async userOptions => { + await runCli(displayHelp, async (userOptions) => { const options = processOptions(userOptions, defaultConfigPaths); await runTests(options); }); diff --git a/packages/kbn-test/src/functional_tests/cli/start_servers/args.js b/packages/kbn-test/src/functional_tests/cli/start_servers/args.js index c221ad42fcad1..e604e86de8b3a 100644 --- a/packages/kbn-test/src/functional_tests/cli/start_servers/args.js +++ b/packages/kbn-test/src/functional_tests/cli/start_servers/args.js @@ -45,8 +45,8 @@ const options = { export function displayHelp() { const helpOptions = Object.keys(options) - .filter(name => name !== '_') - .map(name => { + .filter((name) => name !== '_') + .map((name) => { const option = options[name]; return { ...option, @@ -54,7 +54,7 @@ export function displayHelp() { default: option.defaultHelp || '', }; }) - .map(option => { + .map((option) => { return `--${option.usage.padEnd(30)} ${option.desc} ${option.default}`; }) .join(`\n `); diff --git a/packages/kbn-test/src/functional_tests/cli/start_servers/cli.js b/packages/kbn-test/src/functional_tests/cli/start_servers/cli.js index 5716441798aa4..d4499ee76e313 100644 --- a/packages/kbn-test/src/functional_tests/cli/start_servers/cli.js +++ b/packages/kbn-test/src/functional_tests/cli/start_servers/cli.js @@ -27,7 +27,7 @@ import { processOptions, displayHelp } from './args'; * if no config option is passed */ export async function startServersCli(defaultConfigPath) { - await runCli(displayHelp, async userOptions => { + await runCli(displayHelp, async (userOptions) => { const options = processOptions(userOptions, defaultConfigPath); await startServers(options); }); diff --git a/packages/kbn-test/src/functional_tests/lib/run_cli.js b/packages/kbn-test/src/functional_tests/lib/run_cli.js index 56f6f36f5388f..51a970e1a305d 100644 --- a/packages/kbn-test/src/functional_tests/lib/run_cli.js +++ b/packages/kbn-test/src/functional_tests/lib/run_cli.js @@ -53,12 +53,7 @@ export async function runCli(getHelpText, run) { if (!(error instanceof CliError)) { // first line in the stack trace is the message, skip it as we log it directly and color it red if (error.stack) { - console.log( - error.stack - .split('\n') - .slice(1) - .join('\n') - ); + console.log(error.stack.split('\n').slice(1).join('\n')); } else { console.log(' (no stack trace)'); } diff --git a/packages/kbn-test/src/functional_tests/lib/run_cli.test.js b/packages/kbn-test/src/functional_tests/lib/run_cli.test.js index 235f50f0d9dd7..959f965917530 100644 --- a/packages/kbn-test/src/functional_tests/lib/run_cli.test.js +++ b/packages/kbn-test/src/functional_tests/lib/run_cli.test.js @@ -25,7 +25,7 @@ const mockConsoleLog = jest.spyOn(console, 'log').mockImplementation(() => {}); const actualProcessArgv = process.argv; -const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); beforeEach(() => { process.argv = actualProcessArgv.slice(0, 2); @@ -72,7 +72,7 @@ it('waits for promise returned from run function to resolve before resolving', a let resolveMockRun; const mockRun = jest.fn().mockImplementation( () => - new Promise(resolve => { + new Promise((resolve) => { resolveMockRun = resolve; }) ); diff --git a/packages/kbn-test/src/functional_tests/lib/run_elasticsearch.js b/packages/kbn-test/src/functional_tests/lib/run_elasticsearch.js index 5f58190078f0d..3d174791fffc1 100644 --- a/packages/kbn-test/src/functional_tests/lib/run_elasticsearch.js +++ b/packages/kbn-test/src/functional_tests/lib/run_elasticsearch.js @@ -63,7 +63,7 @@ export async function runElasticsearch({ config, options }) { function getRelativeCertificateAuthorityPath(esConfig = []) { const caConfig = esConfig.find( - config => config.indexOf('--elasticsearch.ssl.certificateAuthorities') === 0 + (config) => config.indexOf('--elasticsearch.ssl.certificateAuthorities') === 0 ); return caConfig ? caConfig.split('=')[1] : undefined; } diff --git a/packages/kbn-test/src/functional_tests/lib/run_kibana_server.js b/packages/kbn-test/src/functional_tests/lib/run_kibana_server.js index a5744d6498801..fb9f8f7a52408 100644 --- a/packages/kbn-test/src/functional_tests/lib/run_kibana_server.js +++ b/packages/kbn-test/src/functional_tests/lib/run_kibana_server.js @@ -58,9 +58,9 @@ function collectCliArgs(config, { installDir, extraKbnOpts }) { return pipe( serverArgs, - args => (installDir ? args.filter(a => a !== '--oss') : args), - args => (installDir ? [...buildArgs, ...args] : [KIBANA_EXEC_PATH, ...sourceArgs, ...args]), - args => args.concat(extraKbnOpts || []) + (args) => (installDir ? args.filter((a) => a !== '--oss') : args), + (args) => (installDir ? [...buildArgs, ...args] : [KIBANA_EXEC_PATH, ...sourceArgs, ...args]), + (args) => args.concat(extraKbnOpts || []) ); } @@ -79,7 +79,7 @@ function filterCliArgs(args) { // the current val. If so, skip this val. if ( !allowsDuplicate(val) && - findIndexFrom(args, ++ind, opt => opt.split('=')[0] === val.split('=')[0]) > -1 + findIndexFrom(args, ++ind, (opt) => opt.split('=')[0] === val.split('=')[0]) > -1 ) { return acc; } @@ -112,7 +112,7 @@ function isBasePathSettingOverridden(args, val, ind) { const basePathKeys = ['--no-base-path', '--server.basePath']; if (basePathKeys.includes(key)) { - if (findIndexFrom(args, ++ind, opt => basePathKeys.includes(opt.split('=')[0])) > -1) { + if (findIndexFrom(args, ++ind, (opt) => basePathKeys.includes(opt.split('=')[0])) > -1) { return true; } } diff --git a/packages/kbn-test/src/functional_tests/tasks.js b/packages/kbn-test/src/functional_tests/tasks.js index 8645923a13d30..7d4fc84d47bda 100644 --- a/packages/kbn-test/src/functional_tests/tasks.js +++ b/packages/kbn-test/src/functional_tests/tasks.js @@ -34,7 +34,7 @@ import { import { readConfigFile } from '../functional_test_runner/lib'; -const makeSuccessMessage = options => { +const makeSuccessMessage = (options) => { const installDirFlag = options.installDir ? ` --kibana-install-dir=${options.installDir}` : ''; return ( @@ -92,7 +92,7 @@ export async function runTests(options) { continue; } - await withProcRunner(log, async procs => { + await withProcRunner(log, async (procs) => { const config = await readConfigFile(log, configPath); let es; @@ -128,7 +128,7 @@ export async function startServers(options) { log, }; - await withProcRunner(log, async procs => { + await withProcRunner(log, async (procs) => { const config = await readConfigFile(log, options.config); const es = await runElasticsearch({ config, options: opts }); diff --git a/packages/kbn-test/src/mocha/__tests__/junit_report_generation.js b/packages/kbn-test/src/mocha/__tests__/junit_report_generation.js index 6edd0a551ebd0..00a11432dd9e8 100644 --- a/packages/kbn-test/src/mocha/__tests__/junit_report_generation.js +++ b/packages/kbn-test/src/mocha/__tests__/junit_report_generation.js @@ -49,8 +49,8 @@ describe('dev/mocha/junit report generation', () => { }); mocha.addFile(resolve(PROJECT_DIR, 'test.js')); - await new Promise(resolve => mocha.run(resolve)); - const report = await fcb(cb => + await new Promise((resolve) => mocha.run(resolve)); + const report = await fcb((cb) => parseString(readFileSync(makeJunitReportPath(PROJECT_DIR, 'test')), cb) ); diff --git a/packages/kbn-test/src/mocha/junit_report_generation.js b/packages/kbn-test/src/mocha/junit_report_generation.js index b56741b48d367..7e39c32ee4db8 100644 --- a/packages/kbn-test/src/mocha/junit_report_generation.js +++ b/packages/kbn-test/src/mocha/junit_report_generation.js @@ -39,26 +39,26 @@ export function setupJUnitReportGeneration(runner, options = {}) { const stats = {}; const results = []; - const getDuration = node => + const getDuration = (node) => node.startTime && node.endTime ? ((node.endTime - node.startTime) / 1000).toFixed(3) : null; - const findAllTests = suite => + const findAllTests = (suite) => suite.suites.reduce((acc, suite) => acc.concat(findAllTests(suite)), suite.tests); - const setStartTime = node => { + const setStartTime = (node) => { node.startTime = dateNow(); }; - const setEndTime = node => { + const setEndTime = (node) => { node.endTime = dateNow(); }; - const getFullTitle = node => { + const getFullTitle = (node) => { const parentTitle = node.parent && getFullTitle(node.parent); return parentTitle ? `${parentTitle} ${node.title}` : node.title; }; - const getPath = node => { + const getPath = (node) => { if (node.file) { return relative(rootDirectory, node.file); } @@ -75,7 +75,7 @@ export function setupJUnitReportGeneration(runner, options = {}) { runner.on('hook', setStartTime); runner.on('hook end', setEndTime); runner.on('test', setStartTime); - runner.on('pass', node => results.push({ node })); + runner.on('pass', (node) => results.push({ node })); runner.on('pass', setEndTime); runner.on('fail', (node, error) => results.push({ failed: true, error, node })); runner.on('fail', setEndTime); @@ -89,16 +89,16 @@ export function setupJUnitReportGeneration(runner, options = {}) { } // filter out just the failures - const failures = results.filter(result => result.failed); + const failures = results.filter((result) => result.failed); // any failure that isn't for a test is for a hook - const failedHooks = failures.filter(result => !allTests.includes(result.node)); + const failedHooks = failures.filter((result) => !allTests.includes(result.node)); // mocha doesn't emit 'pass' or 'fail' when it skips a test // or a test is pending, so we find them ourselves const skippedResults = allTests - .filter(node => node.pending || !results.find(result => result.node === node)) - .map(node => ({ skipped: true, node })); + .filter((node) => node.pending || !results.find((result) => result.node === node)) + .map((node) => ({ skipped: true, node })); const builder = xmlBuilder.create( 'testsuites', @@ -124,7 +124,7 @@ export function setupJUnitReportGeneration(runner, options = {}) { }); } - [...results, ...skippedResults].forEach(result => { + [...results, ...skippedResults].forEach((result) => { const el = addTestcaseEl(result.node); if (result.failed) { diff --git a/packages/kbn-test/src/mocha/run_mocha_cli.js b/packages/kbn-test/src/mocha/run_mocha_cli.js index 77f40aded1d7f..3c77fef963a76 100644 --- a/packages/kbn-test/src/mocha/run_mocha_cli.js +++ b/packages/kbn-test/src/mocha/run_mocha_cli.js @@ -85,7 +85,7 @@ export function runMochaCli() { ], } ) - .forEach(file => { + .forEach((file) => { process.argv.push(file); }); } diff --git a/packages/kbn-ui-framework/Gruntfile.js b/packages/kbn-ui-framework/Gruntfile.js index cf0c1643055eb..177fd1f153155 100644 --- a/packages/kbn-ui-framework/Gruntfile.js +++ b/packages/kbn-ui-framework/Gruntfile.js @@ -26,7 +26,7 @@ const debounce = require('lodash/function/debounce'); const platform = require('os').platform(); const isPlatformWindows = /^win/.test(platform); -module.exports = function(grunt) { +module.exports = function (grunt) { grunt.initConfig({ clean: { target: ['target'], @@ -62,7 +62,7 @@ module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-copy'); grunt.registerTask('prodBuild', ['clean:target', 'copy:makeProdBuild', 'babel:prodBuild']); - grunt.registerTask('docSiteBuild', function() { + grunt.registerTask('docSiteBuild', function () { const done = this.async(); const serverCmd = { @@ -94,17 +94,17 @@ module.exports = function(grunt) { uiFrameworkServerBuild.then(done); }); - grunt.registerTask('docSiteStart', function() { + grunt.registerTask('docSiteStart', function () { const done = this.async(); Promise.all([uiFrameworkWatch(), uiFrameworkServerStart()]).then(done); }); - grunt.registerTask('compileCssLight', function() { + grunt.registerTask('compileCssLight', function () { const done = this.async(); uiFrameworkCompileLight().then(done); }); - grunt.registerTask('compileCssDark', function() { + grunt.registerTask('compileCssDark', function () { const done = this.async(); uiFrameworkCompileDark().then(done); }); @@ -146,19 +146,19 @@ module.exports = function(grunt) { const src = 'src/kui_light.scss'; const dest = 'dist/kui_light.css'; - return new Promise(resolve => { + return new Promise((resolve) => { sass.render( { file: src, }, - function(error, result) { + function (error, result) { if (error) { grunt.log.error(error); } postcss([postcssConfig]) .process(result.css, { from: src, to: dest }) - .then(result => { + .then((result) => { grunt.file.write(dest, result.css); if (result.map) { @@ -176,19 +176,19 @@ module.exports = function(grunt) { const src = 'src/kui_dark.scss'; const dest = 'dist/kui_dark.css'; - return new Promise(resolve => { + return new Promise((resolve) => { sass.render( { file: src, }, - function(error, result) { + function (error, result) { if (error) { grunt.log.error(error); } postcss([postcssConfig]) .process(result.css, { from: src, to: dest }) - .then(result => { + .then((result) => { grunt.file.write(dest, result.css); if (result.map) { diff --git a/packages/kbn-ui-framework/doc_site/src/actions/example_nav_actions.js b/packages/kbn-ui-framework/doc_site/src/actions/example_nav_actions.js index 205be7920aa60..1836d00af4ab3 100644 --- a/packages/kbn-ui-framework/doc_site/src/actions/example_nav_actions.js +++ b/packages/kbn-ui-framework/doc_site/src/actions/example_nav_actions.js @@ -25,7 +25,7 @@ export const registerSection = (id, name) => ({ name, }); -export const unregisterSection = id => ({ +export const unregisterSection = (id) => ({ type: ActionTypes.UNREGISTER_SECTION, id, }); diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_code/guide_code.js b/packages/kbn-ui-framework/doc_site/src/components/guide_code/guide_code.js index f5845becbe77f..41aeb74d24b6b 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_code/guide_code.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_code/guide_code.js @@ -19,4 +19,4 @@ import React from 'react'; -export const GuideCode = props => {props.children}; +export const GuideCode = (props) => {props.children}; diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_code_viewer/guide_code_viewer.js b/packages/kbn-ui-framework/doc_site/src/components/guide_code_viewer/guide_code_viewer.js index b1d2f8e031f7c..b387a89b7072c 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_code_viewer/guide_code_viewer.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_code_viewer/guide_code_viewer.js @@ -65,7 +65,7 @@ export class GuideCodeViewer extends Component { 'is-code-viewer-open': this.props.isOpen, }); - const codeSections = this.props.source.map(sourceObject => + const codeSections = this.props.source.map((sourceObject) => this.renderSection(sourceObject.type, sourceObject.code) ); diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_demo/guide_demo.js b/packages/kbn-ui-framework/doc_site/src/components/guide_demo/guide_demo.js index 93470ac6de128..d968e014370f8 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_demo/guide_demo.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_demo/guide_demo.js @@ -68,7 +68,7 @@ export class GuideDemo extends Component { }); return ( -
(this.content = c)} {...rest}> +
(this.content = c)} {...rest}> {children}
); diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_link/guide_link.js b/packages/kbn-ui-framework/doc_site/src/components/guide_link/guide_link.js index b49880e0e3bfa..62d1e3ac8bedd 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_link/guide_link.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_link/guide_link.js @@ -19,7 +19,7 @@ import React from 'react'; -export const GuideLink = props => ( +export const GuideLink = (props) => ( {props.children} diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_nav/guide_nav.js b/packages/kbn-ui-framework/doc_site/src/components/guide_nav/guide_nav.js index f31a3b10eef4e..49225c96ba5e5 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_nav/guide_nav.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_nav/guide_nav.js @@ -120,7 +120,7 @@ export class GuideNav extends Component { }); const componentNavItems = this.props.components - .filter(item => item.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) + .filter((item) => item.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) .map((item, index) => { const icon = item.hasReact ?
: undefined; return ( @@ -135,7 +135,7 @@ export class GuideNav extends Component { }); const sandboxNavItems = this.props.sandboxes - .filter(item => item.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) + .filter((item) => item.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1) .map((item, index) => { const icon = item.hasReact ?
: undefined; return ( diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_page/guide_page_container.js b/packages/kbn-ui-framework/doc_site/src/components/guide_page/guide_page_container.js index 5d8e6993abe4e..0a7442fce4723 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_page/guide_page_container.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_page/guide_page_container.js @@ -21,7 +21,7 @@ import { connect } from 'react-redux'; import { getSections } from '../../store'; import { GuidePage } from './guide_page'; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ sections: getSections(state), }); diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_page_side_nav/guide_page_side_nav.js b/packages/kbn-ui-framework/doc_site/src/components/guide_page_side_nav/guide_page_side_nav.js index bd7dc0705c6d9..9aeca1b30e03d 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_page_side_nav/guide_page_side_nav.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_page_side_nav/guide_page_side_nav.js @@ -20,7 +20,7 @@ import PropTypes from 'prop-types'; import React from 'react'; -export const GuidePageSideNav = props => { +export const GuidePageSideNav = (props) => { return (
{props.title}
diff --git a/packages/kbn-ui-framework/doc_site/src/components/guide_text/guide_text.js b/packages/kbn-ui-framework/doc_site/src/components/guide_text/guide_text.js index 26c68dfe87951..820e4728da86d 100644 --- a/packages/kbn-ui-framework/doc_site/src/components/guide_text/guide_text.js +++ b/packages/kbn-ui-framework/doc_site/src/components/guide_text/guide_text.js @@ -19,4 +19,4 @@ import React from 'react'; -export const GuideText = props =>
{props.children}
; +export const GuideText = (props) =>
{props.children}
; diff --git a/packages/kbn-ui-framework/doc_site/src/index.js b/packages/kbn-ui-framework/doc_site/src/index.js index 5473024ae93c9..f7f1df059a041 100644 --- a/packages/kbn-ui-framework/doc_site/src/index.js +++ b/packages/kbn-ui-framework/doc_site/src/index.js @@ -58,16 +58,16 @@ const routes = [ ]; // Update document title with route name. -const onRouteEnter = route => { +const onRouteEnter = (route) => { const leafRoute = route.routes[route.routes.length - 1]; document.title = leafRoute.name ? `Kibana UI Framework - ${leafRoute.name}` : 'Kibana UI Framework'; }; -const syncTitleWithRoutes = routesList => { +const syncTitleWithRoutes = (routesList) => { if (!routesList) return; - routesList.forEach(route => { + routesList.forEach((route) => { route.onEnter = onRouteEnter; // eslint-disable-line no-param-reassign if (route.indexRoute) { // Index routes have a weird relationship with their "parent" routes, diff --git a/packages/kbn-ui-framework/doc_site/src/services/routes/routes.js b/packages/kbn-ui-framework/doc_site/src/services/routes/routes.js index 32912d5eb9c86..510a7fea7a026 100644 --- a/packages/kbn-ui-framework/doc_site/src/services/routes/routes.js +++ b/packages/kbn-ui-framework/doc_site/src/services/routes/routes.js @@ -159,14 +159,14 @@ export default { return allRoutes; }, getPreviousRoute: function getPreviousRoute(routeName) { - const index = allRoutes.findIndex(item => { + const index = allRoutes.findIndex((item) => { return item.name === routeName; }); return index >= 0 ? allRoutes[index - 1] : undefined; }, getNextRoute: function getNextRoute(routeName) { - const index = allRoutes.findIndex(item => { + const index = allRoutes.findIndex((item) => { return item.name === routeName; }); diff --git a/packages/kbn-ui-framework/doc_site/src/services/string/slugify.js b/packages/kbn-ui-framework/doc_site/src/services/string/slugify.js index f016857ff4414..2e0678f569774 100644 --- a/packages/kbn-ui-framework/doc_site/src/services/string/slugify.js +++ b/packages/kbn-ui-framework/doc_site/src/services/string/slugify.js @@ -32,7 +32,7 @@ function one(str) { } function each(items, src, dest) { - return items.map(item => { + return items.map((item) => { const _item = item; _item[dest] = one(_item[src]); return _item; diff --git a/packages/kbn-ui-framework/doc_site/src/store/reducers/sections_reducer.js b/packages/kbn-ui-framework/doc_site/src/store/reducers/sections_reducer.js index 6b61c009c5186..a86580903de68 100644 --- a/packages/kbn-ui-framework/doc_site/src/store/reducers/sections_reducer.js +++ b/packages/kbn-ui-framework/doc_site/src/store/reducers/sections_reducer.js @@ -40,7 +40,7 @@ export default function sectionsReducer(state = defaultState, action) { case ActionTypes.UNREGISTER_SECTION: { const sections = state.sections.slice(); - const index = sections.findIndex(section => section.id === action.id); + const index = sections.findIndex((section) => section.id === action.id); sections.splice(index, 1); return { diff --git a/packages/kbn-ui-framework/doc_site/src/views/bar/bar_example.js b/packages/kbn-ui-framework/doc_site/src/views/bar/bar_example.js index a71b2ff28ee65..9f2f1dec56055 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/bar/bar_example.js +++ b/packages/kbn-ui-framework/doc_site/src/views/bar/bar_example.js @@ -36,7 +36,7 @@ import BarThreeSections from './bar_three_sections'; import barThreeSectionsSource from '!!raw-loader!./bar_three_sections'; const barThreeSectionsHtml = renderToHtml(BarThreeSections); -export default props => ( +export default (props) => ( (
{ + onSubmit={(e) => { e.preventDefault(); window.alert('Submit'); }} @@ -40,7 +40,7 @@ export default () => (
{ + onSubmit={(e) => { e.preventDefault(); window.alert('Submit'); }} diff --git a/packages/kbn-ui-framework/doc_site/src/views/button/button_example.js b/packages/kbn-ui-framework/doc_site/src/views/button/button_example.js index daea2978aeffb..4943748ab1830 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/button/button_example.js +++ b/packages/kbn-ui-framework/doc_site/src/views/button/button_example.js @@ -71,7 +71,7 @@ const elementsHtml = renderToHtml(Elements); import sizesHtml from './button_sizes.html'; -export default props => ( +export default (props) => ( { + onToggleContent = (ev) => { ev.preventDefault(); - this.setState(state => ({ + this.setState((state) => ({ isExpanded: !state.isExpanded, })); }; diff --git a/packages/kbn-ui-framework/doc_site/src/views/collapse_button/collapse_button_example.js b/packages/kbn-ui-framework/doc_site/src/views/collapse_button/collapse_button_example.js index d008a0d5f23f7..52e8a91b17aa9 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/collapse_button/collapse_button_example.js +++ b/packages/kbn-ui-framework/doc_site/src/views/collapse_button/collapse_button_example.js @@ -32,7 +32,7 @@ import CollapseButtonAria from './collapse_button_aria'; import collapseButtonAriaSource from '!!raw-loader!./collapse_button_aria'; const collapseButtonAriaHtml = renderToHtml(CollapseButtonAria); -export default props => ( +export default (props) => ( ( +export default (props) => ( this.handleChange(event, 'value1')} + onChange={(event) => this.handleChange(event, 'value1')} />
this.handleChange(event, 'value2')} + onChange={(event) => this.handleChange(event, 'value2')} />
this.handleChange(event, 'value3')} + onChange={(event) => this.handleChange(event, 'value3')} isDisabled />
this.handleChange(event, 'value4')} + onChange={(event) => this.handleChange(event, 'value4')} />
); diff --git a/packages/kbn-ui-framework/doc_site/src/views/form/form_example.js b/packages/kbn-ui-framework/doc_site/src/views/form/form_example.js index 0717459151584..88edfc5242564 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/form/form_example.js +++ b/packages/kbn-ui-framework/doc_site/src/views/form/form_example.js @@ -59,7 +59,7 @@ import CheckBox from './check_box'; import checkBoxSource from '!!raw-loader!./check_box'; const checkBoxHtml = renderToHtml(CheckBox); -export default props => ( +export default (props) => ( - this.handleChange(event, 'value1')}> + this.handleChange(event, 'value1')} + > @@ -44,7 +47,7 @@ class KuiSelectExample extends Component {
this.handleChange(event, 'value2')} + onChange={(event) => this.handleChange(event, 'value2')} isDisabled > @@ -52,7 +55,7 @@ class KuiSelectExample extends Component {
this.handleChange(event, 'value3')} + onChange={(event) => this.handleChange(event, 'value3')} isInvalid > @@ -60,7 +63,7 @@ class KuiSelectExample extends Component {
this.handleChange(event, 'value4')} + onChange={(event) => this.handleChange(event, 'value4')} size="small" > @@ -68,7 +71,7 @@ class KuiSelectExample extends Component {
this.handleChange(event, 'value5')} + onChange={(event) => this.handleChange(event, 'value5')} size="large" > diff --git a/packages/kbn-ui-framework/doc_site/src/views/form/text_area.js b/packages/kbn-ui-framework/doc_site/src/views/form/text_area.js index b56051071a6da..0d4e876d996a2 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/form/text_area.js +++ b/packages/kbn-ui-framework/doc_site/src/views/form/text_area.js @@ -40,38 +40,38 @@ class KuiTextAreaExample extends Component { this.handleChange(event, 'value1')} + onChange={(event) => this.handleChange(event, 'value1')} />
this.handleChange(event, 'value2')} + onChange={(event) => this.handleChange(event, 'value2')} />
this.handleChange(event, 'value3')} + onChange={(event) => this.handleChange(event, 'value3')} />
this.handleChange(event, 'value4')} + onChange={(event) => this.handleChange(event, 'value4')} />
this.handleChange(event, 'value5')} + onChange={(event) => this.handleChange(event, 'value5')} />
this.handleChange(event, 'value6')} + onChange={(event) => this.handleChange(event, 'value6')} />
); diff --git a/packages/kbn-ui-framework/doc_site/src/views/form/text_area_non_resizable.js b/packages/kbn-ui-framework/doc_site/src/views/form/text_area_non_resizable.js index aba16bae1269b..65c7fa765a359 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/form/text_area_non_resizable.js +++ b/packages/kbn-ui-framework/doc_site/src/views/form/text_area_non_resizable.js @@ -33,7 +33,7 @@ class KuiTextAreaNonResizableExample extends Component { return ( this.handleChange(event, 'value1')} + onChange={(event) => this.handleChange(event, 'value1')} isNonResizable /> ); diff --git a/packages/kbn-ui-framework/doc_site/src/views/form/text_input.js b/packages/kbn-ui-framework/doc_site/src/views/form/text_input.js index a3cebcb07bf2b..5bb3fabe22fa5 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/form/text_input.js +++ b/packages/kbn-ui-framework/doc_site/src/views/form/text_input.js @@ -40,39 +40,39 @@ class KuiTextInputExample extends Component { this.handleChange(event, 'value1')} + onChange={(event) => this.handleChange(event, 'value1')} />
this.handleChange(event, 'value2')} + onChange={(event) => this.handleChange(event, 'value2')} />
this.handleChange(event, 'value3')} + onChange={(event) => this.handleChange(event, 'value3')} />
this.handleChange(event, 'value4')} + onChange={(event) => this.handleChange(event, 'value4')} />
this.handleChange(event, 'value5')} + onChange={(event) => this.handleChange(event, 'value5')} />
this.handleChange(event, 'value6')} + onChange={(event) => this.handleChange(event, 'value6')} />
); diff --git a/packages/kbn-ui-framework/doc_site/src/views/form_layout/form_layout_example.js b/packages/kbn-ui-framework/doc_site/src/views/form_layout/form_layout_example.js index 9c76a8b3a1d3a..7b1a5d2785cac 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/form_layout/form_layout_example.js +++ b/packages/kbn-ui-framework/doc_site/src/views/form_layout/form_layout_example.js @@ -28,7 +28,7 @@ import FieldGroup from './field_group'; import fieldGroupSource from '!!raw-loader!./field_group'; const fieldGroupHtml = renderToHtml(FieldGroup); -export default props => ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( item.title.toLowerCase(), + getValue: (item) => item.title.toLowerCase(), isAscending: true, }, { name: 'description', - getValue: item => item.description.toLowerCase(), + getValue: (item) => item.description.toLowerCase(), isAscending: true, }, ], @@ -70,7 +70,7 @@ export class FluidTable extends Component { ); } - onSort = prop => { + onSort = (prop) => { this.sortableProperties.sortOn(prop); this.setState({ @@ -79,7 +79,7 @@ export class FluidTable extends Component { }; renderRows() { - return this.items.map(item => ( + return this.items.map((item) => ( {item.title} diff --git a/packages/kbn-ui-framework/doc_site/src/views/table/listing_table.js b/packages/kbn-ui-framework/doc_site/src/views/table/listing_table.js index fece33c16980a..38eaa7b396ef5 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/table/listing_table.js +++ b/packages/kbn-ui-framework/doc_site/src/views/table/listing_table.js @@ -137,7 +137,7 @@ export class ListingTable extends Component { ]; } - onItemSelectionChanged = selectedRowIds => { + onItemSelectionChanged = (selectedRowIds) => { this.setState({ selectedRowIds }); }; diff --git a/packages/kbn-ui-framework/doc_site/src/views/table/table.js b/packages/kbn-ui-framework/doc_site/src/views/table/table.js index 45f6e389e7234..0c55d1dc5ed51 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/table/table.js +++ b/packages/kbn-ui-framework/doc_site/src/views/table/table.js @@ -85,12 +85,12 @@ export class Table extends Component { [ { name: 'title', - getValue: item => item.title.toLowerCase(), + getValue: (item) => item.title.toLowerCase(), isAscending: true, }, { name: 'status', - getValue: item => item.status.toLowerCase(), + getValue: (item) => item.status.toLowerCase(), isAscending: true, }, ], @@ -98,7 +98,7 @@ export class Table extends Component { ); } - onSort = prop => { + onSort = (prop) => { this.sortableProperties.sortOn(prop); this.setState({ @@ -106,35 +106,35 @@ export class Table extends Component { }); }; - toggleItem = item => { - this.setState(previousState => { + toggleItem = (item) => { + this.setState((previousState) => { const rowToSelectedStateMap = new Map(previousState.rowToSelectedStateMap); rowToSelectedStateMap.set(item, !rowToSelectedStateMap.get(item)); return { rowToSelectedStateMap }; }); }; - isItemChecked = item => { + isItemChecked = (item) => { return this.state.rowToSelectedStateMap.get(item); }; - togglePopover = item => { - this.setState(previousState => { + togglePopover = (item) => { + this.setState((previousState) => { const rowToOpenActionsPopoverMap = new Map(previousState.rowToOpenActionsPopoverMap); rowToOpenActionsPopoverMap.set(item, !rowToOpenActionsPopoverMap.get(item)); return { rowToOpenActionsPopoverMap }; }); }; - closePopover = item => { - this.setState(previousState => { + closePopover = (item) => { + this.setState((previousState) => { const rowToOpenActionsPopoverMap = new Map(previousState.rowToOpenActionsPopoverMap); rowToOpenActionsPopoverMap.set(item, false); return { rowToOpenActionsPopoverMap }; }); }; - isPopoverOpen = item => { + isPopoverOpen = (item) => { return this.state.rowToOpenActionsPopoverMap.get(item); }; @@ -146,7 +146,7 @@ export class Table extends Component { renderRows() { const rows = []; - this.items.forEach(item => { + this.items.forEach((item) => { const classes = classNames({ 'kuiTableRowCell--wrap': item.isWrapped, }); diff --git a/packages/kbn-ui-framework/doc_site/src/views/table/table_example.js b/packages/kbn-ui-framework/doc_site/src/views/table/table_example.js index 9ed449ea9767b..07e328c4e5e83 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/table/table_example.js +++ b/packages/kbn-ui-framework/doc_site/src/views/table/table_example.js @@ -52,7 +52,7 @@ import { ListingTableLoadingItems } from './listing_table_loading_items'; import listingTableLoadingItemsSource from '!!raw-loader!./listing_table_loading_items'; // eslint-disable-line import/default const listingTableLoadingItemsHtml = renderToHtml(ListingTableLoadingItems); -export default props => ( +export default (props) => ( { + onSelectedTabChanged = (id) => { this.setState({ selectedTabId: id, }); diff --git a/packages/kbn-ui-framework/doc_site/src/views/tabs/tabs_example.js b/packages/kbn-ui-framework/doc_site/src/views/tabs/tabs_example.js index 0d3663167520e..125fd0fb53ae3 100644 --- a/packages/kbn-ui-framework/doc_site/src/views/tabs/tabs_example.js +++ b/packages/kbn-ui-framework/doc_site/src/views/tabs/tabs_example.js @@ -35,7 +35,7 @@ import Tabs from './tabs'; import tabsSource from '!!raw-loader!./tabs'; const tabsHtml = renderToHtml(Tabs); -export default props => ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( ( +export default (props) => ( diff --git a/packages/kbn-ui-framework/generator-kui/app/component.js b/packages/kbn-ui-framework/generator-kui/app/component.js index 1cf03b89d54f7..bcb561f6fa729 100644 --- a/packages/kbn-ui-framework/generator-kui/app/component.js +++ b/packages/kbn-ui-framework/generator-kui/app/component.js @@ -39,7 +39,7 @@ module.exports = class extends Generator { }, ], }, - ]).then(answers => { + ]).then((answers) => { this.config = answers; }); } diff --git a/packages/kbn-ui-framework/generator-kui/app/documentation.js b/packages/kbn-ui-framework/generator-kui/app/documentation.js index c2735f1ce978b..3cbc0263789c6 100644 --- a/packages/kbn-ui-framework/generator-kui/app/documentation.js +++ b/packages/kbn-ui-framework/generator-kui/app/documentation.js @@ -43,7 +43,7 @@ module.exports = class extends Generator { }, ], }, - ]).then(answers => { + ]).then((answers) => { this.config = answers; }); } diff --git a/packages/kbn-ui-framework/generator-kui/component/index.js b/packages/kbn-ui-framework/generator-kui/component/index.js index 3abf84b7a2073..56c49fe6fa471 100644 --- a/packages/kbn-ui-framework/generator-kui/component/index.js +++ b/packages/kbn-ui-framework/generator-kui/component/index.js @@ -49,7 +49,7 @@ module.exports = class extends Generator { type: 'confirm', default: true, }, - ]).then(answers => { + ]).then((answers) => { this.config = answers; if (!answers.name || !answers.name.trim()) { @@ -62,7 +62,7 @@ module.exports = class extends Generator { writing() { const config = this.config; - const writeComponent = isStatelessFunction => { + const writeComponent = (isStatelessFunction) => { const componentName = utils.makeComponentName(config.name); const cssClassName = utils.lowerCaseFirstLetter(componentName); const fileName = config.name; diff --git a/packages/kbn-ui-framework/generator-kui/documentation/index.js b/packages/kbn-ui-framework/generator-kui/documentation/index.js index daaaf32c8fd22..03f8d5813b251 100644 --- a/packages/kbn-ui-framework/generator-kui/documentation/index.js +++ b/packages/kbn-ui-framework/generator-kui/documentation/index.js @@ -47,7 +47,7 @@ module.exports = class extends Generator { name: 'folderName', type: 'input', store: true, - default: answers => answers.name, + default: (answers) => answers.name, }); prompts.push({ @@ -58,7 +58,7 @@ module.exports = class extends Generator { }); } - return this.prompt(prompts).then(answers => { + return this.prompt(prompts).then((answers) => { this.config = answers; }); } diff --git a/packages/kbn-ui-framework/generator-kui/utils.js b/packages/kbn-ui-framework/generator-kui/utils.js index c51393121777e..0f7b910451767 100644 --- a/packages/kbn-ui-framework/generator-kui/utils.js +++ b/packages/kbn-ui-framework/generator-kui/utils.js @@ -21,7 +21,7 @@ function makeComponentName(str, usePrefix = true) { const words = str.split('_'); const componentName = words - .map(function(word) { + .map(function (word) { return upperCaseFirstLetter(word); }) .join(''); @@ -30,13 +30,13 @@ function makeComponentName(str, usePrefix = true) { } function lowerCaseFirstLetter(str) { - return str.replace(/\w\S*/g, function(txt) { + return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toLowerCase() + txt.substr(1); }); } function upperCaseFirstLetter(str) { - return str.replace(/\w\S*/g, function(txt) { + return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1); }); } diff --git a/packages/kbn-ui-framework/src/components/button/button.js b/packages/kbn-ui-framework/src/components/button/button.js index b18ca87a27b1e..e95b9209343ae 100644 --- a/packages/kbn-ui-framework/src/components/button/button.js +++ b/packages/kbn-ui-framework/src/components/button/button.js @@ -133,7 +133,7 @@ const KuiLinkButton = ({ children, ...rest }) => { - const onClick = e => { + const onClick = (e) => { if (disabled) { e.preventDefault(); } diff --git a/packages/kbn-ui-framework/src/components/button/button.test.js b/packages/kbn-ui-framework/src/components/button/button.test.js index d664ce85f9a37..db74308d9de8d 100644 --- a/packages/kbn-ui-framework/src/components/button/button.test.js +++ b/packages/kbn-ui-framework/src/components/button/button.test.js @@ -48,7 +48,7 @@ describe('KuiButton', () => { describe('Props', () => { describe('buttonType', () => { - BUTTON_TYPES.forEach(buttonType => { + BUTTON_TYPES.forEach((buttonType) => { describe(`${buttonType}`, () => { test(`renders the ${buttonType} class`, () => { const $button = render(); diff --git a/packages/kbn-ui-framework/src/components/button/button_group/button_group.js b/packages/kbn-ui-framework/src/components/button/button_group/button_group.js index 49eaff03efd40..630d5598cab9c 100644 --- a/packages/kbn-ui-framework/src/components/button/button_group/button_group.js +++ b/packages/kbn-ui-framework/src/components/button/button_group/button_group.js @@ -22,7 +22,7 @@ import React from 'react'; import classNames from 'classnames'; -const KuiButtonGroup = props => { +const KuiButtonGroup = (props) => { const classes = classNames('kuiButtonGroup', { 'kuiButtonGroup--united': props.isUnited, }); diff --git a/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.js b/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.js index 736e349396b7e..256d7c4a1786e 100644 --- a/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.js +++ b/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.js @@ -24,7 +24,7 @@ import classNames from 'classnames'; const ICON_TYPES = ['create', 'delete', 'previous', 'next', 'loading', 'settings', 'menu']; -const KuiButtonIcon = props => { +const KuiButtonIcon = (props) => { const typeToClassNameMap = { create: 'fa-plus', delete: 'fa-trash', diff --git a/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.test.js b/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.test.js index e270f26644393..553fef1432487 100644 --- a/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.test.js +++ b/packages/kbn-ui-framework/src/components/button/button_icon/button_icon.test.js @@ -33,7 +33,7 @@ describe('KuiButtonIcon', () => { describe('Props', () => { describe('type', () => { - ICON_TYPES.forEach(type => { + ICON_TYPES.forEach((type) => { describe(`${type}`, () => { test(`renders the ${type} class`, () => { const $buttonIcon = render(); diff --git a/packages/kbn-ui-framework/src/components/button/link_button.test.js b/packages/kbn-ui-framework/src/components/button/link_button.test.js index 4f77af3febf54..4489dc1a46d2a 100644 --- a/packages/kbn-ui-framework/src/components/button/link_button.test.js +++ b/packages/kbn-ui-framework/src/components/button/link_button.test.js @@ -49,7 +49,7 @@ describe('KuiLinkButton', () => { describe('Props', () => { describe('buttonType', () => { - BUTTON_TYPES.forEach(buttonType => { + BUTTON_TYPES.forEach((buttonType) => { describe(`${buttonType}`, () => { test(`renders the ${buttonType} class`, () => { const $button = render( diff --git a/packages/kbn-ui-framework/src/components/button/submit_button.test.js b/packages/kbn-ui-framework/src/components/button/submit_button.test.js index fc30523649c12..77ad9eb40c55f 100644 --- a/packages/kbn-ui-framework/src/components/button/submit_button.test.js +++ b/packages/kbn-ui-framework/src/components/button/submit_button.test.js @@ -47,7 +47,7 @@ describe('KuiSubmitButton', () => { describe('Props', () => { describe('buttonType', () => { - BUTTON_TYPES.forEach(buttonType => { + BUTTON_TYPES.forEach((buttonType) => { describe(`${buttonType}`, () => { test(`renders the ${buttonType} class`, () => { const $button = render(); diff --git a/packages/kbn-ui-framework/src/components/collapse_button/collapse_button.test.js b/packages/kbn-ui-framework/src/components/collapse_button/collapse_button.test.js index f6245ef654bb9..8ce225038b8b7 100644 --- a/packages/kbn-ui-framework/src/components/collapse_button/collapse_button.test.js +++ b/packages/kbn-ui-framework/src/components/collapse_button/collapse_button.test.js @@ -27,7 +27,7 @@ import { DIRECTIONS, KuiCollapseButton } from './collapse_button'; describe('KuiCollapseButton', () => { describe('Props', () => { describe('direction', () => { - DIRECTIONS.forEach(direction => { + DIRECTIONS.forEach((direction) => { describe(`${direction}`, () => { test(`renders the ${direction} class`, () => { const component = ; diff --git a/packages/kbn-ui-framework/src/components/form/select/select.test.js b/packages/kbn-ui-framework/src/components/form/select/select.test.js index 81c1e4d9a0ff2..056bc88016d51 100644 --- a/packages/kbn-ui-framework/src/components/form/select/select.test.js +++ b/packages/kbn-ui-framework/src/components/form/select/select.test.js @@ -77,7 +77,7 @@ describe('KuiSelect', () => { }); describe('size', () => { - SELECT_SIZE.forEach(size => { + SELECT_SIZE.forEach((size) => { test(`renders ${size}`, () => { const component = {}} />; diff --git a/packages/kbn-ui-framework/src/components/form/text_area/text_area.test.js b/packages/kbn-ui-framework/src/components/form/text_area/text_area.test.js index eddb655094088..d87b7b76789de 100644 --- a/packages/kbn-ui-framework/src/components/form/text_area/text_area.test.js +++ b/packages/kbn-ui-framework/src/components/form/text_area/text_area.test.js @@ -87,7 +87,7 @@ describe('KuiTextArea', () => { }); describe('size', () => { - TEXTAREA_SIZE.forEach(size => { + TEXTAREA_SIZE.forEach((size) => { test(`renders ${size}`, () => { const component = {}} />; diff --git a/packages/kbn-ui-framework/src/components/form/text_input/text_input.test.js b/packages/kbn-ui-framework/src/components/form/text_input/text_input.test.js index 9ef3c420bba68..41d3726582fb5 100644 --- a/packages/kbn-ui-framework/src/components/form/text_input/text_input.test.js +++ b/packages/kbn-ui-framework/src/components/form/text_input/text_input.test.js @@ -89,7 +89,7 @@ describe('KuiTextInput', () => { }); describe('size', () => { - TEXTINPUT_SIZE.forEach(size => { + TEXTINPUT_SIZE.forEach((size) => { test(`renders ${size}`, () => { const component = {}} />; diff --git a/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.js b/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.js index 3478c159cbbb9..82b2afba7bc40 100644 --- a/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.js +++ b/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.js @@ -57,7 +57,7 @@ export function KuiListingTable({ if (areAllRowsSelected()) { onItemSelectionChanged([]); } else { - onItemSelectionChanged(rows.map(row => row.id)); + onItemSelectionChanged(rows.map((row) => row.id)); } } diff --git a/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.test.js b/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.test.js index b47a1275d1565..2607caeba0dbb 100644 --- a/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.test.js +++ b/packages/kbn-ui-framework/src/components/table/listing_table/listing_table.test.js @@ -22,7 +22,7 @@ import { mount, shallow } from 'enzyme'; import { requiredProps, takeMountedSnapshot } from '../../../test'; import { KuiListingTable } from './listing_table'; -const getProps = customProps => { +const getProps = (customProps) => { const defaultProps = { header: ['Breed', 'Description'], rows: [ @@ -59,20 +59,14 @@ test('renders KuiListingTable', () => { test('selecting a row calls onItemSelectionChanged', () => { const props = getProps(); const component = shallow(); - component - .find('KuiListingTableRow') - .at(1) - .prop('onSelectionChanged')('1'); + component.find('KuiListingTableRow').at(1).prop('onSelectionChanged')('1'); expect(props.onItemSelectionChanged).toHaveBeenCalledWith(['1']); }); test('selectedRowIds is preserved when onItemSelectionChanged is called', () => { const props = getProps({ selectedRowIds: ['3'] }); const component = shallow(); - component - .find('KuiListingTableRow') - .at(0) - .prop('onSelectionChanged')('1'); + component.find('KuiListingTableRow').at(0).prop('onSelectionChanged')('1'); expect(props.onItemSelectionChanged).toHaveBeenCalledWith(expect.arrayContaining(['1', '3'])); }); diff --git a/packages/kbn-ui-framework/src/components/typography/typography.test.js b/packages/kbn-ui-framework/src/components/typography/typography.test.js index 7155483354e48..b341a2c442fb2 100644 --- a/packages/kbn-ui-framework/src/components/typography/typography.test.js +++ b/packages/kbn-ui-framework/src/components/typography/typography.test.js @@ -35,7 +35,7 @@ describe('KuiTitle', () => { }); describe('renders size', () => { - SIZES.forEach(size => { + SIZES.forEach((size) => { test(size, () => { const component = render( diff --git a/packages/kbn-ui-framework/src/services/accessibility/html_id_generator.js b/packages/kbn-ui-framework/src/services/accessibility/html_id_generator.js index 6537f0d157997..164910341f027 100644 --- a/packages/kbn-ui-framework/src/services/accessibility/html_id_generator.js +++ b/packages/kbn-ui-framework/src/services/accessibility/html_id_generator.js @@ -27,5 +27,5 @@ import uuid from 'uuid'; */ export function htmlIdGenerator(idPrefix) { const prefix = idPrefix || uuid.v1(); - return suffix => `${prefix}_${suffix || uuid.v1()}`; + return (suffix) => `${prefix}_${suffix || uuid.v1()}`; } diff --git a/packages/kbn-ui-framework/src/services/sort/sortable_properties.js b/packages/kbn-ui-framework/src/services/sort/sortable_properties.js index 4b08b20b68cbf..6c445bf8b747b 100644 --- a/packages/kbn-ui-framework/src/services/sort/sortable_properties.js +++ b/packages/kbn-ui-framework/src/services/sort/sortable_properties.js @@ -73,7 +73,7 @@ export class SortableProperties { * @returns {SortableProperty|undefined} */ getSortablePropertyByName(propertyName) { - return this.sortableProperties.find(property => property.name === propertyName); + return this.sortableProperties.find((property) => property.name === propertyName); } /** diff --git a/packages/kbn-ui-framework/src/services/sort/sortable_properties.test.js b/packages/kbn-ui-framework/src/services/sort/sortable_properties.test.js index 223724edac8b8..0037787830ac2 100644 --- a/packages/kbn-ui-framework/src/services/sort/sortable_properties.test.js +++ b/packages/kbn-ui-framework/src/services/sort/sortable_properties.test.js @@ -22,19 +22,19 @@ import { SortableProperties } from './sortable_properties'; describe('SortProperties', () => { const name = { name: 'name', - getValue: bird => bird.name, + getValue: (bird) => bird.name, isAscending: true, }; const size = { name: 'size', - getValue: bird => bird.size, + getValue: (bird) => bird.size, isAscending: false, }; const color = { name: 'color', - getValue: bird => bird.color, + getValue: (bird) => bird.color, isAscending: true, }; diff --git a/packages/kbn-ui-framework/src/test/take_mounted_snapshot.js b/packages/kbn-ui-framework/src/test/take_mounted_snapshot.js index 4d87930d434b5..d4567ebb800fe 100644 --- a/packages/kbn-ui-framework/src/test/take_mounted_snapshot.js +++ b/packages/kbn-ui-framework/src/test/take_mounted_snapshot.js @@ -23,7 +23,7 @@ * containing both React components and HTML elements. This function removes the React components, * leaving only HTML elements in the snapshot. */ -export const takeMountedSnapshot = mountedComponent => { +export const takeMountedSnapshot = (mountedComponent) => { const html = mountedComponent.html(); const template = document.createElement('template'); template.innerHTML = html; // eslint-disable-line no-unsanitized/property diff --git a/packages/kbn-ui-shared-deps/entry.js b/packages/kbn-ui-shared-deps/entry.js index f19271de8ad27..26efd174f4e39 100644 --- a/packages/kbn-ui-shared-deps/entry.js +++ b/packages/kbn-ui-shared-deps/entry.js @@ -48,9 +48,16 @@ export const ElasticCharts = require('@elastic/charts'); export const ElasticEui = require('@elastic/eui'); export const ElasticEuiLibServices = require('@elastic/eui/lib/services'); export const ElasticEuiLibServicesFormat = require('@elastic/eui/lib/services/format'); -export const ElasticEuiLightTheme = require('@elastic/eui/dist/eui_theme_light.json'); -export const ElasticEuiDarkTheme = require('@elastic/eui/dist/eui_theme_dark.json'); export const ElasticEuiChartsTheme = require('@elastic/eui/dist/eui_charts_theme'); +export let ElasticEuiLightTheme; +export let ElasticEuiDarkTheme; +if (window.__kbnThemeVersion__ === 'v7') { + ElasticEuiLightTheme = require('@elastic/eui/dist/eui_theme_light.json'); + ElasticEuiDarkTheme = require('@elastic/eui/dist/eui_theme_dark.json'); +} else { + ElasticEuiLightTheme = require('@elastic/eui/dist/eui_theme_amsterdam_light.json'); + ElasticEuiDarkTheme = require('@elastic/eui/dist/eui_theme_amsterdam_dark.json'); +} // massive deps that we should really get rid of or reduce in size substantially export const ElasticsearchBrowser = require('elasticsearch-browser/elasticsearch.js'); diff --git a/packages/kbn-ui-shared-deps/index.d.ts b/packages/kbn-ui-shared-deps/index.d.ts index b829c87d91c4a..cd659b6f04853 100644 --- a/packages/kbn-ui-shared-deps/index.d.ts +++ b/packages/kbn-ui-shared-deps/index.d.ts @@ -42,11 +42,21 @@ export const baseCssDistFilename: string; */ export const darkCssDistFilename: string; +/** + * Filename of the dark-theme css file in the distributable directory + */ +export const darkV8CssDistFilename: string; + /** * Filename of the light-theme css file in the distributable directory */ export const lightCssDistFilename: string; +/** + * Filename of the light-theme css file in the distributable directory + */ +export const lightV8CssDistFilename: string; + /** * Externals mapping inteded to be used in a webpack config */ diff --git a/packages/kbn-ui-shared-deps/index.js b/packages/kbn-ui-shared-deps/index.js index 42ed08259ac8f..9aec3ab359924 100644 --- a/packages/kbn-ui-shared-deps/index.js +++ b/packages/kbn-ui-shared-deps/index.js @@ -23,8 +23,10 @@ exports.distDir = Path.resolve(__dirname, 'target'); exports.jsDepFilenames = ['kbn-ui-shared-deps.@elastic.js']; exports.jsFilename = 'kbn-ui-shared-deps.js'; exports.baseCssDistFilename = 'kbn-ui-shared-deps.css'; -exports.lightCssDistFilename = 'kbn-ui-shared-deps.light.css'; -exports.darkCssDistFilename = 'kbn-ui-shared-deps.dark.css'; +exports.lightCssDistFilename = 'kbn-ui-shared-deps.v7.light.css'; +exports.lightV8CssDistFilename = 'kbn-ui-shared-deps.v8.light.css'; +exports.darkCssDistFilename = 'kbn-ui-shared-deps.v7.dark.css'; +exports.darkV8CssDistFilename = 'kbn-ui-shared-deps.v8.dark.css'; exports.externals = { // stateful deps angular: '__kbnSharedDeps__.Angular', diff --git a/packages/kbn-ui-shared-deps/package.json b/packages/kbn-ui-shared-deps/package.json index eddc215db5a62..d34fe3624ab26 100644 --- a/packages/kbn-ui-shared-deps/package.json +++ b/packages/kbn-ui-shared-deps/package.json @@ -6,7 +6,7 @@ "scripts": { "build": "node scripts/build", "kbn:bootstrap": "node scripts/build --dev", - "kbn:watch": "node scripts/build --watch" + "kbn:watch": "node scripts/build --dev --watch" }, "dependencies": { "@elastic/charts": "19.2.0", diff --git a/packages/kbn-ui-shared-deps/public_path_loader.js b/packages/kbn-ui-shared-deps/public_path_loader.js index 6b7a27c9ca52b..fceebd6d6b3a1 100644 --- a/packages/kbn-ui-shared-deps/public_path_loader.js +++ b/packages/kbn-ui-shared-deps/public_path_loader.js @@ -17,7 +17,7 @@ * under the License. */ -module.exports = function(source) { +module.exports = function (source) { const options = this.query; return `__webpack_public_path__ = window.__kbnPublicPath__['${options.key}'];${source}`; }; diff --git a/packages/kbn-ui-shared-deps/scripts/build.js b/packages/kbn-ui-shared-deps/scripts/build.js index e45b3dbed1748..af4e3481e624d 100644 --- a/packages/kbn-ui-shared-deps/scripts/build.js +++ b/packages/kbn-ui-shared-deps/scripts/build.js @@ -38,7 +38,7 @@ run( ); /** @param {webpack.Stats} stats */ - const onCompilationComplete = stats => { + const onCompilationComplete = (stats) => { const took = Math.round((stats.endTime - stats.startTime) / 1000); if (!stats.hasErrors() && !stats.hasWarnings()) { @@ -55,7 +55,7 @@ run( }; if (flags.watch) { - compiler.hooks.done.tap('report on stats', stats => { + compiler.hooks.done.tap('report on stats', (stats) => { try { onCompilationComplete(stats); } catch (error) { @@ -72,7 +72,7 @@ run( log.info('Running webpack compilation...'); }); - compiler.watch({}, error => { + compiler.watch({}, (error) => { if (error) { log.error('Fatal webpack error'); log.error(error); diff --git a/packages/kbn-ui-shared-deps/webpack.config.js b/packages/kbn-ui-shared-deps/webpack.config.js index ca913d0f16417..7295f2e88c530 100644 --- a/packages/kbn-ui-shared-deps/webpack.config.js +++ b/packages/kbn-ui-shared-deps/webpack.config.js @@ -32,14 +32,22 @@ exports.getWebpackConfig = ({ dev = false } = {}) => ({ mode: dev ? 'development' : 'production', entry: { 'kbn-ui-shared-deps': './entry.js', - 'kbn-ui-shared-deps.dark': [ + 'kbn-ui-shared-deps.v7.dark': [ '@elastic/eui/dist/eui_theme_dark.css', '@elastic/charts/dist/theme_only_dark.css', ], - 'kbn-ui-shared-deps.light': [ + 'kbn-ui-shared-deps.v7.light': [ '@elastic/eui/dist/eui_theme_light.css', '@elastic/charts/dist/theme_only_light.css', ], + 'kbn-ui-shared-deps.v8.dark': [ + '@elastic/eui/dist/eui_theme_amsterdam_dark.css', + '@elastic/charts/dist/theme_only_dark.css', + ], + 'kbn-ui-shared-deps.v8.light': [ + '@elastic/eui/dist/eui_theme_amsterdam_light.css', + '@elastic/charts/dist/theme_only_light.css', + ], }, context: __dirname, devtool: dev ? '#cheap-source-map' : false, @@ -47,7 +55,7 @@ exports.getWebpackConfig = ({ dev = false } = {}) => ({ path: UiSharedDeps.distDir, filename: '[name].js', sourceMapFilename: '[file].map', - devtoolModuleFilenameTemplate: info => + devtoolModuleFilenameTemplate: (info) => `kbn-ui-shared-deps/${Path.relative(REPO_ROOT, info.absoluteResourcePath)}`, library: '__kbnSharedDeps__', }, @@ -96,7 +104,7 @@ exports.getWebpackConfig = ({ dev = false } = {}) => ({ cacheGroups: { 'kbn-ui-shared-deps.@elastic': { name: 'kbn-ui-shared-deps.@elastic', - test: m => m.resource && m.resource.includes('@elastic'), + test: (m) => m.resource && m.resource.includes('@elastic'), chunks: 'all', enforce: true, }, diff --git a/packages/kbn-utility-types/index.ts b/packages/kbn-utility-types/index.ts index 657d9f547de66..9a8a81460f410 100644 --- a/packages/kbn-utility-types/index.ts +++ b/packages/kbn-utility-types/index.ts @@ -82,9 +82,9 @@ export type Values = T extends any[] ? T[number] : T extends object ? T[keyof * type. This is necessary in the case of distinguishing one collection from * another. */ -export type UnionToIntersection = (U extends any -? (k: U) => void -: never) extends (k: infer I) => void +export type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ( + k: infer I +) => void ? I : never; diff --git a/scripts/es.js b/scripts/es.js index 4f15cc11801e3..93f1d69350bac 100644 --- a/scripts/es.js +++ b/scripts/es.js @@ -32,7 +32,7 @@ kbnEs 'base-path': resolve(__dirname, '../.es'), ssl: false, }) - .catch(function(e) { + .catch(function (e) { console.error(e); process.exitCode = 1; }); diff --git a/scripts/test_hardening.js b/scripts/test_hardening.js index c0a20a9ff6cb4..0bc0d1c045ac0 100644 --- a/scripts/test_hardening.js +++ b/scripts/test_hardening.js @@ -28,10 +28,10 @@ program .description( 'Run the tests in test/harden directory. If no files are provided, all files within the directory will be run.' ) - .action(function(globs) { + .action(function (globs) { if (globs.length === 0) globs.push(path.join('test', 'harden', '*')); - globs.forEach(function(glob) { - syncGlob(glob).forEach(function(filename) { + globs.forEach(function (glob) { + syncGlob(glob).forEach(function (filename) { if (path.basename(filename)[0] === '_') return; console.log(process.argv[0], filename); execFileSync(process.argv[0], [filename], { stdio: 'inherit' }); diff --git a/src/apm.js b/src/apm.js index e3f4d84d9b523..6c10539c6b7d3 100644 --- a/src/apm.js +++ b/src/apm.js @@ -85,7 +85,7 @@ function getConfig(serviceName) { */ const isKibanaDistributable = Boolean(build && build.distributable === true); -module.exports = function(serviceName = name) { +module.exports = function (serviceName = name) { if (process.env.kbnWorkerType === 'optmzr') return; const conf = getConfig(serviceName); diff --git a/src/cli/cli.js b/src/cli/cli.js index b6598520352a6..50a8d4c7f7f01 100644 --- a/src/cli/cli.js +++ b/src/cli/cli.js @@ -40,13 +40,13 @@ serveCommand(program); program .command('help ') .description('Get the help for a specific command') - .action(function(cmdName) { + .action(function (cmdName) { const cmd = _.find(program.commands, { _name: cmdName }); if (!cmd) return program.error(`unknown command ${cmdName}`); cmd.help(); }); -program.command('*', null, { noHelp: true }).action(function(cmd) { +program.command('*', null, { noHelp: true }).action(function (cmd) { program.error(`unknown command ${cmd}`); }); diff --git a/src/cli/cluster/cluster_manager.test.ts b/src/cli/cluster/cluster_manager.test.ts index 707778861fb59..66f68f815edac 100644 --- a/src/cli/cluster/cluster_manager.test.ts +++ b/src/cli/cluster/cluster_manager.test.ts @@ -153,7 +153,7 @@ describe('CLI cluster manager', () => { const events: Array = []; delayUntil().subscribe( () => events.push('next'), - error => events.push(error), + (error) => events.push(error), () => events.push('complete') ); diff --git a/src/cli/cluster/cluster_manager.ts b/src/cli/cluster/cluster_manager.ts index 3b3e4d78320d2..fc94f8d585a02 100644 --- a/src/cli/cluster/cluster_manager.ts +++ b/src/cli/cluster/cluster_manager.ts @@ -37,7 +37,7 @@ process.env.kbnWorkerType = 'managr'; const firstAllTrue = (...sources: Array>) => Rx.combineLatest(...sources).pipe( - filter(values => values.every(v => v === true)), + filter((values) => values.every((v) => v === true)), take(1), mapTo(undefined) ); @@ -75,7 +75,7 @@ export class ClusterManager { .pipe( map(({ state }) => state.phase === 'success' || state.phase === 'issue'), tap({ - error: error => { + error: (error) => { this.log.bad('New platform optimizer error', error.stack); process.exit(1); }, @@ -139,9 +139,9 @@ export class ClusterManager { .subscribe(this.optimizerReady$); // broker messages between workers - this.workers.forEach(worker => { - worker.on('broadcast', msg => { - this.workers.forEach(to => { + this.workers.forEach((worker) => { + worker.on('broadcast', (msg) => { + this.workers.forEach((to) => { if (to !== worker && to.online) { to.fork!.send(msg); } @@ -156,7 +156,7 @@ export class ClusterManager { this.server.on('reloadLoggingConfigFromServerWorker', () => { process.emit('message' as any, { reloadLoggingConfig: true } as any); - this.workers.forEach(worker => { + this.workers.forEach((worker) => { worker.fork!.send({ reloadLoggingConfig: true }); }); }); @@ -182,7 +182,7 @@ export class ClusterManager { const extraPaths = [...pluginPaths, ...scanDirs]; const pluginInternalDirsIgnore = scanDirs - .map(scanDir => resolve(scanDir, '*')) + .map((scanDir) => resolve(scanDir, '*')) .concat(pluginPaths) .reduce( (acc, path) => @@ -212,10 +212,7 @@ export class ClusterManager { shouldRedirectFromOldBasePath: (path: string) => { // strip `s/{id}` prefix when checking for need to redirect if (path.startsWith('s/')) { - path = path - .split('/') - .slice(2) - .join('/'); + path = path.split('/').slice(2).join('/'); } const isApp = path.startsWith('app/'); @@ -253,7 +250,7 @@ export class ClusterManager { fromRoot('x-pack/legacy/server'), fromRoot('config'), ...extraPaths, - ].map(path => resolve(path)) + ].map((path) => resolve(path)) ) ); diff --git a/src/cli/cluster/run_kbn_optimizer.ts b/src/cli/cluster/run_kbn_optimizer.ts index e4bd6b98dd2b9..f36ce70f65a45 100644 --- a/src/cli/cluster/run_kbn_optimizer.ts +++ b/src/cli/cluster/run_kbn_optimizer.ts @@ -33,9 +33,10 @@ import { LegacyConfig } from '../../core/server/legacy'; export function runKbnOptimizer(opts: Record, config: LegacyConfig) { const optimizerConfig = OptimizerConfig.create({ repoRoot: REPO_ROOT, - watch: true, + watch: !!opts.watch, includeCoreBundle: true, cache: !!opts.cache, + dist: !!opts.dist, oss: !!opts.oss, examples: !!opts.runExamples, pluginPaths: config.get('plugins.paths'), diff --git a/src/cli/cluster/worker.ts b/src/cli/cluster/worker.ts index c73d3edbf7df7..dc6e6d5676651 100644 --- a/src/cli/cluster/worker.ts +++ b/src/cli/cluster/worker.ts @@ -136,7 +136,7 @@ export class Worker extends EventEmitter { this.processBinder.destroy(); // wait until the cluster reports this fork has exited, then resolve - await new Promise(resolve => this.once('fork:exit', resolve)); + await new Promise((resolve) => this.once('fork:exit', resolve)); } } @@ -179,7 +179,7 @@ export class Worker extends EventEmitter { flushChangeBuffer() { const files = _.unique(this.changes.splice(0)); const prefix = files.length > 1 ? '\n - ' : ''; - return files.reduce(function(list, file) { + return files.reduce(function (list, file) { return `${list || ''}${prefix}"${file}"`; }, ''); } @@ -188,7 +188,7 @@ export class Worker extends EventEmitter { if (this.fork) { // once "exit" event is received with 0 status, start() is called again this.shutdown(); - await new Promise(cb => this.once('online', cb)); + await new Promise((cb) => this.once('online', cb)); return; } @@ -214,6 +214,6 @@ export class Worker extends EventEmitter { this.processBinder.on('exit', () => this.shutdown()); // wait for the fork to report it is online before resolving - await new Promise(cb => this.once('fork:online', cb)); + await new Promise((cb) => this.once('fork:online', cb)); } } diff --git a/src/cli/command.js b/src/cli/command.js index 6f083bb2a1fa2..f4781fcab1e20 100644 --- a/src/cli/command.js +++ b/src/cli/command.js @@ -23,7 +23,7 @@ import Chalk from 'chalk'; import help from './help'; import { Command } from 'commander'; -Command.prototype.error = function(err) { +Command.prototype.error = function (err) { if (err && err.message) err = err.message; console.log( @@ -37,7 +37,7 @@ ${help(this, ' ')} process.exit(64); // eslint-disable-line no-process-exit }; -Command.prototype.defaultHelp = function() { +Command.prototype.defaultHelp = function () { console.log( ` ${help(this, ' ')} @@ -48,7 +48,7 @@ ${help(this, ' ')} process.exit(64); // eslint-disable-line no-process-exit }; -Command.prototype.unknownArgv = function(argv) { +Command.prototype.unknownArgv = function (argv) { if (argv) this.__unknownArgv = argv; return this.__unknownArgv ? this.__unknownArgv.slice(0) : []; }; @@ -57,11 +57,11 @@ Command.prototype.unknownArgv = function(argv) { * setup the command to accept arbitrary configuration via the cli * @return {[type]} [description] */ -Command.prototype.collectUnknownOptions = function() { +Command.prototype.collectUnknownOptions = function () { const title = `Extra ${this._name} options`; this.allowUnknownOption(); - this.getUnknownOptions = function() { + this.getUnknownOptions = function () { const opts = {}; const unknowns = this.unknownArgv(); @@ -95,17 +95,17 @@ Command.prototype.collectUnknownOptions = function() { return this; }; -Command.prototype.parseOptions = _.wrap(Command.prototype.parseOptions, function(parse, argv) { +Command.prototype.parseOptions = _.wrap(Command.prototype.parseOptions, function (parse, argv) { const opts = parse.call(this, argv); this.unknownArgv(opts.unknown); return opts; }); -Command.prototype.action = _.wrap(Command.prototype.action, function(action, fn) { - return action.call(this, function(...args) { +Command.prototype.action = _.wrap(Command.prototype.action, function (action, fn) { + return action.call(this, function (...args) { const ret = fn.apply(this, args); if (ret && typeof ret.then === 'function') { - ret.then(null, function(e) { + ret.then(null, function (e) { console.log('FATAL CLI ERROR', e.stack); process.exit(1); }); diff --git a/src/cli/help.js b/src/cli/help.js index a2dc638d2b6ee..656944d85b254 100644 --- a/src/cli/help.js +++ b/src/cli/help.js @@ -24,7 +24,7 @@ export default function help(command, spaces) { return command.outputHelp(); } - const defCmd = _.find(command.commands, function(cmd) { + const defCmd = _.find(command.commands, function (cmd) { return cmd._name === 'serve'; }); @@ -53,12 +53,12 @@ function indent(str, n) { function commandsSummary(program) { const cmds = _.compact( - program.commands.map(function(cmd) { + program.commands.map(function (cmd) { const name = cmd._name; if (name === '*') return; const opts = cmd.options.length ? ' [options]' : ''; const args = cmd._args - .map(function(arg) { + .map(function (arg) { return humanReadableArgName(arg); }) .join(' '); @@ -67,11 +67,11 @@ function commandsSummary(program) { }) ); - const cmdLColWidth = cmds.reduce(function(width, cmd) { + const cmdLColWidth = cmds.reduce(function (width, cmd) { return Math.max(width, cmd[0].length); }, 0); - return cmds.reduce(function(help, cmd) { + return cmds.reduce(function (help, cmd) { return `${help || ''}${_.padRight(cmd[0], cmdLColWidth)} ${cmd[1] || ''}\n`; }, ''); } diff --git a/src/cli/repl/index.js b/src/cli/repl/index.js index 37a51b4d1ec9e..0b27fafcef84e 100644 --- a/src/cli/repl/index.js +++ b/src/cli/repl/index.js @@ -72,7 +72,7 @@ function prettyPrint(text, o, depth) { // This lets us handle promises more gracefully than the default REPL, // which doesn't show the results. function promiseFriendlyWriter({ displayPrompt, getPrintDepth }) { - return result => promisePrint(result, displayPrompt, getPrintDepth); + return (result) => promisePrint(result, displayPrompt, getPrintDepth); } function promisePrint(result, displayPrompt, getPrintDepth) { @@ -83,8 +83,8 @@ function promisePrint(result, displayPrompt, getPrintDepth) { Promise.resolve() .then(() => console.log('Waiting for promise...')) .then(() => result) - .then(o => prettyPrint('Promise Resolved: \n', o, depth)) - .catch(err => prettyPrint('Promise Rejected: \n', err, depth)) + .then((o) => prettyPrint('Promise Resolved: \n', o, depth)) + .catch((err) => prettyPrint('Promise Rejected: \n', err, depth)) .then(displayPrompt); return ''; } diff --git a/src/cli/repl/repl.test.js b/src/cli/repl/repl.test.js index 9abb43c338290..3a032d415e5f2 100644 --- a/src/cli/repl/repl.test.js +++ b/src/cli/repl/repl.test.js @@ -17,7 +17,7 @@ * under the License. */ -jest.mock('repl', () => ({ start: opts => ({ opts, context: {} }) }), { virtual: true }); +jest.mock('repl', () => ({ start: (opts) => ({ opts, context: {} }) }), { virtual: true }); describe('repl', () => { const originalConsoleLog = console.log; @@ -25,7 +25,7 @@ describe('repl', () => { beforeEach(() => { global.console.log = jest.fn(); - require('repl').start = opts => { + require('repl').start = (opts) => { let resetHandler; const replServer = { opts, @@ -188,7 +188,7 @@ describe('repl', () => { async function waitForPrompt(replServer, fn) { let resolveDone; - const done = new Promise(resolve => (resolveDone = resolve)); + const done = new Promise((resolve) => (resolveDone = resolve)); replServer.displayPrompt = () => { resolveDone(); }; diff --git a/src/cli/serve/integration_tests/invalid_config.test.ts b/src/cli/serve/integration_tests/invalid_config.test.ts index da6684fae8cef..fd6fa1bf192fc 100644 --- a/src/cli/serve/integration_tests/invalid_config.test.ts +++ b/src/cli/serve/integration_tests/invalid_config.test.ts @@ -29,10 +29,10 @@ interface LogEntry { type: string; } -describe('cli invalid config support', function() { +describe('cli invalid config support', function () { it( 'exits with statusCode 64 and logs a single line when config is invalid', - function() { + function () { // Unused keys only throw once LegacyService starts, so disable migrations so that Core // will finish the start lifecycle without a running Elasticsearch instance. const { error, status, stdout } = spawnSync( @@ -47,9 +47,9 @@ describe('cli invalid config support', function() { .toString('utf8') .split('\n') .filter(Boolean) - .map(line => JSON.parse(line) as LogEntry) - .filter(line => line.tags.includes('fatal')) - .map(obj => ({ + .map((line) => JSON.parse(line) as LogEntry) + .filter((line) => line.tags.includes('fatal')) + .map((obj) => ({ ...obj, pid: '## PID ##', '@timestamp': '## @timestamp ##', diff --git a/src/cli/serve/integration_tests/reload_logging_config.test.ts b/src/cli/serve/integration_tests/reload_logging_config.test.ts index 9ad8438c312a1..35391b9b58ecc 100644 --- a/src/cli/serve/integration_tests/reload_logging_config.test.ts +++ b/src/cli/serve/integration_tests/reload_logging_config.test.ts @@ -70,7 +70,7 @@ function watchFileUntil(path: string, matcher: RegExp, timeout: number) { } function containsJsonOnly(content: string[]) { - return content.every(line => line.startsWith('{')); + return content.every((line) => line.startsWith('{')); } function createConfigManager(configPath: string) { @@ -83,7 +83,7 @@ function createConfigManager(configPath: string) { }; } -describe('Server logging configuration', function() { +describe('Server logging configuration', function () { let child: undefined | Child.ChildProcess; beforeEach(() => { @@ -92,7 +92,7 @@ describe('Server logging configuration', function() { afterEach(async () => { if (child !== undefined) { - const exitPromise = new Promise(resolve => child?.once('exit', resolve)); + const exitPromise = new Promise((resolve) => child?.once('exit', resolve)); child.kill('SIGKILL'); await exitPromise; } @@ -110,7 +110,7 @@ describe('Server logging configuration', function() { describe('legacy logging', () => { it( 'should be reloadable via SIGHUP process signaling', - async function() { + async function () { const configFilePath = Path.resolve(tempDir, 'kibana.yml'); Fs.copyFileSync(legacyConfig, configFilePath); @@ -123,17 +123,13 @@ describe('Server logging configuration', function() { ]); const message$ = Rx.fromEvent(child.stdout, 'data').pipe( - map(messages => - String(messages) - .split('\n') - .filter(Boolean) - ) + map((messages) => String(messages).split('\n').filter(Boolean)) ); await message$ .pipe( // We know the sighup handler will be registered before this message logged - filter(messages => messages.some(m => m.includes('setting up root'))), + filter((messages) => messages.some((m) => m.includes('setting up root'))), take(1) ) .toPromise(); @@ -141,7 +137,7 @@ describe('Server logging configuration', function() { const lastMessage = await message$.pipe(take(1)).toPromise(); expect(containsJsonOnly(lastMessage)).toBe(true); - createConfigManager(configFilePath).modify(oldConfig => { + createConfigManager(configFilePath).modify((oldConfig) => { oldConfig.logging.json = false; return oldConfig; }); @@ -150,7 +146,7 @@ describe('Server logging configuration', function() { await message$ .pipe( - filter(messages => !containsJsonOnly(messages)), + filter((messages) => !containsJsonOnly(messages)), take(1) ) .toPromise(); @@ -160,7 +156,7 @@ describe('Server logging configuration', function() { it( 'should recreate file handle on SIGHUP', - async function() { + async function () { const logPath = Path.resolve(tempDir, 'kibana.log'); const logPathArchived = Path.resolve(tempDir, 'kibana_archive.log'); @@ -188,24 +184,20 @@ describe('Server logging configuration', function() { describe('platform logging', () => { it( 'should be reloadable via SIGHUP process signaling', - async function() { + async function () { const configFilePath = Path.resolve(tempDir, 'kibana.yml'); Fs.copyFileSync(configFileLogConsole, configFilePath); child = Child.spawn(process.execPath, [kibanaPath, '--oss', '--config', configFilePath]); const message$ = Rx.fromEvent(child.stdout, 'data').pipe( - map(messages => - String(messages) - .split('\n') - .filter(Boolean) - ) + map((messages) => String(messages).split('\n').filter(Boolean)) ); await message$ .pipe( // We know the sighup handler will be registered before this message logged - filter(messages => messages.some(m => m.includes('setting up root'))), + filter((messages) => messages.some((m) => m.includes('setting up root'))), take(1) ) .toPromise(); @@ -213,7 +205,7 @@ describe('Server logging configuration', function() { const lastMessage = await message$.pipe(take(1)).toPromise(); expect(containsJsonOnly(lastMessage)).toBe(true); - createConfigManager(configFilePath).modify(oldConfig => { + createConfigManager(configFilePath).modify((oldConfig) => { oldConfig.logging.appenders.console.layout.kind = 'pattern'; return oldConfig; }); @@ -221,7 +213,7 @@ describe('Server logging configuration', function() { await message$ .pipe( - filter(messages => !containsJsonOnly(messages)), + filter((messages) => !containsJsonOnly(messages)), take(1) ) .toPromise(); @@ -230,14 +222,14 @@ describe('Server logging configuration', function() { ); it( 'should recreate file handle on SIGHUP', - async function() { + async function () { const configFilePath = Path.resolve(tempDir, 'kibana.yml'); Fs.copyFileSync(configFileLogFile, configFilePath); const logPath = Path.resolve(tempDir, 'kibana.log'); const logPathArchived = Path.resolve(tempDir, 'kibana_archive.log'); - createConfigManager(configFilePath).modify(oldConfig => { + createConfigManager(configFilePath).modify((oldConfig) => { oldConfig.logging.appenders.file.path = logPath; return oldConfig; }); diff --git a/src/cli/serve/read_keystore.js b/src/cli/serve/read_keystore.js index c17091a11f5c1..cfe02735630f2 100644 --- a/src/cli/serve/read_keystore.js +++ b/src/cli/serve/read_keystore.js @@ -30,7 +30,7 @@ export function readKeystore(dataPath = getDataPath()) { const keys = Object.keys(keystore.data); const data = {}; - keys.forEach(key => { + keys.forEach((key) => { set(data, key, keystore.data[key]); }); diff --git a/src/cli/serve/serve.js b/src/cli/serve/serve.js index eaec8d55f6a56..8bc65f3da7111 100644 --- a/src/cli/serve/serve.js +++ b/src/cli/serve/serve.js @@ -52,9 +52,9 @@ const CAN_REPL = canRequire(REPL_PATH); const XPACK_DIR = resolve(__dirname, '../../../x-pack'); const XPACK_INSTALLED = canRequire(XPACK_DIR); -const pathCollector = function() { +const pathCollector = function () { const paths = []; - return function(path) { + return function (path) { paths.push(resolve(process.cwd(), path)); return paths; }; @@ -109,7 +109,7 @@ function applyConfigOverrides(rawConfig, opts, extraCliOptions) { (customElasticsearchHosts.length > 0 && customElasticsearchHosts) || [ 'https://localhost:9200', ] - ).map(hostUrl => { + ).map((hostUrl) => { const parsedUrl = url.parse(hostUrl); if (parsedUrl.hostname !== 'localhost') { throw new Error( @@ -159,7 +159,7 @@ function applyConfigOverrides(rawConfig, opts, extraCliOptions) { return rawConfig; } -export default function(program) { +export default function (program) { const command = program.command('serve'); command @@ -213,6 +213,7 @@ export default function(program) { .option('--dev', 'Run the server with development mode defaults') .option('--open', 'Open a browser window to the base url after the server is started') .option('--ssl', 'Run the dev server using HTTPS') + .option('--dist', 'Use production assets from kbn/optimizer') .option( '--no-base-path', "Don't put a proxy in front of the dev server, which adds a random basePath" @@ -222,7 +223,7 @@ export default function(program) { .option('--no-dev-config', 'Prevents loading the kibana.dev.yml file in --dev mode'); } - command.action(async function(opts) { + command.action(async function (opts) { if (opts.dev && opts.devConfig !== false) { try { const kbnDevConfig = fromRoot('config/kibana.dev.yml'); @@ -255,12 +256,13 @@ export default function(program) { optimize: !!opts.optimize, oss: !!opts.oss, cache: !!opts.cache, + dist: !!opts.dist, }, features: { isClusterModeSupported: CAN_CLUSTER, isReplModeSupported: CAN_REPL, }, - applyConfigOverrides: rawConfig => applyConfigOverrides(rawConfig, opts, unknownOptions), + applyConfigOverrides: (rawConfig) => applyConfigOverrides(rawConfig, opts, unknownOptions), }); }); } diff --git a/src/cli_keystore/add.test.js b/src/cli_keystore/add.test.js index 72f15a5439ef0..320581b470c2b 100644 --- a/src/cli_keystore/add.test.js +++ b/src/cli_keystore/add.test.js @@ -23,14 +23,14 @@ const mockKeystoreData = 'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; jest.mock('fs', () => ({ - readFileSync: jest.fn().mockImplementation(path => { + readFileSync: jest.fn().mockImplementation((path) => { if (!path.includes('nonexistent')) { return JSON.stringify(mockKeystoreData); } throw { code: 'ENOENT' }; }), - existsSync: jest.fn().mockImplementation(path => { + existsSync: jest.fn().mockImplementation((path) => { return !path.includes('nonexistent'); }), writeFileSync: jest.fn(), diff --git a/src/cli_keystore/cli_keystore.js b/src/cli_keystore/cli_keystore.js index 7c90d88f7b0cd..e1561b343ef39 100644 --- a/src/cli_keystore/cli_keystore.js +++ b/src/cli_keystore/cli_keystore.js @@ -50,13 +50,13 @@ removeCli(program, keystore); program .command('help ') .description('get the help for a specific command') - .action(function(cmdName) { + .action(function (cmdName) { const cmd = _.find(program.commands, { _name: cmdName }); if (!cmd) return program.error(`unknown command ${cmdName}`); cmd.help(); }); -program.command('*', null, { noHelp: true }).action(function(cmd) { +program.command('*', null, { noHelp: true }).action(function (cmd) { program.error(`unknown command ${cmd}`); }); diff --git a/src/cli_keystore/create.test.js b/src/cli_keystore/create.test.js index 01355f51a0c55..33b5aa4bd07d8 100644 --- a/src/cli_keystore/create.test.js +++ b/src/cli_keystore/create.test.js @@ -23,14 +23,14 @@ const mockKeystoreData = 'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; jest.mock('fs', () => ({ - readFileSync: jest.fn().mockImplementation(path => { + readFileSync: jest.fn().mockImplementation((path) => { if (!path.includes('foo')) { return JSON.stringify(mockKeystoreData); } throw { code: 'ENOENT' }; }), - existsSync: jest.fn().mockImplementation(path => { + existsSync: jest.fn().mockImplementation((path) => { return !path.includes('foo'); }), writeFileSync: jest.fn(), diff --git a/src/cli_keystore/list.test.js b/src/cli_keystore/list.test.js index 3fb5014820865..857991b5ae3b9 100644 --- a/src/cli_keystore/list.test.js +++ b/src/cli_keystore/list.test.js @@ -23,14 +23,14 @@ const mockKeystoreData = 'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; jest.mock('fs', () => ({ - readFileSync: jest.fn().mockImplementation(path => { + readFileSync: jest.fn().mockImplementation((path) => { if (!path.includes('nonexistent')) { return JSON.stringify(mockKeystoreData); } throw { code: 'ENOENT' }; }), - existsSync: jest.fn().mockImplementation(path => { + existsSync: jest.fn().mockImplementation((path) => { return !path.includes('nonexistent'); }), })); diff --git a/src/cli_plugin/cli.js b/src/cli_plugin/cli.js index d1cdf983c0da4..da1068b54b4b5 100644 --- a/src/cli_plugin/cli.js +++ b/src/cli_plugin/cli.js @@ -43,13 +43,13 @@ removeCommand(program); program .command('help ') .description('get the help for a specific command') - .action(function(cmdName) { + .action(function (cmdName) { const cmd = _.find(program.commands, { _name: cmdName }); if (!cmd) return program.error(`unknown command ${cmdName}`); cmd.help(); }); -program.command('*', null, { noHelp: true }).action(function(cmd) { +program.command('*', null, { noHelp: true }).action(function (cmd) { program.error(`unknown command ${cmd}`); }); diff --git a/src/cli_plugin/install/cleanup.js b/src/cli_plugin/install/cleanup.js index eaa25962ef0e4..f31e028226c27 100644 --- a/src/cli_plugin/install/cleanup.js +++ b/src/cli_plugin/install/cleanup.js @@ -21,7 +21,7 @@ import del from 'del'; import fs from 'fs'; export function cleanPrevious(settings, logger) { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { try { fs.statSync(settings.workingPath); diff --git a/src/cli_plugin/install/cleanup.test.js b/src/cli_plugin/install/cleanup.test.js index c6602636cb481..46089f61d5e83 100644 --- a/src/cli_plugin/install/cleanup.test.js +++ b/src/cli_plugin/install/cleanup.test.js @@ -24,32 +24,32 @@ import del from 'del'; import { cleanPrevious, cleanArtifacts } from './cleanup'; import Logger from '../lib/logger'; -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('pluginCleaner', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('pluginCleaner', function () { const settings = { workingPath: 'dummy', }; - describe('cleanPrevious', function() { + describe('cleanPrevious', function () { let errorStub; let logger; - beforeEach(function() { + beforeEach(function () { errorStub = sinon.stub(); logger = new Logger(settings); sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); }); - afterEach(function() { + afterEach(function () { logger.log.restore(); logger.error.restore(); fs.statSync.restore(); del.sync.restore(); }); - it('should resolve if the working path does not exist', function() { + it('should resolve if the working path does not exist', function () { sinon.stub(del, 'sync'); sinon.stub(fs, 'statSync').callsFake(() => { const error = new Error('ENOENT'); @@ -59,75 +59,75 @@ describe('kibana cli', function() { return cleanPrevious(settings, logger) .catch(errorStub) - .then(function() { + .then(function () { expect(errorStub.called).toBe(false); }); }); - it('should rethrow any exception except ENOENT from fs.statSync', function() { + it('should rethrow any exception except ENOENT from fs.statSync', function () { sinon.stub(del, 'sync'); sinon.stub(fs, 'statSync').throws(new Error('An Unhandled Error')); errorStub = sinon.stub(); return cleanPrevious(settings, logger) .catch(errorStub) - .then(function() { + .then(function () { expect(errorStub.called).toBe(true); }); }); - it('should log a message if there was a working directory', function() { + it('should log a message if there was a working directory', function () { sinon.stub(del, 'sync'); sinon.stub(fs, 'statSync'); return cleanPrevious(settings, logger) .catch(errorStub) - .then(function() { + .then(function () { expect(logger.log.calledWith('Found previous install attempt. Deleting...')).toBe( true ); }); }); - it('should rethrow any exception from del.sync', function() { + it('should rethrow any exception from del.sync', function () { sinon.stub(fs, 'statSync'); sinon.stub(del, 'sync').throws(new Error('I am an error thrown by del')); errorStub = sinon.stub(); return cleanPrevious(settings, logger) .catch(errorStub) - .then(function() { + .then(function () { expect(errorStub.called).toBe(true); }); }); - it('should resolve if the working path is deleted', function() { + it('should resolve if the working path is deleted', function () { sinon.stub(del, 'sync'); sinon.stub(fs, 'statSync'); return cleanPrevious(settings, logger) .catch(errorStub) - .then(function() { + .then(function () { expect(errorStub.called).toBe(false); }); }); }); - describe('cleanArtifacts', function() { - beforeEach(function() {}); + describe('cleanArtifacts', function () { + beforeEach(function () {}); - afterEach(function() { + afterEach(function () { del.sync.restore(); }); - it('should attempt to delete the working directory', function() { + it('should attempt to delete the working directory', function () { sinon.stub(del, 'sync'); cleanArtifacts(settings); expect(del.sync.calledWith(settings.workingPath)).toBe(true); }); - it('should swallow any errors thrown by del.sync', function() { + it('should swallow any errors thrown by del.sync', function () { sinon.stub(del, 'sync').throws(new Error('Something bad happened.')); expect(() => cleanArtifacts(settings)).not.toThrow(); diff --git a/src/cli_plugin/install/download.js b/src/cli_plugin/install/download.js index fc1fe8323520b..10d20367c1b7b 100644 --- a/src/cli_plugin/install/download.js +++ b/src/cli_plugin/install/download.js @@ -80,7 +80,7 @@ export function download(settings, logger) { logger.log(`Attempting to transfer from ${sourceUrl}`); - return _downloadSingle(settings, logger, sourceUrl).catch(err => { + return _downloadSingle(settings, logger, sourceUrl).catch((err) => { const isUnsupportedProtocol = err instanceof UnsupportedProtocolError; const isDownloadResourceNotFound = err.message === 'ENOTFOUND'; if (isUnsupportedProtocol || isDownloadResourceNotFound) { diff --git a/src/cli_plugin/install/download.test.js b/src/cli_plugin/install/download.test.js index ef924f28a65e7..93e5e414fed74 100644 --- a/src/cli_plugin/install/download.test.js +++ b/src/cli_plugin/install/download.test.js @@ -28,8 +28,8 @@ import { download, _downloadSingle, _getFilePath, _checkFilePathDeprecation } fr import { join } from 'path'; import http from 'http'; -describe('kibana cli', function() { - describe('plugin downloader', function() { +describe('kibana cli', function () { + describe('plugin downloader', function () { const testWorkingPath = join(__dirname, '.test.data.download'); const tempArchiveFilePath = join(testWorkingPath, 'archive.part'); @@ -57,46 +57,44 @@ describe('kibana cli', function() { throw new Error('expected the promise to reject'); } - beforeEach(function() { + beforeEach(function () { sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); del.sync(testWorkingPath); Fs.mkdirSync(testWorkingPath, { recursive: true }); }); - afterEach(function() { + afterEach(function () { logger.log.restore(); logger.error.restore(); del.sync(testWorkingPath); }); - describe('_downloadSingle', function() { - beforeEach(function() {}); + describe('_downloadSingle', function () { + beforeEach(function () {}); - describe('http downloader', function() { - it('should throw an ENOTFOUND error for a http ulr that returns 404', function() { - nock('http://example.com') - .get('/plugin.tar.gz') - .reply(404); + describe('http downloader', function () { + it('should throw an ENOTFOUND error for a http ulr that returns 404', function () { + nock('http://example.com').get('/plugin.tar.gz').reply(404); const sourceUrl = 'http://example.com/plugin.tar.gz'; - return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function(err) { + return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function (err) { expect(err.message).toMatch(/ENOTFOUND/); expectWorkingPathEmpty(); }); }); - it('should throw an UnsupportedProtocolError for an invalid url', function() { + it('should throw an UnsupportedProtocolError for an invalid url', function () { const sourceUrl = 'i am an invalid url'; - return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function(err) { + return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function (err) { expect(err).toBeInstanceOf(UnsupportedProtocolError); expectWorkingPathEmpty(); }); }); - it('should download a file from a valid http url', function() { + it('should download a file from a valid http url', function () { const filePath = join(__dirname, '__fixtures__/replies/banana.jpg'); nock('http://example.com') @@ -109,40 +107,40 @@ describe('kibana cli', function() { const sourceUrl = 'http://example.com/plugin.zip'; - return _downloadSingle(settings, logger, sourceUrl).then(function() { + return _downloadSingle(settings, logger, sourceUrl).then(function () { expectWorkingPathNotEmpty(); }); }); }); - describe('local file downloader', function() { - it('should throw an ENOTFOUND error for an invalid local file', function() { + describe('local file downloader', function () { + it('should throw an ENOTFOUND error for an invalid local file', function () { const filePath = join(__dirname, '__fixtures__/replies/i-am-not-there.zip'); const sourceUrl = 'file://' + filePath.replace(/\\/g, '/'); - return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function(err) { + return _downloadSingle(settings, logger, sourceUrl).then(shouldReject, function (err) { expect(err.message).toMatch(/ENOTFOUND/); expectWorkingPathEmpty(); }); }); - it('should copy a valid local file', function() { + it('should copy a valid local file', function () { const filePath = join(__dirname, '__fixtures__/replies/banana.jpg'); const sourceUrl = 'file://' + filePath.replace(/\\/g, '/'); - return _downloadSingle(settings, logger, sourceUrl).then(function() { + return _downloadSingle(settings, logger, sourceUrl).then(function () { expectWorkingPathNotEmpty(); }); }); }); }); - describe('_getFilePath', function() { - it('should decode paths', function() { + describe('_getFilePath', function () { + it('should decode paths', function () { expect(_getFilePath('Test%20folder/file.zip')).toBe('Test folder/file.zip'); }); - it('should remove the leading slash from windows paths', function() { + it('should remove the leading slash from windows paths', function () { const platform = Object.getOwnPropertyDescriptor(process, 'platform'); Object.defineProperty(process, 'platform', { value: 'win32' }); @@ -152,8 +150,8 @@ describe('kibana cli', function() { }); }); - describe('Windows file:// deprecation', function() { - it('should log a warning if a file:// path is used', function() { + describe('Windows file:// deprecation', function () { + it('should log a warning if a file:// path is used', function () { const platform = Object.getOwnPropertyDescriptor(process, 'platform'); Object.defineProperty(process, 'platform', { value: 'win32' }); const logger = { @@ -169,8 +167,8 @@ describe('kibana cli', function() { }); }); - describe('download', function() { - it('should loop through bad urls until it finds a good one.', function() { + describe('download', function () { + it('should loop through bad urls until it finds a good one.', function () { const filePath = join(__dirname, '__fixtures__/replies/test_plugin.zip'); settings.urls = [ 'http://example.com/badfile1.tar.gz', @@ -190,7 +188,7 @@ describe('kibana cli', function() { .get('/goodfile.tar.gz') .replyWithFile(200, filePath); - return download(settings, logger).then(function() { + return download(settings, logger).then(function () { expect(logger.log.getCall(0).args[0]).toMatch(/badfile1.tar.gz/); expect(logger.log.getCall(1).args[0]).toMatch(/badfile2.tar.gz/); expect(logger.log.getCall(2).args[0]).toMatch(/I am a bad uri/); @@ -199,7 +197,7 @@ describe('kibana cli', function() { }); }); - it('should stop looping through urls when it finds a good one.', function() { + it('should stop looping through urls when it finds a good one.', function () { const filePath = join(__dirname, '__fixtures__/replies/test_plugin.zip'); settings.urls = [ 'http://example.com/badfile1.tar.gz', @@ -221,7 +219,7 @@ describe('kibana cli', function() { .get('/badfile3.tar.gz') .reply(404); - return download(settings, logger).then(function() { + return download(settings, logger).then(function () { for (let i = 0; i < logger.log.callCount; i++) { expect(logger.log.getCall(i).args[0]).not.toMatch(/badfile3.tar.gz/); } @@ -229,7 +227,7 @@ describe('kibana cli', function() { }); }); - it("should throw an error when it doesn't find a good url.", function() { + it("should throw an error when it doesn't find a good url.", function () { settings.urls = [ 'http://example.com/badfile1.tar.gz', 'http://example.com/badfile2.tar.gz', @@ -247,25 +245,25 @@ describe('kibana cli', function() { .get('/badfile3.tar.gz') .reply(404); - return download(settings, logger).then(shouldReject, function(err) { + return download(settings, logger).then(shouldReject, function (err) { expect(err.message).toMatch(/no valid url specified/i); expectWorkingPathEmpty(); }); }); - afterAll(function() { + afterAll(function () { nock.cleanAll(); }); }); - describe('proxy support', function() { + describe('proxy support', function () { const proxyPort = 2626; const proxyUrl = `http://localhost:${proxyPort}`; let proxyHit = false; let proxyConnectHit = false; - const proxy = http.createServer(function(req, res) { + const proxy = http.createServer(function (req, res) { proxyHit = true; // Our test proxy simply returns an empty 200 response, since we only // care about the download promise being resolved. @@ -301,29 +299,29 @@ describe('kibana cli', function() { .replyWithFile(200, join(__dirname, '__fixtures__/replies/test_plugin.zip')); } - beforeAll(function(done) { + beforeAll(function (done) { proxy.listen(proxyPort, done); }); - beforeEach(function() { + beforeEach(function () { proxyHit = false; proxyConnectHit = false; }); - afterEach(function() { + afterEach(function () { delete process.env.http_proxy; delete process.env.https_proxy; delete process.env.no_proxy; }); - it('should use http_proxy env variable', function() { + it('should use http_proxy env variable', function () { process.env.http_proxy = proxyUrl; settings.urls = ['http://example.com/plugin.zip']; return download(settings, logger).then(expectProxyHit); }); - it('should use https_proxy for secure URLs', function() { + it('should use https_proxy for secure URLs', function () { process.env.https_proxy = proxyUrl; settings.urls = ['https://example.com/plugin.zip']; @@ -340,7 +338,7 @@ describe('kibana cli', function() { ); }); - it('should not use http_proxy for HTTPS urls', function() { + it('should not use http_proxy for HTTPS urls', function () { process.env.http_proxy = proxyUrl; settings.urls = ['https://example.com/plugin.zip']; @@ -349,7 +347,7 @@ describe('kibana cli', function() { return download(settings, logger).then(expectNoProxyHit); }); - it('should not use https_proxy for HTTP urls', function() { + it('should not use https_proxy for HTTP urls', function () { process.env.https_proxy = proxyUrl; settings.urls = ['http://example.com/plugin.zip']; @@ -358,7 +356,7 @@ describe('kibana cli', function() { return download(settings, logger).then(expectNoProxyHit); }); - it('should support domains in no_proxy', function() { + it('should support domains in no_proxy', function () { process.env.http_proxy = proxyUrl; process.env.no_proxy = 'foo.bar, example.com'; settings.urls = ['http://example.com/plugin.zip']; @@ -368,7 +366,7 @@ describe('kibana cli', function() { return download(settings, logger).then(expectNoProxyHit); }); - it('should support subdomains in no_proxy', function() { + it('should support subdomains in no_proxy', function () { process.env.http_proxy = proxyUrl; process.env.no_proxy = 'foo.bar,plugins.example.com'; settings.urls = ['http://plugins.example.com/plugin.zip']; @@ -378,7 +376,7 @@ describe('kibana cli', function() { return download(settings, logger).then(expectNoProxyHit); }); - it('should accept wildcard subdomains in no_proxy', function() { + it('should accept wildcard subdomains in no_proxy', function () { process.env.http_proxy = proxyUrl; process.env.no_proxy = 'foo.bar, .example.com'; settings.urls = ['http://plugins.example.com/plugin.zip']; @@ -388,7 +386,7 @@ describe('kibana cli', function() { return download(settings, logger).then(expectNoProxyHit); }); - it('should support asterisk wildcard no_proxy syntax', function() { + it('should support asterisk wildcard no_proxy syntax', function () { process.env.http_proxy = proxyUrl; process.env.no_proxy = '*.example.com'; settings.urls = ['http://plugins.example.com/plugin.zip']; @@ -398,7 +396,7 @@ describe('kibana cli', function() { return download(settings, logger).then(expectNoProxyHit); }); - it('should support implicit ports in no_proxy', function() { + it('should support implicit ports in no_proxy', function () { process.env.https_proxy = proxyUrl; process.env.no_proxy = 'example.com:443'; settings.urls = ['https://example.com/plugin.zip']; @@ -408,7 +406,7 @@ describe('kibana cli', function() { return download(settings, logger).then(expectNoProxyHit); }); - afterAll(function(done) { + afterAll(function (done) { proxy.close(done); }); }); diff --git a/src/cli_plugin/install/downloaders/file.js b/src/cli_plugin/install/downloaders/file.js index eee8ddb21d6dd..56f83b03d5a90 100644 --- a/src/cli_plugin/install/downloaders/file.js +++ b/src/cli_plugin/install/downloaders/file.js @@ -43,7 +43,7 @@ async function copyFile({ readStream, writeStream, progress }) { writeStream.on('error', reject); // report progress as we transfer - readStream.on('data', chunk => { + readStream.on('data', (chunk) => { progress.progress(chunk.length); }); diff --git a/src/cli_plugin/install/downloaders/http.js b/src/cli_plugin/install/downloaders/http.js index 88dcdabe70dfd..0fc01453f2b4c 100644 --- a/src/cli_plugin/install/downloaders/http.js +++ b/src/cli_plugin/install/downloaders/http.js @@ -76,7 +76,7 @@ function downloadResponse({ resp, targetPath, progress }) { writeStream.on('error', reject); // report progress as we download - resp.on('data', chunk => { + resp.on('data', (chunk) => { progress.progress(chunk.length); }); diff --git a/src/cli_plugin/install/index.test.js b/src/cli_plugin/install/index.test.js index 6a64a673bb93e..39352f52f20fd 100644 --- a/src/cli_plugin/install/index.test.js +++ b/src/cli_plugin/install/index.test.js @@ -20,25 +20,25 @@ import sinon from 'sinon'; import index from './index'; -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('commander options', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('commander options', function () { const program = { - command: function() { + command: function () { return program; }, - description: function() { + description: function () { return program; }, - option: function() { + option: function () { return program; }, - action: function() { + action: function () { return program; }, }; - it('should define the command', function() { + it('should define the command', function () { sinon.spy(program, 'command'); index(program); @@ -47,7 +47,7 @@ describe('kibana cli', function() { program.command.restore(); }); - it('should define the description', function() { + it('should define the description', function () { sinon.spy(program, 'description'); index(program); @@ -56,7 +56,7 @@ describe('kibana cli', function() { program.description.restore(); }); - it('should define the command line options', function() { + it('should define the command line options', function () { const spy = sinon.spy(program, 'option'); const options = [/-q/, /-s/, /-c/, /-t/, /-d/]; @@ -77,7 +77,7 @@ describe('kibana cli', function() { expect(options).toHaveLength(0); }); - it('should call the action function', function() { + it('should call the action function', function () { sinon.spy(program, 'action'); index(program); diff --git a/src/cli_plugin/install/kibana.test.js b/src/cli_plugin/install/kibana.test.js index bbf364a755f8a..8c5dd00d09953 100644 --- a/src/cli_plugin/install/kibana.test.js +++ b/src/cli_plugin/install/kibana.test.js @@ -30,9 +30,9 @@ beforeEach(() => { jest.clearAllMocks(); }); -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('kibana', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('kibana', function () { const testWorkingPath = join(__dirname, '.test.data.kibana'); const tempArchiveFilePath = join(testWorkingPath, 'archive.part'); const pluginDir = join(__dirname, 'plugins'); @@ -48,21 +48,21 @@ describe('kibana cli', function() { const logger = new Logger(settings); - describe('assertVersion', function() { - beforeEach(function() { + describe('assertVersion', function () { + beforeEach(function () { del.sync(testWorkingPath); fs.mkdirSync(testWorkingPath, { recursive: true }); sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); }); - afterEach(function() { + afterEach(function () { logger.log.restore(); logger.error.restore(); del.sync(testWorkingPath); }); - it('should succeed with exact match', function() { + it('should succeed with exact match', function () { const settings = { workingPath: testWorkingPath, tempArchiveFile: tempArchiveFilePath, @@ -76,60 +76,60 @@ describe('kibana cli', function() { expect(() => assertVersion(settings)).not.toThrow(); }); - it('should throw an error if plugin is missing a kibana version.', function() { + it('should throw an error if plugin is missing a kibana version.', function () { expect(() => assertVersion(settings)).toThrow( /plugin package\.json is missing both a version property/i ); }); - it('should throw an error if plugin kibanaVersion does not match kibana version', function() { + it('should throw an error if plugin kibanaVersion does not match kibana version', function () { settings.plugins[0].kibanaVersion = '1.2.3.4'; expect(() => assertVersion(settings)).toThrow(/incompatible with Kibana/i); }); - it('should not throw an error if plugin kibanaVersion matches kibana version', function() { + it('should not throw an error if plugin kibanaVersion matches kibana version', function () { settings.plugins[0].kibanaVersion = '1.0.0'; expect(() => assertVersion(settings)).not.toThrow(); }); - it('should ignore version info after the dash in checks on valid version', function() { + it('should ignore version info after the dash in checks on valid version', function () { settings.plugins[0].kibanaVersion = '1.0.0-foo-bar-version-1.2.3'; expect(() => assertVersion(settings)).not.toThrow(); }); - it('should ignore version info after the dash in checks on invalid version', function() { + it('should ignore version info after the dash in checks on invalid version', function () { settings.plugins[0].kibanaVersion = '2.0.0-foo-bar-version-1.2.3'; expect(() => assertVersion(settings)).toThrow(/incompatible with Kibana/i); }); }); - describe('existingInstall', function() { + describe('existingInstall', function () { let processExitStub; - beforeEach(function() { + beforeEach(function () { processExitStub = sinon.stub(process, 'exit'); sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); }); - afterEach(function() { + afterEach(function () { processExitStub.restore(); logger.log.restore(); logger.error.restore(); }); - it('should throw an error if the plugin already exists.', function() { + it('should throw an error if the plugin already exists.', function () { fs.statSync.mockImplementationOnce(() => true); existingInstall(settings, logger); expect(logger.error.firstCall.args[0]).toMatch(/already exists/); expect(process.exit.called).toBe(true); }); - it('should not throw an error if the plugin does not exist.', function() { + it('should not throw an error if the plugin does not exist.', function () { fs.statSync.mockImplementationOnce(() => { throw { code: 'ENOENT' }; }); diff --git a/src/cli_plugin/install/pack.test.js b/src/cli_plugin/install/pack.test.js index efe310a4fed40..05a60107f80ff 100644 --- a/src/cli_plugin/install/pack.test.js +++ b/src/cli_plugin/install/pack.test.js @@ -27,8 +27,8 @@ import { extract, getPackData } from './pack'; import { _downloadSingle } from './download'; import { join } from 'path'; -describe('kibana cli', function() { - describe('pack', function() { +describe('kibana cli', function () { + describe('pack', function () { let testNum = 0; const workingPathRoot = join(__dirname, '.test.data.pack'); let testWorkingPath; @@ -37,7 +37,7 @@ describe('kibana cli', function() { let logger; let settings; - beforeEach(function() { + beforeEach(function () { //These tests are dependent on the file system, and I had some inconsistent //behavior with del.sync show up. Until these tests are re-written to not //depend on the file system, I make sure that each test uses a different @@ -60,7 +60,7 @@ describe('kibana cli', function() { Fs.mkdirSync(testWorkingPath, { recursive: true }); }); - afterEach(function() { + afterEach(function () { logger.log.restore(); logger.error.restore(); del.sync(workingPathRoot); @@ -77,10 +77,10 @@ describe('kibana cli', function() { throw new Error('expected the promise to reject'); } - describe('extract', function() { + describe('extract', function () { //Also only extracts the content from the kibana folder. //Ignores the others. - it('successfully extract a valid zip', function() { + it('successfully extract a valid zip', function () { return copyReplyFile('test_plugin.zip') .then(() => { return getPackData(settings, logger); @@ -104,8 +104,8 @@ describe('kibana cli', function() { }); }); - describe('getPackData', function() { - it('populate settings.plugins', function() { + describe('getPackData', function () { + it('populate settings.plugins', function () { return copyReplyFile('test_plugin.zip') .then(() => { return getPackData(settings, logger); @@ -118,7 +118,7 @@ describe('kibana cli', function() { }); }); - it('populate settings.plugin.kibanaVersion', function() { + it('populate settings.plugin.kibanaVersion', function () { //kibana.version is defined in this package.json and is different than plugin version return copyReplyFile('test_plugin_different_version.zip') .then(() => { @@ -129,7 +129,7 @@ describe('kibana cli', function() { }); }); - it('populate settings.plugin.kibanaVersion (default to plugin version)', function() { + it('populate settings.plugin.kibanaVersion (default to plugin version)', function () { //kibana.version is not defined in this package.json, defaults to plugin version return copyReplyFile('test_plugin.zip') .then(() => { @@ -140,7 +140,7 @@ describe('kibana cli', function() { }); }); - it('populate settings.plugins with multiple plugins', function() { + it('populate settings.plugins with multiple plugins', function () { return copyReplyFile('test_plugin_many.zip') .then(() => { return getPackData(settings, logger); @@ -172,32 +172,32 @@ describe('kibana cli', function() { }); }); - it('throw an error if there is no kibana plugin', function() { + it('throw an error if there is no kibana plugin', function () { return copyReplyFile('test_plugin_no_kibana.zip') .then(() => { return getPackData(settings, logger); }) - .then(shouldReject, err => { + .then(shouldReject, (err) => { expect(err.message).toMatch(/No kibana plugins found in archive/i); }); }); - it('throw an error with a corrupt zip', function() { + it('throw an error with a corrupt zip', function () { return copyReplyFile('corrupt.zip') .then(() => { return getPackData(settings, logger); }) - .then(shouldReject, err => { + .then(shouldReject, (err) => { expect(err.message).toMatch(/error retrieving/i); }); }); - it('throw an error if there an invalid plugin name', function() { + it('throw an error if there an invalid plugin name', function () { return copyReplyFile('invalid_name.zip') .then(() => { return getPackData(settings, logger); }) - .then(shouldReject, err => { + .then(shouldReject, (err) => { expect(err.message).toMatch(/invalid plugin name/i); }); }); diff --git a/src/cli_plugin/install/progress.test.js b/src/cli_plugin/install/progress.test.js index 5430af75968bb..3b66e8b3dc86c 100644 --- a/src/cli_plugin/install/progress.test.js +++ b/src/cli_plugin/install/progress.test.js @@ -21,26 +21,26 @@ import sinon from 'sinon'; import Progress from './progress'; import Logger from '../lib/logger'; -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('progressReporter', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('progressReporter', function () { let logger; let progress; - beforeEach(function() { + beforeEach(function () { logger = new Logger({ silent: false, quiet: false }); sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); progress = new Progress(logger); }); - afterEach(function() { + afterEach(function () { logger.log.restore(); logger.error.restore(); }); - describe('handleData', function() { - it('should show a max of 20 dots for full progress', function() { + describe('handleData', function () { + it('should show a max of 20 dots for full progress', function () { progress.init(1000); progress.progress(1000); progress.complete(); @@ -70,7 +70,7 @@ describe('kibana cli', function() { expect(logger.log.getCall(21).args[0]).toMatch(/complete/i); }); - it('should show dot for each 5% of completion', function() { + it('should show dot for each 5% of completion', function () { progress.init(1000); expect(logger.log.callCount).toBe(1); diff --git a/src/cli_plugin/install/rename.js b/src/cli_plugin/install/rename.js index 92adb21368007..1e5d94d474375 100644 --- a/src/cli_plugin/install/rename.js +++ b/src/cli_plugin/install/rename.js @@ -21,7 +21,7 @@ import { rename } from 'fs'; import { delay } from 'lodash'; export function renamePlugin(workingPath, finalPath) { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { const start = Date.now(); const retryTime = 3000; const retryDelay = 100; diff --git a/src/cli_plugin/install/rename.test.js b/src/cli_plugin/install/rename.test.js index c725a1218cbd2..40df75adc5efa 100644 --- a/src/cli_plugin/install/rename.test.js +++ b/src/cli_plugin/install/rename.test.js @@ -22,63 +22,63 @@ import fs from 'fs'; import { renamePlugin } from './rename'; -describe('plugin folder rename', function() { +describe('plugin folder rename', function () { let renameStub; - beforeEach(function() { + beforeEach(function () { renameStub = sinon.stub(); }); - afterEach(function() { + afterEach(function () { fs.rename.restore(); }); - it('should rethrow any exceptions', function() { + it('should rethrow any exceptions', function () { renameStub = sinon.stub(fs, 'rename').callsFake((from, to, cb) => { cb({ code: 'error', }); }); - return renamePlugin('/foo/bar', '/bar/foo').catch(function(err) { + return renamePlugin('/foo/bar', '/bar/foo').catch(function (err) { expect(err.code).toBe('error'); expect(renameStub.callCount).toBe(1); }); }); - it('should resolve if there are no errors', function() { + it('should resolve if there are no errors', function () { renameStub = sinon.stub(fs, 'rename').callsFake((from, to, cb) => { cb(); }); return renamePlugin('/foo/bar', '/bar/foo') - .then(function() { + .then(function () { expect(renameStub.callCount).toBe(1); }) - .catch(function() { + .catch(function () { throw new Error("We shouldn't have any errors"); }); }); - describe('Windows', function() { + describe('Windows', function () { let platform; - beforeEach(function() { + beforeEach(function () { platform = Object.getOwnPropertyDescriptor(process, 'platform'); Object.defineProperty(process, 'platform', { value: 'win32', }); }); - afterEach(function() { + afterEach(function () { Object.defineProperty(process, 'platform', platform); }); - it('should retry on Windows EPERM errors for up to 3 seconds', function() { + it('should retry on Windows EPERM errors for up to 3 seconds', function () { renameStub = sinon.stub(fs, 'rename').callsFake((from, to, cb) => { cb({ code: 'EPERM', }); }); - return renamePlugin('/foo/bar', '/bar/foo').catch(function(err) { + return renamePlugin('/foo/bar', '/bar/foo').catch(function (err) { expect(err.code).toBe('EPERM'); expect(renameStub.callCount).toBeGreaterThan(1); }); diff --git a/src/cli_plugin/install/settings.js b/src/cli_plugin/install/settings.js index 1f924caddf1b7..40c845fc37a9e 100644 --- a/src/cli_plugin/install/settings.js +++ b/src/cli_plugin/install/settings.js @@ -56,7 +56,7 @@ export function parse(command, options, kbnPackage) { settings.workingPath = resolve(settings.pluginDir, '.plugin.installing'); settings.tempArchiveFile = resolve(settings.workingPath, 'archive.part'); settings.tempPackageFile = resolve(settings.workingPath, 'package.json'); - settings.setPlugin = function(plugin) { + settings.setPlugin = function (plugin) { settings.plugin = plugin; settings.pluginPath = resolve(settings.pluginDir, settings.plugin.name); }; diff --git a/src/cli_plugin/install/settings.test.js b/src/cli_plugin/install/settings.test.js index 1f0aef4377b40..39ca07405ade2 100644 --- a/src/cli_plugin/install/settings.test.js +++ b/src/cli_plugin/install/settings.test.js @@ -21,23 +21,23 @@ import { fromRoot } from '../../core/server/utils'; import { resolve } from 'path'; import { parseMilliseconds, parse } from './settings'; -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('command line option parsing', function() { - describe('parseMilliseconds function', function() { - it('should return 0 for an empty string', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('command line option parsing', function () { + describe('parseMilliseconds function', function () { + it('should return 0 for an empty string', function () { const value = ''; const result = parseMilliseconds(value); expect(result).toBe(0); }); - it('should return 0 for a number with an invalid unit of measure', function() { + it('should return 0 for a number with an invalid unit of measure', function () { const result = parseMilliseconds('1gigablasts'); expect(result).toBe(0); }); - it('should assume a number with no unit of measure is specified as milliseconds', function() { + it('should assume a number with no unit of measure is specified as milliseconds', function () { const result = parseMilliseconds(1); expect(result).toBe(1); @@ -45,53 +45,53 @@ describe('kibana cli', function() { expect(result2).toBe(1); }); - it('should interpret a number with "s" as the unit of measure as seconds', function() { + it('should interpret a number with "s" as the unit of measure as seconds', function () { const result = parseMilliseconds('5s'); expect(result).toBe(5 * 1000); }); - it('should interpret a number with "second" as the unit of measure as seconds', function() { + it('should interpret a number with "second" as the unit of measure as seconds', function () { const result = parseMilliseconds('5second'); expect(result).toBe(5 * 1000); }); - it('should interpret a number with "seconds" as the unit of measure as seconds', function() { + it('should interpret a number with "seconds" as the unit of measure as seconds', function () { const result = parseMilliseconds('5seconds'); expect(result).toBe(5 * 1000); }); - it('should interpret a number with "m" as the unit of measure as minutes', function() { + it('should interpret a number with "m" as the unit of measure as minutes', function () { const result = parseMilliseconds('9m'); expect(result).toBe(9 * 1000 * 60); }); - it('should interpret a number with "minute" as the unit of measure as minutes', function() { + it('should interpret a number with "minute" as the unit of measure as minutes', function () { const result = parseMilliseconds('9minute'); expect(result).toBe(9 * 1000 * 60); }); - it('should interpret a number with "minutes" as the unit of measure as minutes', function() { + it('should interpret a number with "minutes" as the unit of measure as minutes', function () { const result = parseMilliseconds('9minutes'); expect(result).toBe(9 * 1000 * 60); }); }); - describe('parse function', function() { + describe('parse function', function () { const command = 'plugin name'; let options = {}; const kbnPackage = { version: 1234 }; - beforeEach(function() { + beforeEach(function () { options = { pluginDir: fromRoot('plugins') }; }); - describe('timeout option', function() { - it('should default to 0 (milliseconds)', function() { + describe('timeout option', function () { + it('should default to 0 (milliseconds)', function () { const settings = parse(command, options, kbnPackage); expect(settings.timeout).toBe(0); }); - it('should set settings.timeout property', function() { + it('should set settings.timeout property', function () { options.timeout = 1234; const settings = parse(command, options, kbnPackage); @@ -99,14 +99,14 @@ describe('kibana cli', function() { }); }); - describe('quiet option', function() { - it('should default to false', function() { + describe('quiet option', function () { + it('should default to false', function () { const settings = parse(command, options, kbnPackage); expect(settings.quiet).toBe(false); }); - it('should set settings.quiet property to true', function() { + it('should set settings.quiet property to true', function () { options.quiet = true; const settings = parse(command, options, kbnPackage); @@ -114,14 +114,14 @@ describe('kibana cli', function() { }); }); - describe('silent option', function() { - it('should default to false', function() { + describe('silent option', function () { + it('should default to false', function () { const settings = parse(command, options, kbnPackage); expect(settings.silent).toBe(false); }); - it('should set settings.silent property to true', function() { + it('should set settings.silent property to true', function () { options.silent = true; const settings = parse(command, options, kbnPackage); @@ -129,14 +129,14 @@ describe('kibana cli', function() { }); }); - describe('config option', function() { - it('should default to ZLS', function() { + describe('config option', function () { + it('should default to ZLS', function () { const settings = parse(command, options, kbnPackage); expect(settings.config).toBe(''); }); - it('should set settings.config property', function() { + it('should set settings.config property', function () { options.config = 'foo bar baz'; const settings = parse(command, options, kbnPackage); @@ -144,14 +144,14 @@ describe('kibana cli', function() { }); }); - describe('pluginDir option', function() { - it('should default to plugins', function() { + describe('pluginDir option', function () { + it('should default to plugins', function () { const settings = parse(command, options, kbnPackage); expect(settings.pluginDir).toBe(fromRoot('plugins')); }); - it('should set settings.config property', function() { + it('should set settings.config property', function () { options.pluginDir = 'foo bar baz'; const settings = parse(command, options, kbnPackage); @@ -159,16 +159,16 @@ describe('kibana cli', function() { }); }); - describe('command value', function() { - it('should set settings.plugin property', function() { + describe('command value', function () { + it('should set settings.plugin property', function () { const settings = parse(command, options, kbnPackage); expect(settings.plugin).toBe(command); }); }); - describe('urls collection', function() { - it('should populate the settings.urls property', function() { + describe('urls collection', function () { + it('should populate the settings.urls property', function () { const settings = parse(command, options, kbnPackage); const expected = [ @@ -180,8 +180,8 @@ describe('kibana cli', function() { }); }); - describe('workingPath value', function() { - it('should set settings.workingPath property', function() { + describe('workingPath value', function () { + it('should set settings.workingPath property', function () { options.pluginDir = 'foo/bar/baz'; const settings = parse(command, options, kbnPackage); const expected = resolve('foo/bar/baz', '.plugin.installing'); @@ -190,8 +190,8 @@ describe('kibana cli', function() { }); }); - describe('tempArchiveFile value', function() { - it('should set settings.tempArchiveFile property', function() { + describe('tempArchiveFile value', function () { + it('should set settings.tempArchiveFile property', function () { options.pluginDir = 'foo/bar/baz'; const settings = parse(command, options, kbnPackage); const expected = resolve('foo/bar/baz', '.plugin.installing', 'archive.part'); @@ -200,8 +200,8 @@ describe('kibana cli', function() { }); }); - describe('tempPackageFile value', function() { - it('should set settings.tempPackageFile property', function() { + describe('tempPackageFile value', function () { + it('should set settings.tempPackageFile property', function () { options.pluginDir = 'foo/bar/baz'; const settings = parse(command, options, kbnPackage); const expected = resolve('foo/bar/baz', '.plugin.installing', 'package.json'); diff --git a/src/cli_plugin/install/zip.js b/src/cli_plugin/install/zip.js index 03e6edb63b4ff..52eba2ea239a2 100644 --- a/src/cli_plugin/install/zip.js +++ b/src/cli_plugin/install/zip.js @@ -34,29 +34,29 @@ export function analyzeArchive(archive) { const regExp = new RegExp('(kibana[\\\\/][^\\\\/]+)[\\\\/]package.json', 'i'); return new Promise((resolve, reject) => { - yauzl.open(archive, { lazyEntries: true }, function(err, zipfile) { + yauzl.open(archive, { lazyEntries: true }, function (err, zipfile) { if (err) { return reject(err); } zipfile.readEntry(); - zipfile.on('entry', function(entry) { + zipfile.on('entry', function (entry) { const match = entry.fileName.match(regExp); if (!match) { return zipfile.readEntry(); } - zipfile.openReadStream(entry, function(err, readable) { + zipfile.openReadStream(entry, function (err, readable) { const chunks = []; if (err) { return reject(err); } - readable.on('data', chunk => chunks.push(chunk)); + readable.on('data', (chunk) => chunks.push(chunk)); - readable.on('end', function() { + readable.on('end', function () { const contents = Buffer.concat(chunks).toString(); const pkg = JSON.parse(contents); @@ -92,14 +92,14 @@ export function _isDirectory(filename) { export function extractArchive(archive, targetDir, extractPath) { return new Promise((resolve, reject) => { - yauzl.open(archive, { lazyEntries: true }, function(err, zipfile) { + yauzl.open(archive, { lazyEntries: true }, function (err, zipfile) { if (err) { return reject(err); } zipfile.readEntry(); zipfile.on('close', resolve); - zipfile.on('entry', function(entry) { + zipfile.on('entry', function (entry) { let fileName = entry.fileName; if (extractPath && fileName.startsWith(extractPath)) { @@ -113,7 +113,7 @@ export function extractArchive(archive, targetDir, extractPath) { } if (_isDirectory(fileName)) { - mkdir(fileName, { recursive: true }, function(err) { + mkdir(fileName, { recursive: true }, function (err) { if (err) { return reject(err); } @@ -122,13 +122,13 @@ export function extractArchive(archive, targetDir, extractPath) { }); } else { // file entry - zipfile.openReadStream(entry, function(err, readStream) { + zipfile.openReadStream(entry, function (err, readStream) { if (err) { return reject(err); } // ensure parent directory exists - mkdir(path.dirname(fileName), { recursive: true }, function(err) { + mkdir(path.dirname(fileName), { recursive: true }, function (err) { if (err) { return reject(err); } @@ -136,7 +136,7 @@ export function extractArchive(archive, targetDir, extractPath) { readStream.pipe( createWriteStream(fileName, { mode: entry.externalFileAttributes >>> 16 }) ); - readStream.on('end', function() { + readStream.on('end', function () { zipfile.readEntry(); }); }); diff --git a/src/cli_plugin/install/zip.test.js b/src/cli_plugin/install/zip.test.js index 8f75367ec8eb4..28367e9e24453 100644 --- a/src/cli_plugin/install/zip.test.js +++ b/src/cli_plugin/install/zip.test.js @@ -24,8 +24,8 @@ import glob from 'glob'; import fs from 'fs'; import { analyzeArchive, extractArchive, _isDirectory } from './zip'; -describe('kibana cli', function() { - describe('zip', function() { +describe('kibana cli', function () { + describe('zip', function () { const repliesPath = path.resolve(__dirname, '__fixtures__', 'replies'); const archivePath = path.resolve(repliesPath, 'test_plugin.zip'); @@ -40,7 +40,7 @@ describe('kibana cli', function() { del.sync(tempPath, { force: true }); }); - describe('analyzeArchive', function() { + describe('analyzeArchive', function () { it('returns array of plugins', async () => { const packages = await analyzeArchive(archivePath); const plugin = packages[0]; diff --git a/src/cli_plugin/lib/log_warnings.js b/src/cli_plugin/lib/log_warnings.js index 3adf0ba849c23..b4542acecb305 100644 --- a/src/cli_plugin/lib/log_warnings.js +++ b/src/cli_plugin/lib/log_warnings.js @@ -17,8 +17,8 @@ * under the License. */ -export default function(settings, logger) { - process.on('warning', warning => { +export default function (settings, logger) { + process.on('warning', (warning) => { // deprecation warnings do no reflect a current problem for // the user and therefor should be filtered out. if (warning.name === 'DeprecationWarning') { diff --git a/src/cli_plugin/lib/logger.test.js b/src/cli_plugin/lib/logger.test.js index db8454f465b47..00cad1a9bbb11 100644 --- a/src/cli_plugin/lib/logger.test.js +++ b/src/cli_plugin/lib/logger.test.js @@ -20,21 +20,21 @@ import sinon from 'sinon'; import Logger from './logger'; -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('logger', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('logger', function () { let logger; - describe('logger.log', function() { - beforeEach(function() { + describe('logger.log', function () { + beforeEach(function () { sinon.stub(process.stdout, 'write'); }); - afterEach(function() { + afterEach(function () { process.stdout.write.restore(); }); - it('should log messages to the console and append a new line', function() { + it('should log messages to the console and append a new line', function () { logger = new Logger({ silent: false, quiet: false }); const message = 'this is my message'; @@ -45,7 +45,7 @@ describe('kibana cli', function() { expect(process.stdout.write.getCall(callCount - 1).args[0]).toBe('\n'); }); - it('should log messages to the console and append not append a new line', function() { + it('should log messages to the console and append not append a new line', function () { logger = new Logger({ silent: false, quiet: false }); for (let i = 0; i < 10; i++) { logger.log('.', true); @@ -68,7 +68,7 @@ describe('kibana cli', function() { expect(process.stdout.write.getCall(12).args[0]).toBe('\n'); }); - it('should not log any messages when quiet is set', function() { + it('should not log any messages when quiet is set', function () { logger = new Logger({ silent: false, quiet: true }); const message = 'this is my message'; @@ -82,7 +82,7 @@ describe('kibana cli', function() { expect(process.stdout.write.callCount).toBe(0); }); - it('should not log any messages when silent is set', function() { + it('should not log any messages when silent is set', function () { logger = new Logger({ silent: true, quiet: false }); const message = 'this is my message'; @@ -97,16 +97,16 @@ describe('kibana cli', function() { }); }); - describe('logger.error', function() { - beforeEach(function() { + describe('logger.error', function () { + beforeEach(function () { sinon.stub(process.stderr, 'write'); }); - afterEach(function() { + afterEach(function () { process.stderr.write.restore(); }); - it('should log error messages to the console and append a new line', function() { + it('should log error messages to the console and append a new line', function () { logger = new Logger({ silent: false, quiet: false }); const message = 'this is my error'; @@ -114,7 +114,7 @@ describe('kibana cli', function() { expect(process.stderr.write.calledWith(message + '\n')).toBe(true); }); - it('should log error messages to the console when quiet is set', function() { + it('should log error messages to the console when quiet is set', function () { logger = new Logger({ silent: false, quiet: true }); const message = 'this is my error'; @@ -122,7 +122,7 @@ describe('kibana cli', function() { expect(process.stderr.write.calledWith(message + '\n')).toBe(true); }); - it('should not log any error messages when silent is set', function() { + it('should not log any error messages when silent is set', function () { logger = new Logger({ silent: true, quiet: false }); const message = 'this is my error'; diff --git a/src/cli_plugin/list/list.js b/src/cli_plugin/list/list.js index d53e868b32e36..b34631e5dfd08 100644 --- a/src/cli_plugin/list/list.js +++ b/src/cli_plugin/list/list.js @@ -21,7 +21,7 @@ import { statSync, readdirSync, readFileSync } from 'fs'; import { join } from 'path'; export default function list(settings, logger) { - readdirSync(settings.pluginDir).forEach(filename => { + readdirSync(settings.pluginDir).forEach((filename) => { const stat = statSync(join(settings.pluginDir, filename)); if (stat.isDirectory() && filename[0] !== '.') { diff --git a/src/cli_plugin/list/list.test.js b/src/cli_plugin/list/list.test.js index c6480ca52b59a..071a253fa87fe 100644 --- a/src/cli_plugin/list/list.test.js +++ b/src/cli_plugin/list/list.test.js @@ -30,8 +30,8 @@ function createPlugin(name, version, pluginBaseDir) { appendFileSync(join(pluginDir, 'package.json'), '{"version": "' + version + '"}'); } -describe('kibana cli', function() { - describe('plugin lister', function() { +describe('kibana cli', function () { + describe('plugin lister', function () { const pluginDir = join(__dirname, '.test.data.list'); let logger; @@ -39,7 +39,7 @@ describe('kibana cli', function() { pluginDir: pluginDir, }; - beforeEach(function() { + beforeEach(function () { logger = new Logger(settings); sinon.stub(logger, 'log'); sinon.stub(logger, 'error'); @@ -47,13 +47,13 @@ describe('kibana cli', function() { mkdirSync(pluginDir, { recursive: true }); }); - afterEach(function() { + afterEach(function () { logger.log.restore(); logger.error.restore(); del.sync(pluginDir); }); - it('list all of the folders in the plugin folder', function() { + it('list all of the folders in the plugin folder', function () { createPlugin('plugin1', '5.0.0-alpha2', pluginDir); createPlugin('plugin2', '3.2.1', pluginDir); createPlugin('plugin3', '1.2.3', pluginDir); @@ -65,7 +65,7 @@ describe('kibana cli', function() { expect(logger.log.calledWith('plugin3@1.2.3')).toBe(true); }); - it('ignore folders that start with a period', function() { + it('ignore folders that start with a period', function () { createPlugin('.foo', '1.0.0', pluginDir); createPlugin('plugin1', '5.0.0-alpha2', pluginDir); createPlugin('plugin2', '3.2.1', pluginDir); @@ -78,7 +78,7 @@ describe('kibana cli', function() { expect(logger.log.calledWith('.bar@1.0.0')).toBe(false); }); - it('list should only list folders', function() { + it('list should only list folders', function () { createPlugin('plugin1', '1.0.0', pluginDir); createPlugin('plugin2', '1.0.0', pluginDir); createPlugin('plugin3', '1.0.0', pluginDir); @@ -91,22 +91,22 @@ describe('kibana cli', function() { expect(logger.log.calledWith('plugin3@1.0.0')).toBe(true); }); - it('list should throw an exception if a plugin does not have a package.json', function() { + it('list should throw an exception if a plugin does not have a package.json', function () { createPlugin('plugin1', '1.0.0', pluginDir); mkdirSync(join(pluginDir, 'empty-plugin'), { recursive: true }); - expect(function() { + expect(function () { list(settings, logger); }).toThrowError('Unable to read package.json file for plugin empty-plugin'); }); - it('list should throw an exception if a plugin have an empty package.json', function() { + it('list should throw an exception if a plugin have an empty package.json', function () { createPlugin('plugin1', '1.0.0', pluginDir); const invalidPluginDir = join(pluginDir, 'invalid-plugin'); mkdirSync(invalidPluginDir, { recursive: true }); appendFileSync(join(invalidPluginDir, 'package.json'), ''); - expect(function() { + expect(function () { list(settings, logger); }).toThrowError('Unable to read package.json file for plugin invalid-plugin'); }); diff --git a/src/cli_plugin/list/settings.test.js b/src/cli_plugin/list/settings.test.js index 144b5d8661527..85e6cb88e82fd 100644 --- a/src/cli_plugin/list/settings.test.js +++ b/src/cli_plugin/list/settings.test.js @@ -20,24 +20,24 @@ import { fromRoot } from '../../core/server/utils'; import { parse } from './settings'; -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('command line option parsing', function() { - describe('parse function', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('command line option parsing', function () { + describe('parse function', function () { let command; const options = {}; - beforeEach(function() { + beforeEach(function () { command = { pluginDir: fromRoot('plugins') }; }); - describe('pluginDir option', function() { - it('should default to plugins', function() { + describe('pluginDir option', function () { + it('should default to plugins', function () { const settings = parse(command, options); expect(settings.pluginDir).toBe(fromRoot('plugins')); }); - it('should set settings.config property', function() { + it('should set settings.config property', function () { command.pluginDir = 'foo bar baz'; const settings = parse(command, options); diff --git a/src/cli_plugin/remove/remove.test.js b/src/cli_plugin/remove/remove.test.js index 032a17abe209e..4bf061820aa05 100644 --- a/src/cli_plugin/remove/remove.test.js +++ b/src/cli_plugin/remove/remove.test.js @@ -25,15 +25,15 @@ import remove from './remove'; import { join } from 'path'; import { writeFileSync, existsSync, mkdirSync } from 'fs'; -describe('kibana cli', function() { - describe('plugin remover', function() { +describe('kibana cli', function () { + describe('plugin remover', function () { const pluginDir = join(__dirname, '.test.data.remove'); let processExitStub; let logger; const settings = { pluginDir }; - beforeEach(function() { + beforeEach(function () { processExitStub = sinon.stub(process, 'exit'); logger = new Logger(settings); sinon.stub(logger, 'log'); @@ -42,14 +42,14 @@ describe('kibana cli', function() { mkdirSync(pluginDir, { recursive: true }); }); - afterEach(function() { + afterEach(function () { processExitStub.restore(); logger.log.restore(); logger.error.restore(); del.sync(pluginDir); }); - it('throw an error if the plugin is not installed.', function() { + it('throw an error if the plugin is not installed.', function () { settings.pluginPath = join(pluginDir, 'foo'); settings.plugin = 'foo'; @@ -58,7 +58,7 @@ describe('kibana cli', function() { expect(process.exit.called).toBe(true); }); - it('throw an error if the specified plugin is not a folder.', function() { + it('throw an error if the specified plugin is not a folder.', function () { writeFileSync(join(pluginDir, 'foo'), 'This is a file, and not a folder.'); remove(settings, logger); @@ -85,7 +85,7 @@ describe('kibana cli', function() { ); }); - it('delete the specified folder.', function() { + it('delete the specified folder.', function () { settings.pluginPath = join(pluginDir, 'foo'); mkdirSync(join(pluginDir, 'foo'), { recursive: true }); mkdirSync(join(pluginDir, 'bar'), { recursive: true }); diff --git a/src/cli_plugin/remove/settings.test.js b/src/cli_plugin/remove/settings.test.js index 5bb4b30cfff09..b3110e1ff0499 100644 --- a/src/cli_plugin/remove/settings.test.js +++ b/src/cli_plugin/remove/settings.test.js @@ -20,25 +20,25 @@ import { fromRoot } from '../../core/server/utils'; import { parse } from './settings'; -describe('kibana cli', function() { - describe('plugin installer', function() { - describe('command line option parsing', function() { - describe('parse function', function() { +describe('kibana cli', function () { + describe('plugin installer', function () { + describe('command line option parsing', function () { + describe('parse function', function () { const command = 'plugin name'; let options = {}; const kbnPackage = { version: 1234 }; - beforeEach(function() { + beforeEach(function () { options = { pluginDir: fromRoot('plugins') }; }); - describe('quiet option', function() { - it('should default to false', function() { + describe('quiet option', function () { + it('should default to false', function () { const settings = parse(command, options, kbnPackage); expect(settings.quiet).toBe(false); }); - it('should set settings.quiet property to true', function() { + it('should set settings.quiet property to true', function () { options.quiet = true; const settings = parse(command, options, kbnPackage); @@ -46,14 +46,14 @@ describe('kibana cli', function() { }); }); - describe('silent option', function() { - it('should default to false', function() { + describe('silent option', function () { + it('should default to false', function () { const settings = parse(command, options, kbnPackage); expect(settings.silent).toBe(false); }); - it('should set settings.silent property to true', function() { + it('should set settings.silent property to true', function () { options.silent = true; const settings = parse(command, options, kbnPackage); @@ -61,14 +61,14 @@ describe('kibana cli', function() { }); }); - describe('config option', function() { - it('should default to ZLS', function() { + describe('config option', function () { + it('should default to ZLS', function () { const settings = parse(command, options, kbnPackage); expect(settings.config).toBe(''); }); - it('should set settings.config property', function() { + it('should set settings.config property', function () { options.config = 'foo bar baz'; const settings = parse(command, options, kbnPackage); @@ -76,14 +76,14 @@ describe('kibana cli', function() { }); }); - describe('pluginDir option', function() { - it('should default to plugins', function() { + describe('pluginDir option', function () { + it('should default to plugins', function () { const settings = parse(command, options, kbnPackage); expect(settings.pluginDir).toBe(fromRoot('plugins')); }); - it('should set settings.config property', function() { + it('should set settings.config property', function () { options.pluginDir = 'foo bar baz'; const settings = parse(command, options, kbnPackage); @@ -91,8 +91,8 @@ describe('kibana cli', function() { }); }); - describe('command value', function() { - it('should set settings.plugin property', function() { + describe('command value', function () { + it('should set settings.plugin property', function () { const settings = parse(command, options, kbnPackage); expect(settings.plugin).toBe(command); diff --git a/src/core/public/application/application_leave.test.ts b/src/core/public/application/application_leave.test.ts index e06183d8bb8d9..b560bbc0cbc25 100644 --- a/src/core/public/application/application_leave.test.ts +++ b/src/core/public/application/application_leave.test.ts @@ -31,16 +31,16 @@ describe('isConfirmAction', () => { describe('getLeaveAction', () => { it('returns the default action provided by the handler', () => { - expect(getLeaveAction(actions => actions.default())).toEqual({ + expect(getLeaveAction((actions) => actions.default())).toEqual({ type: AppLeaveActionType.default, }); }); it('returns the confirm action provided by the handler', () => { - expect(getLeaveAction(actions => actions.confirm('some message'))).toEqual({ + expect(getLeaveAction((actions) => actions.confirm('some message'))).toEqual({ type: AppLeaveActionType.confirm, text: 'some message', }); - expect(getLeaveAction(actions => actions.confirm('another message', 'a title'))).toEqual({ + expect(getLeaveAction((actions) => actions.confirm('another message', 'a title'))).toEqual({ type: AppLeaveActionType.confirm, text: 'another message', title: 'a title', diff --git a/src/core/public/application/application_service.mock.ts b/src/core/public/application/application_service.mock.ts index d2a827d381be5..24c0e66359afa 100644 --- a/src/core/public/application/application_service.mock.ts +++ b/src/core/public/application/application_service.mock.ts @@ -50,6 +50,7 @@ const createStartContractMock = (): jest.Mocked => { currentAppId$: currentAppId$.asObservable(), capabilities: capabilitiesServiceMock.createStartContract().capabilities, navigateToApp: jest.fn(), + navigateToUrl: jest.fn(), getUrlForApp: jest.fn(), registerMountContext: jest.fn(), }; @@ -64,7 +65,8 @@ const createInternalStartContractMock = (): jest.Mocked currentAppId$.next(appId)), + navigateToApp: jest.fn().mockImplementation((appId) => currentAppId$.next(appId)), + navigateToUrl: jest.fn(), registerMountContext: jest.fn(), }; }; diff --git a/src/core/public/application/application_service.test.mocks.ts b/src/core/public/application/application_service.test.mocks.ts index d829cf18e56be..a096f05209708 100644 --- a/src/core/public/application/application_service.test.mocks.ts +++ b/src/core/public/application/application_service.test.mocks.ts @@ -34,3 +34,9 @@ export const createBrowserHistoryMock = jest.fn().mockReturnValue(MockHistory); jest.doMock('history', () => ({ createBrowserHistory: createBrowserHistoryMock, })); + +export const parseAppUrlMock = jest.fn(); +jest.doMock('./utils', () => ({ + ...jest.requireActual('./utils'), + parseAppUrl: parseAppUrlMock, +})); diff --git a/src/core/public/application/application_service.test.ts b/src/core/public/application/application_service.test.ts index 04ff844ffc150..b65a8581e5b58 100644 --- a/src/core/public/application/application_service.test.ts +++ b/src/core/public/application/application_service.test.ts @@ -17,6 +17,12 @@ * under the License. */ +import { + MockCapabilitiesService, + MockHistory, + parseAppUrlMock, +} from './application_service.test.mocks'; + import { createElement } from 'react'; import { BehaviorSubject, Subject } from 'rxjs'; import { bufferCount, take, takeUntil } from 'rxjs/operators'; @@ -26,7 +32,6 @@ import { injectedMetadataServiceMock } from '../injected_metadata/injected_metad import { contextServiceMock } from '../context/context_service.mock'; import { httpServiceMock } from '../http/http_service.mock'; import { overlayServiceMock } from '../overlays/overlay_service.mock'; -import { MockCapabilitiesService, MockHistory } from './application_service.test.mocks'; import { MockLifecycle } from './test_types'; import { ApplicationService } from './application_service'; import { App, AppNavLinkStatus, AppStatus, AppUpdater, LegacyApp } from './types'; @@ -61,6 +66,7 @@ describe('#setup()', () => { http, context: contextServiceMock.createSetupContract(), injectedMetadata: injectedMetadataServiceMock.createSetupContract(), + redirectTo: jest.fn(), }; setupDeps.injectedMetadata.getLegacyMode.mockReturnValue(false); startDeps = { http, overlays: overlayServiceMock.createStartContract() }; @@ -92,7 +98,7 @@ describe('#setup()', () => { const setup = service.setup(setupDeps); const pluginId = Symbol('plugin'); - const updater$ = new BehaviorSubject(app => ({})); + const updater$ = new BehaviorSubject((app) => ({})); setup.register(pluginId, createApp({ id: 'app1', updater$ })); setup.register(pluginId, createApp({ id: 'app2' })); const { applications$ } = await service.start(startDeps); @@ -116,7 +122,7 @@ describe('#setup()', () => { }) ); - updater$.next(app => ({ + updater$.next((app) => ({ status: AppStatus.inaccessible, tooltip: 'App inaccessible due to reason', defaultPath: 'foo/bar', @@ -174,6 +180,10 @@ describe('#setup()', () => { ).toThrowErrorMatchingInlineSnapshot( `"Cannot register an application route that includes HTTP base path"` ); + + expect(() => + register(Symbol(), createApp({ id: 'app3', appRoute: '/base-path-i-am-not' })) + ).not.toThrow(); }); }); @@ -220,7 +230,7 @@ describe('#setup()', () => { setup.register(pluginId, createApp({ id: 'app1' })); setup.register(pluginId, createApp({ id: 'app2' })); setup.registerAppUpdater( - new BehaviorSubject(app => { + new BehaviorSubject((app) => { if (app.id === 'app1') { return { status: AppStatus.inaccessible, @@ -260,7 +270,7 @@ describe('#setup()', () => { it(`properly combine with application's updater$`, async () => { const setup = service.setup(setupDeps); const pluginId = Symbol('plugin'); - const appStatusUpdater$ = new BehaviorSubject(app => ({ + const appStatusUpdater$ = new BehaviorSubject((app) => ({ status: AppStatus.inaccessible, navLinkStatus: AppNavLinkStatus.disabled, })); @@ -268,7 +278,7 @@ describe('#setup()', () => { setup.register(pluginId, createApp({ id: 'app2' })); setup.registerAppUpdater( - new BehaviorSubject(app => { + new BehaviorSubject((app) => { if (app.id === 'app1') { return { status: AppStatus.accessible, @@ -311,7 +321,7 @@ describe('#setup()', () => { const pluginId = Symbol('plugin'); setup.register(pluginId, createApp({ id: 'app1' })); setup.registerAppUpdater( - new BehaviorSubject(app => { + new BehaviorSubject((app) => { return { status: AppStatus.inaccessible, navLinkStatus: AppNavLinkStatus.disabled, @@ -319,7 +329,7 @@ describe('#setup()', () => { }) ); setup.registerAppUpdater( - new BehaviorSubject(app => { + new BehaviorSubject((app) => { return { status: AppStatus.accessible, navLinkStatus: AppNavLinkStatus.default, @@ -347,7 +357,7 @@ describe('#setup()', () => { const pluginId = Symbol('plugin'); setup.register(pluginId, createApp({ id: 'app1' })); - const statusUpdater = new BehaviorSubject(app => { + const statusUpdater = new BehaviorSubject((app) => { return { status: AppStatus.inaccessible, navLinkStatus: AppNavLinkStatus.disabled, @@ -357,7 +367,7 @@ describe('#setup()', () => { const start = await service.start(startDeps); let latestValue: ReadonlyMap = new Map(); - start.applications$.subscribe(apps => { + start.applications$.subscribe((apps) => { latestValue = apps; }); @@ -370,7 +380,7 @@ describe('#setup()', () => { }) ); - statusUpdater.next(app => { + statusUpdater.next((app) => { return { status: AppStatus.accessible, navLinkStatus: AppNavLinkStatus.hidden, @@ -393,7 +403,7 @@ describe('#setup()', () => { setup.registerLegacyApp(createLegacyApp({ id: 'app1' })); setup.registerAppUpdater( - new BehaviorSubject(app => { + new BehaviorSubject((app) => { return { status: AppStatus.inaccessible, navLinkStatus: AppNavLinkStatus.hidden, @@ -423,7 +433,7 @@ describe('#setup()', () => { const pluginId = Symbol('plugin'); setup.register(pluginId, createApp({ id: 'app1' })); - const updater = new BehaviorSubject(app => ({})); + const updater = new BehaviorSubject((app) => ({})); setup.registerAppUpdater(updater); const start = await service.start(startDeps); @@ -431,17 +441,17 @@ describe('#setup()', () => { expect(MockHistory.push).toHaveBeenCalledWith('/app/app1', undefined); MockHistory.push.mockClear(); - updater.next(app => ({ defaultPath: 'default-path' })); + updater.next((app) => ({ defaultPath: 'default-path' })); await start.navigateToApp('app1'); expect(MockHistory.push).toHaveBeenCalledWith('/app/app1/default-path', undefined); MockHistory.push.mockClear(); - updater.next(app => ({ defaultPath: 'another-path' })); + updater.next((app) => ({ defaultPath: 'another-path' })); await start.navigateToApp('app1'); expect(MockHistory.push).toHaveBeenCalledWith('/app/app1/another-path', undefined); MockHistory.push.mockClear(); - updater.next(app => ({})); + updater.next((app) => ({})); await start.navigateToApp('app1'); expect(MockHistory.push).toHaveBeenCalledWith('/app/app1', undefined); MockHistory.push.mockClear(); @@ -462,12 +472,14 @@ describe('#setup()', () => { describe('#start()', () => { beforeEach(() => { MockHistory.push.mockReset(); + parseAppUrlMock.mockReset(); const http = httpServiceMock.createSetupContract({ basePath: '/base-path' }); setupDeps = { http, context: contextServiceMock.createSetupContract(), injectedMetadata: injectedMetadataServiceMock.createSetupContract(), + redirectTo: jest.fn(), }; setupDeps.injectedMetadata.getLegacyMode.mockReturnValue(false); startDeps = { http, overlays: overlayServiceMock.createStartContract() }; @@ -775,7 +787,6 @@ describe('#start()', () => { }); it('redirects when in legacyMode', async () => { - setupDeps.redirectTo = jest.fn(); setupDeps.injectedMetadata.getLegacyMode.mockReturnValue(true); service.setup(setupDeps); @@ -816,11 +827,11 @@ describe('#start()', () => { const history = createMemoryHistory(); setupDeps.history = history; - const flushPromises = () => new Promise(resolve => setImmediate(resolve)); + const flushPromises = () => new Promise((resolve) => setImmediate(resolve)); // Create an app and a promise that allows us to control when the app completes mounting const createWaitingApp = (props: Partial): [App, () => void] => { let finishMount: () => void; - const mountPromise = new Promise(resolve => (finishMount = resolve)); + const mountPromise = new Promise((resolve) => (finishMount = resolve)); const app = { id: 'some-id', title: 'some-title', @@ -881,7 +892,6 @@ describe('#start()', () => { it('sets window.location.href when navigating to legacy apps', async () => { setupDeps.http = httpServiceMock.createSetupContract({ basePath: '/test' }); setupDeps.injectedMetadata.getLegacyMode.mockReturnValue(true); - setupDeps.redirectTo = jest.fn(); service.setup(setupDeps); const { navigateToApp } = await service.start(startDeps); @@ -893,7 +903,6 @@ describe('#start()', () => { it('handles legacy apps with subapps', async () => { setupDeps.http = httpServiceMock.createSetupContract({ basePath: '/test' }); setupDeps.injectedMetadata.getLegacyMode.mockReturnValue(true); - setupDeps.redirectTo = jest.fn(); const { registerLegacyApp } = service.setup(setupDeps); @@ -905,6 +914,30 @@ describe('#start()', () => { expect(setupDeps.redirectTo).toHaveBeenCalledWith('/test/app/baseApp'); }); }); + + describe('navigateToUrl', () => { + it('calls `redirectTo` when the url is not parseable', async () => { + parseAppUrlMock.mockReturnValue(undefined); + service.setup(setupDeps); + const { navigateToUrl } = await service.start(startDeps); + + await navigateToUrl('/not-an-app-path'); + + expect(MockHistory.push).not.toHaveBeenCalled(); + expect(setupDeps.redirectTo).toHaveBeenCalledWith('/not-an-app-path'); + }); + + it('calls `navigateToApp` when the url is an internal app link', async () => { + parseAppUrlMock.mockReturnValue({ app: 'foo', path: '/some-path' }); + service.setup(setupDeps); + const { navigateToUrl } = await service.start(startDeps); + + await navigateToUrl('/an-app-path'); + + expect(MockHistory.push).toHaveBeenCalledWith('/app/foo/some-path', undefined); + expect(setupDeps.redirectTo).not.toHaveBeenCalled(); + }); + }); }); describe('#stop()', () => { diff --git a/src/core/public/application/application_service.tsx b/src/core/public/application/application_service.tsx index 6802c2363b9f8..b52b4984fb5e1 100644 --- a/src/core/public/application/application_service.tsx +++ b/src/core/public/application/application_service.tsx @@ -46,17 +46,14 @@ import { Mounter, } from './types'; import { getLeaveAction, isConfirmAction } from './application_leave'; -import { appendAppPath } from './utils'; +import { appendAppPath, parseAppUrl, relativeToAbsolute } from './utils'; interface SetupDeps { context: ContextSetup; http: HttpSetup; injectedMetadata: InjectedMetadataSetup; history?: History; - /** - * Only necessary for redirecting to legacy apps - * @deprecated - */ + /** Used to redirect to external urls (and legacy apps) */ redirectTo?: (path: string) => void; } @@ -109,6 +106,7 @@ export class ApplicationService { private history?: History; private mountContext?: IContextContainer; private navigate?: (url: string, state: any) => void; + private redirectTo?: (url: string) => void; public setup({ context, @@ -131,12 +129,12 @@ export class ApplicationService { this.navigate = (url, state) => // basePath not needed here because `history` is configured with basename this.history ? this.history.push(url, state) : redirectTo(basePath.prepend(url)); - + this.redirectTo = redirectTo; this.mountContext = context.createContextContainer(); const registerStatusUpdater = (application: string, updater$: Observable) => { const updaterId = Symbol(); - const subscription = updater$.subscribe(updater => { + const subscription = updater$.subscribe((updater) => { const nextValue = new Map(this.statusUpdaters$.getValue()); nextValue.set(updaterId, { application, @@ -160,7 +158,7 @@ export class ApplicationService { } else { handler = app.mount; } - return async params => { + return async (params) => { this.currentAppId$.next(app.id); return handler(params); }; @@ -179,7 +177,7 @@ export class ApplicationService { throw new Error( `An application is already registered with the appRoute "${app.appRoute}"` ); - } else if (basename && app.appRoute!.startsWith(basename)) { + } else if (basename && app.appRoute!.startsWith(`${basename}/`)) { throw new Error('Cannot register an application route that includes HTTP base path'); } @@ -201,14 +199,14 @@ export class ApplicationService { legacy: false, }); }, - registerLegacyApp: app => { + registerLegacyApp: (app) => { const appRoute = `/app/${app.id.split(':')[0]}`; if (this.registrationClosed) { throw new Error('Applications cannot be registered after "setup"'); } else if (this.apps.has(app.id)) { throw new Error(`An application is already registered with the id "${app.id}"`); - } else if (basename && appRoute!.startsWith(basename)) { + } else if (basename && appRoute!.startsWith(`${basename}/`)) { throw new Error('Cannot register an application route that includes HTTP base path'); } @@ -262,7 +260,7 @@ export class ApplicationService { const applications$ = new BehaviorSubject(availableApps); this.statusUpdaters$ .pipe( - map(statusUpdaters => { + map((statusUpdaters) => { return new Map( [...availableApps].map(([id, app]) => [ id, @@ -271,18 +269,32 @@ export class ApplicationService { ); }) ) - .subscribe(apps => applications$.next(apps)); + .subscribe((apps) => applications$.next(apps)); const applicationStatuses$ = applications$.pipe( - map(apps => new Map([...apps.entries()].map(([id, app]) => [id, app.status!]))), + map((apps) => new Map([...apps.entries()].map(([id, app]) => [id, app.status!]))), shareReplay(1) ); + const navigateToApp: InternalApplicationStart['navigateToApp'] = async ( + appId, + { path, state }: { path?: string; state?: any } = {} + ) => { + if (await this.shouldNavigate(overlays)) { + if (path === undefined) { + path = applications$.value.get(appId)?.defaultPath; + } + this.appLeaveHandlers.delete(this.currentAppId$.value!); + this.navigate!(getAppUrl(availableMounters, appId, path), state); + this.currentAppId$.next(appId); + } + }; + return { applications$, capabilities, currentAppId$: this.currentAppId$.pipe( - filter(appId => appId !== undefined), + filter((appId) => appId !== undefined), distinctUntilChanged(), takeUntil(this.stop$) ), @@ -294,14 +306,13 @@ export class ApplicationService { const relUrl = http.basePath.prepend(getAppUrl(availableMounters, appId, path)); return absolute ? relativeToAbsolute(relUrl) : relUrl; }, - navigateToApp: async (appId, { path, state }: { path?: string; state?: any } = {}) => { - if (await this.shouldNavigate(overlays)) { - if (path === undefined) { - path = applications$.value.get(appId)?.defaultPath; - } - this.appLeaveHandlers.delete(this.currentAppId$.value!); - this.navigate!(getAppUrl(availableMounters, appId, path), state); - this.currentAppId$.next(appId); + navigateToApp, + navigateToUrl: async (url) => { + const appInfo = parseAppUrl(url, http.basePath, this.apps); + if (appInfo) { + return navigateToApp(appInfo.app, { path: appInfo.path }); + } else { + return this.redirectTo!(url); } }, getComponent: () => { @@ -314,7 +325,7 @@ export class ApplicationService { mounters={availableMounters} appStatuses$={applicationStatuses$} setAppLeaveHandler={this.setAppLeaveHandler} - setIsMounting={isMounting => httpLoadingCount$.next(isMounting ? 1 : 0)} + setIsMounting={(isMounting) => httpLoadingCount$.next(isMounting ? 1 : 0)} /> ); }, @@ -360,14 +371,14 @@ export class ApplicationService { this.stop$.next(); this.currentAppId$.complete(); this.statusUpdaters$.complete(); - this.subscriptions.forEach(sub => sub.unsubscribe()); + this.subscriptions.forEach((sub) => sub.unsubscribe()); window.removeEventListener('beforeunload', this.onBeforeUnload); } } const updateStatus = (app: T, statusUpdaters: AppUpdaterWrapper[]): T => { let changes: Partial = {}; - statusUpdaters.forEach(wrapper => { + statusUpdaters.forEach((wrapper) => { if (wrapper.application !== allApplicationsFilter && wrapper.application !== app.id) { return; } @@ -388,10 +399,3 @@ const updateStatus = (app: T, statusUpdaters: AppUpdaterWrapp ...changes, }; }; - -function relativeToAbsolute(url: string) { - // convert all link urls to absolute urls - const a = document.createElement('a'); - a.setAttribute('href', url); - return a.href; -} diff --git a/src/core/public/application/integration_tests/application_service.test.tsx b/src/core/public/application/integration_tests/application_service.test.tsx index e399fbc726977..89f90a9899dda 100644 --- a/src/core/public/application/integration_tests/application_service.test.tsx +++ b/src/core/public/application/integration_tests/application_service.test.tsx @@ -31,7 +31,7 @@ import { overlayServiceMock } from '../../overlays/overlay_service.mock'; import { AppMountParameters } from '../types'; import { ScopedHistory } from '../scoped_history'; -const flushPromises = () => new Promise(resolve => setImmediate(resolve)); +const flushPromises = () => new Promise((resolve) => setImmediate(resolve)); describe('ApplicationService', () => { let setupDeps: MockLifecycle<'setup'>; @@ -68,7 +68,7 @@ describe('ApplicationService', () => { const { register } = service.setup(setupDeps); let resolveMount: () => void; - const promise = new Promise(resolve => { + const promise = new Promise((resolve) => { resolveMount = resolve; }); @@ -102,7 +102,7 @@ describe('ApplicationService', () => { const { register } = service.setup(setupDeps); let resolveMount: () => void; - const promise = new Promise(resolve => { + const promise = new Promise((resolve) => { resolveMount = resolve; }); @@ -146,7 +146,7 @@ describe('ApplicationService', () => { id: 'app1', title: 'App1', mount: ({ onAppLeave }: AppMountParameters) => { - onAppLeave(actions => actions.default()); + onAppLeave((actions) => actions.default()); return () => undefined; }, }); @@ -178,7 +178,7 @@ describe('ApplicationService', () => { id: 'app1', title: 'App1', mount: ({ onAppLeave }: AppMountParameters) => { - onAppLeave(actions => actions.default()); + onAppLeave((actions) => actions.default()); return () => undefined; }, }); @@ -213,7 +213,7 @@ describe('ApplicationService', () => { id: 'app1', title: 'App1', mount: ({ onAppLeave }: AppMountParameters) => { - onAppLeave(actions => actions.confirm('confirmation-message', 'confirmation-title')); + onAppLeave((actions) => actions.confirm('confirmation-message', 'confirmation-title')); return () => undefined; }, }); @@ -252,7 +252,7 @@ describe('ApplicationService', () => { id: 'app1', title: 'App1', mount: ({ onAppLeave }: AppMountParameters) => { - onAppLeave(actions => actions.confirm('confirmation-message', 'confirmation-title')); + onAppLeave((actions) => actions.confirm('confirmation-message', 'confirmation-title')); return () => undefined; }, }); diff --git a/src/core/public/application/integration_tests/router.test.tsx b/src/core/public/application/integration_tests/router.test.tsx index 9f379859dc34f..2827b93f6d17e 100644 --- a/src/core/public/application/integration_tests/router.test.tsx +++ b/src/core/public/application/integration_tests/router.test.tsx @@ -45,7 +45,7 @@ describe('AppRouter', () => { const mountersToAppStatus$ = () => { return new BehaviorSubject( new Map( - [...mounters.keys()].map(id => [ + [...mounters.keys()].map((id) => [ id, id.startsWith('disabled') ? AppStatus.inaccessible : AppStatus.accessible, ]) diff --git a/src/core/public/application/integration_tests/utils.tsx b/src/core/public/application/integration_tests/utils.tsx index 6c1b81a26d63c..8590fb3c820ef 100644 --- a/src/core/public/application/integration_tests/utils.tsx +++ b/src/core/public/application/integration_tests/utils.tsx @@ -33,7 +33,7 @@ export const createRenderer = (element: ReactElement | null): Renderer => { const dom: Dom = element && mount({element}); return () => - new Promise(async resolve => { + new Promise(async (resolve) => { if (dom) { await act(async () => { dom.update(); diff --git a/src/core/public/application/scoped_history.test.ts b/src/core/public/application/scoped_history.test.ts index a56cffef1e2f2..2b217e54228c2 100644 --- a/src/core/public/application/scoped_history.test.ts +++ b/src/core/public/application/scoped_history.test.ts @@ -217,7 +217,7 @@ describe('ScopedHistory', () => { gh.push('/app/wow'); const h = new ScopedHistory(gh, '/app/wow'); const listenPaths: string[] = []; - h.listen(l => listenPaths.push(l.pathname)); + h.listen((l) => listenPaths.push(l.pathname)); h.push('/first-page'); h.push('/second-page'); h.push('/third-page'); @@ -237,7 +237,7 @@ describe('ScopedHistory', () => { gh.push('/app/wow'); const h = new ScopedHistory(gh, '/app/wow'); const listenPaths: string[] = []; - const unlisten = h.listen(l => listenPaths.push(l.pathname)); + const unlisten = h.listen((l) => listenPaths.push(l.pathname)); h.push('/first-page'); unlisten(); h.push('/second-page'); @@ -252,7 +252,7 @@ describe('ScopedHistory', () => { gh.push('/app/wow'); const h = new ScopedHistory(gh, '/app/wow'); const listenPaths: string[] = []; - h.listen(l => listenPaths.push(l.pathname)); + h.listen((l) => listenPaths.push(l.pathname)); h.push('/first-page'); gh.push('/app/other'); gh.push('/second-page'); diff --git a/src/core/public/application/scoped_history.ts b/src/core/public/application/scoped_history.ts index 9fa8f0b7f8148..1a7fafa5d85c4 100644 --- a/src/core/public/application/scoped_history.ts +++ b/src/core/public/application/scoped_history.ts @@ -324,7 +324,7 @@ export class ScopedHistory throw new Error(`Unrecognized history action: ${action}`); } - [...this.listeners].forEach(listener => { + [...this.listeners].forEach((listener) => { listener(this.stripBasePath(location), action); }); }); diff --git a/src/core/public/application/types.ts b/src/core/public/application/types.ts index 786d11a5ced7f..c07d929fc5cea 100644 --- a/src/core/public/application/types.ts +++ b/src/core/public/application/types.ts @@ -659,12 +659,41 @@ export interface ApplicationStart { */ navigateToApp(appId: string, options?: { path?: string; state?: any }): Promise; + /** + * Navigate to given url, which can either be an absolute url or a relative path, in a SPA friendly way when possible. + * + * If all these criteria are true for the given url: + * - (only for absolute URLs) The origin of the URL matches the origin of the browser's current location + * - The pathname of the URL starts with the current basePath (eg. /mybasepath/s/my-space) + * - The pathname segment after the basePath matches any known application route (eg. /app// or any application's `appRoute` configuration) + * + * Then a SPA navigation will be performed using `navigateToApp` using the corresponding application and path. + * Otherwise, fallback to a full page reload to navigate to the url using `window.location.assign` + * + * @example + * ```ts + * // current url: `https://kibana:8080/base-path/s/my-space/app/dashboard` + * + * // will call `application.navigateToApp('discover', { path: '/some-path?foo=bar'})` + * application.navigateToUrl('https://kibana:8080/base-path/s/my-space/app/discover/some-path?foo=bar') + * application.navigateToUrl('/base-path/s/my-space/app/discover/some-path?foo=bar') + * + * // will perform a full page reload using `window.location.assign` + * application.navigateToUrl('https://elsewhere:8080/base-path/s/my-space/app/discover/some-path') // origin does not match + * application.navigateToUrl('/app/discover/some-path') // does not include the current basePath + * application.navigateToUrl('/base-path/s/my-space/app/unknown-app/some-path') // unknown application + * ``` + * + * @param url - an absolute url, or a relative path, to navigate to. + */ + navigateToUrl(url: string): Promise; + /** * Returns an URL to a given app, including the global base path. * By default, the URL is relative (/basePath/app/my-app). * Use the `absolute` option to generate an absolute url (http://host:port/basePath/app/my-app) * - * Note that when generating absolute urls, the protocol, host and port are determined from the browser location. + * Note that when generating absolute urls, the origin (protocol, host and port) are determined from the browser's location. * * @param appId * @param options.path - optional path inside application to deep link to @@ -677,7 +706,6 @@ export interface ApplicationStart { * plugin that registered this context. Deprecated, use {@link CoreSetup.getStartServices}. * * @deprecated - * @param pluginOpaqueId - The opaque ID of the plugin that is registering the context. * @param contextName - The key of {@link AppMountContext} this provider's return value should be attached to. * @param provider - A {@link IContextProvider} function */ @@ -696,7 +724,7 @@ export interface ApplicationStart { export interface InternalApplicationStart extends Pick< ApplicationStart, - 'capabilities' | 'navigateToApp' | 'getUrlForApp' | 'currentAppId$' + 'capabilities' | 'navigateToApp' | 'navigateToUrl' | 'getUrlForApp' | 'currentAppId$' > { /** * Apps available based on the current capabilities. diff --git a/src/core/public/application/ui/app_container.test.tsx b/src/core/public/application/ui/app_container.test.tsx index 5d573d47bd420..229354a014103 100644 --- a/src/core/public/application/ui/app_container.test.tsx +++ b/src/core/public/application/ui/app_container.test.tsx @@ -37,14 +37,14 @@ describe('AppContainer', () => { }); const flushPromises = async () => { - await new Promise(async resolve => { + await new Promise(async (resolve) => { setImmediate(() => resolve()); }); }; const createResolver = (): [Promise, () => void] => { let resolve: () => void | undefined; - const promise = new Promise(r => { + const promise = new Promise((r) => { resolve = r; }); return [promise, resolve!]; diff --git a/src/core/public/application/ui/app_container.tsx b/src/core/public/application/ui/app_container.tsx index 4317ede547202..332c31c64b6ba 100644 --- a/src/core/public/application/ui/app_container.tsx +++ b/src/core/public/application/ui/app_container.tsx @@ -83,7 +83,7 @@ export const AppContainer: FunctionComponent = ({ appBasePath: mounter.appBasePath, history: createScopedHistory(appPath), element: elementRef.current!, - onAppLeave: handler => setAppLeaveHandler(appId, handler), + onAppLeave: (handler) => setAppLeaveHandler(appId, handler), })) || null; } catch (e) { // TODO: add error UI diff --git a/src/core/public/application/utils.test.ts b/src/core/public/application/utils.test.ts index 7ed0919f88c61..a86a1206fc983 100644 --- a/src/core/public/application/utils.test.ts +++ b/src/core/public/application/utils.test.ts @@ -17,7 +17,15 @@ * under the License. */ -import { removeSlashes, appendAppPath } from './utils'; +import { LegacyApp, App } from './types'; +import { BasePath } from '../http/base_path'; +import { + removeSlashes, + appendAppPath, + isLegacyApp, + relativeToAbsolute, + parseAppUrl, +} from './utils'; describe('removeSlashes', () => { it('only removes duplicates by default', () => { @@ -69,3 +77,385 @@ describe('appendAppPath', () => { expect(appendAppPath('/app/my-app', '/some-path#/hash')).toEqual('/app/my-app/some-path#/hash'); }); }); + +describe('isLegacyApp', () => { + it('returns true for legacy apps', () => { + expect( + isLegacyApp({ + id: 'legacy', + title: 'Legacy App', + appUrl: '/some-url', + legacy: true, + }) + ).toEqual(true); + }); + it('returns false for non-legacy apps', () => { + expect( + isLegacyApp({ + id: 'legacy', + title: 'Legacy App', + mount: () => () => undefined, + legacy: false, + }) + ).toEqual(false); + }); +}); + +describe('relativeToAbsolute', () => { + it('converts a relative path to an absolute url', () => { + const origin = window.location.origin; + expect(relativeToAbsolute('path')).toEqual(`${origin}/path`); + expect(relativeToAbsolute('/path#hash')).toEqual(`${origin}/path#hash`); + expect(relativeToAbsolute('/path?query=foo')).toEqual(`${origin}/path?query=foo`); + }); +}); + +describe('parseAppUrl', () => { + let apps: Map | LegacyApp>; + let basePath: BasePath; + + const getOrigin = () => 'https://kibana.local:8080'; + + const createApp = (props: Partial): App => { + const app: App = { + id: 'some-id', + title: 'some-title', + mount: () => () => undefined, + ...props, + legacy: false, + }; + apps.set(app.id, app); + return app; + }; + + const createLegacyApp = (props: Partial): LegacyApp => { + const app: LegacyApp = { + id: 'some-id', + title: 'some-title', + appUrl: '/my-url', + ...props, + legacy: true, + }; + apps.set(app.id, app); + return app; + }; + + beforeEach(() => { + apps = new Map(); + basePath = new BasePath('/base-path'); + + createApp({ + id: 'foo', + }); + createApp({ + id: 'bar', + appRoute: '/custom-bar', + }); + createLegacyApp({ + id: 'legacy', + appUrl: '/app/legacy', + }); + }); + + describe('with relative paths', () => { + it('parses the app id', () => { + expect(parseAppUrl('/base-path/app/foo', basePath, apps, getOrigin)).toEqual({ + app: 'foo', + path: undefined, + }); + expect(parseAppUrl('/base-path/custom-bar', basePath, apps, getOrigin)).toEqual({ + app: 'bar', + path: undefined, + }); + }); + it('parses the path', () => { + expect(parseAppUrl('/base-path/app/foo/some/path', basePath, apps, getOrigin)).toEqual({ + app: 'foo', + path: '/some/path', + }); + expect(parseAppUrl('/base-path/custom-bar/another/path/', basePath, apps, getOrigin)).toEqual( + { + app: 'bar', + path: '/another/path/', + } + ); + }); + it('includes query and hash in the path for default app route', () => { + expect(parseAppUrl('/base-path/app/foo#hash/bang', basePath, apps, getOrigin)).toEqual({ + app: 'foo', + path: '#hash/bang', + }); + expect(parseAppUrl('/base-path/app/foo?hello=dolly', basePath, apps, getOrigin)).toEqual({ + app: 'foo', + path: '?hello=dolly', + }); + expect(parseAppUrl('/base-path/app/foo/path?hello=dolly', basePath, apps, getOrigin)).toEqual( + { + app: 'foo', + path: '/path?hello=dolly', + } + ); + expect(parseAppUrl('/base-path/app/foo/path#hash/bang', basePath, apps, getOrigin)).toEqual({ + app: 'foo', + path: '/path#hash/bang', + }); + expect( + parseAppUrl('/base-path/app/foo/path#hash/bang?hello=dolly', basePath, apps, getOrigin) + ).toEqual({ + app: 'foo', + path: '/path#hash/bang?hello=dolly', + }); + }); + it('includes query and hash in the path for custom app route', () => { + expect(parseAppUrl('/base-path/custom-bar#hash/bang', basePath, apps, getOrigin)).toEqual({ + app: 'bar', + path: '#hash/bang', + }); + expect(parseAppUrl('/base-path/custom-bar?hello=dolly', basePath, apps, getOrigin)).toEqual({ + app: 'bar', + path: '?hello=dolly', + }); + expect( + parseAppUrl('/base-path/custom-bar/path?hello=dolly', basePath, apps, getOrigin) + ).toEqual({ + app: 'bar', + path: '/path?hello=dolly', + }); + expect( + parseAppUrl('/base-path/custom-bar/path#hash/bang', basePath, apps, getOrigin) + ).toEqual({ + app: 'bar', + path: '/path#hash/bang', + }); + expect( + parseAppUrl('/base-path/custom-bar/path#hash/bang?hello=dolly', basePath, apps, getOrigin) + ).toEqual({ + app: 'bar', + path: '/path#hash/bang?hello=dolly', + }); + }); + it('works with legacy apps', () => { + expect(parseAppUrl('/base-path/app/legacy', basePath, apps, getOrigin)).toEqual({ + app: 'legacy', + path: undefined, + }); + expect( + parseAppUrl('/base-path/app/legacy/path#hash?query=bar', basePath, apps, getOrigin) + ).toEqual({ + app: 'legacy', + path: '/path#hash?query=bar', + }); + }); + it('returns undefined when the app is not known', () => { + expect(parseAppUrl('/base-path/app/non-registered', basePath, apps, getOrigin)).toEqual( + undefined + ); + expect(parseAppUrl('/base-path/unknown-path', basePath, apps, getOrigin)).toEqual(undefined); + }); + }); + + describe('with absolute urls', () => { + it('parses the app id', () => { + expect( + parseAppUrl('https://kibana.local:8080/base-path/app/foo', basePath, apps, getOrigin) + ).toEqual({ + app: 'foo', + path: undefined, + }); + expect( + parseAppUrl('https://kibana.local:8080/base-path/custom-bar', basePath, apps, getOrigin) + ).toEqual({ + app: 'bar', + path: undefined, + }); + }); + it('parses the path', () => { + expect( + parseAppUrl( + 'https://kibana.local:8080/base-path/app/foo/some/path', + basePath, + apps, + getOrigin + ) + ).toEqual({ + app: 'foo', + path: '/some/path', + }); + expect( + parseAppUrl( + 'https://kibana.local:8080/base-path/custom-bar/another/path/', + basePath, + apps, + getOrigin + ) + ).toEqual({ + app: 'bar', + path: '/another/path/', + }); + }); + it('includes query and hash in the path for default app routes', () => { + expect( + parseAppUrl( + 'https://kibana.local:8080/base-path/app/foo#hash/bang', + basePath, + apps, + getOrigin + ) + ).toEqual({ + app: 'foo', + path: '#hash/bang', + }); + expect( + parseAppUrl( + 'https://kibana.local:8080/base-path/app/foo?hello=dolly', + basePath, + apps, + getOrigin + ) + ).toEqual({ + app: 'foo', + path: '?hello=dolly', + }); + expect( + parseAppUrl( + 'https://kibana.local:8080/base-path/app/foo/path?hello=dolly', + basePath, + apps, + getOrigin + ) + ).toEqual({ + app: 'foo', + path: '/path?hello=dolly', + }); + expect( + parseAppUrl( + 'https://kibana.local:8080/base-path/app/foo/path#hash/bang', + basePath, + apps, + getOrigin + ) + ).toEqual({ + app: 'foo', + path: '/path#hash/bang', + }); + expect( + parseAppUrl( + 'https://kibana.local:8080/base-path/app/foo/path#hash/bang?hello=dolly', + basePath, + apps, + getOrigin + ) + ).toEqual({ + app: 'foo', + path: '/path#hash/bang?hello=dolly', + }); + }); + it('includes query and hash in the path for custom app route', () => { + expect( + parseAppUrl( + 'https://kibana.local:8080/base-path/custom-bar#hash/bang', + basePath, + apps, + getOrigin + ) + ).toEqual({ + app: 'bar', + path: '#hash/bang', + }); + expect( + parseAppUrl( + 'https://kibana.local:8080/base-path/custom-bar?hello=dolly', + basePath, + apps, + getOrigin + ) + ).toEqual({ + app: 'bar', + path: '?hello=dolly', + }); + expect( + parseAppUrl( + 'https://kibana.local:8080/base-path/custom-bar/path?hello=dolly', + basePath, + apps, + getOrigin + ) + ).toEqual({ + app: 'bar', + path: '/path?hello=dolly', + }); + expect( + parseAppUrl( + 'https://kibana.local:8080/base-path/custom-bar/path#hash/bang', + basePath, + apps, + getOrigin + ) + ).toEqual({ + app: 'bar', + path: '/path#hash/bang', + }); + expect( + parseAppUrl( + 'https://kibana.local:8080/base-path/custom-bar/path#hash/bang?hello=dolly', + basePath, + apps, + getOrigin + ) + ).toEqual({ + app: 'bar', + path: '/path#hash/bang?hello=dolly', + }); + }); + it('works with legacy apps', () => { + expect( + parseAppUrl('https://kibana.local:8080/base-path/app/legacy', basePath, apps, getOrigin) + ).toEqual({ + app: 'legacy', + path: undefined, + }); + expect( + parseAppUrl( + 'https://kibana.local:8080/base-path/app/legacy/path#hash?query=bar', + basePath, + apps, + getOrigin + ) + ).toEqual({ + app: 'legacy', + path: '/path#hash?query=bar', + }); + }); + it('returns undefined when the app is not known', () => { + expect( + parseAppUrl( + 'https://kibana.local:8080/base-path/app/non-registered', + basePath, + apps, + getOrigin + ) + ).toEqual(undefined); + expect( + parseAppUrl('https://kibana.local:8080/base-path/unknown-path', basePath, apps, getOrigin) + ).toEqual(undefined); + }); + it('returns undefined when origin does not match', () => { + expect( + parseAppUrl( + 'https://other-kibana.external:8080/base-path/app/foo', + basePath, + apps, + getOrigin + ) + ).toEqual(undefined); + expect( + parseAppUrl( + 'https://other-kibana.external:8080/base-path/custom-bar', + basePath, + apps, + getOrigin + ) + ).toEqual(undefined); + }); + }); +}); diff --git a/src/core/public/application/utils.ts b/src/core/public/application/utils.ts index 048f195fe1223..8987a9402f2db 100644 --- a/src/core/public/application/utils.ts +++ b/src/core/public/application/utils.ts @@ -17,6 +17,14 @@ * under the License. */ +import { IBasePath } from '../http'; +import { App, LegacyApp } from './types'; + +export interface AppUrlInfo { + app: string; + path?: string; +} + /** * Utility to remove trailing, leading or duplicate slashes. * By default will only remove duplicates. @@ -52,3 +60,62 @@ export const appendAppPath = (appBasePath: string, path: string = '') => { leading: false, }); }; + +export function isLegacyApp(app: App | LegacyApp): app is LegacyApp { + return app.legacy === true; +} + +/** + * Converts a relative path to an absolute url. + * Implementation is based on a specified behavior of the browser to automatically convert + * a relative url to an absolute one when setting the `href` attribute of a `` html element. + * + * @example + * ```ts + * // current url: `https://kibana:8000/base-path/app/my-app` + * relativeToAbsolute('/base-path/app/another-app') => `https://kibana:8000/base-path/app/another-app` + * ``` + */ +export const relativeToAbsolute = (url: string): string => { + const a = document.createElement('a'); + a.setAttribute('href', url); + return a.href; +}; + +/** + * Parse given url and return the associated app id and path if any app matches. + * Input can either be: + * - a path containing the basePath, ie `/base-path/app/my-app/some-path` + * - an absolute url matching the `origin` of the kibana instance (as seen by the browser), + * i.e `https://kibana:8080/base-path/app/my-app/some-path` + */ +export const parseAppUrl = ( + url: string, + basePath: IBasePath, + apps: Map | LegacyApp>, + getOrigin: () => string = () => window.location.origin +): AppUrlInfo | undefined => { + url = removeBasePath(url, basePath, getOrigin()); + if (!url.startsWith('/')) { + return undefined; + } + + for (const app of apps.values()) { + const appPath = isLegacyApp(app) ? app.appUrl : app.appRoute || `/app/${app.id}`; + + if (url.startsWith(appPath)) { + const path = url.substr(appPath.length); + return { + app: app.id, + path: path.length ? path : undefined, + }; + } + } +}; + +const removeBasePath = (url: string, basePath: IBasePath, origin: string): string => { + if (url.startsWith(origin)) { + url = url.substring(origin.length); + } + return basePath.remove(url); +}; diff --git a/src/core/public/chrome/chrome_service.test.ts b/src/core/public/chrome/chrome_service.test.ts index b5cf900d9c39f..0bc305ed9e28c 100644 --- a/src/core/public/chrome/chrome_service.test.ts +++ b/src/core/public/chrome/chrome_service.test.ts @@ -56,7 +56,7 @@ function defaultStartDeps(availableApps?: App[]) { if (availableApps) { deps.application.applications$ = new Rx.BehaviorSubject>( - new Map(availableApps.map(app => [app.id, app])) + new Map(availableApps.map((app) => [app.id, app])) ); } @@ -133,10 +133,7 @@ describe('start', () => { describe('brand', () => { it('updates/emits the brand as it changes', async () => { const { chrome, service } = await start(); - const promise = chrome - .getBrand$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getBrand$().pipe(toArray()).toPromise(); chrome.setBrand({ logo: 'big logo', @@ -166,10 +163,7 @@ describe('start', () => { describe('visibility', () => { it('emits false when no application is mounted', async () => { const { chrome, service } = await start(); - const promise = chrome - .getIsVisible$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getIsVisible$().pipe(toArray()).toPromise(); chrome.setIsVisible(true); chrome.setIsVisible(false); @@ -192,10 +186,7 @@ describe('start', () => { const { navigateToApp } = startDeps.application; const { chrome, service } = await start({ startDeps }); - const promise = chrome - .getIsVisible$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getIsVisible$().pipe(toArray()).toPromise(); await navigateToApp('alpha'); @@ -222,13 +213,10 @@ describe('start', () => { ]); const { applications$, navigateToApp } = startDeps.application; const { chrome, service } = await start({ startDeps }); - const promise = chrome - .getIsVisible$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getIsVisible$().pipe(toArray()).toPromise(); const availableApps = await applications$.pipe(take(1)).toPromise(); - [...availableApps.keys()].forEach(appId => navigateToApp(appId)); + [...availableApps.keys()].forEach((appId) => navigateToApp(appId)); service.stop(); await expect(promise).resolves.toMatchInlineSnapshot(` @@ -245,10 +233,7 @@ describe('start', () => { const startDeps = defaultStartDeps([new FakeApp('alpha', true)]); const { navigateToApp } = startDeps.application; const { chrome, service } = await start({ startDeps }); - const promise = chrome - .getIsVisible$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getIsVisible$().pipe(toArray()).toPromise(); await navigateToApp('alpha'); chrome.setIsVisible(true); @@ -267,10 +252,7 @@ describe('start', () => { describe('application classes', () => { it('updates/emits the application classes', async () => { const { chrome, service } = await start(); - const promise = chrome - .getApplicationClasses$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getApplicationClasses$().pipe(toArray()).toPromise(); chrome.addApplicationClass('foo'); chrome.addApplicationClass('foo'); @@ -318,10 +300,7 @@ describe('start', () => { describe('badge', () => { it('updates/emits the current badge', async () => { const { chrome, service } = await start(); - const promise = chrome - .getBadge$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getBadge$().pipe(toArray()).toPromise(); chrome.setBadge({ text: 'foo', tooltip: `foo's tooltip` }); chrome.setBadge({ text: 'bar', tooltip: `bar's tooltip` }); @@ -348,10 +327,7 @@ describe('start', () => { describe('breadcrumbs', () => { it('updates/emits the current set of breadcrumbs', async () => { const { chrome, service } = await start(); - const promise = chrome - .getBreadcrumbs$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getBreadcrumbs$().pipe(toArray()).toPromise(); chrome.setBreadcrumbs([{ text: 'foo' }, { text: 'bar' }]); chrome.setBreadcrumbs([{ text: 'foo' }]); @@ -389,10 +365,7 @@ describe('start', () => { describe('help extension', () => { it('updates/emits the current help extension', async () => { const { chrome, service } = await start(); - const promise = chrome - .getHelpExtension$() - .pipe(toArray()) - .toPromise(); + const promise = chrome.getHelpExtension$().pipe(toArray()).toPromise(); chrome.setHelpExtension({ appName: 'App name', content: () => () => undefined }); chrome.setHelpExtension(undefined); diff --git a/src/core/public/chrome/chrome_service.tsx b/src/core/public/chrome/chrome_service.tsx index a921e514050b2..fc7e78f209022 100644 --- a/src/core/public/chrome/chrome_service.tsx +++ b/src/core/public/chrome/chrome_service.tsx @@ -117,9 +117,9 @@ export class ChromeService { // in the sense that the chrome UI should not be displayed until a non-chromeless app is mounting or mounted of(true), application.currentAppId$.pipe( - flatMap(appId => + flatMap((appId) => application.applications$.pipe( - map(applications => { + map((applications) => { return !!appId && applications.has(appId) && !!applications.get(appId)!.chromeless; }) ) @@ -260,7 +260,7 @@ export class ChromeService { getApplicationClasses$: () => applicationClasses$.pipe( - map(set => [...set]), + map((set) => [...set]), takeUntil(this.stop$) ), diff --git a/src/core/public/chrome/doc_title/doc_title_service.ts b/src/core/public/chrome/doc_title/doc_title_service.ts index 9453abe54de66..c6e9ec7a40b77 100644 --- a/src/core/public/chrome/doc_title/doc_title_service.ts +++ b/src/core/public/chrome/doc_title/doc_title_service.ts @@ -86,7 +86,7 @@ export class DocTitleService { this.applyTitle(defaultTitle); }, __legacy: { - setBaseTitle: baseTitle => { + setBaseTitle: (baseTitle) => { this.baseTitle = baseTitle; }, }, diff --git a/src/core/public/chrome/nav_controls/nav_controls_service.test.ts b/src/core/public/chrome/nav_controls/nav_controls_service.test.ts index c8f168bbcb2f7..ac556c1d1cc5d 100644 --- a/src/core/public/chrome/nav_controls/nav_controls_service.test.ts +++ b/src/core/public/chrome/nav_controls/nav_controls_service.test.ts @@ -30,12 +30,7 @@ describe('RecentlyAccessed#start()', () => { const navControls = getStart(); const nc = { mount: jest.fn() }; navControls.registerLeft(nc); - expect( - await navControls - .getLeft$() - .pipe(take(1)) - .toPromise() - ).toEqual([nc]); + expect(await navControls.getLeft$().pipe(take(1)).toPromise()).toEqual([nc]); }); it('sorts controls by order property', async () => { @@ -46,12 +41,7 @@ describe('RecentlyAccessed#start()', () => { navControls.registerLeft(nc1); navControls.registerLeft(nc2); navControls.registerLeft(nc3); - expect( - await navControls - .getLeft$() - .pipe(take(1)) - .toPromise() - ).toEqual([nc2, nc1, nc3]); + expect(await navControls.getLeft$().pipe(take(1)).toPromise()).toEqual([nc2, nc1, nc3]); }); }); @@ -60,12 +50,7 @@ describe('RecentlyAccessed#start()', () => { const navControls = getStart(); const nc = { mount: jest.fn() }; navControls.registerRight(nc); - expect( - await navControls - .getRight$() - .pipe(take(1)) - .toPromise() - ).toEqual([nc]); + expect(await navControls.getRight$().pipe(take(1)).toPromise()).toEqual([nc]); }); it('sorts controls by order property', async () => { @@ -76,12 +61,7 @@ describe('RecentlyAccessed#start()', () => { navControls.registerRight(nc1); navControls.registerRight(nc2); navControls.registerRight(nc3); - expect( - await navControls - .getRight$() - .pipe(take(1)) - .toPromise() - ).toEqual([nc2, nc1, nc3]); + expect(await navControls.getRight$().pipe(take(1)).toPromise()).toEqual([nc2, nc1, nc3]); }); }); }); diff --git a/src/core/public/chrome/nav_controls/nav_controls_service.ts b/src/core/public/chrome/nav_controls/nav_controls_service.ts index 7f9c75595a4ce..167948e01cb36 100644 --- a/src/core/public/chrome/nav_controls/nav_controls_service.ts +++ b/src/core/public/chrome/nav_controls/nav_controls_service.ts @@ -74,12 +74,12 @@ export class NavControlsService { getLeft$: () => navControlsLeft$.pipe( - map(controls => sortBy([...controls.values()], 'order')), + map((controls) => sortBy([...controls.values()], 'order')), takeUntil(this.stop$) ), getRight$: () => navControlsRight$.pipe( - map(controls => sortBy([...controls.values()], 'order')), + map((controls) => sortBy([...controls.values()], 'order')), takeUntil(this.stop$) ), }; diff --git a/src/core/public/chrome/nav_links/nav_links_service.test.ts b/src/core/public/chrome/nav_links/nav_links_service.test.ts index 3d9a4bfdb6a56..8f610e238b0fd 100644 --- a/src/core/public/chrome/nav_links/nav_links_service.test.ts +++ b/src/core/public/chrome/nav_links/nav_links_service.test.ts @@ -90,7 +90,7 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.map(l => l.id)) + map((links) => links.map((l) => l.id)) ) .toPromise() ).not.toContain('chromelessApp'); @@ -102,16 +102,16 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.map(l => l.id)) + map((links) => links.map((l) => l.id)) ) .toPromise() ).toEqual(['app2', 'legacyApp2', 'app1', 'legacyApp1', 'legacyApp3']); }); it('emits multiple values', async () => { - const navLinkIds$ = start.getNavLinks$().pipe(map(links => links.map(l => l.id))); + const navLinkIds$ = start.getNavLinks$().pipe(map((links) => links.map((l) => l.id))); const emittedLinks: string[][] = []; - navLinkIds$.subscribe(r => emittedLinks.push(r)); + navLinkIds$.subscribe((r) => emittedLinks.push(r)); start.update('legacyApp1', { active: true }); service.stop(); @@ -122,10 +122,7 @@ describe('NavLinksService', () => { }); it('completes when service is stopped', async () => { - const last$ = start - .getNavLinks$() - .pipe(takeLast(1)) - .toPromise(); + const last$ = start.getNavLinks$().pipe(takeLast(1)).toPromise(); service.stop(); await expect(last$).resolves.toBeInstanceOf(Array); }); @@ -143,7 +140,7 @@ describe('NavLinksService', () => { describe('#getAll()', () => { it('returns a sorted array of navlinks', () => { - expect(start.getAll().map(l => l.id)).toEqual([ + expect(start.getAll().map((l) => l.id)).toEqual([ 'app2', 'legacyApp2', 'app1', @@ -171,7 +168,7 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.map(l => l.id)) + map((links) => links.map((l) => l.id)) ) .toPromise() ).toEqual(['app2', 'legacyApp2', 'app1', 'legacyApp1', 'legacyApp3']); @@ -184,7 +181,7 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.map(l => l.id)) + map((links) => links.map((l) => l.id)) ) .toPromise() ).toEqual(['app2', 'legacyApp2', 'app1', 'legacyApp1', 'legacyApp3']); @@ -197,7 +194,7 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.map(l => l.id)) + map((links) => links.map((l) => l.id)) ) .toPromise() ).toEqual(['legacyApp1']); @@ -211,7 +208,7 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.map(l => l.id)) + map((links) => links.map((l) => l.id)) ) .toPromise() ).toEqual(['legacyApp2']); @@ -236,7 +233,7 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.filter(l => l.hidden).map(l => l.id)) + map((links) => links.filter((l) => l.hidden).map((l) => l.id)) ) .toPromise(); expect(hiddenLinkIds).toEqual(['legacyApp1']); @@ -253,7 +250,7 @@ describe('NavLinksService', () => { .getNavLinks$() .pipe( take(1), - map(links => links.filter(l => l.hidden).map(l => l.id)) + map((links) => links.filter((l) => l.hidden).map((l) => l.id)) ) .toPromise(); expect(hiddenLinkIds).toEqual(['legacyApp1']); @@ -262,21 +259,15 @@ describe('NavLinksService', () => { describe('#enableForcedAppSwitcherNavigation()', () => { it('flips #getForceAppSwitcherNavigation$()', async () => { - await expect( - start - .getForceAppSwitcherNavigation$() - .pipe(take(1)) - .toPromise() - ).resolves.toBe(false); + await expect(start.getForceAppSwitcherNavigation$().pipe(take(1)).toPromise()).resolves.toBe( + false + ); start.enableForcedAppSwitcherNavigation(); - await expect( - start - .getForceAppSwitcherNavigation$() - .pipe(take(1)) - .toPromise() - ).resolves.toBe(true); + await expect(start.getForceAppSwitcherNavigation$().pipe(take(1)).toPromise()).resolves.toBe( + true + ); }); }); }); diff --git a/src/core/public/chrome/nav_links/nav_links_service.ts b/src/core/public/chrome/nav_links/nav_links_service.ts index fec9322b0d77d..3095bb86b72e2 100644 --- a/src/core/public/chrome/nav_links/nav_links_service.ts +++ b/src/core/public/chrome/nav_links/nav_links_service.ts @@ -108,7 +108,7 @@ export class NavLinksService { public start({ application, http }: StartDeps): ChromeNavLinks { const appLinks$ = application.applications$.pipe( - map(apps => { + map((apps) => { return new Map( [...apps] .filter(([, app]) => !app.chromeless) @@ -129,7 +129,7 @@ export class NavLinksService { return linkUpdaters.reduce((links, updater) => updater(links), appLinks); }) ) - .subscribe(navlinks => { + .subscribe((navlinks) => { navLinks$.next(navlinks); }); @@ -158,7 +158,7 @@ export class NavLinksService { return; } - const updater: LinksUpdater = navLinks => + const updater: LinksUpdater = (navLinks) => new Map([...navLinks.entries()].filter(([linkId]) => linkId === id)); linkUpdaters$.next([...linkUpdaters$.value, updater]); @@ -169,7 +169,7 @@ export class NavLinksService { return; } - const updater: LinksUpdater = navLinks => + const updater: LinksUpdater = (navLinks) => new Map( [...navLinks.entries()].map(([linkId, link]) => { return [linkId, link.id === id ? link.update(values) : link] as [ @@ -200,7 +200,7 @@ export class NavLinksService { function sortNavLinks(navLinks: ReadonlyMap) { return sortBy( - [...navLinks.values()].map(link => link.properties), + [...navLinks.values()].map((link) => link.properties), 'order' ); } diff --git a/src/core/public/chrome/recently_accessed/persisted_log.ts b/src/core/public/chrome/recently_accessed/persisted_log.ts index 421f553f6a315..ca94e0bcddfaf 100644 --- a/src/core/public/chrome/recently_accessed/persisted_log.ts +++ b/src/core/public/chrome/recently_accessed/persisted_log.ts @@ -57,7 +57,7 @@ export class PersistedLog { const nextItems = [ val, // remove any duplicate items - ...[...this.items$.value].filter(item => !this.isEqual(item, val)), + ...[...this.items$.value].filter((item) => !this.isEqual(item, val)), ].slice(0, this.maxLength); // truncate // Persist the stack to storage @@ -73,7 +73,7 @@ export class PersistedLog { } public get$() { - return this.items$.pipe(map(items => cloneDeep(items))); + return this.items$.pipe(map((items) => cloneDeep(items))); } private loadItems() { diff --git a/src/core/public/chrome/ui/header/collapsible_nav.tsx b/src/core/public/chrome/ui/header/collapsible_nav.tsx index 60463d8dccc9b..8bca42db23517 100644 --- a/src/core/public/chrome/ui/header/collapsible_nav.tsx +++ b/src/core/public/chrome/ui/header/collapsible_nav.tsx @@ -50,7 +50,7 @@ function getOrderedCategories( ) { return sortBy( Object.keys(mainCategories), - categoryName => categoryDictionary[categoryName]?.order + (categoryName) => categoryDictionary[categoryName]?.order ); } @@ -94,7 +94,7 @@ export function CollapsibleNav({ storage = window.localStorage, }: Props) { const lockRef = useRef(null); - const groupedNavLinks = groupBy(navLinks, link => link?.category?.id); + const groupedNavLinks = groupBy(navLinks, (link) => link?.category?.id); const { undefined: unknowns = [], ...allCategorizedLinks } = groupedNavLinks; const categoryDictionary = getAllCategories(allCategorizedLinks); const orderedCategories = getOrderedCategories(allCategorizedLinks, categoryDictionary); @@ -156,7 +156,7 @@ export function CollapsibleNav({ title={i18n.translate('core.ui.recentlyViewed', { defaultMessage: 'Recently viewed' })} isCollapsible={true} initialIsOpen={getIsCategoryOpen('recentlyViewed', storage)} - onToggle={isCategoryOpen => setIsCategoryOpen('recentlyViewed', isCategoryOpen, storage)} + onToggle={(isCategoryOpen) => setIsCategoryOpen('recentlyViewed', isCategoryOpen, storage)} data-test-subj="collapsibleNavGroup-recentlyViewed" > {recentNavLinks.length > 0 ? ( @@ -218,7 +218,7 @@ export function CollapsibleNav({ title={category.label} isCollapsible={true} initialIsOpen={getIsCategoryOpen(category.id, storage)} - onToggle={isCategoryOpen => setIsCategoryOpen(category.id, isCategoryOpen, storage)} + onToggle={(isCategoryOpen) => setIsCategoryOpen(category.id, isCategoryOpen, storage)} data-test-subj={`collapsibleNavGroup-${category.id}`} > { super(props); let isLocked = false; - props.isLocked$.subscribe(initialIsLocked => (isLocked = initialIsLocked)); + props.isLocked$.subscribe((initialIsLocked) => (isLocked = initialIsLocked)); this.state = { appTitle: 'Kibana', @@ -142,7 +142,7 @@ export class Header extends Component { appTitle, isVisible, forceNavigation, - navLinks: navLinks.filter(navLink => !navLink.hidden), + navLinks: navLinks.filter((navLink) => !navLink.hidden), recentlyAccessed, navControlsLeft, navControlsRight, @@ -183,7 +183,7 @@ export class Header extends Component { kibanaDocLink, kibanaVersion, } = this.props; - const navLinks = this.state.navLinks.map(link => + const navLinks = this.state.navLinks.map((link) => createNavLink( link, this.props.legacyMode, @@ -192,7 +192,7 @@ export class Header extends Component { this.props.application.navigateToApp ) ); - const recentNavLinks = this.state.recentlyAccessed.map(link => + const recentNavLinks = this.state.recentlyAccessed.map((link) => createRecentNavLink(link, this.state.navLinks, this.props.basePath) ); diff --git a/src/core/public/chrome/ui/header/header_badge.tsx b/src/core/public/chrome/ui/header/header_badge.tsx index 4e529ad9a410b..d2d5e5d663300 100644 --- a/src/core/public/chrome/ui/header/header_badge.tsx +++ b/src/core/public/chrome/ui/header/header_badge.tsx @@ -77,7 +77,7 @@ export class HeaderBadge extends Component { } private subscribe() { - this.subscription = this.props.badge$.subscribe(badge => { + this.subscription = this.props.badge$.subscribe((badge) => { this.setState({ badge, }); diff --git a/src/core/public/chrome/ui/header/header_breadcrumbs.tsx b/src/core/public/chrome/ui/header/header_breadcrumbs.tsx index 83840cff45d03..54cfc7131cb2b 100644 --- a/src/core/public/chrome/ui/header/header_breadcrumbs.tsx +++ b/src/core/public/chrome/ui/header/header_breadcrumbs.tsx @@ -70,7 +70,7 @@ export class HeaderBreadcrumbs extends Component { } private subscribe() { - this.subscription = this.props.breadcrumbs$.subscribe(breadcrumbs => { + this.subscription = this.props.breadcrumbs$.subscribe((breadcrumbs) => { this.setState({ breadcrumbs, }); diff --git a/src/core/public/chrome/ui/header/header_logo.tsx b/src/core/public/chrome/ui/header/header_logo.tsx index 4296064945455..147c7cf5dc4b1 100644 --- a/src/core/public/chrome/ui/header/header_logo.tsx +++ b/src/core/public/chrome/ui/header/header_logo.tsx @@ -49,7 +49,7 @@ function onClick( return; } - const navLink = navLinks.find(item => item.href === anchor.href); + const navLink = navLinks.find((item) => item.href === anchor.href); if (navLink && navLink.isDisabled) { event.preventDefault(); return; @@ -95,7 +95,7 @@ export function HeaderLogo({ href, forceNavigation, navLinks, navigateToApp }: P onClick(e, forceNavigation, navLinks, navigateToApp)} + onClick={(e) => onClick(e, forceNavigation, navLinks, navigateToApp)} href={href} aria-label={i18n.translate('core.ui.chrome.headerGlobalNav.goHomePageIconAriaLabel', { defaultMessage: 'Go to home page', diff --git a/src/core/public/chrome/ui/header/nav_link.tsx b/src/core/public/chrome/ui/header/nav_link.tsx index 8003c22b99a36..c979bb8271e1b 100644 --- a/src/core/public/chrome/ui/header/nav_link.tsx +++ b/src/core/public/chrome/ui/header/nav_link.tsx @@ -161,7 +161,7 @@ export function createRecentNavLink( ) { const { link, label } = recentLink; const href = relativeToAbsolute(basePath.prepend(link)); - const navLink = navLinks.find(nl => href.startsWith(nl.baseUrl ?? nl.subUrlBase)); + const navLink = navLinks.find((nl) => href.startsWith(nl.baseUrl ?? nl.subUrlBase)); let titleAndAriaLabel = label; if (navLink) { diff --git a/src/core/public/chrome/ui/loading_indicator.tsx b/src/core/public/chrome/ui/loading_indicator.tsx index 7729302b6b612..0209612eae08c 100644 --- a/src/core/public/chrome/ui/loading_indicator.tsx +++ b/src/core/public/chrome/ui/loading_indicator.tsx @@ -35,7 +35,7 @@ export class LoadingIndicator extends React.Component { + this.loadingCountSubscription = this.props.loadingCount$.subscribe((count) => { this.setState({ visible: count > 0, }); diff --git a/src/core/public/entry_point.ts b/src/core/public/entry_point.ts index 9461acccf30b9..25180c13ccbd4 100644 --- a/src/core/public/entry_point.ts +++ b/src/core/public/entry_point.ts @@ -33,7 +33,11 @@ const injectedMetadata = JSON.parse( document.querySelector('kbn-injected-metadata')!.getAttribute('data')! ); -if (process.env.IS_KIBANA_DISTRIBUTABLE !== 'true' && process.env.ELASTIC_APM_ACTIVE === 'true') { +/** + * `apmConfig` would be populated with relavant APM RUM agent + * configuration if server is started with `ELASTIC_APM_ACTIVE=true` + */ +if (process.env.IS_KIBANA_DISTRIBUTABLE !== 'true' && injectedMetadata.vars.apmConfig != null) { // @ts-ignore // eslint-disable-next-line @typescript-eslint/no-var-requires const { init } = require('@elastic/apm-rum'); @@ -42,8 +46,8 @@ if (process.env.IS_KIBANA_DISTRIBUTABLE !== 'true' && process.env.ELASTIC_APM_AC i18n .load(injectedMetadata.i18n.translationsUrl) - .catch(e => e) - .then(async i18nError => { + .catch((e) => e) + .then(async (i18nError) => { const coreSystem = new CoreSystem({ injectedMetadata, rootDomElement: document.body, diff --git a/src/core/public/fatal_errors/fatal_errors_screen.tsx b/src/core/public/fatal_errors/fatal_errors_screen.tsx index f7184b01a0a78..98eb9f0ef21d5 100644 --- a/src/core/public/fatal_errors/fatal_errors_screen.tsx +++ b/src/core/public/fatal_errors/fatal_errors_screen.tsx @@ -63,8 +63,8 @@ export class FatalErrorsScreen extends React.Component { // consume error notifications and set them to the component state this.props.errorInfo$.pipe( - tap(error => { - this.setState(state => ({ + tap((error) => { + this.setState((state) => ({ ...state, errors: [...state.errors, error], })); diff --git a/src/core/public/fatal_errors/fatal_errors_service.test.ts b/src/core/public/fatal_errors/fatal_errors_service.test.ts index 373b0efddc2cf..a39f31d2c559c 100644 --- a/src/core/public/fatal_errors/fatal_errors_service.test.ts +++ b/src/core/public/fatal_errors/fatal_errors_service.test.ts @@ -20,7 +20,7 @@ import * as Rx from 'rxjs'; expect.addSnapshotSerializer({ - test: val => val instanceof Rx.Observable, + test: (val) => val instanceof Rx.Observable, print: () => `Rx.Observable`, }); diff --git a/src/core/public/fatal_errors/fatal_errors_service.tsx b/src/core/public/fatal_errors/fatal_errors_service.tsx index 309f07859ef26..403f8925b99c7 100644 --- a/src/core/public/fatal_errors/fatal_errors_service.tsx +++ b/src/core/public/fatal_errors/fatal_errors_service.tsx @@ -85,7 +85,7 @@ export class FatalErrorsService { }) ) .subscribe({ - error: error => { + error: (error) => { // eslint-disable-next-line no-console console.error('Uncaught error in fatal error service internals', error); }, @@ -145,7 +145,7 @@ export class FatalErrorsService { private setupGlobalErrorHandlers(fatalErrorsSetup: FatalErrorsSetup) { if (window.addEventListener) { - window.addEventListener('unhandledrejection', function(e) { + window.addEventListener('unhandledrejection', function (e) { console.log(`Detected an unhandled Promise rejection.\n${e.reason}`); // eslint-disable-line no-console }); } diff --git a/src/core/public/http/base_path.ts b/src/core/public/http/base_path.ts index 67464a6196b02..ac85d71c793fe 100644 --- a/src/core/public/http/base_path.ts +++ b/src/core/public/http/base_path.ts @@ -49,7 +49,7 @@ export class BasePath { public prepend = (path: string): string => { if (!this.basePath) return path; - return modifyUrl(path, parts => { + return modifyUrl(path, (parts) => { if (!parts.hostname && parts.pathname && parts.pathname.startsWith('/')) { parts.pathname = `${this.basePath}${parts.pathname}`; } diff --git a/src/core/public/http/fetch.test.ts b/src/core/public/http/fetch.test.ts index f223956075e97..d889fae335ece 100644 --- a/src/core/public/http/fetch.test.ts +++ b/src/core/public/http/fetch.test.ts @@ -28,7 +28,7 @@ import { BasePath } from './base_path'; import { HttpResponse, HttpFetchOptionsWithPath } from './types'; function delay(duration: number) { - return new Promise(r => setTimeout(r, duration)); + return new Promise((r) => setTimeout(r, duration)); } const BASE_PATH = 'http://localhost/myBase'; @@ -44,11 +44,7 @@ describe('Fetch', () => { }); describe('getRequestCount$', () => { - const getCurrentRequestCount = () => - fetchInstance - .getRequestCount$() - .pipe(first()) - .toPromise(); + const getCurrentRequestCount = () => fetchInstance.getRequestCount$().pipe(first()).toPromise(); it('should increase and decrease when request receives success response', async () => { fetchMock.get('*', 200); @@ -88,7 +84,7 @@ describe('Fetch', () => { const requestCounts: number[] = []; const subscription = fetchInstance .getRequestCount$() - .subscribe(count => requestCounts.push(count)); + .subscribe((count) => requestCounts.push(count)); const success1 = fetchInstance.fetch('/success'); const success2 = fetchInstance.fetch('/success'); @@ -371,7 +367,7 @@ describe('Fetch', () => { fetchMock.get('*', Promise.reject(abortError)); - await fetchInstance.fetch('/my/path').catch(e => { + await fetchInstance.fetch('/my/path').catch((e) => { expect(e.name).toEqual('AbortError'); }); }); diff --git a/src/core/public/http/fetch.ts b/src/core/public/http/fetch.ts index d88dc2e3a9037..bf9b4235e9444 100644 --- a/src/core/public/http/fetch.ts +++ b/src/core/public/http/fetch.ts @@ -212,7 +212,7 @@ const validateFetchArguments = ( ); } - const invalidHeaders = Object.keys(fullOptions.headers ?? {}).filter(headerName => + const invalidHeaders = Object.keys(fullOptions.headers ?? {}).filter((headerName) => headerName.startsWith('kbn-') ); if (invalidHeaders.length) { diff --git a/src/core/public/http/intercept.ts b/src/core/public/http/intercept.ts index bacc8748d2680..be02ebbf94fae 100644 --- a/src/core/public/http/intercept.ts +++ b/src/core/public/http/intercept.ts @@ -31,7 +31,7 @@ export async function interceptRequest( return [...interceptors].reduceRight( (promise, interceptor) => promise.then( - async fetchOptions => { + async (fetchOptions) => { current = fetchOptions; checkHalt(controller); @@ -45,7 +45,7 @@ export async function interceptRequest( ...overrides, }; }, - async error => { + async (error) => { checkHalt(controller, error); if (!interceptor.requestError) { @@ -83,7 +83,7 @@ export async function interceptResponse( return await [...interceptors].reduce( (promise, interceptor) => promise.then( - async httpResponse => { + async (httpResponse) => { current = httpResponse; checkHalt(controller); @@ -98,7 +98,7 @@ export async function interceptResponse( ...interceptorOverrides, }; }, - async error => { + async (error) => { const request = error.request || (current && current.request); checkHalt(controller, error); diff --git a/src/core/public/http/loading_count_service.test.ts b/src/core/public/http/loading_count_service.test.ts index 3ba4d315178cc..706d62b4283ba 100644 --- a/src/core/public/http/loading_count_service.test.ts +++ b/src/core/public/http/loading_count_service.test.ts @@ -89,10 +89,7 @@ describe('LoadingCountService', () => { const countA$ = new Subject(); const countB$ = new Subject(); const countC$ = new Subject(); - const promise = loadingCount - .getLoadingCount$() - .pipe(toArray()) - .toPromise(); + const promise = loadingCount.getLoadingCount$().pipe(toArray()).toPromise(); loadingCount.addLoadingCountSource(countA$); loadingCount.addLoadingCountSource(countB$); @@ -125,10 +122,7 @@ describe('LoadingCountService', () => { const { service, loadingCount } = setup(); const count$ = new Subject(); - const promise = loadingCount - .getLoadingCount$() - .pipe(toArray()) - .toPromise(); + const promise = loadingCount.getLoadingCount$().pipe(toArray()).toPromise(); loadingCount.addLoadingCountSource(count$); count$.next(0); diff --git a/src/core/public/http/loading_count_service.ts b/src/core/public/http/loading_count_service.ts index 14b945e0801ca..e4a248daca8f2 100644 --- a/src/core/public/http/loading_count_service.ts +++ b/src/core/public/http/loading_count_service.ts @@ -56,7 +56,7 @@ export class LoadingCountService implements CoreService { + tap((count) => { if (count < 0) { throw new Error( 'Observables passed to loadingCount.add() must only emit positive numbers' @@ -73,10 +73,10 @@ export class LoadingCountService implements CoreService next - prev) ) .subscribe({ - next: delta => { + next: (delta) => { this.loadingCount$.next(this.loadingCount$.getValue() + delta); }, - error: error => fatalErrors.add(error), + error: (error) => fatalErrors.add(error), }); }, }; diff --git a/src/core/public/integrations/moment/moment_service.test.mocks.ts b/src/core/public/integrations/moment/moment_service.test.mocks.ts index bb13232157b78..4c0c584679b2c 100644 --- a/src/core/public/integrations/moment/moment_service.test.mocks.ts +++ b/src/core/public/integrations/moment/moment_service.test.mocks.ts @@ -22,7 +22,7 @@ export const momentMock = { tz: { setDefault: jest.fn(), zone: jest.fn( - z => [{ name: 'tz1' }, { name: 'tz2' }, { name: 'tz3' }].find(f => z === f.name) || null + (z) => [{ name: 'tz1' }, { name: 'tz2' }, { name: 'tz3' }].find((f) => z === f.name) || null ), }, weekdays: jest.fn(() => ['dow1', 'dow2', 'dow3']), diff --git a/src/core/public/integrations/moment/moment_service.test.ts b/src/core/public/integrations/moment/moment_service.test.ts index bc48ba2a85f63..5179ff468f84d 100644 --- a/src/core/public/integrations/moment/moment_service.test.ts +++ b/src/core/public/integrations/moment/moment_service.test.ts @@ -32,7 +32,7 @@ describe('MomentService', () => { }); afterEach(() => service.stop()); - const flushPromises = () => new Promise(resolve => setTimeout(resolve, 100)); + const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 100)); test('sets initial moment config', async () => { const tz$ = new BehaviorSubject('tz1'); diff --git a/src/core/public/integrations/styles/styles_service.test.ts b/src/core/public/integrations/styles/styles_service.test.ts index e413e9cc2f4d7..fc75c6b3e3d06 100644 --- a/src/core/public/integrations/styles/styles_service.test.ts +++ b/src/core/public/integrations/styles/styles_service.test.ts @@ -25,7 +25,7 @@ import { StylesService } from './styles_service'; import { uiSettingsServiceMock } from '../../ui_settings/ui_settings_service.mock'; describe('StylesService', () => { - const flushPromises = () => new Promise(resolve => setTimeout(resolve, 100)); + const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 100)); const getDisableAnimationsTag = () => document.querySelector('style#disableAnimationsCss')!; afterEach(() => getDisableAnimationsTag().remove()); diff --git a/src/core/public/legacy/legacy_service.ts b/src/core/public/legacy/legacy_service.ts index 01837ba6f5940..810416cdbfe16 100644 --- a/src/core/public/legacy/legacy_service.ts +++ b/src/core/public/legacy/legacy_service.ts @@ -115,8 +115,8 @@ export class LegacyPlatformService { // Initialize legacy sub urls core.chrome.navLinks .getAll() - .filter(link => link.legacy) - .forEach(navLink => { + .filter((link) => link.legacy) + .forEach((navLink) => { const lastSubUrl = lastSubUrlStorage.getItem(`lastSubUrl:${navLink.baseUrl}`); core.chrome.navLinks.update(navLink.id, { url: lastSubUrl || navLink.url || navLink.baseUrl, @@ -135,6 +135,7 @@ export class LegacyPlatformService { capabilities: core.application.capabilities, getUrlForApp: core.application.getUrlForApp, navigateToApp: core.application.navigateToApp, + navigateToUrl: core.application.navigateToUrl, registerMountContext: notSupported(`core.application.registerMountContext()`), }, }; diff --git a/src/core/public/notifications/toasts/global_toast_list.test.tsx b/src/core/public/notifications/toasts/global_toast_list.test.tsx index dc2a9dabe791e..1d5d5b86836fd 100644 --- a/src/core/public/notifications/toasts/global_toast_list.test.tsx +++ b/src/core/public/notifications/toasts/global_toast_list.test.tsx @@ -34,7 +34,7 @@ it('renders matching snapshot', () => { it('subscribes to toasts$ on mount and unsubscribes on unmount', () => { const unsubscribeSpy = jest.fn(); - const subscribeSpy = jest.fn(observer => { + const subscribeSpy = jest.fn((observer) => { observer.next([]); return unsubscribeSpy; }); diff --git a/src/core/public/notifications/toasts/global_toast_list.tsx b/src/core/public/notifications/toasts/global_toast_list.tsx index f96a0a6f362bf..cb2d90ff265bf 100644 --- a/src/core/public/notifications/toasts/global_toast_list.tsx +++ b/src/core/public/notifications/toasts/global_toast_list.tsx @@ -47,7 +47,7 @@ export class GlobalToastList extends React.Component { private subscription?: Rx.Subscription; public componentDidMount() { - this.subscription = this.props.toasts$.subscribe(toasts => { + this.subscription = this.props.toasts$.subscribe((toasts) => { this.setState({ toasts }); }); } diff --git a/src/core/public/notifications/toasts/toasts_api.test.ts b/src/core/public/notifications/toasts/toasts_api.test.ts index 7c0ef5576256a..08e1d9711322c 100644 --- a/src/core/public/notifications/toasts/toasts_api.test.ts +++ b/src/core/public/notifications/toasts/toasts_api.test.ts @@ -25,10 +25,7 @@ import { uiSettingsServiceMock } from '../../ui_settings/ui_settings_service.moc import { i18nServiceMock } from '../../i18n/i18n_service.mock'; async function getCurrentToasts(toasts: ToastsApi) { - return await toasts - .get$() - .pipe(take(1)) - .toPromise(); + return await toasts.get$().pipe(take(1)).toPromise(); } function uiSettingsMock() { diff --git a/src/core/public/notifications/toasts/toasts_api.tsx b/src/core/public/notifications/toasts/toasts_api.tsx index 53717b9c2e174..db65ed76d1cb1 100644 --- a/src/core/public/notifications/toasts/toasts_api.tsx +++ b/src/core/public/notifications/toasts/toasts_api.tsx @@ -150,7 +150,7 @@ export class ToastsApi implements IToasts { public remove(toastOrId: Toast | string) { const toRemove = typeof toastOrId === 'string' ? toastOrId : toastOrId.id; const list = this.toasts$.getValue(); - const listWithoutToast = list.filter(t => t.id !== toRemove); + const listWithoutToast = list.filter((t) => t.id !== toRemove); if (listWithoutToast.length !== list.length) { this.toasts$.next(listWithoutToast); } diff --git a/src/core/public/overlays/banners/banners_list.tsx b/src/core/public/overlays/banners/banners_list.tsx index ee7aa73dc34a6..6503af985f9c8 100644 --- a/src/core/public/overlays/banners/banners_list.tsx +++ b/src/core/public/overlays/banners/banners_list.tsx @@ -47,7 +47,7 @@ export const BannersList: React.FunctionComponent = ({ banners$ }) => { return (
- {banners.map(banner => ( + {banners.map((banner) => ( ))}
diff --git a/src/core/public/overlays/banners/banners_service.test.ts b/src/core/public/overlays/banners/banners_service.test.ts index f11a5d6b88bc2..8e76a18178ff0 100644 --- a/src/core/public/overlays/banners/banners_service.test.ts +++ b/src/core/public/overlays/banners/banners_service.test.ts @@ -31,11 +31,7 @@ describe('OverlayBannersService', () => { }); }); - const currentBanners = () => - service - .get$() - .pipe(take(1)) - .toPromise(); + const currentBanners = () => service.get$().pipe(take(1)).toPromise(); describe('adding banners', () => { test('adds a single banner', async () => { diff --git a/src/core/public/overlays/banners/banners_service.tsx b/src/core/public/overlays/banners/banners_service.tsx index ed59ed819b1c2..c0f76a6deaac7 100644 --- a/src/core/public/overlays/banners/banners_service.tsx +++ b/src/core/public/overlays/banners/banners_service.tsx @@ -112,7 +112,7 @@ export class OverlayBannersService { }, get$() { - return banners$.pipe(map(bannerMap => [...bannerMap.values()])); + return banners$.pipe(map((bannerMap) => [...bannerMap.values()])); }, getComponent() { diff --git a/src/core/public/overlays/banners/user_banner_service.tsx b/src/core/public/overlays/banners/user_banner_service.tsx index e3f4d9dee5b78..643d95a1e3bb4 100644 --- a/src/core/public/overlays/banners/user_banner_service.tsx +++ b/src/core/public/overlays/banners/user_banner_service.tsx @@ -63,7 +63,7 @@ export class UserBannerService { id = banners.replace( id, - el => { + (el) => { ReactDOM.render( { describe('openModal()', () => { it('renders a modal to the DOM', () => { expect(mockReactDomRender).not.toHaveBeenCalled(); - modals.open(container => { + modals.open((container) => { const content = document.createElement('span'); content.textContent = 'Modal content'; container.append(content); @@ -104,7 +104,7 @@ describe('ModalService', () => { describe('openConfirm()', () => { it('renders a mountpoint confirm message', () => { expect(mockReactDomRender).not.toHaveBeenCalled(); - modals.openConfirm(container => { + modals.openConfirm((container) => { const content = document.createElement('span'); content.textContent = 'Modal content'; container.append(content); diff --git a/src/core/public/overlays/overlay.test.mocks.ts b/src/core/public/overlays/overlay.test.mocks.ts index 563f414a0ae99..f382511d445ea 100644 --- a/src/core/public/overlays/overlay.test.mocks.ts +++ b/src/core/public/overlays/overlay.test.mocks.ts @@ -19,7 +19,7 @@ export const mockReactDomRender = jest.fn(); export const mockReactDomUnmount = jest.fn(); -export const mockReactDomCreatePortal = jest.fn().mockImplementation(component => component); +export const mockReactDomCreatePortal = jest.fn().mockImplementation((component) => component); jest.doMock('react-dom', () => ({ render: mockReactDomRender, createPortal: mockReactDomCreatePortal, diff --git a/src/core/public/plugins/plugin.test.ts b/src/core/public/plugins/plugin.test.ts index 8fe745db9554d..3f77161f8c34d 100644 --- a/src/core/public/plugins/plugin.test.ts +++ b/src/core/public/plugins/plugin.test.ts @@ -101,7 +101,7 @@ describe('PluginWrapper', () => { setup: jest.fn(), start: jest.fn(async () => { // Add small delay to ensure startDependencies is not resolved until after the plugin instance's start resolves. - await new Promise(resolve => setTimeout(resolve, 10)); + await new Promise((resolve) => setTimeout(resolve, 10)); expect(startDependenciesResolved).toBe(false); return pluginStartContract; }), @@ -113,7 +113,7 @@ describe('PluginWrapper', () => { const deps = { otherDep: 'value' }; // Add promise callback prior to calling `start` to ensure calls in `setup` will not resolve before `start` is // called. - const startDependenciesCheck = plugin.startDependencies.then(res => { + const startDependenciesCheck = plugin.startDependencies.then((res) => { startDependenciesResolved = true; expect(res).toEqual([context, deps, pluginStartContract]); }); diff --git a/src/core/public/plugins/plugin_context.ts b/src/core/public/plugins/plugin_context.ts index c4b3c929415ee..c688373630a07 100644 --- a/src/core/public/plugins/plugin_context.ts +++ b/src/core/public/plugins/plugin_context.ts @@ -95,8 +95,8 @@ export function createPluginSetupContext< ): CoreSetup { return { application: { - register: app => deps.application.register(plugin.opaqueId, app), - registerAppUpdater: statusUpdater$ => deps.application.registerAppUpdater(statusUpdater$), + register: (app) => deps.application.register(plugin.opaqueId, app), + registerAppUpdater: (statusUpdater$) => deps.application.registerAppUpdater(statusUpdater$), registerMountContext: (contextName, provider) => deps.application.registerMountContext(plugin.opaqueId, contextName, provider), }, @@ -138,6 +138,7 @@ export function createPluginStartContext< currentAppId$: deps.application.currentAppId$, capabilities: deps.application.capabilities, navigateToApp: deps.application.navigateToApp, + navigateToUrl: deps.application.navigateToUrl, getUrlForApp: deps.application.getUrlForApp, registerMountContext: (contextName, provider) => deps.application.registerMountContext(plugin.opaqueId, contextName, provider), diff --git a/src/core/public/plugins/plugins_service.test.ts b/src/core/public/plugins/plugins_service.test.ts index 6c5ab5fcedcfd..05127e73d0c7a 100644 --- a/src/core/public/plugins/plugins_service.test.ts +++ b/src/core/public/plugins/plugins_service.test.ts @@ -50,7 +50,7 @@ import { contextServiceMock } from '../context/context_service.mock'; export let mockPluginInitializers: Map; mockPluginInitializerProvider.mockImplementation( - pluginName => mockPluginInitializers.get(pluginName)! + (pluginName) => mockPluginInitializers.get(pluginName)! ); let plugins: InjectedPluginMetadata[]; @@ -251,7 +251,7 @@ describe('PluginsService', () => { }); describe('timeout', () => { - const flushPromises = () => new Promise(resolve => setImmediate(resolve)); + const flushPromises = () => new Promise((resolve) => setImmediate(resolve)); beforeAll(() => { jest.useFakeTimers(); }); @@ -263,7 +263,7 @@ describe('PluginsService', () => { mockPluginInitializers.set( 'pluginA', jest.fn(() => ({ - setup: jest.fn(() => new Promise(i => i)), + setup: jest.fn(() => new Promise((i) => i)), start: jest.fn(() => ({ value: 1 })), stop: jest.fn(), })) @@ -344,7 +344,7 @@ describe('PluginsService', () => { 'pluginA', jest.fn(() => ({ setup: jest.fn(() => ({ value: 1 })), - start: jest.fn(() => new Promise(i => i)), + start: jest.fn(() => new Promise((i) => i)), stop: jest.fn(), })) ); diff --git a/src/core/public/plugins/plugins_service.ts b/src/core/public/plugins/plugins_service.ts index 862aa5043ad4b..f9bc40ca52601 100644 --- a/src/core/public/plugins/plugins_service.ts +++ b/src/core/public/plugins/plugins_service.ts @@ -60,14 +60,14 @@ export class PluginsService implements CoreService(plugins.map(p => [p.id, Symbol(p.id)])); + const opaqueIds = new Map(plugins.map((p) => [p.id, Symbol(p.id)])); // Setup dependency map and plugin wrappers plugins.forEach(({ id, plugin, config = {} }) => { // Setup map of dependencies this.pluginDependencies.set(id, [ ...plugin.requiredPlugins, - ...plugin.optionalPlugins.filter(optPlugin => opaqueIds.has(optPlugin)), + ...plugin.optionalPlugins.filter((optPlugin) => opaqueIds.has(optPlugin)), ]); // Construct plugin wrappers, depending on the topological order set by the server. @@ -87,7 +87,7 @@ export class PluginsService implements CoreService [ this.plugins.get(id)!.opaqueId, - deps.map(depId => this.plugins.get(depId)!.opaqueId), + deps.map((depId) => this.plugins.get(depId)!.opaqueId), ]) ); } diff --git a/src/core/public/public.api.md b/src/core/public/public.api.md index fbd8f474151fa..4ccded9b9afec 100644 --- a/src/core/public/public.api.md +++ b/src/core/public/public.api.md @@ -116,6 +116,7 @@ export interface ApplicationStart { path?: string; state?: any; }): Promise; + navigateToUrl(url: string): Promise; // @deprecated registerMountContext(contextName: T, provider: IContextProvider): void; } diff --git a/src/core/public/saved_objects/saved_objects_client.ts b/src/core/public/saved_objects/saved_objects_client.ts index 7958a4f8134d3..cdc113871c447 100644 --- a/src/core/public/saved_objects/saved_objects_client.ts +++ b/src/core/public/saved_objects/saved_objects_client.ts @@ -156,8 +156,8 @@ export class SavedObjectsClient { this.bulkGet(queue) .then(({ savedObjects }) => { - queue.forEach(queueItem => { - const foundObject = savedObjects.find(savedObject => { + queue.forEach((queueItem) => { + const foundObject = savedObjects.find((savedObject) => { return savedObject.id === queueItem.id && savedObject.type === queueItem.type; }); @@ -168,8 +168,8 @@ export class SavedObjectsClient { queueItem.resolve(foundObject); }); }) - .catch(err => { - queue.forEach(queueItem => { + .catch((err) => { + queue.forEach((queueItem) => { queueItem.reject(err); }); }); @@ -216,7 +216,7 @@ export class SavedObjectsClient { }), }); - return createRequest.then(resp => this.createSavedObject(resp)); + return createRequest.then((resp) => this.createSavedObject(resp)); }; /** @@ -239,8 +239,8 @@ export class SavedObjectsClient { query, body: JSON.stringify(objects), }); - return request.then(resp => { - resp.saved_objects = resp.saved_objects.map(d => this.createSavedObject(d)); + return request.then((resp) => { + resp.saved_objects = resp.saved_objects.map((d) => this.createSavedObject(d)); return renameKeys< PromiseType>, SavedObjectsBatchResponse @@ -301,8 +301,8 @@ export class SavedObjectsClient { method: 'GET', query, }); - return request.then(resp => { - resp.saved_objects = resp.saved_objects.map(d => this.createSavedObject(d)); + return request.then((resp) => { + resp.saved_objects = resp.saved_objects.map((d) => this.createSavedObject(d)); return renameKeys< PromiseType>, SavedObjectsFindResponsePublic @@ -350,14 +350,14 @@ export class SavedObjectsClient { */ public bulkGet = (objects: Array<{ id: string; type: string }> = []) => { const path = this.getPath(['_bulk_get']); - const filteredObjects = objects.map(obj => pick(obj, ['id', 'type'])); + const filteredObjects = objects.map((obj) => pick(obj, ['id', 'type'])); const request: ReturnType = this.savedObjectsFetch(path, { method: 'POST', body: JSON.stringify(filteredObjects), }); - return request.then(resp => { - resp.saved_objects = resp.saved_objects.map(d => this.createSavedObject(d)); + return request.then((resp) => { + resp.saved_objects = resp.saved_objects.map((d) => this.createSavedObject(d)); return renameKeys< PromiseType>, SavedObjectsBatchResponse @@ -414,7 +414,7 @@ export class SavedObjectsClient { return this.savedObjectsFetch(path, { method: 'PUT', body: JSON.stringify(objects), - }).then(resp => { + }).then((resp) => { resp.saved_objects = resp.saved_objects.map((d: SavedObject) => this.createSavedObject(d)); return renameKeys< PromiseType>, diff --git a/src/core/public/ui_settings/ui_settings_api.test.ts b/src/core/public/ui_settings/ui_settings_api.test.ts index 9a462e0541347..bab7081509d53 100644 --- a/src/core/public/ui_settings/ui_settings_api.test.ts +++ b/src/core/public/ui_settings/ui_settings_api.test.ts @@ -26,7 +26,7 @@ import { setup as httpSetup } from '../../../test_utils/public/http_test_setup'; import { UiSettingsApi } from './ui_settings_api'; function setup() { - const { http } = httpSetup(injectedMetadata => { + const { http } = httpSetup((injectedMetadata) => { injectedMetadata.getBasePath.mockReturnValue('/foo/bar'); }); @@ -181,10 +181,7 @@ describe('#getLoadingCount$()', () => { const { uiSettingsApi } = setup(); const done$ = new Rx.Subject(); - const promise = uiSettingsApi - .getLoadingCount$() - .pipe(takeUntil(done$), toArray()) - .toPromise(); + const promise = uiSettingsApi.getLoadingCount$().pipe(takeUntil(done$), toArray()).toPromise(); await uiSettingsApi.batchSet('foo', 'bar'); done$.next(); @@ -209,10 +206,7 @@ describe('#getLoadingCount$()', () => { const { uiSettingsApi } = setup(); const done$ = new Rx.Subject(); - const promise = uiSettingsApi - .getLoadingCount$() - .pipe(takeUntil(done$), toArray()) - .toPromise(); + const promise = uiSettingsApi.getLoadingCount$().pipe(takeUntil(done$), toArray()).toPromise(); await uiSettingsApi.batchSet('foo', 'bar'); await expect(uiSettingsApi.batchSet('foo', 'bar')).rejects.toThrowError(); @@ -230,14 +224,8 @@ describe('#stop', () => { const { uiSettingsApi } = setup(); const promise = Promise.all([ - uiSettingsApi - .getLoadingCount$() - .pipe(toArray()) - .toPromise(), - uiSettingsApi - .getLoadingCount$() - .pipe(toArray()) - .toPromise(), + uiSettingsApi.getLoadingCount$().pipe(toArray()).toPromise(), + uiSettingsApi.getLoadingCount$().pipe(toArray()).toPromise(), ]); const batchSetPromise = uiSettingsApi.batchSet('foo', 'bar'); diff --git a/src/core/public/ui_settings/ui_settings_client.test.ts b/src/core/public/ui_settings/ui_settings_client.test.ts index f394036e3e046..3b67efb740e7d 100644 --- a/src/core/public/ui_settings/ui_settings_client.test.ts +++ b/src/core/public/ui_settings/ui_settings_client.test.ts @@ -88,20 +88,14 @@ describe('#get', () => { describe('#get$', () => { it('emits the current value when called', async () => { const { client } = setup(); - const values = await client - .get$('dateFormat') - .pipe(take(1), toArray()) - .toPromise(); + const values = await client.get$('dateFormat').pipe(take(1), toArray()).toPromise(); expect(values).toEqual(['Browser']); }); it('emits an error notification if the key is unknown', async () => { const { client } = setup(); - const values = await client - .get$('unknown key') - .pipe(materialize()) - .toPromise(); + const values = await client.get$('unknown key').pipe(materialize()).toPromise(); expect(values).toMatchInlineSnapshot(` Notification { @@ -124,10 +118,7 @@ You can use \`IUiSettingsClient.get("unknown key", defaultValue)\`, which will j client.set('dateFormat', 'new format'); }, 10); - const values = await client - .get$('dateFormat') - .pipe(take(2), toArray()) - .toPromise(); + const values = await client.get$('dateFormat').pipe(take(2), toArray()).toPromise(); expect(values).toEqual(['Browser', 'new format']); }); diff --git a/src/core/public/ui_settings/ui_settings_client.ts b/src/core/public/ui_settings/ui_settings_client.ts index f5596b1bc34fc..2a7c3c2fab2f3 100644 --- a/src/core/public/ui_settings/ui_settings_client.ts +++ b/src/core/public/ui_settings/ui_settings_client.ts @@ -97,7 +97,7 @@ You can use \`IUiSettingsClient.get("${key}", defaultValue)\`, which will just r return concat( defer(() => of(this.get(key, defaultOverride))), this.update$.pipe( - filter(update => update.key === key), + filter((update) => update.key === key), map(() => this.get(key, defaultOverride)) ) ); diff --git a/src/core/public/ui_settings/ui_settings_service.test.ts b/src/core/public/ui_settings/ui_settings_service.test.ts index 2747a78d93fa6..4c688d5b7b2c1 100644 --- a/src/core/public/ui_settings/ui_settings_service.test.ts +++ b/src/core/public/ui_settings/ui_settings_service.test.ts @@ -38,7 +38,7 @@ describe('#stop', () => { it('stops the uiSettingsClient and uiSettingsApi', async () => { const service = new UiSettingsService(); let loadingCount$: Rx.Observable; - defaultDeps.http.addLoadingCountSource.mockImplementation(obs$ => (loadingCount$ = obs$)); + defaultDeps.http.addLoadingCountSource.mockImplementation((obs$) => (loadingCount$ = obs$)); const client = service.setup(defaultDeps); service.stop(); diff --git a/src/core/public/utils/share_weak_replay.test.ts b/src/core/public/utils/share_weak_replay.test.ts index 6eaa140e5afad..beac851aa689c 100644 --- a/src/core/public/utils/share_weak_replay.test.ts +++ b/src/core/public/utils/share_weak_replay.test.ts @@ -38,7 +38,7 @@ function counter({ async = true }: { async?: boolean } = {}) { completedCounts += 1; } - return new Rx.Observable(subscriber => { + return new Rx.Observable((subscriber) => { if (!async) { sendCount(subscriber); return; @@ -53,7 +53,7 @@ async function record(observable: Rx.Observable) { return observable .pipe( materialize(), - map(n => (n.kind === 'N' ? `N:${n.value}` : n.kind === 'E' ? `E:${n.error.message}` : 'C')), + map((n) => (n.kind === 'N' ? `N:${n.value}` : n.kind === 'E' ? `E:${n.error.message}` : 'C')), toArray() ) .toPromise(); diff --git a/src/core/public/utils/share_weak_replay.ts b/src/core/public/utils/share_weak_replay.ts index 74ea6cc536888..5ed6f76c5a05a 100644 --- a/src/core/public/utils/share_weak_replay.ts +++ b/src/core/public/utils/share_weak_replay.ts @@ -39,7 +39,7 @@ export function shareWeakReplay(bufferSize?: number): Rx.MonoTypeOperatorFunc let subject: Rx.ReplaySubject | undefined; const stop$ = new Rx.Subject(); - return new Rx.Observable(observer => { + return new Rx.Observable((observer) => { if (!subject) { subject = new Rx.ReplaySubject(bufferSize); } diff --git a/src/core/server/bootstrap.ts b/src/core/server/bootstrap.ts index dff0c00a4625e..5dbe5a0b4f955 100644 --- a/src/core/server/bootstrap.ts +++ b/src/core/server/bootstrap.ts @@ -71,7 +71,7 @@ export async function bootstrap({ // This is only used by the LogRotator service // in order to be able to reload the log configuration // under the cluster mode - process.on('message', msg => { + process.on('message', (msg) => { if (!msg || msg.reloadLoggingConfig !== true) { return; } diff --git a/src/core/server/capabilities/capabilities_service.ts b/src/core/server/capabilities/capabilities_service.ts index d3d6b507da523..f0be9743d4d60 100644 --- a/src/core/server/capabilities/capabilities_service.ts +++ b/src/core/server/capabilities/capabilities_service.ts @@ -127,7 +127,7 @@ export class CapabilitiesService { () => mergeCapabilities( defaultCapabilities, - ...this.capabilitiesProviders.map(provider => provider()) + ...this.capabilitiesProviders.map((provider) => provider()) ), () => this.capabilitiesSwitchers ); @@ -150,7 +150,7 @@ export class CapabilitiesService { public start(): CapabilitiesStart { return { - resolveCapabilities: request => this.resolveCapabilities(request, []), + resolveCapabilities: (request) => this.resolveCapabilities(request, []), }; } } diff --git a/src/core/server/capabilities/resolve_capabilities.ts b/src/core/server/capabilities/resolve_capabilities.ts index dcb93bdca5f16..1be504d4bc314 100644 --- a/src/core/server/capabilities/resolve_capabilities.ts +++ b/src/core/server/capabilities/resolve_capabilities.ts @@ -64,7 +64,7 @@ function recursiveApplyChanges< TSource extends Record >(destination: TDestination, source: TSource): TDestination { return Object.keys(destination) - .map(key => { + .map((key) => { const orig = destination[key]; const changed = source[key]; if (changed == null) { diff --git a/src/core/server/config/config.ts b/src/core/server/config/config.ts index b1a6a8cc525bf..a4026b1d88ac3 100644 --- a/src/core/server/config/config.ts +++ b/src/core/server/config/config.ts @@ -34,7 +34,7 @@ export function isConfigPath(value: unknown): value is ConfigPath { return true; } - return Array.isArray(value) && value.every(segment => typeof segment === 'string'); + return Array.isArray(value) && value.every((segment) => typeof segment === 'string'); } /** diff --git a/src/core/server/config/config_service.test.ts b/src/core/server/config/config_service.test.ts index 773a444dea948..5f28fca1371b0 100644 --- a/src/core/server/config/config_service.test.ts +++ b/src/core/server/config/config_service.test.ts @@ -62,10 +62,10 @@ test('throws if config at path does not match schema', async () => { .atPath('key') .pipe(take(1)) .subscribe( - value => { + (value) => { valuesReceived.push(value); }, - error => { + (error) => { valuesReceived.push(error); } ); @@ -86,10 +86,10 @@ test('re-validate config when updated', async () => { const valuesReceived: any[] = []; await configService.atPath('key').subscribe( - value => { + (value) => { valuesReceived.push(value); }, - error => { + (error) => { valuesReceived.push(error); } ); @@ -133,7 +133,7 @@ test("does not push new configs when reloading if config at path hasn't changed" await configService.setSchema('key', schema.string()); const valuesReceived: any[] = []; - configService.atPath('key').subscribe(value => { + configService.atPath('key').subscribe((value) => { valuesReceived.push(value); }); @@ -150,7 +150,7 @@ test('pushes new config when reloading and config at path has changed', async () await configService.setSchema('key', schema.string()); const valuesReceived: any[] = []; - configService.atPath('key').subscribe(value => { + configService.atPath('key').subscribe((value) => { valuesReceived.push(value); }); diff --git a/src/core/server/config/config_service.ts b/src/core/server/config/config_service.ts index 61630f43bffb5..bceba420bb6ce 100644 --- a/src/core/server/config/config_service.ts +++ b/src/core/server/config/config_service.ts @@ -89,7 +89,7 @@ export class ConfigService { const flatPath = pathToString(path); this.deprecations.next([ ...this.deprecations.value, - ...provider(configDeprecationFactory).map(deprecation => ({ + ...provider(configDeprecationFactory).map((deprecation) => ({ deprecation, path: flatPath, })), @@ -104,9 +104,7 @@ export class ConfigService { public async validate() { const namespaces = [...this.schemas.keys()]; for (let i = 0; i < namespaces.length; i++) { - await this.validateConfigAtPath(namespaces[i]) - .pipe(first()) - .toPromise(); + await this.validateConfigAtPath(namespaces[i]).pipe(first()).toPromise(); } await this.logDeprecation(); @@ -138,7 +136,7 @@ export class ConfigService { */ public optionalAtPath(path: ConfigPath) { return this.getDistinctConfig(path).pipe( - map(config => { + map((config) => { if (config === undefined) return undefined; return this.validateAtPath(path, config) as TSchema; }) @@ -149,9 +147,7 @@ export class ConfigService { const namespace = pathToString(path); const validatedConfig = this.schemas.has(namespace) - ? await this.atPath<{ enabled?: boolean }>(path) - .pipe(first()) - .toPromise() + ? await this.atPath<{ enabled?: boolean }>(path).pipe(first()).toPromise() : undefined; const enabledPath = createPluginEnabledPath(path); @@ -186,26 +182,23 @@ export class ConfigService { const config = await this.config$.pipe(first()).toPromise(); const handledPaths = this.handledPaths.map(pathToString); - return config.getFlattenedPaths().filter(path => !isPathHandled(path, handledPaths)); + return config.getFlattenedPaths().filter((path) => !isPathHandled(path, handledPaths)); } public async getUsedPaths() { const config = await this.config$.pipe(first()).toPromise(); const handledPaths = this.handledPaths.map(pathToString); - return config.getFlattenedPaths().filter(path => isPathHandled(path, handledPaths)); + return config.getFlattenedPaths().filter((path) => isPathHandled(path, handledPaths)); } private async logDeprecation() { - const rawConfig = await this.rawConfigProvider - .getConfig$() - .pipe(take(1)) - .toPromise(); + const rawConfig = await this.rawConfigProvider.getConfig$().pipe(take(1)).toPromise(); const deprecations = await this.deprecations.pipe(take(1)).toPromise(); const deprecationMessages: string[] = []; const logger = (msg: string) => deprecationMessages.push(msg); applyDeprecations(rawConfig, deprecations, logger); - deprecationMessages.forEach(msg => { + deprecationMessages.forEach((msg) => { this.deprecationLog.warn(msg); }); } @@ -228,14 +221,14 @@ export class ConfigService { } private validateConfigAtPath(path: ConfigPath) { - return this.getDistinctConfig(path).pipe(map(config => this.validateAtPath(path, config))); + return this.getDistinctConfig(path).pipe(map((config) => this.validateAtPath(path, config))); } private getDistinctConfig(path: ConfigPath) { this.markAsHandled(path); return this.config$.pipe( - map(config => config.get(path)), + map((config) => config.get(path)), distinctUntilChanged(isEqual) ); } @@ -260,4 +253,4 @@ const pathToString = (path: ConfigPath) => (Array.isArray(path) ? path.join('.') * handled paths. */ const isPathHandled = (path: string, handledPaths: string[]) => - handledPaths.some(handledPath => hasConfigPathIntersection(path, handledPath)); + handledPaths.some((handledPath) => hasConfigPathIntersection(path, handledPath)); diff --git a/src/core/server/config/deprecation/apply_deprecations.test.ts b/src/core/server/config/deprecation/apply_deprecations.test.ts index 25cae80d8b5cb..d7cc85add4e76 100644 --- a/src/core/server/config/deprecation/apply_deprecations.test.ts +++ b/src/core/server/config/deprecation/apply_deprecations.test.ts @@ -36,7 +36,7 @@ describe('applyDeprecations', () => { const handlerC = jest.fn(); applyDeprecations( {}, - [handlerA, handlerB, handlerC].map(h => wrapHandler(h)) + [handlerA, handlerB, handlerC].map((h) => wrapHandler(h)) ); expect(handlerA).toHaveBeenCalledTimes(1); expect(handlerB).toHaveBeenCalledTimes(1); @@ -49,7 +49,7 @@ describe('applyDeprecations', () => { const alteredConfig = { foo: 'bar' }; const handlerA = jest.fn().mockReturnValue(alteredConfig); - const handlerB = jest.fn().mockImplementation(conf => conf); + const handlerB = jest.fn().mockImplementation((conf) => conf); applyDeprecations( initialConfig, diff --git a/src/core/server/config/deprecation/core_deprecations.test.ts b/src/core/server/config/deprecation/core_deprecations.test.ts index a91e128f62d2d..ebdb6f1c88b16 100644 --- a/src/core/server/config/deprecation/core_deprecations.test.ts +++ b/src/core/server/config/deprecation/core_deprecations.test.ts @@ -28,11 +28,11 @@ const applyCoreDeprecations = (settings: Record = {}) => { const deprecationMessages: string[] = []; const migrated = applyDeprecations( settings, - deprecations.map(deprecation => ({ + deprecations.map((deprecation) => ({ deprecation, path: '', })), - msg => deprecationMessages.push(msg) + (msg) => deprecationMessages.push(msg) ); return { messages: deprecationMessages, diff --git a/src/core/server/config/deprecation/core_deprecations.ts b/src/core/server/config/deprecation/core_deprecations.ts index 9e098c06ba155..483534e0c145b 100644 --- a/src/core/server/config/deprecation/core_deprecations.ts +++ b/src/core/server/config/deprecation/core_deprecations.ts @@ -72,26 +72,26 @@ const cspRulesDeprecation: ConfigDeprecation = (settings, fromPath, log) => { const rules: string[] = get(settings, 'csp.rules'); if (rules) { const parsed = new Map( - rules.map(ruleStr => { + rules.map((ruleStr) => { const parts = ruleStr.split(/\s+/); return [parts[0], parts.slice(1)]; }) ); settings.csp.rules = [...parsed].map(([policy, sourceList]) => { - if (sourceList.find(source => source.includes(NONCE_STRING))) { + if (sourceList.find((source) => source.includes(NONCE_STRING))) { log(`csp.rules no longer supports the {nonce} syntax. Replacing with 'self' in ${policy}`); - sourceList = sourceList.filter(source => !source.includes(NONCE_STRING)); + sourceList = sourceList.filter((source) => !source.includes(NONCE_STRING)); // Add 'self' if not present - if (!sourceList.find(source => source.includes(SELF_STRING))) { + if (!sourceList.find((source) => source.includes(SELF_STRING))) { sourceList.push(SELF_STRING); } } if ( SELF_POLICIES.includes(policy) && - !sourceList.find(source => source.includes(SELF_STRING)) + !sourceList.find((source) => source.includes(SELF_STRING)) ) { log(`csp.rules must contain the 'self' source. Automatically adding to ${policy}.`); sourceList.push(SELF_STRING); diff --git a/src/core/server/config/deprecation/deprecation_factory.test.ts b/src/core/server/config/deprecation/deprecation_factory.test.ts index 2595fdd923dd5..3910ee3235caf 100644 --- a/src/core/server/config/deprecation/deprecation_factory.test.ts +++ b/src/core/server/config/deprecation/deprecation_factory.test.ts @@ -24,7 +24,7 @@ describe('DeprecationFactory', () => { const { rename, unused, renameFromRoot, unusedFromRoot } = configDeprecationFactory; let deprecationMessages: string[]; - const logger: ConfigDeprecationLogger = msg => deprecationMessages.push(msg); + const logger: ConfigDeprecationLogger = (msg) => deprecationMessages.push(msg); beforeEach(() => { deprecationMessages = []; diff --git a/src/core/server/config/ensure_deep_object.ts b/src/core/server/config/ensure_deep_object.ts index 58865d13c1afa..6eaaef983355c 100644 --- a/src/core/server/config/ensure_deep_object.ts +++ b/src/core/server/config/ensure_deep_object.ts @@ -31,7 +31,7 @@ export function ensureDeepObject(obj: any): any { } if (Array.isArray(obj)) { - return obj.map(item => ensureDeepObject(item)); + return obj.map((item) => ensureDeepObject(item)); } return Object.keys(obj).reduce((fullObject, propertyKey) => { diff --git a/src/core/server/config/integration_tests/config_deprecation.test.ts b/src/core/server/config/integration_tests/config_deprecation.test.ts index 5bc3887f05f93..3523b074ea5b4 100644 --- a/src/core/server/config/integration_tests/config_deprecation.test.ts +++ b/src/core/server/config/integration_tests/config_deprecation.test.ts @@ -36,7 +36,7 @@ describe('configuration deprecations', () => { await root.setup(); const logs = loggingServiceMock.collect(mockLoggingService); - const warnings = logs.warn.flatMap(i => i); + const warnings = logs.warn.flatMap((i) => i); expect(warnings).not.toContain( '"optimize.lazy" is deprecated and has been replaced by "optimize.watch"' ); @@ -56,7 +56,7 @@ describe('configuration deprecations', () => { await root.setup(); const logs = loggingServiceMock.collect(mockLoggingService); - const warnings = logs.warn.flatMap(i => i); + const warnings = logs.warn.flatMap((i) => i); expect(warnings).toContain( '"optimize.lazy" is deprecated and has been replaced by "optimize.watch"' ); diff --git a/src/core/server/config/raw_config_service.test.ts b/src/core/server/config/raw_config_service.test.ts index f02c31d4659ca..8846ea3847f79 100644 --- a/src/core/server/config/raw_config_service.test.ts +++ b/src/core/server/config/raw_config_service.test.ts @@ -83,10 +83,7 @@ test('returns config at path as observable', async () => { configService.loadConfig(); - const exampleConfig = await configService - .getConfig$() - .pipe(first()) - .toPromise(); + const exampleConfig = await configService.getConfig$().pipe(first()).toPromise(); expect(exampleConfig.key).toEqual('value'); expect(Object.keys(exampleConfig)).toEqual(['key']); @@ -100,7 +97,7 @@ test("pushes new configs when reloading even if config at path hasn't changed", configService.loadConfig(); const valuesReceived: any[] = []; - configService.getConfig$().subscribe(config => { + configService.getConfig$().subscribe((config) => { valuesReceived.push(config); }); @@ -129,7 +126,7 @@ test('pushes new config when reloading and config at path has changed', async () configService.loadConfig(); const valuesReceived: any[] = []; - configService.getConfig$().subscribe(config => { + configService.getConfig$().subscribe((config) => { valuesReceived.push(config); }); @@ -145,7 +142,7 @@ test('pushes new config when reloading and config at path has changed', async () expect(Object.keys(valuesReceived[1])).toEqual(['key']); }); -test('completes config observables when stopped', done => { +test('completes config observables when stopped', (done) => { expect.assertions(0); mockGetConfigFromFiles.mockImplementation(() => ({ key: 'value' })); diff --git a/src/core/server/config/raw_config_service.ts b/src/core/server/config/raw_config_service.ts index 728d793f494a9..257ec612f3249 100644 --- a/src/core/server/config/raw_config_service.ts +++ b/src/core/server/config/raw_config_service.ts @@ -41,10 +41,10 @@ export class RawConfigService { constructor( public readonly configFiles: readonly string[], - configAdapter: RawConfigAdapter = rawConfig => rawConfig + configAdapter: RawConfigAdapter = (rawConfig) => rawConfig ) { this.config$ = this.rawConfigFromFile$.pipe( - map(rawConfig => { + map((rawConfig) => { if (isPlainObject(rawConfig)) { // TODO Make config consistent, e.g. handle dots in keys return configAdapter(cloneDeep(rawConfig)); diff --git a/src/core/server/core_app/integration_tests/default_route_provider_config.test.ts b/src/core/server/core_app/integration_tests/default_route_provider_config.test.ts index 2c7efe075152b..3284be5ba4750 100644 --- a/src/core/server/core_app/integration_tests/default_route_provider_config.test.ts +++ b/src/core/server/core_app/integration_tests/default_route_provider_config.test.ts @@ -44,7 +44,7 @@ describe('default route provider', () => { await root.shutdown(); }); - it('redirects to the configured default route respecting basePath', async function() { + it('redirects to the configured default route respecting basePath', async function () { const { status, header } = await kbnTestServer.request.get(root, '/'); expect(status).toEqual(302); @@ -53,7 +53,7 @@ describe('default route provider', () => { }); }); - it('ignores invalid values', async function() { + it('ignores invalid values', async function () { const invalidRoutes = [ 'http://not-your-kibana.com', '///example.com', @@ -75,7 +75,7 @@ describe('default route provider', () => { }); }); - it('consumes valid values', async function() { + it('consumes valid values', async function () { await kbnTestServer.request .post(root, '/api/kibana/settings/defaultRoute') .send({ value: '/valid' }) diff --git a/src/core/server/core_app/integration_tests/static_assets.test.ts b/src/core/server/core_app/integration_tests/static_assets.test.ts index aad2510ef8c0e..23125cb3a6704 100644 --- a/src/core/server/core_app/integration_tests/static_assets.test.ts +++ b/src/core/server/core_app/integration_tests/static_assets.test.ts @@ -19,17 +19,17 @@ import * as kbnTestServer from '../../../../test_utils/kbn_server'; import { Root } from '../../root'; -describe('Platform assets', function() { +describe('Platform assets', function () { let root: Root; - beforeAll(async function() { + beforeAll(async function () { root = kbnTestServer.createRoot(); await root.setup(); await root.start(); }); - afterAll(async function() { + afterAll(async function () { await root.shutdown(); }); @@ -37,15 +37,15 @@ describe('Platform assets', function() { await kbnTestServer.request.get(root, '/ui/favicons/favicon.ico').expect(200); }); - it('returns 404 if not found', async function() { + it('returns 404 if not found', async function () { await kbnTestServer.request.get(root, '/ui/favicons/not-a-favicon.ico').expect(404); }); - it('does not expose folder content', async function() { + it('does not expose folder content', async function () { await kbnTestServer.request.get(root, '/ui/favicons/').expect(403); }); - it('does not allow file tree traversing', async function() { + it('does not allow file tree traversing', async function () { await kbnTestServer.request.get(root, '/ui/../../../../../README.md').expect(404); }); }); diff --git a/src/core/server/elasticsearch/elasticsearch_config.test.ts b/src/core/server/elasticsearch/elasticsearch_config.test.ts index cb4501a51e849..ccd5fd0c7a571 100644 --- a/src/core/server/elasticsearch/elasticsearch_config.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_config.test.ts @@ -35,11 +35,11 @@ const applyElasticsearchDeprecations = (settings: Record = {}) => { _config[CONFIG_PATH] = settings; const migrated = applyDeprecations( _config, - deprecations.map(deprecation => ({ + deprecations.map((deprecation) => ({ deprecation, path: CONFIG_PATH, })), - msg => deprecationMessages.push(msg) + (msg) => deprecationMessages.push(msg) ); return { messages: deprecationMessages, diff --git a/src/core/server/elasticsearch/elasticsearch_config.ts b/src/core/server/elasticsearch/elasticsearch_config.ts index c87c94bcd0b6a..cac8c75a04486 100644 --- a/src/core/server/elasticsearch/elasticsearch_config.ts +++ b/src/core/server/elasticsearch/elasticsearch_config.ts @@ -51,7 +51,7 @@ export const configSchema = schema.object({ schema.contextRef('dist'), false, schema.string({ - validate: rawConfig => { + validate: (rawConfig) => { if (rawConfig === 'elastic') { return ( 'value of "elastic" is forbidden. This is a superuser account that can obfuscate ' + @@ -96,7 +96,7 @@ export const configSchema = schema.object({ alwaysPresentCertificate: schema.boolean({ defaultValue: false }), }, { - validate: rawConfig => { + validate: (rawConfig) => { if (rawConfig.key && rawConfig.keystore.path) { return 'cannot use [key] when [keystore.path] is specified'; } @@ -112,7 +112,7 @@ export const configSchema = schema.object({ schema.contextRef('dev'), false, schema.boolean({ - validate: rawValue => { + validate: (rawValue) => { if (rawValue === true) { return '"ignoreVersionMismatch" can only be set to true in development mode'; } diff --git a/src/core/server/elasticsearch/elasticsearch_service.test.ts b/src/core/server/elasticsearch/elasticsearch_service.test.ts index 2667859f303d4..26144eaaa4afa 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.test.ts @@ -34,7 +34,7 @@ import { elasticsearchServiceMock } from './elasticsearch_service.mock'; import { duration } from 'moment'; const delay = async (durationMs: number) => - await new Promise(resolve => setTimeout(resolve, durationMs)); + await new Promise((resolve) => setTimeout(resolve, durationMs)); let elasticsearchService: ElasticsearchService; const configService = configServiceMock.create(); @@ -217,7 +217,7 @@ describe('#setup', () => { }); }); - it('esNodeVersionCompatibility$ only starts polling when subscribed to', async done => { + it('esNodeVersionCompatibility$ only starts polling when subscribed to', async (done) => { const mockAdminClusterClientInstance = elasticsearchServiceMock.createClusterClient(); const mockDataClusterClientInstance = elasticsearchServiceMock.createClusterClient(); MockClusterClient.mockImplementationOnce( @@ -236,7 +236,7 @@ describe('#setup', () => { }); }); - it('esNodeVersionCompatibility$ stops polling when unsubscribed from', async done => { + it('esNodeVersionCompatibility$ stops polling when unsubscribed from', async (done) => { const mockAdminClusterClientInstance = elasticsearchServiceMock.createClusterClient(); const mockDataClusterClientInstance = elasticsearchServiceMock.createClusterClient(); MockClusterClient.mockImplementationOnce( @@ -272,7 +272,7 @@ describe('#stop', () => { expect(mockDataClusterClientInstance.close).toHaveBeenCalledTimes(1); }); - it('stops pollEsNodeVersions even if there are active subscriptions', async done => { + it('stops pollEsNodeVersions even if there are active subscriptions', async (done) => { expect.assertions(2); const mockAdminClusterClientInstance = elasticsearchServiceMock.createCustomClusterClient(); const mockDataClusterClientInstance = elasticsearchServiceMock.createCustomClusterClient(); diff --git a/src/core/server/elasticsearch/elasticsearch_service.ts b/src/core/server/elasticsearch/elasticsearch_service.ts index 18725f04a05b5..ab9c9e11fedc8 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.ts @@ -77,7 +77,7 @@ export class ElasticsearchService this.log = coreContext.logger.get('elasticsearch-service'); this.config$ = coreContext.configService .atPath('elasticsearch') - .pipe(map(rawConfig => new ElasticsearchConfig(rawConfig))); + .pipe(map((rawConfig) => new ElasticsearchConfig(rawConfig))); } public async setup(deps: SetupDeps): Promise { @@ -93,8 +93,8 @@ export class ElasticsearchService return true; }), switchMap( - config => - new Observable(subscriber => { + (config) => + new Observable((subscriber) => { this.log.debug(`Creating elasticsearch clients`); const coreClients = { @@ -120,8 +120,8 @@ export class ElasticsearchService const config = await this.config$.pipe(first()).toPromise(); - const adminClient$ = clients$.pipe(map(clients => clients.adminClient)); - const dataClient$ = clients$.pipe(map(clients => clients.dataClient)); + const adminClient$ = clients$.pipe(map((clients) => clients.adminClient)); + const dataClient$ = clients$.pipe(map((clients) => clients.dataClient)); this.adminClient = { async callAsInternalUser( @@ -189,7 +189,7 @@ export class ElasticsearchService }; return { - legacy: { config$: clients$.pipe(map(clients => clients.config)) }, + legacy: { config$: clients$.pipe(map((clients) => clients.config)) }, esNodesCompatibility$, adminClient: this.adminClient, dataClient, diff --git a/src/core/server/elasticsearch/retry_call_cluster.test.ts b/src/core/server/elasticsearch/retry_call_cluster.test.ts index 4f391f0aba34b..8be138e6752d2 100644 --- a/src/core/server/elasticsearch/retry_call_cluster.test.ts +++ b/src/core/server/elasticsearch/retry_call_cluster.test.ts @@ -75,7 +75,7 @@ describe('migrationsRetryCallCluster', () => { loggingServiceMock.clear(mockLogger); }); - errors.forEach(errorName => { + errors.forEach((errorName) => { it('retries ES API calls that rejects with ' + errorName, () => { expect.assertions(1); const callEsApi = jest.fn(); diff --git a/src/core/server/elasticsearch/retry_call_cluster.ts b/src/core/server/elasticsearch/retry_call_cluster.ts index 901b801159cb6..aa3e39d948593 100644 --- a/src/core/server/elasticsearch/retry_call_cluster.ts +++ b/src/core/server/elasticsearch/retry_call_cluster.ts @@ -47,7 +47,7 @@ export function migrationsRetryCallCluster( return (endpoint: string, clientParams: Record = {}, options?: CallAPIOptions) => { return defer(() => apiCaller(endpoint, clientParams, options)) .pipe( - retryWhen(error$ => + retryWhen((error$) => error$.pipe( concatMap((error, i) => { if (!previousErrors.includes(error.message)) { @@ -90,7 +90,7 @@ export function retryCallCluster(apiCaller: APICaller) { return (endpoint: string, clientParams: Record = {}, options?: CallAPIOptions) => { return defer(() => apiCaller(endpoint, clientParams, options)) .pipe( - retryWhen(errors => + retryWhen((errors) => errors.pipe( concatMap((error, i) => iif( diff --git a/src/core/server/elasticsearch/scoped_cluster_client.ts b/src/core/server/elasticsearch/scoped_cluster_client.ts index 920d236935261..4b64bfba15190 100644 --- a/src/core/server/elasticsearch/scoped_cluster_client.ts +++ b/src/core/server/elasticsearch/scoped_cluster_client.ts @@ -89,7 +89,7 @@ export class ScopedClusterClient implements IScopedClusterClient { const customHeaders: any = clientParams.headers; if (isObject(customHeaders)) { const duplicates = intersection(Object.keys(defaultHeaders), Object.keys(customHeaders)); - duplicates.forEach(duplicate => { + duplicates.forEach((duplicate) => { if (defaultHeaders[duplicate] !== (customHeaders as any)[duplicate]) { throw Error(`Cannot override default header ${duplicate}.`); } diff --git a/src/core/server/elasticsearch/status.test.ts b/src/core/server/elasticsearch/status.test.ts index dd5fb04bfd1c6..ef7ca7cd04608 100644 --- a/src/core/server/elasticsearch/status.test.ts +++ b/src/core/server/elasticsearch/status.test.ts @@ -38,11 +38,7 @@ const nodeInfo = { describe('calculateStatus', () => { it('starts in unavailable', async () => { - expect( - await calculateStatus$(new Subject()) - .pipe(take(1)) - .toPromise() - ).toEqual({ + expect(await calculateStatus$(new Subject()).pipe(take(1)).toPromise()).toEqual({ level: ServiceStatusLevels.unavailable, summary: 'Waiting for Elasticsearch', meta: { @@ -123,7 +119,7 @@ describe('calculateStatus', () => { const nodeCompat$ = new Subject(); const statusUpdates: ServiceStatus[] = []; - const subscription = calculateStatus$(nodeCompat$).subscribe(status => + const subscription = calculateStatus$(nodeCompat$).subscribe((status) => statusUpdates.push(status) ); diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts index 4989c4a31295c..a4cf0ffd58088 100644 --- a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts +++ b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts @@ -30,7 +30,7 @@ const KIBANA_VERSION = '5.1.0'; function createNodes(...versions: string[]): NodesInfo { const nodes = {} as any; versions - .map(version => { + .map((version) => { return { version, http: { @@ -121,7 +121,7 @@ describe('pollEsNodesVersion', () => { callWithInternalUser.mockClear(); }); - it('returns iscCompatible=false and keeps polling when a poll request throws', done => { + it('returns iscCompatible=false and keeps polling when a poll request throws', (done) => { expect.assertions(3); const expectedCompatibilityResults = [false, false, true]; jest.clearAllMocks(); @@ -137,7 +137,7 @@ describe('pollEsNodesVersion', () => { }) .pipe(take(3)) .subscribe({ - next: result => { + next: (result) => { expect(result.isCompatible).toBe(expectedCompatibilityResults.shift()); }, complete: done, @@ -145,7 +145,7 @@ describe('pollEsNodesVersion', () => { }); }); - it('returns compatibility results', done => { + it('returns compatibility results', (done) => { expect.assertions(1); const nodes = createNodes('5.1.0', '5.2.0', '5.0.0'); callWithInternalUser.mockResolvedValueOnce(nodes); @@ -158,7 +158,7 @@ describe('pollEsNodesVersion', () => { }) .pipe(take(1)) .subscribe({ - next: result => { + next: (result) => { expect(result).toEqual(mapNodesVersionCompatibility(nodes, KIBANA_VERSION, false)); }, complete: done, @@ -166,7 +166,7 @@ describe('pollEsNodesVersion', () => { }); }); - it('only emits if the node versions changed since the previous poll', done => { + it('only emits if the node versions changed since the previous poll', (done) => { expect.assertions(4); callWithInternalUser.mockResolvedValueOnce(createNodes('5.1.0', '5.2.0', '5.0.0')); // emit callWithInternalUser.mockResolvedValueOnce(createNodes('5.0.0', '5.1.0', '5.2.0')); // ignore, same versions, different ordering @@ -184,7 +184,7 @@ describe('pollEsNodesVersion', () => { }) .pipe(take(4)) .subscribe({ - next: result => expect(result).toBeDefined(), + next: (result) => expect(result).toBeDefined(), complete: done, error: done, }); diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.ts index 7bd6331978d1d..776298e5869a0 100644 --- a/src/core/server/elasticsearch/version_check/ensure_es_version.ts +++ b/src/core/server/elasticsearch/version_check/ensure_es_version.ts @@ -83,32 +83,32 @@ export function mapNodesVersionCompatibility( } const nodes = Object.keys(nodesInfo.nodes) .sort() // Sorting ensures a stable node ordering for comparison - .map(key => nodesInfo.nodes[key]) - .map(node => Object.assign({}, node, { name: getHumanizedNodeName(node) })); + .map((key) => nodesInfo.nodes[key]) + .map((node) => Object.assign({}, node, { name: getHumanizedNodeName(node) })); // Aggregate incompatible ES nodes. const incompatibleNodes = nodes.filter( - node => !esVersionCompatibleWithKibana(node.version, kibanaVersion) + (node) => !esVersionCompatibleWithKibana(node.version, kibanaVersion) ); // Aggregate ES nodes which should prompt a Kibana upgrade. It's acceptable // if ES and Kibana versions are not the same as long as they are not // incompatible, but we should warn about it. // Ignore version qualifiers https://github.com/elastic/elasticsearch/issues/36859 - const warningNodes = nodes.filter(node => !esVersionEqualsKibana(node.version, kibanaVersion)); + const warningNodes = nodes.filter((node) => !esVersionEqualsKibana(node.version, kibanaVersion)); // Note: If incompatible and warning nodes are present `message` only contains // an incompatibility notice. let message; if (incompatibleNodes.length > 0) { - const incompatibleNodeNames = incompatibleNodes.map(node => node.name).join(', '); + const incompatibleNodeNames = incompatibleNodes.map((node) => node.name).join(', '); if (ignoreVersionMismatch) { message = `Ignoring version incompatibility between Kibana v${kibanaVersion} and the following Elasticsearch nodes: ${incompatibleNodeNames}`; } else { message = `This version of Kibana (v${kibanaVersion}) is incompatible with the following Elasticsearch nodes in your cluster: ${incompatibleNodeNames}`; } } else if (warningNodes.length > 0) { - const warningNodeNames = warningNodes.map(node => node.name).join(', '); + const warningNodeNames = warningNodes.map((node) => node.name).join(', '); message = `You're running Kibana ${kibanaVersion} with some different versions of ` + 'Elasticsearch. Update Kibana or Elasticsearch to the same ' + @@ -151,7 +151,7 @@ export const pollEsNodesVersion = ({ filterPath: ['nodes.*.version', 'nodes.*.http.publish_address', 'nodes.*.ip'], }) ).pipe( - catchError(_err => { + catchError((_err) => { return of({ nodes: {} }); }) ); diff --git a/src/core/server/http/auth_headers_storage.ts b/src/core/server/http/auth_headers_storage.ts index 469e194a61fed..f532afc8b4bc7 100644 --- a/src/core/server/http/auth_headers_storage.ts +++ b/src/core/server/http/auth_headers_storage.ts @@ -33,7 +33,7 @@ export class AuthHeadersStorage { public set = (request: KibanaRequest | LegacyRequest, headers: AuthHeaders) => { this.authHeadersCache.set(ensureRawRequest(request), headers); }; - public get: GetAuthHeaders = request => { + public get: GetAuthHeaders = (request) => { return this.authHeadersCache.get(ensureRawRequest(request)); }; } diff --git a/src/core/server/http/auth_state_storage.ts b/src/core/server/http/auth_state_storage.ts index 10c8ccca32401..1172f06d06ab3 100644 --- a/src/core/server/http/auth_state_storage.ts +++ b/src/core/server/http/auth_state_storage.ts @@ -71,7 +71,7 @@ export class AuthStateStorage { return { status, state }; }; - public isAuthenticated: IsAuthenticated = request => { + public isAuthenticated: IsAuthenticated = (request) => { return this.get(request).status === AuthStatus.authenticated; }; } diff --git a/src/core/server/http/base_path_proxy_server.ts b/src/core/server/http/base_path_proxy_server.ts index acefbd00ae2be..ffbdabadd03f7 100644 --- a/src/core/server/http/base_path_proxy_server.ts +++ b/src/core/server/http/base_path_proxy_server.ts @@ -180,9 +180,7 @@ export class BasePathProxyServer { // condition is met (e.g. until target listener is ready). async (request, responseToolkit) => { apm.setTransactionName(`${request.method.toUpperCase()} /{basePath}/{kbnPath*}`); - await delayUntil() - .pipe(take(1)) - .toPromise(); + await delayUntil().pipe(take(1)).toPromise(); return responseToolkit.continue; }, ], @@ -216,9 +214,7 @@ export class BasePathProxyServer { // Before we proxy request to a target port we may want to wait until some // condition is met (e.g. until target listener is ready). async (request, responseToolkit) => { - await delayUntil() - .pipe(take(1)) - .toPromise(); + await delayUntil().pipe(take(1)).toPromise(); return responseToolkit.continue; }, ], diff --git a/src/core/server/http/base_path_service.ts b/src/core/server/http/base_path_service.ts index 5b5901b0ad6fb..093d73b2da3bf 100644 --- a/src/core/server/http/base_path_service.ts +++ b/src/core/server/http/base_path_service.ts @@ -69,7 +69,7 @@ export class BasePath { */ public prepend = (path: string): string => { if (this.serverBasePath === '') return path; - return modifyUrl(path, parts => { + return modifyUrl(path, (parts) => { if (!parts.hostname && parts.pathname && parts.pathname.startsWith('/')) { parts.pathname = `${this.serverBasePath}${parts.pathname}`; } diff --git a/src/core/server/http/cookie_session_storage.test.ts b/src/core/server/http/cookie_session_storage.test.ts index 0ca87eae6e235..a5612675c37de 100644 --- a/src/core/server/http/cookie_session_storage.test.ts +++ b/src/core/server/http/cookie_session_storage.test.ts @@ -101,7 +101,7 @@ const userData = { id: '42' }; const sessionDurationMs = 1000; const path = '/'; const sessVal = () => ({ value: userData, expires: Date.now() + sessionDurationMs, path }); -const delay = (ms: number) => new Promise(res => setTimeout(res, ms)); +const delay = (ms: number) => new Promise((res) => setTimeout(res, ms)); const cookieOptions = { name: 'sid', encryptionKey: 'something_at_least_32_characters', @@ -135,9 +135,7 @@ describe('Cookie based SessionStorage', () => { ); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(200); + const response = await supertest(innerServer.listener).get('/').expect(200); const cookies = response.get('set-cookie'); expect(cookies).toBeDefined(); @@ -174,9 +172,7 @@ describe('Cookie based SessionStorage', () => { ); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(200); + const response = await supertest(innerServer.listener).get('/').expect(200); const cookies = response.get('set-cookie'); expect(cookies).toBeDefined(); @@ -207,9 +203,7 @@ describe('Cookie based SessionStorage', () => { ); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(200, { value: null }); + const response = await supertest(innerServer.listener).get('/').expect(200, { value: null }); const cookies = response.get('set-cookie'); expect(cookies).not.toBeDefined(); @@ -414,9 +408,7 @@ describe('Cookie based SessionStorage', () => { ); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(200); + const response = await supertest(innerServer.listener).get('/').expect(200); const cookies = response.get('set-cookie'); const sessionCookie = retrieveSessionCookie(cookies[0]); diff --git a/src/core/server/http/http_config.ts b/src/core/server/http/http_config.ts index 7c72e3270743e..289b6539fd762 100644 --- a/src/core/server/http/http_config.ts +++ b/src/core/server/http/http_config.ts @@ -103,7 +103,7 @@ export const config = { }), }, { - validate: rawConfig => { + validate: (rawConfig) => { if (!rawConfig.basePath && rawConfig.rewriteBasePath) { return 'cannot use [rewriteBasePath] when [basePath] is not specified'; } @@ -157,7 +157,7 @@ export class HttpConfig { (headers, [key, value]) => { return { ...headers, - [key]: Array.isArray(value) ? value.map(e => convertHeader(e)) : convertHeader(value), + [key]: Array.isArray(value) ? value.map((e) => convertHeader(e)) : convertHeader(value), }; }, {} diff --git a/src/core/server/http/http_server.test.ts b/src/core/server/http/http_server.test.ts index 4fb433b5c77ba..1798c3a921da4 100644 --- a/src/core/server/http/http_server.test.ts +++ b/src/core/server/http/http_server.test.ts @@ -163,7 +163,7 @@ test('valid params', async () => { await supertest(innerServer.listener) .get('/foo/some-string') .expect(200) - .then(res => { + .then((res) => { expect(res.text).toBe('some-string'); }); }); @@ -193,7 +193,7 @@ test('invalid params', async () => { await supertest(innerServer.listener) .get('/foo/some-string') .expect(400) - .then(res => { + .then((res) => { expect(res.body).toEqual({ error: 'Bad Request', statusCode: 400, @@ -228,7 +228,7 @@ test('valid query', async () => { await supertest(innerServer.listener) .get('/foo/?bar=test&quux=123') .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', quux: 123 }); }); }); @@ -258,7 +258,7 @@ test('invalid query', async () => { await supertest(innerServer.listener) .get('/foo/?bar=test') .expect(400) - .then(res => { + .then((res) => { expect(res.body).toEqual({ error: 'Bad Request', statusCode: 400, @@ -297,7 +297,7 @@ test('valid body', async () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', baz: 123 }); }); }); @@ -335,7 +335,7 @@ test('valid body with validate function', async () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', baz: 123 }); }); }); @@ -378,7 +378,7 @@ test('not inline validation - specifying params', async () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', baz: 123 }); }); }); @@ -421,7 +421,7 @@ test('not inline validation - specifying validation handler', async () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', baz: 123 }); }); }); @@ -471,7 +471,7 @@ test('not inline handler - KibanaRequest', async () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'TEST', baz: '123' }); }); }); @@ -520,7 +520,7 @@ test('not inline handler - RequestHandler', async () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'TEST', baz: '123' }); }); }); @@ -551,7 +551,7 @@ test('invalid body', async () => { .post('/foo/') .send({ bar: 'test' }) .expect(400) - .then(res => { + .then((res) => { expect(res.body).toEqual({ error: 'Bad Request', statusCode: 400, @@ -586,7 +586,7 @@ test('handles putting', async () => { .put('/foo/') .send({ key: 'new value' }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ key: 'new value' }); }); }); @@ -616,7 +616,7 @@ test('handles deleting', async () => { await supertest(innerServer.listener) .delete('/foo/3') .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ key: 3 }); }); }); @@ -646,28 +646,22 @@ describe('with `basepath: /bar` and `rewriteBasePath: false`', () => { }); test('/bar => 404', async () => { - await supertest(innerServerListener) - .get('/bar') - .expect(404); + await supertest(innerServerListener).get('/bar').expect(404); }); test('/bar/ => 404', async () => { - await supertest(innerServerListener) - .get('/bar/') - .expect(404); + await supertest(innerServerListener).get('/bar/').expect(404); }); test('/bar/foo => 404', async () => { - await supertest(innerServerListener) - .get('/bar/foo') - .expect(404); + await supertest(innerServerListener).get('/bar/foo').expect(404); }); test('/ => /', async () => { await supertest(innerServerListener) .get('/') .expect(200) - .then(res => { + .then((res) => { expect(res.text).toBe('value:/'); }); }); @@ -676,7 +670,7 @@ describe('with `basepath: /bar` and `rewriteBasePath: false`', () => { await supertest(innerServerListener) .get('/foo') .expect(200) - .then(res => { + .then((res) => { expect(res.text).toBe('value:/foo'); }); }); @@ -710,7 +704,7 @@ describe('with `basepath: /bar` and `rewriteBasePath: true`', () => { await supertest(innerServerListener) .get('/bar') .expect(200) - .then(res => { + .then((res) => { expect(res.text).toBe('value:/'); }); }); @@ -719,7 +713,7 @@ describe('with `basepath: /bar` and `rewriteBasePath: true`', () => { await supertest(innerServerListener) .get('/bar/') .expect(200) - .then(res => { + .then((res) => { expect(res.text).toBe('value:/'); }); }); @@ -728,21 +722,17 @@ describe('with `basepath: /bar` and `rewriteBasePath: true`', () => { await supertest(innerServerListener) .get('/bar/foo') .expect(200) - .then(res => { + .then((res) => { expect(res.text).toBe('value:/foo'); }); }); test('/ => 404', async () => { - await supertest(innerServerListener) - .get('/') - .expect(404); + await supertest(innerServerListener).get('/').expect(404); }); test('/foo => 404', async () => { - await supertest(innerServerListener) - .get('/foo') - .expect(404); + await supertest(innerServerListener).get('/foo').expect(404); }); }); @@ -787,13 +777,9 @@ test('allows attaching metadata to attach meta-data tag strings to a route', asy registerRouter(router); await server.start(); - await supertest(innerServer.listener) - .get('/with-tags') - .expect(200, { tags }); + await supertest(innerServer.listener).get('/with-tags').expect(200, { tags }); - await supertest(innerServer.listener) - .get('/without-tags') - .expect(200, { tags: [] }); + await supertest(innerServer.listener).get('/without-tags').expect(200, { tags: [] }); }); test('exposes route details of incoming request to a route handler', async () => { @@ -835,9 +821,7 @@ describe('conditional compression', () => { test('with `compression.enabled: true`', async () => { const listener = await setupServer(config); - const response = await supertest(listener) - .get('/') - .set('accept-encoding', 'gzip'); + const response = await supertest(listener).get('/').set('accept-encoding', 'gzip'); expect(response.header).toHaveProperty('content-encoding', 'gzip'); }); @@ -848,9 +832,7 @@ describe('conditional compression', () => { compression: { enabled: false }, }); - const response = await supertest(listener) - .get('/') - .set('accept-encoding', 'gzip'); + const response = await supertest(listener).get('/').set('accept-encoding', 'gzip'); expect(response.header).not.toHaveProperty('content-encoding'); }); @@ -865,9 +847,7 @@ describe('conditional compression', () => { }); test('enables compression for no referer', async () => { - const response = await supertest(listener) - .get('/') - .set('accept-encoding', 'gzip'); + const response = await supertest(listener).get('/').set('accept-encoding', 'gzip'); expect(response.header).toHaveProperty('content-encoding', 'gzip'); }); @@ -952,14 +932,11 @@ describe('body options', () => { registerRouter(router); await server.start(); - await supertest(innerServer.listener) - .post('/') - .send({ test: 1 }) - .expect(415, { - statusCode: 415, - error: 'Unsupported Media Type', - message: 'Unsupported Media Type', - }); + await supertest(innerServer.listener).post('/').send({ test: 1 }).expect(415, { + statusCode: 415, + error: 'Unsupported Media Type', + message: 'Unsupported Media Type', + }); }); test('should reject the request because the payload is too large', async () => { @@ -977,14 +954,11 @@ describe('body options', () => { registerRouter(router); await server.start(); - await supertest(innerServer.listener) - .post('/') - .send({ test: 1 }) - .expect(413, { - statusCode: 413, - error: 'Request Entity Too Large', - message: 'Payload content length greater than maximum allowed: 1', - }); + await supertest(innerServer.listener).post('/').send({ test: 1 }).expect(413, { + statusCode: 413, + error: 'Request Entity Too Large', + message: 'Payload content length greater than maximum allowed: 1', + }); }); test('should not parse the content in the request', async () => { @@ -1010,14 +984,11 @@ describe('body options', () => { registerRouter(router); await server.start(); - await supertest(innerServer.listener) - .post('/') - .send({ test: 1 }) - .expect(200, { - parse: false, - maxBytes: 1024, // hapi populates the default - output: 'data', - }); + await supertest(innerServer.listener).post('/').send({ test: 1 }).expect(200, { + parse: false, + maxBytes: 1024, // hapi populates the default + output: 'data', + }); }); }); @@ -1043,14 +1014,11 @@ test('should return a stream in the body', async () => { registerRouter(router); await server.start(); - await supertest(innerServer.listener) - .put('/') - .send({ test: 1 }) - .expect(200, { - parse: true, - maxBytes: 1024, // hapi populates the default - output: 'stream', - }); + await supertest(innerServer.listener).put('/').send({ test: 1 }).expect(200, { + parse: true, + maxBytes: 1024, // hapi populates the default + output: 'stream', + }); }); describe('setup contract', () => { diff --git a/src/core/server/http/http_server.ts b/src/core/server/http/http_server.ts index 92ac5220735a1..8089ee901fa65 100644 --- a/src/core/server/http/http_server.ts +++ b/src/core/server/http/http_server.ts @@ -176,7 +176,7 @@ export class HttpServer { // validation applied in ./http_tools#getServerOptions // (All NP routes are already required to specify their own validation in order to access the payload) validate, - payload: [allow, maxBytes, output, parse].some(v => typeof v !== 'undefined') + payload: [allow, maxBytes, output, parse].some((v) => typeof v !== 'undefined') ? { allow, maxBytes, output, parse } : undefined, }, diff --git a/src/core/server/http/http_tools.test.ts b/src/core/server/http/http_tools.test.ts index bdaab4f2999ed..79a1e32d1b51e 100644 --- a/src/core/server/http/http_tools.test.ts +++ b/src/core/server/http/http_tools.test.ts @@ -81,7 +81,7 @@ describe('timeouts', () => { test('closes sockets on timeout', async () => { const router = new Router('', logger.get(), enhanceWithContext); router.get({ path: '/a', validate: false }, async (context, req, res) => { - await new Promise(resolve => setTimeout(resolve, 2000)); + await new Promise((resolve) => setTimeout(resolve, 2000)); return res.ok({}); }); router.get({ path: '/b', validate: false }, (context, req, res) => res.ok({})); @@ -98,9 +98,7 @@ describe('timeouts', () => { expect(supertest(innerServer.listener).get('/a')).rejects.toThrow('socket hang up'); - await supertest(innerServer.listener) - .get('/b') - .expect(200); + await supertest(innerServer.listener).get('/b').expect(200); }); afterAll(async () => { diff --git a/src/core/server/http/http_tools.ts b/src/core/server/http/http_tools.ts index 6e785ae9f8f00..4e47cf492e287 100644 --- a/src/core/server/http/http_tools.ts +++ b/src/core/server/http/http_tools.ts @@ -53,7 +53,7 @@ export function getServerOptions(config: HttpConfig, { configureTLS = true } = { // This is a default payload validation which applies to all LP routes which do not specify their own // `validate.payload` handler, in order to reduce the likelyhood of prototype pollution vulnerabilities. // (All NP routes are already required to specify their own validation in order to access the payload) - payload: value => Promise.resolve(validateObject(value)), + payload: (value) => Promise.resolve(validateObject(value)), }, }, state: { @@ -104,7 +104,7 @@ export function createServer(serverOptions: ServerOptions, listenerOptions: List server.listener.keepAliveTimeout = listenerOptions.keepaliveTimeout; server.listener.setTimeout(listenerOptions.socketTimeout); - server.listener.on('timeout', socket => { + server.listener.on('timeout', (socket) => { socket.destroy(); }); server.listener.on('clientError', (err, socket) => { @@ -155,7 +155,7 @@ export function defaultValidationErrorHandler( const validationError: HapiValidationError = err as HapiValidationError; const validationKeys: string[] = []; - validationError.details.forEach(detail => { + validationError.details.forEach((detail) => { if (detail.path.length > 0) { validationKeys.push(Hoek.escapeHtml(detail.path.join('.'))); } else { diff --git a/src/core/server/http/https_redirect_server.test.ts b/src/core/server/http/https_redirect_server.test.ts index e7cd653bb9eec..a7d3cbe41aa3d 100644 --- a/src/core/server/http/https_redirect_server.test.ts +++ b/src/core/server/http/https_redirect_server.test.ts @@ -100,7 +100,7 @@ test('forwards http requests to https', async () => { await supertest(getServerListener(server)) .get('/') .expect(302) - .then(res => { + .then((res) => { expect(res.header.location).toEqual(`https://${config.host}:${config.port}/`); }); }); diff --git a/src/core/server/http/integration_tests/core_service.test.mocks.ts b/src/core/server/http/integration_tests/core_service.test.mocks.ts index b3adda8dd22d1..8e782970e2a8e 100644 --- a/src/core/server/http/integration_tests/core_service.test.mocks.ts +++ b/src/core/server/http/integration_tests/core_service.test.mocks.ts @@ -20,7 +20,7 @@ import { elasticsearchServiceMock } from '../../elasticsearch/elasticsearch_serv export const clusterClientMock = jest.fn(); jest.doMock('../../elasticsearch/scoped_cluster_client', () => ({ - ScopedClusterClient: clusterClientMock.mockImplementation(function() { + ScopedClusterClient: clusterClientMock.mockImplementation(function () { return elasticsearchServiceMock.createScopedClusterClient(); }), })); @@ -30,7 +30,7 @@ jest.doMock('elasticsearch', () => { return { ...realES, // eslint-disable-next-line object-shorthand - Client: function() { + Client: function () { return elasticsearchServiceMock.createElasticsearchClient(); }, }; diff --git a/src/core/server/http/integration_tests/lifecycle.test.ts b/src/core/server/http/integration_tests/lifecycle.test.ts index 0f0d54e88daca..73ed4e5de4b04 100644 --- a/src/core/server/http/integration_tests/lifecycle.test.ts +++ b/src/core/server/http/integration_tests/lifecycle.test.ts @@ -75,9 +75,7 @@ describe('OnPreAuth', () => { }); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, 'ok'); + await supertest(innerServer.listener).get('/').expect(200, 'ok'); expect(callingOrder).toEqual(['first', 'second']); }); @@ -108,9 +106,7 @@ describe('OnPreAuth', () => { await server.start(); - await supertest(innerServer.listener) - .get('/initial') - .expect(200, 'redirected'); + await supertest(innerServer.listener).get('/initial').expect(200, 'redirected'); expect(urlBeforeForwarding).toBe('/initial'); expect(urlAfterForwarding).toBe('/redirectUrl'); @@ -132,9 +128,7 @@ describe('OnPreAuth', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/initial') - .expect(302); + const result = await supertest(innerServer.listener).get('/initial').expect(302); expect(result.header.location).toBe(redirectUrl); }); @@ -154,9 +148,7 @@ describe('OnPreAuth', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.header['www-authenticate']).toBe('challenge'); }); @@ -172,9 +164,7 @@ describe('OnPreAuth', () => { }); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -195,9 +185,7 @@ describe('OnPreAuth', () => { registerOnPreAuth((req, res, t) => ({} as any)); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -232,9 +220,7 @@ describe('OnPreAuth', () => { await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { customField: 'undefined' }); + await supertest(innerServer.listener).get('/').expect(200, { customField: 'undefined' }); }); }); @@ -257,9 +243,7 @@ describe('OnPostAuth', () => { }); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, 'ok'); + await supertest(innerServer.listener).get('/').expect(200, 'ok'); expect(callingOrder).toEqual(['first', 'second']); }); @@ -280,9 +264,7 @@ describe('OnPostAuth', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/initial') - .expect(302); + const result = await supertest(innerServer.listener).get('/initial').expect(302); expect(result.header.location).toBe(redirectUrl); }); @@ -301,9 +283,7 @@ describe('OnPostAuth', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.header['www-authenticate']).toBe('challenge'); }); @@ -318,9 +298,7 @@ describe('OnPostAuth', () => { }); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -340,9 +318,7 @@ describe('OnPostAuth', () => { registerOnPostAuth((req, res, t) => ({} as any)); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -378,9 +354,7 @@ describe('OnPostAuth', () => { await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { customField: 'undefined' }); + await supertest(innerServer.listener).get('/').expect(200, { customField: 'undefined' }); }); }); @@ -410,9 +384,7 @@ describe('Auth', () => { registerAuth((req, res, t) => t.authenticated()); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { content: 'ok' }); + await supertest(innerServer.listener).get('/').expect(200, { content: 'ok' }); }); it('blocks access to a resource if credentials are not provided', async () => { @@ -425,9 +397,7 @@ describe('Auth', () => { registerAuth((req, res, t) => t.notHandled()); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.body.message).toBe('Unauthorized'); }); @@ -443,9 +413,7 @@ describe('Auth', () => { registerAuth(authenticate); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { authRequired: true }); + await supertest(innerServer.listener).get('/').expect(200, { authRequired: true }); expect(authenticate).toHaveBeenCalledTimes(1); }); @@ -463,9 +431,7 @@ describe('Auth', () => { registerAuth(authenticate); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { authRequired: false }); + await supertest(innerServer.listener).get('/').expect(200, { authRequired: false }); expect(authenticate).toHaveBeenCalledTimes(0); }); @@ -483,9 +449,7 @@ describe('Auth', () => { await registerAuth(authenticate); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { authRequired: true }); + await supertest(innerServer.listener).get('/').expect(200, { authRequired: true }); expect(authenticate).toHaveBeenCalledTimes(1); }); @@ -498,9 +462,7 @@ describe('Auth', () => { registerAuth((req, res) => res.unauthorized()); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(401); + await supertest(innerServer.listener).get('/').expect(401); }); it('supports redirecting', async () => { @@ -516,9 +478,7 @@ describe('Auth', () => { ); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(302); + const response = await supertest(innerServer.listener).get('/').expect(302); expect(response.header.location).toBe(redirectTo); }); @@ -530,9 +490,7 @@ describe('Auth', () => { registerAuth((req, res, t) => t.redirected({} as any)); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(500); + await supertest(innerServer.listener).get('/').expect(500); }); it(`doesn't expose internal error details`, async () => { @@ -545,9 +503,7 @@ describe('Auth', () => { }); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -582,9 +538,7 @@ describe('Auth', () => { await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(200); + const response = await supertest(innerServer.listener).get('/').expect(200); expect(response.header['set-cookie']).toBeDefined(); const cookies = response.header['set-cookie']; @@ -628,9 +582,7 @@ describe('Auth', () => { }); await server.start(); - const responseToSetCookie = await supertest(innerServer.listener) - .get('/') - .expect(200); + const responseToSetCookie = await supertest(innerServer.listener).get('/').expect(200); expect(responseToSetCookie.header['set-cookie']).toBeDefined(); @@ -680,10 +632,7 @@ describe('Auth', () => { await server.start(); const token = 'Basic: user:password'; - await supertest(innerServer.listener) - .get('/') - .set('Authorization', token) - .expect(200); + await supertest(innerServer.listener).get('/').set('Authorization', token).expect(200); expect(fromRegisterOnPreAuth).toEqual({}); expect(fromRegisterAuth).toEqual({ authorization: token }); @@ -705,9 +654,7 @@ describe('Auth', () => { router.get({ path: '/', validate: false }, (context, req, res) => res.ok()); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(200); + const response = await supertest(innerServer.listener).get('/').expect(200); expect(response.header['www-authenticate']).toBe(authResponseHeader['www-authenticate']); }); @@ -726,9 +673,7 @@ describe('Auth', () => { router.get({ path: '/', validate: false }, (context, req, res) => res.badRequest()); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(400); + const response = await supertest(innerServer.listener).get('/').expect(400); expect(response.header['www-authenticate']).toBe(authResponseHeader['www-authenticate']); }); @@ -755,9 +700,7 @@ describe('Auth', () => { ); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(200); + const response = await supertest(innerServer.listener).get('/').expect(200); expect(response.header['www-authenticate']).toBe('from auth interceptor'); expect(loggingServiceMock.collect(logger).warn).toMatchInlineSnapshot(` @@ -790,9 +733,7 @@ describe('Auth', () => { ); await server.start(); - const response = await supertest(innerServer.listener) - .get('/') - .expect(400); + const response = await supertest(innerServer.listener).get('/').expect(400); expect(response.header['www-authenticate']).toBe('from auth interceptor'); expect(loggingServiceMock.collect(logger).warn).toMatchInlineSnapshot(` @@ -819,9 +760,7 @@ describe('Auth', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/initial') - .expect(302); + const result = await supertest(innerServer.listener).get('/initial').expect(302); expect(result.header.location).toBe(redirectUrl); }); @@ -841,9 +780,7 @@ describe('Auth', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.header['www-authenticate']).toBe('challenge'); }); @@ -858,9 +795,7 @@ describe('Auth', () => { }); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -880,9 +815,7 @@ describe('Auth', () => { registerOnPostAuth((req, res, t) => ({} as any)); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -917,9 +850,7 @@ describe('Auth', () => { await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { customField: 'undefined' }); + await supertest(innerServer.listener).get('/').expect(200, { customField: 'undefined' }); }); }); @@ -944,9 +875,7 @@ describe('OnPreResponse', () => { }); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, 'ok'); + await supertest(innerServer.listener).get('/').expect(200, 'ok'); expect(callingOrder).toEqual(['first', 'second']); }); @@ -974,9 +903,7 @@ describe('OnPreResponse', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.header['x-kibana-header']).toBe('value'); expect(result.header['x-my-header']).toBe('foo'); @@ -1000,9 +927,7 @@ describe('OnPreResponse', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200); + await supertest(innerServer.listener).get('/').expect(200); expect(loggingServiceMock.collect(logger).warn).toMatchInlineSnapshot(` Array [ @@ -1025,9 +950,7 @@ describe('OnPreResponse', () => { }); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -1049,9 +972,7 @@ describe('OnPreResponse', () => { registerOnPreResponse((req, res, t) => ({} as any)); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -1078,8 +999,6 @@ describe('OnPreResponse', () => { await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200); + await supertest(innerServer.listener).get('/').expect(200); }); }); diff --git a/src/core/server/http/integration_tests/lifecycle_handlers.test.ts b/src/core/server/http/integration_tests/lifecycle_handlers.test.ts index b5364c616f17c..2120fb5b881de 100644 --- a/src/core/server/http/integration_tests/lifecycle_handlers.test.ts +++ b/src/core/server/http/integration_tests/lifecycle_handlers.test.ts @@ -94,9 +94,7 @@ describe('core lifecycle handlers', () => { }); it('accepts requests that do not include a version header', async () => { - await supertest(innerServer.listener) - .get(testRoute) - .expect(200, 'ok'); + await supertest(innerServer.listener).get(testRoute).expect(200, 'ok'); }); it('rejects requests with an incorrect version passed in the version header', async () => { @@ -122,9 +120,7 @@ describe('core lifecycle handlers', () => { }); it('adds the kbn-name header', async () => { - const result = await supertest(innerServer.listener) - .get(testRoute) - .expect(200, 'ok'); + const result = await supertest(innerServer.listener).get(testRoute).expect(200, 'ok'); const headers = result.header as Record; expect(headers).toEqual( expect.objectContaining({ @@ -134,9 +130,7 @@ describe('core lifecycle handlers', () => { }); it('adds the kbn-name header in case of error', async () => { - const result = await supertest(innerServer.listener) - .get(testErrorRoute) - .expect(400); + const result = await supertest(innerServer.listener).get(testErrorRoute).expect(400); const headers = result.header as Record; expect(headers).toEqual( expect.objectContaining({ @@ -146,17 +140,13 @@ describe('core lifecycle handlers', () => { }); it('adds the custom headers', async () => { - const result = await supertest(innerServer.listener) - .get(testRoute) - .expect(200, 'ok'); + const result = await supertest(innerServer.listener).get(testRoute).expect(200, 'ok'); const headers = result.header as Record; expect(headers).toEqual(expect.objectContaining({ 'some-header': 'some-value' })); }); it('adds the custom headers in case of error', async () => { - const result = await supertest(innerServer.listener) - .get(testErrorRoute) - .expect(400); + const result = await supertest(innerServer.listener).get(testErrorRoute).expect(400); const headers = result.header as Record; expect(headers).toEqual(expect.objectContaining({ 'some-header': 'some-value' })); }); @@ -176,7 +166,7 @@ describe('core lifecycle handlers', () => { return res.ok({ body: 'ok' }); }); - destructiveMethods.forEach(method => { + destructiveMethods.forEach((method) => { ((router as any)[method.toLowerCase()] as RouteRegistrar)( { path: testPath, validate: false }, (context, req, res) => { @@ -200,7 +190,7 @@ describe('core lifecycle handlers', () => { await server.start(); }); - nonDestructiveMethods.forEach(method => { + nonDestructiveMethods.forEach((method) => { describe(`When using non-destructive ${method} method`, () => { it('accepts requests without a token', async () => { await getSupertest(method.toLowerCase(), testPath).expect( @@ -217,7 +207,7 @@ describe('core lifecycle handlers', () => { }); }); - destructiveMethods.forEach(method => { + destructiveMethods.forEach((method) => { describe(`When using destructive ${method} method`, () => { it('accepts requests with the xsrf header', async () => { await getSupertest(method.toLowerCase(), testPath) diff --git a/src/core/server/http/integration_tests/request.test.ts b/src/core/server/http/integration_tests/request.test.ts index 85270174fbc04..d33757273042b 100644 --- a/src/core/server/http/integration_tests/request.test.ts +++ b/src/core/server/http/integration_tests/request.test.ts @@ -43,7 +43,7 @@ afterEach(async () => { await server.stop(); }); -const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); describe('KibanaRequest', () => { describe('auth', () => { describe('isAuthenticated', () => { @@ -56,11 +56,9 @@ describe('KibanaRequest', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - isAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + isAuthenticated: false, + }); }); it('returns false if not authenticated on a route with authRequired: "optional"', async () => { const { server: innerServer, createRouter, registerAuth } = await server.setup(setupDeps); @@ -72,11 +70,9 @@ describe('KibanaRequest', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - isAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + isAuthenticated: false, + }); }); it('returns false if redirected on a route with authRequired: "optional"', async () => { const { server: innerServer, createRouter, registerAuth } = await server.setup(setupDeps); @@ -88,11 +84,9 @@ describe('KibanaRequest', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - isAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + isAuthenticated: false, + }); }); it('returns true if authenticated on a route with authRequired: "optional"', async () => { const { server: innerServer, createRouter, registerAuth } = await server.setup(setupDeps); @@ -104,11 +98,9 @@ describe('KibanaRequest', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - isAuthenticated: true, - }); + await supertest(innerServer.listener).get('/').expect(200, { + isAuthenticated: true, + }); }); it('returns true if authenticated', async () => { const { server: innerServer, createRouter, registerAuth } = await server.setup(setupDeps); @@ -120,17 +112,15 @@ describe('KibanaRequest', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - isAuthenticated: true, - }); + await supertest(innerServer.listener).get('/').expect(200, { + isAuthenticated: true, + }); }); }); }); describe('events', () => { describe('aborted$', () => { - it('emits once and completes when request aborted', async done => { + it('emits once and completes when request aborted', async (done) => { expect.assertions(1); const { server: innerServer, createRouter } = await server.setup(setupDeps); const router = createRouter('/'); diff --git a/src/core/server/http/integration_tests/router.test.ts b/src/core/server/http/integration_tests/router.test.ts index af05229f86f20..8f3799b12eccb 100644 --- a/src/core/server/http/integration_tests/router.test.ts +++ b/src/core/server/http/integration_tests/router.test.ts @@ -65,12 +65,10 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - httpAuthIsAuthenticated: false, - requestIsAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + httpAuthIsAuthenticated: false, + requestIsAuthenticated: false, + }); }); it('Authenticated user has access to a route', async () => { @@ -94,12 +92,10 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - httpAuthIsAuthenticated: true, - requestIsAuthenticated: true, - }); + await supertest(innerServer.listener).get('/').expect(200, { + httpAuthIsAuthenticated: true, + requestIsAuthenticated: true, + }); }); it('User with no credentials can access a route', async () => { @@ -122,12 +118,10 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - httpAuthIsAuthenticated: false, - requestIsAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + httpAuthIsAuthenticated: false, + requestIsAuthenticated: false, + }); }); it('User with invalid credentials cannot access a route', async () => { @@ -142,9 +136,7 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(401); + await supertest(innerServer.listener).get('/').expect(401); }); it('does not redirect user and allows access to a resource', async () => { @@ -171,12 +163,10 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - httpAuthIsAuthenticated: false, - requestIsAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + httpAuthIsAuthenticated: false, + requestIsAuthenticated: false, + }); }); }); @@ -197,12 +187,10 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - httpAuthIsAuthenticated: false, - requestIsAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + httpAuthIsAuthenticated: false, + requestIsAuthenticated: false, + }); }); it('Authenticated user has access to a route', async () => { @@ -226,12 +214,10 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - httpAuthIsAuthenticated: true, - requestIsAuthenticated: true, - }); + await supertest(innerServer.listener).get('/').expect(200, { + httpAuthIsAuthenticated: true, + requestIsAuthenticated: true, + }); }); it('User with no credentials cannot access a route', async () => { @@ -245,9 +231,7 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(401); + await supertest(innerServer.listener).get('/').expect(401); }); it('User with invalid credentials cannot access a route', async () => { @@ -262,9 +246,7 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(401); + await supertest(innerServer.listener).get('/').expect(401); }); it('allows redirecting an user', async () => { @@ -284,9 +266,7 @@ describe('Options', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(302); + const result = await supertest(innerServer.listener).get('/').expect(302); expect(result.header.location).toBe(redirectUrl); }); @@ -313,12 +293,10 @@ describe('Options', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200, { - httpAuthIsAuthenticated: false, - requestIsAuthenticated: false, - }); + await supertest(innerServer.listener).get('/').expect(200, { + httpAuthIsAuthenticated: false, + requestIsAuthenticated: false, + }); expect(authHook).toHaveBeenCalledTimes(0); }); @@ -352,9 +330,7 @@ describe('Cache-Control', () => { ); await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect('Cache-Control', 'public, max-age=1200'); + await supertest(innerServer.listener).get('/').expect('Cache-Control', 'public, max-age=1200'); }); }); @@ -368,9 +344,7 @@ describe('Handler', () => { }); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -391,9 +365,7 @@ describe('Handler', () => { }); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -412,9 +384,7 @@ describe('Handler', () => { router.get({ path: '/', validate: false }, (context, req, res) => 'ok' as any); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -501,11 +471,7 @@ describe('Handler', () => { ); await server.start(); - await supertest(innerServer.listener) - .post('/') - .type('json') - .send('12') - .expect(200); + await supertest(innerServer.listener).post('/').type('json').send('12').expect(200); expect(body).toEqual(12); }); @@ -524,9 +490,7 @@ describe('handleLegacyErrors', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(404); + const result = await supertest(innerServer.listener).get('/').expect(404); expect(result.body.message).toBe('Not Found'); }); @@ -546,9 +510,7 @@ describe('handleLegacyErrors', () => { ); await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body).toEqual({ error: 'Internal Server Error', @@ -570,9 +532,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.body).toEqual({ key: 'value' }); expect(result.header['content-type']).toBe('application/json; charset=utf-8'); @@ -588,9 +548,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.text).toBe('result'); expect(result.header['content-type']).toBe('text/html; charset=utf-8'); @@ -606,9 +564,7 @@ describe('Response factory', () => { await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(200); + await supertest(innerServer.listener).get('/').expect(200); }); it('supports answering with Stream', async () => { @@ -630,9 +586,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.text).toBe('abc'); expect(result.header['content-type']).toBe(undefined); @@ -646,7 +600,7 @@ describe('Response factory', () => { const stream = new Stream.PassThrough(); stream.write('a'); stream.write('b'); - setTimeout(function() { + setTimeout(function () { stream.write('c'); stream.end(); }, 100); @@ -656,9 +610,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.text).toBe('abc'); expect(result.header['transfer-encoding']).toBe('chunked'); @@ -681,10 +633,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200) - .buffer(true); + const result = await supertest(innerServer.listener).get('/').expect(200).buffer(true); expect(result.header['content-encoding']).toBe('binary'); expect(result.header['content-length']).toBe('1028'); @@ -708,10 +657,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200) - .buffer(true); + const result = await supertest(innerServer.listener).get('/').expect(200).buffer(true); expect(result.text).toBe('abc'); expect(result.header['content-length']).toBe('3'); @@ -733,9 +679,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.text).toEqual('value'); expect(result.header.etag).toBe('1234'); @@ -757,9 +701,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.text).toEqual('value'); expect(result.header.etag).toBe('1234'); @@ -781,9 +723,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.header.etag).toBe('1234'); }); @@ -803,9 +743,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.header['set-cookie']).toEqual(['foo', 'bar']); }); @@ -822,9 +760,7 @@ describe('Response factory', () => { await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(500); + await supertest(innerServer.listener).get('/').expect(500); // error happens within hapi when route handler already finished execution. expect(loggingServiceMock.collect(logger).error).toHaveLength(0); @@ -840,9 +776,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(200); + const result = await supertest(innerServer.listener).get('/').expect(200); expect(result.body).toEqual({ key: 'value' }); expect(result.header['content-type']).toBe('application/json; charset=utf-8'); @@ -858,9 +792,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(202); + const result = await supertest(innerServer.listener).get('/').expect(202); expect(result.body).toEqual({ location: 'somewhere' }); expect(result.header['content-type']).toBe('application/json; charset=utf-8'); @@ -876,9 +808,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(204); + const result = await supertest(innerServer.listener).get('/').expect(204); expect(result.noContent).toBe(true); }); @@ -901,9 +831,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(302); + const result = await supertest(innerServer.listener).get('/').expect(302); expect(result.text).toBe('The document has moved'); expect(result.header.location).toBe('/new-url'); @@ -924,9 +852,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -951,9 +877,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(400); + const result = await supertest(innerServer.listener).get('/').expect(400); expect(result.body).toEqual({ error: 'Bad Request', @@ -972,9 +896,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(400); + const result = await supertest(innerServer.listener).get('/').expect(400); expect(result.body).toEqual({ error: 'Bad Request', @@ -995,9 +917,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(400); + const result = await supertest(innerServer.listener).get('/').expect(400); expect(result.body).toEqual({ error: 'Bad Request', @@ -1040,7 +960,7 @@ describe('Response factory', () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', baz: 123 }); }); @@ -1051,7 +971,7 @@ describe('Response factory', () => { baz: '123', }) .expect(400) - .then(res => { + .then((res) => { expect(res.body).toEqual({ error: 'Bad Request', message: '[request body.body]: Wrong payload', @@ -1088,7 +1008,7 @@ describe('Response factory', () => { baz: 123, }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', baz: 123 }); }); @@ -1099,7 +1019,7 @@ describe('Response factory', () => { baz: '123', // Automatic casting happens }) .expect(200) - .then(res => { + .then((res) => { expect(res.body).toEqual({ bar: 'test', baz: 123 }); }); @@ -1110,7 +1030,7 @@ describe('Response factory', () => { baz: 'test', // Can't cast it into number }) .expect(400) - .then(res => { + .then((res) => { expect(res.body).toEqual({ error: 'Bad Request', message: '[request body.baz]: expected value of type [number] but got [string]', @@ -1135,9 +1055,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.body.message).toBe('no access'); expect(result.header['www-authenticate']).toBe('challenge'); @@ -1153,9 +1071,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.body.message).toBe('Unauthorized'); }); @@ -1171,9 +1087,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(403); + const result = await supertest(innerServer.listener).get('/').expect(403); expect(result.body.message).toBe('reason'); }); @@ -1188,9 +1102,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(403); + const result = await supertest(innerServer.listener).get('/').expect(403); expect(result.body.message).toBe('Forbidden'); }); @@ -1206,9 +1118,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(404); + const result = await supertest(innerServer.listener).get('/').expect(404); expect(result.body.message).toBe('file is not found'); }); @@ -1223,9 +1133,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(404); + const result = await supertest(innerServer.listener).get('/').expect(404); expect(result.body.message).toBe('Not Found'); }); @@ -1241,9 +1149,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(409); + const result = await supertest(innerServer.listener).get('/').expect(409); expect(result.body.message).toBe('stale version'); }); @@ -1258,9 +1164,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(409); + const result = await supertest(innerServer.listener).get('/').expect(409); expect(result.body.message).toBe('Conflict'); }); @@ -1279,9 +1183,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(418); + const result = await supertest(innerServer.listener).get('/').expect(418); expect(result.body).toEqual({ error: "I'm a teapot", @@ -1305,9 +1207,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body).toEqual({ error: 'Internal Server Error', @@ -1331,9 +1231,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body).toEqual({ error: 'Internal Server Error', @@ -1356,9 +1254,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body).toEqual({ error: 'Internal Server Error', @@ -1392,9 +1288,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(201); + const result = await supertest(innerServer.listener).get('/').expect(201); expect(result.header.location).toBe('somewhere'); }); @@ -1415,9 +1309,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(301); + const result = await supertest(innerServer.listener).get('/').expect(301); expect(result.header.location).toBe('/new-url'); }); @@ -1436,9 +1328,7 @@ describe('Response factory', () => { await server.start(); - await supertest(innerServer.listener) - .get('/') - .expect(500); + await supertest(innerServer.listener).get('/').expect(500); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` Array [ @@ -1463,9 +1353,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.body.message).toBe('unauthorized'); }); @@ -1486,9 +1374,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.body).toEqual({ error: 'Unauthorized', @@ -1514,9 +1400,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.body).toEqual({ error: 'Unauthorized', @@ -1540,9 +1424,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(401); + const result = await supertest(innerServer.listener).get('/').expect(401); expect(result.body.message).toBe('Unauthorized'); }); @@ -1560,9 +1442,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('reason'); expect(loggingServiceMock.collect(logger).error).toHaveLength(0); @@ -1581,9 +1461,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -1607,9 +1485,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -1632,9 +1508,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` @@ -1657,9 +1531,7 @@ describe('Response factory', () => { await server.start(); - const result = await supertest(innerServer.listener) - .get('/') - .expect(500); + const result = await supertest(innerServer.listener).get('/').expect(500); expect(result.body.message).toBe('An internal server error occurred.'); expect(loggingServiceMock.collect(logger).error).toMatchInlineSnapshot(` diff --git a/src/core/server/http/lifecycle/on_pre_response.ts b/src/core/server/http/lifecycle/on_pre_response.ts index 050881472bc80..9c8c6fba690d1 100644 --- a/src/core/server/http/lifecycle/on_pre_response.ts +++ b/src/core/server/http/lifecycle/on_pre_response.ts @@ -147,7 +147,7 @@ function findHeadersIntersection( headers: ResponseHeaders, log: Logger ) { - Object.keys(headers).forEach(headerName => { + Object.keys(headers).forEach((headerName) => { if (Reflect.has(responseHeaders, headerName)) { log.warn(`onPreResponseHandler rewrote a response header [${headerName}].`); } diff --git a/src/core/server/http/prototype_pollution/validate_object.test.ts b/src/core/server/http/prototype_pollution/validate_object.test.ts index 9e23d6cec6444..23d6c4ae3b49f 100644 --- a/src/core/server/http/prototype_pollution/validate_object.test.ts +++ b/src/core/server/http/prototype_pollution/validate_object.test.ts @@ -51,8 +51,8 @@ test(`fails on circular references`, () => { }, { constructor: { foo: { prototype: null } } }, { prototype: { foo: { constructor: null } } }, -].forEach(value => { - ['headers', 'payload', 'query', 'params'].forEach(property => { +].forEach((value) => { + ['headers', 'payload', 'query', 'params'].forEach((property) => { const obj = { [property]: value, }; @@ -72,7 +72,7 @@ test(`fails on circular references`, () => { JSON.parse(`{ "constructor": { "prototype" : null } }`), JSON.parse(`{ "foo": { "constructor": { "prototype" : null } } }`), JSON.parse(`{ "foo": { "bar": { "constructor": { "prototype" : null } } } }`), -].forEach(value => { +].forEach((value) => { test(`can't submit ${JSON.stringify(value)}`, () => { expect(() => validateObject(value)).toThrowErrorMatchingSnapshot(); }); diff --git a/src/core/server/http/router/error_wrapper.ts b/src/core/server/http/router/error_wrapper.ts index af99812eff4b3..75d0e0d630296 100644 --- a/src/core/server/http/router/error_wrapper.ts +++ b/src/core/server/http/router/error_wrapper.ts @@ -20,7 +20,7 @@ import Boom from 'boom'; import { RequestHandlerWrapper } from './router'; -export const wrapErrors: RequestHandlerWrapper = handler => { +export const wrapErrors: RequestHandlerWrapper = (handler) => { return async (context, request, response) => { try { return await handler(context, request, response); diff --git a/src/core/server/http/router/headers.ts b/src/core/server/http/router/headers.ts index b79cc0d325f1e..f27f5e937b2c0 100644 --- a/src/core/server/http/router/headers.ts +++ b/src/core/server/http/router/headers.ts @@ -71,7 +71,7 @@ export function filterHeaders( // Normalize list of headers we want to allow in upstream request const fieldsToKeepNormalized = fieldsToKeep .map(normalizeHeaderField) - .filter(name => !fieldsToExcludeNormalized.includes(name)); + .filter((name) => !fieldsToExcludeNormalized.includes(name)); return pick(headers, fieldsToKeepNormalized); } diff --git a/src/core/server/http/router/router.mock.ts b/src/core/server/http/router/router.mock.ts index b43db0ca7ed5a..651d1712100ee 100644 --- a/src/core/server/http/router/router.mock.ts +++ b/src/core/server/http/router/router.mock.ts @@ -30,7 +30,7 @@ function create({ routerPath = '' }: { routerPath?: string } = {}): RouterMock { put: jest.fn(), patch: jest.fn(), getRoutes: jest.fn(), - handleLegacyErrors: jest.fn().mockImplementation(handler => handler), + handleLegacyErrors: jest.fn().mockImplementation((handler) => handler), }; } diff --git a/src/core/server/http/router/validator/validator.test.ts b/src/core/server/http/router/validator/validator.test.ts index e972e2075e705..30f66f5d41fbe 100644 --- a/src/core/server/http/router/validator/validator.test.ts +++ b/src/core/server/http/router/validator/validator.test.ts @@ -46,7 +46,7 @@ describe('Router validator', () => { it('should validate and infer the type from a function that does not use the resolver', () => { const validator = RouteValidator.from({ - params: data => { + params: (data) => { if (typeof data.foo === 'string') { return { value: { foo: data.foo as string } }; } @@ -112,7 +112,7 @@ describe('Router validator', () => { it('should catch the errors thrown by the validate function', () => { const validator = RouteValidator.from({ - params: data => { + params: (data) => { throw new Error('Something went terribly wrong'); }, }); diff --git a/src/core/server/http/ssl_config.ts b/src/core/server/http/ssl_config.ts index 4eb0c50e72362..75dc05d1a801b 100644 --- a/src/core/server/http/ssl_config.ts +++ b/src/core/server/http/ssl_config.ts @@ -65,7 +65,7 @@ export const sslSchema = schema.object( ), }, { - validate: ssl => { + validate: (ssl) => { if (ssl.key && ssl.keystore.path) { return 'cannot use [key] when [keystore.path] is specified'; } diff --git a/src/core/server/legacy/config/ensure_valid_configuration.ts b/src/core/server/legacy/config/ensure_valid_configuration.ts index a68d3df577a89..5cd1603ea65fb 100644 --- a/src/core/server/legacy/config/ensure_valid_configuration.ts +++ b/src/core/server/legacy/config/ensure_valid_configuration.ts @@ -36,7 +36,7 @@ export async function ensureValidConfiguration( if (unusedConfigKeys.length > 0) { const message = `Unknown configuration key(s): ${unusedConfigKeys - .map(key => `"${key}"`) + .map((key) => `"${key}"`) .join(', ')}. Check for spelling errors and ensure that expected plugins are installed.`; throw new InvalidConfigurationError(message); } diff --git a/src/core/server/legacy/config/get_unused_config_keys.ts b/src/core/server/legacy/config/get_unused_config_keys.ts index 20c9776f63c58..6cd193d896109 100644 --- a/src/core/server/legacy/config/get_unused_config_keys.ts +++ b/src/core/server/legacy/config/get_unused_config_keys.ts @@ -72,8 +72,8 @@ export async function getUnusedConfigKeys({ // Filter out keys that are marked as used in the core (e.g. by new core plugins). return difference(inputKeys, appliedKeys).filter( - unusedConfigKey => - !coreHandledConfigPaths.some(usedInCoreConfigKey => + (unusedConfigKey) => + !coreHandledConfigPaths.some((usedInCoreConfigKey) => hasConfigPathIntersection(unusedConfigKey, usedInCoreConfigKey) ) ); diff --git a/src/core/server/legacy/config/legacy_deprecation_adapters.test.ts b/src/core/server/legacy/config/legacy_deprecation_adapters.test.ts index 8651d05064492..b09f9d00b3bed 100644 --- a/src/core/server/legacy/config/legacy_deprecation_adapters.test.ts +++ b/src/core/server/legacy/config/legacy_deprecation_adapters.test.ts @@ -27,7 +27,7 @@ jest.spyOn(configDeprecationFactory, 'unusedFromRoot'); jest.spyOn(configDeprecationFactory, 'renameFromRoot'); const executeHandlers = (handlers: ConfigDeprecation[]) => { - handlers.forEach(handler => { + handlers.forEach((handler) => { handler({}, '', () => null); }); }; @@ -99,7 +99,7 @@ describe('convertLegacyDeprecationProvider', () => { const migrated = applyDeprecations( rawConfig, - handlers.map(handler => ({ deprecation: handler, path: '' })) + handlers.map((handler) => ({ deprecation: handler, path: '' })) ); expect(migrated).toEqual({ new: 'oldvalue', goodValue: 'good' }); }); diff --git a/src/core/server/legacy/legacy_internals.test.ts b/src/core/server/legacy/legacy_internals.test.ts index dcab62627442b..2ae5e3a3fd1e8 100644 --- a/src/core/server/legacy/legacy_internals.test.ts +++ b/src/core/server/legacy/legacy_internals.test.ts @@ -84,7 +84,7 @@ describe('LegacyInternals', () => { jest.fn().mockResolvedValue({ is: 'merged-core' }), ]; - injectors.forEach(injector => legacyInternals.injectUiAppVars('core', injector)); + injectors.forEach((injector) => legacyInternals.injectUiAppVars('core', injector)); await expect(legacyInternals.getInjectedUiAppVars('core')).resolves.toMatchInlineSnapshot(` Object { @@ -136,10 +136,10 @@ describe('LegacyInternals', () => { it('gets: no default injectors, with injected vars replacers, with ui app injectors, no inject arg', async () => { uiExports.injectedVarsReplacers = [ - jest.fn(async vars => ({ ...vars, added: 'key' })), - jest.fn(vars => vars), - jest.fn(vars => ({ replaced: 'all' })), - jest.fn(async vars => ({ ...vars, added: 'last-key' })), + jest.fn(async (vars) => ({ ...vars, added: 'key' })), + jest.fn((vars) => vars), + jest.fn((vars) => ({ replaced: 'all' })), + jest.fn(async (vars) => ({ ...vars, added: 'last-key' })), ]; const request = httpServerMock.createRawRequest(); @@ -186,7 +186,7 @@ describe('LegacyInternals', () => { varsProvider({ gamma: 'gamma' }), varsProvider({ alpha: 'beta' }), ]; - uiExports.injectedVarsReplacers = [jest.fn(async vars => ({ ...vars, gamma: 'delta' }))]; + uiExports.injectedVarsReplacers = [jest.fn(async (vars) => ({ ...vars, gamma: 'delta' }))]; legacyInternals.injectUiAppVars('core', async () => ({ is: 'core' })); legacyInternals.injectUiAppVars('core', () => ({ sync: 'injector' })); diff --git a/src/core/server/legacy/legacy_service.test.ts b/src/core/server/legacy/legacy_service.test.ts index a75f7dda302c2..d9a0ac5e4ecff 100644 --- a/src/core/server/legacy/legacy_service.test.ts +++ b/src/core/server/legacy/legacy_service.test.ts @@ -353,7 +353,7 @@ describe('once LegacyService is set up without connection info', () => { describe('once LegacyService is set up in `devClusterMaster` mode', () => { beforeEach(() => { - configService.atPath.mockImplementation(path => { + configService.atPath.mockImplementation((path) => { return new BehaviorSubject( path === 'dev' ? { basePathProxyTargetPort: 100500 } : { basePath: '/abc' } ); @@ -447,7 +447,7 @@ describe('#discoverPlugins()', () => { it(`register legacy plugin's deprecation providers`, async () => { findLegacyPluginSpecsMock.mockImplementation( - settings => + (settings) => Promise.resolve({ pluginSpecs: [ { @@ -486,7 +486,7 @@ describe('#discoverPlugins()', () => { { getId: () => 'pluginB', getDeprecationsProvider: () => undefined }, ]; findLegacyPluginSpecsMock.mockImplementation( - settings => + (settings) => Promise.resolve({ pluginSpecs, pluginExtendedConfig: settings, diff --git a/src/core/server/legacy/legacy_service.ts b/src/core/server/legacy/legacy_service.ts index b95362e1ea26e..df1ed3e100923 100644 --- a/src/core/server/legacy/legacy_service.ts +++ b/src/core/server/legacy/legacy_service.ts @@ -91,7 +91,7 @@ export class LegacyService implements CoreService { this.log = logger.get('legacy-service'); this.devConfig$ = configService .atPath(devConfig.path) - .pipe(map(rawConfig => new DevConfig(rawConfig))); + .pipe(map((rawConfig) => new DevConfig(rawConfig))); this.httpConfig$ = combineLatest( configService.atPath(httpConfig.path), configService.atPath(cspConfig.path) @@ -108,7 +108,7 @@ export class LegacyService implements CoreService { this.kbnServer.applyLoggingConfiguration(getLegacyRawConfig(config, pathConfig)); } }), - tap({ error: err => this.log.error(err) }), + tap({ error: (err) => this.log.error(err) }), publishReplay(1) ) as ConnectableObservable<[Config, PathConfigType]>; @@ -146,14 +146,14 @@ export class LegacyService implements CoreService { }; const deprecationProviders = await pluginSpecs - .map(spec => spec.getDeprecationsProvider()) + .map((spec) => spec.getDeprecationsProvider()) .reduce(async (providers, current) => { if (current) { return [...(await providers), await convertLegacyDeprecationProvider(current)]; } return providers; }, Promise.resolve([] as ConfigDeprecationProvider[])); - deprecationProviders.forEach(provider => + deprecationProviders.forEach((provider) => this.coreContext.configService.addDeprecationProvider('', provider) ); diff --git a/src/core/server/legacy/merge_vars.ts b/src/core/server/legacy/merge_vars.ts index a1d43af2f861d..5d1820988e57a 100644 --- a/src/core/server/legacy/merge_vars.ts +++ b/src/core/server/legacy/merge_vars.ts @@ -25,9 +25,9 @@ export function mergeVars(...sources: LegacyVars[]): LegacyVars { return Object.assign( {}, ...sources, - ...ELIGIBLE_FLAT_MERGE_KEYS.flatMap(key => - sources.some(source => key in source) - ? [{ [key]: Object.assign({}, ...sources.map(source => source[key] || {})) }] + ...ELIGIBLE_FLAT_MERGE_KEYS.flatMap((key) => + sources.some((source) => key in source) + ? [{ [key]: Object.assign({}, ...sources.map((source) => source[key] || {})) }] : [] ) ); diff --git a/src/core/server/legacy/plugins/find_legacy_plugin_specs.ts b/src/core/server/legacy/plugins/find_legacy_plugin_specs.ts index 44f02f0c90d4e..5039b3a55cc58 100644 --- a/src/core/server/legacy/plugins/find_legacy_plugin_specs.ts +++ b/src/core/server/legacy/plugins/find_legacy_plugin_specs.ts @@ -63,14 +63,14 @@ export async function findLegacyPluginSpecs( const log$ = merge( pack$.pipe( - tap(definition => { + tap((definition) => { const path = definition.getPath(); logger.debug(`Found plugin at ${path}`, { path }); }) ), invalidDirectoryError$.pipe( - tap(error => { + tap((error) => { logger.warn(`Unable to scan directory for plugins "${error.path}"`, { err: error, dir: error.path, @@ -79,7 +79,7 @@ export async function findLegacyPluginSpecs( ), invalidPackError$.pipe( - tap(error => { + tap((error) => { logger.warn(`Skipping non-plugin directory at ${error.path}`, { path: error.path, }); @@ -87,21 +87,21 @@ export async function findLegacyPluginSpecs( ), otherError$.pipe( - tap(error => { + tap((error) => { // rethrow unhandled errors, which will fail the server throw error; }) ), invalidVersionSpec$.pipe( - map(spec => { + map((spec) => { const name = spec.getId(); const pluginVersion = spec.getExpectedKibanaVersion(); const kibanaVersion = packageInfo.version; return `Plugin "${name}" was disabled because it expected Kibana version "${pluginVersion}", and found "${kibanaVersion}".`; }), distinct(), - tap(message => { + tap((message) => { logger.warn(message); }) ), diff --git a/src/core/server/legacy/plugins/get_nav_links.test.ts b/src/core/server/legacy/plugins/get_nav_links.test.ts index 5e84f27acabd5..af10706d0ea08 100644 --- a/src/core/server/legacy/plugins/get_nav_links.test.ts +++ b/src/core/server/legacy/plugins/get_nav_links.test.ts @@ -40,7 +40,7 @@ const createLegacyExports = ({ const createPluginSpecs = (...ids: string[]): LegacyPluginSpec[] => ids.map( - id => + (id) => ({ getId: () => id, } as LegacyPluginSpec) diff --git a/src/core/server/legacy/plugins/get_nav_links.ts b/src/core/server/legacy/plugins/get_nav_links.ts index 067fb204ca7f3..b1d22df41e345 100644 --- a/src/core/server/legacy/plugins/get_nav_links.ts +++ b/src/core/server/legacy/plugins/get_nav_links.ts @@ -66,11 +66,11 @@ function isHidden(app: LegacyAppSpec) { export function getNavLinks(uiExports: LegacyUiExports, pluginSpecs: LegacyPluginSpec[]) { const navLinkSpecs = uiExports.navLinkSpecs || []; const appSpecs = (uiExports.uiAppSpecs || []).filter( - app => app !== undefined && !isHidden(app) + (app) => app !== undefined && !isHidden(app) ) as LegacyAppSpec[]; - const pluginIds = (pluginSpecs || []).map(spec => spec.getId()); - appSpecs.forEach(spec => { + const pluginIds = (pluginSpecs || []).map((spec) => spec.getId()); + appSpecs.forEach((spec) => { if (spec.pluginId && !pluginIds.includes(spec.pluginId)) { throw new Error(`Unknown plugin id "${spec.pluginId}"`); } diff --git a/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts b/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts index df86f5a2b4031..4a4a1b1b0e60b 100644 --- a/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts +++ b/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts @@ -36,7 +36,7 @@ export const logLegacyThirdPartyPluginDeprecationWarning = ({ }) => { const thirdPartySpecs = specs.filter(isThirdPartyPluginSpec); if (thirdPartySpecs.length > 0) { - const pluginIds = thirdPartySpecs.map(spec => spec.getId()); + const pluginIds = thirdPartySpecs.map((spec) => spec.getId()); log.warn( `Some installed third party plugin(s) [${pluginIds.join( ', ' @@ -49,5 +49,5 @@ export const logLegacyThirdPartyPluginDeprecationWarning = ({ const isThirdPartyPluginSpec = (spec: LegacyPluginSpec): boolean => { const pluginPath = spec.getPack().getPath(); - return !internalPaths.some(internalPath => pluginPath.indexOf(internalPath) > -1); + return !internalPaths.some((internalPath) => pluginPath.indexOf(internalPath) > -1); }; diff --git a/src/core/server/logging/appenders/file/file_appender.test.ts b/src/core/server/logging/appenders/file/file_appender.test.ts index 0483a06b199b6..bff60029faf11 100644 --- a/src/core/server/logging/appenders/file/file_appender.test.ts +++ b/src/core/server/logging/appenders/file/file_appender.test.ts @@ -23,7 +23,7 @@ import { LogLevel } from '../../log_level'; import { LogRecord } from '../../log_record'; import { FileAppender } from './file_appender'; -const tickMs = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); +const tickMs = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); beforeEach(() => { mockCreateWriteStream.mockReset(); diff --git a/src/core/server/logging/appenders/file/file_appender.ts b/src/core/server/logging/appenders/file/file_appender.ts index 3aca59fb3f42c..728e82ebcec9a 100644 --- a/src/core/server/logging/appenders/file/file_appender.ts +++ b/src/core/server/logging/appenders/file/file_appender.ts @@ -66,7 +66,7 @@ export class FileAppender implements DisposableAppender { * Disposes `FileAppender`. Waits for the underlying file stream to be completely flushed and closed. */ public async dispose() { - await new Promise(resolve => { + await new Promise((resolve) => { if (this.outputStream === undefined) { return resolve(); } diff --git a/src/core/server/logging/integration_tests/utils.ts b/src/core/server/logging/integration_tests/utils.ts index 81a76ce76ad73..e4c2c8866cb92 100644 --- a/src/core/server/logging/integration_tests/utils.ts +++ b/src/core/server/logging/integration_tests/utils.ts @@ -55,7 +55,7 @@ export async function getPlatformLogsFromFile(path: string) { const fileContent = await readFile(path, 'utf-8'); return fileContent .split('\n') - .map(s => normalizePlatformLogging(s)) + .map((s) => normalizePlatformLogging(s)) .join('\n'); } @@ -63,6 +63,6 @@ export async function getLegacyPlatformLogsFromFile(path: string) { const fileContent = await readFile(path, 'utf-8'); return fileContent .split('\n') - .map(s => normalizeLegacyPlatformLogging(s)) + .map((s) => normalizeLegacyPlatformLogging(s)) .join('\n'); } diff --git a/src/core/server/logging/layouts/pattern_layout.ts b/src/core/server/logging/layouts/pattern_layout.ts index 9490db149cc0f..7839345a3703b 100644 --- a/src/core/server/logging/layouts/pattern_layout.ts +++ b/src/core/server/logging/layouts/pattern_layout.ts @@ -37,7 +37,7 @@ import { const DEFAULT_PATTERN = `[%date][%level][%logger]%meta %message`; export const patternSchema = schema.string({ - validate: string => { + validate: (string) => { DateConversion.validate!(string); }, }); diff --git a/src/core/server/logging/logging_config.ts b/src/core/server/logging/logging_config.ts index 8f80be7d79cb1..772909ce584e5 100644 --- a/src/core/server/logging/logging_config.ts +++ b/src/core/server/logging/logging_config.ts @@ -167,13 +167,13 @@ export class LoggingConfig { ]; const loggerConfigByContext = new Map( - loggers.map(loggerConfig => toTuple(loggerConfig.context, loggerConfig)) + loggers.map((loggerConfig) => toTuple(loggerConfig.context, loggerConfig)) ); for (const [loggerContext, loggerConfig] of loggerConfigByContext) { // Ensure logger config only contains valid appenders. const unsupportedAppenderKey = loggerConfig.appenders.find( - appenderKey => !this.appenders.has(appenderKey) + (appenderKey) => !this.appenders.has(appenderKey) ); if (unsupportedAppenderKey) { diff --git a/src/core/server/logging/logging_service.ts b/src/core/server/logging/logging_service.ts index f9535e6c8283e..2e6f895724122 100644 --- a/src/core/server/logging/logging_service.ts +++ b/src/core/server/logging/logging_service.ts @@ -108,7 +108,7 @@ export class LoggingService implements LoggerFactory { const { level, appenders } = this.getLoggerConfigByContext(config, context); const loggerLevel = LogLevel.fromId(level); - const loggerAppenders = appenders.map(appenderKey => this.appenders.get(appenderKey)!); + const loggerAppenders = appenders.map((appenderKey) => this.appenders.get(appenderKey)!); return new BaseLogger(context, loggerLevel, loggerAppenders, this.asLoggerFactory()); } diff --git a/src/core/server/metrics/collectors/process.ts b/src/core/server/metrics/collectors/process.ts index a3b59a7cc8b7c..b020eebcbbd0b 100644 --- a/src/core/server/metrics/collectors/process.ts +++ b/src/core/server/metrics/collectors/process.ts @@ -46,7 +46,7 @@ export class ProcessMetricsCollector implements MetricsCollector => { const bench = new Bench(); - return new Promise(resolve => { + return new Promise((resolve) => { setImmediate(() => { return resolve(bench.elapsed()); }); diff --git a/src/core/server/metrics/collectors/server.ts b/src/core/server/metrics/collectors/server.ts index 84204d0466ff3..036332c24c34f 100644 --- a/src/core/server/metrics/collectors/server.ts +++ b/src/core/server/metrics/collectors/server.ts @@ -45,7 +45,7 @@ export class ServerMetricsCollector implements MetricsCollector { + this.server.events.on('response', (request) => { const statusCode = (request.response as ResponseObject)?.statusCode; if (statusCode) { if (!this.requests.statusCodes[statusCode]) { @@ -62,7 +62,7 @@ export class ServerMetricsCollector implements MetricsCollector { - const connections = await new Promise(resolve => { + const connections = await new Promise((resolve) => { this.server.listener.getConnections((_, count) => { resolve(count); }); diff --git a/src/core/server/metrics/integration_tests/server_collector.test.ts b/src/core/server/metrics/integration_tests/server_collector.test.ts index 3b982a06cf06c..4476b3c26a2e1 100644 --- a/src/core/server/metrics/integration_tests/server_collector.test.ts +++ b/src/core/server/metrics/integration_tests/server_collector.test.ts @@ -34,7 +34,7 @@ describe('ServerMetricsCollector', () => { let hapiServer: HapiServer; let router: IRouter; - const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); + const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const sendGet = (path: string) => supertest(hapiServer.listener).get(path); beforeEach(async () => { @@ -81,7 +81,7 @@ describe('ServerMetricsCollector', () => { }); it('collect disconnects requests infos', async () => { - const never = new Promise(resolve => undefined); + const never = new Promise((resolve) => undefined); const hitSubject = new BehaviorSubject(0); router.get({ path: '/', validate: false }, async (ctx, req, res) => { @@ -100,7 +100,7 @@ describe('ServerMetricsCollector', () => { await hitSubject .pipe( - filter(count => count >= 2), + filter((count) => count >= 2), take(1) ) .toPromise(); @@ -177,7 +177,7 @@ describe('ServerMetricsCollector', () => { const waitForHits = (hits: number) => hitSubject .pipe( - filter(count => count >= hits), + filter((count) => count >= hits), take(1) ) .toPromise(); @@ -189,12 +189,12 @@ describe('ServerMetricsCollector', () => { // however in this test we need to send the request now and await for it later in the code. // also using `.end` is not possible as it would execute the request twice. // so the only option is this noop `.then`. - const res1 = sendGet('/').then(res => res); + const res1 = sendGet('/').then((res) => res); await waitForHits(1); metrics = await collector.collect(); expect(metrics.concurrent_connections).toEqual(1); - const res2 = sendGet('/').then(res => res); + const res2 = sendGet('/').then((res) => res); await waitForHits(2); metrics = await collector.collect(); expect(metrics.concurrent_connections).toEqual(2); diff --git a/src/core/server/metrics/metrics_service.test.ts b/src/core/server/metrics/metrics_service.test.ts index f6334cc5d3c0f..01a7429745cda 100644 --- a/src/core/server/metrics/metrics_service.test.ts +++ b/src/core/server/metrics/metrics_service.test.ts @@ -82,10 +82,7 @@ describe('MetricsService', () => { // however the `reset` call is executed after the async call to `collect` // meaning that we are going to miss the call if we don't wait for the // actual observable emission that is performed after - const waitForNextEmission = () => - getOpsMetrics$() - .pipe(take(1)) - .toPromise(); + const waitForNextEmission = () => getOpsMetrics$().pipe(take(1)).toPromise(); expect(mockOpsCollector.collect).toHaveBeenCalledTimes(1); expect(mockOpsCollector.reset).toHaveBeenCalledTimes(1); diff --git a/src/core/server/path/index.ts b/src/core/server/path/index.ts index 004aa2a279927..2e05e3856bd4c 100644 --- a/src/core/server/path/index.ts +++ b/src/core/server/path/index.ts @@ -37,7 +37,7 @@ const DATA_PATHS = [ ].filter(isString); function findFile(paths: string[]) { - const availablePath = paths.find(configPath => { + const availablePath = paths.find((configPath) => { try { accessSync(configPath, constants.R_OK); return true; diff --git a/src/core/server/plugins/discovery/plugin_manifest_parser.ts b/src/core/server/plugins/discovery/plugin_manifest_parser.ts index 573109c9db35a..27c3ca5a71e16 100644 --- a/src/core/server/plugins/discovery/plugin_manifest_parser.ts +++ b/src/core/server/plugins/discovery/plugin_manifest_parser.ts @@ -154,7 +154,9 @@ export async function parseManifest(pluginPath: string, packageInfo: PackageInfo ); } - const unknownManifestKeys = Object.keys(manifest).filter(key => !KNOWN_MANIFEST_FIELDS.has(key)); + const unknownManifestKeys = Object.keys(manifest).filter( + (key) => !KNOWN_MANIFEST_FIELDS.has(key) + ); if (unknownManifestKeys.length > 0) { throw PluginDiscoveryError.invalidManifest( manifestPath, diff --git a/src/core/server/plugins/discovery/plugins_discovery.test.ts b/src/core/server/plugins/discovery/plugins_discovery.test.ts index 2902aafdbf146..73f274957cbc4 100644 --- a/src/core/server/plugins/discovery/plugins_discovery.test.ts +++ b/src/core/server/plugins/discovery/plugins_discovery.test.ts @@ -143,7 +143,7 @@ test('properly iterates through plugin search locations', async () => { resolve(TEST_PLUGIN_SEARCH_PATHS.nonEmptySrcPlugins, '6'), TEST_EXTRA_PLUGIN_PATH, ]) { - const discoveredPlugin = plugins.find(plugin => plugin.path === path)!; + const discoveredPlugin = plugins.find((plugin) => plugin.path === path)!; expect(discoveredPlugin).toBeInstanceOf(PluginWrapper); expect(discoveredPlugin.configPath).toEqual(['core', 'config']); expect(discoveredPlugin.requiredPlugins).toEqual(['a', 'b']); @@ -153,7 +153,7 @@ test('properly iterates through plugin search locations', async () => { await expect( error$ .pipe( - map(error => error.toString()), + map((error) => error.toString()), toArray() ) .toPromise() diff --git a/src/core/server/plugins/discovery/plugins_discovery.ts b/src/core/server/plugins/discovery/plugins_discovery.ts index e7f82c9dc15ad..1910483211e34 100644 --- a/src/core/server/plugins/discovery/plugins_discovery.ts +++ b/src/core/server/plugins/discovery/plugins_discovery.ts @@ -56,7 +56,7 @@ export function discover(config: PluginsConfig, coreContext: CoreContext) { from(config.additionalPluginPaths), processPluginSearchPaths$(config.pluginSearchPaths, log) ).pipe( - mergeMap(pluginPathOrError => { + mergeMap((pluginPathOrError) => { return typeof pluginPathOrError === 'string' ? createPlugin$(pluginPathOrError, log, coreContext) : [pluginPathOrError]; @@ -83,21 +83,21 @@ export function discover(config: PluginsConfig, coreContext: CoreContext) { */ function processPluginSearchPaths$(pluginDirs: readonly string[], log: Logger) { return from(pluginDirs).pipe( - mergeMap(dir => { + mergeMap((dir) => { log.debug(`Scanning "${dir}" for plugin sub-directories...`); return fsReadDir$(dir).pipe( - mergeMap((subDirs: string[]) => subDirs.map(subDir => resolve(dir, subDir))), - mergeMap(path => + mergeMap((subDirs: string[]) => subDirs.map((subDir) => resolve(dir, subDir))), + mergeMap((path) => fsStat$(path).pipe( // Filter out non-directory entries from target directories, it's expected that // these directories may contain files (e.g. `README.md` or `package.json`). // We shouldn't silently ignore the entries we couldn't get stat for though. - mergeMap(pathStat => (pathStat.isDirectory() ? [path] : [])), - catchError(err => [PluginDiscoveryError.invalidPluginPath(path, err)]) + mergeMap((pathStat) => (pathStat.isDirectory() ? [path] : [])), + catchError((err) => [PluginDiscoveryError.invalidPluginPath(path, err)]) ) ), - catchError(err => [PluginDiscoveryError.invalidSearchPath(dir, err)]) + catchError((err) => [PluginDiscoveryError.invalidSearchPath(dir, err)]) ); }) ); @@ -113,7 +113,7 @@ function processPluginSearchPaths$(pluginDirs: readonly string[], log: Logger) { */ function createPlugin$(path: string, log: Logger, coreContext: CoreContext) { return from(parseManifest(path, coreContext.env.packageInfo, log)).pipe( - map(manifest => { + map((manifest) => { log.debug(`Successfully discovered plugin "${manifest.id}" at "${path}"`); const opaqueId = Symbol(manifest.id); return new PluginWrapper({ @@ -123,6 +123,6 @@ function createPlugin$(path: string, log: Logger, coreContext: CoreContext) { initializerContext: createPluginInitializerContext(coreContext, opaqueId, manifest), }); }), - catchError(err => [err]) + catchError((err) => [err]) ); } diff --git a/src/core/server/plugins/integration_tests/plugins_service.test.ts b/src/core/server/plugins/integration_tests/plugins_service.test.ts index 1521fc332bcdb..04f570cca489b 100644 --- a/src/core/server/plugins/integration_tests/plugins_service.test.ts +++ b/src/core/server/plugins/integration_tests/plugins_service.test.ts @@ -139,7 +139,7 @@ describe('PluginsService', () => { }, start: async (core, plugins) => { contextFromStart = { core, plugins }; - await new Promise(resolve => setTimeout(resolve, 10)); + await new Promise((resolve) => setTimeout(resolve, 10)); expect(startDependenciesResolved).toBe(false); return pluginStartContract; }, diff --git a/src/core/server/plugins/plugin.test.ts b/src/core/server/plugins/plugin.test.ts index 1e4d94dd00d0d..8d82d96f949c7 100644 --- a/src/core/server/plugins/plugin.test.ts +++ b/src/core/server/plugins/plugin.test.ts @@ -260,7 +260,7 @@ test("`start` resolves `startDependencies` Promise after plugin's start", async setup: jest.fn(), start: async () => { // delay to ensure startDependencies is not resolved until after the plugin instance's start resolves. - await new Promise(resolve => setTimeout(resolve, 10)); + await new Promise((resolve) => setTimeout(resolve, 10)); expect(startDependenciesResolved).toBe(false); return pluginStartContract; }, @@ -269,7 +269,7 @@ test("`start` resolves `startDependencies` Promise after plugin's start", async await plugin.setup({} as any, {} as any); - const startDependenciesCheck = plugin.startDependencies.then(resolvedStartDeps => { + const startDependenciesCheck = plugin.startDependencies.then((resolvedStartDeps) => { startDependenciesResolved = true; expect(resolvedStartDeps).toEqual([startContext, pluginDeps, pluginStartContract]); }); diff --git a/src/core/server/plugins/plugins_service.test.ts b/src/core/server/plugins/plugins_service.test.ts index 38fda12bd290f..6f8d15838641f 100644 --- a/src/core/server/plugins/plugins_service.test.ts +++ b/src/core/server/plugins/plugins_service.test.ts @@ -51,7 +51,7 @@ const logger = loggingServiceMock.create(); expect.addSnapshotSerializer(createAbsolutePathSerializer()); -['path-1', 'path-2', 'path-3', 'path-4', 'path-5'].forEach(path => { +['path-1', 'path-2', 'path-3', 'path-4', 'path-5'].forEach((path) => { jest.doMock(join(path, 'server'), () => ({}), { virtual: true, }); @@ -200,7 +200,7 @@ describe('PluginsService', () => { it('properly detects plugins that should be disabled.', async () => { jest .spyOn(configService, 'isEnabledAtPath') - .mockImplementation(path => Promise.resolve(!path.includes('disabled'))); + .mockImplementation((path) => Promise.resolve(!path.includes('disabled'))); mockPluginSystem.setupPlugins.mockResolvedValue(new Map()); diff --git a/src/core/server/plugins/plugins_service.ts b/src/core/server/plugins/plugins_service.ts index d7a348affe94f..7441e753efa6a 100644 --- a/src/core/server/plugins/plugins_service.ts +++ b/src/core/server/plugins/plugins_service.ts @@ -87,7 +87,7 @@ export class PluginsService implements CoreService('plugins') - .pipe(map(rawConfig => new PluginsConfig(rawConfig, coreContext.env))); + .pipe(map((rawConfig) => new PluginsConfig(rawConfig, coreContext.env))); } public async discover() { @@ -153,7 +153,7 @@ export class PluginsService implements CoreService exposed) + Object.values(configDescriptor?.exposeToBrowser).some((exposed) => exposed) ); }) .map(([pluginId, plugin]) => { @@ -186,14 +186,14 @@ export class PluginsService implements CoreService errorTypesToReport.includes(error.type)), - tap(pluginError => this.log.error(pluginError)), + filter((error) => errorTypesToReport.includes(error.type)), + tap((pluginError) => this.log.error(pluginError)), toArray() ) .toPromise(); if (errors.length > 0) { throw new Error( - `Failed to initialize plugins:${errors.map(err => `\n\t${err.message}`).join('')}` + `Failed to initialize plugins:${errors.map((err) => `\n\t${err.message}`).join('')}` ); } } @@ -205,7 +205,7 @@ export class PluginsService implements CoreService(); await plugin$ .pipe( - mergeMap(async plugin => { + mergeMap(async (plugin) => { const configDescriptor = plugin.getConfigDescriptor(); if (configDescriptor) { this.pluginConfigDescriptors.set(plugin.name, configDescriptor); @@ -263,8 +263,8 @@ export class PluginsService implements CoreService !parents.includes(dep)) - .every(dependencyName => + .filter((dep) => !parents.includes(dep)) + .every((dependencyName) => this.shouldEnablePlugin(dependencyName, pluginEnableStatuses, [...parents, pluginName]) ) ); diff --git a/src/core/server/plugins/plugins_system.test.ts b/src/core/server/plugins/plugins_system.test.ts index 22dfbeecbaedd..8b318ad1b735e 100644 --- a/src/core/server/plugins/plugins_system.test.ts +++ b/src/core/server/plugins/plugins_system.test.ts @@ -342,7 +342,7 @@ test('`uiPlugins` returns ordered Maps of all plugin manifests', async () => { ], ] as Array<[PluginWrapper, Record]>); - [...plugins.keys()].forEach(plugin => { + [...plugins.keys()].forEach((plugin) => { pluginsSystem.addPlugin(plugin); }); @@ -371,7 +371,7 @@ test('`uiPlugins` returns only ui plugin dependencies', async () => { createPlugin('opt-no-ui', { ui: false, server: true }), ]; - plugins.forEach(plugin => { + plugins.forEach((plugin) => { pluginsSystem.addPlugin(plugin); }); @@ -424,7 +424,7 @@ describe('setup', () => { }); it('throws timeout error if "setup" was not completed in 30 sec.', async () => { const plugin: PluginWrapper = createPlugin('timeout-setup'); - jest.spyOn(plugin, 'setup').mockImplementation(() => new Promise(i => i)); + jest.spyOn(plugin, 'setup').mockImplementation(() => new Promise((i) => i)); pluginsSystem.addPlugin(plugin); mockCreatePluginSetupContext.mockImplementation(() => ({})); @@ -447,7 +447,7 @@ describe('start', () => { it('throws timeout error if "start" was not completed in 30 sec.', async () => { const plugin: PluginWrapper = createPlugin('timeout-start'); jest.spyOn(plugin, 'setup').mockResolvedValue({}); - jest.spyOn(plugin, 'start').mockImplementation(() => new Promise(i => i)); + jest.spyOn(plugin, 'start').mockImplementation(() => new Promise((i) => i)); pluginsSystem.addPlugin(plugin); mockCreatePluginSetupContext.mockImplementation(() => ({})); diff --git a/src/core/server/plugins/plugins_system.ts b/src/core/server/plugins/plugins_system.ts index dd2df7c8e01d1..e0401006ffac9 100644 --- a/src/core/server/plugins/plugins_system.ts +++ b/src/core/server/plugins/plugins_system.ts @@ -53,9 +53,9 @@ export class PluginsSystem { [ ...new Set([ ...plugin.requiredPlugins, - ...plugin.optionalPlugins.filter(optPlugin => this.plugins.has(optPlugin)), + ...plugin.optionalPlugins.filter((optPlugin) => this.plugins.has(optPlugin)), ]), - ].map(depId => this.plugins.get(depId)!.opaqueId), + ].map((depId) => this.plugins.get(depId)!.opaqueId), ]) ); } @@ -161,18 +161,22 @@ export class PluginsSystem { */ public uiPlugins() { const uiPluginNames = [...this.getTopologicallySortedPluginNames().keys()].filter( - pluginName => this.plugins.get(pluginName)!.includesUiPlugin + (pluginName) => this.plugins.get(pluginName)!.includesUiPlugin ); const publicPlugins = new Map( - uiPluginNames.map(pluginName => { + uiPluginNames.map((pluginName) => { const plugin = this.plugins.get(pluginName)!; return [ pluginName, { id: pluginName, configPath: plugin.manifest.configPath, - requiredPlugins: plugin.manifest.requiredPlugins.filter(p => uiPluginNames.includes(p)), - optionalPlugins: plugin.manifest.optionalPlugins.filter(p => uiPluginNames.includes(p)), + requiredPlugins: plugin.manifest.requiredPlugins.filter((p) => + uiPluginNames.includes(p) + ), + optionalPlugins: plugin.manifest.optionalPlugins.filter((p) => + uiPluginNames.includes(p) + ), }, ]; }) @@ -200,7 +204,7 @@ export class PluginsSystem { pluginName, new Set([ ...plugin.requiredPlugins, - ...plugin.optionalPlugins.filter(dependency => this.plugins.has(dependency)), + ...plugin.optionalPlugins.filter((dependency) => this.plugins.has(dependency)), ]), ] as [PluginName, Set]; }) @@ -209,7 +213,7 @@ export class PluginsSystem { // First, find a list of "start nodes" which have no outgoing edges. At least // one such node must exist in a non-empty acyclic graph. const pluginsWithAllDependenciesSorted = [...pluginsDependenciesGraph.keys()].filter( - pluginName => pluginsDependenciesGraph.get(pluginName)!.size === 0 + (pluginName) => pluginsDependenciesGraph.get(pluginName)!.size === 0 ); const sortedPluginNames = new Set(); diff --git a/src/core/server/rendering/views/fonts.tsx b/src/core/server/rendering/views/fonts.tsx index e87179920202a..8e460a150439d 100644 --- a/src/core/server/rendering/views/fonts.tsx +++ b/src/core/server/rendering/views/fonts.tsx @@ -249,7 +249,7 @@ export const Fonts: FunctionComponent = ({ url }) => { .flatMap(({ family, variants }) => variants.map(({ style, weight, format, sources, unicodeRange }) => { const src = sources - .map(source => + .map((source) => source.startsWith(url) ? `url('${source}') format('${format || source.split('.').pop()}')` : `local('${source}')` diff --git a/src/core/server/root/index.test.ts b/src/core/server/root/index.test.ts index 3b187aac022c3..5b853903ea4be 100644 --- a/src/core/server/root/index.test.ts +++ b/src/core/server/root/index.test.ts @@ -183,7 +183,7 @@ test('stops services if consequent logger upgrade fails', async () => { // Wait for shutdown to be called. await onShutdown .pipe( - filter(e => e !== null), + filter((e) => e !== null), first() ) .toPromise(); diff --git a/src/core/server/root/index.ts b/src/core/server/root/index.ts index eecc6399366dc..d6d0c641e00b0 100644 --- a/src/core/server/root/index.ts +++ b/src/core/server/root/index.ts @@ -99,10 +99,10 @@ export class Root { const update$ = configService.getConfig$().pipe( // always read the logging config when the underlying config object is re-read switchMap(() => configService.atPath('logging')), - map(config => this.loggingService.upgrade(config)), + map((config) => this.loggingService.upgrade(config)), // This specifically console.logs because we were not able to configure the logger. // eslint-disable-next-line no-console - tap({ error: err => console.error('Configuring logger failed:', err) }), + tap({ error: (err) => console.error('Configuring logger failed:', err) }), publishReplay(1) ) as ConnectableObservable; @@ -112,7 +112,7 @@ export class Root { // Send subsequent update failures to this.shutdown(), stopped via loggingConfigSubscription. this.loggingConfigSubscription = update$.subscribe({ - error: err => this.shutdown(err), + error: (err) => this.shutdown(err), }); // Add subscription we got from `connect` so that we can dispose both of them diff --git a/src/core/server/saved_objects/export/get_sorted_objects_for_export.ts b/src/core/server/saved_objects/export/get_sorted_objects_for_export.ts index a703c9f9fbd96..cafaa5a3147db 100644 --- a/src/core/server/saved_objects/export/get_sorted_objects_for_export.ts +++ b/src/core/server/saved_objects/export/get_sorted_objects_for_export.ts @@ -95,7 +95,7 @@ async function fetchObjectsToExport({ throw Boom.badRequest(`Can't specify both "search" and "objects" properties when exporting`); } const bulkGetResult = await savedObjectsClient.bulkGet(objects, { namespace }); - const erroredObjects = bulkGetResult.saved_objects.filter(obj => !!obj.error); + const erroredObjects = bulkGetResult.saved_objects.filter((obj) => !!obj.error); if (erroredObjects.length) { const err = Boom.badRequest(); err.output.payload.attributes = { diff --git a/src/core/server/saved_objects/export/inject_nested_depdendencies.ts b/src/core/server/saved_objects/export/inject_nested_depdendencies.ts index d00650926e57a..1f8c645340dbf 100644 --- a/src/core/server/saved_objects/export/inject_nested_depdendencies.ts +++ b/src/core/server/saved_objects/export/inject_nested_depdendencies.ts @@ -51,8 +51,10 @@ export async function fetchNestedDependencies( } const allObjects = [...savedObjectsMap.values()]; return { - objects: allObjects.filter(obj => !obj.error), - missingRefs: allObjects.filter(obj => !!obj.error).map(obj => ({ type: obj.type, id: obj.id })), + objects: allObjects.filter((obj) => !obj.error), + missingRefs: allObjects + .filter((obj) => !!obj.error) + .map((obj) => ({ type: obj.type, id: obj.id })), }; } diff --git a/src/core/server/saved_objects/export/sort_objects.ts b/src/core/server/saved_objects/export/sort_objects.ts index 522146737d9cf..64bab9f43bf14 100644 --- a/src/core/server/saved_objects/export/sort_objects.ts +++ b/src/core/server/saved_objects/export/sort_objects.ts @@ -24,7 +24,7 @@ export function sortObjects(savedObjects: SavedObject[]): SavedObject[] { const path = new Set(); const sorted = new Set(); const objectsByTypeId = new Map( - savedObjects.map(object => [`${object.type}:${object.id}`, object] as [string, SavedObject]) + savedObjects.map((object) => [`${object.type}:${object.id}`, object] as [string, SavedObject]) ); function includeObjects(objects: SavedObject[]) { @@ -32,13 +32,13 @@ export function sortObjects(savedObjects: SavedObject[]): SavedObject[] { if (path.has(object)) { throw Boom.badRequest( `circular reference: ${[...path, object] - .map(obj => `[${obj.type}:${obj.id}]`) + .map((obj) => `[${obj.type}:${obj.id}]`) .join(' ref-> ')}` ); } const refdObjects = object.references - .map(ref => objectsByTypeId.get(`${ref.type}:${ref.id}`)) + .map((ref) => objectsByTypeId.get(`${ref.type}:${ref.id}`)) .filter((ref): ref is SavedObject => !!ref); if (refdObjects.length) { diff --git a/src/core/server/saved_objects/import/collect_saved_objects.ts b/src/core/server/saved_objects/import/collect_saved_objects.ts index 1a8ede41d0b2c..1b787c7d9dc10 100644 --- a/src/core/server/saved_objects/import/collect_saved_objects.ts +++ b/src/core/server/saved_objects/import/collect_saved_objects.ts @@ -45,7 +45,7 @@ export async function collectSavedObjects({ const collectedObjects: Array> = await createPromiseFromStreams([ readStream, createLimitStream(objectLimit), - createFilterStream>(obj => { + createFilterStream>((obj) => { if (supportedTypes.includes(obj.type)) { return true; } @@ -59,7 +59,7 @@ export async function collectSavedObjects({ }); return false; }), - createFilterStream(obj => (filter ? filter(obj) : true)), + createFilterStream((obj) => (filter ? filter(obj) : true)), createMapStream((obj: SavedObject) => { // Ensure migrations execute on every saved object return Object.assign({ migrationVersion: {} }, obj); diff --git a/src/core/server/saved_objects/import/create_objects_filter.ts b/src/core/server/saved_objects/import/create_objects_filter.ts index c48cded00f1ec..55b8ab128d753 100644 --- a/src/core/server/saved_objects/import/create_objects_filter.ts +++ b/src/core/server/saved_objects/import/create_objects_filter.ts @@ -21,7 +21,7 @@ import { SavedObject } from '../types'; import { SavedObjectsImportRetry } from './types'; export function createObjectsFilter(retries: SavedObjectsImportRetry[]) { - const retryKeys = new Set(retries.map(retry => `${retry.type}:${retry.id}`)); + const retryKeys = new Set(retries.map((retry) => `${retry.type}:${retry.id}`)); return (obj: SavedObject) => { return retryKeys.has(`${obj.type}:${obj.id}`); }; 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 b43e5063c13e1..e204cd7bddfc7 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 @@ -95,7 +95,7 @@ describe('importSavedObjects()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); @@ -178,7 +178,7 @@ describe('importSavedObjects()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); @@ -262,7 +262,7 @@ describe('importSavedObjects()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); @@ -345,13 +345,13 @@ describe('importSavedObjects()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); savedObjectsClient.find.mockResolvedValueOnce(emptyResponse); savedObjectsClient.bulkCreate.mockResolvedValue({ - saved_objects: savedObjects.map(savedObject => ({ + saved_objects: savedObjects.map((savedObject) => ({ type: savedObject.type, id: savedObject.id, error: { @@ -527,7 +527,7 @@ describe('importSavedObjects()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push({ id: '1', type: 'wigwags', attributes: { title: 'my title' }, references: [] }); this.push(null); }, diff --git a/src/core/server/saved_objects/import/import_saved_objects.ts b/src/core/server/saved_objects/import/import_saved_objects.ts index cb1d70e5c8dc4..6065e03fb1628 100644 --- a/src/core/server/saved_objects/import/import_saved_objects.ts +++ b/src/core/server/saved_objects/import/import_saved_objects.ts @@ -78,7 +78,7 @@ export async function importSavedObjectsFromStream({ return { success: errorAccumulator.length === 0, - successCount: bulkCreateResult.saved_objects.filter(obj => !obj.error).length, + successCount: bulkCreateResult.saved_objects.filter((obj) => !obj.error).length, ...(errorAccumulator.length ? { errors: errorAccumulator } : {}), }; } 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 2c6d89e0a0a47..54ebecc7dca70 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 @@ -73,7 +73,7 @@ describe('resolveImportErrors()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); @@ -100,12 +100,12 @@ describe('resolveImportErrors()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); savedObjectsClient.bulkCreate.mockResolvedValueOnce({ - saved_objects: savedObjects.filter(obj => obj.type === 'visualization' && obj.id === '3'), + saved_objects: savedObjects.filter((obj) => obj.type === 'visualization' && obj.id === '3'), }); const result = await resolveSavedObjectsImportErrors({ readStream, @@ -161,12 +161,12 @@ describe('resolveImportErrors()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); savedObjectsClient.bulkCreate.mockResolvedValue({ - saved_objects: savedObjects.filter(obj => obj.type === 'index-pattern' && obj.id === '1'), + saved_objects: savedObjects.filter((obj) => obj.type === 'index-pattern' && obj.id === '1'), }); const result = await resolveSavedObjectsImportErrors({ readStream, @@ -223,12 +223,12 @@ describe('resolveImportErrors()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); savedObjectsClient.bulkCreate.mockResolvedValue({ - saved_objects: savedObjects.filter(obj => obj.type === 'dashboard' && obj.id === '4'), + saved_objects: savedObjects.filter((obj) => obj.type === 'dashboard' && obj.id === '4'), }); const result = await resolveSavedObjectsImportErrors({ readStream, @@ -296,12 +296,12 @@ describe('resolveImportErrors()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); savedObjectsClient.bulkCreate.mockResolvedValue({ - saved_objects: savedObjects.map(savedObject => ({ + saved_objects: savedObjects.map((savedObject) => ({ type: savedObject.type, id: savedObject.id, error: { @@ -315,7 +315,7 @@ describe('resolveImportErrors()', () => { const result = await resolveSavedObjectsImportErrors({ readStream, objectLimit: 4, - retries: savedObjects.map(obj => ({ + retries: savedObjects.map((obj) => ({ type: obj.type, id: obj.id, overwrite: false, @@ -495,7 +495,7 @@ describe('resolveImportErrors()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push({ id: '1', type: 'wigwags', attributes: { title: 'my title' }, references: [] }); this.push(null); }, @@ -540,12 +540,12 @@ describe('resolveImportErrors()', () => { const readStream = new Readable({ objectMode: true, read() { - savedObjects.forEach(obj => this.push(obj)); + savedObjects.forEach((obj) => this.push(obj)); this.push(null); }, }); savedObjectsClient.bulkCreate.mockResolvedValue({ - saved_objects: savedObjects.filter(obj => obj.type === 'index-pattern' && obj.id === '1'), + saved_objects: savedObjects.filter((obj) => obj.type === 'index-pattern' && obj.id === '1'), }); const result = await resolveSavedObjectsImportErrors({ readStream, diff --git a/src/core/server/saved_objects/import/resolve_import_errors.ts b/src/core/server/saved_objects/import/resolve_import_errors.ts index d9ac567882573..a5175aa080598 100644 --- a/src/core/server/saved_objects/import/resolve_import_errors.ts +++ b/src/core/server/saved_objects/import/resolve_import_errors.ts @@ -99,7 +99,7 @@ export async function resolveSavedObjectsImportErrors({ ...errorAccumulator, ...extractErrors(bulkCreateResult.saved_objects, objectsToOverwrite), ]; - successCount += bulkCreateResult.saved_objects.filter(obj => !obj.error).length; + successCount += bulkCreateResult.saved_objects.filter((obj) => !obj.error).length; } if (objectsToNotOverwrite.length) { const bulkCreateResult = await savedObjectsClient.bulkCreate(objectsToNotOverwrite, { @@ -109,7 +109,7 @@ export async function resolveSavedObjectsImportErrors({ ...errorAccumulator, ...extractErrors(bulkCreateResult.saved_objects, objectsToNotOverwrite), ]; - successCount += bulkCreateResult.saved_objects.filter(obj => !obj.error).length; + successCount += bulkCreateResult.saved_objects.filter((obj) => !obj.error).length; } return { diff --git a/src/core/server/saved_objects/import/split_overwrites.ts b/src/core/server/saved_objects/import/split_overwrites.ts index 192d43e9edb24..be55e049a2bfc 100644 --- a/src/core/server/saved_objects/import/split_overwrites.ts +++ b/src/core/server/saved_objects/import/split_overwrites.ts @@ -24,8 +24,8 @@ export function splitOverwrites(savedObjects: SavedObject[], retries: SavedObjec const objectsToOverwrite: SavedObject[] = []; const objectsToNotOverwrite: SavedObject[] = []; const overwrites = retries - .filter(retry => retry.overwrite) - .map(retry => `${retry.type}:${retry.id}`); + .filter((retry) => retry.overwrite) + .map((retry) => `${retry.type}:${retry.id}`); for (const savedObject of savedObjects) { if (overwrites.includes(`${savedObject.type}:${savedObject.id}`)) { diff --git a/src/core/server/saved_objects/import/validate_references.ts b/src/core/server/saved_objects/import/validate_references.ts index f0c033c1d00b4..2a30dcc96c08a 100644 --- a/src/core/server/saved_objects/import/validate_references.ts +++ b/src/core/server/saved_objects/import/validate_references.ts @@ -50,12 +50,12 @@ export async function getNonExistingReferenceAsKeys( } // Fetch references to see if they exist - const bulkGetOpts = Array.from(collector.values()).map(obj => ({ ...obj, fields: ['id'] })); + const bulkGetOpts = Array.from(collector.values()).map((obj) => ({ ...obj, fields: ['id'] })); const bulkGetResponse = await savedObjectsClient.bulkGet(bulkGetOpts, { namespace }); // Error handling const erroredObjects = bulkGetResponse.saved_objects.filter( - obj => obj.error && obj.error.statusCode !== 404 + (obj) => obj.error && obj.error.statusCode !== 404 ); if (erroredObjects.length) { const err = Boom.badRequest(); @@ -89,7 +89,7 @@ export async function validateReferences( ); // Filter out objects with missing references, add to error object - let filteredObjects = savedObjects.filter(savedObject => { + let filteredObjects = savedObjects.filter((savedObject) => { const missingReferences = []; const enforcedTypeReferences = (savedObject.references || []).filter( filterReferencesToValidate @@ -117,7 +117,7 @@ export async function validateReferences( // Filter out objects that reference objects within the import but are missing_references // For example: visualization referencing a search that is missing an index pattern needs to be filtered out - filteredObjects = filteredObjects.filter(savedObject => { + filteredObjects = filteredObjects.filter((savedObject) => { let isBlocked = false; for (const reference of savedObject.references || []) { const referencedObjectError = errorMap[`${reference.type}:${reference.id}`]; diff --git a/src/core/server/saved_objects/mappings/lib/get_types.ts b/src/core/server/saved_objects/mappings/lib/get_types.ts index d77d48f410ae0..66d54aede365b 100644 --- a/src/core/server/saved_objects/mappings/lib/get_types.ts +++ b/src/core/server/saved_objects/mappings/lib/get_types.ts @@ -23,5 +23,5 @@ import { IndexMapping } from '../types'; * Get the names of the types defined in the EsMappingsDsl */ export function getTypes(mappings: IndexMapping) { - return Object.keys(mappings).filter(type => type !== '_default_'); + return Object.keys(mappings).filter((type) => type !== '_default_'); } diff --git a/src/core/server/saved_objects/migrations/core/build_active_mappings.ts b/src/core/server/saved_objects/migrations/core/build_active_mappings.ts index 418ed95f14e05..c2a7b11e057cd 100644 --- a/src/core/server/saved_objects/migrations/core/build_active_mappings.ts +++ b/src/core/server/saved_objects/migrations/core/build_active_mappings.ts @@ -76,10 +76,7 @@ export function diffMappings(actual: IndexMapping, expected: IndexMapping) { // Convert an object to an md5 hash string, using a stable serialization (canonicalStringify) function md5Object(obj: any) { - return crypto - .createHash('md5') - .update(canonicalStringify(obj)) - .digest('hex'); + return crypto.createHash('md5').update(canonicalStringify(obj)).digest('hex'); } // JSON.stringify is non-canonical, meaning the same object may produce slightly @@ -106,7 +103,7 @@ function canonicalStringify(obj: any): string { const sortedObj = keys .sort((a, b) => a.localeCompare(b)) - .map(k => `${k}: ${canonicalStringify(obj[k])}`); + .map((k) => `${k}: ${canonicalStringify(obj[k])}`); return `{${sortedObj}}`; } @@ -120,7 +117,7 @@ function md5Values(obj: any) { // care, as it could be a disabled plugin, etc, and keeping stale stuff // around is better than migrating unecessesarily. function findChangedProp(actual: any, expected: any) { - return Object.keys(expected).find(k => actual[k] !== expected[k]); + return Object.keys(expected).find((k) => actual[k] !== expected[k]); } /** @@ -170,7 +167,7 @@ function validateAndMerge( dest: SavedObjectsMappingProperties, source: SavedObjectsTypeMappingDefinitions | SavedObjectsMappingProperties ) { - Object.keys(source).forEach(k => { + Object.keys(source).forEach((k) => { if (k.startsWith('_')) { throw new Error(`Invalid mapping "${k}". Mappings cannot start with _.`); } diff --git a/src/core/server/saved_objects/migrations/core/build_index_map.test.ts b/src/core/server/saved_objects/migrations/core/build_index_map.test.ts index 2c710d4eaa079..031d63a565e88 100644 --- a/src/core/server/saved_objects/migrations/core/build_index_map.test.ts +++ b/src/core/server/saved_objects/migrations/core/build_index_map.test.ts @@ -23,7 +23,7 @@ import { SavedObjectsType } from '../../types'; const createRegistry = (...types: Array>) => { const registry = new SavedObjectTypeRegistry(); - types.forEach(type => + types.forEach((type) => registry.registerType({ name: 'unknown', namespaceType: 'single', diff --git a/src/core/server/saved_objects/migrations/core/build_index_map.ts b/src/core/server/saved_objects/migrations/core/build_index_map.ts index 8f7fe2f8eac5b..0848fcf56d9fb 100644 --- a/src/core/server/saved_objects/migrations/core/build_index_map.ts +++ b/src/core/server/saved_objects/migrations/core/build_index_map.ts @@ -38,7 +38,7 @@ export interface IndexMap { */ export function createIndexMap({ kibanaIndexName, registry, indexMap }: CreateIndexMapOptions) { const map: IndexMap = {}; - Object.keys(indexMap).forEach(type => { + Object.keys(indexMap).forEach((type) => { const typeDef = registry.getType(type); const script = typeDef?.convertToAliasScript; // Defaults to kibanaIndexName if indexPattern isn't defined diff --git a/src/core/server/saved_objects/migrations/core/document_migrator.test.ts b/src/core/server/saved_objects/migrations/core/document_migrator.test.ts index bd10520ca1c57..a364710322524 100644 --- a/src/core/server/saved_objects/migrations/core/document_migrator.test.ts +++ b/src/core/server/saved_objects/migrations/core/document_migrator.test.ts @@ -29,7 +29,7 @@ const mockLogger = mockLoggerFactory.get('mock logger'); const createRegistry = (...types: Array>) => { const registry = new SavedObjectTypeRegistry(); - types.forEach(type => + types.forEach((type) => registry.registerType({ name: 'unknown', namespaceType: 'single', @@ -73,7 +73,7 @@ describe('DocumentMigrator', () => { typeRegistry: createRegistry({ name: 'foo', migrations: { - bar: doc => doc, + bar: (doc) => doc, }, }), validateDoc: _.noop, @@ -131,7 +131,7 @@ describe('DocumentMigrator', () => { typeRegistry: createRegistry({ name: 'user', migrations: { - '1.2.3': doc => { + '1.2.3': (doc) => { _.set(doc, 'attributes.name', 'Mike'); return doc; }, @@ -639,10 +639,10 @@ describe('DocumentMigrator', () => { typeRegistry: createRegistry({ name: 'aaa', migrations: { - '2.3.4': d => _.set(d, 'attributes.counter', 42), + '2.3.4': (d) => _.set(d, 'attributes.counter', 42), }, }), - validateDoc: d => { + validateDoc: (d) => { if ((d.attributes as any).counter === 42) { throw new Error('Meaningful!'); } diff --git a/src/core/server/saved_objects/migrations/core/document_migrator.ts b/src/core/server/saved_objects/migrations/core/document_migrator.ts index 07c1da5586107..376f823267ebe 100644 --- a/src/core/server/saved_objects/migrations/core/document_migrator.ts +++ b/src/core/server/saved_objects/migrations/core/document_migrator.ts @@ -183,7 +183,7 @@ function validateMigrationDefinition(registry: ISavedObjectTypeRegistry) { } } - registry.getAllTypes().forEach(type => { + registry.getAllTypes().forEach((type) => { if (type.migrations) { assertObject( type.migrations, @@ -209,7 +209,7 @@ function buildActiveMigrations( ): ActiveMigrations { return typeRegistry .getAllTypes() - .filter(type => type.migrations && Object.keys(type.migrations).length > 0) + .filter((type) => type.migrations && Object.keys(type.migrations).length > 0) .reduce((migrations, type) => { const transforms = Object.entries(type.migrations!) .map(([version, transform]) => ({ @@ -334,7 +334,7 @@ function wrapWithTry( * Finds the first unmigrated property in the specified document. */ function nextUnmigratedProp(doc: SavedObjectUnsanitizedDoc, migrations: ActiveMigrations) { - return props(doc).find(p => { + return props(doc).find((p) => { const latestVersion = propVersion(migrations, p); const docVersion = propVersion(doc, p); @@ -431,7 +431,7 @@ function assertNoDowngrades( } const downgrade = Object.keys(migrationVersion).find( - k => !docVersion.hasOwnProperty(k) || Semver.lt(docVersion[k], migrationVersion[k]) + (k) => !docVersion.hasOwnProperty(k) || Semver.lt(docVersion[k], migrationVersion[k]) ); if (downgrade) { diff --git a/src/core/server/saved_objects/migrations/core/elastic_index.ts b/src/core/server/saved_objects/migrations/core/elastic_index.ts index e7621d88f78ee..e87c3e3ff0d64 100644 --- a/src/core/server/saved_objects/migrations/core/elastic_index.ts +++ b/src/core/server/saved_objects/migrations/core/elastic_index.ts @@ -194,7 +194,7 @@ export async function migrationsUpToDate( throw e; } - await new Promise(r => setTimeout(r, 1000)); + await new Promise((r) => setTimeout(r, 1000)); return await migrationsUpToDate(callCluster, index, migrationVersion, retryCount - 1); } @@ -259,7 +259,7 @@ export async function claimAlias( ) { const result = await callCluster('indices.getAlias', { ignore: [404], name: alias }); const aliasInfo = (result as NotFound).status === 404 ? {} : result; - const removeActions = Object.keys(aliasInfo).map(key => ({ remove: { index: key, alias } })); + const removeActions = Object.keys(aliasInfo).map((key) => ({ remove: { index: key, alias } })); await callCluster('indices.updateAliases', { body: { @@ -347,11 +347,11 @@ async function reindex( let completed = false; while (!completed) { - await new Promise(r => setTimeout(r, pollInterval)); + await new Promise((r) => setTimeout(r, pollInterval)); completed = await callCluster('tasks.get', { taskId: task, - }).then(result => { + }).then((result) => { if (result.error) { const e = result.error; throw new Error(`Re-index failed [${e.type}] ${e.reason} :: ${JSON.stringify(e)}`); diff --git a/src/core/server/saved_objects/migrations/core/index_migrator.test.ts b/src/core/server/saved_objects/migrations/core/index_migrator.test.ts index 19208e6c83596..392089c69f5a0 100644 --- a/src/core/server/saved_objects/migrations/core/index_migrator.test.ts +++ b/src/core/server/saved_objects/migrations/core/index_migrator.test.ts @@ -341,7 +341,7 @@ function withIndex(callCluster: jest.Mock, opts: any = {}) { let scrollCallCounter = 1; - callCluster.mockImplementation(method => { + callCluster.mockImplementation((method) => { if (method === 'indices.get') { return Promise.resolve(index); } else if (method === 'indices.getAlias') { diff --git a/src/core/server/saved_objects/migrations/core/index_migrator.ts b/src/core/server/saved_objects/migrations/core/index_migrator.ts index ef2a8870d78d0..b2ffe2ad04a88 100644 --- a/src/core/server/saved_objects/migrations/core/index_migrator.ts +++ b/src/core/server/saved_objects/migrations/core/index_migrator.ts @@ -153,11 +153,11 @@ async function deleteIndexTemplates({ callCluster, log, obsoleteIndexTemplatePat return; } - const templateNames = templates.map(t => t.name); + const templateNames = templates.map((t) => t.name); log.info(`Removing index templates: ${templateNames}`); - return Promise.all(templateNames.map(name => callCluster('indices.deleteTemplate', { name }))); + return Promise.all(templateNames.map((name) => callCluster('indices.deleteTemplate', { name }))); } /** @@ -190,7 +190,7 @@ async function migrateSourceToDest(context: Context) { return; } - log.debug(`Migrating saved objects ${docs.map(d => d._id).join(', ')}`); + log.debug(`Migrating saved objects ${docs.map((d) => d._id).join(', ')}`); await Index.write( callCluster, diff --git a/src/core/server/saved_objects/migrations/core/migrate_raw_docs.ts b/src/core/server/saved_objects/migrations/core/migrate_raw_docs.ts index 49acea82e1c8a..a2b72ea76c1a2 100644 --- a/src/core/server/saved_objects/migrations/core/migrate_raw_docs.ts +++ b/src/core/server/saved_objects/migrations/core/migrate_raw_docs.ts @@ -39,7 +39,7 @@ export function migrateRawDocs( rawDocs: SavedObjectsRawDoc[], log: SavedObjectsMigrationLogger ): SavedObjectsRawDoc[] { - return rawDocs.map(raw => { + return rawDocs.map((raw) => { if (serializer.isRawSavedObject(raw)) { const savedObject = serializer.rawToSavedObject(raw); savedObject.migrationVersion = savedObject.migrationVersion || {}; diff --git a/src/core/server/saved_objects/migrations/core/migration_coordinator.ts b/src/core/server/saved_objects/migrations/core/migration_coordinator.ts index 5ba2d0afc692e..2e32763f4e637 100644 --- a/src/core/server/saved_objects/migrations/core/migration_coordinator.ts +++ b/src/core/server/saved_objects/migrations/core/migration_coordinator.ts @@ -123,5 +123,5 @@ async function waitForMigration( } function sleep(ms: number) { - return new Promise(r => setTimeout(r, ms)); + return new Promise((r) => setTimeout(r, ms)); } diff --git a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.mock.ts b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.mock.ts index 3f5c0c3876615..fae33bc050dee 100644 --- a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.mock.ts +++ b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.mock.ts @@ -65,7 +65,7 @@ const createMigrator = ( }; mockMigrator.getActiveMappings.mockReturnValue(buildActiveMappings(mergeTypes(types))); - mockMigrator.migrateDocument.mockImplementation(doc => doc); + mockMigrator.migrateDocument.mockImplementation((doc) => doc); return mockMigrator; }; diff --git a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts index cda0e86f15bdf..7a5c044924d0e 100644 --- a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts +++ b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts @@ -25,7 +25,7 @@ import { SavedObjectsType } from '../../types'; const createRegistry = (types: Array>) => { const registry = new SavedObjectTypeRegistry(); - types.forEach(type => + types.forEach((type) => registry.registerType({ name: 'unknown', hidden: false, @@ -77,7 +77,7 @@ describe('KibanaMigrator', () => { // and should only be done once const callClusterCommands = clusterStub.mock.calls .map(([callClusterPath]) => callClusterPath) - .filter(callClusterPath => callClusterPath === 'cat.templates'); + .filter((callClusterPath) => callClusterPath === 'cat.templates'); expect(callClusterCommands.length).toBe(1); }); @@ -87,10 +87,7 @@ describe('KibanaMigrator', () => { options.callCluster = clusterStub; const migrator = new KibanaMigrator(options); - const migratorStatus = migrator - .getStatus$() - .pipe(take(3)) - .toPromise(); + const migratorStatus = migrator.getStatus$().pipe(take(3)).toPromise(); await migrator.runMigrations(); const { status, result } = await migratorStatus; expect(status).toEqual('completed'); diff --git a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.ts b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.ts index 7d9ff9bed6d72..4f69d45c192e9 100644 --- a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.ts +++ b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.ts @@ -125,7 +125,7 @@ export class KibanaMigrator { > { if (this.migrationResult === undefined || rerun) { this.status$.next({ status: 'running' }); - this.migrationResult = this.runMigrationsInternal().then(result => { + this.migrationResult = this.runMigrationsInternal().then((result) => { this.status$.next({ status: 'completed', result }); return result; }); @@ -146,7 +146,7 @@ export class KibanaMigrator { registry: this.typeRegistry, }); - const migrators = Object.keys(indexMap).map(index => { + const migrators = Object.keys(indexMap).map((index) => { return new IndexMigrator({ batchSize: this.savedObjectsConfig.batchSize, callCluster: this.callCluster, @@ -164,7 +164,7 @@ export class KibanaMigrator { }); }); - return Promise.all(migrators.map(migrator => migrator.migrate())); + return Promise.all(migrators.map((migrator) => migrator.migrate())); } /** diff --git a/src/core/server/saved_objects/migrations/mocks.ts b/src/core/server/saved_objects/migrations/mocks.ts index 50a7191393472..1c4e55566b61b 100644 --- a/src/core/server/saved_objects/migrations/mocks.ts +++ b/src/core/server/saved_objects/migrations/mocks.ts @@ -20,7 +20,9 @@ import { SavedObjectMigrationContext } from './types'; import { SavedObjectsMigrationLogger } from './core'; -export const createSavedObjectsMigrationLoggerMock = (): jest.Mocked => { +export const createSavedObjectsMigrationLoggerMock = (): jest.Mocked< + SavedObjectsMigrationLogger +> => { const mock = { debug: jest.fn(), info: jest.fn(), diff --git a/src/core/server/saved_objects/routes/export.ts b/src/core/server/saved_objects/routes/export.ts index 7205699ddc702..9445c144ecda4 100644 --- a/src/core/server/saved_objects/routes/export.ts +++ b/src/core/server/saved_objects/routes/export.ts @@ -61,7 +61,7 @@ export const registerExportRoute = (router: IRouter, config: SavedObjectConfig) // need to access the registry for type validation, can't use the schema for this const supportedTypes = context.core.savedObjects.typeRegistry .getImportableAndExportableTypes() - .map(t => t.name); + .map((t) => t.name); if (types) { const validationError = validateTypes(types, supportedTypes); if (validationError) { diff --git a/src/core/server/saved_objects/routes/import.ts b/src/core/server/saved_objects/routes/import.ts index 0731d4159356d..8fce6f49fb850 100644 --- a/src/core/server/saved_objects/routes/import.ts +++ b/src/core/server/saved_objects/routes/import.ts @@ -63,7 +63,7 @@ export const registerImportRoute = (router: IRouter, config: SavedObjectConfig) const supportedTypes = context.core.savedObjects.typeRegistry .getImportableAndExportableTypes() - .map(type => type.name); + .map((type) => type.name); const result = await importSavedObjectsFromStream({ supportedTypes, diff --git a/src/core/server/saved_objects/routes/integration_tests/export.test.ts b/src/core/server/saved_objects/routes/integration_tests/export.test.ts index 858d34d5a93bf..bdb2e23f0826d 100644 --- a/src/core/server/saved_objects/routes/integration_tests/export.test.ts +++ b/src/core/server/saved_objects/routes/integration_tests/export.test.ts @@ -98,7 +98,7 @@ describe('POST /api/saved_objects/_export', () => { }) ); - const objects = (result.text as string).split('\n').map(row => JSON.parse(row)); + const objects = (result.text as string).split('\n').map((row) => JSON.parse(row)); expect(objects).toEqual(sortedObjects); expect(exportSavedObjectsToStream.mock.calls[0][0]).toEqual( expect.objectContaining({ diff --git a/src/core/server/saved_objects/routes/integration_tests/find.test.ts b/src/core/server/saved_objects/routes/integration_tests/find.test.ts index 907bf44c7748f..7916100e46831 100644 --- a/src/core/server/saved_objects/routes/integration_tests/find.test.ts +++ b/src/core/server/saved_objects/routes/integration_tests/find.test.ts @@ -129,9 +129,7 @@ describe('GET /api/saved_objects/_find', () => { }); it('accepts the optional query parameter has_reference', async () => { - await supertest(httpSetup.server.listener) - .get('/api/saved_objects/_find?type=foo') - .expect(200); + await supertest(httpSetup.server.listener).get('/api/saved_objects/_find?type=foo').expect(200); expect(savedObjectsClient.find).toHaveBeenCalledTimes(1); diff --git a/src/core/server/saved_objects/routes/integration_tests/migrate.test.ts b/src/core/server/saved_objects/routes/integration_tests/migrate.test.ts index 928d17e7e5be2..5bc7d126ace03 100644 --- a/src/core/server/saved_objects/routes/integration_tests/migrate.test.ts +++ b/src/core/server/saved_objects/routes/integration_tests/migrate.test.ts @@ -35,27 +35,18 @@ describe('SavedObjects /_migrate endpoint', () => { }); it('calls runMigrations on the migrator with rerun=true when accessed', async () => { - await kbnTestServer.request - .post(root, '/internal/saved_objects/_migrate') - .send({}) - .expect(200); + await kbnTestServer.request.post(root, '/internal/saved_objects/_migrate').send({}).expect(200); expect(migratorInstanceMock.runMigrations).toHaveBeenCalledTimes(1); expect(migratorInstanceMock.runMigrations).toHaveBeenCalledWith({ rerun: true }); }); it('calls runMigrations multiple time when multiple access', async () => { - await kbnTestServer.request - .post(root, '/internal/saved_objects/_migrate') - .send({}) - .expect(200); + await kbnTestServer.request.post(root, '/internal/saved_objects/_migrate').send({}).expect(200); expect(migratorInstanceMock.runMigrations).toHaveBeenCalledTimes(1); - await kbnTestServer.request - .post(root, '/internal/saved_objects/_migrate') - .send({}) - .expect(200); + await kbnTestServer.request.post(root, '/internal/saved_objects/_migrate').send({}).expect(200); expect(migratorInstanceMock.runMigrations).toHaveBeenCalledTimes(2); }); diff --git a/src/core/server/saved_objects/routes/resolve_import_errors.ts b/src/core/server/saved_objects/routes/resolve_import_errors.ts index 05bff871b3520..3458e601e0fe6 100644 --- a/src/core/server/saved_objects/routes/resolve_import_errors.ts +++ b/src/core/server/saved_objects/routes/resolve_import_errors.ts @@ -74,7 +74,7 @@ export const registerResolveImportErrorsRoute = (router: IRouter, config: SavedO const supportedTypes = context.core.savedObjects.typeRegistry .getImportableAndExportableTypes() - .map(type => type.name); + .map((type) => type.name); const result = await resolveSavedObjectsImportErrors({ supportedTypes, diff --git a/src/core/server/saved_objects/routes/utils.ts b/src/core/server/saved_objects/routes/utils.ts index 5f0db3c4d548c..3963833a9c718 100644 --- a/src/core/server/saved_objects/routes/utils.ts +++ b/src/core/server/saved_objects/routes/utils.ts @@ -37,13 +37,13 @@ export function createSavedObjectsStreamFromNdJson(ndJsonStream: Readable) { ) .pipe( createFilterStream( - obj => !!obj && !(obj as SavedObjectsExportResultDetails).exportedCount + (obj) => !!obj && !(obj as SavedObjectsExportResultDetails).exportedCount ) ); } export function validateTypes(types: string[], supportedTypes: string[]): string | undefined { - const invalidTypes = types.filter(t => !supportedTypes.includes(t)); + const invalidTypes = types.filter((t) => !supportedTypes.includes(t)); if (invalidTypes.length) { return `Trying to export non-exportable type(s): ${invalidTypes.join(', ')}`; } @@ -53,10 +53,10 @@ export function validateObjects( objects: Array<{ id: string; type: string }>, supportedTypes: string[] ): string | undefined { - const invalidObjects = objects.filter(obj => !supportedTypes.includes(obj.type)); + const invalidObjects = objects.filter((obj) => !supportedTypes.includes(obj.type)); if (invalidObjects.length) { return `Trying to export object(s) with non-exportable types: ${invalidObjects - .map(obj => `${obj.type}:${obj.id}`) + .map((obj) => `${obj.type}:${obj.id}`) .join(', ')}`; } } 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 7dea7a017a47d..bff392e8761eb 100644 --- a/src/core/server/saved_objects/saved_objects_service.test.ts +++ b/src/core/server/saved_objects/saved_objects_service.test.ts @@ -46,7 +46,7 @@ describe('SavedObjectsService', () => { env, }: { skipMigration?: boolean; env?: Env } = {}) => { const configService = configServiceMock.create({ atPath: { skip: true } }); - configService.atPath.mockImplementation(path => { + configService.atPath.mockImplementation((path) => { if (path === 'migrations') { return new BehaviorSubject({ skip: skipMigration }); } @@ -192,7 +192,7 @@ describe('SavedObjectsService', () => { expect(migratorInstanceMock.runMigrations).not.toHaveBeenCalled(); }); - it('waits for all es nodes to be compatible before running migrations', async done => { + it('waits for all es nodes to be compatible before running migrations', async (done) => { expect.assertions(2); const coreContext = createCoreContext({ skipMigration: false }); const soService = new SavedObjectsService(coreContext); diff --git a/src/core/server/saved_objects/saved_objects_service.ts b/src/core/server/saved_objects/saved_objects_service.ts index 373b8bd1d2bc6..a822a92acb91a 100644 --- a/src/core/server/saved_objects/saved_objects_service.ts +++ b/src/core/server/saved_objects/saved_objects_service.ts @@ -310,7 +310,7 @@ export class SavedObjectsService setupDeps.legacyPlugins.uiExports, setupDeps.legacyPlugins.pluginExtendedConfig ); - legacyTypes.forEach(type => this.typeRegistry.registerType(type)); + legacyTypes.forEach((type) => this.typeRegistry.registerType(type)); this.validations = setupDeps.legacyPlugins.uiExports.savedObjectValidations || {}; const savedObjectsConfig = await this.coreContext.configService @@ -332,10 +332,10 @@ export class SavedObjectsService return { status$: calculateStatus$( - this.migrator$.pipe(switchMap(migrator => migrator.getStatus$())), + this.migrator$.pipe(switchMap((migrator) => migrator.getStatus$())), setupDeps.elasticsearch.status$ ), - setClientFactoryProvider: provider => { + setClientFactoryProvider: (provider) => { if (this.started) { throw new Error('cannot call `setClientFactoryProvider` after service startup.'); } @@ -354,7 +354,7 @@ export class SavedObjectsService factory, }); }, - registerType: type => { + registerType: (type) => { if (this.started) { throw new Error('cannot call `registerType` after service startup.'); } @@ -415,7 +415,7 @@ export class SavedObjectsService }); await this.setupDeps!.elasticsearch.esNodesCompatibility$.pipe( - filter(nodes => nodes.isCompatible), + filter((nodes) => nodes.isCompatible), take(1) ).toPromise(); diff --git a/src/core/server/saved_objects/saved_objects_type_registry.mock.ts b/src/core/server/saved_objects/saved_objects_type_registry.mock.ts index 8bb66859feca2..5636dcadb444e 100644 --- a/src/core/server/saved_objects/saved_objects_type_registry.mock.ts +++ b/src/core/server/saved_objects/saved_objects_type_registry.mock.ts @@ -19,8 +19,9 @@ import { ISavedObjectTypeRegistry, SavedObjectTypeRegistry } from './saved_objects_type_registry'; -const createRegistryMock = (): jest.Mocked> => { +const createRegistryMock = (): jest.Mocked< + ISavedObjectTypeRegistry & Pick +> => { const mock = { registerType: jest.fn(), getType: jest.fn(), diff --git a/src/core/server/saved_objects/saved_objects_type_registry.test.ts b/src/core/server/saved_objects/saved_objects_type_registry.test.ts index f82822f90f489..e0f4d6fa28e50 100644 --- a/src/core/server/saved_objects/saved_objects_type_registry.test.ts +++ b/src/core/server/saved_objects/saved_objects_type_registry.test.ts @@ -44,7 +44,7 @@ describe('SavedObjectTypeRegistry', () => { expect( registry .getAllTypes() - .map(type => type.name) + .map((type) => type.name) .sort() ).toEqual(['typeA', 'typeB', 'typeC']); }); @@ -300,7 +300,7 @@ describe('SavedObjectTypeRegistry', () => { const types = registry.getImportableAndExportableTypes(); expect(types.length).toEqual(2); - expect(types.map(t => t.name)).toEqual(['typeA', 'typeD']); + expect(types.map((t) => t.name)).toEqual(['typeA', 'typeD']); }); }); }); diff --git a/src/core/server/saved_objects/saved_objects_type_registry.ts b/src/core/server/saved_objects/saved_objects_type_registry.ts index 740313a53d1e2..99262d7a31e21 100644 --- a/src/core/server/saved_objects/saved_objects_type_registry.ts +++ b/src/core/server/saved_objects/saved_objects_type_registry.ts @@ -64,7 +64,7 @@ export class SavedObjectTypeRegistry { * Return all {@link SavedObjectsType | types} currently registered that are importable/exportable. */ public getImportableAndExportableTypes() { - return this.getAllTypes().filter(type => this.isImportableAndExportable(type.name)); + return this.getAllTypes().filter((type) => this.isImportableAndExportable(type.name)); } /** diff --git a/src/core/server/saved_objects/service/lib/filter_utils.ts b/src/core/server/saved_objects/service/lib/filter_utils.ts index 55859f7108b26..4c31f37f63dad 100644 --- a/src/core/server/saved_objects/service/lib/filter_utils.ts +++ b/src/core/server/saved_objects/service/lib/filter_utils.ts @@ -48,22 +48,22 @@ export const validateConvertFilterToKueryNode = ( ); } - if (validationFilterKuery.some(obj => obj.error != null)) { + if (validationFilterKuery.some((obj) => obj.error != null)) { throw SavedObjectsErrorHelpers.createBadRequestError( validationFilterKuery - .filter(obj => obj.error != null) - .map(obj => obj.error) + .filter((obj) => obj.error != null) + .map((obj) => obj.error) .join('\n') ); } - validationFilterKuery.forEach(item => { + validationFilterKuery.forEach((item) => { const path: string[] = item.astPath.length === 0 ? [] : item.astPath.split('.'); const existingKueryNode: KueryNode = path.length === 0 ? filterKueryNode : get(filterKueryNode, path); if (item.isSavedObjectAttr) { existingKueryNode.arguments[0].value = existingKueryNode.arguments[0].value.split('.')[1]; - const itemType = allowedTypes.filter(t => t === item.type); + const itemType = allowedTypes.filter((t) => t === item.type); if (itemType.length === 1) { set( filterKueryNode, diff --git a/src/core/server/saved_objects/service/lib/included_fields.ts b/src/core/server/saved_objects/service/lib/included_fields.ts index c50ac22594008..33bca49e3fc58 100644 --- a/src/core/server/saved_objects/service/lib/included_fields.ts +++ b/src/core/server/saved_objects/service/lib/included_fields.ts @@ -34,7 +34,7 @@ export function includedFields(type: string | string[] = '*', fields?: string[] return sourceType .reduce((acc: string[], t) => { - return [...acc, ...sourceFields.map(f => `${t}.${f}`)]; + return [...acc, ...sourceFields.map((f) => `${t}.${f}`)]; }, []) .concat('namespace') .concat('namespaces') diff --git a/src/core/server/saved_objects/service/lib/priority_collection.test.ts b/src/core/server/saved_objects/service/lib/priority_collection.test.ts index 13180b912e7d7..62f9415927db9 100644 --- a/src/core/server/saved_objects/service/lib/priority_collection.test.ts +++ b/src/core/server/saved_objects/service/lib/priority_collection.test.ts @@ -64,6 +64,6 @@ test(`#has when empty returns false`, () => { test(`#has returns result of predicate`, () => { const priorityCollection = new PriorityCollection(); priorityCollection.add(1, 'foo'); - expect(priorityCollection.has(val => val === 'foo')).toEqual(true); - expect(priorityCollection.has(val => val === 'bar')).toEqual(false); + expect(priorityCollection.has((val) => val === 'foo')).toEqual(true); + expect(priorityCollection.has((val) => val === 'bar')).toEqual(false); }); diff --git a/src/core/server/saved_objects/service/lib/priority_collection.ts b/src/core/server/saved_objects/service/lib/priority_collection.ts index a2fe13b933347..350d549b7e8f2 100644 --- a/src/core/server/saved_objects/service/lib/priority_collection.ts +++ b/src/core/server/saved_objects/service/lib/priority_collection.ts @@ -26,7 +26,7 @@ export class PriorityCollection { private readonly array: Array> = []; public add(priority: number, value: T) { - const foundIndex = this.array.findIndex(current => { + const foundIndex = this.array.findIndex((current) => { if (priority === current.priority) { throw new Error('Already have entry with this priority'); } @@ -39,10 +39,10 @@ export class PriorityCollection { } public has(predicate: (value: T) => boolean): boolean { - return this.array.some(entry => predicate(entry.value)); + return this.array.some((entry) => predicate(entry.value)); } public toPrioritizedArray(): T[] { - return this.array.map(entry => entry.value); + return this.array.map((entry) => entry.value); } } diff --git a/src/core/server/saved_objects/service/lib/repository.test.js b/src/core/server/saved_objects/service/lib/repository.test.js index c46fcfbc6dbd7..83e037fb2da66 100644 --- a/src/core/server/saved_objects/service/lib/repository.test.js +++ b/src/core/server/saved_objects/service/lib/repository.test.js @@ -113,10 +113,10 @@ describe('SavedObjectsRepository', () => { }, }; - const createType = type => ({ + const createType = (type) => ({ name: type, mappings: { properties: mappings.properties[type].properties }, - migrations: { '1.1.1': doc => doc }, + migrations: { '1.1.1': (doc) => doc }, }); const registry = new SavedObjectTypeRegistry(); @@ -171,7 +171,7 @@ describe('SavedObjectsRepository', () => { const getMockMgetResponse = (objects, namespace) => ({ status: 200, - docs: objects.map(obj => + docs: objects.map((obj) => obj.found === false ? obj : getMockGetResponse({ ...obj, namespace }) ), }); @@ -202,10 +202,11 @@ describe('SavedObjectsRepository', () => { const expectSuccess = ({ type, id }) => expect.toBeDocumentWithoutError(type, id); const expectError = ({ type, id }) => ({ type, id, error: expect.any(Object) }); const expectErrorResult = ({ type, id }, error) => ({ type, id, error }); - const expectErrorNotFound = obj => + const expectErrorNotFound = (obj) => expectErrorResult(obj, createGenericNotFoundError(obj.type, obj.id)); - const expectErrorConflict = obj => expectErrorResult(obj, createConflictError(obj.type, obj.id)); - const expectErrorInvalidType = obj => + const expectErrorConflict = (obj) => + expectErrorResult(obj, createConflictError(obj.type, obj.id)); + const expectErrorInvalidType = (obj) => expectErrorResult(obj, createUnsupportedTypeError(obj.type, obj.id)); const expectMigrationArgs = (args, contains = true, n = 1) => { @@ -229,12 +230,12 @@ describe('SavedObjectsRepository', () => { trimIdPrefix: jest.fn(), }; const _serializer = new SavedObjectsSerializer(registry); - Object.keys(serializer).forEach(key => { + Object.keys(serializer).forEach((key) => { serializer[key].mockImplementation((...args) => _serializer[key](...args)); }); - const allTypes = registry.getAllTypes().map(type => type.name); - const allowedTypes = [...new Set(allTypes.filter(type => !registry.isHidden(type)))]; + const allTypes = registry.getAllTypes().map((type) => type.name); + const allowedTypes = [...new Set(allTypes.filter((type) => !registry.isHidden(type)))]; savedObjectsRepository = new SavedObjectsRepository({ index: '.kibana-test', @@ -251,7 +252,7 @@ describe('SavedObjectsRepository', () => { }); const mockMigrationVersion = { foo: '2.3.4' }; - const mockMigrateDocument = doc => ({ + const mockMigrateDocument = (doc) => ({ ...doc, attributes: { ...doc.attributes, @@ -345,7 +346,7 @@ describe('SavedObjectsRepository', () => { }); it(`throws when type is not multi-namespace`, async () => { - const test = async type => { + const test = async (type) => { const message = `${type} doesn't support multiple namespaces`; await expectBadRequestError(type, id, [newNs1, newNs2], message); expect(callAdminCluster).not.toHaveBeenCalled(); @@ -355,7 +356,7 @@ describe('SavedObjectsRepository', () => { }); it(`throws when namespaces is an empty array`, async () => { - const test = async namespaces => { + const test = async (namespaces) => { const message = 'namespaces must be a non-empty array of strings'; await expectBadRequestError(type, id, namespaces, message); expect(callAdminCluster).not.toHaveBeenCalled(); @@ -489,7 +490,7 @@ describe('SavedObjectsRepository', () => { }), ]; - const expectSuccessResult = obj => ({ + const expectSuccessResult = (obj) => ({ ...obj, migrationVersion: { [obj.type]: '1.1.1' }, version: mockVersion, @@ -511,13 +512,13 @@ describe('SavedObjectsRepository', () => { }); it(`should use the ES create method if ID is undefined and overwrite=true`, async () => { - const objects = [obj1, obj2].map(obj => ({ ...obj, id: undefined })); + const objects = [obj1, obj2].map((obj) => ({ ...obj, id: undefined })); await bulkCreateSuccess(objects, { overwrite: true }); expectClusterCallArgsAction(objects, { method: 'create' }); }); it(`should use the ES create method if ID is undefined and overwrite=false`, async () => { - const objects = [obj1, obj2].map(obj => ({ ...obj, id: undefined })); + const objects = [obj1, obj2].map((obj) => ({ ...obj, id: undefined })); await bulkCreateSuccess(objects); expectClusterCallArgsAction(objects, { method: 'create' }); }); @@ -557,8 +558,8 @@ describe('SavedObjectsRepository', () => { }); it(`adds namespaces to request body for any types that are multi-namespace`, async () => { - const test = async namespace => { - const objects = [obj1, obj2].map(x => ({ ...x, type: MULTI_NAMESPACE_TYPE })); + const test = async (namespace) => { + const objects = [obj1, obj2].map((x) => ({ ...x, type: MULTI_NAMESPACE_TYPE })); const namespaces = [namespace ?? 'default']; await bulkCreateSuccess(objects, { namespace, overwrite: true }); const expected = expect.objectContaining({ namespaces }); @@ -571,7 +572,7 @@ describe('SavedObjectsRepository', () => { }); it(`doesn't add namespaces to request body for any types that are not multi-namespace`, async () => { - const test = async namespace => { + const test = async (namespace) => { const objects = [obj1, { ...obj2, type: NAMESPACE_AGNOSTIC_TYPE }]; await bulkCreateSuccess(objects, { namespace, overwrite: true }); const expected = expect.not.objectContaining({ namespaces: expect.anything() }); @@ -600,7 +601,7 @@ describe('SavedObjectsRepository', () => { }); it(`should use custom index`, async () => { - await bulkCreateSuccess([obj1, obj2].map(x => ({ ...x, type: CUSTOM_INDEX_TYPE }))); + await bulkCreateSuccess([obj1, obj2].map((x) => ({ ...x, type: CUSTOM_INDEX_TYPE }))); expectClusterCallArgsAction([obj1, obj2], { method: 'create', _index: 'custom' }); }); @@ -730,11 +731,11 @@ describe('SavedObjectsRepository', () => { it(`migrates the docs and serializes the migrated docs`, async () => { migrator.migrateDocument.mockImplementation(mockMigrateDocument); await bulkCreateSuccess([obj1, obj2]); - const docs = [obj1, obj2].map(x => ({ ...x, ...mockTimestampFields })); + const docs = [obj1, obj2].map((x) => ({ ...x, ...mockTimestampFields })); expectMigrationArgs(docs[0], true, 1); expectMigrationArgs(docs[1], true, 2); - const migratedDocs = docs.map(x => migrator.migrateDocument(x)); + const migratedDocs = docs.map((x) => migrator.migrateDocument(x)); expect(serializer.savedObjectToRaw).toHaveBeenNthCalledWith(1, migratedDocs[0]); expect(serializer.savedObjectToRaw).toHaveBeenNthCalledWith(2, migratedDocs[1]); }); @@ -762,14 +763,14 @@ describe('SavedObjectsRepository', () => { }); it(`adds namespaces to body when providing namespace for multi-namespace type`, async () => { - const objects = [obj1, obj2].map(obj => ({ ...obj, type: MULTI_NAMESPACE_TYPE })); + const objects = [obj1, obj2].map((obj) => ({ ...obj, type: MULTI_NAMESPACE_TYPE })); await bulkCreateSuccess(objects, { namespace }); expectMigrationArgs({ namespaces: [namespace] }, true, 1); expectMigrationArgs({ namespaces: [namespace] }, true, 2); }); it(`adds default namespaces to body when providing no namespace for multi-namespace type`, async () => { - const objects = [obj1, obj2].map(obj => ({ ...obj, type: MULTI_NAMESPACE_TYPE })); + const objects = [obj1, obj2].map((obj) => ({ ...obj, type: MULTI_NAMESPACE_TYPE })); await bulkCreateSuccess(objects); expectMigrationArgs({ namespaces: ['default'] }, true, 1); expectMigrationArgs({ namespaces: ['default'] }, true, 2); @@ -787,7 +788,7 @@ describe('SavedObjectsRepository', () => { it(`formats the ES response`, async () => { const result = await bulkCreateSuccess([obj1, obj2]); expect(result).toEqual({ - saved_objects: [obj1, obj2].map(x => expectSuccessResult(x)), + saved_objects: [obj1, obj2].map((x) => expectSuccessResult(x)), }); }); @@ -909,12 +910,12 @@ describe('SavedObjectsRepository', () => { it(`doesn't prepend namespace to the id when not using single-namespace type`, async () => { const getId = (type, id) => `${type}:${id}`; - let objects = [obj1, obj2].map(obj => ({ ...obj, type: NAMESPACE_AGNOSTIC_TYPE })); + let objects = [obj1, obj2].map((obj) => ({ ...obj, type: NAMESPACE_AGNOSTIC_TYPE })); await bulkGetSuccess(objects, { namespace }); _expectClusterCallArgs(objects, { getId }); callAdminCluster.mockReset(); - objects = [obj1, obj2].map(obj => ({ ...obj, type: MULTI_NAMESPACE_TYPE })); + objects = [obj1, obj2].map((obj) => ({ ...obj, type: MULTI_NAMESPACE_TYPE })); await bulkGetSuccess(objects, { namespace }); _expectClusterCallArgs(objects, { getId }); }); @@ -1136,7 +1137,7 @@ describe('SavedObjectsRepository', () => { }); it(`doesnt call Elasticsearch if there are no valid objects to update`, async () => { - const objects = [obj1, obj2].map(x => ({ ...x, type: 'unknownType' })); + const objects = [obj1, obj2].map((x) => ({ ...x, type: 'unknownType' })); await savedObjectsRepository.bulkUpdate(objects); expect(callAdminCluster).toHaveBeenCalledTimes(0); }); @@ -1149,8 +1150,8 @@ describe('SavedObjectsRepository', () => { }); it(`accepts custom references array`, async () => { - const test = async references => { - const objects = [obj1, obj2].map(obj => ({ ...obj, references })); + const test = async (references) => { + const objects = [obj1, obj2].map((obj) => ({ ...obj, references })); await bulkUpdateSuccess(objects); const expected = { doc: expect.objectContaining({ references }) }; const body = [expect.any(Object), expected, expect.any(Object), expected]; @@ -1163,8 +1164,8 @@ describe('SavedObjectsRepository', () => { }); it(`doesn't accept custom references if not an array`, async () => { - const test = async references => { - const objects = [obj1, obj2].map(obj => ({ ...obj, references })); + const test = async (references) => { + const objects = [obj1, obj2].map((obj) => ({ ...obj, references })); await bulkUpdateSuccess(objects); const expected = { doc: expect.not.objectContaining({ references: expect.anything() }) }; const body = [expect.any(Object), expected, expect.any(Object), expected]; @@ -1366,7 +1367,7 @@ describe('SavedObjectsRepository', () => { }); it(`includes references`, async () => { - const objects = [obj1, obj2].map(obj => ({ ...obj, references })); + const objects = [obj1, obj2].map((obj) => ({ ...obj, references })); const response = await bulkUpdateSuccess(objects); expect(response).toEqual({ saved_objects: objects.map(expectSuccessResult), @@ -1463,7 +1464,7 @@ describe('SavedObjectsRepository', () => { }); it(`accepts custom references array`, async () => { - const test = async references => { + const test = async (references) => { await createSuccess(type, attributes, { id, references }); expectClusterCallArgs({ body: expect.objectContaining({ references }), @@ -1476,7 +1477,7 @@ describe('SavedObjectsRepository', () => { }); it(`doesn't accept custom references if not an array`, async () => { - const test = async references => { + const test = async (references) => { await createSuccess(type, attributes, { id, references }); expectClusterCallArgs({ body: expect.not.objectContaining({ references: expect.anything() }), @@ -1871,7 +1872,7 @@ describe('SavedObjectsRepository', () => { describe('errors', () => { it(`throws when namespace is not a string`, async () => { - const test = async namespace => { + const test = async (namespace) => { await expect(savedObjectsRepository.deleteByNamespace(namespace)).rejects.toThrowError( `namespace is required, and must be a string` ); @@ -1904,17 +1905,17 @@ describe('SavedObjectsRepository', () => { describe('search dsl', () => { it(`constructs a query using all multi-namespace types, and another using all single-namespace types`, async () => { await deleteByNamespaceSuccess(namespace); - const allTypes = registry.getAllTypes().map(type => type.name); + const allTypes = registry.getAllTypes().map((type) => type.name); expect(getSearchDslNS.getSearchDsl).toHaveBeenCalledWith(mappings, registry, { namespace, - type: allTypes.filter(type => !registry.isNamespaceAgnostic(type)), + type: allTypes.filter((type) => !registry.isNamespaceAgnostic(type)), }); }); }); }); describe('#find', () => { - const generateSearchResults = namespace => { + const generateSearchResults = (namespace) => { return { hits: { total: 4, @@ -2038,7 +2039,7 @@ describe('SavedObjectsRepository', () => { }); it(`should not make a cluster call when attempting to find only invalid or hidden types`, async () => { - const test = async types => { + const test = async (types) => { await savedObjectsRepository.find({ type: types }); expect(callAdminCluster).not.toHaveBeenCalled(); }; @@ -2154,7 +2155,7 @@ describe('SavedObjectsRepository', () => { }); it(`should return empty results when attempting to find only invalid or hidden types`, async () => { - const test = async types => { + const test = async (types) => { const result = await savedObjectsRepository.find({ type: types }); expect(result).toEqual(expect.objectContaining({ saved_objects: [] })); }; @@ -2468,7 +2469,7 @@ describe('SavedObjectsRepository', () => { }; it(`throws when type is not a string`, async () => { - const test = async type => { + const test = async (type) => { await expect( savedObjectsRepository.incrementCounter(type, id, field) ).rejects.toThrowError(`"type" argument must be a string`); @@ -2482,7 +2483,7 @@ describe('SavedObjectsRepository', () => { }); it(`throws when counterFieldName is not a string`, async () => { - const test = async field => { + const test = async (field) => { await expect( savedObjectsRepository.incrementCounter(type, id, field) ).rejects.toThrowError(`"counterFieldName" argument must be a string`); @@ -2610,7 +2611,7 @@ describe('SavedObjectsRepository', () => { options ) => { mockGetResponse(type, id, currentNamespaces); // this._callCluster('get', ...) - const isDelete = currentNamespaces.every(namespace => namespaces.includes(namespace)); + const isDelete = currentNamespaces.every((namespace) => namespaces.includes(namespace)); callAdminCluster.mockResolvedValue({ _id: `${type}:${id}`, ...mockVersionProps, @@ -2629,7 +2630,7 @@ describe('SavedObjectsRepository', () => { describe('cluster calls', () => { describe('delete action', () => { const deleteFromNamespacesSuccessDelete = async (expectFn, options, _type = type) => { - const test = async namespaces => { + const test = async (namespaces) => { await deleteFromNamespacesSuccess(_type, id, namespaces, namespaces, options); expectFn(); callAdminCluster.mockReset(); @@ -2680,7 +2681,7 @@ describe('SavedObjectsRepository', () => { describe('update action', () => { const deleteFromNamespacesSuccessUpdate = async (expectFn, options, _type = type) => { - const test = async remaining => { + const test = async (remaining) => { const currentNamespaces = [namespace1].concat(remaining); await deleteFromNamespacesSuccess(_type, id, [namespace1], currentNamespaces, options); expectFn(); @@ -2761,7 +2762,7 @@ describe('SavedObjectsRepository', () => { }); it(`throws when type is not namespace-agnostic`, async () => { - const test = async type => { + const test = async (type) => { const message = `${type} doesn't support multiple namespaces`; await expectBadRequestError(type, id, [namespace1, namespace2], message); expect(callAdminCluster).not.toHaveBeenCalled(); @@ -2771,7 +2772,7 @@ describe('SavedObjectsRepository', () => { }); it(`throws when namespaces is an empty array`, async () => { - const test = async namespaces => { + const test = async (namespaces) => { const message = 'namespaces must be a non-empty array of strings'; await expectBadRequestError(type, id, namespaces, message); expect(callAdminCluster).not.toHaveBeenCalled(); @@ -2844,7 +2845,7 @@ describe('SavedObjectsRepository', () => { describe('returns', () => { it(`returns an empty object on success (delete)`, async () => { - const test = async namespaces => { + const test = async (namespaces) => { const result = await deleteFromNamespacesSuccess(type, id, namespaces, namespaces); expect(result).toEqual({}); callAdminCluster.mockReset(); @@ -2854,7 +2855,7 @@ describe('SavedObjectsRepository', () => { }); it(`returns an empty object on success (update)`, async () => { - const test = async remaining => { + const test = async (remaining) => { const currentNamespaces = [namespace1].concat(remaining); const result = await deleteFromNamespacesSuccess( type, @@ -2929,7 +2930,7 @@ describe('SavedObjectsRepository', () => { }); it(`accepts custom references array`, async () => { - const test = async references => { + const test = async (references) => { await updateSuccess(type, id, attributes, { references }); expectClusterCallArgs({ body: { doc: expect.objectContaining({ references }) }, @@ -2942,7 +2943,7 @@ describe('SavedObjectsRepository', () => { }); it(`doesn't accept custom references if not an array`, async () => { - const test = async references => { + const test = async (references) => { await updateSuccess(type, id, attributes, { references }); expectClusterCallArgs({ body: { doc: expect.not.objectContaining({ references: expect.anything() }) }, diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts index f76b05c4af1b9..e23f8dec5927c 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -138,9 +138,9 @@ export class SavedObjectsRepository { const mappings = migrator.getActiveMappings(); const allTypes = Object.keys(getRootPropertiesObjects(mappings)); const serializer = new SavedObjectsSerializer(typeRegistry); - const visibleTypes = allTypes.filter(type => !typeRegistry.isHidden(type)); + const visibleTypes = allTypes.filter((type) => !typeRegistry.isHidden(type)); - const missingTypeMappings = includedHiddenTypes.filter(type => !allTypes.includes(type)); + const missingTypeMappings = includedHiddenTypes.filter((type) => !allTypes.includes(type)); if (missingTypeMappings.length > 0) { throw new Error( `Missing mappings for saved objects types: '${missingTypeMappings.join(', ')}'` @@ -284,7 +284,7 @@ export class SavedObjectsRepository { const time = this._getCurrentTime(); let bulkGetRequestIndexCounter = 0; - const expectedResults: Either[] = objects.map(object => { + const expectedResults: Either[] = objects.map((object) => { if (!this._allowedTypes.includes(object.type)) { return { tag: 'Left' as 'Left', @@ -331,7 +331,7 @@ export class SavedObjectsRepository { let bulkRequestIndexCounter = 0; const bulkCreateParams: object[] = []; - const expectedBulkResults: Either[] = expectedResults.map(expectedBulkGetResult => { + const expectedBulkResults: Either[] = expectedResults.map((expectedBulkGetResult) => { if (isLeft(expectedBulkGetResult)) { return expectedBulkGetResult; } @@ -401,7 +401,7 @@ export class SavedObjectsRepository { : undefined; return { - saved_objects: expectedBulkResults.map(expectedResult => { + saved_objects: expectedBulkResults.map((expectedResult) => { if (isLeft(expectedResult)) { return expectedResult.error as any; } @@ -453,7 +453,7 @@ export class SavedObjectsRepository { preflightResult = await this.preflightCheckIncludesNamespace(type, id, namespace); const existingNamespaces = getSavedObjectNamespaces(undefined, preflightResult); const remainingNamespaces = existingNamespaces?.filter( - x => x !== getNamespaceString(namespace) + (x) => x !== getNamespaceString(namespace) ); if (remainingNamespaces?.length) { @@ -530,7 +530,7 @@ export class SavedObjectsRepository { const { refresh = DEFAULT_REFRESH_SETTING } = options; const allTypes = Object.keys(getRootPropertiesObjects(this._mappings)); - const typesToUpdate = allTypes.filter(type => !this._registry.isNamespaceAgnostic(type)); + const typesToUpdate = allTypes.filter((type) => !this._registry.isNamespaceAgnostic(type)); const updateOptions = { index: this.getIndicesForTypes(typesToUpdate), @@ -599,7 +599,7 @@ export class SavedObjectsRepository { } const types = Array.isArray(type) ? type : [type]; - const allowedTypes = types.filter(t => this._allowedTypes.includes(t)); + const allowedTypes = types.filter((t) => this._allowedTypes.includes(t)); if (allowedTypes.length === 0) { return { page, @@ -702,7 +702,7 @@ export class SavedObjectsRepository { } let bulkGetRequestIndexCounter = 0; - const expectedBulkGetResults: Either[] = objects.map(object => { + const expectedBulkGetResults: Either[] = objects.map((object) => { const { type, id, fields } = object; if (!this._allowedTypes.includes(type)) { @@ -744,7 +744,7 @@ export class SavedObjectsRepository { : undefined; return { - saved_objects: expectedBulkGetResults.map(expectedResult => { + saved_objects: expectedBulkGetResults.map((expectedResult) => { if (isLeft(expectedResult)) { return expectedResult.error as any; } @@ -981,7 +981,7 @@ export class SavedObjectsRepository { const preflightResult = await this.preflightCheckIncludesNamespace(type, id, namespace); const existingNamespaces = getSavedObjectNamespaces(undefined, preflightResult); // if there are somehow no existing namespaces, allow the operation to proceed and delete this saved object - const remainingNamespaces = existingNamespaces?.filter(x => !namespaces.includes(x)); + const remainingNamespaces = existingNamespaces?.filter((x) => !namespaces.includes(x)); if (remainingNamespaces?.length) { // if there is 1 or more namespace remaining, update the saved object @@ -1057,7 +1057,7 @@ export class SavedObjectsRepository { const { namespace } = options; let bulkGetRequestIndexCounter = 0; - const expectedBulkGetResults: Either[] = objects.map(object => { + const expectedBulkGetResults: Either[] = objects.map((object) => { const { type, id } = object; if (!this._allowedTypes.includes(type)) { @@ -1113,7 +1113,7 @@ export class SavedObjectsRepository { let bulkUpdateRequestIndexCounter = 0; const bulkUpdateParams: object[] = []; const expectedBulkUpdateResults: Either[] = expectedBulkGetResults.map( - expectedBulkGetResult => { + (expectedBulkGetResult) => { if (isLeft(expectedBulkGetResult)) { return expectedBulkGetResult; } @@ -1173,7 +1173,7 @@ export class SavedObjectsRepository { : {}; return { - saved_objects: expectedBulkUpdateResults.map(expectedResult => { + saved_objects: expectedBulkUpdateResults.map((expectedResult) => { if (isLeft(expectedResult)) { return expectedResult.error as any; } @@ -1326,7 +1326,7 @@ export class SavedObjectsRepository { * @param types The types whose indices should be retrieved */ private getIndicesForTypes(types: string[]) { - return unique(types.map(t => this.getIndexForType(t))); + return unique(types.map((t) => this.getIndexForType(t))); } private _getCurrentTime() { diff --git a/src/core/server/saved_objects/service/lib/scoped_client_provider.ts b/src/core/server/saved_objects/service/lib/scoped_client_provider.ts index 3250737e1287d..ab80f37e6652f 100644 --- a/src/core/server/saved_objects/service/lib/scoped_client_provider.ts +++ b/src/core/server/saved_objects/service/lib/scoped_client_provider.ts @@ -107,7 +107,7 @@ export class SavedObjectsClientProvider { id: string, factory: SavedObjectsClientWrapperFactory ): void { - if (this._wrapperFactories.has(entry => entry.id === id)) { + if (this._wrapperFactories.has((entry) => entry.id === id)) { throw new Error(`wrapper factory with id ${id} is already defined`); } diff --git a/src/core/server/saved_objects/service/lib/search_dsl/query_params.test.ts b/src/core/server/saved_objects/service/lib/search_dsl/query_params.test.ts index a72c21dd5eee4..a0ffa91f53671 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/query_params.test.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/query_params.test.ts @@ -43,11 +43,11 @@ const MAPPINGS = { const ALL_TYPES = Object.keys(MAPPINGS.properties); // get all possible subsets (combination) of all types const ALL_TYPE_SUBSETS = ALL_TYPES.reduce( - (subsets, value) => subsets.concat(subsets.map(set => [...set, value])), + (subsets, value) => subsets.concat(subsets.map((set) => [...set, value])), [[] as string[]] ) - .filter(x => x.length) // exclude empty set - .map(x => (x.length === 1 ? x[0] : x)); // if a subset is a single string, destructure it + .filter((x) => x.length) // exclude empty set + .map((x) => (x.length === 1 ? x[0] : x)); // if a subset is a single string, destructure it /** * Note: these tests cases are defined in the order they appear in the source code, for readability's sake @@ -163,7 +163,7 @@ describe('#getQueryParams', () => { expect.arrayContaining([ { bool: expect.objectContaining({ - should: types.map(type => ({ + should: types.map((type) => ({ bool: expect.objectContaining({ must: expect.arrayContaining([{ term: { type } }]), }), @@ -233,11 +233,11 @@ describe('#getQueryParams', () => { for (const typeOrTypes of ALL_TYPE_SUBSETS) { const result = getQueryParams({ mappings, registry, type: typeOrTypes, namespace }); const types = Array.isArray(typeOrTypes) ? typeOrTypes : [typeOrTypes]; - expectResult(result, ...types.map(x => createTypeClause(x, namespace))); + expectResult(result, ...types.map((x) => createTypeClause(x, namespace))); } // also test with no specified type/s const result = getQueryParams({ mappings, registry, type: undefined, namespace }); - expectResult(result, ...ALL_TYPES.map(x => createTypeClause(x, namespace))); + expectResult(result, ...ALL_TYPES.map((x) => createTypeClause(x, namespace))); }; it('filters results with "namespace" field when `namespace` is not specified', () => { @@ -280,7 +280,7 @@ describe('#getQueryParams', () => { describe('`searchFields` parameter', () => { const getExpectedFields = (searchFields: string[], typeOrTypes: string | string[]) => { const types = Array.isArray(typeOrTypes) ? typeOrTypes : [typeOrTypes]; - return searchFields.map(x => types.map(y => `${y}.${x}`)).flat(); + return searchFields.map((x) => types.map((y) => `${y}.${x}`)).flat(); }; const test = (searchFields: string[]) => { diff --git a/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts b/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts index 967ce8bceaf84..40485564176a6 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts @@ -51,7 +51,7 @@ function getFieldsForTypes(types: string[], searchFields?: string[]) { let fields: string[] = []; for (const field of searchFields) { - fields = fields.concat(types.map(prefix => `${prefix}.${field}`)); + fields = fields.concat(types.map((prefix) => `${prefix}.${field}`)); } return { fields }; @@ -152,7 +152,7 @@ export function getQueryParams({ }, ] : undefined, - should: types.map(shouldType => getClauseForType(registry, namespace, shouldType)), + should: types.map((shouldType) => getClauseForType(registry, namespace, shouldType)), minimum_should_match: 1, }, }, diff --git a/src/core/server/saved_objects/status.ts b/src/core/server/saved_objects/status.ts index 66a6e2baa17a7..1823fbe95b8ba 100644 --- a/src/core/server/saved_objects/status.ts +++ b/src/core/server/saved_objects/status.ts @@ -28,7 +28,7 @@ export const calculateStatus$ = ( elasticsearchStatus$: Observable ): Observable> => { const migratorStatus$: Observable> = rawMigratorStatus$.pipe( - map(migrationStatus => { + map((migrationStatus) => { if (migrationStatus.status === 'waiting') { return { level: ServiceStatusLevels.unavailable, diff --git a/src/core/server/saved_objects/utils.test.ts b/src/core/server/saved_objects/utils.test.ts index 033aeea7c018d..21229bee489c2 100644 --- a/src/core/server/saved_objects/utils.test.ts +++ b/src/core/server/saved_objects/utils.test.ts @@ -142,7 +142,7 @@ describe('convertLegacyTypes', () => { }); it('invokes indexPattern to retrieve the index when it is a function', () => { - const indexPatternAccessor: (config: LegacyConfig) => string = jest.fn(config => { + const indexPatternAccessor: (config: LegacyConfig) => string = jest.fn((config) => { config.get('foo.bar'); return 'myIndex'; }); @@ -301,13 +301,13 @@ describe('convertLegacyTypes', () => { isImportableAndExportable: true, icon: 'iconA', defaultSearchField: 'searchFieldA', - getTitle: savedObject => savedObject.id, + getTitle: (savedObject) => savedObject.id, }, typeB: { isImportableAndExportable: false, icon: 'iconB', - getEditUrl: savedObject => `/some-url/${savedObject.id}`, - getInAppUrl: savedObject => ({ path: 'path', uiCapabilitiesPath: 'ui-path' }), + getEditUrl: (savedObject) => `/some-url/${savedObject.id}`, + getInAppUrl: (savedObject) => ({ path: 'path', uiCapabilitiesPath: 'ui-path' }), }, }, savedObjectMigrations: {}, @@ -377,7 +377,7 @@ describe('convertLegacyTypes', () => { }, savedObjectSchemas: { typeA: { - indexPattern: jest.fn(config => { + indexPattern: jest.fn((config) => { config.get('foo.bar'); return 'myIndex'; }), diff --git a/src/core/server/saved_objects/validation/index.ts b/src/core/server/saved_objects/validation/index.ts index 98dc6254178c5..b1b33f91d3fd4 100644 --- a/src/core/server/saved_objects/validation/index.ts +++ b/src/core/server/saved_objects/validation/index.ts @@ -57,7 +57,7 @@ export function docValidator(validators: PropertyValidators = {}): ValidateDoc { return function validateDoc(doc: SavedObjectDoc) { Object.keys(doc) .concat(doc.type) - .forEach(prop => { + .forEach((prop) => { const validator = validators[prop]; if (validator) { validator(doc); diff --git a/src/core/server/status/status_service.test.ts b/src/core/server/status/status_service.test.ts index 6d92a266369b9..b692cf3161901 100644 --- a/src/core/server/status/status_service.test.ts +++ b/src/core/server/status/status_service.test.ts @@ -93,7 +93,7 @@ describe('StatusService', () => { }); const statusUpdates: CoreStatus[] = []; - const subscription = setup.core$.subscribe(status => statusUpdates.push(status)); + const subscription = setup.core$.subscribe((status) => statusUpdates.push(status)); elasticsearch$.next(available); elasticsearch$.next(available); @@ -198,7 +198,7 @@ describe('StatusService', () => { }); const statusUpdates: ServiceStatus[] = []; - const subscription = setup.overall$.subscribe(status => statusUpdates.push(status)); + const subscription = setup.overall$.subscribe((status) => statusUpdates.push(status)); elasticsearch$.next(available); elasticsearch$.next(available); diff --git a/src/core/server/status/status_service.ts b/src/core/server/status/status_service.ts index b6697d8221951..ef7bed9587245 100644 --- a/src/core/server/status/status_service.ts +++ b/src/core/server/status/status_service.ts @@ -47,7 +47,7 @@ export class StatusService implements CoreService { public setup(core: SetupDeps) { const core$ = this.setupCoreStatus(core); const overall$: Observable = core$.pipe( - map(coreStatus => { + map((coreStatus) => { const summary = getSummaryStatus(Object.entries(coreStatus)); this.logger.debug(`Recalculated overall status`, { status: summary }); return summary; diff --git a/src/core/server/ui_settings/create_or_upgrade_saved_config/create_or_upgrade_saved_config.test.ts b/src/core/server/ui_settings/create_or_upgrade_saved_config/create_or_upgrade_saved_config.test.ts index eab96cc80c883..9c5a0625e8fd0 100644 --- a/src/core/server/ui_settings/create_or_upgrade_saved_config/create_or_upgrade_saved_config.test.ts +++ b/src/core/server/ui_settings/create_or_upgrade_saved_config/create_or_upgrade_saved_config.test.ts @@ -27,7 +27,7 @@ import { getUpgradeableConfigMock } from './get_upgradeable_config.test.mock'; import { createOrUpgradeSavedConfig } from './create_or_upgrade_saved_config'; const chance = new Chance(); -describe('uiSettings/createOrUpgradeSavedConfig', function() { +describe('uiSettings/createOrUpgradeSavedConfig', function () { afterEach(() => jest.resetAllMocks()); const version = '4.0.1'; @@ -73,7 +73,7 @@ describe('uiSettings/createOrUpgradeSavedConfig', function() { }; } - describe('nothing is upgradeable', function() { + describe('nothing is upgradeable', function () { it('should create config with current version and buildNum', async () => { const { run, savedObjectsClient } = setup(); diff --git a/src/core/server/ui_settings/create_or_upgrade_saved_config/get_upgradeable_config.ts b/src/core/server/ui_settings/create_or_upgrade_saved_config/get_upgradeable_config.ts index a916d4c3317a6..abf33658db545 100644 --- a/src/core/server/ui_settings/create_or_upgrade_saved_config/get_upgradeable_config.ts +++ b/src/core/server/ui_settings/create_or_upgrade_saved_config/get_upgradeable_config.ts @@ -43,5 +43,5 @@ export async function getUpgradeableConfig({ }); // try to find a config that we can upgrade - return savedConfigs.find(savedConfig => isConfigVersionUpgradeable(savedConfig.id, version)); + return savedConfigs.find((savedConfig) => isConfigVersionUpgradeable(savedConfig.id, version)); } diff --git a/src/core/server/ui_settings/create_or_upgrade_saved_config/integration_tests/create_or_upgrade.test.ts b/src/core/server/ui_settings/create_or_upgrade_saved_config/integration_tests/create_or_upgrade.test.ts index 218de8e7acb3a..49d8137a65d39 100644 --- a/src/core/server/ui_settings/create_or_upgrade_saved_config/integration_tests/create_or_upgrade.test.ts +++ b/src/core/server/ui_settings/create_or_upgrade_saved_config/integration_tests/create_or_upgrade.test.ts @@ -38,9 +38,9 @@ describe('createOrUpgradeSavedConfig()', () => { let kbnServer: TestKibanaUtils['kbnServer']; - beforeAll(async function() { + beforeAll(async function () { servers = createTestServers({ - adjustTimeout: t => { + adjustTimeout: (t) => { jest.setTimeout(t); }, }); @@ -86,7 +86,7 @@ describe('createOrUpgradeSavedConfig()', () => { await kbn.stop(); }, 30000); - it('upgrades the previous version on each increment', async function() { + it('upgrades the previous version on each increment', async function () { jest.setTimeout(30000); // ------------------------------------ // upgrade to 5.4.0 diff --git a/src/core/server/ui_settings/create_or_upgrade_saved_config/is_config_version_upgradeable.test.ts b/src/core/server/ui_settings/create_or_upgrade_saved_config/is_config_version_upgradeable.test.ts index feb63817fe073..5d8c4b01d0664 100644 --- a/src/core/server/ui_settings/create_or_upgrade_saved_config/is_config_version_upgradeable.test.ts +++ b/src/core/server/ui_settings/create_or_upgrade_saved_config/is_config_version_upgradeable.test.ts @@ -19,7 +19,7 @@ import { isConfigVersionUpgradeable } from './is_config_version_upgradeable'; -describe('savedObjects/health_check/isConfigVersionUpgradeable', function() { +describe('savedObjects/health_check/isConfigVersionUpgradeable', function () { function isUpgradeableTest(savedVersion: string, kibanaVersion: string, expected: boolean) { it(`should return ${expected} for config version ${savedVersion} and kibana version ${kibanaVersion}`, () => { expect(isConfigVersionUpgradeable(savedVersion, kibanaVersion)).toBe(expected); diff --git a/src/core/server/ui_settings/integration_tests/index.test.ts b/src/core/server/ui_settings/integration_tests/index.test.ts index db271761b39ea..e704532ee4cdf 100644 --- a/src/core/server/ui_settings/integration_tests/index.test.ts +++ b/src/core/server/ui_settings/integration_tests/index.test.ts @@ -23,7 +23,7 @@ import { docExistsSuite } from './doc_exists'; import { docMissingSuite } from './doc_missing'; import { docMissingAndIndexReadOnlySuite } from './doc_missing_and_index_read_only'; -describe('uiSettings/routes', function() { +describe('uiSettings/routes', function () { /** * The "doc missing" and "index missing" tests verify how the uiSettings * API behaves in between healthChecks, so they interact with the healthCheck diff --git a/src/core/server/ui_settings/integration_tests/lib/servers.ts b/src/core/server/ui_settings/integration_tests/lib/servers.ts index 57448541d68c5..486abd5a0c790 100644 --- a/src/core/server/ui_settings/integration_tests/lib/servers.ts +++ b/src/core/server/ui_settings/integration_tests/lib/servers.ts @@ -46,7 +46,7 @@ let services: AllServices; export async function startServers() { servers = createTestServers({ - adjustTimeout: t => jest.setTimeout(t), + adjustTimeout: (t) => jest.setTimeout(t), settings: { kbn: { uiSettings: { diff --git a/src/core/server/ui_settings/ui_settings_client.ts b/src/core/server/ui_settings/ui_settings_client.ts index 76c8284175f11..f168784a93330 100644 --- a/src/core/server/ui_settings/ui_settings_client.ts +++ b/src/core/server/ui_settings/ui_settings_client.ts @@ -122,7 +122,7 @@ export class UiSettingsClient implements IUiSettingsClient { async removeMany(keys: string[]) { const changes: Record = {}; - keys.forEach(key => { + keys.forEach((key) => { changes[key] = null; }); await this.setMany(changes); diff --git a/src/core/server/utils/crypto/pkcs12.test.ts b/src/core/server/utils/crypto/pkcs12.test.ts index e9eb72fe395ff..ccfeea27c79c6 100644 --- a/src/core/server/utils/crypto/pkcs12.test.ts +++ b/src/core/server/utils/crypto/pkcs12.test.ts @@ -65,7 +65,7 @@ describe('#readPkcs12Keystore', () => { }; const expectCA = (pkcs12ReadResult: Pkcs12ReadResult, ca = [pemCA]) => { - const result = pkcs12ReadResult.ca?.map(x => reformatPem(x)); + const result = pkcs12ReadResult.ca?.map((x) => reformatPem(x)); expect(result).toEqual(ca); }; @@ -199,7 +199,7 @@ describe('#readPkcs12Keystore', () => { describe('#readPkcs12Truststore', () => { it('reads all certificates into one CA array and discards any certificates that have keys', () => { const ca = readPkcs12Truststore(ES_P12_PATH, ES_P12_PASSWORD); - const result = ca?.map(x => reformatPem(x)); + const result = ca?.map((x) => reformatPem(x)); expect(result).toEqual([pemCA]); }); }); diff --git a/src/core/server/utils/crypto/pkcs12.ts b/src/core/server/utils/crypto/pkcs12.ts index 74f22bb685c2f..7de68a71ad72e 100644 --- a/src/core/server/utils/crypto/pkcs12.ts +++ b/src/core/server/utils/crypto/pkcs12.ts @@ -115,9 +115,9 @@ const getCerts = (p12: pkcs12.Pkcs12Pfx, pubKey?: PublicKeyData) => { let ca; let cert; if (bags && bags.length) { - const certs = bags.map(convertCert).filter(x => x !== undefined); - cert = certs.find(x => doesPubKeyMatch(x!.publicKeyData, pubKey))?.cert; - ca = certs.filter(x => !doesPubKeyMatch(x!.publicKeyData, pubKey)).map(x => x!.cert); + const certs = bags.map(convertCert).filter((x) => x !== undefined); + cert = certs.find((x) => doesPubKeyMatch(x!.publicKeyData, pubKey))?.cert; + ca = certs.filter((x) => !doesPubKeyMatch(x!.publicKeyData, pubKey)).map((x) => x!.cert); if (ca.length === 0) { ca = undefined; } diff --git a/src/core/server/uuid/resolve_uuid.test.ts b/src/core/server/uuid/resolve_uuid.test.ts index efc90c07c1fa6..eab027b532ddb 100644 --- a/src/core/server/uuid/resolve_uuid.test.ts +++ b/src/core/server/uuid/resolve_uuid.test.ts @@ -68,7 +68,7 @@ const mockWriteFile = (error?: object) => { const getConfigService = (serverUuid: string | undefined) => { const configService = configServiceMock.create(); - configService.atPath.mockImplementation(path => { + configService.atPath.mockImplementation((path) => { if (path === 'path') { return new BehaviorSubject({ data: 'data-folder', diff --git a/src/core/server/uuid/resolve_uuid.ts b/src/core/server/uuid/resolve_uuid.ts index 516357e10d3f7..c3e79cc519a1b 100644 --- a/src/core/server/uuid/resolve_uuid.ts +++ b/src/core/server/uuid/resolve_uuid.ts @@ -44,14 +44,8 @@ export async function resolveInstanceUuid({ logger: Logger; }): Promise { const [pathConfig, serverConfig] = await Promise.all([ - configService - .atPath(pathConfigDef.path) - .pipe(take(1)) - .toPromise(), - configService - .atPath(httpConfigDef.path) - .pipe(take(1)) - .toPromise(), + configService.atPath(pathConfigDef.path).pipe(take(1)).toPromise(), + configService.atPath(httpConfigDef.path).pipe(take(1)).toPromise(), ]); const uuidFilePath = join(pathConfig.data, FILE_NAME); diff --git a/src/core/utils/context.test.ts b/src/core/utils/context.test.ts index 4bfeddc2e08c9..dcc6c63bcf545 100644 --- a/src/core/utils/context.test.ts +++ b/src/core/utils/context.test.ts @@ -75,24 +75,24 @@ describe('ContextContainer', () => { coreId ); expect.assertions(8); - contextContainer.registerContext(coreId, 'core1', context => { + contextContainer.registerContext(coreId, 'core1', (context) => { expect(context).toEqual({}); return 'core'; }); - contextContainer.registerContext(pluginA, 'ctxFromA', context => { + contextContainer.registerContext(pluginA, 'ctxFromA', (context) => { expect(context).toEqual({ core1: 'core' }); return 'aString'; }); - contextContainer.registerContext(pluginB, 'ctxFromB', context => { + contextContainer.registerContext(pluginB, 'ctxFromB', (context) => { expect(context).toEqual({ core1: 'core', ctxFromA: 'aString' }); return 299; }); - contextContainer.registerContext(pluginC, 'ctxFromC', context => { + contextContainer.registerContext(pluginC, 'ctxFromC', (context) => { expect(context).toEqual({ core1: 'core', ctxFromA: 'aString', ctxFromB: 299 }); return false; }); - contextContainer.registerContext(pluginD, 'ctxFromD', context => { + contextContainer.registerContext(pluginD, 'ctxFromD', (context) => { expect(context).toEqual({ core1: 'core' }); return {}; }); @@ -129,13 +129,13 @@ describe('ContextContainer', () => { coreId ); contextContainer - .registerContext(pluginA, 'ctxFromA', context => { + .registerContext(pluginA, 'ctxFromA', (context) => { expect(context).toEqual({ core1: 'core', core2: 101 }); return `aString ${context.core1} ${context.core2}`; }) .registerContext(coreId, 'core1', () => 'core') .registerContext(coreId, 'core2', () => 101) - .registerContext(pluginB, 'ctxFromB', context => { + .registerContext(pluginB, 'ctxFromB', (context) => { expect(context).toEqual({ core1: 'core', core2: 101, ctxFromA: 'aString core 101' }); return 277; }); @@ -161,11 +161,11 @@ describe('ContextContainer', () => { ); contextContainer - .registerContext(coreId, 'core1', context => { + .registerContext(coreId, 'core1', (context) => { expect(context).toEqual({}); return 'core'; }) - .registerContext(coreId, 'core2', context => { + .registerContext(coreId, 'core2', (context) => { expect(context).toEqual({ core1: 'core' }); return 101; }); @@ -189,8 +189,8 @@ describe('ContextContainer', () => { ); contextContainer - .registerContext(coreId, 'core1', context => 'core') - .registerContext(pluginA, 'ctxFromA', context => 'aString'); + .registerContext(coreId, 'core1', (context) => 'core') + .registerContext(pluginA, 'ctxFromA', (context) => 'aString'); const rawHandler1 = jest.fn(() => 'handler1'); const handler1 = contextContainer.createHandler(coreId, rawHandler1); diff --git a/src/core/utils/context.ts b/src/core/utils/context.ts index de311f91d56fa..941bbceb0cd92 100644 --- a/src/core/utils/context.ts +++ b/src/core/utils/context.ts @@ -304,7 +304,7 @@ export class ContextContainer> // Contexts source created ...(this.contextNamesBySource.get(pluginId) || []), // Contexts sources's dependencies created - ...flatten(pluginDeps.map(p => this.contextNamesBySource.get(p) || [])), + ...flatten(pluginDeps.map((p) => this.contextNamesBySource.get(p) || [])), ]); } } diff --git a/src/core/utils/integration_tests/deep_freeze.test.ts b/src/core/utils/integration_tests/deep_freeze.test.ts index e6625542bc38a..f58e298fecfbf 100644 --- a/src/core/utils/integration_tests/deep_freeze.test.ts +++ b/src/core/utils/integration_tests/deep_freeze.test.ts @@ -30,7 +30,7 @@ it( execa('tsc', ['--noEmit'], { cwd: resolve(__dirname, '__fixtures__/frozen_object_mutation'), preferLocal: true, - }).catch(err => err.stdout) + }).catch((err) => err.stdout) ).resolves.toMatchInlineSnapshot(` "index.ts(28,12): error TS2540: Cannot assign to 'baz' because it is a read-only property. index.ts(36,11): error TS2540: Cannot assign to 'bar' because it is a read-only property." diff --git a/src/core/utils/map_utils.ts b/src/core/utils/map_utils.ts index 47a1d6b34b99f..2f6ec94da1283 100644 --- a/src/core/utils/map_utils.ts +++ b/src/core/utils/map_utils.ts @@ -27,7 +27,7 @@ export function mapValuesOfMap(map: Map, mapper: (item: G) => H): export function groupIntoMap(collection: T[], groupBy: (item: T) => G): Map { const map = new Map(); - collection.forEach(item => { + collection.forEach((item) => { const key = groupBy(item); const values = map.get(key) || []; values.push(item); diff --git a/src/core/utils/promise.test.ts b/src/core/utils/promise.test.ts index 97d16c5158c7b..b78b6bc5120f9 100644 --- a/src/core/utils/promise.test.ts +++ b/src/core/utils/promise.test.ts @@ -20,7 +20,7 @@ import { withTimeout } from './promise'; const delay = (ms: number, resolveValue?: any) => - new Promise(resolve => setTimeout(resolve, ms, resolveValue)); + new Promise((resolve) => setTimeout(resolve, ms, resolveValue)); describe('withTimeout', () => { it('resolves with a promise value if resolved in given timeout', async () => { @@ -44,7 +44,7 @@ describe('withTimeout', () => { await expect( withTimeout({ - promise: new Promise(i => i), + promise: new Promise((i) => i), timeout: 10, errorMessage: 'error-message', }) diff --git a/src/core/utils/unset.ts b/src/core/utils/unset.ts index 8008d4ee08ba3..88bf2503c6d69 100644 --- a/src/core/utils/unset.ts +++ b/src/core/utils/unset.ts @@ -32,8 +32,8 @@ import { get } from './get'; export function unset(obj: OBJ, atPath: string) { const paths = atPath .split('.') - .map(s => s.trim()) - .filter(v => v !== ''); + .map((s) => s.trim()) + .filter((v) => v !== ''); if (paths.length === 0) { return; } diff --git a/src/core/utils/url.test.ts b/src/core/utils/url.test.ts index 419c0cda2b8cb..7e9b6adfd3f49 100644 --- a/src/core/utils/url.test.ts +++ b/src/core/utils/url.test.ts @@ -32,7 +32,7 @@ describe('modifyUrl()', () => { test('supports modifying the passed object', () => { expect( - modifyUrl('http://localhost', parsed => { + modifyUrl('http://localhost', (parsed) => { parsed.port = '9999'; parsed.auth = 'foo:bar'; return parsed; @@ -42,7 +42,7 @@ describe('modifyUrl()', () => { test('supports changing pathname', () => { expect( - modifyUrl('http://localhost/some/path', parsed => { + modifyUrl('http://localhost/some/path', (parsed) => { parsed.pathname += '/subpath'; return parsed; }) @@ -51,7 +51,7 @@ describe('modifyUrl()', () => { test('supports changing port', () => { expect( - modifyUrl('http://localhost:5601', parsed => { + modifyUrl('http://localhost:5601', (parsed) => { parsed.port = (Number(parsed.port!) + 1).toString(); return parsed; }) @@ -60,7 +60,7 @@ describe('modifyUrl()', () => { test('supports changing protocol', () => { expect( - modifyUrl('http://localhost', parsed => { + modifyUrl('http://localhost', (parsed) => { parsed.protocol = 'mail'; parsed.slashes = false; parsed.pathname = null; diff --git a/src/dev/build/args.ts b/src/dev/build/args.ts index 49bb8e150fcdc..f411e4c962093 100644 --- a/src/dev/build/args.ts +++ b/src/dev/build/args.ts @@ -63,7 +63,7 @@ export function readCliArgs(argv: string[]): ParsedArgs { oss: null, 'version-qualifier': '', }, - unknown: flag => { + unknown: (flag) => { unknownFlags.push(flag); return false; }, diff --git a/src/dev/build/cli.js b/src/dev/build/cli.js index f23832dfcdd56..a42930f57f82d 100644 --- a/src/dev/build/cli.js +++ b/src/dev/build/cli.js @@ -62,7 +62,7 @@ if (showHelp) { process.exit(1); } -buildDistributables({ log, ...buildArgs }).catch(error => { +buildDistributables({ log, ...buildArgs }).catch((error) => { if (!isErrorLogged(error)) { log.error('Uncaught error'); log.error(error); diff --git a/src/dev/build/lib/__tests__/config.js b/src/dev/build/lib/__tests__/config.js index d9238ad1eef43..d2f408378da25 100644 --- a/src/dev/build/lib/__tests__/config.js +++ b/src/dev/build/lib/__tests__/config.js @@ -26,7 +26,7 @@ import { getConfig } from '../config'; import { getVersionInfo } from '../version_info'; describe('dev/build/lib/config', () => { - const setup = async function({ targetAllPlatforms = true } = {}) { + const setup = async function ({ targetAllPlatforms = true } = {}) { const isRelease = Boolean(Math.round(Math.random())); const config = await getConfig({ isRelease, @@ -78,7 +78,7 @@ describe('dev/build/lib/config', () => { expect( config .getTargetPlatforms() - .map(p => p.getName()) + .map((p) => p.getName()) .sort() ).to.eql(['darwin', 'linux', 'windows']); }); @@ -99,7 +99,7 @@ describe('dev/build/lib/config', () => { expect( config .getTargetPlatforms() - .map(p => p.getName()) + .map((p) => p.getName()) .sort() ).to.eql(['darwin', 'linux', 'windows']); }); diff --git a/src/dev/build/lib/__tests__/exec.js b/src/dev/build/lib/__tests__/exec.js index 4123c0e3e8ed1..8e122c65132ac 100644 --- a/src/dev/build/lib/__tests__/exec.js +++ b/src/dev/build/lib/__tests__/exec.js @@ -31,7 +31,7 @@ describe('dev/build/lib/exec', () => { const log = new ToolingLog({ level: 'verbose', writeTo: { - write: chunk => { + write: (chunk) => { onLogLine(stripAnsi(chunk)); }, }, diff --git a/src/dev/build/lib/__tests__/fs.js b/src/dev/build/lib/__tests__/fs.js index 9125ace28ce8a..0b2db4c538fb8 100644 --- a/src/dev/build/lib/__tests__/fs.js +++ b/src/dev/build/lib/__tests__/fs.js @@ -35,9 +35,7 @@ const isWindows = /^win/.test(process.platform); // get the mode of a file as a string, like 777, or 644, function getCommonMode(path) { - return statSync(path) - .mode.toString(8) - .slice(-3); + return statSync(path).mode.toString(8).slice(-3); } function assertNonAbsoluteError(error) { diff --git a/src/dev/build/lib/__tests__/runner.js b/src/dev/build/lib/__tests__/runner.js index 0cf68ed1152cd..314c2dd45d50f 100644 --- a/src/dev/build/lib/__tests__/runner.js +++ b/src/dev/build/lib/__tests__/runner.js @@ -46,8 +46,8 @@ describe('dev/build/lib/runner', () => { getLogTag: sinon.match.func, }); - const ossBuildMatcher = buildMatcher.and(sinon.match(b => b.isOss(), 'is oss build')); - const defaultBuildMatcher = buildMatcher.and(sinon.match(b => !b.isOss(), 'is not oss build')); + const ossBuildMatcher = buildMatcher.and(sinon.match((b) => b.isOss(), 'is oss build')); + const defaultBuildMatcher = buildMatcher.and(sinon.match((b) => !b.isOss(), 'is not oss build')); afterEach(() => sandbox.reset()); @@ -159,9 +159,7 @@ describe('dev/build/lib/runner', () => { }); throw new Error('expected run() to reject'); } catch (error) { - expect(error) - .to.have.property('message') - .be('FOO'); + expect(error).to.have.property('message').be('FOO'); sinon.assert.calledWith(onLogLine, sinon.match(/FOO/)); expect(isErrorLogged(error)).to.be(true); } @@ -177,9 +175,7 @@ describe('dev/build/lib/runner', () => { throw new Error('expected run() to reject'); } catch (error) { - expect(error) - .to.have.property('message') - .be('FOO'); + expect(error).to.have.property('message').be('FOO'); sinon.assert.neverCalledWith(onLogLine, sinon.match(/FOO/)); expect(isErrorLogged(error)).to.be(true); } diff --git a/src/dev/build/lib/__tests__/version_info.js b/src/dev/build/lib/__tests__/version_info.js index a4e9b49a570e6..a7329642e4f9a 100644 --- a/src/dev/build/lib/__tests__/version_info.js +++ b/src/dev/build/lib/__tests__/version_info.js @@ -34,10 +34,7 @@ describe('dev/build/lib/version_info', () => { expect(versionInfo) .to.have.property('buildSha') .match(/^[0-9a-f]{40}$/); - expect(versionInfo) - .to.have.property('buildNumber') - .a('number') - .greaterThan(1000); + expect(versionInfo).to.have.property('buildNumber').a('number').greaterThan(1000); }); }); describe('isRelease = false', () => { @@ -54,10 +51,7 @@ describe('dev/build/lib/version_info', () => { expect(versionInfo) .to.have.property('buildSha') .match(/^[0-9a-f]{40}$/); - expect(versionInfo) - .to.have.property('buildNumber') - .a('number') - .greaterThan(1000); + expect(versionInfo).to.have.property('buildNumber').a('number').greaterThan(1000); }); }); diff --git a/src/dev/build/lib/config.js b/src/dev/build/lib/config.js index aed47da421460..cd762d9bb1f20 100644 --- a/src/dev/build/lib/config.js +++ b/src/dev/build/lib/config.js @@ -112,7 +112,7 @@ export async function getConfig({ isRelease, targetAllPlatforms, versionQualifie * @return {Platform} */ getLinuxPlatform() { - return platforms.find(p => p.isLinux()); + return platforms.find((p) => p.isLinux()); } /** @@ -120,7 +120,7 @@ export async function getConfig({ isRelease, targetAllPlatforms, versionQualifie * @return {Platform} */ getWindowsPlatform() { - return platforms.find(p => p.isWindows()); + return platforms.find((p) => p.isWindows()); } /** @@ -128,7 +128,7 @@ export async function getConfig({ isRelease, targetAllPlatforms, versionQualifie * @return {Platform} */ getMacPlatform() { - return platforms.find(p => p.isMac()); + return platforms.find((p) => p.isMac()); } /** diff --git a/src/dev/build/lib/exec.js b/src/dev/build/lib/exec.js index c83bc13a44302..5e47500c72c5c 100644 --- a/src/dev/build/lib/exec.js +++ b/src/dev/build/lib/exec.js @@ -34,5 +34,5 @@ export async function exec(log, cmd, args, options = {}) { preferLocal: true, }); - await watchStdioForLine(proc, line => log[level](line), exitAfter); + await watchStdioForLine(proc, (line) => log[level](line), exitAfter); } diff --git a/src/dev/build/lib/fs.js b/src/dev/build/lib/fs.js index 278f6851f3421..864a07e837c3f 100644 --- a/src/dev/build/lib/fs.js +++ b/src/dev/build/lib/fs.js @@ -82,7 +82,7 @@ export async function read(path) { export async function getChildPaths(path) { assertAbsolute(path); const childNames = await readdirAsync(path); - return childNames.map(name => resolve(path, name)); + return childNames.map((name) => resolve(path, name)); } export async function deleteAll(patterns, log) { @@ -122,8 +122,8 @@ export async function deleteEmptyFolders(log, rootFolderPath, foldersToKeep) { // Delete empty is used to gather all the empty folders and // then we use del to actually delete them const emptyFoldersList = await deleteEmpty(rootFolderPath, { dryRun: true }); - const foldersToDelete = emptyFoldersList.filter(folderToDelete => { - return !foldersToKeep.some(folderToKeep => folderToDelete.includes(folderToKeep)); + const foldersToDelete = emptyFoldersList.filter((folderToDelete) => { + return !foldersToKeep.some((folderToKeep) => folderToDelete.includes(folderToKeep)); }); const deletedEmptyFolders = await del(foldersToDelete, { concurrency: 4, @@ -159,7 +159,7 @@ export async function copyAll(sourceDir, destination, options = {}) { base: destination, dot, }), - createMapStream(file => utimesAsync(file.path, time, time)), + createMapStream((file) => utimesAsync(file.path, time, time)), ]); } } @@ -171,7 +171,7 @@ export async function getFileHash(path, algo) { const readStream = fs.createReadStream(path); await new Promise((resolve, reject) => { readStream - .on('data', chunk => hash.update(chunk)) + .on('data', (chunk) => hash.update(chunk)) .on('error', reject) .on('end', resolve); }); diff --git a/src/dev/build/lib/scan.ts b/src/dev/build/lib/scan.ts index 45e61ca051879..1d77101bdfdb2 100644 --- a/src/dev/build/lib/scan.ts +++ b/src/dev/build/lib/scan.ts @@ -50,7 +50,7 @@ export function scan$(directory: string) { return Rx.concat( [path], getStat$(path).pipe( - mergeMap(stat => (stat.isDirectory() ? getChildPath$(path) : Rx.EMPTY)), + mergeMap((stat) => (stat.isDirectory() ? getChildPath$(path) : Rx.EMPTY)), mergeMap(getPaths$) ) ); diff --git a/src/dev/build/lib/scan_copy.test.ts b/src/dev/build/lib/scan_copy.test.ts index cda009f9137f8..ba693770445dc 100644 --- a/src/dev/build/lib/scan_copy.test.ts +++ b/src/dev/build/lib/scan_copy.test.ts @@ -31,10 +31,7 @@ const FIXTURES = resolve(__dirname, '__tests__/fixtures'); const WORLD_EXECUTABLE = resolve(FIXTURES, 'bin/world_executable'); const TMP = resolve(__dirname, '__tests__/__tmp__'); -const getCommonMode = (path: string) => - statSync(path) - .mode.toString(8) - .slice(-3); +const getCommonMode = (path: string) => statSync(path).mode.toString(8).slice(-3); // ensure WORLD_EXECUTABLE is actually executable by all beforeAll(async () => { @@ -104,7 +101,7 @@ it('applies filter function specified', async () => { await scanCopy({ source: FIXTURES, destination, - filter: record => !record.name.includes('bar'), + filter: (record) => !record.name.includes('bar'), }); expect((await getChildPaths(resolve(destination, 'foo_dir'))).sort()).toEqual([ diff --git a/src/dev/build/lib/scan_copy.ts b/src/dev/build/lib/scan_copy.ts index 0a4bfdc8d0b4f..7fa2d9b9d25a3 100644 --- a/src/dev/build/lib/scan_copy.ts +++ b/src/dev/build/lib/scan_copy.ts @@ -72,20 +72,20 @@ export async function scanCopy(options: Options) { const getChildRecords = async (parent: Record) => { const names = await readdirAsync(parent.absolute); const records = await Promise.all( - names.map(async name => { + names.map(async (name) => { const absolute = join(parent.absolute, name); const stat = await statAsync(absolute); return new Record(stat.isDirectory(), name, absolute, join(parent.absoluteDest, name)); }) ); - return records.filter(record => (filter ? filter(record) : true)); + return records.filter((record) => (filter ? filter(record) : true)); }; // create or copy each child of a directory const copyChildren = async (record: Record) => { const children = await getChildRecords(record); - await Promise.all(children.map(async child => await copy(child))); + await Promise.all(children.map(async (child) => await copy(child))); }; // create or copy a record and recurse into directories diff --git a/src/dev/build/lib/scan_delete.ts b/src/dev/build/lib/scan_delete.ts index cb4e64ce1b5f9..6e41d207e3111 100644 --- a/src/dev/build/lib/scan_delete.ts +++ b/src/dev/build/lib/scan_delete.ts @@ -49,7 +49,7 @@ export async function scanDelete(options: Options) { const { directory, regularExpressions, concurrency = 20, excludePaths } = options; assertAbsolute(directory); - (excludePaths || []).forEach(excluded => assertAbsolute(excluded)); + (excludePaths || []).forEach((excluded) => assertAbsolute(excluded)); // get an observable of absolute paths within a directory const getChildPath$ = (path: string) => @@ -66,12 +66,12 @@ export async function scanDelete(options: Options) { return Rx.EMPTY; } - if (regularExpressions.some(re => re.test(path))) { + if (regularExpressions.some((re) => re.test(path))) { return Rx.of(path); } return getStat$(path).pipe( - mergeMap(stat => (stat.isDirectory() ? getChildPath$(path) : Rx.EMPTY)), + mergeMap((stat) => (stat.isDirectory() ? getChildPath$(path) : Rx.EMPTY)), mergeMap(getPathsToDelete$) ); }; @@ -79,7 +79,7 @@ export async function scanDelete(options: Options) { return await Rx.of(directory) .pipe( mergeMap(getPathsToDelete$), - mergeMap(async path => await del(path), concurrency), + mergeMap(async (path) => await del(path), concurrency), count() ) .toPromise(); diff --git a/src/dev/build/tasks/clean_tasks.js b/src/dev/build/tasks/clean_tasks.js index b23db67cc1b07..ec38dd8a1195c 100644 --- a/src/dev/build/tasks/clean_tasks.js +++ b/src/dev/build/tasks/clean_tasks.js @@ -63,8 +63,8 @@ export const CleanExtraFilesFromModulesTask = { description: 'Cleaning tests, examples, docs, etc. from node_modules', async run(config, log, build) { - const makeRegexps = patterns => - patterns.map(pattern => minimatch.makeRe(pattern, { nocase: true })); + const makeRegexps = (patterns) => + patterns.map((pattern) => minimatch.makeRe(pattern, { nocase: true })); const regularExpressions = makeRegexps([ // tests @@ -205,12 +205,12 @@ export const CleanExtraBrowsersTask = { description: 'Cleaning extra browsers from platform-specific builds', async run(config, log, build) { - const getBrowserPathsForPlatform = platform => { + const getBrowserPathsForPlatform = (platform) => { const reportingDir = 'x-pack/legacy/plugins/reporting'; const chromiumDir = '.chromium'; - const chromiumPath = p => + const chromiumPath = (p) => build.resolvePathForPlatform(platform, reportingDir, chromiumDir, p); - return platforms => { + return (platforms) => { const paths = []; if (platforms.windows) { paths.push(chromiumPath('chromium-*-win32.zip')); diff --git a/src/dev/build/tasks/create_archives_sources_task.js b/src/dev/build/tasks/create_archives_sources_task.js index 999fb0481bd4b..53cf750f484a1 100644 --- a/src/dev/build/tasks/create_archives_sources_task.js +++ b/src/dev/build/tasks/create_archives_sources_task.js @@ -24,7 +24,7 @@ export const CreateArchivesSourcesTask = { description: 'Creating platform-specific archive source directories', async run(config, log, build) { await Promise.all( - config.getTargetPlatforms().map(async platform => { + config.getTargetPlatforms().map(async (platform) => { // copy all files from generic build source directory into platform-specific build directory await scanCopy({ source: build.resolvePath(), diff --git a/src/dev/build/tasks/create_package_json_task.js b/src/dev/build/tasks/create_package_json_task.js index b65d3615633a5..e7a410b4c6350 100644 --- a/src/dev/build/tasks/create_package_json_task.js +++ b/src/dev/build/tasks/create_package_json_task.js @@ -50,7 +50,9 @@ export const CreatePackageJsonTask = { }; if (build.isOss()) { - newPkg.workspaces.packages = newPkg.workspaces.packages.filter(p => !p.startsWith('x-pack')); + newPkg.workspaces.packages = newPkg.workspaces.packages.filter( + (p) => !p.startsWith('x-pack') + ); } await write(build.resolvePath('package.json'), JSON.stringify(newPkg, null, ' ')); diff --git a/src/dev/build/tasks/nodejs/__tests__/download.js b/src/dev/build/tasks/nodejs/__tests__/download.js index 81ed7a6195ae7..49cb9caaaf4ec 100644 --- a/src/dev/build/tasks/nodejs/__tests__/download.js +++ b/src/dev/build/tasks/nodejs/__tests__/download.js @@ -62,7 +62,7 @@ describe('src/dev/build/tasks/nodejs/download', () => { }); const FOO_SHA256 = '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae'; - const createSendHandler = send => (req, res) => { + const createSendHandler = (send) => (req, res) => { res.statusCode = 200; res.end(send); }; @@ -91,7 +91,7 @@ describe('src/dev/build/tasks/nodejs/download', () => { new Promise((resolve, reject) => { server.once('error', reject); }), - new Promise(resolve => { + new Promise((resolve) => { server.listen(resolve); }), ]); @@ -206,9 +206,7 @@ describe('src/dev/build/tasks/nodejs/download', () => { }); throw new Error('Expected download() to reject'); } catch (error) { - expect(error) - .to.have.property('message') - .contain('Request failed with status code 500'); + expect(error).to.have.property('message').contain('Request failed with status code 500'); expect(reqCount).to.be(6); } }); @@ -232,9 +230,7 @@ describe('src/dev/build/tasks/nodejs/download', () => { throw new Error('expected download() to reject'); } catch (error) { - expect(error) - .to.have.property('message') - .contain('refusing to download'); + expect(error).to.have.property('message').contain('refusing to download'); } }); }); diff --git a/src/dev/build/tasks/nodejs/__tests__/download_node_builds_task.js b/src/dev/build/tasks/nodejs/__tests__/download_node_builds_task.js index 4c94ed776417d..9357735e3f5a3 100644 --- a/src/dev/build/tasks/nodejs/__tests__/download_node_builds_task.js +++ b/src/dev/build/tasks/nodejs/__tests__/download_node_builds_task.js @@ -91,9 +91,7 @@ describe('src/dev/build/tasks/nodejs/download_node_builds_task', () => { await DownloadNodeBuildsTask.run(config, log); throw new Error('Expected DownloadNodeBuildsTask to reject'); } catch (error) { - expect(error) - .to.have.property('message') - .be('Download failed for reasons'); + expect(error).to.have.property('message').be('Download failed for reasons'); } }); }); diff --git a/src/dev/build/tasks/nodejs/__tests__/verify_existing_node_builds_task.js b/src/dev/build/tasks/nodejs/__tests__/verify_existing_node_builds_task.js index 0fc151258d779..a8f732a869d2d 100644 --- a/src/dev/build/tasks/nodejs/__tests__/verify_existing_node_builds_task.js +++ b/src/dev/build/tasks/nodejs/__tests__/verify_existing_node_builds_task.js @@ -58,7 +58,7 @@ describe('src/dev/build/tasks/nodejs/verify_existing_node_builds_task', () => { } ); - sandbox.stub(FsNS, 'getFileHash').callsFake(path => { + sandbox.stub(FsNS, 'getFileHash').callsFake((path) => { switch (path) { case 'foo:downloadPath': return 'foo:sha256'; diff --git a/src/dev/build/tasks/nodejs/download.js b/src/dev/build/tasks/nodejs/download.js index 0bd10e5b84015..fb3294e2d1221 100644 --- a/src/dev/build/tasks/nodejs/download.js +++ b/src/dev/build/tasks/nodejs/download.js @@ -62,7 +62,7 @@ export async function download(options) { const hash = createHash('sha256'); await new Promise((resolve, reject) => { - response.data.on('data', chunk => { + response.data.on('data', (chunk) => { hash.update(chunk); writeSync(fileHandle, chunk); }); diff --git a/src/dev/build/tasks/nodejs/download_node_builds_task.js b/src/dev/build/tasks/nodejs/download_node_builds_task.js index df841960677c1..86ddb0506f972 100644 --- a/src/dev/build/tasks/nodejs/download_node_builds_task.js +++ b/src/dev/build/tasks/nodejs/download_node_builds_task.js @@ -27,7 +27,7 @@ export const DownloadNodeBuildsTask = { async run(config, log) { const shasums = await getNodeShasums(config.getNodeVersion()); await Promise.all( - config.getNodePlatforms().map(async platform => { + config.getNodePlatforms().map(async (platform) => { const { url, downloadPath, downloadName } = getNodeDownloadInfo(config, platform); await download({ log, diff --git a/src/dev/build/tasks/nodejs/extract_node_builds_task.js b/src/dev/build/tasks/nodejs/extract_node_builds_task.js index 68e56ac7d4aa6..caf0a389b4cc0 100644 --- a/src/dev/build/tasks/nodejs/extract_node_builds_task.js +++ b/src/dev/build/tasks/nodejs/extract_node_builds_task.js @@ -32,7 +32,7 @@ export const ExtractNodeBuildsTask = { description: 'Extracting node.js builds for all platforms', async run(config) { await Promise.all( - config.getNodePlatforms().map(async platform => { + config.getNodePlatforms().map(async (platform) => { const { downloadPath, extractDir } = getNodeDownloadInfo(config, platform); // windows executable is not extractable, it's just an .exe file if (platform.isWindows()) { diff --git a/src/dev/build/tasks/nodejs/verify_existing_node_builds_task.js b/src/dev/build/tasks/nodejs/verify_existing_node_builds_task.js index 1a6adcd5d1db4..b320471fda33f 100644 --- a/src/dev/build/tasks/nodejs/verify_existing_node_builds_task.js +++ b/src/dev/build/tasks/nodejs/verify_existing_node_builds_task.js @@ -28,7 +28,7 @@ export const VerifyExistingNodeBuildsTask = { const shasums = await getNodeShasums(config.getNodeVersion()); await Promise.all( - config.getNodePlatforms().map(async platform => { + config.getNodePlatforms().map(async (platform) => { const { downloadPath, downloadName } = getNodeDownloadInfo(config, platform); const sha256 = await getFileHash(downloadPath, 'sha256'); diff --git a/src/dev/build/tasks/nodejs_modules/clean_client_modules_on_dll_task.js b/src/dev/build/tasks/nodejs_modules/clean_client_modules_on_dll_task.js index 8e8d69a4dfefa..05bfd3ca31a65 100644 --- a/src/dev/build/tasks/nodejs_modules/clean_client_modules_on_dll_task.js +++ b/src/dev/build/tasks/nodejs_modules/clean_client_modules_on_dll_task.js @@ -34,7 +34,7 @@ export const CleanClientModulesOnDLLTask = { const kbnPkg = config.getKibanaPkg(); const kbnPkgDependencies = (kbnPkg && kbnPkg.dependencies) || {}; const kbnWebpackLoaders = Object.keys(kbnPkgDependencies).filter( - dep => !!dep.includes('-loader') + (dep) => !!dep.includes('-loader') ); // Define the entry points for the server code in order to @@ -44,7 +44,7 @@ export const CleanClientModulesOnDLLTask = { `${baseDir}/src/cli_keystore`, `${baseDir}/src/cli_plugin`, `${baseDir}/x-pack`, - ...kbnWebpackLoaders.map(loader => `${baseDir}/node_modules/${loader}`), + ...kbnWebpackLoaders.map((loader) => `${baseDir}/node_modules/${loader}`), ]; const discoveredLegacyCorePluginEntries = await globby([ `${baseDir}/src/legacy/core_plugins/*/index.js`, @@ -84,7 +84,7 @@ export const CleanClientModulesOnDLLTask = { // consider the top modules as exceptions as the entry points // to look for other exceptions dependent on that one const manualExceptionEntries = [ - ...manualExceptionModules.map(module => `${baseDir}/node_modules/${module}`), + ...manualExceptionModules.map((module) => `${baseDir}/node_modules/${module}`), ]; // dependencies for declared exception modules diff --git a/src/dev/build/tasks/nodejs_modules/webpack_dll.js b/src/dev/build/tasks/nodejs_modules/webpack_dll.js index 72910226bb04a..8de5e582c3d36 100644 --- a/src/dev/build/tasks/nodejs_modules/webpack_dll.js +++ b/src/dev/build/tasks/nodejs_modules/webpack_dll.js @@ -31,7 +31,7 @@ function checkDllEntryAccess(entry, baseDir = '') { export async function getDllEntries(manifestPaths, whiteListedModules, baseDir = '') { // Read and parse all manifests const manifests = await Promise.all( - manifestPaths.map(async manifestPath => JSON.parse(await read(manifestPath))) + manifestPaths.map(async (manifestPath) => JSON.parse(await read(manifestPath))) ); // Process and group modules from all manifests @@ -58,8 +58,8 @@ export async function getDllEntries(manifestPaths, whiteListedModules, baseDir = // Only includes modules who are not in the white list of modules // and that are node_modules - return manifestsModules.filter(entry => { - const isWhiteListed = whiteListedModules.some(nonEntry => + return manifestsModules.filter((entry) => { + const isWhiteListed = whiteListedModules.some((nonEntry) => normalizePosixPath(entry).includes(`node_modules/${nonEntry}`) ); const isNodeModule = entry.includes('node_modules'); @@ -113,7 +113,7 @@ export async function cleanDllModuleFromEntryPath(logger, entryPath) { ]); await deleteAll( - filesToDelete.filter(path => { + filesToDelete.filter((path) => { const relativePath = relative(moduleDir, path); return !relativePath.endsWith('package.json') || relativePath.includes('node_modules'); }) diff --git a/src/dev/build/tasks/path_length_task.js b/src/dev/build/tasks/path_length_task.js index b108b8820575b..29ab9ce5a2499 100644 --- a/src/dev/build/tasks/path_length_task.js +++ b/src/dev/build/tasks/path_length_task.js @@ -30,10 +30,10 @@ export const PathLengthTask = { const buildRoot = build.resolvePath(); await scan$(buildRoot) .pipe( - map(path => relative(buildRoot, path)), - filter(relativePath => relativePath.length > 200), + map((path) => relative(buildRoot, path)), + filter((relativePath) => relativePath.length > 200), toArray(), - tap(tooLongPaths => { + tap((tooLongPaths) => { if (!tooLongPaths.length) { return; } diff --git a/src/dev/code_coverage/ingest_coverage/either.js b/src/dev/code_coverage/ingest_coverage/either.js index bdab6e5882d26..a52fd2f7212d6 100644 --- a/src/dev/code_coverage/ingest_coverage/either.js +++ b/src/dev/code_coverage/ingest_coverage/either.js @@ -20,9 +20,9 @@ /* eslint new-cap: 0 */ /* eslint no-unused-vars: 0 */ -export const Right = x => ({ - chain: f => f(x), - map: f => Right(f(x)), +export const Right = (x) => ({ + chain: (f) => f(x), + map: (f) => Right(f(x)), fold: (f, g) => g(x), inspect: () => `Right(${x})`, }); @@ -35,9 +35,9 @@ export function right(x) { return Right.of(x); } -export const Left = x => ({ - chain: f => Left(x), - map: f => Left(x), +export const Left = (x) => ({ + chain: (f) => Left(x), + map: (f) => Left(x), fold: (f, g) => f(x), inspect: () => `Left(${x})`, }); @@ -50,10 +50,10 @@ export function left(x) { return Left.of(x); } -export const fromNullable = x => +export const fromNullable = (x) => x !== null && x !== undefined && x !== false && x !== 'undefined' ? Right(x) : Left(null); -export const tryCatch = f => { +export const tryCatch = (f) => { try { return Right(f()); } catch (e) { diff --git a/src/dev/code_coverage/ingest_coverage/ingest.js b/src/dev/code_coverage/ingest_coverage/ingest.js index 769fe250a8e18..9167bea17ae05 100644 --- a/src/dev/code_coverage/ingest_coverage/ingest.js +++ b/src/dev/code_coverage/ingest_coverage/ingest.js @@ -28,9 +28,9 @@ const node = process.env.ES_HOST || 'http://localhost:9200'; const redacted = redact(node); const client = new Client({ node }); -const indexName = body => (body.isTotal ? TOTALS_INDEX : COVERAGE_INDEX); +const indexName = (body) => (body.isTotal ? TOTALS_INDEX : COVERAGE_INDEX); -export const ingest = log => async body => { +export const ingest = (log) => async (body) => { const index = indexName(body); if (process.env.NODE_ENV === 'integration_test') { @@ -80,10 +80,7 @@ ${red('Perhaps the coverage data was not merged properly?\n')} } function partial(x) { - return x - .split('\n') - .splice(0, 2) - .join('\n'); + return x.split('\n').splice(0, 2).join('\n'); } function redact(x) { const url = new URL(x); diff --git a/src/dev/code_coverage/ingest_coverage/integration_tests/ingest_coverage.test.js b/src/dev/code_coverage/ingest_coverage/integration_tests/ingest_coverage.test.js index 2ffb005993619..dcd78250986df 100644 --- a/src/dev/code_coverage/ingest_coverage/integration_tests/ingest_coverage.test.js +++ b/src/dev/code_coverage/ingest_coverage/integration_tests/ingest_coverage.test.js @@ -37,9 +37,9 @@ const env = { NODE_ENV: 'integration_test', COVERAGE_INGESTION_KIBANA_ROOT: '/var/lib/jenkins/workspace/elastic+kibana+code-coverage/kibana', }; -const includesSiteUrlPredicate = x => x.includes('staticSiteUrl'); +const includesSiteUrlPredicate = (x) => x.includes('staticSiteUrl'); const siteUrlLines = specificLinesOnly(includesSiteUrlPredicate); -const splitByNewLine = x => x.split('\n'); +const splitByNewLine = (x) => x.split('\n'); const siteUrlsSplitByNewLine = siteUrlLines(splitByNewLine); const siteUrlsSplitByNewLineWithoutBlanks = siteUrlsSplitByNewLine(notBlankLines); const verboseArgs = [ @@ -56,7 +56,7 @@ describe('Ingesting coverage', () => { describe(`to the coverage index`, () => { const mutableCoverageIndexChunks = []; - beforeAll(done => { + beforeAll((done) => { const ingestAndMutateAsync = ingestAndMutate(done); const ingestAndMutateAsyncWithPath = ingestAndMutateAsync(bothIndexesPath); const verboseIngestAndMutateAsyncWithPath = ingestAndMutateAsyncWithPath(verboseArgs); @@ -78,19 +78,19 @@ describe('Ingesting coverage', () => { }); function ingestAndMutate(done) { - return summaryPathSuffix => args => xs => { + return (summaryPathSuffix) => (args) => (xs) => { const coverageSummaryPath = resolve(MOCKS_DIR, summaryPathSuffix); const opts = [...args, coverageSummaryPath]; const ingest = spawn(process.execPath, opts, { cwd: ROOT_DIR, env }); - ingest.stdout.on('data', x => xs.push(x + '')); + ingest.stdout.on('data', (x) => xs.push(x + '')); ingest.on('close', done); }; } function specificLinesOnly(predicate) { - return splitByNewLine => notBlankLines => xs => - xs.filter(predicate).map(x => splitByNewLine(x).reduce(notBlankLines)); + return (splitByNewLine) => (notBlankLines) => (xs) => + xs.filter(predicate).map((x) => splitByNewLine(x).reduce(notBlankLines)); } function notBlankLines(acc, item) { @@ -99,8 +99,8 @@ function notBlankLines(acc, item) { } function expectAllRegexesToPass(staticSiteUrlRegexes) { - return urlLine => - Object.entries(staticSiteUrlRegexes).forEach(regexTuple => { + return (urlLine) => + Object.entries(staticSiteUrlRegexes).forEach((regexTuple) => { if (!regexTuple[1].test(urlLine)) throw new Error( `\n### ${green('FAILED')}\nAsserting: [\n\t${green( diff --git a/src/dev/code_coverage/ingest_coverage/json_stream.js b/src/dev/code_coverage/ingest_coverage/json_stream.js index fbc704b6372f2..edc329309df92 100644 --- a/src/dev/code_coverage/ingest_coverage/json_stream.js +++ b/src/dev/code_coverage/ingest_coverage/json_stream.js @@ -20,4 +20,4 @@ import oboe from 'oboe'; import { createReadStream } from 'fs'; -export default jsonSummaryPath => oboe(createReadStream(jsonSummaryPath)); +export default (jsonSummaryPath) => oboe(createReadStream(jsonSummaryPath)); diff --git a/src/dev/code_coverage/ingest_coverage/process.js b/src/dev/code_coverage/ingest_coverage/process.js index ecd09e0b2fd1a..6b9c8f09febfe 100644 --- a/src/dev/code_coverage/ingest_coverage/process.js +++ b/src/dev/code_coverage/ingest_coverage/process.js @@ -46,11 +46,11 @@ const addPrePopulatedTimeStamp = addTimeStamp(process.env.TIME_STAMP); const preamble = pipe(statsAndstaticSiteUrl, rootDirAndOrigPath, buildId, addPrePopulatedTimeStamp); const addTestRunnerAndStaticSiteUrl = pipe(testRunner, staticSite(staticSiteUrlBase)); -const transform = jsonSummaryPath => log => vcsInfo => { +const transform = (jsonSummaryPath) => (log) => (vcsInfo) => { const objStream = jsonStream(jsonSummaryPath).on('done', noop); const itemizeVcsInfo = itemizeVcs(vcsInfo); - const jsonSummary$ = _ => objStream.on('node', '!.*', _); + const jsonSummary$ = (_) => objStream.on('node', '!.*', _); fromEventPattern(jsonSummary$) .pipe( @@ -60,7 +60,7 @@ const transform = jsonSummaryPath => log => vcsInfo => { map(ciRunUrl), map(addJsonSummaryPath(jsonSummaryPath)), map(addTestRunnerAndStaticSiteUrl), - concatMap(x => of(x).pipe(delay(ms))) + concatMap((x) => of(x).pipe(delay(ms))) ) .subscribe(ingest(log)); }; @@ -73,8 +73,8 @@ function rootDirAndOrigPath(obj) { }; } -const mutateVcsInfo = vcsInfo => x => vcsInfo.push(x.trimStart().trimEnd()); -const vcsInfoLines$ = vcsInfoFilePath => { +const mutateVcsInfo = (vcsInfo) => (x) => vcsInfo.push(x.trimStart().trimEnd()); +const vcsInfoLines$ = (vcsInfoFilePath) => { const rl = readline.createInterface({ input: createReadStream(vcsInfoFilePath) }); return fromEvent(rl, 'line').pipe(takeUntil(fromEvent(rl, 'close'))); }; @@ -88,7 +88,7 @@ export const prok = ({ jsonSummaryPath, vcsInfoFilePath }, log) => { const vcsInfo = []; vcsInfoLines$(vcsInfoFilePath).subscribe( mutateVcsInfo(vcsInfo), - err => log.error(err), + (err) => log.error(err), always(xformWithPath(vcsInfo)) ); }; diff --git a/src/dev/code_coverage/ingest_coverage/transforms.js b/src/dev/code_coverage/ingest_coverage/transforms.js index d5a4d8933e36b..cecaf1e192b8c 100644 --- a/src/dev/code_coverage/ingest_coverage/transforms.js +++ b/src/dev/code_coverage/ingest_coverage/transforms.js @@ -20,7 +20,7 @@ import { left, right, fromNullable } from './either'; import { always, id, noop } from './utils'; -const maybeTotal = x => (x === 'total' ? left(x) : right(x)); +const maybeTotal = (x) => (x === 'total' ? left(x) : right(x)); const trimLeftFrom = (text, x) => x.substr(x.indexOf(text)); @@ -33,43 +33,43 @@ export const statsAndstaticSiteUrl = (...xs) => { }; }; -export const addJsonSummaryPath = jsonSummaryPath => obj => ({ jsonSummaryPath, ...obj }); +export const addJsonSummaryPath = (jsonSummaryPath) => (obj) => ({ jsonSummaryPath, ...obj }); -export const truncate = text => obj => { +export const truncate = (text) => (obj) => { const { staticSiteUrl } = obj; if (staticSiteUrl.includes(text)) obj.staticSiteUrl = trimLeftFrom(text, staticSiteUrl); return obj; }; -export const addTimeStamp = ts => obj => ({ +export const addTimeStamp = (ts) => (obj) => ({ ...obj, '@timestamp': ts, }); -const setTotal = x => obj => (obj.isTotal = x); +const setTotal = (x) => (obj) => (obj.isTotal = x); const mutateTrue = setTotal(true); const mutateFalse = setTotal(false); -const root = urlBase => ts => testRunnerType => +const root = (urlBase) => (ts) => (testRunnerType) => `${urlBase}/${ts}/${testRunnerType.toLowerCase()}-combined`; -const prokForTotalsIndex = mutateTrue => urlRoot => obj => +const prokForTotalsIndex = (mutateTrue) => (urlRoot) => (obj) => right(obj) .map(mutateTrue) .map(always(`${urlRoot}/index.html`)) .fold(noop, id); -const prokForCoverageIndex = root => mutateFalse => urlRoot => obj => siteUrl => +const prokForCoverageIndex = (root) => (mutateFalse) => (urlRoot) => (obj) => (siteUrl) => right(siteUrl) - .map(x => { + .map((x) => { mutateFalse(obj); return x; }) - .map(x => x.replace(root, '')) - .map(x => `${urlRoot}${x}.html`) + .map((x) => x.replace(root, '')) + .map((x) => `${urlRoot}${x}.html`) .fold(noop, id); -export const staticSite = urlBase => obj => { +export const staticSite = (urlBase) => (obj) => { const { staticSiteUrl, testRunnerType, COVERAGE_INGESTION_KIBANA_ROOT } = obj; const ts = obj['@timestamp']; const urlRoot = root(urlBase)(ts)(testRunnerType); @@ -82,27 +82,27 @@ export const staticSite = urlBase => obj => { return { ...obj, staticSiteUrl: prokForBoth() }; }; -export const coveredFilePath = obj => { +export const coveredFilePath = (obj) => { const { staticSiteUrl, COVERAGE_INGESTION_KIBANA_ROOT } = obj; const withoutCoveredFilePath = always(obj); const leadingSlashRe = /^\//; - const maybeDropLeadingSlash = x => (leadingSlashRe.test(x) ? right(x) : left(x)); - const dropLeadingSlash = x => x.replace(leadingSlashRe, ''); - const dropRoot = root => x => + const maybeDropLeadingSlash = (x) => (leadingSlashRe.test(x) ? right(x) : left(x)); + const dropLeadingSlash = (x) => x.replace(leadingSlashRe, ''); + const dropRoot = (root) => (x) => maybeDropLeadingSlash(x.replace(root, '')).fold(id, dropLeadingSlash); return maybeTotal(staticSiteUrl) .map(dropRoot(COVERAGE_INGESTION_KIBANA_ROOT)) - .fold(withoutCoveredFilePath, coveredFilePath => ({ ...obj, coveredFilePath })); + .fold(withoutCoveredFilePath, (coveredFilePath) => ({ ...obj, coveredFilePath })); }; -export const ciRunUrl = obj => - fromNullable(process.env.CI_RUN_URL).fold(always(obj), ciRunUrl => ({ ...obj, ciRunUrl })); +export const ciRunUrl = (obj) => + fromNullable(process.env.CI_RUN_URL).fold(always(obj), (ciRunUrl) => ({ ...obj, ciRunUrl })); const size = 50; -const truncateCommitMsg = x => (x.length > size ? `${x.slice(0, 50)}...` : x); +const truncateCommitMsg = (x) => (x.length > size ? `${x.slice(0, 50)}...` : x); -export const itemizeVcs = vcsInfo => obj => { +export const itemizeVcs = (vcsInfo) => (obj) => { const [branch, sha, author, commitMsg] = vcsInfo; return { ...obj, @@ -115,12 +115,12 @@ export const itemizeVcs = vcsInfo => obj => { }, }; }; -export const testRunner = obj => { +export const testRunner = (obj) => { const { jsonSummaryPath } = obj; let testRunnerType = 'other'; - const upperTestRunnerType = x => { + const upperTestRunnerType = (x) => { if (jsonSummaryPath.includes(x)) { testRunnerType = x.toUpperCase(); return; @@ -135,7 +135,7 @@ export const testRunner = obj => { }; }; -export const buildId = obj => { +export const buildId = (obj) => { const { env } = process; if (env.BUILD_ID) obj.BUILD_ID = env.BUILD_ID; diff --git a/src/dev/code_coverage/ingest_coverage/utils.js b/src/dev/code_coverage/ingest_coverage/utils.js index df064e73842e7..7d817bdf7a6f3 100644 --- a/src/dev/code_coverage/ingest_coverage/utils.js +++ b/src/dev/code_coverage/ingest_coverage/utils.js @@ -21,7 +21,7 @@ import chalk from 'chalk'; export const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); export const noop = () => {}; -export const green = x => chalk.greenBright.bold(x); -export const id = x => x; -export const always = x => () => x; -export const pretty = x => JSON.stringify(x, null, 2); +export const green = (x) => chalk.greenBright.bold(x); +export const id = (x) => x; +export const always = (x) => () => x; +export const pretty = (x) => JSON.stringify(x, null, 2); diff --git a/src/dev/eslint/lint_files.ts b/src/dev/eslint/lint_files.ts index 80c493233f39a..ba16163fc9bd3 100644 --- a/src/dev/eslint/lint_files.ts +++ b/src/dev/eslint/lint_files.ts @@ -38,7 +38,7 @@ export function lintFiles(log: ToolingLog, files: File[], { fix }: { fix?: boole fix, }); - const paths = files.map(file => file.getRelativePath()); + const paths = files.map((file) => file.getRelativePath()); const report = cli.executeOnFiles(paths); if (fix) { diff --git a/src/dev/eslint/pick_files_to_lint.ts b/src/dev/eslint/pick_files_to_lint.ts index b96781fc3a611..dc6713c5efd00 100644 --- a/src/dev/eslint/pick_files_to_lint.ts +++ b/src/dev/eslint/pick_files_to_lint.ts @@ -31,7 +31,7 @@ import { File } from '../file'; export function pickFilesToLint(log: ToolingLog, files: File[]) { const cli = new CLIEngine({}); - return files.filter(file => { + return files.filter((file) => { if (!file.isJs() && !file.isTypescript()) { return; } diff --git a/src/dev/globs.js b/src/dev/globs.js index 3d1637ff97f18..1289be7599ca9 100644 --- a/src/dev/globs.js +++ b/src/dev/globs.js @@ -20,7 +20,7 @@ import minimatch from 'minimatch'; export function matchesAnyGlob(path, globs) { - return globs.some(pattern => + return globs.some((pattern) => minimatch(path, pattern, { dot: true, }) diff --git a/src/dev/i18n/config.ts b/src/dev/i18n/config.ts index cd59408947d9b..c11ced51bce65 100644 --- a/src/dev/i18n/config.ts +++ b/src/dev/i18n/config.ts @@ -51,7 +51,7 @@ export async function assignConfigFromPath( for (const [namespace, namespacePaths] of Object.entries(additionalConfig.paths)) { const paths = Array.isArray(namespacePaths) ? namespacePaths : [namespacePaths]; - config.paths[namespace] = paths.map(path => normalizePath(resolve(configPath, '..', path))); + config.paths[namespace] = paths.map((path) => normalizePath(resolve(configPath, '..', path))); } for (const exclude of additionalConfig.exclude) { @@ -80,15 +80,17 @@ export function filterConfigPaths(inputPaths: string[], config: I18nConfig) { // If input path is the sub path of or equal to any available path, include it. if ( - availablePaths.some(path => normalizedPath.startsWith(`${path}/`) || path === normalizedPath) + availablePaths.some( + (path) => normalizedPath.startsWith(`${path}/`) || path === normalizedPath + ) ) { pathsForExtraction.add(normalizedPath); } else { // Otherwise go through all available paths and see if any of them is the sub // path of the input path (empty normalized path corresponds to root or above). availablePaths - .filter(path => !normalizedPath || path.startsWith(`${normalizedPath}/`)) - .forEach(ePath => pathsForExtraction.add(ePath)); + .filter((path) => !normalizedPath || path.startsWith(`${normalizedPath}/`)) + .forEach((ePath) => pathsForExtraction.add(ePath)); } } diff --git a/src/dev/i18n/extract_default_translations.js b/src/dev/i18n/extract_default_translations.js index 9daf431ad5401..e70c666422f7b 100644 --- a/src/dev/i18n/extract_default_translations.js +++ b/src/dev/i18n/extract_default_translations.js @@ -38,8 +38,8 @@ function addMessageToMap(targetMap, key, value, reporter) { } function filterEntries(entries, exclude) { - return entries.filter(entry => - exclude.every(excludedPath => !normalizePath(entry).startsWith(excludedPath)) + return entries.filter((entry) => + exclude.every((excludedPath) => !normalizePath(entry).startsWith(excludedPath)) ); } @@ -47,7 +47,7 @@ export function validateMessageNamespace(id, filePath, allowedPaths, reporter) { const normalizedPath = normalizePath(filePath); const [expectedNamespace] = Object.entries(allowedPaths).find(([, pluginPaths]) => - pluginPaths.some(pluginPath => normalizedPath.startsWith(`${pluginPath}/`)) + pluginPaths.some((pluginPath) => normalizedPath.startsWith(`${pluginPath}/`)) ); if (!id.startsWith(`${expectedNamespace}.`)) { @@ -107,7 +107,7 @@ export async function extractMessagesFromPathToMap(inputPath, targetMap, config, return Promise.all( categorizedEntries.map(async ([entries, extractFunction]) => { const files = await Promise.all( - filterEntries(entries, config.exclude).map(async entry => { + filterEntries(entries, config.exclude).map(async (entry) => { return { name: entry, content: await readFileAsync(entry), diff --git a/src/dev/i18n/extractors/code.test.js b/src/dev/i18n/extractors/code.test.js index 34861aee38352..726afedd9f929 100644 --- a/src/dev/i18n/extractors/code.test.js +++ b/src/dev/i18n/extractors/code.test.js @@ -94,11 +94,11 @@ describe('isIntlFormatMessageFunction', () => { test('detects intl.formatMessage call expression', () => { const callExpressionNodes = [ ...traverseNodes(parse(intlFormatMessageSource).program.body), - ].filter(node => isCallExpression(node)); + ].filter((node) => isCallExpression(node)); expect(callExpressionNodes).toHaveLength(4); expect( - callExpressionNodes.every(callExpressionNode => + callExpressionNodes.every((callExpressionNode) => isIntlFormatMessageFunction(callExpressionNode) ) ).toBe(true); @@ -108,7 +108,7 @@ describe('isIntlFormatMessageFunction', () => { describe('isFormattedMessageElement', () => { test('detects FormattedMessage jsx element', () => { const AST = parse(formattedMessageSource, { plugins: ['jsx'] }); - const jsxOpeningElementNode = [...traverseNodes(AST.program.body)].find(node => + const jsxOpeningElementNode = [...traverseNodes(AST.program.body)].find((node) => isJSXOpeningElement(node) ); diff --git a/src/dev/i18n/extractors/html.js b/src/dev/i18n/extractors/html.js index 5b45738209264..6c7b982b872a5 100644 --- a/src/dev/i18n/extractors/html.js +++ b/src/dev/i18n/extractors/html.js @@ -68,7 +68,7 @@ function parseExpression(expression) { */ function parseFilterObjectExpression(expression, messageId) { const ast = parseExpression(expression); - const objectExpressionNode = [...traverseNodes(ast.program.body)].find(node => + const objectExpressionNode = [...traverseNodes(ast.program.body)].find((node) => isObjectExpression(node) ); @@ -80,7 +80,9 @@ function parseFilterObjectExpression(expression, messageId) { DEFAULT_MESSAGE_KEY, DESCRIPTION_KEY, VALUES_KEY, - ].map(key => objectExpressionNode.properties.find(property => isPropertyWithKey(property, key))); + ].map((key) => + objectExpressionNode.properties.find((property) => isPropertyWithKey(property, key)) + ); const message = messageProperty ? formatJSString(extractMessageValueFromNode(messageProperty.value, messageId)) @@ -99,7 +101,7 @@ function parseFilterObjectExpression(expression, messageId) { function parseIdExpression(expression) { const ast = parseExpression(expression); - const stringNode = [...traverseNodes(ast.program.body)].find(node => isStringLiteral(node)); + const stringNode = [...traverseNodes(ast.program.body)].find((node) => isStringLiteral(node)); if (!stringNode) { throw createFailError(`Message id should be a string literal, but got: \n${expression}`); @@ -131,15 +133,13 @@ function trimOneTimeBindingOperator(string) { } function* extractExpressions(htmlContent) { - const elements = cheerio - .load(htmlContent)('*') - .toArray(); + const elements = cheerio.load(htmlContent)('*').toArray(); for (const element of elements) { for (const node of element.children) { if (node.type === 'text') { yield* (node.data.match(ANGULAR_EXPRESSION_REGEX) || []) - .filter(expression => expression.includes(I18N_FILTER_MARKER)) + .filter((expression) => expression.includes(I18N_FILTER_MARKER)) .map(trimCurlyBraces); } } @@ -232,7 +232,7 @@ function* getDirectiveMessages(htmlContent, reporter) { try { if (element.values) { const ast = parseExpression(element.values); - const valuesObjectNode = [...traverseNodes(ast.program.body)].find(node => + const valuesObjectNode = [...traverseNodes(ast.program.body)].find((node) => isObjectExpression(node) ); const valuesKeys = extractValuesKeysFromNode(valuesObjectNode); diff --git a/src/dev/i18n/extractors/i18n_call.js b/src/dev/i18n/extractors/i18n_call.js index 118cf63ce8a30..79aeee0ee2c5f 100644 --- a/src/dev/i18n/extractors/i18n_call.js +++ b/src/dev/i18n/extractors/i18n_call.js @@ -52,7 +52,7 @@ export function extractI18nCallMessages(node) { DEFAULT_MESSAGE_KEY, DESCRIPTION_KEY, VALUES_KEY, - ].map(key => optionsSubTree.properties.find(property => isPropertyWithKey(property, key))); + ].map((key) => optionsSubTree.properties.find((property) => isPropertyWithKey(property, key))); const message = messageProperty ? formatJSString(extractMessageValueFromNode(messageProperty.value, messageId)) diff --git a/src/dev/i18n/extractors/i18n_call.test.js b/src/dev/i18n/extractors/i18n_call.test.js index fd2873b5f8d43..7292ec83ec3b2 100644 --- a/src/dev/i18n/extractors/i18n_call.test.js +++ b/src/dev/i18n/extractors/i18n_call.test.js @@ -41,19 +41,19 @@ describe('dev/i18n/extractors/i18n_call', () => { test('extracts "i18n" and "i18n.translate" functions call message', () => { let callExpressionNode = [ ...traverseNodes(parse(i18nCallMessageSource).program.body), - ].find(node => isCallExpression(node)); + ].find((node) => isCallExpression(node)); expect(extractI18nCallMessages(callExpressionNode)).toMatchSnapshot(); callExpressionNode = [ ...traverseNodes(parse(translateCallMessageSource).program.body), - ].find(node => isCallExpression(node)); + ].find((node) => isCallExpression(node)); expect(extractI18nCallMessages(callExpressionNode)).toMatchSnapshot(); callExpressionNode = [ ...traverseNodes(parse(i18nCallMessageWithTemplateLiteralSource).program.body), - ].find(node => isCallExpression(node)); + ].find((node) => isCallExpression(node)); expect(extractI18nCallMessages(callExpressionNode)).toMatchSnapshot(); }); @@ -62,7 +62,7 @@ describe('dev/i18n/extractors/i18n_call', () => { const source = ` i18n(messageIdIdentifier, { defaultMessage: 'Default message', description: 'Message description' }); `; - const callExpressionNode = [...traverseNodes(parse(source).program.body)].find(node => + const callExpressionNode = [...traverseNodes(parse(source).program.body)].find((node) => isCallExpression(node) ); @@ -71,7 +71,7 @@ i18n(messageIdIdentifier, { defaultMessage: 'Default message', description: 'Mes test('throws if properties object is not provided', () => { const source = `i18n('message-id');`; - const callExpressionNode = [...traverseNodes(parse(source).program.body)].find(node => + const callExpressionNode = [...traverseNodes(parse(source).program.body)].find((node) => isCallExpression(node) ); @@ -83,7 +83,7 @@ i18n(messageIdIdentifier, { defaultMessage: 'Default message', description: 'Mes const message = 'Default message'; i18n('message-id', { defaultMessage: message }); `; - const callExpressionNode = [...traverseNodes(parse(source).program.body)].find(node => + const callExpressionNode = [...traverseNodes(parse(source).program.body)].find((node) => isCallExpression(node) ); @@ -92,7 +92,7 @@ i18n('message-id', { defaultMessage: message }); test('throws on empty defaultMessage', () => { const source = `i18n('message-id', { defaultMessage: '' });`; - const callExpressionNode = [...traverseNodes(parse(source).program.body)].find(node => + const callExpressionNode = [...traverseNodes(parse(source).program.body)].find((node) => isCallExpression(node) ); diff --git a/src/dev/i18n/extractors/pug.js b/src/dev/i18n/extractors/pug.js index a19d2183af2a1..20fc72a404843 100644 --- a/src/dev/i18n/extractors/pug.js +++ b/src/dev/i18n/extractors/pug.js @@ -56,7 +56,9 @@ export function* extractPugMessages(buffer, reporter) { for (const expression of expressions) { try { const ast = parsePugExpression(expression); - const node = [...traverseNodes(ast.program.body)].find(node => isI18nTranslateFunction(node)); + const node = [...traverseNodes(ast.program.body)].find((node) => + isI18nTranslateFunction(node) + ); if (node) { yield extractI18nCallMessages(node); diff --git a/src/dev/i18n/extractors/react.js b/src/dev/i18n/extractors/react.js index b5a55a825312b..6d3719faaeb61 100644 --- a/src/dev/i18n/extractors/react.js +++ b/src/dev/i18n/extractors/react.js @@ -50,7 +50,7 @@ export function extractIntlMessages(node) { 'id', DEFAULT_MESSAGE_KEY, DESCRIPTION_KEY, - ].map(key => options.properties.find(property => isPropertyWithKey(property, key))); + ].map((key) => options.properties.find((property) => isPropertyWithKey(property, key))); const messageId = messageIdProperty ? formatJSString(extractMessageIdFromNode(messageIdProperty.value)) @@ -92,7 +92,9 @@ export function extractFormattedMessages(node) { DEFAULT_MESSAGE_KEY, DESCRIPTION_KEY, VALUES_KEY, - ].map(key => node.attributes.find(attribute => isJSXIdentifier(attribute.name, { name: key }))); + ].map((key) => + node.attributes.find((attribute) => isJSXIdentifier(attribute.name, { name: key })) + ); const messageId = messageIdAttribute ? formatHTMLString(extractMessageIdFromNode(messageIdAttribute.value)) diff --git a/src/dev/i18n/extractors/react.test.js b/src/dev/i18n/extractors/react.test.js index d363672626ee9..f6fc85d28f139 100644 --- a/src/dev/i18n/extractors/react.test.js +++ b/src/dev/i18n/extractors/react.test.js @@ -83,7 +83,7 @@ describe('dev/i18n/extractors/react', () => { describe('extractIntlMessages', () => { test('extracts messages from "intl.formatMessage" function call', () => { const ast = parse(intlFormatMessageCallSource, { plugins: ['jsx'] }); - const expressionNode = [...traverseNodes(ast.program.body)].find(node => + const expressionNode = [...traverseNodes(ast.program.body)].find((node) => isCallExpression(node) ); @@ -93,7 +93,7 @@ describe('dev/i18n/extractors/react', () => { test('throws if message id is not a string literal', () => { const source = intlFormatMessageCallErrorSources[0]; const ast = parse(source, { plugins: ['jsx'] }); - const callExpressionNode = [...traverseNodes(ast.program.body)].find(node => + const callExpressionNode = [...traverseNodes(ast.program.body)].find((node) => isCallExpression(node) ); @@ -103,7 +103,7 @@ describe('dev/i18n/extractors/react', () => { test('throws if defaultMessage value is not a string literal', () => { const source = intlFormatMessageCallErrorSources[1]; const ast = parse(source, { plugins: ['jsx'] }); - const callExpressionNode = [...traverseNodes(ast.program.body)].find(node => + const callExpressionNode = [...traverseNodes(ast.program.body)].find((node) => isCallExpression(node) ); @@ -113,7 +113,7 @@ describe('dev/i18n/extractors/react', () => { test('throws if description value is not a string literal', () => { const source = intlFormatMessageCallErrorSources[2]; const ast = parse(source, { plugins: ['jsx'] }); - const callExpressionNode = [...traverseNodes(ast.program.body)].find(node => + const callExpressionNode = [...traverseNodes(ast.program.body)].find((node) => isCallExpression(node) ); @@ -125,7 +125,7 @@ describe('dev/i18n/extractors/react', () => { test('extracts messages from "" element', () => { const ast = parse(formattedMessageElementSource, { plugins: ['jsx'] }); const jsxOpeningElementNode = [...traverseNodes(ast.program.body)].find( - node => + (node) => isJSXOpeningElement(node) && isJSXIdentifier(node.name, { name: 'FormattedMessage' }) ); diff --git a/src/dev/i18n/integrate_locale_files.ts b/src/dev/i18n/integrate_locale_files.ts index 2ac8768ed72ad..d8ccccca15559 100644 --- a/src/dev/i18n/integrate_locale_files.ts +++ b/src/dev/i18n/integrate_locale_files.ts @@ -116,7 +116,7 @@ function groupMessagesByNamespace( ) { const localizedMessagesByNamespace = new Map(); for (const [messageId, messageValue] of localizedMessagesMap) { - const namespace = knownNamespaces.find(key => messageId.startsWith(`${key}.`)); + const namespace = knownNamespaces.find((key) => messageId.startsWith(`${key}.`)); if (!namespace) { throw createFailError(`Unknown namespace in id ${messageId}.`); } diff --git a/src/dev/i18n/serializers/json5.ts b/src/dev/i18n/serializers/json5.ts index 5b09764ce4d9b..a1c89d5ff8cf2 100644 --- a/src/dev/i18n/serializers/json5.ts +++ b/src/dev/i18n/serializers/json5.ts @@ -26,9 +26,7 @@ const ESCAPE_SINGLE_QUOTE_REGEX = /\\([\s\S])|(')/g; export const serializeToJson5: Serializer = (messages, formats = i18n.formats) => { // .slice(0, -4): remove closing curly braces from json to append messages let jsonBuffer = Buffer.from( - JSON5.stringify({ formats, messages: {} }, { quote: `'`, space: 2 }) - .slice(0, -4) - .concat('\n') + JSON5.stringify({ formats, messages: {} }, { quote: `'`, space: 2 }).slice(0, -4).concat('\n') ); for (const [mapKey, mapValue] of messages) { diff --git a/src/dev/i18n/tasks/check_compatibility.ts b/src/dev/i18n/tasks/check_compatibility.ts index 3c5f8c23466a4..5900bf5aff252 100644 --- a/src/dev/i18n/tasks/check_compatibility.ts +++ b/src/dev/i18n/tasks/check_compatibility.ts @@ -29,7 +29,7 @@ export interface I18nFlags { export function checkCompatibility(config: I18nConfig, flags: I18nFlags, log: ToolingLog) { const { fix, ignoreIncompatible, ignoreUnused, ignoreMissing } = flags; - return config.translations.map(translationsPath => ({ + return config.translations.map((translationsPath) => ({ task: async ({ messages }: { messages: Map }) => { // If `fix` is set we should try apply all possible fixes and override translations file. await integrateLocaleFiles(messages, { diff --git a/src/dev/i18n/tasks/check_configs.ts b/src/dev/i18n/tasks/check_configs.ts index ffb9a499fbb43..89d55cae07ffd 100644 --- a/src/dev/i18n/tasks/check_configs.ts +++ b/src/dev/i18n/tasks/check_configs.ts @@ -28,7 +28,7 @@ export function checkConfigs(additionalConfigPaths: string | string[] = []) { const configPaths = [kibanaRC, xpackRC, ...arrayify(additionalConfigPaths)]; - return configPaths.map(configPath => ({ + return configPaths.map((configPath) => ({ task: async (context: { reporter: ErrorReporter }) => { try { await checkConfigNamespacePrefix(configPath); diff --git a/src/dev/i18n/tasks/extract_default_translations.ts b/src/dev/i18n/tasks/extract_default_translations.ts index 8ff2bc14abafd..b8f4ede69526d 100644 --- a/src/dev/i18n/tasks/extract_default_translations.ts +++ b/src/dev/i18n/tasks/extract_default_translations.ts @@ -30,7 +30,7 @@ export function extractDefaultMessages(config: I18nConfig, inputPaths: string[]) )} None of input paths is covered by the mappings in .i18nrc.json.` ); } - return filteredPaths.map(filteredPath => ({ + return filteredPaths.map((filteredPath) => ({ task: async (context: { messages: Map; reporter: ErrorReporter; diff --git a/src/dev/i18n/tasks/extract_untracked_translations.ts b/src/dev/i18n/tasks/extract_untracked_translations.ts index 7c640d566dea2..39f8a1cc59c6b 100644 --- a/src/dev/i18n/tasks/extract_untracked_translations.ts +++ b/src/dev/i18n/tasks/extract_untracked_translations.ts @@ -67,10 +67,10 @@ export async function extractUntrackedMessagesTask({ for (const [entries, extractFunction] of categorizedEntries) { const files = await Promise.all( filterEntries(entries, config.exclude) - .filter(entry => { + .filter((entry) => { const normalizedEntry = normalizePath(entry); return !availablePaths.some( - availablePath => + (availablePath) => normalizedEntry.startsWith(`${normalizePath(availablePath)}/`) || normalizePath(availablePath) === normalizedEntry ); @@ -93,7 +93,7 @@ export async function extractUntrackedMessagesTask({ } export function extractUntrackedMessages(inputPaths: string[]) { - return inputPaths.map(inputPath => ({ + return inputPaths.map((inputPath) => ({ title: `Checking untracked messages in ${inputPath}`, task: async (context: { reporter: ErrorReporter; config: I18nConfig }) => { const { reporter, config } = context; diff --git a/src/dev/i18n/tasks/merge_configs.ts b/src/dev/i18n/tasks/merge_configs.ts index ec005f0ce9367..6e7b89fe4a668 100644 --- a/src/dev/i18n/tasks/merge_configs.ts +++ b/src/dev/i18n/tasks/merge_configs.ts @@ -27,7 +27,7 @@ export function mergeConfigs(additionalConfigPaths: string | string[] = []) { const configPaths = [kibanaRC, xpackRC, ...arrayify(additionalConfigPaths)]; - return configPaths.map(configPath => ({ + return configPaths.map((configPath) => ({ task: async (context: { reporter: ErrorReporter; config?: I18nConfig }) => { try { context.config = await assignConfigFromPath(context.config, configPath); diff --git a/src/dev/i18n/utils.js b/src/dev/i18n/utils.js index 091056c0837c3..1d1c3118e0852 100644 --- a/src/dev/i18n/utils.js +++ b/src/dev/i18n/utils.js @@ -55,7 +55,7 @@ export function normalizePath(inputPath) { } export function difference(left = [], right = []) { - return left.filter(value => !right.includes(value)); + return left.filter((value) => !right.includes(value)); } export function isPropertyWithKey(property, identifierName) { @@ -103,7 +103,9 @@ export function* traverseNodes(nodes) { // if node is an object / array, traverse all of its object values if (node && typeof node === 'object') { - yield* traverseNodes(Object.values(node).filter(value => value && typeof value === 'object')); + yield* traverseNodes( + Object.values(node).filter((value) => value && typeof value === 'object') + ); } } } @@ -187,7 +189,7 @@ export function checkValuesProperty(prefixedValuesKeys, defaultMessage, messageI return; } - const valuesKeys = prefixedValuesKeys.map(key => + const valuesKeys = prefixedValuesKeys.map((key) => key.startsWith(HTML_KEY_PREFIX) ? key.slice(HTML_KEY_PREFIX.length) : key ); @@ -309,7 +311,7 @@ export function extractValuesKeysFromNode(node, messageId) { throw createFailError(`"values" value should be an inline object literal ("${messageId}").`); } - return node.properties.map(property => + return node.properties.map((property) => isStringLiteral(property.key) ? property.key.value : property.key.name ); } @@ -318,7 +320,7 @@ export class ErrorReporter { errors = []; withContext(context) { - return { report: error => this.report(error, context) }; + return { report: (error) => this.report(error, context) }; } report(error, context) { diff --git a/src/dev/i18n/utils.test.js b/src/dev/i18n/utils.test.js index 7019218d4e249..49c42d3b577ad 100644 --- a/src/dev/i18n/utils.test.js +++ b/src/dev/i18n/utils.test.js @@ -32,7 +32,7 @@ import { } from './utils'; const i18nTranslateSources = ['i18n', 'i18n.translate'].map( - callee => ` + (callee) => ` ${callee}('plugin_1.id_1', { values: { key: 'value', @@ -64,14 +64,14 @@ describe('i18n utils', () => { test('should detect i18n translate function call', () => { let source = i18nTranslateSources[0]; - let expressionStatementNode = [...traverseNodes(parse(source).program.body)].find(node => + let expressionStatementNode = [...traverseNodes(parse(source).program.body)].find((node) => isExpressionStatement(node) ); expect(isI18nTranslateFunction(expressionStatementNode.expression)).toBe(true); source = i18nTranslateSources[1]; - expressionStatementNode = [...traverseNodes(parse(source).program.body)].find(node => + expressionStatementNode = [...traverseNodes(parse(source).program.body)].find((node) => isExpressionStatement(node) ); @@ -81,7 +81,7 @@ describe('i18n utils', () => { test('should detect object property with defined key', () => { const objectExpresssionNode = [ ...traverseNodes(parse(objectPropertySource).program.body), - ].find(node => isObjectExpression(node)); + ].find((node) => isObjectExpression(node)); const [objectExpresssionProperty] = objectExpresssionNode.properties; expect(isPropertyWithKey(objectExpresssionProperty, 'id')).toBe(true); @@ -183,7 +183,7 @@ describe('i18n utils', () => { i18n('namespace.id', { defaultMessage: 'Very ' + 'long ' + 'concatenated ' + 'string', });`; - const objectProperty = [...traverseNodes(parse(source).program.body)].find(node => + const objectProperty = [...traverseNodes(parse(source).program.body)].find((node) => isObjectProperty(node) ); diff --git a/src/dev/jest/config.integration.js b/src/dev/jest/config.integration.js index e13d0289a7e9b..2fd6bd120d553 100644 --- a/src/dev/jest/config.integration.js +++ b/src/dev/jest/config.integration.js @@ -27,7 +27,7 @@ export default { '**/integration_tests/**/*.test.tsx', ], testPathIgnorePatterns: config.testPathIgnorePatterns.filter( - pattern => !pattern.includes('integration_tests') + (pattern) => !pattern.includes('integration_tests') ), reporters: [ 'default', diff --git a/src/dev/jest/junit_reporter.js b/src/dev/jest/junit_reporter.js index 0f8003f4ed6a1..f33358c081a06 100644 --- a/src/dev/jest/junit_reporter.js +++ b/src/dev/jest/junit_reporter.js @@ -58,8 +58,8 @@ export default class JestJUnitReporter { { skipNullAttributes: true } ); - const msToIso = ms => (ms ? new Date(ms).toISOString().slice(0, -5) : undefined); - const msToSec = ms => (ms ? (ms / 1000).toFixed(3) : undefined); + const msToIso = (ms) => (ms ? new Date(ms).toISOString().slice(0, -5) : undefined); + const msToSec = (ms) => (ms ? (ms / 1000).toFixed(3) : undefined); root.att({ name: 'jest', @@ -71,7 +71,7 @@ export default class JestJUnitReporter { }); // top level test results are the files/suites - results.testResults.forEach(suite => { + results.testResults.forEach((suite) => { const suiteEl = root.ele('testsuite', { name: relative(rootDirectory, suite.testFilePath), timestamp: msToIso(suite.perfStats.start), @@ -85,14 +85,14 @@ export default class JestJUnitReporter { // nested in there are the tests in that file const relativePath = dirname(relative(rootDirectory, suite.testFilePath)); const classname = `${reportName}.${relativePath.replace(/\./g, '·')}`; - suite.testResults.forEach(test => { + suite.testResults.forEach((test) => { const testEl = suiteEl.ele('testcase', { classname, name: [...test.ancestorTitles, test.title].join(' '), time: msToSec(test.duration), }); - test.failureMessages.forEach(message => { + test.failureMessages.forEach((message) => { testEl.ele('failure').dat(escapeCdata(message)); }); diff --git a/src/dev/jest/setup/mocks.js b/src/dev/jest/setup/mocks.js index 095c82bd50fbd..6e7160e858cd7 100644 --- a/src/dev/jest/setup/mocks.js +++ b/src/dev/jest/setup/mocks.js @@ -54,6 +54,6 @@ jest.mock('@elastic/eui/lib/services/react', () => { // This is for performance, but when used in certain Jest scernarios it can be nondeterministic. // Jest tests are never concerned about the state prior to batch completion, so we bypass batching entirely. return { - enqueueStateChange: fn => fn(), + enqueueStateChange: (fn) => fn(), }; }); diff --git a/src/dev/jest/setup/polyfills.js b/src/dev/jest/setup/polyfills.js index a3342883d084e..9e4f1db9ac289 100644 --- a/src/dev/jest/setup/polyfills.js +++ b/src/dev/jest/setup/polyfills.js @@ -20,7 +20,7 @@ // bluebird < v3.3.5 does not work with MutationObserver polyfill // when MutationObserver exists, bluebird avoids using node's builtin async schedulers const bluebird = require('bluebird'); -bluebird.Promise.setScheduler(function(fn) { +bluebird.Promise.setScheduler(function (fn) { global.setImmediate.call(global, fn); }); diff --git a/src/dev/license_checker/run_check_licenses_cli.ts b/src/dev/license_checker/run_check_licenses_cli.ts index b011e8ff6ecb2..0267a1a90d4fe 100644 --- a/src/dev/license_checker/run_check_licenses_cli.ts +++ b/src/dev/license_checker/run_check_licenses_cli.ts @@ -35,7 +35,7 @@ run( // Assert if the found licenses in the production // packages are valid assertLicensesValid({ - packages: packages.filter(pkg => !pkg.isDevOnly), + packages: packages.filter((pkg) => !pkg.isDevOnly), validLicenses: LICENSE_WHITELIST, }); log.success('All production dependency licenses are allowed'); @@ -44,7 +44,7 @@ run( // if the dev flag is found if (flags.dev) { assertLicensesValid({ - packages: packages.filter(pkg => pkg.isDevOnly), + packages: packages.filter((pkg) => pkg.isDevOnly), validLicenses: LICENSE_WHITELIST.concat(DEV_ONLY_LICENSE_WHITELIST), }); log.success('All development dependency licenses are allowed'); diff --git a/src/dev/license_checker/valid.ts b/src/dev/license_checker/valid.ts index 9142955185a1a..f24f8a9bfdba7 100644 --- a/src/dev/license_checker/valid.ts +++ b/src/dev/license_checker/valid.ts @@ -37,7 +37,7 @@ interface Options { */ export function assertLicensesValid({ packages, validLicenses }: Options) { const invalidMsgs = packages.reduce((acc, pkg) => { - const invalidLicenses = pkg.licenses.filter(license => !validLicenses.includes(license)); + const invalidLicenses = pkg.licenses.filter((license) => !validLicenses.includes(license)); if (pkg.licenses.length && !invalidLicenses.length) { return acc; @@ -57,7 +57,7 @@ export function assertLicensesValid({ packages, validLicenses }: Options) { `Non-conforming licenses:\n${invalidMsgs .join('\n') .split('\n') - .map(l => ` ${l}`) + .map((l) => ` ${l}`) .join('\n')}` ); } diff --git a/src/dev/notice/bundled_notices.js b/src/dev/notice/bundled_notices.js index 1bdf526460016..a4710a79b0610 100644 --- a/src/dev/notice/bundled_notices.js +++ b/src/dev/notice/bundled_notices.js @@ -25,11 +25,11 @@ import glob from 'glob'; export async function getBundledNotices(packageDirectory) { const pattern = resolve(packageDirectory, '*{LICENSE,NOTICE}*'); - const paths = await fcb(cb => glob(pattern, cb)); + const paths = await fcb((cb) => glob(pattern, cb)); return Promise.all( - paths.map(async path => ({ + paths.map(async (path) => ({ path, - text: await fcb(cb => readFile(path, 'utf8', cb)), + text: await fcb((cb) => readFile(path, 'utf8', cb)), })) ); } diff --git a/src/dev/notice/cli.js b/src/dev/notice/cli.js index e5377d7f177d2..34217ef48a33b 100644 --- a/src/dev/notice/cli.js +++ b/src/dev/notice/cli.js @@ -41,7 +41,7 @@ const log = new ToolingLog({ }); if (unknownFlags.length) { - log.error(`Unknown flags ${unknownFlags.map(f => `"${f}"`).join(',')}`); + log.error(`Unknown flags ${unknownFlags.map((f) => `"${f}"`).join(',')}`); process.exitCode = 1; opts.help = true; } @@ -90,7 +90,7 @@ if (opts.help) { 'NOTICE.txt is out of date, run `node scripts/notice` to update and commit the results.' ); process.exit(1); -})().catch(error => { +})().catch((error) => { log.error(error); process.exit(1); }); diff --git a/src/dev/notice/generate_notice_from_source.ts b/src/dev/notice/generate_notice_from_source.ts index 6dd47db929f45..fb74bed0f26f4 100644 --- a/src/dev/notice/generate_notice_from_source.ts +++ b/src/dev/notice/generate_notice_from_source.ts @@ -62,7 +62,7 @@ export async function generateNoticeFromSource({ productName, directory, log }: const noticeComments: string[] = []; await new Promise((resolve, reject) => { files - .on('data', file => { + .on('data', (file) => { log.verbose(`Checking for @notice comments in ${file.relative}`); const source = file.contents.toString('utf8'); @@ -86,7 +86,7 @@ export async function generateNoticeFromSource({ productName, directory, log }: noticeText += '\n---\n'; noticeText += comment .split(NEWLINE_RE) - .map(line => + .map((line) => line // trim whitespace .trim() diff --git a/src/dev/notice/generate_package_notice_text.js b/src/dev/notice/generate_package_notice_text.js index 77c080d258e12..673f34fc57bf1 100644 --- a/src/dev/notice/generate_package_notice_text.js +++ b/src/dev/notice/generate_package_notice_text.js @@ -19,7 +19,7 @@ import { getBundledNotices } from './bundled_notices'; -const concatNotices = notices => notices.map(notice => notice.text).join('\n'); +const concatNotices = (notices) => notices.map((notice) => notice.text).join('\n'); export async function generatePackageNoticeText(pkg) { const bundledNotices = concatNotices(await getBundledNotices(pkg.directory)); diff --git a/src/dev/npm/integration_tests/installed_packages.test.ts b/src/dev/npm/integration_tests/installed_packages.test.ts index 75cd0e5607698..58c954cbc12f7 100644 --- a/src/dev/npm/integration_tests/installed_packages.test.ts +++ b/src/dev/npm/integration_tests/installed_packages.test.ts @@ -27,11 +27,11 @@ import { REPO_ROOT } from '../../constants'; const FIXTURE1_ROOT = resolve(__dirname, '__fixtures__/fixture1'); describe('src/dev/npm/installed_packages', () => { - describe('getInstalledPackages()', function() { + describe('getInstalledPackages()', function () { let kibanaPackages: InstalledPackage[]; let fixture1Packages: InstalledPackage[]; - beforeAll(async function() { + beforeAll(async function () { [kibanaPackages, fixture1Packages] = await Promise.all([ getInstalledPackages({ directory: REPO_ROOT, @@ -76,16 +76,16 @@ describe('src/dev/npm/installed_packages', () => { }); it('returns a single entry for every package/version combo', () => { - const tags = kibanaPackages.map(pkg => `${pkg.name}@${pkg.version}`); + const tags = kibanaPackages.map((pkg) => `${pkg.name}@${pkg.version}`); expect(tags).toEqual(uniq(tags)); }); it('does not include root package in the list', () => { - if (kibanaPackages.find(pkg => pkg.name === 'kibana')) { + if (kibanaPackages.find((pkg) => pkg.name === 'kibana')) { throw new Error('Expected getInstalledPackages(kibana) to not include kibana pkg'); } - if (fixture1Packages.find(pkg => pkg.name === 'fixture1')) { + if (fixture1Packages.find((pkg) => pkg.name === 'fixture1')) { throw new Error('Expected getInstalledPackages(fixture1) to not include fixture1 pkg'); } }); diff --git a/src/dev/precommit_hook/check_file_casing.js b/src/dev/precommit_hook/check_file_casing.js index be0fbe22457bf..ec77d9a8bad3c 100644 --- a/src/dev/precommit_hook/check_file_casing.js +++ b/src/dev/precommit_hook/check_file_casing.js @@ -35,7 +35,7 @@ const NON_SNAKE_CASE_RE = /[A-Z \-]/; const NON_KEBAB_CASE_RE = /[A-Z \_]/; function listPaths(paths) { - return paths.map(path => ` - ${path}`).join('\n'); + return paths.map((path) => ` - ${path}`).join('\n'); } /** @@ -78,7 +78,7 @@ async function checkForKebabCase(log, files) { return acc.concat( parents.filter( - parent => + (parent) => matchesAnyGlob(parent, KEBAB_CASE_DIRECTORY_GLOBS) && NON_KEBAB_CASE_RE.test(basename(parent)) ) @@ -109,7 +109,7 @@ async function checkForSnakeCase(log, files) { const errorPaths = []; const warningPaths = []; - files.forEach(file => { + files.forEach((file) => { const path = file.getRelativePath(); if (TEMPORARILY_IGNORED_PATHS.includes(path)) { diff --git a/src/dev/precommit_hook/get_files_for_commit.js b/src/dev/precommit_hook/get_files_for_commit.js index 418e6d1d0a852..dc5560be0d1ad 100644 --- a/src/dev/precommit_hook/get_files_for_commit.js +++ b/src/dev/precommit_hook/get_files_for_commit.js @@ -33,16 +33,16 @@ import { File } from '../file'; export async function getFilesForCommit() { const simpleGit = new SimpleGit(REPO_ROOT); - const output = await fcb(cb => simpleGit.diff(['--name-status', '--cached'], cb)); + const output = await fcb((cb) => simpleGit.diff(['--name-status', '--cached'], cb)); return ( output .split('\n') // Ignore blank lines - .filter(line => line.trim().length > 0) + .filter((line) => line.trim().length > 0) // git diff --name-status outputs lines with two OR three parts // separated by a tab character - .map(line => line.trim().split('\t')) + .map((line) => line.trim().split('\t')) .map(([status, ...paths]) => { // ignore deleted files if (status === 'D') { diff --git a/src/dev/prs/helpers.ts b/src/dev/prs/helpers.ts index d25db1a79a1b9..b10b30806942b 100644 --- a/src/dev/prs/helpers.ts +++ b/src/dev/prs/helpers.ts @@ -25,7 +25,7 @@ import { takeUntil } from 'rxjs/operators'; * Convert a Readable stream to an observable of lines */ export const getLine$ = (stream: Readable) => { - return new Rx.Observable(subscriber => { + return new Rx.Observable((subscriber) => { let buffer = ''; return Rx.fromEvent(stream, 'data') .pipe(takeUntil(Rx.fromEvent(stream, 'close'))) diff --git a/src/dev/prs/run_update_prs_cli.ts b/src/dev/prs/run_update_prs_cli.ts index bb7f50758a28c..49668199a26d4 100644 --- a/src/dev/prs/run_update_prs_cli.ts +++ b/src/dev/prs/run_update_prs_cli.ts @@ -48,7 +48,7 @@ run( throw createFlagError('invalid --repo-dir, expected a single string'); } - const prNumbers = flags._.map(arg => Pr.parseInput(arg)); + const prNumbers = flags._.map((arg) => Pr.parseInput(arg)); /** * Call the Gitub API once for each PR to get the targetRef so we know which branch to pull @@ -56,7 +56,7 @@ run( */ const api = new GithubApi(accessToken); const prs = await Promise.all( - prNumbers.map(async prNumber => { + prNumbers.map(async (prNumber) => { const { targetRef, owner, sourceBranch } = await api.getPrInfo(prNumber); return new Pr(prNumber, targetRef, owner, sourceBranch); }) @@ -73,7 +73,7 @@ run( await Promise.all([ proc.then(() => log.debug(` - ${cmd} exited with 0`)), Rx.merge(getLine$(proc.stdout), getLine$(proc.stderr)) - .pipe(tap(line => log.debug(line))) + .pipe(tap((line) => log.debug(line))) .toPromise(), ]); }; @@ -130,9 +130,7 @@ run( `) + '\n' ); - await getLine$(process.stdin) - .pipe(first()) - .toPromise(); + await getLine$(process.stdin).pipe(first()).toPromise(); try { await execInDir('git', ['diff-index', '--quiet', 'HEAD', '--']); diff --git a/src/dev/renovate/config.ts b/src/dev/renovate/config.ts index fae424982c930..09283e6a5bf2d 100644 --- a/src/dev/renovate/config.ts +++ b/src/dev/renovate/config.ts @@ -85,11 +85,11 @@ export const RENOVATE_CONFIG = { * Define groups of packages that should be updated/configured together */ packageRules: [ - ...RENOVATE_PACKAGE_GROUPS.map(group => ({ + ...RENOVATE_PACKAGE_GROUPS.map((group) => ({ groupSlug: group.name, groupName: `${group.name} related packages`, - packagePatterns: maybeMap(group.packageWords, word => wordRegExp(word).source), - packageNames: maybeFlatMap(group.packageNames, name => [name, getTypePackageName(name)]), + packagePatterns: maybeMap(group.packageWords, (word) => wordRegExp(word).source), + packageNames: maybeFlatMap(group.packageNames, (name) => [name, getTypePackageName(name)]), labels: group.extraLabels && [...DEFAULT_LABELS, ...group.extraLabels], enabled: group.enabled === false ? false : undefined, allowedVersions: group.allowedVersions || undefined, diff --git a/src/dev/renovate/package_groups.ts b/src/dev/renovate/package_groups.ts index 9f5aa8556ac21..d051f956d14df 100644 --- a/src/dev/renovate/package_groups.ts +++ b/src/dev/renovate/package_groups.ts @@ -214,9 +214,9 @@ for (const dep of getAllDepNames()) { // determine if one of the existing groups has typesFor in its // packageNames or if any of the packageWords is in typesFor const existing = RENOVATE_PACKAGE_GROUPS.some( - group => + (group) => (group.packageNames || []).includes(typesFor) || - (group.packageWords || []).some(word => wordRegExp(word).test(typesFor)) + (group.packageWords || []).some((word) => wordRegExp(word).test(typesFor)) ); if (existing) { diff --git a/src/dev/run_check_file_casing.js b/src/dev/run_check_file_casing.js index 87107b43d9ba0..bdbf1827897e7 100644 --- a/src/dev/run_check_file_casing.js +++ b/src/dev/run_check_file_casing.js @@ -39,7 +39,7 @@ run(async ({ log }) => { ], }); - const files = paths.map(path => new File(path)); + const files = paths.map((path) => new File(path)); await checkFileCasing(log, files); }); diff --git a/src/dev/run_check_lockfile_symlinks.js b/src/dev/run_check_lockfile_symlinks.js index b912ea9ddb87e..5ebb7952e2cf3 100644 --- a/src/dev/run_check_lockfile_symlinks.js +++ b/src/dev/run_check_lockfile_symlinks.js @@ -55,13 +55,15 @@ run(async ({ log }) => { ], }); - const files = paths.map(path => new File(path)); + const files = paths.map((path) => new File(path)); await checkLockfileSymlinks(log, files); }); async function checkLockfileSymlinks(log, files) { - const filtered = files.filter(file => !matchesAnyGlob(file.getRelativePath(), IGNORE_FILE_GLOBS)); + const filtered = files.filter( + (file) => !matchesAnyGlob(file.getRelativePath(), IGNORE_FILE_GLOBS) + ); await checkOnlyLockfileAtProjectRoot(filtered); await checkSuperfluousSymlinks(log, filtered); await checkMissingSymlinks(log, filtered); @@ -72,8 +74,8 @@ async function checkOnlyLockfileAtProjectRoot(files) { const errorPaths = []; files - .filter(file => matchesAnyGlob(file.getRelativePath(), LOCKFILE_GLOBS)) - .forEach(file => { + .filter((file) => matchesAnyGlob(file.getRelativePath(), LOCKFILE_GLOBS)) + .forEach((file) => { const path = file.getRelativePath(); const parent = dirname(path); const stats = lstatSync(path); @@ -93,8 +95,8 @@ async function checkSuperfluousSymlinks(log, files) { const errorPaths = []; files - .filter(file => matchesAnyGlob(file.getRelativePath(), LOCKFILE_GLOBS)) - .forEach(file => { + .filter((file) => matchesAnyGlob(file.getRelativePath(), LOCKFILE_GLOBS)) + .forEach((file) => { const path = file.getRelativePath(); const parent = dirname(path); const stats = lstatSync(path); @@ -146,8 +148,8 @@ async function checkMissingSymlinks(log, files) { const errorPaths = []; files - .filter(file => matchesAnyGlob(file.getRelativePath(), MANIFEST_GLOBS)) - .forEach(file => { + .filter((file) => matchesAnyGlob(file.getRelativePath(), MANIFEST_GLOBS)) + .forEach((file) => { const path = file.getRelativePath(); const parent = dirname(path); const lockfilePath = `${parent}/yarn.lock`; @@ -185,8 +187,8 @@ async function checkIncorrectSymlinks(log, files) { const errorPaths = []; files - .filter(file => matchesAnyGlob(file.getRelativePath(), LOCKFILE_GLOBS)) - .forEach(file => { + .filter((file) => matchesAnyGlob(file.getRelativePath(), LOCKFILE_GLOBS)) + .forEach((file) => { const path = file.getRelativePath(); const stats = lstatSync(path); if (!stats.isSymbolicLink()) { @@ -218,5 +220,5 @@ function getCorrectSymlink(path) { } function listPaths(paths) { - return paths.map(path => ` - ${path}`).join('\n'); + return paths.map((path) => ` - ${path}`).join('\n'); } diff --git a/src/dev/run_check_published_api_changes.ts b/src/dev/run_check_published_api_changes.ts index 6d5fa04a93951..45dafe1b415e3 100644 --- a/src/dev/run_check_published_api_changes.ts +++ b/src/dev/run_check_published_api_changes.ts @@ -268,14 +268,14 @@ async function run( const results = await Promise.all( folders - .filter(folder => (opts.filter.length ? folder.match(opts.filter) : true)) - .map(folder => run(folder, { log, opts })) + .filter((folder) => (opts.filter.length ? folder.match(opts.filter) : true)) + .map((folder) => run(folder, { log, opts })) ); - if (results.find(r => r === false) !== undefined) { + if (results.find((r) => r === false) !== undefined) { process.exitCode = 1; } -})().catch(e => { +})().catch((e) => { console.log(e); process.exitCode = 1; }); diff --git a/src/dev/run_i18n_extract.ts b/src/dev/run_i18n_extract.ts index 106c8f10cb5cc..208c86d4acecc 100644 --- a/src/dev/run_i18n_extract.ts +++ b/src/dev/run_i18n_extract.ts @@ -60,8 +60,8 @@ run( }, { title: 'Writing to file', - enabled: ctx => outputDir && ctx.messages.size, - task: async ctx => { + enabled: (ctx) => outputDir && ctx.messages.size, + task: async (ctx) => { const sortedMessages = [...ctx.messages].sort(([key1], [key2]) => key1.localeCompare(key2) ); diff --git a/src/dev/run_prettier_on_changed.ts b/src/dev/run_prettier_on_changed.ts index deca4fa1be3ce..776d4d5ffd389 100644 --- a/src/dev/run_prettier_on_changed.ts +++ b/src/dev/run_prettier_on_changed.ts @@ -57,10 +57,10 @@ run(async function getChangedFiles({ log }) { const changedFiles = changedFileStatuses .split('\n') // Ignore blank lines - .filter(line => line.trim().length > 0) + .filter((line) => line.trim().length > 0) // git diff --name-status outputs lines with two OR three parts // separated by a tab character - .map(line => line.trim().split('\t')) + .map((line) => line.trim().split('\t')) .map(([status, ...paths]) => { // ignore deleted files if (status === 'D') { @@ -75,7 +75,7 @@ run(async function getChangedFiles({ log }) { }) .filter((file): file is File => Boolean(file)); - const pathsToLint = Eslint.pickFilesToLint(log, changedFiles).map(f => f.getAbsolutePath()); + const pathsToLint = Eslint.pickFilesToLint(log, changedFiles).map((f) => f.getAbsolutePath()); if (pathsToLint.length > 0) { log.debug('[prettier] run on %j files: ', pathsToLint.length, pathsToLint); diff --git a/src/dev/sass/build_sass.js b/src/dev/sass/build_sass.js index 1ff7c700d0386..7075bcf55adf5 100644 --- a/src/dev/sass/build_sass.js +++ b/src/dev/sass/build_sass.js @@ -44,7 +44,7 @@ const build = async ({ log, kibanaDir, styleSheetPaths, watch }) => { sourceMap: true, }); - bundles.forEach(bundle => { + bundles.forEach((bundle) => { log.debug(`Compiled SCSS: ${bundle.sourcePath} (theme=${bundle.theme})`); }); @@ -63,9 +63,7 @@ export async function buildSass({ log, kibanaDir, watch }) { const scanDirs = [resolve(kibanaDir, 'src/legacy/core_plugins')]; const paths = [resolve(kibanaDir, 'x-pack')]; const { spec$, disabledSpec$ } = findPluginSpecs({ plugins: { scanDirs, paths } }); - const allPlugins = await Rx.merge(spec$, disabledSpec$) - .pipe(toArray()) - .toPromise(); + const allPlugins = await Rx.merge(spec$, disabledSpec$).pipe(toArray()).toPromise(); const uiExports = collectUiExports(allPlugins); const { styleSheetPaths } = uiExports; @@ -73,17 +71,17 @@ export async function buildSass({ log, kibanaDir, watch }) { log.verbose(styleSheetPaths); if (watch) { - const debouncedBuild = debounce(async path => { + const debouncedBuild = debounce(async (path) => { let buildPaths = styleSheetPaths; if (path) { - buildPaths = styleSheetPaths.filter(styleSheetPath => + buildPaths = styleSheetPaths.filter((styleSheetPath) => path.includes(styleSheetPath.urlImports.publicDir) ); } await build({ log, kibanaDir, styleSheetPaths: buildPaths, watch }); }); - const watchPaths = styleSheetPaths.map(styleSheetPath => styleSheetPath.urlImports.publicDir); + const watchPaths = styleSheetPaths.map((styleSheetPath) => styleSheetPath.urlImports.publicDir); await build({ log, kibanaDir, styleSheetPaths }); diff --git a/src/dev/sasslint/lint_files.js b/src/dev/sasslint/lint_files.js index b9df6a1fa9abb..3a560b4a6ea1a 100644 --- a/src/dev/sasslint/lint_files.js +++ b/src/dev/sasslint/lint_files.js @@ -30,7 +30,7 @@ import { createFailError } from '@kbn/dev-utils'; * @return {undefined} */ export function lintFiles(log, files) { - const paths = files.map(file => file.getRelativePath()); + const paths = files.map((file) => file.getRelativePath()); const report = sassLint.lintFiles( paths.join(', '), diff --git a/src/dev/sasslint/pick_files_to_lint.js b/src/dev/sasslint/pick_files_to_lint.js index c4d8af7bb674f..57c38d0069e06 100644 --- a/src/dev/sasslint/pick_files_to_lint.js +++ b/src/dev/sasslint/pick_files_to_lint.js @@ -28,7 +28,7 @@ const sassLintConfig = safeLoad(fs.readFileSync(sassLintPath)); const { files: { include: includeGlobs }, } = sassLintConfig; -const includeRegex = includeGlobs.map(glob => makeRe(glob)); +const includeRegex = includeGlobs.map((glob) => makeRe(glob)); function matchesInclude(file) { for (let i = 0; i < includeRegex.length; i++) { @@ -40,5 +40,5 @@ function matchesInclude(file) { } export function pickFilesToLint(log, files) { - return files.filter(file => file.isSass()).filter(matchesInclude); + return files.filter((file) => file.isSass()).filter(matchesInclude); } diff --git a/src/dev/storybook/run_storybook_cli.ts b/src/dev/storybook/run_storybook_cli.ts index efb618a48cd6e..7f97cff91aaaa 100644 --- a/src/dev/storybook/run_storybook_cli.ts +++ b/src/dev/storybook/run_storybook_cli.ts @@ -24,7 +24,7 @@ import { storybookAliases } from './aliases'; import { clean } from './commands/clean'; run( - async params => { + async (params) => { const { flags, log } = params; const { _: [alias], @@ -62,7 +62,7 @@ run( Available aliases: ${Object.keys(storybookAliases) - .map(alias => `📕 ${alias}`) + .map((alias) => `📕 ${alias}`) .join('\n ')} Add your alias in src/dev/storybook/aliases.ts diff --git a/src/dev/typescript/exec_in_projects.ts b/src/dev/typescript/exec_in_projects.ts index a34f2bdd28670..5197aa67c7268 100644 --- a/src/dev/typescript/exec_in_projects.ts +++ b/src/dev/typescript/exec_in_projects.ts @@ -37,7 +37,7 @@ export function execInProjects( getArgs: (project: Project) => string[] ) { const list = new Listr( - projects.map(project => ({ + projects.map((project) => ({ task: () => execa(cmd, getArgs(project), { // execute in the current working directory so that relative paths in errors @@ -46,7 +46,7 @@ export function execInProjects( env: chalk.enabled ? { FORCE_COLOR: 'true' } : {}, stdio: ['ignore', 'pipe', 'pipe'], preferLocal: true, - }).catch(error => { + }).catch((error) => { throw new ProjectFailure(project, error); }), title: project.name, diff --git a/src/dev/typescript/get_ts_project_for_absolute_path.ts b/src/dev/typescript/get_ts_project_for_absolute_path.ts index 68ce70685b607..54d7e950834a4 100644 --- a/src/dev/typescript/get_ts_project_for_absolute_path.ts +++ b/src/dev/typescript/get_ts_project_for_absolute_path.ts @@ -35,7 +35,7 @@ import { PROJECTS } from './projects'; export function getTsProjectForAbsolutePath(path: string): Project { const relPath = relative(REPO_ROOT, path); const file = new File(resolve(REPO_ROOT, path)); - const projects = PROJECTS.filter(p => p.isAbsolutePathSelected(path)); + const projects = PROJECTS.filter((p) => p.isAbsolutePathSelected(path)); if (!projects.length) { throw new Error( @@ -44,7 +44,7 @@ export function getTsProjectForAbsolutePath(path: string): Project { } if (projects.length !== 1 && !file.isTypescriptAmbient()) { - const configPaths = projects.map(p => `"${relative(REPO_ROOT, p.tsConfigPath)}"`); + const configPaths = projects.map((p) => `"${relative(REPO_ROOT, p.tsConfigPath)}"`); const pathsMsg = `${configPaths.slice(0, -1).join(', ')} or ${ configPaths[configPaths.length - 1] diff --git a/src/dev/typescript/project.ts b/src/dev/typescript/project.ts index 623c248144ff6..4cf87d812a0b3 100644 --- a/src/dev/typescript/project.ts +++ b/src/dev/typescript/project.ts @@ -27,7 +27,7 @@ import { REPO_ROOT } from '../constants'; function makeMatchers(directory: string, patterns: string[]) { return patterns.map( - pattern => + (pattern) => new Minimatch(resolve(directory, pattern), { dot: true, }) @@ -45,7 +45,7 @@ function parseTsConfig(path: string) { } function testMatchers(matchers: IMinimatch[], path: string) { - return matchers.some(matcher => matcher.match(path)); + return matchers.some((matcher) => matcher.match(path)); } export class Project { diff --git a/src/dev/typescript/projects.ts b/src/dev/typescript/projects.ts index 5019c8bd22341..b368949cc33e1 100644 --- a/src/dev/typescript/projects.ts +++ b/src/dev/typescript/projects.ts @@ -40,19 +40,19 @@ export const PROJECTS = [ // both took closer to 1000ms. ...glob .sync('packages/*/tsconfig.json', { cwd: REPO_ROOT }) - .map(path => new Project(resolve(REPO_ROOT, path))), + .map((path) => new Project(resolve(REPO_ROOT, path))), ...glob .sync('examples/*/tsconfig.json', { cwd: REPO_ROOT }) - .map(path => new Project(resolve(REPO_ROOT, path))), + .map((path) => new Project(resolve(REPO_ROOT, path))), ...glob .sync('x-pack/examples/*/tsconfig.json', { cwd: REPO_ROOT }) - .map(path => new Project(resolve(REPO_ROOT, path))), + .map((path) => new Project(resolve(REPO_ROOT, path))), ...glob .sync('test/plugin_functional/plugins/*/tsconfig.json', { cwd: REPO_ROOT }) - .map(path => new Project(resolve(REPO_ROOT, path))), + .map((path) => new Project(resolve(REPO_ROOT, path))), ...glob .sync('test/interpreter_functional/plugins/*/tsconfig.json', { cwd: REPO_ROOT }) - .map(path => new Project(resolve(REPO_ROOT, path))), + .map((path) => new Project(resolve(REPO_ROOT, path))), ]; export function filterProjectsByFlag(projectFlag?: string) { @@ -61,5 +61,5 @@ export function filterProjectsByFlag(projectFlag?: string) { } const tsConfigPath = resolve(projectFlag); - return PROJECTS.filter(project => project.tsConfigPath === tsConfigPath); + return PROJECTS.filter((project) => project.tsConfigPath === tsConfigPath); } diff --git a/src/dev/typescript/run_check_ts_projects_cli.ts b/src/dev/typescript/run_check_ts_projects_cli.ts index 85f3d473dce6b..b0c125ea47829 100644 --- a/src/dev/typescript/run_check_ts_projects_cli.ts +++ b/src/dev/typescript/run_check_ts_projects_cli.ts @@ -51,7 +51,7 @@ export async function runCheckTsProjectsCli() { log.verbose('Checking %s', file.getAbsolutePath()); - const projects = PROJECTS.filter(p => p.isAbsolutePathSelected(file.getAbsolutePath())); + const projects = PROJECTS.filter((p) => p.isAbsolutePathSelected(file.getAbsolutePath())); if (projects.length === 0) { isNotInTsProject.push(file); } @@ -68,7 +68,7 @@ export async function runCheckTsProjectsCli() { if (isNotInTsProject.length) { log.error( `The following files do not belong to a tsconfig.json file, or that tsconfig.json file is not listed in src/dev/typescript/projects.ts\n${isNotInTsProject - .map(file => ` - ${file.getRelativePath()}`) + .map((file) => ` - ${file.getRelativePath()}`) .join('\n')}` ); } @@ -76,7 +76,7 @@ export async function runCheckTsProjectsCli() { if (isInMultipleTsProjects.length) { log.error( `The following files belong to multiple tsconfig.json files listed in src/dev/typescript/projects.ts\n${isInMultipleTsProjects - .map(file => ` - ${file.getRelativePath()}`) + .map((file) => ` - ${file.getRelativePath()}`) .join('\n')}` ); } diff --git a/src/dev/typescript/run_type_check_cli.ts b/src/dev/typescript/run_type_check_cli.ts index 1f0e4b48b7b4b..1417d30484678 100644 --- a/src/dev/typescript/run_type_check_cli.ts +++ b/src/dev/typescript/run_type_check_cli.ts @@ -80,14 +80,14 @@ export function runTypeCheckCli() { } const tscArgs = ['--noEmit', '--pretty', ...(opts['skip-lib-check'] ? ['--skipLibCheck'] : [])]; - const projects = filterProjectsByFlag(opts.project).filter(p => !p.disableTypeCheck); + const projects = filterProjectsByFlag(opts.project).filter((p) => !p.disableTypeCheck); if (!projects.length) { log.error(`Unable to find project at ${opts.project}`); process.exit(1); } - execInProjects(log, projects, process.execPath, project => [ + execInProjects(log, projects, process.execPath, (project) => [ ...(project.name === 'x-pack' ? ['--max-old-space-size=4096'] : []), require.resolve('typescript/bin/tsc'), ...['--project', project.tsConfigPath], diff --git a/src/es_archiver/actions/edit.ts b/src/es_archiver/actions/edit.ts index de63081a1ea1b..afa51a3b96477 100644 --- a/src/es_archiver/actions/edit.ts +++ b/src/es_archiver/actions/edit.ts @@ -44,13 +44,13 @@ export async function editAction({ cwd: prefix ? resolve(dataDir, prefix) : dataDir, absolute: true, }) - ).map(path => ({ + ).map((path) => ({ path, rawPath: path.slice(0, -3), })); await Promise.all( - archives.map(async archive => { + archives.map(async (archive) => { await createPromiseFromStreams([ Fs.createReadStream(archive.path), createGunzip(), @@ -70,7 +70,7 @@ export async function editAction({ await handler(); await Promise.all( - archives.map(async archive => { + archives.map(async (archive) => { await createPromiseFromStreams([ Fs.createReadStream(archive.rawPath), createGzip({ level: Z_BEST_COMPRESSION }), diff --git a/src/es_archiver/actions/load.ts b/src/es_archiver/actions/load.ts index ae7799205b299..19b5b9e75f31a 100644 --- a/src/es_archiver/actions/load.ts +++ b/src/es_archiver/actions/load.ts @@ -43,7 +43,7 @@ import { // are not listened for const pipeline = (...streams: Readable[]) => streams.reduce((source, dest) => - source.once('error', error => dest.emit('error', error)).pipe(dest as any) + source.once('error', (error) => dest.emit('error', error)).pipe(dest as any) ); export async function loadAction({ @@ -70,7 +70,7 @@ export async function loadAction({ // order, so that createIndexStream can track the state of indexes // across archives and properly skip docs from existing indexes const recordStream = concatStreamProviders( - files.map(filename => () => { + files.map((filename) => () => { log.info('[%s] Loading %j', name, filename); return pipeline( @@ -105,7 +105,7 @@ export async function loadAction({ }); // If we affected the Kibana index, we need to ensure it's migrated... - if (Object.keys(result).some(k => k.startsWith('.kibana'))) { + if (Object.keys(result).some((k) => k.startsWith('.kibana'))) { await migrateKibanaIndex({ client, kbnClient }); if (kibanaPluginIds.includes('spaces')) { diff --git a/src/es_archiver/actions/rebuild_all.ts b/src/es_archiver/actions/rebuild_all.ts index f35b2ca49c666..dfbd51300e04d 100644 --- a/src/es_archiver/actions/rebuild_all.ts +++ b/src/es_archiver/actions/rebuild_all.ts @@ -33,7 +33,7 @@ import { } from '../lib'; async function isDirectory(path: string): Promise { - const stats: Stats = await fromNode(cb => stat(path, cb)); + const stats: Stats = await fromNode((cb) => stat(path, cb)); return stats.isDirectory(); } @@ -71,7 +71,7 @@ export async function rebuildAllAction({ createWriteStream(tempFile), ] as [Readable, ...Writable[]]); - await fromNode(cb => rename(tempFile, childPath, cb)); + await fromNode((cb) => rename(tempFile, childPath, cb)); log.info(`${archiveName} Rebuilt ${childName}`); } } diff --git a/src/es_archiver/cli.ts b/src/es_archiver/cli.ts index 252f99f8f47af..98888b81d9a31 100644 --- a/src/es_archiver/cli.ts +++ b/src/es_archiver/cli.ts @@ -69,34 +69,34 @@ cmd cmd .command('load ') .description('load the archive in --dir with ') - .action(name => execute(archiver => archiver.load(name))); + .action((name) => execute((archiver) => archiver.load(name))); cmd .command('unload ') .description('remove indices created by the archive in --dir with ') - .action(name => execute(archiver => archiver.unload(name))); + .action((name) => execute((archiver) => archiver.unload(name))); cmd .command('empty-kibana-index') .description( '[internal] Delete any Kibana indices, and initialize the Kibana index as Kibana would do on startup.' ) - .action(() => execute(archiver => archiver.emptyKibanaIndex())); + .action(() => execute((archiver) => archiver.emptyKibanaIndex())); cmd .command('edit [prefix]') .description( 'extract the archives under the prefix, wait for edits to be completed, and then recompress the archives' ) - .action(prefix => - execute(archiver => + .action((prefix) => + execute((archiver) => archiver.edit(prefix, async () => { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); - await new Promise(resolveInput => { + await new Promise((resolveInput) => { rl.question(`Press enter when you're done`, () => { rl.close(); resolveInput(); @@ -109,11 +109,11 @@ cmd cmd .command('rebuild-all') .description('[internal] read and write all archives in --dir to remove any inconsistencies') - .action(() => execute(archiver => archiver.rebuildAll())); + .action(() => execute((archiver) => archiver.rebuildAll())); cmd.parse(process.argv); -const missingCommand = cmd.args.every(a => !((a as any) instanceof Command)); +const missingCommand = cmd.args.every((a) => !((a as any) instanceof Command)); if (missingCommand) { execute(); } diff --git a/src/es_archiver/lib/__tests__/stats.ts b/src/es_archiver/lib/__tests__/stats.ts index 28e337b3da529..0ab7d161feb6e 100644 --- a/src/es_archiver/lib/__tests__/stats.ts +++ b/src/es_archiver/lib/__tests__/stats.ts @@ -28,7 +28,7 @@ function createBufferedLog(): ToolingLog & { buffer: string } { const log: ToolingLog = new ToolingLog({ level: 'debug', writeTo: { - write: chunk => ((log as any).buffer += chunk), + write: (chunk) => ((log as any).buffer += chunk), }, }); (log as any).buffer = ''; @@ -47,7 +47,7 @@ function assertDeepClones(a: any, b: any) { expect(one).to.eql(two); expect(one).to.not.be(two); const keys = uniq(Object.keys(one).concat(Object.keys(two))); - keys.forEach(k => { + keys.forEach((k) => { path.push(k); recurse(one[k], two[k]); path.pop(); diff --git a/src/es_archiver/lib/archives/__tests__/format.ts b/src/es_archiver/lib/archives/__tests__/format.ts index f472f094134d7..f3829273ea808 100644 --- a/src/es_archiver/lib/archives/__tests__/format.ts +++ b/src/es_archiver/lib/archives/__tests__/format.ts @@ -31,7 +31,7 @@ import { import { createFormatArchiveStreams } from '../format'; const INPUTS = [1, 2, { foo: 'bar' }, [1, 2]]; -const INPUT_JSON = INPUTS.map(i => JSON.stringify(i, null, 2)).join('\n\n'); +const INPUT_JSON = INPUTS.map((i) => JSON.stringify(i, null, 2)).join('\n\n'); describe('esArchiver createFormatArchiveStreams', () => { describe('{ gzip: false }', () => { @@ -39,7 +39,7 @@ describe('esArchiver createFormatArchiveStreams', () => { const streams = createFormatArchiveStreams({ gzip: false }); expect(streams).to.be.an('array'); expect(streams.length).to.be.greaterThan(0); - streams.forEach(s => expect(s).to.be.a(Stream)); + streams.forEach((s) => expect(s).to.be.a(Stream)); }); it('streams consume js values and produces buffers', async () => { @@ -50,7 +50,7 @@ describe('esArchiver createFormatArchiveStreams', () => { ] as [Readable, ...Writable[]]); expect(output.length).to.be.greaterThan(0); - output.forEach(b => expect(b).to.be.a(Buffer)); + output.forEach((b) => expect(b).to.be.a(Buffer)); }); it('product is pretty-printed JSON separated by two newlines', async () => { @@ -69,7 +69,7 @@ describe('esArchiver createFormatArchiveStreams', () => { const streams = createFormatArchiveStreams({ gzip: true }); expect(streams).to.be.an('array'); expect(streams.length).to.be.greaterThan(0); - streams.forEach(s => expect(s).to.be.a(Stream)); + streams.forEach((s) => expect(s).to.be.a(Stream)); }); it('streams consume js values and produces buffers', async () => { @@ -80,7 +80,7 @@ describe('esArchiver createFormatArchiveStreams', () => { ] as [Readable, ...Writable[]]); expect(output.length).to.be.greaterThan(0); - output.forEach(b => expect(b).to.be.a(Buffer)); + output.forEach((b) => expect(b).to.be.a(Buffer)); }); it('output can be gunzipped', async () => { diff --git a/src/es_archiver/lib/archives/__tests__/parse.ts b/src/es_archiver/lib/archives/__tests__/parse.ts index ba30156b5af39..50cbdfe06f361 100644 --- a/src/es_archiver/lib/archives/__tests__/parse.ts +++ b/src/es_archiver/lib/archives/__tests__/parse.ts @@ -36,7 +36,7 @@ describe('esArchiver createParseArchiveStreams', () => { const streams = createParseArchiveStreams({ gzip: false }); expect(streams).to.be.an('array'); expect(streams.length).to.be.greaterThan(0); - streams.forEach(s => expect(s).to.be.a(Stream)); + streams.forEach((s) => expect(s).to.be.a(Stream)); }); describe('streams', () => { @@ -73,7 +73,7 @@ describe('esArchiver createParseArchiveStreams', () => { it('provides each JSON object as soon as it is parsed', async () => { let onReceived: (resolved: any) => void; - const receivedPromise = new Promise(resolve => (onReceived = resolve)); + const receivedPromise = new Promise((resolve) => (onReceived = resolve)); const input = new PassThrough(); const check = new Transform({ writableObjectMode: true, @@ -124,7 +124,7 @@ describe('esArchiver createParseArchiveStreams', () => { const streams = createParseArchiveStreams({ gzip: true }); expect(streams).to.be.an('array'); expect(streams.length).to.be.greaterThan(0); - streams.forEach(s => expect(s).to.be.a(Stream)); + streams.forEach((s) => expect(s).to.be.a(Stream)); }); describe('streams', () => { diff --git a/src/es_archiver/lib/archives/format.ts b/src/es_archiver/lib/archives/format.ts index 9bef4c9adbf05..ac18147ad6948 100644 --- a/src/es_archiver/lib/archives/format.ts +++ b/src/es_archiver/lib/archives/format.ts @@ -26,7 +26,7 @@ import { RECORD_SEPARATOR } from './constants'; export function createFormatArchiveStreams({ gzip = false }: { gzip?: boolean } = {}) { return [ - createMapStream(record => stringify(record, { space: ' ' })), + createMapStream((record) => stringify(record, { space: ' ' })), createIntersperseStream(RECORD_SEPARATOR), gzip ? createGzip({ level: Z_BEST_COMPRESSION }) : new PassThrough(), ]; diff --git a/src/es_archiver/lib/archives/parse.ts b/src/es_archiver/lib/archives/parse.ts index 0f4460c925019..1d650815f9358 100644 --- a/src/es_archiver/lib/archives/parse.ts +++ b/src/es_archiver/lib/archives/parse.ts @@ -29,7 +29,7 @@ export function createParseArchiveStreams({ gzip = false } = {}) { gzip ? createGunzip() : new PassThrough(), createReplaceStream('\r\n', '\n'), createSplitStream(RECORD_SEPARATOR), - createFilterStream(l => !!l.match(/[^\s]/)), - createMapStream(json => JSON.parse(json.trim())), + createFilterStream((l) => !!l.match(/[^\s]/)), + createMapStream((json) => JSON.parse(json.trim())), ]; } diff --git a/src/es_archiver/lib/directory.ts b/src/es_archiver/lib/directory.ts index 8581207fa795d..3a48e576f44ce 100644 --- a/src/es_archiver/lib/directory.ts +++ b/src/es_archiver/lib/directory.ts @@ -21,6 +21,6 @@ import { readdir } from 'fs'; import { fromNode } from 'bluebird'; export async function readDirectory(path: string) { - const allNames = await fromNode(cb => readdir(path, cb)); - return allNames.filter(name => !name.startsWith('.')); + const allNames = await fromNode((cb) => readdir(path, cb)); + return allNames.filter((name) => !name.startsWith('.')); } diff --git a/src/es_archiver/lib/docs/__tests__/stubs.ts b/src/es_archiver/lib/docs/__tests__/stubs.ts index 698d62e450cb4..d8d961fa054ff 100644 --- a/src/es_archiver/lib/docs/__tests__/stubs.ts +++ b/src/es_archiver/lib/docs/__tests__/stubs.ts @@ -55,7 +55,7 @@ export const createStubClient = ( responses: Array<(name: string, params: any) => any | Promise> = [] ): MockClient => { const createStubClientMethod = (name: string) => - sinon.spy(async params => { + sinon.spy(async (params) => { if (responses.length === 0) { throw new Error(`unexpected client.${name} call`); } diff --git a/src/es_archiver/lib/docs/index_doc_records_stream.ts b/src/es_archiver/lib/docs/index_doc_records_stream.ts index 8236ae8adb6db..a21227aae66c2 100644 --- a/src/es_archiver/lib/docs/index_doc_records_stream.ts +++ b/src/es_archiver/lib/docs/index_doc_records_stream.ts @@ -26,7 +26,7 @@ export function createIndexDocRecordsStream(client: Client, stats: Stats, progre async function indexDocs(docs: any[]) { const body: any[] = []; - docs.forEach(doc => { + docs.forEach((doc) => { stats.indexedDoc(doc.index); body.push( { diff --git a/src/es_archiver/lib/indices/__tests__/generate_index_records_stream.ts b/src/es_archiver/lib/indices/__tests__/generate_index_records_stream.ts index 7a3712ca1a336..fe927483da7b0 100644 --- a/src/es_archiver/lib/indices/__tests__/generate_index_records_stream.ts +++ b/src/es_archiver/lib/indices/__tests__/generate_index_records_stream.ts @@ -63,10 +63,10 @@ describe('esArchiver: createGenerateIndexRecordsStream()', () => { const params = (client.indices.get as sinon.SinonSpy).args[0][0]; expect(params).to.have.property('filterPath'); const filters: string[] = params.filterPath; - expect(filters.some(path => path.includes('index.creation_date'))).to.be(true); - expect(filters.some(path => path.includes('index.uuid'))).to.be(true); - expect(filters.some(path => path.includes('index.version'))).to.be(true); - expect(filters.some(path => path.includes('index.provided_name'))).to.be(true); + expect(filters.some((path) => path.includes('index.creation_date'))).to.be(true); + expect(filters.some((path) => path.includes('index.uuid'))).to.be(true); + expect(filters.some((path) => path.includes('index.version'))).to.be(true); + expect(filters.some((path) => path.includes('index.provided_name'))).to.be(true); }); it('produces one index record for each index name it receives', async () => { diff --git a/src/es_archiver/lib/indices/__tests__/stubs.ts b/src/es_archiver/lib/indices/__tests__/stubs.ts index 3f4682299c38d..c894468dcfcf6 100644 --- a/src/es_archiver/lib/indices/__tests__/stubs.ts +++ b/src/es_archiver/lib/indices/__tests__/stubs.ts @@ -35,7 +35,7 @@ export const createStubStats = (): StubStats => archivedIndex: sinon.stub(), getTestSummary() { const summary: Record = {}; - Object.keys(this).forEach(key => { + Object.keys(this).forEach((key) => { if (this[key].callCount) { summary[key] = this[key].callCount; } @@ -74,7 +74,7 @@ const createEsClientError = (errorType: string) => { }; const indexAlias = (aliases: Record, index: string) => - Object.keys(aliases).find(k => aliases[k] === index); + Object.keys(aliases).find((k) => aliases[k] === index); type StubClient = Client; @@ -133,15 +133,15 @@ export const createStubClient = ( }), delete: sinon.spy(async ({ index }) => { const indices = Array.isArray(index) ? index : [index]; - if (indices.every(ix => existingIndices.includes(ix))) { + if (indices.every((ix) => existingIndices.includes(ix))) { // Delete aliases associated with our indices - indices.forEach(ix => { - const alias = Object.keys(aliases).find(k => aliases[k] === ix); + indices.forEach((ix) => { + const alias = Object.keys(aliases).find((k) => aliases[k] === ix); if (alias) { delete aliases[alias]; } }); - indices.forEach(ix => existingIndices.splice(existingIndices.indexOf(ix), 1)); + indices.forEach((ix) => existingIndices.splice(existingIndices.indexOf(ix), 1)); return { ok: true }; } else { throw createEsClientError('index_not_found_exception'); diff --git a/src/es_archiver/lib/indices/delete_index.ts b/src/es_archiver/lib/indices/delete_index.ts index e3fca587fbc3d..d7ef20b072b26 100644 --- a/src/es_archiver/lib/indices/delete_index.ts +++ b/src/es_archiver/lib/indices/delete_index.ts @@ -109,7 +109,7 @@ export async function waitForSnapshotCompletion(client: Client, index: string, l while (await isSnapshotPending(repository, found.snapshot)) { // wait a bit before getting status again - await new Promise(resolve => setTimeout(resolve, 500)); + await new Promise((resolve) => setTimeout(resolve, 500)); } return; diff --git a/src/es_archiver/lib/records/__tests__/filter_records_stream.ts b/src/es_archiver/lib/records/__tests__/filter_records_stream.ts index d5830478decba..f4f9f32e239ea 100644 --- a/src/es_archiver/lib/records/__tests__/filter_records_stream.ts +++ b/src/es_archiver/lib/records/__tests__/filter_records_stream.ts @@ -66,6 +66,6 @@ describe('esArchiver: createFilterRecordsStream()', () => { ]); expect(output).to.have.length(3); - expect(output.map(o => o.type)).to.eql([type1, type1, type1]); + expect(output.map((o) => o.type)).to.eql([type1, type1, type1]); }); }); diff --git a/src/es_archiver/lib/stats.ts b/src/es_archiver/lib/stats.ts index c69b764fc7290..c7b98c42d3efb 100644 --- a/src/es_archiver/lib/stats.ts +++ b/src/es_archiver/lib/stats.ts @@ -101,7 +101,7 @@ export function createStats(name: string, log: ToolingLog) { public createdIndex(index: string, metadata: Record = {}) { getOrCreate(index).created = true; info('Created index %j', index); - Object.keys(metadata).forEach(key => { + Object.keys(metadata).forEach((key) => { debug('%j %s %j', index, key, metadata[key]); }); } @@ -113,7 +113,7 @@ export function createStats(name: string, log: ToolingLog) { public archivedIndex(index: string, metadata: Record = {}) { getOrCreate(index).archived = true; info('Archived %j', index); - Object.keys(metadata).forEach(key => { + Object.keys(metadata).forEach((key) => { debug('%j %s %j', index, key, metadata[key]); }); } @@ -147,7 +147,7 @@ export function createStats(name: string, log: ToolingLog) { */ public forEachIndex(fn: (index: string, stats: IndexStats) => void) { const clone = this.toJSON(); - Object.keys(clone).forEach(index => { + Object.keys(clone).forEach((index) => { fn(index, clone[index]); }); } diff --git a/src/fixtures/agg_resp/geohash_grid.js b/src/fixtures/agg_resp/geohash_grid.js index 98d3128f7eb2c..0e576a88ab36a 100644 --- a/src/fixtures/agg_resp/geohash_grid.js +++ b/src/fixtures/agg_resp/geohash_grid.js @@ -40,14 +40,14 @@ export default function GeoHashGridAggResponseFixture() { _.range(97, 122) // a-z ); - const tags = _.times(_.random(4, 20), function(i) { + const tags = _.times(_.random(4, 20), function (i) { // random number of tags let docCount = 0; - const buckets = _.times(_.random(40, 200), function() { + const buckets = _.times(_.random(40, 200), function () { return _.sample(geoHashCharts, 3).join(''); }) .sort() - .map(function(geoHash) { + .map(function (geoHash) { const count = _.random(1, 5000); docCount += count; diff --git a/src/fixtures/logstash_fields.js b/src/fixtures/logstash_fields.js index 35a059f0c11f6..a824a94dbd939 100644 --- a/src/fixtures/logstash_fields.js +++ b/src/fixtures/logstash_fields.js @@ -52,7 +52,7 @@ function stubbedLogstashFields() { ['script number', 'long', true, false, { script: '1234' }], ['script date', 'date', true, false, { script: '1234', lang: 'painless' }], ['script murmur3', 'murmur3', true, false, { script: '1234' }], - ].map(function(row) { + ].map(function (row) { const [name, esType, aggregatable, searchable, metadata = {}, subType = undefined] = row; const { diff --git a/src/fixtures/mock_index_patterns.js b/src/fixtures/mock_index_patterns.js index 648fb13156816..f14fb02bd1ec7 100644 --- a/src/fixtures/mock_index_patterns.js +++ b/src/fixtures/mock_index_patterns.js @@ -20,7 +20,7 @@ import sinon from 'sinon'; import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern'; -export default function(Private) { +export default function (Private) { const indexPatterns = Private(FixturesStubbedLogstashIndexPatternProvider); const getIndexPatternStub = sinon.stub().resolves(indexPatterns); diff --git a/src/fixtures/mock_ui_state.js b/src/fixtures/mock_ui_state.js index 42454df2837f7..919274390d4d0 100644 --- a/src/fixtures/mock_ui_state.js +++ b/src/fixtures/mock_ui_state.js @@ -20,24 +20,24 @@ import _ from 'lodash'; let values = {}; export default { - get: function(path, def) { + get: function (path, def) { return _.get(values, path, def); }, - set: function(path, val) { + set: function (path, val) { _.set(values, path, val); return val; }, - setSilent: function(path, val) { + setSilent: function (path, val) { _.set(values, path, val); return val; }, emit: _.noop, on: _.noop, off: _.noop, - clearAllKeys: function() { + clearAllKeys: function () { values = {}; }, - _reset: function() { + _reset: function () { values = {}; }, }; diff --git a/src/fixtures/stubbed_logstash_index_pattern.js b/src/fixtures/stubbed_logstash_index_pattern.js index e20d1b5cd7717..5bb926799fcf6 100644 --- a/src/fixtures/stubbed_logstash_index_pattern.js +++ b/src/fixtures/stubbed_logstash_index_pattern.js @@ -26,7 +26,7 @@ import { npSetup } from '../legacy/ui/public/new_platform/new_platform.karma_moc export default function stubbedLogstashIndexPatternService() { const mockLogstashFields = stubbedLogstashFields(); - const fields = mockLogstashFields.map(function(field) { + const fields = mockLogstashFields.map(function (field) { const kbnType = getKbnFieldType(field.type); if (!kbnType || kbnType.name === 'unknown') { @@ -41,7 +41,13 @@ export default function stubbedLogstashIndexPatternService() { }; }); - const indexPattern = new StubIndexPattern('logstash-*', cfg => cfg, 'time', fields, npSetup.core); + const indexPattern = new StubIndexPattern( + 'logstash-*', + (cfg) => cfg, + 'time', + fields, + npSetup.core + ); indexPattern.id = 'logstash-*'; indexPattern.isTimeNanosBased = () => false; diff --git a/src/fixtures/stubbed_search_source.js b/src/fixtures/stubbed_search_source.js index b444a9a27a6b1..4e43dcf70a7f3 100644 --- a/src/fixtures/stubbed_search_source.js +++ b/src/fixtures/stubbed_search_source.js @@ -30,7 +30,7 @@ export default function stubSearchSource(Private, $q, Promise) { setField: sinon.spy(), fetch: sinon.spy(), destroy: sinon.spy(), - getField: function(param) { + getField: function (param) { switch (param) { case 'index': return indexPattern; @@ -38,11 +38,11 @@ export default function stubSearchSource(Private, $q, Promise) { throw new Error(`Param "${param}" is not implemented in the stubbed search source`); } }, - crankResults: function() { + crankResults: function () { deferedResult.resolve(searchResponse); deferedResult = $q.defer(); }, - onResults: function() { + onResults: function () { onResultsCount++; // Up to the test to resolve this manually @@ -50,10 +50,10 @@ export default function stubSearchSource(Private, $q, Promise) { // someHandler.resolve(require('fixtures/search_response')) return deferedResult.promise; }, - getOnResultsCount: function() { + getOnResultsCount: function () { return onResultsCount; }, - _flatten: function() { + _flatten: function () { return Promise.resolve({ index: indexPattern, body: {} }); }, _requestStartHandlers: [], diff --git a/src/legacy/core_plugins/apm_oss/index.js b/src/legacy/core_plugins/apm_oss/index.js index 5923c1e85ee12..b7ab6797c0de9 100644 --- a/src/legacy/core_plugins/apm_oss/index.js +++ b/src/legacy/core_plugins/apm_oss/index.js @@ -52,7 +52,7 @@ export default function apmOss(kibana) { 'spanIndices', 'metricsIndices', 'onboardingIndices', - ].map(type => server.config().get(`apm_oss.${type}`)) + ].map((type) => server.config().get(`apm_oss.${type}`)) ) ); }, diff --git a/src/legacy/core_plugins/console_legacy/index.ts b/src/legacy/core_plugins/console_legacy/index.ts index af080fd5ace9c..c588b941112d1 100644 --- a/src/legacy/core_plugins/console_legacy/index.ts +++ b/src/legacy/core_plugins/console_legacy/index.ts @@ -28,7 +28,7 @@ export const readLegacyEsConfig = () => { }; // eslint-disable-next-line import/no-default-export -export default function(kibana: any) { +export default function (kibana: any) { return new kibana.Plugin({ id: 'console_legacy', diff --git a/src/legacy/core_plugins/elasticsearch/index.js b/src/legacy/core_plugins/elasticsearch/index.js index 35dd6562aed98..a7d6810ac6158 100644 --- a/src/legacy/core_plugins/elasticsearch/index.js +++ b/src/legacy/core_plugins/elasticsearch/index.js @@ -22,7 +22,7 @@ import { createProxy } from './server/lib/create_proxy'; import { handleESError } from './server/lib/handle_es_error'; import { versionHealthCheck } from './lib/version_health_check'; -export default function(kibana) { +export default function (kibana) { let defaultVars; return new kibana.Plugin({ @@ -49,7 +49,7 @@ export default function(kibana) { }; const clusters = new Map(); - server.expose('getCluster', name => { + server.expose('getCluster', (name) => { if (name === 'admin') { return adminCluster; } diff --git a/src/legacy/core_plugins/elasticsearch/integration_tests/elasticsearch.test.ts b/src/legacy/core_plugins/elasticsearch/integration_tests/elasticsearch.test.ts index 5806c31b78414..0331153cdf615 100644 --- a/src/legacy/core_plugins/elasticsearch/integration_tests/elasticsearch.test.ts +++ b/src/legacy/core_plugins/elasticsearch/integration_tests/elasticsearch.test.ts @@ -43,7 +43,7 @@ describe('Elasticsearch plugin', () => { kibanaVersion: '8.0.0', }); - beforeAll(async function() { + beforeAll(async function () { const settings = { elasticsearch: {}, adjustTimeout: (t: any) => { @@ -72,12 +72,12 @@ describe('Elasticsearch plugin', () => { await root.shutdown(); }, 30000); - it("should set it's status to green when all nodes are compatible", done => { + it("should set it's status to green when all nodes are compatible", (done) => { jest.setTimeout(30000); elasticsearch.status.on('green', () => done()); }); - it("should set it's status to red when some nodes aren't compatible", done => { + it("should set it's status to red when some nodes aren't compatible", (done) => { esNodesCompatibility$.next({ isCompatible: false, incompatibleNodes: [], diff --git a/src/legacy/core_plugins/elasticsearch/lib/version_health_check.js b/src/legacy/core_plugins/elasticsearch/lib/version_health_check.js index 4ee8307f490eb..b1a106d2aae5d 100644 --- a/src/legacy/core_plugins/elasticsearch/lib/version_health_check.js +++ b/src/legacy/core_plugins/elasticsearch/lib/version_health_check.js @@ -20,7 +20,7 @@ export const versionHealthCheck = (esPlugin, logWithMetadata, esNodesCompatibility$) => { esPlugin.status.yellow('Waiting for Elasticsearch'); - return new Promise(resolve => { + return new Promise((resolve) => { esNodesCompatibility$.subscribe(({ isCompatible, message, kibanaVersion, warningNodes }) => { if (!isCompatible) { esPlugin.status.red(message); diff --git a/src/legacy/core_plugins/elasticsearch/lib/version_health_check.test.js b/src/legacy/core_plugins/elasticsearch/lib/version_health_check.test.js index ba7c95bcdfec5..4c03c0c0105ee 100644 --- a/src/legacy/core_plugins/elasticsearch/lib/version_health_check.test.js +++ b/src/legacy/core_plugins/elasticsearch/lib/version_health_check.test.js @@ -20,7 +20,7 @@ import { versionHealthCheck } from './version_health_check'; import { Subject } from 'rxjs'; describe('plugins/elasticsearch', () => { - describe('lib/health_version_check', function() { + describe('lib/health_version_check', function () { let plugin; let logWithMetadata; @@ -37,7 +37,7 @@ describe('plugins/elasticsearch', () => { jest.clearAllMocks(); }); - it('returned promise resolves when all nodes are compatible ', function() { + it('returned promise resolves when all nodes are compatible ', function () { const esNodesCompatibility$ = new Subject(); const versionHealthyPromise = versionHealthCheck( plugin, @@ -48,7 +48,7 @@ describe('plugins/elasticsearch', () => { return expect(versionHealthyPromise).resolves.toBe(undefined); }); - it('should set elasticsearch plugin status to green when all nodes are compatible', function() { + it('should set elasticsearch plugin status to green when all nodes are compatible', function () { const esNodesCompatibility$ = new Subject(); versionHealthCheck(plugin, logWithMetadata, esNodesCompatibility$); expect(plugin.status.yellow).toHaveBeenCalledWith('Waiting for Elasticsearch'); @@ -58,7 +58,7 @@ describe('plugins/elasticsearch', () => { expect(plugin.status.red).not.toHaveBeenCalled(); }); - it('should set elasticsearch plugin status to red when some nodes are incompatible', function() { + it('should set elasticsearch plugin status to red when some nodes are incompatible', function () { const esNodesCompatibility$ = new Subject(); versionHealthCheck(plugin, logWithMetadata, esNodesCompatibility$); expect(plugin.status.yellow).toHaveBeenCalledWith('Waiting for Elasticsearch'); diff --git a/src/legacy/core_plugins/elasticsearch/server/lib/__tests__/handle_es_error.js b/src/legacy/core_plugins/elasticsearch/server/lib/__tests__/handle_es_error.js index 9ec4598674d5d..ccab1a3b830b6 100644 --- a/src/legacy/core_plugins/elasticsearch/server/lib/__tests__/handle_es_error.js +++ b/src/legacy/core_plugins/elasticsearch/server/lib/__tests__/handle_es_error.js @@ -21,8 +21,8 @@ import expect from '@kbn/expect'; import { handleESError } from '../handle_es_error'; import { errors as esErrors } from 'elasticsearch'; -describe('handleESError', function() { - it('should transform elasticsearch errors into boom errors with the same status code', function() { +describe('handleESError', function () { + it('should transform elasticsearch errors into boom errors with the same status code', function () { const conflict = handleESError(new esErrors.Conflict()); expect(conflict.isBoom).to.be(true); expect(conflict.output.statusCode).to.be(409); @@ -40,21 +40,19 @@ describe('handleESError', function() { expect(badRequest.output.statusCode).to.be(400); }); - it('should return an unknown error without transforming it', function() { + it('should return an unknown error without transforming it', function () { const unknown = new Error('mystery error'); expect(handleESError(unknown)).to.be(unknown); }); - it('should return a boom 503 server timeout error for ES connection errors', function() { + it('should return a boom 503 server timeout error for ES connection errors', function () { expect(handleESError(new esErrors.ConnectionFault()).output.statusCode).to.be(503); expect(handleESError(new esErrors.ServiceUnavailable()).output.statusCode).to.be(503); expect(handleESError(new esErrors.NoConnections()).output.statusCode).to.be(503); expect(handleESError(new esErrors.RequestTimeout()).output.statusCode).to.be(503); }); - it('should throw an error if called with a non-error argument', function() { - expect(handleESError) - .withArgs('notAnError') - .to.throwException(); + it('should throw an error if called with a non-error argument', function () { + expect(handleESError).withArgs('notAnError').to.throwException(); }); }); diff --git a/src/legacy/core_plugins/elasticsearch/server/lib/create_proxy.js b/src/legacy/core_plugins/elasticsearch/server/lib/create_proxy.js index 85bc57f89e91c..7302241c46939 100644 --- a/src/legacy/core_plugins/elasticsearch/server/lib/create_proxy.js +++ b/src/legacy/core_plugins/elasticsearch/server/lib/create_proxy.js @@ -43,7 +43,7 @@ export function createProxy(server) { body: payload.toString('utf8'), }, { signal } - ).finally(r => h.response(r)); + ).finally((r) => h.response(r)); }), }); diff --git a/src/legacy/core_plugins/kibana/index.js b/src/legacy/core_plugins/kibana/index.js index 5807c439bd277..ef56ae0e2380c 100644 --- a/src/legacy/core_plugins/kibana/index.js +++ b/src/legacy/core_plugins/kibana/index.js @@ -32,22 +32,16 @@ import { kbnBaseUrl } from '../../../plugins/kibana_legacy/server'; const mkdirAsync = promisify(Fs.mkdir); -export default function(kibana) { +export default function (kibana) { return new kibana.Plugin({ id: 'kibana', - config: function(Joi) { + config: function (Joi) { return Joi.object({ enabled: Joi.boolean().default(true), index: Joi.string().default('.kibana'), - autocompleteTerminateAfter: Joi.number() - .integer() - .min(1) - .default(100000), + autocompleteTerminateAfter: Joi.number().integer().min(1).default(100000), // TODO Also allow units here like in elasticsearch config once this is moved to the new platform - autocompleteTimeout: Joi.number() - .integer() - .min(1) - .default(1000), + autocompleteTimeout: Joi.number().integer().min(1).default(1000), }).default(); }, @@ -96,7 +90,7 @@ export default function(kibana) { uiSettingDefaults: getUiSettingDefaults(), }, - preInit: async function(server) { + preInit: async function (server) { try { // Create the data directory (recursively, if the a parent dir doesn't exist). // If it already exists, does nothing. @@ -108,7 +102,7 @@ export default function(kibana) { } }, - init: async function(server) { + init: async function (server) { const { usageCollection } = server.newPlatform.setup.plugins; // routes importApi(server); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/discover/doc_table.js b/src/legacy/core_plugins/kibana/public/__tests__/discover/doc_table.js index e4ad8a5638fd1..504b00808718b 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/discover/doc_table.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/discover/doc_table.js @@ -35,8 +35,8 @@ let $timeout; let indexPattern; -const init = function($elem, props) { - ngMock.inject(function($rootScope, $compile, _$timeout_) { +const init = function ($elem, props) { + ngMock.inject(function ($rootScope, $compile, _$timeout_) { $timeout = _$timeout_; $parentScope = $rootScope; _.assign($parentScope, props); @@ -44,7 +44,7 @@ const init = function($elem, props) { $compile($elem)($parentScope); // I think the prereq requires this? - $timeout(function() { + $timeout(function () { $elem.scope().$digest(); }, 0); @@ -52,19 +52,19 @@ const init = function($elem, props) { }); }; -const destroy = function() { +const destroy = function () { $scope.$destroy(); $parentScope.$destroy(); }; -describe('docTable', function() { +describe('docTable', function () { let $elem; before(() => setScopedHistory(createBrowserHistory())); beforeEach(() => pluginInstance.initializeInnerAngular()); beforeEach(() => pluginInstance.initializeServices()); beforeEach(ngMock.module('app/discover')); - beforeEach(function() { + beforeEach(function () { $elem = angular.element(` `); - ngMock.inject(function(Private) { + ngMock.inject(function (Private) { indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); }); init($elem, { @@ -87,15 +87,15 @@ describe('docTable', function() { $scope.$digest(); }); - afterEach(function() { + afterEach(function () { destroy(); }); - it('should compile', function() { + it('should compile', function () { expect($elem.text()).to.not.be.empty(); }); - it('should have an addRows function that increases the row count', function() { + it('should have an addRows function that increases the row count', function () { expect($scope.addRows).to.be.a(Function); $scope.$digest(); expect($scope.limit).to.be(50); @@ -103,7 +103,7 @@ describe('docTable', function() { expect($scope.limit).to.be(100); }); - it('should reset the row limit when results are received', function() { + it('should reset the row limit when results are received', function () { $scope.limit = 100; expect($scope.limit).to.be(100); $scope.hits = [...hits]; @@ -111,7 +111,7 @@ describe('docTable', function() { expect($scope.limit).to.be(50); }); - it('should have a header and a table element', function() { + it('should have a header and a table element', function () { $scope.$digest(); expect($elem.find('thead').length).to.be(1); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/discover/fixed_scroll.js b/src/legacy/core_plugins/kibana/public/__tests__/discover/fixed_scroll.js index 4a8736cc0d6a4..9bb0ebc76474d 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/discover/fixed_scroll.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/discover/fixed_scroll.js @@ -37,7 +37,7 @@ angular .service('debounce', ['$timeout', DebounceProviderTimeout]) .directive('fixedScroll', FixedScrollProvider); -describe('FixedScroll directive', function() { +describe('FixedScroll directive', function () { const sandbox = sinon.createSandbox(); let compile; @@ -45,13 +45,13 @@ describe('FixedScroll directive', function() { const trash = []; beforeEach(ngMock.module(testModuleName)); beforeEach( - ngMock.inject(function($compile, $rootScope, $timeout) { + ngMock.inject(function ($compile, $rootScope, $timeout) { flushPendingTasks = function flushPendingTasks() { $rootScope.$digest(); $timeout.flush(); }; - compile = function(ratioY, ratioX) { + compile = function (ratioY, ratioX) { if (ratioX == null) ratioX = ratioY; // since the directive works at the sibling level we create a @@ -93,15 +93,15 @@ describe('FixedScroll directive', function() { }) ); - afterEach(function() { - trash.splice(0).forEach(function($el) { + afterEach(function () { + trash.splice(0).forEach(function ($el) { $el.remove(); }); sandbox.restore(); }); - it('does nothing when not needed', function() { + it('does nothing when not needed', function () { let els = compile(0.5, 1.5); expect(els.$scroller).to.have.length(0); @@ -109,23 +109,23 @@ describe('FixedScroll directive', function() { expect(els.$scroller).to.have.length(0); }); - it('attaches a scroller below the element when the content is larger then the container', function() { + it('attaches a scroller below the element when the content is larger then the container', function () { const els = compile(1.5); expect(els.$scroller).to.have.length(1); }); - it('copies the width of the container', function() { + it('copies the width of the container', function () { const els = compile(1.5); expect(els.$scroller.width()).to.be(els.$container.width()); }); - it('mimics the scrollWidth of the element', function() { + it('mimics the scrollWidth of the element', function () { const els = compile(1.5); expect(els.$scroller.prop('scrollWidth')).to.be(els.$container.prop('scrollWidth')); }); - describe('scroll event handling / tug of war prevention', function() { - it('listens when needed, unlistens when not needed', function() { + describe('scroll event handling / tug of war prevention', function () { + it('listens when needed, unlistens when not needed', function () { const on = sandbox.spy($.fn, 'on'); const off = sandbox.spy($.fn, 'off'); @@ -143,7 +143,7 @@ describe('FixedScroll directive', function() { // the this values should be different expect(spy.thisValues[0].is(spy.thisValues[1])).to.be(false); // but they should be either $scroller or $container - spy.thisValues.forEach(function($this) { + spy.thisValues.forEach(function ($this) { if ($this.is(els.$scroller) || $this.is(els.$container)) return; expect.fail('expected ' + name + ' to be called with $scroller or $container'); }); @@ -153,21 +153,21 @@ describe('FixedScroll directive', function() { [ { from: '$container', to: '$scroller' }, { from: '$scroller', to: '$container' }, - ].forEach(function(names) { - describe('scroll events ' + JSON.stringify(names), function() { + ].forEach(function (names) { + describe('scroll events ' + JSON.stringify(names), function () { let spy; let els; let $from; let $to; - beforeEach(function() { + beforeEach(function () { spy = sandbox.spy($.fn, 'scrollLeft'); els = compile(1.5); $from = els[names.from]; $to = els[names.to]; }); - it('transfers the scrollLeft', function() { + it('transfers the scrollLeft', function () { expect(spy.callCount).to.be(0); $from.scroll(); expect(spy.callCount).to.be(2); @@ -188,7 +188,7 @@ describe('FixedScroll directive', function() { * but the browser seems to be very careful about triggering the event too much * and I can't reliably recreate the browsers behavior in a test. So... faking it! */ - it('prevents tug of war by ignoring echo scroll events', function() { + it('prevents tug of war by ignoring echo scroll events', function () { $from.scroll(); expect(spy.callCount).to.be(2); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/discover/row_headers.js b/src/legacy/core_plugins/kibana/public/__tests__/discover/row_headers.js index 2a34ace8f1312..29c301bf065c4 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/discover/row_headers.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/discover/row_headers.js @@ -28,7 +28,7 @@ import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logsta import { setScopedHistory } from '../../../../../../plugins/discover/public/kibana_services'; import { createBrowserHistory } from 'history'; -describe('Doc Table', function() { +describe('Doc Table', function () { let $parentScope; let $scope; @@ -42,7 +42,7 @@ describe('Doc Table', function() { before(() => setScopedHistory(createBrowserHistory())); beforeEach(ngMock.module('app/discover')); beforeEach( - ngMock.inject(function($rootScope, Private) { + ngMock.inject(function ($rootScope, Private) { $parentScope = $rootScope; $parentScope.indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider); mapping = $parentScope.indexPattern.fields; @@ -50,7 +50,7 @@ describe('Doc Table', function() { // Stub `getConverterFor` for a field in the indexPattern to return mock data. // Returns `val` if provided, otherwise generates fake data for the field. fakeRowVals = getFakeRowVals('formatted', 0, mapping); - stubFieldFormatConverter = function($root, field, val) { + stubFieldFormatConverter = function ($root, field, val) { const convertFn = (value, type, options) => { if (val) { return val; @@ -67,8 +67,8 @@ describe('Doc Table', function() { ); // Sets up the directive, take an element, and a list of properties to attach to the parent scope. - const init = function($elem, props) { - ngMock.inject(function($compile) { + const init = function ($elem, props) { + ngMock.inject(function ($compile) { _.assign($parentScope, props); $compile($elem)($parentScope); $elem.scope().$digest(); @@ -76,19 +76,19 @@ describe('Doc Table', function() { }); }; - const destroy = function() { + const destroy = function () { $scope.$destroy(); $parentScope.$destroy(); }; // For testing column removing/adding for the header and the rows - const columnTests = function(elemType, parentElem) { - it('should create a time column if the timefield is defined', function() { + const columnTests = function (elemType, parentElem) { + it('should create a time column if the timefield is defined', function () { const childElems = parentElem.find(elemType); expect(childElems.length).to.be(1); }); - it('should be able to add and remove columns', function() { + it('should be able to add and remove columns', function () { let childElems; stubFieldFormatConverter($parentScope, 'bytes'); @@ -114,7 +114,7 @@ describe('Doc Table', function() { expect($(childElems[1]).text()).to.contain('request_body'); }); - it('should create only the toggle column if there is no timeField', function() { + it('should create only the toggle column if there is no timeField', function () { delete parentElem.scope().indexPattern.timeFieldName; parentElem.scope().$digest(); @@ -123,7 +123,7 @@ describe('Doc Table', function() { }); }; - describe('kbnTableRow', function() { + describe('kbnTableRow', function () { const $elem = angular.element( ' stubFieldFormatConverter($root, f.name)); + $root.indexPattern.fields.forEach((f) => stubFieldFormatConverter($root, f.name)); $row = $('').attr({ 'kbn-table-row': 'row', @@ -262,26 +262,16 @@ describe('Doc Table', function() { $before = $row.find('td'); expect($before).to.have.length(3); - expect( - $before - .eq(0) - .text() - .trim() - ).to.be(''); - expect( - $before - .eq(1) - .text() - .trim() - ).to.match(/^time_formatted/); + expect($before.eq(0).text().trim()).to.be(''); + expect($before.eq(1).text().trim()).to.match(/^time_formatted/); }) ); - afterEach(function() { + afterEach(function () { $row.remove(); }); - it('handles a new column', function() { + it('handles a new column', function () { $root.columns.push('bytes'); $root.$apply(); @@ -290,15 +280,10 @@ describe('Doc Table', function() { expect($after[0]).to.be($before[0]); expect($after[1]).to.be($before[1]); expect($after[2]).to.be($before[2]); - expect( - $after - .eq(3) - .text() - .trim() - ).to.match(/^bytes_formatted/); + expect($after.eq(3).text().trim()).to.match(/^bytes_formatted/); }); - it('handles two new columns at once', function() { + it('handles two new columns at once', function () { $root.columns.push('bytes'); $root.columns.push('request_body'); $root.$apply(); @@ -308,21 +293,11 @@ describe('Doc Table', function() { expect($after[0]).to.be($before[0]); expect($after[1]).to.be($before[1]); expect($after[2]).to.be($before[2]); - expect( - $after - .eq(3) - .text() - .trim() - ).to.match(/^bytes_formatted/); - expect( - $after - .eq(4) - .text() - .trim() - ).to.match(/^request_body_formatted/); + expect($after.eq(3).text().trim()).to.match(/^bytes_formatted/); + expect($after.eq(4).text().trim()).to.match(/^request_body_formatted/); }); - it('handles three new columns in odd places', function() { + it('handles three new columns in odd places', function () { $root.columns = ['@timestamp', 'bytes', '_source', 'request_body']; $root.$apply(); @@ -330,28 +305,13 @@ describe('Doc Table', function() { expect($after).to.have.length(6); expect($after[0]).to.be($before[0]); expect($after[1]).to.be($before[1]); - expect( - $after - .eq(2) - .text() - .trim() - ).to.match(/^@timestamp_formatted/); - expect( - $after - .eq(3) - .text() - .trim() - ).to.match(/^bytes_formatted/); + expect($after.eq(2).text().trim()).to.match(/^@timestamp_formatted/); + expect($after.eq(3).text().trim()).to.match(/^bytes_formatted/); expect($after[4]).to.be($before[2]); - expect( - $after - .eq(5) - .text() - .trim() - ).to.match(/^request_body_formatted/); + expect($after.eq(5).text().trim()).to.match(/^request_body_formatted/); }); - it('handles a removed column', function() { + it('handles a removed column', function () { _.pull($root.columns, '_source'); $root.$apply(); @@ -361,7 +321,7 @@ describe('Doc Table', function() { expect($after[1]).to.be($before[1]); }); - it('handles two removed columns', function() { + it('handles two removed columns', function () { // first add a column $root.columns.push('@timestamp'); $root.$apply(); @@ -379,7 +339,7 @@ describe('Doc Table', function() { expect($after[1]).to.be($before[1]); }); - it('handles three removed random columns', function() { + it('handles three removed random columns', function () { // first add two column $root.columns.push('@timestamp', 'bytes'); $root.$apply(); @@ -396,15 +356,10 @@ describe('Doc Table', function() { expect($after).to.have.length(3); expect($after[0]).to.be($before[0]); expect($after[1]).to.be($before[1]); - expect( - $after - .eq(2) - .text() - .trim() - ).to.match(/^@timestamp_formatted/); + expect($after.eq(2).text().trim()).to.match(/^@timestamp_formatted/); }); - it('handles two columns with the same content', function() { + it('handles two columns with the same content', function () { stubFieldFormatConverter($root, 'request_body', fakeRowVals.bytes); $root.columns.length = 0; @@ -414,21 +369,11 @@ describe('Doc Table', function() { const $after = $row.find('td'); expect($after).to.have.length(4); - expect( - $after - .eq(2) - .text() - .trim() - ).to.match(/^bytes_formatted/); - expect( - $after - .eq(3) - .text() - .trim() - ).to.match(/^bytes_formatted/); + expect($after.eq(2).text().trim()).to.match(/^bytes_formatted/); + expect($after.eq(3).text().trim()).to.match(/^bytes_formatted/); }); - it('handles two columns swapping position', function() { + it('handles two columns swapping position', function () { $root.columns.push('bytes'); $root.$apply(); @@ -446,7 +391,7 @@ describe('Doc Table', function() { expect($after[3]).to.be($mid[2]); }); - it('handles four columns all reversing position', function() { + it('handles four columns all reversing position', function () { $root.columns.push('bytes', 'response', '@timestamp'); $root.$apply(); @@ -466,7 +411,7 @@ describe('Doc Table', function() { expect($after[5]).to.be($mid[2]); }); - it('handles multiple columns with the same name', function() { + it('handles multiple columns with the same name', function () { $root.columns.push('bytes', 'bytes', 'bytes'); $root.$apply(); @@ -475,24 +420,9 @@ describe('Doc Table', function() { expect($after[0]).to.be($before[0]); expect($after[1]).to.be($before[1]); expect($after[2]).to.be($before[2]); - expect( - $after - .eq(3) - .text() - .trim() - ).to.match(/^bytes_formatted/); - expect( - $after - .eq(4) - .text() - .trim() - ).to.match(/^bytes_formatted/); - expect( - $after - .eq(5) - .text() - .trim() - ).to.match(/^bytes_formatted/); + expect($after.eq(3).text().trim()).to.match(/^bytes_formatted/); + expect($after.eq(4).text().trim()).to.match(/^bytes_formatted/); + expect($after.eq(5).text().trim()).to.match(/^bytes_formatted/); }); }); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table.js index de85bec011eeb..413afaa90d4f2 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table.js @@ -35,7 +35,7 @@ import { tabifiedData } from './tabified_data'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { configureAppAngularModule } from '../../../../../../plugins/kibana_legacy/public/angular'; -describe('Table Vis - AggTable Directive', function() { +describe('Table Vis - AggTable Directive', function () { let $rootScope; let $compile; let settings; @@ -50,7 +50,7 @@ describe('Table Vis - AggTable Directive', function() { beforeEach(ngMock.module('kibana/table_vis')); beforeEach( - ngMock.inject(function($injector, config) { + ngMock.inject(function ($injector, config) { settings = config; $rootScope = $injector.get('$rootScope'); @@ -59,14 +59,14 @@ describe('Table Vis - AggTable Directive', function() { ); let $scope; - beforeEach(function() { + beforeEach(function () { $scope = $rootScope.$new(); }); - afterEach(function() { + afterEach(function () { $scope.$destroy(); }); - it('renders a simple response properly', function() { + it('renders a simple response properly', function () { $scope.dimensions = { metrics: [{ accessor: 0, format: { id: 'number' }, params: {} }], buckets: [], @@ -83,7 +83,7 @@ describe('Table Vis - AggTable Directive', function() { expect($el.find('td').text()).to.eql('1,000'); }); - it('renders nothing if the table is empty', function() { + it('renders nothing if the table is empty', function () { $scope.dimensions = {}; $scope.table = null; const $el = $compile('')( @@ -94,7 +94,7 @@ describe('Table Vis - AggTable Directive', function() { expect($el.find('tbody').length).to.be(0); }); - it('renders a complex response properly', async function() { + it('renders a complex response properly', async function () { $scope.dimensions = { buckets: [ { accessor: 0, params: {} }, @@ -124,15 +124,13 @@ describe('Table Vis - AggTable Directive', function() { } } - $rows.each(function() { + $rows.each(function () { // 6 cells in every row const $cells = $(this).find('td'); expect($cells.length).to.be(6); - const txts = $cells.map(function() { - return $(this) - .text() - .trim(); + const txts = $cells.map(function () { + return $(this).text().trim(); }); // two character country code @@ -149,7 +147,7 @@ describe('Table Vis - AggTable Directive', function() { }); }); - describe('renders totals row', function() { + describe('renders totals row', function () { async function totalsRowTest(totalFunc, expected) { function setDefaultTimezone() { moment.tz.setDefault(settings.get('dateFormat:tz')); @@ -192,19 +190,15 @@ describe('Table Vis - AggTable Directive', function() { expect($cells.length).to.be(6); for (let i = 0; i < 6; i++) { - expect( - $($cells[i]) - .text() - .trim() - ).to.be(expected[i]); + expect($($cells[i]).text().trim()).to.be(expected[i]); } settings.set('dateFormat:tz', oldTimezoneSetting); off(); } - it('as count', async function() { + it('as count', async function () { await totalsRowTest('count', ['18', '18', '18', '18', '18', '18']); }); - it('as min', async function() { + it('as min', async function () { await totalsRowTest('min', [ '', '2014-09-28', @@ -214,7 +208,7 @@ describe('Table Vis - AggTable Directive', function() { '11', ]); }); - it('as max', async function() { + it('as max', async function () { await totalsRowTest('max', [ '', '2014-10-03', @@ -224,16 +218,16 @@ describe('Table Vis - AggTable Directive', function() { '837', ]); }); - it('as avg', async function() { + it('as avg', async function () { await totalsRowTest('avg', ['', '', '87,221.5', '', '64.667', '206.833']); }); - it('as sum', async function() { + it('as sum', async function () { await totalsRowTest('sum', ['', '', '1,569,987', '', '1,164', '3,723']); }); }); - describe('aggTable.toCsv()', function() { - it('escapes rows and columns properly', function() { + describe('aggTable.toCsv()', function () { + it('escapes rows and columns properly', function () { const $el = $compile('')( $scope ); @@ -255,7 +249,7 @@ describe('Table Vis - AggTable Directive', function() { ); }); - it('exports rows and columns properly', async function() { + it('exports rows and columns properly', async function () { $scope.dimensions = { buckets: [ { accessor: 0, params: {} }, @@ -310,7 +304,7 @@ describe('Table Vis - AggTable Directive', function() { ); }); - it('exports formatted rows and columns properly', async function() { + it('exports formatted rows and columns properly', async function () { $scope.dimensions = { buckets: [ { accessor: 0, params: {} }, @@ -335,7 +329,7 @@ describe('Table Vis - AggTable Directive', function() { $tableScope.table = $scope.table; // Create our own converter since the ones we use for tests don't actually transform the provided value - $tableScope.formattedColumns[0].formatter.convert = v => `${v}_formatted`; + $tableScope.formattedColumns[0].formatter.convert = (v) => `${v}_formatted`; const formatted = aggTable.toCsv(true); expect(formatted).to.be( @@ -369,7 +363,7 @@ describe('Table Vis - AggTable Directive', function() { }); }); - it('renders percentage columns', async function() { + it('renders percentage columns', async function () { $scope.dimensions = { buckets: [ { accessor: 0, params: {} }, @@ -397,22 +391,12 @@ describe('Table Vis - AggTable Directive', function() { const $headings = $el.find('th'); expect($headings.length).to.be(7); - expect( - $headings - .eq(3) - .text() - .trim() - ).to.be('Average bytes percentages'); - - const countColId = $scope.table.columns.find(col => col.name === $scope.percentageCol).id; - const counts = $scope.table.rows.map(row => row[countColId]); + expect($headings.eq(3).text().trim()).to.be('Average bytes percentages'); + + const countColId = $scope.table.columns.find((col) => col.name === $scope.percentageCol).id; + const counts = $scope.table.rows.map((row) => row[countColId]); const total = counts.reduce((sum, curr) => sum + curr, 0); - const $percentageColValues = $el.find('tbody tr').map((i, el) => - $(el) - .find('td') - .eq(3) - .text() - ); + const $percentageColValues = $el.find('tbody tr').map((i, el) => $(el).find('td').eq(3).text()); $percentageColValues.each((i, value) => { const percentage = `${round((counts[i] / total) * 100, 3)}%`; @@ -420,23 +404,23 @@ describe('Table Vis - AggTable Directive', function() { }); }); - describe('aggTable.exportAsCsv()', function() { + describe('aggTable.exportAsCsv()', function () { let origBlob; function FakeBlob(slices, opts) { this.slices = slices; this.opts = opts; } - beforeEach(function() { + beforeEach(function () { origBlob = window.Blob; window.Blob = FakeBlob; }); - afterEach(function() { + afterEach(function () { window.Blob = origBlob; }); - it('calls _saveAs properly', function() { + it('calls _saveAs properly', function () { const $el = $compile('')($scope); $scope.$digest(); @@ -468,7 +452,7 @@ describe('Table Vis - AggTable Directive', function() { expect(call.args[1]).to.be('somefilename.csv'); }); - it('should use the export-title attribute', function() { + it('should use the export-title attribute', function () { const expected = 'export file name'; const $el = $compile( `` diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table_group.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table_group.js index 3cd7de393d66a..99b397167009d 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table_group.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_table/agg_table_group.js @@ -31,7 +31,7 @@ import { npStart } from 'ui/new_platform'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { configureAppAngularModule } from '../../../../../../plugins/kibana_legacy/public/angular'; -describe('Table Vis - AggTableGroup Directive', function() { +describe('Table Vis - AggTableGroup Directive', function () { let $rootScope; let $compile; @@ -45,21 +45,21 @@ describe('Table Vis - AggTableGroup Directive', function() { beforeEach(ngMock.module('kibana/table_vis')); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $rootScope = $injector.get('$rootScope'); $compile = $injector.get('$compile'); }) ); let $scope; - beforeEach(function() { + beforeEach(function () { $scope = $rootScope.$new(); }); - afterEach(function() { + afterEach(function () { $scope.$destroy(); }); - it('renders a simple split response properly', function() { + it('renders a simple split response properly', function () { $scope.dimensions = { metrics: [{ accessor: 0, format: { id: 'number' }, params: {} }], buckets: [], @@ -80,7 +80,7 @@ describe('Table Vis - AggTableGroup Directive', function() { expect($el.find('kbn-agg-table').length).to.be(1); }); - it('renders nothing if the table list is empty', function() { + it('renders nothing if the table list is empty', function () { const $el = $( '' ); @@ -96,7 +96,7 @@ describe('Table Vis - AggTableGroup Directive', function() { expect($subTables.length).to.be(0); }); - it('renders a complex response properly', function() { + it('renders a complex response properly', function () { $scope.dimensions = { splitRow: [{ accessor: 0, params: {} }], buckets: [ @@ -122,7 +122,7 @@ describe('Table Vis - AggTableGroup Directive', function() { const $subTableHeaders = $el.find('.kbnAggTable__groupHeader'); expect($subTableHeaders.length).to.be(3); - $subTableHeaders.each(function(i) { + $subTableHeaders.each(function (i) { expect($(this).text()).to.be(group.tables[i].title); }); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud.js index 8f08f6a1f37e6..35c7b77687b94 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud.js @@ -32,7 +32,7 @@ import { seedColors } from '../../../../../../plugins/charts/public/services/col // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { TagCloud } from '../../../../../../plugins/vis_type_tagcloud/public/components/tag_cloud'; -describe('tag cloud tests', function() { +describe('tag cloud tests', function () { const minValue = 1; const maxValue = 9; const midValue = (minValue + maxValue) / 2; @@ -126,30 +126,30 @@ describe('tag cloud tests', function() { sqrtScaleTest, biggerFontTest, trimDataTest, - ].forEach(function(test) { + ].forEach(function (test) { describe(`should position elements correctly for options: ${JSON.stringify( test.options - )}`, function() { - beforeEach(async function() { + )}`, function () { + beforeEach(async function () { setupDOM(); tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(test.data); tagCloud.setOptions(test.options); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); it( 'completeness should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.COMPLETE); }) ); it( 'positions should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { const textElements = domNode.querySelectorAll('text'); verifyTagProperties(test.expected, textElements, tagCloud); }) @@ -157,9 +157,9 @@ describe('tag cloud tests', function() { }); }); - [5, 100, 200, 300, 500].forEach(function(timeout) { - describe(`should only send single renderComplete event at the very end, using ${timeout}ms timeout`, function() { - beforeEach(async function() { + [5, 100, 200, 300, 500].forEach(function (timeout) { + describe(`should only send single renderComplete event at the very end, using ${timeout}ms timeout`, function () { + beforeEach(async function () { setupDOM(); //TagCloud takes at least 600ms to complete (due to d3 animation) @@ -171,21 +171,21 @@ describe('tag cloud tests', function() { //this timeout modifies the settings before the cloud is rendered. //the cloud needs to use the correct options setTimeout(() => tagCloud.setOptions(logScaleTest.options), timeout); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); it( 'completeness should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.COMPLETE); }) ); it( 'positions should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { const textElements = domNode.querySelectorAll('text'); verifyTagProperties(logScaleTest.expected, textElements, tagCloud); }) @@ -193,63 +193,63 @@ describe('tag cloud tests', function() { }); }); - describe('should use the latest state before notifying (when modifying options multiple times)', function() { - beforeEach(async function() { + describe('should use the latest state before notifying (when modifying options multiple times)', function () { + beforeEach(async function () { setupDOM(); tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(baseTest.data); tagCloud.setOptions(baseTest.options); tagCloud.setOptions(logScaleTest.options); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); it( 'completeness should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.COMPLETE); }) ); it( 'positions should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { const textElements = domNode.querySelectorAll('text'); verifyTagProperties(logScaleTest.expected, textElements, tagCloud); }) ); }); - describe('should use the latest state before notifying (when modifying data multiple times)', function() { - beforeEach(async function() { + describe('should use the latest state before notifying (when modifying data multiple times)', function () { + beforeEach(async function () { setupDOM(); tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(baseTest.data); tagCloud.setOptions(baseTest.options); tagCloud.setData(trimDataTest.data); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); it( 'completeness should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.COMPLETE); }) ); it( 'positions should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { const textElements = domNode.querySelectorAll('text'); verifyTagProperties(trimDataTest.expected, textElements, tagCloud); }) ); }); - describe('should not get multiple render-events', function() { + describe('should not get multiple render-events', function () { let counter; - beforeEach(function() { + beforeEach(function () { counter = 0; setupDOM(); return new Promise((resolve, reject) => { @@ -283,21 +283,21 @@ describe('tag cloud tests', function() { it( 'completeness should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.COMPLETE); }) ); it( 'positions should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { const textElements = domNode.querySelectorAll('text'); verifyTagProperties(logScaleTest.expected, textElements, tagCloud); }) ); }); - describe('should show correct data when state-updates are interleaved with resize event', function() { - beforeEach(async function() { + describe('should show correct data when state-updates are interleaved with resize event', function () { + beforeEach(async function () { setupDOM(); tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(logScaleTest.data); @@ -312,43 +312,43 @@ describe('tag cloud tests', function() { tagCloud.setData(baseTest.data); tagCloud.setOptions(baseTest.options); }, 200); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); it( 'completeness should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.COMPLETE); }) ); it( 'positions should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { const textElements = domNode.querySelectorAll('text'); verifyTagProperties(baseTest.expected, textElements, tagCloud); }) ); }); - describe(`should not put elements in view when container is too small`, function() { - beforeEach(async function() { + describe(`should not put elements in view when container is too small`, function () { + beforeEach(async function () { setupDOM(); domNode.style.width = '1px'; domNode.style.height = '1px'; tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(baseTest.data); tagCloud.setOptions(baseTest.options); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); - it('completeness should not be ok', function() { + it('completeness should not be ok', function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.INCOMPLETE); }); - it('positions should not be ok', function() { + it('positions should not be ok', function () { const textElements = domNode.querySelectorAll('text'); for (let i = 0; i < textElements; i++) { const bbox = textElements[i].getBoundingClientRect(); @@ -357,8 +357,8 @@ describe('tag cloud tests', function() { }); }); - describe(`tags should fit after making container bigger`, function() { - beforeEach(async function() { + describe(`tags should fit after making container bigger`, function () { + beforeEach(async function () { setupDOM(); domNode.style.width = '1px'; domNode.style.height = '1px'; @@ -366,50 +366,50 @@ describe('tag cloud tests', function() { tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(baseTest.data); tagCloud.setOptions(baseTest.options); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); //make bigger domNode.style.width = '512px'; domNode.style.height = '512px'; tagCloud.resize(); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); it( 'completeness should be ok', - handleExpectedBlip(function() { + handleExpectedBlip(function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.COMPLETE); }) ); }); - describe(`tags should no longer fit after making container smaller`, function() { - beforeEach(async function() { + describe(`tags should no longer fit after making container smaller`, function () { + beforeEach(async function () { setupDOM(); tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(baseTest.data); tagCloud.setOptions(baseTest.options); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); //make smaller domNode.style.width = '1px'; domNode.style.height = '1px'; tagCloud.resize(); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); }); afterEach(teardownDOM); - it('completeness should not be ok', function() { + it('completeness should not be ok', function () { expect(tagCloud.getStatus()).to.equal(TagCloud.STATUS.INCOMPLETE); }); }); - describe('tagcloudscreenshot', function() { + describe('tagcloudscreenshot', function () { let imageComparator; - beforeEach(async function() { + beforeEach(async function () { setupDOM(); imageComparator = new ImageComparator(); }); @@ -419,12 +419,12 @@ describe('tag cloud tests', function() { teardownDOM(); }); - it('should render simple image', async function() { + it('should render simple image', async function () { tagCloud = new TagCloud(domNode, colorScale); tagCloud.setData(baseTest.data); tagCloud.setOptions(baseTest.options); - await fromNode(cb => tagCloud.once('renderComplete', cb)); + await fromNode((cb) => tagCloud.once('renderComplete', cb)); const mismatchedPixels = await imageComparator.compareDOMContents( domNode.innerHTML, @@ -522,7 +522,7 @@ describe('tag cloud tests', function() { const centered = largest[1] === 0 && largest[2] === 0; const halfWidth = debugInfo.size.width / 2; const halfHeight = debugInfo.size.height / 2; - const inside = debugInfo.positions.filter(position => { + const inside = debugInfo.positions.filter((position) => { const x = position.x + halfWidth; const y = position.y + halfHeight; return 0 <= x && x <= debugInfo.size.width && 0 <= y && y <= debugInfo.size.height; @@ -532,7 +532,7 @@ describe('tag cloud tests', function() { } function handleExpectedBlip(assertion) { - return function() { + return function () { if (!shouldAssert()) { return; } diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud_visualization.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud_visualization.js index 040ee18916fa2..4a6e9e7765213 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud_visualization.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_tagcloud/tag_cloud_visualization.js @@ -42,7 +42,7 @@ import { setFormatService } from '../../../../../../plugins/vis_type_tagcloud/pu const THRESHOLD = 0.65; const PIXEL_DIFF = 64; -describe('TagCloudVisualizationTest', function() { +describe('TagCloudVisualizationTest', function () { let domNode; let vis; let imageComparator; @@ -76,8 +76,8 @@ describe('TagCloudVisualizationTest', function() { beforeEach(ngMock.module('kibana')); - describe('TagCloudVisualization - basics', function() { - beforeEach(async function() { + describe('TagCloudVisualization - basics', function () { + beforeEach(async function () { const visType = new BaseVisType(createTagCloudVisTypeDefinition({ colors: seedColors })); setupDOM('512px', '512px'); imageComparator = new ImageComparator(); @@ -91,12 +91,12 @@ describe('TagCloudVisualizationTest', function() { }); }); - afterEach(function() { + afterEach(function () { teardownDOM(); imageComparator.destroy(); }); - it('simple draw', async function() { + it('simple draw', async function () { const tagcloudVisualization = new TagCloudVisualization(domNode, vis); await tagcloudVisualization.render(dummyTableGroup, vis.params, { @@ -118,7 +118,7 @@ describe('TagCloudVisualizationTest', function() { expect(mismatchedPixels).to.be.lessThan(PIXEL_DIFF); }); - it('with resize', async function() { + it('with resize', async function () { const tagcloudVisualization = new TagCloudVisualization(domNode, vis); await tagcloudVisualization.render(dummyTableGroup, vis.params, { resize: false, @@ -149,7 +149,7 @@ describe('TagCloudVisualizationTest', function() { expect(mismatchedPixels).to.be.lessThan(PIXEL_DIFF); }); - it('with param change', async function() { + it('with param change', async function () { const tagcloudVisualization = new TagCloudVisualization(domNode, vis); await tagcloudVisualization.render(dummyTableGroup, vis.params, { resize: false, diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js index 691318e32245b..6d6eb69e66792 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js @@ -139,7 +139,7 @@ describe('VegaVisualizations', () => { beforeEach(ngMock.module('kibana')); beforeEach( ngMock.inject(() => { - setInjectedVarFunc(injectedVar => { + setInjectedVarFunc((injectedVar) => { switch (injectedVar) { case 'mapConfig': return { @@ -186,7 +186,7 @@ describe('VegaVisualizations', () => { ); describe('VegaVisualization - basics', () => { - beforeEach(async function() { + beforeEach(async function () { setupDOM('512px', '512px'); imageComparator = new ImageComparator(); @@ -195,12 +195,12 @@ describe('VegaVisualizations', () => { }); }); - afterEach(function() { + afterEach(function () { teardownDOM(); imageComparator.destroy(); }); - it('should show vegalite graph and update on resize (may fail in dev env)', async function() { + it('should show vegalite graph and update on resize (may fail in dev env)', async function () { let vegaVis; try { vegaVis = new VegaVisualization(domNode, vis); @@ -223,7 +223,7 @@ describe('VegaVisualizations', () => { } }); - it('should show vega graph (may fail in dev env)', async function() { + it('should show vega graph (may fail in dev env)', async function () { let vegaVis; try { vegaVis = new VegaVisualization(domNode, vis); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/_vis_fixture.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/_vis_fixture.js index 8a542fec0639c..7a68e847f13b1 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/_vis_fixture.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/_vis_fixture.js @@ -42,15 +42,13 @@ const $visCanvas = $('
') let count = 0; const visHeight = $visCanvas.height(); -$visCanvas.new = function() { +$visCanvas.new = function () { count += 1; if (count > 1) $visCanvas.height(visHeight * count); - return $('
') - .addClass('visChart') - .appendTo($visCanvas); + return $('
').addClass('visChart').appendTo($visCanvas); }; -afterEach(function() { +afterEach(function () { $visCanvas.empty(); if (count > 1) $visCanvas.height(visHeight); count = 0; diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/chart_title.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/chart_title.js index 81fef155daf57..6790c49691dfd 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/chart_title.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/chart_title.js @@ -25,7 +25,7 @@ import { ChartTitle } from '../../../../../../../plugins/vis_type_vislib/public/ import { VisConfig } from '../../../../../../../plugins/vis_type_vislib/public/vislib/lib/vis_config'; import { getMockUiState } from '../../../../../../../plugins/vis_type_vislib/public/fixtures/mocks'; -describe('Vislib ChartTitle Class Test Suite', function() { +describe('Vislib ChartTitle Class Test Suite', function () { let mockUiState; let chartTitle; let el; @@ -90,15 +90,9 @@ describe('Vislib ChartTitle Class Test Suite', function() { beforeEach(() => { mockUiState = getMockUiState(); - el = d3 - .select('body') - .append('div') - .attr('class', 'visWrapper') - .datum(data); + el = d3.select('body').append('div').attr('class', 'visWrapper').datum(data); - el.append('div') - .attr('class', 'chart-title') - .style('height', '20px'); + el.append('div').attr('class', 'chart-title').style('height', '20px'); const visConfig = new VisConfig( { @@ -115,31 +109,26 @@ describe('Vislib ChartTitle Class Test Suite', function() { chartTitle = new ChartTitle(visConfig); }); - afterEach(function() { + afterEach(function () { el.remove(); }); - describe('render Method', function() { - beforeEach(function() { + describe('render Method', function () { + beforeEach(function () { chartTitle.render(); }); - it('should append an svg to div', function() { + it('should append an svg to div', function () { expect(el.select('.chart-title').selectAll('svg').length).to.be(1); }); - it('should append text', function() { - expect( - !!el - .select('.chart-title') - .selectAll('svg') - .selectAll('text') - ).to.be(true); + it('should append text', function () { + expect(!!el.select('.chart-title').selectAll('svg').selectAll('text')).to.be(true); }); }); - describe('draw Method', function() { - it('should be a function', function() { + describe('draw Method', function () { + it('should be a function', function () { expect(_.isFunction(chartTitle.draw())).to.be(true); }); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/dispatch.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/dispatch.js index eb4e109690c37..4f8cee2651a9f 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/dispatch.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/dispatch.js @@ -27,20 +27,16 @@ import data from '../../../../../../../plugins/vis_type_vislib/public/fixtures/m import { getMockUiState } from '../../../../../../../plugins/vis_type_vislib/public/fixtures/mocks'; import { getVis } from '../_vis_fixture'; -describe('Vislib Dispatch Class Test Suite', function() { +describe('Vislib Dispatch Class Test Suite', function () { function destroyVis(vis) { vis.destroy(); } function getEls(element, n, type) { - return d3 - .select(element) - .data(new Array(n)) - .enter() - .append(type); + return d3.select(element).data(new Array(n)).enter().append(type); } - describe('', function() { + describe('', function () { let vis; let mockUiState; @@ -50,14 +46,14 @@ describe('Vislib Dispatch Class Test Suite', function() { vis.render(data, mockUiState); }); - afterEach(function() { + afterEach(function () { destroyVis(vis); }); - it('implements on, off, emit methods', function() { + it('implements on, off, emit methods', function () { const events = _.pluck(vis.handler.charts, 'events'); expect(events.length).to.be.above(0); - events.forEach(function(dispatch) { + events.forEach(function (dispatch) { expect(dispatch).to.have.property('on'); expect(dispatch).to.have.property('off'); expect(dispatch).to.have.property('emit'); @@ -65,7 +61,7 @@ describe('Vislib Dispatch Class Test Suite', function() { }); }); - describe('Stock event handlers', function() { + describe('Stock event handlers', function () { let vis; let mockUiState; @@ -76,19 +72,19 @@ describe('Vislib Dispatch Class Test Suite', function() { vis.render(data, mockUiState); }); - afterEach(function() { + afterEach(function () { destroyVis(vis); }); - describe('addEvent method', function() { - it('returns a function that binds the passed event to a selection', function() { + describe('addEvent method', function () { + it('returns a function that binds the passed event to a selection', function () { const chart = _.first(vis.handler.charts); const apply = chart.events.addEvent('event', _.noop); expect(apply).to.be.a('function'); const els = getEls(vis.element, 3, 'div'); apply(els); - els.each(function() { + els.each(function () { expect(d3.select(this).on('event')).to.be(_.noop); }); }); @@ -97,21 +93,21 @@ describe('Vislib Dispatch Class Test Suite', function() { // test the addHoverEvent, addClickEvent methods by // checking that they return function which bind the events expected function checkBoundAddMethod(name, event) { - describe(name + ' method', function() { - it('should be a function', function() { - vis.handler.charts.forEach(function(chart) { + describe(name + ' method', function () { + it('should be a function', function () { + vis.handler.charts.forEach(function (chart) { expect(chart.events[name]).to.be.a('function'); }); }); - it('returns a function that binds ' + event + ' events to a selection', function() { + it('returns a function that binds ' + event + ' events to a selection', function () { const chart = _.first(vis.handler.charts); const apply = chart.events[name](chart.series[0].chartEl); expect(apply).to.be.a('function'); const els = getEls(vis.element, 3, 'div'); apply(els); - els.each(function() { + els.each(function () { expect(d3.select(this).on(event)).to.be.a('function'); }); }); @@ -122,9 +118,9 @@ describe('Vislib Dispatch Class Test Suite', function() { checkBoundAddMethod('addMouseoutEvent', 'mouseout'); checkBoundAddMethod('addClickEvent', 'click'); - describe('addMousePointer method', function() { - it('should be a function', function() { - vis.handler.charts.forEach(function(chart) { + describe('addMousePointer method', function () { + it('should be a function', function () { + vis.handler.charts.forEach(function (chart) { const pointer = chart.events.addMousePointer; expect(_.isFunction(pointer)).to.be(true); @@ -177,14 +173,14 @@ describe('Vislib Dispatch Class Test Suite', function() { }); }); - describe('Custom event handlers', function() { - it('should attach whatever gets passed on vis.on() to chart.events', function(done) { + describe('Custom event handlers', function () { + it('should attach whatever gets passed on vis.on() to chart.events', function (done) { const vis = getVis(); const mockUiState = getMockUiState(); vis.on('someEvent', _.noop); vis.render(data, mockUiState); - vis.handler.charts.forEach(function(chart) { + vis.handler.charts.forEach(function (chart) { expect(chart.events.listenerCount('someEvent')).to.be(1); }); @@ -192,13 +188,13 @@ describe('Vislib Dispatch Class Test Suite', function() { done(); }); - it('can be added after rendering', function() { + it('can be added after rendering', function () { const vis = getVis(); const mockUiState = getMockUiState(); vis.render(data, mockUiState); vis.on('someEvent', _.noop); - vis.handler.charts.forEach(function(chart) { + vis.handler.charts.forEach(function (chart) { expect(chart.events.listenerCount('someEvent')).to.be(1); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/handler/handler.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/handler/handler.js index 27f7f4ed3e073..e4f75c47e621c 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/handler/handler.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/handler/handler.js @@ -31,8 +31,8 @@ import { getVis } from '../../_vis_fixture'; const dateHistogramArray = [series, columns, rows, stackedSeries]; const names = ['series', 'columns', 'rows', 'stackedSeries']; -dateHistogramArray.forEach(function(data, i) { - describe('Vislib Handler Test Suite for ' + names[i] + ' Data', function() { +dateHistogramArray.forEach(function (data, i) { + describe('Vislib Handler Test Suite for ' + names[i] + ' Data', function () { const events = ['click', 'brush']; let vis; @@ -41,100 +41,100 @@ dateHistogramArray.forEach(function(data, i) { vis.render(data, getMockUiState()); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - describe('render Method', function() { - it('should render charts', function() { + describe('render Method', function () { + it('should render charts', function () { expect(vis.handler.charts.length).to.be.greaterThan(0); - vis.handler.charts.forEach(function(chart) { + vis.handler.charts.forEach(function (chart) { expect($(chart.chartEl).find('svg').length).to.be(1); }); }); }); - describe('enable Method', function() { + describe('enable Method', function () { let charts; - beforeEach(function() { + beforeEach(function () { charts = vis.handler.charts; - charts.forEach(function(chart) { - events.forEach(function(event) { + charts.forEach(function (chart) { + events.forEach(function (event) { vis.handler.enable(event, chart); }); }); }); - it('should add events to chart and emit to the Events class', function() { - charts.forEach(function(chart) { - events.forEach(function(event) { + it('should add events to chart and emit to the Events class', function () { + charts.forEach(function (chart) { + events.forEach(function (event) { expect(chart.events.listenerCount(event)).to.be.above(0); }); }); }); }); - describe('disable Method', function() { + describe('disable Method', function () { let charts; - beforeEach(function() { + beforeEach(function () { charts = vis.handler.charts; - charts.forEach(function(chart) { - events.forEach(function(event) { + charts.forEach(function (chart) { + events.forEach(function (event) { vis.handler.disable(event, chart); }); }); }); - it('should remove events from the chart', function() { - charts.forEach(function(chart) { - events.forEach(function(event) { + it('should remove events from the chart', function () { + charts.forEach(function (chart) { + events.forEach(function (event) { expect(chart.events.listenerCount(event)).to.be(0); }); }); }); }); - describe('removeAll Method', function() { - beforeEach(function() { + describe('removeAll Method', function () { + beforeEach(function () { vis.handler.removeAll(vis.element); }); - it('should remove all DOM elements from the el', function() { + it('should remove all DOM elements from the el', function () { expect($(vis.element).children().length).to.be(0); }); }); - describe('error Method', function() { - beforeEach(function() { + describe('error Method', function () { + beforeEach(function () { vis.handler.error('This is an error!'); }); - it('should return an error classed DOM element with a text message', function() { + it('should return an error classed DOM element with a text message', function () { expect($(vis.element).find('.error').length).to.be(1); expect($('.error h4').html()).to.be('This is an error!'); }); }); - describe('destroy Method', function() { - beforeEach(function() { + describe('destroy Method', function () { + beforeEach(function () { vis.handler.destroy(); }); - it('should destroy all the charts in the visualization', function() { + it('should destroy all the charts in the visualization', function () { expect(vis.handler.charts.length).to.be(0); }); }); - describe('event proxying', function() { - it('should only pass the original event object to downstream handlers', function(done) { + describe('event proxying', function () { + it('should only pass the original event object to downstream handlers', function (done) { const event = {}; const chart = vis.handler.charts[0]; - const mockEmitter = function() { + const mockEmitter = function () { const args = Array.from(arguments); expect(args.length).to.be(2); expect(args[0]).to.be('click'); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/layout/layout.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/layout/layout.js index 505b0a04c6183..7ad962fefc341 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/layout/layout.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/lib/layout/layout.js @@ -34,8 +34,8 @@ import { getVis } from '../../_vis_fixture'; const dateHistogramArray = [series, columns, rows, stackedSeries]; const names = ['series', 'columns', 'rows', 'stackedSeries']; -dateHistogramArray.forEach(function(data, i) { - describe('Vislib Layout Class Test Suite for ' + names[i] + ' Data', function() { +dateHistogramArray.forEach(function (data, i) { + describe('Vislib Layout Class Test Suite for ' + names[i] + ' Data', function () { let vis; let mockUiState; let numberOfCharts; @@ -52,8 +52,8 @@ dateHistogramArray.forEach(function(data, i) { vis.destroy(); }); - describe('createLayout Method', function() { - it('should append all the divs', function() { + describe('createLayout Method', function () { + it('should append all the divs', function () { expect($(vis.element).find('.visWrapper').length).to.be(1); expect($(vis.element).find('.visAxis--y').length).to.be(2); expect($(vis.element).find('.visWrapper__column').length).to.be(1); @@ -68,8 +68,8 @@ dateHistogramArray.forEach(function(data, i) { }); }); - describe('layout Method', function() { - beforeEach(function() { + describe('layout Method', function () { + beforeEach(function () { const visConfig = new VisConfig( { type: 'histogram', @@ -82,28 +82,24 @@ dateHistogramArray.forEach(function(data, i) { testLayout = new Layout(visConfig); }); - it('should append a div with the correct class name', function() { + it('should append a div with the correct class name', function () { expect($(vis.element).find('.chart').length).to.be(numberOfCharts); }); - it('should bind data to the DOM element', function() { - expect( - !!$(vis.element) - .find('.chart') - .data() - ).to.be(true); + it('should bind data to the DOM element', function () { + expect(!!$(vis.element).find('.chart').data()).to.be(true); }); - it('should create children', function() { + it('should create children', function () { expect(typeof $(vis.element).find('.x-axis-div')).to.be('object'); }); - it('should call split function when provided', function() { + it('should call split function when provided', function () { expect(typeof $(vis.element).find('.x-axis-div')).to.be('object'); }); - it('should throw errors when incorrect arguments provided', function() { - expect(function() { + it('should throw errors when incorrect arguments provided', function () { + expect(function () { testLayout.layout({ parent: vis.element, type: undefined, @@ -111,24 +107,24 @@ dateHistogramArray.forEach(function(data, i) { }); }).to.throwError(); - expect(function() { + expect(function () { testLayout.layout({ type: 'div', class: 'chart', }); }).to.throwError(); - expect(function() { + expect(function () { testLayout.layout({ parent: 'histogram', type: 'div', }); }).to.throwError(); - expect(function() { + expect(function () { testLayout.layout({ parent: vis.element, - type: function(d) { + type: function (d) { return d; }, class: 'chart', @@ -137,27 +133,25 @@ dateHistogramArray.forEach(function(data, i) { }); }); - describe('appendElem Method', function() { - beforeEach(function() { + describe('appendElem Method', function () { + beforeEach(function () { vis.handler.layout.appendElem(vis.element, 'svg', 'column'); vis.handler.layout.appendElem('.visChart', 'div', 'test'); }); - it('should append DOM element to el with a class name', function() { + it('should append DOM element to el with a class name', function () { expect(typeof $(vis.element).find('.column')).to.be('object'); expect(typeof $(vis.element).find('.test')).to.be('object'); }); }); - describe('removeAll Method', function() { - beforeEach(function() { - d3.select(vis.element) - .append('div') - .attr('class', 'visualize'); + describe('removeAll Method', function () { + beforeEach(function () { + d3.select(vis.element).append('div').attr('class', 'visualize'); vis.handler.layout.removeAll(vis.element); }); - it('should remove all DOM elements from the el', function() { + it('should remove all DOM elements from the el', function () { expect($(vis.element).children().length).to.be(0); }); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/vis.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/vis.js index 67f29ee96a336..36decdc415ed8 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/vis.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/vis.js @@ -31,8 +31,8 @@ import { getVis } from './_vis_fixture'; const dataArray = [series, columns, rows, stackedSeries]; const names = ['series', 'columns', 'rows', 'stackedSeries']; -dataArray.forEach(function(data, i) { - describe('Vislib Vis Test Suite for ' + names[i] + ' Data', function() { +dataArray.forEach(function (data, i) { + describe('Vislib Vis Test Suite for ' + names[i] + ' Data', function () { const beforeEvent = 'click'; const afterEvent = 'brush'; let vis; @@ -46,31 +46,31 @@ dataArray.forEach(function(data, i) { mockUiState = getMockUiState(); }); - afterEach(function() { + afterEach(function () { vis.destroy(); secondVis.destroy(); }); - describe('render Method', function() { - beforeEach(function() { + describe('render Method', function () { + beforeEach(function () { vis.render(data, mockUiState); numberOfCharts = vis.handler.charts.length; }); - it('should bind data to this object', function() { + it('should bind data to this object', function () { expect(_.isObject(vis.data)).to.be(true); }); - it('should instantiate a handler object', function() { + it('should instantiate a handler object', function () { expect(_.isObject(vis.handler)).to.be(true); }); - it('should append a chart', function() { + it('should append a chart', function () { expect($('.chart').length).to.be(numberOfCharts); }); - it('should throw an error if no data is provided', function() { - expect(function() { + it('should throw an error if no data is provided', function () { + expect(function () { vis.render(null, mockUiState); }).to.throwError(); }); @@ -82,55 +82,55 @@ dataArray.forEach(function(data, i) { }); }); - describe('destroy Method', function() { - beforeEach(function() { + describe('destroy Method', function () { + beforeEach(function () { vis.render(data, mockUiState); secondVis.render(data, mockUiState); secondVis.destroy(); }); - it('should remove all DOM elements from el', function() { + it('should remove all DOM elements from el', function () { expect($(secondVis.el).find('.visWrapper').length).to.be(0); }); - it('should not remove visualizations that have not been destroyed', function() { + it('should not remove visualizations that have not been destroyed', function () { expect($(vis.element).find('.visWrapper').length).to.be(1); }); }); - describe('set Method', function() { - beforeEach(function() { + describe('set Method', function () { + beforeEach(function () { vis.render(data, mockUiState); vis.set('addLegend', false); vis.set('offset', 'wiggle'); }); - it('should set an attribute', function() { + it('should set an attribute', function () { expect(vis.get('addLegend')).to.be(false); expect(vis.get('offset')).to.be('wiggle'); }); }); - describe('get Method', function() { - beforeEach(function() { + describe('get Method', function () { + beforeEach(function () { vis.render(data, mockUiState); }); - it('should get attribute values', function() { + it('should get attribute values', function () { expect(vis.get('addLegend')).to.be(true); expect(vis.get('addTooltip')).to.be(true); expect(vis.get('type')).to.be('point_series'); }); }); - describe('on Method', function() { + describe('on Method', function () { let listeners; - beforeEach(function() { - listeners = [function() {}, function() {}]; + beforeEach(function () { + listeners = [function () {}, function () {}]; // Add event and listeners to chart - listeners.forEach(function(listener) { + listeners.forEach(function (listener) { vis.on(beforeEvent, listener); }); @@ -138,50 +138,50 @@ dataArray.forEach(function(data, i) { vis.render(data, mockUiState); // Add event after charts have rendered - listeners.forEach(function(listener) { + listeners.forEach(function (listener) { vis.on(afterEvent, listener); }); }); - afterEach(function() { + afterEach(function () { vis.removeAllListeners(beforeEvent); vis.removeAllListeners(afterEvent); }); - it('should add an event and its listeners', function() { - listeners.forEach(function(listener) { + it('should add an event and its listeners', function () { + listeners.forEach(function (listener) { expect(vis.listeners(beforeEvent)).to.contain(listener); }); - listeners.forEach(function(listener) { + listeners.forEach(function (listener) { expect(vis.listeners(afterEvent)).to.contain(listener); }); }); - it('should cause a listener for each event to be attached to each chart', function() { + it('should cause a listener for each event to be attached to each chart', function () { const charts = vis.handler.charts; - charts.forEach(function(chart) { + charts.forEach(function (chart) { expect(chart.events.listenerCount(beforeEvent)).to.be.above(0); expect(chart.events.listenerCount(afterEvent)).to.be.above(0); }); }); }); - describe('off Method', function() { + describe('off Method', function () { let listeners; let listener1; let listener2; - beforeEach(function() { + beforeEach(function () { listeners = []; - listener1 = function() {}; - listener2 = function() {}; + listener1 = function () {}; + listener2 = function () {}; listeners.push(listener1); listeners.push(listener2); // Add event and listeners to chart - listeners.forEach(function(listener) { + listeners.forEach(function (listener) { vis.on(beforeEvent, listener); }); @@ -192,7 +192,7 @@ dataArray.forEach(function(data, i) { vis.render(data, mockUiState); // Add event after charts have rendered - listeners.forEach(function(listener) { + listeners.forEach(function (listener) { vis.on(afterEvent, listener); }); @@ -200,12 +200,12 @@ dataArray.forEach(function(data, i) { vis.off(afterEvent, listener1); }); - afterEach(function() { + afterEach(function () { vis.removeAllListeners(beforeEvent); vis.removeAllListeners(afterEvent); }); - it('should remove a listener', function() { + it('should remove a listener', function () { const charts = vis.handler.charts; expect(vis.listeners(beforeEvent)).to.not.contain(listener1); @@ -215,13 +215,13 @@ dataArray.forEach(function(data, i) { expect(vis.listeners(afterEvent)).to.contain(listener2); // Events should still be attached to charts - charts.forEach(function(chart) { + charts.forEach(function (chart) { expect(chart.events.listenerCount(beforeEvent)).to.be.above(0); expect(chart.events.listenerCount(afterEvent)).to.be.above(0); }); }); - it('should remove the event and all listeners when only event passed an argument', function() { + it('should remove the event and all listeners when only event passed an argument', function () { const charts = vis.handler.charts; vis.removeAllListeners(afterEvent); @@ -230,19 +230,19 @@ dataArray.forEach(function(data, i) { expect(vis.listeners(afterEvent)).to.not.contain(listener2); // should remove the event from the charts - charts.forEach(function(chart) { + charts.forEach(function (chart) { expect(chart.events.listenerCount(beforeEvent)).to.be.above(0); expect(chart.events.listenerCount(afterEvent)).to.be(0); }); }); - it('should remove the event from the chart when the last listener is removed', function() { + it('should remove the event from the chart when the last listener is removed', function () { const charts = vis.handler.charts; vis.off(afterEvent, listener2); expect(vis.listenerCount(afterEvent)).to.be(0); - charts.forEach(function(chart) { + charts.forEach(function (chart) { expect(chart.events.listenerCount(afterEvent)).to.be(0); }); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/area_chart.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/area_chart.js index eb529c380cdda..fd2240c0c64c5 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/area_chart.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/area_chart.js @@ -41,8 +41,8 @@ const visLibParams = { mode: 'stacked', }; -_.forOwn(dataTypesArray, function(dataType, dataTypeName) { - describe('Vislib Area Chart Test Suite for ' + dataTypeName + ' Data', function() { +_.forOwn(dataTypesArray, function (dataType, dataTypeName) { + describe('Vislib Area Chart Test Suite for ' + dataTypeName + ' Data', function () { let vis; let mockUiState; @@ -53,46 +53,46 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { vis.render(dataType, mockUiState); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - describe('stackData method', function() { + describe('stackData method', function () { let stackedData; let isStacked; - beforeEach(function() { - vis.handler.charts.forEach(function(chart) { + beforeEach(function () { + vis.handler.charts.forEach(function (chart) { stackedData = chart.chartData; - isStacked = stackedData.series.every(function(arr) { - return arr.values.every(function(d) { + isStacked = stackedData.series.every(function (arr) { + return arr.values.every(function (d) { return _.isNumber(d.y0); }); }); }); }); - it('should append a d.y0 key to the data object', function() { + it('should append a d.y0 key to the data object', function () { expect(isStacked).to.be(true); }); }); - describe('addPath method', function() { - it('should append a area paths', function() { - vis.handler.charts.forEach(function(chart) { + describe('addPath method', function () { + it('should append a area paths', function () { + vis.handler.charts.forEach(function (chart) { expect($(chart.chartEl).find('path').length).to.be.greaterThan(0); }); }); }); - describe('addPathEvents method', function() { + describe('addPathEvents method', function () { let path; let d3selectedPath; let onMouseOver; - beforeEach(function() { - vis.handler.charts.forEach(function(chart) { + beforeEach(function () { + vis.handler.charts.forEach(function (chart) { path = $(chart.chartEl).find('path')[0]; d3selectedPath = d3.select(path)[0][0]; @@ -101,14 +101,14 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { }); }); - it('should attach a hover event', function() { - vis.handler.charts.forEach(function() { + it('should attach a hover event', function () { + vis.handler.charts.forEach(function () { expect(onMouseOver).to.be(true); }); }); }); - describe('addCircleEvents method', function() { + describe('addCircleEvents method', function () { let circle; let brush; let d3selectedCircle; @@ -117,7 +117,7 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { let onMouseOver; beforeEach(() => { - vis.handler.charts.forEach(function(chart) { + vis.handler.charts.forEach(function (chart) { circle = $(chart.chartEl).find('circle')[0]; brush = $(chart.chartEl).find('.brush'); d3selectedCircle = d3.select(circle)[0][0]; @@ -134,40 +134,40 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { // listeners, however, I was not able to test for the listener // function being present. I will need to update this test // in the future. - it('should attach a brush g element', function() { - vis.handler.charts.forEach(function() { + it('should attach a brush g element', function () { + vis.handler.charts.forEach(function () { expect(onBrush).to.be(true); }); }); - it('should attach a click event', function() { - vis.handler.charts.forEach(function() { + it('should attach a click event', function () { + vis.handler.charts.forEach(function () { expect(onClick).to.be(true); }); }); - it('should attach a hover event', function() { - vis.handler.charts.forEach(function() { + it('should attach a hover event', function () { + vis.handler.charts.forEach(function () { expect(onMouseOver).to.be(true); }); }); }); - describe('addCircles method', function() { - it('should append circles', function() { - vis.handler.charts.forEach(function(chart) { + describe('addCircles method', function () { + it('should append circles', function () { + vis.handler.charts.forEach(function (chart) { expect($(chart.chartEl).find('circle').length).to.be.greaterThan(0); }); }); - it('should not draw circles where d.y === 0', function() { - vis.handler.charts.forEach(function(chart) { + it('should not draw circles where d.y === 0', function () { + vis.handler.charts.forEach(function (chart) { const series = chart.chartData.series; - const isZero = series.some(function(d) { + const isZero = series.some(function (d) { return d.y === 0; }); const circles = $.makeArray($(chart.chartEl).find('circle')); - const isNotDrawn = circles.some(function(d) { + const isNotDrawn = circles.some(function (d) { return d.__data__.y === 0; }); @@ -178,15 +178,15 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { }); }); - describe('draw method', function() { - it('should return a function', function() { - vis.handler.charts.forEach(function(chart) { + describe('draw method', function () { + it('should return a function', function () { + vis.handler.charts.forEach(function (chart) { expect(_.isFunction(chart.draw())).to.be(true); }); }); - it('should return a yMin and yMax', function() { - vis.handler.charts.forEach(function(chart) { + it('should return a yMin and yMax', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const domain = yAxis.getScale().domain(); @@ -195,8 +195,8 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { }); }); - it('should render a zero axis line', function() { - vis.handler.charts.forEach(function(chart) { + it('should render a zero axis line', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; if (yAxis.yMin < 0 && yAxis.yMax > 0) { @@ -206,14 +206,14 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { }); }); - describe('defaultYExtents is true', function() { - beforeEach(function() { + describe('defaultYExtents is true', function () { + beforeEach(function () { vis.visConfigArgs.defaultYExtents = true; vis.render(dataType, mockUiState); }); - it('should return yAxis extents equal to data extents', function() { - vis.handler.charts.forEach(function(chart) { + it('should return yAxis extents equal to data extents', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const min = vis.handler.valueAxes[0].axisScale.getYMin(); const max = vis.handler.valueAxes[0].axisScale.getYMax(); @@ -223,16 +223,16 @@ _.forOwn(dataTypesArray, function(dataType, dataTypeName) { }); }); }); - [0, 2, 4, 8].forEach(function(boundsMarginValue) { - describe('defaultYExtents is true and boundsMargin is defined', function() { - beforeEach(function() { + [0, 2, 4, 8].forEach(function (boundsMarginValue) { + describe('defaultYExtents is true and boundsMargin is defined', function () { + beforeEach(function () { vis.visConfigArgs.defaultYExtents = true; vis.visConfigArgs.boundsMargin = boundsMarginValue; vis.render(dataType, mockUiState); }); - it('should return yAxis extents equal to data extents with boundsMargin', function() { - vis.handler.charts.forEach(function(chart) { + it('should return yAxis extents equal to data extents with boundsMargin', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const min = vis.handler.valueAxes[0].axisScale.getYMin(); const max = vis.handler.valueAxes[0].axisScale.getYMax(); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/chart.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/chart.js index 4c5e3db316243..2b41ce5d1a5c6 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/chart.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/chart.js @@ -24,7 +24,7 @@ import { Chart } from '../../../../../../../plugins/vis_type_vislib/public/visli import { getMockUiState } from '../../../../../../../plugins/vis_type_vislib/public/fixtures/mocks'; import { getVis } from '../_vis_fixture'; -describe('Vislib _chart Test Suite', function() { +describe('Vislib _chart Test Suite', function () { let vis; let el; let myChart; @@ -96,10 +96,10 @@ describe('Vislib _chart Test Suite', function() { ], }, ], - tooltipFormatter: function(datapoint) { + tooltipFormatter: function (datapoint) { return datapoint; }, - xAxisFormatter: function(thing) { + xAxisFormatter: function (thing) { return thing; }, xAxisLabel: 'Date Histogram', @@ -107,10 +107,7 @@ describe('Vislib _chart Test Suite', function() { }; beforeEach(() => { - el = d3 - .select('body') - .append('div') - .attr('class', 'column-chart'); + el = d3.select('body').append('div').attr('class', 'column-chart'); config = { type: 'histogram', @@ -125,16 +122,16 @@ describe('Vislib _chart Test Suite', function() { myChart = vis.handler.charts[0]; }); - afterEach(function() { + afterEach(function () { el.remove(); vis.destroy(); }); - it('should be a constructor for visualization modules', function() { + it('should be a constructor for visualization modules', function () { expect(myChart instanceof Chart).to.be(true); }); - it('should have a render method', function() { + it('should have a render method', function () { expect(typeof myChart.render === 'function').to.be(true); }); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/column_chart.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/column_chart.js index 5cbd5948bc477..f075dff466793 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/column_chart.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/column_chart.js @@ -46,12 +46,12 @@ const dataTypesArray = [ ['stackedSeries', 'stacked', stackedSeries], ]; -dataTypesArray.forEach(function(dataType) { +dataTypesArray.forEach(function (dataType) { const name = dataType[0]; const mode = dataType[1]; const data = dataType[2]; - describe('Vislib Column Chart Test Suite for ' + name + ' Data', function() { + describe('Vislib Column Chart Test Suite for ' + name + ' Data', function () { let vis; let mockUiState; const visLibParams = { @@ -73,46 +73,46 @@ dataTypesArray.forEach(function(dataType) { vis.render(data, mockUiState); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - describe('stackData method', function() { + describe('stackData method', function () { let stackedData; let isStacked; - beforeEach(function() { - vis.handler.charts.forEach(function(chart) { + beforeEach(function () { + vis.handler.charts.forEach(function (chart) { stackedData = chart.chartData; - isStacked = stackedData.series.every(function(arr) { - return arr.values.every(function(d) { + isStacked = stackedData.series.every(function (arr) { + return arr.values.every(function (d) { return _.isNumber(d.y0); }); }); }); }); - it('should stack values when mode is stacked', function() { + it('should stack values when mode is stacked', function () { if (mode === 'stacked') { expect(isStacked).to.be(true); } }); - it('should stack values when mode is percentage', function() { + it('should stack values when mode is percentage', function () { if (mode === 'percentage') { expect(isStacked).to.be(true); } }); }); - describe('addBars method', function() { - it('should append rects', function() { + describe('addBars method', function () { + it('should append rects', function () { let numOfSeries; let numOfValues; let product; - vis.handler.charts.forEach(function(chart) { + vis.handler.charts.forEach(function (chart) { numOfSeries = chart.chartData.series.length; numOfValues = chart.chartData.series[0].values.length; product = numOfSeries * numOfValues; @@ -121,11 +121,9 @@ dataTypesArray.forEach(function(dataType) { }); }); - describe('addBarEvents method', function() { + describe('addBarEvents method', function () { function checkChart(chart) { - const rect = $(chart.chartEl) - .find('.series rect') - .get(0); + const rect = $(chart.chartEl).find('.series rect').get(0); // check for existence of stuff and things return { @@ -140,8 +138,8 @@ dataTypesArray.forEach(function(dataType) { }; } - it('should attach the brush if data is a set is ordered', function() { - vis.handler.charts.forEach(function(chart) { + it('should attach the brush if data is a set is ordered', function () { + vis.handler.charts.forEach(function (chart) { const has = checkChart(chart); const ordered = vis.handler.data.get('ordered'); const allowBrushing = Boolean(ordered); @@ -149,30 +147,30 @@ dataTypesArray.forEach(function(dataType) { }); }); - it('should attach a click event', function() { - vis.handler.charts.forEach(function(chart) { + it('should attach a click event', function () { + vis.handler.charts.forEach(function (chart) { const has = checkChart(chart); expect(has.click).to.be(true); }); }); - it('should attach a hover event', function() { - vis.handler.charts.forEach(function(chart) { + it('should attach a hover event', function () { + vis.handler.charts.forEach(function (chart) { const has = checkChart(chart); expect(has.mouseOver).to.be(true); }); }); }); - describe('draw method', function() { - it('should return a function', function() { - vis.handler.charts.forEach(function(chart) { + describe('draw method', function () { + it('should return a function', function () { + vis.handler.charts.forEach(function (chart) { expect(_.isFunction(chart.draw())).to.be(true); }); }); - it('should return a yMin and yMax', function() { - vis.handler.charts.forEach(function(chart) { + it('should return a yMin and yMax', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const domain = yAxis.getScale().domain(); @@ -181,8 +179,8 @@ dataTypesArray.forEach(function(dataType) { }); }); - it('should render a zero axis line', function() { - vis.handler.charts.forEach(function(chart) { + it('should render a zero axis line', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; if (yAxis.yMin < 0 && yAxis.yMax > 0) { @@ -192,14 +190,14 @@ dataTypesArray.forEach(function(dataType) { }); }); - describe('defaultYExtents is true', function() { - beforeEach(function() { + describe('defaultYExtents is true', function () { + beforeEach(function () { vis.visConfigArgs.defaultYExtents = true; vis.render(data, mockUiState); }); - it('should return yAxis extents equal to data extents', function() { - vis.handler.charts.forEach(function(chart) { + it('should return yAxis extents equal to data extents', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const min = vis.handler.valueAxes[0].axisScale.getYMin(); const max = vis.handler.valueAxes[0].axisScale.getYMax(); @@ -209,16 +207,16 @@ dataTypesArray.forEach(function(dataType) { }); }); }); - [0, 2, 4, 8].forEach(function(boundsMarginValue) { - describe('defaultYExtents is true and boundsMargin is defined', function() { - beforeEach(function() { + [0, 2, 4, 8].forEach(function (boundsMarginValue) { + describe('defaultYExtents is true and boundsMargin is defined', function () { + beforeEach(function () { vis.visConfigArgs.defaultYExtents = true; vis.visConfigArgs.boundsMargin = boundsMarginValue; vis.render(data, mockUiState); }); - it('should return yAxis extents equal to data extents with boundsMargin', function() { - vis.handler.charts.forEach(function(chart) { + it('should return yAxis extents equal to data extents with boundsMargin', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const min = vis.handler.valueAxes[0].axisScale.getYMin(); const max = vis.handler.valueAxes[0].axisScale.getYMax(); @@ -240,7 +238,7 @@ dataTypesArray.forEach(function(dataType) { }); }); -describe('stackData method - data set with zeros in percentage mode', function() { +describe('stackData method - data set with zeros in percentage mode', function () { let vis; let mockUiState; const visLibParams = { @@ -257,11 +255,11 @@ describe('stackData method - data set with zeros in percentage mode', function() vis.on('brush', _.noop); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - it('should not mutate the injected zeros', function() { + it('should not mutate the injected zeros', function () { vis.render(seriesMonthlyInterval, mockUiState); expect(vis.handler.charts).to.have.length(1); @@ -274,7 +272,7 @@ describe('stackData method - data set with zeros in percentage mode', function() expect(point.y).to.be(0); }); - it('should not mutate zeros that exist in the data', function() { + it('should not mutate zeros that exist in the data', function () { vis.render(rowsWithZeros, mockUiState); expect(vis.handler.charts).to.have.length(2); @@ -287,7 +285,7 @@ describe('stackData method - data set with zeros in percentage mode', function() }); }); -describe('datumWidth - split chart data set with holes', function() { +describe('datumWidth - split chart data set with holes', function () { let vis; let mockUiState; const visLibParams = { @@ -305,23 +303,23 @@ describe('datumWidth - split chart data set with holes', function() { vis.render(rowsSeriesWithHoles, mockUiState); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - it('should not have bar widths that span multiple time bins', function() { + it('should not have bar widths that span multiple time bins', function () { expect(vis.handler.charts.length).to.equal(1); const chart = vis.handler.charts[0]; const rects = $(chart.chartEl).find('.series rect'); const MAX_WIDTH_IN_PIXELS = 27; - rects.each(function() { + rects.each(function () { const width = $(this).attr('width'); expect(width).to.be.lessThan(MAX_WIDTH_IN_PIXELS); }); }); }); -describe('datumWidth - monthly interval', function() { +describe('datumWidth - monthly interval', function () { let vis; let mockUiState; const visLibParams = { @@ -339,11 +337,11 @@ describe('datumWidth - monthly interval', function() { vis.render(seriesMonthlyInterval, mockUiState); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - it('should vary bar width when date histogram intervals are not equal', function() { + it('should vary bar width when date histogram intervals are not equal', function () { expect(vis.handler.charts.length).to.equal(1); const chart = vis.handler.charts[0]; const rects = $(chart.chartEl).find('.series rect'); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/gauge_chart.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/gauge_chart.js index d8ce8f1f5f44b..7c588800ae659 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/gauge_chart.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/gauge_chart.js @@ -25,7 +25,7 @@ import data from '../../../../../../../plugins/vis_type_vislib/public/fixtures/m import { getMockUiState } from '../../../../../../../plugins/vis_type_vislib/public/fixtures/mocks'; import { getVis } from '../_vis_fixture'; -describe('Vislib Gauge Chart Test Suite', function() { +describe('Vislib Gauge Chart Test Suite', function () { let vis; let chartEl; const visLibParams = { @@ -86,21 +86,17 @@ describe('Vislib Gauge Chart Test Suite', function() { generateVis(); }); - afterEach(function() { + afterEach(function () { vis.destroy(); $('.visChart').remove(); }); - it('creates meter gauge', function() { + it('creates meter gauge', function () { expect($(chartEl).find('svg').length).to.equal(5); - expect( - $(chartEl) - .find('svg > g > g > text') - .text() - ).to.equal('2820231918357341352'); + expect($(chartEl).find('svg > g > g > text').text()).to.equal('2820231918357341352'); }); - it('creates circle gauge', function() { + it('creates circle gauge', function () { generateVis({ gauge: { minAngle: 0, @@ -110,36 +106,28 @@ describe('Vislib Gauge Chart Test Suite', function() { expect($(chartEl).find('svg').length).to.equal(5); }); - it('creates gauge with automatic mode', function() { + it('creates gauge with automatic mode', function () { generateVis({ gauge: { alignment: 'automatic', }, }); - expect( - $(chartEl) - .find('svg') - .width() - ).to.equal(197); + expect($(chartEl).find('svg').width()).to.equal(197); }); - it('creates gauge with vertical mode', function() { + it('creates gauge with vertical mode', function () { generateVis({ gauge: { alignment: 'vertical', }, }); - expect( - $(chartEl) - .find('svg') - .width() - ).to.equal($(chartEl).width()); + expect($(chartEl).find('svg').width()).to.equal($(chartEl).width()); }); - it('applies range settings correctly', function() { + it('applies range settings correctly', function () { const paths = $(chartEl).find('svg > g > g:nth-child(1) > path:nth-child(2)'); const fills = []; - paths.each(function() { + paths.each(function () { fills.push(this.style.fill); }); expect(fills).to.eql([ @@ -151,7 +139,7 @@ describe('Vislib Gauge Chart Test Suite', function() { ]); }); - it('applies color schema correctly', function() { + it('applies color schema correctly', function () { generateVis({ gauge: { colorSchema: 'Blues', @@ -159,7 +147,7 @@ describe('Vislib Gauge Chart Test Suite', function() { }); const paths = $(chartEl).find('svg > g > g:nth-child(1) > path:nth-child(2)'); const fills = []; - paths.each(function() { + paths.each(function () { fills.push(this.style.fill); }); expect(fills).to.eql([ diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/heatmap_chart.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/heatmap_chart.js index 765b9118e6844..9fa51fb59ed48 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/heatmap_chart.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/heatmap_chart.js @@ -40,12 +40,12 @@ const dataTypesArray = [ ['stackedSeries', stackedSeries], ]; -describe('Vislib Heatmap Chart Test Suite', function() { - dataTypesArray.forEach(function(dataType) { +describe('Vislib Heatmap Chart Test Suite', function () { + dataTypesArray.forEach(function (dataType) { const name = dataType[0]; const data = dataType[1]; - describe('for ' + name + ' Data', function() { + describe('for ' + name + ' Data', function () { let vis; let mockUiState; const visLibParams = { @@ -72,12 +72,12 @@ describe('Vislib Heatmap Chart Test Suite', function() { generateVis(); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); it('category axes should be rendered in reverse order', () => { - const renderedCategoryAxes = vis.handler.renderArray.filter(item => { + const renderedCategoryAxes = vis.handler.renderArray.filter((item) => { return ( item.constructor && item.constructor.name === 'Axis' && @@ -93,9 +93,9 @@ describe('Vislib Heatmap Chart Test Suite', function() { ); }); - describe('addSquares method', function() { - it('should append rects', function() { - vis.handler.charts.forEach(function(chart) { + describe('addSquares method', function () { + it('should append rects', function () { + vis.handler.charts.forEach(function (chart) { const numOfRects = chart.chartData.series.reduce((result, series) => { return result + series.values.length; }, 0); @@ -104,11 +104,9 @@ describe('Vislib Heatmap Chart Test Suite', function() { }); }); - describe('addBarEvents method', function() { + describe('addBarEvents method', function () { function checkChart(chart) { - const rect = $(chart.chartEl) - .find('.series rect') - .get(0); + const rect = $(chart.chartEl).find('.series rect').get(0); return { click: !!rect.__onclick, @@ -122,8 +120,8 @@ describe('Vislib Heatmap Chart Test Suite', function() { }; } - it('should attach the brush if data is a set of ordered dates', function() { - vis.handler.charts.forEach(function(chart) { + it('should attach the brush if data is a set of ordered dates', function () { + vis.handler.charts.forEach(function (chart) { const has = checkChart(chart); const ordered = vis.handler.data.get('ordered'); const date = Boolean(ordered && ordered.date); @@ -131,30 +129,30 @@ describe('Vislib Heatmap Chart Test Suite', function() { }); }); - it('should attach a click event', function() { - vis.handler.charts.forEach(function(chart) { + it('should attach a click event', function () { + vis.handler.charts.forEach(function (chart) { const has = checkChart(chart); expect(has.click).to.be(true); }); }); - it('should attach a hover event', function() { - vis.handler.charts.forEach(function(chart) { + it('should attach a hover event', function () { + vis.handler.charts.forEach(function (chart) { const has = checkChart(chart); expect(has.mouseOver).to.be(true); }); }); }); - describe('draw method', function() { - it('should return a function', function() { - vis.handler.charts.forEach(function(chart) { + describe('draw method', function () { + it('should return a function', function () { + vis.handler.charts.forEach(function (chart) { expect(_.isFunction(chart.draw())).to.be(true); }); }); - it('should return a yMin and yMax', function() { - vis.handler.charts.forEach(function(chart) { + it('should return a yMin and yMax', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const domain = yAxis.getScale().domain(); @@ -164,11 +162,11 @@ describe('Vislib Heatmap Chart Test Suite', function() { }); }); - it('should define default colors', function() { + it('should define default colors', function () { expect(mockUiState.get('vis.defaultColors')).to.not.be(undefined); }); - it('should set custom range', function() { + it('should set custom range', function () { vis.destroy(); generateVis({ setColorRange: true, @@ -186,7 +184,7 @@ describe('Vislib Heatmap Chart Test Suite', function() { expect(labels[3]).to.be('500 - Infinity'); }); - it('should show correct Y axis title', function() { + it('should show correct Y axis title', function () { expect(vis.handler.categoryAxes[1].axisConfig.get('title.text')).to.equal(''); }); }); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/line_chart.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/line_chart.js index 691417e968eed..dae92c831cd8d 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/line_chart.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/line_chart.js @@ -41,12 +41,12 @@ const dataTypes = [ ['term series', termSeries], ]; -describe('Vislib Line Chart', function() { - dataTypes.forEach(function(type) { +describe('Vislib Line Chart', function () { + dataTypes.forEach(function (type) { const name = type[0]; const data = type[1]; - describe(name + ' Data', function() { + describe(name + ' Data', function () { let vis; let mockUiState; @@ -64,11 +64,11 @@ describe('Vislib Line Chart', function() { vis.on('brush', _.noop); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - describe('addCircleEvents method', function() { + describe('addCircleEvents method', function () { let circle; let brush; let d3selectedCircle; @@ -76,8 +76,8 @@ describe('Vislib Line Chart', function() { let onClick; let onMouseOver; - beforeEach(function() { - vis.handler.charts.forEach(function(chart) { + beforeEach(function () { + vis.handler.charts.forEach(function (chart) { circle = $(chart.chartEl).find('.circle')[0]; brush = $(chart.chartEl).find('.brush'); d3selectedCircle = d3.select(circle)[0][0]; @@ -94,36 +94,36 @@ describe('Vislib Line Chart', function() { // listeners, however, I was not able to test for the listener // function being present. I will need to update this test // in the future. - it('should attach a brush g element', function() { - vis.handler.charts.forEach(function() { + it('should attach a brush g element', function () { + vis.handler.charts.forEach(function () { expect(onBrush).to.be(true); }); }); - it('should attach a click event', function() { - vis.handler.charts.forEach(function() { + it('should attach a click event', function () { + vis.handler.charts.forEach(function () { expect(onClick).to.be(true); }); }); - it('should attach a hover event', function() { - vis.handler.charts.forEach(function() { + it('should attach a hover event', function () { + vis.handler.charts.forEach(function () { expect(onMouseOver).to.be(true); }); }); }); - describe('addCircles method', function() { - it('should append circles', function() { - vis.handler.charts.forEach(function(chart) { + describe('addCircles method', function () { + it('should append circles', function () { + vis.handler.charts.forEach(function (chart) { expect($(chart.chartEl).find('circle').length).to.be.greaterThan(0); }); }); }); - describe('addLines method', function() { - it('should append a paths', function() { - vis.handler.charts.forEach(function(chart) { + describe('addLines method', function () { + it('should append a paths', function () { + vis.handler.charts.forEach(function (chart) { expect($(chart.chartEl).find('path').length).to.be.greaterThan(0); }); }); @@ -139,15 +139,15 @@ describe('Vislib Line Chart', function() { // }); //}); - describe('draw method', function() { - it('should return a function', function() { - vis.handler.charts.forEach(function(chart) { + describe('draw method', function () { + it('should return a function', function () { + vis.handler.charts.forEach(function (chart) { expect(chart.draw()).to.be.a(Function); }); }); - it('should return a yMin and yMax', function() { - vis.handler.charts.forEach(function(chart) { + it('should return a yMin and yMax', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const domain = yAxis.getScale().domain(); expect(domain[0]).to.not.be(undefined); @@ -155,8 +155,8 @@ describe('Vislib Line Chart', function() { }); }); - it('should render a zero axis line', function() { - vis.handler.charts.forEach(function(chart) { + it('should render a zero axis line', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; if (yAxis.yMin < 0 && yAxis.yMax > 0) { @@ -166,14 +166,14 @@ describe('Vislib Line Chart', function() { }); }); - describe('defaultYExtents is true', function() { - beforeEach(function() { + describe('defaultYExtents is true', function () { + beforeEach(function () { vis.visConfigArgs.defaultYExtents = true; vis.render(data, mockUiState); }); - it('should return yAxis extents equal to data extents', function() { - vis.handler.charts.forEach(function(chart) { + it('should return yAxis extents equal to data extents', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const min = vis.handler.valueAxes[0].axisScale.getYMin(); const max = vis.handler.valueAxes[0].axisScale.getYMax(); @@ -183,16 +183,16 @@ describe('Vislib Line Chart', function() { }); }); }); - [0, 2, 4, 8].forEach(function(boundsMarginValue) { - describe('defaultYExtents is true and boundsMargin is defined', function() { - beforeEach(function() { + [0, 2, 4, 8].forEach(function (boundsMarginValue) { + describe('defaultYExtents is true and boundsMargin is defined', function () { + beforeEach(function () { vis.visConfigArgs.defaultYExtents = true; vis.visConfigArgs.boundsMargin = boundsMarginValue; vis.render(data, mockUiState); }); - it('should return yAxis extents equal to data extents with boundsMargin', function() { - vis.handler.charts.forEach(function(chart) { + it('should return yAxis extents equal to data extents with boundsMargin', function () { + vis.handler.charts.forEach(function (chart) { const yAxis = chart.handler.valueAxes[0]; const min = vis.handler.valueAxes[0].axisScale.getYMin(); const max = vis.handler.valueAxes[0].axisScale.getYMax(); diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/pie_chart.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/pie_chart.js index 506ad2af85c34..d245905729c7e 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/pie_chart.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vislib/visualizations/pie_chart.js @@ -30,7 +30,7 @@ const names = ['rows', 'columns', 'slices']; const sizes = [0, 5, 15, 30, 60, 120]; -describe('No global chart settings', function() { +describe('No global chart settings', function () { const visLibParams1 = { el: '
', type: 'pie', @@ -49,15 +49,15 @@ describe('No global chart settings', function() { chart1.render(pieChartMockData.rowData, mockUiState); }); - afterEach(function() { + afterEach(function () { chart1.destroy(); }); - it('should render chart titles for all charts', function() { + it('should render chart titles for all charts', function () { expect($(chart1.element).find('.visAxis__splitTitles--y').length).to.be(1); }); - describe('_validatePieData method', function() { + describe('_validatePieData method', function () { const allZeros = [ { slices: { children: [] } }, { slices: { children: [] } }, @@ -76,26 +76,26 @@ describe('No global chart settings', function() { { slices: { children: [{}] } }, ]; - it('should throw an error when all charts contain zeros', function() { - expect(function() { + it('should throw an error when all charts contain zeros', function () { + expect(function () { chart1.handler.ChartClass.prototype._validatePieData(allZeros); }).to.throwError(); }); - it('should not throw an error when only some or no charts contain zeros', function() { - expect(function() { + it('should not throw an error when only some or no charts contain zeros', function () { + expect(function () { chart1.handler.ChartClass.prototype._validatePieData(someZeros); }).to.not.throwError(); - expect(function() { + expect(function () { chart1.handler.ChartClass.prototype._validatePieData(noZeros); }).to.not.throwError(); }); }); }); -describe('Vislib PieChart Class Test Suite', function() { - ['rowData', 'columnData', 'sliceData'].forEach(function(aggItem, i) { - describe('Vislib PieChart Class Test Suite for ' + names[i] + ' data', function() { +describe('Vislib PieChart Class Test Suite', function () { + ['rowData', 'columnData', 'sliceData'].forEach(function (aggItem, i) { + describe('Vislib PieChart Class Test Suite for ' + names[i] + ' data', function () { const mockPieData = pieChartMockData[aggItem]; const visLibParams = { @@ -111,18 +111,18 @@ describe('Vislib PieChart Class Test Suite', function() { vis.render(mockPieData, mockUiState); }); - afterEach(function() { + afterEach(function () { vis.destroy(); }); - describe('addPathEvents method', function() { + describe('addPathEvents method', function () { let path; let d3selectedPath; let onClick; let onMouseOver; - beforeEach(function() { - vis.handler.charts.forEach(function(chart) { + beforeEach(function () { + vis.handler.charts.forEach(function (chart) { path = $(chart.chartEl).find('path')[0]; d3selectedPath = d3.select(path)[0][0]; @@ -132,30 +132,28 @@ describe('Vislib PieChart Class Test Suite', function() { }); }); - it('should attach a click event', function() { - vis.handler.charts.forEach(function() { + it('should attach a click event', function () { + vis.handler.charts.forEach(function () { expect(onClick).to.be(true); }); }); - it('should attach a hover event', function() { - vis.handler.charts.forEach(function() { + it('should attach a hover event', function () { + vis.handler.charts.forEach(function () { expect(onMouseOver).to.be(true); }); }); }); - describe('addPath method', function() { + describe('addPath method', function () { let width; let height; let svg; let slices; - it('should return an SVG object', function() { - vis.handler.charts.forEach(function(chart) { - $(chart.chartEl) - .find('svg') - .empty(); + it('should return an SVG object', function () { + vis.handler.charts.forEach(function (chart) { + $(chart.chartEl).find('svg').empty(); width = $(chart.chartEl).width(); height = $(chart.chartEl).height(); svg = d3.select($(chart.chartEl).find('svg')[0]); @@ -164,18 +162,16 @@ describe('Vislib PieChart Class Test Suite', function() { }); }); - it('should draw path elements', function() { - vis.handler.charts.forEach(function(chart) { + it('should draw path elements', function () { + vis.handler.charts.forEach(function (chart) { // test whether path elements are drawn expect($(chart.chartEl).find('path').length).to.be.greaterThan(0); }); }); - it('should draw labels', function() { - vis.handler.charts.forEach(function(chart) { - $(chart.chartEl) - .find('svg') - .empty(); + it('should draw labels', function () { + vis.handler.charts.forEach(function (chart) { + $(chart.chartEl).find('svg').empty(); width = $(chart.chartEl).width(); height = $(chart.chartEl).height(); svg = d3.select($(chart.chartEl).find('svg')[0]); @@ -187,37 +183,37 @@ describe('Vislib PieChart Class Test Suite', function() { }); }); - describe('draw method', function() { - it('should return a function', function() { - vis.handler.charts.forEach(function(chart) { + describe('draw method', function () { + it('should return a function', function () { + vis.handler.charts.forEach(function (chart) { expect(_.isFunction(chart.draw())).to.be(true); }); }); }); - sizes.forEach(function(size) { - describe('containerTooSmall error', function() { - it('should throw an error', function() { + sizes.forEach(function (size) { + describe('containerTooSmall error', function () { + it('should throw an error', function () { // 20px is the minimum height and width - vis.handler.charts.forEach(function(chart) { + vis.handler.charts.forEach(function (chart) { $(chart.chartEl).height(size); $(chart.chartEl).width(size); if (size < 20) { - expect(function() { + expect(function () { chart.render(); }).to.throwError(); } }); }); - it('should not throw an error', function() { - vis.handler.charts.forEach(function(chart) { + it('should not throw an error', function () { + vis.handler.charts.forEach(function (chart) { $(chart.chartEl).height(size); $(chart.chartEl).width(size); if (size > 20) { - expect(function() { + expect(function () { chart.render(); }).to.not.throwError(); } diff --git a/src/legacy/core_plugins/kibana/public/local_application_service/local_application_service.ts b/src/legacy/core_plugins/kibana/public/local_application_service/local_application_service.ts index 44a3507e57aa5..59e5238578d25 100644 --- a/src/legacy/core_plugins/kibana/public/local_application_service/local_application_service.ts +++ b/src/legacy/core_plugins/kibana/public/local_application_service/local_application_service.ts @@ -50,7 +50,7 @@ export class LocalApplicationService { * @param angularRouteManager The current `ui/routes` instance */ attachToAngular(angularRouteManager: UIRoutes) { - npStart.plugins.kibanaLegacy.getApps().forEach(app => { + npStart.plugins.kibanaLegacy.getApps().forEach((app) => { const wrapperElementId = this.idGenerator(); angularRouteManager.when(matchAllWithPrefix(app), { outerAngularWrapperRoute: true, @@ -87,7 +87,7 @@ export class LocalApplicationService { }); if (app.updater$) { - app.updater$.subscribe(updater => { + app.updater$.subscribe((updater) => { const updatedFields = updater(app); if (updatedFields && updatedFields.activeUrl) { npStart.core.chrome.navLinks.update(app.navLinkId || app.id, { @@ -98,7 +98,7 @@ export class LocalApplicationService { } }); - npStart.plugins.kibanaLegacy.getForwards().forEach(forwardDefinition => { + npStart.plugins.kibanaLegacy.getForwards().forEach((forwardDefinition) => { angularRouteManager.when(matchAllWithPrefix(forwardDefinition.legacyAppId), { outerAngularWrapperRoute: true, reloadOnSearch: false, diff --git a/src/legacy/core_plugins/kibana/public/management/index.js b/src/legacy/core_plugins/kibana/public/management/index.js index ff253629a4825..48f0e2517a486 100644 --- a/src/legacy/core_plugins/kibana/public/management/index.js +++ b/src/legacy/core_plugins/kibana/public/management/index.js @@ -117,12 +117,12 @@ export function updateSidebar(legacySections, id) { ); } -export const destroyReact = id => { +export const destroyReact = (id) => { const node = document.getElementById(id); node && unmountComponentAtNode(node); }; -uiModules.get('apps/management').directive('kbnManagementApp', function($location) { +uiModules.get('apps/management').directive('kbnManagementApp', function ($location) { return { restrict: 'E', template: appTemplate, @@ -133,14 +133,14 @@ uiModules.get('apps/management').directive('kbnManagementApp', function($locatio pageTitle: '=', }, - link: function($scope) { + link: function ($scope) { timefilter.disableAutoRefreshSelector(); timefilter.disableTimeRangeSelector(); $scope.sections = management.visibleItems; $scope.section = management.getSection($scope.sectionName) || management; if ($scope.section) { - $scope.section.items.forEach(item => { + $scope.section.items.forEach((item) => { item.active = `#${$location.path()}`.indexOf(item.url) > -1; }); } @@ -155,10 +155,10 @@ uiModules.get('apps/management').directive('kbnManagementApp', function($locatio }; }); -uiModules.get('apps/management').directive('kbnManagementLanding', function(kbnVersion) { +uiModules.get('apps/management').directive('kbnManagementLanding', function (kbnVersion) { return { restrict: 'E', - link: function($scope) { + link: function ($scope) { $scope.sections = management.visibleItems; $scope.kbnVersion = kbnVersion; }, diff --git a/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.test.ts b/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.test.ts index 8aedc6f7332dc..d1be3d64fdb3f 100644 --- a/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.test.ts +++ b/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.test.ts @@ -103,13 +103,13 @@ const data: Array> = [ test('collects dashboard and all dependencies', async () => { const savedObjectClient = savedObjectsClientMock.create(); - savedObjectClient.bulkGet.mockImplementation(objects => { + savedObjectClient.bulkGet.mockImplementation((objects) => { if (!objects) { throw new Error('Invalid test data'); } return Promise.resolve({ saved_objects: objects.map( - (obj: any) => data.find(row => row.id === obj.id && row.type === obj.type)! + (obj: any) => data.find((row) => row.id === obj.id && row.type === obj.type)! ), }); }); diff --git a/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.ts b/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.ts index 9d620b69bf2e3..e44db901a0cb8 100644 --- a/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.ts +++ b/src/legacy/core_plugins/kibana/server/lib/export/collect_references_deep.ts @@ -40,7 +40,7 @@ export async function collectReferencesDeep( for (const reference of references) { const isDuplicate = queue .concat(result) - .some(obj => obj.type === reference.type && obj.id === reference.id); + .some((obj) => obj.type === reference.type && obj.id === reference.id); if (isDuplicate) { continue; } diff --git a/src/legacy/core_plugins/kibana/server/lib/export/export_dashboards.js b/src/legacy/core_plugins/kibana/server/lib/export/export_dashboards.js index 8df55aabb5554..913ebff588f84 100644 --- a/src/legacy/core_plugins/kibana/server/lib/export/export_dashboards.js +++ b/src/legacy/core_plugins/kibana/server/lib/export/export_dashboards.js @@ -25,7 +25,7 @@ export async function exportDashboards(req) { const config = req.server.config(); const savedObjectsClient = req.getSavedObjectsClient(); - const objectsToExport = ids.map(id => ({ id, type: 'dashboard' })); + const objectsToExport = ids.map((id) => ({ id, type: 'dashboard' })); const objects = await collectReferencesDeep(savedObjectsClient, objectsToExport); return { diff --git a/src/legacy/core_plugins/kibana/server/lib/import/import_dashboards.js b/src/legacy/core_plugins/kibana/server/lib/import/import_dashboards.js index 4c68df7a1a960..7c28b184144f1 100644 --- a/src/legacy/core_plugins/kibana/server/lib/import/import_dashboards.js +++ b/src/legacy/core_plugins/kibana/server/lib/import/import_dashboards.js @@ -32,8 +32,8 @@ export async function importDashboards(req) { // need to set migrationVersion to something other than undefined, so that imported // docs are not seen as automatically up-to-date. const docs = payload.objects - .filter(item => !exclude.includes(item.type)) - .map(doc => ({ ...doc, migrationVersion: doc.migrationVersion || {} })); + .filter((item) => !exclude.includes(item.type)) + .map((doc) => ({ ...doc, migrationVersion: doc.migrationVersion || {} })); const results = await savedObjectsClient.bulkCreate(docs, { overwrite }); return { objects: results.saved_objects }; diff --git a/src/legacy/core_plugins/kibana/server/lib/management/saved_objects/relationships.js b/src/legacy/core_plugins/kibana/server/lib/management/saved_objects/relationships.js index 585d9ce938710..e0a6c574b7ad8 100644 --- a/src/legacy/core_plugins/kibana/server/lib/management/saved_objects/relationships.js +++ b/src/legacy/core_plugins/kibana/server/lib/management/saved_objects/relationships.js @@ -43,16 +43,16 @@ export async function findRelationships(type, id, options = {}) { return [].concat( referencedObjects.saved_objects - .map(obj => injectMetaAttributes(obj, savedObjectsManagement)) + .map((obj) => injectMetaAttributes(obj, savedObjectsManagement)) .map(extractCommonProperties) - .map(obj => ({ + .map((obj) => ({ ...obj, relationship: 'child', })), referencedResponse.saved_objects - .map(obj => injectMetaAttributes(obj, savedObjectsManagement)) + .map((obj) => injectMetaAttributes(obj, savedObjectsManagement)) .map(extractCommonProperties) - .map(obj => ({ + .map((obj) => ({ ...obj, relationship: 'parent', })) diff --git a/src/legacy/core_plugins/kibana/server/routes/api/export/index.js b/src/legacy/core_plugins/kibana/server/routes/api/export/index.js index b939e06b7bdb9..ef556ed53f4fc 100644 --- a/src/legacy/core_plugins/kibana/server/routes/api/export/index.js +++ b/src/legacy/core_plugins/kibana/server/routes/api/export/index.js @@ -38,7 +38,7 @@ export function exportApi(server) { method: ['GET'], handler: async (req, h) => { const currentDate = moment.utc(); - return exportDashboards(req).then(resp => { + return exportDashboards(req).then((resp) => { const json = JSON.stringify(resp, null, ' '); const filename = `kibana-dashboards.${currentDate.format('YYYY-MM-DD-HH-mm-ss')}.json`; return h diff --git a/src/legacy/core_plugins/kibana/server/routes/api/import/index.js b/src/legacy/core_plugins/kibana/server/routes/api/import/index.js index d0fa0bb4489cb..b7efb7da3c5a9 100644 --- a/src/legacy/core_plugins/kibana/server/routes/api/import/index.js +++ b/src/legacy/core_plugins/kibana/server/routes/api/import/index.js @@ -38,7 +38,7 @@ export function importApi(server) { tags: ['api'], }, - handler: async req => { + handler: async (req) => { return await importDashboards(req); }, }); diff --git a/src/legacy/core_plugins/kibana/server/ui_setting_defaults.js b/src/legacy/core_plugins/kibana/server/ui_setting_defaults.js index 275f1cb687e22..0d1b69778263c 100644 --- a/src/legacy/core_plugins/kibana/server/ui_setting_defaults.js +++ b/src/legacy/core_plugins/kibana/server/ui_setting_defaults.js @@ -32,7 +32,7 @@ export function getUiSettingDefaults() { // default fallback in case the locale is not found. const numeralLanguageIds = [ 'en', - ...numeralLanguages.map(function(numeralLanguage) { + ...numeralLanguages.map(function (numeralLanguage) { return numeralLanguage.id; }), ]; @@ -655,7 +655,7 @@ export function getUiSettingDefaults() { type: 'select', options: numeralLanguageIds, optionLabels: Object.fromEntries( - numeralLanguages.map(language => [language.id, language.name]) + numeralLanguages.map((language) => [language.id, language.name]) ), description: i18n.translate('kbn.advancedSettings.format.formattingLocaleText', { defaultMessage: `{numeralLanguageLink} locale`, @@ -810,6 +810,18 @@ export function getUiSettingDefaults() { }), requiresPageReload: true, }, + 'theme:version': { + name: i18n.translate('kbn.advancedSettings.themeVersionTitle', { + defaultMessage: 'Theme version', + }), + value: 'v7', + type: 'select', + options: ['v7', 'v8 (beta)'], + description: i18n.translate('kbn.advancedSettings.themeVersionText', { + defaultMessage: `Switch between the theme used for the current and next version of Kibana. A page refresh is required for the setting to be applied.`, + }), + requiresPageReload: true, + }, 'filters:pinnedByDefault': { name: i18n.translate('kbn.advancedSettings.pinFiltersTitle', { defaultMessage: 'Pin filters by default', diff --git a/src/legacy/core_plugins/status_page/index.js b/src/legacy/core_plugins/status_page/index.js index fc3bfc4c7c6c6..01991d8439a04 100644 --- a/src/legacy/core_plugins/status_page/index.js +++ b/src/legacy/core_plugins/status_page/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function(kibana) { +export default function (kibana) { return new kibana.Plugin({ uiExports: { app: { diff --git a/src/legacy/core_plugins/status_page/public/components/metric_tiles.js b/src/legacy/core_plugins/status_page/public/components/metric_tiles.js index 8500bfea63aba..6cde975875ad1 100644 --- a/src/legacy/core_plugins/status_page/public/components/metric_tiles.js +++ b/src/legacy/core_plugins/status_page/public/components/metric_tiles.js @@ -36,7 +36,7 @@ export class MetricTile extends Component { const metrics = [].concat(value); return metrics - .map(function(metric) { + .map(function (metric) { return formatNumber(metric, type); }) .join(', '); @@ -54,7 +54,7 @@ Wrapper component that simply maps each metric to MetricTile inside a FlexGroup */ const MetricTiles = ({ metrics }) => ( - {metrics.map(metric => ( + {metrics.map((metric) => ( diff --git a/src/legacy/core_plugins/status_page/public/components/status_app.js b/src/legacy/core_plugins/status_page/public/components/status_app.js index 353938e783a47..a6b0321e53a8f 100644 --- a/src/legacy/core_plugins/status_page/public/components/status_app.js +++ b/src/legacy/core_plugins/status_page/public/components/status_app.js @@ -53,7 +53,7 @@ class StatusApp extends Component { }; } - componentDidMount = async function() { + componentDidMount = async function () { const data = await loadStatus(); if (data) { diff --git a/src/legacy/core_plugins/status_page/public/components/status_table.js b/src/legacy/core_plugins/status_page/public/components/status_table.js index 3eb04409f5f89..68b93153951cb 100644 --- a/src/legacy/core_plugins/status_page/public/components/status_table.js +++ b/src/legacy/core_plugins/status_page/public/components/status_table.js @@ -37,7 +37,7 @@ class StatusTable extends Component { { field: 'state', name: '', - render: state => , + render: (state) => , width: '32px', }, { @@ -51,7 +51,7 @@ class StatusTable extends Component { name: i18n.translate('statusPage.statusTable.columns.statusHeader', { defaultMessage: 'Status', }), - render: state => {state.message}, + render: (state) => {state.message}, }, ]; diff --git a/src/legacy/core_plugins/status_page/public/lib/load_status.test.js b/src/legacy/core_plugins/status_page/public/lib/load_status.test.js index 2a37b443b8653..a0f1930ca7667 100644 --- a/src/legacy/core_plugins/status_page/public/lib/load_status.test.js +++ b/src/legacy/core_plugins/status_page/public/lib/load_status.test.js @@ -99,7 +99,7 @@ describe('response processing', () => { test('builds the metrics', async () => { const data = await loadStatus(mockFetch); - const names = data.metrics.map(m => m.name); + const names = data.metrics.map((m) => m.name); expect(names).toEqual([ 'Heap total', 'Heap used', @@ -109,7 +109,7 @@ describe('response processing', () => { 'Requests per second', ]); - const values = data.metrics.map(m => m.value); + const values = data.metrics.map((m) => m.value); expect(values).toEqual([1000000, 100, [4.1, 2.1, 0.1], 4000, 8000, 400]); }); }); diff --git a/src/legacy/core_plugins/status_page/public/status_page.js b/src/legacy/core_plugins/status_page/public/status_page.js index 82cd2aa5f395d..709164caa9e04 100644 --- a/src/legacy/core_plugins/status_page/public/status_page.js +++ b/src/legacy/core_plugins/status_page/public/status_page.js @@ -25,7 +25,7 @@ import template from 'plugins/status_page/status_page.html'; npStart.core.chrome.navLinks.enableForcedAppSwitcherNavigation(); -chrome.setRootTemplate(template).setRootController('ui', function($scope, buildNum, buildSha) { +chrome.setRootTemplate(template).setRootController('ui', function ($scope, buildNum, buildSha) { $scope.$$postDigest(() => { renderStatusPage(buildNum, buildSha.substr(0, 8)); $scope.$on('$destroy', destroyStatusPage); diff --git a/src/legacy/core_plugins/testbed/index.js b/src/legacy/core_plugins/testbed/index.js index 0cbd966100811..f0b61ea0c3de7 100644 --- a/src/legacy/core_plugins/testbed/index.js +++ b/src/legacy/core_plugins/testbed/index.js @@ -19,7 +19,7 @@ import { resolve } from 'path'; -export default function(kibana) { +export default function (kibana) { return new kibana.Plugin({ id: 'testbed', publicDir: resolve(__dirname, 'public'), diff --git a/src/legacy/core_plugins/tests_bundle/find_source_files.js b/src/legacy/core_plugins/tests_bundle/find_source_files.js index a834072b258a3..eed88a5ecb8b0 100644 --- a/src/legacy/core_plugins/tests_bundle/find_source_files.js +++ b/src/legacy/core_plugins/tests_bundle/find_source_files.js @@ -27,7 +27,7 @@ import glob from 'glob-all'; const findSourceFiles = async (patterns, cwd = fromRoot('.')) => { patterns = [].concat(patterns || []); - const matches = await fromNode(cb => { + const matches = await fromNode((cb) => { glob( patterns, { @@ -52,7 +52,7 @@ const findSourceFiles = async (patterns, cwd = fromRoot('.')) => { return chain(matches) .flatten() .uniq() - .map(match => resolve(cwd, match)) + .map((match) => resolve(cwd, match)) .value(); }; diff --git a/src/legacy/core_plugins/tests_bundle/index.js b/src/legacy/core_plugins/tests_bundle/index.js index 3348096c0e2f1..431c161585fe0 100644 --- a/src/legacy/core_plugins/tests_bundle/index.js +++ b/src/legacy/core_plugins/tests_bundle/index.js @@ -30,9 +30,9 @@ import { replacePlaceholder } from '../../../optimize/public_path_placeholder'; import findSourceFiles from './find_source_files'; import { createTestEntryTemplate } from './tests_entry_template'; -export default kibana => { +export default (kibana) => { return new kibana.Plugin({ - config: Joi => { + config: (Joi) => { return Joi.object({ enabled: Joi.boolean().default(true), instrument: Joi.boolean().default(false), @@ -58,8 +58,8 @@ export default kibana => { const testingPluginIds = config.get('tests_bundle.pluginId'); if (testingPluginIds) { - testingPluginIds.split(',').forEach(pluginId => { - const plugin = plugins.find(plugin => plugin.id === pluginId); + testingPluginIds.split(',').forEach((pluginId) => { + const plugin = plugins.find((plugin) => plugin.id === pluginId); if (!plugin) { throw new Error('Invalid testingPluginId :: unknown plugin ' + pluginId); @@ -134,20 +134,17 @@ export default kibana => { async handler(_, h) { const cssFiles = await globby( testingPluginIds - ? testingPluginIds.split(',').map(id => `built_assets/css/plugins/${id}/**/*.css`) + ? testingPluginIds.split(',').map((id) => `built_assets/css/plugins/${id}/**/*.css`) : `built_assets/css/**/*.css`, { cwd: fromRoot('.'), absolute: true } ); const stream = replacePlaceholder( - new MultiStream(cssFiles.map(path => createReadStream(path))), + new MultiStream(cssFiles.map((path) => createReadStream(path))), '/built_assets/css/' ); - return h - .response(stream) - .code(200) - .type('text/css'); + return h.response(stream).code(200).type('text/css'); }, }); diff --git a/src/legacy/core_plugins/tests_bundle/tests_entry_template.js b/src/legacy/core_plugins/tests_bundle/tests_entry_template.js index f075d8365c299..28c26f08621eb 100644 --- a/src/legacy/core_plugins/tests_bundle/tests_entry_template.js +++ b/src/legacy/core_plugins/tests_bundle/tests_entry_template.js @@ -19,7 +19,7 @@ import { Type } from '@kbn/config-schema'; import pkg from '../../../../package.json'; -export const createTestEntryTemplate = defaultUiSettings => bundle => ` +export const createTestEntryTemplate = (defaultUiSettings) => (bundle) => ` /** * Test entry file * diff --git a/src/legacy/core_plugins/timelion/public/app.js b/src/legacy/core_plugins/timelion/public/app.js index 6c1dc81dc341b..b5501982cec09 100644 --- a/src/legacy/core_plugins/timelion/public/app.js +++ b/src/legacy/core_plugins/timelion/public/app.js @@ -70,7 +70,7 @@ routes.when('/:id?', { reloadOnSearch: false, k7Breadcrumbs: ($injector, $route) => $injector.invoke($route.current.params.id ? getSavedSheetBreadcrumbs : getCreateBreadcrumbs), - badge: uiCapabilities => { + badge: (uiCapabilities) => { if (uiCapabilities.timelion.save) { return undefined; } @@ -86,10 +86,10 @@ routes.when('/:id?', { }; }, resolve: { - savedSheet: function(redirectWhenMissing, savedSheets, $route) { + savedSheet: function (redirectWhenMissing, savedSheets, $route) { return savedSheets .get($route.current.params.id) - .then(savedSheet => { + .then((savedSheet) => { if ($route.current.params.id) { npStart.core.chrome.recentlyAccessed.add( savedSheet.getFullPath(), @@ -110,7 +110,7 @@ routes.when('/:id?', { const location = 'Timelion'; -app.controller('timelion', function( +app.controller('timelion', function ( $http, $route, $routeParams, @@ -123,7 +123,7 @@ app.controller('timelion', function( // Keeping this at app scope allows us to keep the current page when the user // switches to say, the timepicker. $scope.page = config.get('timelion:showTutorial', true) ? 1 : 0; - $scope.setPage = page => ($scope.page = page); + $scope.setPage = (page) => ($scope.page = page); timefilter.enableAutoRefreshSelector(); timefilter.enableTimeRangeSelector(); @@ -136,7 +136,7 @@ app.controller('timelion', function( $scope.topNavMenu = getTopNavMenu(); - $timeout(function() { + $timeout(function () { if (config.get('timelion:showTutorial', true)) { $scope.toggleMenu('showHelp'); } @@ -163,7 +163,7 @@ app.controller('timelion', function( description: i18n.translate('timelion.topNavMenu.newSheetButtonAriaLabel', { defaultMessage: 'New Sheet', }), - run: function() { + run: function () { kbnUrl.change('/'); }, testId: 'timelionNewButton', @@ -177,7 +177,7 @@ app.controller('timelion', function( description: i18n.translate('timelion.topNavMenu.addChartButtonAriaLabel', { defaultMessage: 'Add a chart', }), - run: function() { + run: function () { $scope.$evalAsync(() => $scope.newCell()); }, testId: 'timelionAddChartButton', @@ -205,10 +205,10 @@ app.controller('timelion', function( description: i18n.translate('timelion.topNavMenu.deleteSheetButtonAriaLabel', { defaultMessage: 'Delete current sheet', }), - disableButton: function() { + disableButton: function () { return !savedSheet.id; }, - run: function() { + run: function () { const title = savedSheet.title; function doDelete() { savedSheet @@ -222,7 +222,7 @@ app.controller('timelion', function( ); kbnUrl.change('/'); }) - .catch(error => fatalError(error, location)); + .catch((error) => fatalError(error, location)); } const confirmModalOptions = { @@ -243,7 +243,7 @@ app.controller('timelion', function( }), confirmModalOptions ) - .then(isConfirmed => { + .then((isConfirmed) => { if (isConfirmed) { doDelete(); } @@ -310,12 +310,12 @@ app.controller('timelion', function( } let refresher; - const setRefreshData = function() { + const setRefreshData = function () { if (refresher) $timeout.cancel(refresher); const interval = timefilter.getRefreshInterval(); if (interval.value > 0 && !interval.pause) { function startRefresh() { - refresher = $timeout(function() { + refresher = $timeout(function () { if (!$scope.running) $scope.search(); startRefresh(); }, interval.value); @@ -324,7 +324,7 @@ app.controller('timelion', function( } }; - const init = function() { + const init = function () { $scope.running = false; $scope.search(); setRefreshData(); @@ -343,7 +343,7 @@ app.controller('timelion', function( savedSheet: savedSheet, state: $scope.state, search: $scope.search, - dontShowHelp: function() { + dontShowHelp: function () { config.set('timelion:showTutorial', false); $scope.setPage(0); $scope.closeMenus(); @@ -357,27 +357,27 @@ app.controller('timelion', function( showOptions: false, }; - $scope.toggleMenu = menuName => { + $scope.toggleMenu = (menuName) => { const curState = $scope.menus[menuName]; $scope.closeMenus(); $scope.menus[menuName] = !curState; }; $scope.closeMenus = () => { - _.forOwn($scope.menus, function(value, key) { + _.forOwn($scope.menus, function (value, key) { $scope.menus[key] = false; }); }; }; - $scope.onTimeUpdate = function({ dateRange }) { + $scope.onTimeUpdate = function ({ dateRange }) { $scope.model.timeRange = { ...dateRange, }; timefilter.setTime(dateRange); }; - $scope.onRefreshChange = function({ isPaused, refreshInterval }) { + $scope.onRefreshChange = function ({ isPaused, refreshInterval }) { $scope.model.refreshInterval = { pause: isPaused, value: refreshInterval, @@ -391,33 +391,33 @@ app.controller('timelion', function( }; $scope.$watch( - function() { + function () { return savedSheet.lastSavedTitle; }, - function(newTitle) { + function (newTitle) { docTitle.change(savedSheet.id ? newTitle : undefined); } ); - $scope.toggle = function(property) { + $scope.toggle = function (property) { $scope[property] = !$scope[property]; }; - $scope.newSheet = function() { + $scope.newSheet = function () { kbnUrl.change('/', {}); }; - $scope.newCell = function() { + $scope.newCell = function () { $scope.state.sheet.push(defaultExpression); $scope.state.selected = $scope.state.sheet.length - 1; $scope.safeSearch(); }; - $scope.setActiveCell = function(cell) { + $scope.setActiveCell = function (cell) { $scope.state.selected = cell; }; - $scope.search = function() { + $scope.search = function () { $scope.state.save(); $scope.running = true; @@ -438,23 +438,23 @@ app.controller('timelion', function( } ), }) - .then(resp => resp.data) - .catch(resp => { + .then((resp) => resp.data) + .catch((resp) => { throw resp.data; }); httpResult - .then(function(resp) { + .then(function (resp) { $scope.stats = resp.stats; $scope.sheet = resp.sheet; - _.each(resp.sheet, function(cell) { + _.each(resp.sheet, function (cell) { if (cell.exception) { $scope.state.selected = cell.plot; } }); $scope.running = false; }) - .catch(function(resp) { + .catch(function (resp) { $scope.sheet = []; $scope.running = false; @@ -475,7 +475,7 @@ app.controller('timelion', function( savedSheet.timelion_interval = $scope.state.interval; savedSheet.timelion_columns = $scope.state.columns; savedSheet.timelion_rows = $scope.state.rows; - savedSheet.save().then(function(id) { + savedSheet.save().then(function (id) { if (id) { toastNotifications.addSuccess({ title: i18n.translate('timelion.saveSheet.successNotificationText', { @@ -493,14 +493,14 @@ app.controller('timelion', function( } function saveExpression(title) { - savedVisualizations.get({ type: 'timelion' }).then(function(savedExpression) { + savedVisualizations.get({ type: 'timelion' }).then(function (savedExpression) { savedExpression.visState.params = { expression: $scope.state.sheet[$scope.state.selected], interval: $scope.state.interval, }; savedExpression.title = title; savedExpression.visState.title = title; - savedExpression.save().then(function(id) { + savedExpression.save().then(function (id) { if (id) { toastNotifications.addSuccess( i18n.translate('timelion.saveExpression.successNotificationText', { diff --git a/src/legacy/core_plugins/timelion/public/components/timelionhelp_tabs_directive.js b/src/legacy/core_plugins/timelion/public/components/timelionhelp_tabs_directive.js index 16d814a11cc7b..7e77027f750c6 100644 --- a/src/legacy/core_plugins/timelion/public/components/timelionhelp_tabs_directive.js +++ b/src/legacy/core_plugins/timelion/public/components/timelionhelp_tabs_directive.js @@ -25,6 +25,6 @@ const module = uiModules.get('apps/timelion', ['react']); import { TimelionHelpTabs } from './timelionhelp_tabs'; -module.directive('timelionHelpTabs', function(reactDirective) { +module.directive('timelionHelpTabs', function (reactDirective) { return reactDirective(wrapInI18nContext(TimelionHelpTabs), undefined, { restrict: 'E' }); }); diff --git a/src/legacy/core_plugins/timelion/public/directives/cells/cells.js b/src/legacy/core_plugins/timelion/public/directives/cells/cells.js index 3e59025e920b9..104af3b1043d6 100644 --- a/src/legacy/core_plugins/timelion/public/directives/cells/cells.js +++ b/src/legacy/core_plugins/timelion/public/directives/cells/cells.js @@ -27,7 +27,7 @@ require('plugins/timelion/directives/timelion_grid'); const app = require('ui/modules').get('apps/timelion', ['angular-sortable-view']); import html from './cells.html'; -app.directive('timelionCells', function() { +app.directive('timelionCells', function () { return { restrict: 'E', scope: { @@ -38,13 +38,13 @@ app.directive('timelionCells', function() { onSelect: '=', }, template: html, - link: function($scope) { - $scope.removeCell = function(index) { + link: function ($scope) { + $scope.removeCell = function (index) { _.pullAt($scope.state.sheet, index); $scope.onSearch(); }; - $scope.dropCell = function(item, partFrom, partTo, indexFrom, indexTo) { + $scope.dropCell = function (item, partFrom, partTo, indexFrom, indexTo) { $scope.onSelect(indexTo); move($scope.sheet, indexFrom, indexTo); }; diff --git a/src/legacy/core_plugins/timelion/public/directives/chart/chart.js b/src/legacy/core_plugins/timelion/public/directives/chart/chart.js index 332567c35b163..14bd3281a683e 100644 --- a/src/legacy/core_plugins/timelion/public/directives/chart/chart.js +++ b/src/legacy/core_plugins/timelion/public/directives/chart/chart.js @@ -28,7 +28,7 @@ export function Chart(timelionPanels) { interval: '=', // Required for formatting x-axis ticks rerenderTrigger: '=', }, - link: function($scope, $elem) { + link: function ($scope, $elem) { let panelScope = $scope.$new(true); function render() { diff --git a/src/legacy/core_plugins/timelion/public/directives/fixed_element.js b/src/legacy/core_plugins/timelion/public/directives/fixed_element.js index 71907c4014a29..e3a8b2184bb20 100644 --- a/src/legacy/core_plugins/timelion/public/directives/fixed_element.js +++ b/src/legacy/core_plugins/timelion/public/directives/fixed_element.js @@ -20,12 +20,12 @@ import $ from 'jquery'; const app = require('ui/modules').get('apps/timelion', []); -app.directive('fixedElementRoot', function() { +app.directive('fixedElementRoot', function () { return { restrict: 'A', - link: function($elem) { + link: function ($elem) { let fixedAt; - $(window).bind('scroll', function() { + $(window).bind('scroll', function () { const fixed = $('[fixed-element]', $elem); const body = $('[fixed-element-body]', $elem); const top = fixed.offset().top; diff --git a/src/legacy/core_plugins/timelion/public/directives/fullscreen/fullscreen.js b/src/legacy/core_plugins/timelion/public/directives/fullscreen/fullscreen.js index 325ed4d5c786e..5c4bd72ceb708 100644 --- a/src/legacy/core_plugins/timelion/public/directives/fullscreen/fullscreen.js +++ b/src/legacy/core_plugins/timelion/public/directives/fullscreen/fullscreen.js @@ -24,7 +24,7 @@ require('plugins/timelion/directives/timelion_grid'); const app = require('ui/modules').get('apps/timelion', ['angular-sortable-view']); import html from './fullscreen.html'; -app.directive('timelionFullscreen', function() { +app.directive('timelionFullscreen', function () { return { restrict: 'E', scope: { diff --git a/src/legacy/core_plugins/timelion/public/directives/saved_object_finder.js b/src/legacy/core_plugins/timelion/public/directives/saved_object_finder.js index ee729d2b427ad..08a347fbf7295 100644 --- a/src/legacy/core_plugins/timelion/public/directives/saved_object_finder.js +++ b/src/legacy/core_plugins/timelion/public/directives/saved_object_finder.js @@ -35,7 +35,7 @@ const module = uiModules.get('kibana'); module .directive('paginate', PaginateDirectiveProvider) .directive('paginateControls', PaginateControlsDirectiveProvider) - .directive('savedObjectFinder', function($location, kbnUrl, Private, config) { + .directive('savedObjectFinder', function ($location, kbnUrl, Private, config) { return { restrict: 'E', scope: { @@ -59,7 +59,7 @@ module }, template: savedObjectFinderTemplate, controllerAs: 'finder', - controller: function($scope, $element) { + controller: function ($scope, $element) { const self = this; // the text input element @@ -97,7 +97,7 @@ module * @param {Array} hits Array of saved finder object hits * @return {Array} Array sorted either ascending or descending */ - self.sortHits = function(hits) { + self.sortHits = function (hits) { self.isAscending = !self.isAscending; self.hits = self.isAscending ? _.sortBy(hits, 'title') @@ -109,7 +109,7 @@ module * hit should have a url in the UI, returns it if so * @return {string|null} - the url or nothing */ - self.makeUrl = function(hit) { + self.makeUrl = function (hit) { if ($scope.userMakeUrl) { return $scope.userMakeUrl(hit); } @@ -121,7 +121,7 @@ module return '#'; }; - self.preventClick = function($event) { + self.preventClick = function ($event) { $event.preventDefault(); }; @@ -129,7 +129,7 @@ module * Called when a hit object is clicked, can override the * url behavior if necessary. */ - self.onChoose = function(hit, $event) { + self.onChoose = function (hit, $event) { if ($scope.userOnChoose) { $scope.userOnChoose(hit, $event); } @@ -143,7 +143,7 @@ module kbnUrl.change(url.substr(1)); }; - $scope.$watch('filter', function(newFilter) { + $scope.$watch('filter', function (newFilter) { // ensure that the currentFilter changes from undefined to '' // which triggers currentFilter = newFilter || ''; @@ -152,7 +152,7 @@ module $scope.pageFirstItem = 0; $scope.pageLastItem = 0; - $scope.onPageChanged = page => { + $scope.onPageChanged = (page) => { $scope.pageFirstItem = page.firstItem; $scope.pageLastItem = page.lastItem; }; @@ -163,14 +163,12 @@ module index: -1, }; - self.getLabel = function() { - return _.words(self.properties.nouns) - .map(_.capitalize) - .join(' '); + self.getLabel = function () { + return _.words(self.properties.nouns).map(_.capitalize).join(' '); }; //key handler for the filter text box - self.filterKeyDown = function($event) { + self.filterKeyDown = function ($event) { switch (keyMap[$event.keyCode]) { case 'enter': if (self.hitCount !== 1) return; @@ -185,7 +183,7 @@ module }; //key handler for the list items - self.hitKeyDown = function($event, page, paginate) { + self.hitKeyDown = function ($event, page, paginate) { switch (keyMap[$event.keyCode]) { case 'tab': if (!self.selector.enabled) break; @@ -263,21 +261,21 @@ module } }; - self.hitBlur = function() { + self.hitBlur = function () { self.selector.index = -1; self.selector.enabled = false; }; - self.manageObjects = function(type) { + self.manageObjects = function (type) { $location.url('/management/kibana/objects?_a=' + rison.encode({ tab: type })); }; - self.hitCountNoun = function() { + self.hitCountNoun = function () { return (self.hitCount === 1 ? self.properties.noun : self.properties.nouns).toLowerCase(); }; function selectTopHit() { - setTimeout(function() { + setTimeout(function () { //triggering a focus event kicks off a new angular digest cycle. $list.find('a:first').focus(); }, 0); @@ -297,9 +295,9 @@ module prevSearch = filter; const isLabsEnabled = config.get('visualize:enableLabs'); - self.service.find(filter).then(function(hits) { + self.service.find(filter).then(function (hits) { hits.hits = hits.hits.filter( - hit => isLabsEnabled || _.get(hit, 'type.stage') !== 'experimental' + (hit) => isLabsEnabled || _.get(hit, 'type.stage') !== 'experimental' ); hits.total = hits.hits.length; diff --git a/src/legacy/core_plugins/timelion/public/directives/saved_object_save_as_checkbox.js b/src/legacy/core_plugins/timelion/public/directives/saved_object_save_as_checkbox.js index ac830092ce670..0671bc3e20123 100644 --- a/src/legacy/core_plugins/timelion/public/directives/saved_object_save_as_checkbox.js +++ b/src/legacy/core_plugins/timelion/public/directives/saved_object_save_as_checkbox.js @@ -20,7 +20,7 @@ import { uiModules } from 'ui/modules'; import saveObjectSaveAsCheckboxTemplate from './saved_object_save_as_checkbox.html'; -uiModules.get('kibana').directive('savedObjectSaveAsCheckBox', function() { +uiModules.get('kibana').directive('savedObjectSaveAsCheckBox', function () { return { restrict: 'E', template: saveObjectSaveAsCheckboxTemplate, diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input.js b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input.js index 35ac883e5d99c..f3fd2fde8f2c5 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input.js @@ -67,7 +67,7 @@ export function TimelionExpInput($http, $timeout) { }, replace: true, template: timelionExpressionInputTemplate, - link: function(scope, elem) { + link: function (scope, elem) { const argValueSuggestions = npStart.plugins.visTypeTimelion.getArgValueSuggestions(); const expressionInput = elem.find('[data-expression-input]'); const functionReference = {}; @@ -76,7 +76,7 @@ export function TimelionExpInput($http, $timeout) { scope.suggestions = new Suggestions(); function init() { - $http.get('../api/timelion/functions').then(function(resp) { + $http.get('../api/timelion/functions').then(function (resp) { Object.assign(functionReference, { byName: _.indexBy(resp.data, 'name'), list: resp.data, @@ -193,7 +193,7 @@ export function TimelionExpInput($http, $timeout) { scope.suggestions.hide(); }; - scope.onKeyDownInput = e => { + scope.onKeyDownInput = (e) => { // If we've pressed any non-navigational keys, then the user has typed something and we // can exit early without doing any navigation. The keyup handler will pull up suggestions. if (!isNavigationalKey(e.keyCode)) { @@ -253,7 +253,7 @@ export function TimelionExpInput($http, $timeout) { } }; - scope.onKeyUpInput = e => { + scope.onKeyUpInput = (e) => { // If the user isn't navigating, then we should update the suggestions based on their input. if (!isNavigationalKey(e.keyCode)) { getSuggestions(); @@ -264,7 +264,7 @@ export function TimelionExpInput($http, $timeout) { getSuggestions(); }; - scope.onClickSuggestion = index => { + scope.onClickSuggestion = (index) => { insertSuggestionIntoExpression(index); }; diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input_helpers.js b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input_helpers.js index 36577fcb00719..20edee82f9486 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input_helpers.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_input_helpers.js @@ -101,10 +101,10 @@ function getArgumentsHelp(functionHelp, functionArgs = []) { const argsHelp = functionHelp.chainable ? functionHelp.args.slice(1) : functionHelp.args.slice(0); // ignore arguments that are already provided in function declaration - const functionArgNames = functionArgs.map(arg => { + const functionArgNames = functionArgs.map((arg) => { return arg.name; }); - return argsHelp.filter(arg => { + return argsHelp.filter((arg) => { return !functionArgNames.includes(arg.name); }); } @@ -115,7 +115,7 @@ async function extractSuggestionsFromParsedResult( functionList, argValueSuggestions ) { - const activeFunc = result.functions.find(func => { + const activeFunc = result.functions.find((func) => { return cursorPosition >= func.location.min && cursorPosition < func.location.max; }); @@ -123,7 +123,7 @@ async function extractSuggestionsFromParsedResult( return; } - const functionHelp = functionList.find(func => { + const functionHelp = functionList.find((func) => { return func.name === activeFunc.function; }); @@ -135,7 +135,7 @@ async function extractSuggestionsFromParsedResult( } // return argument value suggestions when cursor is inside argument value - const activeArg = activeFunc.arguments.find(argument => { + const activeArg = activeFunc.arguments.find((argument) => { return inLocation(cursorPosition, argument.location); }); if ( @@ -159,7 +159,7 @@ async function extractSuggestionsFromParsedResult( partialInput ); } else { - const { suggestions: staticSuggestions } = functionHelp.args.find(arg => { + const { suggestions: staticSuggestions } = functionHelp.args.find((arg) => { return arg.name === activeArg.name; }); valueSuggestions = argValueSuggestions.getStaticSuggestionsForInput( @@ -176,7 +176,7 @@ async function extractSuggestionsFromParsedResult( // return argument suggestions const argsHelp = getArgumentsHelp(functionHelp, activeFunc.arguments); - const argumentSuggestions = argsHelp.filter(arg => { + const argumentSuggestions = argsHelp.filter((arg) => { if (_.get(activeArg, 'type') === 'namedArg') { return _.startsWith(arg.name, activeArg.name); } else if (activeArg) { @@ -222,7 +222,7 @@ export async function suggest( if (message.function) { // The user has start typing a function name, so we'll filter the list down to only // possible matches. - list = functionList.filter(func => _.startsWith(func.name, message.function)); + list = functionList.filter((func) => _.startsWith(func.name, message.function)); } else { // The user hasn't typed anything yet, so we'll just return the entire list. list = functionList; @@ -231,7 +231,7 @@ export async function suggest( } case 'incompleteArgument': { const { currentFunction: functionName, currentArgs: functionArgs } = message; - const functionHelp = functionList.find(func => func.name === functionName); + const functionHelp = functionList.find((func) => func.name === functionName); return { list: getArgumentsHelp(functionHelp, functionArgs), location: message.location, @@ -248,9 +248,9 @@ export async function suggest( functionArgs ); } else { - const functionHelp = functionList.find(func => func.name === functionName); + const functionHelp = functionList.find((func) => func.name === functionName); if (functionHelp) { - const argHelp = functionHelp.args.find(arg => arg.name === argName); + const argHelp = functionHelp.args.find((arg) => arg.name === argName); if (argHelp && argHelp.suggestions) { valueSuggestions = argHelp.suggestions; } diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/__tests__/timelion_expression_suggestions.js b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/__tests__/timelion_expression_suggestions.js index a74cf19df29e3..8a35a72ed19e6 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/__tests__/timelion_expression_suggestions.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/__tests__/timelion_expression_suggestions.js @@ -21,34 +21,34 @@ import expect from '@kbn/expect'; import ngMock from 'ng_mock'; import '../timelion_expression_suggestions'; -describe('Timelion expression suggestions directive', function() { +describe('Timelion expression suggestions directive', function () { let scope; let $compile; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $compile = $injector.get('$compile'); scope = $injector.get('$rootScope').$new(); }) ); - describe('attributes', function() { - describe('suggestions', function() { + describe('attributes', function () { + describe('suggestions', function () { let element = null; const template = ``; - beforeEach(function() { + beforeEach(function () { element = $compile(template)(scope); scope.$apply(() => { scope.list = [{ name: 'suggestion1' }, { name: 'suggestion2' }, { name: 'suggestion3' }]; }); }); - it('are rendered', function() { + it('are rendered', function () { expect(element.find('[data-test-subj="timelionSuggestionListItem"]').length).to.be( scope.list.length ); diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/timelion_expression_suggestions.js b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/timelion_expression_suggestions.js index c560b213731e3..5d8168a3197ca 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/timelion_expression_suggestions.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_expression_suggestions/timelion_expression_suggestions.js @@ -31,9 +31,9 @@ export function TimelionExpressionSuggestions() { }, replace: true, template, - link: function(scope) { + link: function (scope) { // This will prevent the expression input from losing focus. - scope.onMouseDown = e => e.preventDefault(); + scope.onMouseDown = (e) => e.preventDefault(); }, }; } diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_grid.js b/src/legacy/core_plugins/timelion/public/directives/timelion_grid.js index 3ef65f60d2ef4..256c35331d016 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_grid.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_grid.js @@ -20,27 +20,27 @@ import $ from 'jquery'; const app = require('ui/modules').get('apps/timelion', []); -app.directive('timelionGrid', function() { +app.directive('timelionGrid', function () { return { restrict: 'A', scope: { timelionGridRows: '=', timelionGridColumns: '=', }, - link: function($scope, $elem) { + link: function ($scope, $elem) { function init() { setDimensions(); } - $scope.$on('$destroy', function() { + $scope.$on('$destroy', function () { $(window).off('resize'); //remove the handler added earlier }); - $(window).resize(function() { + $(window).resize(function () { setDimensions(); }); - $scope.$watchMulti(['timelionGridColumns', 'timelionGridRows'], function() { + $scope.$watchMulti(['timelionGridColumns', 'timelionGridRows'], function () { setDimensions(); }); diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_help/timelion_help.js b/src/legacy/core_plugins/timelion/public/directives/timelion_help/timelion_help.js index e152ca165c810..25f3df13153ba 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_help/timelion_help.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_help/timelion_help.js @@ -26,18 +26,18 @@ import '../../components/timelionhelp_tabs_directive'; const app = uiModules.get('apps/timelion', []); -app.directive('timelionHelp', function($http) { +app.directive('timelionHelp', function ($http) { return { restrict: 'E', template, - controller: function($scope) { + controller: function ($scope) { $scope.functions = { list: [], details: null, }; $scope.activeTab = 'funcref'; - $scope.activateTab = function(tabName) { + $scope.activateTab = function (tabName) { $scope.activeTab = tabName; }; @@ -123,19 +123,19 @@ app.directive('timelionHelp', function($http) { } function getFunctions() { - return $http.get('../api/timelion/functions').then(function(resp) { + return $http.get('../api/timelion/functions').then(function (resp) { $scope.functions.list = resp.data; }); } - $scope.recheckElasticsearch = function() { + $scope.recheckElasticsearch = function () { $scope.es.valid = null; - checkElasticsearch().then(function(valid) { + checkElasticsearch().then(function (valid) { if (!valid) $scope.es.invalidCount++; }); }; function checkElasticsearch() { - return $http.get('../api/timelion/validate/es').then(function(resp) { + return $http.get('../api/timelion/validate/es').then(function (resp) { if (resp.data.ok) { $scope.es.valid = true; $scope.es.stats = { @@ -145,7 +145,7 @@ app.directive('timelionHelp', function($http) { }; } else { $scope.es.valid = false; - $scope.es.invalidReason = (function() { + $scope.es.invalidReason = (function () { try { const esResp = JSON.parse(resp.data.resp.response); return _.get(esResp, 'error.root_cause[0].reason'); diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_interval/timelion_interval.js b/src/legacy/core_plugins/timelion/public/directives/timelion_interval/timelion_interval.js index 4031916ce9708..577ee984e05c6 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_interval/timelion_interval.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_interval/timelion_interval.js @@ -29,7 +29,7 @@ export function TimelionInterval($timeout) { model: '=', }, template, - link: function($scope, $elem) { + link: function ($scope, $elem) { $scope.intervalOptions = ['auto', '1s', '1m', '1h', '1d', '1w', '1M', '1y', 'other']; $scope.intervalLabels = { auto: 'auto', @@ -43,7 +43,7 @@ export function TimelionInterval($timeout) { other: 'other', }; - $scope.$watch('model', function(newVal, oldVal) { + $scope.$watch('model', function (newVal, oldVal) { // Only run this on initialization if (newVal !== oldVal || oldVal == null) return; @@ -58,13 +58,13 @@ export function TimelionInterval($timeout) { } }); - $scope.$watch('interval', function(newVal, oldVal) { + $scope.$watch('interval', function (newVal, oldVal) { if (newVal === oldVal) return; if (newVal === 'other') { $scope.otherInterval = oldVal; $scope.model = $scope.otherInterval; - $timeout(function() { + $timeout(function () { $('input', $elem).select(); }, 0); } else { @@ -73,7 +73,7 @@ export function TimelionInterval($timeout) { } }); - $scope.$watch('otherInterval', function(newVal, oldVal) { + $scope.$watch('otherInterval', function (newVal, oldVal) { if (newVal === oldVal) return; $scope.model = newVal; }); diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_load_sheet.js b/src/legacy/core_plugins/timelion/public/directives/timelion_load_sheet.js index cf74026791ef1..d80770cbc2ae1 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_load_sheet.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_load_sheet.js @@ -21,7 +21,7 @@ import { uiModules } from 'ui/modules'; import template from 'plugins/timelion/partials/load_sheet.html'; const app = uiModules.get('apps/timelion', []); -app.directive('timelionLoad', function() { +app.directive('timelionLoad', function () { return { replace: true, restrict: 'E', diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_options_sheet.js b/src/legacy/core_plugins/timelion/public/directives/timelion_options_sheet.js index f41138fe5f382..067c831f09de5 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_options_sheet.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_options_sheet.js @@ -21,7 +21,7 @@ import { uiModules } from 'ui/modules'; import template from 'plugins/timelion/partials/sheet_options.html'; const app = uiModules.get('apps/timelion', []); -app.directive('timelionOptions', function() { +app.directive('timelionOptions', function () { return { replace: true, restrict: 'E', diff --git a/src/legacy/core_plugins/timelion/public/directives/timelion_save_sheet.js b/src/legacy/core_plugins/timelion/public/directives/timelion_save_sheet.js index 03d17d95b43d1..6dd44a10dc48c 100644 --- a/src/legacy/core_plugins/timelion/public/directives/timelion_save_sheet.js +++ b/src/legacy/core_plugins/timelion/public/directives/timelion_save_sheet.js @@ -21,7 +21,7 @@ import { uiModules } from 'ui/modules'; import saveTemplate from 'plugins/timelion/partials/save_sheet.html'; const app = uiModules.get('apps/timelion', []); -app.directive('timelionSave', function() { +app.directive('timelionSave', function () { return { replace: true, restrict: 'E', diff --git a/src/legacy/core_plugins/timelion/public/lib/observe_resize.js b/src/legacy/core_plugins/timelion/public/lib/observe_resize.js index a75f2d7c6a713..62962e38c196e 100644 --- a/src/legacy/core_plugins/timelion/public/lib/observe_resize.js +++ b/src/legacy/core_plugins/timelion/public/lib/observe_resize.js @@ -17,7 +17,7 @@ * under the License. */ -export default function($elem, fn, frequency) { +export default function ($elem, fn, frequency) { frequency = frequency || 500; let currentHeight = $elem.height(); let currentWidth = $elem.width(); @@ -25,7 +25,7 @@ export default function($elem, fn, frequency) { let timeout; function checkLoop() { - timeout = setTimeout(function() { + timeout = setTimeout(function () { if (currentHeight !== $elem.height() || currentWidth !== $elem.width()) { currentHeight = $elem.height(); currentWidth = $elem.width(); @@ -38,7 +38,7 @@ export default function($elem, fn, frequency) { checkLoop(); - return function() { + return function () { clearTimeout(timeout); }; } diff --git a/src/legacy/core_plugins/timelion/public/panels/timechart/schema.ts b/src/legacy/core_plugins/timelion/public/panels/timechart/schema.ts index 34b389f5ff4ce..b1999eb4b483c 100644 --- a/src/legacy/core_plugins/timelion/public/panels/timechart/schema.ts +++ b/src/legacy/core_plugins/timelion/public/panels/timechart/schema.ts @@ -43,7 +43,7 @@ const DEBOUNCE_DELAY = 50; export function timechartFn(dependencies: TimelionVisualizationDependencies) { const { $rootScope, $compile, uiSettings } = dependencies; - return function() { + return function () { return { help: 'Draw a timeseries chart', render($scope: any, $elem: any) { @@ -157,7 +157,7 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { }); drawPlot($scope.chart); } - $scope.highlightSeries = _.debounce(function(id: any) { + $scope.highlightSeries = _.debounce(function (id: any) { if (highlightedSeries === id) { return; } @@ -172,50 +172,50 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { }); drawPlot($scope.chart); }, DEBOUNCE_DELAY); - $scope.focusSeries = function(id: any) { + $scope.focusSeries = function (id: any) { focusedSeries = id; $scope.highlightSeries(id); }; - $scope.toggleSeries = function(id: any) { + $scope.toggleSeries = function (id: any) { const series = $scope.chart[id]; series._hide = !series._hide; drawPlot($scope.chart); }; - const cancelResize = observeResize($elem, function() { + const cancelResize = observeResize($elem, function () { drawPlot($scope.chart); }); - $scope.$on('$destroy', function() { + $scope.$on('$destroy', function () { cancelResize(); $elem.off('plothover'); $elem.off('plotselected'); $elem.off('mouseleave'); }); - $elem.on('plothover', function(event: any, pos: any, item: any) { + $elem.on('plothover', function (event: any, pos: any, item: any) { $rootScope.$broadcast('timelionPlotHover', event, pos, item); }); - $elem.on('plotselected', function(event: any, ranges: any) { + $elem.on('plotselected', function (event: any, ranges: any) { timefilter.setTime({ from: moment(ranges.xaxis.from), to: moment(ranges.xaxis.to), }); }); - $elem.on('mouseleave', function() { + $elem.on('mouseleave', function () { $rootScope.$broadcast('timelionPlotLeave'); }); - $scope.$on('timelionPlotHover', function(angularEvent: any, flotEvent: any, pos: any) { + $scope.$on('timelionPlotHover', function (angularEvent: any, flotEvent: any, pos: any) { if (!$scope.plot) return; $scope.plot.setCrosshair(pos); debouncedSetLegendNumbers(pos); }); - $scope.$on('timelionPlotLeave', function() { + $scope.$on('timelionPlotLeave', function () { if (!$scope.plot) return; $scope.plot.clearCrosshair(); clearLegendNumbers(); @@ -277,7 +277,7 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { if (legendCaption) { legendCaption.html(emptyCaption); } - _.each(legendValueNumbers, function(num) { + _.each(legendValueNumbers, function (num) { $(num).empty(); }); } @@ -293,10 +293,7 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { return; } - const title = _(plotConfig) - .map('_title') - .compact() - .last() as any; + const title = _(plotConfig).map('_title').compact().last() as any; $('.chart-top-title', $elem).text(title == null ? '' : title); const options = _.cloneDeep(defaultOptions) as any; @@ -313,7 +310,7 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { const format = getxAxisFormatter(interval); // Use moment to format ticks so we get timezone correction - options.xaxis.tickFormatter = function(val: any) { + options.xaxis.tickFormatter = function (val: any) { return moment(val).format(format); }; @@ -324,7 +321,7 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { $elem.width() / (format.length * tickLetterWidth + tickPadding) ); - const series = _.map(plotConfig, function(serie: any, index) { + const series = _.map(plotConfig, function (serie: any, index) { serie = _.cloneDeep( _.defaults(serie, { shadowSize: 0, @@ -349,7 +346,7 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { } if (serie._global) { - _.merge(options, serie._global, function(objVal, srcVal) { + _.merge(options, serie._global, function (objVal, srcVal) { // This is kind of gross, it means that you can't replace a global value with a null // best you can do is an empty string. Deal with it. if (objVal == null) return srcVal; @@ -383,7 +380,7 @@ export function timechartFn(dependencies: TimelionVisualizationDependencies) { legendScope = $scope.$new(); // Used to toggle the series, and for displaying values on hover legendValueNumbers = canvasElem.find('.ngLegendValueNumber'); - _.each(canvasElem.find('.ngLegendValue'), function(elem) { + _.each(canvasElem.find('.ngLegendValue'), function (elem) { $compile(elem)(legendScope); }); diff --git a/src/legacy/core_plugins/timelion/public/services/saved_sheets.ts b/src/legacy/core_plugins/timelion/public/services/saved_sheets.ts index e7f431a178ea0..1fb29de83d3d7 100644 --- a/src/legacy/core_plugins/timelion/public/services/saved_sheets.ts +++ b/src/legacy/core_plugins/timelion/public/services/saved_sheets.ts @@ -40,7 +40,7 @@ export const savedSheetLoader = new SavedObjectLoader( savedObjectsClient, npStart.core.chrome ); -savedSheetLoader.urlFor = id => `#/${encodeURIComponent(id)}`; +savedSheetLoader.urlFor = (id) => `#/${encodeURIComponent(id)}`; // Customize loader properties since adding an 's' on type doesn't work for type 'timelion-sheet'. savedSheetLoader.loaderProperties = { name: 'timelion-sheet', diff --git a/src/legacy/core_plugins/timelion/public/shim/timelion_legacy_module.ts b/src/legacy/core_plugins/timelion/public/shim/timelion_legacy_module.ts index 8fadf223e1807..8122259f1c991 100644 --- a/src/legacy/core_plugins/timelion/public/shim/timelion_legacy_module.ts +++ b/src/legacy/core_plugins/timelion/public/shim/timelion_legacy_module.ts @@ -41,7 +41,7 @@ export const initTimelionLegacyModule = once((timelionPanels: Map uiModules .get('apps/timelion', []) - .controller('TimelionVisController', function($scope: any) { + .controller('TimelionVisController', function ($scope: any) { $scope.$on('timelionChartRendered', (event: any) => { event.stopPropagation(); $scope.renderComplete(); diff --git a/src/legacy/deprecation/__tests__/create_transform.js b/src/legacy/deprecation/__tests__/create_transform.js index 5e0616b729c06..d3838da5c3399 100644 --- a/src/legacy/deprecation/__tests__/create_transform.js +++ b/src/legacy/deprecation/__tests__/create_transform.js @@ -21,14 +21,14 @@ import { createTransform } from '../create_transform'; import expect from '@kbn/expect'; import sinon from 'sinon'; -describe('deprecation', function() { - describe('createTransform', function() { - it(`doesn't modify settings parameter`, function() { +describe('deprecation', function () { + describe('createTransform', function () { + it(`doesn't modify settings parameter`, function () { const settings = { original: true, }; const deprecations = [ - settings => { + (settings) => { settings.original = false; }, ]; @@ -36,22 +36,22 @@ describe('deprecation', function() { expect(settings.original).to.be(true); }); - it('calls single deprecation in array', function() { + it('calls single deprecation in array', function () { const deprecations = [sinon.spy()]; createTransform(deprecations)({}); expect(deprecations[0].calledOnce).to.be(true); }); - it('calls multiple deprecations in array', function() { + it('calls multiple deprecations in array', function () { const deprecations = [sinon.spy(), sinon.spy()]; createTransform(deprecations)({}); expect(deprecations[0].calledOnce).to.be(true); expect(deprecations[1].calledOnce).to.be(true); }); - it('passes log function to deprecation', function() { + it('passes log function to deprecation', function () { const deprecation = sinon.spy(); - const log = function() {}; + const log = function () {}; createTransform([deprecation])({}, log); expect(deprecation.args[0][1]).to.be(log); }); diff --git a/src/legacy/deprecation/create_transform.js b/src/legacy/deprecation/create_transform.js index 58418e3f50def..72e8e153ed819 100644 --- a/src/legacy/deprecation/create_transform.js +++ b/src/legacy/deprecation/create_transform.js @@ -24,7 +24,7 @@ export function createTransform(deprecations) { return (settings, log = noop) => { const result = clone(settings); - forEach(deprecations, deprecation => { + forEach(deprecations, (deprecation) => { deprecation(result, log); }); diff --git a/src/legacy/deprecation/deprecations/__tests__/rename.js b/src/legacy/deprecation/deprecations/__tests__/rename.js index 56b1c16d1607b..47c6b3257ff69 100644 --- a/src/legacy/deprecation/deprecations/__tests__/rename.js +++ b/src/legacy/deprecation/deprecations/__tests__/rename.js @@ -21,9 +21,9 @@ import expect from '@kbn/expect'; import { rename } from '../rename'; import sinon from 'sinon'; -describe('deprecation/deprecations', function() { - describe('rename', function() { - it('should rename simple property', function() { +describe('deprecation/deprecations', function () { + describe('rename', function () { + it('should rename simple property', function () { const value = 'value'; const settings = { before: value, @@ -34,7 +34,7 @@ describe('deprecation/deprecations', function() { expect(settings.after).to.be(value); }); - it('should rename nested property', function() { + it('should rename nested property', function () { const value = 'value'; const settings = { someObject: { @@ -47,7 +47,7 @@ describe('deprecation/deprecations', function() { expect(settings.someObject.after).to.be(value); }); - it('should rename property, even when the value is null', function() { + it('should rename property, even when the value is null', function () { const value = null; const settings = { before: value, @@ -58,7 +58,7 @@ describe('deprecation/deprecations', function() { expect(settings.after).to.be(null); }); - it(`shouldn't log when a rename doesn't occur`, function() { + it(`shouldn't log when a rename doesn't occur`, function () { const settings = { exists: true, }; @@ -68,7 +68,7 @@ describe('deprecation/deprecations', function() { expect(log.called).to.be(false); }); - it('should log when a rename does occur', function() { + it('should log when a rename does occur', function () { const settings = { exists: true, }; diff --git a/src/legacy/deprecation/deprecations/__tests__/unused.js b/src/legacy/deprecation/deprecations/__tests__/unused.js index 3f049a4ff678c..4907c2b166989 100644 --- a/src/legacy/deprecation/deprecations/__tests__/unused.js +++ b/src/legacy/deprecation/deprecations/__tests__/unused.js @@ -21,9 +21,9 @@ import expect from '@kbn/expect'; import sinon from 'sinon'; import { unused } from '../unused'; -describe('deprecation/deprecations', function() { - describe('unused', function() { - it('should remove unused setting', function() { +describe('deprecation/deprecations', function () { + describe('unused', function () { + it('should remove unused setting', function () { const settings = { old: true, }; @@ -32,7 +32,7 @@ describe('deprecation/deprecations', function() { expect(settings.old).to.be(undefined); }); - it(`shouldn't remove used setting`, function() { + it(`shouldn't remove used setting`, function () { const value = 'value'; const settings = { new: value, @@ -42,7 +42,7 @@ describe('deprecation/deprecations', function() { expect(settings.new).to.be(value); }); - it('should remove unused setting, even when null', function() { + it('should remove unused setting, even when null', function () { const settings = { old: null, }; @@ -51,7 +51,7 @@ describe('deprecation/deprecations', function() { expect(settings.old).to.be(undefined); }); - it('should log when removing unused setting', function() { + it('should log when removing unused setting', function () { const settings = { old: true, }; @@ -63,7 +63,7 @@ describe('deprecation/deprecations', function() { expect(log.args[0][0]).to.match(/old.+deprecated/); }); - it(`shouldn't log when no setting is unused`, function() { + it(`shouldn't log when no setting is unused`, function () { const settings = { new: true, }; diff --git a/src/legacy/plugin_discovery/__tests__/find_plugin_specs.js b/src/legacy/plugin_discovery/__tests__/find_plugin_specs.js index 5544c0b483aa9..e6af23d69c549 100644 --- a/src/legacy/plugin_discovery/__tests__/find_plugin_specs.js +++ b/src/legacy/plugin_discovery/__tests__/find_plugin_specs.js @@ -29,7 +29,7 @@ const PLUGIN_FIXTURES = resolve(__dirname, 'fixtures/plugins'); const CONFLICT_FIXTURES = resolve(__dirname, 'fixtures/conflicts'); describe('plugin discovery', () => { - describe('findPluginSpecs()', function() { + describe('findPluginSpecs()', function () { this.timeout(10000); describe('spec$', () => { @@ -46,10 +46,10 @@ describe('plugin discovery', () => { const specs = await spec$.pipe(toArray()).toPromise(); expect(specs).to.have.length(3); - specs.forEach(spec => { + specs.forEach((spec) => { expect(spec).to.be.a(PluginSpec); }); - expect(specs.map(s => s.getId()).sort()).to.eql(['bar:one', 'bar:two', 'foo']); + expect(specs.map((s) => s.getId()).sort()).to.eql(['bar:one', 'bar:two', 'foo']); }); it('finds all specs in scanDirs', async () => { @@ -64,10 +64,10 @@ describe('plugin discovery', () => { const specs = await spec$.pipe(toArray()).toPromise(); expect(specs).to.have.length(3); - specs.forEach(spec => { + specs.forEach((spec) => { expect(spec).to.be.a(PluginSpec); }); - expect(specs.map(s => s.getId()).sort()).to.eql(['bar:one', 'bar:two', 'foo']); + expect(specs.map((s) => s.getId()).sort()).to.eql(['bar:one', 'bar:two', 'foo']); }); it('does not find disabled plugins', async () => { @@ -87,10 +87,10 @@ describe('plugin discovery', () => { const specs = await spec$.pipe(toArray()).toPromise(); expect(specs).to.have.length(2); - specs.forEach(spec => { + specs.forEach((spec) => { expect(spec).to.be.a(PluginSpec); }); - expect(specs.map(s => s.getId()).sort()).to.eql(['bar:two', 'foo']); + expect(specs.map((s) => s.getId()).sort()).to.eql(['bar:two', 'foo']); }); it('dedupes duplicate packs', async () => { @@ -110,10 +110,10 @@ describe('plugin discovery', () => { const specs = await spec$.pipe(toArray()).toPromise(); expect(specs).to.have.length(3); - specs.forEach(spec => { + specs.forEach((spec) => { expect(spec).to.be.a(PluginSpec); }); - expect(specs.map(s => s.getId()).sort()).to.eql(['bar:one', 'bar:two', 'foo']); + expect(specs.map((s) => s.getId()).sort()).to.eql(['bar:one', 'bar:two', 'foo']); }); describe('conflicting plugin spec ids', () => { @@ -137,9 +137,9 @@ describe('plugin discovery', () => { }); describe('packageJson$', () => { - const checkPackageJsons = packageJsons => { + const checkPackageJsons = (packageJsons) => { expect(packageJsons).to.have.length(2); - const package1 = packageJsons.find(packageJson => + const package1 = packageJsons.find((packageJson) => isEqual( { directoryPath: resolve(PLUGIN_FIXTURES, 'foo'), @@ -152,7 +152,7 @@ describe('plugin discovery', () => { ) ); expect(package1).to.be.an(Object); - const package2 = packageJsons.find(packageJson => + const package2 = packageJsons.find((packageJson) => isEqual( { directoryPath: resolve(PLUGIN_FIXTURES, 'bar'), diff --git a/src/legacy/plugin_discovery/__tests__/fixtures/conflicts/foo/index.js b/src/legacy/plugin_discovery/__tests__/fixtures/conflicts/foo/index.js index 1ad8b1a277b84..fcbe3487463b7 100644 --- a/src/legacy/plugin_discovery/__tests__/fixtures/conflicts/foo/index.js +++ b/src/legacy/plugin_discovery/__tests__/fixtures/conflicts/foo/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function(kibana) { +export default function (kibana) { return [ // two plugins exported without ids will both inherit // the id of the pack and conflict diff --git a/src/legacy/plugin_discovery/__tests__/fixtures/plugins/bar/index.js b/src/legacy/plugin_discovery/__tests__/fixtures/plugins/bar/index.js index bcc9619a517cf..0eef126f2255a 100644 --- a/src/legacy/plugin_discovery/__tests__/fixtures/plugins/bar/index.js +++ b/src/legacy/plugin_discovery/__tests__/fixtures/plugins/bar/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default function(kibana) { +export default function (kibana) { return [ new kibana.Plugin({ id: 'bar:one', diff --git a/src/legacy/plugin_discovery/__tests__/fixtures/plugins/foo/index.js b/src/legacy/plugin_discovery/__tests__/fixtures/plugins/foo/index.js index 2ccd8f438eec7..e43a1dcedb372 100644 --- a/src/legacy/plugin_discovery/__tests__/fixtures/plugins/foo/index.js +++ b/src/legacy/plugin_discovery/__tests__/fixtures/plugins/foo/index.js @@ -17,7 +17,7 @@ * under the License. */ -module.exports = function(kibana) { +module.exports = function (kibana) { return new kibana.Plugin({ id: 'foo', }); diff --git a/src/legacy/plugin_discovery/find_plugin_specs.js b/src/legacy/plugin_discovery/find_plugin_specs.js index efb9bf47ab71c..b97476bb456a5 100644 --- a/src/legacy/plugin_discovery/find_plugin_specs.js +++ b/src/legacy/plugin_discovery/find_plugin_specs.js @@ -52,7 +52,7 @@ function bufferAllResults(observable) { // buffer all results into a single array toArray(), // merge the array back into the stream when complete - mergeMap(array => array) + mergeMap((array) => array) ); } @@ -110,7 +110,7 @@ export function findPluginSpecs(settings, configToMutate) { // find plugin packs in configured paths/dirs const packageJson$ = config$.pipe( - mergeMap(config => + mergeMap((config) => Rx.merge( ...config.get('plugins.paths').map(createPackageJsonAtPath$), ...config.get('plugins.scanDirs').map(createPackageJsonsInDirectory$) @@ -123,19 +123,19 @@ export function findPluginSpecs(settings, configToMutate) { const pack$ = createPack$(packageJson$).pipe(share()); const extendConfig$ = config$.pipe( - mergeMap(config => + mergeMap((config) => pack$.pipe( // get the specs for each found plugin pack mergeMap(({ pack }) => (pack ? pack.getPluginSpecs() : [])), // make sure that none of the plugin specs have conflicting ids, fail // early if conflicts detected or merge the specs back into the stream toArray(), - mergeMap(allSpecs => { + mergeMap((allSpecs) => { for (const [id, specs] of groupSpecsById(allSpecs)) { if (specs.length > 1) { throw new Error( `Multiple plugins found with the id "${id}":\n${specs - .map(spec => ` - ${id} at ${spec.getPath()}`) + .map((spec) => ` - ${id} at ${spec.getPath()}`) .join('\n')}` ); } @@ -143,12 +143,12 @@ export function findPluginSpecs(settings, configToMutate) { return allSpecs; }), - mergeMap(async spec => { + mergeMap(async (spec) => { // extend the config service with this plugin spec and // collect its deprecations messages if some of its // settings are outdated const deprecations = []; - await extendConfigService(spec, config, settings, message => { + await extendConfigService(spec, config, settings, (message) => { deprecations.push({ spec, message }); }); @@ -173,7 +173,7 @@ export function findPluginSpecs(settings, configToMutate) { }), // determine which plugins are disabled before actually removing things from the config bufferAllResults, - tap(result => { + tap((result) => { for (const spec of result.disabledSpecs) { disableConfigExtension(spec, config); } @@ -186,46 +186,46 @@ export function findPluginSpecs(settings, configToMutate) { return { // package JSONs found when searching configure paths packageJson$: packageJson$.pipe( - mergeMap(result => (result.packageJson ? [result.packageJson] : [])) + mergeMap((result) => (result.packageJson ? [result.packageJson] : [])) ), // plugin packs found when searching configured paths - pack$: pack$.pipe(mergeMap(result => (result.pack ? [result.pack] : []))), + pack$: pack$.pipe(mergeMap((result) => (result.pack ? [result.pack] : []))), // errors caused by invalid directories of plugin directories invalidDirectoryError$: pack$.pipe( - mergeMap(result => (isInvalidDirectoryError(result.error) ? [result.error] : [])) + mergeMap((result) => (isInvalidDirectoryError(result.error) ? [result.error] : [])) ), // errors caused by directories that we expected to be plugin but were invalid invalidPackError$: pack$.pipe( - mergeMap(result => (isInvalidPackError(result.error) ? [result.error] : [])) + mergeMap((result) => (isInvalidPackError(result.error) ? [result.error] : [])) ), otherError$: pack$.pipe( - mergeMap(result => (isUnhandledError(result.error) ? [result.error] : [])) + mergeMap((result) => (isUnhandledError(result.error) ? [result.error] : [])) ), // { spec, message } objects produced when transforming deprecated // settings for a plugin spec - deprecation$: extendConfig$.pipe(mergeMap(result => result.deprecations)), + deprecation$: extendConfig$.pipe(mergeMap((result) => result.deprecations)), // the config service we extended with all of the plugin specs, // only emitted once it is fully extended by all extendedConfig$: extendConfig$.pipe( - mergeMap(result => result.config), + mergeMap((result) => result.config), filter(Boolean), last() ), // all enabled PluginSpec objects - spec$: extendConfig$.pipe(mergeMap(result => result.enabledSpecs)), + spec$: extendConfig$.pipe(mergeMap((result) => result.enabledSpecs)), // all disabled PluginSpec objects - disabledSpec$: extendConfig$.pipe(mergeMap(result => result.disabledSpecs)), + disabledSpec$: extendConfig$.pipe(mergeMap((result) => result.disabledSpecs)), // all PluginSpec objects that were disabled because their version was incompatible - invalidVersionSpec$: extendConfig$.pipe(mergeMap(result => result.invalidVersionSpecs)), + invalidVersionSpec$: extendConfig$.pipe(mergeMap((result) => result.invalidVersionSpecs)), }; } diff --git a/src/legacy/plugin_discovery/plugin_config/__tests__/extend_config_service.js b/src/legacy/plugin_discovery/plugin_config/__tests__/extend_config_service.js index 21f427a545b25..a74bfb872e99c 100644 --- a/src/legacy/plugin_discovery/plugin_config/__tests__/extend_config_service.js +++ b/src/legacy/plugin_discovery/plugin_config/__tests__/extend_config_service.js @@ -40,7 +40,7 @@ describe('plugin discovery/extend config service', () => { new Plugin({ configPrefix: 'foo.bar.baz', - config: Joi => + config: (Joi) => Joi.object({ enabled: Joi.boolean().default(true), test: Joi.string().default('bonk'), diff --git a/src/legacy/plugin_discovery/plugin_config/__tests__/schema.js b/src/legacy/plugin_discovery/plugin_config/__tests__/schema.js index e359b20be491d..78adb1e680e20 100644 --- a/src/legacy/plugin_discovery/plugin_config/__tests__/schema.js +++ b/src/legacy/plugin_discovery/plugin_config/__tests__/schema.js @@ -54,9 +54,7 @@ describe('plugin discovery/schema', () => { it('uses default schema when no config provider', async () => { const schema = await getSchema(createPluginSpec()); expect(schema).to.be.an('object'); - expect(schema) - .to.have.property('validate') - .a('function'); + expect(schema).to.have.property('validate').a('function'); expect(schema.validate({}).value).to.eql({ enabled: true, }); @@ -65,9 +63,7 @@ describe('plugin discovery/schema', () => { it('uses default schema when config returns falsy value', async () => { const schema = await getSchema(createPluginSpec(() => null)); expect(schema).to.be.an('object'); - expect(schema) - .to.have.property('validate') - .a('function'); + expect(schema).to.have.property('validate').a('function'); expect(schema.validate({}).value).to.eql({ enabled: true, }); @@ -76,9 +72,7 @@ describe('plugin discovery/schema', () => { it('uses default schema when config promise resolves to falsy value', async () => { const schema = await getSchema(createPluginSpec(() => Promise.resolve(null))); expect(schema).to.be.an('object'); - expect(schema) - .to.have.property('validate') - .a('function'); + expect(schema).to.have.property('validate').a('function'); expect(schema.validate({}).value).to.eql({ enabled: true, }); @@ -89,9 +83,7 @@ describe('plugin discovery/schema', () => { it('returns schema with enabled: false', async () => { const schema = await getStubSchema(); expect(schema).to.be.an('object'); - expect(schema) - .to.have.property('validate') - .a('function'); + expect(schema).to.have.property('validate').a('function'); expect(schema.validate({}).value).to.eql({ enabled: false, }); diff --git a/src/legacy/plugin_discovery/plugin_pack/__tests__/create_pack.js b/src/legacy/plugin_discovery/plugin_pack/__tests__/create_pack.js index d724b9add190c..b17bd69479ffa 100644 --- a/src/legacy/plugin_discovery/plugin_pack/__tests__/create_pack.js +++ b/src/legacy/plugin_discovery/plugin_pack/__tests__/create_pack.js @@ -39,9 +39,7 @@ describe('plugin discovery/create pack', () => { }, }, ]); - const results = await createPack$(packageJson$) - .pipe(toArray()) - .toPromise(); + const results = await createPack$(packageJson$).pipe(toArray()).toPromise(); expect(results).to.have.length(1); expect(results[0]).to.only.have.keys(['pack']); const { pack } = results[0]; @@ -58,31 +56,29 @@ describe('plugin discovery/create pack', () => { }, ]); - const results = await createPack$(packageJson$) - .pipe(toArray()) - .toPromise(); + const results = await createPack$(packageJson$).pipe(toArray()).toPromise(); expect(results).to.have.length(1); expect(results[0]).to.only.have.keys(['error']); const { error } = results[0]; await check(error); } it('default export is an object', () => - checkError(resolve(PLUGINS_DIR, 'exports_object'), error => { + checkError(resolve(PLUGINS_DIR, 'exports_object'), (error) => { assertInvalidPackError(error); expect(error.message).to.contain('must export a function'); })); it('default export is an number', () => - checkError(resolve(PLUGINS_DIR, 'exports_number'), error => { + checkError(resolve(PLUGINS_DIR, 'exports_number'), (error) => { assertInvalidPackError(error); expect(error.message).to.contain('must export a function'); })); it('default export is an string', () => - checkError(resolve(PLUGINS_DIR, 'exports_string'), error => { + checkError(resolve(PLUGINS_DIR, 'exports_string'), (error) => { assertInvalidPackError(error); expect(error.message).to.contain('must export a function'); })); it('directory with code that fails when required', () => - checkError(resolve(PLUGINS_DIR, 'broken_code'), error => { + checkError(resolve(PLUGINS_DIR, 'broken_code'), (error) => { expect(error.message).to.contain("Cannot find module 'does-not-exist'"); })); }); diff --git a/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/broken_code/index.js b/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/broken_code/index.js index 29bfa89e20399..bdb26504d6b6e 100644 --- a/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/broken_code/index.js +++ b/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/broken_code/index.js @@ -1,6 +1,6 @@ const brokenRequire = require('does-not-exist'); // eslint-disable-line -module.exports = function(kibana) { +module.exports = function (kibana) { return new kibana.Plugin({ id: 'foo', }); diff --git a/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/foo/index.js b/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/foo/index.js index 2ccd8f438eec7..e43a1dcedb372 100644 --- a/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/foo/index.js +++ b/src/legacy/plugin_discovery/plugin_pack/__tests__/fixtures/plugins/foo/index.js @@ -17,7 +17,7 @@ * under the License. */ -module.exports = function(kibana) { +module.exports = function (kibana) { return new kibana.Plugin({ id: 'foo', }); diff --git a/src/legacy/plugin_discovery/plugin_pack/__tests__/package_json_at_path.js b/src/legacy/plugin_discovery/plugin_pack/__tests__/package_json_at_path.js index a8913c0be531b..fa1033180954e 100644 --- a/src/legacy/plugin_discovery/plugin_pack/__tests__/package_json_at_path.js +++ b/src/legacy/plugin_discovery/plugin_pack/__tests__/package_json_at_path.js @@ -28,9 +28,7 @@ import { PLUGINS_DIR, assertInvalidPackError, assertInvalidDirectoryError } from describe('plugin discovery/plugin_pack', () => { describe('createPackageJsonAtPath$()', () => { it('returns an observable', () => { - expect(createPackageJsonAtPath$()) - .to.have.property('subscribe') - .a('function'); + expect(createPackageJsonAtPath$()).to.have.property('subscribe').a('function'); }); it('gets the default provider from prebuilt babel modules', async () => { const results = await createPackageJsonAtPath$(resolve(PLUGINS_DIR, 'prebuilt')) @@ -44,46 +42,44 @@ describe('plugin discovery/plugin_pack', () => { }); describe('errors emitted as { error } results', () => { async function checkError(path, check) { - const results = await createPackageJsonAtPath$(path) - .pipe(toArray()) - .toPromise(); + const results = await createPackageJsonAtPath$(path).pipe(toArray()).toPromise(); expect(results).to.have.length(1); expect(results[0]).to.only.have.keys(['error']); const { error } = results[0]; await check(error); } it('undefined path', () => - checkError(undefined, error => { + checkError(undefined, (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('path must be a string'); })); it('relative path', () => - checkError('plugins/foo', error => { + checkError('plugins/foo', (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('path must be absolute'); })); it('./relative path', () => - checkError('./plugins/foo', error => { + checkError('./plugins/foo', (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('path must be absolute'); })); it('non-existent path', () => - checkError(resolve(PLUGINS_DIR, 'baz'), error => { + checkError(resolve(PLUGINS_DIR, 'baz'), (error) => { assertInvalidPackError(error); expect(error.message).to.contain('must be a directory'); })); it('path to a file', () => - checkError(resolve(PLUGINS_DIR, 'index.js'), error => { + checkError(resolve(PLUGINS_DIR, 'index.js'), (error) => { assertInvalidPackError(error); expect(error.message).to.contain('must be a directory'); })); it('directory without a package.json', () => - checkError(resolve(PLUGINS_DIR, 'lib'), error => { + checkError(resolve(PLUGINS_DIR, 'lib'), (error) => { assertInvalidPackError(error); expect(error.message).to.contain('must have a package.json file'); })); it('directory with an invalid package.json', () => - checkError(resolve(PLUGINS_DIR, 'broken'), error => { + checkError(resolve(PLUGINS_DIR, 'broken'), (error) => { assertInvalidPackError(error); expect(error.message).to.contain('must have a valid package.json file'); })); diff --git a/src/legacy/plugin_discovery/plugin_pack/__tests__/package_jsons_in_directory.js b/src/legacy/plugin_discovery/plugin_pack/__tests__/package_jsons_in_directory.js index ea42d4d876bb9..37cb4cc064da7 100644 --- a/src/legacy/plugin_discovery/plugin_pack/__tests__/package_jsons_in_directory.js +++ b/src/legacy/plugin_discovery/plugin_pack/__tests__/package_jsons_in_directory.js @@ -30,9 +30,7 @@ describe('plugin discovery/packs in directory', () => { describe('createPackageJsonsInDirectory$()', () => { describe('errors emitted as { error } results', () => { async function checkError(path, check) { - const results = await createPackageJsonsInDirectory$(path) - .pipe(toArray()) - .toPromise(); + const results = await createPackageJsonsInDirectory$(path).pipe(toArray()).toPromise(); expect(results).to.have.length(1); expect(results[0]).to.only.have.keys('error'); const { error } = results[0]; @@ -40,42 +38,40 @@ describe('plugin discovery/packs in directory', () => { } it('undefined path', () => - checkError(undefined, error => { + checkError(undefined, (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('path must be a string'); })); it('relative path', () => - checkError('my/plugins', error => { + checkError('my/plugins', (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('path must be absolute'); })); it('./relative path', () => - checkError('./my/pluginsd', error => { + checkError('./my/pluginsd', (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('path must be absolute'); })); it('non-existent path', () => - checkError(resolve(PLUGINS_DIR, 'notreal'), error => { + checkError(resolve(PLUGINS_DIR, 'notreal'), (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('no such file or directory'); })); it('path to a file', () => - checkError(resolve(PLUGINS_DIR, 'index.js'), error => { + checkError(resolve(PLUGINS_DIR, 'index.js'), (error) => { assertInvalidDirectoryError(error); expect(error.message).to.contain('not a directory'); })); }); it('includes child errors for invalid packageJsons within a valid directory', async () => { - const results = await createPackageJsonsInDirectory$(PLUGINS_DIR) - .pipe(toArray()) - .toPromise(); + const results = await createPackageJsonsInDirectory$(PLUGINS_DIR).pipe(toArray()).toPromise(); - const errors = results.map(result => result.error).filter(Boolean); + const errors = results.map((result) => result.error).filter(Boolean); - const packageJsons = results.map(result => result.packageJson).filter(Boolean); + const packageJsons = results.map((result) => result.packageJson).filter(Boolean); - packageJsons.forEach(pack => expect(pack).to.be.an(Object)); + packageJsons.forEach((pack) => expect(pack).to.be.an(Object)); // there should be one result for each item in PLUGINS_DIR expect(results).to.have.length(8); // three of the fixtures are errors of some sort diff --git a/src/legacy/plugin_discovery/plugin_pack/__tests__/plugin_pack.js b/src/legacy/plugin_discovery/plugin_pack/__tests__/plugin_pack.js index 3ab08f138b184..769fcd74ce6fb 100644 --- a/src/legacy/plugin_discovery/plugin_pack/__tests__/plugin_pack.js +++ b/src/legacy/plugin_discovery/plugin_pack/__tests__/plugin_pack.js @@ -53,7 +53,7 @@ describe('plugin discovery/plugin pack', () => { pack.getPluginSpecs(); sinon.assert.calledOnce(provider); sinon.assert.calledWithExactly(provider, { - Plugin: sinon.match(Class => { + Plugin: sinon.match((Class) => { return Class.prototype instanceof PluginSpec; }, 'Subclass of PluginSpec'), }); @@ -96,7 +96,7 @@ describe('plugin discovery/plugin pack', () => { const otherPack = new PluginPack({ path: '/dev/null', pkg: { name: 'foo', version: 'kibana' }, - provider: api => { + provider: (api) => { OtherPluginSpecClass = api.Plugin; }, }); @@ -112,12 +112,12 @@ describe('plugin discovery/plugin pack', () => { new PluginPack({ provider: () => true }), new PluginPack({ provider: () => new Date() }), new PluginPack({ provider: () => /foo.*bar/ }), - new PluginPack({ provider: () => function() {} }), + new PluginPack({ provider: () => function () {} }), new PluginPack({ provider: () => new OtherPluginSpecClass({}) }), ]; for (const pack of badPacks) { - expect(() => pack.getPluginSpecs()).to.throwError(error => { + expect(() => pack.getPluginSpecs()).to.throwError((error) => { expect(error.message).to.contain('unexpected plugin export'); }); } diff --git a/src/legacy/plugin_discovery/plugin_pack/create_pack.js b/src/legacy/plugin_discovery/plugin_pack/create_pack.js index 62e7d9f1914bf..189c2ea324103 100644 --- a/src/legacy/plugin_discovery/plugin_pack/create_pack.js +++ b/src/legacy/plugin_discovery/plugin_pack/create_pack.js @@ -33,7 +33,7 @@ function createPack(packageJson) { return new PluginPack({ path: packageJson.directoryPath, pkg: packageJson.contents, provider }); } -export const createPack$ = packageJson$ => +export const createPack$ = (packageJson$) => packageJson$.pipe( map(({ error, packageJson }) => { if (error) { @@ -50,5 +50,5 @@ export const createPack$ = packageJson$ => }), // createPack can throw errors, and we want them to be represented // like the errors we consume from createPackageJsonAtPath/Directory - catchError(error => [{ error }]) + catchError((error) => [{ error }]) ); diff --git a/src/legacy/plugin_discovery/plugin_pack/lib/fs.js b/src/legacy/plugin_discovery/plugin_pack/lib/fs.js index e2af5fd7e5b10..2b531e314df52 100644 --- a/src/legacy/plugin_discovery/plugin_pack/lib/fs.js +++ b/src/legacy/plugin_discovery/plugin_pack/lib/fs.js @@ -38,7 +38,7 @@ function assertAbsolutePath(path) { async function statTest(path, test) { try { - const stats = await fcb(cb => stat(path, cb)); + const stats = await fcb((cb) => stat(path, cb)); return Boolean(test(stats)); } catch (error) { if (error.code !== 'ENOENT') { @@ -55,7 +55,7 @@ async function statTest(path, test) { */ export async function isDirectory(path) { assertAbsolutePath(path); - return await statTest(path, stat => stat.isDirectory()); + return await statTest(path, (stat) => stat.isDirectory()); } /** @@ -63,18 +63,18 @@ export async function isDirectory(path) { * @param {string} path * @return {Promise>} */ -export const createChildDirectory$ = path => +export const createChildDirectory$ = (path) => Rx.defer(() => { assertAbsolutePath(path); - return fcb(cb => readdir(path, cb)); + return fcb((cb) => readdir(path, cb)); }).pipe( - catchError(error => { + catchError((error) => { throw createInvalidDirectoryError(error, path); }), mergeAll(), - filter(name => !name.startsWith('.')), - map(name => resolve(path, name)), - mergeMap(async absolute => { + filter((name) => !name.startsWith('.')), + map((name) => resolve(path, name)), + mergeMap(async (absolute) => { if (await isDirectory(absolute)) { return [absolute]; } else { diff --git a/src/legacy/plugin_discovery/plugin_pack/package_json_at_path.js b/src/legacy/plugin_discovery/plugin_pack/package_json_at_path.js index aa21d8242f3fa..18629ef3ea802 100644 --- a/src/legacy/plugin_discovery/plugin_pack/package_json_at_path.js +++ b/src/legacy/plugin_discovery/plugin_pack/package_json_at_path.js @@ -52,11 +52,11 @@ async function createPackageJsonAtPath(path) { }; } -export const createPackageJsonAtPath$ = path => +export const createPackageJsonAtPath$ = (path) => // If plugin directory contains manifest file, we should skip it since it // should have been handled by the core plugin system already. Rx.defer(() => isNewPlatformPlugin(path)).pipe( - mergeMap(isNewPlatformPlugin => (isNewPlatformPlugin ? [] : createPackageJsonAtPath(path))), - map(packageJson => ({ packageJson })), - catchError(error => [{ error }]) + mergeMap((isNewPlatformPlugin) => (isNewPlatformPlugin ? [] : createPackageJsonAtPath(path))), + map((packageJson) => ({ packageJson })), + catchError((error) => [{ error }]) ); diff --git a/src/legacy/plugin_discovery/plugin_pack/package_jsons_in_directory.js b/src/legacy/plugin_discovery/plugin_pack/package_jsons_in_directory.js index 2873f01d90c16..5f0977f4829b8 100644 --- a/src/legacy/plugin_discovery/plugin_pack/package_jsons_in_directory.js +++ b/src/legacy/plugin_discovery/plugin_pack/package_jsons_in_directory.js @@ -36,10 +36,10 @@ import { createPackageJsonAtPath$ } from './package_json_at_path'; * @param {String} path * @return {Array<{pack}|{error}>} */ -export const createPackageJsonsInDirectory$ = path => +export const createPackageJsonsInDirectory$ = (path) => createChildDirectory$(path).pipe( mergeMap(createPackageJsonAtPath$), - catchError(error => { + catchError((error) => { // this error is produced by createChildDirectory$() when the path // is invalid, we return them as an error result similar to how // createPackAtPath$ works when it finds invalid packs in a directory diff --git a/src/legacy/plugin_discovery/plugin_pack/plugin_pack.js b/src/legacy/plugin_discovery/plugin_pack/plugin_pack.js index 0734a85d587a9..1baf3d104ca84 100644 --- a/src/legacy/plugin_discovery/plugin_pack/plugin_pack.js +++ b/src/legacy/plugin_discovery/plugin_pack/plugin_pack.js @@ -63,7 +63,7 @@ export class PluginPack { const specs = [].concat(result === undefined ? [] : result); // verify that all specs are instances of passed "Plugin" class - specs.forEach(spec => { + specs.forEach((spec) => { if (!(spec instanceof api.Plugin)) { throw new TypeError('unexpected plugin export ' + inspect(spec)); } diff --git a/src/legacy/plugin_discovery/plugin_spec/__tests__/plugin_spec.js b/src/legacy/plugin_discovery/plugin_spec/__tests__/plugin_spec.js index 3649de165f0aa..02675f0bd60f8 100644 --- a/src/legacy/plugin_discovery/plugin_spec/__tests__/plugin_spec.js +++ b/src/legacy/plugin_discovery/plugin_spec/__tests__/plugin_spec.js @@ -36,21 +36,21 @@ describe('plugin discovery/plugin spec', () => { describe('validation', () => { it('throws if missing spec.id AND Pack has no name', () => { const pack = new PluginPack({ pkg: {} }); - expect(() => new PluginSpec(pack, {})).to.throwError(error => { + expect(() => new PluginSpec(pack, {})).to.throwError((error) => { expect(error.message).to.contain('Unable to determine plugin id'); }); }); it('throws if missing spec.kibanaVersion AND Pack has no version', () => { const pack = new PluginPack({ pkg: { name: 'foo' } }); - expect(() => new PluginSpec(pack, {})).to.throwError(error => { + expect(() => new PluginSpec(pack, {})).to.throwError((error) => { expect(error.message).to.contain('Unable to determine plugin version'); }); }); it('throws if spec.require is defined, but not an array', () => { function assert(require) { - expect(() => new PluginSpec(fooPack, { require })).to.throwError(error => { + expect(() => new PluginSpec(fooPack, { require })).to.throwError((error) => { expect(error.message).to.contain('"plugin.require" must be an array of plugin ids'); }); } @@ -65,7 +65,7 @@ describe('plugin discovery/plugin spec', () => { it('throws if spec.publicDir is truthy and not a string', () => { function assert(publicDir) { - expect(() => new PluginSpec(fooPack, { publicDir })).to.throwError(error => { + expect(() => new PluginSpec(fooPack, { publicDir })).to.throwError((error) => { expect(error.message).to.contain( `The "path" argument must be of type string. Received type ${typeof publicDir}` ); @@ -73,14 +73,14 @@ describe('plugin discovery/plugin spec', () => { } assert(1); - assert(function() {}); + assert(function () {}); assert([]); assert(/a.*b/); }); it('throws if spec.publicDir is not an absolute path', () => { function assert(publicDir) { - expect(() => new PluginSpec(fooPack, { publicDir })).to.throwError(error => { + expect(() => new PluginSpec(fooPack, { publicDir })).to.throwError((error) => { expect(error.message).to.contain('plugin.publicDir must be an absolute path'); }); } @@ -91,7 +91,7 @@ describe('plugin discovery/plugin spec', () => { it('throws if spec.publicDir basename is not `public`', () => { function assert(publicDir) { - expect(() => new PluginSpec(fooPack, { publicDir })).to.throwError(error => { + expect(() => new PluginSpec(fooPack, { publicDir })).to.throwError((error) => { expect(error.message).to.contain('must end with a "public" directory'); }); } @@ -171,13 +171,13 @@ describe('plugin discovery/plugin spec', () => { it('throws if not passed a config service', () => { const { spec } = setup('a.b.c', () => true); - expect(() => spec.isEnabled()).to.throwError(error => { + expect(() => spec.isEnabled()).to.throwError((error) => { expect(error.message).to.contain('must be called with a config service'); }); - expect(() => spec.isEnabled(null)).to.throwError(error => { + expect(() => spec.isEnabled(null)).to.throwError((error) => { expect(error.message).to.contain('must be called with a config service'); }); - expect(() => spec.isEnabled({ get: () => {} })).to.throwError(error => { + expect(() => spec.isEnabled({ get: () => {} })).to.throwError((error) => { expect(error.message).to.contain('must be called with a config service'); }); }); @@ -214,13 +214,13 @@ describe('plugin discovery/plugin spec', () => { it('throws if not passed a config service', () => { const { spec } = setup(() => true); - expect(() => spec.isEnabled()).to.throwError(error => { + expect(() => spec.isEnabled()).to.throwError((error) => { expect(error.message).to.contain('must be called with a config service'); }); - expect(() => spec.isEnabled(null)).to.throwError(error => { + expect(() => spec.isEnabled(null)).to.throwError((error) => { expect(error.message).to.contain('must be called with a config service'); }); - expect(() => spec.isEnabled({ get: () => {} })).to.throwError(error => { + expect(() => spec.isEnabled({ get: () => {} })).to.throwError((error) => { expect(error.message).to.contain('must be called with a config service'); }); }); diff --git a/src/legacy/server/capabilities/capabilities_mixin.ts b/src/legacy/server/capabilities/capabilities_mixin.ts index 23a0c35414ae6..1f8c869f17f66 100644 --- a/src/legacy/server/capabilities/capabilities_mixin.ts +++ b/src/legacy/server/capabilities/capabilities_mixin.ts @@ -24,12 +24,12 @@ export async function capabilitiesMixin(kbnServer: KbnServer, server: Server) { const registerLegacyCapabilities = async () => { const capabilitiesList = await Promise.all( kbnServer.pluginSpecs - .map(spec => spec.getUiCapabilitiesProvider()) - .filter(provider => !!provider) - .map(provider => provider(server)) + .map((spec) => spec.getUiCapabilitiesProvider()) + .filter((provider) => !!provider) + .map((provider) => provider(server)) ); - capabilitiesList.forEach(capabilities => { + capabilitiesList.forEach((capabilities) => { kbnServer.newPlatform.setup.core.capabilities.registerProvider(() => capabilities); }); }; diff --git a/src/legacy/server/config/complete.js b/src/legacy/server/config/complete.js index 2cdd8c32bcbeb..7dbb3a722e38f 100644 --- a/src/legacy/server/config/complete.js +++ b/src/legacy/server/config/complete.js @@ -17,8 +17,8 @@ * under the License. */ -export default function(kbnServer, server) { - server.decorate('server', 'config', function() { +export default function (kbnServer, server) { + server.decorate('server', 'config', function () { return kbnServer.config; }); } diff --git a/src/legacy/server/config/complete.test.js b/src/legacy/server/config/complete.test.js index 122c60e103b50..e5484693ae55f 100644 --- a/src/legacy/server/config/complete.test.js +++ b/src/legacy/server/config/complete.test.js @@ -20,7 +20,7 @@ import completeMixin from './complete'; import sinon from 'sinon'; -describe('server/config completeMixin()', function() { +describe('server/config completeMixin()', function () { const sandbox = sinon.createSandbox(); afterEach(() => sandbox.restore()); diff --git a/src/legacy/server/config/config.js b/src/legacy/server/config/config.js index b186071edeaf7..d32ec29e6d701 100644 --- a/src/legacy/server/config/config.js +++ b/src/legacy/server/config/config.js @@ -47,7 +47,7 @@ export class Config { } if (!key) { - return _.each(extension._inner.children, child => { + return _.each(extension._inner.children, (child) => { this.extendSchema(child.schema, _.get(settings, child.key), child.key); }); } @@ -193,9 +193,7 @@ export class Config { getSchema() { if (!this[schema]) { this[schema] = (function convertToSchema(children) { - let schema = Joi.object() - .keys({}) - .default(); + let schema = Joi.object().keys({}).default(); for (const key of Object.keys(children)) { const child = children[key]; diff --git a/src/legacy/server/config/config.test.js b/src/legacy/server/config/config.test.js index e71cd9f0e6ac9..d7dec19b7ca6e 100644 --- a/src/legacy/server/config/config.test.js +++ b/src/legacy/server/config/config.test.js @@ -56,55 +56,55 @@ const schema = Joi.object({ }).default(), }).default(); -describe('lib/config/config', function() { - describe('class Config()', function() { - describe('constructor', function() { - it('should not allow any config if the schema is not passed', function() { +describe('lib/config/config', function () { + describe('class Config()', function () { + describe('constructor', function () { + it('should not allow any config if the schema is not passed', function () { const config = new Config(); - const run = function() { + const run = function () { config.set('something.enable', true); }; expect(run).toThrow(); }); - it('should allow keys in the schema', function() { + it('should allow keys in the schema', function () { const config = new Config(schema); - const run = function() { + const run = function () { config.set('test.client.host', 'http://localhost'); }; expect(run).not.toThrow(); }); - it('should not allow keys not in the schema', function() { + it('should not allow keys not in the schema', function () { const config = new Config(schema); - const run = function() { + const run = function () { config.set('paramNotDefinedInTheSchema', true); }; expect(run).toThrow(); }); - it('should not allow child keys not in the schema', function() { + it('should not allow child keys not in the schema', function () { const config = new Config(schema); - const run = function() { + const run = function () { config.set('test.client.paramNotDefinedInTheSchema', true); }; expect(run).toThrow(); }); - it('should set defaults', function() { + it('should set defaults', function () { const config = new Config(schema); expect(config.get('test.enable')).toBe(true); expect(config.get('test.client.type')).toBe('datastore'); }); }); - describe('#resetTo(object)', function() { + describe('#resetTo(object)', function () { let config; - beforeEach(function() { + beforeEach(function () { config = new Config(schema); }); - it('should reset the config object with new values', function() { + it('should reset the config object with new values', function () { config.set(data); const newData = config.get(); newData.test.enable = false; @@ -113,52 +113,52 @@ describe('lib/config/config', function() { }); }); - describe('#has(key)', function() { + describe('#has(key)', function () { let config; - beforeEach(function() { + beforeEach(function () { config = new Config(schema); }); - it('should return true for fields that exist in the schema', function() { + it('should return true for fields that exist in the schema', function () { expect(config.has('test.undefValue')).toBe(true); }); - it('should return true for partial objects that exist in the schema', function() { + it('should return true for partial objects that exist in the schema', function () { expect(config.has('test.client')).toBe(true); }); - it('should return false for fields that do not exist in the schema', function() { + it('should return false for fields that do not exist in the schema', function () { expect(config.has('test.client.pool')).toBe(false); }); }); - describe('#set(key, value)', function() { + describe('#set(key, value)', function () { let config; - beforeEach(function() { + beforeEach(function () { config = new Config(schema); }); - it('should use a key and value to set a config value', function() { + it('should use a key and value to set a config value', function () { config.set('test.enable', false); expect(config.get('test.enable')).toBe(false); }); - it('should use an object to set config values', function() { + it('should use an object to set config values', function () { const hosts = ['host-01', 'host-02']; config.set({ test: { enable: false, hosts: hosts } }); expect(config.get('test.enable')).toBe(false); expect(config.get('test.hosts')).toEqual(hosts); }); - it('should use a flatten object to set config values', function() { + it('should use a flatten object to set config values', function () { const hosts = ['host-01', 'host-02']; config.set({ 'test.enable': false, 'test.hosts': hosts }); expect(config.get('test.enable')).toBe(false); expect(config.get('test.hosts')).toEqual(hosts); }); - it('should override values with just the values present', function() { + it('should override values with just the values present', function () { const newData = _.cloneDeep(data); config.set(data); newData.test.enable = false; @@ -166,10 +166,10 @@ describe('lib/config/config', function() { expect(config.get()).toEqual(newData); }); - it('should thow an exception when setting a value with the wrong type', function(done) { + it('should thow an exception when setting a value with the wrong type', function (done) { expect.assertions(4); - const run = function() { + const run = function () { config.set('test.enable', 'something'); }; @@ -189,37 +189,37 @@ describe('lib/config/config', function() { }); }); - describe('#get(key)', function() { + describe('#get(key)', function () { let config; - beforeEach(function() { + beforeEach(function () { config = new Config(schema); config.set(data); }); - it('should return the whole config object when called without a key', function() { + it('should return the whole config object when called without a key', function () { const newData = _.cloneDeep(data); newData.test.enable = true; expect(config.get()).toEqual(newData); }); - it('should return the value using dot notation', function() { + it('should return the value using dot notation', function () { expect(config.get('test.enable')).toBe(true); }); - it('should return the clone of partial object using dot notation', function() { + it('should return the clone of partial object using dot notation', function () { expect(config.get('test.client')).not.toBe(data.test.client); expect(config.get('test.client')).toEqual(data.test.client); }); - it('should throw exception for unknown config values', function() { - const run = function() { + it('should throw exception for unknown config values', function () { + const run = function () { config.get('test.does.not.exist'); }; expect(run).toThrowError(/Unknown config key: test.does.not.exist/); }); - it('should not throw exception for undefined known config values', function() { + it('should not throw exception for undefined known config values', function () { const run = function getUndefValue() { config.get('test.undefValue'); }; @@ -227,56 +227,54 @@ describe('lib/config/config', function() { }); }); - describe('#getDefault(key)', function() { + describe('#getDefault(key)', function () { let config; - beforeEach(function() { + beforeEach(function () { config = new Config(schema); config.set(data); }); - describe('dot notation key', function() { - it('should return undefined if there is no default', function() { + describe('dot notation key', function () { + it('should return undefined if there is no default', function () { const hostDefault = config.getDefault('test.client.host'); expect(hostDefault).toBeUndefined(); }); - it('should return default if specified', function() { + it('should return default if specified', function () { const typeDefault = config.getDefault('test.client.type'); expect(typeDefault).toBe('datastore'); }); - it('should throw exception for unknown key', function() { + it('should throw exception for unknown key', function () { expect(() => { config.getDefault('foo.bar'); }).toThrowErrorMatchingSnapshot(); }); }); - describe('array key', function() { - it('should return undefined if there is no default', function() { + describe('array key', function () { + it('should return undefined if there is no default', function () { const hostDefault = config.getDefault(['test', 'client', 'host']); expect(hostDefault).toBeUndefined(); }); - it('should return default if specified', function() { + it('should return default if specified', function () { const typeDefault = config.getDefault(['test', 'client', 'type']); expect(typeDefault).toBe('datastore'); }); - it('should throw exception for unknown key', function() { + it('should throw exception for unknown key', function () { expect(() => { config.getDefault(['foo', 'bar']); }).toThrowErrorMatchingSnapshot(); }); }); - it('object schema with no default should return default value for property', function() { + it('object schema with no default should return default value for property', function () { const noDefaultSchema = Joi.object() .keys({ - foo: Joi.array() - .items(Joi.string().min(1)) - .default(['bar']), + foo: Joi.array().items(Joi.string().min(1)).default(['bar']), }) .required(); @@ -289,12 +287,10 @@ describe('lib/config/config', function() { expect(fooDefault).toEqual(['bar']); }); - it('should return clone of the default', function() { + it('should return clone of the default', function () { const schemaWithArrayDefault = Joi.object() .keys({ - foo: Joi.array() - .items(Joi.string().min(1)) - .default(['bar']), + foo: Joi.array().items(Joi.string().min(1)).default(['bar']), }) .default(); @@ -308,19 +304,19 @@ describe('lib/config/config', function() { }); }); - describe('#extendSchema(key, schema)', function() { + describe('#extendSchema(key, schema)', function () { let config; - beforeEach(function() { + beforeEach(function () { config = new Config(schema); }); - it('should allow you to extend the schema at the top level', function() { + it('should allow you to extend the schema at the top level', function () { const newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); config.extendSchema(newSchema, {}, 'myTest'); expect(config.get('myTest.test')).toBe(true); }); - it('should allow you to extend the schema with a prefix', function() { + it('should allow you to extend the schema with a prefix', function () { const newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); config.extendSchema(newSchema, {}, 'prefix.myTest'); expect(config.get('prefix')).toEqual({ myTest: { test: true } }); @@ -328,17 +324,17 @@ describe('lib/config/config', function() { expect(config.get('prefix.myTest.test')).toBe(true); }); - it('should NOT allow you to extend the schema if something else is there', function() { + it('should NOT allow you to extend the schema if something else is there', function () { const newSchema = Joi.object({ test: Joi.boolean().default(true) }).default(); - const run = function() { + const run = function () { config.extendSchema('test', newSchema); }; expect(run).toThrow(); }); }); - describe('#removeSchema(key)', function() { - it('should completely remove the key', function() { + describe('#removeSchema(key)', function () { + it('should completely remove the key', function () { const config = new Config( Joi.object().keys({ a: Joi.number().default(1), @@ -350,7 +346,7 @@ describe('lib/config/config', function() { expect(() => config.get('a')).toThrowError('Unknown config key'); }); - it('only removes existing keys', function() { + it('only removes existing keys', function () { const config = new Config(Joi.object()); expect(() => config.removeSchema('b')).toThrowError('Unknown schema'); diff --git a/src/legacy/server/config/override.test.ts b/src/legacy/server/config/override.test.ts index 4e21a88e79e61..31b01004f72ad 100644 --- a/src/legacy/server/config/override.test.ts +++ b/src/legacy/server/config/override.test.ts @@ -19,8 +19,8 @@ import { override } from './override'; -describe('override(target, source)', function() { - it('should override the values form source to target', function() { +describe('override(target, source)', function () { + it('should override the values form source to target', function () { const target = { test: { enable: true, diff --git a/src/legacy/server/config/schema.js b/src/legacy/server/config/schema.js index 87db8c184ad36..53f5185442688 100644 --- a/src/legacy/server/config/schema.js +++ b/src/legacy/server/config/schema.js @@ -77,9 +77,7 @@ export default () => .default('') .allow('') .regex(/(^$|^\/.*[^\/]$)/, `start with a slash, don't end with one`), - host: Joi.string() - .hostname() - .default('localhost'), + host: Joi.string().hostname().default('localhost'), port: Joi.number().default(5601), rewriteBasePath: Joi.boolean().when('basePath', { is: '', @@ -139,14 +137,8 @@ export default () => .less(1073741825) // 10MB .default(10485760), - keepFiles: Joi.number() - .greater(2) - .less(1024) - .default(7), - pollingInterval: Joi.number() - .greater(5000) - .less(3600000) - .default(10000), + keepFiles: Joi.number().greater(2).less(1024).default(7), + pollingInterval: Joi.number().greater(5000).less(3600000).default(10000), usePolling: Joi.boolean().default(false), }) .default(), @@ -158,12 +150,8 @@ export default () => }).default(), plugins: Joi.object({ - paths: Joi.array() - .items(Joi.string()) - .default([]), - scanDirs: Joi.array() - .items(Joi.string()) - .default([]), + paths: Joi.array().items(Joi.string()).default([]), + scanDirs: Joi.array().items(Joi.string()).default([]), initialize: Joi.boolean().default(true), }).default(), @@ -180,9 +168,7 @@ export default () => viewCaching: Joi.boolean().default(Joi.ref('$prod')), watch: Joi.boolean().default(false), watchPort: Joi.number().default(5602), - watchHost: Joi.string() - .hostname() - .default('localhost'), + watchHost: Joi.string().hostname().default('localhost'), watchPrebuild: Joi.boolean().default(false), watchProxyTimeout: Joi.number().default(10 * 60000), useBundleCache: Joi.boolean().default(!!process.env.CODE_COVERAGE ? true : Joi.ref('$prod')), @@ -207,25 +193,14 @@ export default () => url: Joi.string(), options: Joi.object({ attribution: Joi.string(), - minZoom: Joi.number() - .min(0, 'Must be 0 or higher') - .default(0), + minZoom: Joi.number().min(0, 'Must be 0 or higher').default(0), maxZoom: Joi.number().default(10), tileSize: Joi.number(), - subdomains: Joi.array() - .items(Joi.string()) - .single(), + subdomains: Joi.array().items(Joi.string()).single(), errorTileUrl: Joi.string().uri(), tms: Joi.boolean(), reuseTiles: Joi.boolean(), - bounds: Joi.array() - .items( - Joi.array() - .items(Joi.number()) - .min(2) - .required() - ) - .min(2), + bounds: Joi.array().items(Joi.array().items(Joi.number()).min(2).required()).min(2), default: Joi.boolean(), }).default({ default: true, @@ -259,9 +234,7 @@ export default () => ) .default([]), }).default(), - manifestServiceUrl: Joi.string() - .default('') - .allow(''), + manifestServiceUrl: Joi.string().default('').allow(''), emsFileApiUrl: Joi.string().default('https://vector.maps.elastic.co'), emsTileApiUrl: Joi.string().default('https://tiles.maps.elastic.co'), emsLandingPageUrl: Joi.string().default('https://maps.elastic.co/v7.8'), diff --git a/src/legacy/server/config/schema.test.js b/src/legacy/server/config/schema.test.js index 03d2fe53c2ce7..aa09c15e9324d 100644 --- a/src/legacy/server/config/schema.test.js +++ b/src/legacy/server/config/schema.test.js @@ -20,7 +20,7 @@ import schemaProvider from './schema'; import Joi from 'joi'; -describe('Config schema', function() { +describe('Config schema', function () { let schema; beforeEach(async () => (schema = await schemaProvider())); @@ -28,38 +28,38 @@ describe('Config schema', function() { return Joi.validate(data, schema, options); } - describe('server', function() { - it('everything is optional', function() { + describe('server', function () { + it('everything is optional', function () { const { error } = validate({}); expect(error).toBe(null); }); - describe('basePath', function() { - it('accepts empty strings', function() { + describe('basePath', function () { + it('accepts empty strings', function () { const { error, value } = validate({ server: { basePath: '' } }); expect(error).toBe(null); expect(value.server.basePath).toBe(''); }); - it('accepts strings with leading slashes', function() { + it('accepts strings with leading slashes', function () { const { error, value } = validate({ server: { basePath: '/path' } }); expect(error).toBe(null); expect(value.server.basePath).toBe('/path'); }); - it('rejects strings with trailing slashes', function() { + it('rejects strings with trailing slashes', function () { const { error } = validate({ server: { basePath: '/path/' } }); expect(error).toHaveProperty('details'); expect(error.details[0]).toHaveProperty('path', ['server', 'basePath']); }); - it('rejects strings without leading slashes', function() { + it('rejects strings without leading slashes', function () { const { error } = validate({ server: { basePath: 'path' } }); expect(error).toHaveProperty('details'); expect(error.details[0]).toHaveProperty('path', ['server', 'basePath']); }); - it('rejects things that are not strings', function() { + it('rejects things that are not strings', function () { for (const value of [1, true, {}, [], /foo/]) { const { error } = validate({ server: { basePath: value } }); expect(error).toHaveProperty('details'); @@ -68,32 +68,32 @@ describe('Config schema', function() { }); }); - describe('rewriteBasePath', function() { + describe('rewriteBasePath', function () { it('defaults to false', () => { const { error, value } = validate({}); expect(error).toBe(null); expect(value.server.rewriteBasePath).toBe(false); }); - it('accepts false', function() { + it('accepts false', function () { const { error, value } = validate({ server: { rewriteBasePath: false } }); expect(error).toBe(null); expect(value.server.rewriteBasePath).toBe(false); }); - it('accepts true if basePath set', function() { + it('accepts true if basePath set', function () { const { error, value } = validate({ server: { basePath: '/foo', rewriteBasePath: true } }); expect(error).toBe(null); expect(value.server.rewriteBasePath).toBe(true); }); - it('rejects true if basePath not set', function() { + it('rejects true if basePath not set', function () { const { error } = validate({ server: { rewriteBasePath: true } }); expect(error).toHaveProperty('details'); expect(error.details[0]).toHaveProperty('path', ['server', 'rewriteBasePath']); }); - it('rejects strings', function() { + it('rejects strings', function () { const { error } = validate({ server: { rewriteBasePath: 'foo' } }); expect(error).toHaveProperty('details'); expect(error.details[0]).toHaveProperty('path', ['server', 'rewriteBasePath']); diff --git a/src/legacy/server/http/index.js b/src/legacy/server/http/index.js index 3649987d89b9a..2d62d12dfd9f3 100644 --- a/src/legacy/server/http/index.js +++ b/src/legacy/server/http/index.js @@ -24,7 +24,7 @@ import Boom from 'boom'; import { registerHapiPlugins } from './register_hapi_plugins'; import { setupBasePathProvider } from './setup_base_path_provider'; -export default async function(kbnServer, server, config) { +export default async function (kbnServer, server, config) { server = kbnServer.server; setupBasePathProvider(kbnServer); @@ -32,7 +32,7 @@ export default async function(kbnServer, server, config) { await registerHapiPlugins(server); // helper for creating view managers for servers - server.decorate('server', 'setupViews', function(path, engines) { + server.decorate('server', 'setupViews', function (path, engines) { this.views({ path: path, isCached: config.get('optimize.viewCaching'), @@ -43,7 +43,7 @@ export default async function(kbnServer, server, config) { server.route({ method: 'GET', path: '/{p*}', - handler: function(req, h) { + handler: function (req, h) { const path = req.path; if (path === '/' || path.charAt(path.length - 1) !== '/') { throw Boom.notFound(); diff --git a/src/legacy/server/http/integration_tests/max_payload_size.test.js b/src/legacy/server/http/integration_tests/max_payload_size.test.js index 7f22f83c78f0e..a019220ca7a2a 100644 --- a/src/legacy/server/http/integration_tests/max_payload_size.test.js +++ b/src/legacy/server/http/integration_tests/max_payload_size.test.js @@ -30,7 +30,7 @@ beforeAll(async () => { path: '/payload_size_check/test/route', method: 'POST', config: { payload: { maxBytes: 200 } }, - handler: req => req.payload.data.slice(0, 5), + handler: (req) => req.payload.data.slice(0, 5), }); }, 30000); @@ -40,9 +40,7 @@ test('accepts payload with a size larger than default but smaller than route con await kbnTestServer.request .post(root, '/payload_size_check/test/route') .send({ - data: Array(150) - .fill('+') - .join(''), + data: Array(150).fill('+').join(''), }) .expect(200, '+++++'); }); @@ -51,9 +49,7 @@ test('fails with 413 if payload size is larger than default and route config all await kbnTestServer.request .post(root, '/payload_size_check/test/route') .send({ - data: Array(250) - .fill('+') - .join(''), + data: Array(250).fill('+').join(''), }) .expect(413, { statusCode: 413, diff --git a/src/legacy/server/http/setup_base_path_provider.js b/src/legacy/server/http/setup_base_path_provider.js index 07917ebd63895..6949d7e2eebd0 100644 --- a/src/legacy/server/http/setup_base_path_provider.js +++ b/src/legacy/server/http/setup_base_path_provider.js @@ -18,7 +18,7 @@ */ export function setupBasePathProvider(kbnServer) { - kbnServer.server.decorate('request', 'getBasePath', function() { + kbnServer.server.decorate('request', 'getBasePath', function () { const request = this; return kbnServer.newPlatform.setup.core.http.basePath.get(request); }); diff --git a/src/legacy/server/i18n/get_translations_path.ts b/src/legacy/server/i18n/get_translations_path.ts index ac7c61dcf8543..a2a292e2278be 100644 --- a/src/legacy/server/i18n/get_translations_path.ts +++ b/src/legacy/server/i18n/get_translations_path.ts @@ -39,7 +39,7 @@ export async function getTranslationPaths({ cwd, glob }: { cwd: string; glob: st const content = await readFileAsync(entryFullPath, 'utf8'); const { translations } = JSON.parse(content) as I18NRCFileStructure; if (translations && translations.length) { - translations.forEach(translation => { + translations.forEach((translation) => { const translationFullPath = resolve(pluginBasePath, translation); translationPaths.push(translationFullPath); }); diff --git a/src/legacy/server/i18n/index.ts b/src/legacy/server/i18n/index.ts index 9902aaa1e8914..09f7022436049 100644 --- a/src/legacy/server/i18n/index.ts +++ b/src/legacy/server/i18n/index.ts @@ -35,10 +35,10 @@ export async function i18nMixin(kbnServer: KbnServer, server: Server, config: Ki cwd: fromRoot('.'), glob: I18N_RC, }), - ...(config.get('plugins.paths') as string[]).map(cwd => + ...(config.get('plugins.paths') as string[]).map((cwd) => getTranslationPaths({ cwd, glob: I18N_RC }) ), - ...(config.get('plugins.scanDirs') as string[]).map(cwd => + ...(config.get('plugins.scanDirs') as string[]).map((cwd) => getTranslationPaths({ cwd, glob: `*/${I18N_RC}` }) ), getTranslationPaths({ @@ -49,7 +49,7 @@ export async function i18nMixin(kbnServer: KbnServer, server: Server, config: Ki const currentTranslationPaths = ([] as string[]) .concat(...translationPaths) - .filter(translationPath => basename(translationPath, '.json') === locale); + .filter((translationPath) => basename(translationPath, '.json') === locale); i18nLoader.registerTranslationFiles(currentTranslationPaths); const translations = await i18nLoader.getTranslationsByLocale(locale); diff --git a/src/legacy/server/i18n/localization/file_integrity.test.mocks.ts b/src/legacy/server/i18n/localization/file_integrity.test.mocks.ts index cb77ce581eff2..9495098ede1a8 100644 --- a/src/legacy/server/i18n/localization/file_integrity.test.mocks.ts +++ b/src/legacy/server/i18n/localization/file_integrity.test.mocks.ts @@ -28,7 +28,7 @@ jest.doMock('fs', () => ({ const streamData = filepath.split(''); let cursor = 0; - readableStream._read = function(size) { + readableStream._read = function (size) { const current = streamData[cursor++]; if (typeof current === 'undefined') { return this.push(null); diff --git a/src/legacy/server/keystore/keystore.test.js b/src/legacy/server/keystore/keystore.test.js index db5276958c41c..0897ce55d086b 100644 --- a/src/legacy/server/keystore/keystore.test.js +++ b/src/legacy/server/keystore/keystore.test.js @@ -28,7 +28,7 @@ const mockUnprotectedKeystoreData = 'I4lzJ9MRy21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; jest.mock('fs', () => ({ - readFileSync: jest.fn().mockImplementation(path => { + readFileSync: jest.fn().mockImplementation((path) => { if (path.includes('data/unprotected')) { return JSON.stringify(mockUnprotectedKeystoreData); } @@ -43,7 +43,7 @@ jest.mock('fs', () => ({ throw { code: 'EACCES' }; }), - existsSync: jest.fn().mockImplementation(path => { + existsSync: jest.fn().mockImplementation((path) => { return ( path.includes('data/unprotected') || path.includes('data/protected') || diff --git a/src/legacy/server/logging/apply_filters_to_keys.js b/src/legacy/server/logging/apply_filters_to_keys.js index 62e287ec9a286..63e5ab4c62f29 100644 --- a/src/legacy/server/logging/apply_filters_to_keys.js +++ b/src/legacy/server/logging/apply_filters_to_keys.js @@ -51,7 +51,7 @@ function apply(obj, key, action) { return obj; } -export default function(obj, actionsByKey) { +export default function (obj, actionsByKey) { return Object.keys(actionsByKey).reduce((output, key) => { return apply(output, key, actionsByKey[key]); }, toPojo(obj)); diff --git a/src/legacy/server/logging/apply_filters_to_keys.test.js b/src/legacy/server/logging/apply_filters_to_keys.test.js index 7ca26ed0f3bd6..e007157e9488b 100644 --- a/src/legacy/server/logging/apply_filters_to_keys.test.js +++ b/src/legacy/server/logging/apply_filters_to_keys.test.js @@ -19,8 +19,8 @@ import applyFiltersToKeys from './apply_filters_to_keys'; -describe('applyFiltersToKeys(obj, actionsByKey)', function() { - it('applies for each key+prop in actionsByKey', function() { +describe('applyFiltersToKeys(obj, actionsByKey)', function () { + it('applies for each key+prop in actionsByKey', function () { const data = applyFiltersToKeys( { a: { diff --git a/src/legacy/server/logging/configuration.js b/src/legacy/server/logging/configuration.js index 45a17d96a77cf..267dc9a334de8 100644 --- a/src/legacy/server/logging/configuration.js +++ b/src/legacy/server/logging/configuration.js @@ -64,7 +64,7 @@ export default function loggingConfiguration(config) { }, events: _.transform( events, - function(filtered, val, key) { + function (filtered, val, key) { // provide a string compatible way to remove events if (val !== '!') filtered[key] = val; }, diff --git a/src/legacy/server/logging/log_format.js b/src/legacy/server/logging/log_format.js index ca1d756704dd0..9bc1d67dd5857 100644 --- a/src/legacy/server/logging/log_format.js +++ b/src/legacy/server/logging/log_format.js @@ -38,7 +38,7 @@ function serializeError(err = {}) { }; } -const levelColor = function(code) { +const levelColor = function (code) { if (code < 299) return chalk.green(code); if (code < 399) return chalk.yellow(code); if (code < 499) return chalk.magentaBright(code); @@ -128,7 +128,7 @@ export default class TransformObjStream extends Stream.Transform { data.message += ' '; data.message += chalk.gray('load: ['); data.message += get(data, 'os.load', []) - .map(function(val) { + .map(function (val) { return numeral(val).format('0.00'); }) .join(' '); diff --git a/src/legacy/server/logging/log_format_json.js b/src/legacy/server/logging/log_format_json.js index bc9c9e6746f8a..bfceb78b24504 100644 --- a/src/legacy/server/logging/log_format_json.js +++ b/src/legacy/server/logging/log_format_json.js @@ -20,7 +20,7 @@ import LogFormat from './log_format'; import stringify from 'json-stringify-safe'; -const stripColors = function(string) { +const stripColors = function (string) { return string.replace(/\u001b[^m]+m/g, ''); }; diff --git a/src/legacy/server/logging/log_format_json.test.js b/src/legacy/server/logging/log_format_json.test.js index b39891440a75e..31e622ecae611 100644 --- a/src/legacy/server/logging/log_format_json.test.js +++ b/src/legacy/server/logging/log_format_json.test.js @@ -27,7 +27,7 @@ import KbnLoggerJsonFormat from './log_format_json'; const time = +moment('2010-01-01T05:15:59Z', moment.ISO_8601); -const makeEvent = eventType => ({ +const makeEvent = (eventType) => ({ event: eventType, timestamp: time, }); diff --git a/src/legacy/server/logging/log_format_string.js b/src/legacy/server/logging/log_format_string.js index 9cbbbbee33d91..3c18aab2e3d09 100644 --- a/src/legacy/server/logging/log_format_string.js +++ b/src/legacy/server/logging/log_format_string.js @@ -47,11 +47,11 @@ const typeColors = { scss: 'magentaBright', }; -const color = _.memoize(function(name) { +const color = _.memoize(function (name) { return chalk[typeColors[name]] || _.identity; }); -const type = _.memoize(function(t) { +const type = _.memoize(function (t) { return color(t)(_.pad(t, 7).slice(0, 7)); }); @@ -63,12 +63,12 @@ export default class KbnLoggerStringFormat extends LogFormat { const msg = data.error ? color('error')(data.error.stack) : color('message')(data.message); const tags = _(data.tags) - .sortBy(function(tag) { + .sortBy(function (tag) { if (color(tag) === _.identity) return `2${tag}`; if (_.includes(statuses, tag)) return `0${tag}`; return `1${tag}`; }) - .reduce(function(s, t) { + .reduce(function (s, t) { return s + `[${color(t)(t)}]`; }, ''); diff --git a/src/legacy/server/logging/log_reporter.js b/src/legacy/server/logging/log_reporter.js index b784d03a5b86e..4afb00b568844 100644 --- a/src/legacy/server/logging/log_reporter.js +++ b/src/legacy/server/logging/log_reporter.js @@ -51,10 +51,7 @@ export function getLoggerStream({ events, config }) { }); } - logInterceptor - .pipe(squeeze) - .pipe(format) - .pipe(dest); + logInterceptor.pipe(squeeze).pipe(format).pipe(dest); return logInterceptor; } diff --git a/src/legacy/server/logging/rotate/log_rotator.ts b/src/legacy/server/logging/rotate/log_rotator.ts index eeb91fd0f2636..22183b2f0777a 100644 --- a/src/legacy/server/logging/rotate/log_rotator.ts +++ b/src/legacy/server/logging/rotate/log_rotator.ts @@ -115,7 +115,7 @@ export class LogRotator { // await writeFileAsync(tempFile, 'test'); - const usePollingTest$ = new Observable(observer => { + const usePollingTest$ = new Observable((observer) => { // observable complete function const completeFn = (completeStatus: boolean) => { if (this.stalkerUsePollingPolicyTestTimeout) { @@ -297,10 +297,10 @@ export class LogRotator { return ( foundLogFiles - .filter(file => new RegExp(`${logFileBaseName}\\.\\d`).test(file)) + .filter((file) => new RegExp(`${logFileBaseName}\\.\\d`).test(file)) // we use .slice(-1) here in order to retrieve the last number match in the read filenames .sort((a, b) => Number(a.match(/(\d+)/g)!.slice(-1)) - Number(b.match(/(\d+)/g)!.slice(-1))) - .map(filename => `${logFilesFolder}${sep}${filename}`) + .map((filename) => `${logFilesFolder}${sep}${filename}`) ); } diff --git a/src/legacy/server/pid/index.js b/src/legacy/server/pid/index.js index c4402b0542eaa..d7b9da1292252 100644 --- a/src/legacy/server/pid/index.js +++ b/src/legacy/server/pid/index.js @@ -23,14 +23,14 @@ import Bluebird from 'bluebird'; import { unlinkSync as unlink } from 'fs'; const writeFile = Bluebird.promisify(require('fs').writeFile); -export default Bluebird.method(function(kbnServer, server, config) { +export default Bluebird.method(function (kbnServer, server, config) { const path = config.get('pid.file'); if (!path) return; const pid = String(process.pid); return writeFile(path, pid, { flag: 'wx' }) - .catch(function(err) { + .catch(function (err) { if (err.code !== 'EEXIST') throw err; const message = `pid file already exists at ${path}`; @@ -47,18 +47,18 @@ export default Bluebird.method(function(kbnServer, server, config) { return writeFile(path, pid); }) - .then(function() { + .then(function () { server.logWithMetadata(['pid', 'debug'], `wrote pid file to ${path}`, { path: path, pid: pid, }); - const clean = _.once(function() { + const clean = _.once(function () { unlink(path); }); process.once('exit', clean); // for "natural" exits - process.once('SIGINT', function() { + process.once('SIGINT', function () { // for Ctrl-C exits clean(); @@ -66,7 +66,7 @@ export default Bluebird.method(function(kbnServer, server, config) { process.kill(process.pid, 'SIGINT'); }); - process.on('unhandledRejection', function(reason) { + process.on('unhandledRejection', function (reason) { server.log(['warning'], `Detected an unhandled Promise rejection.\n${reason}`); }); }); diff --git a/src/legacy/server/plugins/initialize_mixin.js b/src/legacy/server/plugins/initialize_mixin.js index 9cc317f002c5a..ccf4cd1c1a404 100644 --- a/src/legacy/server/plugins/initialize_mixin.js +++ b/src/legacy/server/plugins/initialize_mixin.js @@ -34,7 +34,7 @@ export async function initializeMixin(kbnServer, server, config) { async function callHookOnPlugins(hookName) { const { plugins } = kbnServer; - const ids = plugins.map(p => p.id); + const ids = plugins.map((p) => p.id); for (const id of ids) { await callPluginHook(hookName, plugins, id, []); diff --git a/src/legacy/server/plugins/lib/call_plugin_hook.js b/src/legacy/server/plugins/lib/call_plugin_hook.js index c62a3460fa3e2..b665869f5d25f 100644 --- a/src/legacy/server/plugins/lib/call_plugin_hook.js +++ b/src/legacy/server/plugins/lib/call_plugin_hook.js @@ -20,7 +20,7 @@ import { last } from 'lodash'; export async function callPluginHook(hookName, plugins, id, history) { - const plugin = plugins.find(plugin => plugin.id === id); + const plugin = plugins.find((plugin) => plugin.id === id); // make sure this is a valid plugin id if (!plugin) { diff --git a/src/legacy/server/plugins/scan_mixin.js b/src/legacy/server/plugins/scan_mixin.js index c66ce8da3a07a..89ebaf920d9d1 100644 --- a/src/legacy/server/plugins/scan_mixin.js +++ b/src/legacy/server/plugins/scan_mixin.js @@ -19,5 +19,5 @@ import { Plugin } from './lib'; export async function scanMixin(kbnServer) { - kbnServer.plugins = kbnServer.pluginSpecs.map(spec => new Plugin(kbnServer, spec)); + kbnServer.plugins = kbnServer.pluginSpecs.map((spec) => new Plugin(kbnServer, spec)); } diff --git a/src/legacy/server/plugins/wait_for_plugins_init.js b/src/legacy/server/plugins/wait_for_plugins_init.js index 1625ee127f56c..144eb5ef803cc 100644 --- a/src/legacy/server/plugins/wait_for_plugins_init.js +++ b/src/legacy/server/plugins/wait_for_plugins_init.js @@ -27,7 +27,7 @@ const queues = new WeakMap(); export function waitForInitSetupMixin(kbnServer) { queues.set(kbnServer, []); - kbnServer.afterPluginsInit = function(callback) { + kbnServer.afterPluginsInit = function (callback) { const queue = queues.get(kbnServer); if (!queue) { diff --git a/src/legacy/server/sass/build.js b/src/legacy/server/sass/build.js index 1ec656786ccc5..2c0a2d84be2c0 100644 --- a/src/legacy/server/sass/build.js +++ b/src/legacy/server/sass/build.js @@ -35,7 +35,7 @@ const copyFile = promisify(fs.copyFile); const mkdirAsync = promisify(fs.mkdir); const UI_ASSETS_DIR = resolve(__dirname, '../../../core/server/core_app/assets'); -const DARK_THEME_IMPORTER = url => { +const DARK_THEME_IMPORTER = (url) => { if (url.includes('eui_colors_light')) { return { file: url.replace('eui_colors_light', 'eui_colors_dark') }; } @@ -101,7 +101,7 @@ export class Build { if (this.urlImports) { processor.use( postcssUrl({ - url: request => { + url: (request) => { if (!request.pathname) { return request.url; } @@ -144,7 +144,7 @@ export class Build { // verify that asset sources exist and import is valid before writing anything await Promise.all( - urlAssets.map(async asset => { + urlAssets.map(async (asset) => { try { await access(asset.path); } catch (e) { @@ -171,7 +171,7 @@ export class Build { // copy non-shared urlAssets await Promise.all( - urlAssets.map(async asset => { + urlAssets.map(async (asset) => { if (!asset.copyTo) { return; } diff --git a/src/legacy/server/sass/build_all.js b/src/legacy/server/sass/build_all.js index 1d3d76d1cb01a..dac6ac87a40d3 100644 --- a/src/legacy/server/sass/build_all.js +++ b/src/legacy/server/sass/build_all.js @@ -23,7 +23,7 @@ import { Build } from './build'; export async function buildAll({ styleSheets, log, buildDir }) { const bundles = await Promise.all( - styleSheets.map(async styleSheet => { + styleSheets.map(async (styleSheet) => { if (!styleSheet.localPath.endsWith('.scss')) { return; } @@ -41,5 +41,5 @@ export async function buildAll({ styleSheets, log, buildDir }) { }) ); - return bundles.filter(v => v); + return bundles.filter((v) => v); } diff --git a/src/legacy/server/sass/index.js b/src/legacy/server/sass/index.js index 9109e1b1dcea7..001457d110276 100644 --- a/src/legacy/server/sass/index.js +++ b/src/legacy/server/sass/index.js @@ -41,9 +41,9 @@ export async function sassMixin(kbnServer, server, config) { let trackedFiles = new Set(); const log = { - info: msg => server.log(['info', 'scss'], msg), - warn: msg => server.log(['warn', 'scss'], msg), - error: msg => server.log(['error', 'scss'], msg), + info: (msg) => server.log(['info', 'scss'], msg), + warn: (msg) => server.log(['warn', 'scss'], msg), + error: (msg) => server.log(['error', 'scss'], msg), }; try { @@ -53,8 +53,8 @@ export async function sassMixin(kbnServer, server, config) { buildDir: fromRoot('built_assets/css'), }); - scssBundles.forEach(bundle => { - bundle.includedFiles.forEach(file => trackedFiles.add(file)); + scssBundles.forEach((bundle) => { + bundle.includedFiles.forEach((file) => trackedFiles.add(file)); server.log(['info', 'scss'], `Compiled CSS: ${bundle.sourcePath} (theme=${bundle.theme})`); }); } catch (error) { @@ -89,13 +89,13 @@ export async function sassMixin(kbnServer, server, config) { // build bundles containing the changed file await Promise.all( - scssBundles.map(async bundle => { + scssBundles.map(async (bundle) => { try { if (await bundle.buildIfIncluded(path)) { server.log(['info', 'scss'], `Compiled ${bundle.sourcePath} due to change in ${path}`); } // if the bundle rebuilt, includedFiles is the new set; otherwise includedFiles is unchanged and remains tracked - bundle.includedFiles.forEach(file => currentlyTrackedFiles.add(file)); + bundle.includedFiles.forEach((file) => currentlyTrackedFiles.add(file)); } catch (error) { const { message, line, file } = error; if (!file) { @@ -113,7 +113,7 @@ export async function sassMixin(kbnServer, server, config) { */ // un-watch files no longer included in any bundle - trackedFiles.forEach(file => { + trackedFiles.forEach((file) => { if (currentlyTrackedFiles.has(file)) { return; } @@ -123,7 +123,7 @@ export async function sassMixin(kbnServer, server, config) { }); // watch files not previously included in any bundle - currentlyTrackedFiles.forEach(file => { + currentlyTrackedFiles.forEach((file) => { if (trackedFiles.has(file)) { return; } diff --git a/src/legacy/server/saved_objects/saved_objects_mixin.js b/src/legacy/server/saved_objects/saved_objects_mixin.js index 26fecc68fda4b..7d84c27bd1ef0 100644 --- a/src/legacy/server/saved_objects/saved_objects_mixin.js +++ b/src/legacy/server/saved_objects/saved_objects_mixin.js @@ -36,14 +36,14 @@ export function savedObjectsMixin(kbnServer, server) { const mappings = migrator.getActiveMappings(); const allTypes = Object.keys(getRootPropertiesObjects(mappings)); const schema = new SavedObjectsSchema(convertTypesToLegacySchema(typeRegistry.getAllTypes())); - const visibleTypes = allTypes.filter(type => !schema.isHiddenType(type)); + const visibleTypes = allTypes.filter((type) => !schema.isHiddenType(type)); server.decorate('server', 'kibanaMigrator', migrator); - const warn = message => server.log(['warning', 'saved-objects'], message); + const warn = (message) => server.log(['warning', 'saved-objects'], message); // we use kibana.index which is technically defined in the kibana plugin, so if // we don't have the plugin (mainly tests) we can't initialize the saved objects - if (!kbnServer.pluginSpecs.some(p => p.getId() === 'kibana')) { + if (!kbnServer.pluginSpecs.some((p) => p.getId() === 'kibana')) { warn('Saved Objects uninitialized because the Kibana plugin is disabled.'); return; } @@ -55,7 +55,7 @@ export function savedObjectsMixin(kbnServer, server) { throw new TypeError('Repository requires a "callCluster" function to be provided.'); } // throw an exception if an extraType is not defined. - includedHiddenTypes.forEach(type => { + includedHiddenTypes.forEach((type) => { if (!allTypes.includes(type)) { throw new Error(`Missing mappings for saved objects type '${type}'`); } @@ -98,7 +98,7 @@ export function savedObjectsMixin(kbnServer, server) { server.decorate('server', 'savedObjects', service); const savedObjectsClientCache = new WeakMap(); - server.decorate('request', 'getSavedObjectsClient', function(options) { + server.decorate('request', 'getSavedObjectsClient', function (options) { const request = this; if (savedObjectsClientCache.has(request)) { diff --git a/src/legacy/server/saved_objects/saved_objects_mixin.test.js b/src/legacy/server/saved_objects/saved_objects_mixin.test.js index d49b18ee2ce6c..5b40cc4b5aa35 100644 --- a/src/legacy/server/saved_objects/saved_objects_mixin.test.js +++ b/src/legacy/server/saved_objects/saved_objects_mixin.test.js @@ -88,7 +88,7 @@ const savedObjectTypes = convertLegacyTypes( ); const typeRegistry = new SavedObjectTypeRegistry(); -savedObjectTypes.forEach(type => typeRegistry.registerType(type)); +savedObjectTypes.forEach((type) => typeRegistry.registerType(type)); const migrator = mockKibanaMigrator.create({ types: savedObjectTypes, @@ -103,7 +103,7 @@ describe('Saved Objects Mixin', () => { 'kibana.index': 'kibana.index', 'savedObjects.maxImportExportSize': 10000, }; - const stubConfig = jest.fn(key => { + const stubConfig = jest.fn((key) => { return config[key]; }); diff --git a/src/legacy/server/server_extensions/add_memoized_factory_to_request.test.js b/src/legacy/server/server_extensions/add_memoized_factory_to_request.test.js index cbae6450ea405..48bd082468061 100644 --- a/src/legacy/server/server_extensions/add_memoized_factory_to_request.test.js +++ b/src/legacy/server/server_extensions/add_memoized_factory_to_request.test.js @@ -104,7 +104,7 @@ describe('server.addMemoizedFactoryToRequest()', () => { expect(() => server.addMemoizedFactoryToRequest('name', () => {})).not.toThrowError( 'more than one argument' ); - expect(() => server.addMemoizedFactoryToRequest('name', a => {})).not.toThrowError( + expect(() => server.addMemoizedFactoryToRequest('name', (a) => {})).not.toThrowError( 'more than one argument' ); expect(() => server.addMemoizedFactoryToRequest('name', (a, b) => {})).toThrowError( diff --git a/src/legacy/server/server_extensions/server_extensions_mixin.js b/src/legacy/server/server_extensions/server_extensions_mixin.js index fac8eda4adfb1..19c0b24ae15a1 100644 --- a/src/legacy/server/server_extensions/server_extensions_mixin.js +++ b/src/legacy/server/server_extensions/server_extensions_mixin.js @@ -51,7 +51,7 @@ export function serverExtensionsMixin(kbnServer, server) { } const requestCache = new WeakMap(); - server.decorate('request', methodName, function() { + server.decorate('request', methodName, function () { const request = this; if (!requestCache.has(request)) { diff --git a/src/legacy/server/status/index.js b/src/legacy/server/status/index.js index 5bd1efa99eb2c..377a5d74610a9 100644 --- a/src/legacy/server/status/index.js +++ b/src/legacy/server/status/index.js @@ -31,7 +31,7 @@ export function statusMixin(kbnServer, server, config) { const metrics = new Metrics(config, server); const oppsy = new Oppsy(server); - oppsy.on('ops', event => { + oppsy.on('ops', (event) => { // Oppsy has a bad race condition that will modify this data before // we ship it off to the buffer. Let's create our copy first. event = cloneDeep(event); @@ -41,7 +41,7 @@ export function statusMixin(kbnServer, server, config) { // captures (performs transforms on) the latest event data and stashes // the metrics for status/stats API payload - metrics.capture(event).then(data => { + metrics.capture(event).then((data) => { kbnServer.metrics = data; }); }); diff --git a/src/legacy/server/status/lib/__mocks__/_fs_stubs.js b/src/legacy/server/status/lib/__mocks__/_fs_stubs.js index a22822776f461..2be6402baa5fe 100644 --- a/src/legacy/server/status/lib/__mocks__/_fs_stubs.js +++ b/src/legacy/server/status/lib/__mocks__/_fs_stubs.js @@ -19,9 +19,7 @@ export function cGroups(hierarchy) { if (!hierarchy) { - hierarchy = Math.random() - .toString(36) - .substring(7); + hierarchy = Math.random().toString(36).substring(7); } const cpuAcctDir = `/sys/fs/cgroup/cpuacct/${hierarchy}`; @@ -68,7 +66,7 @@ class FSError extends Error { let _mockFiles = Object.create({}); -export const setMockFiles = mockFiles => { +export const setMockFiles = (mockFiles) => { _mockFiles = Object.create({}); if (mockFiles) { const files = Object.keys(mockFiles); diff --git a/src/legacy/server/status/lib/cgroup.js b/src/legacy/server/status/lib/cgroup.js index 8f59ce6d84d0e..4d21cafbedcaa 100644 --- a/src/legacy/server/status/lib/cgroup.js +++ b/src/legacy/server/status/lib/cgroup.js @@ -41,13 +41,13 @@ const CPU_STATS_FILE = 'cpu.stat'; const readFile = promisify(fs.readFile); export function readControlGroups() { - return readFile(PROC_SELF_CGROUP_FILE).then(data => { + return readFile(PROC_SELF_CGROUP_FILE).then((data) => { const response = {}; data .toString() .split(/\n/) - .forEach(line => { + .forEach((line) => { const matches = line.match(CONTROL_GROUP_RE); if (matches === null) { @@ -55,7 +55,7 @@ export function readControlGroups() { } const controllers = matches[1].split(CONTROLLER_SEPARATOR_RE); - controllers.forEach(controller => { + controllers.forEach((controller) => { response[controller] = matches[2]; }); }); @@ -65,7 +65,7 @@ export function readControlGroups() { } function fileContentsToInteger(path) { - return readFile(path).then(data => { + return readFile(path).then((data) => { return parseInt(data.toString(), 10); }); } @@ -91,11 +91,11 @@ export function readCPUStat(controlGroup) { }; readFile(joinPath(PROC_CGROUP_CPU_DIR, controlGroup, CPU_STATS_FILE)) - .then(data => { + .then((data) => { data .toString() .split(/\n/) - .forEach(line => { + .forEach((line) => { const fields = line.split(/\s+/); switch (fields[0]) { @@ -115,7 +115,7 @@ export function readCPUStat(controlGroup) { resolve(stat); }) - .catch(err => { + .catch((err) => { if (err.code === 'ENOENT') { return resolve(stat); } @@ -128,7 +128,7 @@ export function readCPUStat(controlGroup) { export function getAllStats(options = {}) { return new Promise((resolve, reject) => { readControlGroups() - .then(groups => { + .then((groups) => { const cpuPath = options.cpuPath || groups[GROUP_CPU]; const cpuAcctPath = options.cpuAcctPath || groups[GROUP_CPUACCT]; diff --git a/src/legacy/server/status/lib/cgroup.test.js b/src/legacy/server/status/lib/cgroup.test.js index 1134dd89f752e..62feba45d1b3c 100644 --- a/src/legacy/server/status/lib/cgroup.test.js +++ b/src/legacy/server/status/lib/cgroup.test.js @@ -25,7 +25,7 @@ import fs from 'fs'; import { cGroups as cGroupsFsStub, setMockFiles, readFileMock } from './__mocks__/_fs_stubs'; import { getAllStats, readControlGroups, readCPUStat } from './cgroup'; -describe('Control Group', function() { +describe('Control Group', function () { const fsStub = cGroupsFsStub(); beforeAll(() => { diff --git a/src/legacy/server/status/lib/get_os_info.test.js b/src/legacy/server/status/lib/get_os_info.test.js index eaa310f603fa2..11af7e1588090 100644 --- a/src/legacy/server/status/lib/get_os_info.test.js +++ b/src/legacy/server/status/lib/get_os_info.test.js @@ -46,7 +46,7 @@ describe('getOSInfo', () => { os.release.mockImplementation(() => '4.9.93-linuxkit-aufs'); // Mock getos response - getos.mockImplementation(cb => + getos.mockImplementation((cb) => cb(null, { os: 'linux', dist: 'Ubuntu Linux', diff --git a/src/legacy/server/status/lib/metrics.test.js b/src/legacy/server/status/lib/metrics.test.js index 4798ae7c5c888..6a734941eb70c 100644 --- a/src/legacy/server/status/lib/metrics.test.js +++ b/src/legacy/server/status/lib/metrics.test.js @@ -40,7 +40,7 @@ import sinon from 'sinon'; import { cGroups as cGroupsFsStub, setMockFiles, readFileMock } from './__mocks__/_fs_stubs'; import { Metrics } from './metrics'; -describe('Metrics', function() { +describe('Metrics', function () { fs.readFile.mockImplementation(readFileMock); const sampleConfig = { @@ -51,7 +51,7 @@ describe('Metrics', function() { port: 5603, }, }; - const config = { get: path => _.get(sampleConfig, path) }; + const config = { get: (path) => _.get(sampleConfig, path) }; let metrics; diff --git a/src/legacy/server/status/routes/api/register_stats.js b/src/legacy/server/status/routes/api/register_stats.js index 2dd66cb8caff7..09957e61f74d3 100644 --- a/src/legacy/server/status/routes/api/register_stats.js +++ b/src/legacy/server/status/routes/api/register_stats.js @@ -40,12 +40,12 @@ const STATS_NOT_READY_MESSAGE = i18n.translate('server.stats.notReadyMessage', { export function registerStatsApi(usageCollection, server, config, kbnServer) { const wrapAuth = wrapAuthConfig(config.get('status.allowAnonymous')); - const getClusterUuid = async callCluster => { + const getClusterUuid = async (callCluster) => { const { cluster_uuid: uuid } = await callCluster('info', { filterPath: 'cluster_uuid' }); return uuid; }; - const getUsage = async callCluster => { + const getUsage = async (callCluster) => { const usage = await usageCollection.bulkFetchUsage(callCluster); return usageCollection.toObject(usage); }; @@ -54,7 +54,7 @@ export function registerStatsApi(usageCollection, server, config, kbnServer) { /* kibana_stats gets singled out from the collector set as it is used * for health-checking Kibana and fetch does not rely on fetching data * from ES */ - server.newPlatform.setup.core.metrics.getOpsMetrics$().subscribe(metrics => { + server.newPlatform.setup.core.metrics.getOpsMetrics$().subscribe((metrics) => { lastMetrics = { ...metrics, timestamp: new Date().toISOString(), diff --git a/src/legacy/server/status/routes/page/register_status.js b/src/legacy/server/status/routes/page/register_status.js index 08d266e6dbf84..47bd3c34eba59 100644 --- a/src/legacy/server/status/routes/page/register_status.js +++ b/src/legacy/server/status/routes/page/register_status.js @@ -23,7 +23,7 @@ export function registerStatusPage(kbnServer, server, config) { const allowAnonymous = config.get('status.allowAnonymous'); const wrapAuth = wrapAuthConfig(allowAnonymous); - server.decorate('toolkit', 'renderStatusPage', async function() { + server.decorate('toolkit', 'renderStatusPage', async function () { const app = server.getHiddenUiAppById('status_page'); const h = this; diff --git a/src/legacy/server/status/samples.js b/src/legacy/server/status/samples.js index 69f25125e2666..9c41e29945a77 100644 --- a/src/legacy/server/status/samples.js +++ b/src/legacy/server/status/samples.js @@ -25,11 +25,11 @@ function Samples(max) { this.length = 0; } -Samples.prototype.add = function(sample) { +Samples.prototype.add = function (sample) { const vals = this.vals; const length = (this.length = Math.min(this.length + 1, this.max)); - _.forOwn(sample, function(val, name) { + _.forOwn(sample, function (val, name) { if (val == null) val = null; if (!vals[name]) vals[name] = new Array(length); @@ -38,7 +38,7 @@ Samples.prototype.add = function(sample) { }); }; -Samples.prototype.toJSON = function() { +Samples.prototype.toJSON = function () { return this.vals; }; diff --git a/src/legacy/server/status/server_status.js b/src/legacy/server/status/server_status.js index 3be1c17110711..3ee4d37d0b823 100644 --- a/src/legacy/server/status/server_status.js +++ b/src/legacy/server/status/server_status.js @@ -45,7 +45,7 @@ export default class ServerStatus { each(fn) { const self = this; - _.forOwn(self._created, function(status, i, list) { + _.forOwn(self._created, function (status, i, list) { if (status.state !== 'disabled') { fn.call(self, status, i, list); } @@ -57,7 +57,7 @@ export default class ServerStatus { } getForPluginId(pluginId) { - return _.find(this._created, s => s.plugin && s.plugin.id === pluginId); + return _.find(this._created, (s) => s.plugin && s.plugin.id === pluginId); } getState(id) { @@ -77,7 +77,7 @@ export default class ServerStatus { // take all created status objects .values(this._created) // get the state descriptor for each status - .map(status => states.get(status.state)) + .map((status) => states.get(status.state)) // reduce to the state with the highest severity, defaulting to green .reduce((a, b) => (a.severity > b.severity ? a : b), states.get('green')); diff --git a/src/legacy/server/status/server_status.test.js b/src/legacy/server/status/server_status.test.js index 7155e3df69a4f..bf94d693b1310 100644 --- a/src/legacy/server/status/server_status.test.js +++ b/src/legacy/server/status/server_status.test.js @@ -24,13 +24,13 @@ import * as states from './states'; import Status from './status'; import ServerStatus from './server_status'; -describe('ServerStatus class', function() { +describe('ServerStatus class', function () { const plugin = { id: 'name', version: '1.2.3' }; let server; let serverStatus; - beforeEach(function() { + beforeEach(function () { server = { expose: sinon.stub(), logWithMetadata: sinon.stub() }; serverStatus = new ServerStatus(server); }); @@ -42,8 +42,8 @@ describe('ServerStatus class', function() { }); }); - describe('#createForPlugin(plugin)', function() { - it('should create a new status by plugin', function() { + describe('#createForPlugin(plugin)', function () { + it('should create a new status by plugin', function () { const status = serverStatus.createForPlugin(plugin); expect(status).toBeInstanceOf(Status); }); @@ -61,41 +61,41 @@ describe('ServerStatus class', function() { }); }); - describe('#getForPluginId(plugin)', function() { - it('exposes plugin status for the plugin', function() { + describe('#getForPluginId(plugin)', function () { + it('exposes plugin status for the plugin', function () { const status = serverStatus.createForPlugin(plugin); expect(serverStatus.getForPluginId(plugin.id)).toBe(status); }); - it('does not get plain statuses by their id', function() { + it('does not get plain statuses by their id', function () { serverStatus.create('someid'); expect(serverStatus.getForPluginId('someid')).toBe(undefined); }); }); - describe('#getState(id)', function() { - it('should expose the state of a status by id', function() { + describe('#getState(id)', function () { + it('should expose the state of a status by id', function () { const status = serverStatus.create('someid'); status.green(); expect(serverStatus.getState('someid')).toBe('green'); }); }); - describe('#getStateForPluginId(plugin)', function() { - it('should expose the state of a plugin by id', function() { + describe('#getStateForPluginId(plugin)', function () { + it('should expose the state of a plugin by id', function () { const status = serverStatus.createForPlugin(plugin); status.green(); expect(serverStatus.getStateForPluginId(plugin.id)).toBe('green'); }); }); - describe('#overall()', function() { - it('considers each status to produce a summary', function() { + describe('#overall()', function () { + it('considers each status to produce a summary', function () { const status = serverStatus.createForPlugin(plugin); expect(serverStatus.overall().state).toBe('uninitialized'); - const match = function(overall, state) { + const match = function (overall, state) { expect(overall).toHaveProperty('state', state.id); expect(overall).toHaveProperty('title', state.title); expect(overall).toHaveProperty('icon', state.icon); @@ -114,8 +114,8 @@ describe('ServerStatus class', function() { }); }); - describe('#toJSON()', function() { - it('serializes to overall status and individuals', function() { + describe('#toJSON()', function () { + it('serializes to overall status and individuals', function () { const pluginOne = { id: 'one', version: '1.0.0' }; const pluginTwo = { id: 'two', version: '2.0.0' }; const pluginThree = { id: 'three', version: 'kibana' }; @@ -134,7 +134,7 @@ describe('ServerStatus class', function() { expect(json.overall.state).toEqual(serverStatus.overall().state); expect(json.statuses).toHaveLength(4); - const out = status => find(json.statuses, { id: status.id }); + const out = (status) => find(json.statuses, { id: status.id }); expect(out(service)).toHaveProperty('state', 'green'); expect(out(p1)).toHaveProperty('state', 'yellow'); expect(out(p2)).toHaveProperty('state', 'red'); diff --git a/src/legacy/server/status/status.js b/src/legacy/server/status/status.js index 373f3b316b993..10e94da3ac352 100644 --- a/src/legacy/server/status/status.js +++ b/src/legacy/server/status/status.js @@ -33,7 +33,7 @@ export default class Status extends EventEmitter { this.state = 'uninitialized'; this.message = 'uninitialized'; - this.on('change', function(previous, previousMsg) { + this.on('change', function (previous, previousMsg) { this.since = new Date(); const tags = ['status', this.id, this.state === 'red' ? 'error' : 'info']; @@ -81,8 +81,8 @@ export default class Status extends EventEmitter { } } -states.getAll().forEach(function(state) { - Status.prototype[state.id] = function(message) { +states.getAll().forEach(function (state) { + Status.prototype[state.id] = function (message) { if (this.state === 'disabled') return; const previous = this.state; diff --git a/src/legacy/server/status/status.test.js b/src/legacy/server/status/status.test.js index 89c0da74febe9..def7b5a2182e1 100644 --- a/src/legacy/server/status/status.test.js +++ b/src/legacy/server/status/status.test.js @@ -20,13 +20,13 @@ import sinon from 'sinon'; import ServerStatus from './server_status'; -describe('Status class', function() { +describe('Status class', function () { const plugin = { id: 'test', version: '1.2.3' }; let server; let serverStatus; - beforeEach(function() { + beforeEach(function () { server = { expose: sinon.stub(), logWithMetadata: sinon.stub() }; serverStatus = new ServerStatus(server); }); @@ -35,15 +35,15 @@ describe('Status class', function() { expect(serverStatus.createForPlugin(plugin)).toHaveProperty('state', 'uninitialized'); }); - it('emits change when the status is set', function(done) { + it('emits change when the status is set', function (done) { const status = serverStatus.createForPlugin(plugin); - status.once('change', function(prevState, prevMsg, newState, newMsg) { + status.once('change', function (prevState, prevMsg, newState, newMsg) { expect(newState).toBe('green'); expect(newMsg).toBe('GREEN'); expect(prevState).toBe('uninitialized'); - status.once('change', function(prevState, prevMsg, newState, newMsg) { + status.once('change', function (prevState, prevMsg, newState, newMsg) { expect(newState).toBe('red'); expect(newMsg).toBe('RED'); expect(prevState).toBe('green'); @@ -58,7 +58,7 @@ describe('Status class', function() { status.green('GREEN'); }); - it('should only trigger the change listener when something changes', function() { + it('should only trigger the change listener when something changes', function () { const status = serverStatus.createForPlugin(plugin); const stub = sinon.stub(); status.on('change', stub); @@ -68,7 +68,7 @@ describe('Status class', function() { sinon.assert.calledTwice(stub); }); - it('should create a JSON representation of the status', function() { + it('should create a JSON representation of the status', function () { const status = serverStatus.createForPlugin(plugin); status.green('Ready'); @@ -78,12 +78,12 @@ describe('Status class', function() { expect(json.message).toEqual('Ready'); }); - it('should call on handler if status is already matched', function(done) { + it('should call on handler if status is already matched', function (done) { const status = serverStatus.createForPlugin(plugin); const msg = 'Test Ready'; status.green(msg); - status.on('green', function(prev, prevMsg) { + status.on('green', function (prev, prevMsg) { expect(arguments.length).toBe(2); expect(prev).toBe('green'); expect(prevMsg).toBe(msg); @@ -92,12 +92,12 @@ describe('Status class', function() { }); }); - it('should call once handler if status is already matched', function(done) { + it('should call once handler if status is already matched', function (done) { const status = serverStatus.createForPlugin(plugin); const msg = 'Test Ready'; status.green(msg); - status.once('green', function(prev, prevMsg) { + status.once('green', function (prev, prevMsg) { expect(arguments.length).toBe(2); expect(prev).toBe('green'); expect(prevMsg).toBe(msg); @@ -107,7 +107,7 @@ describe('Status class', function() { }); function testState(color) { - it(`should change the state to ${color} when #${color}() is called`, function() { + it(`should change the state to ${color} when #${color}() is called`, function () { const status = serverStatus.createForPlugin(plugin); const message = 'testing ' + color; status[color](message); @@ -115,10 +115,10 @@ describe('Status class', function() { expect(status).toHaveProperty('message', message); }); - it(`should trigger the "change" listener when #${color}() is called`, function(done) { + it(`should trigger the "change" listener when #${color}() is called`, function (done) { const status = serverStatus.createForPlugin(plugin); const message = 'testing ' + color; - status.on('change', function(prev, prevMsg) { + status.on('change', function (prev, prevMsg) { expect(status.state).toBe(color); expect(status.message).toBe(message); @@ -129,10 +129,10 @@ describe('Status class', function() { status[color](message); }); - it(`should trigger the "${color}" listener when #${color}() is called`, function(done) { + it(`should trigger the "${color}" listener when #${color}() is called`, function (done) { const status = serverStatus.createForPlugin(plugin); const message = 'testing ' + color; - status.on(color, function() { + status.on(color, function () { expect(status.state).toBe(color); expect(status.message).toBe(message); done(); diff --git a/src/legacy/server/status/wrap_auth_config.js b/src/legacy/server/status/wrap_auth_config.js index a55318ee49582..04e71a02d30de 100644 --- a/src/legacy/server/status/wrap_auth_config.js +++ b/src/legacy/server/status/wrap_auth_config.js @@ -19,9 +19,9 @@ import { assign, identity } from 'lodash'; -export const wrapAuthConfig = allowAnonymous => { +export const wrapAuthConfig = (allowAnonymous) => { if (allowAnonymous) { - return options => assign(options, { config: { auth: false } }); + return (options) => assign(options, { config: { auth: false } }); } return identity; }; diff --git a/src/legacy/server/status/wrap_auth_config.test.js b/src/legacy/server/status/wrap_auth_config.test.js index 9b2a1c33d4ff1..fa0230a96a587 100644 --- a/src/legacy/server/status/wrap_auth_config.test.js +++ b/src/legacy/server/status/wrap_auth_config.test.js @@ -26,7 +26,7 @@ describe('Status wrapAuthConfig', () => { options = { method: 'GET', path: '/status', - handler: function(request, h) { + handler: function (request, h) { return h.response(); }, }; diff --git a/src/legacy/server/utils/prompt.js b/src/legacy/server/utils/prompt.js index 3fdac1b685808..2e53558213140 100644 --- a/src/legacy/server/utils/prompt.js +++ b/src/legacy/server/utils/prompt.js @@ -33,11 +33,11 @@ export function confirm(question, options = {}) { output: options.output || process.stdout, }); - return new Promise(resolve => { + return new Promise((resolve) => { const defaultValue = options.default ? true : false; const defaultPrompt = defaultValue ? 'Y/n' : 'y/N'; - rl.question(`${question} [${defaultPrompt}] `, input => { + rl.question(`${question} [${defaultPrompt}] `, (input) => { let value = defaultValue; if (input != null && input !== '') { @@ -65,8 +65,8 @@ export function question(question, options = {}) { const questionPrompt = `${question}: `; const rl = createInterface({ input, output }); - return new Promise(resolve => { - input.on('data', char => { + return new Promise((resolve) => { + input.on('data', (char) => { char = char + ''; switch (char) { @@ -85,7 +85,7 @@ export function question(question, options = {}) { } }); - rl.question(questionPrompt, value => { + rl.question(questionPrompt, (value) => { resolve(value); }); }); diff --git a/src/legacy/server/warnings/index.js b/src/legacy/server/warnings/index.js index 6fa29d0f407c6..e96366893076a 100644 --- a/src/legacy/server/warnings/index.js +++ b/src/legacy/server/warnings/index.js @@ -17,8 +17,8 @@ * under the License. */ -export default function(kbnServer, server) { - process.on('warning', warning => { +export default function (kbnServer, server) { + process.on('warning', (warning) => { // deprecation warnings do no reflect a current problem for // the user and therefor should be filtered out. if (warning.name === 'DeprecationWarning') { diff --git a/src/legacy/ui/__tests__/fixtures/plugin_async_foo/index.js b/src/legacy/ui/__tests__/fixtures/plugin_async_foo/index.js index 1c2d08c968dc0..afe618c6d3d9c 100644 --- a/src/legacy/ui/__tests__/fixtures/plugin_async_foo/index.js +++ b/src/legacy/ui/__tests__/fixtures/plugin_async_foo/index.js @@ -19,7 +19,7 @@ import Bluebird from 'bluebird'; -export default kibana => +export default (kibana) => new kibana.Plugin({ config(Joi) { return Joi.object() diff --git a/src/legacy/ui/__tests__/fixtures/plugin_bar/index.js b/src/legacy/ui/__tests__/fixtures/plugin_bar/index.js index 8c11a2ee160c0..975a1dc7c92e7 100644 --- a/src/legacy/ui/__tests__/fixtures/plugin_bar/index.js +++ b/src/legacy/ui/__tests__/fixtures/plugin_bar/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default kibana => +export default (kibana) => new kibana.Plugin({ config(Joi) { return Joi.object() diff --git a/src/legacy/ui/__tests__/fixtures/plugin_foo/index.js b/src/legacy/ui/__tests__/fixtures/plugin_foo/index.js index 8c11a2ee160c0..975a1dc7c92e7 100644 --- a/src/legacy/ui/__tests__/fixtures/plugin_foo/index.js +++ b/src/legacy/ui/__tests__/fixtures/plugin_foo/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default kibana => +export default (kibana) => new kibana.Plugin({ config(Joi) { return Joi.object() diff --git a/src/legacy/ui/__tests__/fixtures/test_app/index.js b/src/legacy/ui/__tests__/fixtures/test_app/index.js index 1491e6135c096..3eddefd618ce0 100644 --- a/src/legacy/ui/__tests__/fixtures/test_app/index.js +++ b/src/legacy/ui/__tests__/fixtures/test_app/index.js @@ -17,7 +17,7 @@ * under the License. */ -export default kibana => +export default (kibana) => new kibana.Plugin({ uiExports: { app: { diff --git a/src/legacy/ui/apm/index.js b/src/legacy/ui/apm/index.js index e2ff415865b56..f1074091e2624 100644 --- a/src/legacy/ui/apm/index.js +++ b/src/legacy/ui/apm/index.js @@ -30,22 +30,21 @@ export function apmInit(config) { return apmEnabled ? `init(${config})` : ''; } -export function getApmConfig(appMetadata) { +export function getApmConfig(app) { if (!apmEnabled) { - return {}; + return null; } /** * we use the injected app metadata from the server to extract the - * app URL path to be used for page-load transaction + * app id to be used for page-load transaction */ - const navLink = appMetadata.getNavLink(); - const pageUrl = navLink ? navLink.toJSON().url : appMetadata._url; + const appId = app.getId(); const config = { ...getConfig('kibana-frontend'), ...{ active: true, - pageLoadTransactionName: pageUrl, + pageLoadTransactionName: appId, }, }; /** diff --git a/src/legacy/ui/public/__tests__/events.js b/src/legacy/ui/public/__tests__/events.js index aff756cd1807d..c225c2a8ac1c0 100644 --- a/src/legacy/ui/public/__tests__/events.js +++ b/src/legacy/ui/public/__tests__/events.js @@ -26,7 +26,7 @@ import '../private'; import { createDefer } from 'ui/promises'; import { createLegacyClass } from '../utils/legacy_class'; -describe('Events', function() { +describe('Events', function () { require('test_utils/no_digest_promises').activateForSuite(); let Events; @@ -35,16 +35,16 @@ describe('Events', function() { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector, Private) { + ngMock.inject(function ($injector, Private) { Promise = $injector.get('Promise'); Events = Private(EventsProvider); eventsInstance = new Events(); }) ); - it('should handle on events', function() { + it('should handle on events', function () { const obj = new Events(); - const prom = obj.on('test', function(message) { + const prom = obj.on('test', function (message) { expect(message).to.equal('Hello World'); }); @@ -53,14 +53,14 @@ describe('Events', function() { return prom; }); - it('should work with inherited objects', function() { + it('should work with inherited objects', function () { createLegacyClass(MyEventedObject).inherits(Events); function MyEventedObject() { MyEventedObject.Super.call(this); } const obj = new MyEventedObject(); - const prom = obj.on('test', function(message) { + const prom = obj.on('test', function (message) { expect(message).to.equal('Hello World'); }); @@ -69,7 +69,7 @@ describe('Events', function() { return prom; }); - it('should clear events when off is called', function() { + it('should clear events when off is called', function () { const obj = new Events(); obj.on('test', _.noop); expect(obj._listeners).to.have.property('test'); @@ -78,7 +78,7 @@ describe('Events', function() { expect(obj._listeners).to.not.have.property('test'); }); - it('should clear a specific handler when off is called for an event', function() { + it('should clear a specific handler when off is called for an event', function () { const obj = new Events(); const handler1 = sinon.stub(); const handler2 = sinon.stub(); @@ -87,13 +87,13 @@ describe('Events', function() { expect(obj._listeners).to.have.property('test'); obj.off('test', handler1); - return obj.emit('test', 'Hello World').then(function() { + return obj.emit('test', 'Hello World').then(function () { sinon.assert.calledOnce(handler2); sinon.assert.notCalled(handler1); }); }); - it('should clear a all handlers when off is called for an event', function() { + it('should clear a all handlers when off is called for an event', function () { const obj = new Events(); const handler1 = sinon.stub(); obj.on('test', handler1); @@ -101,19 +101,19 @@ describe('Events', function() { obj.off('test'); expect(obj._listeners).to.not.have.property('test'); - return obj.emit('test', 'Hello World').then(function() { + return obj.emit('test', 'Hello World').then(function () { sinon.assert.notCalled(handler1); }); }); - it('should handle multiple identical emits in the same tick', function() { + it('should handle multiple identical emits in the same tick', function () { const obj = new Events(); const handler1 = sinon.stub(); obj.on('test', handler1); const emits = [obj.emit('test', 'one'), obj.emit('test', 'two'), obj.emit('test', 'three')]; - return Promise.all(emits).then(function() { + return Promise.all(emits).then(function () { expect(handler1.callCount).to.be(emits.length); expect(handler1.getCall(0).calledWith('one')).to.be(true); expect(handler1.getCall(1).calledWith('two')).to.be(true); @@ -121,11 +121,11 @@ describe('Events', function() { }); }); - it('should handle emits from the handler', function() { + it('should handle emits from the handler', function () { const obj = new Events(); const secondEmit = createDefer(Promise); - const handler1 = sinon.spy(function() { + const handler1 = sinon.spy(function () { if (handler1.calledTwice) { return; } @@ -134,12 +134,12 @@ describe('Events', function() { obj.on('test', handler1); - return Promise.all([obj.emit('test'), secondEmit.promise]).then(function() { + return Promise.all([obj.emit('test'), secondEmit.promise]).then(function () { expect(handler1.callCount).to.be(2); }); }); - it('should only emit to handlers registered before emit is called', function() { + it('should only emit to handlers registered before emit is called', function () { const obj = new Events(); const handler1 = sinon.stub(); const handler2 = sinon.stub(); @@ -147,34 +147,34 @@ describe('Events', function() { obj.on('test', handler1); const emits = [obj.emit('test', 'one'), obj.emit('test', 'two'), obj.emit('test', 'three')]; - return Promise.all(emits).then(function() { + return Promise.all(emits).then(function () { expect(handler1.callCount).to.be(emits.length); obj.on('test', handler2); const emits2 = [obj.emit('test', 'four'), obj.emit('test', 'five'), obj.emit('test', 'six')]; - return Promise.all(emits2).then(function() { + return Promise.all(emits2).then(function () { expect(handler1.callCount).to.be(emits.length + emits2.length); expect(handler2.callCount).to.be(emits2.length); }); }); }); - it('should pass multiple arguments from the emitter', function() { + it('should pass multiple arguments from the emitter', function () { const obj = new Events(); const handler = sinon.stub(); const payload = ['one', { hello: 'tests' }, null]; obj.on('test', handler); - return obj.emit('test', payload[0], payload[1], payload[2]).then(function() { + return obj.emit('test', payload[0], payload[1], payload[2]).then(function () { expect(handler.callCount).to.be(1); expect(handler.calledWithExactly(payload[0], payload[1], payload[2])).to.be(true); }); }); - it('should preserve the scope of the handler', function() { + it('should preserve the scope of the handler', function () { const obj = new Events(); const expected = 'some value'; let testValue; @@ -185,12 +185,12 @@ describe('Events', function() { handler.getVal = _.constant(expected); obj.on('test', handler); - return obj.emit('test').then(function() { + return obj.emit('test').then(function () { expect(testValue).to.equal(expected); }); }); - it('should always emit in the same order', function() { + it('should always emit in the same order', function () { const handler = sinon.stub(); const obj = new Events(); @@ -208,15 +208,15 @@ describe('Events', function() { obj.emit('block'), obj.emit('block'), obj.emit('last'), - ]).then(function() { + ]).then(function () { expect(handler.callCount).to.be(10); - handler.args.forEach(function(args, i) { + handler.args.forEach(function (args, i) { expect(args[0]).to.be(i < 9 ? 'block' : 'last'); }); }); }); - it('calls emitted handlers asynchronously', done => { + it('calls emitted handlers asynchronously', (done) => { const listenerStub = sinon.stub(); eventsInstance.on('test', listenerStub); eventsInstance.emit('test'); @@ -228,7 +228,7 @@ describe('Events', function() { }, 100); }); - it('calling off after an emit that has not yet triggered the handler, will not call the handler', done => { + it('calling off after an emit that has not yet triggered the handler, will not call the handler', (done) => { const listenerStub = sinon.stub(); eventsInstance.on('test', listenerStub); eventsInstance.emit('test'); diff --git a/src/legacy/ui/public/accessibility/__tests__/kbn_accessible_click.js b/src/legacy/ui/public/accessibility/__tests__/kbn_accessible_click.js index 381b8655ac374..5466e7d43f566 100644 --- a/src/legacy/ui/public/accessibility/__tests__/kbn_accessible_click.js +++ b/src/legacy/ui/public/accessibility/__tests__/kbn_accessible_click.js @@ -31,7 +31,7 @@ describe('kbnAccessibleClick directive', () => { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function(_$compile_, _$rootScope_) { + ngMock.inject(function (_$compile_, _$rootScope_) { $compile = _$compile_; $rootScope = _$rootScope_; }) @@ -103,7 +103,7 @@ describe('kbnAccessibleClick directive', () => { let scope; let element; - beforeEach(function() { + beforeEach(function () { scope = $rootScope.$new(); scope.handleClick = sinon.stub(); const html = `
`; diff --git a/src/legacy/ui/public/accessibility/angular_aria.js b/src/legacy/ui/public/accessibility/angular_aria.js index 00e773619aa50..4335eddf0d8cd 100644 --- a/src/legacy/ui/public/accessibility/angular_aria.js +++ b/src/legacy/ui/public/accessibility/angular_aria.js @@ -30,7 +30,7 @@ import { uiModules } from '../modules'; * handling keyboard events for `ngClick` directives. Kibana uses `kbnAccessibleClick` to handle * those cases where you need an `ngClick` non button element to have keyboard access. */ -uiModules.get('kibana', ['ngAria']).config($ariaProvider => { +uiModules.get('kibana', ['ngAria']).config(($ariaProvider) => { $ariaProvider.config({ bindKeydown: false, bindRoleForClick: false, diff --git a/src/legacy/ui/public/accessibility/kbn_ui_ace_keyboard_mode.js b/src/legacy/ui/public/accessibility/kbn_ui_ace_keyboard_mode.js index b18464b9ab90f..9ffcbc426e49c 100644 --- a/src/legacy/ui/public/accessibility/kbn_ui_ace_keyboard_mode.js +++ b/src/legacy/ui/public/accessibility/kbn_ui_ace_keyboard_mode.js @@ -71,7 +71,7 @@ uiModules hint.removeClass('kbnUiAceKeyboardHint-isInactive'); } - hint.keydown(ev => { + hint.keydown((ev) => { if (ev.keyCode === keyCodes.ENTER) { ev.preventDefault(); startEditing(); @@ -102,7 +102,7 @@ uiModules { capture: true } ); - uiAceTextbox.keydown(ev => { + uiAceTextbox.keydown((ev) => { if (ev.keyCode === keyCodes.ESCAPE) { // If the autocompletion context menu is open then we want to let ESC close it but // **not** exit out of editing mode. @@ -121,7 +121,7 @@ uiModules element.prepend(hint); }, })) - .directive('kbnUiAceKeyboardMode', kbnUiAceKeyboardModeService => ({ + .directive('kbnUiAceKeyboardMode', (kbnUiAceKeyboardModeService) => ({ restrict: 'A', link(scope, element) { kbnUiAceKeyboardModeService.initialize(scope, element); diff --git a/src/legacy/ui/public/accessibility/scrollto_activedescendant.js b/src/legacy/ui/public/accessibility/scrollto_activedescendant.js index d8883bd5d427b..1034cb1df3dda 100644 --- a/src/legacy/ui/public/accessibility/scrollto_activedescendant.js +++ b/src/legacy/ui/public/accessibility/scrollto_activedescendant.js @@ -30,7 +30,7 @@ uiModules.get('kibana').directive('scrolltoActivedescendant', () => ({ link(scope, element, attrs) { scope.$watch( () => attrs.ariaActivedescendant, - val => { + (val) => { if (val) { const activeDescendant = element.find(`#${val}`); if (activeDescendant.length) { diff --git a/src/legacy/ui/public/binder/__tests__/binder.js b/src/legacy/ui/public/binder/__tests__/binder.js index f30442c86d6ab..de30df36f6b2b 100644 --- a/src/legacy/ui/public/binder/__tests__/binder.js +++ b/src/legacy/ui/public/binder/__tests__/binder.js @@ -24,25 +24,25 @@ import ngMock from 'ng_mock'; import { Binder } from '..'; import $ from 'jquery'; -describe('Binder class', function() { +describe('Binder class', function () { let $scope; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($rootScope) { + ngMock.inject(function ($rootScope) { $scope = $rootScope.$new(); }) ); - describe('Constructing with a $scope', function() { - it('accepts a $scope and listens for $destroy', function() { + describe('Constructing with a $scope', function () { + it('accepts a $scope and listens for $destroy', function () { sinon.stub($scope, '$on'); new Binder($scope); expect($scope.$on.callCount).to.be(1); expect($scope.$on.args[0][0]).to.be('$destroy'); }); - it('unbinds when the $scope is destroyed', function() { + it('unbinds when the $scope is destroyed', function () { const binder = new Binder($scope); sinon.stub(binder, 'destroy'); $scope.$destroy(); @@ -50,8 +50,8 @@ describe('Binder class', function() { }); }); - describe('Binder#on', function() { - it('binds to normal event emitters', function() { + describe('Binder#on', function () { + it('binds to normal event emitters', function () { const binder = new Binder(); const emitter = { on: sinon.stub(), @@ -71,8 +71,8 @@ describe('Binder class', function() { }); }); - describe('Binder#jqOn', function() { - it('binds jquery event handlers', function() { + describe('Binder#jqOn', function () { + it('binds jquery event handlers', function () { const binder = new Binder(); const el = document.createElement('div'); const handler = sinon.stub(); diff --git a/src/legacy/ui/public/binder/binder.js b/src/legacy/ui/public/binder/binder.js index 8b0f95ab87fef..0d535d3bdcb0e 100644 --- a/src/legacy/ui/public/binder/binder.js +++ b/src/legacy/ui/public/binder/binder.js @@ -39,7 +39,7 @@ export class Binder extends BinderBase { } fakeD3Bind(el, event, handler) { - this.jqOn(el, event, e => { + this.jqOn(el, event, (e) => { // mimic https://github.com/mbostock/d3/blob/3abb00113662463e5c19eb87cd33f6d0ddc23bc0/src/selection/on.js#L87-L94 const o = d3.event; // Events can be reentrant (e.g., focus). d3.event = e; diff --git a/src/legacy/ui/public/bound_to_config_obj.js b/src/legacy/ui/public/bound_to_config_obj.js index 1bf13b4da951c..dc1eedebe2b77 100644 --- a/src/legacy/ui/public/bound_to_config_obj.js +++ b/src/legacy/ui/public/bound_to_config_obj.js @@ -37,7 +37,7 @@ export function BoundToConfigObjProvider(config) { function BoundToConfigObj(input) { const self = this; - _.forOwn(input, function(value, prop) { + _.forOwn(input, function (value, prop) { if (!_.isString(value) || value.charAt(0) !== '=') { self[prop] = value; return; diff --git a/src/legacy/ui/public/capabilities/react/ui_capabilities_provider.tsx b/src/legacy/ui/public/capabilities/react/ui_capabilities_provider.tsx index b6ffca350239c..90da657cc93e0 100644 --- a/src/legacy/ui/public/capabilities/react/ui_capabilities_provider.tsx +++ b/src/legacy/ui/public/capabilities/react/ui_capabilities_provider.tsx @@ -21,7 +21,7 @@ import React from 'react'; import { UICapabilitiesContext } from './ui_capabilities_context'; import { capabilities } from '..'; -export const UICapabilitiesProvider: React.FC = props => ( +export const UICapabilitiesProvider: React.FC = (props) => ( {props.children} diff --git a/src/legacy/ui/public/chrome/__mocks__/index.js b/src/legacy/ui/public/chrome/__mocks__/index.js index 8f88cf5c65ecf..d6f0df83a0e3d 100644 --- a/src/legacy/ui/public/chrome/__mocks__/index.js +++ b/src/legacy/ui/public/chrome/__mocks__/index.js @@ -27,7 +27,7 @@ const uiSettingsClient = { }; const chrome = { - addBasePath: path => (path ? path : 'test/base/path'), + addBasePath: (path) => (path ? path : 'test/base/path'), breadcrumbs: { set: () => ({}), }, @@ -58,8 +58,8 @@ const internals = _.defaults(_.cloneDeep(metadata), { applicationClasses: [], }); -const waitForBootstrap = new Promise(resolve => { - chrome.bootstrap = function(targetDomElement) { +const waitForBootstrap = new Promise((resolve) => { + chrome.bootstrap = function (targetDomElement) { // import chrome nav controls and hacks now so that they are executed after // everything else, can safely import the chrome, and interact with services // and such setup by all other modules @@ -79,7 +79,7 @@ const waitForBootstrap = new Promise(resolve => { }); chrome.dangerouslyGetActiveInjector = () => { - return waitForBootstrap.then(targetDomElement => { + return waitForBootstrap.then((targetDomElement) => { const $injector = angular.element(targetDomElement).injector(); if (!$injector) { return Promise.reject('targetDomElement had no angular context after bootstrapping'); diff --git a/src/legacy/ui/public/chrome/api/__tests__/apps.js b/src/legacy/ui/public/chrome/api/__tests__/apps.js index 7158b7ef22263..98da8db52bad1 100644 --- a/src/legacy/ui/public/chrome/api/__tests__/apps.js +++ b/src/legacy/ui/public/chrome/api/__tests__/apps.js @@ -21,43 +21,43 @@ import expect from '@kbn/expect'; import setup from '../apps'; -describe('Chrome API :: apps', function() { - describe('#get/setShowAppsLink()', function() { - describe('defaults to false if there are less than two apps', function() { - it('appCount = 0', function() { +describe('Chrome API :: apps', function () { + describe('#get/setShowAppsLink()', function () { + describe('defaults to false if there are less than two apps', function () { + it('appCount = 0', function () { const chrome = {}; setup(chrome, { nav: [] }); expect(chrome.getShowAppsLink()).to.equal(false); }); - it('appCount = 1', function() { + it('appCount = 1', function () { const chrome = {}; setup(chrome, { nav: [{ url: '/' }] }); expect(chrome.getShowAppsLink()).to.equal(false); }); }); - describe('defaults to true if there are two or more apps', function() { - it('appCount = 2', function() { + describe('defaults to true if there are two or more apps', function () { + it('appCount = 2', function () { const chrome = {}; setup(chrome, { nav: [{ url: '/' }, { url: '/2' }] }); expect(chrome.getShowAppsLink()).to.equal(true); }); - it('appCount = 3', function() { + it('appCount = 3', function () { const chrome = {}; setup(chrome, { nav: [{ url: '/' }, { url: '/2' }, { url: '/3' }] }); expect(chrome.getShowAppsLink()).to.equal(true); }); }); - it('is chainable', function() { + it('is chainable', function () { const chrome = {}; setup(chrome, { nav: [{ url: '/' }] }); expect(chrome.setShowAppsLink(true)).to.equal(chrome); }); - it('can be changed', function() { + it('can be changed', function () { const chrome = {}; setup(chrome, { nav: [{ url: '/' }] }); @@ -69,8 +69,8 @@ describe('Chrome API :: apps', function() { }); }); - describe('#getApp()', function() { - it('returns a clone of the current app', function() { + describe('#getApp()', function () { + it('returns a clone of the current app', function () { const chrome = {}; const app = { url: '/' }; setup(chrome, { app }); @@ -79,30 +79,30 @@ describe('Chrome API :: apps', function() { expect(chrome.getApp()).to.not.equal(app); }); - it('returns undefined if no active app', function() { + it('returns undefined if no active app', function () { const chrome = {}; setup(chrome, {}); expect(chrome.getApp()).to.equal(undefined); }); }); - describe('#getAppTitle()', function() { - it('returns the title property of the current app', function() { + describe('#getAppTitle()', function () { + it('returns the title property of the current app', function () { const chrome = {}; const app = { url: '/', title: 'foo' }; setup(chrome, { app }); expect(chrome.getAppTitle()).to.eql('foo'); }); - it('returns undefined if no active app', function() { + it('returns undefined if no active app', function () { const chrome = {}; setup(chrome, {}); expect(chrome.getAppTitle()).to.equal(undefined); }); }); - describe('#getAppUrl()', function() { - it('returns the resolved url of the current app', function() { + describe('#getAppUrl()', function () { + it('returns the resolved url of the current app', function () { const chrome = {}; const app = { navLink: { url: '/foo' } }; setup(chrome, { app }); @@ -112,7 +112,7 @@ describe('Chrome API :: apps', function() { expect(chrome.getAppUrl()).to.equal(a.href); }); - it('returns undefined if no active app', function() { + it('returns undefined if no active app', function () { const chrome = {}; setup(chrome, {}); expect(chrome.getAppUrl()).to.equal(undefined); diff --git a/src/legacy/ui/public/chrome/api/__tests__/nav.js b/src/legacy/ui/public/chrome/api/__tests__/nav.js index 877da3539828f..accb56dd42aa3 100644 --- a/src/legacy/ui/public/chrome/api/__tests__/nav.js +++ b/src/legacy/ui/public/chrome/api/__tests__/nav.js @@ -29,7 +29,7 @@ const basePath = '/someBasePath'; function init(customInternals = { basePath }) { const chrome = { - addBasePath: path => path, + addBasePath: (path) => path, getBasePath: () => customInternals.basePath || '', }; const internals = { @@ -40,11 +40,11 @@ function init(customInternals = { basePath }) { return { chrome, internals }; } -describe('chrome nav apis', function() { +describe('chrome nav apis', function () { let coreNavLinks; let fakedLinks = []; - const baseUrl = (function() { + const baseUrl = (function () { const a = document.createElement('a'); a.setAttribute('href', '/'); return a.href.slice(0, a.href.length - 1); @@ -60,7 +60,9 @@ describe('chrome nav apis', function() { return link; }); sinon.stub(coreNavLinks, 'getAll').callsFake(() => fakedLinks); - sinon.stub(coreNavLinks, 'get').callsFake(linkId => fakedLinks.find(({ id }) => id === linkId)); + sinon + .stub(coreNavLinks, 'get') + .callsFake((linkId) => fakedLinks.find(({ id }) => id === linkId)); }); afterEach(() => { @@ -69,12 +71,12 @@ describe('chrome nav apis', function() { coreNavLinks.get.restore(); }); - describe('#untrackNavLinksForDeletedSavedObjects', function() { + describe('#untrackNavLinksForDeletedSavedObjects', function () { const appId = 'appId'; const appUrl = `${baseUrl}/app/kibana#test`; const deletedId = 'IAMDELETED'; - it('should clear last url when last url contains link to deleted saved object', function() { + it('should clear last url when last url contains link to deleted saved object', function () { const appUrlStore = new StubBrowserStorage(); fakedLinks = [ { @@ -92,7 +94,7 @@ describe('chrome nav apis', function() { expect(coreNavLinks.update.calledWith(appId, { url: appUrl })).to.be(true); }); - it('should not clear last url when last url does not contains link to deleted saved object', function() { + it('should not clear last url when last url does not contains link to deleted saved object', function () { const lastUrl = `${appUrl}?id=anotherSavedObjectId`; const appUrlStore = new StubBrowserStorage(); fakedLinks = [ @@ -112,8 +114,8 @@ describe('chrome nav apis', function() { }); }); - describe('chrome.trackSubUrlForApp()', function() { - it('injects a manual app url', function() { + describe('chrome.trackSubUrlForApp()', function () { + it('injects a manual app url', function () { const appUrlStore = new StubBrowserStorage(); fakedLinks = [ { diff --git a/src/legacy/ui/public/chrome/api/__tests__/sub_url_route_filter.js b/src/legacy/ui/public/chrome/api/__tests__/sub_url_route_filter.js index 0fc4d9c1cdccd..901fbd1d0edf6 100644 --- a/src/legacy/ui/public/chrome/api/__tests__/sub_url_route_filter.js +++ b/src/legacy/ui/public/chrome/api/__tests__/sub_url_route_filter.js @@ -26,14 +26,14 @@ describe('kbn-chrome subUrlRouteFilter()', () => { describe('no ngRoute', () => { beforeEach(ngMock.module('kibana/private')); beforeEach( - ngMock.inject($injector => { + ngMock.inject(($injector) => { expect($injector.has('$route')).to.be(false); }) ); it( 'always returns true when there is no $route service', - ngMock.inject(Private => { + ngMock.inject((Private) => { const subUrlRouteFilter = Private(SubUrlRouteFilterProvider); expect(subUrlRouteFilter()).to.be(true); }) @@ -42,7 +42,7 @@ describe('kbn-chrome subUrlRouteFilter()', () => { describe('with ngRoute', () => { beforeEach( - ngMock.module('kibana/private', 'ngRoute', $routeProvider => { + ngMock.module('kibana/private', 'ngRoute', ($routeProvider) => { $routeProvider.when('/foo', { redirectTo: '/bar', }); diff --git a/src/legacy/ui/public/chrome/api/__tests__/xsrf.js b/src/legacy/ui/public/chrome/api/__tests__/xsrf.js index 54ecd4ee2ca1c..3197b79f407da 100644 --- a/src/legacy/ui/public/chrome/api/__tests__/xsrf.js +++ b/src/legacy/ui/public/chrome/api/__tests__/xsrf.js @@ -24,15 +24,15 @@ import { initChromeXsrfApi } from '../xsrf'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { version } from '../../../../../../core/server/utils/package_json'; -describe('chrome xsrf apis', function() { +describe('chrome xsrf apis', function () { const sandbox = sinon.createSandbox(); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - describe('#getXsrfToken()', function() { - it('exposes the token', function() { + describe('#getXsrfToken()', function () { + it('exposes the token', function () { const chrome = {}; initChromeXsrfApi(chrome, { version }); expect(chrome.getXsrfToken()).to.be(version); diff --git a/src/legacy/ui/public/chrome/api/angular.js b/src/legacy/ui/public/chrome/api/angular.js index bad6e5f12f0d7..a9113b2df2ed7 100644 --- a/src/legacy/ui/public/chrome/api/angular.js +++ b/src/legacy/ui/public/chrome/api/angular.js @@ -25,7 +25,7 @@ import { configureAppAngularModule } from 'ui/legacy_compat'; import { npStart } from '../../new_platform/new_platform'; export function initAngularApi(chrome, internals) { - chrome.setupAngular = function() { + chrome.setupAngular = function () { const kibana = uiModules.get('kibana'); configureAppAngularModule(kibana, npStart.core, false); diff --git a/src/legacy/ui/public/chrome/api/apps.js b/src/legacy/ui/public/chrome/api/apps.js index 23eb84fda97a3..c4cbe7be6f1c3 100644 --- a/src/legacy/ui/public/chrome/api/apps.js +++ b/src/legacy/ui/public/chrome/api/apps.js @@ -21,7 +21,7 @@ import { clone, get } from 'lodash'; import { resolve } from 'url'; // eslint-disable-next-line import/no-default-export -export default function(chrome, internals) { +export default function (chrome, internals) { if (get(internals, 'app.navLink.url')) { internals.app.navLink.url = resolve(window.location.href, internals.app.navLink.url); } @@ -48,36 +48,36 @@ export default function(chrome, internals) { * than one app installed. */ - chrome.setShowAppsLink = function(val) { + chrome.setShowAppsLink = function (val) { internals.showAppsLink = !!val; return chrome; }; - chrome.getShowAppsLink = function() { + chrome.getShowAppsLink = function () { return internals.showAppsLink == null ? internals.nav.length > 1 : internals.showAppsLink; }; - chrome.getKibanaVersion = function() { + chrome.getKibanaVersion = function () { return internals.version; }; - chrome.getApp = function() { + chrome.getApp = function () { return clone(internals.app); }; - chrome.getAppTitle = function() { + chrome.getAppTitle = function () { return get(internals, ['app', 'title']); }; - chrome.getAppUrl = function() { + chrome.getAppUrl = function () { return get(internals, ['app', 'navLink', 'url']); }; - chrome.getLastUrlFor = function(appId) { + chrome.getLastUrlFor = function (appId) { return internals.appUrlStore.getItem(`appLastUrl:${appId}`); }; - chrome.setLastUrlFor = function(appId, url) { + chrome.setLastUrlFor = function (appId, url) { internals.appUrlStore.setItem(`appLastUrl:${appId}`, url); }; } diff --git a/src/legacy/ui/public/chrome/api/nav.ts b/src/legacy/ui/public/chrome/api/nav.ts index ae32473e451b7..2b655419d98aa 100644 --- a/src/legacy/ui/public/chrome/api/nav.ts +++ b/src/legacy/ui/public/chrome/api/nav.ts @@ -41,13 +41,13 @@ export function initChromeNavApi(chrome: any, internals: NavInternals) { */ chrome.untrackNavLinksForDeletedSavedObjects = (deletedIds: string[]) => { function urlContainsDeletedId(url: string) { - const includedId = deletedIds.find(deletedId => { + const includedId = deletedIds.find((deletedId) => { return url.includes(deletedId); }); return includedId !== undefined; } - coreNavLinks.getAll().forEach(link => { + coreNavLinks.getAll().forEach((link) => { if (link.linkToLastSubUrl && urlContainsDeletedId(link.url!)) { setLastUrl(link, link.baseUrl); } @@ -72,14 +72,14 @@ export function initChromeNavApi(chrome: any, internals: NavInternals) { } }; - internals.trackPossibleSubUrl = async function(url: string) { + internals.trackPossibleSubUrl = async function (url: string) { const kibanaParsedUrl = absoluteToParsedUrl(url, chrome.getBasePath()); coreNavLinks .getAll() // Filter only legacy links - .filter(link => link.legacy && !link.disableSubUrlTracking) - .forEach(link => { + .filter((link) => link.legacy && !link.disableSubUrlTracking) + .forEach((link) => { const active = url.startsWith(link.subUrlBase!); link = coreNavLinks.update(link.id, { active })!; @@ -146,8 +146,8 @@ export function initChromeNavApi(chrome: any, internals: NavInternals) { // link.active and link.lastUrl properties coreNavLinks .getAll() - .filter(link => link.subUrlBase && !link.disableSubUrlTracking) - .forEach(link => { + .filter((link) => link.subUrlBase && !link.disableSubUrlTracking) + .forEach((link) => { coreNavLinks.update(link.id, { subUrlBase: relativeToAbsolute(chrome.addBasePath(link.subUrlBase)), }); diff --git a/src/legacy/ui/public/chrome/api/saved_object_client.ts b/src/legacy/ui/public/chrome/api/saved_object_client.ts index b42e74e5a5865..76d4e301e3c77 100644 --- a/src/legacy/ui/public/chrome/api/saved_object_client.ts +++ b/src/legacy/ui/public/chrome/api/saved_object_client.ts @@ -23,7 +23,7 @@ import { Chrome } from '..'; const savedObjectsClient = npStart.core.savedObjects.client; export function initSavedObjectClient(chrome: Chrome) { - chrome.getSavedObjectsClient = function() { + chrome.getSavedObjectsClient = function () { return savedObjectsClient; }; } diff --git a/src/legacy/ui/public/chrome/api/template.js b/src/legacy/ui/public/chrome/api/template.js index 8c3100ab87a27..d29a7eba7316f 100644 --- a/src/legacy/ui/public/chrome/api/template.js +++ b/src/legacy/ui/public/chrome/api/template.js @@ -18,7 +18,7 @@ */ // eslint-disable-next-line import/no-default-export -export default function(chrome, internals) { +export default function (chrome, internals) { /** * ui/chrome Template API * @@ -48,7 +48,7 @@ export default function(chrome, internals) { * @param {string} template * @return {chrome} */ - chrome.setRootTemplate = function(template) { + chrome.setRootTemplate = function (template) { internals.rootTemplate = template; return chrome; }; @@ -58,7 +58,7 @@ export default function(chrome, internals) { * @param {Function} controller - the controller initializer function * @return {chrome} */ - chrome.setRootController = function(as, controllerName) { + chrome.setRootController = function (as, controllerName) { if (controllerName === undefined) { controllerName = as; as = null; diff --git a/src/legacy/ui/public/chrome/api/ui_settings.js b/src/legacy/ui/public/chrome/api/ui_settings.js index bd5c7a39b17ed..dbdd6a9c12653 100644 --- a/src/legacy/ui/public/chrome/api/ui_settings.js +++ b/src/legacy/ui/public/chrome/api/ui_settings.js @@ -22,7 +22,7 @@ import { npSetup } from 'ui/new_platform'; const newPlatformUiSettingsClient = npSetup.core.uiSettings; export function initUiSettingsApi(chrome) { - chrome.getUiSettingsClient = function() { + chrome.getUiSettingsClient = function () { return newPlatformUiSettingsClient; }; } diff --git a/src/legacy/ui/public/chrome/api/xsrf.js b/src/legacy/ui/public/chrome/api/xsrf.js index 56a69696a3464..5086903604667 100644 --- a/src/legacy/ui/public/chrome/api/xsrf.js +++ b/src/legacy/ui/public/chrome/api/xsrf.js @@ -18,7 +18,7 @@ */ export function initChromeXsrfApi(chrome, internals) { - chrome.getXsrfToken = function() { + chrome.getXsrfToken = function () { return internals.version; }; } diff --git a/src/legacy/ui/public/chrome/chrome.js b/src/legacy/ui/public/chrome/chrome.js index 7a75ad906a870..0640017f7806a 100644 --- a/src/legacy/ui/public/chrome/chrome.js +++ b/src/legacy/ui/public/chrome/chrome.js @@ -79,8 +79,8 @@ initChromeThemeApi(chrome); npStart.core.chrome.setAppTitle(chrome.getAppTitle()); -const waitForBootstrap = new Promise(resolve => { - chrome.bootstrap = function(targetDomElement) { +const waitForBootstrap = new Promise((resolve) => { + chrome.bootstrap = function (targetDomElement) { // import chrome nav controls and hacks now so that they are executed after // everything else, can safely import the chrome, and interact with services // and such setup by all other modules @@ -114,7 +114,7 @@ const waitForBootstrap = new Promise(resolve => { * tests. Look into 'src/test_utils/public/stub_get_active_injector' for more information. */ chrome.dangerouslyGetActiveInjector = () => { - return waitForBootstrap.then(targetDomElement => { + return waitForBootstrap.then((targetDomElement) => { const $injector = angular.element(targetDomElement).injector(); if (!$injector) { return Promise.reject('targetDomElement had no angular context after bootstrapping'); diff --git a/src/legacy/ui/public/chrome/directives/kbn_chrome.js b/src/legacy/ui/public/chrome/directives/kbn_chrome.js index 45da4ab6b7472..5ba34e553201e 100644 --- a/src/legacy/ui/public/chrome/directives/kbn_chrome.js +++ b/src/legacy/ui/public/chrome/directives/kbn_chrome.js @@ -60,13 +60,13 @@ export function kbnChromeProvider(chrome, internals) { // Continue to support legacy nav controls not registered with the NP. const navControls = Private(chromeHeaderNavControlsRegistry); - (navControls.bySide[NavControlSide.Left] || []).forEach(navControl => + (navControls.bySide[NavControlSide.Left] || []).forEach((navControl) => npStart.core.chrome.navControls.registerLeft({ order: navControl.order, mount: navControl.render, }) ); - (navControls.bySide[NavControlSide.Right] || []).forEach(navControl => + (navControls.bySide[NavControlSide.Right] || []).forEach((navControl) => npStart.core.chrome.navControls.registerRight({ order: navControl.order, mount: navControl.render, diff --git a/src/legacy/ui/public/config/__tests__/config.js b/src/legacy/ui/public/config/__tests__/config.js index 843fa864453fd..90dbdaf264a29 100644 --- a/src/legacy/ui/public/config/__tests__/config.js +++ b/src/legacy/ui/public/config/__tests__/config.js @@ -31,7 +31,7 @@ describe('Config service', () => { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject($injector => { + ngMock.inject(($injector) => { config = $injector.get('config'); uiSettings = chrome.getUiSettingsClient(); $q = $injector.get('$q'); @@ -191,8 +191,8 @@ describe('Config service', () => { it('synchronously emits events when changes are outside a digest cycle', async () => { const stub = sinon.stub(); - await new Promise(resolve => { - setTimeout(function() { + await new Promise((resolve) => { + setTimeout(function () { const off = $rootScope.$on('change:config.foobar', stub); config.set('foobar', 'baz'); // we unlisten to make sure that stub is not called before our assertions below diff --git a/src/legacy/ui/public/config/config.js b/src/legacy/ui/public/config/config.js index 80a9d39221b2c..a8f24c126caff 100644 --- a/src/legacy/ui/public/config/config.js +++ b/src/legacy/ui/public/config/config.js @@ -31,7 +31,7 @@ const module = uiModules.get('kibana/config'); * to expose the exact same API as the config service that has existed since forever. * @name config */ -module.service(`config`, function($rootScope, Promise) { +module.service(`config`, function ($rootScope, Promise) { const uiSettings = chrome.getUiSettingsClient(); // direct bind sync methods @@ -43,7 +43,7 @@ module.service(`config`, function($rootScope, Promise) { this.isOverridden = (...args) => uiSettings.isOverridden(...args); // modify remove() to use angular Promises - this.remove = key => Promise.resolve(uiSettings.remove(key)); + this.remove = (key) => Promise.resolve(uiSettings.remove(key)); // modify set() to use angular Promises and angular.toJson() this.set = (key, value) => @@ -66,7 +66,7 @@ module.service(`config`, function($rootScope, Promise) { ); $rootScope.$on('$destroy', () => subscription.unsubscribe()); - this.watchAll = function(handler, scope = $rootScope) { + this.watchAll = function (handler, scope = $rootScope) { // call handler immediately to initialize handler(null, null, null, this); @@ -75,7 +75,7 @@ module.service(`config`, function($rootScope, Promise) { }); }; - this.watch = function(key, handler, scope = $rootScope) { + this.watch = function (key, handler, scope = $rootScope) { if (!this.isDeclared(key)) { throw new Error(`Unexpected \`config.watch("${key}", fn)\` call on unrecognized configuration setting "${key}". Setting an initial value via \`config.set("${key}", value)\` before binding @@ -100,8 +100,8 @@ any custom setting configuration watchers for "${key}" may fix this issue.`); * be stored. Defaults to the config key * @return {function} - an unbind function */ - this.bindToScope = function(scope, key, property = key) { - const onUpdate = newVal => { + this.bindToScope = function (scope, key, property = key) { + const onUpdate = (newVal) => { scope[property] = newVal; }; diff --git a/src/legacy/ui/public/directives/__tests__/input_focus.js b/src/legacy/ui/public/directives/__tests__/input_focus.js index 840803c4d28a0..45b1821cbfd21 100644 --- a/src/legacy/ui/public/directives/__tests__/input_focus.js +++ b/src/legacy/ui/public/directives/__tests__/input_focus.js @@ -22,7 +22,7 @@ import ngMock from 'ng_mock'; import $ from 'jquery'; import '../input_focus'; -describe('Input focus directive', function() { +describe('Input focus directive', function () { let $compile; let $rootScope; let $timeout; @@ -34,7 +34,7 @@ describe('Input focus directive', function() { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function(_$compile_, _$rootScope_, _$timeout_) { + ngMock.inject(function (_$compile_, _$rootScope_, _$timeout_) { $compile = _$compile_; $rootScope = _$rootScope_; $timeout = _$timeout_; @@ -44,7 +44,7 @@ describe('Input focus directive', function() { }) ); - afterEach(function() { + afterEach(function () { $el.remove(); $el = null; }); @@ -61,25 +61,25 @@ describe('Input focus directive', function() { } } - it('should focus the input', function() { + it('should focus the input', function () { renderEl(''); expect(selectedEl).to.equal(element[0]); expect(selectedText.length).to.equal(0); }); - it('should select the text in the input', function() { + it('should select the text in the input', function () { renderEl(''); expect(selectedEl).to.equal(element[0]); expect(selectedText.length).to.equal(inputValue.length); expect(selectedText).to.equal(inputValue); }); - it('should not focus the input if disable-input-focus is set to true on the same element', function() { + it('should not focus the input if disable-input-focus is set to true on the same element', function () { renderEl(''); expect(selectedEl).not.to.be(element[0]); }); - it('should still focus the input if disable-input-focus is falsy', function() { + it('should still focus the input if disable-input-focus is falsy', function () { renderEl(''); expect(selectedEl).to.be(element[0]); }); diff --git a/src/legacy/ui/public/directives/bind/__tests__/bind.js b/src/legacy/ui/public/directives/bind/__tests__/bind.js index 1d2b46b2e0523..658a726e8c4cf 100644 --- a/src/legacy/ui/public/directives/bind/__tests__/bind.js +++ b/src/legacy/ui/public/directives/bind/__tests__/bind.js @@ -19,19 +19,19 @@ import expect from '@kbn/expect'; import ngMock from 'ng_mock'; -describe('$scope.$bind', function() { +describe('$scope.$bind', function () { let $rootScope; let $scope; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $rootScope = $injector.get('$rootScope'); $scope = $rootScope.$new(); }) ); - it('exposes $bind on all scopes', function() { + it('exposes $bind on all scopes', function () { expect($rootScope.$bind).to.be.a('function'); expect($scope).to.have.property('$bind', $rootScope.$bind); @@ -39,7 +39,7 @@ describe('$scope.$bind', function() { expect($isoScope).to.have.property('$bind', $rootScope.$bind); }); - it("sets up binding from a parent scope to it's child", function() { + it("sets up binding from a parent scope to it's child", function () { $rootScope.val = 'foo'; $scope.$bind('localVal', 'val'); expect($scope.localVal).to.be('foo'); @@ -51,7 +51,7 @@ describe('$scope.$bind', function() { expect($scope.localVal).to.be('bar'); }); - it('sets up a binding from the child to the parent scope', function() { + it('sets up a binding from the child to the parent scope', function () { $rootScope.val = 'foo'; $scope.$bind('localVal', 'val'); expect($scope.localVal).to.be('foo'); @@ -63,7 +63,7 @@ describe('$scope.$bind', function() { expect($rootScope.val).to.be('bar'); }); - it('pulls from the scopes $parent by default', function() { + it('pulls from the scopes $parent by default', function () { const $parent = $rootScope.$new(); const $self = $parent.$new(); @@ -74,7 +74,7 @@ describe('$scope.$bind', function() { expect($self.localVal).to.be('foo'); }); - it('accepts an alternate scope to read from', function() { + it('accepts an alternate scope to read from', function () { const $parent = $rootScope.$new(); const $self = $parent.$new(); diff --git a/src/legacy/ui/public/directives/bind/bind.js b/src/legacy/ui/public/directives/bind/bind.js index 490816501564d..a9210cace5cea 100644 --- a/src/legacy/ui/public/directives/bind/bind.js +++ b/src/legacy/ui/public/directives/bind/bind.js @@ -20,7 +20,7 @@ import angular from 'angular'; import { uiModules } from '../../modules'; -uiModules.get('kibana').config(function($provide) { +uiModules.get('kibana').config(function ($provide) { function strictEquality(a, b) { // are the values equal? or, are they both NaN? return a === b || (a !== a && b !== b); @@ -37,7 +37,7 @@ uiModules.get('kibana').config(function($provide) { ); } - $provide.decorator('$rootScope', function($delegate, $parse) { + $provide.decorator('$rootScope', function ($delegate, $parse) { /** * Two-way bind a value from scope to another property on scope. This * allow values on scope that work like they do in an isolate scope, but @@ -48,7 +48,7 @@ uiModules.get('kibana').config(function($provide) { * @param {Scope} $sourceScope - the scope to read "from" expression from * @return {undefined} */ - $delegate.constructor.prototype.$bind = function(to, from, $sourceScope) { + $delegate.constructor.prototype.$bind = function (to, from, $sourceScope) { const $source = $sourceScope || this.$parent; const $target = this; @@ -58,16 +58,16 @@ uiModules.get('kibana').config(function($provide) { const $from = $parse(from); // bind scopes to expressions - const getTarget = function() { + const getTarget = function () { return $to($target); }; - const setTarget = function(v) { + const setTarget = function (v) { return $to.assign($target, v); }; - const getSource = function() { + const getSource = function () { return $from($source); }; - const setSource = function(v) { + const setSource = function (v) { return $from.assignOrFail($source, v); }; @@ -80,7 +80,7 @@ uiModules.get('kibana').config(function($provide) { $from.assignOrFail = $from.assign || - function() { + function () { // revert the change and throw an error, child writes aren't supported $to($target, (lastSourceVal = $from($source))); errorNotAssignable(from, to); @@ -94,7 +94,7 @@ uiModules.get('kibana').config(function($provide) { setTarget(lastSourceVal); $target.$watch( - function() { + function () { const sourceVal = getSource(); const targetVal = getTarget(); diff --git a/src/legacy/ui/public/directives/input_focus.js b/src/legacy/ui/public/directives/input_focus.js index d9f744cb77de1..f047ff2547ba2 100644 --- a/src/legacy/ui/public/directives/input_focus.js +++ b/src/legacy/ui/public/directives/input_focus.js @@ -20,13 +20,13 @@ import { uiModules } from '../modules'; const module = uiModules.get('kibana'); -module.directive('inputFocus', function($parse, $timeout) { +module.directive('inputFocus', function ($parse, $timeout) { return { restrict: 'A', - link: function($scope, $elem, attrs) { + link: function ($scope, $elem, attrs) { const isDisabled = attrs.disableInputFocus && $parse(attrs.disableInputFocus)($scope); if (!isDisabled) { - $timeout(function() { + $timeout(function () { $elem.focus(); if (attrs.inputFocus === 'select') $elem.select(); }); diff --git a/src/legacy/ui/public/directives/kbn_href.js b/src/legacy/ui/public/directives/kbn_href.js index d7a5f886fd4e0..5c71396e6c4de 100644 --- a/src/legacy/ui/public/directives/kbn_href.js +++ b/src/legacy/ui/public/directives/kbn_href.js @@ -23,11 +23,11 @@ import { words, kebabCase } from 'lodash'; export function kbnUrlDirective(name) { const attr = kebabCase(words(name).slice(1)); - uiModules.get('kibana').directive(name, function(chrome) { + uiModules.get('kibana').directive(name, function (chrome) { return { restrict: 'A', - link: function($scope, $el, $attr) { - $attr.$observe(name, function(val) { + link: function ($scope, $el, $attr) { + $attr.$observe(name, function (val) { $attr.$set(attr, chrome.addBasePath(val)); }); }, diff --git a/src/legacy/ui/public/directives/listen/__tests__/listen.js b/src/legacy/ui/public/directives/listen/__tests__/listen.js index 7aa1a2d0e430c..9a1d482956154 100644 --- a/src/legacy/ui/public/directives/listen/__tests__/listen.js +++ b/src/legacy/ui/public/directives/listen/__tests__/listen.js @@ -23,24 +23,24 @@ import ngMock from 'ng_mock'; import '..'; import { EventsProvider } from '../../../events'; -describe('listen component', function() { +describe('listen component', function () { let $rootScope; let Events; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector, Private) { + ngMock.inject(function ($injector, Private) { $rootScope = $injector.get('$rootScope'); Events = Private(EventsProvider); }) ); - it('exposes the $listen method on all scopes', function() { + it('exposes the $listen method on all scopes', function () { expect($rootScope.$listen).to.be.a('function'); expect($rootScope.$new().$listen).to.be.a('function'); }); - it('binds to an event emitter', function() { + it('binds to an event emitter', function () { const emitter = new Events(); const $scope = $rootScope.$new(); @@ -51,7 +51,7 @@ describe('listen component', function() { expect(emitter._listeners.hello[0].handler).to.be(handler); }); - it('binds to $scope, waiting for the destroy event', function() { + it('binds to $scope, waiting for the destroy event', function () { const emitter = new Events(); const $scope = $rootScope.$new(); @@ -69,7 +69,7 @@ describe('listen component', function() { expect(call.args[1]).to.be.a('function'); }); - it('unbinds the event handler when $destroy is triggered', function() { + it('unbinds the event handler when $destroy is triggered', function () { const emitter = new Events(); const $scope = $rootScope.$new(); diff --git a/src/legacy/ui/public/directives/render_directive/__tests__/render_directive.js b/src/legacy/ui/public/directives/render_directive/__tests__/render_directive.js index 313f9e12b017a..a604eca52affe 100644 --- a/src/legacy/ui/public/directives/render_directive/__tests__/render_directive.js +++ b/src/legacy/ui/public/directives/render_directive/__tests__/render_directive.js @@ -27,10 +27,10 @@ let init; let $rootScope; let $compile; -describe('render_directive', function() { +describe('render_directive', function () { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $rootScope = $injector.get('$rootScope'); $compile = $injector.get('$compile'); init = function init(markup = '', definition = {}) { @@ -55,14 +55,14 @@ describe('render_directive', function() { }) ); - describe('directive requirements', function() { - it('should throw if not given a definition', function() { + describe('directive requirements', function () { + it('should throw if not given a definition', function () { expect(() => init('', null)).to.throwException(/must have a definition/); }); }); - describe('rendering with definition', function() { - it('should call link method', function() { + describe('rendering with definition', function () { + it('should call link method', function () { const markup = '

hello world

'; const definition = { link: sinon.stub(), @@ -73,7 +73,7 @@ describe('render_directive', function() { sinon.assert.callCount(definition.link, 1); }); - it('should call controller method', function() { + it('should call controller method', function () { const markup = '

hello world

'; const definition = { controller: sinon.stub(), @@ -85,8 +85,8 @@ describe('render_directive', function() { }); }); - describe('definition scope binding', function() { - it('should accept two-way, attribute, and expression binding directives', function() { + describe('definition scope binding', function () { + it('should accept two-way, attribute, and expression binding directives', function () { const $el = angular.element(` { if (!bindingRE.test(binding)) { throw new Error(`Invalid scope binding "${binding}". Expected it to match ${bindingRE}`); @@ -44,7 +44,7 @@ export function ApplyScopeBindingsProvider($parse) { case '&': if (attr) { const getter = $parse(attr); - $scope[local] = function() { + $scope[local] = function () { return getter($scope.$parent); }; } else { @@ -53,7 +53,7 @@ export function ApplyScopeBindingsProvider($parse) { break; case '@': $scope[local] = attr; - $attrs.$observe(attribute, v => ($scope[local] = v)); + $attrs.$observe(attribute, (v) => ($scope[local] = v)); break; } }); diff --git a/src/legacy/ui/public/directives/render_directive/render_directive.js b/src/legacy/ui/public/directives/render_directive/render_directive.js index 1d28377ef9126..a5232f39b82c3 100644 --- a/src/legacy/ui/public/directives/render_directive/render_directive.js +++ b/src/legacy/ui/public/directives/render_directive/render_directive.js @@ -43,7 +43,7 @@ import { ApplyScopeBindingsProvider } from './apply_scope_bindings'; * @param [Object|Function] definition.link - either a post link function or an object with pre and/or * post link functions. */ -uiModules.get('kibana').directive('renderDirective', function(Private) { +uiModules.get('kibana').directive('renderDirective', function (Private) { const applyScopeBindings = Private(ApplyScopeBindingsProvider); return { @@ -51,10 +51,10 @@ uiModules.get('kibana').directive('renderDirective', function(Private) { scope: { definition: '=', }, - template: function($el) { + template: function ($el) { return $el.html(); }, - controller: function($scope, $element, $attrs, $transclude, $injector) { + controller: function ($scope, $element, $attrs, $transclude, $injector) { if (!$scope.definition) throw new Error('render-directive must have a definition attribute'); const { controller, controllerAs, scope } = $scope.definition; diff --git a/src/legacy/ui/public/directives/storage/index.js b/src/legacy/ui/public/directives/storage/index.js index 80e4c3b645108..7c195ecc85d2f 100644 --- a/src/legacy/ui/public/directives/storage/index.js +++ b/src/legacy/ui/public/directives/storage/index.js @@ -20,8 +20,8 @@ import { uiModules } from '../../modules'; import { Storage } from '../../../../../plugins/kibana_utils/public'; -const createService = function(type) { - return function($window) { +const createService = function (type) { + return function ($window) { return new Storage($window[type]); }; }; diff --git a/src/legacy/ui/public/directives/watch_multi/__tests__/watch_multi.js b/src/legacy/ui/public/directives/watch_multi/__tests__/watch_multi.js index 7aab953c55ac7..0de41a5ae57cb 100644 --- a/src/legacy/ui/public/directives/watch_multi/__tests__/watch_multi.js +++ b/src/legacy/ui/public/directives/watch_multi/__tests__/watch_multi.js @@ -22,20 +22,20 @@ import ngMock from 'ng_mock'; import expect from '@kbn/expect'; import sinon from 'sinon'; -describe('$scope.$watchMulti', function() { +describe('$scope.$watchMulti', function () { let $rootScope; let $scope; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $rootScope = $injector.get('$rootScope'); $scope = $rootScope.$new(); }) ); - describe('basic functionality', function() { - it('exposes $watchMulti on all scopes', function() { + describe('basic functionality', function () { + it('exposes $watchMulti on all scopes', function () { expect($rootScope.$watchMulti).to.be.a('function'); expect($scope).to.have.property('$watchMulti', $rootScope.$watchMulti); @@ -43,11 +43,11 @@ describe('$scope.$watchMulti', function() { expect($isoScope).to.have.property('$watchMulti', $rootScope.$watchMulti); }); - it('returns a working unwatch function', function() { + it('returns a working unwatch function', function () { $scope.a = 0; $scope.b = 0; let triggers = 0; - const unwatch = $scope.$watchMulti(['a', 'b'], function() { + const unwatch = $scope.$watchMulti(['a', 'b'], function () { triggers++; }); @@ -72,8 +72,8 @@ describe('$scope.$watchMulti', function() { }); }); - describe('simple scope watchers', function() { - it('only triggers a single watch on initialization', function() { + describe('simple scope watchers', function () { + it('only triggers a single watch on initialization', function () { const stub = sinon.stub(); $scope.$watchMulti(['one', 'two', 'three'], stub); @@ -82,8 +82,8 @@ describe('$scope.$watchMulti', function() { expect(stub.callCount).to.be(1); }); - it('only triggers a single watch when multiple values change', function() { - const stub = sinon.spy(function() {}); + it('only triggers a single watch when multiple values change', function () { + const stub = sinon.spy(function () {}); $scope.$watchMulti(['one', 'two', 'three'], stub); @@ -98,8 +98,8 @@ describe('$scope.$watchMulti', function() { expect(stub.callCount).to.be(2); }); - it('passes an array of the current and previous values, in order', function() { - const stub = sinon.spy(function() {}); + it('passes an array of the current and previous values, in order', function () { + const stub = sinon.spy(function () {}); $scope.one = 'a'; $scope.two = 'b'; @@ -123,17 +123,17 @@ describe('$scope.$watchMulti', function() { ]); }); - it('always has an up to date value', function() { + it('always has an up to date value', function () { let count = 0; $scope.vals = [1, 0]; - $scope.$watchMulti(['vals[0]', 'vals[1]'], function(cur) { + $scope.$watchMulti(['vals[0]', 'vals[1]'], function (cur) { expect(cur).to.eql($scope.vals); count++; }); const $child = $scope.$new(); - $child.$watch('vals[0]', function(cur) { + $child.$watch('vals[0]', function (cur) { $child.vals[1] = cur; }); @@ -142,17 +142,17 @@ describe('$scope.$watchMulti', function() { }); }); - describe('complex watch expressions', function() { + describe('complex watch expressions', function () { let stateWatchers; let firstValue; let secondValue; - beforeEach(function() { - const firstGetter = function() { + beforeEach(function () { + const firstGetter = function () { return firstValue; }; - const secondGetter = function() { + const secondGetter = function () { return secondValue; }; @@ -168,7 +168,7 @@ describe('$scope.$watchMulti', function() { ]; }); - it('should trigger the watcher on initialization', function() { + it('should trigger the watcher on initialization', function () { const stub = sinon.stub(); firstValue = 'first'; secondValue = 'second'; @@ -183,8 +183,8 @@ describe('$scope.$watchMulti', function() { }); }); - describe('nested watchers', function() { - it('should trigger the handler at least once', function() { + describe('nested watchers', function () { + it('should trigger the handler at least once', function () { const $scope = $rootScope.$new(); $scope.$$watchers = [ { @@ -205,7 +205,7 @@ describe('$scope.$watchMulti', function() { const second = sinon.stub(); function registerWatchers() { - $scope.$watchMulti([first, second], function() { + $scope.$watchMulti([first, second], function () { expect(first.callCount).to.be.greaterThan(0); expect(second.callCount).to.be.greaterThan(0); }); diff --git a/src/legacy/ui/public/doc_title/__tests__/doc_title.js b/src/legacy/ui/public/doc_title/__tests__/doc_title.js index 8e4af5aa11dc3..fa8b83f755957 100644 --- a/src/legacy/ui/public/doc_title/__tests__/doc_title.js +++ b/src/legacy/ui/public/doc_title/__tests__/doc_title.js @@ -23,38 +23,38 @@ import ngMock from 'ng_mock'; import { docTitle } from '../doc_title'; import { npStart } from '../../new_platform'; -describe('docTitle Service', function() { +describe('docTitle Service', function () { let initialDocTitle; const MAIN_TITLE = 'Kibana 4'; let $rootScope; - beforeEach(function() { + beforeEach(function () { initialDocTitle = document.title; document.title = MAIN_TITLE; npStart.core.chrome.docTitle.__legacy.setBaseTitle(MAIN_TITLE); }); - afterEach(function() { + afterEach(function () { document.title = initialDocTitle; npStart.core.chrome.docTitle.__legacy.setBaseTitle(initialDocTitle); }); beforeEach( - ngMock.module('kibana', function($provide) { + ngMock.module('kibana', function ($provide) { $provide.decorator('$rootScope', decorateWithSpy('$on')); }) ); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $rootScope = $injector.get('$rootScope'); }) ); - describe('setup', function() { - it('resets the title when a route change begins', function() { + describe('setup', function () { + it('resets the title when a route change begins', function () { const spy = $rootScope.$on; - const found = spy.args.some(function(args) { + const found = spy.args.some(function (args) { return args[0] === '$routeChangeStart' && args[1] === docTitle.reset; }); @@ -64,8 +64,8 @@ describe('docTitle Service', function() { }); }); - describe('#reset', function() { - it('clears the internal state', function() { + describe('#reset', function () { + it('clears the internal state', function () { docTitle.change('some title'); expect(document.title).to.be('some title - ' + MAIN_TITLE); @@ -74,8 +74,8 @@ describe('docTitle Service', function() { }); }); - describe('#change', function() { - it('writes the first param to as the first part of the doc name', function() { + describe('#change', function () { + it('writes the first param to as the first part of the doc name', function () { expect(document.title).to.be(MAIN_TITLE); docTitle.change('some secondary title'); expect(document.title).to.be('some secondary title - ' + MAIN_TITLE); @@ -83,7 +83,7 @@ describe('docTitle Service', function() { }); function decorateWithSpy(prop) { - return function($delegate) { + return function ($delegate) { sinon.spy($delegate, prop); return $delegate; }; diff --git a/src/legacy/ui/public/doc_title/doc_title.js b/src/legacy/ui/public/doc_title/doc_title.js index 5d0d63380f152..096e49e7a6de8 100644 --- a/src/legacy/ui/public/doc_title/doc_title.js +++ b/src/legacy/ui/public/doc_title/doc_title.js @@ -36,7 +36,7 @@ export const docTitle = { reset, }; -uiModules.get('kibana').run(function($rootScope) { +uiModules.get('kibana').run(function ($rootScope) { // always bind to the route events $rootScope.$on('$routeChangeStart', docTitle.reset); }); diff --git a/src/legacy/ui/public/documentation_links/__tests__/documentation_links.js b/src/legacy/ui/public/documentation_links/__tests__/documentation_links.js index 0e38ec998d62e..6c9cdd12422cf 100644 --- a/src/legacy/ui/public/documentation_links/__tests__/documentation_links.js +++ b/src/legacy/ui/public/documentation_links/__tests__/documentation_links.js @@ -23,8 +23,8 @@ import { metadata } from '../../metadata'; const urlVersion = metadata.branch; -describe('documentation link service', function() { - it("should inject Kibana's major.minor version into doc links", function() { +describe('documentation link service', function () { + it("should inject Kibana's major.minor version into doc links", function () { expect(documentationLinks.filebeat.configuration).to.contain(urlVersion); }); }); diff --git a/src/legacy/ui/public/dom_location.js b/src/legacy/ui/public/dom_location.js index 18411f3f66ed0..baf03ba4c4b1c 100644 --- a/src/legacy/ui/public/dom_location.js +++ b/src/legacy/ui/public/dom_location.js @@ -19,7 +19,7 @@ export function DomLocationProvider($window) { return { - reload: function(forceFetch) { + reload: function (forceFetch) { $window.location.reload(forceFetch); }, diff --git a/src/legacy/ui/public/events.js b/src/legacy/ui/public/events.js index 00c92038e7c9f..1dc8a71afb193 100644 --- a/src/legacy/ui/public/events.js +++ b/src/legacy/ui/public/events.js @@ -45,7 +45,7 @@ export function EventsProvider(Promise) { * @param {function} handler - The function to call when the event is triggered * @return {Events} - this, for chaining */ - Events.prototype.on = function(name, handler) { + Events.prototype.on = function (name, handler) { if (!Array.isArray(this._listeners[name])) { this._listeners[name] = []; } @@ -57,11 +57,11 @@ export function EventsProvider(Promise) { (function rebuildDefer() { listener.defer = createDefer(Promise); - listener.resolved = listener.defer.promise.then(function(args) { + listener.resolved = listener.defer.promise.then(function (args) { rebuildDefer(); // we ignore the completion of handlers, just watch for unhandled errors - Promise.resolve(handler.apply(handler, args)).catch(error => fatalError(error, location)); + Promise.resolve(handler.apply(handler, args)).catch((error) => fatalError(error, location)); // indicate to bluebird not to worry about this promise being a "runaway" return null; @@ -77,7 +77,7 @@ export function EventsProvider(Promise) { * @param {function} [handler] - The handler to remove * @return {Events} - this, for chaining */ - Events.prototype.off = function(name, handler) { + Events.prototype.off = function (name, handler) { if (!name && !handler) { this._listeners = {}; return this.removeAllListeners(); @@ -90,7 +90,7 @@ export function EventsProvider(Promise) { if (!handler) { delete this._listeners[name]; } else { - this._listeners[name] = _.filter(this._listeners[name], function(listener) { + this._listeners[name] = _.filter(this._listeners[name], function (listener) { return handler !== listener.handler; }); } @@ -105,7 +105,7 @@ export function EventsProvider(Promise) { * @param {any} [value] - The value that will be passed to all event handlers. * @returns {Promise} */ - Events.prototype.emit = function(name) { + Events.prototype.emit = function (name) { const self = this; const args = _.rest(arguments); @@ -113,8 +113,8 @@ export function EventsProvider(Promise) { return self._emitChain; } - return Promise.map(self._listeners[name], function(listener) { - return (self._emitChain = self._emitChain.then(function() { + return Promise.map(self._listeners[name], function (listener) { + return (self._emitChain = self._emitChain.then(function () { // Double check that off wasn't called after an emit, but before this is fired. if (!self._listeners[name] || self._listeners[name].indexOf(listener) < 0) return; @@ -130,7 +130,7 @@ export function EventsProvider(Promise) { * @param {string} name * @return {array[function]} */ - Events.prototype.listeners = function(name) { + Events.prototype.listeners = function (name) { return _.pluck(this._listeners[name], 'handler'); }; diff --git a/src/legacy/ui/public/i18n/index.tsx b/src/legacy/ui/public/i18n/index.tsx index 6f1120dce0c7c..290e82a1334b9 100644 --- a/src/legacy/ui/public/i18n/index.tsx +++ b/src/legacy/ui/public/i18n/index.tsx @@ -29,7 +29,7 @@ import { npStart } from 'ui/new_platform'; export const I18nContext = npStart.core.i18n.Context; export function wrapInI18nContext

(ComponentToWrap: React.ComponentType

) { - const ContextWrapper: React.FC

= props => { + const ContextWrapper: React.FC

= (props) => { return ( diff --git a/src/legacy/ui/public/indexed_array/__tests__/indexed_array.js b/src/legacy/ui/public/indexed_array/__tests__/indexed_array.js index bbc72d599651a..a8abbba9df433 100644 --- a/src/legacy/ui/public/indexed_array/__tests__/indexed_array.js +++ b/src/legacy/ui/public/indexed_array/__tests__/indexed_array.js @@ -37,42 +37,42 @@ users.inIdOrder = _.sortBy(users, 'id'); // then things started becoming unruly... so IndexedArray! -describe('IndexedArray', function() { - describe('Basics', function() { +describe('IndexedArray', function () { + describe('Basics', function () { let reg; - beforeEach(function() { + beforeEach(function () { reg = new IndexedArray(); }); - it('Extends Array', function() { + it('Extends Array', function () { expect(reg).to.be.a(Array); }); - it('fails basic lodash check', function() { + it('fails basic lodash check', function () { expect(Array.isArray(reg)).to.be(false); }); - it('clones to an object', function() { + it('clones to an object', function () { expect(_.isPlainObject(_.clone(reg))).to.be(true); expect(Array.isArray(_.clone(reg))).to.be(false); }); }); - describe('Indexing', function() { - it('provides the initial set', function() { + describe('Indexing', function () { + it('provides the initial set', function () { const reg = new IndexedArray({ initialSet: [1, 2, 3], }); expect(reg).to.have.length(3); - reg.forEach(function(v, i) { + reg.forEach(function (v, i) { expect(v).to.eql(i + 1); }); }); - it('indexes the initial set', function() { + it('indexes the initial set', function () { const reg = new IndexedArray({ index: ['username'], initialSet: users, @@ -82,7 +82,7 @@ describe('IndexedArray', function() { expect(reg.byUsername).to.eql(users.byUsername); }); - it('updates indices after values are added', function() { + it('updates indices after values are added', function () { // split up the user list, and add it in chunks const firstUser = users.slice(0, 1).pop(); const otherUsers = users.slice(1); @@ -106,7 +106,7 @@ describe('IndexedArray', function() { expect(reg.inIdOrder).to.eql(users.inIdOrder); }); - it('updates indices after values are removed', function() { + it('updates indices after values are removed', function () { // start off with all const reg = new IndexedArray({ group: ['group'], @@ -123,7 +123,7 @@ describe('IndexedArray', function() { const sumOfGroups = _.reduce( reg.byGroup, - function(note, group) { + function (note, group) { return note + group.length; }, 0 @@ -131,7 +131,7 @@ describe('IndexedArray', function() { expect(sumOfGroups).to.eql(expectedCount); }); - it('removes items based on a predicate', function() { + it('removes items based on a predicate', function () { const reg = new IndexedArray({ group: ['group'], order: ['id'], @@ -145,12 +145,12 @@ describe('IndexedArray', function() { expect(reg[0].name).to.be('Anon'); }); - it('updates indices after values are re-ordered', function() { + it('updates indices after values are re-ordered', function () { const rawUsers = users.slice(0); // collect and shuffle the ids available let ids = []; - _.times(rawUsers.length, function(i) { + _.times(rawUsers.length, function (i) { ids.push(i); }); ids = _.shuffle(ids); @@ -160,7 +160,7 @@ describe('IndexedArray', function() { // from here const fromI = ids.shift(); // do the move - const move = function(arr) { + const move = function (arr) { arr.splice(toI, 0, arr.splice(fromI, 1)[0]); }; @@ -178,8 +178,8 @@ describe('IndexedArray', function() { }); }); - describe('Ordering', function() { - it('ordering is case insensitive', function() { + describe('Ordering', function () { + it('ordering is case insensitive', function () { const reg = new IndexedArray({ index: ['title'], order: ['title'], @@ -191,7 +191,7 @@ describe('IndexedArray', function() { expect(ordered[1].title).to.be('APM'); }); - it('ordering handles numbers', function() { + it('ordering handles numbers', function () { const reg = new IndexedArray({ index: ['id'], order: ['id'], diff --git a/src/legacy/ui/public/indexed_array/__tests__/inflector.js b/src/legacy/ui/public/indexed_array/__tests__/inflector.js index 51e4b94b416eb..49ac79094e501 100644 --- a/src/legacy/ui/public/indexed_array/__tests__/inflector.js +++ b/src/legacy/ui/public/indexed_array/__tests__/inflector.js @@ -20,14 +20,14 @@ import { inflector } from '../inflector'; import expect from '@kbn/expect'; -describe('IndexedArray Inflector', function() { - it('returns a function', function() { +describe('IndexedArray Inflector', function () { + it('returns a function', function () { const getter = inflector(); expect(getter).to.be.a('function'); }); - describe('fn', function() { - it('prepends a prefix', function() { + describe('fn', function () { + it('prepends a prefix', function () { const inflect = inflector('my'); expect(inflect('Family')).to.be('myFamily'); @@ -35,7 +35,7 @@ describe('IndexedArray Inflector', function() { expect(inflect('fAmIlY')).to.be('myFAmIlY'); }); - it('adds both a prefix and suffix', function() { + it('adds both a prefix and suffix', function () { const inflect = inflector('foo', 'Bar'); expect(inflect('box')).to.be('fooBoxBar'); @@ -43,19 +43,19 @@ describe('IndexedArray Inflector', function() { expect(inflect('BaZzY')).to.be('fooBaZzYBar'); }); - it('ignores prefix if it is already at the end of the inflected string', function() { + it('ignores prefix if it is already at the end of the inflected string', function () { const inflect = inflector('foo', 'Bar'); expect(inflect('fooBox')).to.be('fooBoxBar'); expect(inflect('FooBox')).to.be('FooBoxBar'); }); - it('ignores postfix if it is already at the end of the inflected string', function() { + it('ignores postfix if it is already at the end of the inflected string', function () { const inflect = inflector('foo', 'Bar'); expect(inflect('bar')).to.be('fooBar'); expect(inflect('showBoxBar')).to.be('fooShowBoxBar'); }); - it('works with "name"', function() { + it('works with "name"', function () { const inflect = inflector('in', 'Order'); expect(inflect('name')).to.be('inNameOrder'); }); diff --git a/src/legacy/ui/public/indexed_array/indexed_array.js b/src/legacy/ui/public/indexed_array/indexed_array.js index 39c79b2f021a3..79ef5e8c183da 100644 --- a/src/legacy/ui/public/indexed_array/indexed_array.js +++ b/src/legacy/ui/public/indexed_array/indexed_array.js @@ -21,9 +21,7 @@ import _ from 'lodash'; import { inflector } from './inflector'; import { organizeBy } from './helpers/organize_by'; -const pathGetter = _(_.get) - .rearg(1, 0) - .ary(2); +const pathGetter = _(_.get).rearg(1, 0).ary(2); const inflectIndex = inflector('by'); const inflectOrder = inflector('in', 'Order'); @@ -62,9 +60,7 @@ export class IndexedArray { if (typeof a === 'number' && typeof b === 'number') { return a - b; } - return String(a) - .toLowerCase() - .localeCompare(String(b).toLowerCase()); + return String(a).toLowerCase().localeCompare(String(b).toLowerCase()); }); }) ); @@ -171,7 +167,7 @@ export class IndexedArray { // shortcut for empty props if (!props || props.length === 0) return; - return props.map(prop => { + return props.map((prop) => { const indexName = inflect(prop); const getIndexValueFromItem = pathGetter.partial(prop).value(); let cache; @@ -180,7 +176,7 @@ export class IndexedArray { enumerable: false, configurable: false, - set: val => { + set: (val) => { // can't set any value other than the CLEAR_CACHE constant if (val === CLEAR_CACHE) { cache = false; @@ -208,7 +204,7 @@ export class IndexedArray { * @return {undefined} */ _clearIndices() { - this._indexNames.forEach(name => { + this._indexNames.forEach((name) => { this[name] = CLEAR_CACHE; }); } diff --git a/src/legacy/ui/public/indexed_array/inflector.js b/src/legacy/ui/public/indexed_array/inflector.js index 00aa4cdefc4f3..e034146f5f62f 100644 --- a/src/legacy/ui/public/indexed_array/inflector.js +++ b/src/legacy/ui/public/indexed_array/inflector.js @@ -39,7 +39,7 @@ export function inflector(prefix, postfix) { if (key.indexOf('.') !== -1) { inflected = key .split('.') - .map(function(step, i) { + .map(function (step, i) { return i === 0 ? step : upFirst(step, true); }) .join(''); diff --git a/src/legacy/ui/public/kfetch/kfetch.test.ts b/src/legacy/ui/public/kfetch/kfetch.test.ts index 259acc2753a43..c45a142d54e9b 100644 --- a/src/legacy/ui/public/kfetch/kfetch.test.ts +++ b/src/legacy/ui/public/kfetch/kfetch.test.ts @@ -353,11 +353,11 @@ describe('kfetch', () => { beforeEach(async () => { fetchMock.get('*', { foo: 'bar' }); addInterceptor({ - request: config => ({ + request: (config) => ({ ...config, pathname: '/my/intercepted-route', }), - response: res => ({ + response: (res) => ({ ...res, addedByResponseInterceptor: true, }), @@ -386,12 +386,12 @@ describe('kfetch', () => { beforeEach(async () => { fetchMock.get('*', { foo: 'bar' }); addInterceptor({ - request: config => + request: (config) => Promise.resolve({ ...config, pathname: '/my/intercepted-route', }), - response: res => + response: (res) => Promise.resolve({ ...res, addedByResponseInterceptor: true, @@ -421,7 +421,7 @@ function mockInterceptorCalls(interceptors: Interceptor[]) { const interceptorCalls: string[] = []; interceptors.forEach((interceptor, i) => { addInterceptor({ - request: config => { + request: (config) => { interceptorCalls.push(`Request #${i + 1}`); if (interceptor.request) { @@ -430,7 +430,7 @@ function mockInterceptorCalls(interceptors: Interceptor[]) { return config; }, - requestError: e => { + requestError: (e) => { interceptorCalls.push(`RequestError #${i + 1}`); if (interceptor.requestError) { return interceptor.requestError(e); @@ -438,7 +438,7 @@ function mockInterceptorCalls(interceptors: Interceptor[]) { throw e; }, - response: res => { + response: (res) => { interceptorCalls.push(`Response #${i + 1}`); if (interceptor.response) { @@ -447,7 +447,7 @@ function mockInterceptorCalls(interceptors: Interceptor[]) { return res; }, - responseError: e => { + responseError: (e) => { interceptorCalls.push(`ResponseError #${i + 1}`); if (interceptor.responseError) { diff --git a/src/legacy/ui/public/kfetch/kfetch.ts b/src/legacy/ui/public/kfetch/kfetch.ts index 02be7a32db296..4eb7149931575 100644 --- a/src/legacy/ui/public/kfetch/kfetch.ts +++ b/src/legacy/ui/public/kfetch/kfetch.ts @@ -60,7 +60,7 @@ export function createKfetch(http: HttpSetup) { .then(({ pathname, ...restOptions }) => http.fetch(pathname, { ...restOptions, prependBasePath }) ) - .catch(err => { + .catch((err) => { throw new KFetchError(err.response || { statusText: err.message }, err.body); }) ); diff --git a/src/legacy/ui/public/legacy_compat/__tests__/xsrf.js b/src/legacy/ui/public/legacy_compat/__tests__/xsrf.js index 3ca836e23881a..efcfb77997265 100644 --- a/src/legacy/ui/public/legacy_compat/__tests__/xsrf.js +++ b/src/legacy/ui/public/legacy_compat/__tests__/xsrf.js @@ -28,30 +28,30 @@ import { version } from '../../../../../core/server/utils/package_json'; const xsrfHeader = 'kbn-version'; -describe('chrome xsrf apis', function() { +describe('chrome xsrf apis', function () { const sandbox = sinon.createSandbox(); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - describe('jQuery support', function() { - it('adds a global jQuery prefilter', function() { + describe('jQuery support', function () { + it('adds a global jQuery prefilter', function () { sandbox.stub($, 'ajaxPrefilter'); $setupXsrfRequestInterceptor(version); expect($.ajaxPrefilter.callCount).to.be(1); }); - describe('jQuery prefilter', function() { + describe('jQuery prefilter', function () { let prefilter; - beforeEach(function() { + beforeEach(function () { sandbox.stub($, 'ajaxPrefilter'); $setupXsrfRequestInterceptor(version); prefilter = $.ajaxPrefilter.args[0][0]; }); - it(`sets the ${xsrfHeader} header`, function() { + it(`sets the ${xsrfHeader} header`, function () { const setHeader = sinon.stub(); prefilter({}, {}, { setRequestHeader: setHeader }); @@ -59,24 +59,24 @@ describe('chrome xsrf apis', function() { expect(setHeader.args[0]).to.eql([xsrfHeader, version]); }); - it('can be canceled by setting the kbnXsrfToken option', function() { + it('can be canceled by setting the kbnXsrfToken option', function () { const setHeader = sinon.stub(); prefilter({ kbnXsrfToken: false }, {}, { setRequestHeader: setHeader }); expect(setHeader.callCount).to.be(0); }); }); - describe('Angular support', function() { + describe('Angular support', function () { let $http; let $httpBackend; - beforeEach(function() { + beforeEach(function () { sandbox.stub($, 'ajaxPrefilter'); ngMock.module($setupXsrfRequestInterceptor(version)); }); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $http = $injector.get('$http'); $httpBackend = $injector.get('$httpBackend'); @@ -84,14 +84,14 @@ describe('chrome xsrf apis', function() { }) ); - afterEach(function() { + afterEach(function () { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); - it(`injects a ${xsrfHeader} header on every request`, function() { + it(`injects a ${xsrfHeader} header on every request`, function () { $httpBackend - .expectPOST('/api/test', undefined, function(headers) { + .expectPOST('/api/test', undefined, function (headers) { return headers[xsrfHeader] === version; }) .respond(200, ''); @@ -100,9 +100,9 @@ describe('chrome xsrf apis', function() { $httpBackend.flush(); }); - it('skips requests with the kbnXsrfToken set falsy', function() { + it('skips requests with the kbnXsrfToken set falsy', function () { $httpBackend - .expectPOST('/api/test', undefined, function(headers) { + .expectPOST('/api/test', undefined, function (headers) { return !(xsrfHeader in headers); }) .respond(200, ''); @@ -128,10 +128,10 @@ describe('chrome xsrf apis', function() { $httpBackend.flush(); }); - it('treats the kbnXsrfToken option as boolean-y', function() { + it('treats the kbnXsrfToken option as boolean-y', function () { const customToken = `custom:${version}`; $httpBackend - .expectPOST('/api/test', undefined, function(headers) { + .expectPOST('/api/test', undefined, function (headers) { return headers[xsrfHeader] === version; }) .respond(200, ''); diff --git a/src/legacy/ui/public/modules.js b/src/legacy/ui/public/modules.js index cbc222061e757..bb1c8aead1c34 100644 --- a/src/legacy/ui/public/modules.js +++ b/src/legacy/ui/public/modules.js @@ -107,7 +107,7 @@ export function get(moduleName, requires) { module.close = _.partial(close, moduleName); // ensure that it is required by linked modules - _.each(links, function(app) { + _.each(links, function (app) { if (!~app.requires.indexOf(moduleName)) app.requires.push(moduleName); }); } @@ -131,7 +131,7 @@ export function close(moduleName) { if (i > -1) links.splice(i, 1); // remove from linked modules list of required modules - _.each(links, function(app) { + _.each(links, function (app) { _.pull(app.requires, moduleName); }); diff --git a/src/legacy/ui/public/new_platform/new_platform.karma_mock.js b/src/legacy/ui/public/new_platform/new_platform.karma_mock.js index 67422fa659439..229bfb1978a4e 100644 --- a/src/legacy/ui/public/new_platform/new_platform.karma_mock.js +++ b/src/legacy/ui/public/new_platform/new_platform.karma_mock.js @@ -49,7 +49,7 @@ let isTimeRangeSelectorEnabled = true; let isAutoRefreshSelectorEnabled = true; export const mockUiSettings = { - get: item => { + get: (item) => { return mockUiSettings[item]; }, getUpdate$: () => ({ @@ -134,7 +134,7 @@ const querySetup = { getRefreshInterval: () => { return refreshInterval; }, - setRefreshInterval: interval => { + setRefreshInterval: (interval) => { refreshInterval = interval; }, enableTimeRangeSelector: () => { @@ -173,8 +173,8 @@ const mockAggTypesRegistry = () => { notifications: mockCoreStart.notifications, }), }); - aggTypes.buckets.forEach(type => registrySetup.registerBucket(type)); - aggTypes.metrics.forEach(type => registrySetup.registerMetric(type)); + aggTypes.buckets.forEach((type) => registrySetup.registerBucket(type)); + aggTypes.metrics.forEach((type) => registrySetup.registerMetric(type)); return registry; }; @@ -382,7 +382,7 @@ export const npStart = { }, getSuggestions: sinon.fake(), indexPatterns: { - get: sinon.spy(indexPatternId => + get: sinon.spy((indexPatternId) => Promise.resolve({ id: indexPatternId, isTimeNanosBased: () => false, @@ -428,7 +428,7 @@ export const npStart = { getRefreshInterval: () => { return refreshInterval; }, - setRefreshInterval: interval => { + setRefreshInterval: (interval) => { refreshInterval = interval; }, enableTimeRangeSelector: () => { diff --git a/src/legacy/ui/public/new_platform/new_platform.test.ts b/src/legacy/ui/public/new_platform/new_platform.test.ts index 21e7b559f71f5..d515c348ca440 100644 --- a/src/legacy/ui/public/new_platform/new_platform.test.ts +++ b/src/legacy/ui/public/new_platform/new_platform.test.ts @@ -113,7 +113,7 @@ describe('ui/new_platform', () => { controller(scopeMock, elementMock); // Flush promise queue. Must be done this way because the controller cannot return a Promise without breaking // angular. - await new Promise(resolve => setTimeout(resolve, 1)); + await new Promise((resolve) => setTimeout(resolve, 1)); const [event, eventHandler] = scopeMock.$on.mock.calls[0]; expect(event).toEqual('$destroy'); diff --git a/src/legacy/ui/public/new_platform/set_services.test.ts b/src/legacy/ui/public/new_platform/set_services.test.ts index 25a4524925169..b7878954846fa 100644 --- a/src/legacy/ui/public/new_platform/set_services.test.ts +++ b/src/legacy/ui/public/new_platform/set_services.test.ts @@ -29,8 +29,8 @@ import { npSetup, npStart } from './__mocks__'; describe('ui/new_platform', () => { describe('set service getters', () => { const testServiceGetters = (name: string, services: Record) => { - const getters = Object.keys(services).filter(k => k.substring(0, 3) === 'get'); - getters.forEach(g => { + const getters = Object.keys(services).filter((k) => k.substring(0, 3) === 'get'); + getters.forEach((g) => { it(`ui/new_platform sets a value for ${name} getter ${g}`, () => { __reset__(); __setup__( diff --git a/src/legacy/ui/public/private/__tests__/private.js b/src/legacy/ui/public/private/__tests__/private.js index c8c9c7467ad2e..1f9d696bb440f 100644 --- a/src/legacy/ui/public/private/__tests__/private.js +++ b/src/legacy/ui/public/private/__tests__/private.js @@ -20,17 +20,17 @@ import expect from '@kbn/expect'; import ngMock from 'ng_mock'; -describe('Private module loader', function() { +describe('Private module loader', function () { let Private; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { Private = $injector.get('Private'); }) ); - it('accepts a provider that will be called to init a module', function() { + it('accepts a provider that will be called to init a module', function () { const football = {}; function Provider() { return football; @@ -40,7 +40,7 @@ describe('Private module loader', function() { expect(instance).to.be(football); }); - it('injects angular dependencies into the Provider', function() { + it('injects angular dependencies into the Provider', function () { function Provider(Private) { return Private; } @@ -49,8 +49,8 @@ describe('Private module loader', function() { expect(instance).to.be(Private); }); - it('detects circular dependencies', function() { - expect(function() { + it('detects circular dependencies', function () { + expect(function () { function Provider1() { Private(Provider2); } @@ -63,7 +63,7 @@ describe('Private module loader', function() { }).to.throwException(/circular/i); }); - it('always provides the same instance form the Provider', function() { + it('always provides the same instance form the Provider', function () { function Provider() { return {}; } @@ -71,8 +71,8 @@ describe('Private module loader', function() { expect(Private(Provider)).to.be(Private(Provider)); }); - describe('#stub', function() { - it('accepts a replacement instance for a Provider', function() { + describe('#stub', function () { + it('accepts a replacement instance for a Provider', function () { const replaced = {}; const replacement = {}; @@ -95,8 +95,8 @@ describe('Private module loader', function() { }); }); - describe('#swap', function() { - it('accepts a new Provider that should replace an existing Provider', function() { + describe('#swap', function () { + it('accepts a new Provider that should replace an existing Provider', function () { function Provider1() { return {}; } @@ -120,7 +120,7 @@ describe('Private module loader', function() { expect(instance3).to.be(instance1); }); - it('gives the new Provider access to the Provider it replaced via an injectable dependency called $decorate', function() { + it('gives the new Provider access to the Provider it replaced via an injectable dependency called $decorate', function () { function Provider1() { return {}; } diff --git a/src/legacy/ui/public/promises/__tests__/promises.js b/src/legacy/ui/public/promises/__tests__/promises.js index cbf995d76e994..7041aa2993376 100644 --- a/src/legacy/ui/public/promises/__tests__/promises.js +++ b/src/legacy/ui/public/promises/__tests__/promises.js @@ -35,7 +35,7 @@ describe('Promise service', () => { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject($injector => { + ngMock.inject(($injector) => { sandbox.useFakeTimers(); Promise = $injector.get('Promise'); @@ -126,8 +126,8 @@ describe('Promise service', () => { describe('Promise.race()', () => { it(`resolves with the first resolved promise's value`, () => { - const p1 = new Promise(resolve => setTimeout(resolve, 100, 1)); - const p2 = new Promise(resolve => setTimeout(resolve, 200, 2)); + const p1 = new Promise((resolve) => setTimeout(resolve, 100, 1)); + const p2 = new Promise((resolve) => setTimeout(resolve, 200, 2)); const onResolve = sinon.stub(); Promise.race([p1, p2]).then(onResolve); @@ -155,10 +155,10 @@ describe('Promise service', () => { it('does not wait for subsequent promises to resolve/reject', () => { const onP1Resolve = sinon.stub(); - const p1 = new Promise(resolve => setTimeout(resolve, 100)).then(onP1Resolve); + const p1 = new Promise((resolve) => setTimeout(resolve, 100)).then(onP1Resolve); const onP2Resolve = sinon.stub(); - const p2 = new Promise(resolve => setTimeout(resolve, 101)).then(onP2Resolve); + const p2 = new Promise((resolve) => setTimeout(resolve, 101)).then(onP2Resolve); const onResolve = sinon.stub(); Promise.race([p1, p2]).then(onResolve); @@ -226,8 +226,8 @@ describe('Promise service', () => { describe('argument is a generator', () => { it('resolves with the first resolved value', () => { function* gen() { - yield new Promise(resolve => setTimeout(resolve, 100, 1)); - yield new Promise(resolve => setTimeout(resolve, 200, 2)); + yield new Promise((resolve) => setTimeout(resolve, 100, 1)); + yield new Promise((resolve) => setTimeout(resolve, 200, 2)); } const onResolve = sinon.stub(); @@ -242,7 +242,7 @@ describe('Promise service', () => { it('resolves with the first non-promise value', () => { function* gen() { yield 1; - yield new Promise(resolve => setTimeout(resolve, 200, 2)); + yield new Promise((resolve) => setTimeout(resolve, 200, 2)); } const onResolve = sinon.stub(); @@ -260,7 +260,7 @@ describe('Promise service', () => { yieldCount += 1; yield 1; yieldCount += 1; - yield new Promise(resolve => setTimeout(resolve, 200, 2)); + yield new Promise((resolve) => setTimeout(resolve, 200, 2)); } const onResolve = sinon.stub(); diff --git a/src/legacy/ui/public/react_components.js b/src/legacy/ui/public/react_components.js index b771e37c9d538..21fb53d6407fa 100644 --- a/src/legacy/ui/public/react_components.js +++ b/src/legacy/ui/public/react_components.js @@ -25,8 +25,8 @@ import { uiModules } from './modules'; const app = uiModules.get('app/kibana', ['react']); -app.directive('icon', reactDirective => reactDirective(EuiIcon)); +app.directive('icon', (reactDirective) => reactDirective(EuiIcon)); -app.directive('iconTip', reactDirective => +app.directive('iconTip', (reactDirective) => reactDirective(EuiIconTip, ['content', 'type', 'position', 'title', 'color']) ); diff --git a/src/legacy/ui/public/registry/__tests__/registry.js b/src/legacy/ui/public/registry/__tests__/registry.js index 14e4ce4a14e28..10b2423abc0e3 100644 --- a/src/legacy/ui/public/registry/__tests__/registry.js +++ b/src/legacy/ui/public/registry/__tests__/registry.js @@ -21,23 +21,23 @@ import { uiRegistry } from '../_registry'; import expect from '@kbn/expect'; import ngMock from 'ng_mock'; -describe('Registry', function() { +describe('Registry', function () { let Private; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { Private = $injector.get('Private'); }) ); - it('is technically a function', function() { + it('is technically a function', function () { const reg = uiRegistry(); expect(reg).to.be.a('function'); }); - describe('#register', function() { - it('accepts a Private module', function() { + describe('#register', function () { + it('accepts a Private module', function () { const reg = uiRegistry(); const mod = function SomePrivateModule() {}; @@ -45,9 +45,9 @@ describe('Registry', function() { // modules are not exposed, so this is the most that we can test }); - it('applies the filter function if one is specified', function() { + it('applies the filter function if one is specified', function () { const reg = uiRegistry({ - filter: item => item.value % 2 === 0, // register only even numbers + filter: (item) => item.value % 2 === 0, // register only even numbers }); reg.register(() => ({ value: 17 })); @@ -60,8 +60,8 @@ describe('Registry', function() { }); }); - describe('as a module', function() { - it('exposes the list of registered modules', function() { + describe('as a module', function () { + it('exposes the list of registered modules', function () { const reg = uiRegistry(); const mod = function SomePrivateModule(Private) { this.PrivateModuleLoader = Private; @@ -74,12 +74,12 @@ describe('Registry', function() { }); }); - describe('spec', function() { - it('executes with the module list as "this", and can override it', function() { + describe('spec', function () { + it('executes with the module list as "this", and can override it', function () { let self; const reg = uiRegistry({ - constructor: function() { + constructor: function () { return { mods: (self = this) }; }, }); @@ -90,8 +90,8 @@ describe('Registry', function() { }); }); - describe('spec.name', function() { - it('sets the displayName of the registry and the name param on the final instance', function() { + describe('spec.name', function () { + it('sets the displayName of the registry and the name param on the final instance', function () { const reg = uiRegistry({ name: 'visTypes', }); @@ -101,12 +101,12 @@ describe('Registry', function() { }); }); - describe('spec.constructor', function() { - it('executes before the modules are returned', function() { + describe('spec.constructor', function () { + it('executes before the modules are returned', function () { let i = 0; const reg = uiRegistry({ - constructor: function() { + constructor: function () { i = i + 1; }, }); @@ -115,11 +115,11 @@ describe('Registry', function() { expect(i).to.be(1); }); - it('executes with the module list as "this", and can override it', function() { + it('executes with the module list as "this", and can override it', function () { let self; const reg = uiRegistry({ - constructor: function() { + constructor: function () { return { mods: (self = this) }; }, }); @@ -134,7 +134,7 @@ describe('Registry', function() { it('is called with the registered providers and defines the initial set of values in the registry', () => { const reg = uiRegistry({ invokeProviders(providers) { - return providers.map(i => i * 1000); + return providers.map((i) => i * 1000); }, }); @@ -152,10 +152,10 @@ describe('Registry', function() { }); }); - describe('spec[any]', function() { - it('mixes the extra properties into the module list', function() { + describe('spec[any]', function () { + it('mixes the extra properties into the module list', function () { const reg = uiRegistry({ - someMethod: function() { + someMethod: function () { return this; }, }); diff --git a/src/legacy/ui/public/registry/_registry.js b/src/legacy/ui/public/registry/_registry.js index 39e0d1526fd8a..85aa1d9f2eca8 100644 --- a/src/legacy/ui/public/registry/_registry.js +++ b/src/legacy/ui/public/registry/_registry.js @@ -91,14 +91,14 @@ export function uiRegistry(spec) { * that were registered, the registry spec * defines how things will be indexed. */ - const registry = function(Private, $injector) { - getInvokedProviders = function(newProviders) { + const registry = function (Private, $injector) { + getInvokedProviders = function (newProviders) { let set = invokeProviders ? $injector.invoke(invokeProviders, undefined, { providers: newProviders }) : newProviders.map(Private); if (filter && _.isFunction(filter)) { - set = set.filter(item => filter(item)); + set = set.filter((item) => filter(item)); } return set; @@ -123,7 +123,7 @@ export function uiRegistry(spec) { registry.displayName = '[registry ' + props.name + ']'; - registry.register = function(privateModule) { + registry.register = function (privateModule) { providers.push(privateModule); if (isInstantiated) { diff --git a/src/legacy/ui/public/routes/__tests__/_route_manager.js b/src/legacy/ui/public/routes/__tests__/_route_manager.js index 011922c7ed789..51bde8b8605ac 100644 --- a/src/legacy/ui/public/routes/__tests__/_route_manager.js +++ b/src/legacy/ui/public/routes/__tests__/_route_manager.js @@ -31,9 +31,9 @@ const chainableMethods = [ ]; let $rp; -describe('routes/route_manager', function() { +describe('routes/route_manager', function () { beforeEach( - ngMock.module('kibana', function($routeProvider) { + ngMock.module('kibana', function ($routeProvider) { $rp = $routeProvider; sinon.stub($rp, 'otherwise'); sinon.stub($rp, 'when'); @@ -41,19 +41,19 @@ describe('routes/route_manager', function() { ); beforeEach( - ngMock.inject(function() { + ngMock.inject(function () { routes = new RouteManager(); }) ); - it('should have chainable methods: ' + _.pluck(chainableMethods, 'name').join(', '), function() { - chainableMethods.forEach(function(meth) { + it('should have chainable methods: ' + _.pluck(chainableMethods, 'name').join(', '), function () { + chainableMethods.forEach(function (meth) { expect(routes[meth.name].apply(routes, _.clone(meth.args))).to.be(routes); }); }); - describe('#otherwise', function() { - it('should forward the last otherwise route', function() { + describe('#otherwise', function () { + it('should forward the last otherwise route', function () { const otherRoute = {}; routes.otherwise({}); routes.otherwise(otherRoute); @@ -65,15 +65,15 @@ describe('routes/route_manager', function() { }); }); - describe('#when', function() { - it('should merge the additions into the when() defined routes', function() { + describe('#when', function () { + it('should merge the additions into the when() defined routes', function () { routes.when('/some/route'); routes.when('/some/other/route'); // add the addition resolve to every route routes.defaults(/.*/, { resolve: { - addition: function() {}, + addition: function () {}, }, }); @@ -89,21 +89,21 @@ describe('routes/route_manager', function() { }); }); - describe('#config', function() { - it('should add defined routes to the global $routeProvider service in order', function() { + describe('#config', function () { + it('should add defined routes to the global $routeProvider service in order', function () { const args = [ ['/one', {}], ['/two', {}], ]; - args.forEach(function(a) { + args.forEach(function (a) { routes.when(a[0], a[1]); }); routes.config($rp); expect($rp.when.callCount).to.be(args.length); - _.times(args.length, function(i) { + _.times(args.length, function (i) { const call = $rp.when.getCall(i); const a = args.shift(); @@ -112,7 +112,7 @@ describe('routes/route_manager', function() { }); }); - it('sets route.reloadOnSearch to false by default', function() { + it('sets route.reloadOnSearch to false by default', function () { routes.when('/nothing-set'); routes.when('/no-reload', { reloadOnSearch: false }); routes.when('/always-reload', { reloadOnSearch: true }); diff --git a/src/legacy/ui/public/routes/__tests__/_work_queue.js b/src/legacy/ui/public/routes/__tests__/_work_queue.js index cc6b4ce8d29bc..72891f7321fbd 100644 --- a/src/legacy/ui/public/routes/__tests__/_work_queue.js +++ b/src/legacy/ui/public/routes/__tests__/_work_queue.js @@ -24,32 +24,32 @@ import { WorkQueue } from '../work_queue'; import sinon from 'sinon'; import { createDefer } from 'ui/promises'; -describe('work queue', function() { +describe('work queue', function () { let queue; let Promise; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function(_Promise_) { + ngMock.inject(function (_Promise_) { Promise = _Promise_; }) ); - beforeEach(function() { + beforeEach(function () { queue = new WorkQueue(); }); - afterEach(function() { + afterEach(function () { queue.empty(); }); - describe('#push', function() { - it('adds to the interval queue', function() { + describe('#push', function () { + it('adds to the interval queue', function () { queue.push(createDefer(Promise)); expect(queue).to.have.length(1); }); }); - describe('#resolveWhenFull', function() { - it('resolves requests waiting for the queue to fill when appropriate', function() { + describe('#resolveWhenFull', function () { + it('resolves requests waiting for the queue to fill when appropriate', function () { const size = _.random(5, 50); queue.limit = size; @@ -58,7 +58,7 @@ describe('work queue', function() { queue.resolveWhenFull(whenFull); // push all but one into the queue - _.times(size - 1, function() { + _.times(size - 1, function () { queue.push(createDefer(Promise)); }); @@ -81,7 +81,7 @@ describe('work queue', function() { const size = _.random(5, 50); const stub = sinon.stub(); - _.times(size, function() { + _.times(size, function () { const d = createDefer(Promise); // overwrite the defer methods with the stub d.resolve = stub; @@ -92,9 +92,9 @@ describe('work queue', function() { then(size, stub); } - describe('#doWork', function() { - it('flushes the queue and resolves all promises', function() { - fillWithStubs(function(size, stub) { + describe('#doWork', function () { + it('flushes the queue and resolves all promises', function () { + fillWithStubs(function (size, stub) { expect(queue).to.have.length(size); queue.doWork(); expect(queue).to.have.length(0); @@ -103,9 +103,9 @@ describe('work queue', function() { }); }); - describe('#empty()', function() { - it('empties the internal queue WITHOUT resolving any promises', function() { - fillWithStubs(function(size, stub) { + describe('#empty()', function () { + it('empties the internal queue WITHOUT resolving any promises', function () { + fillWithStubs(function (size, stub) { expect(queue).to.have.length(size); queue.empty(); expect(queue).to.have.length(0); diff --git a/src/legacy/ui/public/routes/__tests__/_wrap_route_with_prep.js b/src/legacy/ui/public/routes/__tests__/_wrap_route_with_prep.js index c5175e86040c1..8ae85fce591a1 100644 --- a/src/legacy/ui/public/routes/__tests__/_wrap_route_with_prep.js +++ b/src/legacy/ui/public/routes/__tests__/_wrap_route_with_prep.js @@ -26,20 +26,20 @@ import '../../private'; let routes; -describe('wrapRouteWithPrep fn', function() { +describe('wrapRouteWithPrep fn', function () { require('test_utils/no_digest_promises').activateForSuite(); - beforeEach(function() { + beforeEach(function () { routes = new RouteManager(); }); - const SchedulingTest = function(opts) { + const SchedulingTest = function (opts) { opts = opts || {}; const delaySetup = opts.delayUserWork ? 0 : 50; const delayUserWork = opts.delayUserWork ? 50 : 0; - return function() { + return function () { ngMock.module('kibana'); let setupComplete = false; let userWorkComplete = false; @@ -47,14 +47,14 @@ describe('wrapRouteWithPrep fn', function() { let Promise; let $injector; - ngMock.inject(function(_Promise_, _$injector_) { + ngMock.inject(function (_Promise_, _$injector_) { Promise = _Promise_; $injector = _$injector_; }); - routes.addSetupWork(function() { - return new Promise(function(resolve) { - setTimeout(function() { + routes.addSetupWork(function () { + return new Promise(function (resolve) { + setTimeout(function () { setupComplete = true; resolve(); }, delaySetup); @@ -64,26 +64,26 @@ describe('wrapRouteWithPrep fn', function() { routes .when('/', { resolve: { - test: function() { + test: function () { expect(setupComplete).to.be(true); userWorkComplete = true; }, }, }) .config({ - when: function(p, _r) { + when: function (p, _r) { route = _r; }, }); - return new Promise(function(resolve, reject) { - setTimeout(function() { + return new Promise(function (resolve, reject) { + setTimeout(function () { Promise.all( - _.map(route.resolve, function(fn) { + _.map(route.resolve, function (fn) { return $injector.invoke(fn); }) ) - .then(function() { + .then(function () { expect(setupComplete).to.be(true); expect(userWorkComplete).to.be(true); }) diff --git a/src/legacy/ui/public/routes/__tests__/index.js b/src/legacy/ui/public/routes/__tests__/index.js index 62bbec9ef3e67..30cedaaca3d19 100644 --- a/src/legacy/ui/public/routes/__tests__/index.js +++ b/src/legacy/ui/public/routes/__tests__/index.js @@ -20,4 +20,4 @@ import './_route_manager'; import './_work_queue'; import './_wrap_route_with_prep'; -describe('Custom Route Management', function() {}); +describe('Custom Route Management', function () {}); diff --git a/src/legacy/ui/public/routes/route_manager.js b/src/legacy/ui/public/routes/route_manager.js index 1cf2a5fc5a64a..de8a541d1c50a 100644 --- a/src/legacy/ui/public/routes/route_manager.js +++ b/src/legacy/ui/public/routes/route_manager.js @@ -31,12 +31,12 @@ export default function RouteManager() { const defaults = []; let otherwise; - self.config = function($routeProvider) { - when.forEach(function(args) { + self.config = function ($routeProvider) { + when.forEach(function (args) { const path = args[0]; const route = args[1] || {}; - defaults.forEach(def => { + defaults.forEach((def) => { if (def.regex.test(path)) { defaultsDeep(route, cloneDeep(def.value)); } @@ -56,7 +56,7 @@ export default function RouteManager() { } }; - self.run = function($location, $route, $injector, $rootScope) { + self.run = function ($location, $route, $injector, $rootScope) { if (window.elasticApm && typeof window.elasticApm.startTransaction === 'function') { /** * capture route-change events as transactions which happens after @@ -89,24 +89,24 @@ export default function RouteManager() { this.afterSetupWork = wrap(setup.afterSetupWork, wrapSetupAndChain); this.afterWork = wrap(setup.afterWork, wrapSetupAndChain); - self.when = function(path, route) { + self.when = function (path, route) { when.push([path, route]); return self; }; // before attaching the routes to the routeProvider, test the RE // against the .when() path and add/override the resolves if there is a match - self.defaults = function(regex, value) { + self.defaults = function (regex, value) { defaults.push({ regex, value }); return self; }; - self.otherwise = function(route) { + self.otherwise = function (route) { otherwise = route; return self; }; - self.getBreadcrumbs = function() { + self.getBreadcrumbs = function () { // overwritten in self.run(); return []; }; diff --git a/src/legacy/ui/public/routes/route_setup_manager.js b/src/legacy/ui/public/routes/route_setup_manager.js index ded295e97d4c4..a7a2f078f40fb 100644 --- a/src/legacy/ui/public/routes/route_setup_manager.js +++ b/src/legacy/ui/public/routes/route_setup_manager.js @@ -55,7 +55,7 @@ export class RouteSetupManager { */ doWork(Promise, $injector, userWork) { const invokeEach = (arr, locals) => { - return Promise.map(arr, fn => { + return Promise.map(arr, (fn) => { if (!fn) return; return $injector.invoke(fn, null, locals); }); @@ -69,13 +69,13 @@ export class RouteSetupManager { // clone so we don't discard handlers or loose them handlers = handlers.slice(0); - const next = err => { + const next = (err) => { if (!handlers.length) throw err; const handler = handlers.shift(); if (!handler) return next(err); - return Promise.try(function() { + return Promise.try(function () { return $injector.invoke(handler, null, { err }); }).catch(next); }; @@ -86,7 +86,7 @@ export class RouteSetupManager { return invokeEach(this.setupWork) .then( () => invokeEach(this.onSetupComplete), - err => callErrorHandlers(this.onSetupError, err) + (err) => callErrorHandlers(this.onSetupError, err) ) .then(() => { // wait for the queue to fill up, then do all the work @@ -95,7 +95,7 @@ export class RouteSetupManager { return defer.promise.then(() => Promise.all(userWork.doWork())); }) - .catch(error => { + .catch((error) => { if (error === WAIT_FOR_URL_CHANGE_TOKEN) { // prevent moving forward, return a promise that never resolves // so that the $router can observe the $location update @@ -106,7 +106,7 @@ export class RouteSetupManager { }) .then( () => invokeEach(this.onWorkComplete), - err => callErrorHandlers(this.onWorkError, err) + (err) => callErrorHandlers(this.onWorkError, err) ); } } diff --git a/src/legacy/ui/public/routes/work_queue.js b/src/legacy/ui/public/routes/work_queue.js index f733375697438..5c4c83663c590 100644 --- a/src/legacy/ui/public/routes/work_queue.js +++ b/src/legacy/ui/public/routes/work_queue.js @@ -25,40 +25,40 @@ export function WorkQueue() { q.limit = 0; Object.defineProperty(q, 'length', { - get: function() { + get: function () { return work.length; }, }); - const resolve = function(defers) { - return defers.splice(0).map(function(defer) { + const resolve = function (defers) { + return defers.splice(0).map(function (defer) { return defer.resolve(); }); }; - const checkIfFull = function() { + const checkIfFull = function () { if (work.length >= q.limit && fullDefers.length) { resolve(fullDefers); } }; - q.resolveWhenFull = function(defer) { + q.resolveWhenFull = function (defer) { fullDefers.push(defer); checkIfFull(); }; - q.doWork = function() { + q.doWork = function () { const resps = resolve(work); checkIfFull(); return resps; }; - q.empty = function() { + q.empty = function () { work.splice(0); checkIfFull(); }; - q.push = function(defer) { + q.push = function (defer) { work.push(defer); checkIfFull(); }; diff --git a/src/legacy/ui/public/routes/wrap_route_with_prep.js b/src/legacy/ui/public/routes/wrap_route_with_prep.js index e74de9c85efa8..e9ed33148d9ac 100644 --- a/src/legacy/ui/public/routes/wrap_route_with_prep.js +++ b/src/legacy/ui/public/routes/wrap_route_with_prep.js @@ -30,18 +30,18 @@ export function wrapRouteWithPrep(route, setup) { userWork.limit = _.keys(route.resolve).length; const resolve = { - __prep__: function($injector) { + __prep__: function ($injector) { return $injector.invoke(setup.doWork, setup, { userWork }); }, }; // send each user resolve to the userWork queue, which will prevent it from running before the // prep is complete - _.forOwn(route.resolve || {}, function(expr, name) { - resolve[name] = function($injector, Promise) { + _.forOwn(route.resolve || {}, function (expr, name) { + resolve[name] = function ($injector, Promise) { const defer = createDefer(Promise); userWork.push(defer); - return defer.promise.then(function() { + return defer.promise.then(function () { return $injector[angular.isString(expr) ? 'get' : 'invoke'](expr); }); }; diff --git a/src/legacy/ui/public/state_management/__tests__/app_state.js b/src/legacy/ui/public/state_management/__tests__/app_state.js index 1c8cfe7f796a1..c47fa3bb0417f 100644 --- a/src/legacy/ui/public/state_management/__tests__/app_state.js +++ b/src/legacy/ui/public/state_management/__tests__/app_state.js @@ -22,31 +22,31 @@ import expect from '@kbn/expect'; import ngMock from 'ng_mock'; import { AppStateProvider } from '../app_state'; -describe('State Management', function() { +describe('State Management', function () { let $rootScope; let AppState; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function(_$rootScope_, _$location_, Private) { + ngMock.inject(function (_$rootScope_, _$location_, Private) { $rootScope = _$rootScope_; AppState = Private(AppStateProvider); }) ); - describe('App State', function() { + describe('App State', function () { let appState; - beforeEach(function() { + beforeEach(function () { appState = new AppState(); }); - it('should have _urlParam of _a', function() { + it('should have _urlParam of _a', function () { expect(appState).to.have.property('_urlParam'); expect(appState._urlParam).to.equal('_a'); }); - it('should use passed in params', function() { + it('should use passed in params', function () { const params = { test: true, mock: false, @@ -55,17 +55,17 @@ describe('State Management', function() { appState = new AppState(params); expect(appState).to.have.property('_defaults'); - Object.keys(params).forEach(function(key) { + Object.keys(params).forEach(function (key) { expect(appState._defaults).to.have.property(key); expect(appState._defaults[key]).to.equal(params[key]); }); }); - it('should have a destroy method', function() { + it('should have a destroy method', function () { expect(appState).to.have.property('destroy'); }); - it('should be destroyed on $routeChangeStart', function() { + it('should be destroyed on $routeChangeStart', function () { const destroySpy = sinon.spy(appState, 'destroy'); $rootScope.$emit('$routeChangeStart'); diff --git a/src/legacy/ui/public/state_management/__tests__/config_provider.js b/src/legacy/ui/public/state_management/__tests__/config_provider.js index 1f971bed6c165..9f756bc51dcb0 100644 --- a/src/legacy/ui/public/state_management/__tests__/config_provider.js +++ b/src/legacy/ui/public/state_management/__tests__/config_provider.js @@ -21,13 +21,13 @@ import expect from '@kbn/expect'; import ngMock from 'ng_mock'; import '../config_provider'; -describe('State Management Config', function() { +describe('State Management Config', function () { let stateManagementConfig; describe('is enabled', () => { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function(_stateManagementConfig_) { + ngMock.inject(function (_stateManagementConfig_) { stateManagementConfig = _stateManagementConfig_; }) ); @@ -39,13 +39,13 @@ describe('State Management Config', function() { describe('can be disabled', () => { beforeEach( - ngMock.module('kibana', function(stateManagementConfigProvider) { + ngMock.module('kibana', function (stateManagementConfigProvider) { stateManagementConfigProvider.disable(); }) ); beforeEach( - ngMock.inject(function(_stateManagementConfig_) { + ngMock.inject(function (_stateManagementConfig_) { stateManagementConfig = _stateManagementConfig_; }) ); diff --git a/src/legacy/ui/public/state_management/__tests__/global_state.js b/src/legacy/ui/public/state_management/__tests__/global_state.js index 08c90bab0d2ef..e9dae5880a8d1 100644 --- a/src/legacy/ui/public/state_management/__tests__/global_state.js +++ b/src/legacy/ui/public/state_management/__tests__/global_state.js @@ -21,20 +21,20 @@ import expect from '@kbn/expect'; import ngMock from 'ng_mock'; import '../global_state'; -describe('State Management', function() { +describe('State Management', function () { let $location; let state; beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function(_$location_, globalState) { + ngMock.inject(function (_$location_, globalState) { $location = _$location_; state = globalState; }) ); - describe('Global State', function() { - it('should use previous state when not in URL', function() { + describe('Global State', function () { + it('should use previous state when not in URL', function () { // set satte via URL $location.search({ _g: '(foo:(bar:baz))' }); state.fetch(); diff --git a/src/legacy/ui/public/state_management/__tests__/state.js b/src/legacy/ui/public/state_management/__tests__/state.js index ab70413c2d10e..cde123e6c1d85 100644 --- a/src/legacy/ui/public/state_management/__tests__/state.js +++ b/src/legacy/ui/public/state_management/__tests__/state.js @@ -46,18 +46,15 @@ describe('State Management', () => { beforeEach(ngMock.module('kibana')); beforeEach( - ngMock.inject(function(_$rootScope_, _$location_, Private, config) { + ngMock.inject(function (_$rootScope_, _$location_, Private, config) { const State = Private(StateProvider); $location = _$location_; $rootScope = _$rootScope_; Events = Private(EventsProvider); - setup = opts => { + setup = (opts) => { const { param, initial, storeInHash } = opts || {}; - sinon - .stub(config, 'get') - .withArgs('state:storeInSessionStorage') - .returns(!!storeInHash); + sinon.stub(config, 'get').withArgs('state:storeInSessionStorage').returns(!!storeInHash); const store = new StubBrowserStorage(); const hashedItemStore = new HashedItemStore(store); const state = new State(param, initial, hashedItemStore); @@ -89,9 +86,9 @@ describe('State Management', () => { expect(state).to.be.an(Events); }); - it('should emit an event if reset with changes', done => { + it('should emit an event if reset with changes', (done) => { const { state } = setup({ initial: { message: ['test'] } }); - state.on('reset_with_changes', keys => { + state.on('reset_with_changes', (keys) => { expect(keys).to.eql(['message']); done(); }); @@ -122,9 +119,9 @@ describe('State Management', () => { expect(search._s).to.equal('(test:foo)'); }); - it('should emit an event if changes are saved', done => { + it('should emit an event if changes are saved', (done) => { const { state, getUnhashedSearch } = setup(); - state.on('save_with_changes', keys => { + state.on('save_with_changes', (keys) => { expect(keys).to.eql(['test']); done(); }); @@ -136,9 +133,9 @@ describe('State Management', () => { }); describe('Fetch', () => { - it('should emit an event if changes are fetched', done => { + it('should emit an event if changes are fetched', (done) => { const { state } = setup(); - state.on('fetch_with_changes', keys => { + state.on('fetch_with_changes', (keys) => { expect(keys).to.eql(['foo']); done(); }); @@ -148,9 +145,9 @@ describe('State Management', () => { $rootScope.$apply(); }); - it('should have events that attach to scope', done => { + it('should have events that attach to scope', (done) => { const { state } = setup(); - state.on('test', message => { + state.on('test', (message) => { expect(message).to.equal('foo'); done(); }); @@ -158,9 +155,9 @@ describe('State Management', () => { $rootScope.$apply(); }); - it('should fire listeners for #onUpdate() on #fetch()', done => { + it('should fire listeners for #onUpdate() on #fetch()', (done) => { const { state } = setup(); - state.on('fetch_with_changes', keys => { + state.on('fetch_with_changes', (keys) => { expect(keys).to.eql(['foo']); done(); }); @@ -230,7 +227,7 @@ describe('State Management', () => { it('does not replace the state value on read', () => { const { state } = setup(); - sinon.stub($location, 'search').callsFake(newSearch => { + sinon.stub($location, 'search').callsFake((newSearch) => { if (newSearch) { return $location; } else { @@ -310,7 +307,7 @@ describe('State Management', () => { sinon.assert.calledOnce(fatalErrorStub); sinon.assert.calledWith( fatalErrorStub, - sinon.match(error => error instanceof Error && error.message.includes('github.com')) + sinon.match((error) => error instanceof Error && error.message.includes('github.com')) ); }); @@ -344,20 +341,17 @@ describe('State Management', () => { }; beforeEach( - ngMock.module('kibana', function(stateManagementConfigProvider) { + ngMock.module('kibana', function (stateManagementConfigProvider) { stateManagementConfigProvider.disable(); }) ); beforeEach( - ngMock.inject(function(_$rootScope_, _$location_, Private, config) { + ngMock.inject(function (_$rootScope_, _$location_, Private, config) { const State = Private(StateProvider); $location = _$location_; $rootScope = _$rootScope_; - sinon - .stub(config, 'get') - .withArgs('state:storeInSessionStorage') - .returns(false); + sinon.stub(config, 'get').withArgs('state:storeInSessionStorage').returns(false); class MockPersistedState extends State { _persistAcrossApps = true; @@ -372,7 +366,7 @@ describe('State Management', () => { describe('changing state', () => { const methods = ['save', 'replace', 'reset']; - methods.forEach(method => { + methods.forEach((method) => { it(`${method} should not change the URL`, () => { $location.search({ _s: '(foo:bar)' }); state[method](); diff --git a/src/legacy/ui/public/state_management/__tests__/state_monitor_factory.js b/src/legacy/ui/public/state_management/__tests__/state_monitor_factory.js index 601212d2da1a5..dc00d4e05e82f 100644 --- a/src/legacy/ui/public/state_management/__tests__/state_monitor_factory.js +++ b/src/legacy/ui/public/state_management/__tests__/state_monitor_factory.js @@ -23,7 +23,7 @@ import { EventEmitter } from 'events'; import { cloneDeep } from 'lodash'; import { stateMonitorFactory } from '../state_monitor_factory'; -describe('stateMonitorFactory', function() { +describe('stateMonitorFactory', function () { const noop = () => {}; const eventTypes = ['save_with_changes', 'reset_with_changes', 'fetch_with_changes']; @@ -44,27 +44,27 @@ describe('stateMonitorFactory', function() { mockState = createMockState({}); }); - it('should have a create method', function() { + it('should have a create method', function () { expect(stateMonitorFactory).to.have.property('create'); expect(stateMonitorFactory.create).to.be.a('function'); }); - describe('factory creation', function() { - it('should not call onChange with only the state', function() { + describe('factory creation', function () { + it('should not call onChange with only the state', function () { const monitor = stateMonitorFactory.create(mockState); const changeStub = sinon.stub(); monitor.onChange(changeStub); sinon.assert.notCalled(changeStub); }); - it('should not call onChange with matching defaultState', function() { + it('should not call onChange with matching defaultState', function () { const monitor = stateMonitorFactory.create(mockState, {}); const changeStub = sinon.stub(); monitor.onChange(changeStub); sinon.assert.notCalled(changeStub); }); - it('should call onChange with differing defaultState', function() { + it('should call onChange with differing defaultState', function () { const monitor = stateMonitorFactory.create(mockState, { test: true }); const changeStub = sinon.stub(); monitor.onChange(changeStub); @@ -72,21 +72,21 @@ describe('stateMonitorFactory', function() { }); }); - describe('instance', function() { + describe('instance', function () { let monitor; beforeEach(() => { monitor = stateMonitorFactory.create(mockState); }); - describe('onChange', function() { - it('should throw if not given a handler function', function() { + describe('onChange', function () { + it('should throw if not given a handler function', function () { const fn = () => monitor.onChange('not a function'); expect(fn).to.throwException(/must be a function/); }); - eventTypes.forEach(eventType => { - describe(`when ${eventType} is emitted`, function() { + eventTypes.forEach((eventType) => { + describe(`when ${eventType} is emitted`, function () { let handlerFn; beforeEach(() => { @@ -95,24 +95,24 @@ describe('stateMonitorFactory', function() { sinon.assert.notCalled(handlerFn); }); - it('should get called', function() { + it('should get called', function () { mockState.emit(eventType); sinon.assert.calledOnce(handlerFn); }); - it('should be given the state status', function() { + it('should be given the state status', function () { mockState.emit(eventType); const args = handlerFn.firstCall.args; expect(args[0]).to.be.an('object'); }); - it('should be given the event type', function() { + it('should be given the event type', function () { mockState.emit(eventType); const args = handlerFn.firstCall.args; expect(args[1]).to.equal(eventType); }); - it('should be given the changed keys', function() { + it('should be given the changed keys', function () { const keys = ['one', 'two', 'three']; mockState.emit(eventType, keys); const args = handlerFn.firstCall.args; @@ -122,8 +122,8 @@ describe('stateMonitorFactory', function() { }); }); - describe('ignoreProps', function() { - it('should not set status to dirty when ignored properties change', function() { + describe('ignoreProps', function () { + it('should not set status to dirty when ignored properties change', function () { let status; const mockState = createMockState({ messages: { world: 'hello', foo: 'bar' } }); const monitor = stateMonitorFactory.create(mockState); @@ -148,7 +148,7 @@ describe('stateMonitorFactory', function() { }); }); - describe('setInitialState', function() { + describe('setInitialState', function () { let changeStub; beforeEach(() => { @@ -157,22 +157,22 @@ describe('stateMonitorFactory', function() { sinon.assert.notCalled(changeStub); }); - it('should throw if no state is provided', function() { + it('should throw if no state is provided', function () { const fn = () => monitor.setInitialState(); expect(fn).to.throwException(/must be an object/); }); - it('should throw if given the wrong type', function() { + it('should throw if given the wrong type', function () { const fn = () => monitor.setInitialState([]); expect(fn).to.throwException(/must be an object/); }); - it('should trigger the onChange handler', function() { + it('should trigger the onChange handler', function () { monitor.setInitialState({ new: 'state' }); sinon.assert.calledOnce(changeStub); }); - it('should change the status with differing state', function() { + it('should change the status with differing state', function () { monitor.setInitialState({ new: 'state' }); sinon.assert.calledOnce(changeStub); @@ -181,13 +181,13 @@ describe('stateMonitorFactory', function() { expect(status).to.have.property('dirty', true); }); - it('should not trigger the onChange handler without state change', function() { + it('should not trigger the onChange handler without state change', function () { monitor.setInitialState(cloneDeep(mockState.toJSON())); sinon.assert.notCalled(changeStub); }); }); - describe('status object', function() { + describe('status object', function () { let handlerFn; beforeEach(() => { @@ -195,21 +195,21 @@ describe('stateMonitorFactory', function() { monitor.onChange(handlerFn); }); - it('should be clean by default', function() { + it('should be clean by default', function () { mockState.emit(eventTypes[0]); const status = handlerFn.firstCall.args[0]; expect(status).to.have.property('clean', true); expect(status).to.have.property('dirty', false); }); - it('should be dirty when state changes', function() { + it('should be dirty when state changes', function () { setState(mockState, { message: 'i am dirty now' }); const status = handlerFn.firstCall.args[0]; expect(status).to.have.property('clean', false); expect(status).to.have.property('dirty', true); }); - it('should be clean when state is reset', function() { + it('should be clean when state is reset', function () { const defaultState = { message: 'i am the original state' }; const handlerFn = sinon.stub(); @@ -237,7 +237,7 @@ describe('stateMonitorFactory', function() { }); }); - describe('destroy', function() { + describe('destroy', function () { let stateSpy; beforeEach(() => { @@ -245,16 +245,16 @@ describe('stateMonitorFactory', function() { sinon.assert.notCalled(stateSpy); }); - it('should remove the listeners', function() { + it('should remove the listeners', function () { monitor.onChange(noop); monitor.destroy(); sinon.assert.callCount(stateSpy, eventTypes.length); - eventTypes.forEach(eventType => { + eventTypes.forEach((eventType) => { sinon.assert.calledWith(stateSpy, eventType); }); }); - it('should stop the instance from being used any more', function() { + it('should stop the instance from being used any more', function () { monitor.onChange(noop); monitor.destroy(); const fn = () => monitor.onChange(noop); diff --git a/src/legacy/ui/public/state_management/app_state.js b/src/legacy/ui/public/state_management/app_state.js index 76675b05e0fe5..ec680d163b9da 100644 --- a/src/legacy/ui/public/state_management/app_state.js +++ b/src/legacy/ui/public/state_management/app_state.js @@ -58,17 +58,17 @@ export function AppStateProvider(Private, $location) { // if the url param is missing, write it back AppState.prototype._persistAcrossApps = false; - AppState.prototype.destroy = function() { + AppState.prototype.destroy = function () { AppState.Super.prototype.destroy.call(this); AppState.getAppState._set(null); - eventUnsubscribers.forEach(listener => listener()); + eventUnsubscribers.forEach((listener) => listener()); }; /** * @returns PersistedState instance. */ - AppState.prototype.makeStateful = function(prop) { + AppState.prototype.makeStateful = function (prop) { if (persistedStates[prop]) return persistedStates[prop]; const self = this; @@ -76,25 +76,25 @@ export function AppStateProvider(Private, $location) { persistedStates[prop] = new PersistedState(); // update the app state when the stateful instance changes - const updateOnChange = function() { + const updateOnChange = function () { const replaceState = false; // TODO: debouncing logic self[prop] = persistedStates[prop].getChanges(); // Save state to the URL. self.save(replaceState); }; - const handlerOnChange = method => persistedStates[prop][method]('change', updateOnChange); + const handlerOnChange = (method) => persistedStates[prop][method]('change', updateOnChange); handlerOnChange('on'); eventUnsubscribers.push(() => handlerOnChange('off')); // update the stateful object when the app state changes - const persistOnChange = function(changes) { + const persistOnChange = function (changes) { if (!changes) return; if (changes.indexOf(prop) !== -1) { persistedStates[prop].set(self[prop]); } }; - const handlePersist = method => this[method]('fetch_with_changes', persistOnChange); + const handlePersist = (method) => this[method]('fetch_with_changes', persistOnChange); handlePersist('on'); eventUnsubscribers.push(() => handlePersist('off')); @@ -104,7 +104,7 @@ export function AppStateProvider(Private, $location) { return persistedStates[prop]; }; - AppState.getAppState = (function() { + AppState.getAppState = (function () { let currentAppState; function get() { @@ -112,12 +112,12 @@ export function AppStateProvider(Private, $location) { } // Checks to see if the appState might already exist, even if it hasn't been newed up - get.previouslyStored = function() { + get.previouslyStored = function () { const search = $location.search(); return search[urlParam] ? true : false; }; - get._set = function(current) { + get._set = function (current) { currentAppState = current; }; @@ -129,9 +129,9 @@ export function AppStateProvider(Private, $location) { uiModules .get('kibana/global_state') - .factory('AppState', function(Private) { + .factory('AppState', function (Private) { return Private(AppStateProvider); }) - .service('getAppState', function(Private) { + .service('getAppState', function (Private) { return Private(AppStateProvider).getAppState; }); diff --git a/src/legacy/ui/public/state_management/global_state.js b/src/legacy/ui/public/state_management/global_state.js index d8ff38106b978..0e8dfe40d5950 100644 --- a/src/legacy/ui/public/state_management/global_state.js +++ b/src/legacy/ui/public/state_management/global_state.js @@ -37,6 +37,6 @@ export function GlobalStateProvider(Private) { return new GlobalState(); } -module.service('globalState', function(Private) { +module.service('globalState', function (Private) { return Private(GlobalStateProvider); }); diff --git a/src/legacy/ui/public/state_management/state.js b/src/legacy/ui/public/state_management/state.js index c2274eae59f50..93428e9f8fa4e 100644 --- a/src/legacy/ui/public/state_management/state.js +++ b/src/legacy/ui/public/state_management/state.js @@ -90,7 +90,7 @@ export function StateProvider( this.fetch(); } - State.prototype._readFromURL = function() { + State.prototype._readFromURL = function () { const search = $location.search(); const urlVal = search[this._urlParam]; @@ -139,7 +139,7 @@ export function StateProvider( * Fetches the state from the url * @returns {void} */ - State.prototype.fetch = function() { + State.prototype.fetch = function () { if (!stateManagementConfig.enabled) { return; } @@ -168,7 +168,7 @@ export function StateProvider( * Saves the state to the url * @returns {void} */ - State.prototype.save = function(replace) { + State.prototype.save = function (replace) { if (!stateManagementConfig.enabled) { return; } @@ -207,7 +207,7 @@ export function StateProvider( * Calls save with a forced replace * @returns {void} */ - State.prototype.replace = function() { + State.prototype.replace = function () { if (!stateManagementConfig.enabled) { return; } @@ -220,7 +220,7 @@ export function StateProvider( * * @returns {void} */ - State.prototype.reset = function() { + State.prototype.reset = function () { if (!stateManagementConfig.enabled) { return; } @@ -239,14 +239,14 @@ export function StateProvider( * Cleans up the state object * @returns {void} */ - State.prototype.destroy = function() { + State.prototype.destroy = function () { this.off(); // removes all listeners // Removes the $routeUpdate listener - this._cleanUpListeners.forEach(listener => listener(this)); + this._cleanUpListeners.forEach((listener) => listener(this)); }; - State.prototype.setDefaults = function(defaults) { + State.prototype.setDefaults = function (defaults) { this._defaults = defaults || {}; }; @@ -257,7 +257,7 @@ export function StateProvider( * @param {string} stateHash - state hash value from the query string. * @return {any} - the stored value, or null if hash does not resolve. */ - State.prototype._parseStateHash = function(stateHash) { + State.prototype._parseStateHash = function (stateHash) { const json = this._hashedItemStore.getItem(stateHash); if (json === null) { toastNotifications.addDanger( @@ -278,7 +278,7 @@ export function StateProvider( * @param {string} stateHashOrRison - either state hash value or rison string. * @return {string} rison */ - State.prototype.translateHashToRison = function(stateHashOrRison) { + State.prototype.translateHashToRison = function (stateHashOrRison) { if (isStateHash(stateHashOrRison)) { return rison.encode(this._parseStateHash(stateHashOrRison)); } @@ -286,7 +286,7 @@ export function StateProvider( return stateHashOrRison; }; - State.prototype.isHashingEnabled = function() { + State.prototype.isHashingEnabled = function () { return !!config.get('state:storeInSessionStorage'); }; @@ -295,7 +295,7 @@ export function StateProvider( * * @return {string} */ - State.prototype.toQueryParam = function(state = this.toObject()) { + State.prototype.toQueryParam = function (state = this.toObject()) { if (!this.isHashingEnabled()) { return rison.encode(state); } @@ -330,7 +330,7 @@ export function StateProvider( * Get the query string parameter name where this state writes and reads * @return {string} */ - State.prototype.getQueryParamName = function() { + State.prototype.getQueryParamName = function () { return this._urlParam; }; @@ -340,7 +340,7 @@ export function StateProvider( * * @return {object} */ - State.prototype.toObject = function() { + State.prototype.toObject = function () { return _.omit(this, (value, key) => { return key.charAt(0) === '$' || key.charAt(0) === '_' || _.isFunction(value); }); @@ -351,7 +351,7 @@ export function StateProvider( * @obsolete Please use 'toObject' method instead * @return {object} */ - State.prototype.toJSON = function() { + State.prototype.toJSON = function () { return this.toObject(); }; diff --git a/src/legacy/ui/public/state_management/state_monitor_factory.ts b/src/legacy/ui/public/state_management/state_monitor_factory.ts index 27f3e59852569..454fefd4f8253 100644 --- a/src/legacy/ui/public/state_management/state_monitor_factory.ts +++ b/src/legacy/ui/public/state_management/state_monitor_factory.ts @@ -57,7 +57,7 @@ function stateMonitor( } function removeIgnoredProps(innerState: TStateDefault) { - ignoredProps.forEach(path => { + ignoredProps.forEach((path) => { set(innerState, path, true); }); return innerState; @@ -79,7 +79,7 @@ function stateMonitor( if (!changeHandlers) { throw new Error('Change handlers is undefined, this object has been destroyed'); } - changeHandlers.forEach(changeHandler => { + changeHandlers.forEach((changeHandler) => { changeHandler(status, type, keys); }); } diff --git a/src/legacy/ui/public/test_harness/test_harness.js b/src/legacy/ui/public/test_harness/test_harness.js index 22c78b1952e18..22c981fe0cf54 100644 --- a/src/legacy/ui/public/test_harness/test_harness.js +++ b/src/legacy/ui/public/test_harness/test_harness.js @@ -73,7 +73,7 @@ function createStubUiSettings() { createStubUiSettings(); sinon.stub(chrome, 'getUiSettingsClient').callsFake(() => stubUiSettings); -afterEach(function() { +afterEach(function () { createStubUiSettings(); }); diff --git a/src/legacy/ui/public/test_harness/test_sharding/find_test_bundle_url.js b/src/legacy/ui/public/test_harness/test_sharding/find_test_bundle_url.js index f830b8208aea3..53800d08ca05b 100644 --- a/src/legacy/ui/public/test_harness/test_sharding/find_test_bundle_url.js +++ b/src/legacy/ui/public/test_harness/test_sharding/find_test_bundle_url.js @@ -28,8 +28,8 @@ */ export function findTestBundleUrl() { const scriptTags = document.querySelectorAll('script[src]'); - const scriptUrls = [].map.call(scriptTags, el => el.getAttribute('src')); - const testBundleUrl = scriptUrls.find(url => url.includes('/tests.bundle.js')); + const scriptUrls = [].map.call(scriptTags, (el) => el.getAttribute('src')); + const testBundleUrl = scriptUrls.find((url) => url.includes('/tests.bundle.js')); if (!testBundleUrl) { throw new Error("test bundle url couldn't be found"); diff --git a/src/legacy/ui/public/test_harness/test_sharding/setup_test_sharding.js b/src/legacy/ui/public/test_harness/test_sharding/setup_test_sharding.js index 0093102f72390..fce1876162387 100644 --- a/src/legacy/ui/public/test_harness/test_sharding/setup_test_sharding.js +++ b/src/legacy/ui/public/test_harness/test_sharding/setup_test_sharding.js @@ -58,7 +58,7 @@ export function setupTestSharding() { }); // Filter top-level describe statements as they come - setupTopLevelDescribeFilter(describeName => { + setupTopLevelDescribeFilter((describeName) => { const describeShardNum = getShardNum(shardTotal, describeName); if (describeShardNum === shardNum) return true; // track shard numbers that we ignore diff --git a/src/legacy/ui/public/test_harness/test_sharding/setup_top_level_describe_filter.js b/src/legacy/ui/public/test_harness/test_sharding/setup_top_level_describe_filter.js index 9790b5367af81..726f890077b94 100644 --- a/src/legacy/ui/public/test_harness/test_sharding/setup_top_level_describe_filter.js +++ b/src/legacy/ui/public/test_harness/test_sharding/setup_top_level_describe_filter.js @@ -87,7 +87,7 @@ export function setupTopLevelDescribeFilter(test) { */ let describeCallDepth = 0; - const describeInterceptor = function(describeName, describeBody) { + const describeInterceptor = function (describeName, describeBody) { const context = this; const isTopLevelCall = describeCallDepth === 0; diff --git a/src/legacy/ui/public/url/__tests__/extract_app_path_and_id.js b/src/legacy/ui/public/url/__tests__/extract_app_path_and_id.js index 254ad3907e441..965e8f4bc9f38 100644 --- a/src/legacy/ui/public/url/__tests__/extract_app_path_and_id.js +++ b/src/legacy/ui/public/url/__tests__/extract_app_path_and_id.js @@ -21,100 +21,100 @@ import expect from '@kbn/expect'; import { extractAppPathAndId } from '../extract_app_path_and_id'; -describe('extractAppPathAndId', function() { - describe('from an absolute url with a base path', function() { - describe('with a base path', function() { +describe('extractAppPathAndId', function () { + describe('from an absolute url with a base path', function () { + describe('with a base path', function () { const basePath = '/gza'; const absoluteUrl = 'http://www.test.com:5601/gza/app/appId#appPathIsHere?query=here'; - it('extracts app path', function() { + it('extracts app path', function () { expect(extractAppPathAndId(absoluteUrl, basePath).appPath).to.be( 'appPathIsHere?query=here' ); }); - it('extracts app id', function() { + it('extracts app id', function () { expect(extractAppPathAndId(absoluteUrl, basePath).appId).to.be('appId'); }); - it('returns an empty object when there is no app path', function() { + it('returns an empty object when there is no app path', function () { const appPathAndId = extractAppPathAndId('http://www.test.com:5601/gza/noapppath'); expect(appPathAndId.appId).to.be(undefined); expect(appPathAndId.appPath).to.be(undefined); }); }); - describe('without a base path', function() { + describe('without a base path', function () { const absoluteUrl = 'http://www.test.com:5601/app/appId#appPathIsHere?query=here'; - it('extracts app path', function() { + it('extracts app path', function () { expect(extractAppPathAndId(absoluteUrl).appPath).to.be('appPathIsHere?query=here'); }); - it('extracts app id', function() { + it('extracts app id', function () { expect(extractAppPathAndId(absoluteUrl).appId).to.be('appId'); }); - it('returns an empty object when there is no app path', function() { + it('returns an empty object when there is no app path', function () { const appPathAndId = extractAppPathAndId('http://www.test.com:5601/noapppath'); expect(appPathAndId.appId).to.be(undefined); expect(appPathAndId.appPath).to.be(undefined); }); }); - describe('when appPath is empty', function() { + describe('when appPath is empty', function () { const absoluteUrl = 'http://www.test.com:5601/app/appId'; - it('extracts app id', function() { + it('extracts app id', function () { expect(extractAppPathAndId(absoluteUrl).appId).to.be('appId'); }); - it('extracts empty appPath', function() { + it('extracts empty appPath', function () { expect(extractAppPathAndId(absoluteUrl).appPath).to.be(''); }); }); }); - describe('from a root relative url', function() { - describe('with a base path', function() { + describe('from a root relative url', function () { + describe('with a base path', function () { const basePath = '/gza'; const rootRelativePath = '/gza/app/appId#appPathIsHere?query=here'; - it('extracts app path', function() { + it('extracts app path', function () { expect(extractAppPathAndId(rootRelativePath, basePath).appPath).to.be( 'appPathIsHere?query=here' ); }); - it('extracts app id', function() { + it('extracts app id', function () { expect(extractAppPathAndId(rootRelativePath, basePath).appId).to.be('appId'); }); - it('returns an empty object when there is no app path', function() { + it('returns an empty object when there is no app path', function () { const appPathAndId = extractAppPathAndId('/gza/notformattedright'); expect(appPathAndId.appId).to.be(undefined); expect(appPathAndId.appPath).to.be(undefined); }); }); - describe('without a base path', function() { + describe('without a base path', function () { const rootRelativePath = '/app/appId#appPathIsHere?query=here'; - it('extracts app path', function() { + it('extracts app path', function () { expect(extractAppPathAndId(rootRelativePath).appPath).to.be('appPathIsHere?query=here'); }); - it('extracts app id', function() { + it('extracts app id', function () { expect(extractAppPathAndId(rootRelativePath).appId).to.be('appId'); }); - it('returns an empty object when there is no app path', function() { + it('returns an empty object when there is no app path', function () { const appPathAndId = extractAppPathAndId('/notformattedright'); expect(appPathAndId.appId).to.be(undefined); expect(appPathAndId.appPath).to.be(undefined); }); }); - describe('when appPath is empty', function() { + describe('when appPath is empty', function () { const rootRelativePath = '/app/appId'; - it('extracts app id', function() { + it('extracts app id', function () { expect(extractAppPathAndId(rootRelativePath).appId).to.be('appId'); }); - it('extracts empty appPath', function() { + it('extracts empty appPath', function () { expect(extractAppPathAndId(rootRelativePath).appPath).to.be(''); }); }); diff --git a/src/legacy/ui/public/url/__tests__/kibana_parsed_url.js b/src/legacy/ui/public/url/__tests__/kibana_parsed_url.js index 422b1318bc82c..6ea199c3d22cc 100644 --- a/src/legacy/ui/public/url/__tests__/kibana_parsed_url.js +++ b/src/legacy/ui/public/url/__tests__/kibana_parsed_url.js @@ -21,8 +21,8 @@ import expect from '@kbn/expect'; import { KibanaParsedUrl } from '../kibana_parsed_url'; -describe('KibanaParsedUrl', function() { - it('getHashedAppPath', function() { +describe('KibanaParsedUrl', function () { + it('getHashedAppPath', function () { const kibanaParsedUrl = new KibanaParsedUrl({ basePath: '/hi', appId: 'bye', @@ -31,7 +31,7 @@ describe('KibanaParsedUrl', function() { expect(kibanaParsedUrl.getHashedAppPath()).to.be('#visualize?hi=there&bye'); }); - it('getAppRootPath', function() { + it('getAppRootPath', function () { const kibanaParsedUrl = new KibanaParsedUrl({ basePath: '/hi', appId: 'appId', @@ -40,8 +40,8 @@ describe('KibanaParsedUrl', function() { expect(kibanaParsedUrl.getAppRootPath()).to.be('/app/appId#dashboard?edit=123'); }); - describe('when basePath is specified', function() { - it('getRootRelativePath', function() { + describe('when basePath is specified', function () { + it('getRootRelativePath', function () { const kibanaParsedUrl = new KibanaParsedUrl({ basePath: '/base', appId: 'appId', @@ -50,12 +50,12 @@ describe('KibanaParsedUrl', function() { expect(kibanaParsedUrl.getRootRelativePath()).to.be('/base/app/appId#visualize?hi=there&bye'); }); - describe('getAbsolutePath', function() { + describe('getAbsolutePath', function () { const protocol = 'http'; const hostname = 'www.test.com'; const port = '5601'; - it('returns the absolute url when there is a port', function() { + it('returns the absolute url when there is a port', function () { const kibanaParsedUrl = new KibanaParsedUrl({ basePath: '/base', appId: 'appId', @@ -69,7 +69,7 @@ describe('KibanaParsedUrl', function() { ); }); - it('returns the absolute url when there are no query parameters', function() { + it('returns the absolute url when there are no query parameters', function () { const kibanaParsedUrl = new KibanaParsedUrl({ basePath: '/base', appId: 'appId', @@ -82,7 +82,7 @@ describe('KibanaParsedUrl', function() { ); }); - it('returns the absolute url when the are query parameters', function() { + it('returns the absolute url when the are query parameters', function () { const kibanaParsedUrl = new KibanaParsedUrl({ basePath: '/base', appId: 'appId', @@ -97,8 +97,8 @@ describe('KibanaParsedUrl', function() { }); }); - describe('when basePath is not specified', function() { - it('getRootRelativePath', function() { + describe('when basePath is not specified', function () { + it('getRootRelativePath', function () { const kibanaParsedUrl = new KibanaParsedUrl({ appId: 'appId', appPath: 'visualize?hi=there&bye', @@ -106,12 +106,12 @@ describe('KibanaParsedUrl', function() { expect(kibanaParsedUrl.getRootRelativePath()).to.be('/app/appId#visualize?hi=there&bye'); }); - describe('getAbsolutePath', function() { + describe('getAbsolutePath', function () { const protocol = 'http'; const hostname = 'www.test.com'; const port = '5601'; - it('returns the absolute url when there is a port', function() { + it('returns the absolute url when there is a port', function () { const kibanaParsedUrl = new KibanaParsedUrl({ appId: 'appId', appPath: 'visualize?hi=there&bye', @@ -124,7 +124,7 @@ describe('KibanaParsedUrl', function() { ); }); - it('returns the absolute url when there are no query parameters', function() { + it('returns the absolute url when there are no query parameters', function () { const kibanaParsedUrl = new KibanaParsedUrl({ appId: 'appId', appPath: 'visualize', @@ -134,7 +134,7 @@ describe('KibanaParsedUrl', function() { expect(kibanaParsedUrl.getAbsoluteUrl()).to.be('http://www.test.com/app/appId#visualize'); }); - it('returns the absolute url when there are query parameters', function() { + it('returns the absolute url when there are query parameters', function () { const kibanaParsedUrl = new KibanaParsedUrl({ appId: 'appId', appPath: 'visualize?hi=bye&tata', @@ -148,21 +148,21 @@ describe('KibanaParsedUrl', function() { }); }); - describe('getGlobalState', function() { + describe('getGlobalState', function () { const basePath = '/xyz'; const appId = 'myApp'; - it('returns an empty string when the KibanaParsedUrl is in an invalid state', function() { + it('returns an empty string when the KibanaParsedUrl is in an invalid state', function () { const url = new KibanaParsedUrl({ basePath }); expect(url.getGlobalState()).to.be(''); }); - it('returns an empty string when there is no global state', function() { + it('returns an empty string when there is no global state', function () { const url = new KibanaParsedUrl({ basePath, appId, appPath: '/hi?notg=something' }); expect(url.getGlobalState()).to.be(''); }); - it('returns the global state when it is the last parameter', function() { + it('returns the global state when it is the last parameter', function () { const url = new KibanaParsedUrl({ basePath, appId, @@ -171,7 +171,7 @@ describe('KibanaParsedUrl', function() { expect(url.getGlobalState()).to.be('(thisismyglobalstate)'); }); - it('returns the global state when it is the first parameter', function() { + it('returns the global state when it is the first parameter', function () { const url = new KibanaParsedUrl({ basePath, appId, @@ -181,23 +181,23 @@ describe('KibanaParsedUrl', function() { }); }); - describe('setGlobalState', function() { + describe('setGlobalState', function () { const basePath = '/xyz'; const appId = 'myApp'; - it('does nothing when KibanaParsedUrl is in an invalid state', function() { + it('does nothing when KibanaParsedUrl is in an invalid state', function () { const url = new KibanaParsedUrl({ basePath }); url.setGlobalState('newglobalstate'); expect(url.getGlobalState()).to.be(''); }); - it('clears the global state when setting it to an empty string', function() { + it('clears the global state when setting it to an empty string', function () { const url = new KibanaParsedUrl({ basePath, appId, appPath: '/hi?_g=globalstate' }); url.setGlobalState(''); expect(url.getGlobalState()).to.be(''); }); - it('updates the global state when a string is passed in', function() { + it('updates the global state when a string is passed in', function () { const url = new KibanaParsedUrl({ basePath, appId, @@ -207,7 +207,7 @@ describe('KibanaParsedUrl', function() { expect(url.getGlobalState()).to.be('newstate'); }); - it('adds the global state parameters if it did not exist before', function() { + it('adds the global state parameters if it did not exist before', function () { const url = new KibanaParsedUrl({ basePath, appId, appPath: '/hi' }); url.setGlobalState('newstate'); expect(url.getGlobalState()).to.be('newstate'); diff --git a/src/legacy/ui/public/url/__tests__/prepend_path.js b/src/legacy/ui/public/url/__tests__/prepend_path.js index 488a16e17410e..36991b77553e4 100644 --- a/src/legacy/ui/public/url/__tests__/prepend_path.js +++ b/src/legacy/ui/public/url/__tests__/prepend_path.js @@ -21,59 +21,59 @@ import expect from '@kbn/expect'; import { prependPath } from '../prepend_path'; -describe('url prependPath', function() { - describe('returns the relative path unchanged', function() { - it('if it is null', function() { +describe('url prependPath', function () { + describe('returns the relative path unchanged', function () { + it('if it is null', function () { expect(prependPath(null, 'kittens')).to.be(null); }); - it('if it is undefined', function() { + it('if it is undefined', function () { expect(prependPath(undefined, 'kittens')).to.be(undefined); }); - it('if it is an absolute url', function() { + it('if it is an absolute url', function () { expect(prependPath('http://www.hithere.com/howareyou', 'welcome')).to.be( 'http://www.hithere.com/howareyou' ); }); - it('if it does not start with a /', function() { + it('if it does not start with a /', function () { expect(prependPath('are/so/cool', 'cats')).to.be('are/so/cool'); }); - it('when new path is empty', function() { + it('when new path is empty', function () { expect(prependPath('/are/so/cool', '')).to.be('/are/so/cool'); }); - it('when it is only a slash and new path is empty', function() { + it('when it is only a slash and new path is empty', function () { expect(prependPath('/', '')).to.be('/'); }); }); - describe('returns an updated relative path', function() { - it('when it starts with a slash', function() { + describe('returns an updated relative path', function () { + it('when it starts with a slash', function () { expect(prependPath('/are/so/cool', 'dinosaurs')).to.be('dinosaurs/are/so/cool'); }); - it('when new path starts with a slash', function() { + it('when new path starts with a slash', function () { expect(prependPath('/are/so/cool', '/fish')).to.be('/fish/are/so/cool'); }); - it('with two slashes if new path is a slash', function() { + it('with two slashes if new path is a slash', function () { expect(prependPath('/are/so/cool', '/')).to.be('//are/so/cool'); }); - it('when there is a slash on the end', function() { + it('when there is a slash on the end', function () { expect(prependPath('/are/delicious/', 'lollipops')).to.be('lollipops/are/delicious/'); }); - it('when pathname that ends with a file', function() { + it('when pathname that ends with a file', function () { expect(prependPath('/are/delicious/index.html', 'donuts')).to.be( 'donuts/are/delicious/index.html' ); }); - it('when it is only a slash', function() { + it('when it is only a slash', function () { expect(prependPath('/', 'kittens')).to.be('kittens/'); }); }); diff --git a/src/legacy/ui/public/url/__tests__/url.js b/src/legacy/ui/public/url/__tests__/url.js index 999bef24ac5e2..8b173482e1bb4 100644 --- a/src/legacy/ui/public/url/__tests__/url.js +++ b/src/legacy/ui/public/url/__tests__/url.js @@ -41,22 +41,22 @@ class StubAppState { } function init() { - ngMock.module('kibana/url', 'kibana', function($provide, PrivateProvider) { - $provide.service('$route', function() { + ngMock.module('kibana/url', 'kibana', function ($provide, PrivateProvider) { + $provide.service('$route', function () { return { reload: _.noop, }; }); appState = new StubAppState(); - PrivateProvider.swap(AppStateProvider, $decorate => { + PrivateProvider.swap(AppStateProvider, ($decorate) => { const AppState = $decorate(); AppState.getAppState = () => appState; return AppState; }); }); - ngMock.inject(function($injector) { + ngMock.inject(function ($injector) { $route = $injector.get('$route'); $location = $injector.get('$location'); $rootScope = $injector.get('$rootScope'); @@ -64,13 +64,13 @@ function init() { }); } -describe('kbnUrl', function() { - beforeEach(function() { +describe('kbnUrl', function () { + beforeEach(function () { init(); }); - describe('forcing reload', function() { - it('schedules a listener for $locationChangeSuccess on the $rootScope', function() { + describe('forcing reload', function () { + it('schedules a listener for $locationChangeSuccess on the $rootScope', function () { $location.url('/url'); $route.current = { $$route: { @@ -87,7 +87,7 @@ describe('kbnUrl', function() { expect($rootScope.$on.firstCall.args[0]).to.be('$locationChangeSuccess'); }); - it('handler unbinds the listener and calls reload', function() { + it('handler unbinds the listener and calls reload', function () { $location.url('/url'); $route.current = { $$route: { @@ -109,7 +109,7 @@ describe('kbnUrl', function() { expect($route.reload.callCount).to.be(1); }); - it('reloads requested before the first are ignored', function() { + it('reloads requested before the first are ignored', function () { $location.url('/url'); $route.current = { $$route: { @@ -130,7 +130,7 @@ describe('kbnUrl', function() { expect($rootScope.$on.callCount).to.be(1); }); - it('one reload can happen once the first has completed', function() { + it('one reload can happen once the first has completed', function () { $location.url('/url'); $route.current = { $$route: { @@ -155,34 +155,34 @@ describe('kbnUrl', function() { }); }); - describe('remove', function() { - it('removes a parameter with a value from the url', function() { + describe('remove', function () { + it('removes a parameter with a value from the url', function () { $location.url('/myurl?exist&WithAParamToRemove=2&anothershouldexist=5'); kbnUrl.removeParam('WithAParamToRemove'); expect($location.url()).to.be('/myurl?exist&anothershouldexist=5'); }); - it('removes a parameter with no value from the url', function() { + it('removes a parameter with no value from the url', function () { $location.url('/myurl?removeme&hi=5'); kbnUrl.removeParam('removeme'); expect($location.url()).to.be('/myurl?hi=5'); }); - it('is noop if the given parameter doesn\t exist in the url', function() { + it('is noop if the given parameter doesn\t exist in the url', function () { $location.url('/myurl?hi&bye'); kbnUrl.removeParam('noexist'); expect($location.url()).to.be('/myurl?hi&bye'); }); - it('is noop if given empty string param', function() { + it('is noop if given empty string param', function () { $location.url('/myurl?hi&bye'); kbnUrl.removeParam(''); expect($location.url()).to.be('/myurl?hi&bye'); }); }); - describe('change', function() { - it('should set $location.url', function() { + describe('change', function () { + it('should set $location.url', function () { sinon.stub($location, 'url'); expect($location.url.callCount).to.be(0); @@ -190,7 +190,7 @@ describe('kbnUrl', function() { expect($location.url.callCount).to.be(1); }); - it('should uri encode replaced params', function() { + it('should uri encode replaced params', function () { const url = '/some/path/'; const params = { replace: faker.Lorem.words(3).join(' ') }; const check = encodeURIComponent(params.replace); @@ -201,7 +201,7 @@ describe('kbnUrl', function() { expect($location.url.firstCall.args[0]).to.be(url + check); }); - it('should parse angular expression in substitutions and uri encode the results', function() { + it('should parse angular expression in substitutions and uri encode the results', function () { // build url by piecing together these parts const urlParts = ['/', '/', '?', '&', '#']; // make sure it can parse templates with weird spacing @@ -219,14 +219,14 @@ describe('kbnUrl', function() { // the words (template keys) used must all be unique const words = _.uniq(faker.Lorem.words(10)) .slice(0, urlParts.length) - .map(function(word, i) { + .map(function (word, i) { if (filters[i].length) { return word + '|' + filters[i]; } return word; }); - const replacements = faker.Lorem.words(urlParts.length).map(function(word, i) { + const replacements = faker.Lorem.words(urlParts.length).map(function (word, i) { // make selected replacement into an object if (i === objIndex) { return { replace: word }; @@ -238,7 +238,7 @@ describe('kbnUrl', function() { // build the url and test url let url = ''; let testUrl = ''; - urlParts.forEach(function(part, i) { + urlParts.forEach(function (part, i) { url += part + wrappers[i][0] + words[i] + wrappers[i][1]; const locals = {}; locals[words[i].split('|')[0]] = replacements[i]; @@ -247,7 +247,7 @@ describe('kbnUrl', function() { // create the locals replacement object const params = {}; - replacements.forEach(function(replacement, i) { + replacements.forEach(function (replacement, i) { const word = words[i].split('|')[0]; params[word] = replacement; }); @@ -260,7 +260,7 @@ describe('kbnUrl', function() { expect($location.url.firstCall.args[0]).to.be(testUrl); }); - it('should handle dot notation', function() { + it('should handle dot notation', function () { const url = '/some/thing/{{that.is.substituted}}'; kbnUrl.change(url, { @@ -274,7 +274,7 @@ describe('kbnUrl', function() { expect($location.url()).to.be('/some/thing/test'); }); - it('should throw when params are missing', function() { + it('should throw when params are missing', function () { const url = '/{{replace_me}}'; const params = {}; @@ -287,7 +287,7 @@ describe('kbnUrl', function() { } }); - it('should throw when filtered params are missing', function() { + it('should throw when filtered params are missing', function () { const url = '/{{replace_me|number}}'; const params = {}; @@ -300,16 +300,13 @@ describe('kbnUrl', function() { } }); - it('should change the entire url', function() { + it('should change the entire url', function () { const path = '/test/path'; const search = { search: 'test' }; const hash = 'hash'; const newPath = '/new/location'; - $location - .path(path) - .search(search) - .hash(hash); + $location.path(path).search(search).hash(hash); // verify the starting state expect($location.path()).to.be(path); @@ -324,16 +321,13 @@ describe('kbnUrl', function() { expect($location.hash()).to.be(''); }); - it('should allow setting app state on the target url', function() { + it('should allow setting app state on the target url', function () { const path = '/test/path'; const search = { search: 'test' }; const hash = 'hash'; const newPath = '/new/location'; - $location - .path(path) - .search(search) - .hash(hash); + $location.path(path).search(search).hash(hash); // verify the starting state expect($location.path()).to.be(path); @@ -349,17 +343,14 @@ describe('kbnUrl', function() { }); }); - describe('changePath', function() { - it('should change just the path', function() { + describe('changePath', function () { + it('should change just the path', function () { const path = '/test/path'; const search = { search: 'test' }; const hash = 'hash'; const newPath = '/new/location'; - $location - .path(path) - .search(search) - .hash(hash); + $location.path(path).search(search).hash(hash); // verify the starting state expect($location.path()).to.be(path); @@ -375,17 +366,14 @@ describe('kbnUrl', function() { }); }); - describe('redirect', function() { - it('should change the entire url', function() { + describe('redirect', function () { + it('should change the entire url', function () { const path = '/test/path'; const search = { search: 'test' }; const hash = 'hash'; const newPath = '/new/location'; - $location - .path(path) - .search(search) - .hash(hash); + $location.path(path).search(search).hash(hash); // verify the starting state expect($location.path()).to.be(path); @@ -400,16 +388,13 @@ describe('kbnUrl', function() { expect($location.hash()).to.be(''); }); - it('should allow setting app state on the target url', function() { + it('should allow setting app state on the target url', function () { const path = '/test/path'; const search = { search: 'test' }; const hash = 'hash'; const newPath = '/new/location'; - $location - .path(path) - .search(search) - .hash(hash); + $location.path(path).search(search).hash(hash); // verify the starting state expect($location.path()).to.be(path); @@ -424,7 +409,7 @@ describe('kbnUrl', function() { expect($location.hash()).to.be(''); }); - it('should replace the current history entry', function() { + it('should replace the current history entry', function () { sinon.stub($location, 'replace'); $location.url('/some/path'); @@ -433,7 +418,7 @@ describe('kbnUrl', function() { expect($location.replace.callCount).to.be(1); }); - it('should call replace on $location', function() { + it('should call replace on $location', function () { sinon.stub(kbnUrl, '_shouldForceReload').returns(false); sinon.stub($location, 'replace'); @@ -443,17 +428,14 @@ describe('kbnUrl', function() { }); }); - describe('redirectPath', function() { - it('should only change the path', function() { + describe('redirectPath', function () { + it('should only change the path', function () { const path = '/test/path'; const search = { search: 'test' }; const hash = 'hash'; const newPath = '/new/location'; - $location - .path(path) - .search(search) - .hash(hash); + $location.path(path).search(search).hash(hash); // verify the starting state expect($location.path()).to.be(path); @@ -468,7 +450,7 @@ describe('kbnUrl', function() { expect($location.hash()).to.be(hash); }); - it('should call replace on $location', function() { + it('should call replace on $location', function () { sinon.stub(kbnUrl, '_shouldForceReload').returns(false); sinon.stub($location, 'replace'); @@ -478,11 +460,11 @@ describe('kbnUrl', function() { }); }); - describe('_shouldForceReload', function() { + describe('_shouldForceReload', function () { let next; let prev; - beforeEach(function() { + beforeEach(function () { $route.current = { $$route: { regexp: /^\/is-current-route\/(\d+)/, @@ -494,21 +476,21 @@ describe('kbnUrl', function() { next = { path: '/is-current-route/1', search: {} }; }); - it("returns false if the passed url doesn't match the current route", function() { + it("returns false if the passed url doesn't match the current route", function () { next.path = '/not current'; expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(false); }); - describe('if the passed url does match the route', function() { - describe('and the route reloads on search', function() { - describe('and the path is the same', function() { - describe('and the search params are the same', function() { - it('returns true', function() { + describe('if the passed url does match the route', function () { + describe('and the route reloads on search', function () { + describe('and the path is the same', function () { + describe('and the search params are the same', function () { + it('returns true', function () { expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(true); }); }); - describe('but the search params are different', function() { - it('returns false', function() { + describe('but the search params are different', function () { + it('returns false', function () { next.search = {}; prev.search = { q: 'search term' }; expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(false); @@ -516,18 +498,18 @@ describe('kbnUrl', function() { }); }); - describe('and the path is different', function() { - beforeEach(function() { + describe('and the path is different', function () { + beforeEach(function () { next.path = '/not-same'; }); - describe('and the search params are the same', function() { - it('returns false', function() { + describe('and the search params are the same', function () { + it('returns false', function () { expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(false); }); }); - describe('but the search params are different', function() { - it('returns false', function() { + describe('but the search params are different', function () { + it('returns false', function () { next.search = {}; prev.search = { q: 'search term' }; expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(false); @@ -536,19 +518,19 @@ describe('kbnUrl', function() { }); }); - describe('but the route does not reload on search', function() { - beforeEach(function() { + describe('but the route does not reload on search', function () { + beforeEach(function () { $route.current.$$route.reloadOnSearch = false; }); - describe('and the path is the same', function() { - describe('and the search params are the same', function() { - it('returns true', function() { + describe('and the path is the same', function () { + describe('and the search params are the same', function () { + it('returns true', function () { expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(true); }); }); - describe('but the search params are different', function() { - it('returns true', function() { + describe('but the search params are different', function () { + it('returns true', function () { next.search = {}; prev.search = { q: 'search term' }; expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(true); @@ -556,18 +538,18 @@ describe('kbnUrl', function() { }); }); - describe('and the path is different', function() { - beforeEach(function() { + describe('and the path is different', function () { + beforeEach(function () { next.path = '/not-same'; }); - describe('and the search params are the same', function() { - it('returns false', function() { + describe('and the search params are the same', function () { + it('returns false', function () { expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(false); }); }); - describe('but the search params are different', function() { - it('returns false', function() { + describe('but the search params are different', function () { + it('returns false', function () { next.search = {}; prev.search = { q: 'search term' }; expect(kbnUrl._shouldForceReload(next, prev, $route)).to.be(false); diff --git a/src/legacy/ui/public/url/kibana_parsed_url.ts b/src/legacy/ui/public/url/kibana_parsed_url.ts index 712dfd119c615..1c60e8729e0ff 100644 --- a/src/legacy/ui/public/url/kibana_parsed_url.ts +++ b/src/legacy/ui/public/url/kibana_parsed_url.ts @@ -111,13 +111,13 @@ export class KibanaParsedUrl { return; } - this.appPath = modifyUrl(this.appPath, parsed => { + this.appPath = modifyUrl(this.appPath, (parsed) => { parsed.query._g = newGlobalState; }); } public addQueryParameter(name: string, val: string) { - this.appPath = modifyUrl(this.appPath, parsed => { + this.appPath = modifyUrl(this.appPath, (parsed) => { parsed.query[name] = val; }); } @@ -139,7 +139,7 @@ export class KibanaParsedUrl { } public getAbsoluteUrl() { - return modifyUrl(this.getRootRelativePath(), parsed => { + return modifyUrl(this.getRootRelativePath(), (parsed) => { parsed.protocol = this.protocol; parsed.port = this.port; parsed.hostname = this.hostname; diff --git a/src/legacy/ui/public/url/redirect_when_missing.js b/src/legacy/ui/public/url/redirect_when_missing.js index e6b4a488160dd..85c90a14d9fd7 100644 --- a/src/legacy/ui/public/url/redirect_when_missing.js +++ b/src/legacy/ui/public/url/redirect_when_missing.js @@ -24,7 +24,7 @@ import { toastNotifications } from 'ui/notify'; import { SavedObjectNotFound } from '../../../../plugins/kibana_utils/public'; import { uiModules } from '../modules'; -uiModules.get('kibana/url').service('redirectWhenMissing', function(Private) { +uiModules.get('kibana/url').service('redirectWhenMissing', function (Private) { return Private(RedirectWhenMissingProvider); }); @@ -37,12 +37,12 @@ export function RedirectWhenMissingProvider(kbnUrl, Promise) { * couldn't be found, or just a string that will be used for all types * @return {function} - the handler to pass to .catch() */ - return function(mapping) { + return function (mapping) { if (typeof mapping === 'string') { mapping = { '*': mapping }; } - return function(error) { + return function (error) { // if this error is not "404", rethrow const savedObjectNotFound = error instanceof SavedObjectNotFound; const unknownVisType = error.message.indexOf('Invalid type') === 0; diff --git a/src/legacy/ui/public/url/url.js b/src/legacy/ui/public/url/url.js index 8c854950784c4..fb243b02e05c7 100644 --- a/src/legacy/ui/public/url/url.js +++ b/src/legacy/ui/public/url/url.js @@ -22,7 +22,7 @@ import { i18n } from '@kbn/i18n'; import { uiModules } from '../modules'; import { AppStateProvider } from '../state_management/app_state'; -uiModules.get('kibana/url').service('kbnUrl', function(Private, $injector) { +uiModules.get('kibana/url').service('kbnUrl', function (Private, $injector) { //config is not directly used but registers global event listeners to kbnUrl to function $injector.get('config'); return Private(KbnUrlProvider); @@ -56,7 +56,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {Object} [paramObj] - optional set of parameters for the url template * @return {undefined} */ - self.change = function(url, paramObj, appState) { + self.change = function (url, paramObj, appState) { self._changeLocation('url', url, paramObj, false, appState); }; @@ -68,7 +68,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {Object} [paramObj] - optional set of parameters for the path template * @return {undefined} */ - self.changePath = function(path, paramObj) { + self.changePath = function (path, paramObj) { self._changeLocation('path', path, paramObj); }; @@ -79,7 +79,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {Object} [paramObj] - optional set of parameters for the url template * @return {undefined} */ - self.redirect = function(url, paramObj, appState) { + self.redirect = function (url, paramObj, appState) { self._changeLocation('url', url, paramObj, true, appState); }; @@ -91,7 +91,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {Object} [paramObj] - optional set of parameters for the path template * @return {undefined} */ - self.redirectPath = function(path, paramObj) { + self.redirectPath = function (path, paramObj) { self._changeLocation('path', path, paramObj, true); }; @@ -104,10 +104,10 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @return {String} - the evaluated result * @throws {Error} If any of the expressions can't be parsed. */ - self.eval = function(template, paramObj) { + self.eval = function (template, paramObj) { paramObj = paramObj || {}; - return template.replace(/\{\{([^\}]+)\}\}/g, function(match, expr) { + return template.replace(/\{\{([^\}]+)\}\}/g, function (match, expr) { // remove filters const key = expr.split('|')[0].trim(); @@ -136,7 +136,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {string} route - the route name * @return {string} - the computed href */ - self.getRouteHref = function(obj, route) { + self.getRouteHref = function (obj, route) { return '#' + self.getRouteUrl(obj, route); }; @@ -147,7 +147,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {string} route - the route name * @return {string} - the computed url */ - self.getRouteUrl = function(obj, route) { + self.getRouteUrl = function (obj, route) { const template = obj && obj.routes && obj.routes[route]; if (template) return self.eval(template, obj); }; @@ -160,7 +160,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {string} route - the route name * @return {undefined} */ - self.redirectToRoute = function(obj, route) { + self.redirectToRoute = function (obj, route) { self.redirect(self.getRouteUrl(obj, route)); }; @@ -172,7 +172,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * @param {string} route - the route name * @return {undefined} */ - self.changeToRoute = function(obj, route) { + self.changeToRoute = function (obj, route) { self.change(self.getRouteUrl(obj, route)); }; @@ -181,7 +181,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private * history. * @param param */ - self.removeParam = function(param) { + self.removeParam = function (param) { $location.search(param, null).replace(); }; @@ -190,7 +190,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private ///// let reloading; - self._changeLocation = function(type, url, paramObj, replace, appState) { + self._changeLocation = function (type, url, paramObj, replace, appState) { const prev = { path: $location.path(), search: $location.search(), @@ -216,7 +216,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private const appState = Private(AppStateProvider).getAppState(); if (appState) appState.destroy(); - reloading = $rootScope.$on('$locationChangeSuccess', function() { + reloading = $rootScope.$on('$locationChangeSuccess', function () { // call the "unlisten" function returned by $on reloading(); reloading = false; @@ -228,7 +228,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse, Private }; // determine if the router will automatically reload the route - self._shouldForceReload = function(next, prev, $route) { + self._shouldForceReload = function (next, prev, $route) { if (reloading) return false; const route = $route.current && $route.current.$$route; diff --git a/src/legacy/ui/public/utils/legacy_class.js b/src/legacy/ui/public/utils/legacy_class.js index 0aebdd4f5b667..f47650a77bb6d 100644 --- a/src/legacy/ui/public/utils/legacy_class.js +++ b/src/legacy/ui/public/utils/legacy_class.js @@ -29,7 +29,7 @@ function describeConst(val) { } const props = { - inherits: describeConst(function(SuperClass) { + inherits: describeConst(function (SuperClass) { const prototype = Object.create(SuperClass.prototype, { constructor: describeConst(this), superConstructor: describeConst(SuperClass), diff --git a/src/legacy/ui/ui_apps/__tests__/ui_app.js b/src/legacy/ui/ui_apps/__tests__/ui_app.js index 50cefd7032e11..bb4bcfe2d7443 100644 --- a/src/legacy/ui/ui_apps/__tests__/ui_app.js +++ b/src/legacy/ui/ui_apps/__tests__/ui_app.js @@ -41,10 +41,7 @@ function createStubKbnServer(extraParams) { return { plugins: [], config: { - get: sinon - .stub() - .withArgs('server.basePath') - .returns(''), + get: sinon.stub().withArgs('server.basePath').returns(''), }, server: {}, ...extraParams, @@ -288,7 +285,7 @@ describe('ui apps / UiApp', () => { it('throws an error at instantiation', () => { expect(() => { createUiApp(createStubUiAppSpec({ pluginId: 'foo' })); - }).to.throwException(error => { + }).to.throwException((error) => { expect(error.message).to.match(/Unknown plugin id/); }); }); diff --git a/src/legacy/ui/ui_apps/ui_app.js b/src/legacy/ui/ui_apps/ui_app.js index 926db5836e9d1..7da9e39394deb 100644 --- a/src/legacy/ui/ui_apps/ui_app.js +++ b/src/legacy/ui/ui_apps/ui_app.js @@ -109,7 +109,7 @@ export class UiApp { const pluginId = this._pluginId; const { plugins } = this._kbnServer; - return pluginId ? plugins.find(plugin => plugin.id === pluginId) : undefined; + return pluginId ? plugins.find((plugin) => plugin.id === pluginId) : undefined; } toJSON() { diff --git a/src/legacy/ui/ui_apps/ui_apps_mixin.js b/src/legacy/ui/ui_apps/ui_apps_mixin.js index 5165c9859fec5..c80b12a46bee3 100644 --- a/src/legacy/ui/ui_apps/ui_apps_mixin.js +++ b/src/legacy/ui/ui_apps/ui_apps_mixin.js @@ -34,7 +34,7 @@ export function uiAppsMixin(kbnServer, server) { const appsById = new Map(); const hiddenAppsById = new Map(); - kbnServer.uiApps = uiAppSpecs.map(spec => { + kbnServer.uiApps = uiAppSpecs.map((spec) => { const app = new UiApp(kbnServer, spec); const id = app.getId(); @@ -54,14 +54,14 @@ export function uiAppsMixin(kbnServer, server) { }); server.decorate('server', 'getAllUiApps', () => kbnServer.uiApps.slice(0)); - server.decorate('server', 'getUiAppById', id => appsById.get(id)); - server.decorate('server', 'getHiddenUiAppById', id => hiddenAppsById.get(id)); + server.decorate('server', 'getUiAppById', (id) => appsById.get(id)); + server.decorate('server', 'getHiddenUiAppById', (id) => hiddenAppsById.get(id)); server.decorate('server', 'injectUiAppVars', (appId, provider) => kbnServer.newPlatform.__internals.legacy.injectUiAppVars(appId, provider) ); server.decorate( 'server', 'getInjectedUiAppVars', - async appId => await kbnServer.newPlatform.__internals.legacy.getInjectedUiAppVars(appId) + async (appId) => await kbnServer.newPlatform.__internals.legacy.getInjectedUiAppVars(appId) ); } diff --git a/src/legacy/ui/ui_bundles/app_entry_template.js b/src/legacy/ui/ui_bundles/app_entry_template.js index 683fedd34316f..a48de9a8cf7ee 100644 --- a/src/legacy/ui/ui_bundles/app_entry_template.js +++ b/src/legacy/ui/ui_bundles/app_entry_template.js @@ -19,7 +19,7 @@ import { apmImport, apmInit } from '../apm'; -export const appEntryTemplate = bundle => ` +export const appEntryTemplate = (bundle) => ` /** * Kibana entry file * diff --git a/src/legacy/ui/ui_bundles/ui_bundle.js b/src/legacy/ui/ui_bundles/ui_bundle.js index a8d4259fb98f2..4e853ad410efe 100644 --- a/src/legacy/ui/ui_bundles/ui_bundle.js +++ b/src/legacy/ui/ui_bundles/ui_bundle.js @@ -57,7 +57,7 @@ export class UiBundle { } getRequires() { - return this._modules.map(module => `require('${normalizePath(module)}');`); + return this._modules.map((module) => `require('${normalizePath(module)}');`); } renderContent() { @@ -66,7 +66,7 @@ export class UiBundle { async readEntryFile() { try { - const content = await fcb(cb => readFile(this.getEntryPath(), cb)); + const content = await fcb((cb) => readFile(this.getEntryPath(), cb)); return content.toString('utf8'); } catch (e) { return null; @@ -74,11 +74,11 @@ export class UiBundle { } async writeEntryFile() { - return await fcb(cb => writeFile(this.getEntryPath(), this.renderContent(), 'utf8', cb)); + return await fcb((cb) => writeFile(this.getEntryPath(), this.renderContent(), 'utf8', cb)); } async touchStyleFile() { - return await fcb(cb => writeFile(this.getStylePath(), '', 'utf8', cb)); + return await fcb((cb) => writeFile(this.getStylePath(), '', 'utf8', cb)); } /** @@ -98,8 +98,8 @@ export class UiBundle { } try { - await fcb(cb => stat(this.getOutputPath(), cb)); - await fcb(cb => stat(this.getStylePath(), cb)); + await fcb((cb) => stat(this.getOutputPath(), cb)); + await fcb((cb) => stat(this.getStylePath(), cb)); return true; } catch (e) { return false; diff --git a/src/legacy/ui/ui_bundles/ui_bundles_controller.js b/src/legacy/ui/ui_bundles/ui_bundles_controller.js index 79112fd687e84..dadb28cbb2f3a 100644 --- a/src/legacy/ui/ui_bundles/ui_bundles_controller.js +++ b/src/legacy/ui/ui_bundles/ui_bundles_controller.js @@ -56,7 +56,7 @@ function stableCloneAppExtensions(appExtensions) { Object.entries(appExtensions).map(([extensionType, moduleIds]) => [ extensionType, moduleIds - .map(moduleId => { + .map((moduleId) => { if (isAbsolute(moduleId)) { moduleId = `absolute:${relative(REPO_ROOT, moduleId)}`; } @@ -246,7 +246,7 @@ export class UiBundlesController { } getIds() { - return this._bundles.map(bundle => bundle.getId()); + return this._bundles.map((bundle) => bundle.getId()); } getExtendedConfig(webpackConfig) { diff --git a/src/legacy/ui/ui_exports/__tests__/collect_ui_exports.js b/src/legacy/ui/ui_exports/__tests__/collect_ui_exports.js index 352e8642e930e..3686a2dad8f24 100644 --- a/src/legacy/ui/ui_exports/__tests__/collect_ui_exports.js +++ b/src/legacy/ui/ui_exports/__tests__/collect_ui_exports.js @@ -106,7 +106,7 @@ describe('plugin discovery', () => { uiExports: { migrations: { 'test-type': { - '1.2.3': doc => { + '1.2.3': (doc) => { return doc; }, }, @@ -116,7 +116,7 @@ describe('plugin discovery', () => { ]; }, }).getPluginSpecs(); - expect(() => collectUiExports(invalidSpecs)).to.throwError(err => { + expect(() => collectUiExports(invalidSpecs)).to.throwError((err) => { expect(err).to.be.a(Error); expect(err).to.have.property( 'message', diff --git a/src/legacy/ui/ui_exports/ui_export_defaults.js b/src/legacy/ui/ui_exports/ui_export_defaults.js index 1341777bc0991..d60bf7df899e3 100644 --- a/src/legacy/ui/ui_exports/ui_export_defaults.js +++ b/src/legacy/ui/ui_exports/ui_export_defaults.js @@ -33,7 +33,7 @@ export const UI_EXPORT_DEFAULTS = { test_harness: resolve(ROOT, 'src/test_harness/public'), }, - styleSheetPaths: ['light', 'dark'].map(theme => ({ + styleSheetPaths: ['light', 'dark'].map((theme) => ({ theme, localPath: resolve(ROOT, 'src/core/public/index.scss'), publicPath: `core.${theme}.css`, diff --git a/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/alias.js b/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/alias.js index 511e7c20bd3b0..a894e59a03c81 100644 --- a/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/alias.js +++ b/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/alias.js @@ -24,5 +24,5 @@ * @param {String} newType * @return {Function} */ -export const alias = newType => next => (acc, spec, type, pluginSpec) => +export const alias = (newType) => (next) => (acc, spec, type, pluginSpec) => next(acc, spec, newType, pluginSpec); diff --git a/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/map_spec.js b/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/map_spec.js index de0cfb177b6e9..5970c45e7445e 100644 --- a/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/map_spec.js +++ b/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/map_spec.js @@ -25,5 +25,5 @@ * @param {Function} mapFn receives `(specs, type, pluginSpec)` * @return {Function} */ -export const mapSpec = mapFn => next => (acc, spec, type, pluginSpec) => +export const mapSpec = (mapFn) => (next) => (acc, spec, type, pluginSpec) => next(acc, mapFn(spec, type, pluginSpec), type, pluginSpec); diff --git a/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/unique_keys.js b/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/unique_keys.js index 9a2519f79eda8..dedcd057b09e3 100644 --- a/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/unique_keys.js +++ b/src/legacy/ui/ui_exports/ui_export_types/modify_reduce/unique_keys.js @@ -17,10 +17,10 @@ * under the License. */ -const pluginId = pluginSpec => (pluginSpec.id ? pluginSpec.id() : pluginSpec.getId()); +const pluginId = (pluginSpec) => (pluginSpec.id ? pluginSpec.id() : pluginSpec.getId()); -export const uniqueKeys = sourceType => next => (acc, spec, type, pluginSpec) => { - const duplicates = Object.keys(spec).filter(key => acc[type] && acc[type].hasOwnProperty(key)); +export const uniqueKeys = (sourceType) => (next) => (acc, spec, type, pluginSpec) => { + const duplicates = Object.keys(spec).filter((key) => acc[type] && acc[type].hasOwnProperty(key)); if (duplicates.length) { throw new Error( diff --git a/src/legacy/ui/ui_exports/ui_export_types/reduce/lib/create_type_reducer.js b/src/legacy/ui/ui_exports/ui_export_types/reduce/lib/create_type_reducer.js index a4df5debf1316..bf4793c208308 100644 --- a/src/legacy/ui/ui_exports/ui_export_types/reduce/lib/create_type_reducer.js +++ b/src/legacy/ui/ui_exports/ui_export_types/reduce/lib/create_type_reducer.js @@ -26,7 +26,7 @@ * @param {Function} reducer * @return {Function} */ -export const createTypeReducer = reducer => (acc, spec, type, pluginSpec) => ({ +export const createTypeReducer = (reducer) => (acc, spec, type, pluginSpec) => ({ ...acc, [type]: reducer(acc[type], spec, type, pluginSpec), }); diff --git a/src/legacy/ui/ui_exports/ui_export_types/saved_object.js b/src/legacy/ui/ui_exports/ui_export_types/saved_object.js index 63a3c5f036993..be6898d3e642c 100644 --- a/src/legacy/ui/ui_exports/ui_export_types/saved_object.js +++ b/src/legacy/ui/ui_exports/ui_export_types/saved_object.js @@ -30,7 +30,7 @@ export const mappings = wrap( flatConcatAtType ); -const pluginId = pluginSpec => (pluginSpec.id ? pluginSpec.id() : pluginSpec.getId()); +const pluginId = (pluginSpec) => (pluginSpec.id ? pluginSpec.id() : pluginSpec.getId()); // Combines the `migrations` property of each plugin, // ensuring that properties are unique across plugins @@ -38,9 +38,9 @@ const pluginId = pluginSpec => (pluginSpec.id ? pluginSpec.id() : pluginSpec.get // See saved_objects/migrations for more details. export const migrations = wrap( alias('savedObjectMigrations'), - next => (acc, spec, type, pluginSpec) => { + (next) => (acc, spec, type, pluginSpec) => { const mappings = pluginSpec.getExportSpecs().mappings || {}; - const invalidMigrationTypes = Object.keys(spec).filter(type => !mappings[type]); + const invalidMigrationTypes = Object.keys(spec).filter((type) => !mappings[type]); if (invalidMigrationTypes.length) { throw new Error( 'Migrations and mappings must be defined together in the uiExports of a single plugin. ' + diff --git a/src/legacy/ui/ui_exports/ui_export_types/style_sheet_paths.test.js b/src/legacy/ui/ui_exports/ui_export_types/style_sheet_paths.test.js index e3e051cbfac7e..6a1fa7bdf3633 100644 --- a/src/legacy/ui/ui_exports/ui_export_types/style_sheet_paths.test.js +++ b/src/legacy/ui/ui_exports/ui_export_types/style_sheet_paths.test.js @@ -28,8 +28,8 @@ const pluginSpec = { }; expect.addSnapshotSerializer({ - test: value => typeof value === 'string' && value.startsWith(dir), - print: value => value.replace(dir, '').replace(/\\/g, '/'), + test: (value) => typeof value === 'string' && value.startsWith(dir), + print: (value) => value.replace(dir, '').replace(/\\/g, '/'), }); describe('uiExports.styleSheetPaths', () => { diff --git a/src/legacy/ui/ui_exports/ui_export_types/webpack_customizations.js b/src/legacy/ui/ui_exports/ui_export_types/webpack_customizations.js index 83aa91b810c5f..3f3ff8b97999c 100644 --- a/src/legacy/ui/ui_exports/ui_export_types/webpack_customizations.js +++ b/src/legacy/ui/ui_exports/ui_export_types/webpack_customizations.js @@ -33,7 +33,7 @@ export const __bundleProvider__ = wrap(alias('uiBundleProviders'), flatConcatAtT export const __webpackPluginProvider__ = wrap(alias('webpackPluginProviders'), flatConcatAtType); export const noParse = wrap( alias('webpackNoParseRules'), - mapSpec(rule => { + mapSpec((rule) => { if (typeof rule === 'string') { return new RegExp(`${isAbsolute(rule) ? '^' : ''}${escapeRegExp(rule)}`); } diff --git a/src/legacy/ui/ui_render/bootstrap/template.js.hbs b/src/legacy/ui/ui_render/bootstrap/template.js.hbs index b60442690af3c..1453c974c1180 100644 --- a/src/legacy/ui/ui_render/bootstrap/template.js.hbs +++ b/src/legacy/ui/ui_render/bootstrap/template.js.hbs @@ -1,6 +1,7 @@ var kbnCsp = JSON.parse(document.querySelector('kbn-csp').getAttribute('data')); window.__kbnStrictCsp__ = kbnCsp.strictCsp; window.__kbnDarkMode__ = {{darkMode}}; +window.__kbnThemeVersion__ = "{{themeVersion}}"; window.__kbnPublicPath__ = {{publicPathMap}}; if (window.__kbnStrictCsp__ && window.__kbnCspNotEnforced__) { diff --git a/src/legacy/ui/ui_render/ui_render_mixin.js b/src/legacy/ui/ui_render/ui_render_mixin.js index 9b44395fa9c68..52c43c426ed91 100644 --- a/src/legacy/ui/ui_render/ui_render_mixin.js +++ b/src/legacy/ui/ui_render/ui_render_mixin.js @@ -96,6 +96,11 @@ export function uiRenderMixin(kbnServer, server, config) { ? await uiSettings.get('theme:darkMode') : false; + const themeVersion = + !authEnabled || request.auth.isAuthenticated + ? await uiSettings.get('theme:version') + : 'v7'; + const buildHash = server.newPlatform.env.packageInfo.buildNum; const basePath = config.get('server.basePath'); @@ -103,10 +108,10 @@ export function uiRenderMixin(kbnServer, server, config) { const dllBundlePath = `${basePath}/${buildHash}/built_assets/dlls`; const dllStyleChunks = DllCompiler.getRawDllConfig().chunks.map( - chunk => `${dllBundlePath}/vendors${chunk}.style.dll.css` + (chunk) => `${dllBundlePath}/vendors${chunk}.style.dll.css` ); const dllJsChunks = DllCompiler.getRawDllConfig().chunks.map( - chunk => `${dllBundlePath}/vendors${chunk}.bundle.dll.js` + (chunk) => `${dllBundlePath}/vendors${chunk}.bundle.dll.js` ); const styleSheetPaths = [ @@ -114,12 +119,16 @@ export function uiRenderMixin(kbnServer, server, config) { `${regularBundlePath}/kbn-ui-shared-deps/${UiSharedDeps.baseCssDistFilename}`, ...(darkMode ? [ - `${regularBundlePath}/kbn-ui-shared-deps/${UiSharedDeps.darkCssDistFilename}`, + themeVersion === 'v7' + ? `${regularBundlePath}/kbn-ui-shared-deps/${UiSharedDeps.darkCssDistFilename}` + : `${regularBundlePath}/kbn-ui-shared-deps/${UiSharedDeps.darkV8CssDistFilename}`, `${basePath}/node_modules/@kbn/ui-framework/dist/kui_dark.css`, `${regularBundlePath}/dark_theme.style.css`, ] : [ - `${regularBundlePath}/kbn-ui-shared-deps/${UiSharedDeps.lightCssDistFilename}`, + themeVersion === 'v7' + ? `${regularBundlePath}/kbn-ui-shared-deps/${UiSharedDeps.lightCssDistFilename}` + : `${regularBundlePath}/kbn-ui-shared-deps/${UiSharedDeps.lightV8CssDistFilename}`, `${basePath}/node_modules/@kbn/ui-framework/dist/kui_light.css`, `${regularBundlePath}/light_theme.style.css`, ]), @@ -130,9 +139,9 @@ export function uiRenderMixin(kbnServer, server, config) { `${regularBundlePath}/${app.getId()}.style.css`, ...kbnServer.uiExports.styleSheetPaths .filter( - path => path.theme === '*' || path.theme === (darkMode ? 'dark' : 'light') + (path) => path.theme === '*' || path.theme === (darkMode ? 'dark' : 'light') ) - .map(path => + .map((path) => path.localPath.endsWith('.scss') ? `${basePath}/${buildHash}/built_assets/css/${path.publicPath}` : `${basePath}/${path.publicPath}` @@ -153,7 +162,7 @@ export function uiRenderMixin(kbnServer, server, config) { const jsDependencyPaths = [ ...UiSharedDeps.jsDepFilenames.map( - filename => `${regularBundlePath}/kbn-ui-shared-deps/${filename}` + (filename) => `${regularBundlePath}/kbn-ui-shared-deps/${filename}` ), `${regularBundlePath}/kbn-ui-shared-deps/${UiSharedDeps.jsFilename}`, ...(isCore @@ -165,7 +174,7 @@ export function uiRenderMixin(kbnServer, server, config) { ]), ...kpPluginIds.map( - pluginId => `${regularBundlePath}/plugin/${pluginId}/${pluginId}.plugin.js` + (pluginId) => `${regularBundlePath}/plugin/${pluginId}/${pluginId}.plugin.js` ), ]; @@ -186,6 +195,7 @@ export function uiRenderMixin(kbnServer, server, config) { const bootstrap = new AppBootstrap({ templateData: { darkMode, + themeVersion, jsDependencyPaths, styleSheetPaths, publicPathMap, @@ -250,17 +260,14 @@ export function uiRenderMixin(kbnServer, server, config) { vars, }); - return h - .response(content) - .type('text/html') - .header('content-security-policy', http.csp.header); + return h.response(content).type('text/html').header('content-security-policy', http.csp.header); } - server.decorate('toolkit', 'renderApp', function(app, overrides) { + server.decorate('toolkit', 'renderApp', function (app, overrides) { return renderApp(this, app, true, overrides); }); - server.decorate('toolkit', 'renderAppWithDefaultConfig', function(app) { + server.decorate('toolkit', 'renderAppWithDefaultConfig', function (app) { return renderApp(this, app, false); }); } diff --git a/src/legacy/ui/ui_settings/integration_tests/ui_settings_mixin.test.ts b/src/legacy/ui/ui_settings/integration_tests/ui_settings_mixin.test.ts index dd3f12903abca..bee0d69706ebb 100644 --- a/src/legacy/ui/ui_settings/integration_tests/ui_settings_mixin.test.ts +++ b/src/legacy/ui/ui_settings/integration_tests/ui_settings_mixin.test.ts @@ -52,7 +52,7 @@ describe('uiSettingsMixin()', () => { log: sinon.stub(), route: sinon.stub(), addMemoizedFactoryToRequest(name: string, factory: (...args: any[]) => any) { - this.decorate('request', name, function(this: typeof server) { + this.decorate('request', name, function (this: typeof server) { return factory(this); }); }, @@ -103,9 +103,7 @@ describe('uiSettingsMixin()', () => { describe('server.uiSettingsServiceFactory()', () => { it('decorates server with "uiSettingsServiceFactory"', () => { const { decorations } = setup(); - expect(decorations.server) - .to.have.property('uiSettingsServiceFactory') - .a('function'); + expect(decorations.server).to.have.property('uiSettingsServiceFactory').a('function'); const uiSettingsServiceFactoryStub = sandbox.stub( uiSettingsServiceFactoryNS, @@ -118,9 +116,7 @@ describe('uiSettingsMixin()', () => { it('passes `server` and `options` argument to factory', () => { const { decorations, server } = setup(); - expect(decorations.server) - .to.have.property('uiSettingsServiceFactory') - .a('function'); + expect(decorations.server).to.have.property('uiSettingsServiceFactory').a('function'); const uiSettingsServiceFactoryStub = sandbox.stub( uiSettingsServiceFactoryNS, @@ -143,9 +139,7 @@ describe('uiSettingsMixin()', () => { describe('request.getUiSettingsService()', () => { it('exposes "getUiSettingsService" on requests', () => { const { decorations } = setup(); - expect(decorations.request) - .to.have.property('getUiSettingsService') - .a('function'); + expect(decorations.request).to.have.property('getUiSettingsService').a('function'); const getUiSettingsServiceForRequestStub = sandbox.stub( getUiSettingsServiceForRequestNS, @@ -158,9 +152,7 @@ describe('uiSettingsMixin()', () => { it('passes request to getUiSettingsServiceForRequest', () => { const { server, decorations } = setup(); - expect(decorations.request) - .to.have.property('getUiSettingsService') - .a('function'); + expect(decorations.request).to.have.property('getUiSettingsService').a('function'); const getUiSettingsServiceForRequestStub = sandbox.stub( getUiSettingsServiceForRequestNS, @@ -176,9 +168,7 @@ describe('uiSettingsMixin()', () => { describe('server.uiSettings()', () => { it('throws an error, links to pr', () => { const { decorations } = setup(); - expect(decorations.server) - .to.have.property('uiSettings') - .a('function'); + expect(decorations.server).to.have.property('uiSettings').a('function'); expect(() => { decorations.server.uiSettings(); }).to.throwError('http://github.com' as any); // incorrect typings diff --git a/src/legacy/ui/ui_settings/ui_exports_consumer.js b/src/legacy/ui/ui_settings/ui_exports_consumer.js index 0ced11afc8d2c..d2bb3a00ce0ed 100644 --- a/src/legacy/ui/ui_settings/ui_exports_consumer.js +++ b/src/legacy/ui/ui_settings/ui_exports_consumer.js @@ -41,7 +41,7 @@ export class UiExportsConsumer { switch (type) { case 'uiSettingDefaults': return (plugin, settingDefinitions) => { - Object.keys(settingDefinitions).forEach(key => { + Object.keys(settingDefinitions).forEach((key) => { if (key in this._uiSettingDefaults) { throw new Error(`uiSettingDefaults for key "${key}" are already defined`); } diff --git a/src/legacy/ui/ui_settings/ui_settings_mixin.js b/src/legacy/ui/ui_settings/ui_settings_mixin.js index 64251d290776c..accdc4d043d1a 100644 --- a/src/legacy/ui/ui_settings/ui_settings_mixin.js +++ b/src/legacy/ui/ui_settings/ui_settings_mixin.js @@ -43,7 +43,7 @@ export function uiSettingsMixin(kbnServer, server) { return uiSettingsServiceFactory(server, options); }); - server.addMemoizedFactoryToRequest('getUiSettingsService', request => { + server.addMemoizedFactoryToRequest('getUiSettingsService', (request) => { return getUiSettingsServiceForRequest(server, request); }); diff --git a/src/legacy/utils/__tests__/unset.js b/src/legacy/utils/__tests__/unset.js index 6e6840758c7ae..69122e06ac572 100644 --- a/src/legacy/utils/__tests__/unset.js +++ b/src/legacy/utils/__tests__/unset.js @@ -20,77 +20,77 @@ import { unset } from '../unset'; import expect from '@kbn/expect'; -describe('unset(obj, key)', function() { - describe('invalid input', function() { - it('should do nothing if not given an object', function() { +describe('unset(obj, key)', function () { + describe('invalid input', function () { + it('should do nothing if not given an object', function () { const obj = 'hello'; unset(obj, 'e'); expect(obj).to.equal('hello'); }); - it('should do nothing if not given a key', function() { + it('should do nothing if not given a key', function () { const obj = { one: 1 }; unset(obj); expect(obj).to.eql({ one: 1 }); }); - it('should do nothing if given an empty string as a key', function() { + it('should do nothing if given an empty string as a key', function () { const obj = { one: 1 }; unset(obj, ''); expect(obj).to.eql({ one: 1 }); }); }); - describe('shallow removal', function() { + describe('shallow removal', function () { let obj; - beforeEach(function() { + beforeEach(function () { obj = { one: 1, two: 2, deep: { three: 3, four: 4 } }; }); - it('should remove the param using a string key', function() { + it('should remove the param using a string key', function () { unset(obj, 'two'); expect(obj).to.eql({ one: 1, deep: { three: 3, four: 4 } }); }); - it('should remove the param using an array key', function() { + it('should remove the param using an array key', function () { unset(obj, ['two']); expect(obj).to.eql({ one: 1, deep: { three: 3, four: 4 } }); }); }); - describe('deep removal', function() { + describe('deep removal', function () { let obj; - beforeEach(function() { + beforeEach(function () { obj = { one: 1, two: 2, deep: { three: 3, four: 4 } }; }); - it('should remove the param using a string key', function() { + it('should remove the param using a string key', function () { unset(obj, 'deep.three'); expect(obj).to.eql({ one: 1, two: 2, deep: { four: 4 } }); }); - it('should remove the param using an array key', function() { + it('should remove the param using an array key', function () { unset(obj, ['deep', 'three']); expect(obj).to.eql({ one: 1, two: 2, deep: { four: 4 } }); }); }); - describe('recursive removal', function() { - it('should clear object if only value is removed', function() { + describe('recursive removal', function () { + it('should clear object if only value is removed', function () { const obj = { one: { two: { three: 3 } } }; unset(obj, 'one.two.three'); expect(obj).to.eql({}); }); - it('should clear object if no props are left', function() { + it('should clear object if no props are left', function () { const obj = { one: { two: { three: 3 } } }; unset(obj, 'one.two'); expect(obj).to.eql({}); }); - it('should remove deep property, then clear the object', function() { + it('should remove deep property, then clear the object', function () { const obj = { one: { two: { three: 3, four: 4 } } }; unset(obj, 'one.two.three'); expect(obj).to.eql({ one: { two: { four: 4 } } }); diff --git a/src/legacy/utils/__tests__/watch_stdio_for_line.js b/src/legacy/utils/__tests__/watch_stdio_for_line.js index 1bd69cfd8b64d..32d61658c1114 100644 --- a/src/legacy/utils/__tests__/watch_stdio_for_line.js +++ b/src/legacy/utils/__tests__/watch_stdio_for_line.js @@ -23,12 +23,12 @@ import sinon from 'sinon'; import { watchStdioForLine } from '../watch_stdio_for_line'; -describe('src/legacy/utils/watch_stdio_for_line', function() { +describe('src/legacy/utils/watch_stdio_for_line', function () { const sandbox = sinon.sandbox.create(); afterEach(() => sandbox.reset()); const onLogLine = sandbox.stub(); - const logFn = line => onLogLine(stripAnsi(line)); + const logFn = (line) => onLogLine(stripAnsi(line)); it('calls logFn with log lines', async () => { const proc = execa(process.execPath, ['-e', 'console.log("hi")']); @@ -39,7 +39,7 @@ describe('src/legacy/utils/watch_stdio_for_line', function() { sinon.assert.calledWithExactly(onLogLine, sinon.match(/hi/)); }); - it('send the proc SIGKILL if it logs a line matching exitAfter regexp', async function() { + it('send the proc SIGKILL if it logs a line matching exitAfter regexp', async function () { // fixture proc will exit after 10 seconds if sigint not received, but the test won't fail // unless we see the log line `SIGINT not received`, so we let the test take up to 30 seconds // for potentially huge delays here and there diff --git a/src/legacy/utils/binder.ts b/src/legacy/utils/binder.ts index 20c7cb9d4d490..55577e3a69e2b 100644 --- a/src/legacy/utils/binder.ts +++ b/src/legacy/utils/binder.ts @@ -38,6 +38,6 @@ export class BinderBase { public destroy() { const destroyers = this.disposal; this.disposal = []; - destroyers.forEach(fn => fn()); + destroyers.forEach((fn) => fn()); } } diff --git a/src/legacy/utils/streams/concat_stream_providers.js b/src/legacy/utils/streams/concat_stream_providers.js index 64643787ea771..11dfb84284df3 100644 --- a/src/legacy/utils/streams/concat_stream_providers.js +++ b/src/legacy/utils/streams/concat_stream_providers.js @@ -51,7 +51,7 @@ export function concatStreamProviders(sourceProviders, options = {}) { source // proxy errors from the source to the destination - .once('error', error => destination.emit('error', error)) + .once('error', (error) => destination.emit('error', error)) // pipe the source to the destination but only proxy the // end event if this is the last source .pipe(destination, { end: isLast }); diff --git a/src/legacy/utils/streams/filter_stream.test.ts b/src/legacy/utils/streams/filter_stream.test.ts index f5140b7639c74..7f4901f31c173 100644 --- a/src/legacy/utils/streams/filter_stream.test.ts +++ b/src/legacy/utils/streams/filter_stream.test.ts @@ -64,7 +64,7 @@ describe('createFilterStream()', () => { test('send the filtered values on the output stream', async () => { const result = await createPromiseFromStreams([ createListStream([1, 2, 3]), - createFilterStream(n => n % 2 === 0), + createFilterStream((n) => n % 2 === 0), createConcatStream([]), ]); diff --git a/src/legacy/utils/streams/list_stream.js b/src/legacy/utils/streams/list_stream.js index 703d664a97ec7..a614620b054b7 100644 --- a/src/legacy/utils/streams/list_stream.js +++ b/src/legacy/utils/streams/list_stream.js @@ -32,7 +32,7 @@ export function createListStream(items = []) { return new Readable({ objectMode: true, read(size) { - queue.splice(0, size).forEach(item => { + queue.splice(0, size).forEach((item) => { this.push(item); }); diff --git a/src/legacy/utils/streams/list_stream.test.js b/src/legacy/utils/streams/list_stream.test.js index 9052127793c6e..12e20696b0510 100644 --- a/src/legacy/utils/streams/list_stream.test.js +++ b/src/legacy/utils/streams/list_stream.test.js @@ -25,7 +25,7 @@ describe('listStream', () => { const onData = jest.fn(); str.on('data', onData); - await new Promise(resolve => str.on('end', resolve)); + await new Promise((resolve) => str.on('end', resolve)); expect(onData).toHaveBeenCalledTimes(4); expect(onData.mock.calls[0]).toEqual([1]); @@ -38,7 +38,7 @@ describe('listStream', () => { const list = [1, 2, 3, 4]; const str = createListStream(list); str.resume(); - await new Promise(resolve => str.on('end', resolve)); + await new Promise((resolve) => str.on('end', resolve)); expect(list).toEqual([1, 2, 3, 4]); }); }); diff --git a/src/legacy/utils/streams/map_stream.test.js b/src/legacy/utils/streams/map_stream.test.js index 4ffabe7477d73..d86da178f0c1b 100644 --- a/src/legacy/utils/streams/map_stream.test.js +++ b/src/legacy/utils/streams/map_stream.test.js @@ -39,7 +39,7 @@ describe('createMapStream()', () => { test('send the return value from the mapper on the output stream', async () => { const result = await createPromiseFromStreams([ createListStream([1, 2, 3]), - createMapStream(n => n * 100), + createMapStream((n) => n * 100), createConcatStream([]), ]); diff --git a/src/legacy/utils/streams/promise_from_streams.js b/src/legacy/utils/streams/promise_from_streams.js index 9c8205702f254..05f6a08aa1a09 100644 --- a/src/legacy/utils/streams/promise_from_streams.js +++ b/src/legacy/utils/streams/promise_from_streams.js @@ -58,7 +58,7 @@ export async function createPromiseFromStreams(streams) { ); } return new Promise((resolve, reject) => { - pipeline(...streams, err => { + pipeline(...streams, (err) => { if (err) return reject(err); resolve(finalChunk); }); diff --git a/src/legacy/utils/streams/promise_from_streams.test.js b/src/legacy/utils/streams/promise_from_streams.test.js index 9876e452e262b..e4d9835106f12 100644 --- a/src/legacy/utils/streams/promise_from_streams.test.js +++ b/src/legacy/utils/streams/promise_from_streams.test.js @@ -25,9 +25,9 @@ describe('promiseFromStreams', () => { test('pipes together an array of streams', async () => { const str1 = createListStream([1, 2, 3]); const str2 = createReduceStream((acc, n) => acc + n, 0); - const sumPromise = new Promise(resolve => str2.once('data', resolve)); + const sumPromise = new Promise((resolve) => str2.once('data', resolve)); createPromiseFromStreams([str1, str2]); - await new Promise(resolve => str2.once('end', resolve)); + await new Promise((resolve) => str2.once('end', resolve)); expect(await sumPromise).toBe(6); }); @@ -88,7 +88,7 @@ describe('promiseFromStreams', () => { write(chunk, enc, cb) { duplexReadQueue.push( - new Promise(resolve => { + new Promise((resolve) => { setTimeout(() => { written += chunk; cb(); diff --git a/src/legacy/utils/streams/reduce_stream.test.js b/src/legacy/utils/streams/reduce_stream.test.js index 98d01ec2c773a..2c073f67f82a8 100644 --- a/src/legacy/utils/streams/reduce_stream.test.js +++ b/src/legacy/utils/streams/reduce_stream.test.js @@ -20,7 +20,7 @@ import { createReduceStream, createPromiseFromStreams, createListStream } from './'; const promiseFromEvent = (name, emitter) => - new Promise(resolve => emitter.on(name, () => resolve(name))); + new Promise((resolve) => emitter.on(name, () => resolve(name))); describe('reduceStream', () => { test('calls the reducer for each item provided', async () => { @@ -41,7 +41,7 @@ describe('reduceStream', () => { test('provides the return value of the last iteration of the reducer', async () => { const result = await createPromiseFromStreams([ createListStream('abcdefg'.split('')), - createReduceStream(acc => acc + 1, 0), + createReduceStream((acc) => acc + 1, 0), ]); expect(result).toBe(7); }); diff --git a/src/legacy/utils/streams/replace_stream.test.js b/src/legacy/utils/streams/replace_stream.test.js index 219d4fb18a59e..01b89f93e5af0 100644 --- a/src/legacy/utils/streams/replace_stream.test.js +++ b/src/legacy/utils/streams/replace_stream.test.js @@ -28,7 +28,7 @@ import { async function concatToString(streams) { return await createPromiseFromStreams([ ...streams, - createMapStream(buff => buff.toString('utf8')), + createMapStream((buff) => buff.toString('utf8')), createConcatStream(''), ]); } @@ -41,7 +41,7 @@ describe('replaceStream', () => { createConcatStream([]), ]); - chunks.forEach(chunk => { + chunks.forEach((chunk) => { expect(chunk).toBeInstanceOf(Buffer); }); }); @@ -53,7 +53,7 @@ describe('replaceStream', () => { createConcatStream([]), ]); - chunks.forEach(chunk => { + chunks.forEach((chunk) => { expect(chunk).toBeInstanceOf(Buffer); }); }); diff --git a/src/legacy/utils/streams/split_stream.test.js b/src/legacy/utils/streams/split_stream.test.js index 148b9211b81bb..e0736d220ba5c 100644 --- a/src/legacy/utils/streams/split_stream.test.js +++ b/src/legacy/utils/streams/split_stream.test.js @@ -25,7 +25,7 @@ async function split(stream, input) { stream.pipe(concat); const output = createPromiseFromStreams([concat]); - input.forEach(i => { + input.forEach((i) => { stream.write(i); }); stream.end(); diff --git a/src/legacy/utils/watch_stdio_for_line.js b/src/legacy/utils/watch_stdio_for_line.js index dc822602931b7..01323b4d4e967 100644 --- a/src/legacy/utils/watch_stdio_for_line.js +++ b/src/legacy/utils/watch_stdio_for_line.js @@ -53,7 +53,7 @@ export async function watchStdioForLine(proc, logFn, exitAfter) { } await Promise.all([ - proc.catch(error => { + proc.catch((error) => { // ignore the error thrown by execa if it's because we killed with SIGINT if (error.signal !== 'SIGINT') { throw error; diff --git a/src/optimize/base_optimizer.js b/src/optimize/base_optimizer.js index 9d3a834b455db..12131b89e03c1 100644 --- a/src/optimize/base_optimizer.js +++ b/src/optimize/base_optimizer.js @@ -109,7 +109,7 @@ export default class BaseOptimizer { } registerCompilerDoneHook() { - this.compiler.hooks.done.tap('base_optimizer-done', stats => { + this.compiler.hooks.done.tap('base_optimizer-done', (stats) => { // We are not done while we have an additional // compilation pass to run // We also don't need to emit the stats if we don't have @@ -120,7 +120,7 @@ export default class BaseOptimizer { const path = this.uiBundles.resolvePath('stats.json'); const content = JSON.stringify(stats.toJson()); - writeFile(path, content, function(err) { + writeFile(path, content, function (err) { if (err) throw err; }); }); @@ -226,7 +226,7 @@ export default class BaseOptimizer { * Creates the selection rules for a loader that will only pass for * source files that are eligible for automatic transpilation. */ - const createSourceFileResourceSelector = test => { + const createSourceFileResourceSelector = (test) => { return [ { test, @@ -268,20 +268,22 @@ export default class BaseOptimizer { cacheGroups: { commons: { name: 'commons', - chunks: chunk => + chunks: (chunk) => chunk.canBeInitial() && chunk.name !== 'light_theme' && chunk.name !== 'dark_theme', minChunks: 2, reuseExistingChunk: true, }, light_theme: { name: 'light_theme', - test: m => m.constructor.name === 'CssModule' && recursiveIssuer(m) === 'light_theme', + test: (m) => + m.constructor.name === 'CssModule' && recursiveIssuer(m) === 'light_theme', chunks: 'all', enforce: true, }, dark_theme: { name: 'dark_theme', - test: m => m.constructor.name === 'CssModule' && recursiveIssuer(m) === 'dark_theme', + test: (m) => + m.constructor.name === 'CssModule' && recursiveIssuer(m) === 'dark_theme', chunks: 'all', enforce: true, }, @@ -302,13 +304,13 @@ export default class BaseOptimizer { }), // ignore scss imports in new-platform code that finds its way into legacy bundles - new webpack.NormalModuleReplacementPlugin(/\.scss$/, resource => { + new webpack.NormalModuleReplacementPlugin(/\.scss$/, (resource) => { resource.request = EMPTY_MODULE_PATH; }), // replace imports for `uiExports/*` modules with a synthetic module // created by create_ui_exports_module.js - new webpack.NormalModuleReplacementPlugin(/^uiExports\//, resource => { + new webpack.NormalModuleReplacementPlugin(/^uiExports\//, (resource) => { // the map of uiExport types to module ids const extensions = this.uiBundles.getAppExtensions(); @@ -330,7 +332,7 @@ export default class BaseOptimizer { ].join(''); }), - ...this.uiBundles.getWebpackPluginProviders().map(provider => provider(webpack)), + ...this.uiBundles.getWebpackPluginProviders().map((provider) => provider(webpack)), ], module: { @@ -376,7 +378,7 @@ export default class BaseOptimizer { }, ]), }, - ...this.uiBundles.getPostLoaders().map(loader => ({ + ...this.uiBundles.getPostLoaders().map((loader) => ({ enforce: 'post', ...loader, })), diff --git a/src/optimize/bundles_route/file_hash.ts b/src/optimize/bundles_route/file_hash.ts index 7b0801098ed10..d8b4c4419b844 100644 --- a/src/optimize/bundles_route/file_hash.ts +++ b/src/optimize/bundles_route/file_hash.ts @@ -46,15 +46,15 @@ export async function getFileHash(cache: FileHashCache, path: string, stat: Fs.S const promise = Rx.merge( Rx.fromEvent(read, 'data'), Rx.fromEvent(read, 'error').pipe( - map(error => { + map((error) => { throw error; }) ) ) .pipe(takeUntil(Rx.fromEvent(read, 'end'))) - .forEach(chunk => hash.update(chunk)) + .forEach((chunk) => hash.update(chunk)) .then(() => hash.digest('hex')) - .catch(error => { + .catch((error) => { // don't cache failed attempts cache.del(key); throw error; diff --git a/src/optimize/create_ui_exports_module.js b/src/optimize/create_ui_exports_module.js index 2ab19d71e1f1c..d20814b10931b 100644 --- a/src/optimize/create_ui_exports_module.js +++ b/src/optimize/create_ui_exports_module.js @@ -22,7 +22,7 @@ function normalizePath(path) { return path.replace(/[\\\/]+/g, '/'); } -module.exports = function() { +module.exports = function () { if (!module.id.includes('?')) { throw new Error('create_ui_exports_module loaded without JSON args in module.id'); } @@ -31,7 +31,7 @@ module.exports = function() { const comment = `// dynamically generated to load ${type} uiExports from plugins`; const requires = modules .sort((a, b) => a.localeCompare(b)) - .map(m => `require('${normalizePath(m)}')`) + .map((m) => `require('${normalizePath(m)}')`) .join('\n '); return { diff --git a/src/optimize/dynamic_dll_plugin/dll_compiler.js b/src/optimize/dynamic_dll_plugin/dll_compiler.js index 9889c1f71c3bf..9ab21ee0e9076 100644 --- a/src/optimize/dynamic_dll_plugin/dll_compiler.js +++ b/src/optimize/dynamic_dll_plugin/dll_compiler.js @@ -48,7 +48,7 @@ export class DllCompiler { uiBundles = {}, babelLoaderCacheDir = '', threadLoaderPoolConfig = {}, - chunks = Array.from(Array(4).keys()).map(chunkN => `_${chunkN}`) + chunks = Array.from(Array(4).keys()).map((chunkN) => `_${chunkN}`) ) { return { uiBundles, @@ -130,25 +130,25 @@ export class DllCompiler { } getDllPaths() { - return this.rawDllConfig.chunks.map(chunk => + return this.rawDllConfig.chunks.map((chunk) => this.resolvePath(`${this.rawDllConfig.entryName}${chunk}${this.rawDllConfig.dllExt}`) ); } getEntryPaths() { - return this.rawDllConfig.chunks.map(chunk => + return this.rawDllConfig.chunks.map((chunk) => this.resolvePath(`${this.rawDllConfig.entryName}${chunk}${this.rawDllConfig.entryExt}`) ); } getManifestPaths() { - return this.rawDllConfig.chunks.map(chunk => + return this.rawDllConfig.chunks.map((chunk) => this.resolvePath(`${this.rawDllConfig.entryName}${chunk}${this.rawDllConfig.manifestExt}`) ); } getStylePaths() { - return this.rawDllConfig.chunks.map(chunk => + return this.rawDllConfig.chunks.map((chunk) => this.resolvePath(`${this.rawDllConfig.entryName}${chunk}${this.rawDllConfig.styleExt}`) ); } @@ -156,7 +156,7 @@ export class DllCompiler { async ensureEntryFilesExists() { const entryPaths = this.getEntryPaths(); - await Promise.all(entryPaths.map(async entryPath => await this.ensureFileExists(entryPath))); + await Promise.all(entryPaths.map(async (entryPath) => await this.ensureFileExists(entryPath))); } async ensureManifestFilesExists() { @@ -179,7 +179,7 @@ export class DllCompiler { async ensureStyleFileExists() { const stylePaths = this.getStylePaths(); - await Promise.all(stylePaths.map(async stylePath => await this.ensureFileExists(stylePath))); + await Promise.all(stylePaths.map(async (stylePath) => await this.ensureFileExists(stylePath))); } async ensureFileExists(filePath, content) { @@ -208,7 +208,7 @@ export class DllCompiler { dllsExistsSync() { const dllPaths = this.getDllPaths(); - return dllPaths.every(dllPath => this.existsSync(dllPath)); + return dllPaths.every((dllPath) => this.existsSync(dllPath)); } existsSync(filePath) { @@ -223,7 +223,7 @@ export class DllCompiler { const entryPaths = this.getEntryPaths(); const entryFilesContent = await Promise.all( - entryPaths.map(async entryPath => await this.readFile(entryPath)) + entryPaths.map(async (entryPath) => await this.readFile(entryPath)) ); // merge all the module contents from entry files again into @@ -304,7 +304,7 @@ export class DllCompiler { // bundled inside the dll bundle const notAllowedModules = []; - stats.compilation.modules.forEach(module => { + stats.compilation.modules.forEach((module) => { // ignore if no module or userRequest are defined if (!module || !module.resource) { return; @@ -327,7 +327,7 @@ export class DllCompiler { if (notInNodeModulesOrWebpackShims(module.resource)) { const reasons = module.reasons || []; - reasons.forEach(reason => { + reasons.forEach((reason) => { // Skip if we can't read the reason info if (!reason || !reason.module || !reason.module.resource) { return; diff --git a/src/optimize/dynamic_dll_plugin/dll_entry_template.js b/src/optimize/dynamic_dll_plugin/dll_entry_template.js index 0c286896d0b71..351bed4e591ba 100644 --- a/src/optimize/dynamic_dll_plugin/dll_entry_template.js +++ b/src/optimize/dynamic_dll_plugin/dll_entry_template.js @@ -19,7 +19,7 @@ export function dllEntryTemplate(requirePaths = []) { return requirePaths - .map(path => `require('${path}');`) + .map((path) => `require('${path}');`) .sort() .join('\n'); } @@ -33,9 +33,5 @@ export function dllEntryFileContentArrayToString(content = []) { } export function dllMergeAllEntryFilesContent(content = []) { - return content - .join('\n') - .split('\n') - .sort() - .join('\n'); + return content.join('\n').split('\n').sort().join('\n'); } diff --git a/src/optimize/dynamic_dll_plugin/dynamic_dll_plugin.js b/src/optimize/dynamic_dll_plugin/dynamic_dll_plugin.js index 484c7dfbfd595..fb6f6e097b5cd 100644 --- a/src/optimize/dynamic_dll_plugin/dynamic_dll_plugin.js +++ b/src/optimize/dynamic_dll_plugin/dynamic_dll_plugin.js @@ -72,7 +72,7 @@ export class DynamicDllPlugin { const dllContext = rawDllConfig.context; const dllManifestPaths = this.dllCompiler.getManifestPaths(); - dllManifestPaths.forEach(dllChunkManifestPath => { + dllManifestPaths.forEach((dllChunkManifestPath) => { new webpack.DllReferencePlugin({ context: dllContext, manifest: dllChunkManifestPath, @@ -109,10 +109,10 @@ export class DynamicDllPlugin { registerBeforeCompileHook(compiler) { compiler.hooks.beforeCompile.tapPromise('DynamicDllPlugin', async ({ normalModuleFactory }) => { - normalModuleFactory.hooks.factory.tap('DynamicDllPlugin', actualFactory => (params, cb) => { + normalModuleFactory.hooks.factory.tap('DynamicDllPlugin', (actualFactory) => (params, cb) => { // This is used in order to avoid the cache for DLL modules // resolved from other dependencies - normalModuleFactory.cachePredicate = module => + normalModuleFactory.cachePredicate = (module) => !(module.stubType === DLL_ENTRY_STUB_MODULE_TYPE); // Overrides the normalModuleFactory module creation behaviour @@ -123,7 +123,7 @@ export class DynamicDllPlugin { } else { this.mapNormalModule(module).then( (m = module) => cb(undefined, m), - error => cb(error) + (error) => cb(error) ); } }); @@ -132,7 +132,7 @@ export class DynamicDllPlugin { } registerCompilationHook(compiler) { - compiler.hooks.compilation.tap('DynamicDllPlugin', compilation => { + compiler.hooks.compilation.tap('DynamicDllPlugin', (compilation) => { compilation.hooks.needAdditionalPass.tap('DynamicDllPlugin', () => { // Run the procedures in order to execute our dll compilation // The process is very straightforward in it's conception: @@ -215,7 +215,7 @@ export class DynamicDllPlugin { } registerDoneHook(compiler) { - compiler.hooks.done.tapPromise('DynamicDllPlugin', async stats => { + compiler.hooks.done.tapPromise('DynamicDllPlugin', async (stats) => { if (stats.compilation.needsDLLCompilation) { // Run the dlls compiler and increment // the performed compilations @@ -341,7 +341,7 @@ export class DynamicDllPlugin { // that we rely in next ones. this.dllCompiler .getManifestPaths() - .forEach(chunkDllManifestPath => mainCompiler.inputFileSystem.purge(chunkDllManifestPath)); + .forEach((chunkDllManifestPath) => mainCompiler.inputFileSystem.purge(chunkDllManifestPath)); this.performedCompilations++; diff --git a/src/optimize/fs_optimizer.js b/src/optimize/fs_optimizer.js index 03e413f04eb46..71a4c85a9e5a5 100644 --- a/src/optimize/fs_optimizer.js +++ b/src/optimize/fs_optimizer.js @@ -26,7 +26,7 @@ export default class FsOptimizer extends BaseOptimizer { await this.init(); } - await fromNode(cb => { + await fromNode((cb) => { this.compiler.run((err, stats) => { if (err || !stats) return cb(err); diff --git a/src/optimize/np_ui_plugin_public_dirs.ts b/src/optimize/np_ui_plugin_public_dirs.ts index e7c3207948f6a..8b49ffb74cb08 100644 --- a/src/optimize/np_ui_plugin_public_dirs.ts +++ b/src/optimize/np_ui_plugin_public_dirs.ts @@ -36,7 +36,7 @@ export function isNpUiPluginPublicDirs(x: any): x is NpUiPluginPublicDirs { return ( Array.isArray(x) && x.every( - s => typeof s === 'object' && s && typeof s.id === 'string' && typeof s.path === 'string' + (s) => typeof s === 'object' && s && typeof s.id === 'string' && typeof s.path === 'string' ) ); } diff --git a/src/optimize/public_path_placeholder.ts b/src/optimize/public_path_placeholder.ts index 1ec2b4a431aa6..d5f57a1586774 100644 --- a/src/optimize/public_path_placeholder.ts +++ b/src/optimize/public_path_placeholder.ts @@ -38,7 +38,7 @@ export function replacePlaceholder(read: Stream.Readable, replacement: string) { // choose what to do with them. Rx.fromEvent(read, 'error') .pipe(take(1), takeUntil(Rx.fromEvent(read, 'end'))) - .forEach(error => { + .forEach((error) => { replace.emit('error', error); replace.end(); }); diff --git a/src/optimize/watch/optmzr_role.js b/src/optimize/watch/optmzr_role.js index 1f6107996277c..ba8007e1065b4 100644 --- a/src/optimize/watch/optmzr_role.js +++ b/src/optimize/watch/optmzr_role.js @@ -71,7 +71,7 @@ export default async (kbnServer, kibanaHapiServer, config) => { process.send(['WORKER_BROADCAST', { optimizeReady: ready }]); }; - process.on('message', msg => { + process.on('message', (msg) => { if (msg && msg.optimizeReady === '?') sendReady(); }); diff --git a/src/optimize/watch/proxy_role.js b/src/optimize/watch/proxy_role.js index 0f6f3b2d4b622..ce2d63aa2eff0 100644 --- a/src/optimize/watch/proxy_role.js +++ b/src/optimize/watch/proxy_role.js @@ -30,7 +30,7 @@ export default (kbnServer, server, config) => { }) ); - return fromNode(cb => { + return fromNode((cb) => { const timeout = setTimeout(() => { cb(new Error('Timeout waiting for the optimizer to become ready')); }, config.get('optimize.watchProxyTimeout')); @@ -42,7 +42,7 @@ export default (kbnServer, server, config) => { if (!process.connected) return; process.send(['WORKER_BROADCAST', { optimizeReady: '?' }]); - process.on('message', msg => { + process.on('message', (msg) => { switch (get(msg, 'optimizeReady')) { case true: clearTimeout(timeout); diff --git a/src/optimize/watch/watch.js b/src/optimize/watch/watch.js index a84fcc59e13f5..a284da11f294f 100644 --- a/src/optimize/watch/watch.js +++ b/src/optimize/watch/watch.js @@ -19,7 +19,7 @@ import { isWorker } from 'cluster'; -export default async kbnServer => { +export default async (kbnServer) => { if (!isWorker) { throw new Error(`watch optimization is only available when using the "--dev" cli flag`); } diff --git a/src/optimize/watch/watch_cache.ts b/src/optimize/watch/watch_cache.ts index b6784c1734a17..40bd1d6075f47 100644 --- a/src/optimize/watch/watch_cache.ts +++ b/src/optimize/watch/watch_cache.ts @@ -174,7 +174,7 @@ async function recursiveDelete(directory: string) { const entries = await readdirAsync(directory, { withFileTypes: true }); await Promise.all( - entries.map(entry => { + entries.map((entry) => { const absolutePath = path.join(directory, entry.name); return entry.isDirectory() ? recursiveDelete(absolutePath) : unlinkAsync(absolutePath); }) diff --git a/src/optimize/watch/watch_optimizer.js b/src/optimize/watch/watch_optimizer.js index cdff57a00c2e0..816185e544ab5 100644 --- a/src/optimize/watch/watch_optimizer.js +++ b/src/optimize/watch/watch_optimizer.js @@ -83,7 +83,7 @@ export default class WatchOptimizer extends BaseOptimizer { registerCompilerDoneHook() { super.registerCompilerDoneHook(); - this.compiler.hooks.done.tap('watch_optimizer-done', stats => { + this.compiler.hooks.done.tap('watch_optimizer-done', (stats) => { if (stats.compilation.needAdditionalPass) { return; } @@ -145,7 +145,7 @@ export default class WatchOptimizer extends BaseOptimizer { } } - compilerWatchErrorHandler = error => { + compilerWatchErrorHandler = (error) => { if (error) { this.status$.next({ type: STATUS.FATAL, diff --git a/src/plugins/advanced_settings/public/management_app/advanced_settings.tsx b/src/plugins/advanced_settings/public/management_app/advanced_settings.tsx index 97abdcb10016d..d8853015d362a 100644 --- a/src/plugins/advanced_settings/public/management_app/advanced_settings.tsx +++ b/src/plugins/advanced_settings/public/management_app/advanced_settings.tsx @@ -125,7 +125,7 @@ export class AdvancedSettingsComponent extends Component< mapConfig(config: IUiSettingsClient) { const all = config.getAll(); return Object.entries(all) - .map(setting => { + .map((setting) => { return toEditableConfig({ def: setting[1], name: setting[0], @@ -134,7 +134,7 @@ export class AdvancedSettingsComponent extends Component< isOverridden: config.isOverridden(setting[0]), }); }) - .filter(c => !c.readonly) + .filter((c) => !c.readonly) .sort(Comparators.property('name', Comparators.default('asc'))); } diff --git a/src/plugins/advanced_settings/public/management_app/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.tsx b/src/plugins/advanced_settings/public/management_app/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.tsx index cb2999830b053..9e06da5f79008 100644 --- a/src/plugins/advanced_settings/public/management_app/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.tsx +++ b/src/plugins/advanced_settings/public/management_app/components/advanced_settings_voice_announcement/advanced_settings_voice_announcement.tsx @@ -60,8 +60,8 @@ export class AdvancedSettingsVoiceAnnouncement extends Component { }; render() { - const filteredSections = Object.values(this.props.settings).map(setting => - setting.map(option => option.ariaName) + const filteredSections = Object.values(this.props.settings).map((setting) => + setting.map((option) => option.ariaName) ); const filteredOptions = [...filteredSections]; return ( diff --git a/src/plugins/advanced_settings/public/management_app/components/field/field.test.tsx b/src/plugins/advanced_settings/public/management_app/components/field/field.test.tsx index 356e38c799659..72992c190e8ae 100644 --- a/src/plugins/advanced_settings/public/management_app/components/field/field.test.tsx +++ b/src/plugins/advanced_settings/public/management_app/components/field/field.test.tsx @@ -205,7 +205,7 @@ const getFieldSettingValue = (wrapper: ReactWrapper, name: string, type: string) }; describe('Field', () => { - Object.keys(settings).forEach(type => { + Object.keys(settings).forEach((type) => { const setting = settings[type]; describe(`for ${type} setting`, () => { @@ -325,10 +325,10 @@ describe('Field', () => { ); const select = findTestSubject(component, `advancedSetting-editField-${setting.name}`); // @ts-ignore - const values = select.find('option').map(option => option.prop('value')); + const values = select.find('option').map((option) => option.prop('value')); expect(values).toEqual(['apple', 'orange', 'banana']); // @ts-ignore - const labels = select.find('option').map(option => option.text()); + const labels = select.find('option').map((option) => option.text()); expect(labels).toEqual(['Apple', 'Orange', 'banana']); }); } diff --git a/src/plugins/advanced_settings/public/management_app/components/field/field.tsx b/src/plugins/advanced_settings/public/management_app/components/field/field.tsx index 60d2b55dfceb4..32bfc0826e7c4 100644 --- a/src/plugins/advanced_settings/public/management_app/components/field/field.tsx +++ b/src/plugins/advanced_settings/public/management_app/components/field/field.tsx @@ -266,7 +266,7 @@ export class Field extends PureComponent { reader.onload = () => { resolve(reader.result || undefined); }; - reader.onerror = err => { + reader.onerror = (err) => { reject(err); }; }); @@ -378,7 +378,7 @@ export class Field extends PureComponent { { + options={(options as string[]).map((option) => { return { text: optionLabels.hasOwnProperty(option) ? optionLabels[option] : option, value: option, diff --git a/src/plugins/advanced_settings/public/management_app/components/form/form.tsx b/src/plugins/advanced_settings/public/management_app/components/form/form.tsx index 2cd4d3c0b43ec..142ea06c7dce4 100644 --- a/src/plugins/advanced_settings/public/management_app/components/form/form.tsx +++ b/src/plugins/advanced_settings/public/management_app/components/form/form.tsx @@ -82,7 +82,7 @@ export class Form extends PureComponent { getSettingByKey = (key: string): FieldSetting | undefined => { return Object.values(this.props.settings) .flat() - .find(el => el.name === key); + .find((el) => el.name === key); }; getCountOfUnsavedChanges = (): number => { @@ -92,8 +92,8 @@ export class Form extends PureComponent { getCountOfHiddenUnsavedChanges = (): number => { const shownSettings = Object.values(this.props.visibleSettings) .flat() - .map(setting => setting.name); - return Object.keys(this.state.unsavedChanges).filter(key => !shownSettings.includes(key)) + .map((setting) => setting.name); + return Object.keys(this.state.unsavedChanges).filter((key) => !shownSettings.includes(key)) .length; }; @@ -256,7 +256,7 @@ export class Form extends PureComponent { - {settings.map(setting => { + {settings.map((setting) => { return ( { // TODO #64541 // Delete these classes let bottomBarClasses = ''; - const pageNav = this.props.settings.general.find(setting => setting.name === 'pageNavigation'); + const pageNav = this.props.settings.general.find( + (setting) => setting.name === 'pageNavigation' + ); if (pageNav?.value === 'legacy') { bottomBarClasses = classNames('mgtAdvancedSettingsForm__bottomBar', { @@ -401,7 +403,7 @@ export class Form extends PureComponent { const { visibleSettings, categories, categoryCounts, clearQuery } = this.props; const currentCategories: Category[] = []; - categories.forEach(category => { + categories.forEach((category) => { if (visibleSettings[category] && visibleSettings[category].length) { currentCategories.push(category); } @@ -411,7 +413,7 @@ export class Form extends PureComponent {

{currentCategories.length - ? currentCategories.map(category => { + ? currentCategories.map((category) => { return this.renderCategory( category, visibleSettings[category], diff --git a/src/plugins/advanced_settings/public/management_app/components/search/search.tsx b/src/plugins/advanced_settings/public/management_app/components/search/search.tsx index 74e4894a27a6d..e440159b0ed71 100644 --- a/src/plugins/advanced_settings/public/management_app/components/search/search.tsx +++ b/src/plugins/advanced_settings/public/management_app/components/search/search.tsx @@ -35,7 +35,7 @@ export class Search extends PureComponent { constructor(props: SearchProps) { super(props); const { categories } = props; - this.categories = categories.map(category => { + this.categories = categories.map((category) => { return { value: category, name: getCategoryName(category), diff --git a/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.test.ts b/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.test.ts index e129481a397c1..f27f58c599cca 100644 --- a/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.test.ts +++ b/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.test.ts @@ -20,16 +20,16 @@ import expect from '@kbn/expect'; import { getAriaName } from './get_aria_name'; -describe('Settings', function() { - describe('Advanced', function() { - describe('getAriaName(name)', function() { - it('should return a space delimited lower-case string with no special characters', function() { +describe('Settings', function () { + describe('Advanced', function () { + describe('getAriaName(name)', function () { + it('should return a space delimited lower-case string with no special characters', function () { expect(getAriaName('xPack:defaultAdminEmail')).to.be('x pack default admin email'); expect(getAriaName('doc_table:highlight')).to.be('doc table highlight'); expect(getAriaName('foo')).to.be('foo'); }); - it('should return an empty string if passed undefined or null', function() { + it('should return an empty string if passed undefined or null', function () { expect(getAriaName()).to.be(''); expect(getAriaName(undefined)).to.be(''); }); diff --git a/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.ts b/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.ts index d5c2be752a278..c33ac6abafb54 100644 --- a/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.ts +++ b/src/plugins/advanced_settings/public/management_app/lib/get_aria_name.ts @@ -28,6 +28,6 @@ import { words } from 'lodash'; */ export function getAriaName(name?: string) { return words(name || '') - .map(word => word.toLowerCase()) + .map((word) => word.toLowerCase()) .join(' '); } diff --git a/src/plugins/advanced_settings/public/management_app/lib/get_category_name.test.ts b/src/plugins/advanced_settings/public/management_app/lib/get_category_name.test.ts index 73e303e20c64d..74b61587524f5 100644 --- a/src/plugins/advanced_settings/public/management_app/lib/get_category_name.test.ts +++ b/src/plugins/advanced_settings/public/management_app/lib/get_category_name.test.ts @@ -20,14 +20,14 @@ import expect from '@kbn/expect'; import { getCategoryName } from './get_category_name'; -describe('Settings', function() { - describe('Advanced', function() { - describe('getCategoryName(category)', function() { - it('should capitalize unknown category', function() { +describe('Settings', function () { + describe('Advanced', function () { + describe('getCategoryName(category)', function () { + it('should capitalize unknown category', function () { expect(getCategoryName('elasticsearch')).to.be('Elasticsearch'); }); - it('should return empty string for no category', function() { + it('should return empty string for no category', function () { expect(getCategoryName()).to.be(''); expect(getCategoryName('')).to.be(''); }); diff --git a/src/plugins/advanced_settings/public/management_app/lib/get_category_name.ts b/src/plugins/advanced_settings/public/management_app/lib/get_category_name.ts index 46d28ce9d5c40..bf3ac9628754a 100644 --- a/src/plugins/advanced_settings/public/management_app/lib/get_category_name.ts +++ b/src/plugins/advanced_settings/public/management_app/lib/get_category_name.ts @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; -const upperFirst = (str = '') => str.replace(/^./, strng => strng.toUpperCase()); +const upperFirst = (str = '') => str.replace(/^./, (strng) => strng.toUpperCase()); const names: Record = { general: i18n.translate('advancedSettings.categoryNames.generalLabel', { diff --git a/src/plugins/advanced_settings/public/management_app/lib/get_val_type.test.ts b/src/plugins/advanced_settings/public/management_app/lib/get_val_type.test.ts index ec59dcaa1ea29..e971f545fd605 100644 --- a/src/plugins/advanced_settings/public/management_app/lib/get_val_type.test.ts +++ b/src/plugins/advanced_settings/public/management_app/lib/get_val_type.test.ts @@ -20,16 +20,16 @@ import expect from '@kbn/expect'; import { getValType } from './get_val_type'; -describe('Settings', function() { - describe('Advanced', function() { - describe('getValType(def, val)', function() { - it('should return the explicitly defined type of a setting', function() { +describe('Settings', function () { + describe('Advanced', function () { + describe('getValType(def, val)', function () { + it('should return the explicitly defined type of a setting', function () { expect(getValType({ type: 'string' })).to.be('string'); expect(getValType({ type: 'json' })).to.be('json'); expect(getValType({ type: 'string', value: 5 })).to.be('string'); }); - it('should return array if the value is an Array and there is no defined type', function() { + it('should return array if the value is an Array and there is no defined type', function () { expect(getValType({ type: 'string' }, [1, 2, 3])).to.be('string'); expect(getValType({ type: 'json', value: [1, 2, 3] })).to.be('json'); @@ -37,12 +37,12 @@ describe('Settings', function() { expect(getValType({ value: [1, 2, 3] }, 'someString')).to.be('array'); }); - it('should return the type of the default value if there is no type and it is not an array', function() { + it('should return the type of the default value if there is no type and it is not an array', function () { expect(getValType({ value: 'someString' })).to.be('string'); expect(getValType({ value: 'someString' }, 42)).to.be('string'); }); - it('should return the type of the value if the default value is null', function() { + it('should return the type of the value if the default value is null', function () { expect(getValType({ value: null }, 'someString')).to.be('string'); }); }); diff --git a/src/plugins/advanced_settings/public/management_app/lib/is_default_value.test.ts b/src/plugins/advanced_settings/public/management_app/lib/is_default_value.test.ts index 836dcb6b87676..4cde8bf517499 100644 --- a/src/plugins/advanced_settings/public/management_app/lib/is_default_value.test.ts +++ b/src/plugins/advanced_settings/public/management_app/lib/is_default_value.test.ts @@ -21,10 +21,10 @@ import expect from '@kbn/expect'; import { isDefaultValue } from './is_default_value'; import { UiSettingsType } from '../../../../../core/public'; -describe('Settings', function() { - describe('Advanced', function() { - describe('getCategoryName(category)', function() { - describe('when given a setting definition object', function() { +describe('Settings', function () { + describe('Advanced', function () { + describe('getCategoryName(category)', function () { + describe('when given a setting definition object', function () { const setting = { isCustom: false, value: 'value', @@ -43,21 +43,21 @@ describe('Settings', function() { validation: { regex: /regexString/, message: 'validation description' }, }; - describe('that is custom', function() { - it('should return true', function() { + describe('that is custom', function () { + it('should return true', function () { expect(isDefaultValue({ ...setting, isCustom: true })).to.be(true); }); }); - describe('without a value', function() { - it('should return true', function() { + describe('without a value', function () { + it('should return true', function () { expect(isDefaultValue({ ...setting, value: undefined })).to.be(true); expect(isDefaultValue({ ...setting, value: '' })).to.be(true); }); }); - describe('with a value that is the same as the default value', function() { - it('should return true', function() { + describe('with a value that is the same as the default value', function () { + it('should return true', function () { expect(isDefaultValue({ ...setting, value: 'defaultValue' })).to.be(true); expect(isDefaultValue({ ...setting, value: [], defVal: [] })).to.be(true); expect( @@ -69,8 +69,8 @@ describe('Settings', function() { }); }); - describe('with a value that is different than the default value', function() { - it('should return false', function() { + describe('with a value that is different than the default value', function () { + it('should return false', function () { expect(isDefaultValue({ ...setting })).to.be(false); expect(isDefaultValue({ ...setting, value: [1], defVal: [2] })).to.be(false); expect( diff --git a/src/plugins/advanced_settings/public/management_app/lib/to_editable_config.test.ts b/src/plugins/advanced_settings/public/management_app/lib/to_editable_config.test.ts index 7ac9b281eb99a..0f7edb4bd6332 100644 --- a/src/plugins/advanced_settings/public/management_app/lib/to_editable_config.test.ts +++ b/src/plugins/advanced_settings/public/management_app/lib/to_editable_config.test.ts @@ -37,26 +37,26 @@ function invoke({ return toEditableConfig({ def, name, value, isCustom: def === defDefault, isOverridden: true }); } -describe('Settings', function() { - describe('Advanced', function() { - describe('toEditableConfig(def, name, value)', function() { - it('sets name', function() { +describe('Settings', function () { + describe('Advanced', function () { + describe('toEditableConfig(def, name, value)', function () { + it('sets name', function () { expect(invoke({ name: 'who' }).name).to.equal('who'); }); - it('sets value', function() { + it('sets value', function () { expect(invoke({ value: 'what' }).value).to.equal('what'); }); - it('sets type', function() { + it('sets type', function () { expect(invoke({ value: 'what' }).type).to.be('string'); expect(invoke({ value: 0 }).type).to.be('number'); expect(invoke({ value: [] }).type).to.be('array'); }); - describe('when given a setting definition object', function() { + describe('when given a setting definition object', function () { let def: PublicUiSettingsParams & { isOverridden?: boolean }; - beforeEach(function() { + beforeEach(function () { def = { value: 'the original', description: 'the one and only', @@ -64,38 +64,38 @@ describe('Settings', function() { }; }); - it('is not marked as custom', function() { + it('is not marked as custom', function () { expect(invoke({ def }).isCustom).to.be(false); }); - it('sets a default value', function() { + it('sets a default value', function () { expect(invoke({ def }).defVal).to.equal(def.value); }); - it('sets a description', function() { + it('sets a description', function () { expect(invoke({ def }).description).to.equal(def.description); }); - it('sets options', function() { + it('sets options', function () { expect(invoke({ def }).options).to.equal(def.options); }); - describe('that contains a type', function() { - it('sets that type', function() { + describe('that contains a type', function () { + it('sets that type', function () { def.type = 'string'; expect(invoke({ def }).type).to.equal(def.type); }); }); - describe('that contains a value of type array', function() { - it('sets type to array', function() { + describe('that contains a value of type array', function () { + it('sets type to array', function () { def.value = []; expect(invoke({ def }).type).to.equal('array'); }); }); - describe('that contains a validation object', function() { - it('constructs a validation regex with message', function() { + describe('that contains a validation object', function () { + it('constructs a validation regex with message', function () { def.validation = { regexString: '^foo', message: 'must start with "foo"', @@ -108,24 +108,24 @@ describe('Settings', function() { }); }); - describe('when not given a setting definition object', function() { - it('is marked as custom', function() { + describe('when not given a setting definition object', function () { + it('is marked as custom', function () { expect(invoke({}).isCustom).to.be(true); }); - it('sets defVal to undefined', function() { + it('sets defVal to undefined', function () { expect(invoke({}).defVal).to.be(undefined); }); - it('sets description to undefined', function() { + it('sets description to undefined', function () { expect(invoke({}).description).to.be(undefined); }); - it('sets options to undefined', function() { + it('sets options to undefined', function () { expect(invoke({}).options).to.be(undefined); }); - it('sets validation to undefined', function() { + it('sets validation to undefined', function () { expect(invoke({}).validation).to.be(undefined); }); }); diff --git a/src/plugins/apm_oss/server/tutorial/instructions/apm_agent_instructions.ts b/src/plugins/apm_oss/server/tutorial/instructions/apm_agent_instructions.ts index 271bcab21172f..d2a4ee8297a11 100644 --- a/src/plugins/apm_oss/server/tutorial/instructions/apm_agent_instructions.ts +++ b/src/plugins/apm_oss/server/tutorial/instructions/apm_agent_instructions.ts @@ -644,8 +644,9 @@ export const createDotNetAgentInstructions = (apmServerUrl = '', secretToken = ' commands: `{curlyOpen} "ElasticApm": {curlyOpen} "SecretToken": "${secretToken}", - "ServerUrls": "${apmServerUrl || - 'http://localhost:8200'}", //Set custom APM Server URL (default: http://localhost:8200) + "ServerUrls": "${ + apmServerUrl || 'http://localhost:8200' + }", //Set custom APM Server URL (default: http://localhost:8200) "ServiceName" : "MyApp", //allowed characters: a-z, A-Z, 0-9, -, _, and space. Default is the entry assembly of the application {curlyClose} {curlyClose}`.split('\n'), diff --git a/src/plugins/bfetch/common/buffer/tests/create_batched_function.test.ts b/src/plugins/bfetch/common/buffer/tests/create_batched_function.test.ts index 5b145a2523070..c924cf3a04f1c 100644 --- a/src/plugins/bfetch/common/buffer/tests/create_batched_function.test.ts +++ b/src/plugins/bfetch/common/buffer/tests/create_batched_function.test.ts @@ -66,7 +66,7 @@ describe('createBatchedFunction', () => { expect(onCall).toHaveBeenCalledWith(123); expect(onBatch).toHaveBeenCalledTimes(0); - await new Promise(r => setTimeout(r, 15)); + await new Promise((r) => setTimeout(r, 15)); expect(onCall).toHaveBeenCalledTimes(1); expect(onBatch).toHaveBeenCalledTimes(1); diff --git a/src/plugins/bfetch/public/batching/create_streaming_batched_function.test.ts b/src/plugins/bfetch/public/batching/create_streaming_batched_function.test.ts index 064b791327e69..26c1d9e5033e0 100644 --- a/src/plugins/bfetch/public/batching/create_streaming_batched_function.test.ts +++ b/src/plugins/bfetch/public/batching/create_streaming_batched_function.test.ts @@ -24,17 +24,17 @@ import { Subject } from 'rxjs'; const getPromiseState = (promise: Promise): Promise<'resolved' | 'rejected' | 'pending'> => Promise.race<'resolved' | 'rejected' | 'pending'>([ - new Promise(resolve => + new Promise((resolve) => promise.then( () => resolve('resolved'), () => resolve('rejected') ) ), - new Promise<'pending'>(resolve => resolve()).then(() => 'pending'), + new Promise<'pending'>((resolve) => resolve()).then(() => 'pending'), ]); const isPending = (promise: Promise): Promise => - getPromiseState(promise).then(state => state === 'pending'); + getPromiseState(promise).then((state) => state === 'pending'); const setup = () => { const xhr = ({} as unknown) as XMLHttpRequest; @@ -93,7 +93,7 @@ describe('createStreamingBatchedFunction()', () => { fn({ baz: 'quix' }); expect(fetchStreaming).toHaveBeenCalledTimes(0); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); expect(fetchStreaming).toHaveBeenCalledTimes(1); }); @@ -107,7 +107,7 @@ describe('createStreamingBatchedFunction()', () => { }); expect(fetchStreaming).toHaveBeenCalledTimes(0); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); expect(fetchStreaming).toHaveBeenCalledTimes(0); }); @@ -121,7 +121,7 @@ describe('createStreamingBatchedFunction()', () => { }); fn({ foo: 'bar' }); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); expect(fetchStreaming.mock.calls[0][0]).toMatchObject({ url: '/test', @@ -141,7 +141,7 @@ describe('createStreamingBatchedFunction()', () => { fn({ foo: 'bar' }); fn({ baz: 'quix' }); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); const { body } = fetchStreaming.mock.calls[0][0]; expect(JSON.parse(body)).toEqual({ batch: [{ foo: 'bar' }, { baz: 'quix' }], @@ -205,7 +205,7 @@ describe('createStreamingBatchedFunction()', () => { fn({ c: '3' }); expect(fetchStreaming).toHaveBeenCalledTimes(1); fn({ d: '4' }); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); expect(fetchStreaming).toHaveBeenCalledTimes(2); }); }); @@ -222,7 +222,7 @@ describe('createStreamingBatchedFunction()', () => { const promise1 = fn({ a: '1' }); const promise2 = fn({ b: '2' }); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); expect(await isPending(promise1)).toBe(true); expect(await isPending(promise2)).toBe(true); @@ -240,7 +240,7 @@ describe('createStreamingBatchedFunction()', () => { const promise1 = fn({ a: '1' }); const promise2 = fn({ b: '2' }); const promise3 = fn({ c: '3' }); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); expect(await isPending(promise1)).toBe(true); expect(await isPending(promise2)).toBe(true); @@ -281,7 +281,7 @@ describe('createStreamingBatchedFunction()', () => { const promise1 = fn({ a: '1' }); const promise2 = fn({ b: '2' }); const promise3 = fn({ c: '3' }); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); stream.next( JSON.stringify({ @@ -313,7 +313,7 @@ describe('createStreamingBatchedFunction()', () => { }); const promise = fn({ a: '1' }); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); expect(await isPending(promise)).toBe(true); @@ -344,7 +344,7 @@ describe('createStreamingBatchedFunction()', () => { const promise2 = of(fn({ a: '2' })); const promise3 = of(fn({ a: '3' })); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); stream.next( JSON.stringify({ @@ -353,7 +353,7 @@ describe('createStreamingBatchedFunction()', () => { }) + '\n' ); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); stream.next( JSON.stringify({ @@ -362,7 +362,7 @@ describe('createStreamingBatchedFunction()', () => { }) + '\n' ); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); stream.next( JSON.stringify({ @@ -371,7 +371,7 @@ describe('createStreamingBatchedFunction()', () => { }) + '\n' ); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); const [result1] = await promise1; const [, error2] = await promise2; @@ -395,11 +395,11 @@ describe('createStreamingBatchedFunction()', () => { const promise1 = of(fn({ a: '1' })); const promise2 = of(fn({ a: '2' })); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); stream.complete(); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); const [, error1] = await promise1; const [, error2] = await promise2; @@ -425,7 +425,7 @@ describe('createStreamingBatchedFunction()', () => { const promise1 = of(fn({ a: '1' })); const promise2 = of(fn({ a: '2' })); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); stream.next( JSON.stringify({ @@ -435,7 +435,7 @@ describe('createStreamingBatchedFunction()', () => { ); stream.complete(); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); const [, error1] = await promise1; const [result1] = await promise2; @@ -462,13 +462,13 @@ describe('createStreamingBatchedFunction()', () => { const promise1 = of(fn({ a: '1' })); const promise2 = of(fn({ a: '2' })); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); stream.error({ message: 'something went wrong', }); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); const [, error1] = await promise1; const [, error2] = await promise2; @@ -494,7 +494,7 @@ describe('createStreamingBatchedFunction()', () => { const promise1 = of(fn({ a: '1' })); const promise2 = of(fn({ a: '2' })); - await new Promise(r => setTimeout(r, 6)); + await new Promise((r) => setTimeout(r, 6)); stream.next( JSON.stringify({ @@ -504,7 +504,7 @@ describe('createStreamingBatchedFunction()', () => { ); stream.error('oops'); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); const [, error1] = await promise1; const [result1] = await promise2; diff --git a/src/plugins/bfetch/public/batching/create_streaming_batched_function.ts b/src/plugins/bfetch/public/batching/create_streaming_batched_function.ts index 07d5724a2520d..f80a97137d1ab 100644 --- a/src/plugins/bfetch/public/batching/create_streaming_batched_function.ts +++ b/src/plugins/bfetch/public/batching/create_streaming_batched_function.ts @@ -91,7 +91,7 @@ export const createStreamingBatchedFunction = ( }; return [future.promise, entry]; }, - onBatch: async items => { + onBatch: async (items) => { try { let responsesReceived = 0; const batch = items.map(({ payload }) => payload); @@ -111,7 +111,7 @@ export const createStreamingBatchedFunction = ( items[response.id].future.resolve(response.result); } }, - error: error => { + error: (error) => { const normalizedError = normalizeError(error); normalizedError.code = 'STREAM'; for (const { future } of items) future.reject(normalizedError); diff --git a/src/plugins/bfetch/public/plugin.ts b/src/plugins/bfetch/public/plugin.ts index 783c448c567e5..5f01957c0908e 100644 --- a/src/plugins/bfetch/public/plugin.ts +++ b/src/plugins/bfetch/public/plugin.ts @@ -78,7 +78,7 @@ export class BfetchPublicPlugin private fetchStreaming = ( version: string, basePath: string - ): BfetchPublicSetup['fetchStreaming'] => params => + ): BfetchPublicSetup['fetchStreaming'] => (params) => fetchStreamingStatic({ ...params, url: `${basePath}/${removeLeadingSlash(params.url)}`, @@ -91,7 +91,7 @@ export class BfetchPublicPlugin private batchedFunction = ( fetchStreaming: BfetchPublicContract['fetchStreaming'] - ): BfetchPublicContract['batchedFunction'] => params => + ): BfetchPublicContract['batchedFunction'] => (params) => createStreamingBatchedFunction({ ...params, fetchStreaming: params.fetchStreaming || fetchStreaming, diff --git a/src/plugins/bfetch/public/streaming/fetch_streaming.test.ts b/src/plugins/bfetch/public/streaming/fetch_streaming.test.ts index 7845616026ea1..27adc6dc8b549 100644 --- a/src/plugins/bfetch/public/streaming/fetch_streaming.test.ts +++ b/src/plugins/bfetch/public/streaming/fetch_streaming.test.ts @@ -20,7 +20,7 @@ import { fetchStreaming } from './fetch_streaming'; import { mockXMLHttpRequest } from '../test_helpers/xhr'; -const tick = () => new Promise(resolve => setTimeout(resolve, 1)); +const tick = () => new Promise((resolve) => setTimeout(resolve, 1)); const setup = () => { const { xhr, XMLHttpRequest } = mockXMLHttpRequest(); diff --git a/src/plugins/bfetch/public/streaming/split.test.ts b/src/plugins/bfetch/public/streaming/split.test.ts index 6eb3e27ad8598..fb9dcfb210d36 100644 --- a/src/plugins/bfetch/public/streaming/split.test.ts +++ b/src/plugins/bfetch/public/streaming/split.test.ts @@ -26,7 +26,7 @@ test('splits a single IP address', () => { const subject = new Subject(); const splitted = split('.')(subject); - splitted.subscribe(value => list.push(value)); + splitted.subscribe((value) => list.push(value)); subject.next(ip); subject.complete(); @@ -56,7 +56,7 @@ for (const stream of streams) { const list: string[] = []; const subject = new Subject(); const splitted = split('.')(subject); - splitted.subscribe(value => list.push(value)); + splitted.subscribe((value) => list.push(value)); let i = 0; while (i < stream.length) { const len = Math.round(Math.random() * 10); diff --git a/src/plugins/bfetch/public/streaming/split.ts b/src/plugins/bfetch/public/streaming/split.ts index 665411f472ac3..c970e07c97e9f 100644 --- a/src/plugins/bfetch/public/streaming/split.ts +++ b/src/plugins/bfetch/public/streaming/split.ts @@ -40,7 +40,7 @@ export const split = (delimiter: string = '\n') => ( let startingText = ''; in$.subscribe( - chunk => { + (chunk) => { const messages = (startingText + chunk).split(delimiter); // We don't want to send the last message here, since it may or diff --git a/src/plugins/bfetch/server/plugin.ts b/src/plugins/bfetch/server/plugin.ts index 0502781e34ce2..c27f34b8233cb 100644 --- a/src/plugins/bfetch/server/plugin.ts +++ b/src/plugins/bfetch/server/plugin.ts @@ -161,7 +161,7 @@ export class BfetchServerPlugin logger, }: { logger: Logger; - }): BfetchServerSetup['createStreamingRequestHandler'] => streamHandler => async ( + }): BfetchServerSetup['createStreamingRequestHandler'] => (streamHandler) => async ( context, request, response @@ -186,7 +186,7 @@ export class BfetchServerPlugin addStreamingResponseRoute< BatchRequestData, BatchResponseItem - >(path, request => { + >(path, (request) => { const handlerInstance = handler(request); return { getResponseStream: ({ batch }) => { diff --git a/src/plugins/bfetch/server/streaming/create_ndjson_stream.ts b/src/plugins/bfetch/server/streaming/create_ndjson_stream.ts index c567784becd16..2f476e95497e5 100644 --- a/src/plugins/bfetch/server/streaming/create_ndjson_stream.ts +++ b/src/plugins/bfetch/server/streaming/create_ndjson_stream.ts @@ -39,7 +39,7 @@ export const createNDJSONStream = ( logger.error(error); } }, - error: error => { + error: (error) => { stream.end(); logger.error(error); }, diff --git a/src/plugins/charts/public/services/colors/color_palette.ts b/src/plugins/charts/public/services/colors/color_palette.ts index 7b8e93bbde240..464e9e3a66101 100644 --- a/src/plugins/charts/public/services/colors/color_palette.ts +++ b/src/plugins/charts/public/services/colors/color_palette.ts @@ -24,7 +24,7 @@ import { seedColors } from './seed_colors'; const offset = 300; // Hue offset to start at -const fraction = function(goal: number) { +const fraction = function (goal: number) { const walkTree = (numerator: number, denominator: number, bytes: number[]): number => { if (bytes.length) { return walkTree(numerator * 2 + (bytes.pop() ? 1 : -1), denominator * 2, bytes); @@ -36,7 +36,7 @@ const fraction = function(goal: number) { const b = (goal + 2) .toString(2) .split('') - .map(function(num) { + .map(function (num) { return parseInt(num, 10); }); b.shift(); @@ -57,7 +57,7 @@ export function createColorPalette(num?: any): string[] { const colors = seedColors; const seedLength = seedColors.length; - _.times(num - seedLength, function(i) { + _.times(num - seedLength, function (i) { colors.push(d3.hsl((fraction(i + seedLength + 1) * 360 + offset) % 360, 0.5, 0.5).toString()); }); diff --git a/src/plugins/charts/public/services/colors/colors.test.ts b/src/plugins/charts/public/services/colors/colors.test.ts index e3f99f2407f75..a4d7a0781eabd 100644 --- a/src/plugins/charts/public/services/colors/colors.test.ts +++ b/src/plugins/charts/public/services/colors/colors.test.ts @@ -28,7 +28,7 @@ const config = new Map(); describe('Vislib Color Service', () => { const colors = new ColorsService(); const mockUiSettings = coreMock.createSetup().uiSettings; - mockUiSettings.get.mockImplementation(a => config.get(a)); + mockUiSettings.get.mockImplementation((a) => config.get(a)); mockUiSettings.set.mockImplementation((...a) => config.set(...a) as any); colors.init(mockUiSettings); diff --git a/src/plugins/charts/public/services/colors/colors.ts b/src/plugins/charts/public/services/colors/colors.ts index 3c12adf84d8b2..7a1ffc433ee87 100644 --- a/src/plugins/charts/public/services/colors/colors.ts +++ b/src/plugins/charts/public/services/colors/colors.ts @@ -57,7 +57,7 @@ export class ColorsService { ); } - arrayOfStringsOrNumbers.forEach(function(val) { + arrayOfStringsOrNumbers.forEach(function (val) { if (!_.isString(val) && !_.isNumber(val) && !_.isUndefined(val)) { throw new TypeError( 'createColorLookupFunction expects an array of strings, numbers, or undefined values' diff --git a/src/plugins/charts/public/services/colors/mapped_colors.test.ts b/src/plugins/charts/public/services/colors/mapped_colors.test.ts index c3b9b0909051c..2c9f37afc14c5 100644 --- a/src/plugins/charts/public/services/colors/mapped_colors.test.ts +++ b/src/plugins/charts/public/services/colors/mapped_colors.test.ts @@ -30,7 +30,7 @@ const config = new Map(); describe('Mapped Colors', () => { const mockUiSettings = coreMock.createSetup().uiSettings; - mockUiSettings.get.mockImplementation(a => config.get(a)); + mockUiSettings.get.mockImplementation((a) => config.get(a)); mockUiSettings.set.mockImplementation((...a) => config.set(...a) as any); const mappedColors = new MappedColors(mockUiSettings); @@ -50,12 +50,7 @@ describe('Mapped Colors', () => { const arr = [1, 2, 3, 4, 5]; mappedColors.mapKeys(arr); - expect( - _(mappedColors.mapping) - .values() - .uniq() - .size() - ).toBe(arr.length); + expect(_(mappedColors.mapping).values().uniq().size()).toBe(arr.length); }); it('should not include colors used by the config', () => { @@ -77,15 +72,8 @@ describe('Mapped Colors', () => { const arr = ['foo', 'bar', 'baz', 'qux']; mappedColors.mapKeys(arr); - const expectedSize = _(arr) - .difference(_.keys(newConfig)) - .size(); - expect( - _(mappedColors.mapping) - .values() - .uniq() - .size() - ).toBe(expectedSize); + const expectedSize = _(arr).difference(_.keys(newConfig)).size(); + expect(_(mappedColors.mapping).values().uniq().size()).toBe(expectedSize); expect(mappedColors.get(arr[0])).not.toBe(seedColors[0]); }); @@ -98,20 +86,13 @@ describe('Mapped Colors', () => { const arr = ['foo', 'bar', 'baz', 'qux']; mappedColors.mapKeys(arr); - const expectedSize = _(arr) - .difference(_.keys(newConfig)) - .size(); - expect( - _(mappedColors.mapping) - .values() - .uniq() - .size() - ).toBe(expectedSize); + const expectedSize = _(arr).difference(_.keys(newConfig)).size(); + expect(_(mappedColors.mapping).values().uniq().size()).toBe(expectedSize); expect(mappedColors.get(arr[0])).not.toBe(seedColors[0]); expect(mappedColors.get('bar')).toBe(seedColors[0]); }); - it('should have a flush method that moves the current map to the old map', function() { + it('should have a flush method that moves the current map to the old map', function () { const arr = [1, 2, 3, 4, 5]; mappedColors.mapKeys(arr); expect(_.keys(mappedColors.mapping).length).toBe(5); @@ -128,7 +109,7 @@ describe('Mapped Colors', () => { expect(_.keys(mappedColors.mapping).length).toBe(0); }); - it('should use colors in the oldMap if they are available', function() { + it('should use colors in the oldMap if they are available', function () { const arr = [1, 2, 3, 4, 5]; mappedColors.mapKeys(arr); expect(_.keys(mappedColors.mapping).length).toBe(5); @@ -147,7 +128,7 @@ describe('Mapped Colors', () => { expect(mappedColors.mapping[5]).toEqual(mappedColors.oldMap[5]); }); - it('should have a purge method that clears both maps', function() { + it('should have a purge method that clears both maps', function () { const arr = [1, 2, 3, 4, 5]; mappedColors.mapKeys(arr); mappedColors.flush(); diff --git a/src/plugins/charts/public/services/colors/mapped_colors.ts b/src/plugins/charts/public/services/colors/mapped_colors.ts index 1469d357e7e79..fe0deac734e6b 100644 --- a/src/plugins/charts/public/services/colors/mapped_colors.ts +++ b/src/plugins/charts/public/services/colors/mapped_colors.ts @@ -73,7 +73,7 @@ export class MappedColors { const oldColors = _.values(this._oldMap); const keysToMap: Array = []; - _.each(keys, key => { + _.each(keys, (key) => { // If this key is mapped in the config, it's unnecessary to have it mapped here if (configMapping[key]) delete this._mapping[key]; @@ -88,11 +88,7 @@ export class MappedColors { }); // Generate a color palette big enough that all new keys can have unique color values - const allColors = _(this._mapping) - .values() - .union(configColors) - .union(oldColors) - .value(); + const allColors = _(this._mapping).values().union(configColors).union(oldColors).value(); const colorPalette = createColorPalette(allColors.length + keysToMap.length); let newColors = _.difference(colorPalette, allColors); diff --git a/src/plugins/charts/public/services/colors/seed_colors.test.ts b/src/plugins/charts/public/services/colors/seed_colors.test.ts index c4aac726e49e7..51a96409a4ec1 100644 --- a/src/plugins/charts/public/services/colors/seed_colors.test.ts +++ b/src/plugins/charts/public/services/colors/seed_colors.test.ts @@ -19,8 +19,8 @@ import { seedColors } from './seed_colors'; -describe('Seed Colors', function() { - it('should return an array', function() { +describe('Seed Colors', function () { + it('should return an array', function () { expect(seedColors).toBeInstanceOf(Array); }); }); diff --git a/src/plugins/charts/public/services/theme/theme.ts b/src/plugins/charts/public/services/theme/theme.ts index 65d4dc3393658..166e1c539688a 100644 --- a/src/plugins/charts/public/services/theme/theme.ts +++ b/src/plugins/charts/public/services/theme/theme.ts @@ -57,7 +57,7 @@ export class ThemeService { this._chartsTheme$ = uiSettings .get$('theme:darkMode') .pipe( - map(darkMode => (darkMode ? EUI_CHARTS_THEME_DARK.theme : EUI_CHARTS_THEME_LIGHT.theme)) + map((darkMode) => (darkMode ? EUI_CHARTS_THEME_DARK.theme : EUI_CHARTS_THEME_LIGHT.theme)) ); } } diff --git a/src/plugins/charts/public/static/color_maps/heatmap_color.ts b/src/plugins/charts/public/static/color_maps/heatmap_color.ts index afc649b68826e..9c3067fd8d6ac 100644 --- a/src/plugins/charts/public/static/color_maps/heatmap_color.ts +++ b/src/plugins/charts/public/static/color_maps/heatmap_color.ts @@ -37,7 +37,7 @@ function interpolateLinearly(x: number, values: RawColorSchema['value']) { const rValues: number[] = []; const gValues: number[] = []; const bValues: number[] = []; - values.forEach(value => { + values.forEach((value) => { xValues.push(value[0]); rValues.push(value[1][0]); gValues.push(value[1][1]); diff --git a/src/plugins/charts/public/static/components/number_input.tsx b/src/plugins/charts/public/static/components/number_input.tsx index b614e00ba8cd0..8c2874f522902 100644 --- a/src/plugins/charts/public/static/components/number_input.tsx +++ b/src/plugins/charts/public/static/components/number_input.tsx @@ -65,7 +65,7 @@ function NumberInputOption({ max={max} min={min} value={value} - onChange={ev => + onChange={(ev) => setValue(paramName, isNaN(ev.target.valueAsNumber) ? '' : ev.target.valueAsNumber) } /> diff --git a/src/plugins/charts/public/static/components/select.tsx b/src/plugins/charts/public/static/components/select.tsx index 8ce7f4d640898..31cc1cd14e2f6 100644 --- a/src/plugins/charts/public/static/components/select.tsx +++ b/src/plugins/charts/public/static/components/select.tsx @@ -63,7 +63,7 @@ function SelectOption setValue(paramName, ev.target.value as ValidParamValues)} + onChange={(ev) => setValue(paramName, ev.target.value as ValidParamValues)} fullWidth={true} data-test-subj={dataTestSubj} /> diff --git a/src/plugins/charts/public/static/components/switch.tsx b/src/plugins/charts/public/static/components/switch.tsx index bdaf602cad5c6..a873e6d15feeb 100644 --- a/src/plugins/charts/public/static/components/switch.tsx +++ b/src/plugins/charts/public/static/components/switch.tsx @@ -49,7 +49,7 @@ function SwitchOption({ checked={value} disabled={disabled} data-test-subj={dataTestSubj} - onChange={ev => setValue(paramName, ev.target.checked)} + onChange={(ev) => setValue(paramName, ev.target.checked)} /> diff --git a/src/plugins/charts/public/static/components/text_input.tsx b/src/plugins/charts/public/static/components/text_input.tsx index 0ab004102bdb8..03486c7056d62 100644 --- a/src/plugins/charts/public/static/components/text_input.tsx +++ b/src/plugins/charts/public/static/components/text_input.tsx @@ -47,7 +47,7 @@ function TextInputOption({ data-test-subj={dataTestSubj} disabled={disabled} value={value} - onChange={ev => setValue(paramName, ev.target.value)} + onChange={(ev) => setValue(paramName, ev.target.value)} /> ); diff --git a/src/plugins/console/public/application/components/console_menu.tsx b/src/plugins/console/public/application/components/console_menu.tsx index 7842c15be267f..df0c8145fd5ce 100644 --- a/src/plugins/console/public/application/components/console_menu.tsx +++ b/src/plugins/console/public/application/components/console_menu.tsx @@ -48,7 +48,7 @@ export class ConsoleMenu extends Component { mouseEnter = () => { if (this.state.isPopoverOpen) return; - this.props.getCurl().then(text => { + this.props.getCurl().then((text) => { this.setState({ curlCode: text }); }); }; @@ -75,7 +75,7 @@ export class ConsoleMenu extends Component { } onButtonClick = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; diff --git a/src/plugins/console/public/application/components/settings_modal.tsx b/src/plugins/console/public/application/components/settings_modal.tsx index 3cd20bf1bc343..377e739a0c59a 100644 --- a/src/plugins/console/public/application/components/settings_modal.tsx +++ b/src/plugins/console/public/application/components/settings_modal.tsx @@ -87,7 +87,7 @@ export function DevToolsSettingsModal(props: Props) { }; const onAutocompleteChange = (optionId: AutocompleteOptions) => { - const option = _.find(autoCompleteCheckboxes, item => item.id === optionId); + const option = _.find(autoCompleteCheckboxes, (item) => item.id === optionId); if (option) { option.stateSetter(!checkboxIdToSelectedMap[optionId]); } @@ -136,7 +136,7 @@ export function DevToolsSettingsModal(props: Props) { id="console.settingsPage.pollingLabelText" /> } - onChange={e => setPolling(e.target.checked)} + onChange={(e) => setPolling(e.target.checked)} /> @@ -158,9 +158,7 @@ export function DevToolsSettingsModal(props: Props) { /> - ) : ( - undefined - ); + ) : undefined; return ( @@ -193,7 +191,7 @@ export function DevToolsSettingsModal(props: Props) { value={fontSize} min={6} max={50} - onChange={e => { + onChange={(e) => { const val = parseInt(e.target.value, 10); if (!val) return; setFontSize(val); @@ -212,7 +210,7 @@ export function DevToolsSettingsModal(props: Props) { id="console.settingsPage.wrapLongLinesLabelText" /> } - onChange={e => setWrapMode(e.target.checked)} + onChange={(e) => setWrapMode(e.target.checked)} /> @@ -234,7 +232,7 @@ export function DevToolsSettingsModal(props: Props) { id="console.settingsPage.tripleQuotesMessage" /> } - onChange={e => setTripleQuotes(e.target.checked)} + onChange={(e) => setTripleQuotes(e.target.checked)} /> @@ -248,7 +246,7 @@ export function DevToolsSettingsModal(props: Props) { } > { + options={autoCompleteCheckboxes.map((opts) => { const { stateSetter, ...rest } = opts; return rest; })} diff --git a/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.tsx b/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.tsx index 47f7aa1635205..6d4f532887cd9 100644 --- a/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.tsx +++ b/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor.tsx @@ -119,7 +119,7 @@ function EditorUI({ initialTextValue }: EditorProps) { } // Fire and forget. - $.ajax(loadFrom).done(async data => { + $.ajax(loadFrom).done(async (data) => { const coreEditor = editor.getCoreEditor(); await editor.update(data, true); editor.moveToNextRequestEdge(false); @@ -188,10 +188,7 @@ function EditorUI({ initialTextValue }: EditorProps) { const { current: editor } = editorInstanceRef; applyCurrentSettings(editor!.getCoreEditor(), settings); // Preserve legacy focus behavior after settings have updated. - editor! - .getCoreEditor() - .getContainer() - .focus(); + editor!.getCoreEditor().getContainer().focus(); }, [settings]); useEffect(() => { diff --git a/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor_output.tsx b/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor_output.tsx index 8510aaebfaa1e..dd5ef5209a244 100644 --- a/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor_output.tsx +++ b/src/plugins/console/public/application/containers/editor/legacy/console_editor/editor_output.tsx @@ -72,8 +72,8 @@ function EditorOutputUI() { editor.session.setMode(mode); editor.update( data - .map(d => d.response.value as string) - .map(readOnlySettings.tripleQuotes ? expandLiteralStrings : a => a) + .map((d) => d.response.value as string) + .map(readOnlySettings.tripleQuotes ? expandLiteralStrings : (a) => a) .join('\n') ); } else if (error) { diff --git a/src/plugins/console/public/application/containers/editor/legacy/console_menu_actions.ts b/src/plugins/console/public/application/containers/editor/legacy/console_menu_actions.ts index 2bbe49cd53eac..a10458aaf28bd 100644 --- a/src/plugins/console/public/application/containers/editor/legacy/console_menu_actions.ts +++ b/src/plugins/console/public/application/containers/editor/legacy/console_menu_actions.ts @@ -23,17 +23,14 @@ import { SenseEditor } from '../../../models/sense_editor'; export async function autoIndent(editor: SenseEditor, event: Event) { event.preventDefault(); await editor.autoIndent(); - editor - .getCoreEditor() - .getContainer() - .focus(); + editor.getCoreEditor().getContainer().focus(); } export function getDocumentation( editor: SenseEditor, docLinkVersion: string ): Promise { - return editor.getRequestsInRange().then(requests => { + return editor.getRequestsInRange().then((requests) => { if (!requests || requests.length === 0) { return null; } diff --git a/src/plugins/console/public/application/containers/editor/legacy/subscribe_console_resize_checker.ts b/src/plugins/console/public/application/containers/editor/legacy/subscribe_console_resize_checker.ts index 2d992aadbf15a..01233a7c42d52 100644 --- a/src/plugins/console/public/application/containers/editor/legacy/subscribe_console_resize_checker.ts +++ b/src/plugins/console/public/application/containers/editor/legacy/subscribe_console_resize_checker.ts @@ -22,7 +22,7 @@ import { ResizeChecker } from '../../../../../../kibana_utils/public'; export function subscribeResizeChecker(el: HTMLElement, ...editors: any[]) { const checker = new ResizeChecker(el); checker.on('resize', () => - editors.forEach(e => { + editors.forEach((e) => { if (e.getCoreEditor) { e.getCoreEditor().resize(); } else { diff --git a/src/plugins/console/public/application/containers/settings.tsx b/src/plugins/console/public/application/containers/settings.tsx index 81938a83435de..acd9b88d8b5b9 100644 --- a/src/plugins/console/public/application/containers/settings.tsx +++ b/src/plugins/console/public/application/containers/settings.tsx @@ -26,7 +26,7 @@ import { useServicesContext, useEditorActionContext } from '../contexts'; import { DevToolsSettings, Settings as SettingsService } from '../../services'; const getAutocompleteDiff = (newSettings: DevToolsSettings, prevSettings: DevToolsSettings) => { - return Object.keys(newSettings.autocomplete).filter(key => { + return Object.keys(newSettings.autocomplete).filter((key) => { // @ts-ignore return prevSettings.autocomplete[key] !== newSettings.autocomplete[key]; }); diff --git a/src/plugins/console/public/application/contexts/editor_context/editor_context.tsx b/src/plugins/console/public/application/contexts/editor_context/editor_context.tsx index d5ed44e3f6ba2..884ad7d7e3585 100644 --- a/src/plugins/console/public/application/contexts/editor_context/editor_context.tsx +++ b/src/plugins/console/public/application/contexts/editor_context/editor_context.tsx @@ -31,7 +31,7 @@ export interface EditorContextArgs { } export function EditorContextProvider({ children, settings }: EditorContextArgs) { - const [state, dispatch] = useReducer(editor.reducer, editor.initialValue, value => ({ + const [state, dispatch] = useReducer(editor.reducer, editor.initialValue, (value) => ({ ...value, settings, })); diff --git a/src/plugins/console/public/application/models/legacy_core_editor/__tests__/input.test.js b/src/plugins/console/public/application/models/legacy_core_editor/__tests__/input.test.js index a68a2b3939864..81171c2bd26fe 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/__tests__/input.test.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/__tests__/input.test.js @@ -81,7 +81,7 @@ describe('Input', () => { data = prefix; } - test('Token test ' + testCount++ + ' prefix: ' + prefix, async function() { + test('Token test ' + testCount++ + ' prefix: ' + prefix, async function () { await coreEditor.setValue(data, true); const tokens = tokensAsList(); const normTokenList = []; @@ -473,7 +473,7 @@ describe('Input', () => { data = prefix; } - test('States test ' + testCount++ + ' prefix: ' + prefix, async function() { + test('States test ' + testCount++ + ' prefix: ' + prefix, async function () { await coreEditor.setValue(data, true); const modes = statesAsList(); expect(modes).toEqual(statesList); diff --git a/src/plugins/console/public/application/models/legacy_core_editor/__tests__/output_tokenization.test.js b/src/plugins/console/public/application/models/legacy_core_editor/__tests__/output_tokenization.test.js index 1db9ca7bc0a86..ea7530bd21387 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/__tests__/output_tokenization.test.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/__tests__/output_tokenization.test.js @@ -57,8 +57,8 @@ describe('Output Tokenization', () => { data = JSON.stringify(data, null, 3); } - test('Token test ' + testCount++, async function(done) { - output.update(data, function() { + test('Token test ' + testCount++, async function (done) { + output.update(data, function () { const tokens = tokensAsList(); const normTokenList = []; for (let i = 0; i < tokenList.length; i++) { diff --git a/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.test.mocks.ts b/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.test.mocks.ts index 66673ff42e4e8..f90b803a77004 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.test.mocks.ts +++ b/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.test.mocks.ts @@ -22,7 +22,7 @@ jest.mock('./mode/worker', () => { }); // @ts-ignore -window.Worker = function() { +window.Worker = function () { this.postMessage = () => {}; (this as any).terminate = () => {}; }; diff --git a/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.ts b/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.ts index fc419b0f10dca..396356f98500d 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.ts +++ b/src/plugins/console/public/application/models/legacy_core_editor/legacy_core_editor.ts @@ -74,7 +74,7 @@ export class LegacyCoreEditor implements CoreEditor { // dirty check for tokenizer state, uses a lot less cycles // than listening for tokenizerUpdate waitForLatestTokens(): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { const session = this.editor.getSession(); const checkInterval = 25; @@ -239,9 +239,9 @@ export class LegacyCoreEditor implements CoreEditor { private forceRetokenize() { const session = this.editor.getSession(); - return new Promise(resolve => { + return new Promise((resolve) => { // force update of tokens, but not on this thread to allow for ace rendering. - setTimeout(function() { + setTimeout(function () { let i; for (i = 0; i < session.getLength(); i++) { session.getTokens(i); @@ -368,11 +368,11 @@ export class LegacyCoreEditor implements CoreEditor { // disable standard context based autocompletion. // @ts-ignore - ace.define('ace/autocomplete/text_completer', ['require', 'exports', 'module'], function( + ace.define('ace/autocomplete/text_completer', ['require', 'exports', 'module'], function ( require: any, exports: any ) { - exports.getCompletions = function( + exports.getCompletions = function ( innerEditor: any, session: any, pos: any, diff --git a/src/plugins/console/public/application/models/legacy_core_editor/mode/input.js b/src/plugins/console/public/application/models/legacy_core_editor/mode/input.js index 77b4ba8cea6ff..4031167f72c91 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/mode/input.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/mode/input.js @@ -43,13 +43,13 @@ export function Mode() { } oop.inherits(Mode, TextMode); -(function() { - this.getCompletions = function() { +(function () { + this.getCompletions = function () { // autocomplete is done by the autocomplete module. return []; }; - this.getNextLineIndent = function(state, line, tab) { + this.getNextLineIndent = function (state, line, tab) { let indent = this.$getIndent(line); if (state !== 'string_literal') { @@ -62,21 +62,21 @@ oop.inherits(Mode, TextMode); return indent; }; - this.checkOutdent = function(state, line, input) { + this.checkOutdent = function (state, line, input) { return this.$outdent.checkOutdent(line, input); }; - this.autoOutdent = function(state, doc, row) { + this.autoOutdent = function (state, doc, row) { this.$outdent.autoOutdent(doc, row); }; - this.createWorker = function(session) { + this.createWorker = function (session) { const worker = new WorkerClient(['ace', 'sense_editor'], workerModule, 'SenseWorker'); worker.attachToDocument(session.getDocument()); - worker.on('error', function(e) { + worker.on('error', function (e) { session.setAnnotations([e.data]); }); - worker.on('ok', function(anno) { + worker.on('ok', function (anno) { session.setAnnotations(anno.data); }); diff --git a/src/plugins/console/public/application/models/legacy_core_editor/mode/output.js b/src/plugins/console/public/application/models/legacy_core_editor/mode/output.js index 5ad34532d1861..da9ce41611671 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/mode/output.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/mode/output.js @@ -37,8 +37,8 @@ export function Mode() { } oop.inherits(Mode, JSONMode); -(function() { - this.createWorker = function() { +(function () { + this.createWorker = function () { return null; }; diff --git a/src/plugins/console/public/application/models/legacy_core_editor/mode/script.js b/src/plugins/console/public/application/models/legacy_core_editor/mode/script.js index 89adea8921c07..6079c9db40eef 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/mode/script.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/mode/script.js @@ -35,10 +35,10 @@ export function ScriptMode() { oop.inherits(ScriptMode, TextMode); -(function() { +(function () { this.HighlightRules = ScriptHighlightRules; - this.getNextLineIndent = function(state, line, tab) { + this.getNextLineIndent = function (state, line, tab) { let indent = this.$getIndent(line); const match = line.match(/^.*[\{\[]\s*$/); if (match) { @@ -48,11 +48,11 @@ oop.inherits(ScriptMode, TextMode); return indent; }; - this.checkOutdent = function(state, line, input) { + this.checkOutdent = function (state, line, input) { return this.$outdent.checkOutdent(line, input); }; - this.autoOutdent = function(state, doc, row) { + this.autoOutdent = function (state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }.call(ScriptMode.prototype)); diff --git a/src/plugins/console/public/application/models/legacy_core_editor/smart_resize.ts b/src/plugins/console/public/application/models/legacy_core_editor/smart_resize.ts index 7c4d871c4d73e..e6d7d8272b35b 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/smart_resize.ts +++ b/src/plugins/console/public/application/models/legacy_core_editor/smart_resize.ts @@ -20,7 +20,7 @@ import { get, throttle } from 'lodash'; // eslint-disable-next-line import/no-default-export -export default function(editor: any) { +export default function (editor: any) { const resize = editor.resize; const throttledResize = throttle(() => { diff --git a/src/plugins/console/public/application/models/legacy_core_editor/theme_sense_dark.js b/src/plugins/console/public/application/models/legacy_core_editor/theme_sense_dark.js index 8a0eb9a03480b..86d17933c746f 100644 --- a/src/plugins/console/public/application/models/legacy_core_editor/theme_sense_dark.js +++ b/src/plugins/console/public/application/models/legacy_core_editor/theme_sense_dark.js @@ -20,7 +20,7 @@ /* eslint import/no-unresolved: 0 */ import ace from 'brace'; -ace.define('ace/theme/sense-dark', ['require', 'exports', 'module'], function(require, exports) { +ace.define('ace/theme/sense-dark', ['require', 'exports', 'module'], function (require, exports) { exports.isDark = true; exports.cssClass = 'ace-sense-dark'; exports.cssText = diff --git a/src/plugins/console/public/application/models/sense_editor/__tests__/integration.test.js b/src/plugins/console/public/application/models/sense_editor/__tests__/integration.test.js index edd09885c1ad2..b7cc8f2f4b72f 100644 --- a/src/plugins/console/public/application/models/sense_editor/__tests__/integration.test.js +++ b/src/plugins/console/public/application/models/sense_editor/__tests__/integration.test.js @@ -41,7 +41,7 @@ describe('Integration', () => { }); function processContextTest(data, mapping, kbSchemes, requestLine, testToRun) { - test(testToRun.name, async function(done) { + test(testToRun.name, async function (done) { let lineOffset = 0; // add one for the extra method line let editorValue = data; if (requestLine != null) { @@ -67,7 +67,7 @@ describe('Integration', () => { // }); // } if (kbSchemes.endpoints) { - $.each(kbSchemes.endpoints, function(endpoint, scheme) { + $.each(kbSchemes.endpoints, function (endpoint, scheme) { testApi.addEndpointDescription(endpoint, scheme); }); } @@ -81,10 +81,10 @@ describe('Integration', () => { //setTimeout(function () { senseEditor.completer = { base: {}, - changeListener: function() {}, + changeListener: function () {}, }; // mimic auto complete - senseEditor.autocomplete._test.getCompletions(senseEditor, null, cursor, '', function( + senseEditor.autocomplete._test.getCompletions(senseEditor, null, cursor, '', function ( err, terms ) { @@ -110,7 +110,7 @@ describe('Integration', () => { } if (testToRun.autoCompleteSet) { - const expectedTerms = _.map(testToRun.autoCompleteSet, function(t) { + const expectedTerms = _.map(testToRun.autoCompleteSet, function (t) { if (typeof t !== 'object') { t = { name: t }; } @@ -119,10 +119,10 @@ describe('Integration', () => { if (terms.length !== expectedTerms.length) { expect(_.pluck(terms, 'name')).toEqual(_.pluck(expectedTerms, 'name')); } else { - const filteredActualTerms = _.map(terms, function(actualTerm, i) { + const filteredActualTerms = _.map(terms, function (actualTerm, i) { const expectedTerm = expectedTerms[i]; const filteredTerm = {}; - _.each(expectedTerm, function(v, p) { + _.each(expectedTerm, function (v, p) { filteredTerm[p] = actualTerm[p]; }); return filteredTerm; @@ -739,7 +739,7 @@ describe('Integration', () => { }, ], g: { - __scope_link: function() { + __scope_link: function () { return { a: 1, b: 2, diff --git a/src/plugins/console/public/application/models/sense_editor/__tests__/sense_editor.test.js b/src/plugins/console/public/application/models/sense_editor/__tests__/sense_editor.test.js index 219e6262ab346..c3fb879f2eeeb 100644 --- a/src/plugins/console/public/application/models/sense_editor/__tests__/sense_editor.test.js +++ b/src/plugins/console/public/application/models/sense_editor/__tests__/sense_editor.test.js @@ -28,7 +28,7 @@ import editorInput1 from './editor_input1.txt'; describe('Editor', () => { let input; - beforeEach(function() { + beforeEach(function () { // Set up our document body document.body.innerHTML = `
@@ -40,14 +40,14 @@ describe('Editor', () => { $(input.getCoreEditor().getContainer()).show(); input.autocomplete._test.removeChangeListener(); }); - afterEach(function() { + afterEach(function () { $(input.getCoreEditor().getContainer()).hide(); input.autocomplete._test.addChangeListener(); }); let testCount = 0; - const callWithEditorMethod = (editorMethod, fn) => async done => { + const callWithEditorMethod = (editorMethod, fn) => async (done) => { const results = await input[editorMethod](); fn(results, done); }; @@ -69,7 +69,7 @@ describe('Editor', () => { data = prefix; } - test('Utils test ' + id + ' : ' + name, async function(done) { + test('Utils test ' + id + ' : ' + name, async function (done) { await input.update(data, true); testToRun(done); }); @@ -81,7 +81,7 @@ describe('Editor', () => { expected = [expected]; } - _.each(requests, function(r) { + _.each(requests, function (r) { delete r.range; }); expect(requests).toEqual(expected); @@ -340,10 +340,10 @@ describe('Editor', () => { ); function multiReqTest(name, editorInput, range, expected) { - utilsTest('multi request select - ' + name, editorInput, async function(done) { + utilsTest('multi request select - ' + name, editorInput, async function (done) { const requests = await input.getRequestsInRange(range, false); // convert to format returned by request. - _.each(expected, function(req) { + _.each(expected, function (req) { req.data = req.data == null ? [] : [JSON.stringify(req.data, null, 2)]; }); @@ -451,7 +451,7 @@ describe('Editor', () => { ); function multiReqCopyAsCurlTest(name, editorInput, range, expected) { - utilsTest('multi request copy as curl - ' + name, editorInput, async function(done) { + utilsTest('multi request copy as curl - ' + name, editorInput, async function (done) { const curl = await input.getRequestsAsCURL('http://localhost:9200', range); expect(curl).toEqual(expected); done(); diff --git a/src/plugins/console/public/application/models/sense_editor/sense_editor.ts b/src/plugins/console/public/application/models/sense_editor/sense_editor.ts index d326543bbe00b..dbf4f1adcba0a 100644 --- a/src/plugins/console/public/application/models/sense_editor/sense_editor.ts +++ b/src/plugins/console/public/application/models/sense_editor/sense_editor.ts @@ -425,8 +425,8 @@ export class SenseEditor { } const column = - (this.coreEditor.getLineValue(curLineNumber) || '').length + - 1 /* Range goes to 1 after last char */; + (this.coreEditor.getLineValue(curLineNumber) || '').length + + 1; /* Range goes to 1 after last char */ return { lineNumber: curLineNumber, @@ -467,7 +467,7 @@ export class SenseEditor { getRequestsAsCURL = async (elasticsearchBaseUrl: string, range?: Range): Promise => { const requests = await this.getRequestsInRange(range, true); - const result = _.map(requests, req => { + const result = _.map(requests, (req) => { if (typeof req === 'string') { // no request block return req; diff --git a/src/plugins/console/public/application/stores/editor.ts b/src/plugins/console/public/application/stores/editor.ts index 73c29e7ff8575..c8a5b2421d52d 100644 --- a/src/plugins/console/public/application/stores/editor.ts +++ b/src/plugins/console/public/application/stores/editor.ts @@ -44,7 +44,7 @@ export type Action = | { type: 'updateSettings'; payload: DevToolsSettings }; export const reducer: Reducer = (state, action) => - produce(state, draft => { + produce(state, (draft) => { if (action.type === 'setInputEditor') { if (action.payload) { draft.ready = true; diff --git a/src/plugins/console/public/application/stores/request.ts b/src/plugins/console/public/application/stores/request.ts index f711330df3911..4ec9eae7e10d4 100644 --- a/src/plugins/console/public/application/stores/request.ts +++ b/src/plugins/console/public/application/stores/request.ts @@ -50,7 +50,7 @@ export const initialValue: Store = produce( ); export const reducer: Reducer = (state, action) => - produce(state, draft => { + produce(state, (draft) => { if (action.type === 'sendRequest') { draft.requestInFlight = true; draft.lastResult = initialResultValue; diff --git a/src/plugins/console/public/lib/ace_token_provider/token_provider.test.ts b/src/plugins/console/public/lib/ace_token_provider/token_provider.test.ts index d5465ebe96514..75b1bb802327e 100644 --- a/src/plugins/console/public/lib/ace_token_provider/token_provider.test.ts +++ b/src/plugins/console/public/lib/ace_token_provider/token_provider.test.ts @@ -74,7 +74,7 @@ describe('Ace (legacy) token provider', () => { }; describe('base cases', () => { - test('case 1 - only url', done => { + test('case 1 - only url', (done) => { runTest({ input: `GET http://somehost/_search`, expectedTokens: [ @@ -92,7 +92,7 @@ describe('Ace (legacy) token provider', () => { }); }); - test('case 2 - basic auth in host name', done => { + test('case 2 - basic auth in host name', (done) => { runTest({ input: `GET http://test:user@somehost/`, expectedTokens: [ @@ -109,7 +109,7 @@ describe('Ace (legacy) token provider', () => { }); }); - test('case 3 - handles empty lines', done => { + test('case 3 - handles empty lines', (done) => { runTest({ input: `POST abc @@ -128,7 +128,7 @@ describe('Ace (legacy) token provider', () => { }); describe('with newlines', () => { - test('case 1 - newlines base case', done => { + test('case 1 - newlines base case', (done) => { runTest({ input: `GET http://test:user@somehost/ { @@ -148,7 +148,7 @@ describe('Ace (legacy) token provider', () => { }); describe('edge cases', () => { - test('case 1 - getting token outside of document', done => { + test('case 1 - getting token outside of document', (done) => { runTest({ input: `GET http://test:user@somehost/ { @@ -160,7 +160,7 @@ describe('Ace (legacy) token provider', () => { }); }); - test('case 2 - empty lines', done => { + test('case 2 - empty lines', (done) => { runTest({ input: `GET http://test:user@somehost/ @@ -193,7 +193,7 @@ describe('Ace (legacy) token provider', () => { }; describe('base cases', () => { - it('case 1 - gets a token from the url', done => { + it('case 1 - gets a token from the url', (done) => { const input = `GET http://test:user@somehost/`; runTest({ input, @@ -219,7 +219,7 @@ describe('Ace (legacy) token provider', () => { }); describe('special cases', () => { - it('case 1 - handles input outside of range', done => { + it('case 1 - handles input outside of range', (done) => { runTest({ input: `GET abc`, expectedToken: null, diff --git a/src/plugins/console/public/lib/ace_token_provider/token_provider.ts b/src/plugins/console/public/lib/ace_token_provider/token_provider.ts index 134ab6c0e82d5..93bf7ce4c76d5 100644 --- a/src/plugins/console/public/lib/ace_token_provider/token_provider.ts +++ b/src/plugins/console/public/lib/ace_token_provider/token_provider.ts @@ -36,7 +36,7 @@ const toToken = (lineNumber: number, column: number, token: TokenInfo): Token => const toTokens = (lineNumber: number, tokens: TokenInfo[]): Token[] => { let acc = ''; - return tokens.map(token => { + return tokens.map((token) => { const column = acc.length + 1; acc += token.value; return toToken(lineNumber, column, token); diff --git a/src/plugins/console/public/lib/autocomplete/__jest__/url_autocomplete.test.js b/src/plugins/console/public/lib/autocomplete/__jest__/url_autocomplete.test.js index ebde8c39cffbc..0c3fcbafbe9f9 100644 --- a/src/plugins/console/public/lib/autocomplete/__jest__/url_autocomplete.test.js +++ b/src/plugins/console/public/lib/autocomplete/__jest__/url_autocomplete.test.js @@ -28,11 +28,11 @@ import { populateContext } from '../../autocomplete/engine'; describe('Url autocomplete', () => { function patternsTest(name, endpoints, tokenPath, expectedContext, globalUrlComponentFactories) { - test(name, function() { + test(name, function () { const patternMatcher = new UrlPatternMatcher(globalUrlComponentFactories); - _.each(endpoints, function(e, id) { + _.each(endpoints, function (e, id) { e.id = id; - _.each(e.patterns, function(p) { + _.each(e.patterns, function (p) { patternMatcher.addEndpoint(p, e); }); }); @@ -40,7 +40,7 @@ describe('Url autocomplete', () => { if (tokenPath[tokenPath.length - 1] === '$') { tokenPath = tokenPath.substr(0, tokenPath.length - 1) + '/' + URL_PATH_END_MARKER; } - tokenPath = _.map(tokenPath.split('/'), function(p) { + tokenPath = _.map(tokenPath.split('/'), function (p) { p = p.split(','); if (p.length === 1) { return p[0]; @@ -50,7 +50,7 @@ describe('Url autocomplete', () => { } if (expectedContext.autoCompleteSet) { - expectedContext.autoCompleteSet = _.map(expectedContext.autoCompleteSet, function(t) { + expectedContext.autoCompleteSet = _.map(expectedContext.autoCompleteSet, function (t) { if (_.isString(t)) { t = { name: t }; } @@ -91,7 +91,7 @@ describe('Url autocomplete', () => { return name; } - (function() { + (function () { const endpoints = { '1': { patterns: ['a/b'], @@ -123,7 +123,7 @@ describe('Url autocomplete', () => { patternsTest('simple single path - different path', endpoints, 'a/c', {}); })(); - (function() { + (function () { const endpoints = { '1': { patterns: ['a/b', 'a/b/{p}'], @@ -174,7 +174,7 @@ describe('Url autocomplete', () => { }); })(); - (function() { + (function () { const endpoints = { '1': { patterns: ['a/{p}'], @@ -228,7 +228,7 @@ describe('Url autocomplete', () => { }); })(); - (function() { + (function () { const endpoints = { '1': { patterns: ['a/{p}'], @@ -254,7 +254,7 @@ describe('Url autocomplete', () => { }, }; const globalFactories = { - p: function(name, parent) { + p: function (name, parent) { return new ListComponent(name, ['g1', 'g2'], parent); }, getComponent(name) { @@ -313,7 +313,7 @@ describe('Url autocomplete', () => { ); })(); - (function() { + (function () { const endpoints = { '1': { patterns: ['a/b/{p}/c/e'], @@ -343,7 +343,7 @@ describe('Url autocomplete', () => { }); })(); - (function() { + (function () { const endpoints = { '1_param': { patterns: ['a/{p}'], @@ -378,7 +378,7 @@ describe('Url autocomplete', () => { }); })(); - (function() { + (function () { const endpoints = { '1_GET': { patterns: ['a'], diff --git a/src/plugins/console/public/lib/autocomplete/__jest__/url_params.test.js b/src/plugins/console/public/lib/autocomplete/__jest__/url_params.test.js index 286aefcd133a0..e624e7ba57b61 100644 --- a/src/plugins/console/public/lib/autocomplete/__jest__/url_params.test.js +++ b/src/plugins/console/public/lib/autocomplete/__jest__/url_params.test.js @@ -22,10 +22,10 @@ import { populateContext } from '../../autocomplete/engine'; describe('Url params', () => { function paramTest(name, description, tokenPath, expectedContext, globalParams) { - test(name, function() { + test(name, function () { const urlParams = new UrlParams(description, globalParams || {}); if (typeof tokenPath === 'string') { - tokenPath = _.map(tokenPath.split('/'), function(p) { + tokenPath = _.map(tokenPath.split('/'), function (p) { p = p.split(','); if (p.length === 1) { return p[0]; @@ -35,7 +35,7 @@ describe('Url params', () => { } if (expectedContext.autoCompleteSet) { - expectedContext.autoCompleteSet = _.map(expectedContext.autoCompleteSet, function(t) { + expectedContext.autoCompleteSet = _.map(expectedContext.autoCompleteSet, function (t) { if (_.isString(t)) { t = { name: t }; } @@ -79,7 +79,7 @@ describe('Url params', () => { return r; } - (function() { + (function () { const params = { a: ['1', '2'], b: '__flag__', diff --git a/src/plugins/console/public/lib/autocomplete/autocomplete.ts b/src/plugins/console/public/lib/autocomplete/autocomplete.ts index d4f10ff4e4277..b05c7ddbb020d 100644 --- a/src/plugins/console/public/lib/autocomplete/autocomplete.ts +++ b/src/plugins/console/public/lib/autocomplete/autocomplete.ts @@ -321,7 +321,7 @@ export default function({ coreEditor: editor, parser }: { coreEditor: CoreEditor } function addMetaToTermsList(list: any, meta: any, template?: string) { - return _.map(list, function(t: any) { + return _.map(list, function (t: any) { if (typeof t !== 'object') { t = { name: t }; } @@ -955,7 +955,7 @@ export default function({ coreEditor: editor, parser }: { coreEditor: CoreEditor } else { const terms = _.map( context.autoCompleteSet.filter((term: any) => Boolean(term) && term.name != null), - function(term: any) { + function (term: any) { if (typeof term !== 'object') { term = { name: term, @@ -981,7 +981,7 @@ export default function({ coreEditor: editor, parser }: { coreEditor: CoreEditor } ); - terms.sort(function(t1: any, t2: any) { + terms.sort(function (t1: any, t2: any) { /* score sorts from high to low */ if (t1.score > t2.score) { return -1; @@ -1001,7 +1001,7 @@ export default function({ coreEditor: editor, parser }: { coreEditor: CoreEditor callback( null, - _.map(terms, function(t: any, i: any) { + _.map(terms, function (t: any, i: any) { t.insertValue = t.insertValue || t.value; t.value = '' + t.value; // normalize to strings t.score = -i; diff --git a/src/plugins/console/public/lib/autocomplete/body_completer.js b/src/plugins/console/public/lib/autocomplete/body_completer.js index 9bb1f14a6266a..f37b3ac0cca9c 100644 --- a/src/plugins/console/public/lib/autocomplete/body_completer.js +++ b/src/plugins/console/public/lib/autocomplete/body_completer.js @@ -104,7 +104,7 @@ class ScopeResolver extends SharedComponent { getTerms(context, editor) { const options = []; const components = this.resolveLinkToComponents(context, editor); - _.each(components, function(component) { + _.each(components, function (component) { options.push.apply(options, component.getTerms(context, editor)); }); return options; @@ -115,7 +115,7 @@ class ScopeResolver extends SharedComponent { next: [], }; const components = this.resolveLinkToComponents(context, editor); - _.each(components, function(component) { + _.each(components, function (component) { const componentResult = component.match(token, context, editor); if (componentResult && componentResult.next) { result.next.push.apply(result.next, componentResult.next); @@ -193,7 +193,7 @@ function compileDescription(description, compilingContext) { } if (description.__one_of) { return _.flatten( - _.map(description.__one_of, function(d) { + _.map(description.__one_of, function (d) { return compileDescription(d, compilingContext); }) ); @@ -228,7 +228,7 @@ function compileObject(objDescription, compilingContext) { const objectC = new ConstantComponent('{'); const constants = []; const patterns = []; - _.each(objDescription, function(desc, key) { + _.each(objDescription, function (desc, key) { if (key.indexOf('__') === 0) { // meta key return; @@ -247,7 +247,7 @@ function compileObject(objDescription, compilingContext) { component = new ConstantComponent(key, null, [options]); constants.push(component); } - _.map(compileDescription(desc, compilingContext), function(subComponent) { + _.map(compileDescription(desc, compilingContext), function (subComponent) { component.addComponent(subComponent); }); }); @@ -257,8 +257,8 @@ function compileObject(objDescription, compilingContext) { function compileList(listRule, compilingContext) { const listC = new ConstantComponent('['); - _.each(listRule, function(desc) { - _.each(compileDescription(desc, compilingContext), function(component) { + _.each(listRule, function (desc) { + _.each(compileDescription(desc, compilingContext), function (component) { listC.addComponent(component); }); }); @@ -268,7 +268,7 @@ function compileList(listRule, compilingContext) { /** takes a compiled object and wraps in a {@link ConditionalProxy }*/ function compileCondition(description, compiledObject) { if (description.lines_regex) { - return new ConditionalProxy(function(context, editor) { + return new ConditionalProxy(function (context, editor) { const lines = editor .getLines(context.requestStartRow, editor.getCurrentPosition().lineNumber) .join('\n'); diff --git a/src/plugins/console/public/lib/autocomplete/components/field_autocomplete_component.js b/src/plugins/console/public/lib/autocomplete/components/field_autocomplete_component.js index 80f65406cf5d3..05c72ea8a8dc5 100644 --- a/src/plugins/console/public/lib/autocomplete/components/field_autocomplete_component.js +++ b/src/plugins/console/public/lib/autocomplete/components/field_autocomplete_component.js @@ -21,7 +21,7 @@ import { getFields } from '../../mappings/mappings'; import { ListComponent } from './list_component'; function FieldGenerator(context) { - return _.map(getFields(context.indices, context.types), function(field) { + return _.map(getFields(context.indices, context.types), function (field) { return { name: field.name, meta: field.type }; }); } @@ -35,7 +35,7 @@ export class FieldAutocompleteComponent extends ListComponent { return false; } - return !_.find(tokens, function(token) { + return !_.find(tokens, function (token) { return token.match(/[^\w.?*]/); }); } diff --git a/src/plugins/console/public/lib/autocomplete/components/id_autocomplete_component.js b/src/plugins/console/public/lib/autocomplete/components/id_autocomplete_component.js index d6deadc75ed74..88b9320b3c45e 100644 --- a/src/plugins/console/public/lib/autocomplete/components/id_autocomplete_component.js +++ b/src/plugins/console/public/lib/autocomplete/components/id_autocomplete_component.js @@ -33,7 +33,7 @@ export class IdAutocompleteComponent extends SharedComponent { } token = Array.isArray(token) ? token : [token]; if ( - _.find(token, function(t) { + _.find(token, function (t) { return t.match(/[\/,]/); }) ) { diff --git a/src/plugins/console/public/lib/autocomplete/components/list_component.js b/src/plugins/console/public/lib/autocomplete/components/list_component.js index 2f443ffaf6c93..b770638a61ff7 100644 --- a/src/plugins/console/public/lib/autocomplete/components/list_component.js +++ b/src/plugins/console/public/lib/autocomplete/components/list_component.js @@ -24,7 +24,7 @@ export class ListComponent extends SharedComponent { constructor(name, list, parent, multiValued, allowNonValidValues) { super(name, parent); this.listGenerator = Array.isArray(list) - ? function() { + ? function () { return list; } : list; @@ -44,7 +44,7 @@ export class ListComponent extends SharedComponent { if (this.getDefaultTermMeta()) { const meta = this.getDefaultTermMeta(); - ret = _.map(ret, function(term) { + ret = _.map(ret, function (term) { if (_.isString(term)) { term = { name: term }; } @@ -62,7 +62,7 @@ export class ListComponent extends SharedComponent { // verify we have all tokens const list = this.listGenerator(); - const notFound = _.any(tokens, function(token) { + const notFound = _.any(tokens, function (token) { return list.indexOf(token) === -1; }); diff --git a/src/plugins/console/public/lib/autocomplete/components/object_component.js b/src/plugins/console/public/lib/autocomplete/components/object_component.js index f73625cccf38b..34cfb892a65d9 100644 --- a/src/plugins/console/public/lib/autocomplete/components/object_component.js +++ b/src/plugins/console/public/lib/autocomplete/components/object_component.js @@ -32,10 +32,10 @@ export class ObjectComponent extends SharedComponent { } getTerms(context, editor) { const options = []; - _.each(this.constants, function(component) { + _.each(this.constants, function (component) { options.push.apply(options, component.getTerms(context, editor)); }); - _.each(this.patternsAndWildCards, function(component) { + _.each(this.patternsAndWildCards, function (component) { options.push.apply(options, component.getTerms(context, editor)); }); return options; @@ -45,7 +45,7 @@ export class ObjectComponent extends SharedComponent { const result = { next: [], }; - _.each(this.constants, function(component) { + _.each(this.constants, function (component) { const componentResult = component.match(token, context, editor); if (componentResult && componentResult.next) { result.next.push.apply(result.next, componentResult.next); @@ -61,7 +61,7 @@ export class ObjectComponent extends SharedComponent { if (result.next.length) { return result; } - _.each(this.patternsAndWildCards, function(component) { + _.each(this.patternsAndWildCards, function (component) { const componentResult = component.match(token, context, editor); if (componentResult && componentResult.next) { result.next.push.apply(result.next, componentResult.next); diff --git a/src/plugins/console/public/lib/autocomplete/components/url_pattern_matcher.js b/src/plugins/console/public/lib/autocomplete/components/url_pattern_matcher.js index 5921a910f4175..79a332624e5e1 100644 --- a/src/plugins/console/public/lib/autocomplete/components/url_pattern_matcher.js +++ b/src/plugins/console/public/lib/autocomplete/components/url_pattern_matcher.js @@ -43,7 +43,7 @@ export class UrlPatternMatcher { // We'll group endpoints by the methods which are attached to them, //to avoid suggesting endpoints that are incompatible with the //method that the user has entered. - ['HEAD', 'GET', 'PUT', 'POST', 'DELETE'].forEach(method => { + ['HEAD', 'GET', 'PUT', 'POST', 'DELETE'].forEach((method) => { this[method] = { rootComponent: new SharedComponent('ROOT'), parametrizedComponentFactories: parametrizedComponentFactories || { @@ -53,7 +53,7 @@ export class UrlPatternMatcher { }); } addEndpoint(pattern, endpoint) { - endpoint.methods.forEach(method => { + endpoint.methods.forEach((method) => { let c; let activeComponent = this[method].rootComponent; if (endpoint.template) { @@ -63,7 +63,7 @@ export class UrlPatternMatcher { const partList = pattern.split('/'); _.each( partList, - function(part, partIndex) { + function (part, partIndex) { if (part.search(/^{.+}$/) >= 0) { part = part.substr(1, part.length - 2); if (activeComponent.getComponent(part)) { @@ -133,7 +133,7 @@ export class UrlPatternMatcher { }); } - getTopLevelComponents = function(method) { + getTopLevelComponents = function (method) { const methodRoot = this[method]; if (!methodRoot) { return []; diff --git a/src/plugins/console/public/lib/autocomplete/engine.js b/src/plugins/console/public/lib/autocomplete/engine.js index ae943a74ffb3a..38be0d8a7e4c9 100644 --- a/src/plugins/console/public/lib/autocomplete/engine.js +++ b/src/plugins/console/public/lib/autocomplete/engine.js @@ -21,14 +21,14 @@ import _ from 'lodash'; export function wrapComponentWithDefaults(component, defaults) { const originalGetTerms = component.getTerms; - component.getTerms = function(context, editor) { + component.getTerms = function (context, editor) { let result = originalGetTerms.call(component, context, editor); if (!result) { return result; } result = _.map( result, - function(term) { + function (term) { if (!_.isObject(term)) { term = { name: term }; } @@ -41,7 +41,7 @@ export function wrapComponentWithDefaults(component, defaults) { return component; } -const tracer = function() { +const tracer = function () { if (window.engine_trace) { console.log.call(console, ...arguments); } @@ -77,9 +77,9 @@ export function walkTokenPath(tokenPath, walkingStates, context, editor) { tracer('starting token evaluation [' + token + ']'); - _.each(walkingStates, function(ws) { + _.each(walkingStates, function (ws) { const contextForState = passThroughContext(context, ws.contextExtensionList); - _.each(ws.components, function(component) { + _.each(ws.components, function (component) { tracer('evaluating [' + token + '] with [' + component.name + ']', component); const result = component.match(token, contextForState, editor); if (result && !_.isEmpty(result)) { @@ -117,7 +117,7 @@ export function walkTokenPath(tokenPath, walkingStates, context, editor) { if (nextWalkingStates.length === 0) { // no where to go, still return context variables returned so far.. - return _.map(walkingStates, function(ws) { + return _.map(walkingStates, function (ws) { return new WalkingState(ws.name, [], ws.contextExtensionList); }); } @@ -134,10 +134,10 @@ export function populateContext(tokenPath, context, editor, includeAutoComplete, ); if (includeAutoComplete) { let autoCompleteSet = []; - _.each(walkStates, function(ws) { + _.each(walkStates, function (ws) { const contextForState = passThroughContext(context, ws.contextExtensionList); - _.each(ws.components, function(component) { - _.each(component.getTerms(contextForState, editor), function(term) { + _.each(ws.components, function (component) { + _.each(component.getTerms(contextForState, editor), function (term) { if (!_.isObject(term)) { term = { name: term }; } @@ -152,10 +152,10 @@ export function populateContext(tokenPath, context, editor, includeAutoComplete, // apply what values were set so far to context, selecting the deepest on which sets the context if (walkStates.length !== 0) { let wsToUse; - walkStates = _.sortBy(walkStates, function(ws) { + walkStates = _.sortBy(walkStates, function (ws) { return _.isNumber(ws.priority) ? ws.priority : Number.MAX_VALUE; }); - wsToUse = _.find(walkStates, function(ws) { + wsToUse = _.find(walkStates, function (ws) { return _.isEmpty(ws.components); }); @@ -170,7 +170,7 @@ export function populateContext(tokenPath, context, editor, includeAutoComplete, wsToUse = walkStates[0]; } - _.each(wsToUse.contextExtensionList, function(extension) { + _.each(wsToUse.contextExtensionList, function (extension) { _.assign(context, extension); }); } diff --git a/src/plugins/console/public/lib/autocomplete/url_params.js b/src/plugins/console/public/lib/autocomplete/url_params.js index 0519a2daade87..a237fe5dd59d6 100644 --- a/src/plugins/console/public/lib/autocomplete/url_params.js +++ b/src/plugins/console/public/lib/autocomplete/url_params.js @@ -52,7 +52,7 @@ export class UrlParams { _.defaults(description, defaults); _.each( description, - function(pDescription, param) { + function (pDescription, param) { const component = new ParamComponent(param, this.rootComponent, pDescription); if (Array.isArray(pDescription)) { new ListComponent(param, pDescription, component); diff --git a/src/plugins/console/public/lib/curl_parsing/__tests__/curl_parsing.test.js b/src/plugins/console/public/lib/curl_parsing/__tests__/curl_parsing.test.js index 6a8caebfc6874..068dd68be4ba8 100644 --- a/src/plugins/console/public/lib/curl_parsing/__tests__/curl_parsing.test.js +++ b/src/plugins/console/public/lib/curl_parsing/__tests__/curl_parsing.test.js @@ -23,13 +23,13 @@ import curlTests from './curl_parsing.txt'; describe('CURL', () => { const notCURLS = ['sldhfsljfhs', 's;kdjfsldkfj curl -XDELETE ""', '{ "hello": 1 }']; - _.each(notCURLS, function(notCURL, i) { - test('cURL Detection - broken strings ' + i, function() { + _.each(notCURLS, function (notCURL, i) { + test('cURL Detection - broken strings ' + i, function () { expect(detectCURL(notCURL)).toEqual(false); }); }); - curlTests.split(/^=+$/m).forEach(function(fixture) { + curlTests.split(/^=+$/m).forEach(function (fixture) { if (fixture.trim() === '') { return; } @@ -38,7 +38,7 @@ describe('CURL', () => { const curlText = fixture[1]; const response = fixture[2].trim(); - test('cURL Detection - ' + name, function() { + test('cURL Detection - ' + name, function () { expect(detectCURL(curlText)).toBe(true); const r = parseCURL(curlText); expect(r).toEqual(response); diff --git a/src/plugins/console/public/lib/kb/__tests__/kb.test.js b/src/plugins/console/public/lib/kb/__tests__/kb.test.js index c80f5671449b3..eaf5023053880 100644 --- a/src/plugins/console/public/lib/kb/__tests__/kb.test.js +++ b/src/plugins/console/public/lib/kb/__tests__/kb.test.js @@ -58,7 +58,7 @@ describe('Knowledge base', () => { function testUrlContext(tokenPath, otherTokenValues, expectedContext) { if (expectedContext.autoCompleteSet) { - expectedContext.autoCompleteSet = _.map(expectedContext.autoCompleteSet, function(t) { + expectedContext.autoCompleteSet = _.map(expectedContext.autoCompleteSet, function (t) { if (_.isString(t)) { t = { name: t }; } @@ -111,7 +111,7 @@ describe('Knowledge base', () => { } function indexTest(name, tokenPath, otherTokenValues, expectedContext) { - test(name, function() { + test(name, function () { // eslint-disable-next-line new-cap const testApi = new kb._test.loadApisFromJson( { @@ -161,7 +161,7 @@ describe('Knowledge base', () => { }); function typeTest(name, tokenPath, otherTokenValues, expectedContext) { - test(name, function() { + test(name, function () { const testApi = kb._test.loadApisFromJson( { typeTest: { diff --git a/src/plugins/console/public/lib/kb/api.js b/src/plugins/console/public/lib/kb/api.js index c418a7cb414ef..aafb234b0f446 100644 --- a/src/plugins/console/public/lib/kb/api.js +++ b/src/plugins/console/public/lib/kb/api.js @@ -41,8 +41,8 @@ function Api(urlParametrizedComponentFactories, bodyParametrizedComponentFactori this.name = ''; } -(function(cls) { - cls.addGlobalAutocompleteRules = function(parentNode, rules) { +(function (cls) { + cls.addGlobalAutocompleteRules = function (parentNode, rules) { this.globalRules[parentNode] = compileBodyDescription( 'GLOBAL.' + parentNode, rules, @@ -50,7 +50,7 @@ function Api(urlParametrizedComponentFactories, bodyParametrizedComponentFactori ); }; - cls.getGlobalAutocompleteComponents = function(term, throwOnMissing) { + cls.getGlobalAutocompleteComponents = function (term, throwOnMissing) { const result = this.globalRules[term]; if (_.isUndefined(result) && (throwOnMissing || _.isUndefined(throwOnMissing))) { throw new Error("failed to resolve global components for ['" + term + "']"); @@ -58,7 +58,7 @@ function Api(urlParametrizedComponentFactories, bodyParametrizedComponentFactori return result; }; - cls.addEndpointDescription = function(endpoint, description) { + cls.addEndpointDescription = function (endpoint, description) { const copiedDescription = {}; _.extend(copiedDescription, description || {}); _.defaults(copiedDescription, { @@ -68,7 +68,7 @@ function Api(urlParametrizedComponentFactories, bodyParametrizedComponentFactori }); _.each( copiedDescription.patterns, - function(p) { + function (p) { this.urlPatternMatcher.addEndpoint(p, copiedDescription); }, this @@ -84,19 +84,19 @@ function Api(urlParametrizedComponentFactories, bodyParametrizedComponentFactori this.endpoints[endpoint] = copiedDescription; }; - cls.getEndpointDescriptionByEndpoint = function(endpoint) { + cls.getEndpointDescriptionByEndpoint = function (endpoint) { return this.endpoints[endpoint]; }; - cls.getTopLevelUrlCompleteComponents = function(method) { + cls.getTopLevelUrlCompleteComponents = function (method) { return this.urlPatternMatcher.getTopLevelComponents(method); }; - cls.getUnmatchedEndpointComponents = function() { + cls.getUnmatchedEndpointComponents = function () { return globalsOnlyAutocompleteComponents(); }; - cls.clear = function() { + cls.clear = function () { this.endpoints = {}; this.globalRules = {}; }; diff --git a/src/plugins/console/public/lib/kb/kb.js b/src/plugins/console/public/lib/kb/kb.js index 0d0f42319d0d8..e0bf1ef09c4d3 100644 --- a/src/plugins/console/public/lib/kb/kb.js +++ b/src/plugins/console/public/lib/kb/kb.js @@ -32,68 +32,68 @@ import _ from 'lodash'; import Api from './api'; let ACTIVE_API = new Api(); -const isNotAnIndexName = name => name[0] === '_' && name !== '_all'; +const isNotAnIndexName = (name) => name[0] === '_' && name !== '_all'; const idAutocompleteComponentFactory = (name, parent) => { return new IdAutocompleteComponent(name, parent); }; const parametrizedComponentFactories = { - getComponent: function(name, parent, provideDefault) { + getComponent: function (name, parent, provideDefault) { if (this[name]) { return this[name]; } else if (provideDefault) { return idAutocompleteComponentFactory; } }, - index: function(name, parent) { + index: function (name, parent) { if (isNotAnIndexName(name)) return; return new IndexAutocompleteComponent(name, parent, false); }, - indices: function(name, parent) { + indices: function (name, parent) { if (isNotAnIndexName(name)) return; return new IndexAutocompleteComponent(name, parent, true); }, - type: function(name, parent) { + type: function (name, parent) { return new TypeAutocompleteComponent(name, parent, false); }, - types: function(name, parent) { + types: function (name, parent) { return new TypeAutocompleteComponent(name, parent, true); }, - id: function(name, parent) { + id: function (name, parent) { return idAutocompleteComponentFactory(name, parent); }, - transform_id: function(name, parent) { + transform_id: function (name, parent) { return idAutocompleteComponentFactory(name, parent); }, - username: function(name, parent) { + username: function (name, parent) { return new UsernameAutocompleteComponent(name, parent); }, - user: function(name, parent) { + user: function (name, parent) { return new UsernameAutocompleteComponent(name, parent); }, - template: function(name, parent) { + template: function (name, parent) { return new TemplateAutocompleteComponent(name, parent); }, - task_id: function(name, parent) { + task_id: function (name, parent) { return idAutocompleteComponentFactory(name, parent); }, - ids: function(name, parent) { + ids: function (name, parent) { return idAutocompleteComponentFactory(name, parent, true); }, - fields: function(name, parent) { + fields: function (name, parent) { return new FieldAutocompleteComponent(name, parent, true); }, - field: function(name, parent) { + field: function (name, parent) { return new FieldAutocompleteComponent(name, parent, false); }, - nodes: function(name, parent) { + nodes: function (name, parent) { return new ListComponent( name, ['_local', '_master', 'data:true', 'data:false', 'master:true', 'master:false'], parent ); }, - node: function(name, parent) { + node: function (name, parent) { return new ListComponent(name, [], parent, false); }, }; @@ -133,12 +133,12 @@ function loadApisFromJson( bodyParametrizedComponentFactories || urlParametrizedComponentFactories; const api = new Api(urlParametrizedComponentFactories, bodyParametrizedComponentFactories); const names = []; - _.each(json, function(apiJson, name) { + _.each(json, function (apiJson, name) { names.unshift(name); - _.each(apiJson.globals || {}, function(globalJson, globalName) { + _.each(apiJson.globals || {}, function (globalJson, globalName) { api.addGlobalAutocompleteRules(globalName, globalJson); }); - _.each(apiJson.endpoints || {}, function(endpointJson, endpointName) { + _.each(apiJson.endpoints || {}, function (endpointJson, endpointName) { api.addEndpointDescription(endpointName, endpointJson); }); }); @@ -159,10 +159,10 @@ export function setActiveApi(api) { 'kbn-xsrf': 'kibana', }, }).then( - function(data) { + function (data) { setActiveApi(loadApisFromJson(data)); }, - function(jqXHR) { + function (jqXHR) { console.log("failed to load API '" + api + "': " + jqXHR.responseText); } ); diff --git a/src/plugins/console/public/lib/local_storage_object_client/local_storage_object_client.ts b/src/plugins/console/public/lib/local_storage_object_client/local_storage_object_client.ts index 8eac345898f9a..a6b47559a4ef5 100644 --- a/src/plugins/console/public/lib/local_storage_object_client/local_storage_object_client.ts +++ b/src/plugins/console/public/lib/local_storage_object_client/local_storage_object_client.ts @@ -40,7 +40,7 @@ export class LocalObjectStorage implements ObjectStorage } async findAll(): Promise { - const allLocalKeys = this.client.keys().filter(key => { + const allLocalKeys = this.client.keys().filter((key) => { return key.includes(this.prefix); }); diff --git a/src/plugins/console/public/lib/mappings/__tests__/mapping.test.js b/src/plugins/console/public/lib/mappings/__tests__/mapping.test.js index 292b1b4fb1bf5..ce52b060f418f 100644 --- a/src/plugins/console/public/lib/mappings/__tests__/mapping.test.js +++ b/src/plugins/console/public/lib/mappings/__tests__/mapping.test.js @@ -41,7 +41,7 @@ describe('Mappings', () => { return { name: name, type: type || 'string' }; } - test('Multi fields 1.0 style', function() { + test('Multi fields 1.0 style', function () { mappings.loadMappings({ index: { properties: { @@ -72,7 +72,7 @@ describe('Mappings', () => { ]); }); - test('Simple fields', function() { + test('Simple fields', function () { mappings.loadMappings({ index: { properties: { @@ -89,7 +89,7 @@ describe('Mappings', () => { expect(mappings.getFields('index').sort(fc)).toEqual([f('number', 'int'), f('str', 'string')]); }); - test('Simple fields - 1.0 style', function() { + test('Simple fields - 1.0 style', function () { mappings.loadMappings({ index: { mappings: { @@ -108,7 +108,7 @@ describe('Mappings', () => { expect(mappings.getFields('index').sort(fc)).toEqual([f('number', 'int'), f('str', 'string')]); }); - test('Nested fields', function() { + test('Nested fields', function () { mappings.loadMappings({ index: { properties: { @@ -137,7 +137,7 @@ describe('Mappings', () => { ]); }); - test('Enabled fields', function() { + test('Enabled fields', function () { mappings.loadMappings({ index: { properties: { @@ -159,7 +159,7 @@ describe('Mappings', () => { expect(mappings.getFields('index', []).sort(fc)).toEqual([f('message'), f('person.sid')]); }); - test('Path tests', function() { + test('Path tests', function () { mappings.loadMappings({ index: { properties: { @@ -191,7 +191,7 @@ describe('Mappings', () => { ]); }); - test('Use index_name tests', function() { + test('Use index_name tests', function () { mappings.loadMappings({ index: { properties: { @@ -203,7 +203,7 @@ describe('Mappings', () => { expect(mappings.getFields().sort(fc)).toEqual([f('i_last_1')]); }); - test('Aliases', function() { + test('Aliases', function () { mappings.loadAliases({ test_index1: { aliases: { diff --git a/src/plugins/console/public/lib/mappings/mappings.js b/src/plugins/console/public/lib/mappings/mappings.js index b5bcc2b105996..22aae8da030d4 100644 --- a/src/plugins/console/public/lib/mappings/mappings.js +++ b/src/plugins/console/public/lib/mappings/mappings.js @@ -43,7 +43,7 @@ export function expandAliases(indicesOrAliases) { if (typeof indicesOrAliases === 'string') { indicesOrAliases = [indicesOrAliases]; } - indicesOrAliases = $.map(indicesOrAliases, function(iOrA) { + indicesOrAliases = $.map(indicesOrAliases, function (iOrA) { if (perAliasIndexes[iOrA]) { return perAliasIndexes[iOrA]; } @@ -52,7 +52,7 @@ export function expandAliases(indicesOrAliases) { let ret = [].concat.apply([], indicesOrAliases); ret.sort(); let last; - ret = $.map(ret, function(v) { + ret = $.map(ret, function (v) { const r = last === v ? null : v; last = v; return r; @@ -80,7 +80,7 @@ export function getFields(indices, types) { ret = f ? f : []; } else { // filter what we need - $.each(typeDict, function(type, fields) { + $.each(typeDict, function (type, fields) { if (!types || types.length === 0 || $.inArray(type, types) !== -1) { ret.push(fields); } @@ -90,7 +90,7 @@ export function getFields(indices, types) { } } else { // multi index mode. - $.each(perIndexTypes, function(index) { + $.each(perIndexTypes, function (index) { if (!indices || indices.length === 0 || $.inArray(index, indices) !== -1) { ret.push(getFields(index, types)); } @@ -98,7 +98,7 @@ export function getFields(indices, types) { ret = [].concat.apply([], ret); } - return _.uniq(ret, function(f) { + return _.uniq(ret, function (f) { return f.name + ':' + f.type; }); } @@ -113,12 +113,12 @@ export function getTypes(indices) { } // filter what we need - $.each(typeDict, function(type) { + $.each(typeDict, function (type) { ret.push(type); }); } else { // multi index mode. - $.each(perIndexTypes, function(index) { + $.each(perIndexTypes, function (index) { if (!indices || $.inArray(index, indices) !== -1) { ret.push(getTypes(index)); } @@ -131,11 +131,11 @@ export function getTypes(indices) { export function getIndices(includeAliases) { const ret = []; - $.each(perIndexTypes, function(index) { + $.each(perIndexTypes, function (index) { ret.push(index); }); if (typeof includeAliases === 'undefined' ? true : includeAliases) { - $.each(perAliasIndexes, function(alias) { + $.each(perAliasIndexes, function (alias) { ret.push(alias); }); } @@ -151,7 +151,7 @@ function getFieldNamesFromFieldMapping(fieldName, fieldMapping) { function applyPathSettings(nestedFieldNames) { const pathType = fieldMapping.path || 'full'; if (pathType === 'full') { - return $.map(nestedFieldNames, function(f) { + return $.map(nestedFieldNames, function (f) { f.name = fieldName + '.' + f.name; return f; }); @@ -174,7 +174,7 @@ function getFieldNamesFromFieldMapping(fieldName, fieldMapping) { } if (fieldMapping.fields) { - nestedFields = $.map(fieldMapping.fields, function(fieldMapping, fieldName) { + nestedFields = $.map(fieldMapping.fields, function (fieldMapping, fieldName) { return getFieldNamesFromFieldMapping(fieldName, fieldMapping); }); nestedFields = applyPathSettings(nestedFields); @@ -186,12 +186,12 @@ function getFieldNamesFromFieldMapping(fieldName, fieldMapping) { } function getFieldNamesFromProperties(properties = {}) { - const fieldList = $.map(properties, function(fieldMapping, fieldName) { + const fieldList = $.map(properties, function (fieldMapping, fieldName) { return getFieldNamesFromFieldMapping(fieldName, fieldMapping); }); // deduping - return _.uniq(fieldList, function(f) { + return _.uniq(fieldList, function (f) { return f.name + ':' + f.type; }); } @@ -203,7 +203,7 @@ function loadTemplates(templatesObject = {}) { export function loadMappings(mappings) { perIndexTypes = {}; - $.each(mappings, function(index, indexMapping) { + $.each(mappings, function (index, indexMapping) { const normalizedIndexMappings = {}; // Migrate 1.0.0 mappings. This format has changed, so we need to extract the underlying mapping. @@ -211,7 +211,7 @@ export function loadMappings(mappings) { indexMapping = indexMapping.mappings; } - $.each(indexMapping, function(typeName, typeMapping) { + $.each(indexMapping, function (typeName, typeMapping) { if (typeName === 'properties') { const fieldList = getFieldNamesFromProperties(typeMapping); normalizedIndexMappings[typeName] = fieldList; @@ -226,11 +226,11 @@ export function loadMappings(mappings) { export function loadAliases(aliases) { perAliasIndexes = {}; - $.each(aliases || {}, function(index, omdexAliases) { + $.each(aliases || {}, function (index, omdexAliases) { // verify we have an index defined. useful when mapping loading is disabled perIndexTypes[index] = perIndexTypes[index] || {}; - $.each(omdexAliases.aliases || {}, function(alias) { + $.each(omdexAliases.aliases || {}, function (alias) { if (alias === index) { return; } // alias which is identical to index means no index. diff --git a/src/plugins/console/public/lib/token_iterator/token_iterator.ts b/src/plugins/console/public/lib/token_iterator/token_iterator.ts index 643938536b306..5939741bc96e6 100644 --- a/src/plugins/console/public/lib/token_iterator/token_iterator.ts +++ b/src/plugins/console/public/lib/token_iterator/token_iterator.ts @@ -33,7 +33,7 @@ export class TokenIterator { constructor(private readonly provider: TokensProvider, startPosition: Position) { this.tokensLineCache = this.provider.getTokens(startPosition.lineNumber) || []; - const tokenIdx = this.tokensLineCache.findIndex(token => + const tokenIdx = this.tokensLineCache.findIndex((token) => isColumnInTokenRange(startPosition.column, token) ); if (tokenIdx > -1) { diff --git a/src/plugins/console/public/lib/utils/__tests__/utils.test.js b/src/plugins/console/public/lib/utils/__tests__/utils.test.js index 3a2e6a54c1328..e47e71c742a81 100644 --- a/src/plugins/console/public/lib/utils/__tests__/utils.test.js +++ b/src/plugins/console/public/lib/utils/__tests__/utils.test.js @@ -20,7 +20,7 @@ import * as utils from '../'; describe('Utils class', () => { - test('extract deprecation messages', function() { + test('extract deprecation messages', function () { expect( utils.extractDeprecationMessages( '299 Elasticsearch-6.0.0-alpha1-SNAPSHOT-abcdef1 "this is a warning" "Mon, 27 Feb 2017 14:52:14 GMT"' @@ -70,7 +70,7 @@ describe('Utils class', () => { ]); }); - test('unescape', function() { + test('unescape', function () { expect(utils.unescape('escaped backslash \\\\')).toEqual('escaped backslash \\'); expect(utils.unescape('a pair of \\"escaped quotes\\"')).toEqual('a pair of "escaped quotes"'); expect(utils.unescape('escaped quotes do not have to come in pairs: \\"')).toEqual( @@ -78,7 +78,7 @@ describe('Utils class', () => { ); }); - test('split on unquoted comma followed by space', function() { + test('split on unquoted comma followed by space', function () { expect(utils.splitOnUnquotedCommaSpace('a, b')).toEqual(['a', 'b']); expect(utils.splitOnUnquotedCommaSpace('a,b, c')).toEqual(['a,b', 'c']); expect(utils.splitOnUnquotedCommaSpace('"a, b"')).toEqual(['"a, b"']); diff --git a/src/plugins/console/public/lib/utils/index.ts b/src/plugins/console/public/lib/utils/index.ts index 0ebea0f9d4055..917988e0e811b 100644 --- a/src/plugins/console/public/lib/utils/index.ts +++ b/src/plugins/console/public/lib/utils/index.ts @@ -61,7 +61,7 @@ export function extractDeprecationMessages(warnings: string) { // pattern for valid warning header const re = /\d{3} [0-9a-zA-Z!#$%&'*+-.^_`|~]+ \"((?:\t| |!|[\x23-\x5b]|[\x5d-\x7e]|[\x80-\xff]|\\\\|\\")*)\"(?: \"[^"]*\")?/; // split on any comma that is followed by an even number of quotes - return _.map(splitOnUnquotedCommaSpace(warnings), warning => { + return _.map(splitOnUnquotedCommaSpace(warnings), (warning) => { const match = re.exec(warning); // extract the actual warning if there was a match return '#! Deprecation: ' + (match !== null ? unescape(match[1]) : warning); diff --git a/src/plugins/console/public/services/history.ts b/src/plugins/console/public/services/history.ts index 04dae0beacefe..440014b362c7a 100644 --- a/src/plugins/console/public/services/history.ts +++ b/src/plugins/console/public/services/history.ts @@ -34,7 +34,7 @@ export class History { } getHistory() { - return this.getHistoryKeys().map(key => this.storage.get(key)); + return this.getHistoryKeys().map((key) => this.storage.get(key)); } // This is used as an optimization mechanism so that different components @@ -50,7 +50,7 @@ export class History { addToHistory(endpoint: string, method: string, data: any) { const keys = this.getHistoryKeys(); keys.splice(0, 500); // only maintain most recent X; - keys.forEach(key => { + keys.forEach((key) => { this.storage.delete(key); }); @@ -89,7 +89,7 @@ export class History { } clearHistory() { - this.getHistoryKeys().forEach(key => this.storage.delete(key)); + this.getHistoryKeys().forEach((key) => this.storage.delete(key)); } } diff --git a/src/plugins/console/server/__tests__/elasticsearch_proxy_config.js b/src/plugins/console/server/__tests__/elasticsearch_proxy_config.js index df8b49b0a089e..fcf385165a591 100644 --- a/src/plugins/console/server/__tests__/elasticsearch_proxy_config.js +++ b/src/plugins/console/server/__tests__/elasticsearch_proxy_config.js @@ -31,9 +31,9 @@ const getDefaultElasticsearchConfig = () => { }; }; -describe('plugins/console', function() { - describe('#getElasticsearchProxyConfig', function() { - it('sets timeout', function() { +describe('plugins/console', function () { + describe('#getElasticsearchProxyConfig', function () { + it('sets timeout', function () { const value = 1000; const proxyConfig = getElasticsearchProxyConfig({ ...getDefaultElasticsearchConfig(), @@ -42,7 +42,7 @@ describe('plugins/console', function() { expect(proxyConfig.timeout).to.be(value); }); - it(`uses https.Agent when url's protocol is https`, function() { + it(`uses https.Agent when url's protocol is https`, function () { const { agent } = getElasticsearchProxyConfig({ ...getDefaultElasticsearchConfig(), hosts: ['https://localhost:9200'], @@ -50,21 +50,21 @@ describe('plugins/console', function() { expect(agent).to.be.a(https.Agent); }); - it(`uses http.Agent when url's protocol is http`, function() { + it(`uses http.Agent when url's protocol is http`, function () { const { agent } = getElasticsearchProxyConfig(getDefaultElasticsearchConfig()); expect(agent).to.be.a(http.Agent); }); - describe('ssl', function() { + describe('ssl', function () { let config; - beforeEach(function() { + beforeEach(function () { config = { ...getDefaultElasticsearchConfig(), hosts: ['https://localhost:9200'], }; }); - it('sets rejectUnauthorized to false when verificationMode is none', function() { + it('sets rejectUnauthorized to false when verificationMode is none', function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { ...config.ssl, verificationMode: 'none' }, @@ -72,7 +72,7 @@ describe('plugins/console', function() { expect(agent.options.rejectUnauthorized).to.be(false); }); - it('sets rejectUnauthorized to true when verificationMode is certificate', function() { + it('sets rejectUnauthorized to true when verificationMode is certificate', function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { ...config.ssl, verificationMode: 'certificate' }, @@ -80,7 +80,7 @@ describe('plugins/console', function() { expect(agent.options.rejectUnauthorized).to.be(true); }); - it('sets checkServerIdentity to not check hostname when verificationMode is certificate', function() { + it('sets checkServerIdentity to not check hostname when verificationMode is certificate', function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { ...config.ssl, verificationMode: 'certificate' }, @@ -99,7 +99,7 @@ describe('plugins/console', function() { expect(result).to.be(undefined); }); - it('sets rejectUnauthorized to true when verificationMode is full', function() { + it('sets rejectUnauthorized to true when verificationMode is full', function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { ...config.ssl, verificationMode: 'full' }, @@ -108,7 +108,7 @@ describe('plugins/console', function() { expect(agent.options.rejectUnauthorized).to.be(true); }); - it(`doesn't set checkServerIdentity when verificationMode is full`, function() { + it(`doesn't set checkServerIdentity when verificationMode is full`, function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { ...config.ssl, verificationMode: 'full' }, @@ -117,7 +117,7 @@ describe('plugins/console', function() { expect(agent.options.checkServerIdentity).to.be(undefined); }); - it(`sets ca when certificateAuthorities are specified`, function() { + it(`sets ca when certificateAuthorities are specified`, function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { ...config.ssl, certificateAuthorities: ['content-of-some-path'] }, @@ -127,7 +127,7 @@ describe('plugins/console', function() { }); describe('when alwaysPresentCertificate is false', () => { - it(`doesn't set cert and key when certificate and key paths are specified`, function() { + it(`doesn't set cert and key when certificate and key paths are specified`, function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { @@ -142,7 +142,7 @@ describe('plugins/console', function() { expect(agent.options.key).to.be(undefined); }); - it(`doesn't set passphrase when certificate, key and keyPassphrase are specified`, function() { + it(`doesn't set passphrase when certificate, key and keyPassphrase are specified`, function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { @@ -159,7 +159,7 @@ describe('plugins/console', function() { }); describe('when alwaysPresentCertificate is true', () => { - it(`sets cert and key when certificate and key are specified`, async function() { + it(`sets cert and key when certificate and key are specified`, async function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { @@ -174,7 +174,7 @@ describe('plugins/console', function() { expect(agent.options.key).to.be('content-of-another-path'); }); - it(`sets passphrase when certificate, key and keyPassphrase are specified`, function() { + it(`sets passphrase when certificate, key and keyPassphrase are specified`, function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { @@ -189,7 +189,7 @@ describe('plugins/console', function() { expect(agent.options.passphrase).to.be('secret'); }); - it(`doesn't set cert when only certificate path is specified`, async function() { + it(`doesn't set cert when only certificate path is specified`, async function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { @@ -204,7 +204,7 @@ describe('plugins/console', function() { expect(agent.options.key).to.be(undefined); }); - it(`doesn't set key when only key path is specified`, async function() { + it(`doesn't set key when only key path is specified`, async function () { const { agent } = getElasticsearchProxyConfig({ ...config, ssl: { diff --git a/src/plugins/console/server/__tests__/proxy_config.js b/src/plugins/console/server/__tests__/proxy_config.js index b0b85e6bb7d06..1f3a94c4fe20f 100644 --- a/src/plugins/console/server/__tests__/proxy_config.js +++ b/src/plugins/console/server/__tests__/proxy_config.js @@ -34,17 +34,17 @@ const matchGoogle = { const parsedGoogle = parseUrl('https://google.com/search'); const parsedLocalEs = parseUrl('https://localhost:5601/search'); -describe('ProxyConfig', function() { - describe('constructor', function() { - beforeEach(function() { +describe('ProxyConfig', function () { + describe('constructor', function () { + beforeEach(function () { sinon.stub(https, 'Agent'); }); - afterEach(function() { + afterEach(function () { https.Agent.restore(); }); - it('uses ca to create sslAgent', function() { + it('uses ca to create sslAgent', function () { const config = new ProxyConfig({ ssl: { ca: ['content-of-some-path'], @@ -62,7 +62,7 @@ describe('ProxyConfig', function() { }); }); - it('uses cert, and key to create sslAgent', function() { + it('uses cert, and key to create sslAgent', function () { const config = new ProxyConfig({ ssl: { cert: 'content-of-some-path', @@ -81,7 +81,7 @@ describe('ProxyConfig', function() { }); }); - it('uses ca, cert, and key to create sslAgent', function() { + it('uses ca, cert, and key to create sslAgent', function () { const config = new ProxyConfig({ ssl: { ca: ['content-of-some-path'], @@ -103,9 +103,9 @@ describe('ProxyConfig', function() { }); }); - describe('#getForParsedUri', function() { - describe('parsed url does not match', function() { - it('returns {}', function() { + describe('#getForParsedUri', function () { + describe('parsed url does not match', function () { + it('returns {}', function () { const config = new ProxyConfig({ match: matchGoogle, timeout: 100, @@ -115,8 +115,8 @@ describe('ProxyConfig', function() { }); }); - describe('parsed url does match', function() { - it('assigns timeout value', function() { + describe('parsed url does match', function () { + it('assigns timeout value', function () { const football = {}; const config = new ProxyConfig({ match: matchGoogle, @@ -126,7 +126,7 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri(parsedGoogle).timeout).to.be(football); }); - it('assigns ssl.verify to rejectUnauthorized', function() { + it('assigns ssl.verify to rejectUnauthorized', function () { const football = {}; const config = new ProxyConfig({ match: matchGoogle, @@ -138,9 +138,9 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri(parsedGoogle).rejectUnauthorized).to.be(football); }); - describe('uri us http', function() { - describe('ca is set', function() { - it('creates but does not output the agent', function() { + describe('uri us http', function () { + describe('ca is set', function () { + it('creates but does not output the agent', function () { const config = new ProxyConfig({ ssl: { ca: ['path/to/ca'], @@ -151,8 +151,8 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri({ protocol: 'http:' }).agent).to.be(undefined); }); }); - describe('cert is set', function() { - it('creates but does not output the agent', function() { + describe('cert is set', function () { + it('creates but does not output the agent', function () { const config = new ProxyConfig({ ssl: { cert: 'path/to/cert', @@ -163,8 +163,8 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri({ protocol: 'http:' }).agent).to.be(undefined); }); }); - describe('key is set', function() { - it('creates but does not output the agent', function() { + describe('key is set', function () { + it('creates but does not output the agent', function () { const config = new ProxyConfig({ ssl: { key: 'path/to/key', @@ -175,8 +175,8 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri({ protocol: 'http:' }).agent).to.be(undefined); }); }); - describe('cert + key are set', function() { - it('creates but does not output the agent', function() { + describe('cert + key are set', function () { + it('creates but does not output the agent', function () { const config = new ProxyConfig({ ssl: { cert: 'path/to/cert', @@ -190,9 +190,9 @@ describe('ProxyConfig', function() { }); }); - describe('uri us https', function() { - describe('ca is set', function() { - it('creates and outputs the agent', function() { + describe('uri us https', function () { + describe('ca is set', function () { + it('creates and outputs the agent', function () { const config = new ProxyConfig({ ssl: { ca: ['path/to/ca'], @@ -203,8 +203,8 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri({ protocol: 'https:' }).agent).to.be(config.sslAgent); }); }); - describe('cert is set', function() { - it('creates and outputs the agent', function() { + describe('cert is set', function () { + it('creates and outputs the agent', function () { const config = new ProxyConfig({ ssl: { cert: 'path/to/cert', @@ -215,8 +215,8 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri({ protocol: 'https:' }).agent).to.be(config.sslAgent); }); }); - describe('key is set', function() { - it('creates and outputs the agent', function() { + describe('key is set', function () { + it('creates and outputs the agent', function () { const config = new ProxyConfig({ ssl: { key: 'path/to/key', @@ -227,8 +227,8 @@ describe('ProxyConfig', function() { expect(config.getForParsedUri({ protocol: 'https:' }).agent).to.be(config.sslAgent); }); }); - describe('cert + key are set', function() { - it('creates and outputs the agent', function() { + describe('cert + key are set', function () { + it('creates and outputs the agent', function () { const config = new ProxyConfig({ ssl: { cert: 'path/to/cert', diff --git a/src/plugins/console/server/__tests__/proxy_config_collection.js b/src/plugins/console/server/__tests__/proxy_config_collection.js index e1bc099ac1e85..729972399f0bb 100644 --- a/src/plugins/console/server/__tests__/proxy_config_collection.js +++ b/src/plugins/console/server/__tests__/proxy_config_collection.js @@ -26,12 +26,12 @@ import { Agent as HttpsAgent } from 'https'; import { ProxyConfigCollection } from '../lib/proxy_config_collection'; -describe('ProxyConfigCollection', function() { - beforeEach(function() { +describe('ProxyConfigCollection', function () { + beforeEach(function () { sinon.stub(fs, 'readFileSync').callsFake(() => Buffer.alloc(0)); }); - afterEach(function() { + afterEach(function () { fs.readFileSync.restore(); }); @@ -86,67 +86,67 @@ describe('ProxyConfigCollection', function() { return collection.configForUri(uri).timeout; } - describe('http://localhost:5601', function() { - it('defaults to the first matching timeout', function() { + describe('http://localhost:5601', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('http://localhost:5601')).to.be(3); }); }); - describe('https://localhost:5601/.kibana', function() { - it('defaults to the first matching timeout', function() { + describe('https://localhost:5601/.kibana', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('https://localhost:5601/.kibana')).to.be(1); }); }); - describe('http://localhost:5602', function() { - it('defaults to the first matching timeout', function() { + describe('http://localhost:5602', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('http://localhost:5602')).to.be(4); }); }); - describe('https://localhost:5602', function() { - it('defaults to the first matching timeout', function() { + describe('https://localhost:5602', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('https://localhost:5602')).to.be(4); }); }); - describe('http://localhost:5603', function() { - it('defaults to the first matching timeout', function() { + describe('http://localhost:5603', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('http://localhost:5603')).to.be(4); }); }); - describe('https://localhost:5603', function() { - it('defaults to the first matching timeout', function() { + describe('https://localhost:5603', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('https://localhost:5603')).to.be(4); }); }); - describe('https://localhost:5601/index', function() { - it('defaults to the first matching timeout', function() { + describe('https://localhost:5601/index', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('https://localhost:5601/index')).to.be(2); }); }); - describe('http://localhost:5601/index', function() { - it('defaults to the first matching timeout', function() { + describe('http://localhost:5601/index', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('http://localhost:5601/index')).to.be(3); }); }); - describe('https://localhost:5601/index/type', function() { - it('defaults to the first matching timeout', function() { + describe('https://localhost:5601/index/type', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('https://localhost:5601/index/type')).to.be(2); }); }); - describe('http://notlocalhost', function() { - it('defaults to the first matching timeout', function() { + describe('http://notlocalhost', function () { + it('defaults to the first matching timeout', function () { expect(getTimeout('http://notlocalhost')).to.be(5); }); }); - describe('collection with ssl config and root level verify:false', function() { + describe('collection with ssl config and root level verify:false', function () { function makeCollection() { return new ProxyConfigCollection([ { @@ -160,13 +160,13 @@ describe('ProxyConfigCollection', function() { ]); } - it('verifies for config that produces ssl agent', function() { + it('verifies for config that produces ssl agent', function () { const conf = makeCollection().configForUri('https://es.internal.org/_search'); expect(conf.agent.options).to.have.property('rejectUnauthorized', true); expect(conf.agent).to.be.an(HttpsAgent); }); - it('disabled verification for * config', function() { + it('disabled verification for * config', function () { const conf = makeCollection().configForUri('https://extenal.org/_search'); expect(conf).to.have.property('rejectUnauthorized', false); expect(conf.agent).to.be(undefined); diff --git a/src/plugins/console/server/__tests__/proxy_route/body.test.ts b/src/plugins/console/server/__tests__/proxy_route/body.test.ts index 252009a8977f3..526c2e4c78ea4 100644 --- a/src/plugins/console/server/__tests__/proxy_route/body.test.ts +++ b/src/plugins/console/server/__tests__/proxy_route/body.test.ts @@ -46,9 +46,9 @@ describe('Console Proxy Route', () => { }); const readStream = (s: Readable) => - new Promise(resolve => { + new Promise((resolve) => { let v = ''; - s.on('data', data => { + s.on('data', (data) => { v += data; }); s.on('end', () => resolve(v)); diff --git a/src/plugins/console/server/__tests__/set_headers.js b/src/plugins/console/server/__tests__/set_headers.js index 1f349cbbb571e..3ddd30777bb5b 100644 --- a/src/plugins/console/server/__tests__/set_headers.js +++ b/src/plugins/console/server/__tests__/set_headers.js @@ -20,18 +20,18 @@ import expect from '@kbn/expect'; import { setHeaders } from '../lib'; -describe('#set_headers', function() { - it('throws if not given an object as the first argument', function() { +describe('#set_headers', function () { + it('throws if not given an object as the first argument', function () { const fn = () => setHeaders(null, {}); expect(fn).to.throwError(); }); - it('throws if not given an object as the second argument', function() { + it('throws if not given an object as the second argument', function () { const fn = () => setHeaders({}, null); expect(fn).to.throwError(); }); - it('returns a new object', function() { + it('returns a new object', function () { const originalHeaders = {}; const newHeaders = {}; const returnedHeaders = setHeaders(originalHeaders, newHeaders); @@ -39,14 +39,14 @@ describe('#set_headers', function() { expect(returnedHeaders).not.to.be(newHeaders); }); - it('returns object with newHeaders merged with originalHeaders', function() { + it('returns object with newHeaders merged with originalHeaders', function () { const originalHeaders = { foo: 'bar' }; const newHeaders = { one: 'two' }; const returnedHeaders = setHeaders(originalHeaders, newHeaders); expect(returnedHeaders).to.eql({ foo: 'bar', one: 'two' }); }); - it('returns object where newHeaders takes precedence for any matching keys', function() { + it('returns object where newHeaders takes precedence for any matching keys', function () { const originalHeaders = { foo: 'bar' }; const newHeaders = { one: 'two', foo: 'notbar' }; const returnedHeaders = setHeaders(originalHeaders, newHeaders); diff --git a/src/plugins/console/server/__tests__/wildcard_matcher.js b/src/plugins/console/server/__tests__/wildcard_matcher.js index ccf68f3c16ca3..3e0e06efad50f 100644 --- a/src/plugins/console/server/__tests__/wildcard_matcher.js +++ b/src/plugins/console/server/__tests__/wildcard_matcher.js @@ -32,8 +32,8 @@ function shouldNot(candidate, ...constructorArgs) { } } -describe('WildcardMatcher', function() { - describe('pattern = *', function() { +describe('WildcardMatcher', function () { + describe('pattern = *', function () { it('matches http', () => should('http', '*')); it('matches https', () => should('https', '*')); it('matches nothing', () => should('', '*')); @@ -41,12 +41,12 @@ describe('WildcardMatcher', function() { it('matches localhost', () => should('localhost', '*')); it('matches a path', () => should('/index/_search', '*')); - describe('defaultValue = /', function() { + describe('defaultValue = /', function () { it('matches /', () => should('/', '*', '/')); }); }); - describe('pattern = http', function() { + describe('pattern = http', function () { it('matches http', () => should('http', 'http')); it('does not match https', () => shouldNot('https', 'http')); it('does not match nothing', () => shouldNot('', 'http')); @@ -54,7 +54,7 @@ describe('WildcardMatcher', function() { it('does not match a path', () => shouldNot('/index/_search', 'http')); }); - describe('pattern = 560{1..9}', function() { + describe('pattern = 560{1..9}', function () { it('does not match http', () => shouldNot('http', '560{1..9}')); it('does not matches 5600', () => shouldNot('5600', '560{1..9}')); it('matches 5601', () => should('5601', '560{1..9}')); diff --git a/src/plugins/console/server/lib/proxy_config_collection.ts b/src/plugins/console/server/lib/proxy_config_collection.ts index 5d0b02fed5b18..36f4f8359c5fe 100644 --- a/src/plugins/console/server/lib/proxy_config_collection.ts +++ b/src/plugins/console/server/lib/proxy_config_collection.ts @@ -26,7 +26,7 @@ export class ProxyConfigCollection { private configs: ProxyConfig[]; constructor(configs: Array<{ match: any; timeout: number }> = []) { - this.configs = configs.map(settings => new ProxyConfig(settings)); + this.configs = configs.map((settings) => new ProxyConfig(settings)); } hasConfig() { @@ -35,7 +35,7 @@ export class ProxyConfigCollection { configForUri(uri: string): object { const parsedUri = parseUrl(uri); - const settings = this.configs.map(config => config.getForParsedUri(parsedUri as any)); + const settings = this.configs.map((config) => config.getForParsedUri(parsedUri as any)); return defaultsDeep({}, ...settings); } } diff --git a/src/plugins/console/server/lib/proxy_request.ts b/src/plugins/console/server/lib/proxy_request.ts index cc957551e47a7..4c6c7c21f32a4 100644 --- a/src/plugins/console/server/lib/proxy_request.ts +++ b/src/plugins/console/server/lib/proxy_request.ts @@ -58,7 +58,7 @@ export const proxyRequest = ({ }); const finalUserHeaders = { ...headers }; - const hasHostHeader = Object.keys(finalUserHeaders).some(key => key.toLowerCase() === 'host'); + const hasHostHeader = Object.keys(finalUserHeaders).some((key) => key.toLowerCase() === 'host'); if (!hasHostHeader) { finalUserHeaders.host = hostname; } @@ -79,7 +79,7 @@ export const proxyRequest = ({ agent, }); - req.once('response', res => { + req.once('response', (res) => { resolved = true; resolve(res); }); diff --git a/src/plugins/console/server/lib/spec_definitions/js/mappings.ts b/src/plugins/console/server/lib/spec_definitions/js/mappings.ts index 8491bc17a2ff6..fbc9a822e509c 100644 --- a/src/plugins/console/server/lib/spec_definitions/js/mappings.ts +++ b/src/plugins/console/server/lib/spec_definitions/js/mappings.ts @@ -177,7 +177,7 @@ export const mappings = (specService: SpecDefinitionsService) => { 'week_date_time', 'week_date_time_no_millis', ], - function(s) { + function (s) { return ['basic_' + s, 'strict_' + s]; } ), diff --git a/src/plugins/console/server/plugin.ts b/src/plugins/console/server/plugin.ts index 85b728ea83891..eedd1541e8898 100644 --- a/src/plugins/console/server/plugin.ts +++ b/src/plugins/console/server/plugin.ts @@ -45,10 +45,7 @@ export class ConsoleServerPlugin implements Plugin { }, })); - const config = await this.ctx.config - .create() - .pipe(first()) - .toPromise(); + const config = await this.ctx.config.create().pipe(first()).toPromise(); const { elasticsearch } = await this.ctx.config.legacy.globalConfig$.pipe(first()).toPromise(); diff --git a/src/plugins/console/server/routes/api/console/proxy/create_handler.ts b/src/plugins/console/server/routes/api/console/proxy/create_handler.ts index 9446289ff03ea..272f63322ffaa 100644 --- a/src/plugins/console/server/routes/api/console/proxy/create_handler.ts +++ b/src/plugins/console/server/routes/api/console/proxy/create_handler.ts @@ -57,7 +57,7 @@ function toURL(base: string, path: string) { } function filterHeaders(originalHeaders: object, headersToKeep: string[]): object { - const normalizeHeader = function(header: any) { + const normalizeHeader = function (header: any) { if (!header) { return ''; } @@ -131,7 +131,7 @@ export const createHandler = ({ const { body, query } = request; const { path, method } = query; - if (!pathFilters.some(re => re.test(path))) { + if (!pathFilters.some((re) => re.test(path))) { return response.forbidden({ body: `Error connecting to '${path}':\n\nUnable to send requests to that path.`, headers: { diff --git a/src/plugins/console/server/routes/api/console/proxy/validation_config.ts b/src/plugins/console/server/routes/api/console/proxy/validation_config.ts index f2372e9ee80d0..c46fc5c808a42 100644 --- a/src/plugins/console/server/routes/api/console/proxy/validation_config.ts +++ b/src/plugins/console/server/routes/api/console/proxy/validation_config.ts @@ -22,9 +22,9 @@ export type Query = TypeOf; export type Body = TypeOf; const acceptedHttpVerb = schema.string({ - validate: method => { + validate: (method) => { return ['HEAD', 'GET', 'POST', 'PUT', 'DELETE'].some( - verb => verb.toLowerCase() === method.toLowerCase() + (verb) => verb.toLowerCase() === method.toLowerCase() ) ? undefined : `Method must be one of, case insensitive ['HEAD', 'GET', 'POST', 'PUT', 'DELETE']. Received '${method}'.`; @@ -32,7 +32,7 @@ const acceptedHttpVerb = schema.string({ }); const nonEmptyString = schema.string({ - validate: s => (s === '' ? 'Expected non-empty string' : undefined), + validate: (s) => (s === '' ? 'Expected non-empty string' : undefined), }); export const routeValidationConfig = { diff --git a/src/plugins/console/server/services/spec_definitions_service.ts b/src/plugins/console/server/services/spec_definitions_service.ts index 39a8d5094bd5c..ccd3b6b1c0a82 100644 --- a/src/plugins/console/server/services/spec_definitions_service.ts +++ b/src/plugins/console/server/services/spec_definitions_service.ts @@ -45,7 +45,7 @@ export class SpecDefinitionsService { copiedDescription = { ...this.endpoints[endpoint] }; } let urlParamsDef: any; - _.each(description.patterns || [], function(p) { + _.each(description.patterns || [], function (p) { if (p.indexOf('{indices}') >= 0) { urlParamsDef = urlParamsDef || {}; urlParamsDef.ignore_unavailable = '__flag__'; @@ -114,7 +114,7 @@ export class SpecDefinitionsService { const overrideFiles = glob.sync(join(dirname, 'overrides', '*.json')); return generatedFiles.reduce((acc, file) => { - const overrideFile = overrideFiles.find(f => basename(f) === basename(file)); + const overrideFile = overrideFiles.find((f) => basename(f) === basename(file)); const loadedSpec = JSON.parse(readFileSync(file, 'utf8')); if (overrideFile) { merge(loadedSpec, JSON.parse(readFileSync(overrideFile, 'utf8'))); @@ -135,16 +135,16 @@ export class SpecDefinitionsService { private loadJsonSpec() { const result = this.loadJSONSpecInDir(PATH_TO_OSS_JSON_SPEC); - this.extensionSpecFilePaths.forEach(extensionSpecFilePath => { + this.extensionSpecFilePaths.forEach((extensionSpecFilePath) => { merge(result, this.loadJSONSpecInDir(extensionSpecFilePath)); }); - Object.keys(result).forEach(endpoint => { + Object.keys(result).forEach((endpoint) => { this.addEndpointDescription(endpoint, result[endpoint]); }); } private loadJSSpec() { - jsSpecLoaders.forEach(addJsSpec => addJsSpec(this)); + jsSpecLoaders.forEach((addJsSpec) => addJsSpec(this)); } } diff --git a/src/plugins/dashboard/common/migrate_to_730_panels.test.ts b/src/plugins/dashboard/common/migrate_to_730_panels.test.ts index 0867909225ddb..f7a03a54376ca 100644 --- a/src/plugins/dashboard/common/migrate_to_730_panels.test.ts +++ b/src/plugins/dashboard/common/migrate_to_730_panels.test.ts @@ -134,7 +134,7 @@ test('6.0 migrates old panel data in the right order', () => { false, {} ) as SavedDashboardPanel730ToLatest[]; - const foo8Panel = newPanels.find(panel => panel.id === 'foo8'); + const foo8Panel = newPanels.find((panel) => panel.id === 'foo8'); expect(foo8Panel).toBeDefined(); expect((foo8Panel! as any).row).toBe(undefined); @@ -195,7 +195,7 @@ test('6.0 migrates old panel data in the right order without margins', () => { false, {} ) as SavedDashboardPanel730ToLatest[]; - const foo8Panel = newPanels.find(panel => panel.id === 'foo8'); + const foo8Panel = newPanels.find((panel) => panel.id === 'foo8'); expect(foo8Panel).toBeDefined(); expect((foo8Panel! as any).row).toBe(undefined); @@ -239,7 +239,7 @@ test('6.0 migrates old panel data in the right order with margins', () => { true, {} ) as SavedDashboardPanel730ToLatest[]; - const foo8Panel = newPanels.find(panel => panel.id === 'foo8'); + const foo8Panel = newPanels.find((panel) => panel.id === 'foo8'); expect(foo8Panel).toBeDefined(); expect((foo8Panel! as any).row).toBe(undefined); diff --git a/src/plugins/dashboard/common/migrate_to_730_panels.ts b/src/plugins/dashboard/common/migrate_to_730_panels.ts index b89345f0a872c..d870e3c87d6ab 100644 --- a/src/plugins/dashboard/common/migrate_to_730_panels.ts +++ b/src/plugins/dashboard/common/migrate_to_730_panels.ts @@ -150,7 +150,7 @@ function migrate610PanelToLatest( useMargins: boolean, uiState?: { [key: string]: { [key: string]: unknown } } ): RawSavedDashboardPanel730ToLatest { - (['w', 'x', 'h', 'y'] as Array).forEach(key => { + (['w', 'x', 'h', 'y'] as Array).forEach((key) => { if (panel.gridData[key] === undefined) { throw new Error( i18n.translate('dashboard.panel.unableToMigratePanelDataForSixThreeZeroErrorMessage', { @@ -285,7 +285,7 @@ export function migratePanelsTo730( useMargins: boolean, uiState?: { [key: string]: { [key: string]: unknown } } ): RawSavedDashboardPanel730ToLatest[] { - return panels.map(panel => { + return panels.map((panel) => { if (isPre61Panel(panel)) { return migratePre61PanelToLatest(panel, version, useMargins, uiState); } diff --git a/src/plugins/dashboard/public/application/actions/clone_panel_action.test.tsx b/src/plugins/dashboard/public/application/actions/clone_panel_action.test.tsx index 17943333d25b0..e7534fa09aa3f 100644 --- a/src/plugins/dashboard/public/application/actions/clone_panel_action.test.tsx +++ b/src/plugins/dashboard/public/application/actions/clone_panel_action.test.tsx @@ -96,7 +96,7 @@ test('Clone adds a new embeddable', async () => { await action.execute({ embeddable }); expect(Object.keys(container.getInput().panels).length).toEqual(originalPanelCount + 1); const newPanelId = Object.keys(container.getInput().panels).find( - key => !originalPanelKeySet.has(key) + (key) => !originalPanelKeySet.has(key) ); expect(newPanelId).toBeDefined(); const newPanel = container.getInput().panels[newPanelId!]; diff --git a/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx b/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx index ff4e50ba8c327..96210358c05e4 100644 --- a/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx +++ b/src/plugins/dashboard/public/application/actions/clone_panel_action.tsx @@ -97,10 +97,7 @@ export class ClonePanelAction implements ActionByType }); const cloneRegex = new RegExp(`\\(${clonedTag}\\)`, 'g'); const cloneNumberRegex = new RegExp(`\\(${clonedTag} [0-9]+\\)`, 'g'); - const baseTitle = rawTitle - .replace(cloneNumberRegex, '') - .replace(cloneRegex, '') - .trim(); + const baseTitle = rawTitle.replace(cloneNumberRegex, '').replace(cloneRegex, '').trim(); const similarSavedObjects = await this.core.savedObjects.client.find({ type: embeddableType, diff --git a/src/plugins/dashboard/public/application/actions/replace_panel_flyout.tsx b/src/plugins/dashboard/public/application/actions/replace_panel_flyout.tsx index fe9a19030602e..57fe4acf08145 100644 --- a/src/plugins/dashboard/public/application/actions/replace_panel_flyout.tsx +++ b/src/plugins/dashboard/public/application/actions/replace_panel_flyout.tsx @@ -107,7 +107,7 @@ export class ReplacePanelFlyout extends React.Component { })} savedObjectMetaData={[...this.props.getEmbeddableFactories()] .filter( - embeddableFactory => + (embeddableFactory) => Boolean(embeddableFactory.savedObjectMetaData) && !embeddableFactory.isContainerType ) .map(({ savedObjectMetaData }) => savedObjectMetaData as any)} diff --git a/src/plugins/dashboard/public/application/application.ts b/src/plugins/dashboard/public/application/application.ts index 8e29d2734065e..543450916c505 100644 --- a/src/plugins/dashboard/public/application/application.ts +++ b/src/plugins/dashboard/public/application/application.ts @@ -134,7 +134,7 @@ function createLocalAngularModule() { function createLocalIconModule() { angular .module('app/dashboard/icon', ['react']) - .directive('icon', reactDirective => reactDirective(EuiIcon)); + .directive('icon', (reactDirective) => reactDirective(EuiIcon)); } function createLocalI18nModule() { diff --git a/src/plugins/dashboard/public/application/dashboard_app_controller.tsx b/src/plugins/dashboard/public/application/dashboard_app_controller.tsx index fa2f06bfcdcdd..8dd0a766da97b 100644 --- a/src/plugins/dashboard/public/application/dashboard_app_controller.tsx +++ b/src/plugins/dashboard/public/application/dashboard_app_controller.tsx @@ -160,7 +160,7 @@ export class DashboardAppController { set: ({ filters }) => dashboardStateManager.setFilters(filters || []), get: () => ({ filters: dashboardStateManager.appState.filters }), state$: dashboardStateManager.appState$.pipe( - map(state => ({ + map((state) => ({ filters: state.filters, })) ), @@ -228,7 +228,7 @@ export class DashboardAppController { } let panelIndexPatterns: IndexPattern[] = []; - Object.values(container.getChildIds()).forEach(id => { + Object.values(container.getChildIds()).forEach((id) => { const embeddableInstance = container.getChild(id); if (isErrorEmbeddable(embeddableInstance)) return; const embeddableIndexPatterns = (embeddableInstance.getOutput() as any).indexPatterns; @@ -242,7 +242,7 @@ export class DashboardAppController { $scope.indexPatterns = panelIndexPatterns; }); } else { - indexPatterns.getDefault().then(defaultIndexPattern => { + indexPatterns.getDefault().then((defaultIndexPattern) => { $scope.$evalAsync(() => { $scope.indexPatterns = [defaultIndexPattern as IndexPattern]; }); @@ -421,7 +421,7 @@ export class DashboardAppController { dirty: !dash.id, }; - dashboardStateManager.registerChangeListener(status => { + dashboardStateManager.registerChangeListener((status) => { this.appStatus.dirty = status.dirty || !dash.id; updateState(); }); @@ -484,7 +484,7 @@ export class DashboardAppController { differences.filters = appStateDashboardInput.filters; } - Object.keys(_.omit(containerInput, 'filters')).forEach(key => { + Object.keys(_.omit(containerInput, 'filters')).forEach((key) => { const containerValue = (containerInput as { [key: string]: unknown })[key]; const appStateValue = ((appStateDashboardInput as unknown) as { [key: string]: unknown })[ key @@ -506,7 +506,7 @@ export class DashboardAppController { } }; - $scope.updateQueryAndFetch = function({ query, dateRange }) { + $scope.updateQueryAndFetch = function ({ query, dateRange }) { if (dateRange) { timefilter.setTime(dateRange); } @@ -554,7 +554,7 @@ export class DashboardAppController { () => { return dashboardStateManager.getSavedQueryId(); }, - newSavedQueryId => { + (newSavedQueryId) => { if (!newSavedQueryId) { $scope.savedQuery = undefined; return; @@ -579,7 +579,7 @@ export class DashboardAppController { $scope.$watch( () => dashboardCapabilities.saveQuery, - newCapability => { + (newCapability) => { $scope.showSaveQuery = newCapability as boolean; } ); @@ -712,7 +712,7 @@ export class DashboardAppController { }), } ) - .then(isConfirmed => { + .then((isConfirmed) => { if (isConfirmed) { revertChangesAndExitEditMode(); } @@ -735,7 +735,7 @@ export class DashboardAppController { */ function save(saveOptions: SavedObjectSaveOpts): Promise { return saveDashboard(angular.toJson, timefilter, dashboardStateManager, saveOptions) - .then(function(id) { + .then(function (id) { if (id) { notifications.toasts.addSuccess({ title: i18n.translate('dashboard.dashboardWasSavedSuccessMessage', { @@ -758,7 +758,7 @@ export class DashboardAppController { } return { id }; }) - .catch(error => { + .catch((error) => { notifications.toasts.addDanger({ title: i18n.translate('dashboard.dashboardWasNotSavedDangerMessage', { defaultMessage: `Dashboard '{dashTitle}' was not saved. Error: {errorMessage}`, @@ -904,7 +904,7 @@ export class DashboardAppController { } }; - navActions[TopNavIds.OPTIONS] = anchorElement => { + navActions[TopNavIds.OPTIONS] = (anchorElement) => { showOptionsPopover({ anchorElement, useMargins: dashboardStateManager.getUseMargins(), @@ -920,7 +920,7 @@ export class DashboardAppController { if (share) { // the share button is only availabale if "share" plugin contract enabled - navActions[TopNavIds.SHARE] = anchorElement => { + navActions[TopNavIds.SHARE] = (anchorElement) => { share.toggleShareContextMenu({ anchorElement, allowEmbed: true, @@ -950,7 +950,7 @@ export class DashboardAppController { }, }); - const visibleSubscription = chrome.getIsVisible$().subscribe(isVisible => { + const visibleSubscription = chrome.getIsVisible$().subscribe((isVisible) => { $scope.$evalAsync(() => { $scope.isVisible = isVisible; showSearchBar = isVisible || showFilterBar(); diff --git a/src/plugins/dashboard/public/application/dashboard_state.test.ts b/src/plugins/dashboard/public/application/dashboard_state.test.ts index cfb7fc7e56e42..e32bb9b9ecabe 100644 --- a/src/plugins/dashboard/public/application/dashboard_state.test.ts +++ b/src/plugins/dashboard/public/application/dashboard_state.test.ts @@ -24,7 +24,7 @@ import { InputTimeRange, TimefilterContract, TimeRange } from 'src/plugins/data/ import { ViewMode } from 'src/plugins/embeddable/public'; import { createKbnUrlStateStorage } from 'src/plugins/kibana_utils/public'; -describe('DashboardState', function() { +describe('DashboardState', function () { let dashboardState: DashboardStateManager; const savedDashboard = getSavedDashboardMock(); @@ -48,8 +48,8 @@ describe('DashboardState', function() { }); } - describe('syncTimefilterWithDashboard', function() { - test('syncs quick time', function() { + describe('syncTimefilterWithDashboard', function () { + test('syncs quick time', function () { savedDashboard.timeRestore = true; savedDashboard.timeFrom = 'now/w'; savedDashboard.timeTo = 'now/w'; @@ -64,7 +64,7 @@ describe('DashboardState', function() { expect(mockTime.from).toBe('now/w'); }); - test('syncs relative time', function() { + test('syncs relative time', function () { savedDashboard.timeRestore = true; savedDashboard.timeFrom = 'now-13d'; savedDashboard.timeTo = 'now'; @@ -79,7 +79,7 @@ describe('DashboardState', function() { expect(mockTime.from).toBe('now-13d'); }); - test('syncs absolute time', function() { + test('syncs absolute time', function () { savedDashboard.timeRestore = true; savedDashboard.timeFrom = '2015-09-19 06:31:44.000'; savedDashboard.timeTo = '2015-09-29 06:31:44.000'; @@ -95,7 +95,7 @@ describe('DashboardState', function() { }); }); - describe('isDirty', function() { + describe('isDirty', function () { beforeAll(() => { initDashboardState(); }); diff --git a/src/plugins/dashboard/public/application/dashboard_state_manager.ts b/src/plugins/dashboard/public/application/dashboard_state_manager.ts index b03ea95069a3d..5fed38487dc54 100644 --- a/src/plugins/dashboard/public/application/dashboard_state_manager.ts +++ b/src/plugins/dashboard/public/application/dashboard_state_manager.ts @@ -139,8 +139,8 @@ export class DashboardStateManager { this.stateContainer = createStateContainer( initialState, { - set: state => (prop, value) => ({ ...state, [prop]: value }), - setOption: state => (option, value) => ({ + set: (state) => (prop, value) => ({ ...state, [prop]: value }), + setOption: (state) => (option, value) => ({ ...state, options: { ...state.options, @@ -162,7 +162,7 @@ export class DashboardStateManager { this.stateContainerChangeSub = this.stateContainer.state$.subscribe(() => { this.isDirty = this.checkIsDirty(); - this.changeListeners.forEach(listener => listener({ dirty: this.isDirty })); + this.changeListeners.forEach((listener) => listener({ dirty: this.isDirty })); }); // setup state syncing utils. state container will be synced with url into `this.STATE_STORAGE_KEY` query param @@ -218,7 +218,7 @@ export class DashboardStateManager { const savedDashboardPanelMap: { [key: string]: SavedDashboardPanel } = {}; const input = dashboardContainer.getInput(); - this.getPanels().forEach(savedDashboardPanel => { + this.getPanels().forEach((savedDashboardPanel) => { if (input.panels[savedDashboardPanel.panelIndex] !== undefined) { savedDashboardPanelMap[savedDashboardPanel.panelIndex] = savedDashboardPanel; } else { @@ -229,7 +229,7 @@ export class DashboardStateManager { const convertedPanelStateMap: { [key: string]: SavedDashboardPanel } = {}; - Object.values(input.panels).forEach(panelState => { + Object.values(input.panels).forEach((panelState) => { if (savedDashboardPanelMap[panelState.explicitInput.id] === undefined) { dirty = true; } @@ -271,7 +271,7 @@ export class DashboardStateManager { this.setQuery(input.query); } - this.changeListeners.forEach(listener => listener({ dirty })); + this.changeListeners.forEach((listener) => listener({ dirty })); } public getFullScreenMode() { diff --git a/src/plugins/dashboard/public/application/embeddable/dashboard_container.test.tsx b/src/plugins/dashboard/public/application/embeddable/dashboard_container.test.tsx index 6785a373c065b..3cebe2b847155 100644 --- a/src/plugins/dashboard/public/application/embeddable/dashboard_container.test.tsx +++ b/src/plugins/dashboard/public/application/embeddable/dashboard_container.test.tsx @@ -53,7 +53,7 @@ beforeEach(() => { options.embeddable = doStart(); }); -test('DashboardContainer initializes embeddables', async done => { +test('DashboardContainer initializes embeddables', async (done) => { const initialInput = getSampleDashboardInput({ panels: { '123': getSampleDashboardPanel({ @@ -64,7 +64,7 @@ test('DashboardContainer initializes embeddables', async done => { }); const container = new DashboardContainer(initialInput, options); - const subscription = container.getOutput$().subscribe(output => { + const subscription = container.getOutput$().subscribe((output) => { if (container.getOutput().embeddableLoaded['123']) { const embeddable = container.getChild('123'); expect(embeddable).toBeDefined(); diff --git a/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.test.tsx b/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.test.tsx index 948e22e86a302..9b7cec2f182ba 100644 --- a/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.test.tsx +++ b/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.test.tsx @@ -167,7 +167,7 @@ test('DashboardGrid renders expanded panel', () => { ).toBeUndefined(); }); -test('DashboardGrid unmount unsubscribes', async done => { +test('DashboardGrid unmount unsubscribes', async (done) => { const { props, options } = prepare(); const component = mountWithIntl( diff --git a/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.tsx b/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.tsx index f8632011002d0..19d9ad34e729c 100644 --- a/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.tsx +++ b/src/plugins/dashboard/public/application/embeddable/grid/dashboard_grid.tsx @@ -199,7 +199,7 @@ class DashboardGridUi extends React.Component { } public buildLayoutFromPanels = (): GridData[] => { - return _.map(this.state.panels, panel => { + return _.map(this.state.panels, (panel) => { return panel.gridData; }); }; @@ -250,7 +250,7 @@ class DashboardGridUi extends React.Component { } }); - return _.map(panelsInOrder, panel => { + return _.map(panelsInOrder, (panel) => { const expandPanel = expandedPanelId !== undefined && expandedPanelId === panel.explicitInput.id; const hidePanel = expandedPanelId !== undefined && expandedPanelId !== panel.explicitInput.id; @@ -264,7 +264,7 @@ class DashboardGridUi extends React.Component { className={classes} key={panel.explicitInput.id} data-test-subj="dashboardPanel" - ref={reactGridItem => { + ref={(reactGridItem) => { this.gridItems[panel.explicitInput.id] = reactGridItem; }} > diff --git a/src/plugins/dashboard/public/application/embeddable/panel/dashboard_panel_placement.ts b/src/plugins/dashboard/public/application/embeddable/panel/dashboard_panel_placement.ts index b95b7f394a27d..62a39ee898d3a 100644 --- a/src/plugins/dashboard/public/application/embeddable/panel/dashboard_panel_placement.ts +++ b/src/plugins/dashboard/public/application/embeddable/panel/dashboard_panel_placement.ts @@ -44,7 +44,7 @@ export function findTopLeftMostOpenSpace({ let maxY = -1; const currentPanelsArray = Object.values(currentPanels); - currentPanelsArray.forEach(panel => { + currentPanelsArray.forEach((panel) => { maxY = Math.max(panel.gridData.y + panel.gridData.h, maxY); }); @@ -58,7 +58,7 @@ export function findTopLeftMostOpenSpace({ grid[y] = new Array(DASHBOARD_GRID_COLUMN_COUNT).fill(0); } - currentPanelsArray.forEach(panel => { + currentPanelsArray.forEach((panel) => { for (let x = panel.gridData.x; x < panel.gridData.x + panel.gridData.w; x++) { for (let y = panel.gridData.y; y < panel.gridData.y + panel.gridData.h; y++) { const row = grid[y]; diff --git a/src/plugins/dashboard/public/application/embeddable/viewport/dashboard_viewport.test.tsx b/src/plugins/dashboard/public/application/embeddable/viewport/dashboard_viewport.test.tsx index b3fc462fd1c50..1b257880b9401 100644 --- a/src/plugins/dashboard/public/application/embeddable/viewport/dashboard_viewport.test.tsx +++ b/src/plugins/dashboard/public/application/embeddable/viewport/dashboard_viewport.test.tsx @@ -153,23 +153,17 @@ test('renders exit full screen button when in full screen mode', async () => { ); - expect( - (component - .find('.dshDashboardViewport') - .childAt(0) - .type() as any).name - ).toBe('ExitFullScreenButton'); + expect((component.find('.dshDashboardViewport').childAt(0).type() as any).name).toBe( + 'ExitFullScreenButton' + ); props.container.updateInput({ isFullScreenMode: false }); component.update(); await nextTick(); - expect( - (component - .find('.dshDashboardViewport') - .childAt(0) - .type() as any).name - ).not.toBe('ExitFullScreenButton'); + expect((component.find('.dshDashboardViewport').childAt(0).type() as any).name).not.toBe( + 'ExitFullScreenButton' + ); component.unmount(); }); @@ -186,28 +180,22 @@ test('renders exit full screen button when in full screen mode and empty screen' ); - expect( - (component - .find('.dshDashboardEmptyScreen') - .childAt(0) - .type() as any).name - ).toBe('ExitFullScreenButton'); + expect((component.find('.dshDashboardEmptyScreen').childAt(0).type() as any).name).toBe( + 'ExitFullScreenButton' + ); props.container.updateInput({ isFullScreenMode: false }); component.update(); await nextTick(); - expect( - (component - .find('.dshDashboardEmptyScreen') - .childAt(0) - .type() as any).name - ).not.toBe('ExitFullScreenButton'); + expect((component.find('.dshDashboardEmptyScreen').childAt(0).type() as any).name).not.toBe( + 'ExitFullScreenButton' + ); component.unmount(); }); -test('DashboardViewport unmount unsubscribes', async done => { +test('DashboardViewport unmount unsubscribes', async (done) => { const { props, options } = getProps(); const component = mount( diff --git a/src/plugins/dashboard/public/application/legacy_app.js b/src/plugins/dashboard/public/application/legacy_app.js index 4e3cc15d93ece..2d99a2c6a2253 100644 --- a/src/plugins/dashboard/public/application/legacy_app.js +++ b/src/plugins/dashboard/public/application/legacy_app.js @@ -38,7 +38,7 @@ import { syncQueryStateWithUrl } from '../../../data/public'; export function initDashboardApp(app, deps) { initDashboardAppDirective(app, deps); - app.directive('dashboardListing', function(reactDirective) { + app.directive('dashboardListing', function (reactDirective) { return reactDirective(DashboardListing, [ ['core', { watchDepth: 'reference' }], ['createItem', { watchDepth: 'reference' }], @@ -61,14 +61,14 @@ export function initDashboardApp(app, deps) { } app.factory('history', () => createHashHistory()); - app.factory('kbnUrlStateStorage', history => + app.factory('kbnUrlStateStorage', (history) => createKbnUrlStateStorage({ history, useHash: deps.uiSettings.get('state:storeInSessionStorage'), }) ); - app.config(function($routeProvider) { + app.config(function ($routeProvider) { const defaults = { reloadOnSearch: false, requireUICapability: 'dashboard.show', @@ -96,7 +96,7 @@ export function initDashboardApp(app, deps) { .when(DashboardConstants.LANDING_PAGE_PATH, { ...defaults, template: dashboardListingTemplate, - controller: function($scope, kbnUrlStateStorage, history) { + controller: function ($scope, kbnUrlStateStorage, history) { deps.core.chrome.docTitle.change( i18n.translate('dashboard.dashboardPageTitle', { defaultMessage: 'Dashboards' }) ); @@ -114,7 +114,7 @@ export function initDashboardApp(app, deps) { $scope.create = () => { history.push(DashboardConstants.CREATE_NEW_DASHBOARD_URL); }; - $scope.find = search => { + $scope.find = (search) => { return service.find(search, $scope.listingLimit); }; $scope.editItem = ({ id }) => { @@ -123,8 +123,8 @@ export function initDashboardApp(app, deps) { $scope.getViewUrl = ({ id }) => { return deps.addBasePath(`#${createDashboardEditUrl(id)}`); }; - $scope.delete = dashboards => { - return service.delete(dashboards.map(d => d.id)); + $scope.delete = (dashboards) => { + return service.delete(dashboards.map((d) => d.id)); }; $scope.hideWriteControls = dashboardConfig.getHideWriteControls(); $scope.initialFilter = parse(history.location.search).filter || EMPTY_FILTER; @@ -143,7 +143,7 @@ export function initDashboardApp(app, deps) { }); }, resolve: { - dash: function($route, history) { + dash: function ($route, history) { return deps.data.indexPatterns.ensureDefaultIndexPattern(history).then(() => { const savedObjectsClient = deps.savedObjectsClient; const title = $route.current.params.title; @@ -154,10 +154,11 @@ export function initDashboardApp(app, deps) { search_fields: 'title', type: 'dashboard', }) - .then(results => { + .then((results) => { // The search isn't an exact match, lets see if we can find a single exact match to use const matchingDashboards = results.savedObjects.filter( - dashboard => dashboard.attributes.title.toLowerCase() === title.toLowerCase() + (dashboard) => + dashboard.attributes.title.toLowerCase() === title.toLowerCase() ); if (matchingDashboards.length === 1) { history.replace(createDashboardEditUrl(matchingDashboards[0].id)); @@ -178,7 +179,7 @@ export function initDashboardApp(app, deps) { controller: createNewDashboardCtrl, requireUICapability: 'dashboard.createNew', resolve: { - dash: history => + dash: (history) => deps.data.indexPatterns .ensureDefaultIndexPattern(history) .then(() => deps.savedDashboards.get()) @@ -199,13 +200,13 @@ export function initDashboardApp(app, deps) { template: dashboardTemplate, controller: createNewDashboardCtrl, resolve: { - dash: function($route, history) { + dash: function ($route, history) { const id = $route.current.params.id; return deps.data.indexPatterns .ensureDefaultIndexPattern(history) .then(() => deps.savedDashboards.get(id)) - .then(savedDashboard => { + .then((savedDashboard) => { deps.chrome.recentlyAccessed.add( savedDashboard.getFullPath(), savedDashboard.title, @@ -213,7 +214,7 @@ export function initDashboardApp(app, deps) { ); return savedDashboard; }) - .catch(error => { + .catch((error) => { // Preserve BWC of v5.3.0 links for new, unsaved dashboards. // See https://github.com/elastic/kibana/issues/10951 for more context. if (error instanceof SavedObjectNotFound && id === 'create') { @@ -242,7 +243,7 @@ export function initDashboardApp(app, deps) { }) .otherwise({ template: '', - controller: function() { + controller: function () { deps.navigateToDefaultApp(); }, }); diff --git a/src/plugins/dashboard/public/application/lib/filter_utils.ts b/src/plugins/dashboard/public/application/lib/filter_utils.ts index 775bf90643a21..b6b935d6050ae 100644 --- a/src/plugins/dashboard/public/application/lib/filter_utils.ts +++ b/src/plugins/dashboard/public/application/lib/filter_utils.ts @@ -37,9 +37,7 @@ export class FilterUtils { */ public static convertTimeToUTCString(time?: string | Moment): undefined | string { if (moment(time).isValid()) { - return moment(time) - .utc() - .format('YYYY-MM-DDTHH:mm:ss.SSS[Z]'); + return moment(time).utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]'); } else { // If it's not a valid moment date, then it should be a string representing a relative time // like 'now' or 'now-15m'. @@ -66,7 +64,7 @@ export class FilterUtils { * @returns {Array.} */ public static cleanFiltersForComparison(filters: Filter[]) { - return _.map(filters, filter => { + return _.map(filters, (filter) => { const f: Partial = _.omit(filter, ['$$hashKey', '$state']); if (f.meta) { // f.meta.value is the value displayed in the filter bar. diff --git a/src/plugins/dashboard/public/application/lib/migrate_app_state.ts b/src/plugins/dashboard/public/application/lib/migrate_app_state.ts index f4d97578adebf..6632eafc51f30 100644 --- a/src/plugins/dashboard/public/application/lib/migrate_app_state.ts +++ b/src/plugins/dashboard/public/application/lib/migrate_app_state.ts @@ -58,7 +58,7 @@ export function migrateAppState( | SavedDashboardPanel630 | SavedDashboardPanel640To720 | SavedDashboardPanel730ToLatest - >).some(panel => { + >).some((panel) => { if ((panel as { version?: string }).version === undefined) return true; const version = (panel as SavedDashboardPanel730ToLatest).version; diff --git a/src/plugins/dashboard/public/application/lib/update_saved_dashboard.ts b/src/plugins/dashboard/public/application/lib/update_saved_dashboard.ts index fc519327b41ee..e3b6725ce7449 100644 --- a/src/plugins/dashboard/public/application/lib/update_saved_dashboard.ts +++ b/src/plugins/dashboard/public/application/lib/update_saved_dashboard.ts @@ -53,6 +53,6 @@ export function updateSavedDashboard( // save only unpinned filters const unpinnedFilters = savedDashboard .getFilters() - .filter(filter => !esFilters.isFilterPinned(filter)); + .filter((filter) => !esFilters.isFilterPinned(filter)); savedDashboard.searchSource.setField('filter', unpinnedFilters); } diff --git a/src/plugins/dashboard/public/application/listing/dashboard_listing.test.js b/src/plugins/dashboard/public/application/listing/dashboard_listing.test.js index 0cdefff6a738e..dccac4e7c3c76 100644 --- a/src/plugins/dashboard/public/application/listing/dashboard_listing.test.js +++ b/src/plugins/dashboard/public/application/listing/dashboard_listing.test.js @@ -22,7 +22,7 @@ jest.mock( () => ({ ...require.requireActual('lodash'), // mock debounce to fire immediately with no internal timer - debounce: func => { + debounce: (func) => { function debounced(...args) { return func.apply(this, args); } @@ -37,7 +37,7 @@ import { shallow } from 'enzyme'; import { DashboardListing } from './dashboard_listing'; -const find = num => { +const find = (num) => { const hits = []; for (let i = 0; i < num; i++) { hits.push({ @@ -85,7 +85,7 @@ describe('after fetch', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -107,7 +107,7 @@ describe('after fetch', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -129,7 +129,7 @@ describe('after fetch', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -151,7 +151,7 @@ describe('after fetch', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -173,7 +173,7 @@ describe('after fetch', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/src/plugins/dashboard/public/plugin.tsx b/src/plugins/dashboard/public/plugin.tsx index b4419adfe58da..08740b21f39a4 100644 --- a/src/plugins/dashboard/public/plugin.tsx +++ b/src/plugins/dashboard/public/plugin.tsx @@ -174,7 +174,7 @@ export class DashboardPlugin }, []); }; - const ExitFullScreenButton: React.FC = props => { + const ExitFullScreenButton: React.FC = (props) => { useHideChrome(); return ; }; @@ -290,7 +290,7 @@ export class DashboardPlugin kibanaLegacy.forwardApp( DashboardConstants.DASHBOARD_ID, DashboardConstants.DASHBOARDS_ID, - path => { + (path) => { const [, id, tail] = /dashboard\/?(.*?)($|\?.*)/.exec(path) || []; if (!id && !tail) { // unrecognized sub url @@ -307,7 +307,7 @@ export class DashboardPlugin kibanaLegacy.forwardApp( DashboardConstants.DASHBOARDS_ID, DashboardConstants.DASHBOARDS_ID, - path => { + (path) => { const [, tail] = /(\?.*)/.exec(path) || []; // carry over query if it exists return `#/list${tail || ''}`; diff --git a/src/plugins/dashboard/public/saved_dashboards/saved_dashboard_references.ts b/src/plugins/dashboard/public/saved_dashboards/saved_dashboard_references.ts index 3e49b6636f562..3df9e64887725 100644 --- a/src/plugins/dashboard/public/saved_dashboards/saved_dashboard_references.ts +++ b/src/plugins/dashboard/public/saved_dashboards/saved_dashboard_references.ts @@ -70,11 +70,11 @@ export function injectReferences( if (!Array.isArray(panels)) { return; } - panels.forEach(panel => { + panels.forEach((panel) => { if (!panel.panelRefName) { return; } - const reference = references.find(ref => ref.name === panel.panelRefName); + const reference = references.find((ref) => ref.name === panel.panelRefName); if (!reference) { // Throw an error since "panelRefName" means the reference exists within // "references" and in this scenario we have bad data. diff --git a/src/plugins/dashboard/public/url_generator.ts b/src/plugins/dashboard/public/url_generator.ts index 08ba6a6ca921d..d6805b2d94119 100644 --- a/src/plugins/dashboard/public/url_generator.ts +++ b/src/plugins/dashboard/public/url_generator.ts @@ -83,7 +83,7 @@ export const createDashboardUrlGenerator = ( }> ): UrlGeneratorsDefinition => ({ id: DASHBOARD_APP_URL_GENERATOR, - createUrl: async state => { + createUrl: async (state) => { const startServices = await getStartServices(); const useHash = state.useHash ?? startServices.useHashedUrl; const appBasePath = startServices.appBasePath; @@ -103,7 +103,7 @@ export const createDashboardUrlGenerator = ( }; const cleanEmptyKeys = (stateObj: Record) => { - Object.keys(stateObj).forEach(key => { + Object.keys(stateObj).forEach((key) => { if (stateObj[key] === undefined) { delete stateObj[key]; } @@ -122,7 +122,7 @@ export const createDashboardUrlGenerator = ( STATE_STORAGE_KEY, cleanEmptyKeys({ query: state.query, - filters: filters?.filter(f => !esFilters.isFilterPinned(f)), + filters: filters?.filter((f) => !esFilters.isFilterPinned(f)), }), { useHash }, `${appBasePath}#/${hash}` @@ -132,7 +132,7 @@ export const createDashboardUrlGenerator = ( GLOBAL_STATE_STORAGE_KEY, cleanEmptyKeys({ time: state.timeRange, - filters: filters?.filter(f => esFilters.isFilterPinned(f)), + filters: filters?.filter((f) => esFilters.isFilterPinned(f)), refreshInterval: state.refreshInterval, }), { useHash }, diff --git a/src/plugins/dashboard/server/saved_objects/migrate_match_all_query.ts b/src/plugins/dashboard/server/saved_objects/migrate_match_all_query.ts index db2fbeb278802..75e169b79f320 100644 --- a/src/plugins/dashboard/server/saved_objects/migrate_match_all_query.ts +++ b/src/plugins/dashboard/server/saved_objects/migrate_match_all_query.ts @@ -21,7 +21,7 @@ import { SavedObjectMigrationFn } from 'kibana/server'; import { get } from 'lodash'; import { DEFAULT_QUERY_LANGUAGE } from '../../../data/common'; -export const migrateMatchAllQuery: SavedObjectMigrationFn = doc => { +export const migrateMatchAllQuery: SavedObjectMigrationFn = (doc) => { const searchSourceJSON = get(doc, 'attributes.kibanaSavedObjectMeta.searchSourceJSON'); if (searchSourceJSON) { diff --git a/src/plugins/dashboard/server/saved_objects/move_filters_to_query.ts b/src/plugins/dashboard/server/saved_objects/move_filters_to_query.ts index 01a66445e4fc2..071568831d835 100644 --- a/src/plugins/dashboard/server/saved_objects/move_filters_to_query.ts +++ b/src/plugins/dashboard/server/saved_objects/move_filters_to_query.ts @@ -61,7 +61,7 @@ export function moveFiltersToQuery( searchSource.filter = []; } - searchSource.filter.forEach(filter => { + searchSource.filter.forEach((filter) => { if (isQueryFilter(filter)) { searchSource730.query = { query: filter.query.query_string ? filter.query.query_string.query : '', diff --git a/src/plugins/data/common/es_query/es_query/build_es_query.ts b/src/plugins/data/common/es_query/es_query/build_es_query.ts index e4f5f1f9e216c..66d44f5e0747f 100644 --- a/src/plugins/data/common/es_query/es_query/build_es_query.ts +++ b/src/plugins/data/common/es_query/es_query/build_es_query.ts @@ -53,7 +53,7 @@ export function buildEsQuery( queries = Array.isArray(queries) ? queries : [queries]; filters = Array.isArray(filters) ? filters : [filters]; - const validQueries = queries.filter(query => has(query, 'query')); + const validQueries = queries.filter((query) => has(query, 'query')); const queriesByLanguage = groupBy(validQueries, 'language'); const kueryQuery = buildQueryFromKuery( indexPattern, diff --git a/src/plugins/data/common/es_query/es_query/from_filters.ts b/src/plugins/data/common/es_query/es_query/from_filters.ts index ed91d391fc1fd..d2d52efedd085 100644 --- a/src/plugins/data/common/es_query/es_query/from_filters.ts +++ b/src/plugins/data/common/es_query/es_query/from_filters.ts @@ -58,16 +58,18 @@ export const buildQueryFromFilters = ( indexPattern: IIndexPattern | undefined, ignoreFilterIfFieldNotInIndex: boolean = false ) => { - filters = filters.filter(filter => filter && !isFilterDisabled(filter)); + filters = filters.filter((filter) => filter && !isFilterDisabled(filter)); const filtersToESQueries = (negate: boolean) => { return filters .filter(filterNegate(negate)) - .filter(filter => !ignoreFilterIfFieldNotInIndex || filterMatchesIndex(filter, indexPattern)) - .map(filter => { + .filter( + (filter) => !ignoreFilterIfFieldNotInIndex || filterMatchesIndex(filter, indexPattern) + ) + .map((filter) => { return migrateFilter(filter, indexPattern); }) - .map(filter => handleNestedFilter(filter, indexPattern)) + .map((filter) => handleNestedFilter(filter, indexPattern)) .map(translateToQuery) .map(cleanFilter); }; diff --git a/src/plugins/data/common/es_query/es_query/from_kuery.test.ts b/src/plugins/data/common/es_query/es_query/from_kuery.test.ts index 4574cd5ffd0cb..7ddd4dee743c5 100644 --- a/src/plugins/data/common/es_query/es_query/from_kuery.test.ts +++ b/src/plugins/data/common/es_query/es_query/from_kuery.test.ts @@ -46,7 +46,7 @@ describe('build query', () => { { query: 'machine.os:osx', language: 'kuery' }, ] as Query[]; - const expectedESQueries = queries.map(query => { + const expectedESQueries = queries.map((query) => { return toElasticsearchQuery(fromKueryExpression(query.query), indexPattern); }); @@ -57,7 +57,7 @@ describe('build query', () => { test("should accept a specific date format for a kuery query into an ES query in the bool's filter clause", () => { const queries = [{ query: '@timestamp:"2018-04-03T19:04:17"', language: 'kuery' }] as Query[]; - const expectedESQueries = queries.map(query => { + const expectedESQueries = queries.map((query) => { return toElasticsearchQuery(fromKueryExpression(query.query), indexPattern, { dateFormatTZ: 'America/Phoenix', }); @@ -72,7 +72,7 @@ describe('build query', () => { const queries = [ { query: '@timestamp:"2018-04-03T19:04:17Z"', language: 'kuery' }, ] as Query[]; - const expectedESQueries = queries.map(query => { + const expectedESQueries = queries.map((query) => { return toElasticsearchQuery(fromKueryExpression(query.query), indexPattern); }); diff --git a/src/plugins/data/common/es_query/es_query/from_kuery.ts b/src/plugins/data/common/es_query/es_query/from_kuery.ts index f4ec0fe0b34c5..8af319704067b 100644 --- a/src/plugins/data/common/es_query/es_query/from_kuery.ts +++ b/src/plugins/data/common/es_query/es_query/from_kuery.ts @@ -27,7 +27,7 @@ export function buildQueryFromKuery( allowLeadingWildcards: boolean = false, dateFormatTZ?: string ) { - const queryASTs = queries.map(query => { + const queryASTs = queries.map((query) => { return fromKueryExpression(query.query, { allowLeadingWildcards }); }); diff --git a/src/plugins/data/common/es_query/es_query/from_lucene.test.ts b/src/plugins/data/common/es_query/es_query/from_lucene.test.ts index fc85404a5060c..53edeec37e0b3 100644 --- a/src/plugins/data/common/es_query/es_query/from_lucene.test.ts +++ b/src/plugins/data/common/es_query/es_query/from_lucene.test.ts @@ -41,7 +41,7 @@ describe('build query', () => { { query: 'foo:bar', language: 'lucene' }, { query: 'bar:baz', language: 'lucene' }, ] as unknown) as Query[]; - const expectedESQueries = queries.map(query => { + const expectedESQueries = queries.map((query) => { return decorateQuery(luceneStringToDsl(query.query), {}); }); @@ -64,7 +64,7 @@ describe('build query', () => { { query: 'bar:baz', language: 'lucene' }, ] as unknown) as Query[]; const dateFormatTZ = 'America/Phoenix'; - const expectedESQueries = queries.map(query => { + const expectedESQueries = queries.map((query) => { return decorateQuery(luceneStringToDsl(query.query), {}, dateFormatTZ); }); const result = buildQueryFromLucene(queries, {}, dateFormatTZ); diff --git a/src/plugins/data/common/es_query/es_query/from_lucene.ts b/src/plugins/data/common/es_query/es_query/from_lucene.ts index 8babb6df4fba5..18c2b24872e32 100644 --- a/src/plugins/data/common/es_query/es_query/from_lucene.ts +++ b/src/plugins/data/common/es_query/es_query/from_lucene.ts @@ -25,7 +25,7 @@ export function buildQueryFromLucene( queryStringOptions: Record, dateFormatTZ?: string ) { - const combinedQueries = (queries || []).map(query => { + const combinedQueries = (queries || []).map((query) => { const queryDsl = luceneStringToDsl(query.query); return decorateQuery(queryDsl, queryStringOptions, dateFormatTZ); diff --git a/src/plugins/data/common/es_query/es_query/handle_nested_filter.test.ts b/src/plugins/data/common/es_query/es_query/handle_nested_filter.test.ts index 594b2641c39be..ad1ad34741d20 100644 --- a/src/plugins/data/common/es_query/es_query/handle_nested_filter.test.ts +++ b/src/plugins/data/common/es_query/es_query/handle_nested_filter.test.ts @@ -22,7 +22,7 @@ import { fields } from '../../index_patterns/mocks'; import { buildPhraseFilter, buildQueryFilter } from '../filters'; import { IFieldType, IIndexPattern } from '../../index_patterns'; -describe('handleNestedFilter', function() { +describe('handleNestedFilter', function () { const indexPattern: IIndexPattern = ({ id: 'logstash-*', fields, @@ -86,6 +86,6 @@ describe('handleNestedFilter', function() { }); function getField(name: string) { - return indexPattern.fields.find(field => field.name === name); + return indexPattern.fields.find((field) => field.name === name); } }); diff --git a/src/plugins/data/common/es_query/es_query/handle_nested_filter.ts b/src/plugins/data/common/es_query/es_query/handle_nested_filter.ts index 27be7925fe00c..a0f4abb514b22 100644 --- a/src/plugins/data/common/es_query/es_query/handle_nested_filter.ts +++ b/src/plugins/data/common/es_query/es_query/handle_nested_filter.ts @@ -28,7 +28,9 @@ export const handleNestedFilter = (filter: Filter, indexPattern?: IIndexPattern) return filter; } - const field = indexPattern.fields.find(indexPatternField => indexPatternField.name === fieldName); + const field = indexPattern.fields.find( + (indexPatternField) => indexPatternField.name === fieldName + ); if (!field || !field.subType || !field.subType.nested || !field.subType.nested.path) { return filter; } diff --git a/src/plugins/data/common/es_query/es_query/migrate_filter.test.ts b/src/plugins/data/common/es_query/es_query/migrate_filter.test.ts index 698d7bb48e685..ae9d1c7921955 100644 --- a/src/plugins/data/common/es_query/es_query/migrate_filter.test.ts +++ b/src/plugins/data/common/es_query/es_query/migrate_filter.test.ts @@ -21,7 +21,7 @@ import { isEqual, clone } from 'lodash'; import { migrateFilter, DeprecatedMatchPhraseFilter } from './migrate_filter'; import { PhraseFilter, MatchAllFilter } from '../filters'; -describe('migrateFilter', function() { +describe('migrateFilter', function () { const oldMatchPhraseFilter = ({ query: { match: { @@ -45,13 +45,13 @@ describe('migrateFilter', function() { meta: {}, } as unknown) as PhraseFilter; - it('should migrate match filters of type phrase', function() { + it('should migrate match filters of type phrase', function () { const migratedFilter = migrateFilter(oldMatchPhraseFilter, undefined); expect(migratedFilter).toEqual(newMatchPhraseFilter); }); - it('should not modify the original filter', function() { + it('should not modify the original filter', function () { const oldMatchPhraseFilterCopy = clone(oldMatchPhraseFilter, true); migrateFilter(oldMatchPhraseFilter, undefined); @@ -59,7 +59,7 @@ describe('migrateFilter', function() { expect(isEqual(oldMatchPhraseFilter, oldMatchPhraseFilterCopy)).toBe(true); }); - it('should return the original filter if no migration is necessary', function() { + it('should return the original filter if no migration is necessary', function () { const originalFilter = { match_all: {}, } as MatchAllFilter; diff --git a/src/plugins/data/common/es_query/es_query/migrate_filter.ts b/src/plugins/data/common/es_query/es_query/migrate_filter.ts index a0529d585879e..498763be538de 100644 --- a/src/plugins/data/common/es_query/es_query/migrate_filter.ts +++ b/src/plugins/data/common/es_query/es_query/migrate_filter.ts @@ -45,7 +45,7 @@ export function migrateFilter(filter: Filter, indexPattern?: IIndexPattern) { const params: Record = get(filter, ['query', 'match', fieldName]); let query = params.query; if (indexPattern) { - const field = indexPattern.fields.find(f => f.name === fieldName); + const field = indexPattern.fields.find((f) => f.name === fieldName); if (field) { query = getConvertedValueForField(field, params.query); diff --git a/src/plugins/data/common/es_query/filters/exists_filter.test.ts b/src/plugins/data/common/es_query/filters/exists_filter.test.ts index af52192dd85e4..065301986726d 100644 --- a/src/plugins/data/common/es_query/filters/exists_filter.test.ts +++ b/src/plugins/data/common/es_query/filters/exists_filter.test.ts @@ -21,14 +21,14 @@ import { buildExistsFilter, getExistsFilterField } from './exists_filter'; import { IIndexPattern } from '../../index_patterns'; import { fields } from '../../index_patterns/fields/fields.mocks.ts'; -describe('exists filter', function() { +describe('exists filter', function () { const indexPattern: IIndexPattern = ({ fields, } as unknown) as IIndexPattern; - describe('getExistsFilterField', function() { + describe('getExistsFilterField', function () { it('should return the name of the field an exists query is targeting', () => { - const field = indexPattern.fields.find(patternField => patternField.name === 'extension'); + const field = indexPattern.fields.find((patternField) => patternField.name === 'extension'); const filter = buildExistsFilter(field!, indexPattern); const result = getExistsFilterField(filter); expect(result).toBe('extension'); diff --git a/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.test.ts b/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.test.ts index 63c3a59044c1f..5d605c58a10d3 100644 --- a/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.test.ts +++ b/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.test.ts @@ -19,8 +19,8 @@ import { getGeoBoundingBoxFilterField } from './geo_bounding_box_filter'; -describe('geo_bounding_box filter', function() { - describe('getGeoBoundingBoxFilterField', function() { +describe('geo_bounding_box filter', function () { + describe('getGeoBoundingBoxFilterField', function () { it('should return the name of the field a geo_bounding_box query is targeting', () => { const filter = { geo_bounding_box: { diff --git a/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.ts b/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.ts index 619903954ff55..e41e3f2978344 100644 --- a/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.ts +++ b/src/plugins/data/common/es_query/filters/geo_bounding_box_filter.ts @@ -37,6 +37,6 @@ export const isGeoBoundingBoxFilter = (filter: any): filter is GeoBoundingBoxFil export const getGeoBoundingBoxFilterField = (filter: GeoBoundingBoxFilter) => { return ( filter.geo_bounding_box && - Object.keys(filter.geo_bounding_box).find(key => key !== 'ignore_unmapped') + Object.keys(filter.geo_bounding_box).find((key) => key !== 'ignore_unmapped') ); }; diff --git a/src/plugins/data/common/es_query/filters/geo_polygon_filter.test.ts b/src/plugins/data/common/es_query/filters/geo_polygon_filter.test.ts index ba8e43b0cea85..f309e72e24e5c 100644 --- a/src/plugins/data/common/es_query/filters/geo_polygon_filter.test.ts +++ b/src/plugins/data/common/es_query/filters/geo_polygon_filter.test.ts @@ -19,8 +19,8 @@ import { getGeoPolygonFilterField } from './geo_polygon_filter'; -describe('geo_polygon filter', function() { - describe('getGeoPolygonFilterField', function() { +describe('geo_polygon filter', function () { + describe('getGeoPolygonFilterField', function () { it('should return the name of the field a geo_polygon query is targeting', () => { const filter = { geo_polygon: { diff --git a/src/plugins/data/common/es_query/filters/geo_polygon_filter.ts b/src/plugins/data/common/es_query/filters/geo_polygon_filter.ts index 03367feb83ee4..2b00f2e3cb99c 100644 --- a/src/plugins/data/common/es_query/filters/geo_polygon_filter.ts +++ b/src/plugins/data/common/es_query/filters/geo_polygon_filter.ts @@ -35,6 +35,6 @@ export const isGeoPolygonFilter = (filter: any): filter is GeoPolygonFilter => export const getGeoPolygonFilterField = (filter: GeoPolygonFilter) => { return ( - filter.geo_polygon && Object.keys(filter.geo_polygon).find(key => key !== 'ignore_unmapped') + filter.geo_polygon && Object.keys(filter.geo_polygon).find((key) => key !== 'ignore_unmapped') ); }; diff --git a/src/plugins/data/common/es_query/filters/get_filter_field.test.ts b/src/plugins/data/common/es_query/filters/get_filter_field.test.ts index 2fc8ffef9713b..4329a45f84ef9 100644 --- a/src/plugins/data/common/es_query/filters/get_filter_field.test.ts +++ b/src/plugins/data/common/es_query/filters/get_filter_field.test.ts @@ -23,14 +23,14 @@ import { getFilterField } from './get_filter_field'; import { IIndexPattern } from '../../index_patterns'; import { fields } from '../../index_patterns/fields/fields.mocks.ts'; -describe('getFilterField', function() { +describe('getFilterField', function () { const indexPattern: IIndexPattern = ({ id: 'logstash-*', fields, } as unknown) as IIndexPattern; it('should return the field name from known filter types that target a specific field', () => { - const field = indexPattern.fields.find(patternField => patternField.name === 'extension'); + const field = indexPattern.fields.find((patternField) => patternField.name === 'extension'); const filter = buildPhraseFilter(field!, 'jpg', indexPattern); const result = getFilterField(filter); expect(result).toBe('extension'); diff --git a/src/plugins/data/common/es_query/filters/get_index_pattern_from_filter.ts b/src/plugins/data/common/es_query/filters/get_index_pattern_from_filter.ts index 43d4bdaf03bc1..93b91757e1dac 100644 --- a/src/plugins/data/common/es_query/filters/get_index_pattern_from_filter.ts +++ b/src/plugins/data/common/es_query/filters/get_index_pattern_from_filter.ts @@ -24,5 +24,5 @@ export function getIndexPatternFromFilter( filter: Filter, indexPatterns: IIndexPattern[] ): IIndexPattern | undefined { - return indexPatterns.find(indexPattern => indexPattern.id === filter.meta.index); + return indexPatterns.find((indexPattern) => indexPattern.id === filter.meta.index); } diff --git a/src/plugins/data/common/es_query/filters/missing_filter.test.ts b/src/plugins/data/common/es_query/filters/missing_filter.test.ts index 240d8fb26f3e0..28d2d3776d74c 100644 --- a/src/plugins/data/common/es_query/filters/missing_filter.test.ts +++ b/src/plugins/data/common/es_query/filters/missing_filter.test.ts @@ -19,8 +19,8 @@ import { getMissingFilterField } from './missing_filter'; -describe('missing filter', function() { - describe('getMissingFilterField', function() { +describe('missing filter', function () { + describe('getMissingFilterField', function () { it('should return the name of the field an missing query is targeting', () => { const filter = { missing: { diff --git a/src/plugins/data/common/es_query/filters/phrase_filter.test.ts b/src/plugins/data/common/es_query/filters/phrase_filter.test.ts index 9f90097e55475..a3948777e6d65 100644 --- a/src/plugins/data/common/es_query/filters/phrase_filter.test.ts +++ b/src/plugins/data/common/es_query/filters/phrase_filter.test.ts @@ -100,13 +100,13 @@ describe('buildInlineScriptForPhraseFilter', () => { }); }); -describe('getPhraseFilterField', function() { +describe('getPhraseFilterField', function () { const indexPattern: IIndexPattern = ({ fields, } as unknown) as IIndexPattern; it('should return the name of the field a phrase query is targeting', () => { - const field = indexPattern.fields.find(patternField => patternField.name === 'extension'); + const field = indexPattern.fields.find((patternField) => patternField.name === 'extension'); const filter = buildPhraseFilter(field!, 'jpg', indexPattern); const result = getPhraseFilterField(filter); expect(result).toBe('extension'); diff --git a/src/plugins/data/common/es_query/filters/phrases_filter.test.ts b/src/plugins/data/common/es_query/filters/phrases_filter.test.ts index 3a121eb9da034..7fbab263ac040 100644 --- a/src/plugins/data/common/es_query/filters/phrases_filter.test.ts +++ b/src/plugins/data/common/es_query/filters/phrases_filter.test.ts @@ -21,14 +21,14 @@ import { buildPhrasesFilter, getPhrasesFilterField } from './phrases_filter'; import { IIndexPattern } from '../../index_patterns'; import { fields } from '../../index_patterns/fields/fields.mocks.ts'; -describe('phrases filter', function() { +describe('phrases filter', function () { const indexPattern: IIndexPattern = ({ fields, } as unknown) as IIndexPattern; - describe('getPhrasesFilterField', function() { + describe('getPhrasesFilterField', function () { it('should return the name of the field a phrases query is targeting', () => { - const field = indexPattern.fields.find(patternField => patternField.name === 'extension'); + const field = indexPattern.fields.find((patternField) => patternField.name === 'extension'); const filter = buildPhrasesFilter(field!, ['jpg', 'png'], indexPattern); const result = getPhrasesFilterField(filter); expect(result).toBe('extension'); diff --git a/src/plugins/data/common/es_query/filters/range_filter.test.ts b/src/plugins/data/common/es_query/filters/range_filter.test.ts index 45d59c97941b3..8accca5c29a45 100644 --- a/src/plugins/data/common/es_query/filters/range_filter.test.ts +++ b/src/plugins/data/common/es_query/filters/range_filter.test.ts @@ -173,13 +173,13 @@ describe('Range filter builder', () => { }); }); -describe('getRangeFilterField', function() { +describe('getRangeFilterField', function () { const indexPattern: IIndexPattern = ({ fields, } as unknown) as IIndexPattern; test('should return the name of the field a range query is targeting', () => { - const field = indexPattern.fields.find(patternField => patternField.name === 'bytes'); + const field = indexPattern.fields.find((patternField) => patternField.name === 'bytes'); const filter = buildRangeFilter(field!, {}, indexPattern); const result = getRangeFilterField(filter); expect(result).toBe('bytes'); diff --git a/src/plugins/data/common/es_query/filters/range_filter.ts b/src/plugins/data/common/es_query/filters/range_filter.ts index b300539f4280a..c318a0f0c2c3d 100644 --- a/src/plugins/data/common/es_query/filters/range_filter.ts +++ b/src/plugins/data/common/es_query/filters/range_filter.ts @@ -112,7 +112,7 @@ export const buildRangeFilter = ( filter.meta.formattedValue = formattedValue; } - params = mapValues(params, value => (field.type === 'number' ? parseFloat(value) : value)); + params = mapValues(params, (value) => (field.type === 'number' ? parseFloat(value) : value)); if ('gte' in params && 'gt' in params) throw new Error('gte and gt are mutually exclusive'); if ('lte' in params && 'lt' in params) throw new Error('lte and lt are mutually exclusive'); diff --git a/src/plugins/data/common/es_query/kuery/functions/and.test.ts b/src/plugins/data/common/es_query/kuery/functions/and.test.ts index 133e691b27dba..6f27a6dcb30fa 100644 --- a/src/plugins/data/common/es_query/kuery/functions/and.test.ts +++ b/src/plugins/data/common/es_query/kuery/functions/and.test.ts @@ -61,7 +61,7 @@ describe('kuery functions', () => { expect(Object.keys(result.bool).length).toBe(1); expect(result.bool.filter).toEqual( - [childNode1, childNode2].map(childNode => + [childNode1, childNode2].map((childNode) => ast.toElasticsearchQuery(childNode, indexPattern) ) ); diff --git a/src/plugins/data/common/es_query/kuery/functions/geo_polygon.ts b/src/plugins/data/common/es_query/kuery/functions/geo_polygon.ts index f382e5668bb9d..753fd4e0a5060 100644 --- a/src/plugins/data/common/es_query/kuery/functions/geo_polygon.ts +++ b/src/plugins/data/common/es_query/kuery/functions/geo_polygon.ts @@ -24,7 +24,7 @@ import { LiteralTypeBuildNode } from '../node_types/types'; export function buildNodeParams(fieldName: string, points: LatLon[]) { const fieldNameArg = nodeTypes.literal.buildNode(fieldName); - const args = points.map(point => { + const args = points.map((point) => { const latLon = `${point.lat}, ${point.lon}`; return nodeTypes.literal.buildNode(latLon); }); diff --git a/src/plugins/data/common/es_query/kuery/functions/or.test.ts b/src/plugins/data/common/es_query/kuery/functions/or.test.ts index a6590546e5fc5..5ef8610362ca9 100644 --- a/src/plugins/data/common/es_query/kuery/functions/or.test.ts +++ b/src/plugins/data/common/es_query/kuery/functions/or.test.ts @@ -60,7 +60,7 @@ describe('kuery functions', () => { expect(Object.keys(result).length).toBe(1); expect(result.bool).toHaveProperty('should'); expect(result.bool.should).toEqual( - [childNode1, childNode2].map(childNode => + [childNode1, childNode2].map((childNode) => ast.toElasticsearchQuery(childNode, indexPattern) ) ); diff --git a/src/plugins/data/common/es_query/kuery/functions/utils/get_fields.ts b/src/plugins/data/common/es_query/kuery/functions/utils/get_fields.ts index 0e314ec778af8..cdd050b2647c1 100644 --- a/src/plugins/data/common/es_query/kuery/functions/utils/get_fields.ts +++ b/src/plugins/data/common/es_query/kuery/functions/utils/get_fields.ts @@ -26,13 +26,13 @@ export function getFields(node: KueryNode, indexPattern?: IIndexPattern) { if (!indexPattern) return []; if (node.type === 'literal') { const fieldName = literal.toElasticsearchQuery(node as LiteralTypeBuildNode); - const field = indexPattern.fields.find(fld => fld.name === fieldName); + const field = indexPattern.fields.find((fld) => fld.name === fieldName); if (!field) { return []; } return [field]; } else if (node.type === 'wildcard') { - const fields = indexPattern.fields.filter(fld => wildcard.test(node, fld.name)); + const fields = indexPattern.fields.filter((fld) => wildcard.test(node, fld.name)); return fields; } } diff --git a/src/plugins/data/common/es_query/kuery/functions/utils/get_full_field_name_node.test.ts b/src/plugins/data/common/es_query/kuery/functions/utils/get_full_field_name_node.test.ts index 200c5b51e4d27..abfdb2c363821 100644 --- a/src/plugins/data/common/es_query/kuery/functions/utils/get_full_field_name_node.test.ts +++ b/src/plugins/data/common/es_query/kuery/functions/utils/get_full_field_name_node.test.ts @@ -24,7 +24,7 @@ import { IIndexPattern } from '../../../../index_patterns'; // @ts-ignore import { getFullFieldNameNode } from './get_full_field_name_node'; -describe('getFullFieldNameNode', function() { +describe('getFullFieldNameNode', function () { let indexPattern: IIndexPattern; beforeEach(() => { diff --git a/src/plugins/data/common/es_query/kuery/kuery_syntax_error.ts b/src/plugins/data/common/es_query/kuery/kuery_syntax_error.ts index 4ada139a10a0f..6aac1a3b3486d 100644 --- a/src/plugins/data/common/es_query/kuery/kuery_syntax_error.ts +++ b/src/plugins/data/common/es_query/kuery/kuery_syntax_error.ts @@ -55,7 +55,7 @@ export class KQLSyntaxError extends Error { constructor(error: KQLSyntaxErrorData, expression: any) { let message = error.message; if (error.expected) { - const translatedExpectations = error.expected.map(expected => { + const translatedExpectations = error.expected.map((expected) => { return grammarRuleTranslations[expected.description] || expected.description; }); diff --git a/src/plugins/data/common/es_query/kuery/node_types/wildcard.ts b/src/plugins/data/common/es_query/kuery/node_types/wildcard.ts index 87fcfa1ca2f64..160212c58f0fb 100644 --- a/src/plugins/data/common/es_query/kuery/node_types/wildcard.ts +++ b/src/plugins/data/common/es_query/kuery/node_types/wildcard.ts @@ -46,10 +46,7 @@ export function buildNode(value: string): WildcardTypeBuildNode | KueryNode { export function test(node: any, str: string): boolean { const { value } = node; - const regex = value - .split(wildcardSymbol) - .map(escapeRegExp) - .join('[\\s\\S]*'); + const regex = value.split(wildcardSymbol).map(escapeRegExp).join('[\\s\\S]*'); const regexp = new RegExp(`^${regex}$`); return regexp.test(str); } @@ -61,10 +58,7 @@ export function toElasticsearchQuery(node: any): string { export function toQueryStringQuery(node: any): string { const { value } = node; - return value - .split(wildcardSymbol) - .map(escapeQueryString) - .join('*'); + return value.split(wildcardSymbol).map(escapeQueryString).join('*'); } export function hasLeadingWildcard(node: any): boolean { diff --git a/src/plugins/data/common/field_formats/content_types/text_content_type.ts b/src/plugins/data/common/field_formats/content_types/text_content_type.ts index dc450086edc62..4a90ba6c0b203 100644 --- a/src/plugins/data/common/field_formats/content_types/text_content_type.ts +++ b/src/plugins/data/common/field_formats/content_types/text_content_type.ts @@ -27,7 +27,7 @@ export const setup = ( format: IFieldFormat, convert: TextContextTypeConvert = asPrettyString ): TextContextTypeConvert => { - const recurse: TextContextTypeConvert = value => { + const recurse: TextContextTypeConvert = (value) => { if (!value || !isFunction(value.map)) { return convert.call(format, value); } diff --git a/src/plugins/data/common/field_formats/converters/boolean.test.ts b/src/plugins/data/common/field_formats/converters/boolean.test.ts index 3650df6517611..cef7936aaaf13 100644 --- a/src/plugins/data/common/field_formats/converters/boolean.test.ts +++ b/src/plugins/data/common/field_formats/converters/boolean.test.ts @@ -63,7 +63,7 @@ describe('Boolean Format', () => { input: ' True ', // should handle trailing and mixed case expected: 'true', }, - ].forEach(data => { + ].forEach((data) => { test(`convert ${data.input} to boolean`, () => { expect(boolean.convert(data.input)).toBe(data.expected); }); diff --git a/src/plugins/data/common/field_formats/converters/boolean.ts b/src/plugins/data/common/field_formats/converters/boolean.ts index a824f9e73fb1e..f8304a396f83c 100644 --- a/src/plugins/data/common/field_formats/converters/boolean.ts +++ b/src/plugins/data/common/field_formats/converters/boolean.ts @@ -30,7 +30,7 @@ export class BoolFormat extends FieldFormat { }); static fieldType = [KBN_FIELD_TYPES.BOOLEAN, KBN_FIELD_TYPES.NUMBER, KBN_FIELD_TYPES.STRING]; - textConvert: TextContextTypeConvert = value => { + textConvert: TextContextTypeConvert = (value) => { if (typeof value === 'string') { value = value.trim().toLowerCase(); } diff --git a/src/plugins/data/common/field_formats/converters/color.ts b/src/plugins/data/common/field_formats/converters/color.ts index babf3dbd8c451..ca659916f7671 100644 --- a/src/plugins/data/common/field_formats/converters/color.ts +++ b/src/plugins/data/common/field_formats/converters/color.ts @@ -60,7 +60,7 @@ export class ColorFormat extends FieldFormat { } } - htmlConvert: HtmlContextTypeConvert = val => { + htmlConvert: HtmlContextTypeConvert = (val) => { const color = this.findColorRuleForVal(val) as typeof DEFAULT_CONVERTER_COLOR; if (!color) return escape(asPrettyString(val)); diff --git a/src/plugins/data/common/field_formats/converters/date_nanos.test.ts b/src/plugins/data/common/field_formats/converters/date_nanos.test.ts index ea755eb5d5bdf..267f023e9b69d 100644 --- a/src/plugins/data/common/field_formats/converters/date_nanos.test.ts +++ b/src/plugins/data/common/field_formats/converters/date_nanos.test.ts @@ -67,7 +67,7 @@ describe('Date Nanos Format', () => { pattern: 'SSSSSSSSS', expected: '201900001', }, - ].forEach(fixture => { + ].forEach((fixture) => { const fracPattern = analysePatternForFract(fixture.pattern); const momentDate = moment(fixture.input).utc(); const value = formatWithNanos(momentDate, fixture.input, fracPattern); diff --git a/src/plugins/data/common/field_formats/converters/date_nanos.ts b/src/plugins/data/common/field_formats/converters/date_nanos.ts index 93f3a62842749..3fa2b1c276cd7 100644 --- a/src/plugins/data/common/field_formats/converters/date_nanos.ts +++ b/src/plugins/data/common/field_formats/converters/date_nanos.ts @@ -88,7 +88,7 @@ export class DateNanosFormat extends FieldFormat { }; } - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { // don't give away our ref to converter so // we can hot-swap when config changes const pattern = this.param('pattern'); diff --git a/src/plugins/data/common/field_formats/converters/duration.ts b/src/plugins/data/common/field_formats/converters/duration.ts index 3b3b6f87f36f9..53c2aba98120e 100644 --- a/src/plugins/data/common/field_formats/converters/duration.ts +++ b/src/plugins/data/common/field_formats/converters/duration.ts @@ -186,7 +186,7 @@ export class DurationFormat extends FieldFormat { }; } - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { const inputFormat = this.param('inputFormat'); const outputFormat = this.param('outputFormat') as keyof Duration; const outputPrecision = this.param('outputPrecision'); diff --git a/src/plugins/data/common/field_formats/converters/ip.ts b/src/plugins/data/common/field_formats/converters/ip.ts index 8e65d9c12d6c8..da86cdbd6b051 100644 --- a/src/plugins/data/common/field_formats/converters/ip.ts +++ b/src/plugins/data/common/field_formats/converters/ip.ts @@ -29,7 +29,7 @@ export class IpFormat extends FieldFormat { }); static fieldType = KBN_FIELD_TYPES.IP; - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { if (val === undefined || val === null) return '-'; if (!isFinite(val)) return val; diff --git a/src/plugins/data/common/field_formats/converters/numeral.ts b/src/plugins/data/common/field_formats/converters/numeral.ts index d8e46a480294f..a483b5a1e4f99 100644 --- a/src/plugins/data/common/field_formats/converters/numeral.ts +++ b/src/plugins/data/common/field_formats/converters/numeral.ts @@ -61,7 +61,7 @@ export abstract class NumeralFormat extends FieldFormat { return formatted; } - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { return this.getConvertedValue(val); }; } diff --git a/src/plugins/data/common/field_formats/converters/percent.ts b/src/plugins/data/common/field_formats/converters/percent.ts index 8cbc2d36d0ef1..ef3b0a1503a98 100644 --- a/src/plugins/data/common/field_formats/converters/percent.ts +++ b/src/plugins/data/common/field_formats/converters/percent.ts @@ -36,7 +36,7 @@ export class PercentFormat extends NumeralFormat { fractional: true, }); - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { const formatted = super.getConvertedValue(val); if (this.param('fractional')) { diff --git a/src/plugins/data/common/field_formats/converters/relative_date.ts b/src/plugins/data/common/field_formats/converters/relative_date.ts index 7c7f20ee9c411..e3bdf25da9076 100644 --- a/src/plugins/data/common/field_formats/converters/relative_date.ts +++ b/src/plugins/data/common/field_formats/converters/relative_date.ts @@ -30,7 +30,7 @@ export class RelativeDateFormat extends FieldFormat { }); static fieldType = KBN_FIELD_TYPES.DATE; - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { if (val === null || val === undefined) { return '-'; } diff --git a/src/plugins/data/common/field_formats/converters/source.ts b/src/plugins/data/common/field_formats/converters/source.ts index 7f13d5526cc15..9e50d47bb2624 100644 --- a/src/plugins/data/common/field_formats/converters/source.ts +++ b/src/plugins/data/common/field_formats/converters/source.ts @@ -56,7 +56,7 @@ export class SourceFormat extends FieldFormat { static title = '_source'; static fieldType = KBN_FIELD_TYPES._SOURCE; - textConvert: TextContextTypeConvert = value => JSON.stringify(value); + textConvert: TextContextTypeConvert = (value) => JSON.stringify(value); htmlConvert: HtmlContextTypeConvert = (value, options = {}) => { const { field, hit } = options; @@ -73,7 +73,7 @@ export class SourceFormat extends FieldFormat { const sourcePairs: any[] = []; const isShortDots = this.getConfig!('shortDots:enable'); - keys(formatted).forEach(key => { + keys(formatted).forEach((key) => { const pairs = highlights[key] ? highlightPairs : sourcePairs; const newField = isShortDots ? shortenDottedString(key) : key; const val = formatted[key]; diff --git a/src/plugins/data/common/field_formats/converters/static_lookup.ts b/src/plugins/data/common/field_formats/converters/static_lookup.ts index c835afd3db5ec..394bea5be4f25 100644 --- a/src/plugins/data/common/field_formats/converters/static_lookup.ts +++ b/src/plugins/data/common/field_formats/converters/static_lookup.ts @@ -51,7 +51,7 @@ export class StaticLookupFormat extends FieldFormat { }; } - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { const lookupEntries = this.param('lookupEntries'); const unknownKeyValue = this.param('unknownKeyValue'); diff --git a/src/plugins/data/common/field_formats/converters/string.ts b/src/plugins/data/common/field_formats/converters/string.ts index 22df9f1f88bfb..a543a46f965cc 100644 --- a/src/plugins/data/common/field_formats/converters/string.ts +++ b/src/plugins/data/common/field_formats/converters/string.ts @@ -105,12 +105,12 @@ export class StringFormat extends FieldFormat { } private toTitleCase(val: string) { - return val.replace(/\w\S*/g, txt => { + return val.replace(/\w\S*/g, (txt) => { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); } - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { switch (this.param('transform')) { case 'lower': return String(val).toLowerCase(); diff --git a/src/plugins/data/common/field_formats/converters/truncate.ts b/src/plugins/data/common/field_formats/converters/truncate.ts index 70b2a3dff18f2..a6c4a1133a2ed 100644 --- a/src/plugins/data/common/field_formats/converters/truncate.ts +++ b/src/plugins/data/common/field_formats/converters/truncate.ts @@ -32,7 +32,7 @@ export class TruncateFormat extends FieldFormat { }); static fieldType = KBN_FIELD_TYPES.STRING; - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { const length = this.param('fieldLength'); if (length > 0) { return trunc(val, { diff --git a/src/plugins/data/common/field_formats/converters/url.ts b/src/plugins/data/common/field_formats/converters/url.ts index 60d7efdba34ff..a0a498b6cab34 100644 --- a/src/plugins/data/common/field_formats/converters/url.ts +++ b/src/plugins/data/common/field_formats/converters/url.ts @@ -111,7 +111,7 @@ export class UrlFormat extends FieldFormat { // trim all the odd bits, the variable names const parts = template.split(templateMatchRE).map((part, i) => (i % 2 ? part.trim() : part)); - return function(locals: Record): string { + return function (locals: Record): string { // replace all the odd bits with their local var let output = ''; let i = -1; @@ -139,7 +139,7 @@ export class UrlFormat extends FieldFormat { return `${imageLabel}`; } - textConvert: TextContextTypeConvert = value => this.formatLabel(value); + textConvert: TextContextTypeConvert = (value) => this.formatLabel(value); htmlConvert: HtmlContextTypeConvert = (rawValue, options = {}) => { const { field, hit } = options; @@ -161,7 +161,7 @@ export class UrlFormat extends FieldFormat { return this.generateImgHtml(url, imageLabel); default: - const inWhitelist = whitelistUrlSchemes.some(scheme => url.indexOf(scheme) === 0); + const inWhitelist = whitelistUrlSchemes.some((scheme) => url.indexOf(scheme) === 0); if (!inWhitelist && !parsedUrl) { return url; } diff --git a/src/plugins/data/common/field_formats/field_formats_registry.ts b/src/plugins/data/common/field_formats/field_formats_registry.ts index 2eb9a3e593d1a..c04a371066de3 100644 --- a/src/plugins/data/common/field_formats/field_formats_registry.ts +++ b/src/plugins/data/common/field_formats/field_formats_registry.ts @@ -129,7 +129,7 @@ export class FieldFormatsRegistry { return undefined; } - return esTypes.find(type => this.defaultMap[type] && this.defaultMap[type].es); + return esTypes.find((type) => this.defaultMap[type] && this.defaultMap[type].es); }; /** @@ -231,7 +231,7 @@ export class FieldFormatsRegistry { parseDefaultTypeMap(value: any) { this.defaultMap = value; - forOwn(this, fn => { + forOwn(this, (fn) => { if (isFunction(fn) && fn.cache) { // clear all memoize caches // @ts-ignore @@ -241,7 +241,7 @@ export class FieldFormatsRegistry { } register(fieldFormats: FieldFormatInstanceType[]) { - fieldFormats.forEach(fieldFormat => this.fieldFormats.set(fieldFormat.id, fieldFormat)); + fieldFormats.forEach((fieldFormat) => this.fieldFormats.set(fieldFormat.id, fieldFormat)); } /** diff --git a/src/plugins/data/common/field_formats/utils/highlight/highlight_html.test.ts b/src/plugins/data/common/field_formats/utils/highlight/highlight_html.test.ts index 6ada630851c1d..8df25a2f34269 100644 --- a/src/plugins/data/common/field_formats/utils/highlight/highlight_html.test.ts +++ b/src/plugins/data/common/field_formats/utils/highlight/highlight_html.test.ts @@ -21,7 +21,7 @@ import { highlightTags } from './highlight_tags'; import { htmlTags } from './html_tags'; import { getHighlightHtml } from './highlight_html'; -describe('getHighlightHtml', function() { +describe('getHighlightHtml', function () { const text = '' + 'Bacon ipsum dolor amet pork loin pork cow pig beef chuck ground round shankle sirloin landjaeger kevin ' + @@ -29,20 +29,20 @@ describe('getHighlightHtml', function() { 'sirloin, t-bone ham shoulder jerky turducken bresaola. Chicken cow beef picanha. Picanha hamburger alcatra ' + 'cupim. Salami capicola boudin pork belly shank picanha.'; - test('should not modify text if highlight is empty', function() { + test('should not modify text if highlight is empty', function () { expect(getHighlightHtml(text, undefined)).toBe(text); expect(getHighlightHtml(text, null)).toBe(text); expect(getHighlightHtml(text, [])).toBe(text); }); - test('should preserve escaped text', function() { + test('should preserve escaped text', function () { const highlights = ['']; const result = getHighlightHtml('<foo>', highlights); expect(result.indexOf('')).toBe(-1); expect(result.indexOf('<foo>')).toBeGreaterThan(-1); }); - test('should highlight a single result', function() { + test('should highlight a single result', function () { const highlights = [ highlightTags.pre + 'hamburger' + @@ -56,7 +56,7 @@ describe('getHighlightHtml', function() { ); }); - test('should highlight multiple results', function() { + test('should highlight multiple results', function () { const highlights = [ 'kevin venison sausage ribeye tongue. ' + highlightTags.pre + @@ -76,7 +76,7 @@ describe('getHighlightHtml', function() { ); }); - test('should highlight multiple hits in a result', function() { + test('should highlight multiple hits in a result', function () { const highlights = [ 'Bacon ipsum dolor amet ' + highlightTags.pre + @@ -114,7 +114,7 @@ describe('getHighlightHtml', function() { ); }); - test('should accept an object and return a string containing its properties', function() { + test('should accept an object and return a string containing its properties', function () { const obj = { foo: 1, bar: 2 }; const result = getHighlightHtml(obj, null); expect(result.indexOf('' + obj)).toBe(-1); diff --git a/src/plugins/data/common/field_formats/utils/highlight/highlight_html.ts b/src/plugins/data/common/field_formats/utils/highlight/highlight_html.ts index c7c092941728e..23c72e94b120a 100644 --- a/src/plugins/data/common/field_formats/utils/highlight/highlight_html.ts +++ b/src/plugins/data/common/field_formats/utils/highlight/highlight_html.ts @@ -24,7 +24,7 @@ import { htmlTags } from './html_tags'; export function getHighlightHtml(fieldValue: any, highlights: any) { let highlightHtml = typeof fieldValue === 'object' ? JSON.stringify(fieldValue) : fieldValue; - _.each(highlights, function(highlight) { + _.each(highlights, function (highlight) { const escapedHighlight = _.escape(highlight); // Strip out the highlight tags to compare against the field text diff --git a/src/plugins/data/common/index_patterns/fields/fields.mocks.ts.ts b/src/plugins/data/common/index_patterns/fields/fields.mocks.ts.ts index c27ff42b1e9d2..ed778d0422054 100644 --- a/src/plugins/data/common/index_patterns/fields/fields.mocks.ts.ts +++ b/src/plugins/data/common/index_patterns/fields/fields.mocks.ts.ts @@ -318,4 +318,4 @@ export const fields: IFieldType[] = [ }, ]; -export const getField = (name: string) => fields.find(field => field.name === name) as IFieldType; +export const getField = (name: string) => fields.find((field) => field.name === name) as IFieldType; diff --git a/src/plugins/data/common/index_patterns/utils.test.ts b/src/plugins/data/common/index_patterns/utils.test.ts index e2707d469a317..43d6fadb336ff 100644 --- a/src/plugins/data/common/index_patterns/utils.test.ts +++ b/src/plugins/data/common/index_patterns/utils.test.ts @@ -30,20 +30,20 @@ const mockField = { describe('isFilterable', () => { describe('types', () => { it('should return true for filterable types', () => { - ['string', 'number', 'date', 'ip', 'boolean'].forEach(type => { + ['string', 'number', 'date', 'ip', 'boolean'].forEach((type) => { expect(isFilterable({ ...mockField, type })).toBe(true); }); }); it('should return false for filterable types if the field is not searchable', () => { - ['string', 'number', 'date', 'ip', 'boolean'].forEach(type => { + ['string', 'number', 'date', 'ip', 'boolean'].forEach((type) => { expect(isFilterable({ ...mockField, type, searchable: false })).toBe(false); }); }); it('should return false for un-filterable types', () => { ['geo_point', 'geo_shape', 'attachment', 'murmur3', '_source', 'unknown', 'conflict'].forEach( - type => { + (type) => { expect(isFilterable({ ...mockField, type })).toBe(false); } ); diff --git a/src/plugins/data/common/kbn_field_types/kbn_field_types.ts b/src/plugins/data/common/kbn_field_types/kbn_field_types.ts index 91d3b7404e5b0..ce05dc796bbab 100644 --- a/src/plugins/data/common/kbn_field_types/kbn_field_types.ts +++ b/src/plugins/data/common/kbn_field_types/kbn_field_types.ts @@ -31,7 +31,7 @@ const registeredKbnTypes = createKbnFieldTypes(); * @return {KbnFieldType} */ export const getKbnFieldType = (typeName: string): KbnFieldType | undefined => - registeredKbnTypes.find(t => t.name === typeName); + registeredKbnTypes.find((t) => t.name === typeName); /** * Get the esTypes known by all kbnFieldTypes @@ -39,7 +39,7 @@ export const getKbnFieldType = (typeName: string): KbnFieldType | undefined => * @return {Array} */ export const getKbnTypeNames = (): string[] => - registeredKbnTypes.filter(type => type.name).map(type => type.name); + registeredKbnTypes.filter((type) => type.name).map((type) => type.name); /** * Get the KbnFieldType name for an esType string @@ -48,7 +48,7 @@ export const getKbnTypeNames = (): string[] => * @return {string} */ export const castEsToKbnFieldTypeName = (esType: ES_FIELD_TYPES | string): KBN_FIELD_TYPES => { - const type = registeredKbnTypes.find(t => t.esTypes.includes(esType as ES_FIELD_TYPES)); + const type = registeredKbnTypes.find((t) => t.esTypes.includes(esType as ES_FIELD_TYPES)); return type && type.name ? (type.name as KBN_FIELD_TYPES) : KBN_FIELD_TYPES.UNKNOWN; }; @@ -59,4 +59,4 @@ export const castEsToKbnFieldTypeName = (esType: ES_FIELD_TYPES | string): KBN_F * @return {Array} */ export const getFilterableKbnTypeNames = (): string[] => - registeredKbnTypes.filter(type => type.filterable).map(type => type.name); + registeredKbnTypes.filter((type) => type.filterable).map((type) => type.name); diff --git a/src/plugins/data/common/search/aggs/date_interval_utils/least_common_interval.ts b/src/plugins/data/common/search/aggs/date_interval_utils/least_common_interval.ts index 9df17b4c24a98..fe8ea6e346ba7 100644 --- a/src/plugins/data/common/search/aggs/date_interval_utils/least_common_interval.ts +++ b/src/plugins/data/common/search/aggs/date_interval_utils/least_common_interval.ts @@ -69,7 +69,7 @@ export function leastCommonInterval(a: string, b: string): string { } // Otherwise find the biggest non-calendar unit that divides evenly - const lcmUnit = unitsDesc.find(unit => { + const lcmUnit = unitsDesc.find((unit) => { const unitInfo = unitsMap[unit]; return !!(unitInfo.type !== 'calendar' && lcmMs % unitInfo.base === 0); }); diff --git a/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.test.ts b/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.test.ts index c18ff4c7acead..b2e51faada2ac 100644 --- a/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.test.ts +++ b/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.test.ts @@ -45,7 +45,7 @@ describe('parseEsInterval', () => { const intervals = ['4w', '12M', '10y']; expect.assertions(intervals.length); - intervals.forEach(interval => { + intervals.forEach((interval) => { try { parseEsInterval(interval); } catch (error) { @@ -58,7 +58,7 @@ describe('parseEsInterval', () => { const intervals = ['1', 'h', '0m', '0.5h']; expect.assertions(intervals.length); - intervals.forEach(interval => { + intervals.forEach((interval) => { try { parseEsInterval(interval); } catch (error) { diff --git a/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.ts b/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.ts index f53da19ef476f..7121b776b800e 100644 --- a/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.ts +++ b/src/plugins/data/common/search/aggs/date_interval_utils/parse_es_interval.ts @@ -48,9 +48,7 @@ export type ParsedInterval = ReturnType; * */ export function parseEsInterval(interval: string) { - const matches = String(interval) - .trim() - .match(ES_INTERVAL_STRING_REGEX); + const matches = String(interval).trim().match(ES_INTERVAL_STRING_REGEX); if (!matches) { throw new InvalidEsIntervalFormatError(interval); diff --git a/src/plugins/data/common/search/aggs/date_interval_utils/parse_interval.ts b/src/plugins/data/common/search/aggs/date_interval_utils/parse_interval.ts index 857c8594720ee..e9d708d7061d2 100644 --- a/src/plugins/data/common/search/aggs/date_interval_utils/parse_interval.ts +++ b/src/plugins/data/common/search/aggs/date_interval_utils/parse_interval.ts @@ -25,9 +25,7 @@ import dateMath from '@elastic/datemath'; const INTERVAL_STRING_RE = new RegExp('^([0-9\\.]*)\\s*(' + dateMath.units.join('|') + ')$'); export function parseInterval(interval: string): moment.Duration | null { - const matches = String(interval) - .trim() - .match(INTERVAL_STRING_RE); + const matches = String(interval).trim().match(INTERVAL_STRING_RE); if (!matches) return null; @@ -46,7 +44,7 @@ export function parseInterval(interval: string): moment.Duration | null { // a duration corresponding to 0.5 hours, we return a duration corresponding to 12 hours. const selectedUnit = find( dateMath.units, - u => Math.abs(duration.as(u)) >= 1 + (u) => Math.abs(duration.as(u)) >= 1 ) as unitOfTime.Base; // however if we do this fhe other way around it will also fail diff --git a/src/plugins/data/common/utils/abort_utils.test.ts b/src/plugins/data/common/utils/abort_utils.test.ts index d2a25f2c2dd52..cd78d95b2ab00 100644 --- a/src/plugins/data/common/utils/abort_utils.test.ts +++ b/src/plugins/data/common/utils/abort_utils.test.ts @@ -21,7 +21,7 @@ import { AbortError, toPromise, getCombinedSignal } from './abort_utils'; jest.useFakeTimers(); -const flushPromises = () => new Promise(resolve => setImmediate(resolve)); +const flushPromises = () => new Promise((resolve) => setImmediate(resolve)); describe('AbortUtils', () => { describe('AbortError', () => { diff --git a/src/plugins/data/common/utils/abort_utils.ts b/src/plugins/data/common/utils/abort_utils.ts index 9aec787170840..aef9802cecce9 100644 --- a/src/plugins/data/common/utils/abort_utils.ts +++ b/src/plugins/data/common/utils/abort_utils.ts @@ -61,7 +61,7 @@ export function toPromise(signal: AbortSignal, shouldReject: boolean = false) { * @param signals */ export function getCombinedSignal(signals: AbortSignal[]) { - const promises = signals.map(signal => toPromise(signal)); + const promises = signals.map((signal) => toPromise(signal)); const controller = new AbortController(); Promise.race(promises).then(() => controller.abort()); return controller.signal; diff --git a/src/plugins/data/public/actions/apply_filter_action.ts b/src/plugins/data/public/actions/apply_filter_action.ts index ebaac6b745bec..7e8ed5ec8fb22 100644 --- a/src/plugins/data/public/actions/apply_filter_action.ts +++ b/src/plugins/data/public/actions/apply_filter_action.ts @@ -62,12 +62,12 @@ export function createFilterAction( if (selectedFilters.length > 1) { const indexPatterns = await Promise.all( - filters.map(filter => { + filters.map((filter) => { return getIndexPatterns().get(filter.meta.index!); }) ); - const filterSelectionPromise: Promise = new Promise(resolve => { + const filterSelectionPromise: Promise = new Promise((resolve) => { const overlay = getOverlays().openModal( toMountPoint( applyFiltersPopover( diff --git a/src/plugins/data/public/actions/filters/create_filters_from_value_click.ts b/src/plugins/data/public/actions/filters/create_filters_from_value_click.ts index 2b426813a98a4..2fdd746535519 100644 --- a/src/plugins/data/public/actions/filters/create_filters_from_value_click.ts +++ b/src/plugins/data/public/actions/filters/create_filters_from_value_click.ts @@ -42,16 +42,16 @@ const getOtherBucketFilterTerms = ( } // get only rows where cell value matches current row for all the fields before columnIndex - const rows = table.rows.filter(row => { + const rows = table.rows.filter((row) => { return table.columns.every((column, i) => { return row[column.id] === table.rows[rowIndex][column.id] || i >= columnIndex; }); }); - const terms: any[] = rows.map(row => row[table.columns[columnIndex].id]); + const terms: any[] = rows.map((row) => row[table.columns[columnIndex].id]); return [ ...new Set( - terms.filter(term => { + terms.filter((term) => { const notOther = term !== '__other__'; const notMissing = term !== '__missing__'; return notOther && notMissing; @@ -119,12 +119,12 @@ export const createFiltersFromValueClickAction = async ({ await Promise.all( data - .filter(point => point) - .map(async val => { + .filter((point) => point) + .map(async (val) => { const { table, column, row } = val; const filter: Filter[] = (await createFilter(table, column, row)) || []; if (filter) { - filter.forEach(f => { + filter.forEach((f) => { if (negate) { f = esFilters.toggleFilterNegated(f); } diff --git a/src/plugins/data/public/actions/value_click_action.ts b/src/plugins/data/public/actions/value_click_action.ts index 17c1b1b1e1769..5d4f1f5f1d6db 100644 --- a/src/plugins/data/public/actions/value_click_action.ts +++ b/src/plugins/data/public/actions/value_click_action.ts @@ -68,12 +68,12 @@ export function valueClickAction( if (filters.length > 1) { const indexPatterns = await Promise.all( - filters.map(filter => { + filters.map((filter) => { return getIndexPatterns().get(filter.meta.index!); }) ); - const filterSelectionPromise: Promise = new Promise(resolve => { + const filterSelectionPromise: Promise = new Promise((resolve) => { const overlay = getOverlays().openModal( toMountPoint( applyFiltersPopover( diff --git a/src/plugins/data/public/autocomplete/autocomplete_service.ts b/src/plugins/data/public/autocomplete/autocomplete_service.ts index bc557f31f7466..cf248adea0b05 100644 --- a/src/plugins/data/public/autocomplete/autocomplete_service.ts +++ b/src/plugins/data/public/autocomplete/autocomplete_service.ts @@ -34,7 +34,7 @@ export class AutocompleteService { } }; - private getQuerySuggestions: QuerySuggestionGetFn = args => { + private getQuerySuggestions: QuerySuggestionGetFn = (args) => { const { language } = args; const provider = this.querySuggestionProviders.get(language); diff --git a/src/plugins/data/public/field_formats/converters/date.ts b/src/plugins/data/public/field_formats/converters/date.ts index 3e1efdc69dec8..78ef8b293e8b9 100644 --- a/src/plugins/data/public/field_formats/converters/date.ts +++ b/src/plugins/data/public/field_formats/converters/date.ts @@ -45,7 +45,7 @@ export class DateFormat extends FieldFormat { }; } - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { // don't give away our ref to converter so // we can hot-swap when config changes const pattern = this.param('pattern'); diff --git a/src/plugins/data/public/field_formats/utils/deserialize.ts b/src/plugins/data/public/field_formats/utils/deserialize.ts index 840e023a11589..d9c713c8b1eb4 100644 --- a/src/plugins/data/public/field_formats/utils/deserialize.ts +++ b/src/plugins/data/public/field_formats/utils/deserialize.ts @@ -60,7 +60,7 @@ const getFieldFormat = ( return new DefaultFieldFormat(); }; -export const deserializeFieldFormat: FormatFactory = function( +export const deserializeFieldFormat: FormatFactory = function ( this: DataPublicPluginStart['fieldFormats'], mapping?: SerializedFieldFormat ) { diff --git a/src/plugins/data/public/index_patterns/fields/field_list.ts b/src/plugins/data/public/index_patterns/fields/field_list.ts index 0631e00a1fb62..1aef0b1ccadaa 100644 --- a/src/plugins/data/public/index_patterns/fields/field_list.ts +++ b/src/plugins/data/public/index_patterns/fields/field_list.ts @@ -68,7 +68,7 @@ export const getIndexPatternFieldListCreator = ({ this.indexPattern = indexPattern; this.shortDotsEnable = shortDotsEnable; - specs.map(field => this.add(field)); + specs.map((field) => this.add(field)); } getByName = (name: Field['name']) => this.byName.get(name); @@ -96,7 +96,7 @@ export const getIndexPatternFieldListCreator = ({ fieldFormats, toastNotifications, }); - const index = this.findIndex(f => f.name === newField.name); + const index = this.findIndex((f) => f.name === newField.name); this.splice(index, 1, newField); this.setByName(newField); this.removeByGroup(newField); diff --git a/src/plugins/data/public/index_patterns/fields/obj_define.js b/src/plugins/data/public/index_patterns/fields/obj_define.js index bb32f93d6011a..9c9e5c8f3d55f 100644 --- a/src/plugins/data/public/index_patterns/fields/obj_define.js +++ b/src/plugins/data/public/index_patterns/fields/obj_define.js @@ -27,7 +27,7 @@ export function ObjDefine(defaults, prototype) { this.prototype = prototype || Object.prototype; } -ObjDefine.REDEFINE_SUPPORTED = (function() { +ObjDefine.REDEFINE_SUPPORTED = (function () { const a = Object.create(Object.prototype, { prop: { configurable: true, @@ -49,7 +49,7 @@ ObjDefine.REDEFINE_SUPPORTED = (function() { * @param {any} v - value * @return {object} - property descriptor */ -ObjDefine.prototype.writ = function(name, val) { +ObjDefine.prototype.writ = function (name, val) { this._define(name, val, true, true); }; @@ -59,7 +59,7 @@ ObjDefine.prototype.writ = function(name, val) { * @param {any} v - value * @return {object} - property descriptor */ -ObjDefine.prototype.fact = function(name, val) { +ObjDefine.prototype.fact = function (name, val) { this._define(name, val, true); }; @@ -69,7 +69,7 @@ ObjDefine.prototype.fact = function(name, val) { * @param {any} v - value * @return {object} - property descriptor */ -ObjDefine.prototype.comp = function(name, val) { +ObjDefine.prototype.comp = function (name, val) { this._define(name, val); }; @@ -84,7 +84,7 @@ ObjDefine.prototype.comp = function(name, val) { * * @return {object} - created object */ -ObjDefine.prototype.create = function() { +ObjDefine.prototype.create = function () { const self = this; self.obj = Object.create(this.prototype, self.descs); @@ -94,10 +94,10 @@ ObjDefine.prototype.create = function() { // to include or trim manually. This is currently only in use in PhantomJS // due to https://github.com/ariya/phantomjs/issues/11856 // TODO: remove this: https://github.com/elastic/kibana/issues/27136 - self.obj.toJSON = function() { + self.obj.toJSON = function () { return _.transform( self.obj, - function(json, val, key) { + function (json, val, key) { const desc = self.descs[key]; if (desc && desc.enumerable && val == null) return; json[key] = val; @@ -114,12 +114,12 @@ ObjDefine.prototype.create = function() { * Private APIS */ -ObjDefine.prototype._define = function(name, val, exported, changeable) { +ObjDefine.prototype._define = function (name, val, exported, changeable) { val = val != null ? val : this.defaults[name]; this.descs[name] = this._describe(name, val, !!exported, !!changeable); }; -ObjDefine.prototype._describe = function(name, val, exported, changeable) { +ObjDefine.prototype._describe = function (name, val, exported, changeable) { const self = this; const exists = val != null; @@ -128,7 +128,7 @@ ObjDefine.prototype._describe = function(name, val, exported, changeable) { enumerable: exists, configurable: true, get: _.constant(val), - set: function(update) { + set: function (update) { if (!changeable) return false; // change the descriptor, since the value now exists. diff --git a/src/plugins/data/public/index_patterns/fields/obj_define.test.js b/src/plugins/data/public/index_patterns/fields/obj_define.test.js index 7bcd97ec06813..ec9a022253621 100644 --- a/src/plugins/data/public/index_patterns/fields/obj_define.test.js +++ b/src/plugins/data/public/index_patterns/fields/obj_define.test.js @@ -20,13 +20,13 @@ import expect from '@kbn/expect'; import { ObjDefine } from './obj_define'; -describe('ObjDefine Utility', function() { +describe('ObjDefine Utility', function () { function flatten(obj) { return JSON.parse(JSON.stringify(obj)); } - describe('#writ', function() { - it('creates writeable properties', function() { + describe('#writ', function () { + it('creates writeable properties', function () { const def = new ObjDefine(); def.writ('name', 'foo'); @@ -37,13 +37,13 @@ describe('ObjDefine Utility', function() { expect(obj).to.have.property('name', 'bar'); }); - it('exports the property to JSON', function() { + it('exports the property to JSON', function () { const def = new ObjDefine(); def.writ('name', 'foo'); expect(flatten(def.create())).to.have.property('name', 'foo'); }); - it("does not export property to JSON it it's undefined or null", function() { + it("does not export property to JSON it it's undefined or null", function () { const def = new ObjDefine(); def.writ('name'); expect(flatten(def.create())).to.not.have.property('name'); @@ -52,7 +52,7 @@ describe('ObjDefine Utility', function() { expect(flatten(def.create())).to.not.have.property('name'); }); - it('switched to exporting if a value is written', function() { + it('switched to exporting if a value is written', function () { const def = new ObjDefine(); def.writ('name'); @@ -66,7 +66,7 @@ describe('ObjDefine Utility', function() { expect(flatten(obj)).to.have.property('name', 'foo'); }); - it('setting a writ value to null prevents it from exporting', function() { + it('setting a writ value to null prevents it from exporting', function () { const def = new ObjDefine(); def.writ('name', 'foo'); @@ -78,8 +78,8 @@ describe('ObjDefine Utility', function() { }); }); - describe('#fact', function() { - it('creates an immutable field', function() { + describe('#fact', function () { + it('creates an immutable field', function () { const def = new ObjDefine(); const val = 'foo'; const notval = 'bar'; @@ -90,37 +90,37 @@ describe('ObjDefine Utility', function() { expect(obj).to.have.property('name', val); }); - it('exports the fact to JSON', function() { + it('exports the fact to JSON', function () { const def = new ObjDefine(); def.fact('name', 'foo'); expect(flatten(def.create())).to.have.property('name', 'foo'); }); }); - describe('#comp', function() { - it('creates an immutable field', function() { + describe('#comp', function () { + it('creates an immutable field', function () { const def = new ObjDefine(); const val = 'foo'; const notval = 'bar'; def.comp('name', val); const obj = def.create(); - expect(function() { + expect(function () { 'use strict'; // eslint-disable-line strict obj.name = notval; }).to.throwException(); }); - it('does not export the computed value to JSON', function() { + it('does not export the computed value to JSON', function () { const def = new ObjDefine(); def.comp('name', 'foo'); expect(flatten(def.create())).to.not.have.property('name'); }); }); - describe('#create', function() { - it('creates object that inherits from the prototype', function() { + describe('#create', function () { + it('creates object that inherits from the prototype', function () { function SomeClass() {} const def = new ObjDefine(null, SomeClass.prototype); @@ -129,7 +129,7 @@ describe('ObjDefine Utility', function() { expect(obj).to.be.a(SomeClass); }); - it('uses the defaults for property values', function() { + it('uses the defaults for property values', function () { const def = new ObjDefine({ name: 'bar' }); def.fact('name'); @@ -138,7 +138,7 @@ describe('ObjDefine Utility', function() { expect(obj).to.have.property('name', 'bar'); }); - it('ignores default values that are not defined properties', function() { + it('ignores default values that are not defined properties', function () { const def = new ObjDefine({ name: 'foo', name2: 'bar' }); const obj = def.create(); diff --git a/src/plugins/data/public/index_patterns/index_patterns/flatten_hit.ts b/src/plugins/data/public/index_patterns/index_patterns/flatten_hit.ts index 18c6578e3142d..c194687b7c3bf 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/flatten_hit.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/flatten_hit.ts @@ -30,7 +30,7 @@ function flattenHit(indexPattern: IndexPattern, hit: Record, deep: const fields = indexPattern.fields.getByName; (function flatten(obj, keyPrefix = '') { keyPrefix = keyPrefix ? keyPrefix + '.' : ''; - _.forOwn(obj, function(val, key) { + _.forOwn(obj, function (val, key) { key = keyPrefix + key; if (deep) { @@ -38,7 +38,7 @@ function flattenHit(indexPattern: IndexPattern, hit: Record, deep: const isNestedField = field && field.type === 'nested'; const isArrayOfObjects = Array.isArray(val) && _.isPlainObject(_.first(val)); if (isArrayOfObjects && !isNestedField) { - _.each(val, v => flatten(v, key)); + _.each(val, (v) => flatten(v, key)); return; } } else if (flat[key] !== void 0) { @@ -68,15 +68,15 @@ function flattenHit(indexPattern: IndexPattern, hit: Record, deep: } function decorateFlattenedWrapper(hit: Record, metaFields: Record) { - return function(flattened: Record) { + return function (flattened: Record) { // assign the meta fields - _.each(metaFields, function(meta) { + _.each(metaFields, function (meta) { if (meta === '_source') return; flattened[meta] = hit[meta]; }); // unwrap computed fields - _.forOwn(hit.fields, function(val, key: any) { + _.forOwn(hit.fields, function (val, key: any) { if (key[0] === '_' && !_.contains(metaFields, key)) return; flattened[key] = Array.isArray(val) && val.length === 1 ? val[0] : val; }); diff --git a/src/plugins/data/public/index_patterns/index_patterns/format_hit.ts b/src/plugins/data/public/index_patterns/index_patterns/format_hit.ts index 9b18fb98f3e02..a0597ed4b9026 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/format_hit.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/format_hit.ts @@ -64,7 +64,7 @@ export function formatHitProvider(indexPattern: IndexPattern, defaultFormat: any const cache: Record = {}; formattedCache.set(hit, cache); - _.forOwn(indexPattern.flattenHit(hit), function(val: any, fieldName?: string) { + _.forOwn(indexPattern.flattenHit(hit), function (val: any, fieldName?: string) { // sync the formatted and partial cache if (!fieldName) { return; @@ -77,7 +77,7 @@ export function formatHitProvider(indexPattern: IndexPattern, defaultFormat: any return cache; } - formatHit.formatField = function(hit: Record, fieldName: string) { + formatHit.formatField = function (hit: Record, fieldName: string) { let partials = partialFormattedCache.get(hit); if (partials && partials[fieldName] != null) { return partials[fieldName]; diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts index 305aa8575e4d7..e4058007e0a57 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.test.ts @@ -55,7 +55,7 @@ let mockFieldsFetcherResponse: any[] = []; jest.mock('./_fields_fetcher', () => ({ createFieldsFetcher: jest.fn().mockImplementation(() => ({ fetch: jest.fn().mockImplementation(() => { - return new Promise(resolve => resolve(mockFieldsFetcherResponse)); + return new Promise((resolve) => resolve(mockFieldsFetcherResponse)); }), every: jest.fn(), })), @@ -160,7 +160,7 @@ describe('IndexPattern', () => { }); describe('fields', () => { - test('should have expected properties on fields', function() { + test('should have expected properties on fields', function () { expect(indexPattern.fields[0]).toHaveProperty('displayName'); expect(indexPattern.fields[0]).toHaveProperty('filterable'); expect(indexPattern.fields[0]).toHaveProperty('format'); @@ -191,7 +191,7 @@ describe('IndexPattern', () => { test('should request date fields as docvalue_fields', () => { const { docvalueFields } = indexPattern.getComputedFields(); - const docValueFieldNames = docvalueFields.map(field => field.field); + const docValueFieldNames = docvalueFields.map((field) => field.field); expect(Object.keys(docValueFieldNames).length).toBe(3); expect(docValueFieldNames).toContain('@timestamp'); @@ -201,7 +201,7 @@ describe('IndexPattern', () => { test('should request date field doc values in date_time format', () => { const { docvalueFields } = indexPattern.getComputedFields(); - const timestampField = docvalueFields.find(field => field.field === '@timestamp'); + const timestampField = docvalueFields.find((field) => field.field === '@timestamp'); expect(timestampField).toHaveProperty('format', 'date_time'); }); @@ -237,7 +237,7 @@ describe('IndexPattern', () => { const newFields = indexPattern.getNonScriptedFields(); expect(newFields).toHaveLength(2); - expect(newFields.map(f => f.name)).toEqual(['foo', 'bar']); + expect(newFields.map((f) => f.name)).toEqual(['foo', 'bar']); }); test('should preserve the scripted fields', async () => { @@ -249,7 +249,7 @@ describe('IndexPattern', () => { // called to append scripted fields to the response from mapper.getFieldsForIndexPattern // sinon.assert.calledOnce(indexPattern.getScriptedFields); - expect(indexPattern.getScriptedFields().map(f => f.name)).toEqual( + expect(indexPattern.getScriptedFields().map((f) => f.name)).toEqual( mockLogStashFields() .filter((f: Field) => f.scripted) .map((f: Field) => f.name) @@ -313,7 +313,7 @@ describe('IndexPattern', () => { describe('popularizeField', () => { test('should increment the popularity count by default', () => { // const saveSpy = sinon.stub(indexPattern, 'save'); - indexPattern.fields.forEach(async field => { + indexPattern.fields.forEach(async (field) => { const oldCount = field.count || 0; await indexPattern.popularizeField(field.name); @@ -325,7 +325,7 @@ describe('IndexPattern', () => { test('should increment the popularity count', () => { // const saveSpy = sinon.stub(indexPattern, 'save'); - indexPattern.fields.forEach(async field => { + indexPattern.fields.forEach(async (field) => { const oldCount = field.count || 0; const incrementAmount = 4; @@ -337,7 +337,7 @@ describe('IndexPattern', () => { }); test('should decrement the popularity count', () => { - indexPattern.fields.forEach(async field => { + indexPattern.fields.forEach(async (field) => { const oldCount = field.count || 0; const incrementAmount = 4; const decrementAmount = -2; @@ -350,7 +350,7 @@ describe('IndexPattern', () => { }); test('should not go below 0', () => { - indexPattern.fields.forEach(async field => { + indexPattern.fields.forEach(async (field) => { const decrementAmount = -Number.MAX_VALUE; await indexPattern.popularizeField(field.name, decrementAmount); diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.ts b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.ts index 3780557db50d3..417d8227b121c 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_pattern.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_pattern.ts @@ -85,7 +85,7 @@ export class IndexPattern implements IIndexPattern { return _.isEmpty(serialized) ? undefined : JSON.stringify(serialized); }, _deserialize: (map = '{}') => { - return _.mapValues(JSON.parse(map), mapping => { + return _.mapValues(JSON.parse(map), (mapping) => { return this.deserializeFieldFormatMap(mapping); }); }, @@ -149,7 +149,7 @@ export class IndexPattern implements IIndexPattern { return true; } - return this.fields.every(field => { + return this.fields.every((field) => { // See https://github.com/elastic/kibana/pull/8421 const hasFieldCaps = 'aggregatable' in field && 'searchable' in field; @@ -220,7 +220,7 @@ export class IndexPattern implements IIndexPattern { } ); - each(this.getScriptedFields(), function(field) { + each(this.getScriptedFields(), function (field) { scriptFields[field.name] = { script: { source: field.script, @@ -424,7 +424,7 @@ export class IndexPattern implements IIndexPattern { const body = this.prepBody(); // What keys changed since they last pulled the index pattern const originalChangedKeys = Object.keys(body).filter( - key => body[key] !== this.originalBody[key] + (key) => body[key] !== this.originalBody[key] ); return this.savedObjectsClient .update(type, this.id, body, { version: this.version }) @@ -432,7 +432,7 @@ export class IndexPattern implements IIndexPattern { this.id = resp.id; this.version = resp._version; }) - .catch(err => { + .catch((err) => { if ( _.get(err, 'res.status') === 409 && saveAttempts++ < MAX_ATTEMPTS_TO_RESOLVE_CONFLICTS @@ -452,7 +452,7 @@ export class IndexPattern implements IIndexPattern { // and ensure we ignore the key if the server response // is the same as the original response (since that is expected // if we made a change in that key) - const serverChangedKeys = Object.keys(updatedBody).filter(key => { + const serverChangedKeys = Object.keys(updatedBody).filter((key) => { return updatedBody[key] !== body[key] && this.originalBody[key] !== updatedBody[key]; }); @@ -479,7 +479,7 @@ export class IndexPattern implements IIndexPattern { } // Set the updated response on this object - serverChangedKeys.forEach(key => { + serverChangedKeys.forEach((key) => { this[key] = samePattern[key]; }); this.version = samePattern.version; @@ -505,7 +505,7 @@ export class IndexPattern implements IIndexPattern { refreshFields() { return this._fetchFields() .then(() => this.save()) - .catch(err => { + .catch((err) => { // https://github.com/elastic/kibana/issues/9224 // This call will attempt to remap fields from the matching // ES index which may not actually exist. In that scenario, diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_patterns.ts b/src/plugins/data/public/index_patterns/index_patterns/index_patterns.ts index 515f2e7cf95ee..32b31d4f2758d 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_patterns.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_patterns.ts @@ -100,7 +100,7 @@ export class IndexPatternsService { if (!this.savedObjectsCache) { return []; } - return this.savedObjectsCache.map(obj => obj?.id); + return this.savedObjectsCache.map((obj) => obj?.id); }; getTitles = async (refresh: boolean = false): Promise => { @@ -110,7 +110,7 @@ export class IndexPatternsService { if (!this.savedObjectsCache) { return []; } - return this.savedObjectsCache.map(obj => obj?.attributes?.title); + return this.savedObjectsCache.map((obj) => obj?.attributes?.title); }; getFields = async (fields: IndexPatternCachedFieldType[], refresh: boolean = false) => { diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.mock.ts b/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.mock.ts index 2d3e357e96819..51f4fc7ce94b9 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.mock.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.mock.ts @@ -19,7 +19,7 @@ import { setup } from 'test_utils/http_test_setup'; -export const { http } = setup(injectedMetadata => { +export const { http } = setup((injectedMetadata) => { injectedMetadata.getBasePath.mockReturnValue('/hola/daro/'); }); diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.ts b/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.ts index 0dca025b2bf38..37ee80c2c29e4 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.test.ts @@ -29,7 +29,7 @@ describe('IndexPatternsApiClient', () => { indexPatternsApiClient = new IndexPatternsApiClient(http); }); - test('uses the right URI to fetch fields for time patterns', async function() { + test('uses the right URI to fetch fields for time patterns', async function () { const expectedPath = '/api/index_patterns/_fields_for_time_pattern'; await indexPatternsApiClient.getFieldsForTimePattern(); @@ -37,7 +37,7 @@ describe('IndexPatternsApiClient', () => { expect(fetchSpy).toHaveBeenCalledWith(expectedPath, expect.any(Object)); }); - test('uses the right URI to fetch fields for wildcard', async function() { + test('uses the right URI to fetch fields for wildcard', async function () { const expectedPath = '/api/index_patterns/_fields_for_wildcard'; await indexPatternsApiClient.getFieldsForWildcard(); @@ -45,7 +45,7 @@ describe('IndexPatternsApiClient', () => { expect(fetchSpy).toHaveBeenCalledWith(expectedPath, expect.any(Object)); }); - test('uses the right URI to fetch fields for wildcard given a type', async function() { + test('uses the right URI to fetch fields for wildcard given a type', async function () { const expectedPath = '/api/index_patterns/rollup/_fields_for_wildcard'; await indexPatternsApiClient.getFieldsForWildcard({ type: 'rollup' }); diff --git a/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.ts b/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.ts index 0007d1780c25b..cd189ccf0135b 100644 --- a/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.ts +++ b/src/plugins/data/public/index_patterns/index_patterns/index_patterns_api_client.ts @@ -54,13 +54,7 @@ export class IndexPatternsApiClient { } _getUrl(path: string[]) { - return ( - API_BASE_URL + - path - .filter(Boolean) - .map(encodeURIComponent) - .join('/') - ); + return API_BASE_URL + path.filter(Boolean).map(encodeURIComponent).join('/'); } getFieldsForTimePattern(options: GetFieldsOptions = {}) { diff --git a/src/plugins/data/public/index_patterns/lib/validate_index_pattern.test.ts b/src/plugins/data/public/index_patterns/lib/validate_index_pattern.test.ts index 74e420ffeb5c0..87a702b3a012d 100644 --- a/src/plugins/data/public/index_patterns/lib/validate_index_pattern.test.ts +++ b/src/plugins/data/public/index_patterns/lib/validate_index_pattern.test.ts @@ -29,7 +29,7 @@ describe('Index Pattern Utils', () => { }); it('should not allow illegal characters', () => { - ILLEGAL_CHARACTERS_VISIBLE.forEach(char => { + ILLEGAL_CHARACTERS_VISIBLE.forEach((char) => { const errors = validateIndexPattern(`pattern${char}`); expect(errors[ILLEGAL_CHARACTERS_KEY]).toEqual([char]); }); diff --git a/src/plugins/data/public/query/filter_manager/filter_manager.test.ts b/src/plugins/data/public/query/filter_manager/filter_manager.test.ts index 3b4ca08cbbf14..3c69a498e74cd 100644 --- a/src/plugins/data/public/query/filter_manager/filter_manager.test.ts +++ b/src/plugins/data/public/query/filter_manager/filter_manager.test.ts @@ -154,7 +154,7 @@ describe('filter_manager', () => { expect(updateListener.callCount).toBe(2); }); - test('changing a disabled filter should fire only update event', async function() { + test('changing a disabled filter should fire only update event', async function () { const updateStub = jest.fn(); const fetchStub = jest.fn(); const f1 = getFilter(FilterStateStore.GLOBAL_STATE, true, false, 'age', 34); @@ -178,7 +178,7 @@ describe('filter_manager', () => { expect(updateStub).toBeCalledTimes(1); }); - test('should merge multiple conflicting app filters', async function() { + test('should merge multiple conflicting app filters', async function () { filterManager.addFilters(readyFilters, true); const appFilter1 = _.cloneDeep(readyFilters[1]); appFilter1.meta.negate = true; @@ -198,13 +198,13 @@ describe('filter_manager', () => { const res = filterManager.getFilters(); expect(res).toHaveLength(3); expect( - res.filter(function(filter) { + res.filter(function (filter) { return filter.$state && filter.$state.store === FilterStateStore.GLOBAL_STATE; }).length ).toBe(3); }); - test('should set app filters and merge them with duplicate global filters', async function() { + test('should set app filters and merge them with duplicate global filters', async function () { const [filter, ...otherFilters] = readyFilters; filterManager.addFilters(otherFilters, true); const appFilter1 = _.cloneDeep(readyFilters[1]); @@ -219,7 +219,7 @@ describe('filter_manager', () => { expect(newAppFilters).toHaveLength(1); }); - test('should set global filters and remove any duplicated app filters', async function() { + test('should set global filters and remove any duplicated app filters', async function () { filterManager.addFilters(readyFilters, false); const globalFilter1 = _.cloneDeep(readyFilters[1]); const globalFilter2 = _.cloneDeep(readyFilters[2]); @@ -273,7 +273,7 @@ describe('filter_manager', () => { }); describe('add filters', () => { - test('app state should accept a single filter', async function() { + test('app state should accept a single filter', async function () { updateSubscription = filterManager.getUpdates$().subscribe(updateListener); const f1 = getFilter(FilterStateStore.APP_STATE, false, false, 'age', 34); filterManager.addFilters(f1); @@ -398,7 +398,7 @@ describe('filter_manager', () => { } }); - test('should return app and global filters', async function() { + test('should return app and global filters', async function () { const filters = getFiltersArray(); filterManager.addFilters(filters[0], false); filterManager.addFilters(filters[1], true); @@ -421,7 +421,7 @@ describe('filter_manager', () => { expect(res).toHaveLength(3); }); - test('should skip appStateStub filters that match globalStateStub filters', async function() { + test('should skip appStateStub filters that match globalStateStub filters', async function () { filterManager.addFilters(readyFilters, true); const appFilter = _.cloneDeep(readyFilters[1]); filterManager.addFilters(appFilter, false); @@ -429,12 +429,12 @@ describe('filter_manager', () => { // global filters should be listed first const res = filterManager.getFilters(); expect(res).toHaveLength(3); - _.each(res, function(filter) { + _.each(res, function (filter) { expect(filter.$state && filter.$state.store).toBe(FilterStateStore.GLOBAL_STATE); }); }); - test('should allow overwriting a positive filter by a negated one', async function() { + test('should allow overwriting a positive filter by a negated one', async function () { // Add negate: false version of the filter const filter = _.cloneDeep(readyFilters[0]); filter.meta.negate = false; @@ -453,7 +453,7 @@ describe('filter_manager', () => { expect(filterManager.getFilters()[0]).toEqual(negatedFilter); }); - test('should allow overwriting a negated filter by a positive one', async function() { + test('should allow overwriting a negated filter by a positive one', async function () { // Add negate: true version of the same filter const negatedFilter = _.cloneDeep(readyFilters[0]); negatedFilter.meta.negate = true; @@ -473,7 +473,7 @@ describe('filter_manager', () => { expect(filterManager.getFilters()[0]).toEqual(filter); }); - test('should fire the update and fetch events', async function() { + test('should fire the update and fetch events', async function () { const updateStub = jest.fn(); const fetchStub = jest.fn(); @@ -493,8 +493,8 @@ describe('filter_manager', () => { }); }); - describe('filter reconciliation', function() { - test('should de-dupe app filters being added', async function() { + describe('filter reconciliation', function () { + test('should de-dupe app filters being added', async function () { const newFilter = _.cloneDeep(readyFilters[1]); filterManager.addFilters(readyFilters, false); expect(filterManager.getFilters()).toHaveLength(3); @@ -503,7 +503,7 @@ describe('filter_manager', () => { expect(filterManager.getFilters()).toHaveLength(3); }); - test('should de-dupe global filters being added', async function() { + test('should de-dupe global filters being added', async function () { const newFilter = _.cloneDeep(readyFilters[1]); filterManager.addFilters(readyFilters, true); expect(filterManager.getFilters()).toHaveLength(3); @@ -530,7 +530,7 @@ describe('filter_manager', () => { expect(filterManager.getFilters()).toHaveLength(1); }); - test('should mutate global filters on appStateStub filter changes', async function() { + test('should mutate global filters on appStateStub filter changes', async function () { const idx = 1; filterManager.addFilters(readyFilters, true); @@ -542,14 +542,14 @@ describe('filter_manager', () => { filterManager.addFilters(appFilter); const res = filterManager.getFilters(); expect(res).toHaveLength(3); - _.each(res, function(filter, i) { + _.each(res, function (filter, i) { expect(filter.$state && filter.$state.store).toBe('globalState'); // make sure global filter actually mutated expect(filter.meta.negate).toBe(i === idx); }); }); - test('should merge conflicting app filters', async function() { + test('should merge conflicting app filters', async function () { filterManager.addFilters(readyFilters, true); const appFilter = _.cloneDeep(readyFilters[1]); appFilter.meta.negate = true; @@ -562,15 +562,15 @@ describe('filter_manager', () => { const res = filterManager.getFilters(); expect(res).toHaveLength(3); expect( - res.filter(function(filter) { + res.filter(function (filter) { return filter.$state && filter.$state.store === FilterStateStore.GLOBAL_STATE; }).length ).toBe(3); }); - test('should enable disabled filters - global state', async function() { + test('should enable disabled filters - global state', async function () { // test adding to globalStateStub - const disabledFilters = _.map(readyFilters, function(filter) { + const disabledFilters = _.map(readyFilters, function (filter) { const f = _.cloneDeep(filter); f.meta.disabled = true; return f; @@ -581,15 +581,15 @@ describe('filter_manager', () => { const res = filterManager.getFilters(); expect(res).toHaveLength(3); expect( - res.filter(function(filter) { + res.filter(function (filter) { return filter.meta.disabled === false; }).length ).toBe(3); }); - test('should enable disabled filters - app state', async function() { + test('should enable disabled filters - app state', async function () { // test adding to appStateStub - const disabledFilters = _.map(readyFilters, function(filter) { + const disabledFilters = _.map(readyFilters, function (filter) { const f = _.cloneDeep(filter); f.meta.disabled = true; return f; @@ -600,7 +600,7 @@ describe('filter_manager', () => { const res = filterManager.getFilters(); expect(res).toHaveLength(3); expect( - res.filter(function(filter) { + res.filter(function (filter) { return filter.meta.disabled === false; }).length ).toBe(3); @@ -652,21 +652,21 @@ describe('filter_manager', () => { expect(filterManager.getFilters()).toHaveLength(2); }); - test('should remove the filter from appStateStub', async function() { + test('should remove the filter from appStateStub', async function () { filterManager.addFilters(readyFilters, false); expect(filterManager.getAppFilters()).toHaveLength(3); filterManager.removeFilter(readyFilters[0]); expect(filterManager.getAppFilters()).toHaveLength(2); }); - test('should remove the filter from globalStateStub', async function() { + test('should remove the filter from globalStateStub', async function () { filterManager.addFilters(readyFilters, true); expect(filterManager.getGlobalFilters()).toHaveLength(3); filterManager.removeFilter(readyFilters[0]); expect(filterManager.getGlobalFilters()).toHaveLength(2); }); - test('should fire the update and fetch events', async function() { + test('should fire the update and fetch events', async function () { const updateStub = jest.fn(); const fetchStub = jest.fn(); @@ -687,7 +687,7 @@ describe('filter_manager', () => { expect(updateStub).toBeCalledTimes(1); }); - test('should remove matching filters', async function() { + test('should remove matching filters', async function () { filterManager.addFilters([readyFilters[0], readyFilters[1]], true); filterManager.addFilters([readyFilters[2]], false); @@ -697,7 +697,7 @@ describe('filter_manager', () => { expect(filterManager.getGlobalFilters()).toHaveLength(1); }); - test('should remove matching filters by comparison', async function() { + test('should remove matching filters by comparison', async function () { filterManager.addFilters([readyFilters[0], readyFilters[1]], true); filterManager.addFilters([readyFilters[2]], false); @@ -711,7 +711,7 @@ describe('filter_manager', () => { expect(filterManager.getGlobalFilters()).toHaveLength(1); }); - test('should do nothing with a non-matching filter', async function() { + test('should do nothing with a non-matching filter', async function () { filterManager.addFilters([readyFilters[0], readyFilters[1]], true); filterManager.addFilters([readyFilters[2]], false); @@ -723,7 +723,7 @@ describe('filter_manager', () => { expect(filterManager.getGlobalFilters()).toHaveLength(2); }); - test('should remove all the filters from both states', async function() { + test('should remove all the filters from both states', async function () { filterManager.addFilters([readyFilters[0], readyFilters[1]], true); filterManager.addFilters([readyFilters[2]], false); expect(filterManager.getAppFilters()).toHaveLength(1); @@ -736,7 +736,7 @@ describe('filter_manager', () => { }); describe('invert', () => { - test('should fire the update and fetch events', async function() { + test('should fire the update and fetch events', async function () { filterManager.addFilters(readyFilters); expect(filterManager.getFilters()).toHaveLength(3); diff --git a/src/plugins/data/public/query/filter_manager/filter_manager.ts b/src/plugins/data/public/query/filter_manager/filter_manager.ts index e206286bce147..d58a0eb45c04f 100644 --- a/src/plugins/data/public/query/filter_manager/filter_manager.ts +++ b/src/plugins/data/public/query/filter_manager/filter_manager.ts @@ -53,8 +53,8 @@ export class FilterManager { // existing globalFilters should be mutated by appFilters // ignore original appFilters which are already inside globalFilters const cleanedAppFilters: Filter[] = []; - _.each(appFilters, function(filter, i) { - const match = _.find(globalFilters, function(globalFilter) { + _.each(appFilters, function (filter, i) { + const match = _.find(globalFilters, function (globalFilter) { return compareFilters(globalFilter, filter); }); @@ -203,7 +203,7 @@ export class FilterManager { } public removeFilter(filter: Filter) { - const filterIndex = _.findIndex(this.filters, item => { + const filterIndex = _.findIndex(this.filters, (item) => { return _.isEqual(item.meta, filter.meta) && _.isEqual(item.query, filter.query); }); diff --git a/src/plugins/data/public/query/filter_manager/lib/generate_filters.ts b/src/plugins/data/public/query/filter_manager/lib/generate_filters.ts index 4220df7b1a49b..432a763bfd48c 100644 --- a/src/plugins/data/public/query/filter_manager/lib/generate_filters.ts +++ b/src/plugins/data/public/query/filter_manager/lib/generate_filters.ts @@ -39,7 +39,7 @@ function getExistingFilter( value: any ): Filter | undefined { // TODO: On array fields, negating does not negate the combination, rather all terms - return _.find(appFilters, function(filter) { + return _.find(appFilters, function (filter) { if (!filter) return; if (fieldName === '_exists_' && isExistsFilter(filter)) { @@ -95,7 +95,7 @@ export function generateFilters( const negate = operation === '-'; let filter; - _.each(values, function(value) { + _.each(values, function (value) { const existing = getExistingFilter(appFilters, fieldName, value); if (existing) { diff --git a/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.test.ts b/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.test.ts index 8322e79dd67d1..780db36426dc1 100644 --- a/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/generate_mapping_chain.test.ts @@ -97,7 +97,7 @@ describe('filter manager utilities', () => { expect(result).toEqual({ key: 'test', value: 'example' }); }); - test('should throw an error if no functions match', async done => { + test('should throw an error if no functions match', async (done) => { const filter = buildEmptyFilter(true); mapping.throws(filter); diff --git a/src/plugins/data/public/query/filter_manager/lib/map_filter.test.ts b/src/plugins/data/public/query/filter_manager/lib/map_filter.test.ts index f75970d4dec18..35d2f2b7b294e 100644 --- a/src/plugins/data/public/query/filter_manager/lib/map_filter.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/map_filter.test.ts @@ -77,7 +77,7 @@ describe('filter manager utilities', () => { expect(after.meta).toHaveProperty('negate', false); }); - test('should finish with a catch', async done => { + test('should finish with a catch', async (done) => { const before: any = { meta: { index: 'logstash-*' } }; try { diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.ts index c90c056f4eb35..b5715e33a4677 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_default.ts @@ -22,7 +22,7 @@ import { Filter, FILTERS } from '../../../../../common'; export const mapDefault = (filter: Filter) => { const metaProperty = /(^\$|meta)/; - const key = find(keys(filter), item => !item.match(metaProperty)); + const key = find(keys(filter), (item) => !item.match(metaProperty)); if (key) { const type = FILTERS.CUSTOM; diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.test.ts index 83c39e449d3ea..0e7b12b6f5f58 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_exists.test.ts @@ -44,7 +44,7 @@ describe('filter manager utilities', () => { expect(result).toHaveProperty('value', 'exists'); }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const filter = buildEmptyFilter(true); try { diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.test.ts index 97f275b05a520..035dadfd7432a 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.test.ts @@ -79,7 +79,7 @@ describe('filter manager utilities', () => { } }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } }, diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.ts index f32c459baee5d..c66e65f00efbd 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_bounding_box.ts @@ -41,7 +41,7 @@ const getFormattedValueFn = (params: any) => { }; const getParams = (filter: GeoBoundingBoxFilter) => { - const key = Object.keys(filter.geo_bounding_box).filter(k => k !== 'ignore_unmapped')[0]; + const key = Object.keys(filter.geo_bounding_box).filter((k) => k !== 'ignore_unmapped')[0]; const params = filter.geo_bounding_box[key]; return { diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.test.ts index 4af881aa58542..8da98b3a329d6 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.test.ts @@ -70,7 +70,7 @@ describe('filter manager utilities', () => { } }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const wrongFilter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } }, diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.ts index df5379289dd28..55f744558942a 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_geo_polygon.ts @@ -36,7 +36,7 @@ const getFormattedValueFn = (points: string[]) => { }; function getParams(filter: GeoPolygonFilter) { - const key = Object.keys(filter.geo_polygon).filter(k => k !== 'ignore_unmapped')[0]; + const key = Object.keys(filter.geo_polygon).filter((k) => k !== 'ignore_unmapped')[0]; const params = filter.geo_polygon[key]; return { diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.test.ts index b22583ff8bb24..3d50b87bb32f8 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_match_all.test.ts @@ -38,7 +38,7 @@ describe('filter_manager/lib', () => { }); describe('when given a filter that is not match_all', () => { - test('filter is rejected', async done => { + test('filter is rejected', async (done) => { delete filter.match_all; try { diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.test.ts index 67e5987818fb5..d851e96ad6ac6 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_missing.test.ts @@ -33,7 +33,7 @@ describe('filter manager utilities', () => { expect(result).toHaveProperty('value', 'missing'); }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const filter = buildEmptyFilter(true); try { diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.test.ts index 5dd10ce30111f..8f4a8d1bb35a1 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_phrase.test.ts @@ -38,7 +38,7 @@ describe('filter manager utilities', () => { } }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } }, diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.test.ts index 0589215955562..9b75d5a769d3e 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_query_string.test.ts @@ -30,7 +30,7 @@ describe('filter manager utilities', () => { expect(result).toHaveProperty('value', 'foo:bar'); }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const filter = buildEmptyFilter(true); try { diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.test.ts index c8868b412707b..a6f587ddc7d32 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_range.test.ts @@ -37,7 +37,7 @@ describe('filter manager utilities', () => { } }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const filter = { meta: { index: 'logstash-*' }, query: { query_string: { query: 'foo:bar' } }, diff --git a/src/plugins/data/public/query/filter_manager/lib/mappers/map_spatial_filter.test.ts b/src/plugins/data/public/query/filter_manager/lib/mappers/map_spatial_filter.test.ts index aee1bf257be01..5e58b2c14c262 100644 --- a/src/plugins/data/public/query/filter_manager/lib/mappers/map_spatial_filter.test.ts +++ b/src/plugins/data/public/query/filter_manager/lib/mappers/map_spatial_filter.test.ts @@ -65,7 +65,7 @@ describe('mapSpatialFilter()', () => { expect(result).toHaveProperty('type', FILTERS.SPATIAL_FILTER); }); - test('should return undefined for none matching', async done => { + test('should return undefined for none matching', async (done) => { const filter = { meta: { key: 'location', diff --git a/src/plugins/data/public/query/lib/from_user.test.ts b/src/plugins/data/public/query/lib/from_user.test.ts index b74a1a07dc356..208558bb138c6 100644 --- a/src/plugins/data/public/query/lib/from_user.test.ts +++ b/src/plugins/data/public/query/lib/from_user.test.ts @@ -19,23 +19,23 @@ import { fromUser } from '../'; -describe('user input helpers', function() { - describe('user input parser', function() { - it('should return the input if passed an object', function() { +describe('user input helpers', function () { + describe('user input parser', function () { + it('should return the input if passed an object', function () { expect(fromUser({ foo: 'bar' })).toEqual({ foo: 'bar' }); }); - it('unless the object is empty, then convert it to an empty string', function() { + it('unless the object is empty, then convert it to an empty string', function () { expect(fromUser({})).toEqual(''); }); - it('should pass through input strings that not start with {', function() { + it('should pass through input strings that not start with {', function () { expect(fromUser('foo')).toEqual('foo'); expect(fromUser('400')).toEqual('400'); expect(fromUser('true')).toEqual('true'); }); - it('should parse valid JSON and return the object instead of a string', function() { + it('should parse valid JSON and return the object instead of a string', function () { expect(fromUser('{}')).toEqual({}); // invalid json remains a string diff --git a/src/plugins/data/public/query/lib/match_pairs.ts b/src/plugins/data/public/query/lib/match_pairs.ts index d5cfb4f99c9d5..ce8b5f17644e7 100644 --- a/src/plugins/data/public/query/lib/match_pairs.ts +++ b/src/plugins/data/public/query/lib/match_pairs.ts @@ -31,8 +31,8 @@ */ const pairs = ['()', '[]', '{}', `''`, '""']; -const openers = pairs.map(pair => pair[0]); -const closers = pairs.map(pair => pair[1]); +const openers = pairs.map((pair) => pair[0]); +const closers = pairs.map((pair) => pair[1]); interface MatchPairsOptions { value: string; diff --git a/src/plugins/data/public/query/persisted_log/persisted_log.ts b/src/plugins/data/public/query/persisted_log/persisted_log.ts index 553b0bf5ef7e0..f61315b85b195 100644 --- a/src/plugins/data/public/query/persisted_log/persisted_log.ts +++ b/src/plugins/data/public/query/persisted_log/persisted_log.ts @@ -64,7 +64,7 @@ export class PersistedLog { // remove any matching items from the stack if option is set if (this.filterDuplicates) { - _.remove(this.items, item => { + _.remove(this.items, (item) => { return this.isDuplicate(item, val); }); } diff --git a/src/plugins/data/public/query/saved_query/saved_query_service.test.ts b/src/plugins/data/public/query/saved_query/saved_query_service.test.ts index a86a5b4ed401e..584eb01f44457 100644 --- a/src/plugins/data/public/query/saved_query/saved_query_service.test.ts +++ b/src/plugins/data/public/query/saved_query/saved_query_service.test.ts @@ -89,7 +89,7 @@ describe('saved query service', () => { mockSavedObjectsClient.delete.mockReset(); }); - describe('saveQuery', function() { + describe('saveQuery', function () { it('should create a saved object for the given attributes', async () => { mockSavedObjectsClient.create.mockReturnValue({ id: 'foo', @@ -165,7 +165,7 @@ describe('saved query service', () => { expect(error).not.toBe(null); }); }); - describe('findSavedQueries', function() { + describe('findSavedQueries', function () { it('should find and return saved queries without search text or pagination parameters', async () => { mockSavedObjectsClient.find.mockReturnValue({ savedObjects: [{ id: 'foo', attributes: savedQueryAttributes }], @@ -276,7 +276,7 @@ describe('saved query service', () => { }); }); - describe('getSavedQuery', function() { + describe('getSavedQuery', function () { it('should retrieve a saved query by id', async () => { mockSavedObjectsClient.get.mockReturnValue({ id: 'foo', attributes: savedQueryAttributes }); @@ -291,14 +291,14 @@ describe('saved query service', () => { }); }); - describe('deleteSavedQuery', function() { + describe('deleteSavedQuery', function () { it('should delete the saved query for the given ID', async () => { await deleteSavedQuery('foo'); expect(mockSavedObjectsClient.delete).toHaveBeenCalledWith('query', 'foo'); }); }); - describe('getAllSavedQueries', function() { + describe('getAllSavedQueries', function () { it('should return all the saved queries', async () => { mockSavedObjectsClient.find.mockReturnValue({ savedObjects: [{ id: 'foo', attributes: savedQueryAttributes }], @@ -324,7 +324,7 @@ describe('saved query service', () => { }); }); - describe('getSavedQueryCount', function() { + describe('getSavedQueryCount', function () { it('should return the total number of saved queries', async () => { mockSavedObjectsClient.find.mockReturnValue({ total: 1, diff --git a/src/plugins/data/public/query/state_sync/connect_to_query_state.ts b/src/plugins/data/public/query/state_sync/connect_to_query_state.ts index 3256c1cbd65a1..e74497a5053b4 100644 --- a/src/plugins/data/public/query/state_sync/connect_to_query_state.ts +++ b/src/plugins/data/public/query/state_sync/connect_to_query_state.ts @@ -125,7 +125,7 @@ export const connectToQueryState = ( .pipe( filter(({ changes, state }) => { if (updateInProgress) return false; - return syncKeys.some(syncKey => changes[syncKey]); + return syncKeys.some((syncKey) => changes[syncKey]); }), map(({ changes }) => { const newState: QueryState = {}; @@ -150,10 +150,10 @@ export const connectToQueryState = ( return newState; }) ) - .subscribe(newState => { + .subscribe((newState) => { stateContainer.set({ ...stateContainer.get(), ...newState }); }), - stateContainer.state$.subscribe(state => { + stateContainer.state$.subscribe((state) => { updateInProgress = true; // cloneDeep is required because services are mutating passed objects @@ -204,6 +204,6 @@ export const connectToQueryState = ( ]; return () => { - subs.forEach(s => s.unsubscribe()); + subs.forEach((s) => s.unsubscribe()); }; }; diff --git a/src/plugins/data/public/query/state_sync/create_global_query_observable.ts b/src/plugins/data/public/query/state_sync/create_global_query_observable.ts index dd075f9be7d94..87032925294c6 100644 --- a/src/plugins/data/public/query/state_sync/create_global_query_observable.ts +++ b/src/plugins/data/public/query/state_sync/create_global_query_observable.ts @@ -32,7 +32,7 @@ export function createQueryStateObservable({ timefilter: TimefilterSetup; filterManager: FilterManager; }): Observable<{ changes: QueryStateChange; state: QueryState }> { - return new Observable(subscriber => { + return new Observable((subscriber) => { const state = createStateContainer({ time: timefilter.getTime(), refreshInterval: timefilter.getRefreshInterval(), @@ -53,8 +53,8 @@ export function createQueryStateObservable({ currentChange.filters = true; const { filters } = state.get(); - const globalOld = filters?.filter(f => isFilterPinned(f)); - const appOld = filters?.filter(f => !isFilterPinned(f)); + const globalOld = filters?.filter((f) => isFilterPinned(f)); + const appOld = filters?.filter((f) => !isFilterPinned(f)); const globalNew = filterManager.getGlobalFilters(); const appNew = filterManager.getAppFilters(); @@ -73,7 +73,7 @@ export function createQueryStateObservable({ }), state.state$ .pipe( - map(newState => ({ state: newState, changes: currentChange })), + map((newState) => ({ state: newState, changes: currentChange })), tap(() => { currentChange = {}; }) @@ -81,7 +81,7 @@ export function createQueryStateObservable({ .subscribe(subscriber), ]; return () => { - subs.forEach(s => s.unsubscribe()); + subs.forEach((s) => s.unsubscribe()); }; }); } diff --git a/src/plugins/data/public/query/state_sync/sync_state_with_url.ts b/src/plugins/data/public/query/state_sync/sync_state_with_url.ts index 77e5b0ab02dc1..4d3da7b9313a3 100644 --- a/src/plugins/data/public/query/state_sync/sync_state_with_url.ts +++ b/src/plugins/data/public/query/state_sync/sync_state_with_url.ts @@ -84,7 +84,7 @@ export const syncQueryStateWithUrl = ( stateStorage: kbnUrlStateStorage, stateContainer: { ...globalQueryStateContainer, - set: state => { + set: (state) => { if (state) { // syncState utils requires to handle incoming "null" value globalQueryStateContainer.set(state); diff --git a/src/plugins/data/public/query/timefilter/get_time.ts b/src/plugins/data/public/query/timefilter/get_time.ts index 9cdd25d3213ce..3706972ce4a2e 100644 --- a/src/plugins/data/public/query/timefilter/get_time.ts +++ b/src/plugins/data/public/query/timefilter/get_time.ts @@ -54,7 +54,9 @@ function createTimeRangeFilter( if (!indexPattern) { return; } - const field = indexPattern.fields.find(f => f.name === (fieldName || indexPattern.timeFieldName)); + const field = indexPattern.fields.find( + (f) => f.name === (fieldName || indexPattern.timeFieldName) + ); if (!field) { return; } diff --git a/src/plugins/data/public/query/timefilter/lib/diff_time_picker_vals.ts b/src/plugins/data/public/query/timefilter/lib/diff_time_picker_vals.ts index 850c87635be9c..3a9402209be20 100644 --- a/src/plugins/data/public/query/timefilter/lib/diff_time_picker_vals.ts +++ b/src/plugins/data/public/query/timefilter/lib/diff_time_picker_vals.ts @@ -22,7 +22,7 @@ import _ from 'lodash'; import { RefreshInterval } from '../../../../common'; import { InputTimeRange } from '../types'; -const valueOf = function(o: any) { +const valueOf = function (o: any) { if (o) return o.valueOf(); }; diff --git a/src/plugins/data/public/search/aggs/agg_config.test.ts b/src/plugins/data/public/search/aggs/agg_config.test.ts index b5df90313230c..6a0dad07b69bb 100644 --- a/src/plugins/data/public/search/aggs/agg_config.test.ts +++ b/src/plugins/data/public/search/aggs/agg_config.test.ts @@ -375,7 +375,7 @@ describe('AggConfig', () => { fieldFormats.getDefaultInstance = (() => ({ getConverterFor: (t?: string) => t || identity, })) as any; - indexPattern.fields.getByName = name => + indexPattern.fields.getByName = (name) => ({ format: { getConverterFor: (t?: string) => t || identity, @@ -500,7 +500,7 @@ describe('AggConfig', () => { // Overwrite the `ranges` param in the `range` agg with a mock toExpressionAst function const range: MetricAggType = typesRegistry.get('range'); range.expressionName = 'aggRange'; - const rangesParam = range.params.find(p => p.name === 'ranges'); + const rangesParam = range.params.find((p) => p.name === 'ranges'); rangesParam!.toExpressionAst = (val: any) => ({ type: 'function', function: 'aggRanges', @@ -623,7 +623,7 @@ describe('AggConfig', () => { fieldFormats.getDefaultInstance = (() => ({ getConverterFor: (t?: string) => t || identity, })) as any; - indexPattern.fields.getByName = name => + indexPattern.fields.getByName = (name) => ({ format: { getConverterFor: (t?: string) => t || identity, @@ -649,10 +649,7 @@ describe('AggConfig', () => { }, }; expect(aggConfig.fieldFormatter().toString()).toBe( - aggConfig - .getField() - .format.getConverterFor() - .toString() + aggConfig.getField().format.getConverterFor().toString() ); }); diff --git a/src/plugins/data/public/search/aggs/agg_config.ts b/src/plugins/data/public/search/aggs/agg_config.ts index 86a2c3e0e82e4..ee4116eefc0e2 100644 --- a/src/plugins/data/public/search/aggs/agg_config.ts +++ b/src/plugins/data/public/search/aggs/agg_config.ts @@ -75,12 +75,12 @@ export class AggConfig { static ensureIds(list: any[]) { const have: IAggConfig[] = []; const haveNot: AggConfigOptions[] = []; - list.forEach(function(obj) { + list.forEach(function (obj) { (obj.id ? have : haveNot).push(obj); }); let nextId = AggConfig.nextId(have); - haveNot.forEach(function(obj) { + haveNot.forEach(function (obj) { obj.id = String(nextId++); }); @@ -95,7 +95,7 @@ export class AggConfig { static nextId(list: IAggConfig[]) { return ( 1 + - list.reduce(function(max, obj) { + list.reduce(function (max, obj) { return Math.max(max, +obj.id || 0); }, 0) ); @@ -154,7 +154,7 @@ export class AggConfig { from = from || this.params || {}; const to = (this.params = {} as any); - this.getAggParams().forEach(aggParam => { + this.getAggParams().forEach((aggParam) => { let val = from[aggParam.name]; if (val == null) { @@ -323,7 +323,7 @@ export class AggConfig { // Go through each of the params and convert to an array of expression args. const params = Object.entries(rest.params).reduce((acc, [key, value]) => { - const deserializedParam = this.getAggParams().find(p => p.name === key); + const deserializedParam = this.getAggParams().find((p) => p.name === key); if (deserializedParam && deserializedParam.toExpressionAst) { // If the param provides `toExpressionAst`, we call it with the value @@ -454,7 +454,7 @@ export class AggConfig { if (this.__typeDecorations) { _.forOwn( this.__typeDecorations, - function(prop, name: string | undefined) { + function (prop, name: string | undefined) { // @ts-ignore delete this[name]; }, diff --git a/src/plugins/data/public/search/aggs/agg_configs.test.ts b/src/plugins/data/public/search/aggs/agg_configs.test.ts index 653bf6a266df6..6e6fb3350d901 100644 --- a/src/plugins/data/public/search/aggs/agg_configs.test.ts +++ b/src/plugins/data/public/search/aggs/agg_configs.test.ts @@ -172,7 +172,7 @@ describe('AggConfigs', () => { const ac = new AggConfigs(indexPattern, configStates, { typesRegistry, fieldFormats }); const sorted = ac.getRequestAggs(); - const aggs = indexBy(ac.aggs, agg => agg.type.name); + const aggs = indexBy(ac.aggs, (agg) => agg.type.name); expect(sorted.shift()).toBe(aggs.terms); expect(sorted.shift()).toBe(aggs.histogram); @@ -195,7 +195,7 @@ describe('AggConfigs', () => { const ac = new AggConfigs(indexPattern, configStates, { typesRegistry, fieldFormats }); const sorted = ac.getResponseAggs(); - const aggs = indexBy(ac.aggs, agg => agg.type.name); + const aggs = indexBy(ac.aggs, (agg) => agg.type.name); expect(sorted.shift()).toBe(aggs.terms); expect(sorted.shift()).toBe(aggs.date_histogram); @@ -212,7 +212,7 @@ describe('AggConfigs', () => { const ac = new AggConfigs(indexPattern, configStates, { typesRegistry, fieldFormats }); const sorted = ac.getResponseAggs(); - const aggs = indexBy(ac.aggs, agg => agg.type.name); + const aggs = indexBy(ac.aggs, (agg) => agg.type.name); expect(sorted.shift()).toBe(aggs.terms); expect(sorted.shift()).toBe(aggs.date_histogram); @@ -226,7 +226,7 @@ describe('AggConfigs', () => { describe('#toDsl', () => { beforeEach(() => { indexPattern = stubIndexPattern as IndexPattern; - indexPattern.fields.getByName = name => (name as unknown) as IndexPatternField; + indexPattern.fields.getByName = (name) => (name as unknown) as IndexPatternField; }); it('uses the sorted aggs', () => { @@ -250,7 +250,7 @@ describe('AggConfigs', () => { fieldFormats, }); - const aggInfos = ac.aggs.map(aggConfig => { + const aggInfos = ac.aggs.map((aggConfig) => { const football = {}; aggConfig.toDsl = jest.fn().mockImplementation(() => football); @@ -328,7 +328,7 @@ describe('AggConfigs', () => { expect(typeof dsl[histo.id]).toBe('object'); expect(dsl[histo.id]).toHaveProperty('aggs'); - metrics.forEach(metric => { + metrics.forEach((metric) => { expect(dsl[histo.id].aggs).toHaveProperty(metric.id); expect(dsl[histo.id].aggs[metric.id]).not.toHaveProperty('aggs'); }); diff --git a/src/plugins/data/public/search/aggs/agg_configs.ts b/src/plugins/data/public/search/aggs/agg_configs.ts index d2151a2c5ed4d..6cc03be292d7b 100644 --- a/src/plugins/data/public/search/aggs/agg_configs.ts +++ b/src/plugins/data/public/search/aggs/agg_configs.ts @@ -95,7 +95,7 @@ export class AggConfigs { this.timeRange = timeRange; const updateAggTimeRange = (agg: AggConfig) => { - _.each(agg.params, param => { + _.each(agg.params, (param) => { if (param instanceof AggConfig) { updateAggTimeRange(param); } @@ -176,10 +176,10 @@ export class AggConfigs { if (hierarchical) { // collect all metrics, and filter out the ones that we won't be copying nestedMetrics = this.aggs - .filter(function(agg) { + .filter(function (agg) { return agg.type.type === 'metrics' && agg.type.name !== 'count'; }) - .map(agg => { + .map((agg) => { return { config: agg, dsl: agg.toDsl(this), @@ -239,15 +239,15 @@ export class AggConfigs { } byId(id: string) { - return this.aggs.find(agg => agg.id === id); + return this.aggs.find((agg) => agg.id === id); } byName(name: string) { - return this.aggs.filter(agg => agg.type?.name === name); + return this.aggs.filter((agg) => agg.type?.name === name); } byType(type: string) { - return this.aggs.filter(agg => agg.type?.type === type); + return this.aggs.filter((agg) => agg.type?.type === type); } byTypeName(type: string) { @@ -255,13 +255,13 @@ export class AggConfigs { } bySchemaName(schema: string) { - return this.aggs.filter(agg => agg.schema === schema); + return this.aggs.filter((agg) => agg.schema === schema); } getRequestAggs(): AggConfig[] { // collect all the aggregations const aggregations = this.aggs - .filter(agg => agg.enabled && agg.type) + .filter((agg) => agg.enabled && agg.type) .reduce((requestValuesAggs, agg: AggConfig) => { const aggs = agg.getRequestAggs(); return aggs ? requestValuesAggs.concat(aggs) : requestValuesAggs; @@ -288,7 +288,7 @@ export class AggConfigs { * @return {array[AggConfig]} */ getResponseAggs(): AggConfig[] { - return this.getRequestAggs().reduce(function(responseValuesAggs, agg: AggConfig) { + return this.getRequestAggs().reduce(function (responseValuesAggs, agg: AggConfig) { const aggs = agg.getResponseAggs(); return aggs ? responseValuesAggs.concat(aggs) : responseValuesAggs; }, [] as AggConfig[]); @@ -303,7 +303,7 @@ export class AggConfigs { */ getResponseAggById(id: string): AggConfig | undefined { id = String(id); - const reqAgg = _.find(this.getRequestAggs(), function(agg: AggConfig) { + const reqAgg = _.find(this.getRequestAggs(), function (agg: AggConfig) { return id.substr(0, String(agg.id).length) === agg.id; }); if (!reqAgg) return; diff --git a/src/plugins/data/public/search/aggs/agg_params.test.ts b/src/plugins/data/public/search/aggs/agg_params.test.ts index e116bdca157ff..997027fe88e82 100644 --- a/src/plugins/data/public/search/aggs/agg_params.test.ts +++ b/src/plugins/data/public/search/aggs/agg_params.test.ts @@ -68,7 +68,7 @@ describe('AggParams class', () => { expect(aggParams[0] instanceof OptionedParamType).toBeTruthy(); }); - it('Always converts the params to a BaseParamType', function() { + it('Always converts the params to a BaseParamType', function () { const params = [ { name: 'height', @@ -88,7 +88,7 @@ describe('AggParams class', () => { expect(aggParams).toHaveLength(params.length); - aggParams.forEach(aggParam => expect(aggParam instanceof BaseParamType).toBeTruthy()); + aggParams.forEach((aggParam) => expect(aggParam instanceof BaseParamType).toBeTruthy()); }); }); }); diff --git a/src/plugins/data/public/search/aggs/agg_params.ts b/src/plugins/data/public/search/aggs/agg_params.ts index e7b2f72bae656..4f7bec30fa27d 100644 --- a/src/plugins/data/public/search/aggs/agg_params.ts +++ b/src/plugins/data/public/search/aggs/agg_params.ts @@ -83,7 +83,7 @@ export const writeParams = < }; locals = locals || {}; - params.forEach(param => { + params.forEach((param) => { if (param.write) { param.write(aggConfig, output, aggs, locals); } else { diff --git a/src/plugins/data/public/search/aggs/agg_type.test.ts b/src/plugins/data/public/search/aggs/agg_type.test.ts index 369ae0ce0b3a5..18783bbd9a760 100644 --- a/src/plugins/data/public/search/aggs/agg_type.test.ts +++ b/src/plugins/data/public/search/aggs/agg_type.test.ts @@ -159,7 +159,7 @@ describe('AggType Class', () => { }); }); - describe('getFormat', function() { + describe('getFormat', function () { let aggConfig: IAggConfig; let field: any; diff --git a/src/plugins/data/public/search/aggs/buckets/_terms_other_bucket_helper.ts b/src/plugins/data/public/search/aggs/buckets/_terms_other_bucket_helper.ts index abda6b5fc5980..fba3d35f002af 100644 --- a/src/plugins/data/public/search/aggs/buckets/_terms_other_bucket_helper.ts +++ b/src/plugins/data/public/search/aggs/buckets/_terms_other_bucket_helper.ts @@ -65,7 +65,7 @@ const getAggResultBuckets = ( for (let aggId = 0; aggId < responseAggs.length; aggId++) { const aggById = responseAggs[aggId]; const aggKey = keys(responseAgg)[aggId]; - const aggConfig = find(aggConfigs.aggs, agg => agg.id === aggKey); + const aggConfig = find(aggConfigs.aggs, (agg) => agg.id === aggKey); if (aggConfig) { const aggResultBucket = find(aggById.buckets, (bucket, bucketObjKey) => { const bucketKey = aggConfig @@ -102,9 +102,9 @@ const getAggConfigResultMissingBuckets = (responseAggs: any, aggId: string) => { if (matchingBucket) resultBuckets.push(matchingBucket); return resultBuckets; } - each(responseAggs, agg => { + each(responseAggs, (agg) => { if (agg.buckets) { - each(agg.buckets, bucket => { + each(agg.buckets, (bucket) => { resultBuckets = [...resultBuckets, ...getAggConfigResultMissingBuckets(bucket, aggId)]; }); } @@ -137,8 +137,8 @@ export const buildOtherBucketAgg = ( aggWithOtherBucket: IBucketAggConfig, response: any ) => { - const bucketAggs = aggConfigs.aggs.filter(agg => agg.type.type === AggGroupNames.Buckets); - const index = bucketAggs.findIndex(agg => agg.id === aggWithOtherBucket.id); + const bucketAggs = aggConfigs.aggs.filter((agg) => agg.type.type === AggGroupNames.Buckets); + const index = bucketAggs.findIndex((agg) => agg.id === aggWithOtherBucket.id); const aggs = aggConfigs.toDsl(); const indexPattern = aggWithOtherBucket.params.field.indexPattern; @@ -215,7 +215,7 @@ export const buildOtherBucketAgg = ( } // create not filters for all the buckets - each(agg.buckets, bucket => { + each(agg.buckets, (bucket) => { if (bucket.key === '__missing__') return; const filter = currentAgg.createFilter(bucket.key); filter.meta.negate = true; @@ -289,7 +289,7 @@ export const updateMissingBucket = ( ) => { const updatedResponse = cloneDeep(response); const aggResultBuckets = getAggConfigResultMissingBuckets(updatedResponse.aggregations, agg.id); - aggResultBuckets.forEach(bucket => { + aggResultBuckets.forEach((bucket) => { bucket.key = '__missing__'; }); return updatedResponse; diff --git a/src/plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts b/src/plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts index bb73c8a39df19..2f03b8ec67112 100644 --- a/src/plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts +++ b/src/plugins/data/public/search/aggs/buckets/create_filter/date_histogram.test.ts @@ -121,7 +121,7 @@ describe('AggConfig Filters', () => { }); test('extends the filter edge to 1ms before the next bucket for all interval options', () => { - intervalOptions.forEach(option => { + intervalOptions.forEach((option) => { let duration; if (option.val !== 'custom' && moment(1, option.val).isValid()) { // @ts-ignore @@ -137,12 +137,7 @@ describe('AggConfig Filters', () => { const params = filter.range[field.name]; expect(params.gte).toBe(bucketStart.toISOString()); - expect(params.lt).toBe( - bucketStart - .clone() - .add(interval) - .toISOString() - ); + expect(params.lt).toBe(bucketStart.clone().add(interval).toISOString()); }); }); }); diff --git a/src/plugins/data/public/search/aggs/buckets/date_histogram.ts b/src/plugins/data/public/search/aggs/buckets/date_histogram.ts index 219bb5440c8da..d5c97d0c95c5c 100644 --- a/src/plugins/data/public/search/aggs/buckets/date_histogram.ts +++ b/src/plugins/data/public/search/aggs/buckets/date_histogram.ts @@ -225,7 +225,7 @@ export const getDateHistogramBucketAgg = ({ const scaleMetrics = scaleMetricValues && interval.scaled && interval.scale && interval.scale < 1; if (scaleMetrics && aggs) { - const metrics = aggs.aggs.filter(a => isMetricAggType(a.type)); + const metrics = aggs.aggs.filter((a) => isMetricAggType(a.type)); const all = every(metrics, (a: IBucketAggConfig) => { const { type } = a; @@ -275,7 +275,7 @@ export const getDateHistogramBucketAgg = ({ name: 'drop_partials', default: false, write: noop, - shouldShow: agg => { + shouldShow: (agg) => { const field = agg.params.field; return field && field.name && field.name === agg.getIndexPattern().timeFieldName; }, diff --git a/src/plugins/data/public/search/aggs/buckets/date_range.ts b/src/plugins/data/public/search/aggs/buckets/date_range.ts index 504958854cad4..447347dbfbe10 100644 --- a/src/plugins/data/public/search/aggs/buckets/date_range.ts +++ b/src/plugins/data/public/search/aggs/buckets/date_range.ts @@ -65,7 +65,7 @@ export const getDateRangeBucketAgg = ({ TEXT_CONTEXT_TYPE, fieldFormats.getDefaultInstance(KBN_FIELD_TYPES.DATE) ); - const DateRangeFormat = FieldFormat.from(function(range: DateRangeKey) { + const DateRangeFormat = FieldFormat.from(function (range: DateRangeKey) { return convertDateRangeToString(range, formatter); }); return new DateRangeFormat(); diff --git a/src/plugins/data/public/search/aggs/buckets/filters.ts b/src/plugins/data/public/search/aggs/buckets/filters.ts index 8654645d46a9b..3f3f13bb955c1 100644 --- a/src/plugins/data/public/search/aggs/buckets/filters.ts +++ b/src/plugins/data/public/search/aggs/buckets/filters.ts @@ -75,7 +75,7 @@ export const getFiltersBucketAgg = ({ const inFilters: FilterValue[] = aggConfig.params.filters; if (!size(inFilters)) return; - inFilters.forEach(filter => { + inFilters.forEach((filter) => { const persistedLog = getQueryLog( uiSettings, new Storage(window.localStorage), @@ -87,7 +87,7 @@ export const getFiltersBucketAgg = ({ const outFilters = transform( inFilters, - function(filters, filter) { + function (filters, filter) { const input = cloneDeep(filter.input); if (!input) { diff --git a/src/plugins/data/public/search/aggs/buckets/ip_range.ts b/src/plugins/data/public/search/aggs/buckets/ip_range.ts index 029fd864154be..10fdb2d93b56e 100644 --- a/src/plugins/data/public/search/aggs/buckets/ip_range.ts +++ b/src/plugins/data/public/search/aggs/buckets/ip_range.ts @@ -73,7 +73,7 @@ export const getIpRangeBucketAgg = ({ getInternalStartServices }: IpRangeBucketA TEXT_CONTEXT_TYPE, fieldFormats.getDefaultInstance(KBN_FIELD_TYPES.IP) ); - const IpRangeFormat = FieldFormat.from(function(range: IpRangeKey) { + const IpRangeFormat = FieldFormat.from(function (range: IpRangeKey) { return convertIPRangeToString(range, formatter); }); return new IpRangeFormat(); diff --git a/src/plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts b/src/plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts index 116f8cfad60f6..47da7e59af5e0 100644 --- a/src/plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts +++ b/src/plugins/data/public/search/aggs/buckets/migrate_include_exclude_format.ts @@ -25,7 +25,7 @@ export const isType = (...types: string[]) => { return (agg: IAggConfig): boolean => { const field = agg.params.field; - return types.some(type => field && field.type === type); + return types.some((type) => field && field.type === type); }; }; diff --git a/src/plugins/data/public/search/aggs/buckets/terms.ts b/src/plugins/data/public/search/aggs/buckets/terms.ts index 1bfc508dc3871..45a76f08ddd13 100644 --- a/src/plugins/data/public/search/aggs/buckets/terms.ts +++ b/src/plugins/data/public/search/aggs/buckets/terms.ts @@ -255,7 +255,7 @@ export const getTermsBucketAgg = ({ getInternalStartServices }: TermsBucketAggDe displayName: i18n.translate('data.search.aggs.otherBucket.labelForOtherBucketLabel', { defaultMessage: 'Label for other bucket', }), - shouldShow: agg => agg.getParam('otherBucket'), + shouldShow: (agg) => agg.getParam('otherBucket'), write: noop, }, { @@ -274,7 +274,7 @@ export const getTermsBucketAgg = ({ getInternalStartServices }: TermsBucketAggDe displayName: i18n.translate('data.search.aggs.otherBucket.labelForMissingValuesLabel', { defaultMessage: 'Label for missing values', }), - shouldShow: agg => agg.getParam('missingBucket'), + shouldShow: (agg) => agg.getParam('missingBucket'), write: noop, }, { diff --git a/src/plugins/data/public/search/aggs/index.test.ts b/src/plugins/data/public/search/aggs/index.test.ts index 382c5a10c2da5..4864a8b9d013b 100644 --- a/src/plugins/data/public/search/aggs/index.test.ts +++ b/src/plugins/data/public/search/aggs/index.test.ts @@ -44,7 +44,7 @@ describe('AggTypesComponent', () => { describe('bucket aggs', () => { test('all extend BucketAggType', () => { - buckets.forEach(bucketAgg => { + buckets.forEach((bucketAgg) => { expect(isBucketAggType(bucketAgg)).toBeTruthy(); }); }); @@ -52,7 +52,7 @@ describe('AggTypesComponent', () => { describe('metric aggs', () => { test('all extend MetricAggType', () => { - metrics.forEach(metricAgg => { + metrics.forEach((metricAgg) => { expect(isMetricAggType(metricAgg)).toBeTruthy(); }); }); diff --git a/src/plugins/data/public/search/aggs/metrics/avg.ts b/src/plugins/data/public/search/aggs/metrics/avg.ts index dba18d562ec19..1aa39ccd2aad9 100644 --- a/src/plugins/data/public/search/aggs/metrics/avg.ts +++ b/src/plugins/data/public/search/aggs/metrics/avg.ts @@ -41,7 +41,7 @@ export const getAvgMetricAgg = ({ getInternalStartServices }: AvgMetricAggDepend { name: METRIC_TYPES.AVG, title: averageTitle, - makeLabel: aggConfig => { + makeLabel: (aggConfig) => { return i18n.translate('data.search.aggs.metrics.averageLabel', { defaultMessage: 'Average {field}', values: { field: aggConfig.getFieldDisplayName() }, diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_avg.ts b/src/plugins/data/public/search/aggs/metrics/bucket_avg.ts index ded17eebf465b..927e9a7ae4458 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_avg.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_avg.ts @@ -50,7 +50,7 @@ export const getBucketAvgMetricAgg = ({ { name: METRIC_TYPES.AVG_BUCKET, title: averageBucketTitle, - makeLabel: agg => makeNestedLabel(agg, overallAverageLabel), + makeLabel: (agg) => makeNestedLabel(agg, overallAverageLabel), subtype: siblingPipelineAggHelper.subtype, params: [...siblingPipelineAggHelper.params()], getFormat: siblingPipelineAggHelper.getFormat, diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_max.ts b/src/plugins/data/public/search/aggs/metrics/bucket_max.ts index dde328008b88a..2b171fcbd24fd 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_max.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_max.ts @@ -49,7 +49,7 @@ export const getBucketMaxMetricAgg = ({ { name: METRIC_TYPES.MAX_BUCKET, title: maxBucketTitle, - makeLabel: agg => makeNestedLabel(agg, overallMaxLabel), + makeLabel: (agg) => makeNestedLabel(agg, overallMaxLabel), subtype: siblingPipelineAggHelper.subtype, params: [...siblingPipelineAggHelper.params()], getFormat: siblingPipelineAggHelper.getFormat, diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_min.ts b/src/plugins/data/public/search/aggs/metrics/bucket_min.ts index 9949524ce6110..e6a523eeea374 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_min.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_min.ts @@ -49,7 +49,7 @@ export const getBucketMinMetricAgg = ({ { name: METRIC_TYPES.MIN_BUCKET, title: minBucketTitle, - makeLabel: agg => makeNestedLabel(agg, overallMinLabel), + makeLabel: (agg) => makeNestedLabel(agg, overallMinLabel), subtype: siblingPipelineAggHelper.subtype, params: [...siblingPipelineAggHelper.params()], getFormat: siblingPipelineAggHelper.getFormat, diff --git a/src/plugins/data/public/search/aggs/metrics/bucket_sum.ts b/src/plugins/data/public/search/aggs/metrics/bucket_sum.ts index e69ae5798c6e1..71c88596ea569 100644 --- a/src/plugins/data/public/search/aggs/metrics/bucket_sum.ts +++ b/src/plugins/data/public/search/aggs/metrics/bucket_sum.ts @@ -49,7 +49,7 @@ export const getBucketSumMetricAgg = ({ { name: METRIC_TYPES.SUM_BUCKET, title: sumBucketTitle, - makeLabel: agg => makeNestedLabel(agg, overallSumLabel), + makeLabel: (agg) => makeNestedLabel(agg, overallSumLabel), subtype: siblingPipelineAggHelper.subtype, params: [...siblingPipelineAggHelper.params()], getFormat: siblingPipelineAggHelper.getFormat, diff --git a/src/plugins/data/public/search/aggs/metrics/cardinality.ts b/src/plugins/data/public/search/aggs/metrics/cardinality.ts index af594195fe027..9ff3e84c38cd8 100644 --- a/src/plugins/data/public/search/aggs/metrics/cardinality.ts +++ b/src/plugins/data/public/search/aggs/metrics/cardinality.ts @@ -59,7 +59,7 @@ export const getCardinalityMetricAgg = ({ name: 'field', type: 'field', filterFieldTypes: Object.values(KBN_FIELD_TYPES).filter( - type => type !== KBN_FIELD_TYPES.HISTOGRAM + (type) => type !== KBN_FIELD_TYPES.HISTOGRAM ), }, ], diff --git a/src/plugins/data/public/search/aggs/metrics/cumulative_sum.ts b/src/plugins/data/public/search/aggs/metrics/cumulative_sum.ts index 67e907239799a..44bfca1b6fb87 100644 --- a/src/plugins/data/public/search/aggs/metrics/cumulative_sum.ts +++ b/src/plugins/data/public/search/aggs/metrics/cumulative_sum.ts @@ -51,7 +51,7 @@ export const getCumulativeSumMetricAgg = ({ name: METRIC_TYPES.CUMULATIVE_SUM, title: cumulativeSumTitle, subtype: parentPipelineAggHelper.subtype, - makeLabel: agg => makeNestedLabel(agg, cumulativeSumLabel), + makeLabel: (agg) => makeNestedLabel(agg, cumulativeSumLabel), params: [...parentPipelineAggHelper.params()], getFormat: parentPipelineAggHelper.getFormat, }, diff --git a/src/plugins/data/public/search/aggs/metrics/metric_agg_type.ts b/src/plugins/data/public/search/aggs/metrics/metric_agg_type.ts index bb16cba1bee62..83656db4ac547 100644 --- a/src/plugins/data/public/search/aggs/metrics/metric_agg_type.ts +++ b/src/plugins/data/public/search/aggs/metrics/metric_agg_type.ts @@ -84,7 +84,7 @@ export class MetricAggType { + ((agg) => { const { fieldFormats } = dependencies.getInternalStartServices(); const field = agg.getField(); return field ? field.format : fieldFormats.getDefaultInstance(KBN_FIELD_TYPES.NUMBER); diff --git a/src/plugins/data/public/search/aggs/metrics/moving_avg.ts b/src/plugins/data/public/search/aggs/metrics/moving_avg.ts index 38a824629d304..1173ae5358ee7 100644 --- a/src/plugins/data/public/search/aggs/metrics/moving_avg.ts +++ b/src/plugins/data/public/search/aggs/metrics/moving_avg.ts @@ -54,7 +54,7 @@ export const getMovingAvgMetricAgg = ({ dslName: 'moving_fn', title: movingAvgTitle, subtype: parentPipelineAggHelper.subtype, - makeLabel: agg => makeNestedLabel(agg, movingAvgLabel), + makeLabel: (agg) => makeNestedLabel(agg, movingAvgLabel), params: [ ...parentPipelineAggHelper.params(), { diff --git a/src/plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts b/src/plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts index f386034ea8a7b..2201366cdf78b 100644 --- a/src/plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts +++ b/src/plugins/data/public/search/aggs/metrics/parent_pipeline.test.ts @@ -28,7 +28,7 @@ import { fieldFormatsServiceMock } from '../../../field_formats/mocks'; import { GetInternalStartServicesFn, InternalStartServices } from '../../../types'; import { notificationServiceMock } from '../../../../../../../src/core/public/mocks'; -describe('parent pipeline aggs', function() { +describe('parent pipeline aggs', function () { const getInternalStartServices: GetInternalStartServicesFn = () => (({ fieldFormats: fieldFormatsServiceMock.createStartContract(), @@ -61,7 +61,7 @@ describe('parent pipeline aggs', function() { }, ]; - metrics.forEach(metric => { + metrics.forEach((metric) => { describe(`${metric.title} metric`, () => { let aggDsl: Record; let metricAgg: MetricAggType; @@ -243,7 +243,7 @@ describe('parent pipeline aggs', function() { // Attach a modifyAggConfigOnSearchRequestStart with a spy to the first parameter customMetric.type.params[0].modifyAggConfigOnSearchRequestStart = customMetricSpy; - aggConfig.type.params.forEach(param => { + aggConfig.type.params.forEach((param) => { param.modifyAggConfigOnSearchRequestStart(aggConfig, searchSource, {}); }); expect(customMetricSpy.mock.calls[0]).toEqual([customMetric, searchSource, {}]); diff --git a/src/plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts b/src/plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts index 7491f15aa3002..df52c10a82495 100644 --- a/src/plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts +++ b/src/plugins/data/public/search/aggs/metrics/percentile_ranks.test.ts @@ -30,7 +30,7 @@ import { fieldFormatsServiceMock } from '../../../field_formats/mocks'; import { notificationServiceMock } from '../../../../../../../src/core/public/mocks'; import { InternalStartServices } from '../../../types'; -describe('AggTypesMetricsPercentileRanksProvider class', function() { +describe('AggTypesMetricsPercentileRanksProvider class', function () { let aggConfigs: IAggConfigs; let fieldFormats: FieldFormatsStart; let aggTypesDependencies: PercentileRanksMetricAggDependencies; @@ -78,7 +78,7 @@ describe('AggTypesMetricsPercentileRanksProvider class', function() { ); }); - it('uses the custom label if it is set', function() { + it('uses the custom label if it is set', function () { const responseAggs: any = getPercentileRanksMetricAgg(aggTypesDependencies).getResponseAggs( aggConfigs.aggs[0] as IPercentileRanksAggConfig ); diff --git a/src/plugins/data/public/search/aggs/metrics/serial_diff.ts b/src/plugins/data/public/search/aggs/metrics/serial_diff.ts index fe112a50ad3c1..00bc631cefab8 100644 --- a/src/plugins/data/public/search/aggs/metrics/serial_diff.ts +++ b/src/plugins/data/public/search/aggs/metrics/serial_diff.ts @@ -51,7 +51,7 @@ export const getSerialDiffMetricAgg = ({ name: METRIC_TYPES.SERIAL_DIFF, title: serialDiffTitle, subtype: parentPipelineAggHelper.subtype, - makeLabel: agg => makeNestedLabel(agg, serialDiffLabel), + makeLabel: (agg) => makeNestedLabel(agg, serialDiffLabel), params: [...parentPipelineAggHelper.params()], getFormat: parentPipelineAggHelper.getFormat, }, diff --git a/src/plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts b/src/plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts index 5e1834d3b4935..56bd33b2b6345 100644 --- a/src/plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts +++ b/src/plugins/data/public/search/aggs/metrics/sibling_pipeline.test.ts @@ -61,7 +61,7 @@ describe('sibling pipeline aggs', () => { }, ]; - metrics.forEach(metric => { + metrics.forEach((metric) => { describe(`${metric.title} metric`, () => { let aggDsl: Record; let metricAgg: MetricAggType; @@ -127,7 +127,7 @@ describe('sibling pipeline aggs', () => { expect(metricAgg.makeLabel(aggConfig)).toEqual(`${metric.title} of Count`); }); - it('should set parent aggs', function() { + it('should set parent aggs', function () { init(); expect(aggDsl[metric.name].buckets_path).toBe('2-bucket>_count'); @@ -186,7 +186,7 @@ describe('sibling pipeline aggs', () => { customMetric.type.params[0].modifyAggConfigOnSearchRequestStart = customMetricSpy; customBucket.type.params[0].modifyAggConfigOnSearchRequestStart = customBucketSpy; - aggConfig.type.params.forEach(param => { + aggConfig.type.params.forEach((param) => { param.modifyAggConfigOnSearchRequestStart(aggConfig, searchSource, {}); }); diff --git a/src/plugins/data/public/search/aggs/metrics/top_hit.test.ts b/src/plugins/data/public/search/aggs/metrics/top_hit.test.ts index 617e458cf6243..49e0a3e4b349a 100644 --- a/src/plugins/data/public/search/aggs/metrics/top_hit.test.ts +++ b/src/plugins/data/public/search/aggs/metrics/top_hit.test.ts @@ -78,7 +78,7 @@ describe('Top hit metric', () => { getByName: () => field, filter: () => [field], }, - flattenHit: jest.fn(x => x!._source), + flattenHit: jest.fn((x) => x!._source), } as any; const aggConfigs = new AggConfigs( @@ -336,7 +336,7 @@ describe('Top hit metric', () => { data: [undefined, null], result: null, }, - ].forEach(agg => { + ].forEach((agg) => { it(`should return the result of the ${agg.type} aggregation over the last doc - ${agg.description}`, () => { const bucket = { '1': { diff --git a/src/plugins/data/public/search/aggs/metrics/top_hit.ts b/src/plugins/data/public/search/aggs/metrics/top_hit.ts index df7a76f151c07..c6890f98b20e4 100644 --- a/src/plugins/data/public/search/aggs/metrics/top_hit.ts +++ b/src/plugins/data/public/search/aggs/metrics/top_hit.ts @@ -80,7 +80,7 @@ export const getTopHitMetricAgg = ({ getInternalStartServices }: TopHitMetricAgg type: 'field', onlyAggregatable: false, filterFieldTypes: Object.values(KBN_FIELD_TYPES).filter( - type => type !== KBN_FIELD_TYPES.HISTOGRAM + (type) => type !== KBN_FIELD_TYPES.HISTOGRAM ), write(agg, output) { const field = agg.getParam('field'); @@ -230,7 +230,7 @@ export const getTopHitMetricAgg = ({ getInternalStartServices }: TopHitMetricAgg const path = agg.getParam('field').name; let values = _.flatten( - hits.map(hit => + hits.map((hit) => path === '_source' ? hit._source : agg.getIndexPattern().flattenHit(hit, true)[path] ) ); diff --git a/src/plugins/data/public/search/aggs/param_types/base.ts b/src/plugins/data/public/search/aggs/param_types/base.ts index a6f7e5adea043..79e1cf2a540d1 100644 --- a/src/plugins/data/public/search/aggs/param_types/base.ts +++ b/src/plugins/data/public/search/aggs/param_types/base.ts @@ -82,7 +82,7 @@ export class BaseParamType { this.toExpressionAst = config.toExpressionAst; this.options = config.options; this.modifyAggConfigOnSearchRequestStart = - config.modifyAggConfigOnSearchRequestStart || function() {}; + config.modifyAggConfigOnSearchRequestStart || function () {}; this.valueType = config.valueType || config.type; } } diff --git a/src/plugins/data/public/search/aggs/param_types/json.test.ts b/src/plugins/data/public/search/aggs/param_types/json.test.ts index 12fd29b3a1452..82e12d3bd5be6 100644 --- a/src/plugins/data/public/search/aggs/param_types/json.test.ts +++ b/src/plugins/data/public/search/aggs/param_types/json.test.ts @@ -21,7 +21,7 @@ import { BaseParamType } from './base'; import { JsonParamType } from './json'; import { IAggConfig } from '../agg_config'; -describe('JSON', function() { +describe('JSON', function () { const paramName = 'json_test'; let aggConfig: IAggConfig; let output: Record; @@ -33,7 +33,7 @@ describe('JSON', function() { name: paramName, }); - beforeEach(function() { + beforeEach(function () { aggConfig = { params: {} } as IAggConfig; output = { params: {} }; }); diff --git a/src/plugins/data/public/search/aggs/param_types/json.ts b/src/plugins/data/public/search/aggs/param_types/json.ts index bf85b3b890c35..461f3c300c1d3 100644 --- a/src/plugins/data/public/search/aggs/param_types/json.ts +++ b/src/plugins/data/public/search/aggs/param_types/json.ts @@ -49,7 +49,7 @@ export class JsonParamType extends BaseParamType { return _(a) .keys() .union(_.keys(b)) - .transform(function(dest, key) { + .transform(function (dest, key) { const val = compare(a[key], b[key]); if (val !== undefined) dest[key] = val; }, {}) @@ -58,7 +58,7 @@ export class JsonParamType extends BaseParamType { function mergeArrays(a: any, b: any): any { // attempt to merge each value - return _.times(Math.max(a.length, b.length), function(i) { + return _.times(Math.max(a.length, b.length), function (i) { return compare(a[i], b[i]); }); } diff --git a/src/plugins/data/public/search/aggs/param_types/string.test.ts b/src/plugins/data/public/search/aggs/param_types/string.test.ts index 29ec9741611a3..c4afe1d5d1330 100644 --- a/src/plugins/data/public/search/aggs/param_types/string.test.ts +++ b/src/plugins/data/public/search/aggs/param_types/string.test.ts @@ -21,7 +21,7 @@ import { BaseParamType } from './base'; import { StringParamType } from './string'; import { IAggConfig } from '../agg_config'; -describe('String', function() { +describe('String', function () { let paramName = 'json_test'; let aggConfig: IAggConfig; let output: Record; diff --git a/src/plugins/data/public/search/aggs/test_helpers/function_wrapper.ts b/src/plugins/data/public/search/aggs/test_helpers/function_wrapper.ts index cb0e37c0296d7..aa27bab8f4bd8 100644 --- a/src/plugins/data/public/search/aggs/test_helpers/function_wrapper.ts +++ b/src/plugins/data/public/search/aggs/test_helpers/function_wrapper.ts @@ -34,7 +34,7 @@ import { * expression functions. */ export const functionWrapper = (spec: T) => { - const defaultArgs = mapValues(spec.args, argSpec => argSpec.default); + const defaultArgs = mapValues(spec.args, (argSpec) => argSpec.default); return ( args: T extends ExpressionFunctionDefinition< infer Name, diff --git a/src/plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts b/src/plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts index 3ff2fbf35ad7e..5549ffd2583b1 100644 --- a/src/plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts +++ b/src/plugins/data/public/search/aggs/test_helpers/mock_agg_types_registry.ts @@ -45,7 +45,7 @@ export function mockAggTypesRegistry | MetricAggTyp const registrySetup = registry.setup(); if (types) { - types.forEach(type => { + types.forEach((type) => { if (type instanceof BucketAggType) { registrySetup.registerBucket(type); } else if (type instanceof MetricAggType) { @@ -68,8 +68,8 @@ export function mockAggTypesRegistry | MetricAggTyp } as unknown) as InternalStartServices), }); - aggTypes.buckets.forEach(type => registrySetup.registerBucket(type)); - aggTypes.metrics.forEach(type => registrySetup.registerMetric(type)); + aggTypes.buckets.forEach((type) => registrySetup.registerBucket(type)); + aggTypes.metrics.forEach((type) => registrySetup.registerMetric(type)); } return registry.start(); diff --git a/src/plugins/data/public/search/aggs/utils/prop_filter.ts b/src/plugins/data/public/search/aggs/utils/prop_filter.ts index 01e98a68d3949..cad5c437fc896 100644 --- a/src/plugins/data/public/search/aggs/utils/prop_filter.ts +++ b/src/plugins/data/public/search/aggs/utils/prop_filter.ts @@ -44,7 +44,7 @@ export function propFilter

(prop: P) { filters: string[] | string | FilterFunc = [] ): T[] { if (isFunction(filters)) { - return list.filter(item => (filters as FilterFunc)(item[prop])); + return list.filter((item) => (filters as FilterFunc)(item[prop])); } if (!Array.isArray(filters)) { @@ -75,7 +75,7 @@ export function propFilter

(prop: P) { return acc; }, {} as { [type: string]: string[] }); - return list.filter(item => { + return list.filter((item) => { const value = item[prop]; const excluded = options.exclude && options.exclude.includes(value); diff --git a/src/plugins/data/public/search/expressions/build_tabular_inspector_data.ts b/src/plugins/data/public/search/expressions/build_tabular_inspector_data.ts index 89a46db27e894..906b8862d00aa 100644 --- a/src/plugins/data/public/search/expressions/build_tabular_inspector_data.ts +++ b/src/plugins/data/public/search/expressions/build_tabular_inspector_data.ts @@ -40,8 +40,8 @@ export async function buildTabularInspectorData( table: TabbedTable, queryFilter: { addFilters: (filter: any) => void } ) { - const aggConfigs = table.columns.map(column => column.aggConfig); - const rows = table.rows.map(row => { + const aggConfigs = table.columns.map((column) => column.aggConfig); + const rows = table.rows.map((row) => { return table.columns.reduce>((prev, cur, colIndex) => { const value = row[cur.id]; const fieldFormatter = cur.aggConfig.fieldFormatter('text'); @@ -60,7 +60,7 @@ export async function buildTabularInspectorData( isCellContentFilterable && ((value: { raw: unknown }) => { const rowIndex = rows.findIndex( - row => row[`col-${colIndex}-${col.aggConfig.id}`].raw === value.raw + (row) => row[`col-${colIndex}-${col.aggConfig.id}`].raw === value.raw ); const filter = createFilter(aggConfigs, table, colIndex, rowIndex, value.raw); @@ -72,7 +72,7 @@ export async function buildTabularInspectorData( isCellContentFilterable && ((value: { raw: unknown }) => { const rowIndex = rows.findIndex( - row => row[`col-${colIndex}-${col.aggConfig.id}`].raw === value.raw + (row) => row[`col-${colIndex}-${col.aggConfig.id}`].raw === value.raw ); const filter = createFilter(aggConfigs, table, colIndex, rowIndex, value.raw); @@ -80,7 +80,7 @@ export async function buildTabularInspectorData( const notOther = value.raw !== '__other__'; const notMissing = value.raw !== '__missing__'; if (Array.isArray(filter)) { - filter.forEach(f => set(f, 'meta.negate', notOther && notMissing)); + filter.forEach((f) => set(f, 'meta.negate', notOther && notMissing)); } else { set(filter, 'meta.negate', notOther && notMissing); } diff --git a/src/plugins/data/public/search/expressions/create_filter.ts b/src/plugins/data/public/search/expressions/create_filter.ts index 2e2bd435151b6..94d84380e03df 100644 --- a/src/plugins/data/public/search/expressions/create_filter.ts +++ b/src/plugins/data/public/search/expressions/create_filter.ts @@ -27,16 +27,16 @@ const getOtherBucketFilterTerms = (table: TabbedTable, columnIndex: number, rowI } // get only rows where cell value matches current row for all the fields before columnIndex - const rows = table.rows.filter(row => { + const rows = table.rows.filter((row) => { return table.columns.every((column, i) => { return row[column.id] === table.rows[rowIndex][column.id] || i >= columnIndex; }); }); - const terms = rows.map(row => row[table.columns[columnIndex].id]); + const terms = rows.map((row) => row[table.columns[columnIndex].id]); return [ ...new Set( - terms.filter(term => { + terms.filter((term) => { const notOther = term !== '__other__'; const notMissing = term !== '__missing__'; return notOther && notMissing; diff --git a/src/plugins/data/public/search/expressions/esaggs.ts b/src/plugins/data/public/search/expressions/esaggs.ts index d6901da99319a..153eb7de6f2de 100644 --- a/src/plugins/data/public/search/expressions/esaggs.ts +++ b/src/plugins/data/public/search/expressions/esaggs.ts @@ -115,7 +115,7 @@ const handleCourierRequest = async ({ }, }); - requestSearchSource.setField('aggs', function() { + requestSearchSource.setField('aggs', function () { return aggs.toDsl(metricsAtAllLevels); }); @@ -134,7 +134,7 @@ const handleCourierRequest = async ({ if (timeRange && allTimeFields.length > 0) { timeFilterSearchSource.setField('filter', () => { return allTimeFields - .map(fieldName => getTime(indexPattern, timeRange, { fieldName })) + .map((fieldName) => getTime(indexPattern, timeRange, { fieldName })) .filter(isRangeFilter); }); } diff --git a/src/plugins/data/public/search/fetch/get_search_params.test.ts b/src/plugins/data/public/search/fetch/get_search_params.test.ts index edf18405e8ff7..4809d76a46f59 100644 --- a/src/plugins/data/public/search/fetch/get_search_params.test.ts +++ b/src/plugins/data/public/search/fetch/get_search_params.test.ts @@ -22,7 +22,7 @@ import { IUiSettingsClient } from 'kibana/public'; function getConfigStub(config: any = {}) { return { - get: key => config[key], + get: (key) => config[key], } as IUiSettingsClient; } diff --git a/src/plugins/data/public/search/legacy/call_client.test.ts b/src/plugins/data/public/search/legacy/call_client.test.ts index 9a2a9dc222e7e..a3c4e720b4cab 100644 --- a/src/plugins/data/public/search/legacy/call_client.test.ts +++ b/src/plugins/data/public/search/legacy/call_client.test.ts @@ -34,7 +34,7 @@ jest.mock('./default_search_strategy', () => { search: jest.fn(({ searchRequests }: SearchStrategySearchParams) => { return { searching: Promise.resolve( - searchRequests.map(req => { + searchRequests.map((req) => { return { id: req._searchStrategyId, }; diff --git a/src/plugins/data/public/search/legacy/call_client.ts b/src/plugins/data/public/search/legacy/call_client.ts index c484c46aa4879..4b12f517daf78 100644 --- a/src/plugins/data/public/search/legacy/call_client.ts +++ b/src/plugins/data/public/search/legacy/call_client.ts @@ -40,10 +40,10 @@ export function callClient( }); searchRequests.forEach((request, i) => { - const response = searching.then(results => handleResponse(request, results[i])); + const response = searching.then((results) => handleResponse(request, results[i])); const { abortSignal = null } = requestOptionsMap.get(request) || {}; if (abortSignal) abortSignal.addEventListener('abort', abort); requestResponseMap.set(request, response); }); - return searchRequests.map(request => requestResponseMap.get(request)); + return searchRequests.map((request) => requestResponseMap.get(request)); } diff --git a/src/plugins/data/public/search/legacy/default_search_strategy.test.ts b/src/plugins/data/public/search/legacy/default_search_strategy.test.ts index 9e3d65a69bf02..c619c9b17d9a8 100644 --- a/src/plugins/data/public/search/legacy/default_search_strategy.test.ts +++ b/src/plugins/data/public/search/legacy/default_search_strategy.test.ts @@ -26,7 +26,7 @@ const { search } = defaultSearchStrategy; function getConfigStub(config: any = {}) { return { - get: key => config[key], + get: (key) => config[key], } as IUiSettingsClient; } @@ -38,8 +38,8 @@ const searchMockResponse: any = Promise.resolve([]); searchMockResponse.abort = jest.fn(); const searchMock = jest.fn().mockReturnValue(searchMockResponse); -describe('defaultSearchStrategy', function() { - describe('search', function() { +describe('defaultSearchStrategy', function () { + describe('search', function () { let searchArgs: MockedKeys>; let es: any; diff --git a/src/plugins/data/public/search/legacy/default_search_strategy.ts b/src/plugins/data/public/search/legacy/default_search_strategy.ts index 3216803dcbfa2..284768bc5a1cc 100644 --- a/src/plugins/data/public/search/legacy/default_search_strategy.ts +++ b/src/plugins/data/public/search/legacy/default_search_strategy.ts @@ -25,7 +25,7 @@ import { SearchStrategyProvider, SearchStrategySearchParams } from './types'; export const defaultSearchStrategy: SearchStrategyProvider = { id: 'default', - search: params => { + search: (params) => { return msearch(params); }, }; diff --git a/src/plugins/data/public/search/legacy/fetch_soon.test.ts b/src/plugins/data/public/search/legacy/fetch_soon.test.ts index 6c0467e3297e8..e99e13ba33d1a 100644 --- a/src/plugins/data/public/search/legacy/fetch_soon.test.ts +++ b/src/plugins/data/public/search/legacy/fetch_soon.test.ts @@ -25,7 +25,7 @@ import { SearchRequest, SearchResponse } from '../index'; function getConfigStub(config: any = {}) { return { - get: key => config[key], + get: (key) => config[key], } as IUiSettingsClient; } @@ -41,9 +41,9 @@ jest.mock('./call_client', () => ({ callClient: jest.fn((requests: SearchRequest[]) => { // Allow a request object to specify which mockResponse it wants to receive (_mockResponseId) // in addition to how long to simulate waiting before returning a response (_waitMs) - const responses = requests.map(request => { + const responses = requests.map((request) => { const waitMs = requests.reduce((total, { _waitMs }) => total + _waitMs || 0, 0); - return new Promise(resolve => { + return new Promise((resolve) => { setTimeout(() => { resolve(mockResponses[request._mockResponseId]); }, waitMs); @@ -109,7 +109,7 @@ describe('fetchSoon', () => { }); const requests = [{ _mockResponseId: 'foo' }, { _mockResponseId: 'bar' }]; - const promises = requests.map(request => { + const promises = requests.map((request) => { return fetchSoon(request, {}, { config } as FetchHandlers); }); jest.advanceTimersByTime(50); @@ -125,11 +125,11 @@ describe('fetchSoon', () => { const firstBatch = [{ foo: 1 }, { foo: 2 }]; const secondBatch = [{ bar: 1 }, { bar: 2 }]; - firstBatch.forEach(request => { + firstBatch.forEach((request) => { fetchSoon(request, {}, { config } as FetchHandlers); }); jest.advanceTimersByTime(50); - secondBatch.forEach(request => { + secondBatch.forEach((request) => { fetchSoon(request, {}, { config } as FetchHandlers); }); diff --git a/src/plugins/data/public/search/legacy/fetch_soon.ts b/src/plugins/data/public/search/legacy/fetch_soon.ts index 83617d394fe95..304c1c4d63f5b 100644 --- a/src/plugins/data/public/search/legacy/fetch_soon.ts +++ b/src/plugins/data/public/search/legacy/fetch_soon.ts @@ -42,7 +42,7 @@ export async function fetchSoon( * @return Promise A promise that resolves with the result of executing the function */ function delay(fn: Function, ms: number) { - return new Promise(resolve => { + return new Promise((resolve) => { setTimeout(() => resolve(fn()), ms); }); } diff --git a/src/plugins/data/public/search/legacy/get_msearch_params.test.ts b/src/plugins/data/public/search/legacy/get_msearch_params.test.ts index 9f16d5b408178..ce98f6ab2a7bb 100644 --- a/src/plugins/data/public/search/legacy/get_msearch_params.test.ts +++ b/src/plugins/data/public/search/legacy/get_msearch_params.test.ts @@ -22,7 +22,7 @@ import { IUiSettingsClient } from '../../../../../core/public'; function getConfigStub(config: any = {}) { return { - get: key => config[key], + get: (key) => config[key], } as IUiSettingsClient; } diff --git a/src/plugins/data/public/search/search_interceptor.ts b/src/plugins/data/public/search/search_interceptor.ts index 2815b41eaba5c..53cc650ee7a77 100644 --- a/src/plugins/data/public/search/search_interceptor.ts +++ b/src/plugins/data/public/search/search_interceptor.ts @@ -67,7 +67,7 @@ export class SearchInterceptor { // When search requests go out, a notification is scheduled allowing users to continue the // request past the timeout. When all search requests complete, we remove the notification. this.getPendingCount$() - .pipe(filter(count => count === 0)) + .pipe(filter((count) => count === 0)) .subscribe(this.hideToast); } diff --git a/src/plugins/data/public/search/search_service.ts b/src/plugins/data/public/search/search_service.ts index b69b3261d4a5e..1615aac9e7b7d 100644 --- a/src/plugins/data/public/search/search_service.ts +++ b/src/plugins/data/public/search/search_service.ts @@ -102,12 +102,12 @@ export class SearchService implements Plugin { uiSettings: core.uiSettings, getInternalStartServices, }); - aggTypes.buckets.forEach(b => aggTypesSetup.registerBucket(b)); - aggTypes.metrics.forEach(m => aggTypesSetup.registerMetric(m)); + aggTypes.buckets.forEach((b) => aggTypesSetup.registerBucket(b)); + aggTypes.metrics.forEach((m) => aggTypesSetup.registerMetric(m)); // register expression functions for each agg type const aggFunctions = getAggTypesFunctions(); - aggFunctions.forEach(fn => expressions.registerFunction(fn)); + aggFunctions.forEach((fn) => expressions.registerFunction(fn)); return { aggs: { diff --git a/src/plugins/data/public/search/search_source/filter_docvalue_fields.ts b/src/plugins/data/public/search/search_source/filter_docvalue_fields.ts index 917d26f0decd1..bbac30d7dfdc5 100644 --- a/src/plugins/data/public/search/search_source/filter_docvalue_fields.ts +++ b/src/plugins/data/public/search/search_source/filter_docvalue_fields.ts @@ -26,7 +26,7 @@ export function filterDocvalueFields( docvalueFields: Array, fields: string[] ) { - return docvalueFields.filter(docValue => { + return docvalueFields.filter((docValue) => { const docvalueFieldName = typeof docValue === 'string' ? docValue : docValue.field; return fields.includes(docvalueFieldName); }); diff --git a/src/plugins/data/public/search/search_source/inject_references.ts b/src/plugins/data/public/search/search_source/inject_references.ts index a567c33d2280b..07f37c3c11275 100644 --- a/src/plugins/data/public/search/search_source/inject_references.ts +++ b/src/plugins/data/public/search/search_source/inject_references.ts @@ -27,7 +27,7 @@ export const injectReferences = ( const searchSourceReturnFields: SearchSourceFields = { ...searchSourceFields }; // Inject index id if a reference is saved if (searchSourceFields.indexRefName) { - const reference = references.find(ref => ref.name === searchSourceFields.indexRefName); + const reference = references.find((ref) => ref.name === searchSourceFields.indexRefName); if (!reference) { throw new Error(`Could not find reference for ${searchSourceFields.indexRefName}`); } diff --git a/src/plugins/data/public/search/search_source/normalize_sort_request.test.ts b/src/plugins/data/public/search/search_source/normalize_sort_request.test.ts index 13a6167544b5e..d47aab80ee0bc 100644 --- a/src/plugins/data/public/search/search_source/normalize_sort_request.test.ts +++ b/src/plugins/data/public/search/search_source/normalize_sort_request.test.ts @@ -21,7 +21,7 @@ import { normalizeSortRequest } from './normalize_sort_request'; import { SortDirection } from './types'; import { IIndexPattern } from '../..'; -describe('SearchSource#normalizeSortRequest', function() { +describe('SearchSource#normalizeSortRequest', function () { const scriptedField = { name: 'script string', type: 'number', @@ -40,7 +40,7 @@ describe('SearchSource#normalizeSortRequest', function() { fields: [scriptedField, murmurScriptedField], } as IIndexPattern; - it('should return an array', function() { + it('should return an array', function () { const sortable = { someField: SortDirection.desc }; const result = normalizeSortRequest(sortable, indexPattern); expect(result).toEqual([ @@ -55,7 +55,7 @@ describe('SearchSource#normalizeSortRequest', function() { expect(sortable).toEqual({ someField: SortDirection.desc }); }); - it('should make plain string sort into the more verbose format', function() { + it('should make plain string sort into the more verbose format', function () { const result = normalizeSortRequest([{ someField: SortDirection.desc }], indexPattern); expect(result).toEqual([ { @@ -66,7 +66,7 @@ describe('SearchSource#normalizeSortRequest', function() { ]); }); - it('should append default sort options', function() { + it('should append default sort options', function () { const defaultSortOptions = { unmapped_type: 'boolean', }; @@ -85,7 +85,7 @@ describe('SearchSource#normalizeSortRequest', function() { ]); }); - it('should enable script based sorting', function() { + it('should enable script based sorting', function () { const result = normalizeSortRequest( { [scriptedField.name]: SortDirection.desc, @@ -106,7 +106,7 @@ describe('SearchSource#normalizeSortRequest', function() { ]); }); - it('should use script based sorting only on sortable types', function() { + it('should use script based sorting only on sortable types', function () { const result = normalizeSortRequest( [ { @@ -125,7 +125,7 @@ describe('SearchSource#normalizeSortRequest', function() { ]); }); - it('should remove unmapped_type parameter from _score sorting', function() { + it('should remove unmapped_type parameter from _score sorting', function () { const result = normalizeSortRequest({ _score: SortDirection.desc }, indexPattern, { unmapped_type: 'boolean', }); diff --git a/src/plugins/data/public/search/search_source/normalize_sort_request.ts b/src/plugins/data/public/search/search_source/normalize_sort_request.ts index 9e36d2e416f03..9a0cf371ce81d 100644 --- a/src/plugins/data/public/search/search_source/normalize_sort_request.ts +++ b/src/plugins/data/public/search/search_source/normalize_sort_request.ts @@ -26,7 +26,7 @@ export function normalizeSortRequest( defaultSortOptions: SortOptions = {} ) { const sortArray: EsQuerySortValue[] = Array.isArray(sortObject) ? sortObject : [sortObject]; - return sortArray.map(function(sortable) { + return sortArray.map(function (sortable) { return normalize(sortable, indexPattern, defaultSortOptions); }); } diff --git a/src/plugins/data/public/search/search_source/search_source.test.ts b/src/plugins/data/public/search/search_source/search_source.test.ts index 7783e65889a12..6d53b8dfc4b4e 100644 --- a/src/plugins/data/public/search/search_source/search_source.test.ts +++ b/src/plugins/data/public/search/search_source/search_source.test.ts @@ -58,7 +58,7 @@ describe('SearchSource', () => { const data = dataPluginMock.createStartContract(); mockSearchMethod = jest.fn(() => { - return new Observable(subscriber => { + return new Observable((subscriber) => { setTimeout(() => { subscriber.next({ rawResponse: '', diff --git a/src/plugins/data/public/search/search_source/search_source.ts b/src/plugins/data/public/search/search_source/search_source.ts index 9fdef5e1f3eb0..38f4ce73713c8 100644 --- a/src/plugins/data/public/search/search_source/search_source.ts +++ b/src/plugins/data/public/search/search_source/search_source.ts @@ -309,7 +309,7 @@ export class SearchSource { } } - return Promise.all(handlers.map(fn => fn(this, options))); + return Promise.all(handlers.map((fn) => fn(this, options))); } /** diff --git a/src/plugins/data/public/search/sync_search_strategy.test.ts b/src/plugins/data/public/search/sync_search_strategy.test.ts index 31a1adfa01c75..6197980314b86 100644 --- a/src/plugins/data/public/search/sync_search_strategy.test.ts +++ b/src/plugins/data/public/search/sync_search_strategy.test.ts @@ -61,7 +61,7 @@ describe('Sync search strategy', () => { const request = { serverStrategy: SYNC_SEARCH_STRATEGY }; const loadingCount$ = mockCoreStart.http.addLoadingCountSource.mock.calls[0][0]; - loadingCount$.subscribe(value => receivedLoadingCountValues.push(value)); + loadingCount$.subscribe((value) => receivedLoadingCountValues.push(value)); await syncSearch.search(request, {}).toPromise(); @@ -82,7 +82,7 @@ describe('Sync search strategy', () => { const request = { serverStrategy: SYNC_SEARCH_STRATEGY }; const loadingCount$ = mockCoreStart.http.addLoadingCountSource.mock.calls[0][0]; - loadingCount$.subscribe(value => receivedLoadingCountValues.push(value)); + loadingCount$.subscribe((value) => receivedLoadingCountValues.push(value)); try { await syncSearch.search(request, {}).toPromise(); diff --git a/src/plugins/data/public/search/tabify/buckets.test.ts b/src/plugins/data/public/search/tabify/buckets.test.ts index 81d9f3d5ca3fd..dfd9462d87b68 100644 --- a/src/plugins/data/public/search/tabify/buckets.test.ts +++ b/src/plugins/data/public/search/tabify/buckets.test.ts @@ -86,7 +86,7 @@ describe('Buckets wrapper', () => { expect(buckets).toHaveLength(2); - buckets._keys.forEach(key => { + buckets._keys.forEach((key) => { expect(typeof key).toBe('string'); }); }); @@ -116,7 +116,7 @@ describe('Buckets wrapper', () => { expect(buckets).toHaveLength(2); - buckets._keys.forEach(key => { + buckets._keys.forEach((key) => { expect(typeof key).toBe('string'); }); }); @@ -141,7 +141,7 @@ describe('Buckets wrapper', () => { expect(buckets).toHaveLength(1); - buckets._keys.forEach(key => { + buckets._keys.forEach((key) => { expect(typeof key).toBe('string'); }); }); diff --git a/src/plugins/data/public/search/tabify/buckets.ts b/src/plugins/data/public/search/tabify/buckets.ts index cd52a09caeaad..e6e5ba4e68ea3 100644 --- a/src/plugins/data/public/search/tabify/buckets.ts +++ b/src/plugins/data/public/search/tabify/buckets.ts @@ -68,7 +68,7 @@ export class TabifyBuckets { const buckets = this.buckets; if (this.objectMode) { - this._keys.forEach(key => { + this._keys.forEach((key) => { fn(buckets[key], key); }); } else { diff --git a/src/plugins/data/public/search/tabify/get_columns.test.ts b/src/plugins/data/public/search/tabify/get_columns.test.ts index 1072e9318b40e..b4498aca4079c 100644 --- a/src/plugins/data/public/search/tabify/get_columns.test.ts +++ b/src/plugins/data/public/search/tabify/get_columns.test.ts @@ -159,7 +159,7 @@ describe('get columns', () => { false ); - expect(columns.map(c => c.name)).toEqual([ + expect(columns.map((c) => c.name)).toEqual([ '@timestamp per 20 seconds', 'Sum of @timestamp', '@timestamp per 10 seconds', diff --git a/src/plugins/data/public/search/tabify/get_columns.ts b/src/plugins/data/public/search/tabify/get_columns.ts index ee8c636fb2e86..8c538288d2fea 100644 --- a/src/plugins/data/public/search/tabify/get_columns.ts +++ b/src/plugins/data/public/search/tabify/get_columns.ts @@ -45,7 +45,7 @@ export function tabifyGetColumns(aggs: IAggConfig[], minimalColumns: boolean): T const columns: TabbedAggColumn[] = []; // separate the metrics - const grouped = groupBy(aggs, agg => { + const grouped = groupBy(aggs, (agg) => { return agg.type.type; }); @@ -56,9 +56,9 @@ export function tabifyGetColumns(aggs: IAggConfig[], minimalColumns: boolean): T let columnIndex = 0; // return the buckets, and after each place all of the metrics - grouped.buckets.forEach(agg => { + grouped.buckets.forEach((agg) => { columns.push(getColumn(agg, columnIndex++)); - grouped.metrics.forEach(metric => { + grouped.metrics.forEach((metric) => { columns.push(getColumn(metric, columnIndex++)); }); }); diff --git a/src/plugins/data/public/search/tabify/response_writer.ts b/src/plugins/data/public/search/tabify/response_writer.ts index 02e18d75ae6e5..da9b59cc92791 100644 --- a/src/plugins/data/public/search/tabify/response_writer.ts +++ b/src/plugins/data/public/search/tabify/response_writer.ts @@ -61,15 +61,15 @@ export class TabbedAggResponseWriter { row() { const rowBuffer: TabbedAggRow = {}; - this.bucketBuffer.forEach(bucket => { + this.bucketBuffer.forEach((bucket) => { rowBuffer[bucket.id] = bucket.value; }); - this.metricBuffer.forEach(metric => { + this.metricBuffer.forEach((metric) => { rowBuffer[metric.id] = metric.value; }); - const isPartialRow = !this.columns.every(column => rowBuffer.hasOwnProperty(column.id)); + const isPartialRow = !this.columns.every((column) => rowBuffer.hasOwnProperty(column.id)); const removePartial = isPartialRow && !this.partialRows; if (!isEmpty(rowBuffer) && !removePartial) { this.rows.push(rowBuffer); diff --git a/src/plugins/data/public/search/tabify/tabify.test.ts b/src/plugins/data/public/search/tabify/tabify.test.ts index 63685cc87f5cf..f6691360cec31 100644 --- a/src/plugins/data/public/search/tabify/tabify.test.ts +++ b/src/plugins/data/public/search/tabify/tabify.test.ts @@ -142,7 +142,7 @@ describe('tabifyAggResponse Integration', () => { expectColumns(tabbed, [ext, src, os, avg]); - tabbed.rows.forEach(row => { + tabbed.rows.forEach((row) => { expectRow(row, [expectExtension, expectCountry, expectOS, expectAvgBytes]); }); }); @@ -152,7 +152,7 @@ describe('tabifyAggResponse Integration', () => { expectColumns(tabbed, [ext, avg, src, avg, os, avg]); - tabbed.rows.forEach(row => { + tabbed.rows.forEach((row) => { expectRow(row, [ expectExtension, expectAvgBytes, diff --git a/src/plugins/data/public/ui/filter_bar/filter_bar.tsx b/src/plugins/data/public/ui/filter_bar/filter_bar.tsx index 6852152d059be..d89cf01eedd43 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_bar.tsx +++ b/src/plugins/data/public/ui/filter_bar/filter_bar.tsx @@ -65,7 +65,7 @@ function FilterBarUI(props: Props) { onUpdate(i, newFilter)} + onUpdate={(newFilter) => onUpdate(i, newFilter)} onRemove={() => onRemove(i)} indexPatterns={props.indexPatterns} uiSettings={uiSettings!} diff --git a/src/plugins/data/public/ui/filter_bar/filter_editor/generic_combo_box.tsx b/src/plugins/data/public/ui/filter_bar/filter_editor/generic_combo_box.tsx index a5db8b66caa01..66adbfe9a6fc3 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_editor/generic_combo_box.tsx +++ b/src/plugins/data/public/ui/filter_bar/filter_editor/generic_combo_box.tsx @@ -38,12 +38,12 @@ export function GenericComboBox(props: GenericComboBoxProps) { const { options, selectedOptions, getLabel, onChange, ...otherProps } = props; const labels = options.map(getLabel); - const euiOptions: EuiComboBoxOptionOption[] = labels.map(label => ({ label })); + const euiOptions: EuiComboBoxOptionOption[] = labels.map((label) => ({ label })); const selectedEuiOptions = selectedOptions - .filter(option => { + .filter((option) => { return options.indexOf(option) !== -1; }) - .map(option => { + .map((option) => { return euiOptions[options.indexOf(option)]; }); diff --git a/src/plugins/data/public/ui/filter_bar/filter_editor/index.tsx b/src/plugins/data/public/ui/filter_bar/filter_editor/index.tsx index ffe2a153a87f3..fd228a2213795 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_editor/index.tsx +++ b/src/plugins/data/public/ui/filter_bar/filter_editor/index.tsx @@ -198,7 +198,7 @@ class FilterEditorUI extends Component { if ( this.props.indexPatterns.length <= 1 && this.props.indexPatterns.find( - indexPattern => indexPattern === this.state.selectedIndexPattern + (indexPattern) => indexPattern === this.state.selectedIndexPattern ) ) { return ''; @@ -220,7 +220,7 @@ class FilterEditorUI extends Component { })} options={this.props.indexPatterns} selectedOptions={selectedIndexPattern ? [selectedIndexPattern] : []} - getLabel={indexPattern => indexPattern.title} + getLabel={(indexPattern) => indexPattern.title} onChange={this.onIndexPatternChange} singleSelection={{ asPlainText: true }} isClearable={false} @@ -267,7 +267,7 @@ class FilterEditorUI extends Component { })} options={fields} selectedOptions={selectedField ? [selectedField] : []} - getLabel={field => field.name} + getLabel={(field) => field.name} onChange={this.onFieldChange} singleSelection={{ asPlainText: true }} isClearable={false} diff --git a/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.test.ts b/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.test.ts index 771743a3e5df2..12cdf13caeb55 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.test.ts +++ b/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.test.ts @@ -115,7 +115,7 @@ describe('Filter editor utils', () => { it('limits the fields to the filterable fields', () => { const fieldOptions = getFilterableFields(stubIndexPattern); - const nonFilterableFields = fieldOptions.filter(field => !field.filterable); + const nonFilterableFields = fieldOptions.filter((field) => !field.filterable); expect(nonFilterableFields.length).toBe(0); }); }); @@ -124,14 +124,14 @@ describe('Filter editor utils', () => { it('returns range for number fields', () => { const [field] = stubFields.filter(({ type }) => type === 'number'); const operatorOptions = getOperatorOptions(field); - const rangeOperator = operatorOptions.find(operator => operator.type === 'range'); + const rangeOperator = operatorOptions.find((operator) => operator.type === 'range'); expect(rangeOperator).not.toBeUndefined(); }); it('does not return range for string fields', () => { const [field] = stubFields.filter(({ type }) => type === 'string'); const operatorOptions = getOperatorOptions(field); - const rangeOperator = operatorOptions.find(operator => operator.type === 'range'); + const rangeOperator = operatorOptions.find((operator) => operator.type === 'range'); expect(rangeOperator).toBeUndefined(); }); }); diff --git a/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.ts b/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.ts index beb7714ffcca3..01a664837e704 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.ts +++ b/src/plugins/data/public/ui/filter_bar/filter_editor/lib/filter_editor_utils.ts @@ -29,11 +29,11 @@ import { } from '../../../../../common'; export function getFieldFromFilter(filter: FieldFilter, indexPattern: IIndexPattern) { - return indexPattern.fields.find(field => field.name === filter.meta.key); + return indexPattern.fields.find((field) => field.name === filter.meta.key); } export function getOperatorFromFilter(filter: Filter) { - return FILTER_OPERATORS.find(operator => { + return FILTER_OPERATORS.find((operator) => { return filter.meta.type === operator.type && filter.meta.negate === operator.negate; }); } @@ -43,7 +43,7 @@ export function getFilterableFields(indexPattern: IIndexPattern) { } export function getOperatorOptions(field: IFieldType) { - return FILTER_OPERATORS.filter(operator => { + return FILTER_OPERATORS.filter((operator) => { return !operator.fieldTypes || operator.fieldTypes.includes(field.type); }); } @@ -80,7 +80,7 @@ export function isFilterValid( if (!Array.isArray(params) || !params.length) { return false; } - return params.every(phrase => validateParams(phrase, field.type)); + return params.every((phrase) => validateParams(phrase, field.type)); case 'range': if (typeof params !== 'object') { return false; diff --git a/src/plugins/data/public/ui/filter_bar/filter_editor/phrase_value_input.tsx b/src/plugins/data/public/ui/filter_bar/filter_editor/phrase_value_input.tsx index b16994cb0057b..ca94970afbafd 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_editor/phrase_value_input.tsx +++ b/src/plugins/data/public/ui/filter_bar/filter_editor/phrase_value_input.tsx @@ -71,7 +71,7 @@ class PhraseValueInputUI extends PhraseSuggestorUI { defaultMessage: 'Select a value', })} options={options} - getLabel={option => option} + getLabel={(option) => option} selectedOptions={value ? [valueAsStr] : []} onChange={([newValue = '']) => onChange(newValue)} onSearchChange={this.onSearchChange} diff --git a/src/plugins/data/public/ui/filter_bar/filter_editor/phrases_values_input.tsx b/src/plugins/data/public/ui/filter_bar/filter_editor/phrases_values_input.tsx index 72f92268f3330..7ca46f60bba5b 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_editor/phrases_values_input.tsx +++ b/src/plugins/data/public/ui/filter_bar/filter_editor/phrases_values_input.tsx @@ -49,7 +49,7 @@ class PhrasesValuesInputUI extends PhraseSuggestorUI { defaultMessage: 'Select values', })} options={options} - getLabel={option => option} + getLabel={(option) => option} selectedOptions={values || []} onSearchChange={this.onSearchChange} onCreateOption={(option: string) => onChange([...(values || []), option])} diff --git a/src/plugins/data/public/ui/filter_bar/filter_options.tsx b/src/plugins/data/public/ui/filter_bar/filter_options.tsx index eaa7c291ca00d..3fb7f198d5466 100644 --- a/src/plugins/data/public/ui/filter_bar/filter_options.tsx +++ b/src/plugins/data/public/ui/filter_bar/filter_options.tsx @@ -43,7 +43,7 @@ class FilterOptionsUI extends Component { }; public togglePopover = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; diff --git a/src/plugins/data/public/ui/query_string_input/fetch_index_patterns.ts b/src/plugins/data/public/ui/query_string_input/fetch_index_patterns.ts index 1e01d2452ce04..127dc0f1f41d3 100644 --- a/src/plugins/data/public/ui/query_string_input/fetch_index_patterns.ts +++ b/src/plugins/data/public/ui/query_string_input/fetch_index_patterns.ts @@ -29,7 +29,7 @@ export async function fetchIndexPatterns( return []; } - const searchString = indexPatternStrings.map(string => `"${string}"`).join(' | '); + const searchString = indexPatternStrings.map((string) => `"${string}"`).join(' | '); const indexPatternsFromSavedObjects = await savedObjectsClient.find({ type: 'index-pattern', fields: ['title', 'fields'], @@ -37,7 +37,7 @@ export async function fetchIndexPatterns( searchFields: ['title'], }); - const exactMatches = indexPatternsFromSavedObjects.savedObjects.filter(savedObject => { + const exactMatches = indexPatternsFromSavedObjects.savedObjects.filter((savedObject) => { return indexPatternStrings.includes(savedObject.attributes.title); }); diff --git a/src/plugins/data/public/ui/query_string_input/query_string_input.test.tsx b/src/plugins/data/public/ui/query_string_input/query_string_input.test.tsx index 738c9cfb39398..755716aee8f48 100644 --- a/src/plugins/data/public/ui/query_string_input/query_string_input.test.tsx +++ b/src/plugins/data/public/ui/query_string_input/query_string_input.test.tsx @@ -160,10 +160,7 @@ describe('QueryStringInput', () => { ) ); - component - .find(QueryLanguageSwitcher) - .props() - .onSelectLanguage('lucene'); + component.find(QueryLanguageSwitcher).props().onSelectLanguage('lucene'); expect(mockStorage.set).toHaveBeenCalledWith('kibana.userQueryLanguage', 'lucene'); expect(mockCallback).toHaveBeenCalledWith({ query: '', language: 'lucene' }); }); diff --git a/src/plugins/data/public/ui/query_string_input/query_string_input.tsx b/src/plugins/data/public/ui/query_string_input/query_string_input.tsx index a51362d0ba92e..32295745ce217 100644 --- a/src/plugins/data/public/ui/query_string_input/query_string_input.tsx +++ b/src/plugins/data/public/ui/query_string_input/query_string_input.tsx @@ -105,10 +105,10 @@ export class QueryStringInputUI extends Component { private fetchIndexPatterns = async () => { const stringPatterns = this.props.indexPatterns.filter( - indexPattern => typeof indexPattern === 'string' + (indexPattern) => typeof indexPattern === 'string' ) as string[]; const objectPatterns = this.props.indexPatterns.filter( - indexPattern => typeof indexPattern !== 'string' + (indexPattern) => typeof indexPattern !== 'string' ) as IIndexPattern[]; const objectPatternsFromStrings = (await fetchIndexPatterns( @@ -175,11 +175,11 @@ export class QueryStringInputUI extends Component { return []; } const recentSearches = this.persistedLog.get(); - const matchingRecentSearches = recentSearches.filter(recentQuery => { + const matchingRecentSearches = recentSearches.filter((recentQuery) => { const recentQueryString = typeof recentQuery === 'object' ? toUser(recentQuery) : recentQuery; return recentQueryString.includes(query); }); - return matchingRecentSearches.map(recentSearch => { + return matchingRecentSearches.map((recentSearch) => { const text = toUser(recentSearch); const start = 0; const end = query.length; @@ -536,7 +536,7 @@ export class QueryStringInputUI extends Component { onClick={this.onClickInput} fullWidth autoFocus={!this.props.disableAutoFocus} - inputRef={node => { + inputRef={(node) => { if (node) { this.inputRef = node; } diff --git a/src/plugins/data/public/ui/saved_query_form/save_query_form.tsx b/src/plugins/data/public/ui/saved_query_form/save_query_form.tsx index 5550ea16c22df..c61625dc06c18 100644 --- a/src/plugins/data/public/ui/saved_query_form/save_query_form.tsx +++ b/src/plugins/data/public/ui/saved_query_form/save_query_form.tsx @@ -104,7 +104,7 @@ export function SaveQueryForm({ const errors = []; if ( !!savedQueries.find( - existingSavedQuery => !savedQuery && existingSavedQuery.attributes.title === title + (existingSavedQuery) => !savedQuery && existingSavedQuery.attributes.title === title ) ) { errors.push(titleConflictErrorText); @@ -129,7 +129,7 @@ export function SaveQueryForm({ } }, [validate, onSave, title, description, shouldIncludeFilters, shouldIncludeTimefilter]); - const onInputChange = useCallback(event => { + const onInputChange = useCallback((event) => { setEnabledSaveButton(Boolean(event.target.value)); setFormErrors([]); setTitle(event.target.value); @@ -178,7 +178,7 @@ export function SaveQueryForm({ { + onChange={(event) => { setDescription(event.target.value); }} data-test-subj="saveQueryFormDescription" diff --git a/src/plugins/data/public/ui/saved_query_management/saved_query_management_component.tsx b/src/plugins/data/public/ui/saved_query_management/saved_query_management_component.tsx index 8ad1b5d392f3b..6108de0280183 100644 --- a/src/plugins/data/public/ui/saved_query_management/saved_query_management_component.tsx +++ b/src/plugins/data/public/ui/saved_query_management/saved_query_management_component.tsx @@ -116,7 +116,7 @@ export function SavedQueryManagementComponent({ const onDeleteSavedQuery = async (savedQuery: SavedQuery) => { cancelPendingListingRequest.current(); setSavedQueries( - savedQueries.filter(currentSavedQuery => currentSavedQuery.id !== savedQuery.id) + savedQueries.filter((currentSavedQuery) => currentSavedQuery.id !== savedQuery.id) ); if (loadedSavedQuery && loadedSavedQuery.id === savedQuery.id) { @@ -146,7 +146,7 @@ export function SavedQueryManagementComponent({ ); const savedQueryRows = () => { - const savedQueriesWithoutCurrent = savedQueries.filter(savedQuery => { + const savedQueriesWithoutCurrent = savedQueries.filter((savedQuery) => { if (!loadedSavedQuery) return true; return savedQuery.id !== loadedSavedQuery.id; }); @@ -154,16 +154,16 @@ export function SavedQueryManagementComponent({ loadedSavedQuery && savedQueriesWithoutCurrent.length !== savedQueries.length ? [loadedSavedQuery, ...savedQueriesWithoutCurrent] : [...savedQueriesWithoutCurrent]; - return savedQueriesReordered.map(savedQuery => ( + return savedQueriesReordered.map((savedQuery) => ( { + onSelect={(savedQueryToSelect) => { onLoad(savedQueryToSelect); setIsOpen(false); }} - onDelete={savedQueryToDelete => onDeleteSavedQuery(savedQueryToDelete)} + onDelete={(savedQueryToDelete) => onDeleteSavedQuery(savedQueryToDelete)} showWriteOperations={!!showSaveQuery} /> )); diff --git a/src/plugins/data/public/ui/search_bar/search_bar.tsx b/src/plugins/data/public/ui/search_bar/search_bar.tsx index 2371ccdde068c..a5ac227559115 100644 --- a/src/plugins/data/public/ui/search_bar/search_bar.tsx +++ b/src/plugins/data/public/ui/search_bar/search_bar.tsx @@ -414,13 +414,13 @@ class SearchBarUI extends Component { filterBar = (

{ + ref={(node) => { this.filterBarWrapperRef = node; }} className={filterGroupClasses} >
{ + ref={(node) => { this.filterBarRef = node; }} > @@ -453,7 +453,7 @@ class SearchBarUI extends Component { {this.state.showSaveNewQueryModal ? ( this.onSave(savedQueryMeta, true)} + onSave={(savedQueryMeta) => this.onSave(savedQueryMeta, true)} onClose={() => this.setState({ showSaveNewQueryModal: false })} showFilterOption={this.props.showFilterBar} showTimeFilterOption={this.shouldRenderTimeFilterInSavedQueryForm()} diff --git a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_description_header.tsx b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_description_header.tsx index 947f33efa242c..23cf087de23f3 100644 --- a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_description_header.tsx +++ b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_description_header.tsx @@ -26,8 +26,8 @@ export function getFailurePropsForSummary( ): Array<{ key: string; value: string }> { const failureDetailProps: Array = ['shard', 'index', 'node']; return failureDetailProps - .filter(key => typeof failure[key] === 'number' || typeof failure[key] === 'string') - .map(key => ({ key, value: String(failure[key]) })); + .filter((key) => typeof failure[key] === 'number' || typeof failure[key] === 'string') + .map((key) => ({ key, value: String(failure[key]) })); } export function getFailureSummaryText(failure: ShardFailure, failureDetails?: string): string { @@ -49,7 +49,7 @@ export function getFailureSummaryDetailsText(failure: ShardFailure): string { } export function ShardFailureDescriptionHeader(props: ShardFailure) { - const failureDetails = getFailurePropsForSummary(props).map(kv => ( + const failureDetails = getFailurePropsForSummary(props).map((kv) => ( {kv.key} {kv.value} diff --git a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_modal.tsx b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_modal.tsx index 3dcab7732f769..535f63161966d 100644 --- a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_modal.tsx +++ b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_modal.tsx @@ -104,7 +104,7 @@ export function ShardFailureModal({ request, response, title, onClose }: Props) - {copy => ( + {(copy) => ( { /> ); - component - .find(SuggestionComponent) - .at(1) - .simulate('click'); + component.find(SuggestionComponent).at(1).simulate('click'); expect(mockCallback).toHaveBeenCalledTimes(1); expect(mockCallback).toHaveBeenCalledWith(mockSuggestions[1]); }); @@ -140,10 +137,7 @@ describe('SuggestionsComponent', () => { /> ); - component - .find(SuggestionComponent) - .at(1) - .simulate('mouseenter'); + component.find(SuggestionComponent).at(1).simulate('mouseenter'); expect(mockCallback).toHaveBeenCalledTimes(1); expect(mockCallback).toHaveBeenCalledWith(1); }); diff --git a/src/plugins/data/public/ui/typeahead/suggestions_component.tsx b/src/plugins/data/public/ui/typeahead/suggestions_component.tsx index cdc6cd5b9e772..77dd7dcec01ee 100644 --- a/src/plugins/data/public/ui/typeahead/suggestions_component.tsx +++ b/src/plugins/data/public/ui/typeahead/suggestions_component.tsx @@ -43,7 +43,7 @@ export class SuggestionsComponent extends Component { const suggestions = this.props.suggestions.map((suggestion, index) => { return ( (this.childNodes[index] = node)} + innerRef={(node) => (this.childNodes[index] = node)} selected={index === this.props.index} suggestion={suggestion} onClick={this.props.onClick} @@ -62,7 +62,7 @@ export class SuggestionsComponent extends Component { id="kbnTypeahead__items" className="kbnTypeahead__items" role="listbox" - ref={node => (this.parentNode = node)} + ref={(node) => (this.parentNode = node)} onScroll={this.handleScroll} > {suggestions} diff --git a/src/plugins/data/server/autocomplete/value_suggestions_route.ts b/src/plugins/data/server/autocomplete/value_suggestions_route.ts index b7569a22e9fc9..1b13ff4905c40 100644 --- a/src/plugins/data/server/autocomplete/value_suggestions_route.ts +++ b/src/plugins/data/server/autocomplete/value_suggestions_route.ts @@ -93,7 +93,7 @@ async function getBody( // https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-regexp-query.html#_standard_operators const getEscapedQuery = (q: string = '') => - q.replace(/[.?+*|{}[\]()"\\#@&<>~]/g, match => `\\${match}`); + q.replace(/[.?+*|{}[\]()"\\#@&<>~]/g, (match) => `\\${match}`); // Helps ensure that the regex is not evaluated eagerly against the terms dictionary const executionHint = 'map'; diff --git a/src/plugins/data/server/field_formats/converters/date_server.ts b/src/plugins/data/server/field_formats/converters/date_server.ts index f4e6296259196..85eb65dfc6a8d 100644 --- a/src/plugins/data/server/field_formats/converters/date_server.ts +++ b/src/plugins/data/server/field_formats/converters/date_server.ts @@ -77,7 +77,7 @@ export class DateFormat extends FieldFormat { }; } - textConvert: TextContextTypeConvert = val => { + textConvert: TextContextTypeConvert = (val) => { // don't give away our ref to converter so we can hot-swap when config changes const pattern = this.param('pattern'); const timezone = this.param('timezone'); diff --git a/src/plugins/data/server/field_formats/field_formats_service.ts b/src/plugins/data/server/field_formats/field_formats_service.ts index 3404fe8cee9fd..70584efbee0a0 100644 --- a/src/plugins/data/server/field_formats/field_formats_service.ts +++ b/src/plugins/data/server/field_formats/field_formats_service.ts @@ -42,7 +42,7 @@ export class FieldFormatsService { const uiConfigs = await uiSettings.getAll(); const registeredUiSettings = uiSettings.getRegistered(); - Object.keys(registeredUiSettings).forEach(key => { + Object.keys(registeredUiSettings).forEach((key) => { if (has(uiConfigs, key) && registeredUiSettings[key].type === 'json') { uiConfigs[key] = JSON.parse(uiConfigs[key]); } diff --git a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.test.js b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.test.js index ba4c0865a8d80..a0af7582ac6f3 100644 --- a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.test.js +++ b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.test.js @@ -44,7 +44,7 @@ describe('index_patterns/field_capabilities/field_capabilities', () => { // assert that the stub was called with the exact `args`, using === matching const calledWithExactly = (stub, args, matcher = sinon.match.same) => { - sinon.assert.calledWithExactly(stub, ...args.map(arg => matcher(arg))); + sinon.assert.calledWithExactly(stub, ...args.map((arg) => matcher(arg))); }; const stubDeps = (options = {}) => { @@ -83,10 +83,10 @@ describe('index_patterns/field_capabilities/field_capabilities', () => { const sortedLetters = sortBy(letters); stubDeps({ - fieldsFromFieldCaps: shuffle(letters.map(name => ({ name }))), + fieldsFromFieldCaps: shuffle(letters.map((name) => ({ name }))), }); - const fieldNames = (await getFieldCapabilities()).map(field => field.name); + const fieldNames = (await getFieldCapabilities()).map((field) => field.name); expect(fieldNames).toEqual(sortedLetters); }); }); @@ -99,7 +99,7 @@ describe('index_patterns/field_capabilities/field_capabilities', () => { const resp = await getFieldCapabilities(undefined, undefined, ['meta1', 'meta2']); expect(resp).toHaveLength(4); - expect(resp.map(field => field.name)).toEqual(['bar', 'foo', 'meta1', 'meta2']); + expect(resp.map((field) => field.name)).toEqual(['bar', 'foo', 'meta1', 'meta2']); }); }); @@ -115,7 +115,7 @@ describe('index_patterns/field_capabilities/field_capabilities', () => { }); describe('ensures that every field has property:', () => { - properties.forEach(property => { + properties.forEach((property) => { it(property, async () => { const field = createField(); delete field[property]; @@ -131,7 +131,7 @@ describe('index_patterns/field_capabilities/field_capabilities', () => { // ensure field object was not mutated expect(field).not.toHaveProperty(property); - Object.keys(field).forEach(key => { + Object.keys(field).forEach((key) => { // ensure response field has original values from field expect(resp[0][key]).toBe(footballs[0]); }); diff --git a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.ts b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.ts index 2a30c89342cf3..d8c9466432204 100644 --- a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.ts +++ b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_capabilities.ts @@ -47,10 +47,10 @@ export async function getFieldCapabilities( const fieldsFromFieldCapsByName = indexBy(readFieldCapsResponse(esFieldCaps), 'name'); const allFieldsUnsorted = Object.keys(fieldsFromFieldCapsByName) - .filter(name => !name.startsWith('_')) + .filter((name) => !name.startsWith('_')) .concat(metaFields) .reduce(concatIfUniq, [] as string[]) - .map(name => + .map((name) => defaults({}, fieldsFromFieldCapsByName[name], { name, type: 'string', diff --git a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.test.js b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.test.js index de905ce4f336d..1a4e2b1fe9ee2 100644 --- a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.test.js +++ b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.test.js @@ -49,7 +49,7 @@ describe('index_patterns/field_capabilities/field_caps_response', () => { responseClone.fields['@timestamp'].date.extraCapability = true; const fields = readFieldCapsResponse(responseClone); - fields.forEach(field => { + fields.forEach((field) => { const fieldWithoutOptionalKeys = omit(field, 'conflictDescriptions', 'subType'); expect(Object.keys(fieldWithoutOptionalKeys)).toEqual([ @@ -67,13 +67,13 @@ describe('index_patterns/field_capabilities/field_caps_response', () => { it('calls shouldReadFieldFromDocValues() for each non-conflict field', () => { sandbox.spy(shouldReadFieldFromDocValuesNS, 'shouldReadFieldFromDocValues'); const fields = readFieldCapsResponse(esResponse); - const conflictCount = fields.filter(f => f.type === 'conflict').length; + const conflictCount = fields.filter((f) => f.type === 'conflict').length; // +2 is for the object and nested fields which get filtered out of the final return value from readFieldCapsResponse sinon.assert.callCount(shouldReadFieldFromDocValues, fields.length - conflictCount + 2); }); it('converts es types to kibana types', () => { - readFieldCapsResponse(esResponse).forEach(field => { + readFieldCapsResponse(esResponse).forEach((field) => { if (!getKbnFieldType(field.type)) { throw new Error(`expected field to have kibana type, got ${field.type}`); } @@ -82,7 +82,7 @@ describe('index_patterns/field_capabilities/field_caps_response', () => { it('should include the original ES types found for each field across indices', () => { const fields = readFieldCapsResponse(esResponse); - fields.forEach(field => { + fields.forEach((field) => { const fixtureTypes = Object.keys(esResponse.fields[field.name]); expect(field.esTypes).toEqual(fixtureTypes); }); @@ -90,7 +90,7 @@ describe('index_patterns/field_capabilities/field_caps_response', () => { it('returns fields with multiple types as conflicts', () => { const fields = readFieldCapsResponse(esResponse); - const conflicts = fields.filter(f => f.type === 'conflict'); + const conflicts = fields.filter((f) => f.type === 'conflict'); expect(conflicts).toEqual([ { name: 'success', @@ -109,43 +109,43 @@ describe('index_patterns/field_capabilities/field_caps_response', () => { it('does not return conflicted fields if the types are resolvable to the same kibana type', () => { const fields = readFieldCapsResponse(esResponse); - const resolvableToString = fields.find(f => f.name === 'resolvable_to_string'); - const resolvableToNumber = fields.find(f => f.name === 'resolvable_to_number'); + const resolvableToString = fields.find((f) => f.name === 'resolvable_to_string'); + const resolvableToNumber = fields.find((f) => f.name === 'resolvable_to_number'); expect(resolvableToString.type).toBe('string'); expect(resolvableToNumber.type).toBe('number'); }); it('returns aggregatable if at least one field is aggregatable', () => { const fields = readFieldCapsResponse(esResponse); - const mixAggregatable = fields.find(f => f.name === 'mix_aggregatable'); - const mixAggregatableOther = fields.find(f => f.name === 'mix_aggregatable_other'); + const mixAggregatable = fields.find((f) => f.name === 'mix_aggregatable'); + const mixAggregatableOther = fields.find((f) => f.name === 'mix_aggregatable_other'); expect(mixAggregatable.aggregatable).toBe(true); expect(mixAggregatableOther.aggregatable).toBe(true); }); it('returns searchable if at least one field is searchable', () => { const fields = readFieldCapsResponse(esResponse); - const mixSearchable = fields.find(f => f.name === 'mix_searchable'); - const mixSearchableOther = fields.find(f => f.name === 'mix_searchable_other'); + const mixSearchable = fields.find((f) => f.name === 'mix_searchable'); + const mixSearchableOther = fields.find((f) => f.name === 'mix_searchable_other'); expect(mixSearchable.searchable).toBe(true); expect(mixSearchableOther.searchable).toBe(true); }); it('returns multi fields with a subType key describing the relationship', () => { const fields = readFieldCapsResponse(esResponse); - const child = fields.find(f => f.name === 'multi_parent.child'); + const child = fields.find((f) => f.name === 'multi_parent.child'); expect(child).toHaveProperty('subType', { multi: { parent: 'multi_parent' } }); }); it('returns nested sub-fields with a subType key describing the relationship', () => { const fields = readFieldCapsResponse(esResponse); - const child = fields.find(f => f.name === 'nested_object_parent.child'); + const child = fields.find((f) => f.name === 'nested_object_parent.child'); expect(child).toHaveProperty('subType', { nested: { path: 'nested_object_parent' } }); }); it('handles fields that are both nested and multi', () => { const fields = readFieldCapsResponse(esResponse); - const child = fields.find(f => f.name === 'nested_object_parent.child.keyword'); + const child = fields.find((f) => f.name === 'nested_object_parent.child.keyword'); expect(child).toHaveProperty('subType', { nested: { path: 'nested_object_parent' }, multi: { parent: 'nested_object_parent.child' }, @@ -154,7 +154,7 @@ describe('index_patterns/field_capabilities/field_caps_response', () => { it('does not include the field actually mapped as nested itself', () => { const fields = readFieldCapsResponse(esResponse); - const child = fields.find(f => f.name === 'nested_object_parent'); + const child = fields.find((f) => f.name === 'nested_object_parent'); expect(child).toBeUndefined(); }); @@ -163,7 +163,7 @@ describe('index_patterns/field_capabilities/field_caps_response', () => { // to see if their parents are *not* object fields. In the future we may want to // add subType info for object fields but for now we don't need it. const fields = readFieldCapsResponse(esResponse); - const child = fields.find(f => f.name === 'object_parent.child'); + const child = fields.find((f) => f.name === 'object_parent.child'); expect(child).not.toHaveProperty('subType'); }); }); diff --git a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts index 06eb30db0b24b..cb1ec6a2ebcf3 100644 --- a/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts +++ b/src/plugins/data/server/index_patterns/fetcher/lib/field_capabilities/field_caps_response.ts @@ -93,74 +93,76 @@ export interface FieldCapsResponse { */ export function readFieldCapsResponse(fieldCapsResponse: FieldCapsResponse): FieldDescriptor[] { const capsByNameThenType = fieldCapsResponse.fields; - const kibanaFormattedCaps: FieldDescriptor[] = Object.keys(capsByNameThenType).map(fieldName => { - const capsByType = capsByNameThenType[fieldName]; - const types = Object.keys(capsByType); + const kibanaFormattedCaps: FieldDescriptor[] = Object.keys(capsByNameThenType).map( + (fieldName) => { + const capsByType = capsByNameThenType[fieldName]; + const types = Object.keys(capsByType); - // If a single type is marked as searchable or aggregatable, all the types are searchable or aggregatable - const isSearchable = types.some(type => { - return ( - !!capsByType[type].searchable || - (!!capsByType[type].non_searchable_indices && - capsByType[type].non_searchable_indices!.length > 0) - ); - }); + // If a single type is marked as searchable or aggregatable, all the types are searchable or aggregatable + const isSearchable = types.some((type) => { + return ( + !!capsByType[type].searchable || + (!!capsByType[type].non_searchable_indices && + capsByType[type].non_searchable_indices!.length > 0) + ); + }); - const isAggregatable = types.some(type => { - return ( - !!capsByType[type].aggregatable || - (!!capsByType[type].non_aggregatable_indices && - capsByType[type].non_aggregatable_indices!.length > 0) - ); - }); + const isAggregatable = types.some((type) => { + return ( + !!capsByType[type].aggregatable || + (!!capsByType[type].non_aggregatable_indices && + capsByType[type].non_aggregatable_indices!.length > 0) + ); + }); + + // If there are multiple types but they all resolve to the same kibana type + // ignore the conflict and carry on (my wayward son) + const uniqueKibanaTypes = uniq(types.map(castEsToKbnFieldTypeName)); + if (uniqueKibanaTypes.length > 1) { + return { + name: fieldName, + type: 'conflict', + esTypes: types, + searchable: isSearchable, + aggregatable: isAggregatable, + readFromDocValues: false, + conflictDescriptions: types.reduce( + (acc, esType) => ({ + ...acc, + [esType]: capsByType[esType].indices, + }), + {} + ), + }; + } - // If there are multiple types but they all resolve to the same kibana type - // ignore the conflict and carry on (my wayward son) - const uniqueKibanaTypes = uniq(types.map(castEsToKbnFieldTypeName)); - if (uniqueKibanaTypes.length > 1) { + const esType = types[0]; return { name: fieldName, - type: 'conflict', + type: castEsToKbnFieldTypeName(esType), esTypes: types, searchable: isSearchable, aggregatable: isAggregatable, - readFromDocValues: false, - conflictDescriptions: types.reduce( - (acc, esType) => ({ - ...acc, - [esType]: capsByType[esType].indices, - }), - {} - ), + readFromDocValues: shouldReadFieldFromDocValues(isAggregatable, esType), }; } - - const esType = types[0]; - return { - name: fieldName, - type: castEsToKbnFieldTypeName(esType), - esTypes: types, - searchable: isSearchable, - aggregatable: isAggregatable, - readFromDocValues: shouldReadFieldFromDocValues(isAggregatable, esType), - }; - }); + ); // Get all types of sub fields. These could be multi fields or children of nested/object types - const subFields = kibanaFormattedCaps.filter(field => { + const subFields = kibanaFormattedCaps.filter((field) => { return field.name.includes('.'); }); // Determine the type of each sub field. - subFields.forEach(field => { + subFields.forEach((field) => { const parentFieldNames = field.name .split('.') .slice(0, -1) .map((_, index, parentFieldNameParts) => { return parentFieldNameParts.slice(0, index + 1).join('.'); }); - const parentFieldCaps = parentFieldNames.map(parentFieldName => { - return kibanaFormattedCaps.find(caps => caps.name === parentFieldName); + const parentFieldCaps = parentFieldNames.map((parentFieldName) => { + return kibanaFormattedCaps.find((caps) => caps.name === parentFieldName); }); const parentFieldCapsAscending = parentFieldCaps.reverse(); @@ -174,7 +176,7 @@ export function readFieldCapsResponse(fieldCapsResponse: FieldCapsResponse): Fie // We need to know if any parent field is nested const nestedParentCaps = parentFieldCapsAscending.find( - parentCaps => parentCaps && parentCaps.type === 'nested' + (parentCaps) => parentCaps && parentCaps.type === 'nested' ); if (nestedParentCaps) { subType = { ...subType, nested: { path: nestedParentCaps.name } }; @@ -186,7 +188,7 @@ export function readFieldCapsResponse(fieldCapsResponse: FieldCapsResponse): Fie } }); - return kibanaFormattedCaps.filter(field => { + return kibanaFormattedCaps.filter((field) => { return !['object', 'nested'].includes(field.type); }); } diff --git a/src/plugins/data/server/index_patterns/fetcher/lib/resolve_time_pattern.ts b/src/plugins/data/server/index_patterns/fetcher/lib/resolve_time_pattern.ts index 7504d7bc9c460..764307bef0ba6 100644 --- a/src/plugins/data/server/index_patterns/fetcher/lib/resolve_time_pattern.ts +++ b/src/plugins/data/server/index_patterns/fetcher/lib/resolve_time_pattern.ts @@ -47,7 +47,7 @@ export async function resolveTimePattern(callCluster: APICaller, timePattern: st ) .sortBy((indexName: string) => indexName) .uniq(true) - .map(indexName => { + .map((indexName) => { const parsed = moment(indexName, timePattern, true); if (!parsed.isValid()) { return { @@ -69,8 +69,10 @@ export async function resolveTimePattern(callCluster: APICaller, timePattern: st .value(); return { - all: allIndexDetails.map(details => details.indexName), + all: allIndexDetails.map((details) => details.indexName), - matches: allIndexDetails.filter(details => details.isMatch).map(details => details.indexName), + matches: allIndexDetails + .filter((details) => details.isMatch) + .map((details) => details.indexName), }; } diff --git a/src/plugins/data/server/index_patterns/utils.ts b/src/plugins/data/server/index_patterns/utils.ts index b7adafaeb3e94..e841097fe49c2 100644 --- a/src/plugins/data/server/index_patterns/utils.ts +++ b/src/plugins/data/server/index_patterns/utils.ts @@ -25,7 +25,7 @@ export const getFieldByName = ( indexPattern: IIndexPattern ): IFieldType | undefined => { const fields: IFieldType[] = indexPattern && JSON.parse(indexPattern.attributes.fields); - const field = fields && fields.find(f => f.name === fieldName); + const field = fields && fields.find((f) => f.name === fieldName); return field; }; diff --git a/src/plugins/data/server/kql_telemetry/kql_telemetry_service.ts b/src/plugins/data/server/kql_telemetry/kql_telemetry_service.ts index 3dfaa9c6d0a98..d8ccdcc6a61c5 100644 --- a/src/plugins/data/server/kql_telemetry/kql_telemetry_service.ts +++ b/src/plugins/data/server/kql_telemetry/kql_telemetry_service.ts @@ -42,8 +42,8 @@ export class KqlTelemetryService implements Plugin { this.initializerContext.config.legacy.globalConfig$ .pipe(first()) .toPromise() - .then(config => makeKQLUsageCollector(usageCollection, config.kibana.index)) - .catch(e => { + .then((config) => makeKQLUsageCollector(usageCollection, config.kibana.index)) + .catch((e) => { this.initializerContext.logger .get('kql-telemetry') .warn(`Registering KQL telemetry collector failed: ${e}`); diff --git a/src/plugins/data/server/saved_objects/index_pattern_migrations.ts b/src/plugins/data/server/saved_objects/index_pattern_migrations.ts index c64f7361a8cf4..37819a13b6518 100644 --- a/src/plugins/data/server/saved_objects/index_pattern_migrations.ts +++ b/src/plugins/data/server/saved_objects/index_pattern_migrations.ts @@ -20,7 +20,7 @@ import { flow, omit } from 'lodash'; import { SavedObjectMigrationFn } from 'kibana/server'; -const migrateAttributeTypeAndAttributeTypeMeta: SavedObjectMigrationFn = doc => ({ +const migrateAttributeTypeAndAttributeTypeMeta: SavedObjectMigrationFn = (doc) => ({ ...doc, attributes: { ...doc.attributes, @@ -29,12 +29,12 @@ const migrateAttributeTypeAndAttributeTypeMeta: SavedObjectMigrationFn }, }); -const migrateSubTypeAndParentFieldProperties: SavedObjectMigrationFn = doc => { +const migrateSubTypeAndParentFieldProperties: SavedObjectMigrationFn = (doc) => { if (!doc.attributes.fields) return doc; const fieldsString = doc.attributes.fields; const fields = JSON.parse(fieldsString) as any[]; - const migratedFields = fields.map(field => { + const migratedFields = fields.map((field) => { if (field.subType === 'multi') { return { ...omit(field, 'parent'), diff --git a/src/plugins/data/server/saved_objects/search_migrations.test.ts b/src/plugins/data/server/saved_objects/search_migrations.test.ts index f9b4af7d6d2bf..69db08a689255 100644 --- a/src/plugins/data/server/saved_objects/search_migrations.test.ts +++ b/src/plugins/data/server/saved_objects/search_migrations.test.ts @@ -277,7 +277,7 @@ Object { }); }); - describe('7.4.0', function() { + describe('7.4.0', function () { const migrationFn = searchSavedObjectTypeMigrations['7.4.0']; test('transforms one dimensional sort arrays into two dimensional arrays', () => { diff --git a/src/plugins/data/server/saved_objects/search_migrations.ts b/src/plugins/data/server/saved_objects/search_migrations.ts index c8ded51193c92..2e37cd1255cee 100644 --- a/src/plugins/data/server/saved_objects/search_migrations.ts +++ b/src/plugins/data/server/saved_objects/search_migrations.ts @@ -21,7 +21,7 @@ import { flow, get } from 'lodash'; import { SavedObjectMigrationFn } from 'kibana/server'; import { DEFAULT_QUERY_LANGUAGE } from '../../common'; -const migrateMatchAllQuery: SavedObjectMigrationFn = doc => { +const migrateMatchAllQuery: SavedObjectMigrationFn = (doc) => { const searchSourceJSON = get(doc, 'attributes.kibanaSavedObjectMeta.searchSourceJSON'); if (searchSourceJSON) { @@ -55,7 +55,7 @@ const migrateMatchAllQuery: SavedObjectMigrationFn = doc => { return doc; }; -const migrateIndexPattern: SavedObjectMigrationFn = doc => { +const migrateIndexPattern: SavedObjectMigrationFn = (doc) => { const searchSourceJSON = get(doc, 'attributes.kibanaSavedObjectMeta.searchSourceJSON'); if (typeof searchSourceJSON !== 'string') { return doc; @@ -103,7 +103,7 @@ const setNewReferences: SavedObjectMigrationFn = (doc, context) => { return migrateIndexPattern(doc, context); }; -const migrateSearchSortToNestedArray: SavedObjectMigrationFn = doc => { +const migrateSearchSortToNestedArray: SavedObjectMigrationFn = (doc) => { const sort = get(doc, 'attributes.sort'); if (!sort) return doc; diff --git a/src/plugins/data/server/search/search_service.ts b/src/plugins/data/server/search/search_service.ts index 5ee19cd3df19f..2a0164f113097 100644 --- a/src/plugins/data/server/search/search_service.ts +++ b/src/plugins/data/server/search/search_service.ts @@ -57,7 +57,7 @@ export class SearchService implements Plugin { core.savedObjects.registerType(searchSavedObjectType); - core.http.registerRouteHandlerContext<'search'>('search', context => { + core.http.registerRouteHandlerContext<'search'>('search', (context) => { return createApi({ caller: context.core.elasticsearch.dataClient.callAsCurrentUser, searchStrategies: this.searchStrategies, diff --git a/src/plugins/dev_tools/public/application.tsx b/src/plugins/dev_tools/public/application.tsx index 4e9128c327fe1..1a9d6bf4848f4 100644 --- a/src/plugins/dev_tools/public/application.tsx +++ b/src/plugins/dev_tools/public/application.tsx @@ -60,7 +60,7 @@ function DevToolsWrapper({ return (
- {devTools.map(currentDevTool => ( + {devTools.map((currentDevTool) => ( { + ref={async (element) => { if ( element && (mountedTool.current === null || @@ -172,13 +172,13 @@ export function renderApp( {devTools // Only create routes for devtools that are not disabled - .filter(devTool => !devTool.isDisabled()) - .map(devTool => ( + .filter((devTool) => !devTool.isDisabled()) + .map((devTool) => ( ( + render={(props) => ( { +const k7Breadcrumbs = ($route) => { const { indexPattern } = $route.current.locals; const { id } = $route.current.params; @@ -44,7 +44,7 @@ const k7Breadcrumbs = $route => { ]; }; -getAngularModule().config($routeProvider => { +getAngularModule().config(($routeProvider) => { $routeProvider // deprecated route, kept for compatibility // should be removed in the future @@ -97,7 +97,7 @@ function ContextAppRouteController($routeParams, $scope, $route) { 'contextAppRoute.state.predecessorCount', 'contextAppRoute.state.successorCount', ], - newValues => { + (newValues) => { const [columns, predecessorCount, successorCount] = newValues; if (Array.isArray(columns) && predecessorCount >= 0 && successorCount >= 0) { setAppState({ columns, predecessorCount, successorCount }); diff --git a/src/plugins/discover/public/application/angular/context/api/_stubs.js b/src/plugins/discover/public/application/angular/context/api/_stubs.js index acd609df203e3..35ddf396c2dba 100644 --- a/src/plugins/discover/public/application/angular/context/api/_stubs.js +++ b/src/plugins/discover/public/application/angular/context/api/_stubs.js @@ -22,7 +22,7 @@ import moment from 'moment'; export function createIndexPatternsStub() { return { - get: sinon.spy(indexPatternId => + get: sinon.spy((indexPatternId) => Promise.resolve({ id: indexPatternId, isTimeNanosBased: () => false, @@ -48,7 +48,7 @@ export function createSearchSourceStub(hits, timeField) { searchSourceStub.setParent = sinon.spy(() => searchSourceStub); searchSourceStub.setField = sinon.spy(() => searchSourceStub); - searchSourceStub.getField = sinon.spy(key => { + searchSourceStub.getField = sinon.spy((key) => { const previousSetCall = searchSourceStub.setField.withArgs(key).lastCall; return previousSetCall ? previousSetCall.args[1] : null; }); @@ -83,7 +83,7 @@ export function createContextSearchSourceStub(hits, timeField = '@timestamp') { : (first, second) => second[timeField] - first[timeField]; const filteredHits = searchSourceStub._stubHits .filter( - hit => + (hit) => moment(hit[timeField]).isSameOrAfter(timeRange.gte) && moment(hit[timeField]).isSameOrBefore(timeRange.lte) ) diff --git a/src/plugins/discover/public/application/angular/context/api/anchor.test.js b/src/plugins/discover/public/application/angular/context/api/anchor.test.js index 757e74589555a..993aefc4f59e3 100644 --- a/src/plugins/discover/public/application/angular/context/api/anchor.test.js +++ b/src/plugins/discover/public/application/angular/context/api/anchor.test.js @@ -21,8 +21,8 @@ import { createIndexPatternsStub, createSearchSourceStub } from './_stubs'; import { fetchAnchorProvider } from './anchor'; -describe('context app', function() { - describe('function fetchAnchor', function() { +describe('context app', function () { + describe('function fetchAnchor', function () { let fetchAnchor; let searchSourceStub; @@ -31,7 +31,7 @@ describe('context app', function() { fetchAnchor = fetchAnchorProvider(createIndexPatternsStub(), searchSourceStub); }); - it('should use the `fetch` method of the SearchSource', function() { + it('should use the `fetch` method of the SearchSource', function () { return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, @@ -40,7 +40,7 @@ describe('context app', function() { }); }); - it('should configure the SearchSource to not inherit from the implicit root', function() { + it('should configure the SearchSource to not inherit from the implicit root', function () { return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, @@ -51,7 +51,7 @@ describe('context app', function() { }); }); - it('should set the SearchSource index pattern', function() { + it('should set the SearchSource index pattern', function () { return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, @@ -61,7 +61,7 @@ describe('context app', function() { }); }); - it('should set the SearchSource version flag to true', function() { + it('should set the SearchSource version flag to true', function () { return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, @@ -72,7 +72,7 @@ describe('context app', function() { }); }); - it('should set the SearchSource size to 1', function() { + it('should set the SearchSource size to 1', function () { return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, @@ -83,7 +83,7 @@ describe('context app', function() { }); }); - it('should set the SearchSource query to an ids query', function() { + it('should set the SearchSource query to an ids query', function () { return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, @@ -105,7 +105,7 @@ describe('context app', function() { }); }); - it('should set the SearchSource sort order', function() { + it('should set the SearchSource sort order', function () { return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, @@ -116,7 +116,7 @@ describe('context app', function() { }); }); - it('should reject with an error when no hits were found', function() { + it('should reject with an error when no hits were found', function () { searchSourceStub._stubHits = []; return fetchAnchor('INDEX_PATTERN_ID', 'id', [ @@ -126,19 +126,19 @@ describe('context app', function() { () => { expect().fail('expected the promise to be rejected'); }, - error => { + (error) => { expect(error).toBeInstanceOf(Error); } ); }); - it('should return the first hit after adding an anchor marker', function() { + it('should return the first hit after adding an anchor marker', function () { searchSourceStub._stubHits = [{ property1: 'value1' }, { property2: 'value2' }]; return fetchAnchor('INDEX_PATTERN_ID', 'id', [ { '@timestamp': 'desc' }, { _doc: 'desc' }, - ]).then(anchorDocument => { + ]).then((anchorDocument) => { expect(anchorDocument).toHaveProperty('property1', 'value1'); expect(anchorDocument).toHaveProperty('$$_isAnchor', true); }); diff --git a/src/plugins/discover/public/application/angular/context/api/context.predecessors.test.js b/src/plugins/discover/public/application/angular/context/api/context.predecessors.test.js index ebd4af536aabd..fcde2ade0b2c6 100644 --- a/src/plugins/discover/public/application/angular/context/api/context.predecessors.test.js +++ b/src/plugins/discover/public/application/angular/context/api/context.predecessors.test.js @@ -29,8 +29,8 @@ const ANCHOR_TIMESTAMP_3 = new Date(MS_PER_DAY * 3).toJSON(); const ANCHOR_TIMESTAMP_1000 = new Date(MS_PER_DAY * 1000).toJSON(); const ANCHOR_TIMESTAMP_3000 = new Date(MS_PER_DAY * 3000).toJSON(); -describe('context app', function() { - describe('function fetchPredecessors', function() { +describe('context app', function () { + describe('function fetchPredecessors', function () { let fetchPredecessors; let mockSearchSource; @@ -77,7 +77,7 @@ describe('context app', function() { }; }); - it('should perform exactly one query when enough hits are returned', function() { + it('should perform exactly one query when enough hits are returned', function () { mockSearchSource._stubHits = [ mockSearchSource._createStubHit(MS_PER_DAY * 3000 + 2), mockSearchSource._createStubHit(MS_PER_DAY * 3000 + 1), @@ -96,13 +96,13 @@ describe('context app', function() { 0, 3, [] - ).then(hits => { + ).then((hits) => { expect(mockSearchSource.fetch.calledOnce).toBe(true); expect(hits).toEqual(mockSearchSource._stubHits.slice(0, 3)); }); }); - it('should perform multiple queries with the last being unrestricted when too few hits are returned', function() { + it('should perform multiple queries with the last being unrestricted when too few hits are returned', function () { mockSearchSource._stubHits = [ mockSearchSource._createStubHit(MS_PER_DAY * 3010), mockSearchSource._createStubHit(MS_PER_DAY * 3002), @@ -121,7 +121,7 @@ describe('context app', function() { 0, 6, [] - ).then(hits => { + ).then((hits) => { const intervals = mockSearchSource.setField.args .filter(([property]) => property === 'query') .map(([, { query }]) => @@ -141,7 +141,7 @@ describe('context app', function() { }); }); - it('should perform multiple queries until the expected hit count is returned', function() { + it('should perform multiple queries until the expected hit count is returned', function () { mockSearchSource._stubHits = [ mockSearchSource._createStubHit(MS_PER_DAY * 1700), mockSearchSource._createStubHit(MS_PER_DAY * 1200), @@ -159,7 +159,7 @@ describe('context app', function() { 0, 3, [] - ).then(hits => { + ).then((hits) => { const intervals = mockSearchSource.setField.args .filter(([property]) => property === 'query') .map(([, { query }]) => @@ -175,7 +175,7 @@ describe('context app', function() { }); }); - it('should return an empty array when no hits were found', function() { + it('should return an empty array when no hits were found', function () { return fetchPredecessors( 'INDEX_PATTERN_ID', '@timestamp', @@ -186,12 +186,12 @@ describe('context app', function() { 0, 3, [] - ).then(hits => { + ).then((hits) => { expect(hits).toEqual([]); }); }); - it('should configure the SearchSource to not inherit from the implicit root', function() { + it('should configure the SearchSource to not inherit from the implicit root', function () { return fetchPredecessors( 'INDEX_PATTERN_ID', '@timestamp', @@ -209,7 +209,7 @@ describe('context app', function() { }); }); - it('should set the tiebreaker sort order to the opposite as the time field', function() { + it('should set the tiebreaker sort order to the opposite as the time field', function () { return fetchPredecessors( 'INDEX_PATTERN_ID', '@timestamp', diff --git a/src/plugins/discover/public/application/angular/context/api/context.successors.test.js b/src/plugins/discover/public/application/angular/context/api/context.successors.test.js index 452d0cc9fd1a0..0f84aa82a989a 100644 --- a/src/plugins/discover/public/application/angular/context/api/context.successors.test.js +++ b/src/plugins/discover/public/application/angular/context/api/context.successors.test.js @@ -30,8 +30,8 @@ const ANCHOR_TIMESTAMP = new Date(MS_PER_DAY).toJSON(); const ANCHOR_TIMESTAMP_3 = new Date(MS_PER_DAY * 3).toJSON(); const ANCHOR_TIMESTAMP_3000 = new Date(MS_PER_DAY * 3000).toJSON(); -describe('context app', function() { - describe('function fetchSuccessors', function() { +describe('context app', function () { + describe('function fetchSuccessors', function () { let fetchSuccessors; let mockSearchSource; @@ -78,7 +78,7 @@ describe('context app', function() { }; }); - it('should perform exactly one query when enough hits are returned', function() { + it('should perform exactly one query when enough hits are returned', function () { mockSearchSource._stubHits = [ mockSearchSource._createStubHit(MS_PER_DAY * 5000), mockSearchSource._createStubHit(MS_PER_DAY * 4000), @@ -97,13 +97,13 @@ describe('context app', function() { 0, 3, [] - ).then(hits => { + ).then((hits) => { expect(mockSearchSource.fetch.calledOnce).toBe(true); expect(hits).toEqual(mockSearchSource._stubHits.slice(-3)); }); }); - it('should perform multiple queries with the last being unrestricted when too few hits are returned', function() { + it('should perform multiple queries with the last being unrestricted when too few hits are returned', function () { mockSearchSource._stubHits = [ mockSearchSource._createStubHit(MS_PER_DAY * 3010), mockSearchSource._createStubHit(MS_PER_DAY * 3002), @@ -122,7 +122,7 @@ describe('context app', function() { 0, 6, [] - ).then(hits => { + ).then((hits) => { const intervals = mockSearchSource.setField.args .filter(([property]) => property === 'query') .map(([, { query }]) => @@ -142,7 +142,7 @@ describe('context app', function() { }); }); - it('should perform multiple queries until the expected hit count is returned', function() { + it('should perform multiple queries until the expected hit count is returned', function () { mockSearchSource._stubHits = [ mockSearchSource._createStubHit(MS_PER_DAY * 3000), mockSearchSource._createStubHit(MS_PER_DAY * 3000 - 1), @@ -162,7 +162,7 @@ describe('context app', function() { 0, 4, [] - ).then(hits => { + ).then((hits) => { const intervals = mockSearchSource.setField.args .filter(([property]) => property === 'query') .map(([, { query }]) => @@ -179,7 +179,7 @@ describe('context app', function() { }); }); - it('should return an empty array when no hits were found', function() { + it('should return an empty array when no hits were found', function () { return fetchSuccessors( 'INDEX_PATTERN_ID', '@timestamp', @@ -190,12 +190,12 @@ describe('context app', function() { 0, 3, [] - ).then(hits => { + ).then((hits) => { expect(hits).toEqual([]); }); }); - it('should configure the SearchSource to not inherit from the implicit root', function() { + it('should configure the SearchSource to not inherit from the implicit root', function () { return fetchSuccessors( 'INDEX_PATTERN_ID', '@timestamp', @@ -213,7 +213,7 @@ describe('context app', function() { }); }); - it('should set the tiebreaker sort order to the same as the time field', function() { + it('should set the tiebreaker sort order to the same as the time field', function () { return fetchSuccessors( 'INDEX_PATTERN_ID', '@timestamp', diff --git a/src/plugins/discover/public/application/angular/context/api/context.ts b/src/plugins/discover/public/application/angular/context/api/context.ts index a47005b640538..e244176914a9b 100644 --- a/src/plugins/discover/public/application/angular/context/api/context.ts +++ b/src/plugins/discover/public/application/angular/context/api/context.ts @@ -37,7 +37,7 @@ export type EsHitRecordList = EsHitRecord[]; const DAY_MILLIS = 24 * 60 * 60 * 1000; // look from 1 day up to 10000 days into the past and future -const LOOKUP_OFFSETS = [0, 1, 7, 30, 365, 10000].map(days => days * DAY_MILLIS); +const LOOKUP_OFFSETS = [0, 1, 7, 30, 365, 10000].map((days) => days * DAY_MILLIS); function fetchContextProvider(indexPatterns: IndexPatternsContract) { return { diff --git a/src/plugins/discover/public/application/angular/context/api/utils/date_conversion.test.ts b/src/plugins/discover/public/application/angular/context/api/utils/date_conversion.test.ts index 223b174718296..7cb3ac1f3f745 100644 --- a/src/plugins/discover/public/application/angular/context/api/utils/date_conversion.test.ts +++ b/src/plugins/discover/public/application/angular/context/api/utils/date_conversion.test.ts @@ -18,14 +18,14 @@ */ import { extractNanos } from './date_conversion'; -describe('function extractNanos', function() { - test('extract nanos of 2014-01-01', function() { +describe('function extractNanos', function () { + test('extract nanos of 2014-01-01', function () { expect(extractNanos('2014-01-01')).toBe('000000000'); }); - test('extract nanos of 2014-01-01T12:12:12.234Z', function() { + test('extract nanos of 2014-01-01T12:12:12.234Z', function () { expect(extractNanos('2014-01-01T12:12:12.234Z')).toBe('234000000'); }); - test('extract nanos of 2014-01-01T12:12:12.234123321Z', function() { + test('extract nanos of 2014-01-01T12:12:12.234123321Z', function () { expect(extractNanos('2014-01-01T12:12:12.234123321Z')).toBe('234123321'); }); }); diff --git a/src/plugins/discover/public/application/angular/context/api/utils/generate_intervals.ts b/src/plugins/discover/public/application/angular/context/api/utils/generate_intervals.ts index 1497f54aa5079..81533917dfff8 100644 --- a/src/plugins/discover/public/application/angular/context/api/utils/generate_intervals.ts +++ b/src/plugins/discover/public/application/angular/context/api/utils/generate_intervals.ts @@ -50,5 +50,5 @@ export function generateIntervals( ? 1 : -1; // ending with `null` opens the last interval - return asPairs([...offsets.map(offset => startTime + offset * offsetSign), null]); + return asPairs([...offsets.map((offset) => startTime + offset * offsetSign), null]); } diff --git a/src/plugins/discover/public/application/angular/context/api/utils/sorting.test.ts b/src/plugins/discover/public/application/angular/context/api/utils/sorting.test.ts index 350a0a8ede8d5..20b868367471c 100644 --- a/src/plugins/discover/public/application/angular/context/api/utils/sorting.test.ts +++ b/src/plugins/discover/public/application/angular/context/api/utils/sorting.test.ts @@ -18,8 +18,8 @@ */ import { reverseSortDir, SortDirection } from './sorting'; -describe('function reverseSortDir', function() { - test('reverse a given sort direction', function() { +describe('function reverseSortDir', function () { + test('reverse a given sort direction', function () { expect(reverseSortDir(SortDirection.asc)).toBe(SortDirection.desc); expect(reverseSortDir(SortDirection.desc)).toBe(SortDirection.asc); }); diff --git a/src/plugins/discover/public/application/angular/context/api/utils/sorting.ts b/src/plugins/discover/public/application/angular/context/api/utils/sorting.ts index ef1be8d48d338..2a5d6312921b8 100644 --- a/src/plugins/discover/public/application/angular/context/api/utils/sorting.ts +++ b/src/plugins/discover/public/application/angular/context/api/utils/sorting.ts @@ -36,7 +36,7 @@ const META_FIELD_NAMES: string[] = ['_seq_no', '_doc', '_uid']; */ export function getFirstSortableField(indexPattern: IndexPattern, fieldNames: string[]) { const sortableFields = fieldNames.filter( - fieldName => + (fieldName) => META_FIELD_NAMES.includes(fieldName) || // @ts-ignore (indexPattern.fields.getByName(fieldName) || { sortable: false }).sortable diff --git a/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.test.tsx b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.test.tsx index 325cfb2c9f0bb..8976f8ea3c107 100644 --- a/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.test.tsx +++ b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.test.tsx @@ -25,7 +25,7 @@ import { findTestSubject } from '@elastic/eui/lib/test'; import { MAX_CONTEXT_SIZE, MIN_CONTEXT_SIZE } from '../../query_parameters/constants'; describe('Test Discover Context ActionBar for successor | predecessor records', () => { - ['successors', 'predecessors'].forEach(type => { + ['successors', 'predecessors'].forEach((type) => { const onChangeCount = jest.fn(); const props = { defaultStepSize: 5, diff --git a/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.tsx b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.tsx index 97a29ab21c581..ac88d2aa36696 100644 --- a/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.tsx +++ b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar.tsx @@ -131,7 +131,7 @@ export function ActionBar({ disabled={isDisabled} min={MIN_CONTEXT_SIZE} max={MAX_CONTEXT_SIZE} - onChange={ev => { + onChange={(ev) => { setNewDocCount(ev.target.valueAsNumber); }} onBlur={() => { diff --git a/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar_directive.ts b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar_directive.ts index b705b4e4faeb5..2a77b762c2966 100644 --- a/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar_directive.ts +++ b/src/plugins/discover/public/application/angular/context/components/action_bar/action_bar_directive.ts @@ -19,6 +19,6 @@ import { getAngularModule } from '../../../../../kibana_services'; import { ActionBar } from './action_bar'; -getAngularModule().directive('contextActionBar', function(reactDirective: any) { +getAngularModule().directive('contextActionBar', function (reactDirective: any) { return reactDirective(ActionBar); }); diff --git a/src/plugins/discover/public/application/angular/context/query/actions.js b/src/plugins/discover/public/application/angular/context/query/actions.js index 6f8d5fe64f831..0e057e0a715c4 100644 --- a/src/plugins/discover/public/application/angular/context/query/actions.js +++ b/src/plugins/discover/public/application/angular/context/query/actions.js @@ -37,24 +37,24 @@ export function QueryActionsProvider(Promise) { indexPatterns ); - const setFailedStatus = state => (subject, details = {}) => + const setFailedStatus = (state) => (subject, details = {}) => (state.loadingStatus[subject] = { status: LOADING_STATUS.FAILED, reason: FAILURE_REASONS.UNKNOWN, ...details, }); - const setLoadedStatus = state => subject => + const setLoadedStatus = (state) => (subject) => (state.loadingStatus[subject] = { status: LOADING_STATUS.LOADED, }); - const setLoadingStatus = state => subject => + const setLoadingStatus = (state) => (subject) => (state.loadingStatus[subject] = { status: LOADING_STATUS.LOADING, }); - const fetchAnchorRow = state => () => { + const fetchAnchorRow = (state) => () => { const { queryParameters: { indexPatternId, anchorId, sort, tieBreakerField }, } = state; @@ -72,12 +72,12 @@ export function QueryActionsProvider(Promise) { return Promise.try(() => fetchAnchor(indexPatternId, anchorId, [_.zipObject([sort]), { [tieBreakerField]: sort[1] }]) ).then( - anchorDocument => { + (anchorDocument) => { setLoadedStatus(state)('anchor'); state.rows.anchor = anchorDocument; return anchorDocument; }, - error => { + (error) => { setFailedStatus(state)('anchor', { error }); getServices().toastNotifications.addDanger({ title: i18n.translate('discover.context.unableToLoadAnchorDocumentDescription', { @@ -125,12 +125,12 @@ export function QueryActionsProvider(Promise) { filters ) ).then( - documents => { + (documents) => { setLoadedStatus(state)(type); state.rows[type] = documents; return documents; }, - error => { + (error) => { setFailedStatus(state)(type, { error }); getServices().toastNotifications.addDanger({ title: i18n.translate('discover.context.unableToLoadDocumentDescription', { @@ -143,36 +143,36 @@ export function QueryActionsProvider(Promise) { ); }; - const fetchContextRows = state => () => + const fetchContextRows = (state) => () => Promise.all([ fetchSurroundingRows('predecessors', state), fetchSurroundingRows('successors', state), ]); - const fetchAllRows = state => () => + const fetchAllRows = (state) => () => Promise.try(fetchAnchorRow(state)).then(fetchContextRows(state)); - const fetchContextRowsWithNewQueryParameters = state => queryParameters => { + const fetchContextRowsWithNewQueryParameters = (state) => (queryParameters) => { setQueryParameters(state)(queryParameters); return fetchContextRows(state)(); }; - const fetchAllRowsWithNewQueryParameters = state => queryParameters => { + const fetchAllRowsWithNewQueryParameters = (state) => (queryParameters) => { setQueryParameters(state)(queryParameters); return fetchAllRows(state)(); }; - const fetchGivenPredecessorRows = state => count => { + const fetchGivenPredecessorRows = (state) => (count) => { setPredecessorCount(state)(count); return fetchSurroundingRows('predecessors', state); }; - const fetchGivenSuccessorRows = state => count => { + const fetchGivenSuccessorRows = (state) => (count) => { setSuccessorCount(state)(count); return fetchSurroundingRows('successors', state); }; - const setAllRows = state => (predecessorRows, anchorRow, successorRows) => + const setAllRows = (state) => (predecessorRows, anchorRow, successorRows) => (state.rows.all = [ ...(predecessorRows || []), ...(anchorRow ? [anchorRow] : []), diff --git a/src/plugins/discover/public/application/angular/context/query_parameters/actions.js b/src/plugins/discover/public/application/angular/context/query_parameters/actions.js index 4f86dea08fe84..fcd4b8ac02cfb 100644 --- a/src/plugins/discover/public/application/angular/context/query_parameters/actions.js +++ b/src/plugins/discover/public/application/angular/context/query_parameters/actions.js @@ -23,28 +23,28 @@ import { esFilters } from '../../../../../../data/public'; import { MAX_CONTEXT_SIZE, MIN_CONTEXT_SIZE, QUERY_PARAMETER_KEYS } from './constants'; export function getQueryParameterActions(filterManager, indexPatterns) { - const setPredecessorCount = state => predecessorCount => + const setPredecessorCount = (state) => (predecessorCount) => (state.queryParameters.predecessorCount = clamp( MIN_CONTEXT_SIZE, MAX_CONTEXT_SIZE, predecessorCount )); - const setSuccessorCount = state => successorCount => + const setSuccessorCount = (state) => (successorCount) => (state.queryParameters.successorCount = clamp( MIN_CONTEXT_SIZE, MAX_CONTEXT_SIZE, successorCount )); - const setQueryParameters = state => queryParameters => + const setQueryParameters = (state) => (queryParameters) => Object.assign(state.queryParameters, _.pick(queryParameters, QUERY_PARAMETER_KEYS)); - const updateFilters = () => filters => { + const updateFilters = () => (filters) => { filterManager.setFilters(filters); }; - const addFilter = state => async (field, values, operation) => { + const addFilter = (state) => async (field, values, operation) => { const indexPatternId = state.queryParameters.indexPatternId; const newFilters = esFilters.generateFilters( filterManager, diff --git a/src/plugins/discover/public/application/angular/context/query_parameters/actions.test.ts b/src/plugins/discover/public/application/angular/context/query_parameters/actions.test.ts index 00747fcc81227..6309c61d3bb34 100644 --- a/src/plugins/discover/public/application/angular/context/query_parameters/actions.test.ts +++ b/src/plugins/discover/public/application/angular/context/query_parameters/actions.test.ts @@ -48,7 +48,7 @@ beforeEach(() => { }; }); -describe('context query_parameter actions', function() { +describe('context query_parameter actions', function () { describe('action addFilter', () => { it('should pass the given arguments to the filterManager', () => { const { addFilter } = getQueryParameterActions(filterManager); @@ -90,7 +90,7 @@ describe('context query_parameter actions', function() { }); }); describe('action setSuccessorCount', () => { - it('should set the successorCount to the given value', function() { + it('should set the successorCount to the given value', function () { const { setSuccessorCount } = getQueryParameterActions(filterManager); setSuccessorCount(state)(20); @@ -109,10 +109,10 @@ describe('context query_parameter actions', function() { expect(state.queryParameters.successorCount).toBe(10000); }); }); - describe('action setQueryParameters', function() { + describe('action setQueryParameters', function () { const { setQueryParameters } = getQueryParameterActions(filterManager); - it('should update the queryParameters with valid properties from the given object', function() { + it('should update the queryParameters with valid properties from the given object', function () { const newState = { ...state, queryParameters: { @@ -144,7 +144,7 @@ describe('context query_parameter actions', function() { }); }); - it('should ignore invalid properties', function() { + it('should ignore invalid properties', function () { const newState = { ...state }; setQueryParameters(newState)({ diff --git a/src/plugins/discover/public/application/angular/context_app.js b/src/plugins/discover/public/application/angular/context_app.js index acb94bf97d21f..f698ed84a8948 100644 --- a/src/plugins/discover/public/application/angular/context_app.js +++ b/src/plugins/discover/public/application/angular/context_app.js @@ -69,7 +69,7 @@ function ContextAppController($scope, Private) { ...queryParameterActions, ...queryActions, }, - action => (...args) => action(this.state)(...args) + (action) => (...args) => action(this.state)(...args) ); this.constants = { @@ -83,7 +83,7 @@ function ContextAppController($scope, Private) { () => this.state.rows.anchor, () => this.state.rows.successors, ], - newValues => this.actions.setAllRows(...newValues) + (newValues) => this.actions.setAllRows(...newValues) ); /** @@ -94,7 +94,7 @@ function ContextAppController($scope, Private) { ..._.pick(this, QUERY_PARAMETER_KEYS), indexPatternId: this.indexPattern.id, }), - newQueryParameters => { + (newQueryParameters) => { const { queryParameters } = this.state; if ( newQueryParameters.indexPatternId !== queryParameters.indexPatternId || @@ -120,7 +120,7 @@ function ContextAppController($scope, Private) { predecessorCount: this.state.queryParameters.predecessorCount, successorCount: this.state.queryParameters.successorCount, }), - newParameters => { + (newParameters) => { _.assign(this, newParameters); } ); diff --git a/src/plugins/discover/public/application/angular/directives/collapsible_sidebar/collapsible_sidebar.ts b/src/plugins/discover/public/application/angular/directives/collapsible_sidebar/collapsible_sidebar.ts index 5b6de7f16d444..16fbb0af9f3fd 100644 --- a/src/plugins/discover/public/application/angular/directives/collapsible_sidebar/collapsible_sidebar.ts +++ b/src/plugins/discover/public/application/angular/directives/collapsible_sidebar/collapsible_sidebar.ts @@ -27,7 +27,7 @@ interface LazyScope extends IScope { export function CollapsibleSidebarProvider() { // simply a list of all of all of angulars .col-md-* classes except 12 - const listOfWidthClasses = _.times(11, function(i) { + const listOfWidthClasses = _.times(11, function (i) { return 'col-md-' + i; }); @@ -60,7 +60,7 @@ export function CollapsibleSidebarProvider() { // If there is are only two elements we can assume the other one will take 100% of the width. const hasSingleSibling = $siblings.length === 1 && siblingsClass; - $collapser.on('click', function() { + $collapser.on('click', function () { if (isCollapsed) { isCollapsed = false; $elem.removeClass('closed'); diff --git a/src/plugins/discover/public/application/angular/directives/debounce/debounce.js b/src/plugins/discover/public/application/angular/directives/debounce/debounce.js index 54507f673c2d6..586e8ed4fab59 100644 --- a/src/plugins/discover/public/application/angular/directives/debounce/debounce.js +++ b/src/plugins/discover/public/application/angular/directives/debounce/debounce.js @@ -22,7 +22,7 @@ import _ from 'lodash'; // borrowed heavily from https://github.com/shahata/angular-debounce export function DebounceProviderTimeout($timeout) { - return function(func, wait, options) { + return function (func, wait, options) { let timeout; let args; let self; @@ -37,7 +37,7 @@ export function DebounceProviderTimeout($timeout) { self = this; args = arguments; - const later = function() { + const later = function () { timeout = null; if (!options.leading || options.trailing) { result = func.apply(self, args); @@ -58,7 +58,7 @@ export function DebounceProviderTimeout($timeout) { return result; } - debounce.cancel = function() { + debounce.cancel = function () { $timeout.cancel(timeout); timeout = null; }; diff --git a/src/plugins/discover/public/application/angular/directives/debounce/debounce.test.ts b/src/plugins/discover/public/application/angular/directives/debounce/debounce.test.ts index bc08d8566d48a..ccdee153002e4 100644 --- a/src/plugins/discover/public/application/angular/directives/debounce/debounce.test.ts +++ b/src/plugins/discover/public/application/angular/directives/debounce/debounce.test.ts @@ -31,7 +31,7 @@ import { navigationPluginMock } from '../../../../../../navigation/public/mocks' import { dataPluginMock } from '../../../../../../data/public/mocks'; import { initAngularBootstrap } from '../../../../../../kibana_legacy/public'; -describe('debounce service', function() { +describe('debounce service', function () { let debounce: (fn: () => void, timeout: number, options?: any) => any; let debounceFromProvider: (fn: () => void, timeout: number, options?: any) => any; let $timeout: ITimeoutService; @@ -61,7 +61,7 @@ describe('debounce service', function() { ); }); - it('should have a cancel method', function() { + it('should have a cancel method', function () { const bouncer = debounce(() => {}, 100); const bouncerFromProvider = debounceFromProvider(() => {}, 100); @@ -69,13 +69,13 @@ describe('debounce service', function() { expect(bouncerFromProvider).toHaveProperty('cancel'); }); - describe('delayed execution', function() { + describe('delayed execution', function () { const sandbox = sinon.createSandbox(); beforeEach(() => sandbox.useFakeTimers()); afterEach(() => sandbox.restore()); - it('should delay execution', function() { + it('should delay execution', function () { const bouncer = debounce(spy, 100); const bouncerFromProvider = debounceFromProvider(spy, 100); @@ -92,7 +92,7 @@ describe('debounce service', function() { sinon.assert.calledOnce(spy); }); - it('should fire on leading edge', function() { + it('should fire on leading edge', function () { const bouncer = debounce(spy, 100, { leading: true }); const bouncerFromProvider = debounceFromProvider(spy, 100, { leading: true }); @@ -109,7 +109,7 @@ describe('debounce service', function() { sinon.assert.calledTwice(spy); }); - it('should only fire on leading edge', function() { + it('should only fire on leading edge', function () { const bouncer = debounce(spy, 100, { leading: true, trailing: false }); const bouncerFromProvider = debounceFromProvider(spy, 100, { leading: true, @@ -129,7 +129,7 @@ describe('debounce service', function() { sinon.assert.calledOnce(spy); }); - it('should reset delayed execution', function() { + it('should reset delayed execution', function () { const cancelSpy = sinon.spy($timeout, 'cancel'); const bouncer = debounce(spy, 100); const bouncerFromProvider = debounceFromProvider(spy, 100); @@ -157,8 +157,8 @@ describe('debounce service', function() { }); }); - describe('cancel', function() { - it('should cancel the $timeout', function() { + describe('cancel', function () { + it('should cancel the $timeout', function () { const cancelSpy = sinon.spy($timeout, 'cancel'); const bouncer = debounce(spy, 100); const bouncerFromProvider = debounceFromProvider(spy, 100); diff --git a/src/plugins/discover/public/application/angular/directives/fixed_scroll.js b/src/plugins/discover/public/application/angular/directives/fixed_scroll.js index bc159c14a16a7..182b4aeca9a23 100644 --- a/src/plugins/discover/public/application/angular/directives/fixed_scroll.js +++ b/src/plugins/discover/public/application/angular/directives/fixed_scroll.js @@ -33,7 +33,7 @@ export function FixedScrollProvider(Private) { return { restrict: 'A', - link: function($scope, $el) { + link: function ($scope, $el) { let $window = $(window); let $scroller = $('
').height(SCROLLER_HEIGHT); @@ -69,12 +69,12 @@ export function FixedScrollProvider(Private) { } $from.on('scroll', handler); - return function() { + return function () { $from.off('scroll', handler); }; } - unlisten = _.flow(bind($el, $scroller), bind($scroller, $el), function() { + unlisten = _.flow(bind($el, $scroller), bind($scroller, $el), function () { unlisten = _.noop; }); } @@ -141,7 +141,7 @@ export function FixedScrollProvider(Private) { $scope.$watch(debouncedCheckWidth); // cleanup when the scope is destroyed - $scope.$on('$destroy', function() { + $scope.$on('$destroy', function () { cleanUp(); debouncedCheckWidth.cancel(); $scroller = $window = null; diff --git a/src/plugins/discover/public/application/angular/directives/histogram.tsx b/src/plugins/discover/public/application/angular/directives/histogram.tsx index d856be58958f1..8b646106fe52f 100644 --- a/src/plugins/discover/public/application/angular/directives/histogram.tsx +++ b/src/plugins/discover/public/application/angular/directives/histogram.tsx @@ -66,10 +66,7 @@ function findIntervalFromDuration( ) { const date = moment.tz(dateValue, timeZone); const startOfDate = moment.tz(date, timeZone).startOf(esUnit); - const endOfDate = moment - .tz(date, timeZone) - .startOf(esUnit) - .add(esValue, esUnit); + const endOfDate = moment.tz(date, timeZone).startOf(esUnit).add(esValue, esUnit); return endOfDate.valueOf() - startOfDate.valueOf(); } @@ -242,10 +239,7 @@ export class DiscoverHistogram extends Component reactDirective(DiscoverNoResults)); +app.directive('discoverNoResults', (reactDirective) => reactDirective(DiscoverNoResults)); -app.directive('discoverUninitialized', reactDirective => reactDirective(DiscoverUninitialized)); +app.directive('discoverUninitialized', (reactDirective) => reactDirective(DiscoverUninitialized)); -app.directive('discoverHistogram', reactDirective => reactDirective(DiscoverHistogram)); +app.directive('discoverHistogram', (reactDirective) => reactDirective(DiscoverHistogram)); diff --git a/src/plugins/discover/public/application/angular/discover.html b/src/plugins/discover/public/application/angular/discover.html index d70d5dad9130b..022c39afff27f 100644 --- a/src/plugins/discover/public/application/angular/discover.html +++ b/src/plugins/discover/public/application/angular/discover.html @@ -59,18 +59,7 @@

{{screenTitle}}

fetch-error="fetchError" > -
-

-
-
-
+
diff --git a/src/plugins/discover/public/application/angular/discover.js b/src/plugins/discover/public/application/angular/discover.js index 84b4b2254e703..daea8b5938042 100644 --- a/src/plugins/discover/public/application/angular/discover.js +++ b/src/plugins/discover/public/application/angular/discover.js @@ -91,13 +91,13 @@ const fetchStatuses = { const app = getAngularModule(); -app.config($routeProvider => { +app.config(($routeProvider) => { const defaults = { requireDefaultIndex: true, requireUICapability: 'discover.show', k7Breadcrumbs: ($route, $injector) => $injector.invoke($route.current.params.id ? getSavedSearchBreadcrumbs : getRootBreadcrumbs), - badge: uiCapabilities => { + badge: (uiCapabilities) => { if (uiCapabilities.discover.save) { return undefined; } @@ -118,14 +118,14 @@ app.config($routeProvider => { template: indexTemplate, reloadOnSearch: false, resolve: { - savedObjects: function($route, Promise) { + savedObjects: function ($route, Promise) { const history = getHistory(); const savedSearchId = $route.current.params.id; return data.indexPatterns.ensureDefaultIndexPattern(history).then(() => { const { appStateContainer } = getState({ history }); const { index } = appStateContainer.getState(); return Promise.props({ - ip: indexPatterns.getCache().then(indexPatternList => { + ip: indexPatterns.getCache().then((indexPatternList) => { /** * In making the indexPattern modifiable it was placed in appState. Unfortunately, * the load order of AppState conflicts with the load order of many other things @@ -145,7 +145,7 @@ app.config($routeProvider => { }), savedSearch: getServices() .getSavedSearchById(savedSearchId) - .then(savedSearch => { + .then((savedSearch) => { if (savedSearchId) { chrome.recentlyAccessed.add( savedSearch.getFullPath(), @@ -179,7 +179,7 @@ app.config($routeProvider => { }); }); -app.directive('discoverApp', function() { +app.directive('discoverApp', function () { return { restrict: 'E', controllerAs: 'discoverApp', @@ -249,7 +249,7 @@ function discoverController( { filters: esFilters.FilterStateStore.APP_STATE } ); - const appStateUnsubscribe = appStateContainer.subscribe(async newState => { + const appStateUnsubscribe = appStateContainer.subscribe(async (newState) => { const { state: newStatePartial } = splitState(newState); const { state: oldStatePartial } = splitState(getPreviousAppState()); @@ -259,7 +259,7 @@ function discoverController( // detect changes that should trigger fetching of new data const changes = ['interval', 'sort', 'query'].filter( - prop => !_.isEqual(newStatePartial[prop], oldStatePartial[prop]) + (prop) => !_.isEqual(newStatePartial[prop], oldStatePartial[prop]) ); if (changes.length) { @@ -278,7 +278,7 @@ function discoverController( } }); - $scope.setIndexPattern = async id => { + $scope.setIndexPattern = async (id) => { await replaceUrlAppState({ index: id }); $route.reload(); }; @@ -294,7 +294,7 @@ function discoverController( $scope.updateDataSource(); }, }, - error => addFatalError(core.fatalErrors, error) + (error) => addFatalError(core.fatalErrors, error) ) ); @@ -302,7 +302,7 @@ function discoverController( requests: new RequestAdapter(), }; - $scope.timefilterUpdateHandler = ranges => { + $scope.timefilterUpdateHandler = (ranges) => { timefilter.setTime({ from: moment(ranges.from).toISOString(), to: moment(ranges.to).toISOString(), @@ -316,7 +316,7 @@ function discoverController( $scope.$watch( () => uiCapabilities.discover.saveQuery, - newCapability => { + (newCapability) => { $scope.showSaveQuery = newCapability; } ); @@ -342,7 +342,7 @@ function discoverController( description: i18n.translate('discover.localMenu.newSearchDescription', { defaultMessage: 'New Search', }), - run: function() { + run: function () { $scope.$evalAsync(() => { history.push('/'); }); @@ -374,7 +374,7 @@ function discoverController( isTitleDuplicateConfirmed, onTitleDuplicate, }; - return saveDataSource(saveOptions).then(response => { + return saveDataSource(saveOptions).then((response) => { // If the save wasn't successful, put the original values back. if (!response.id || response.error) { savedSearch.title = currentTitle; @@ -414,7 +414,7 @@ function discoverController( testId: 'discoverOpenButton', run: () => { showOpenSearchPanel({ - makeUrl: searchId => `#/${encodeURIComponent(searchId)}`, + makeUrl: (searchId) => `#/${encodeURIComponent(searchId)}`, I18nContext: core.i18n.Context, }); }, @@ -429,7 +429,7 @@ function discoverController( defaultMessage: 'Share Search', }), testId: 'shareTopNavButton', - run: async anchorElement => { + run: async (anchorElement) => { const sharingData = await this.getSharingData(); share.toggleShareContextMenu({ anchorElement, @@ -524,8 +524,8 @@ function discoverController( return $scope.fieldCounts; } - return await new Promise(resolve => { - const unwatch = $scope.$watch('fetchStatus', newValue => { + return await new Promise((resolve) => { + const unwatch = $scope.$watch('fetchStatus', (newValue) => { if (newValue === fetchStatuses.COMPLETE) { unwatch(); resolve($scope.fieldCounts); @@ -582,8 +582,8 @@ function discoverController( fields: selectFields, metaFields: $scope.indexPattern.metaFields, conflictedTypesFields: $scope.indexPattern.fields - .filter(f => f.type === 'conflict') - .map(f => f.name), + .filter((f) => f.type === 'conflict') + .map((f) => f.name), indexPatternId: searchSource.getField('index').id, }; }; @@ -644,7 +644,7 @@ function discoverController( { next: $scope.fetch, }, - error => addFatalError(core.fatalErrors, error) + (error) => addFatalError(core.fatalErrors, error) ) ); subscriptions.add( @@ -656,11 +656,11 @@ function discoverController( $scope.updateTime(); }, }, - error => addFatalError(core.fatalErrors, error) + (error) => addFatalError(core.fatalErrors, error) ) ); - $scope.changeInterval = interval => { + $scope.changeInterval = (interval) => { if (interval) { setAppState({ interval }); } @@ -694,7 +694,7 @@ function discoverController( else return status.NO_RESULTS; } - return function() { + return function () { const current = { rows: $scope.rows, fetchStatus: $scope.fetchStatus, @@ -768,7 +768,7 @@ function discoverController( } } - $scope.opts.fetch = $scope.fetch = function() { + $scope.opts.fetch = $scope.fetch = function () { // ignore requests to fetch before the app inits if (!init.complete) return; $scope.fetchCounter++; @@ -781,7 +781,7 @@ function discoverController( $scope .updateDataSource() .then(setupVisualization) - .then(function() { + .then(function () { $scope.fetchStatus = fetchStatuses.LOADING; logInspectorRequest(); return $scope.searchSource.fetch({ @@ -789,7 +789,7 @@ function discoverController( }); }) .then(onResults) - .catch(error => { + .catch((error) => { // If the request was aborted then no need to surface this error in the UI if (error instanceof Error && error.name === 'AbortError') return; @@ -808,14 +808,14 @@ function discoverController( }); }; - $scope.updateQuery = function({ query }, isUpdate = true) { + $scope.updateQuery = function ({ query }, isUpdate = true) { if (!_.isEqual(query, appStateContainer.getState().query) || isUpdate === false) { setAppState({ query }); $fetchObservable.next(); } }; - $scope.updateSavedQueryId = newSavedQueryId => { + $scope.updateSavedQueryId = (newSavedQueryId) => { if (newSavedQueryId) { setAppState({ savedQuery: newSavedQueryId }); } else { @@ -878,9 +878,9 @@ function discoverController( // if we haven't counted yet, reset the counts const counts = ($scope.fieldCounts = $scope.fieldCounts || {}); - $scope.rows.forEach(hit => { + $scope.rows.forEach((hit) => { const fields = Object.keys($scope.indexPattern.flattenHit(hit)); - fields.forEach(fieldName => { + fields.forEach((fieldName) => { counts[fieldName] = (counts[fieldName] || 0) + 1; }); }); @@ -898,12 +898,12 @@ function discoverController( }); inspectorRequest = inspectorAdapters.requests.start(title, { description }); inspectorRequest.stats(getRequestInspectorStats($scope.searchSource)); - $scope.searchSource.getSearchRequestBody().then(body => { + $scope.searchSource.getSearchRequestBody().then((body) => { inspectorRequest.json(body); }); } - $scope.updateTime = function() { + $scope.updateTime = function () { //this is the timerange for the histogram, should be refactored $scope.timeRange = { from: dateMath.parse(timefilter.getTime().from), @@ -911,16 +911,16 @@ function discoverController( }; }; - $scope.toMoment = function(datetime) { + $scope.toMoment = function (datetime) { return moment(datetime).format(config.get('dateFormat')); }; - $scope.resetQuery = function() { + $scope.resetQuery = function () { history.push(`/${encodeURIComponent($route.current.params.id)}`); $route.reload(); }; - $scope.newQuery = function() { + $scope.newQuery = function () { history.push('/'); }; @@ -947,7 +947,7 @@ function discoverController( }; // TODO: On array fields, negating does not negate the combination, rather all terms - $scope.filterQuery = function(field, values, operation) { + $scope.filterQuery = function (field, values, operation) { $scope.indexPattern.popularizeField(field, 1); const newFilters = esFilters.generateFilters( filterManager, @@ -976,18 +976,18 @@ function discoverController( setAppState({ columns }); }; - $scope.scrollToTop = function() { + $scope.scrollToTop = function () { $window.scrollTo(0, 0); }; - $scope.scrollToBottom = function() { + $scope.scrollToBottom = function () { // delay scrolling to after the rows have been rendered $timeout(() => { $element.find('#discoverBottomMarker').focus(); }, 0); }; - $scope.showAllRows = function() { + $scope.showAllRows = function () { $scope.minimumVisibleRows = $scope.hits; }; @@ -1029,7 +1029,7 @@ function discoverController( return $scope.vis.data.aggs.onSearchRequestStart(searchSource, options); }); - $scope.searchSource.setField('aggs', function() { + $scope.searchSource.setField('aggs', function () { if (!$scope.vis) return; return $scope.vis.data.aggs.toDsl(); }); diff --git a/src/plugins/discover/public/application/angular/doc.ts b/src/plugins/discover/public/application/angular/doc.ts index 45075f3742f3e..347caa0f3431c 100644 --- a/src/plugins/discover/public/application/angular/doc.ts +++ b/src/plugins/discover/public/application/angular/doc.ts @@ -28,7 +28,7 @@ interface LazyScope extends ng.IScope { const { timefilter } = getServices(); const app = getAngularModule(); -app.directive('discoverDoc', function(reactDirective: any) { +app.directive('discoverDoc', function (reactDirective: any) { return reactDirective( Doc, [ @@ -51,7 +51,7 @@ app.config(($routeProvider: any) => { .when('/doc/:indexPattern/:index', { // have to be written as function expression, because it's not compiled in dev mode // eslint-disable-next-line object-shorthand - controller: function($scope: LazyScope, $route: any, es: any) { + controller: function ($scope: LazyScope, $route: any, es: any) { timefilter.disableAutoRefreshSelector(); timefilter.disableTimeRangeSelector(); $scope.esClient = es; diff --git a/src/plugins/discover/public/application/angular/doc_table/actions/columns.ts b/src/plugins/discover/public/application/angular/doc_table/actions/columns.ts index cec1a097da5bf..8257c79af7e8a 100644 --- a/src/plugins/discover/public/application/angular/doc_table/actions/columns.ts +++ b/src/plugins/discover/public/application/angular/doc_table/actions/columns.ts @@ -24,7 +24,7 @@ */ function buildColumns(columns: string[]) { if (columns.length > 1 && columns.indexOf('_source') !== -1) { - return columns.filter(col => col !== '_source'); + return columns.filter((col) => col !== '_source'); } else if (columns.length !== 0) { return columns; } @@ -42,7 +42,7 @@ export function removeColumn(columns: string[], columnName: string) { if (!columns.includes(columnName)) { return columns; } - return buildColumns(columns.filter(col => col !== columnName)); + return buildColumns(columns.filter((col) => col !== columnName)); } export function moveColumn(columns: string[], columnName: string, newIndex: number) { diff --git a/src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header.tsx b/src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header.tsx index 2ca53d5a34b03..dd5f2a10b8a77 100644 --- a/src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header.tsx +++ b/src/plugins/discover/public/application/angular/doc_table/components/table_header/table_header.tsx @@ -51,7 +51,7 @@ export function TableHeader({ return ( - {displayedColumns.map(col => { + {displayedColumns.map((col) => { return ( name === sortPair[0]) || []; - const currentSortWithoutColumn = sortOrder.filter(pair => pair[0] !== name); - const currentColumnSort = sortOrder.find(pair => pair[0] === name); + const [, sortDirection = ''] = sortOrder.find((sortPair) => name === sortPair[0]) || []; + const currentSortWithoutColumn = sortOrder.filter((pair) => pair[0] !== name); + const currentColumnSort = sortOrder.find((pair) => pair[0] === name); const currentColumnSortDirection = (currentColumnSort && currentColumnSort[1]) || ''; const btnSortIcon = sortDirectionToIcon[sortDirection]; @@ -172,7 +172,7 @@ export function TableHeaderColumn({ {displayName} {buttons - .filter(button => button.active) + .filter((button) => button.active) .map((button, idx) => ( { indexPattern = FixturesStubbedLogstashIndexPatternProvider() as IndexPattern; }); - describe('getSort function', function() { - test('should be a function', function() { + describe('getSort function', function () { + test('should be a function', function () { expect(typeof getSort === 'function').toBeTruthy(); }); - test('should return an array of objects', function() { + test('should return an array of objects', function () { expect(getSort([['bytes', 'desc']], indexPattern)).toEqual([{ bytes: 'desc' }]); delete indexPattern.timeFieldName; @@ -45,7 +45,7 @@ describe('docTable', function() { expect(getSort([{ bytes: 'desc' }], indexPattern)).toEqual([{ bytes: 'desc' }]); }); - test('should return an empty array when passed an unsortable field', function() { + test('should return an empty array when passed an unsortable field', function () { expect(getSort([['non-sortable', 'asc']], indexPattern)).toEqual([]); expect(getSort([['lol_nope', 'asc']], indexPattern)).toEqual([]); @@ -53,27 +53,27 @@ describe('docTable', function() { expect(getSort([['non-sortable', 'asc']], indexPattern)).toEqual([]); }); - test('should return an empty array ', function() { + test('should return an empty array ', function () { expect(getSort([], indexPattern)).toEqual([]); expect(getSort([['foo', 'bar']], indexPattern)).toEqual([]); expect(getSort([{ foo: 'bar' }], indexPattern)).toEqual([]); }); }); - describe('getSortArray function', function() { - test('should have an array method', function() { + describe('getSortArray function', function () { + test('should have an array method', function () { expect(getSortArray).toBeInstanceOf(Function); }); - test('should return an array of arrays for sortable fields', function() { + test('should return an array of arrays for sortable fields', function () { expect(getSortArray([['bytes', 'desc']], indexPattern)).toEqual([['bytes', 'desc']]); }); - test('should return an array of arrays from an array of elasticsearch sort objects', function() { + test('should return an array of arrays from an array of elasticsearch sort objects', function () { expect(getSortArray([{ bytes: 'desc' }], indexPattern)).toEqual([['bytes', 'desc']]); }); - test('should sort by an empty array when an unsortable field is given', function() { + test('should sort by an empty array when an unsortable field is given', function () { expect(getSortArray([{ 'non-sortable': 'asc' }], indexPattern)).toEqual([]); expect(getSortArray([{ lol_nope: 'asc' }], indexPattern)).toEqual([]); diff --git a/src/plugins/discover/public/application/angular/doc_table/lib/get_sort.ts b/src/plugins/discover/public/application/angular/doc_table/lib/get_sort.ts index aa23aa4390673..c28519692318e 100644 --- a/src/plugins/discover/public/application/angular/doc_table/lib/get_sort.ts +++ b/src/plugins/discover/public/application/angular/doc_table/lib/get_sort.ts @@ -57,7 +57,7 @@ export function getSort(sort: SortPair[], indexPattern: IndexPattern): SortPairO if (Array.isArray(sort)) { return sort .map((sortPair: SortPair) => createSortObject(sortPair, indexPattern)) - .filter(sortPairObj => typeof sortPairObj === 'object') as SortPairObj[]; + .filter((sortPairObj) => typeof sortPairObj === 'object') as SortPairObj[]; } return []; } @@ -67,5 +67,5 @@ export function getSort(sort: SortPair[], indexPattern: IndexPattern): SortPairO * [[fieldToSort: directionToSort]] */ export function getSortArray(sort: SortPair[], indexPattern: IndexPattern) { - return getSort(sort, indexPattern).map(sortPair => Object.entries(sortPair).pop()); + return getSort(sort, indexPattern).map((sortPair) => Object.entries(sortPair).pop()); } diff --git a/src/plugins/discover/public/application/angular/helpers/point_series.ts b/src/plugins/discover/public/application/angular/helpers/point_series.ts index db0ca85b0399a..4c280bf43ea12 100644 --- a/src/plugins/discover/public/application/angular/helpers/point_series.ts +++ b/src/plugins/discover/public/application/angular/helpers/point_series.ts @@ -84,7 +84,7 @@ export const buildPointSeriesData = (table: Table, dimensions: Dimensions) => { const yAccessor = table.columns[y.accessor].id; const chart = {} as Chart; - chart.xAxisOrderedValues = uniq(table.rows.map(r => r[xAccessor] as number)); + chart.xAxisOrderedValues = uniq(table.rows.map((r) => r[xAccessor] as number)); chart.xAxisFormat = x.format; chart.xAxisLabel = table.columns[x.accessor].name; @@ -101,8 +101,8 @@ export const buildPointSeriesData = (table: Table, dimensions: Dimensions) => { chart.yAxisLabel = table.columns[y.accessor].name; chart.values = table.rows - .filter(row => row && row[yAccessor] !== 'NaN') - .map(row => ({ + .filter((row) => row && row[yAccessor] !== 'NaN') + .map((row) => ({ x: row[xAccessor] as number, y: row[yAccessor] as number, })); diff --git a/src/plugins/discover/public/application/angular/response_handler.js b/src/plugins/discover/public/application/angular/response_handler.js index 04ccb67ec7e25..00a9ee934430d 100644 --- a/src/plugins/discover/public/application/angular/response_handler.js +++ b/src/plugins/discover/public/application/angular/response_handler.js @@ -87,7 +87,7 @@ function convertTableGroup(tableGroup, convertTable) { const out = {}; let outList; - tables.forEach(function(table) { + tables.forEach(function (table) { if (!outList) { const direction = tableGroup.direction === 'row' ? 'rows' : 'columns'; outList = out[direction] = []; @@ -105,7 +105,7 @@ function convertTableGroup(tableGroup, convertTable) { export const discoverResponseHandler = (response, dimensions) => { const tableGroup = tableResponseHandler(response, dimensions); - let converted = convertTableGroup(tableGroup, table => { + let converted = convertTableGroup(tableGroup, (table) => { return buildPointSeriesData(table, dimensions); }); if (!converted) { diff --git a/src/plugins/discover/public/application/components/doc/doc.test.tsx b/src/plugins/discover/public/application/components/doc/doc.test.tsx index 2cbc1547d1082..0bc621714c70f 100644 --- a/src/plugins/discover/public/application/components/doc/doc.test.tsx +++ b/src/plugins/discover/public/application/components/doc/doc.test.tsx @@ -53,7 +53,7 @@ beforeEach(() => { const waitForPromises = async () => act(async () => { - await new Promise(resolve => setTimeout(resolve)); + await new Promise((resolve) => setTimeout(resolve)); }); /** diff --git a/src/plugins/discover/public/application/components/hits_counter/hits_counter.test.tsx b/src/plugins/discover/public/application/components/hits_counter/hits_counter.test.tsx index ae5fbd05b0aaf..84ad19dbddcbf 100644 --- a/src/plugins/discover/public/application/components/hits_counter/hits_counter.test.tsx +++ b/src/plugins/discover/public/application/components/hits_counter/hits_counter.test.tsx @@ -23,7 +23,7 @@ import { HitsCounter, HitsCounterProps } from './hits_counter'; // @ts-ignore import { findTestSubject } from '@elastic/eui/lib/test'; -describe('hits counter', function() { +describe('hits counter', function () { let props: HitsCounterProps; let component: ReactWrapper; @@ -47,13 +47,13 @@ describe('hits counter', function() { expect(findTestSubject(component, 'resetSavedSearch').length).toBe(0); }); - it('expect to render the number of hits', function() { + it('expect to render the number of hits', function () { component = mountWithIntl(); const hits = findTestSubject(component, 'discoverQueryHits'); expect(hits.text()).toBe('2'); }); - it('expect to render 1,899 hits if 1899 hits given', function() { + it('expect to render 1,899 hits if 1899 hits given', function () { component = mountWithIntl( ); @@ -61,7 +61,7 @@ describe('hits counter', function() { expect(hits.text()).toBe('1,899'); }); - it('should reset query', function() { + it('should reset query', function () { component = mountWithIntl(); findTestSubject(component, 'resetSavedSearch').simulate('click'); expect(props.onResetQuery).toHaveBeenCalled(); diff --git a/packages/kbn-optimizer/src/common/parent_messages.ts b/src/plugins/discover/public/application/components/loading_spinner/loading_spinner.test.tsx similarity index 56% rename from packages/kbn-optimizer/src/common/parent_messages.ts rename to src/plugins/discover/public/application/components/loading_spinner/loading_spinner.test.tsx index c27bcb96f4a89..3321ac764a05b 100644 --- a/packages/kbn-optimizer/src/common/parent_messages.ts +++ b/src/plugins/discover/public/application/components/loading_spinner/loading_spinner.test.tsx @@ -16,18 +16,19 @@ * specific language governing permissions and limitations * under the License. */ +import React from 'react'; +import { mountWithIntl } from 'test_utils/enzyme_helpers'; +import { ReactWrapper } from 'enzyme'; +import { LoadingSpinner } from './loading_spinner'; +// @ts-ignore +import { findTestSubject } from '@elastic/eui/lib/test'; -export interface ParentPongMsg { - type: 'pong'; -} +describe('loading spinner', function () { + let component: ReactWrapper; -export const isParentPong = (value: any): value is ParentPongMsg => - typeof value === 'object' && value && value.type === 'pong'; - -export class ParentMsgs { - pong(): ParentPongMsg { - return { - type: 'pong', - }; - } -} + it('LoadingSpinner renders a Searching text and a spinner', () => { + component = mountWithIntl(); + expect(findTestSubject(component, 'loadingSpinnerText').text()).toBe('Searching'); + expect(findTestSubject(component, 'loadingSpinner').length).toBe(1); + }); +}); diff --git a/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/lib/index.ts b/src/plugins/discover/public/application/components/loading_spinner/loading_spinner.tsx similarity index 53% rename from src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/lib/index.ts rename to src/plugins/discover/public/application/components/loading_spinner/loading_spinner.tsx index af810deaca5b0..44b922bf0f708 100644 --- a/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/lib/index.ts +++ b/src/plugins/discover/public/application/components/loading_spinner/loading_spinner.tsx @@ -16,5 +16,26 @@ * specific language governing permissions and limitations * under the License. */ +import React from 'react'; +import { EuiLoadingSpinner, EuiTitle, EuiSpacer } from '@elastic/eui'; +import { FormattedMessage, I18nProvider } from '@kbn/i18n/react'; -export { nextTick, getRandomString, getRandomNumber } from './utils'; +export function LoadingSpinner() { + return ( + + <> + +

+ +

+
+ + + +
+ ); +} + +export function createLoadingSpinnerDirective(reactDirective: any) { + return reactDirective(LoadingSpinner); +} diff --git a/src/plugins/discover/public/application/components/sidebar/change_indexpattern.tsx b/src/plugins/discover/public/application/components/sidebar/change_indexpattern.tsx index 9d304bfa9c27d..4a539b618f817 100644 --- a/src/plugins/discover/public/application/components/sidebar/change_indexpattern.tsx +++ b/src/plugins/discover/public/application/components/sidebar/change_indexpattern.tsx @@ -51,7 +51,7 @@ export function ChangeIndexPattern({ }) { const [isPopoverOpen, setPopoverIsOpen] = useState(false); - const createTrigger = function() { + const createTrigger = function () { const { label, title, ...rest } = trigger; return ( { + onChange={(choices) => { const choice = (choices.find(({ checked }) => checked) as unknown) as { value: string; }; diff --git a/src/plugins/discover/public/application/components/sidebar/discover_field.test.tsx b/src/plugins/discover/public/application/components/sidebar/discover_field.test.tsx index 7372fab075ea3..8c527475b7480 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_field.test.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_field.test.tsx @@ -92,18 +92,18 @@ function getComponent(selected = false, showDetails = false, useShortDots = fals return { comp, props }; } -describe('discover sidebar field', function() { - it('should allow selecting fields', function() { +describe('discover sidebar field', function () { + it('should allow selecting fields', function () { const { comp, props } = getComponent(); findTestSubject(comp, 'fieldToggle-bytes').simulate('click'); expect(props.onAddField).toHaveBeenCalledWith('bytes'); }); - it('should allow deselecting fields', function() { + it('should allow deselecting fields', function () { const { comp, props } = getComponent(true); findTestSubject(comp, 'fieldToggle-bytes').simulate('click'); expect(props.onRemoveField).toHaveBeenCalledWith('bytes'); }); - it('should trigger onShowDetails', function() { + it('should trigger onShowDetails', function () { const { comp, props } = getComponent(); findTestSubject(comp, 'field-bytes-showDetails').simulate('click'); expect(props.onShowDetails).toHaveBeenCalledWith(true, props.field); diff --git a/src/plugins/discover/public/application/components/sidebar/discover_field_search.tsx b/src/plugins/discover/public/application/components/sidebar/discover_field_search.tsx index a533b798ad09f..99dad418c04bd 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_field_search.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_field_search.tsx @@ -80,7 +80,7 @@ export function DiscoverFieldSearch({ onChange, value, types }: Props) { defaultMessage: 'Type', }); const typeOptions = types - ? types.map(type => { + ? types.map((type) => { return { value: type, text: type }; }) : [{ value: 'any', text: 'any' }]; @@ -224,7 +224,7 @@ export function DiscoverFieldSearch({ onChange, value, types }: Props) { legend={legend} options={toggleButtons(id)} idSelected={`${id}-${values[id]}`} - onChange={optionId => handleValueChange(id, optionId.replace(`${id}-`, ''))} + onChange={(optionId) => handleValueChange(id, optionId.replace(`${id}-`, ''))} buttonSize="compressed" isFullWidth data-test-subj={`${id}ButtonGroup`} @@ -257,7 +257,7 @@ export function DiscoverFieldSearch({ onChange, value, types }: Props) { data-test-subj="fieldFilterSearchInput" compressed fullWidth - onChange={event => onChange('name', event.currentTarget.value)} + onChange={(event) => onChange('name', event.currentTarget.value)} placeholder={searchPlaceholder} value={value} /> diff --git a/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.test.tsx b/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.test.tsx index 79417c07501a3..24e6f5993a0a5 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.test.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.test.tsx @@ -53,18 +53,11 @@ const defaultProps = { }; function getIndexPatternPickerList(instance: ShallowWrapper) { - return instance - .find(ChangeIndexPattern) - .first() - .dive() - .find(EuiSelectable); + return instance.find(ChangeIndexPattern).first().dive().find(EuiSelectable); } function getIndexPatternPickerOptions(instance: ShallowWrapper) { - return getIndexPatternPickerList(instance) - .dive() - .find(EuiSelectableList) - .prop('options'); + return getIndexPatternPickerList(instance).dive().find(EuiSelectableList).prop('options'); } function selectIndexPatternPickerOption(instance: ShallowWrapper, selectedLabel: string) { diff --git a/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.tsx b/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.tsx index 3b01d5e7a9e62..3acdcb1e92091 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_index_pattern.tsx @@ -46,7 +46,7 @@ export function DiscoverIndexPattern({ selectedIndexPattern, setIndexPattern, }: DiscoverIndexPatternProps) { - const options: IndexPatternRef[] = (indexPatternList || []).map(entity => ({ + const options: IndexPatternRef[] = (indexPatternList || []).map((entity) => ({ id: entity.id, title: entity.attributes!.title, })); @@ -76,8 +76,8 @@ export function DiscoverIndexPattern({ }} indexPatternId={selected.id} indexPatternRefs={options} - onChangeIndexPattern={id => { - const indexPattern = options.find(pattern => pattern.id === id); + onChangeIndexPattern={(id) => { + const indexPattern = options.find((pattern) => pattern.id === id); if (indexPattern) { setIndexPattern(id); setSelected(indexPattern); diff --git a/src/plugins/discover/public/application/components/sidebar/discover_sidebar.test.tsx b/src/plugins/discover/public/application/components/sidebar/discover_sidebar.test.tsx index c7512824d7d44..60011914e8f74 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_sidebar.test.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_sidebar.test.tsx @@ -59,7 +59,7 @@ jest.mock('../../../kibana_services', () => ({ })); jest.mock('./lib/get_index_pattern_field_list', () => ({ - getIndexPatternFieldList: jest.fn(indexPattern => indexPattern.fields), + getIndexPatternFieldList: jest.fn((indexPattern) => indexPattern.fields), })); function getCompProps() { @@ -102,7 +102,7 @@ function getCompProps() { }; } -describe('discover sidebar', function() { +describe('discover sidebar', function () { let props: DiscoverSidebarProps; let comp: ReactWrapper; @@ -111,7 +111,7 @@ describe('discover sidebar', function() { comp = mountWithIntl(); }); - it('should have Selected Fields and Available Fields with Popular Fields sections', function() { + it('should have Selected Fields and Available Fields with Popular Fields sections', function () { const popular = findTestSubject(comp, 'fieldList-popular'); const selected = findTestSubject(comp, 'fieldList-selected'); const unpopular = findTestSubject(comp, 'fieldList-unpopular'); @@ -119,15 +119,15 @@ describe('discover sidebar', function() { expect(unpopular.children().length).toBe(7); expect(selected.children().length).toBe(1); }); - it('should allow selecting fields', function() { + it('should allow selecting fields', function () { findTestSubject(comp, 'fieldToggle-bytes').simulate('click'); expect(props.onAddField).toHaveBeenCalledWith('bytes'); }); - it('should allow deselecting fields', function() { + it('should allow deselecting fields', function () { findTestSubject(comp, 'fieldToggle-extension').simulate('click'); expect(props.onRemoveField).toHaveBeenCalledWith('extension'); }); - it('should allow adding filters', function() { + it('should allow adding filters', function () { findTestSubject(comp, 'field-extension-showDetails').simulate('click'); findTestSubject(comp, 'plus-extension-gif').simulate('click'); expect(props.onAddFilter).toHaveBeenCalled(); diff --git a/src/plugins/discover/public/application/components/sidebar/discover_sidebar.tsx b/src/plugins/discover/public/application/components/sidebar/discover_sidebar.tsx index 0d9aebe11ece6..99a5547ed0760 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_sidebar.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_sidebar.tsx @@ -174,7 +174,7 @@ export function DiscoverSidebar({ o.attributes.title)} + indexPatternList={sortBy(indexPatternList, (o) => o.attributes.title)} />
diff --git a/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.js b/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.js index c2d225360d0ef..e055d644e1f91 100644 --- a/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.js +++ b/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.js @@ -23,7 +23,7 @@ import { i18n } from '@kbn/i18n'; function getFieldValues(hits, field) { const name = field.name; const flattenHit = field.indexPattern.flattenHit; - return _.map(hits, function(hit) { + return _.map(hits, function (hit) { return flattenHit(hit)[name]; }); } @@ -55,18 +55,13 @@ function getFieldValueCounts(params) { try { const groups = _groupValues(allValues, params); - counts = _.map( - _.sortBy(groups, 'count') - .reverse() - .slice(0, params.count), - function(bucket) { - return { - value: bucket.value, - count: bucket.count, - percent: ((bucket.count / (params.hits.length - missing)) * 100).toFixed(1), - }; - } - ); + counts = _.map(_.sortBy(groups, 'count').reverse().slice(0, params.count), function (bucket) { + return { + value: bucket.value, + count: bucket.count, + percent: ((bucket.count / (params.hits.length - missing)) * 100).toFixed(1), + }; + }); if (params.hits.length - missing === 0) { return { @@ -103,7 +98,7 @@ function _groupValues(allValues, params) { const groups = {}; let k; - allValues.forEach(function(value) { + allValues.forEach(function (value) { if (_.isObject(value) && !Array.isArray(value)) { throw new Error( i18n.translate( @@ -121,7 +116,7 @@ function _groupValues(allValues, params) { k = value == null ? undefined : [value]; } - _.each(k, function(key) { + _.each(k, function (key) { if (groups.hasOwnProperty(key)) { groups[key].count++; } else { diff --git a/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.test.ts b/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.test.ts index fdfc536485579..875cbf4075aa2 100644 --- a/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.test.ts +++ b/src/plugins/discover/public/application/components/sidebar/lib/field_calculator.test.ts @@ -31,8 +31,8 @@ import { fieldCalculator } from './field_calculator'; let indexPattern: IndexPattern; -describe('fieldCalculator', function() { - beforeEach(function() { +describe('fieldCalculator', function () { + beforeEach(function () { indexPattern = new StubIndexPattern( 'logstash-*', (cfg: any) => cfg, @@ -41,7 +41,7 @@ describe('fieldCalculator', function() { coreMock.createStart() ); }); - it('should have a _countMissing that counts nulls & undefineds in an array', function() { + it('should have a _countMissing that counts nulls & undefineds in an array', function () { const values = [ ['foo', 'bar'], 'foo', @@ -59,11 +59,11 @@ describe('fieldCalculator', function() { expect(fieldCalculator._countMissing(values)).toBe(5); }); - describe('_groupValues', function() { + describe('_groupValues', function () { let groups: Record; let params: any; let values: any; - beforeEach(function() { + beforeEach(function () { values = [ ['foo', 'bar'], 'foo', @@ -82,17 +82,17 @@ describe('fieldCalculator', function() { groups = fieldCalculator._groupValues(values, params); }); - it('should have a _groupValues that counts values', function() { + it('should have a _groupValues that counts values', function () { expect(groups).toBeInstanceOf(Object); }); - it('should throw an error if any value is a plain object', function() { - expect(function() { + it('should throw an error if any value is a plain object', function () { + expect(function () { fieldCalculator._groupValues([{}, true, false], params); }).toThrowError(); }); - it('should handle values with dots in them', function() { + it('should handle values with dots in them', function () { values = ['0', '0.........', '0.......,.....']; params = {}; groups = fieldCalculator._groupValues(values, params); @@ -101,36 +101,36 @@ describe('fieldCalculator', function() { expect(groups[values[2]].count).toBe(1); }); - it('should have a a key for value in the array when not grouping array terms', function() { + it('should have a a key for value in the array when not grouping array terms', function () { expect(_.keys(groups).length).toBe(3); expect(groups.foo).toBeInstanceOf(Object); expect(groups.bar).toBeInstanceOf(Object); expect(groups.baz).toBeInstanceOf(Object); }); - it('should count array terms independently', function() { + it('should count array terms independently', function () { expect(groups['foo,bar']).toBe(undefined); expect(groups.foo.count).toBe(5); expect(groups.bar.count).toBe(3); expect(groups.baz.count).toBe(1); }); - describe('grouped array terms', function() { - beforeEach(function() { + describe('grouped array terms', function () { + beforeEach(function () { params.grouped = true; groups = fieldCalculator._groupValues(values, params); }); - it('should group array terms when passed params.grouped', function() { + it('should group array terms when passed params.grouped', function () { expect(_.keys(groups).length).toBe(4); expect(groups['foo,bar']).toBeInstanceOf(Object); }); - it('should contain the original array as the value', function() { + it('should contain the original array as the value', function () { expect(groups['foo,bar'].value).toEqual(['foo', 'bar']); }); - it('should count the pairs separately from the values they contain', function() { + it('should count the pairs separately from the values they contain', function () { expect(groups['foo,bar'].count).toBe(2); expect(groups.foo.count).toBe(3); expect(groups.bar.count).toBe(1); @@ -138,32 +138,32 @@ describe('fieldCalculator', function() { }); }); - describe('getFieldValues', function() { + describe('getFieldValues', function () { let hits: any; - beforeEach(function() { + beforeEach(function () { hits = _.each(_.cloneDeep(realHits), indexPattern.flattenHit); }); - it('Should return an array of values for _source fields', function() { + it('Should return an array of values for _source fields', function () { const extensions = fieldCalculator.getFieldValues( hits, indexPattern.fields.getByName('extension') ); expect(extensions).toBeInstanceOf(Array); expect( - _.filter(extensions, function(v) { + _.filter(extensions, function (v) { return v === 'html'; }).length ).toBe(8); expect(_.uniq(_.clone(extensions)).sort()).toEqual(['gif', 'html', 'php', 'png']); }); - it('Should return an array of values for core meta fields', function() { + it('Should return an array of values for core meta fields', function () { const types = fieldCalculator.getFieldValues(hits, indexPattern.fields.getByName('_type')); expect(types).toBeInstanceOf(Array); expect( - _.filter(types, function(v) { + _.filter(types, function (v) { return v === 'apache'; }).length ).toBe(18); @@ -171,9 +171,9 @@ describe('fieldCalculator', function() { }); }); - describe('getFieldValueCounts', function() { + describe('getFieldValueCounts', function () { let params: { hits: any; field: any; count: number }; - beforeEach(function() { + beforeEach(function () { params = { hits: _.cloneDeep(realHits), field: indexPattern.fields.getByName('extension'), @@ -181,7 +181,7 @@ describe('fieldCalculator', function() { }; }); - it('counts the top 3 values', function() { + it('counts the top 3 values', function () { const extensions = fieldCalculator.getFieldValueCounts(params); expect(extensions).toBeInstanceOf(Object); expect(extensions.buckets).toBeInstanceOf(Array); @@ -190,7 +190,7 @@ describe('fieldCalculator', function() { expect(extensions.error).toBe(undefined); }); - it('fails to analyze geo and attachment types', function() { + it('fails to analyze geo and attachment types', function () { params.field = indexPattern.fields.getByName('point'); expect(fieldCalculator.getFieldValueCounts(params).error).not.toBe(undefined); @@ -201,16 +201,16 @@ describe('fieldCalculator', function() { expect(fieldCalculator.getFieldValueCounts(params).error).not.toBe(undefined); }); - it('fails to analyze fields that are in the mapping, but not the hits', function() { + it('fails to analyze fields that are in the mapping, but not the hits', function () { params.field = indexPattern.fields.getByName('ip'); expect(fieldCalculator.getFieldValueCounts(params).error).not.toBe(undefined); }); - it('counts the total hits', function() { + it('counts the total hits', function () { expect(fieldCalculator.getFieldValueCounts(params).total).toBe(params.hits.length); }); - it('counts the hits the field exists in', function() { + it('counts the hits the field exists in', function () { params.field = indexPattern.fields.getByName('phpmemory'); expect(fieldCalculator.getFieldValueCounts(params).exists).toBe(5); }); diff --git a/src/plugins/discover/public/application/components/sidebar/lib/field_filter.test.ts b/src/plugins/discover/public/application/components/sidebar/lib/field_filter.test.ts index 1351433e9dd0e..eb139f97c7b00 100644 --- a/src/plugins/discover/public/application/components/sidebar/lib/field_filter.test.ts +++ b/src/plugins/discover/public/application/components/sidebar/lib/field_filter.test.ts @@ -20,8 +20,8 @@ import { getDefaultFieldFilter, setFieldFilterProp, isFieldFiltered } from './field_filter'; import { IndexPatternField } from '../../../../../../data/public'; -describe('field_filter', function() { - it('getDefaultFieldFilter should return default filter state', function() { +describe('field_filter', function () { + it('getDefaultFieldFilter should return default filter state', function () { expect(getDefaultFieldFilter()).toMatchInlineSnapshot(` Object { "aggregatable": null, @@ -32,7 +32,7 @@ describe('field_filter', function() { } `); }); - it('setFieldFilterProp should return allow filter changes', function() { + it('setFieldFilterProp should return allow filter changes', function () { const state = getDefaultFieldFilter(); const targetState = { aggregatable: true, @@ -83,12 +83,12 @@ describe('field_filter', function() { { filter: { aggregatable: true }, result: ['extension'] }, { filter: { aggregatable: true, searchable: false }, result: [] }, { filter: { type: 'string' }, result: ['extension'] }, - ].forEach(test => { + ].forEach((test) => { const filtered = fieldList - .filter(field => + .filter((field) => isFieldFiltered(field, { ...defaultState, ...test.filter }, { bytes: 1, extension: 1 }) ) - .map(field => field.name); + .map((field) => field.name); expect(filtered).toEqual(test.result); }); diff --git a/src/plugins/discover/public/application/components/sidebar/lib/get_index_pattern_field_list.ts b/src/plugins/discover/public/application/components/sidebar/lib/get_index_pattern_field_list.ts index 63e1b761f4dd0..0fcbe925e0798 100644 --- a/src/plugins/discover/public/application/components/sidebar/lib/get_index_pattern_field_list.ts +++ b/src/plugins/discover/public/application/components/sidebar/lib/get_index_pattern_field_list.ts @@ -31,7 +31,7 @@ export function getIndexPatternFieldList( const fieldNamesInDocs = Object.keys(fieldCounts); const fieldNamesInIndexPattern = map(indexPattern.fields, 'name'); - difference(fieldNamesInDocs, fieldNamesInIndexPattern).forEach(unknownFieldName => { + difference(fieldNamesInDocs, fieldNamesInIndexPattern).forEach((unknownFieldName) => { fieldSpecs.push({ name: String(unknownFieldName), type: 'unknown', diff --git a/src/plugins/discover/public/application/components/sidebar/lib/get_warnings.ts b/src/plugins/discover/public/application/components/sidebar/lib/get_warnings.ts index 138e805405c89..c57ee197d856f 100644 --- a/src/plugins/discover/public/application/components/sidebar/lib/get_warnings.ts +++ b/src/plugins/discover/public/application/components/sidebar/lib/get_warnings.ts @@ -34,7 +34,7 @@ export function getWarnings(field: IndexPatternField) { } if (warnings.length > 1) { - warnings = warnings.map(function(warning, i) { + warnings = warnings.map(function (warning, i) { return (i > 0 ? '\n' : '') + (i + 1) + ' - ' + warning; }); } diff --git a/src/plugins/discover/public/application/components/sidebar/lib/group_fields.test.ts b/src/plugins/discover/public/application/components/sidebar/lib/group_fields.test.ts index e83287a139dd0..d4670a1e76011 100644 --- a/src/plugins/discover/public/application/components/sidebar/lib/group_fields.test.ts +++ b/src/plugins/discover/public/application/components/sidebar/lib/group_fields.test.ts @@ -20,8 +20,8 @@ import { groupFields } from './group_fields'; import { getDefaultFieldFilter } from './field_filter'; -describe('group_fields', function() { - it('should group fields in selected, popular, unpopular group', function() { +describe('group_fields', function () { + it('should group fields in selected, popular, unpopular group', function () { const fields = [ { name: 'category', diff --git a/src/plugins/discover/public/application/components/sidebar/lib/group_fields.tsx b/src/plugins/discover/public/application/components/sidebar/lib/group_fields.tsx index e4e5f00172371..fab4637d87ca7 100644 --- a/src/plugins/discover/public/application/components/sidebar/lib/group_fields.tsx +++ b/src/plugins/discover/public/application/components/sidebar/lib/group_fields.tsx @@ -45,9 +45,9 @@ export function groupFields( } const popular = fields - .filter(field => !columns.includes(field.name) && field.count) + .filter((field) => !columns.includes(field.name) && field.count) .sort((a: IndexPatternField, b: IndexPatternField) => (b.count || 0) - (a.count || 0)) - .map(field => field.name) + .map((field) => field.name) .slice(0, popularLimit); const compareFn = (a: IndexPatternField, b: IndexPatternField) => { diff --git a/src/plugins/discover/public/application/components/table/table.test.tsx b/src/plugins/discover/public/application/components/table/table.test.tsx index 04cf5d80da585..0793072fd0cf4 100644 --- a/src/plugins/discover/public/application/components/table/table.test.tsx +++ b/src/plugins/discover/public/application/components/table/table.test.tsx @@ -58,11 +58,11 @@ const indexPattern = { ], metaFields: ['_index', '_score'], flattenHit: undefined, - formatHit: jest.fn(hit => hit._source), + formatHit: jest.fn((hit) => hit._source), } as IndexPattern; indexPattern.fields.getByName = (name: string) => { - return indexPattern.fields.find(field => field.name === name); + return indexPattern.fields.find((field) => field.name === name); }; indexPattern.flattenHit = indexPatterns.flattenHitWrapper(indexPattern, indexPattern.metaFields); @@ -146,7 +146,7 @@ describe('DocViewTable at Discover', () => { toggleColumnButton: true, underScoreWarning: false, }, - ].forEach(check => { + ].forEach((check) => { const rowComponent = findTestSubject(component, `tableDocViewRow-${check._property}`); it(`renders row for ${check._property}`, () => { @@ -158,7 +158,7 @@ describe('DocViewTable at Discover', () => { 'collapseBtn', 'toggleColumnButton', 'underscoreWarning', - ] as const).forEach(element => { + ] as const).forEach((element) => { const elementExist = check[element]; if (typeof elementExist === 'boolean') { @@ -172,7 +172,7 @@ describe('DocViewTable at Discover', () => { } }); - (['noMappingWarning'] as const).forEach(element => { + (['noMappingWarning'] as const).forEach((element) => { const elementExist = check[element]; if (typeof elementExist === 'boolean') { diff --git a/src/plugins/discover/public/application/components/table/table.tsx b/src/plugins/discover/public/application/components/table/table.tsx index 6789f753899f5..9b95f2fc6bd27 100644 --- a/src/plugins/discover/public/application/components/table/table.tsx +++ b/src/plugins/discover/public/application/components/table/table.tsx @@ -47,7 +47,7 @@ export function DocViewTable({ {Object.keys(flattened) .sort() - .map(field => { + .map((field) => { const valueRaw = flattened[field]; const value = trimAngularSpan(String(formatted[field])); @@ -104,15 +104,15 @@ export function DocViewTable({ // to the index pattern, but that has its own complications which you can read more about in the following // issue: https://github.com/elastic/kibana/issues/54957 const isNestedField = - !indexPattern.fields.find(patternField => patternField.name === field) && - !!indexPattern.fields.find(patternField => { + !indexPattern.fields.find((patternField) => patternField.name === field) && + !!indexPattern.fields.find((patternField) => { // We only want to match a full path segment const nestedRootRegex = new RegExp(escapeRegExp(field) + '(\\.|$)'); return nestedRootRegex.test(patternField.subType?.nested?.path ?? ''); }); const fieldType = isNestedField ? 'nested' - : indexPattern.fields.find(patternField => patternField.name === field)?.type; + : indexPattern.fields.find((patternField) => patternField.name === field)?.type; return ( typeof v === 'object' && v !== null); + return Array.isArray(value) && value.some((v) => typeof v === 'object' && v !== null); } /** diff --git a/src/plugins/discover/public/application/components/timechart_header/timechart_header.test.tsx b/src/plugins/discover/public/application/components/timechart_header/timechart_header.test.tsx index 642774d6be202..964f94ca9d9b2 100644 --- a/src/plugins/discover/public/application/components/timechart_header/timechart_header.test.tsx +++ b/src/plugins/discover/public/application/components/timechart_header/timechart_header.test.tsx @@ -24,7 +24,7 @@ import { EuiIconTip } from '@elastic/eui'; // @ts-ignore import { findTestSubject } from '@elastic/eui/lib/test'; -describe('timechart header', function() { +describe('timechart header', function () { let props: TimechartHeaderProps; let component: ReactWrapper; @@ -65,7 +65,7 @@ describe('timechart header', function() { expect(component.find(EuiIconTip).length).toBe(1); }); - it('expect to render the date range', function() { + it('expect to render the date range', function () { component = mountWithIntl(); const datetimeRangeText = findTestSubject(component, 'discoverIntervalDateRange'); expect(datetimeRangeText.text()).toBe( @@ -78,14 +78,14 @@ describe('timechart header', function() { const dropdown = findTestSubject(component, 'discoverIntervalSelect'); expect(dropdown.length).toBe(1); // @ts-ignore - const values = dropdown.find('option').map(option => option.prop('value')); + const values = dropdown.find('option').map((option) => option.prop('value')); expect(values).toEqual(['auto', 'ms', 's']); // @ts-ignore - const labels = dropdown.find('option').map(option => option.text()); + const labels = dropdown.find('option').map((option) => option.text()); expect(labels).toEqual(['Auto', 'Millisecond', 'Second']); }); - it('should change the interval', function() { + it('should change the interval', function () { component = mountWithIntl(); findTestSubject(component, 'discoverIntervalSelect').simulate('change', { target: { value: 'ms' }, diff --git a/src/plugins/discover/public/application/components/timechart_header/timechart_header.tsx b/src/plugins/discover/public/application/components/timechart_header/timechart_header.tsx index 077adcb6b006e..8789847058aff 100644 --- a/src/plugins/discover/public/application/components/timechart_header/timechart_header.tsx +++ b/src/plugins/discover/public/application/components/timechart_header/timechart_header.tsx @@ -147,9 +147,7 @@ export function TimechartHeader({ size="s" type="alert" /> - ) : ( - undefined - ) + ) : undefined } /> diff --git a/src/plugins/discover/public/application/components/top_nav/open_search_panel.js b/src/plugins/discover/public/application/components/top_nav/open_search_panel.js index 06267407dcb21..4266035a5bb4f 100644 --- a/src/plugins/discover/public/application/components/top_nav/open_search_panel.js +++ b/src/plugins/discover/public/application/components/top_nav/open_search_panel.js @@ -71,7 +71,7 @@ export function OpenSearchPanel(props) { }), }, ]} - onChoose={id => { + onChoose={(id) => { window.location.assign(props.makeUrl(id)); props.onClose(); }} diff --git a/src/plugins/discover/public/application/doc_views/doc_views_helpers.tsx b/src/plugins/discover/public/application/doc_views/doc_views_helpers.tsx index b9932da0523f8..958b7b6f8705b 100644 --- a/src/plugins/discover/public/application/doc_views/doc_views_helpers.tsx +++ b/src/plugins/discover/public/application/doc_views/doc_views_helpers.tsx @@ -79,7 +79,7 @@ export function convertDirectiveToRenderFn( directive.controller, getInjector ); - cleanupFnPromise.catch(e => { + cleanupFnPromise.catch((e) => { rejected = true; render(, domNode); }); @@ -88,7 +88,7 @@ export function convertDirectiveToRenderFn( if (!rejected) { // for cleanup // http://roubenmeschian.com/rubo/?p=51 - cleanupFnPromise.then(cleanup => cleanup()); + cleanupFnPromise.then((cleanup) => cleanup()); } }; }; diff --git a/src/plugins/discover/public/application/doc_views/doc_views_registry.ts b/src/plugins/discover/public/application/doc_views/doc_views_registry.ts index cdc22155f4710..589ecd4efe0f5 100644 --- a/src/plugins/discover/public/application/doc_views/doc_views_registry.ts +++ b/src/plugins/discover/public/application/doc_views/doc_views_registry.ts @@ -53,7 +53,7 @@ export class DocViewsRegistry { */ getDocViewsSorted(hit: ElasticSearchHit) { return this.docViews - .filter(docView => docView.shouldShow(hit)) + .filter((docView) => docView.shouldShow(hit)) .sort((a, b) => (Number(a.order) > Number(b.order) ? 1 : -1)); } } diff --git a/src/plugins/discover/public/application/embeddable/search_embeddable.ts b/src/plugins/discover/public/application/embeddable/search_embeddable.ts index ed70c90eb64e6..77d1572b0a40c 100644 --- a/src/plugins/discover/public/application/embeddable/search_embeddable.ts +++ b/src/plugins/discover/public/application/embeddable/search_embeddable.ts @@ -212,7 +212,7 @@ export class SearchEmbeddable extends Embeddable this.pushContainerStateParamsToScope(searchScope); - searchScope.setSortOrder = sort => { + searchScope.setSortOrder = (sort) => { this.updateInput({ sort }); }; @@ -249,7 +249,7 @@ export class SearchEmbeddable extends Embeddable operator, indexPattern.id! ); - filters = filters.map(filter => ({ + filters = filters.map((filter) => ({ ...filter, $state: { store: esFilters.FilterStateStore.APP_STATE }, })); diff --git a/src/plugins/discover/public/application/helpers/get_index_pattern_id.ts b/src/plugins/discover/public/application/helpers/get_index_pattern_id.ts index b78c43b9a74ac..601f892e3c56a 100644 --- a/src/plugins/discover/public/application/helpers/get_index_pattern_id.ts +++ b/src/plugins/discover/public/application/helpers/get_index_pattern_id.ts @@ -26,7 +26,7 @@ export function findIndexPatternById( if (!Array.isArray(indexPatterns) || !id) { return; } - return indexPatterns.find(o => o.id === id); + return indexPatterns.find((o) => o.id === id); } /** diff --git a/src/plugins/discover/public/get_inner_angular.ts b/src/plugins/discover/public/get_inner_angular.ts index d97bbef7aca25..2b4705645cfcc 100644 --- a/src/plugins/discover/public/get_inner_angular.ts +++ b/src/plugins/discover/public/get_inner_angular.ts @@ -59,6 +59,7 @@ import { } from '../../kibana_legacy/public'; import { createDiscoverSidebarDirective } from './application/components/sidebar'; import { createHitsCounterDirective } from '././application/components/hits_counter'; +import { createLoadingSpinnerDirective } from '././application/components/loading_spinner/loading_spinner'; import { createTimechartHeaderDirective } from './application/components/timechart_header'; import { DiscoverStartPlugins } from './plugin'; import { getScopedHistory } from './kibana_services'; @@ -126,7 +127,7 @@ export function initializeInnerAngularModule( 'discoverPromise', ]) .config(watchMultiDecorator) - .directive('icon', reactDirective => reactDirective(EuiIcon)) + .directive('icon', (reactDirective) => reactDirective(EuiIcon)) .directive('renderComplete', createRenderCompleteDirective) .service('debounce', ['$timeout', DebounceProviderTimeout]); } @@ -148,13 +149,14 @@ export function initializeInnerAngularModule( ]) .config(watchMultiDecorator) .run(registerListenEventListener) - .directive('icon', reactDirective => reactDirective(EuiIcon)) + .directive('icon', (reactDirective) => reactDirective(EuiIcon)) .directive('kbnAccessibleClick', KbnAccessibleClickProvider) .directive('collapsibleSidebar', CollapsibleSidebarProvider) .directive('fixedScroll', FixedScrollProvider) .directive('renderComplete', createRenderCompleteDirective) .directive('discoverSidebar', createDiscoverSidebarDirective) .directive('hitsCounter', createHitsCounterDirective) + .directive('loadingSpinner', createLoadingSpinnerDirective) .directive('timechartHeader', createTimechartHeaderDirective) .service('debounce', ['$timeout', DebounceProviderTimeout]); } @@ -189,8 +191,8 @@ function createLocalStorageModule() { .service('sessionStorage', createLocalStorageService('sessionStorage')); } -const createLocalStorageService = function(type: string) { - return function($window: any) { +const createLocalStorageService = function (type: string) { + return function ($window: any) { return new Storage($window[type]); }; }; @@ -200,7 +202,7 @@ function createElasticSearchModule(data: DataPublicPluginStart) { .module('discoverEs', []) // Elasticsearch client used for requesting data. Connects to the /elasticsearch proxy // have to be written as function expression, because it's not compiled in dev mode - .service('es', function() { + .service('es', function () { return data.search.__LEGACY.esClient; }); } diff --git a/src/plugins/embeddable/public/components/panel_options_menu/index.tsx b/src/plugins/embeddable/public/components/panel_options_menu/index.tsx index e0796990e0c4e..7790646a88a68 100644 --- a/src/plugins/embeddable/public/components/panel_options_menu/index.tsx +++ b/src/plugins/embeddable/public/components/panel_options_menu/index.tsx @@ -45,7 +45,7 @@ export const PanelOptionsMenu: React.FC = ({ }, [close]); const handleContextMenuClick = () => { - setOpen(isOpen => !isOpen); + setOpen((isOpen) => !isOpen); }; const handlePopoverClose = () => { diff --git a/src/plugins/embeddable/public/lib/containers/container.ts b/src/plugins/embeddable/public/lib/containers/container.ts index ffbe75f66b581..8cf3d1a15883b 100644 --- a/src/plugins/embeddable/public/lib/containers/container.ts +++ b/src/plugins/embeddable/public/lib/containers/container.ts @@ -80,7 +80,7 @@ export abstract class Container< } public reload() { - Object.values(this.children).forEach(child => child.reload()); + Object.values(this.children).forEach((child) => child.reload()); } public async addNewEmbeddable< @@ -131,7 +131,7 @@ export abstract class Container< // to default back to inherited input. However, if the particular value is not part of the container, then // the caller may be trying to explicitly tell the child to clear out a given value, so in that case, we want // to pass it along. - keys.forEach(key => { + keys.forEach((key) => { if (explicitInput[key] === undefined && containerInput[key] !== undefined) { return; } @@ -149,7 +149,7 @@ export abstract class Container< public destroy() { super.destroy(); - Object.values(this.children).forEach(child => child.destroy()); + Object.values(this.children).forEach((child) => child.destroy()); this.subscription.unsubscribe(); } @@ -251,7 +251,7 @@ export abstract class Container< // Container input overrides defaults. const explicitInput: Partial = partial; - getKeys(defaults).forEach(key => { + getKeys(defaults).forEach((key) => { // @ts-ignore We know this key might not exist on inheritedInput. const inheritedValue = inheritedInput[key]; if (inheritedValue === undefined && explicitInput[key] === undefined) { @@ -330,7 +330,7 @@ export abstract class Container< private maybeUpdateChildren() { const allIds = Object.keys({ ...this.input.panels, ...this.output.embeddableLoaded }); - allIds.forEach(id => { + allIds.forEach((id) => { if (this.input.panels[id] !== undefined && this.output.embeddableLoaded[id] === undefined) { this.onPanelAdded(this.input.panels[id]); } else if ( diff --git a/src/plugins/embeddable/public/lib/embeddables/embeddable.test.tsx b/src/plugins/embeddable/public/lib/embeddables/embeddable.test.tsx index a8ac5abe42a1d..340d851f3eedf 100644 --- a/src/plugins/embeddable/public/lib/embeddables/embeddable.test.tsx +++ b/src/plugins/embeddable/public/lib/embeddables/embeddable.test.tsx @@ -51,7 +51,7 @@ class OutputTestEmbeddable extends Embeddable { reload() {} } -test('Embeddable calls input subscribers when changed', async done => { +test('Embeddable calls input subscribers when changed', async (done) => { const hello = new ContactCardEmbeddable( { id: '123', firstName: 'Brienne', lastName: 'Tarth' }, { execAction: (() => null) as any } @@ -60,7 +60,7 @@ test('Embeddable calls input subscribers when changed', async done => { const subscription = hello .getInput$() .pipe(skip(1)) - .subscribe(input => { + .subscribe((input) => { expect(input.nameTitle).toEqual('Sir'); done(); subscription.unsubscribe(); diff --git a/src/plugins/embeddable/public/lib/embeddables/embeddable_factory_renderer.tsx b/src/plugins/embeddable/public/lib/embeddables/embeddable_factory_renderer.tsx index 81052620fd08d..1ba9e12ec4d20 100644 --- a/src/plugins/embeddable/public/lib/embeddables/embeddable_factory_renderer.tsx +++ b/src/plugins/embeddable/public/lib/embeddables/embeddable_factory_renderer.tsx @@ -62,7 +62,7 @@ export class EmbeddableFactoryRenderer extends React.Component { return; } - factory.create(this.props.input).then(embeddable => { + factory.create(this.props.input).then((embeddable) => { this.embeddable = embeddable; this.setState({ loading: false }); }); diff --git a/src/plugins/embeddable/public/lib/panel/embeddable_panel.test.tsx b/src/plugins/embeddable/public/lib/panel/embeddable_panel.test.tsx index 384297d8dee7d..ff9f466a8d553 100644 --- a/src/plugins/embeddable/public/lib/panel/embeddable_panel.test.tsx +++ b/src/plugins/embeddable/public/lib/panel/embeddable_panel.test.tsx @@ -64,7 +64,7 @@ setup.registerEmbeddableFactory(embeddableFactory.type, embeddableFactory); const start = doStart(); const getEmbeddableFactory = start.getEmbeddableFactory; -test('HelloWorldContainer initializes embeddables', async done => { +test('HelloWorldContainer initializes embeddables', async (done) => { const container = new HelloWorldContainer( { id: '123', diff --git a/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx b/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx index 36ddfb49b0312..4fcf8b9f608f8 100644 --- a/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx +++ b/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx @@ -111,7 +111,7 @@ export class EmbeddablePanel extends React.Component { const { disabledActions } = this.props.embeddable.getInput(); if (disabledActions) { - badges = badges.filter(badge => disabledActions.indexOf(badge.id) === -1); + badges = badges.filter((badge) => disabledActions.indexOf(badge.id) === -1); } this.setState({ @@ -127,7 +127,7 @@ export class EmbeddablePanel extends React.Component { const { disabledActions } = this.props.embeddable.getInput(); if (disabledActions) { - notifications = notifications.filter(badge => disabledActions.indexOf(badge.id) === -1); + notifications = notifications.filter((badge) => disabledActions.indexOf(badge.id) === -1); } this.setState({ @@ -248,12 +248,12 @@ export class EmbeddablePanel extends React.Component { const createGetUserData = (overlays: OverlayStart) => async function getUserData(context: { embeddable: IEmbeddable }) { - return new Promise<{ title: string | undefined }>(resolve => { + return new Promise<{ title: string | undefined }>((resolve) => { const session = overlays.openModal( toMountPoint( { + updateTitle={(title) => { session.close(); resolve({ title }); }} diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.test.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.test.tsx index 3894d6fbed382..34a176400dbb9 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.test.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.test.tsx @@ -81,7 +81,7 @@ test('createNewEmbeddable() add embeddable to container', async () => { expect(Object.values(container.getInput().panels).length).toBe(0); component.instance().createNewEmbeddable(CONTACT_CARD_EMBEDDABLE); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); const ids = Object.keys(container.getInput().panels); const embeddableId = ids[0]; @@ -123,7 +123,7 @@ test('selecting embeddable in "Create new ..." list calls createNewEmbeddable()' getFactory={getEmbeddableFactory} getAllFactories={start.getEmbeddableFactories} notifications={core.notifications} - SavedObjectFinder={props => } + SavedObjectFinder={(props) => } /> ) as ReactWrapper; diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.tsx index 4c23916675e8f..d3e100366f2df 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/add_panel_flyout.tsx @@ -95,7 +95,8 @@ export class AddPanelFlyout extends React.Component { public onAddPanel = async (savedObjectId: string, savedObjectType: string, name: string) => { const factoryForSavedObjectType = [...this.props.getAllFactories()].find( - factory => factory.savedObjectMetaData && factory.savedObjectMetaData.type === savedObjectType + (factory) => + factory.savedObjectMetaData && factory.savedObjectMetaData.type === savedObjectType ); if (!factoryForSavedObjectType) { throw new EmbeddableFactoryNotFoundError(savedObjectType); @@ -111,8 +112,10 @@ export class AddPanelFlyout extends React.Component { private getCreateMenuItems(): ReactElement[] { return [...this.props.getAllFactories()] - .filter(factory => factory.isEditable() && !factory.isContainerType && factory.canCreateNew()) - .map(factory => ( + .filter( + (factory) => factory.isEditable() && !factory.isContainerType && factory.canCreateNew() + ) + .map((factory) => ( { const SavedObjectFinder = this.props.SavedObjectFinder; const metaData = [...this.props.getAllFactories()] .filter( - embeddableFactory => + (embeddableFactory) => Boolean(embeddableFactory.savedObjectMetaData) && !embeddableFactory.isContainerType ) .map(({ savedObjectMetaData }) => savedObjectMetaData as any); diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/tests/saved_object_finder_create_new.test.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/tests/saved_object_finder_create_new.test.tsx index 6275dbd4eaa45..a4c80e1d86a80 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/tests/saved_object_finder_create_new.test.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/add_panel/tests/saved_object_finder_create_new.test.tsx @@ -41,11 +41,9 @@ describe('SavedObjectFinderCreateNew', () => { const onClick = jest.fn(); for (let i = 0; i < 3; i++) { items.push( - {`item${i + 1}`} + {`item${ + i + 1 + }`} ); } @@ -69,11 +67,9 @@ describe('SavedObjectFinderCreateNew', () => { const onClick = jest.fn(); for (let i = 0; i < 3; i++) { items.push( - {`item${i + 1}`} + {`item${ + i + 1 + }`} ); } diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_action.test.ts b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_action.test.ts index 2f66d8eb0d619..6fddcbc84faf7 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_action.test.ts +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_action.test.ts @@ -66,7 +66,7 @@ beforeEach(async () => { } }); -test('Updates the embeddable title when given', async done => { +test('Updates the embeddable title when given', async (done) => { const getUserData = () => Promise.resolve({ title: 'What is up?' }); const customizePanelAction = new CustomizePanelTitleAction(getUserData); expect(embeddable.getInput().title).toBeUndefined(); diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_modal.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_modal.tsx index 663fa50420ccc..b590f20092939 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_modal.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_actions/customize_title/customize_panel_modal.tsx @@ -64,7 +64,7 @@ export class CustomizePanelModal extends Component { }; private onHideTitleToggle = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ hideTitle: !prevState.hideTitle, })); }; @@ -118,7 +118,7 @@ export class CustomizePanelModal extends Component { disabled={this.state.hideTitle} placeholder={this.props.embeddable.getOutput().defaultTitle} value={this.state.title || ''} - onChange={e => this.updateTitle(e.target.value)} + onChange={(e) => this.updateTitle(e.target.value)} aria-label={i18n.translate( 'embeddableApi.customizePanel.modal.optionsMenuForm.panelTitleInputAriaLabel', { diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_header.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_header.tsx index bb2eb52f9df72..8ba7be7880a7b 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_header.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_header.tsx @@ -45,7 +45,7 @@ export interface PanelHeaderProps { } function renderBadges(badges: Array>, embeddable: IEmbeddable) { - return badges.map(badge => ( + return badges.map((badge) => ( >, embeddable: IEmbeddable ) { - return notifications.map(notification => { + return notifications.map((notification) => { const context = { embeddable }; let badge = ( diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_options_menu.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_options_menu.tsx index 5548c9a0596b4..b4c349600e8f6 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_options_menu.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_options_menu.tsx @@ -137,11 +137,11 @@ export class PanelOptionsMenu extends React.Component { + .then((actionContextMenuPanel) => { if (!this.mounted) return; this.setState({ actionContextMenuPanel }); }) - .catch(error => console.error(error)); // eslint-disable-line no-console + .catch((error) => console.error(error)); // eslint-disable-line no-console }; this.setState(({ isPopoverOpen }) => ({ isPopoverOpen: !isPopoverOpen }), after); }; diff --git a/src/plugins/embeddable/public/lib/test_samples/actions/get_message_modal.tsx b/src/plugins/embeddable/public/lib/test_samples/actions/get_message_modal.tsx index 7b396ce1bd10a..bb859d7b8d0c1 100644 --- a/src/plugins/embeddable/public/lib/test_samples/actions/get_message_modal.tsx +++ b/src/plugins/embeddable/public/lib/test_samples/actions/get_message_modal.tsx @@ -58,7 +58,7 @@ export class GetMessageModal extends Component { this.setState({ message: e.target.value })} + onChange={(e) => this.setState({ message: e.target.value })} /> diff --git a/src/plugins/embeddable/public/lib/test_samples/actions/send_message_action.tsx b/src/plugins/embeddable/public/lib/test_samples/actions/send_message_action.tsx index 222fe1f6ed870..04898550532df 100644 --- a/src/plugins/embeddable/public/lib/test_samples/actions/send_message_action.tsx +++ b/src/plugins/embeddable/public/lib/test_samples/actions/send_message_action.tsx @@ -57,7 +57,7 @@ export function createSendMessageAction(overlays: CoreStart['overlays']) { toMountPoint( modal.close()} - onDone={message => { + onDone={(message) => { modal.close(); sendMessage(context, message); }} diff --git a/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable.tsx b/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable.tsx index 078e21df0f0ce..b82cd9ca7cc31 100644 --- a/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable.tsx +++ b/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable.tsx @@ -42,7 +42,7 @@ export interface ContactCardEmbeddableOptions { function getFullName(input: ContactCardEmbeddableInput) { const { nameTitle, firstName, lastName } = input; - const nameParts = [nameTitle, firstName, lastName].filter(name => name !== undefined); + const nameParts = [nameTitle, firstName, lastName].filter((name) => name !== undefined); return nameParts.join(' '); } diff --git a/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable_factory.tsx b/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable_factory.tsx index f977329562b9b..893b6b04e50bc 100644 --- a/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable_factory.tsx +++ b/src/plugins/embeddable/public/lib/test_samples/embeddables/contact_card/contact_card_embeddable_factory.tsx @@ -50,7 +50,7 @@ export class ContactCardEmbeddableFactory } public getExplicitInput = (): Promise> => { - return new Promise(resolve => { + return new Promise((resolve) => { const modalSession = this.overlays.openModal( toMountPoint( this.setState({ firstName: e.target.value })} + onChange={(e) => this.setState({ firstName: e.target.value })} /> @@ -68,7 +68,7 @@ export class ContactCardInitializer extends Component this.setState({ lastName: e.target.value })} + onChange={(e) => this.setState({ lastName: e.target.value })} /> diff --git a/src/plugins/embeddable/public/lib/test_samples/embeddables/hello_world_container_component.tsx b/src/plugins/embeddable/public/lib/test_samples/embeddables/hello_world_container_component.tsx index 49e9c34d95c95..6453046b86e20 100644 --- a/src/plugins/embeddable/public/lib/test_samples/embeddables/hello_world_container_component.tsx +++ b/src/plugins/embeddable/public/lib/test_samples/embeddables/hello_world_container_component.tsx @@ -52,7 +52,7 @@ export class HelloWorldContainerComponent extends Component { constructor(props: Props) { super(props); - Object.values(this.props.container.getInput().panels).forEach(panelState => { + Object.values(this.props.container.getInput().panels).forEach((panelState) => { this.roots[panelState.explicitInput.id] = React.createRef(); }); @@ -102,7 +102,7 @@ export class HelloWorldContainerComponent extends Component { } private renderList() { - const list = Object.values(this.state.panels).map(panelState => { + const list = Object.values(this.state.panels).map((panelState) => { const item = ( { const coreStart = coreMock.createStart(); const { setup, doStart } = testPlugin(coreSetup, coreStart); - const customProvider: EmbeddableFactoryProvider = def => ({ + const customProvider: EmbeddableFactoryProvider = (def) => ({ ...defaultEmbeddableFactoryProvider(def), getDisplayName: () => 'Intercepted!', }); @@ -66,7 +66,7 @@ test('custom embeddable factory provider test for intercepting embeddable creati const { setup, doStart } = testPlugin(coreSetup, coreStart); let updateCount = 0; - const customProvider: EmbeddableFactoryProvider = def => { + const customProvider: EmbeddableFactoryProvider = (def) => { return { ...defaultEmbeddableFactoryProvider(def), create: async (input, parent) => { @@ -105,6 +105,6 @@ test('custom embeddable factory provider test for intercepting embeddable creati expect(updateCount).toEqual(2); embeddable!.destroy(); - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); expect(updateCount).toEqual(0); }); diff --git a/src/plugins/embeddable/public/plugin.tsx b/src/plugins/embeddable/public/plugin.tsx index 36f49f2508e80..40a288545ef27 100644 --- a/src/plugins/embeddable/public/plugin.tsx +++ b/src/plugins/embeddable/public/plugin.tsx @@ -92,7 +92,7 @@ export class EmbeddablePublicPlugin implements Plugin { + this.embeddableFactoryDefinitions.forEach((def) => { this.embeddableFactories.set( def.type, this.customEmbeddableFactoryProvider @@ -166,7 +166,7 @@ export class EmbeddablePublicPlugin implements Plugin { - this.embeddableFactoryDefinitions.forEach(def => this.ensureFactoryExists(def.type)); + this.embeddableFactoryDefinitions.forEach((def) => this.ensureFactoryExists(def.type)); }; private ensureFactoryExists = (type: string) => { diff --git a/src/plugins/embeddable/public/tests/container.test.ts b/src/plugins/embeddable/public/tests/container.test.ts index d2769e208ba42..4cd01abaf7995 100644 --- a/src/plugins/embeddable/public/tests/container.test.ts +++ b/src/plugins/embeddable/public/tests/container.test.ts @@ -91,7 +91,7 @@ async function creatHelloWorldContainerAndEmbeddable( return { container, embeddable, coreSetup, coreStart, setup, start, uiActions }; } -test('Container initializes embeddables', async done => { +test('Container initializes embeddables', async (done) => { const { container } = await creatHelloWorldContainerAndEmbeddable({ id: 'hello', panels: { @@ -130,7 +130,7 @@ test('Container.addNewEmbeddable', async () => { expect(embeddableInContainer.id).toBe(embeddable.id); }); -test('Container.removeEmbeddable removes and cleans up', async done => { +test('Container.removeEmbeddable removes and cleans up', async (done) => { const { start, coreStart, uiActions } = await creatHelloWorldContainerAndEmbeddable(); const container = new HelloWorldContainer( { @@ -294,7 +294,7 @@ test('Container view mode change propagates to children', async () => { expect(embeddable.getInput().viewMode).toBe(ViewMode.EDIT); }); -test(`Container updates its state when a child's input is updated`, async done => { +test(`Container updates its state when a child's input is updated`, async (done) => { const { container, embeddable, @@ -381,7 +381,7 @@ test(`Derived container state passed to children`, async () => { subscription.unsubscribe(); }); -test(`Can subscribe to children embeddable updates`, async done => { +test(`Can subscribe to children embeddable updates`, async (done) => { const { embeddable } = await creatHelloWorldContainerAndEmbeddable( { id: 'hello container', @@ -404,7 +404,7 @@ test(`Can subscribe to children embeddable updates`, async done => { embeddable.updateInput({ nameTitle: 'Dr.' }); }); -test('Test nested reactions', async done => { +test('Test nested reactions', async (done) => { const { container, embeddable } = await creatHelloWorldContainerAndEmbeddable( { id: 'hello', panels: {}, viewMode: ViewMode.VIEW }, { @@ -472,7 +472,7 @@ test('Explicit embeddable input mapped to undefined will default to inherited', ]); }); -test('Explicit embeddable input mapped to undefined with no inherited value will get passed to embeddable', async done => { +test('Explicit embeddable input mapped to undefined with no inherited value will get passed to embeddable', async (done) => { const { container } = await creatHelloWorldContainerAndEmbeddable({ id: 'hello', panels: {} }); const embeddable = await container.addNewEmbeddable< @@ -523,7 +523,7 @@ test('Panel removed from input state', async () => { }; container.updateInput(newInput); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(container.getChild(embeddable.id)).toBeUndefined(); expect(container.getOutput().embeddableLoaded[embeddable.id]).toBeUndefined(); @@ -554,7 +554,7 @@ test('Panel added to input state', async () => { ); container2.updateInput(container.getInput()); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(container.getChild(embeddable.id)).toBeDefined(); expect(container.getOutput().embeddableLoaded[embeddable.id]).toBe(true); @@ -562,7 +562,7 @@ test('Panel added to input state', async () => { expect(container.getOutput().embeddableLoaded[embeddable2.id]).toBe(true); }); -test('Container changes made directly after adding a new embeddable are propagated', async done => { +test('Container changes made directly after adding a new embeddable are propagated', async (done) => { const coreSetup = coreMock.createSetup(); const coreStart = coreMock.createStart(); const { setup, doStart, uiActions } = testPlugin(coreSetup, coreStart); @@ -618,7 +618,7 @@ test('Container changes made directly after adding a new embeddable are propagat container.updateInput({ viewMode: ViewMode.VIEW }); }); -test('container stores ErrorEmbeddables when a factory for a child cannot be found (so the panel can be removed)', async done => { +test('container stores ErrorEmbeddables when a factory for a child cannot be found (so the panel can be removed)', async (done) => { const { container } = await creatHelloWorldContainerAndEmbeddable({ id: 'hello', panels: { @@ -639,7 +639,7 @@ test('container stores ErrorEmbeddables when a factory for a child cannot be fou }); }); -test('container stores ErrorEmbeddables when a saved object cannot be found', async done => { +test('container stores ErrorEmbeddables when a saved object cannot be found', async (done) => { const { container } = await creatHelloWorldContainerAndEmbeddable({ id: 'hello', panels: { @@ -660,7 +660,7 @@ test('container stores ErrorEmbeddables when a saved object cannot be found', as }); }); -test('ErrorEmbeddables get updated when parent does', async done => { +test('ErrorEmbeddables get updated when parent does', async (done) => { const { container } = await creatHelloWorldContainerAndEmbeddable({ id: 'hello', panels: { @@ -723,7 +723,7 @@ test('untilEmbeddableLoaded() throws an error if there is no such child panel in expect(error.message).toMatchInlineSnapshot(`"Panel not found"`); }); -test('untilEmbeddableLoaded() resolves if child is loaded in the container', async done => { +test('untilEmbeddableLoaded() resolves if child is loaded in the container', async (done) => { const { setup, doStart, coreStart, uiActions } = testPlugin( coreMock.createSetup(), coreMock.createStart() @@ -759,7 +759,7 @@ test('untilEmbeddableLoaded() resolves if child is loaded in the container', asy done(); }); -test('untilEmbeddableLoaded resolves with undefined if child is subsequently removed', async done => { +test('untilEmbeddableLoaded resolves with undefined if child is subsequently removed', async (done) => { const { doStart, setup, coreStart, uiActions } = testPlugin( coreMock.createSetup(), coreMock.createStart() @@ -793,7 +793,7 @@ test('untilEmbeddableLoaded resolves with undefined if child is subsequently rem } ); - container.untilEmbeddableLoaded('123').then(embed => { + container.untilEmbeddableLoaded('123').then((embed) => { expect(embed).toBeUndefined(); done(); }); @@ -801,7 +801,7 @@ test('untilEmbeddableLoaded resolves with undefined if child is subsequently rem container.updateInput({ panels: {} }); }); -test('adding a panel then subsequently removing it before its loaded removes the panel', async done => { +test('adding a panel then subsequently removing it before its loaded removes the panel', async (done) => { const { doStart, coreStart, uiActions, setup } = testPlugin( coreMock.createSetup(), coreMock.createStart() diff --git a/src/plugins/embeddable/public/tests/explicit_input.test.ts b/src/plugins/embeddable/public/tests/explicit_input.test.ts index ef3c4b6f17e7f..6bea4fe46a497 100644 --- a/src/plugins/embeddable/public/tests/explicit_input.test.ts +++ b/src/plugins/embeddable/public/tests/explicit_input.test.ts @@ -79,7 +79,7 @@ test('Explicit embeddable input mapped to undefined will default to inherited', ]); }); -test('Explicit embeddable input mapped to undefined with no inherited value will get passed to embeddable', async done => { +test('Explicit embeddable input mapped to undefined with no inherited value will get passed to embeddable', async (done) => { const container = new HelloWorldContainer( { id: 'hello', panels: {} }, { diff --git a/src/plugins/embeddable/public/tests/helpers.ts b/src/plugins/embeddable/public/tests/helpers.ts index de15ef61c2c60..8bdfbc60e1a41 100644 --- a/src/plugins/embeddable/public/tests/helpers.ts +++ b/src/plugins/embeddable/public/tests/helpers.ts @@ -22,7 +22,7 @@ export const expectErrorAsync = (fn: (...args: unknown[]) => Promise): .then(() => { throw new Error('Expected an error throw.'); }) - .catch(error => { + .catch((error) => { if (error.message === 'Expected an error throw.') { throw error; } diff --git a/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/with_privileges.tsx b/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/with_privileges.tsx index 8f4b2b976d141..35d8cdaa67fc4 100644 --- a/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/with_privileges.tsx +++ b/src/plugins/es_ui_shared/__packages_do_not_import__/authorization/components/with_privileges.tsx @@ -43,7 +43,7 @@ const toArray = (value: string | string[]): string[] => export const WithPrivileges = ({ privileges: requiredPrivileges, children }: Props) => { const { isLoading, privileges } = useAuthorizationContext(); - const privilegesToArray: Privilege[] = toArray(requiredPrivileges).map(p => { + const privilegesToArray: Privilege[] = toArray(requiredPrivileges).map((p) => { const [section, privilege] = p.split('.'); if (!privilege) { // Oh! we forgot to use the dot "." notation. @@ -54,7 +54,7 @@ export const WithPrivileges = ({ privileges: requiredPrivileges, children }: Pro const hasPrivileges = isLoading ? false - : privilegesToArray.every(privilege => { + : privilegesToArray.every((privilege) => { const [section, requiredPrivilege] = privilege; if (!privileges.missingPrivileges[section]) { // if the section does not exist in our missingPriviledges, everything is OK diff --git a/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/helpers/enzyme_helpers.tsx b/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/helpers/enzyme_helpers.tsx deleted file mode 100644 index d2e13fe7622f9..0000000000000 --- a/src/plugins/es_ui_shared/__packages_do_not_import__/test_utils_temp/helpers/enzyme_helpers.tsx +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * Components using the react-intl module require access to the intl context. - * This is not available when mounting single components in Enzyme. - * These helper functions aim to address that and wrap a valid, - * intl context around them. - */ - -import { I18nProvider, InjectedIntl, intlShape } from '@kbn/i18n/react'; -import { mount, ReactWrapper, render, shallow } from 'enzyme'; -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<{}, {}, import('react-intl').IntlProvider>) - .instance() - .getChildContext(); - -function getOptions(context = {}, childContextTypes = {}, props = {}) { - return { - context: { - ...context, - intl, - }, - childContextTypes: { - ...childContextTypes, - intl: intlShape, - }, - ...props, - }; -} - -/** - * When using React-Intl `injectIntl` on components, props.intl is required. - */ -function nodeWithIntlProp(node: ReactElement): ReactElement { - return React.cloneElement(node, { intl }); -} - -/** - * Creates the wrapper instance using shallow with provided intl object into context - * - * @param node The React element or cheerio wrapper - * @param options properties to pass into shallow wrapper - * @return The wrapper instance around the rendered output with intl object in context - */ -export function shallowWithIntl( - node: ReactElement, - { - context, - childContextTypes, - ...props - }: { - context?: any; - childContextTypes?: ValidationMap; - } = {} -) { - const options = getOptions(context, childContextTypes, props); - - return shallow(nodeWithIntlProp(node), options); -} - -/** - * Creates the wrapper instance using mount with provided intl object into context - * - * @param node The React element or cheerio wrapper - * @param options properties to pass into mount wrapper - * @return The wrapper instance around the rendered output with intl object in context - */ -export function mountWithIntl( - node: ReactElement, - { - context, - childContextTypes, - ...props - }: { - context?: any; - childContextTypes?: ValidationMap; - } = {} -) { - const options = getOptions(context, childContextTypes, props); - - return mount(nodeWithIntlProp(node), options); -} - -/** - * Creates the wrapper instance using render with provided intl object into context - * - * @param node The React element or cheerio wrapper - * @param options properties to pass into render wrapper - * @return The wrapper instance around the rendered output with intl object in context - */ -export function renderWithIntl( - node: ReactElement, - { - context, - childContextTypes, - ...props - }: { - context?: any; - childContextTypes?: ValidationMap; - } = {} -) { - const options = getOptions(context, childContextTypes, props); - - return render(nodeWithIntlProp(node), options); -} - -/** - * A wrapper object to provide access to the state of a hook under test and to - * enable interaction with that hook. - */ -interface ReactHookWrapper { - /* Ensures that async React operations have settled before and after the - * given actor callback is called. The actor callback arguments provide easy - * access to the last hook value and allow for updating the arguments passed - * to the hook body to trigger reevaluation. - */ - act: (actor: (lastHookValue: HookValue, setArgs: (args: Args) => void) => void) => void; - /* The enzyme wrapper around the test component. */ - component: ReactWrapper; - /* The most recent value return the by test harness of the hook. */ - getLastHookValue: () => HookValue; - /* The jest Mock function that receives the hook values for introspection. */ - hookValueCallback: jest.Mock; -} - -/** - * Allows for execution of hooks inside of a test component which records the - * returned values. - * - * @param body A function that calls the hook and returns data derived from it - * @param WrapperComponent A component that, if provided, will be wrapped - * around the test component. This can be useful to provide context values. - * @return {ReactHookWrapper} An object providing access to the hook state and - * functions to interact with it. - */ -export const mountHook = ( - body: (args: Args) => HookValue, - WrapperComponent?: React.ComponentType, - initialArgs: Args = {} as Args -): ReactHookWrapper => { - const hookValueCallback = jest.fn(); - let component!: ReactWrapper; - - const act: ReactHookWrapper['act'] = actor => { - reactAct(() => { - actor(getLastHookValue(), (args: Args) => component.setProps(args)); - component.update(); - }); - }; - - const getLastHookValue = () => { - const calls = hookValueCallback.mock.calls; - if (calls.length <= 0) { - throw Error('No recent hook value present.'); - } - return calls[calls.length - 1][0]; - }; - - const HookComponent = (props: Args) => { - hookValueCallback(body(props)); - return null; - }; - const TestComponent: React.FunctionComponent = args => - WrapperComponent ? ( - - - - ) : ( - - ); - - reactAct(() => { - component = mount(); - }); - - return { - act, - component, - getLastHookValue, - hookValueCallback, - }; -}; - -export const nextTick = () => new Promise(res => process.nextTick(res)); diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_daily.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_daily.js index 4ac6b0b8a256a..f038766766fe0 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_daily.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_daily.js @@ -41,7 +41,7 @@ export const CronDaily = ({ minute, minuteOptions, hour, hourOptions, onChange } aria-label={i18n.translate('esUi.cronEditor.cronDaily.hourSelectLabel', { defaultMessage: 'Hour', })} - onChange={e => onChange({ hour: e.target.value })} + onChange={(e) => onChange({ hour: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronDaily.fieldHour.textAtLabel', { defaultMessage: 'At', @@ -57,7 +57,7 @@ export const CronDaily = ({ minute, minuteOptions, hour, hourOptions, onChange } aria-label={i18n.translate('esUi.cronEditor.cronDaily.minuteSelectLabel', { defaultMessage: 'Minute', })} - onChange={e => onChange({ minute: e.target.value })} + onChange={(e) => onChange({ minute: e.target.value })} fullWidth prepend=":" data-test-subj="cronFrequencyDailyMinuteSelect" diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.js index 576658882589f..18e9ffcb27c56 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_editor.js @@ -53,27 +53,27 @@ function makeSequence(min, max) { return values; } -const MINUTE_OPTIONS = makeSequence(0, 59).map(value => ({ +const MINUTE_OPTIONS = makeSequence(0, 59).map((value) => ({ value: value.toString(), text: padLeft(value, 2, '0'), })); -const HOUR_OPTIONS = makeSequence(0, 23).map(value => ({ +const HOUR_OPTIONS = makeSequence(0, 23).map((value) => ({ value: value.toString(), text: padLeft(value, 2, '0'), })); -const DAY_OPTIONS = makeSequence(1, 7).map(value => ({ +const DAY_OPTIONS = makeSequence(1, 7).map((value) => ({ value: value.toString(), text: getDayName(value - 1), })); -const DATE_OPTIONS = makeSequence(1, 31).map(value => ({ +const DATE_OPTIONS = makeSequence(1, 31).map((value) => ({ value: value.toString(), text: getOrdinalValue(value), })); -const MONTH_OPTIONS = makeSequence(1, 12).map(value => ({ +const MONTH_OPTIONS = makeSequence(1, 12).map((value) => ({ value: value.toString(), text: getMonthName(value - 1), })); @@ -208,7 +208,7 @@ export class CronEditor extends Component { }; } - onChangeFrequency = frequency => { + onChangeFrequency = (frequency) => { const { onChange, fieldToPreferredValueMap } = this.props; // Update fields which aren't editable with acceptable baseline values. @@ -232,7 +232,7 @@ export class CronEditor extends Component { }); }; - onChangeFields = fields => { + onChangeFields = (fields) => { const { onChange, frequency, fieldToPreferredValueMap } = this.props; const editableFields = Object.keys(frequencyToFieldsMap[frequency]); @@ -354,7 +354,7 @@ export class CronEditor extends Component { this.onChangeFrequency(e.target.value)} + onChange={(e) => this.onChangeFrequency(e.target.value)} fullWidth prepend={i18n.translate('esUi.cronEditor.textEveryLabel', { defaultMessage: 'Every', diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_hourly.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_hourly.js index 194fccf110174..a04e83195b97f 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_hourly.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_hourly.js @@ -36,7 +36,7 @@ export const CronHourly = ({ minute, minuteOptions, onChange }) => ( onChange({ minute: e.target.value })} + onChange={(e) => onChange({ minute: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronHourly.fieldMinute.textAtLabel', { defaultMessage: 'At', diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_monthly.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_monthly.js index f3ffc082a4c60..28057bd7d9293 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_monthly.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_monthly.js @@ -44,7 +44,7 @@ export const CronMonthly = ({ onChange({ date: e.target.value })} + onChange={(e) => onChange({ date: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronMonthly.textOnTheLabel', { defaultMessage: 'On the', @@ -68,7 +68,7 @@ export const CronMonthly = ({ aria-label={i18n.translate('esUi.cronEditor.cronMonthly.hourSelectLabel', { defaultMessage: 'Hour', })} - onChange={e => onChange({ hour: e.target.value })} + onChange={(e) => onChange({ hour: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronMonthly.fieldHour.textAtLabel', { defaultMessage: 'At', @@ -84,7 +84,7 @@ export const CronMonthly = ({ aria-label={i18n.translate('esUi.cronEditor.cronMonthly.minuteSelectLabel', { defaultMessage: 'Minute', })} - onChange={e => onChange({ minute: e.target.value })} + onChange={(e) => onChange({ minute: e.target.value })} fullWidth prepend=":" data-test-subj="cronFrequencyMonthlyMinuteSelect" diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_weekly.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_weekly.js index b328b5cb958b4..c06eecbb381b3 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_weekly.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_weekly.js @@ -44,7 +44,7 @@ export const CronWeekly = ({ onChange({ day: e.target.value })} + onChange={(e) => onChange({ day: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronWeekly.textOnLabel', { defaultMessage: 'On', @@ -68,7 +68,7 @@ export const CronWeekly = ({ aria-label={i18n.translate('esUi.cronEditor.cronWeekly.hourSelectLabel', { defaultMessage: 'Hour', })} - onChange={e => onChange({ hour: e.target.value })} + onChange={(e) => onChange({ hour: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronWeekly.fieldHour.textAtLabel', { defaultMessage: 'At', @@ -81,7 +81,7 @@ export const CronWeekly = ({ onChange({ minute: e.target.value })} + onChange={(e) => onChange({ minute: e.target.value })} aria-label={i18n.translate('esUi.cronEditor.cronWeekly.minuteSelectLabel', { defaultMessage: 'Minute', })} diff --git a/src/plugins/es_ui_shared/public/components/cron_editor/cron_yearly.js b/src/plugins/es_ui_shared/public/components/cron_editor/cron_yearly.js index 26a57756273bd..c3b9691750937 100644 --- a/src/plugins/es_ui_shared/public/components/cron_editor/cron_yearly.js +++ b/src/plugins/es_ui_shared/public/components/cron_editor/cron_yearly.js @@ -46,7 +46,7 @@ export const CronYearly = ({ onChange({ month: e.target.value })} + onChange={(e) => onChange({ month: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronYearly.fieldMonth.textInLabel', { defaultMessage: 'In', @@ -65,7 +65,7 @@ export const CronYearly = ({ onChange({ date: e.target.value })} + onChange={(e) => onChange({ date: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronYearly.fieldDate.textOnTheLabel', { defaultMessage: 'On the', @@ -89,7 +89,7 @@ export const CronYearly = ({ aria-label={i18n.translate('esUi.cronEditor.cronYearly.hourSelectLabel', { defaultMessage: 'Hour', })} - onChange={e => onChange({ hour: e.target.value })} + onChange={(e) => onChange({ hour: e.target.value })} fullWidth prepend={i18n.translate('esUi.cronEditor.cronYearly.fieldHour.textAtLabel', { defaultMessage: 'At', @@ -105,7 +105,7 @@ export const CronYearly = ({ aria-label={i18n.translate('esUi.cronEditor.cronYearly.minuteSelectLabel', { defaultMessage: 'Minute', })} - onChange={e => onChange({ minute: e.target.value })} + onChange={(e) => onChange({ minute: e.target.value })} fullWidth prepend=":" data-test-subj="cronFrequencyYearlyMinuteSelect" diff --git a/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/elasticsearch_sql_highlight_rules.ts b/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/elasticsearch_sql_highlight_rules.ts index 398cf531612ef..41f6a65a5b410 100644 --- a/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/elasticsearch_sql_highlight_rules.ts +++ b/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/elasticsearch_sql_highlight_rules.ts @@ -21,7 +21,7 @@ import ace from 'brace'; const { TextHighlightRules } = ace.acequire('ace/mode/text_highlight_rules'); const oop = ace.acequire('ace/lib/oop'); -export const ElasticsearchSqlHighlightRules = function(this: any) { +export const ElasticsearchSqlHighlightRules = function (this: any) { // See https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-commands.html const keywords = 'describe|between|in|like|not|and|or|desc|select|from|where|having|group|by|order' + diff --git a/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/x_json_highlight_rules.ts b/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/x_json_highlight_rules.ts index 3663b92d92a6f..951cf5fa279b5 100644 --- a/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/x_json_highlight_rules.ts +++ b/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/x_json_highlight_rules.ts @@ -27,7 +27,7 @@ import { ScriptHighlightRules } from './script_highlight_rules'; const { JsonHighlightRules } = ace.acequire('ace/mode/json_highlight_rules'); const oop = ace.acequire('ace/lib/oop'); -const jsonRules = function(root: any) { +const jsonRules = function (root: any) { root = root ? root : 'json'; const rules: any = {}; const xJsonRules = [ diff --git a/src/plugins/es_ui_shared/public/console_lang/ace/modes/x_json/x_json.ts b/src/plugins/es_ui_shared/public/console_lang/ace/modes/x_json/x_json.ts index 9fbfedba1d23f..8d4ebcfad9496 100644 --- a/src/plugins/es_ui_shared/public/console_lang/ace/modes/x_json/x_json.ts +++ b/src/plugins/es_ui_shared/public/console_lang/ace/modes/x_json/x_json.ts @@ -43,16 +43,16 @@ const XJsonMode: any = function XJsonMode(this: any) { oop.inherits(XJsonMode, JSONMode); // Then clobber `createWorker` method to install our worker source. Per ace's wiki: https://github.com/ajaxorg/ace/wiki/Syntax-validation -(XJsonMode.prototype as any).createWorker = function(session: ace.IEditSession) { +(XJsonMode.prototype as any).createWorker = function (session: ace.IEditSession) { const xJsonWorker = new WorkerClient(['ace'], workerModule, 'JsonWorker'); xJsonWorker.attachToDocument(session.getDocument()); - xJsonWorker.on('annotate', function(e: { data: any }) { + xJsonWorker.on('annotate', function (e: { data: any }) { session.setAnnotations(e.data); }); - xJsonWorker.on('terminate', function() { + xJsonWorker.on('terminate', function () { session.clearAnnotations(); }); diff --git a/src/plugins/es_ui_shared/public/console_lang/lib/json_xjson_translation_tools/__tests__/json_xjson_translation_tools.test.ts b/src/plugins/es_ui_shared/public/console_lang/lib/json_xjson_translation_tools/__tests__/json_xjson_translation_tools.test.ts index 92c14ade791cd..419e80ad1608f 100644 --- a/src/plugins/es_ui_shared/public/console_lang/lib/json_xjson_translation_tools/__tests__/json_xjson_translation_tools.test.ts +++ b/src/plugins/es_ui_shared/public/console_lang/lib/json_xjson_translation_tools/__tests__/json_xjson_translation_tools.test.ts @@ -36,7 +36,7 @@ describe('JSON to XJSON conversion tools', () => { }); }); -_.each(collapsingTests.split(/^=+$/m), function(fixture) { +_.each(collapsingTests.split(/^=+$/m), function (fixture) { if (fixture.trim() === '') { return; } @@ -45,12 +45,12 @@ _.each(collapsingTests.split(/^=+$/m), function(fixture) { const expanded = fixture[1].trim(); const collapsed = fixture[2].trim(); - test('Literal collapse - ' + name, function() { + test('Literal collapse - ' + name, function () { expect(utils.collapseLiteralStrings(expanded)).toEqual(collapsed); }); }); -_.each(expandingTests.split(/^=+$/m), function(fixture) { +_.each(expandingTests.split(/^=+$/m), function (fixture) { if (fixture.trim() === '') { return; } @@ -59,7 +59,7 @@ _.each(expandingTests.split(/^=+$/m), function(fixture) { const collapsed = fixture[1].trim(); const expanded = fixture[2].trim(); - test('Literal expand - ' + name, function() { + test('Literal expand - ' + name, function () { expect(utils.expandLiteralStrings(collapsed)).toEqual(expanded); }); }); diff --git a/src/plugins/es_ui_shared/public/indices/validate/validate_index.test.ts b/src/plugins/es_ui_shared/public/indices/validate/validate_index.test.ts index cf81a2abebabf..a6792543cd726 100644 --- a/src/plugins/es_ui_shared/public/indices/validate/validate_index.test.ts +++ b/src/plugins/es_ui_shared/public/indices/validate/validate_index.test.ts @@ -39,7 +39,7 @@ describe('Index name validation', () => { }); it('should not allow illegal characters', () => { - INDEX_ILLEGAL_CHARACTERS_VISIBLE.forEach(char => { + INDEX_ILLEGAL_CHARACTERS_VISIBLE.forEach((char) => { const illegalCharacters = findIllegalCharactersInIndexName(`name${char}`); expect(illegalCharacters).toEqual([char]); }); diff --git a/src/plugins/es_ui_shared/public/request/request.test.js b/src/plugins/es_ui_shared/public/request/request.test.js index cc554b531d88a..190c32517eefe 100644 --- a/src/plugins/es_ui_shared/public/request/request.test.js +++ b/src/plugins/es_ui_shared/public/request/request.test.js @@ -31,11 +31,11 @@ const TestHook = ({ callback }) => { let element; -const testHook = callback => { +const testHook = (callback) => { element = mount(); }; -const wait = async wait => new Promise(resolve => setTimeout(resolve, wait || 1)); +const wait = async (wait) => new Promise((resolve) => setTimeout(resolve, wait || 1)); // FLAKY: // - https://github.com/elastic/kibana/issues/42561 diff --git a/src/plugins/es_ui_shared/static/forms/components/fields/combobox_field.tsx b/src/plugins/es_ui_shared/static/forms/components/fields/combobox_field.tsx index a10da62fa6906..9fb804eb7fafa 100644 --- a/src/plugins/es_ui_shared/static/forms/components/fields/combobox_field.tsx +++ b/src/plugins/es_ui_shared/static/forms/components/fields/combobox_field.tsx @@ -70,7 +70,7 @@ export const ComboBoxField = ({ field, euiFieldProps = {}, ...rest }: Props) => }; const onComboChange = (options: EuiComboBoxOptionOption[]) => { - field.setValue(options.map(option => option.label)); + field.setValue(options.map((option) => option.label)); }; const onSearchComboChange = (value: string) => { @@ -95,7 +95,7 @@ export const ComboBoxField = ({ field, euiFieldProps = {}, ...rest }: Props) => placeholder={i18n.translate('esUi.forms.comboBoxField.placeHolderText', { defaultMessage: 'Type and then hit "ENTER"', })} - selectedOptions={(field.value as any[]).map(v => ({ label: v }))} + selectedOptions={(field.value as any[]).map((v) => ({ label: v }))} onCreateOption={onCreateComboOption} onChange={onComboChange} onSearchChange={onSearchComboChange} diff --git a/src/plugins/es_ui_shared/static/forms/components/fields/json_editor_field.tsx b/src/plugins/es_ui_shared/static/forms/components/fields/json_editor_field.tsx index 9cd5cb3d0f2b9..fd57e098cf806 100644 --- a/src/plugins/es_ui_shared/static/forms/components/fields/json_editor_field.tsx +++ b/src/plugins/es_ui_shared/static/forms/components/fields/json_editor_field.tsx @@ -34,7 +34,7 @@ export const JsonEditorField = ({ field, ...rest }: Props) => { const { label, helpText, value, setValue } = field; const onJsonUpdate: OnJsonEditorUpdateHandler = useCallback( - updatedJson => { + (updatedJson) => { setValue(updatedJson.data.raw); }, [setValue] diff --git a/src/plugins/es_ui_shared/static/forms/components/fields/multi_select_field.tsx b/src/plugins/es_ui_shared/static/forms/components/fields/multi_select_field.tsx index e77337e4ecf53..a33c8009802ee 100644 --- a/src/plugins/es_ui_shared/static/forms/components/fields/multi_select_field.tsx +++ b/src/plugins/es_ui_shared/static/forms/components/fields/multi_select_field.tsx @@ -45,7 +45,7 @@ export const MultiSelectField = ({ field, euiFieldProps = {}, ...rest }: Props) { + onChange={(options) => { field.setValue(options); }} options={field.value as any[]} diff --git a/src/plugins/es_ui_shared/static/forms/components/fields/select_field.tsx b/src/plugins/es_ui_shared/static/forms/components/fields/select_field.tsx index 6e6aeb4de18fe..c22394435be83 100644 --- a/src/plugins/es_ui_shared/static/forms/components/fields/select_field.tsx +++ b/src/plugins/es_ui_shared/static/forms/components/fields/select_field.tsx @@ -50,7 +50,7 @@ export const SelectField = ({ field, euiFieldProps, ...rest }: Props) => { { + onChange={(e) => { field.setValue(e.target.value); }} options={[]} diff --git a/src/plugins/es_ui_shared/static/forms/components/fields/super_select_field.tsx b/src/plugins/es_ui_shared/static/forms/components/fields/super_select_field.tsx index 14a468613ec56..46e2d663eb324 100644 --- a/src/plugins/es_ui_shared/static/forms/components/fields/super_select_field.tsx +++ b/src/plugins/es_ui_shared/static/forms/components/fields/super_select_field.tsx @@ -48,7 +48,7 @@ export const SuperSelectField = ({ field, euiFieldProps = { options: [] }, ...re { + onChange={(value) => { field.setValue(value); }} isInvalid={isInvalid} diff --git a/src/plugins/es_ui_shared/static/forms/helpers/de_serializers.ts b/src/plugins/es_ui_shared/static/forms/helpers/de_serializers.ts index 274aa82b31834..a3ee2b8b84189 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/de_serializers.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/de_serializers.ts @@ -25,13 +25,13 @@ export const multiSelectComponent: Record = { // This deSerializer takes the previously selected options and map them // against the default select options values. selectedValueToOptions(selectOptions) { - return defaultFormValue => { + return (defaultFormValue) => { // If there are no default form value, it means that no previous value has been selected. if (!defaultFormValue) { return selectOptions; } - return (selectOptions as EuiSelectableOption[]).map(option => ({ + return (selectOptions as EuiSelectableOption[]).map((option) => ({ ...option, checked: (defaultFormValue as string[]).includes(option.label) ? 'on' : undefined, })); diff --git a/src/plugins/es_ui_shared/static/forms/helpers/serializers.ts b/src/plugins/es_ui_shared/static/forms/helpers/serializers.ts index bae6b4c2652ca..98287f6bac35d 100644 --- a/src/plugins/es_ui_shared/static/forms/helpers/serializers.ts +++ b/src/plugins/es_ui_shared/static/forms/helpers/serializers.ts @@ -46,7 +46,7 @@ export const multiSelectComponent: Record> = { * @param value The Eui Selectable options array */ optionsToSelectedValue(options: EuiSelectableOption[]): string[] { - return options.filter(option => option.checked === 'on').map(option => option.label); + return options.filter((option) => option.checked === 'on').map((option) => option.label); }, }; diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.test.tsx b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.test.tsx index 8b11b619ea8e0..3e4ce4a412b3b 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.test.tsx +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.test.tsx @@ -38,7 +38,7 @@ describe('', () => { - {formData => { + {(formData) => { onFormData(formData); return null; }} @@ -106,7 +106,7 @@ describe('', () => { - {formData => { + {(formData) => { onFormData(formData); return null; }} @@ -145,7 +145,7 @@ describe('', () => { - {formData => { + {(formData) => { onFormData(formData); return null; }} diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.ts index ddf2212490476..4c4a7f0642022 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.ts @@ -42,7 +42,7 @@ export const FormDataProvider = React.memo(({ children, pathsToWatch }: Props) = ? (pathsToWatch as string[]) : ([pathsToWatch] as string[]); - if (valuesToWatchArray.some(value => previousRawData.current[value] !== raw[value])) { + if (valuesToWatchArray.some((value) => previousRawData.current[value] !== raw[value])) { previousRawData.current = raw; setFormData(raw); } diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_array.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_array.ts index 3f71f83c55694..1605c09f575f6 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_array.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_array.ts @@ -93,15 +93,15 @@ export const UseArray = ({ ); const addItem = () => { - setItems(previousItems => { + setItems((previousItems) => { const itemIndex = previousItems.length; return [...previousItems, getNewItemAtIndex(itemIndex)]; }); }; const removeItem = (id: number) => { - setItems(previousItems => { - const updatedItems = previousItems.filter(item => item.id !== id); + setItems((previousItems) => { + const updatedItems = previousItems.filter((item) => item.id !== id); return updatePaths(updatedItems); }); }; diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.tsx b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.tsx index 136f3e7ad5688..589879f37900e 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.tsx +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.tsx @@ -107,7 +107,7 @@ export const UseField = React.memo(UseFieldComp) as typeof UseFieldComp; * @param partialProps Partial props to apply to all instances */ export function getUseField(partialProps: Partial>) { - return function(props: Partial>) { + return function (props: Partial>) { const componentProps = { ...partialProps, ...props } as Props; return {...componentProps} />; }; diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_multi_fields.tsx b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_multi_fields.tsx index a81af924eb3bd..d69527e36249b 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_multi_fields.tsx +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_multi_fields.tsx @@ -41,7 +41,7 @@ export const UseMultiFields = ({ fields, children }: Props) => { const { id } = fieldsArray[index]; return ( - {field => { + {(field) => { hookFields[id] = field; return index === fieldsArray.length - 1 ? children(hookFields) : renderField(index + 1); }} diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/form_context.tsx b/src/plugins/es_ui_shared/static/forms/hook_form_lib/form_context.tsx index 5dcd076b41533..a7b8713a23a74 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/form_context.tsx +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/form_context.tsx @@ -32,7 +32,7 @@ export const FormProvider = ({ children, form }: Props) => ( {children} ); -export const useFormContext = function() { +export const useFormContext = function () { const context = useContext(FormContext) as FormHook; if (context === undefined) { throw new Error('useFormContext must be used within a '); diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.ts index 3814bbe62e120..9800af2398927 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.ts @@ -79,8 +79,8 @@ export const useField = ( ? (validationTypeToFilterOut as string[]) : ([validationTypeToFilterOut] as string[]); - return _errors.filter(error => - validationTypeToArray.every(_type => error.validationType !== _type) + return _errors.filter((error) => + validationTypeToArray.every((_type) => error.validationType !== _type) ); }; @@ -275,7 +275,7 @@ export const useField = ( // -- API // ---------------------------------- const clearErrors: FieldHook['clearErrors'] = (validationType = VALIDATION_TYPES.FIELD) => { - setErrors(previousErrors => filterErrors(previousErrors, validationType)); + setErrors((previousErrors) => filterErrors(previousErrors, validationType)); }; /** @@ -331,7 +331,7 @@ export const useField = ( * * @param newValue The new value to assign to the field */ - const setValue: FieldHook['setValue'] = newValue => { + const setValue: FieldHook['setValue'] = (newValue) => { if (isPristine) { setPristine(false); } @@ -340,8 +340,8 @@ export const useField = ( setStateValue(formattedValue); }; - const _setErrors: FieldHook['setErrors'] = _errors => { - setErrors(_errors.map(error => ({ validationType: VALIDATION_TYPES.FIELD, ...error }))); + const _setErrors: FieldHook['setErrors'] = (_errors) => { + setErrors(_errors.map((error) => ({ validationType: VALIDATION_TYPES.FIELD, ...error }))); }; /** @@ -349,7 +349,7 @@ export const useField = ( * * @param event Form input change event */ - const onChange: FieldHook['onChange'] = event => { + const onChange: FieldHook['onChange'] = (event) => { const newValue = {}.hasOwnProperty.call(event!.target, 'checked') ? event.target.checked : event.target.value; diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.ts index f539f306db700..f9286d99cbf80 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.ts @@ -73,7 +73,7 @@ export function useForm( useEffect(() => { return () => { - formUpdateSubscribers.current.forEach(subscription => subscription.unsubscribe()); + formUpdateSubscribers.current.forEach((subscription) => subscription.unsubscribe()); formUpdateSubscribers.current = []; isUnmounted.current = true; }; @@ -116,7 +116,7 @@ export function useForm( ) => { if (getDataOptions.unflatten) { const nonEmptyFields = stripEmptyFields(fieldsRefs.current); - const fieldsValue = mapFormFields(nonEmptyFields, field => field.__serializeOutput()); + const fieldsValue = mapFormFields(nonEmptyFields, (field) => field.__serializeOutput()); return serializer(unflattenObject(fieldsValue)) as T; } @@ -147,7 +147,7 @@ export function useForm( const updateFormValidity = () => { const fieldsArray = fieldsToArray(); - const areAllFieldsValidated = fieldsArray.every(field => field.isValidated); + const areAllFieldsValidated = fieldsArray.every((field) => field.isValidated); if (!areAllFieldsValidated) { // If *not* all the fiels have been validated, the validity of the form is unknown, thus still "undefined" @@ -160,10 +160,10 @@ export function useForm( return isFormValid; }; - const validateFields: FormHook['__validateFields'] = async fieldNames => { + const validateFields: FormHook['__validateFields'] = async (fieldNames) => { const fieldsToValidate = fieldNames - .map(name => fieldsRefs.current[name]) - .filter(field => field !== undefined); + .map((name) => fieldsRefs.current[name]) + .filter((field) => field !== undefined); if (fieldsToValidate.length === 0) { // Nothing to validate @@ -171,7 +171,7 @@ export function useForm( } const formData = getFormData({ unflatten: false }); - await Promise.all(fieldsToValidate.map(field => field.validate({ formData }))); + await Promise.all(fieldsToValidate.map((field) => field.validate({ formData }))); const isFormValid = updateFormValidity(); const areFieldsValid = fieldsToValidate.every(isFieldValid); @@ -181,7 +181,7 @@ export function useForm( const validateAllFields = async (): Promise => { const fieldsArray = fieldsToArray(); - const fieldsToValidate = fieldsArray.filter(field => !field.isValidated); + const fieldsToValidate = fieldsArray.filter((field) => !field.isValidated); let isFormValid: boolean | undefined = isValid; @@ -197,12 +197,12 @@ export function useForm( return isFormValid; } - ({ isFormValid } = await validateFields(fieldsToValidate.map(field => field.path))); + ({ isFormValid } = await validateFields(fieldsToValidate.map((field) => field.path))); return isFormValid!; }; - const addField: FormHook['__addField'] = field => { + const addField: FormHook['__addField'] = (field) => { fieldsRefs.current[field.path] = field; if (!{}.hasOwnProperty.call(getFormData$().value, field.path)) { @@ -211,11 +211,11 @@ export function useForm( } }; - const removeField: FormHook['__removeField'] = _fieldNames => { + const removeField: FormHook['__removeField'] = (_fieldNames) => { const fieldNames = Array.isArray(_fieldNames) ? _fieldNames : [_fieldNames]; const currentFormData = { ...getFormData$().value } as FormData; - fieldNames.forEach(name => { + fieldNames.forEach((name) => { delete fieldsRefs.current[name]; delete currentFormData[name]; }); @@ -245,16 +245,16 @@ export function useForm( const getFields: FormHook['getFields'] = () => fieldsRefs.current; - const getFieldDefaultValue: FormHook['getFieldDefaultValue'] = fieldName => + const getFieldDefaultValue: FormHook['getFieldDefaultValue'] = (fieldName) => get(defaultValueDeserialized, fieldName); - const readFieldConfigFromSchema: FormHook['__readFieldConfigFromSchema'] = fieldName => { + const readFieldConfigFromSchema: FormHook['__readFieldConfigFromSchema'] = (fieldName) => { const config = (get(schema ? schema : {}, fieldName) as FieldConfig) || {}; return config; }; - const submitForm: FormHook['submit'] = async e => { + const submitForm: FormHook['submit'] = async (e) => { if (e) { e.preventDefault(); } @@ -278,8 +278,8 @@ export function useForm( return { data: formData, isValid: isFormValid! }; }; - const subscribe: FormHook['subscribe'] = handler => { - const subscription = getFormData$().subscribe(raw => { + const subscribe: FormHook['subscribe'] = (handler) => { + const subscription = getFormData$().subscribe((raw) => { if (!isUnmounted.current) { handler({ isValid, data: { raw, format: getFormData }, validate: validateAllFields }); } @@ -290,7 +290,7 @@ export function useForm( return { unsubscribe() { formUpdateSubscribers.current = formUpdateSubscribers.current.filter( - sub => sub !== subscription + (sub) => sub !== subscription ); return subscription.unsubscribe(); }, diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/subject.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/subject.ts index c805a9ca40e63..8f516c9c8a46f 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/subject.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/subject.ts @@ -49,7 +49,7 @@ export class Subject { next(value: T) { if (value !== this.value) { this.value = value; - this.callbacks.forEach(fn => fn(value)); + this.callbacks.forEach((fn) => fn(value)); } } } diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/shared_imports.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/shared_imports.ts index f54a648fb2fb9..f9f718b8b2f33 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/shared_imports.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/shared_imports.ts @@ -17,8 +17,6 @@ * under the License. */ -export { - registerTestBed, - getRandomString, - TestBed, -} from '../../../__packages_do_not_import__/test_utils_temp'; +export { registerTestBed, TestBed } from '../../../../../test_utils/public/testbed'; + +export { getRandomString } from '../../../../../test_utils/public/helpers'; diff --git a/src/plugins/expressions/common/execution/container.ts b/src/plugins/expressions/common/execution/container.ts index d6271869134d1..6302c0adb550b 100644 --- a/src/plugins/expressions/common/execution/container.ts +++ b/src/plugins/expressions/common/execution/container.ts @@ -66,16 +66,16 @@ export interface ExecutionPureTransitions { } export const executionPureTransitions: ExecutionPureTransitions = { - start: state => () => ({ + start: (state) => () => ({ ...state, state: 'pending', }), - setResult: state => result => ({ + setResult: (state) => (result) => ({ ...state, state: 'result', result, }), - setError: state => error => ({ + setError: (state) => (error) => ({ ...state, state: 'error', error, diff --git a/src/plugins/expressions/common/execution/execution.test.ts b/src/plugins/expressions/common/execution/execution.test.ts index 4776204a8ab2f..6a2f4bb269ff3 100644 --- a/src/plugins/expressions/common/execution/execution.test.ts +++ b/src/plugins/expressions/common/execution/execution.test.ts @@ -264,9 +264,9 @@ describe('Execution', () => { expect(execution.state.get().result).toBe(undefined); execution.start(null); expect(execution.state.get().result).toBe(undefined); - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); expect(execution.state.get().result).toBe(undefined); - await new Promise(r => setTimeout(r, 11)); + await new Promise((r) => setTimeout(r, 11)); expect(execution.state.get().result).toBe(null); }); }); diff --git a/src/plugins/expressions/common/execution/execution.ts b/src/plugins/expressions/common/execution/execution.ts index 6ee12d97a6422..7bfb14b8bfa1c 100644 --- a/src/plugins/expressions/common/execution/execution.ts +++ b/src/plugins/expressions/common/execution/execution.ts @@ -193,16 +193,16 @@ export class Execution< const { resolve, reject } = this.firstResultFuture; const chainPromise = this.invokeChain(this.state.get().ast.chain, input); - this.race(chainPromise).then(resolve, error => { + this.race(chainPromise).then(resolve, (error) => { if (this.abortController.signal.aborted) resolve(createAbortErrorValue()); else reject(error); }); this.firstResultFuture.promise.then( - result => { + (result) => { this.state.transitions.setResult(result); }, - error => { + (error) => { this.state.transitions.setError(error); } ); @@ -396,7 +396,7 @@ export class Execution< // Actually resolve unless the argument definition says not to const resolvedArgValues = await Promise.all( - argNames.map(argName => { + argNames.map((argName) => { const interpretFns = resolveArgFns[argName]; if (!argDefs[argName].resolve) return interpretFns; return Promise.all(interpretFns.map((fn: any) => fn())); diff --git a/src/plugins/expressions/common/executor/container.ts b/src/plugins/expressions/common/executor/container.ts index c9c1ab34e7ac3..fea58ec6294de 100644 --- a/src/plugins/expressions/common/executor/container.ts +++ b/src/plugins/expressions/common/executor/container.ts @@ -43,9 +43,9 @@ export interface ExecutorPureTransitions { } export const pureTransitions: ExecutorPureTransitions = { - addFunction: state => fn => ({ ...state, functions: { ...state.functions, [fn.name]: fn } }), - addType: state => type => ({ ...state, types: { ...state.types, [type.name]: type } }), - extendContext: state => extraContext => ({ + addFunction: (state) => (fn) => ({ ...state, functions: { ...state.functions, [fn.name]: fn } }), + addType: (state) => (type) => ({ ...state, types: { ...state.types, [type.name]: type } }), + extendContext: (state) => (extraContext) => ({ ...state, context: { ...state.context, ...extraContext }, }), @@ -58,8 +58,8 @@ export interface ExecutorPureSelectors { } export const pureSelectors: ExecutorPureSelectors = { - getFunction: state => id => state.functions[id] || null, - getType: state => id => state.types[id] || null, + getFunction: (state) => (id) => state.functions[id] || null, + getType: (state) => (id) => state.types[id] || null, getContext: ({ context }) => () => context, }; diff --git a/src/plugins/expressions/common/executor/executor.test.ts b/src/plugins/expressions/common/executor/executor.test.ts index 4e43cedd18157..81845401d32e4 100644 --- a/src/plugins/expressions/common/executor/executor.test.ts +++ b/src/plugins/expressions/common/executor/executor.test.ts @@ -51,7 +51,7 @@ describe('Executor', () => { for (const type of expressionTypes.typeSpecs) executor.registerType(type); const types = executor.getTypes(); expect(Object.keys(types).sort()).toEqual( - expressionTypes.typeSpecs.map(spec => spec.name).sort() + expressionTypes.typeSpecs.map((spec) => spec.name).sort() ); }); }); @@ -81,7 +81,7 @@ describe('Executor', () => { executor.registerFunction(functionDefinition); const functions = executor.getFunctions(); expect(Object.keys(functions).sort()).toEqual( - expressionFunctions.functionSpecs.map(spec => spec.name).sort() + expressionFunctions.functionSpecs.map((spec) => spec.name).sort() ); }); }); diff --git a/src/plugins/expressions/common/expression_functions/specs/font.ts b/src/plugins/expressions/common/expression_functions/specs/font.ts index 3e305998a0157..c8016bfacc710 100644 --- a/src/plugins/expressions/common/expression_functions/specs/font.ts +++ b/src/plugins/expressions/common/expression_functions/specs/font.ts @@ -26,14 +26,14 @@ const dashify = (str: string) => { return str .trim() .replace(/([a-z])([A-Z])/g, '$1-$2') - .replace(/\W/g, m => (/[À-ž]/.test(m) ? m : '-')) + .replace(/\W/g, (m) => (/[À-ž]/.test(m) ? m : '-')) .replace(/^-+|-+$/g, '') .toLowerCase(); }; const inlineStyle = (obj: Record) => { if (!obj) return ''; - const styles = Object.keys(obj).map(key => { + const styles = Object.keys(obj).map((key) => { const prop = dashify(key); const line = prop.concat(':').concat(String(obj[key])); return line; @@ -123,7 +123,7 @@ export const font: ExpressionFunctionDefinition<'font', null, Arguments, Style> values: { list: Object.values(FontWeight) .slice(0, -1) - .map(weight => `\`"${weight}"\``) + .map((weight) => `\`"${weight}"\``) .join(', '), end: `\`"${Object.values(FontWeight).slice(-1)[0]}"\``, }, diff --git a/src/plugins/expressions/common/expression_functions/specs/tests/utils.ts b/src/plugins/expressions/common/expression_functions/specs/tests/utils.ts index bc721a772d50f..016208aefdfc6 100644 --- a/src/plugins/expressions/common/expression_functions/specs/tests/utils.ts +++ b/src/plugins/expressions/common/expression_functions/specs/tests/utils.ts @@ -26,7 +26,7 @@ import { ExecutionContext } from '../../../execution/types'; * overriding with any provided args. */ export const functionWrapper = (spec: AnyExpressionFunctionDefinition) => { - const defaultArgs = mapValues(spec.args, argSpec => argSpec.default); + const defaultArgs = mapValues(spec.args, (argSpec) => argSpec.default); return ( context: object | null, args: Record = {}, diff --git a/src/plugins/expressions/common/expression_types/expression_type.test.ts b/src/plugins/expressions/common/expression_types/expression_type.test.ts index a692ec9501cc5..b94d9a305121f 100644 --- a/src/plugins/expressions/common/expression_types/expression_type.test.ts +++ b/src/plugins/expressions/common/expression_types/expression_type.test.ts @@ -25,8 +25,8 @@ export const boolean: ExpressionTypeDefinition<'boolean', boolean> = { name: 'boolean', from: { null: () => false, - number: n => Boolean(n), - string: s => Boolean(s), + number: (n) => Boolean(n), + string: (s) => Boolean(s), }, to: { render: (value): ExpressionValueRender<{ text: string }> => { diff --git a/src/plugins/expressions/common/expression_types/specs/boolean.ts b/src/plugins/expressions/common/expression_types/specs/boolean.ts index fee4608418406..d730f95d7c423 100644 --- a/src/plugins/expressions/common/expression_types/specs/boolean.ts +++ b/src/plugins/expressions/common/expression_types/specs/boolean.ts @@ -27,8 +27,8 @@ export const boolean: ExpressionTypeDefinition<'boolean', boolean> = { name, from: { null: () => false, - number: n => Boolean(n), - string: s => Boolean(s), + number: (n) => Boolean(n), + string: (s) => Boolean(s), }, to: { render: (value): ExpressionValueRender<{ text: string }> => { diff --git a/src/plugins/expressions/common/expression_types/specs/datatable.ts b/src/plugins/expressions/common/expression_types/specs/datatable.ts index 92254a3d02438..c113765f8e7e7 100644 --- a/src/plugins/expressions/common/expression_types/specs/datatable.ts +++ b/src/plugins/expressions/common/expression_types/specs/datatable.ts @@ -72,7 +72,7 @@ interface RenderedDatatable { export const datatable: ExpressionTypeDefinition = { name, - validate: table => { + validate: (table) => { // TODO: Check columns types. Only string, boolean, number, date, allowed for now. if (!table.columns) { throw new Error('datatable must have a columns array, even if it is empty'); @@ -82,20 +82,20 @@ export const datatable: ExpressionTypeDefinition { + serialize: (table) => { const { columns, rows } = table; return { ...table, - rows: rows.map(row => { - return columns.map(column => row[column.name]); + rows: rows.map((row) => { + return columns.map((column) => row[column.name]); }), }; }, - deserialize: table => { + deserialize: (table) => { const { columns, rows } = table; return { ...table, - rows: rows.map(row => { + rows: rows.map((row) => { return zipObject(map(columns, 'name'), row); }), }; @@ -127,8 +127,8 @@ export const datatable: ExpressionTypeDefinition { const validFields = ['x', 'y', 'color', 'size', 'text']; - const columns = table.columns.filter(column => validFields.includes(column.name)); - const rows = table.rows.map(row => pick(row, validFields)); + const columns = table.columns.filter((column) => validFields.includes(column.name)); + const rows = table.rows.map((row) => pick(row, validFields)); return { type: 'pointseries', columns: columns.reduce>((acc, column) => { diff --git a/src/plugins/expressions/common/expression_types/specs/kibana_datatable.ts b/src/plugins/expressions/common/expression_types/specs/kibana_datatable.ts index 7742594d751de..7f2f3c37c587c 100644 --- a/src/plugins/expressions/common/expression_types/specs/kibana_datatable.ts +++ b/src/plugins/expressions/common/expression_types/specs/kibana_datatable.ts @@ -53,7 +53,7 @@ export const kibanaDatatable = { return { type: name, rows: context.rows, - columns: context.columns.map(column => { + columns: context.columns.map((column) => { return { id: column.name, name: column.name, diff --git a/src/plugins/expressions/common/expression_types/specs/num.ts b/src/plugins/expressions/common/expression_types/specs/num.ts index 99b3bc3419173..191e617fdc858 100644 --- a/src/plugins/expressions/common/expression_types/specs/num.ts +++ b/src/plugins/expressions/common/expression_types/specs/num.ts @@ -36,11 +36,11 @@ export const num: ExpressionTypeDefinition<'num', ExpressionValueNum> = { type: 'num', value: 0, }), - boolean: b => ({ + boolean: (b) => ({ type: 'num', value: Number(b), }), - string: n => { + string: (n) => { const value = Number(n); if (Number.isNaN(value)) { throw new Error( @@ -57,7 +57,7 @@ export const num: ExpressionTypeDefinition<'num', ExpressionValueNum> = { value, }; }, - '*': value => ({ + '*': (value) => ({ type: 'num', value: Number(value), }), diff --git a/src/plugins/expressions/common/expression_types/specs/number.ts b/src/plugins/expressions/common/expression_types/specs/number.ts index f346ae837adb4..10986659c7848 100644 --- a/src/plugins/expressions/common/expression_types/specs/number.ts +++ b/src/plugins/expressions/common/expression_types/specs/number.ts @@ -28,8 +28,8 @@ export const number: ExpressionTypeDefinition = { name, from: { null: () => 0, - boolean: b => Number(b), - string: n => { + boolean: (b) => Number(b), + string: (n) => { const value = Number(n); if (Number.isNaN(value)) { throw new Error( diff --git a/src/plugins/expressions/common/expression_types/specs/shape.ts b/src/plugins/expressions/common/expression_types/specs/shape.ts index 315838043cb49..80ac67c84c3c0 100644 --- a/src/plugins/expressions/common/expression_types/specs/shape.ts +++ b/src/plugins/expressions/common/expression_types/specs/shape.ts @@ -25,7 +25,7 @@ const name = 'shape'; export const shape: ExpressionTypeDefinition> = { name: 'shape', to: { - render: input => { + render: (input) => { return { type: 'render', as: name, diff --git a/src/plugins/expressions/common/expression_types/specs/string.ts b/src/plugins/expressions/common/expression_types/specs/string.ts index d46f0e5f6b7c2..46f460891c2fb 100644 --- a/src/plugins/expressions/common/expression_types/specs/string.ts +++ b/src/plugins/expressions/common/expression_types/specs/string.ts @@ -27,8 +27,8 @@ export const string: ExpressionTypeDefinition = { name, from: { null: () => '', - boolean: b => String(b), - number: n => String(n), + boolean: (b) => String(b), + number: (n) => String(n), }, to: { render: (text: T): ExpressionValueRender<{ text: T }> => { diff --git a/src/plugins/expressions/common/test_helpers/expression_functions/sleep.ts b/src/plugins/expressions/common/test_helpers/expression_functions/sleep.ts index e9ff6e0698560..f269c0ea19934 100644 --- a/src/plugins/expressions/common/test_helpers/expression_functions/sleep.ts +++ b/src/plugins/expressions/common/test_helpers/expression_functions/sleep.ts @@ -30,7 +30,7 @@ export const sleep: ExpressionFunctionDefinition<'sleep', any, { time: number }, }, help: '', fn: async (input, args, context) => { - await new Promise(r => setTimeout(r, args.time)); + await new Promise((r) => setTimeout(r, args.time)); return input; }, }; diff --git a/src/plugins/expressions/common/util/get_by_alias.ts b/src/plugins/expressions/common/util/get_by_alias.ts index 6868abb5da923..35a98871afabc 100644 --- a/src/plugins/expressions/common/util/get_by_alias.ts +++ b/src/plugins/expressions/common/util/get_by_alias.ts @@ -30,7 +30,7 @@ export function getByAlias( return Object.values(node).find(({ name, aliases }) => { if (!name) return false; if (name.toLowerCase() === lowerCaseName) return true; - return (aliases || []).some(alias => { + return (aliases || []).some((alias) => { return alias.toLowerCase() === lowerCaseName; }); }); diff --git a/src/plugins/expressions/public/loader.ts b/src/plugins/expressions/public/loader.ts index 418ff6fdf8614..9428d7db1d9d0 100644 --- a/src/plugins/expressions/public/loader.ts +++ b/src/plugins/expressions/public/loader.ts @@ -56,7 +56,7 @@ export class ExpressionLoader { // as loading$ could emit straight away in the constructor // and we want to notify subscribers about it, but all subscriptions will happen later this.loading$ = this.loadingSubject.asObservable().pipe( - filter(_ => _ === true), + filter((_) => _ === true), map(() => void 0) ); @@ -67,14 +67,14 @@ export class ExpressionLoader { this.update$ = this.renderHandler.update$; this.events$ = this.renderHandler.events$; - this.update$.subscribe(value => { + this.update$.subscribe((value) => { if (value) { const { newExpression, newParams } = value; this.update(newExpression, newParams); } }); - this.data$.subscribe(data => { + this.data$.subscribe((data) => { this.render(data); }); diff --git a/src/plugins/expressions/public/mocks.tsx b/src/plugins/expressions/public/mocks.tsx index b8f2f693e9c77..3a5ece271c4ee 100644 --- a/src/plugins/expressions/public/mocks.tsx +++ b/src/plugins/expressions/public/mocks.tsx @@ -75,7 +75,7 @@ const createStartContract = (): Start => { getType: jest.fn(), getTypes: jest.fn(), loader: jest.fn(), - ReactExpressionRenderer: jest.fn(props => <>), + ReactExpressionRenderer: jest.fn((props) => <>), render: jest.fn(), run: jest.fn(), }; diff --git a/src/plugins/expressions/public/plugin.ts b/src/plugins/expressions/public/plugin.ts index 720c3b701d504..ec60fbdf44c3a 100644 --- a/src/plugins/expressions/public/plugin.ts +++ b/src/plugins/expressions/public/plugin.ts @@ -145,7 +145,7 @@ export class ExpressionsPublicPlugin // For every sever-side function, register a client-side // function that matches its definition, but which simply // calls the server-side function endpoint. - Object.keys(serverFunctionList).forEach(functionName => { + Object.keys(serverFunctionList).forEach((functionName) => { if (expressionsSetup.getFunction(functionName)) { return; } diff --git a/src/plugins/expressions/public/react_expression_renderer.test.tsx b/src/plugins/expressions/public/react_expression_renderer.test.tsx index caa9bc68dffb8..702f88d785756 100644 --- a/src/plugins/expressions/public/react_expression_renderer.test.tsx +++ b/src/plugins/expressions/public/react_expression_renderer.test.tsx @@ -111,7 +111,7 @@ describe('ExpressionRenderer', () => { const instance = mount(
{message}
} + renderError={(message) =>
{message}
} /> ); diff --git a/src/plugins/expressions/public/react_expression_renderer.tsx b/src/plugins/expressions/public/react_expression_renderer.tsx index 9e237d36ef627..a83c63443906b 100644 --- a/src/plugins/expressions/public/react_expression_renderer.tsx +++ b/src/plugins/expressions/public/react_expression_renderer.tsx @@ -104,7 +104,7 @@ export const ReactExpressionRenderer = ({ }); if (onEvent) { subs.push( - expressionLoaderRef.current.events$.subscribe(event => { + expressionLoaderRef.current.events$.subscribe((event) => { onEvent(event); }) ); @@ -112,11 +112,11 @@ export const ReactExpressionRenderer = ({ subs.push( expressionLoaderRef.current.loading$.subscribe(() => { hasHandledErrorRef.current = false; - setState(prevState => ({ ...prevState, isLoading: true })); + setState((prevState) => ({ ...prevState, isLoading: true })); }), expressionLoaderRef.current.render$ .pipe(filter(() => !hasHandledErrorRef.current)) - .subscribe(item => { + .subscribe((item) => { setState(() => ({ ...defaultState, isEmpty: false, @@ -125,7 +125,7 @@ export const ReactExpressionRenderer = ({ ); return () => { - subs.forEach(s => s.unsubscribe()); + subs.forEach((s) => s.unsubscribe()); if (expressionLoaderRef.current) { expressionLoaderRef.current.destroy(); expressionLoaderRef.current = null; diff --git a/src/plugins/expressions/public/render.test.ts b/src/plugins/expressions/public/render.test.ts index b9601f6d1e920..4e79d0d03ace1 100644 --- a/src/plugins/expressions/public/render.test.ts +++ b/src/plugins/expressions/public/render.test.ts @@ -128,8 +128,8 @@ describe('ExpressionRenderHandler', () => { it('sends a next observable once rendering is complete', () => { const expressionRenderHandler = new ExpressionRenderHandler(element); expect.assertions(1); - return new Promise(resolve => { - expressionRenderHandler.render$.subscribe(renderCount => { + return new Promise((resolve) => { + expressionRenderHandler.render$.subscribe((renderCount) => { expect(renderCount).toBe(1); resolve(); }); diff --git a/src/plugins/expressions/public/render.ts b/src/plugins/expressions/public/render.ts index c8a4022a01131..0d88b3d27f658 100644 --- a/src/plugins/expressions/public/render.ts +++ b/src/plugins/expressions/public/render.ts @@ -68,7 +68,7 @@ export class ExpressionRenderHandler { this.onRenderError = onRenderError || defaultRenderErrorHandler; this.renderSubject = new Rx.BehaviorSubject(null as any | null); - this.render$ = this.renderSubject.asObservable().pipe(filter(_ => _ !== null)) as Observable< + this.render$ = this.renderSubject.asObservable().pipe(filter((_) => _ !== null)) as Observable< any >; @@ -86,10 +86,10 @@ export class ExpressionRenderHandler { reload: () => { this.updateSubject.next(null); }, - update: params => { + update: (params) => { this.updateSubject.next(params); }, - event: data => { + event: (data) => { this.eventsSubject.next(data); }, }; diff --git a/src/plugins/expressions/server/legacy.ts b/src/plugins/expressions/server/legacy.ts index 1487f9f6734e9..4dd9419e59e2d 100644 --- a/src/plugins/expressions/server/legacy.ts +++ b/src/plugins/expressions/server/legacy.ts @@ -114,7 +114,7 @@ export const createLegacyServerEndpoints = ( * Register an endpoint that executes a batch of functions, and streams the * results back using ND-JSON. */ - plugins.bfetch.addBatchProcessingRoute(`/api/interpreter/fns`, request => { + plugins.bfetch.addBatchProcessingRoute(`/api/interpreter/fns`, (request) => { return { onBatchItem: async (fnCall: any) => { const [coreStart] = await core.getStartServices(); diff --git a/src/plugins/home/public/application/components/feature_directory.js b/src/plugins/home/public/application/components/feature_directory.js index 7f685d9d7d804..e9ab348f164c7 100644 --- a/src/plugins/home/public/application/components/feature_directory.js +++ b/src/plugins/home/public/application/components/feature_directory.js @@ -40,7 +40,7 @@ import { createAppNavigationHandler } from './app_navigation_handler'; const ALL_TAB_ID = 'all'; const OTHERS_TAB_ID = 'others'; -const isOtherCategory = directory => { +const isOtherCategory = (directory) => { return ( directory.category !== FeatureCatalogueCategory.DATA && directory.category !== FeatureCatalogueCategory.ADMIN @@ -81,7 +81,7 @@ export class FeatureDirectory extends React.Component { }; } - onSelectedTabChanged = id => { + onSelectedTabChanged = (id) => { this.setState({ selectedTabId: id, }); @@ -102,7 +102,7 @@ export class FeatureDirectory extends React.Component { renderDirectories = () => { return this.props.directories - .filter(directory => { + .filter((directory) => { if (this.state.selectedTabId === ALL_TAB_ID) { return true; } @@ -111,7 +111,7 @@ export class FeatureDirectory extends React.Component { } return this.state.selectedTabId === directory.category; }) - .map(directory => { + .map((directory) => { return ( { + renderDirectories = (category) => { const { addBasePath, directories } = this.props; return directories - .filter(directory => { + .filter((directory) => { return directory.showOnHomePage && directory.category === category; }) - .map(directory => { + .map((directory) => { return ( { decrement: sinon.mock(), }, localStorage: { - getItem: sinon.spy(path => { + getItem: sinon.spy((path) => { expect(path).toEqual('home:welcome:show'); return 'false'; }), @@ -77,11 +77,11 @@ describe('home', () => { const component = shallow(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); return component; } diff --git a/src/plugins/home/public/application/components/home_app.js b/src/plugins/home/public/application/components/home_app.js index bbbb75cd664f7..648915b6dae0c 100644 --- a/src/plugins/home/public/application/components/home_app.js +++ b/src/plugins/home/public/application/components/home_app.js @@ -51,7 +51,7 @@ export function HomeApp({ directories }) { const mlEnabled = environment.ml; const apmUiEnabled = environment.apmUi; - const renderTutorialDirectory = props => { + const renderTutorialDirectory = (props) => { return ( { + const renderTutorial = (props) => { return ( { +const createRecentlyAccessed = (length) => { const recentlyAccessed = []; let i = 0; while (recentlyAccessed.length < length) { diff --git a/src/plugins/home/public/application/components/sample_data_set_cards.js b/src/plugins/home/public/application/components/sample_data_set_cards.js index 404c82676c1c3..255fc57054083 100644 --- a/src/plugins/home/public/application/components/sample_data_set_cards.js +++ b/src/plugins/home/public/application/components/sample_data_set_cards.js @@ -82,12 +82,12 @@ export class SampleDataSetCards extends React.Component { }); }; - install = async id => { - const targetSampleDataSet = this.state.sampleDataSets.find(sampleDataSet => { + install = async (id) => { + const targetSampleDataSet = this.state.sampleDataSets.find((sampleDataSet) => { return sampleDataSet.id === id; }); - this.setState(prevState => ({ + this.setState((prevState) => ({ processingStatus: { ...prevState.processingStatus, [id]: true }, })); @@ -95,7 +95,7 @@ export class SampleDataSetCards extends React.Component { await installSampleDataSet(id, targetSampleDataSet.defaultIndex); } catch (fetchError) { if (this._isMounted) { - this.setState(prevState => ({ + this.setState((prevState) => ({ processingStatus: { ...prevState.processingStatus, [id]: false }, })); } @@ -110,9 +110,9 @@ export class SampleDataSetCards extends React.Component { } if (this._isMounted) { - this.setState(prevState => ({ + this.setState((prevState) => ({ processingStatus: { ...prevState.processingStatus, [id]: false }, - sampleDataSets: prevState.sampleDataSets.map(sampleDataSet => { + sampleDataSets: prevState.sampleDataSets.map((sampleDataSet) => { if (sampleDataSet.id === id) { sampleDataSet.status = INSTALLED_STATUS; } @@ -130,12 +130,12 @@ export class SampleDataSetCards extends React.Component { }); }; - uninstall = async id => { - const targetSampleDataSet = this.state.sampleDataSets.find(sampleDataSet => { + uninstall = async (id) => { + const targetSampleDataSet = this.state.sampleDataSets.find((sampleDataSet) => { return sampleDataSet.id === id; }); - this.setState(prevState => ({ + this.setState((prevState) => ({ processingStatus: { ...prevState.processingStatus, [id]: true }, })); @@ -143,7 +143,7 @@ export class SampleDataSetCards extends React.Component { await uninstallSampleDataSet(id, targetSampleDataSet.defaultIndex); } catch (fetchError) { if (this._isMounted) { - this.setState(prevState => ({ + this.setState((prevState) => ({ processingStatus: { ...prevState.processingStatus, [id]: false }, })); } @@ -158,9 +158,9 @@ export class SampleDataSetCards extends React.Component { } if (this._isMounted) { - this.setState(prevState => ({ + this.setState((prevState) => ({ processingStatus: { ...prevState.processingStatus, [id]: false }, - sampleDataSets: prevState.sampleDataSets.map(sampleDataSet => { + sampleDataSets: prevState.sampleDataSets.map((sampleDataSet) => { if (sampleDataSet.id === id) { sampleDataSet.status = UNINSTALLED_STATUS; } @@ -178,7 +178,7 @@ export class SampleDataSetCards extends React.Component { }); }; - lightOrDarkImage = sampleDataSet => { + lightOrDarkImage = (sampleDataSet) => { return getServices().uiSettings.get('theme:darkMode') && sampleDataSet.darkPreviewImagePath ? sampleDataSet.darkPreviewImagePath : sampleDataSet.previewImagePath; @@ -187,7 +187,7 @@ export class SampleDataSetCards extends React.Component { render() { return ( - {this.state.sampleDataSets.map(sampleDataSet => { + {this.state.sampleDataSets.map((sampleDataSet) => { return ( { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; diff --git a/src/plugins/home/public/application/components/sample_data_view_data_button.test.js b/src/plugins/home/public/application/components/sample_data_view_data_button.test.js index f594ec1264c94..933a58c29ecb4 100644 --- a/src/plugins/home/public/application/components/sample_data_view_data_button.test.js +++ b/src/plugins/home/public/application/components/sample_data_view_data_button.test.js @@ -24,7 +24,7 @@ import { SampleDataViewDataButton } from './sample_data_view_data_button'; jest.mock('../kibana_services', () => ({ getServices: () => ({ - addBasePath: path => `root${path}`, + addBasePath: (path) => `root${path}`, }), })); diff --git a/src/plugins/home/public/application/components/tutorial/instruction.js b/src/plugins/home/public/application/components/tutorial/instruction.js index a44fb26bffbbb..e4b4e34a95662 100644 --- a/src/plugins/home/public/application/components/tutorial/instruction.js +++ b/src/plugins/home/public/application/components/tutorial/instruction.js @@ -52,13 +52,13 @@ export function Instruction({ commands, paramValues, textPost, textPre, replaceT let commandBlock; if (commands) { const cmdText = commands - .map(cmd => { + .map((cmd) => { return replaceTemplateStrings(cmd, paramValues); }) .join('\n'); copyButton = ( - {copy => ( + {(copy) => ( { + this.tabs = props.instructionVariants.map((variant) => { return { id: variant.id, name: getDisplayText(variant.id), @@ -60,10 +60,10 @@ class InstructionSetUi extends React.Component { } handleToggleVisibility = () => { - this.setState(prevState => ({ isParamFormVisible: !prevState.isParamFormVisible })); + this.setState((prevState) => ({ isParamFormVisible: !prevState.isParamFormVisible })); }; - onSelectedTabChanged = id => { + onSelectedTabChanged = (id) => { this.setState({ selectedTabId: id, }); @@ -182,7 +182,7 @@ class InstructionSetUi extends React.Component { } renderInstructions = () => { - const instructionVariant = this.props.instructionVariants.find(variant => { + const instructionVariant = this.props.instructionVariants.find((variant) => { return variant.id === this.state.selectedTabId; }); if (!instructionVariant) { diff --git a/src/plugins/home/public/application/components/tutorial/number_parameter.js b/src/plugins/home/public/application/components/tutorial/number_parameter.js index b3962385b332a..68475f9082bbf 100644 --- a/src/plugins/home/public/application/components/tutorial/number_parameter.js +++ b/src/plugins/home/public/application/components/tutorial/number_parameter.js @@ -21,7 +21,7 @@ import React from 'react'; import PropTypes from 'prop-types'; export function NumberParameter({ id, label, value, setParameter }) { - const handleChange = evt => { + const handleChange = (evt) => { setParameter(id, parseFloat(evt.target.value)); }; diff --git a/src/plugins/home/public/application/components/tutorial/parameter_form.js b/src/plugins/home/public/application/components/tutorial/parameter_form.js index 35db68abee427..99159ae12b16f 100644 --- a/src/plugins/home/public/application/components/tutorial/parameter_form.js +++ b/src/plugins/home/public/application/components/tutorial/parameter_form.js @@ -25,7 +25,7 @@ import { EuiPanel } from '@elastic/eui'; export class ParameterForm extends React.Component { renderInputs = () => { - return this.props.params.map(param => { + return this.props.params.map((param) => { switch (param.type) { case 'number': return ( diff --git a/src/plugins/home/public/application/components/tutorial/saved_objects_installer.js b/src/plugins/home/public/application/components/tutorial/saved_objects_installer.js index bf69c419f6464..790c6d9c2574e 100644 --- a/src/plugins/home/public/application/components/tutorial/saved_objects_installer.js +++ b/src/plugins/home/public/application/components/tutorial/saved_objects_installer.js @@ -90,11 +90,11 @@ class SavedObjectsInstallerUi extends React.Component { return; } - const errors = resp.savedObjects.filter(savedObject => { + const errors = resp.savedObjects.filter((savedObject) => { return Boolean(savedObject.error); }); - const overwriteErrors = errors.filter(savedObject => { + const overwriteErrors = errors.filter((savedObject) => { return savedObject.error.statusCode === 409; }); if (overwriteErrors.length > 0) { diff --git a/src/plugins/home/public/application/components/tutorial/saved_objects_installer.test.js b/src/plugins/home/public/application/components/tutorial/saved_objects_installer.test.js index b3f42436c48c2..6cc02184fbc16 100644 --- a/src/plugins/home/public/application/components/tutorial/saved_objects_installer.test.js +++ b/src/plugins/home/public/application/components/tutorial/saved_objects_installer.test.js @@ -52,7 +52,7 @@ describe('bulkCreate', () => { findTestSubject(component, 'loadSavedObjects').simulate('click'); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -73,7 +73,7 @@ describe('bulkCreate', () => { findTestSubject(component, 'loadSavedObjects').simulate('click'); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/src/plugins/home/public/application/components/tutorial/string_parameter.js b/src/plugins/home/public/application/components/tutorial/string_parameter.js index 0973737136cff..a99e39c298ecf 100644 --- a/src/plugins/home/public/application/components/tutorial/string_parameter.js +++ b/src/plugins/home/public/application/components/tutorial/string_parameter.js @@ -21,7 +21,7 @@ import React from 'react'; import PropTypes from 'prop-types'; export function StringParameter({ id, label, value, setParameter }) { - const handleChange = evt => { + const handleChange = (evt) => { setParameter(id, evt.target.value); }; diff --git a/src/plugins/home/public/application/components/tutorial/tutorial.js b/src/plugins/home/public/application/components/tutorial/tutorial.js index 762d7fde252a1..576f732278b8e 100644 --- a/src/plugins/home/public/application/components/tutorial/tutorial.js +++ b/src/plugins/home/public/application/components/tutorial/tutorial.js @@ -147,7 +147,7 @@ class TutorialUi extends React.Component { const paramValues = {}; if (instructions.params) { - instructions.params.forEach(param => { + instructions.params.forEach((param) => { paramValues[param.id] = param.defaultValue; }); } @@ -162,7 +162,7 @@ class TutorialUi extends React.Component { }); }; - setVisibleInstructions = instructionsType => { + setVisibleInstructions = (instructionsType) => { this.setState( { visibleInstructions: instructionsType, @@ -172,21 +172,21 @@ class TutorialUi extends React.Component { }; setParameter = (paramId, newValue) => { - this.setState(previousState => { + this.setState((previousState) => { const paramValues = _.cloneDeep(previousState.paramValues); paramValues[paramId] = newValue; return { paramValues: paramValues }; }); }; - checkInstructionSetStatus = async instructionSetIndex => { + checkInstructionSetStatus = async (instructionSetIndex) => { const instructionSet = this.getInstructionSets()[instructionSetIndex]; const esHitsCheckConfig = _.get(instructionSet, `statusCheck.esHitsCheck`); if (esHitsCheckConfig) { const statusCheckState = await this.fetchEsHitsStatus(esHitsCheckConfig); - this.setState(prevState => ({ + this.setState((prevState) => ({ statusCheckStates: { ...prevState.statusCheckStates, [instructionSetIndex]: statusCheckState, @@ -200,7 +200,7 @@ class TutorialUi extends React.Component { * @param esHitsCheckConfig * @return {Promise} */ - fetchEsHitsStatus = async esHitsCheckConfig => { + fetchEsHitsStatus = async (esHitsCheckConfig) => { const searchHeader = JSON.stringify({ index: esHitsCheckConfig.index }); const searchBody = JSON.stringify({ query: esHitsCheckConfig.query, size: 1 }); const response = await fetch(this.props.addBasePath('/elasticsearch/_msearch'), { @@ -260,9 +260,9 @@ class TutorialUi extends React.Component { } }; - onStatusCheck = instructionSetIndex => { + onStatusCheck = (instructionSetIndex) => { this.setState( - prevState => ({ + (prevState) => ({ statusCheckStates: { ...prevState.statusCheckStates, [instructionSetIndex]: StatusCheckStates.FETCHING, @@ -272,7 +272,7 @@ class TutorialUi extends React.Component { ); }; - renderInstructionSets = instructions => { + renderInstructionSets = (instructions) => { let offset = 1; return instructions.instructionSets.map((instructionSet, index) => { const currentOffset = offset; @@ -320,7 +320,7 @@ class TutorialUi extends React.Component { label = this.state.tutorial.artifacts.application.label; url = this.props.addBasePath(this.state.tutorial.artifacts.application.path); } else if (_.has(this.state, 'tutorial.artifacts.dashboards')) { - const overviewDashboard = this.state.tutorial.artifacts.dashboards.find(dashboard => { + const overviewDashboard = this.state.tutorial.artifacts.dashboards.find((dashboard) => { return dashboard.isOverview; }); if (overviewDashboard) { diff --git a/src/plugins/home/public/application/components/tutorial/tutorial.test.js b/src/plugins/home/public/application/components/tutorial/tutorial.test.js index 41d83d7562f6e..23b0dc50018c1 100644 --- a/src/plugins/home/public/application/components/tutorial/tutorial.test.js +++ b/src/plugins/home/public/application/components/tutorial/tutorial.test.js @@ -67,10 +67,10 @@ const loadTutorialPromise = Promise.resolve(tutorial); const getTutorial = () => { return loadTutorialPromise; }; -const addBasePath = path => { +const addBasePath = (path) => { return `BASE_PATH/${path}`; }; -const replaceTemplateStrings = text => { +const replaceTemplateStrings = (text) => { return text; }; @@ -130,11 +130,7 @@ describe('isCloudEnabled is false', () => { ); await loadTutorialPromise; component.update(); - component - .find('button#onPremElasticCloud') - .closest('div') - .find('input') - .simulate('change'); + component.find('button#onPremElasticCloud').closest('div').find('input').simulate('change'); component.update(); expect(component.state('visibleInstructions')).toBe('onPremElasticCloud'); }); diff --git a/src/plugins/home/public/application/components/tutorial_directory.js b/src/plugins/home/public/application/components/tutorial_directory.js index 18007931a194a..4d2cec158f63e 100644 --- a/src/plugins/home/public/application/components/tutorial_directory.js +++ b/src/plugins/home/public/application/components/tutorial_directory.js @@ -93,7 +93,7 @@ class TutorialDirectoryUi extends React.Component { let openTab = ALL_TAB_ID; if ( props.openTab && - this.tabs.some(tab => { + this.tabs.some((tab) => { return tab.id === props.openTab; }) ) { @@ -126,7 +126,7 @@ class TutorialDirectoryUi extends React.Component { return; } - let tutorialCards = tutorialConfigs.map(tutorialConfig => { + let tutorialCards = tutorialConfigs.map((tutorialConfig) => { // add base path to SVG based icons let icon = tutorialConfig.euiIconType; if (icon && icon.includes('/')) { @@ -161,7 +161,7 @@ class TutorialDirectoryUi extends React.Component { }); if (this.props.isCloudEnabled) { - tutorialCards = tutorialCards.filter(tutorial => { + tutorialCards = tutorialCards.filter((tutorial) => { return _.has(tutorial, 'elasticCloud'); }); } @@ -176,7 +176,7 @@ class TutorialDirectoryUi extends React.Component { }); } - onSelectedTabChanged = id => { + onSelectedTabChanged = (id) => { this.setState({ selectedTabId: id, }); @@ -202,13 +202,13 @@ class TutorialDirectoryUi extends React.Component { return ( {this.state.tutorialCards - .filter(tutorial => { + .filter((tutorial) => { return ( this.state.selectedTabId === ALL_TAB_ID || this.state.selectedTabId === tutorial.category ); }) - .map(tutorial => { + .map((tutorial) => { return ( { + const tutorial = tutorials.find((tutorial) => { return tutorial.id === id; }); diff --git a/src/plugins/home/public/assets/azure_logs/screenshot.png b/src/plugins/home/public/assets/azure_logs/screenshot.png new file mode 100644 index 0000000000000..32c5a7202d883 Binary files /dev/null and b/src/plugins/home/public/assets/azure_logs/screenshot.png differ diff --git a/src/plugins/home/public/assets/azure_metrics/screenshot.png b/src/plugins/home/public/assets/azure_metrics/screenshot.png new file mode 100644 index 0000000000000..22136049b494a Binary files /dev/null and b/src/plugins/home/public/assets/azure_metrics/screenshot.png differ diff --git a/src/plugins/home/public/assets/iis_metrics/screenshot.png b/src/plugins/home/public/assets/iis_metrics/screenshot.png new file mode 100644 index 0000000000000..35e04c49b43f0 Binary files /dev/null and b/src/plugins/home/public/assets/iis_metrics/screenshot.png differ diff --git a/src/plugins/home/public/plugin.ts b/src/plugins/home/public/plugin.ts index f5ad5e321d274..d05fce652bd40 100644 --- a/src/plugins/home/public/plugin.ts +++ b/src/plugins/home/public/plugin.ts @@ -128,7 +128,7 @@ export class HomePublicPlugin window.location.hash === '' ) { // ...wait for the app to mount initially and then... - currentAppId$.pipe(first()).subscribe(appId => { + currentAppId$.pipe(first()).subscribe((appId) => { if (appId === 'home') { // ...navigate to default app set by `kibana.defaultAppId`. // This doesn't do anything as along as the default settings are kept. diff --git a/src/plugins/home/public/services/feature_catalogue/feature_catalogue_registry.ts b/src/plugins/home/public/services/feature_catalogue/feature_catalogue_registry.ts index 187a75b376d64..c70fc0464b131 100644 --- a/src/plugins/home/public/services/feature_catalogue/feature_catalogue_registry.ts +++ b/src/plugins/home/public/services/feature_catalogue/feature_catalogue_registry.ts @@ -73,7 +73,7 @@ export class FeatureCatalogueRegistry { } const capabilities = this.capabilities; return [...this.features.values()] - .filter(entry => capabilities.catalogue[entry.id] !== false) + .filter((entry) => capabilities.catalogue[entry.id] !== false) .sort(compareByKey('title')); } } diff --git a/src/plugins/home/server/services/sample_data/data_sets/ecommerce/index.ts b/src/plugins/home/server/services/sample_data/data_sets/ecommerce/index.ts index b0cc2e2db3cc9..c4fb636cc9f8f 100644 --- a/src/plugins/home/server/services/sample_data/data_sets/ecommerce/index.ts +++ b/src/plugins/home/server/services/sample_data/data_sets/ecommerce/index.ts @@ -31,7 +31,7 @@ const ecommerceDescription = i18n.translate('home.sampleData.ecommerceSpecDescri }); const initialAppLinks = [] as AppLinkSchema[]; -export const ecommerceSpecProvider = function(): SampleDatasetSchema { +export const ecommerceSpecProvider = function (): SampleDatasetSchema { return { id: 'ecommerce', name: ecommerceName, diff --git a/src/plugins/home/server/services/sample_data/data_sets/flights/index.ts b/src/plugins/home/server/services/sample_data/data_sets/flights/index.ts index fc3cb6094b5ea..0d5b4a8816a03 100644 --- a/src/plugins/home/server/services/sample_data/data_sets/flights/index.ts +++ b/src/plugins/home/server/services/sample_data/data_sets/flights/index.ts @@ -31,7 +31,7 @@ const flightsDescription = i18n.translate('home.sampleData.flightsSpecDescriptio }); const initialAppLinks = [] as AppLinkSchema[]; -export const flightsSpecProvider = function(): SampleDatasetSchema { +export const flightsSpecProvider = function (): SampleDatasetSchema { return { id: 'flights', name: flightsName, diff --git a/src/plugins/home/server/services/sample_data/data_sets/logs/index.ts b/src/plugins/home/server/services/sample_data/data_sets/logs/index.ts index d8f205dff24e8..900b9ab82f47f 100644 --- a/src/plugins/home/server/services/sample_data/data_sets/logs/index.ts +++ b/src/plugins/home/server/services/sample_data/data_sets/logs/index.ts @@ -31,7 +31,7 @@ const logsDescription = i18n.translate('home.sampleData.logsSpecDescription', { }); const initialAppLinks = [] as AppLinkSchema[]; -export const logsSpecProvider = function(): SampleDatasetSchema { +export const logsSpecProvider = function (): SampleDatasetSchema { return { id: 'logs', name: logsName, diff --git a/src/plugins/home/server/services/sample_data/lib/create_index_name.ts b/src/plugins/home/server/services/sample_data/lib/create_index_name.ts index 9aecef405d7ce..e8901a3f1bd3e 100644 --- a/src/plugins/home/server/services/sample_data/lib/create_index_name.ts +++ b/src/plugins/home/server/services/sample_data/lib/create_index_name.ts @@ -17,7 +17,7 @@ * under the License. */ -export const createIndexName = function(sampleDataSetId: string, dataIndexId: string): string { +export const createIndexName = function (sampleDataSetId: string, dataIndexId: string): string { // Sample data schema was updated to support multiple indices in 6.5. // This if statement ensures that sample data sets that used a single index prior to the schema change // have the same index name to avoid orphaned indices when uninstalling. diff --git a/src/plugins/home/server/services/sample_data/lib/load_data.ts b/src/plugins/home/server/services/sample_data/lib/load_data.ts index 481ed8da93dba..4dc55b9685302 100644 --- a/src/plugins/home/server/services/sample_data/lib/load_data.ts +++ b/src/plugins/home/server/services/sample_data/lib/load_data.ts @@ -52,7 +52,7 @@ export function loadData(path: any, bulkInsert: (docs: any[]) => Promise) reject(err); }; - lineStream.on('line', async line => { + lineStream.on('line', async (line) => { if (line.length === 0 || line.charAt(0) === '#') { return; } diff --git a/src/plugins/home/server/services/sample_data/lib/sample_dataset_schema.ts b/src/plugins/home/server/services/sample_data/lib/sample_dataset_schema.ts index e905cb0637b7b..b8077a255ecf6 100644 --- a/src/plugins/home/server/services/sample_data/lib/sample_dataset_schema.ts +++ b/src/plugins/home/server/services/sample_data/lib/sample_dataset_schema.ts @@ -31,9 +31,7 @@ const dataIndexSchema = Joi.object({ fields: Joi.object().required(), // times fields that will be updated relative to now when data is installed - timeFields: Joi.array() - .items(Joi.string()) - .required(), + timeFields: Joi.array().items(Joi.string()).required(), // Reference to now in your test data set. // When data is installed, timestamps are converted to the present time. @@ -41,9 +39,7 @@ const dataIndexSchema = Joi.object({ // For example: // sample data set: timestamp: 2018-01-01T00:00:00Z, currentTimeMarker: 2018-01-01T12:00:00Z // installed data set: timestamp: 2018-04-18T20:33:14Z, currentTimeMarker: 2018-04-19T08:33:14Z - currentTimeMarker: Joi.string() - .isoDate() - .required(), + currentTimeMarker: Joi.string().isoDate().required(), // Set to true to move timestamp to current week, preserving day of week and time of day // Relative distance from timestamp to currentTimeMarker will not remain the same @@ -67,19 +63,13 @@ export const sampleDataSchema = { // saved object id of main dashboard for sample data set overviewDashboard: Joi.string().required(), - appLinks: Joi.array() - .items(appLinkSchema) - .default([]), + appLinks: Joi.array().items(appLinkSchema).default([]), // saved object id of default index-pattern for sample data set defaultIndex: Joi.string().required(), // Kibana saved objects (index patter, visualizations, dashboard, ...) // Should provide a nice demo of Kibana's functionality with the sample data set - savedObjects: Joi.array() - .items(Joi.object()) - .required(), - dataIndices: Joi.array() - .items(dataIndexSchema) - .required(), + savedObjects: Joi.array().items(Joi.object()).required(), + dataIndices: Joi.array().items(dataIndexSchema).required(), }; diff --git a/src/plugins/home/server/services/sample_data/routes/install.ts b/src/plugins/home/server/services/sample_data/routes/install.ts index e2c5ce6883230..940162b10385b 100644 --- a/src/plugins/home/server/services/sample_data/routes/install.ts +++ b/src/plugins/home/server/services/sample_data/routes/install.ts @@ -162,7 +162,7 @@ export function createInstallRoute( logger.warn(errMsg); return res.internalError({ body: errMsg }); } - const errors = createResults.saved_objects.filter(savedObjectCreateResult => { + const errors = createResults.saved_objects.filter((savedObjectCreateResult) => { return Boolean(savedObjectCreateResult.error); }); if (errors.length > 0) { diff --git a/src/plugins/home/server/services/sample_data/routes/list.ts b/src/plugins/home/server/services/sample_data/routes/list.ts index 37ebab1c168d2..4fb67c6c78840 100644 --- a/src/plugins/home/server/services/sample_data/routes/list.ts +++ b/src/plugins/home/server/services/sample_data/routes/list.ts @@ -27,7 +27,7 @@ const UNKNOWN = 'unknown'; export const createListRoute = (router: IRouter, sampleDatasets: SampleDatasetSchema[]) => { router.get({ path: '/api/sample_data', validate: false }, async (context, req, res) => { - const registeredSampleDatasets = sampleDatasets.map(sampleDataset => { + const registeredSampleDatasets = sampleDatasets.map((sampleDataset) => { return { id: sampleDataset.id, name: sampleDataset.name, @@ -42,7 +42,7 @@ export const createListRoute = (router: IRouter, sampleDatasets: SampleDatasetSc statusMsg: sampleDataset.statusMsg, }; }); - const isInstalledPromises = registeredSampleDatasets.map(async sampleDataset => { + const isInstalledPromises = registeredSampleDatasets.map(async (sampleDataset) => { for (let i = 0; i < sampleDataset.dataIndices.length; i++) { const dataIndexConfig = sampleDataset.dataIndices[i]; const index = createIndexName(sampleDataset.id, dataIndexConfig.id); diff --git a/src/plugins/home/server/services/sample_data/sample_data_registry.ts b/src/plugins/home/server/services/sample_data/sample_data_registry.ts index b6d04c5c0b6a3..356c886436413 100644 --- a/src/plugins/home/server/services/sample_data/sample_data_registry.ts +++ b/src/plugins/home/server/services/sample_data/sample_data_registry.ts @@ -97,7 +97,7 @@ export class SampleDataRegistry { getSampleDatasets: () => this.sampleDatasets, addSavedObjectsToSampleDataset: (id: string, savedObjects: SavedObject[]) => { - const sampleDataset = this.sampleDatasets.find(dataset => { + const sampleDataset = this.sampleDatasets.find((dataset) => { return dataset.id === id; }); @@ -109,7 +109,7 @@ export class SampleDataRegistry { }, addAppLinksToSampleDataset: (id: string, appLinks: AppLinkSchema[]) => { - const sampleDataset = this.sampleDatasets.find(dataset => { + const sampleDataset = this.sampleDatasets.find((dataset) => { return dataset.id === id; }); @@ -130,14 +130,14 @@ export class SampleDataRegistry { embeddableType, embeddableConfig, }: SampleDatasetDashboardPanel) => { - const sampleDataset = this.sampleDatasets.find(dataset => { + const sampleDataset = this.sampleDatasets.find((dataset) => { return dataset.id === sampleDataId; }); if (!sampleDataset) { throw new Error(`Unable to find sample dataset with id: ${sampleDataId}`); } - const dashboard = sampleDataset.savedObjects.find(savedObject => { + const dashboard = sampleDataset.savedObjects.find((savedObject) => { return savedObject.id === dashboardId && savedObject.type === 'dashboard'; }) as SavedObject<{ panelsJSON: string }>; if (!dashboard) { diff --git a/src/plugins/home/server/services/sample_data/usage/usage.ts b/src/plugins/home/server/services/sample_data/usage/usage.ts index 59599a1bee68f..ba67906febf1a 100644 --- a/src/plugins/home/server/services/sample_data/usage/usage.ts +++ b/src/plugins/home/server/services/sample_data/usage/usage.ts @@ -37,7 +37,7 @@ export function usage( logger.warn(`saved objects repository incrementCounter encountered an error: ${err}`); }; - const internalRepositoryPromise = savedObjects.then(so => so.createInternalRepository()); + const internalRepositoryPromise = savedObjects.then((so) => so.createInternalRepository()); return { addInstall: async (dataSet: string) => { diff --git a/src/plugins/home/server/services/tutorials/lib/tutorial_schema.ts b/src/plugins/home/server/services/tutorials/lib/tutorial_schema.ts index eb001ac96cceb..24f5a39feb4c5 100644 --- a/src/plugins/home/server/services/tutorials/lib/tutorial_schema.ts +++ b/src/plugins/home/server/services/tutorials/lib/tutorial_schema.ts @@ -47,9 +47,7 @@ const artifactsSchema = Joi.object({ documentationUrl: Joi.string().required(), }), // Kibana dashboards created by this product. - dashboards: Joi.array() - .items(dashboardSchema) - .required(), + dashboards: Joi.array().items(dashboardSchema).required(), application: Joi.object({ path: Joi.string().required(), label: Joi.string().required(), @@ -63,9 +61,7 @@ const statusCheckSchema = Joi.object({ success: Joi.string(), error: Joi.string(), esHitsCheck: Joi.object({ - index: Joi.alternatives() - .try(Joi.string(), Joi.array().items(Joi.string())) - .required(), + index: Joi.alternatives().try(Joi.string(), Joi.array().items(Joi.string())).required(), query: Joi.object().required(), }).required(), }); @@ -79,9 +75,7 @@ const instructionSchema = Joi.object({ const instructionVariantSchema = Joi.object({ id: Joi.string().required(), - instructions: Joi.array() - .items(instructionSchema) - .required(), + instructions: Joi.array().items(instructionSchema).required(), }); const instructionSetSchema = Joi.object({ @@ -92,9 +86,7 @@ const instructionSetSchema = Joi.object({ iconType: Joi.string(), }), // Variants (OSes, languages, etc.) for which tutorial instructions are specified. - instructionVariants: Joi.array() - .items(instructionVariantSchema) - .required(), + instructionVariants: Joi.array().items(instructionVariantSchema).required(), statusCheck: statusCheckSchema, }); @@ -104,15 +96,11 @@ const paramSchema = Joi.object({ .regex(/^[a-zA-Z_]+$/) .required(), label: Joi.string().required(), - type: Joi.string() - .valid(Object.values(PARAM_TYPES)) - .required(), + type: Joi.string().valid(Object.values(PARAM_TYPES)).required(), }); const instructionsSchema = Joi.object({ - instructionSets: Joi.array() - .items(instructionSetSchema) - .required(), + instructionSets: Joi.array().items(instructionSetSchema).required(), params: Joi.array().items(paramSchema), }); @@ -120,9 +108,7 @@ export const tutorialSchema = { id: Joi.string() .regex(/^[a-zA-Z0-9-]+$/) .required(), - category: Joi.string() - .valid(Object.values(TUTORIAL_CATEGORY)) - .required(), + category: Joi.string().valid(Object.values(TUTORIAL_CATEGORY)).required(), name: Joi.string().required(), isBeta: Joi.boolean().default(false), shortDescription: Joi.string().required(), diff --git a/src/plugins/home/server/services/tutorials/tutorials_registry.ts b/src/plugins/home/server/services/tutorials/tutorials_registry.ts index ed28e42dbcf99..2122251743382 100644 --- a/src/plugins/home/server/services/tutorials/tutorials_registry.ts +++ b/src/plugins/home/server/services/tutorials/tutorials_registry.ts @@ -45,7 +45,7 @@ export class TutorialsRegistry { ); return res.ok({ - body: this.tutorialProviders.map(tutorialProvider => { + body: this.tutorialProviders.map((tutorialProvider) => { return tutorialProvider(scopedContext); // All the tutorialProviders need to be refactored so that they don't need the server. }), }); @@ -65,7 +65,7 @@ export class TutorialsRegistry { unregisterTutorial: (specProvider: TutorialProvider) => { this.tutorialProviders = this.tutorialProviders.filter( - provider => provider !== specProvider + (provider) => provider !== specProvider ); }, diff --git a/src/plugins/home/server/tutorials/azure_logs/index.ts b/src/plugins/home/server/tutorials/azure_logs/index.ts new file mode 100644 index 0000000000000..06aef411775f1 --- /dev/null +++ b/src/plugins/home/server/tutorials/azure_logs/index.ts @@ -0,0 +1,74 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; +import { TutorialsCategory } from '../../services/tutorials'; +import { + onPremInstructions, + cloudInstructions, + onPremCloudInstructions, +} from '../instructions/filebeat_instructions'; +import { + TutorialContext, + TutorialSchema, +} from '../../services/tutorials/lib/tutorials_registry_types'; + +export function azureLogsSpecProvider(context: TutorialContext): TutorialSchema { + const moduleName = 'azure'; + const platforms = ['OSX', 'DEB', 'RPM', 'WINDOWS'] as const; + return { + id: 'azureLogs', + name: i18n.translate('home.tutorials.azureLogs.nameTitle', { + defaultMessage: 'Azure logs', + }), + isBeta: true, + category: TutorialsCategory.LOGGING, + shortDescription: i18n.translate('home.tutorials.azureLogs.shortDescription', { + defaultMessage: 'Collects Azure activity and audit related logs.', + }), + longDescription: i18n.translate('home.tutorials.azureLogs.longDescription', { + defaultMessage: + 'The `azure` Filebeat module collects Azure activity and audit related logs. \ +[Learn more]({learnMoreLink}).', + values: { + learnMoreLink: '{config.docs.beats.filebeat}/filebeat-module-azure.html', + }, + }), + euiIconType: 'logoAzure', + artifacts: { + dashboards: [ + { + id: '41e84340-ec20-11e9-90ec-112a988266d5', + linkLabel: i18n.translate('home.tutorials.azureLogs.artifacts.dashboards.linkLabel', { + defaultMessage: 'Azure logs dashboard', + }), + isOverview: true, + }, + ], + exportedFields: { + documentationUrl: '{config.docs.beats.filebeat}/exported-fields-azure.html', + }, + }, + completionTimeMinutes: 10, + previewImagePath: '/plugins/home/assets/azure_logs/screenshot.png', + onPrem: onPremInstructions(moduleName, platforms, context), + elasticCloud: cloudInstructions(moduleName, platforms), + onPremElasticCloud: onPremCloudInstructions(moduleName, platforms), + }; +} diff --git a/src/plugins/home/server/tutorials/azure_metrics/index.ts b/src/plugins/home/server/tutorials/azure_metrics/index.ts index ddf70fcc837b2..c11b3ac0139ba 100644 --- a/src/plugins/home/server/tutorials/azure_metrics/index.ts +++ b/src/plugins/home/server/tutorials/azure_metrics/index.ts @@ -36,7 +36,7 @@ export function azureMetricsSpecProvider(context: TutorialContext): TutorialSche name: i18n.translate('home.tutorials.azureMetrics.nameTitle', { defaultMessage: 'Azure metrics', }), - isBeta: true, + isBeta: false, category: TutorialsCategory.METRICS, shortDescription: i18n.translate('home.tutorials.azureMetrics.shortDescription', { defaultMessage: 'Fetch Azure Monitor metrics.', @@ -51,18 +51,21 @@ export function azureMetricsSpecProvider(context: TutorialContext): TutorialSche }), euiIconType: 'logoAzure', artifacts: { - application: { - label: i18n.translate('home.tutorials.azureMetrics.artifacts.application.label', { - defaultMessage: 'Discover', - }), - path: '/app/discover#/', - }, - dashboards: [], + dashboards: [ + { + id: 'eb3f05f0-ea9a-11e9-90ec-112a988266d5', + linkLabel: i18n.translate('home.tutorials.azureMetrics.artifacts.dashboards.linkLabel', { + defaultMessage: 'Azure metrics dashboard', + }), + isOverview: true, + }, + ], exportedFields: { documentationUrl: '{config.docs.beats.metricbeat}/exported-fields-azure.html', }, }, completionTimeMinutes: 10, + previewImagePath: '/plugins/home/assets/azure_metrics/screenshot.png', onPrem: onPremInstructions(moduleName, context), elasticCloud: cloudInstructions(moduleName), onPremElasticCloud: onPremCloudInstructions(moduleName), diff --git a/src/plugins/home/server/tutorials/iis_metrics/index.ts b/src/plugins/home/server/tutorials/iis_metrics/index.ts new file mode 100644 index 0000000000000..46621677a67ce --- /dev/null +++ b/src/plugins/home/server/tutorials/iis_metrics/index.ts @@ -0,0 +1,73 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; +import { TutorialsCategory } from '../../services/tutorials'; +import { + onPremInstructions, + cloudInstructions, + onPremCloudInstructions, +} from '../instructions/metricbeat_instructions'; +import { + TutorialContext, + TutorialSchema, +} from '../../services/tutorials/lib/tutorials_registry_types'; + +export function iisMetricsSpecProvider(context: TutorialContext): TutorialSchema { + const moduleName = 'iis'; + return { + id: 'iisMetrics', + name: i18n.translate('home.tutorials.iisMetrics.nameTitle', { + defaultMessage: 'IIS Metrics', + }), + category: TutorialsCategory.METRICS, + shortDescription: i18n.translate('home.tutorials.iisMetrics.shortDescription', { + defaultMessage: 'Collect IIS server related metrics.', + }), + longDescription: i18n.translate('home.tutorials.iisMetrics.longDescription', { + defaultMessage: + 'The `iis` Metricbeat module collects metrics from IIS server and the application pools and websites running. \ +[Learn more]({learnMoreLink}).', + values: { + learnMoreLink: '{config.docs.beats.metricbeat}/metricbeat-module-iis.html', + }, + }), + isBeta: true, + euiIconType: '/plugins/home/assets/logos/iis.svg', + artifacts: { + dashboards: [ + { + id: 'ebc23240-8572-11ea-91bc-ab084c7ec0e7', + linkLabel: i18n.translate('home.tutorials.iisMetrics.artifacts.dashboards.linkLabel', { + defaultMessage: 'IIS metrics dashboard', + }), + isOverview: true, + }, + ], + exportedFields: { + documentationUrl: '{config.docs.beats.metricbeat}/exported-fields-iis.html', + }, + }, + completionTimeMinutes: 10, + previewImagePath: '/plugins/home/assets/iis_metrics/screenshot.png', + onPrem: onPremInstructions(moduleName, context), + elasticCloud: cloudInstructions(moduleName), + onPremElasticCloud: onPremCloudInstructions(moduleName), + }; +} diff --git a/src/plugins/home/server/tutorials/register.ts b/src/plugins/home/server/tutorials/register.ts index 1eec15069f87e..d13cce1c22784 100644 --- a/src/plugins/home/server/tutorials/register.ts +++ b/src/plugins/home/server/tutorials/register.ts @@ -89,6 +89,8 @@ import { statsdMetricsSpecProvider } from './statsd_metrics'; import { redisenterpriseMetricsSpecProvider } from './redisenterprise_metrics'; import { openmetricsMetricsSpecProvider } from './openmetrics_metrics'; import { oracleMetricsSpecProvider } from './oracle_metrics'; +import { iisMetricsSpecProvider } from './iis_metrics'; +import { azureLogsSpecProvider } from './azure_logs'; export const builtInTutorials = [ systemLogsSpecProvider, @@ -164,4 +166,6 @@ export const builtInTutorials = [ redisenterpriseMetricsSpecProvider, openmetricsMetricsSpecProvider, oracleMetricsSpecProvider, + iisMetricsSpecProvider, + azureLogsSpecProvider, ]; diff --git a/src/plugins/index_pattern_management/public/components/create_button/create_button.tsx b/src/plugins/index_pattern_management/public/components/create_button/create_button.tsx index d8a44675d80a0..cd21712ca28ed 100644 --- a/src/plugins/index_pattern_management/public/components/create_button/create_button.tsx +++ b/src/plugins/index_pattern_management/public/components/create_button/create_button.tsx @@ -98,7 +98,7 @@ export class CreateButton extends Component { anchorPosition="downLeft" > { + items={options.map((option) => { return (
{ it('should render normally', () => { - const component = shallow( {}} prependBasePath={x => x} />); + const component = shallow( {}} prependBasePath={(x) => x} />); expect(component).toMatchSnapshot(); }); @@ -35,7 +35,7 @@ describe('EmptyState', () => { const onRefreshHandler = sinon.stub(); const component = shallow( - x} /> + x} /> ); component.find('[data-test-subj="refreshIndicesButton"]').simulate('click'); diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/header/__snapshots__/header.test.tsx.snap b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/header/__snapshots__/header.test.tsx.snap index bdfdd2e7ad0a6..81ca3e644d3ce 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/header/__snapshots__/header.test.tsx.snap +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/header/__snapshots__/header.test.tsx.snap @@ -1,122 +1,235 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Header should render a different name, prompt, and beta tag if provided 1`] = ` -
- -

- Create test index pattern - - -

-
- - + Test prompt +
+ } +> +
+ +

+ Create test index pattern + + + + Beta + + +

+
+ - -

- +

- - -

- - - - -
- Test prompt + +
+

+ + + + + Kibana uses index patterns to retrieve data from Elasticsearch indices for things like visualizations. + + + + +

+
+
+
+ +
+
+ +
+ +
+ Test prompt +
+ +
+
- -
+
`; exports[`Header should render normally 1`] = ` -
- -

- Create test index pattern -

-
- - +
+ +

+ Create test index pattern +

+
+ - -

- +

- - -

- - - - -
+ +
+

+ + + + + Kibana uses index patterns to retrieve data from Elasticsearch indices for things like visualizations. + + + + +

+
+
+
+
+
+ + +
+ +
+
`; exports[`Header should render without including system indices 1`] = ` -
- -

- Create test index pattern -

-
- - +
+ +

+ Create test index pattern +

+
+ - -

- +

- - -

- - - - -
+ +
+

+ + + + + Kibana uses index patterns to retrieve data from Elasticsearch indices for things like visualizations. + + + + +

+
+
+
+
+
+ + +
+ +
+ `; diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/header/header.test.tsx b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/header/header.test.tsx index d70746dd930e4..d12e0401380b9 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/header/header.test.tsx +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/header/header.test.tsx @@ -19,46 +19,65 @@ import React from 'react'; import { Header } from '../header'; -import { shallowWithI18nProvider } from 'test_utils/enzyme_helpers'; +import { mount } from 'enzyme'; +import { KibanaContextProvider } from 'src/plugins/kibana_react/public'; +import { mockManagementPlugin } from '../../../../mocks'; describe('Header', () => { const indexPatternName = 'test index pattern'; + const mockedContext = mockManagementPlugin.createIndexPatternManagmentContext(); + it('should render normally', () => { - const component = shallowWithI18nProvider( + const component = mount(
{}} - changeTitle={() => {}} - /> + />, + { + wrappingComponent: KibanaContextProvider, + wrappingComponentProps: { + services: mockedContext, + }, + } ); expect(component).toMatchSnapshot(); }); it('should render without including system indices', () => { - const component = shallowWithI18nProvider( + const component = mount(
{}} - changeTitle={() => {}} - /> + />, + { + wrappingComponent: KibanaContextProvider, + wrappingComponentProps: { + services: mockedContext, + }, + } ); expect(component).toMatchSnapshot(); }); it('should render a different name, prompt, and beta tag if provided', () => { - const component = shallowWithI18nProvider( + const component = mount(
{}} prompt={
Test prompt
} indexPatternName={indexPatternName} isBeta={true} - changeTitle={() => {}} - /> + />, + { + wrappingComponent: KibanaContextProvider, + wrappingComponentProps: { + services: mockedContext, + }, + } ); expect(component).toMatchSnapshot(); diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/header/header.tsx b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/header/header.tsx index 1be33e3edc3bc..35c6e67d0ea0e 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/header/header.tsx +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/header/header.tsx @@ -32,6 +32,8 @@ import { import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; +import { useKibana } from '../../../../../../../plugins/kibana_react/public'; +import { IndexPatternManagmentContext } from '../../../../types'; export const Header = ({ prompt, @@ -40,7 +42,6 @@ export const Header = ({ isIncludingSystemIndices, onChangeIncludingSystemIndices, isBeta = false, - changeTitle, }: { prompt?: React.ReactNode; indexPatternName: string; @@ -48,8 +49,8 @@ export const Header = ({ isIncludingSystemIndices: boolean; onChangeIncludingSystemIndices: () => void; isBeta?: boolean; - changeTitle: (title: string) => void; }) => { + const changeTitle = useKibana().services.chrome.docTitle.change; const createIndexPatternHeader = i18n.translate( 'indexPatternManagement.createIndexPatternHeader', { diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/components/indices_list/indices_list.tsx b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/components/indices_list/indices_list.tsx index e9eff57e17788..c590d2a7ddfe2 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/components/indices_list/indices_list.tsx +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/components/indices_list/indices_list.tsx @@ -114,7 +114,7 @@ export class IndicesList extends React.Component ); - const items = PER_PAGE_INCREMENTS.map(increment => { + const items = PER_PAGE_INCREMENTS.map((increment) => { return ( ({ ensureMinimumTime: async (promises: Array>) => @@ -53,40 +52,43 @@ const allIndices = [ const goToNextStep = () => {}; -const savedObjectClient = coreMock.createStart().savedObjects.client; -savedObjectClient.find = () => - new Promise>(() => ({ savedObjects: [] })); - -const uiSettings = coreMock.createSetup().uiSettings; -uiSettings.get.mockReturnValue(''); - -const createComponent = (props?: Record) => { - return shallowWithI18nProvider( - - ); -}; +const mockContext = mockManagementPlugin.createIndexPatternManagmentContext(); + +mockContext.savedObjects.client.find = async () => + Promise.resolve(({ savedObjects: [] } as unknown) as SavedObjectsFindResponsePublic); +mockContext.uiSettings.get.mockReturnValue(''); describe('StepIndexPattern', () => { it('renders the loading state', () => { - const component = createComponent(); + const component = createComponentWithContext( + StepIndexPattern, + { + allIndices, + isIncludingSystemIndices: false, + goToNextStep, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext + ); component.setState({ isLoadingIndices: true }); expect(component.find('[data-test-subj="createIndexPatternStep1Loading"]')).toMatchSnapshot(); }); it('renders indices which match the initial query', async () => { - const component = createComponent({ initialQuery: 'kibana' }); + const component = createComponentWithContext( + StepIndexPattern, + { + allIndices, + isIncludingSystemIndices: false, + goToNextStep, + indexPatternCreationType: mockIndexPatternCreationType, + initialQuery: 'kibana', + }, + mockContext + ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected await component.update(); @@ -96,12 +98,21 @@ describe('StepIndexPattern', () => { }); it('renders errors when input is invalid', async () => { - const component = createComponent(); + const component = createComponentWithContext( + StepIndexPattern, + { + allIndices, + isIncludingSystemIndices: false, + goToNextStep, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext + ); const instance = component.instance() as StepIndexPattern; instance.onQueryChanged({ target: { value: '?' } } as React.ChangeEvent); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); expect({ @@ -110,12 +121,21 @@ describe('StepIndexPattern', () => { }); it('renders matching indices when input is valid', async () => { - const component = createComponent(); + const component = createComponentWithContext( + StepIndexPattern, + { + allIndices, + isIncludingSystemIndices: false, + goToNextStep, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext + ); const instance = component.instance() as StepIndexPattern; instance.onQueryChanged({ target: { value: 'k' } } as React.ChangeEvent); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -125,24 +145,51 @@ describe('StepIndexPattern', () => { }); it('appends a wildcard automatically to queries', async () => { - const component = createComponent(); + const component = createComponentWithContext( + StepIndexPattern, + { + allIndices, + isIncludingSystemIndices: false, + goToNextStep, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext + ); const instance = component.instance() as StepIndexPattern; instance.onQueryChanged({ target: { value: 'k' } } as React.ChangeEvent); expect(component.state('query')).toBe('k*'); }); it('disables the next step if the index pattern exists', async () => { - const component = createComponent(); + const component = createComponentWithContext( + StepIndexPattern, + { + allIndices, + isIncludingSystemIndices: false, + goToNextStep, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext + ); component.setState({ indexPatternExists: true }); expect(component.find(Header).prop('isNextStepDisabled')).toBe(true); }); it('ensures the response of the latest request is persisted', async () => { - const component = createComponent(); + const component = createComponentWithContext( + StepIndexPattern, + { + allIndices, + isIncludingSystemIndices: false, + goToNextStep, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext + ); const instance = component.instance() as StepIndexPattern; instance.onQueryChanged({ target: { value: 'e' } } as React.ChangeEvent); instance.lastQuery = 'k'; - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Honesty, the state would match the result of the `k` query but // it's hard to mock this in tests but if remove our fix @@ -155,7 +202,7 @@ describe('StepIndexPattern', () => { // Provide `es` so we do not auto append * and enter our other code flow instance.onQueryChanged({ target: { value: 'es' } } as React.ChangeEvent); instance.lastQuery = 'k'; - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); expect(component.state('exactMatchedIndices')).toEqual([]); }); }); diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/step_index_pattern.tsx b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/step_index_pattern.tsx index 5c8fa92d355a3..edb96f119385e 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/step_index_pattern.tsx +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_index_pattern/step_index_pattern.tsx @@ -21,12 +21,7 @@ import React, { Component } from 'react'; import { EuiPanel, EuiSpacer, EuiCallOut } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { - indexPatterns, - DataPublicPluginStart, - IndexPatternAttributes, -} from '../../../../../../../plugins/data/public'; -import { SavedObjectsClientContract, IUiSettingsClient } from '../../../../../../../core/public'; +import { indexPatterns, IndexPatternAttributes } from '../../../../../../../plugins/data/public'; import { MAX_SEARCH_SIZE } from '../../constants'; import { getIndices, @@ -39,18 +34,17 @@ import { LoadingIndices } from './components/loading_indices'; import { StatusMessage } from './components/status_message'; import { IndicesList } from './components/indices_list'; import { Header } from './components/header'; +import { context as contextType } from '../../../../../../kibana_react/public'; import { IndexPatternCreationConfig } from '../../../../../../../plugins/index_pattern_management/public'; import { MatchedIndex } from '../../types'; +import { IndexPatternManagmentContextValue } from '../../../../types'; interface StepIndexPatternProps { allIndices: MatchedIndex[]; isIncludingSystemIndices: boolean; - esService: DataPublicPluginStart['search']['__LEGACY']['esClient']; - savedObjectsClient: SavedObjectsClientContract; indexPatternCreationType: IndexPatternCreationConfig; goToNextStep: (query: string) => void; initialQuery?: string; - uiSettings: IUiSettingsClient; } interface StepIndexPatternState { @@ -66,6 +60,10 @@ interface StepIndexPatternState { } export class StepIndexPattern extends Component { + static contextType = contextType; + + public readonly context!: IndexPatternManagmentContextValue; + state = { partialMatchedIndices: [], exactMatchedIndices: [], @@ -80,11 +78,11 @@ export class StepIndexPattern extends Component { - const { savedObjects } = await this.props.savedObjectsClient.find({ + const { savedObjects } = await this.context.services.savedObjects.client.find< + IndexPatternAttributes + >({ type: 'index-pattern', fields: ['title'], perPage: 10000, }); - const existingIndexPatterns = savedObjects.map(obj => + const existingIndexPatterns = savedObjects.map((obj) => obj && obj.attributes ? obj.attributes.title : '' ) as string[]; @@ -111,7 +111,7 @@ export class StepIndexPattern extends Component { - const { esService, indexPatternCreationType } = this.props; + const { indexPatternCreationType } = this.props; const { existingIndexPatterns } = this.state; if ((existingIndexPatterns as string[]).includes(query)) { @@ -123,7 +123,12 @@ export class StepIndexPattern extends Component {}; +const mockContext = mockManagementPlugin.createIndexPatternManagmentContext(); const fields = [ { name: '@timestamp', type: 'date', }, ]; -const indexPatternsService = { +mockContext.data.indexPatterns = { make: () => ({ fieldsFetcher: { fetchForWildcard: jest.fn().mockReturnValue(Promise.resolve(fields)), @@ -55,28 +57,30 @@ const indexPatternsService = { describe('StepTimeField', () => { it('should render normally', () => { - const component = shallowWithI18nProvider( - + const component = createComponentWithContext( + StepTimeField, + { + indexPattern: 'ki*', + goToPreviousStep: noop, + createIndexPattern: noop, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext ); expect(component).toMatchSnapshot(); }); it('should render timeFields', () => { - const component = shallowWithI18nProvider( - + const component = createComponentWithContext( + StepTimeField, + { + indexPattern: 'ki*', + goToPreviousStep: noop, + createIndexPattern: noop, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext ); component.setState({ @@ -90,14 +94,15 @@ describe('StepTimeField', () => { }); it('should render a selected timeField', () => { - const component = shallowWithI18nProvider( - + const component = createComponentWithContext( + StepTimeField, + { + indexPattern: 'ki*', + goToPreviousStep: noop, + createIndexPattern: noop, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext ); component.setState({ @@ -113,14 +118,15 @@ describe('StepTimeField', () => { }); it('should ensure disabled time field options work properly', () => { - const component = shallowWithI18nProvider( - + const component = createComponentWithContext( + StepTimeField, + { + indexPattern: 'ki*', + goToPreviousStep: noop, + createIndexPattern: noop, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext ); component.setState({ @@ -146,14 +152,15 @@ describe('StepTimeField', () => { }); it('should disable the action button if an invalid time field is selected', () => { - const component = shallowWithI18nProvider( - + const component = createComponentWithContext( + StepTimeField, + { + indexPattern: 'ki*', + goToPreviousStep: noop, + createIndexPattern: noop, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext ); component.setState({ @@ -172,14 +179,15 @@ describe('StepTimeField', () => { }); it('should enable the action button if the user decides to not select a time field', () => { - const component = shallowWithI18nProvider( - + const component = createComponentWithContext( + StepTimeField, + { + indexPattern: 'ki*', + goToPreviousStep: noop, + createIndexPattern: noop, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext ); component.setState({ @@ -198,14 +206,15 @@ describe('StepTimeField', () => { }); it('should render advanced options', () => { - const component = shallowWithI18nProvider( - + const component = createComponentWithContext( + StepTimeField, + { + indexPattern: 'ki*', + goToPreviousStep: noop, + createIndexPattern: noop, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext ); component.setState({ showingAdvancedOptions: true }); @@ -214,14 +223,15 @@ describe('StepTimeField', () => { }); it('should render advanced options with an index pattern id', () => { - const component = shallowWithI18nProvider( - + const component = createComponentWithContext( + StepTimeField, + { + indexPattern: 'ki*', + goToPreviousStep: noop, + createIndexPattern: noop, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext ); component.setState({ @@ -233,14 +243,15 @@ describe('StepTimeField', () => { }); it('should render a loading state when creating the index pattern', () => { - const component = shallowWithI18nProvider( - + const component = createComponentWithContext( + StepTimeField, + { + indexPattern: 'ki*', + goToPreviousStep: noop, + createIndexPattern: noop, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext ); component.setState({ isCreating: true }); @@ -249,14 +260,15 @@ describe('StepTimeField', () => { }); it('should render any error message', () => { - const component = shallowWithI18nProvider( - + const component = createComponentWithContext( + StepTimeField, + { + indexPattern: 'ki*', + goToPreviousStep: noop, + createIndexPattern: noop, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext ); component.setState({ error: 'foobar' }); @@ -265,14 +277,15 @@ describe('StepTimeField', () => { }); it('should render "Custom index pattern ID already exists" when error is "Conflict"', () => { - const component = shallowWithI18nProvider( - + const component = createComponentWithContext( + StepTimeField, + { + indexPattern: 'ki*', + goToPreviousStep: noop, + createIndexPattern: noop, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext ); component.setState({ error: 'Conflict' }); @@ -284,14 +297,15 @@ describe('StepTimeField', () => { const createIndexPattern = async () => { throw new Error('foobar'); }; - const component = shallowWithI18nProvider( - + const component = createComponentWithContext( + StepTimeField, + { + indexPattern: 'ki*', + goToPreviousStep: noop, + createIndexPattern, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext ); await (component.instance() as StepTimeField).createIndexPattern(); @@ -305,14 +319,15 @@ describe('StepTimeField', () => { it('should call createIndexPattern with undefined time field when no time filter chosen', async () => { const createIndexPattern = jest.fn(); - const component = shallowWithI18nProvider( - + const component = createComponentWithContext( + StepTimeField, + { + indexPattern: 'ki*', + goToPreviousStep: noop, + createIndexPattern, + indexPatternCreationType: mockIndexPatternCreationType, + }, + mockContext ); await (component.instance() as StepTimeField).fetchTimeFields(); diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_time_field/step_time_field.tsx b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_time_field/step_time_field.tsx index d22b503937290..98ce22cd14227 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_time_field/step_time_field.tsx +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/components/step_time_field/step_time_field.tsx @@ -34,12 +34,12 @@ import { Header } from './components/header'; import { TimeField } from './components/time_field'; import { AdvancedOptions } from './components/advanced_options'; import { ActionButtons } from './components/action_buttons'; +import { context } from '../../../../../../kibana_react/public'; +import { IndexPatternManagmentContextValue } from '../../../../types'; import { IndexPatternCreationConfig } from '../../../..'; -import { DataPublicPluginStart } from '../../../../../../data/public'; interface StepTimeFieldProps { indexPattern: string; - indexPatternsService: DataPublicPluginStart['indexPatterns']; goToPreviousStep: () => void; createIndexPattern: (selectedTimeField: string | undefined, indexPatternId: string) => void; indexPatternCreationType: IndexPatternCreationConfig; @@ -65,6 +65,10 @@ interface TimeFieldConfig { } export class StepTimeField extends Component { + static contextType = context; + + public readonly context!: IndexPatternManagmentContextValue; + state = { error: '', timeFields: [], @@ -96,10 +100,10 @@ export class StepTimeField extends Component { - const { indexPatternsService, indexPattern: pattern } = this.props; + const { indexPattern: pattern } = this.props; const { getFetchForWildcardOptions } = this.props.indexPatternCreationType; - const indexPattern = await indexPatternsService.make(); + const indexPattern = await this.context.services.data.indexPatterns.make(); indexPattern.title = pattern; this.setState({ isFetchingTimeFields: true }); @@ -133,7 +137,7 @@ export class StepTimeField extends Component { - this.setState(state => ({ + this.setState((state) => ({ isAdvancedOptionsVisible: !state.isAdvancedOptionsVisible, })); }; diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/create_index_pattern_wizard.test.tsx b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/create_index_pattern_wizard.test.tsx index f526aa35c2afe..b14cd526d7e27 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/create_index_pattern_wizard.test.tsx +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/create_index_pattern_wizard.test.tsx @@ -17,18 +17,11 @@ * under the License. */ -import React from 'react'; -import { shallow } from 'enzyme'; - -import { - CreateIndexPatternWizard, - CreateIndexPatternWizardProps, -} from './create_index_pattern_wizard'; -import { coreMock } from '../../../../../core/public/mocks'; -import { dataPluginMock } from '../../../../../plugins/data/public/mocks'; +import { CreateIndexPatternWizard } from './create_index_pattern_wizard'; import { IndexPattern } from '../../../../../plugins/data/public'; -import { SavedObjectsClient } from '../../../../../core/public'; -import { IndexPatternCreationConfig } from '../../service/creation'; +import { mockManagementPlugin } from '../../mocks'; +import { IndexPatternCreationConfig } from '../../'; +import { createComponentWithContext } from '../test_utils'; jest.mock('./components/step_index_pattern', () => ({ StepIndexPattern: 'StepIndexPattern' })); jest.mock('./components/step_time_field', () => ({ StepTimeField: 'StepTimeField' })); @@ -40,30 +33,6 @@ jest.mock('./lib/get_indices', () => ({ return [{ name: 'kibana' }]; }, })); - -const { savedObjects, overlays, uiSettings, chrome, http } = coreMock.createStart(); -const { indexPatterns, search } = dataPluginMock.createStartContract(); - -const mockIndexPatternCreationType = new IndexPatternCreationConfig({ - type: 'default', - name: 'name', -}); - -const services = ({ - indexPatternCreation: { - getType: jest.fn(() => mockIndexPatternCreationType), - }, - es: search.__LEGACY.esClient, - indexPatterns, - savedObjectsClient: savedObjects.client as SavedObjectsClient, - uiSettings, - changeUrl: jest.fn(), - openConfirm: overlays.openConfirm, - setBreadcrumbs: jest.fn(), - docTitle: chrome.docTitle, - prependBasePath: http.basePath.prepend, -} as unknown) as CreateIndexPatternWizardProps['services']; - const routeComponentPropsMock = { history: { push: jest.fn(), @@ -71,19 +40,30 @@ const routeComponentPropsMock = { location: {} as any, match: {} as any, }; +const mockContext = mockManagementPlugin.createIndexPatternManagmentContext(); +mockContext.indexPatternManagementStart.creation.getType = () => { + return new IndexPatternCreationConfig({ + type: 'default', + name: 'name', + }); +}; describe('CreateIndexPatternWizard', () => { test(`defaults to the loading state`, () => { - const component = shallow( - + const component = createComponentWithContext( + CreateIndexPatternWizard, + { ...routeComponentPropsMock }, + mockContext ); expect(component).toMatchSnapshot(); }); test('renders the empty state when there are no indices', async () => { - const component = shallow( - + const component = createComponentWithContext( + CreateIndexPatternWizard, + { ...routeComponentPropsMock }, + mockContext ); component.setState({ @@ -97,8 +77,10 @@ describe('CreateIndexPatternWizard', () => { }); test('renders when there are no indices but there are remote clusters', async () => { - const component = shallow( - + const component = createComponentWithContext( + CreateIndexPatternWizard, + { ...routeComponentPropsMock }, + mockContext ); component.setState({ @@ -112,8 +94,10 @@ describe('CreateIndexPatternWizard', () => { }); test('shows system indices even if there are no other indices if the include system indices is toggled', async () => { - const component = shallow( - + const component = createComponentWithContext( + CreateIndexPatternWizard, + { ...routeComponentPropsMock }, + mockContext ); component.setState({ @@ -127,8 +111,10 @@ describe('CreateIndexPatternWizard', () => { }); test('renders index pattern step when there are indices', async () => { - const component = shallow( - + const component = createComponentWithContext( + CreateIndexPatternWizard, + { ...routeComponentPropsMock }, + mockContext ); component.setState({ @@ -141,8 +127,10 @@ describe('CreateIndexPatternWizard', () => { }); test('renders time field step when step is set to 2', async () => { - const component = shallow( - + const component = createComponentWithContext( + CreateIndexPatternWizard, + { ...routeComponentPropsMock }, + mockContext ); component.setState({ @@ -158,7 +146,7 @@ describe('CreateIndexPatternWizard', () => { test('invokes the provided services when creating an index pattern', async () => { const create = jest.fn().mockImplementation(() => 'id'); const clear = jest.fn(); - services.indexPatterns.clearCache = clear; + mockContext.data.indexPatterns.clearCache = clear; const indexPattern = ({ id: '1', title: 'my-fake-index-pattern', @@ -166,17 +154,19 @@ describe('CreateIndexPatternWizard', () => { fields: [], create, } as unknown) as IndexPattern; - services.indexPatterns.make = async () => { + mockContext.data.indexPatterns.make = async () => { return indexPattern; }; - const component = shallow( - + const component = createComponentWithContext( + CreateIndexPatternWizard, + { ...routeComponentPropsMock }, + mockContext ); component.setState({ indexPattern: 'foo' }); - await component.instance().createIndexPattern(undefined, 'id'); - expect(services.uiSettings.get).toBeCalled(); + await (component.instance() as CreateIndexPatternWizard).createIndexPattern(undefined, 'id'); + expect(mockContext.uiSettings.get).toBeCalled(); expect(create).toBeCalled(); expect(clear).toBeCalledWith('id'); expect(routeComponentPropsMock.history.push).toBeCalledWith(`/patterns/id`); diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/create_index_pattern_wizard.tsx b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/create_index_pattern_wizard.tsx index 62bf47546e103..111be41cfc53a 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/create_index_pattern_wizard.tsx +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/create_index_pattern_wizard.tsx @@ -23,42 +23,20 @@ import { EuiGlobalToastList, EuiGlobalToastListToast, EuiPanel } from '@elastic/ import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; import { withRouter, RouteComponentProps } from 'react-router-dom'; - -import { - SavedObjectsClientContract, - IUiSettingsClient, - OverlayStart, - ChromeDocTitle, - IBasePath, -} from 'src/core/public'; -import { DataPublicPluginStart } from 'src/plugins/data/public'; -import { ManagementAppMountParams } from '../../../../management/public'; import { StepIndexPattern } from './components/step_index_pattern'; import { StepTimeField } from './components/step_time_field'; import { Header } from './components/header'; import { LoadingState } from './components/loading_state'; import { EmptyState } from './components/empty_state'; +import { context as contextType } from '../../../../kibana_react/public'; import { getCreateBreadcrumbs } from '../breadcrumbs'; import { MAX_SEARCH_SIZE } from './constants'; import { ensureMinimumTime, getIndices } from './lib'; -import { IndexPatternCreationConfig, IndexPatternManagementStart } from '../..'; +import { IndexPatternCreationConfig } from '../..'; +import { IndexPatternManagmentContextValue } from '../../types'; import { MatchedIndex } from './types'; -export interface CreateIndexPatternWizardProps extends RouteComponentProps { - services: { - indexPatternCreation: IndexPatternManagementStart['creation']; - es: DataPublicPluginStart['search']['__LEGACY']['esClient']; - indexPatterns: DataPublicPluginStart['indexPatterns']; - savedObjectsClient: SavedObjectsClientContract; - uiSettings: IUiSettingsClient; - openConfirm: OverlayStart['openConfirm']; - setBreadcrumbs: ManagementAppMountParams['setBreadcrumbs']; - docTitle: ChromeDocTitle; - prependBasePath: IBasePath['prepend']; - }; -} - interface CreateIndexPatternWizardState { step: number; indexPattern: string; @@ -71,19 +49,19 @@ interface CreateIndexPatternWizardState { } export class CreateIndexPatternWizard extends Component< - CreateIndexPatternWizardProps, + RouteComponentProps, CreateIndexPatternWizardState > { - constructor(props: CreateIndexPatternWizardProps) { - super(props); - const { - services: { indexPatternCreation, setBreadcrumbs }, - location, - } = props; + static contextType = contextType; - setBreadcrumbs(getCreateBreadcrumbs()); + public readonly context!: IndexPatternManagmentContextValue; - const type = new URLSearchParams(location.search).get('type') || undefined; + constructor(props: RouteComponentProps, context: IndexPatternManagmentContextValue) { + super(props, context); + + context.services.setBreadcrumbs(getCreateBreadcrumbs()); + + const type = new URLSearchParams(props.location.search).get('type') || undefined; this.state = { step: 1, @@ -93,7 +71,7 @@ export class CreateIndexPatternWizard extends Component< isInitiallyLoadingIndices: true, isIncludingSystemIndices: false, toasts: [], - indexPatternCreationType: indexPatternCreation.getType(type), + indexPatternCreationType: context.services.indexPatternManagementStart.creation.getType(type), }; } @@ -109,7 +87,7 @@ export class CreateIndexPatternWizard extends Component< try { return await asyncFn; } catch (errors) { - this.setState(prevState => ({ + this.setState((prevState) => ({ toasts: prevState.toasts.concat([ { title: errorMsg, @@ -124,8 +102,6 @@ export class CreateIndexPatternWizard extends Component< }; fetchData = async () => { - const { services } = this.props; - this.setState({ allIndices: [], isInitiallyLoadingIndices: true, @@ -149,7 +125,12 @@ export class CreateIndexPatternWizard extends Component< // query local and remote indices, updating state independently ensureMinimumTime( this.catchAndWarn( - getIndices(services.es, this.state.indexPatternCreationType, `*`, MAX_SEARCH_SIZE), + getIndices( + this.context.services.data.search.__LEGACY.esClient, + this.state.indexPatternCreationType, + `*`, + MAX_SEARCH_SIZE + ), [], indicesFailMsg ) @@ -160,7 +141,12 @@ export class CreateIndexPatternWizard extends Component< this.catchAndWarn( // if we get an error from remote cluster query, supply fallback value that allows user entry. // ['a'] is fallback value - getIndices(services.es, this.state.indexPatternCreationType, `*:*`, 1), + getIndices( + this.context.services.data.search.__LEGACY.esClient, + this.state.indexPatternCreationType, + `*:*`, + 1 + ), ['a'], clustersFailMsg ).then((remoteIndices: string[] | MatchedIndex[]) => @@ -169,10 +155,10 @@ export class CreateIndexPatternWizard extends Component< }; createIndexPattern = async (timeFieldName: string | undefined, indexPatternId: string) => { - const { services, history } = this.props; + const { history } = this.props; const { indexPattern } = this.state; - const emptyPattern = await services.indexPatterns.make(); + const emptyPattern = await this.context.services.data.indexPatterns.make(); Object.assign(emptyPattern, { id: indexPatternId, @@ -191,7 +177,7 @@ export class CreateIndexPatternWizard extends Component< } ); - const isConfirmed = await services.openConfirm(confirmMessage, { + const isConfirmed = await this.context.services.overlays.openConfirm(confirmMessage, { confirmButtonText: i18n.translate( 'indexPatternManagement.indexPattern.goToPatternButtonLabel', { @@ -207,11 +193,11 @@ export class CreateIndexPatternWizard extends Component< } } - if (!services.uiSettings.get('defaultIndex')) { - await services.uiSettings.set('defaultIndex', createdId); + if (!this.context.services.uiSettings.get('defaultIndex')) { + await this.context.services.uiSettings.set('defaultIndex', createdId); } - services.indexPatterns.clearCache(createdId); + this.context.services.data.indexPatterns.clearCache(createdId); history.push(`/patterns/${createdId}`); }; @@ -224,14 +210,13 @@ export class CreateIndexPatternWizard extends Component< }; onChangeIncludingSystemIndices = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isIncludingSystemIndices: !prevState.isIncludingSystemIndices, })); }; renderHeader() { const { isIncludingSystemIndices } = this.state; - const { services } = this.props; return (
); } @@ -265,13 +249,13 @@ export class CreateIndexPatternWizard extends Component< return ( ); } if (step === 1) { - const { services, location } = this.props; + const { location } = this.props; const initialQuery = new URLSearchParams(location.search).get('id') || undefined; return ( @@ -279,21 +263,16 @@ export class CreateIndexPatternWizard extends Component< allIndices={allIndices} initialQuery={indexPattern || initialQuery} isIncludingSystemIndices={isIncludingSystemIndices} - esService={services.es} - savedObjectsClient={services.savedObjectsClient} indexPatternCreationType={this.state.indexPatternCreationType} goToNextStep={this.goToTimeFieldStep} - uiSettings={services.uiSettings} /> ); } if (step === 2) { - const { services } = this.props; return ( { - this.setState(prevState => ({ - toasts: prevState.toasts.filter(toast => toast.id !== id), + this.setState((prevState) => ({ + toasts: prevState.toasts.filter((toast) => toast.id !== id), })); }; diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/contains_illegal_characters.ts b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/contains_illegal_characters.ts index ca4fc8122903c..48c708b016aef 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/contains_illegal_characters.ts +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/contains_illegal_characters.ts @@ -18,5 +18,5 @@ */ export function containsIllegalCharacters(pattern: string, illegalCharacters: string[]) { - return illegalCharacters.some(char => pattern.includes(char)); + return illegalCharacters.some((char) => pattern.includes(char)); } diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.test.ts b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.test.ts index e5fcfe056923a..a38f3cbd8fe81 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.test.ts +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.test.ts @@ -20,25 +20,25 @@ import { ensureMinimumTime } from './ensure_minimum_time'; describe('ensureMinimumTime', () => { - it('resolves single promise', async done => { - const promiseA = new Promise(resolve => resolve('a')); + it('resolves single promise', async (done) => { + const promiseA = new Promise((resolve) => resolve('a')); const a = await ensureMinimumTime(promiseA, 0); expect(a).toBe('a'); done(); }); - it('resolves multiple promises', async done => { - const promiseA = new Promise(resolve => resolve('a')); - const promiseB = new Promise(resolve => resolve('b')); + it('resolves multiple promises', async (done) => { + const promiseA = new Promise((resolve) => resolve('a')); + const promiseB = new Promise((resolve) => resolve('b')); const [a, b] = await ensureMinimumTime([promiseA, promiseB], 0); expect(a).toBe('a'); expect(b).toBe('b'); done(); }); - it('resolves in the amount of time provided, at minimum', async done => { + it('resolves in the amount of time provided, at minimum', async (done) => { const startTime = new Date().getTime(); - const promise = new Promise(resolve => resolve()); + const promise = new Promise((resolve) => resolve()); await ensureMinimumTime(promise, 100); const endTime = new Date().getTime(); expect(endTime - startTime).toBeGreaterThanOrEqual(100); diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.ts b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.ts index 84852ece485eb..3b3895cbb9ad9 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.ts +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/ensure_minimum_time.ts @@ -54,7 +54,7 @@ export async function ensureMinimumTime( if (asyncActionDuration < bufferedMinimumTimeMs) { const additionalWaitingTime = bufferedMinimumTimeMs - (asyncActionCompletionTime - asyncActionStartTime); - await new Promise(resolve => setTimeout(resolve, additionalWaitingTime)); + await new Promise((resolve) => setTimeout(resolve, additionalWaitingTime)); } return returnValue; diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/extract_time_fields.ts b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/extract_time_fields.ts index 809c9f77b2832..b7056ad17343a 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/extract_time_fields.ts +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/extract_time_fields.ts @@ -21,7 +21,7 @@ import { i18n } from '@kbn/i18n'; import { IFieldType } from '../../../../../../plugins/data/public'; export function extractTimeFields(fields: IFieldType[]) { - const dateFields = fields.filter(field => field.type === 'date'); + const dateFields = fields.filter((field) => field.type === 'date'); const label = i18n.translate( 'indexPatternManagement.createIndexPattern.stepTime.noTimeFieldsLabel', { @@ -54,7 +54,7 @@ export function extractTimeFields(fields: IFieldType[]) { }; return [ - ...dateFields.map(field => ({ + ...dateFields.map((field) => ({ display: field.name, fieldName: field.name, })), diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_indices.test.ts b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_indices.test.ts index 1c67fea9fa352..b1faca8a04964 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_indices.test.ts +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_indices.test.ts @@ -92,7 +92,7 @@ function esClientFactory(search: (params: any) => any): LegacyApiCaller { search, msearch: () => ({ abort: () => {}, - ...new Promise(resolve => resolve({})), + ...new Promise((resolve) => resolve({})), }), }; } @@ -120,7 +120,7 @@ describe('getIndices', () => { it('should trim the input', async () => { let index; const esClient = esClientFactory( - jest.fn().mockImplementation(params => { + jest.fn().mockImplementation((params) => { index = params.index; }) ); @@ -132,7 +132,7 @@ describe('getIndices', () => { it('should use the limit', async () => { let limit; const esClient = esClientFactory( - jest.fn().mockImplementation(params => { + jest.fn().mockImplementation((params) => { limit = params.body.aggs.indices.terms.size; }) ); diff --git a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_matched_indices.ts b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_matched_indices.ts index cc3fd4075aa0e..7e2eeb17ab387 100644 --- a/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_matched_indices.ts +++ b/src/plugins/index_pattern_management/public/components/create_index_pattern_wizard/lib/get_matched_indices.ts @@ -41,7 +41,7 @@ function filterSystemIndices(indices: MatchedIndex[], isIncludingSystemIndices: const acceptableIndices = isIncludingSystemIndices ? indices : // All system indices begin with a period. - indices.filter(index => !isSystemIndex(index.name)); + indices.filter((index) => !isSystemIndex(index.name)); return acceptableIndices.slice(0, MAX_NUMBER_OF_MATCHING_INDICES); } diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/create_edit_field/create_edit_field.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/create_edit_field/create_edit_field.tsx index fb5c27774f506..2d2f084adccc8 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/create_edit_field/create_edit_field.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/create_edit_field/create_edit_field.tsx @@ -21,9 +21,9 @@ import { withRouter, RouteComponentProps } from 'react-router-dom'; import { EuiFlexGroup, EuiFlexItem, EuiPanel } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { HttpStart, DocLinksStart } from 'src/core/public'; -import { ChromeDocTitle, NotificationsStart, IUiSettingsClient } from 'src/core/public'; -import { IndexPattern, DataPublicPluginStart } from '../../../../../../plugins/data/public'; +import { IndexPattern } from '../../../../../../plugins/data/public'; +import { useKibana } from '../../../../../../plugins/kibana_react/public'; +import { IndexPatternManagmentContext } from '../../../types'; import { IndexHeader } from '../index_header'; import { TAB_SCRIPTED_FIELDS, TAB_INDEXED_FIELDS } from '../constants'; @@ -33,17 +33,6 @@ interface CreateEditFieldProps extends RouteComponentProps { indexPattern: IndexPattern; mode?: string; fieldName?: string; - fieldFormatEditors: any; - services: { - uiSettings: IUiSettingsClient; - docTitle: ChromeDocTitle; - http: HttpStart; - docLinksScriptedFields: DocLinksStart['links']['scriptedFields']; - SearchBar: DataPublicPluginStart['ui']['SearchBar']; - toasts: NotificationsStart['toasts']; - fieldFormats: DataPublicPluginStart['fieldFormats']; - indexPatterns: DataPublicPluginStart['indexPatterns']; - }; } const newFieldPlaceholder = i18n.translate( @@ -54,18 +43,14 @@ const newFieldPlaceholder = i18n.translate( ); export const CreateEditField = withRouter( - ({ - indexPattern, - mode, - fieldName, - fieldFormatEditors, - services, - history, - }: CreateEditFieldProps) => { + ({ indexPattern, mode, fieldName, history }: CreateEditFieldProps) => { + const { data, uiSettings, chrome, notifications } = useKibana< + IndexPatternManagmentContext + >().services; const field = mode === 'edit' && fieldName ? indexPattern.fields.getByName(fieldName) - : services.indexPatterns.createField( + : data.indexPatterns.createField( indexPattern, { scripted: true, @@ -85,13 +70,13 @@ export const CreateEditField = withRouter( values: { indexPatternTitle: indexPattern.title, fieldName }, } ); - services.toasts.addWarning(message); + notifications.toasts.addWarning(message); history.push(url); } const docFieldName = field?.name || newFieldPlaceholder; - services.docTitle.change([docFieldName, indexPattern.title]); + chrome.docTitle.change([docFieldName, indexPattern.title]); const redirectAway = () => { history.push(`${url}?_a=(tab:${field?.scripted ? TAB_SCRIPTED_FIELDS : TAB_INDEXED_FIELDS})`); @@ -104,7 +89,7 @@ export const CreateEditField = withRouter( @@ -112,15 +97,7 @@ export const CreateEditField = withRouter( indexPattern={indexPattern} field={field} services={{ - uiSettings: services.uiSettings, - http: services.http, - fieldFormatEditors, redirectAway, - docLinksScriptedFields: services.docLinksScriptedFields, - SearchBar: services.SearchBar, - toasts: services.toasts, - fieldFormats: services.fieldFormats, - indexPatterns: services.indexPatterns, }} /> diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/create_edit_field/create_edit_field_container.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/create_edit_field/create_edit_field_container.tsx index 70851b712d756..39c0add40e9ad 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/create_edit_field/create_edit_field_container.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/create_edit_field/create_edit_field_container.tsx @@ -20,53 +20,30 @@ import React, { useEffect, useState } from 'react'; import { withRouter, RouteComponentProps } from 'react-router-dom'; -import { - HttpStart, - DocLinksStart, - ChromeDocTitle, - NotificationsStart, - IUiSettingsClient, -} from 'src/core/public'; - -import { IndexPattern, DataPublicPluginStart } from '../../../../../../plugins/data/public'; -import { ManagementAppMountParams } from '../../../../../management/public'; +import { IndexPattern } from '../../../../../../plugins/data/public'; import { getEditFieldBreadcrumbs, getCreateFieldBreadcrumbs } from '../../breadcrumbs'; +import { useKibana } from '../../../../../../plugins/kibana_react/public'; +import { IndexPatternManagmentContext } from '../../../types'; import { CreateEditField } from './create_edit_field'; -export interface CreateEditFieldContainerProps - extends RouteComponentProps<{ id: string; fieldName: string }> { - getIndexPattern: (id: string) => Promise; - fieldFormatEditors: any; - getConfig: IUiSettingsClient; - services: { - uiSettings: IUiSettingsClient; - notifications: NotificationsStart; - docTitle: ChromeDocTitle; - http: HttpStart; - docLinksScriptedFields: DocLinksStart['links']['scriptedFields']; - SearchBar: DataPublicPluginStart['ui']['SearchBar']; - toasts: NotificationsStart['toasts']; - fieldFormats: DataPublicPluginStart['fieldFormats']; - indexPatterns: DataPublicPluginStart['indexPatterns']; - setBreadcrumbs: ManagementAppMountParams['setBreadcrumbs']; - }; -} +export type CreateEditFieldContainerProps = RouteComponentProps<{ id: string; fieldName: string }>; const CreateEditFieldCont: React.FC = ({ ...props }) => { + const { setBreadcrumbs, data } = useKibana().services; const [indexPattern, setIndexPattern] = useState(); useEffect(() => { - props.getIndexPattern(props.match.params.id).then((ip: IndexPattern) => { + data.indexPatterns.get(props.match.params.id).then((ip: IndexPattern) => { setIndexPattern(ip); if (ip) { - props.services.setBreadcrumbs( + setBreadcrumbs( props.match.params.fieldName ? getEditFieldBreadcrumbs(ip, props.match.params.fieldName) : getCreateFieldBreadcrumbs(ip) ); } }); - }, [props.match.params.id, props.getIndexPattern, props]); + }, [props.match.params.id, props.match.params.fieldName, setBreadcrumbs, data.indexPatterns]); if (indexPattern) { return ( @@ -74,17 +51,6 @@ const CreateEditFieldCont: React.FC = ({ ...props indexPattern={indexPattern} mode={props.match.params.fieldName ? 'edit' : 'create'} fieldName={props.match.params.fieldName} - fieldFormatEditors={props.fieldFormatEditors} - services={{ - uiSettings: props.services.uiSettings, - http: props.services.http, - docLinksScriptedFields: props.services.docLinksScriptedFields, - SearchBar: props.services.SearchBar, - toasts: props.services.toasts, - fieldFormats: props.services.fieldFormats, - docTitle: props.services.docTitle, - indexPatterns: props.services.indexPatterns, - }} /> ); } else { diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern.tsx index f1c020cc409e0..eab8b2c231c9c 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern.tsx @@ -33,31 +33,16 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { - ChromeDocTitle, - NotificationsStart, - OverlayStart, - IUiSettingsClient, - SavedObjectsClientContract, -} from 'src/core/public'; import { IndexPattern, IndexPatternField } from '../../../../../plugins/data/public'; -import { IndexPatternManagementStart } from '../..'; +import { useKibana } from '../../../../../plugins/kibana_react/public'; +import { IndexPatternManagmentContext } from '../../types'; import { Tabs } from './tabs'; import { IndexHeader } from './index_header'; import { IndexPatternTableItem } from '../types'; import { getIndexPatterns } from '../utils'; -interface EditIndexPatternProps extends RouteComponentProps { +export interface EditIndexPatternProps extends RouteComponentProps { indexPattern: IndexPattern; - config: IUiSettingsClient; - services: { - notifications: NotificationsStart; - docTitle: ChromeDocTitle; - overlays: OverlayStart; - savedObjectsClient: SavedObjectsClientContract; - indexPatternManagement: IndexPatternManagementStart; - painlessDocLink: string; - }; } const mappingAPILink = i18n.translate( @@ -97,68 +82,69 @@ const confirmModalOptionsDelete = { }; export const EditIndexPattern = withRouter( - ({ indexPattern, config, services, history, location }: EditIndexPatternProps) => { + ({ indexPattern, history, location }: EditIndexPatternProps) => { + const { uiSettings, indexPatternManagementStart, overlays, savedObjects, chrome } = useKibana< + IndexPatternManagmentContext + >().services; const [fields, setFields] = useState(indexPattern.getNonScriptedFields()); const [conflictedFields, setConflictedFields] = useState( - indexPattern.fields.filter(field => field.type === 'conflict') + indexPattern.fields.filter((field) => field.type === 'conflict') ); - const [defaultIndex, setDefaultIndex] = useState(config.get('defaultIndex')); + const [defaultIndex, setDefaultIndex] = useState(uiSettings.get('defaultIndex')); const [tags, setTags] = useState([]); useEffect(() => { setFields(indexPattern.getNonScriptedFields()); - setConflictedFields(indexPattern.fields.filter(field => field.type === 'conflict')); + setConflictedFields(indexPattern.fields.filter((field) => field.type === 'conflict')); }, [indexPattern]); useEffect(() => { const indexPatternTags = - services.indexPatternManagement.list.getIndexPatternTags( + indexPatternManagementStart.list.getIndexPatternTags( indexPattern, indexPattern.id === defaultIndex ) || []; setTags(indexPatternTags); - }, [defaultIndex, indexPattern, services.indexPatternManagement.list]); + }, [defaultIndex, indexPattern, indexPatternManagementStart.list]); const setDefaultPattern = useCallback(() => { - config.set('defaultIndex', indexPattern.id); + uiSettings.set('defaultIndex', indexPattern.id); setDefaultIndex(indexPattern.id || ''); - }, [config, indexPattern.id]); + }, [uiSettings, indexPattern.id]); const refreshFields = () => { - services.overlays - .openConfirm(confirmMessage, confirmModalOptionsRefresh) - .then(async isConfirmed => { - if (isConfirmed) { - await indexPattern.init(true); - setFields(indexPattern.getNonScriptedFields()); - } - }); + overlays.openConfirm(confirmMessage, confirmModalOptionsRefresh).then(async (isConfirmed) => { + if (isConfirmed) { + await indexPattern.init(true); + setFields(indexPattern.getNonScriptedFields()); + } + }); }; - const removePatternClick = () => { + const removePattern = () => { async function doRemove() { if (indexPattern.id === defaultIndex) { const indexPatterns: IndexPatternTableItem[] = await getIndexPatterns( - services.savedObjectsClient, - config.get('defaultIndex'), - services.indexPatternManagement + savedObjects.client, + uiSettings.get('defaultIndex'), + indexPatternManagementStart ); - config.remove('defaultIndex'); - const otherPatterns = filter(indexPatterns, pattern => { + uiSettings.remove('defaultIndex'); + const otherPatterns = filter(indexPatterns, (pattern) => { return pattern.id !== indexPattern.id; }); if (otherPatterns.length) { - config.set('defaultIndex', otherPatterns[0].id); + uiSettings.set('defaultIndex', otherPatterns[0].id); } } - Promise.resolve(indexPattern.destroy()).then(function() { + Promise.resolve(indexPattern.destroy()).then(function () { history.push(''); }); } - services.overlays.openConfirm('', confirmModalOptionsDelete).then(isConfirmed => { + overlays.openConfirm('', confirmModalOptionsDelete).then((isConfirmed) => { if (isConfirmed) { doRemove(); } @@ -186,7 +172,7 @@ export const EditIndexPattern = withRouter( defaultMessage: 'Index pattern details', }); - services.docTitle.change(indexPattern.title); + chrome.docTitle.change(indexPattern.title); const showTagsSection = Boolean(indexPattern.timeFieldName || (tags && tags.length > 0)); @@ -199,7 +185,7 @@ export const EditIndexPattern = withRouter( indexPattern={indexPattern} setDefault={setDefaultPattern} refreshFields={refreshFields} - deleteIndexPatternClick={removePatternClick} + deleteIndexPatternClick={removePattern} defaultIndex={defaultIndex} /> @@ -244,11 +230,6 @@ export const EditIndexPattern = withRouter( diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern_container.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern_container.tsx index 2f02765cd0596..9bd42ed8d64ee 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern_container.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern_container.tsx @@ -19,52 +19,26 @@ import React, { useEffect, useState } from 'react'; import { withRouter, RouteComponentProps } from 'react-router-dom'; -import { - ChromeDocTitle, - NotificationsStart, - OverlayStart, - IUiSettingsClient, - SavedObjectsClientContract, -} from 'src/core/public'; import { IndexPattern } from '../../../../../plugins/data/public'; -import { ManagementAppMountParams } from '../../../../management/public'; -import { IndexPatternManagementStart } from '../..'; +import { useKibana } from '../../../../../plugins/kibana_react/public'; +import { IndexPatternManagmentContext } from '../../types'; import { getEditBreadcrumbs } from '../breadcrumbs'; import { EditIndexPattern } from '../edit_index_pattern'; -interface EditIndexPatternContainerProps extends RouteComponentProps<{ id: string }> { - getIndexPattern: (id: string) => Promise; - config: IUiSettingsClient; - services: { - notifications: NotificationsStart; - docTitle: ChromeDocTitle; - overlays: OverlayStart; - savedObjectsClient: SavedObjectsClientContract; - setBreadcrumbs: ManagementAppMountParams['setBreadcrumbs']; - indexPatternManagement: IndexPatternManagementStart; - painlessDocLink: string; - }; -} - -const EditIndexPatternCont: React.FC = ({ ...props }) => { +const EditIndexPatternCont: React.FC> = ({ ...props }) => { + const { data, setBreadcrumbs } = useKibana().services; const [indexPattern, setIndexPattern] = useState(); useEffect(() => { - props.getIndexPattern(props.match.params.id).then((ip: IndexPattern) => { + data.indexPatterns.get(props.match.params.id).then((ip: IndexPattern) => { setIndexPattern(ip); - props.services.setBreadcrumbs(getEditBreadcrumbs(ip)); + setBreadcrumbs(getEditBreadcrumbs(ip)); }); - }, [props.match.params.id, props.getIndexPattern, props]); + }, [data.indexPatterns, props.match.params.id, setBreadcrumbs]); if (indexPattern) { - return ( - - ); + return ; } else { return <>; } diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern_state_container.ts b/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern_state_container.ts index f99a5b072b423..1febef1b3bb75 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern_state_container.ts +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/edit_index_pattern_state_container.ts @@ -69,7 +69,7 @@ export function createEditIndexPatternPageStateContainer({ stateContainer: { ...stateContainer, // state syncing utility requires state containers to handle "null" - set: state => state && stateContainer.set(state), + set: (state) => state && stateContainer.set(state), }, stateStorage: kbnUrlStateStorage, }); diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.test.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.test.tsx index 2f3360880479c..8c024fa7adcf5 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.test.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.test.tsx @@ -71,7 +71,7 @@ describe('IndexedFieldsTable', () => { /> ); - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); component.update(); expect(component).toMatchSnapshot(); @@ -91,7 +91,7 @@ describe('IndexedFieldsTable', () => { /> ); - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); component.setProps({ fieldFilter: 'Elast' }); component.update(); @@ -112,7 +112,7 @@ describe('IndexedFieldsTable', () => { /> ); - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); component.setProps({ indexedFieldTypeFilter: 'date' }); component.update(); diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.tsx index 6b1048d3c9d0c..3344c46c35ac6 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/indexed_fields_table/indexed_fields_table.tsx @@ -73,7 +73,7 @@ export class IndexedFieldsTable extends Component< return ( (fields && - fields.map(field => { + fields.map((field) => { return { ...field, displayName: field.displayName, @@ -95,11 +95,11 @@ export class IndexedFieldsTable extends Component< (fields, fieldFilter, indexedFieldTypeFilter) => { if (fieldFilter) { const normalizedFieldFilter = fieldFilter.toLowerCase(); - fields = fields.filter(field => field.name.toLowerCase().includes(normalizedFieldFilter)); + fields = fields.filter((field) => field.name.toLowerCase().includes(normalizedFieldFilter)); } if (indexedFieldTypeFilter) { - fields = fields.filter(field => field.type === indexedFieldTypeFilter); + fields = fields.filter((field) => field.type === indexedFieldTypeFilter); } return fields; @@ -115,7 +115,7 @@ export class IndexedFieldsTable extends Component< this.props.helpers.redirectToRoute(field)} + editField={(field) => this.props.helpers.redirectToRoute(field)} /> ); diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx index 32520eadaf199..532af2757915b 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/scripted_fields_table.tsx @@ -95,7 +95,7 @@ export class ScriptedFieldsTable extends Component< if (scriptedFieldLanguageFilter) { languageFilteredFields = fields.filter( - field => field.lang === this.props.scriptedFieldLanguageFilter + (field) => field.lang === this.props.scriptedFieldLanguageFilter ); } @@ -104,7 +104,7 @@ export class ScriptedFieldsTable extends Component< if (fieldFilter) { const normalizedFieldFilter = fieldFilter.toLowerCase(); - filteredFields = languageFilteredFields.filter(field => + filteredFields = languageFilteredFields.filter((field) => field.name.toLowerCase().includes(normalizedFieldFilter) ); } @@ -151,7 +151,7 @@ export class ScriptedFieldsTable extends Component<
this.props.helpers.redirectToRoute(field)} + editField={(field) => this.props.helpers.redirectToRoute(field)} deleteField={this.startDeleteField} /> diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/add_filter/add_filter.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/add_filter/add_filter.tsx index 2a5e29827ccc5..1d840743065a1 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/add_filter/add_filter.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/add_filter/add_filter.tsx @@ -49,7 +49,7 @@ export const AddFilter = ({ onAddFilter }: AddFilterProps) => { setFilter(e.target.value.trim())} + onChange={(e) => setFilter(e.target.value.trim())} placeholder={sourcePlaceholder} /> diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/table/table.test.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/table/table.test.tsx index 421b5b67c2288..ab5a253a98e29 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/table/table.test.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/components/table/table.test.tsx @@ -103,10 +103,7 @@ describe('Table', () => { // Wrap in a div because: https://github.com/airbnb/enzyme/issues/1213
{getTableColumnRender(component, 2).render({ clientId, value: 'tim*' })}
); - editingComponent - .find('EuiButtonIcon') - .at(1) - .simulate('click'); + editingComponent.find('EuiButtonIcon').at(1).simulate('click'); // Ensure the state change propagates component.update(); @@ -123,10 +120,7 @@ describe('Table', () => {
{getTableColumnRender(component, 2).render({ clientId, value: 'tim*' })}
); - editingComponent - .find('EuiButtonIcon') - .at(1) - .simulate('click'); + editingComponent.find('EuiButtonIcon').at(1).simulate('click'); // Ensure the state change propagates component.update(); @@ -159,10 +153,7 @@ describe('Table', () => {
{localComponent.prop('columns')[2].render({ clientId, value: 'tim*' })}
); - editingComponent - .find('EuiButtonIcon') - .at(1) - .simulate('click'); + editingComponent.find('EuiButtonIcon').at(1).simulate('click'); // Update the value localComponent.setState({ editingFilterValue: 'time*' }); @@ -191,10 +182,7 @@ describe('Table', () => {
{getTableColumnRender(component, 2).render({ clientId, value: 'tim*' })}
); - editingComponent - .find('EuiButtonIcon') - .at(0) - .simulate('click'); + editingComponent.find('EuiButtonIcon').at(0).simulate('click'); editingComponent.update(); @@ -228,10 +216,7 @@ describe('Table', () => { // Fixes Invariant Violation: ReactShallowRenderer render(): Shallow rendering works only with custom components, but the provided element type was `symbol`.
{component.prop('columns')[2].render({ clientId: 1, value: 'tim*' })}
); - deleteCellComponent - .find('EuiButtonIcon') - .at(1) - .simulate('click'); + deleteCellComponent.find('EuiButtonIcon').at(1).simulate('click'); expect(deleteFilter).toBeCalled(); }); @@ -254,10 +239,7 @@ describe('Table', () => { // Fixes Invariant Violation: ReactShallowRenderer render(): Shallow rendering works only with custom components, but the provided element type was `symbol`.
{component.prop('columns')[2].render({ clientId: 1, value: 'tim*' })}
); - editingComponent - .find('EuiButtonIcon') - .at(0) - .simulate('click'); + editingComponent.find('EuiButtonIcon').at(0).simulate('click'); component.update(); @@ -295,10 +277,7 @@ describe('Table', () => {
{component.prop('columns')[2].render({ clientId: 1, value: 'tim*' })}
); - editingComponent - .find('EuiButtonIcon') - .at(0) - .simulate('click'); + editingComponent.find('EuiButtonIcon').at(0).simulate('click'); // Ensure the state change propagates component.update(); diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/source_filters_table.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/source_filters_table.tsx index ccdda3915e979..e5c753886ea9f 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/source_filters_table.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/source_filters_table/source_filters_table.tsx @@ -80,7 +80,7 @@ export class SourceFiltersTable extends Component< (filters, filterFilter) => { if (filterFilter) { const filterFilterToLowercase = filterFilter.toLowerCase(); - return filters.filter(filter => + return filters.filter((filter) => filter.value.toLowerCase().includes(filterFilterToLowercase) ); } @@ -107,7 +107,7 @@ export class SourceFiltersTable extends Component< const { indexPattern, onAddOrRemoveFilter } = this.props; const { filterToDelete, filters } = this.state; - indexPattern.sourceFilters = filters.filter(filter => { + indexPattern.sourceFilters = filters.filter((filter) => { return filter.clientId !== filterToDelete.clientId; }); @@ -143,7 +143,7 @@ export class SourceFiltersTable extends Component< const { indexPattern } = this.props; const { filters } = this.state; - indexPattern.sourceFilters = filters.map(filter => { + indexPattern.sourceFilters = filters.map((filter) => { if (filter.clientId === clientId) { return { value, diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/tabs.tsx b/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/tabs.tsx index 5cf7fd9b2af06..719df9d8d4cb5 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/tabs.tsx +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/tabs.tsx @@ -31,9 +31,9 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { fieldWildcardMatcher } from '../../../../../kibana_utils/public'; -import { IndexPatternManagementStart } from '../../../../../index_pattern_management/public'; -import { IndexPattern, IndexPatternField } from '../../../../../data/public'; -import { META_FIELDS_SETTING } from '../../../../../data/common'; +import { IndexPattern, IndexPatternField } from '../../../../../../plugins/data/public'; +import { useKibana } from '../../../../../../plugins/kibana_react/public'; +import { IndexPatternManagmentContext } from '../../../types'; import { createEditIndexPatternPageStateContainer } from '../edit_index_pattern_state_container'; import { TAB_INDEXED_FIELDS, TAB_SCRIPTED_FIELDS, TAB_SOURCE_FILTERS } from '../constants'; import { SourceFiltersTable } from '../source_filters_table'; @@ -43,12 +43,7 @@ import { getTabs, getPath, convertToEuiSelectOption } from './utils'; interface TabsProps extends Pick { indexPattern: IndexPattern; - config: Record; fields: IndexPatternField[]; - services: { - indexPatternManagement: IndexPatternManagementStart; - painlessDocLink: string; - }; } const searchAriaLabel = i18n.translate( @@ -72,7 +67,10 @@ const filterPlaceholder = i18n.translate( } ); -export function Tabs({ config, indexPattern, fields, services, history, location }: TabsProps) { +export function Tabs({ indexPattern, fields, history, location }: TabsProps) { + const { uiSettings, indexPatternManagementStart, docLinks } = useKibana< + IndexPatternManagmentContext + >().services; const [fieldFilter, setFieldFilter] = useState(''); const [indexedFieldTypeFilter, setIndexedFieldTypeFilter] = useState(''); const [scriptedFieldLanguageFilter, setScriptedFieldLanguageFilter] = useState(''); @@ -85,7 +83,7 @@ export function Tabs({ config, indexPattern, fields, services, history, location const refreshFilters = useCallback(() => { const tempIndexedFieldTypes: string[] = []; const tempScriptedFieldLanguages: string[] = []; - indexPattern.fields.forEach(field => { + indexPattern.fields.forEach((field) => { if (field.scripted) { if (field.lang) { tempScriptedFieldLanguages.push(field.lang); @@ -106,8 +104,8 @@ export function Tabs({ config, indexPattern, fields, services, history, location }, [indexPattern, indexPattern.fields, refreshFilters]); const fieldWildcardMatcherDecorated = useCallback( - (filters: string[]) => fieldWildcardMatcher(filters, config.get(META_FIELDS_SETTING)), - [config] + (filters: string[]) => fieldWildcardMatcher(filters, uiSettings.get('metaFields')), + [uiSettings] ); const getFilterSection = useCallback( @@ -118,7 +116,7 @@ export function Tabs({ config, indexPattern, fields, services, history, location setFieldFilter(e.target.value)} + onChange={(e) => setFieldFilter(e.target.value)} data-test-subj="indexPatternFieldFilter" aria-label={searchAriaLabel} /> @@ -128,7 +126,7 @@ export function Tabs({ config, indexPattern, fields, services, history, location setIndexedFieldTypeFilter(e.target.value)} + onChange={(e) => setIndexedFieldTypeFilter(e.target.value)} data-test-subj="indexedFieldTypeFilterDropdown" aria-label={filterAriaLabel} /> @@ -139,7 +137,7 @@ export function Tabs({ config, indexPattern, fields, services, history, location setScriptedFieldLanguageFilter(e.target.value)} + onChange={(e) => setScriptedFieldLanguageFilter(e.target.value)} data-test-subj="scriptedFieldLanguageFilterDropdown" /> @@ -175,7 +173,7 @@ export function Tabs({ config, indexPattern, fields, services, history, location redirectToRoute: (field: IndexPatternField) => { history.push(getPath(field)); }, - getFieldInfo: services.indexPatternManagement.list.getFieldInfo, + getFieldInfo: indexPatternManagementStart.list.getFieldInfo, }} /> @@ -196,7 +194,7 @@ export function Tabs({ config, indexPattern, fields, services, history, location }, }} onRemoveField={refreshFilters} - painlessDocLink={services.painlessDocLink} + painlessDocLink={docLinks.links.scriptedFields.painless} /> ); @@ -217,23 +215,23 @@ export function Tabs({ config, indexPattern, fields, services, history, location } }, [ + docLinks.links.scriptedFields.painless, fieldFilter, fieldWildcardMatcherDecorated, fields, getFilterSection, history, indexPattern, + indexPatternManagementStart.list.getFieldInfo, indexedFieldTypeFilter, refreshFilters, scriptedFieldLanguageFilter, - services.indexPatternManagement.list.getFieldInfo, - services.painlessDocLink, ] ); const euiTabs: EuiTabbedContentTab[] = useMemo( () => - getTabs(indexPattern, fieldFilter, services.indexPatternManagement.list).map( + getTabs(indexPattern, fieldFilter, indexPatternManagementStart.list).map( (tab: Pick) => { return { ...tab, @@ -241,7 +239,7 @@ export function Tabs({ config, indexPattern, fields, services, history, location }; } ), - [fieldFilter, getContent, indexPattern, services.indexPatternManagement.list] + [fieldFilter, getContent, indexPattern, indexPatternManagementStart.list] ); const [selectedTabId, setSelectedTabId] = useState(euiTabs[0].id); @@ -253,7 +251,7 @@ export function Tabs({ config, indexPattern, fields, services, history, location setCurrentTab, getCurrentTab, } = createEditIndexPatternPageStateContainer({ - useHashedUrl: config.get('state:storeInSessionStorage'), + useHashedUrl: uiSettings.get('state:storeInSessionStorage'), defaultTab: TAB_INDEXED_FIELDS, }); @@ -267,13 +265,13 @@ export function Tabs({ config, indexPattern, fields, services, history, location return () => { stopSyncingState(); }; - }, [config]); + }, [uiSettings]); return ( tab.id === selectedTabId)} - onTabClick={tab => { + selectedTab={euiTabs.find((tab) => tab.id === selectedTabId)} + onTabClick={(tab) => { setSelectedTabId(tab.id); syncingStateFunc.setCurrentTab(tab.id); }} diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/utils.ts b/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/utils.ts index b9b59142290dc..3088990aae981 100644 --- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/utils.ts +++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/tabs/utils.ts @@ -25,7 +25,7 @@ import { TAB_INDEXED_FIELDS, TAB_SCRIPTED_FIELDS, TAB_SOURCE_FILTERS } from '../ function filterByName(items: IndexPatternField[], filter: string) { const lowercaseFilter = (filter || '').toLowerCase(); - return items.filter(item => item.name.toLowerCase().includes(lowercaseFilter)); + return items.filter((item) => item.name.toLowerCase().includes(lowercaseFilter)); } function getCounts( @@ -35,7 +35,7 @@ function getCounts( }, fieldFilter = '' ) { - const fieldCount = countBy(filterByName(fields, fieldFilter), function(field) { + const fieldCount = countBy(filterByName(fields, fieldFilter), function (field) { return field.scripted ? 'scripted' : 'indexed'; }); @@ -43,7 +43,7 @@ function getCounts( indexed: 0, scripted: 0, sourceFilters: sourceFilters.excludes - ? sourceFilters.excludes.filter(value => + ? sourceFilters.excludes.filter((value) => value.toLowerCase().includes(fieldFilter.toLowerCase()) ).length : 0, @@ -145,7 +145,7 @@ export function convertToEuiSelectOption(options: string[], type: string) { ] : []; return euiOptions.concat( - unique(options).map(option => { + unique(options).map((option) => { return { value: option, text: option, diff --git a/src/plugins/index_pattern_management/public/components/field_editor/__snapshots__/field_editor.test.tsx.snap b/src/plugins/index_pattern_management/public/components/field_editor/__snapshots__/field_editor.test.tsx.snap index a7ed4e1c9cafd..6bc99c356592e 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/__snapshots__/field_editor.test.tsx.snap +++ b/src/plugins/index_pattern_management/public/components/field_editor/__snapshots__/field_editor.test.tsx.snap @@ -19,14 +19,10 @@ exports[`FieldEditor should render create new scripted field correctly 1`] = ` isVisible={false} /> , "painlessLink": { + onChange={(e) => { this.onColorChange( { regex: e.target.value, @@ -129,7 +129,7 @@ export class ColorFormatEditor extends DefaultFormatEditor { + onChange={(e) => { this.onColorChange( { range: e.target.value, @@ -153,7 +153,7 @@ export class ColorFormatEditor extends DefaultFormatEditor { + onChange={(newColor) => { this.onColorChange( { text: newColor, @@ -177,7 +177,7 @@ export class ColorFormatEditor extends DefaultFormatEditor { + onChange={(newColor) => { this.onColorChange( { background: newColor, diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date/date.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date/date.tsx index 55860707a3ee9..e75750210d9c5 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date/date.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date/date.tsx @@ -37,12 +37,8 @@ export class DateFormatEditor extends DefaultFormatEditor { + onChange={(e) => { this.onChange({ pattern: e.target.value }); }} isInvalid={!!error} diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date_nanos/date_nanos.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date_nanos/date_nanos.tsx index 25152370ac928..4c5227ae79118 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date_nanos/date_nanos.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/date_nanos/date_nanos.tsx @@ -77,7 +77,7 @@ export class DateNanosFormatEditor extends DefaultFormatEditor { + onChange={(e) => { this.onChange({ pattern: e.target.value }); }} isInvalid={!!error} diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/default/default.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/default/default.tsx index 68ece63c2efbe..de3038c3fd4f5 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/default/default.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/default/default.tsx @@ -34,7 +34,7 @@ export const convertSampleInput = ( let samples: Sample[] = []; try { - samples = inputs.map(input => { + samples = inputs.map((input) => { return { input, output: converter(input), diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/duration/duration.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/duration/duration.tsx index cdda56b4f1f51..bf25df069435f 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/duration/duration.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/duration/duration.tsx @@ -116,7 +116,7 @@ export class DurationFormatEditor extends DefaultFormatEditor< text: fmt.text, }; })} - onChange={e => { + onChange={(e) => { this.onChange({ inputFormat: e.target.value }); }} isInvalid={!!error} @@ -139,7 +139,7 @@ export class DurationFormatEditor extends DefaultFormatEditor< text: fmt.text, }; })} - onChange={e => { + onChange={(e) => { this.onChange({ outputFormat: e.target.value }); }} isInvalid={!!error} @@ -160,7 +160,7 @@ export class DurationFormatEditor extends DefaultFormatEditor< value={formatParams.outputPrecision} min={0} max={20} - onChange={e => { + onChange={(e) => { this.onChange({ outputPrecision: e.target.value ? Number(e.target.value) : null }); }} isInvalid={!!error} diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/number/number.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/number/number.tsx index 05771afdd33e2..62c88b195f8b6 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/number/number.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/number/number.tsx @@ -70,7 +70,7 @@ export class NumberFormatEditor extends DefaultFormatEditor { + onChange={(e) => { this.onChange({ pattern: e.target.value }); }} isInvalid={!!error} diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/static_lookup/static_lookup.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/static_lookup/static_lookup.tsx index fbbbb22e3d18f..0f80bfa681bf3 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/static_lookup/static_lookup.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/static_lookup/static_lookup.tsx @@ -93,7 +93,7 @@ export class StaticLookupFormatEditor extends DefaultFormatEditor< return ( { + onChange={(e) => { this.onLookupChange( { key: e.target.value, @@ -117,7 +117,7 @@ export class StaticLookupFormatEditor extends DefaultFormatEditor< return ( { + onChange={(e) => { this.onLookupChange( { value: e.target.value, @@ -182,7 +182,7 @@ export class StaticLookupFormatEditor extends DefaultFormatEditor< defaultMessage: 'Leave blank to keep value as-is', } )} - onChange={e => { + onChange={(e) => { this.onChange({ unknownKeyValue: e.target.value }); }} /> diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/string/string.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/string/string.tsx index d1befb77bae64..7a3bb6f5cd398 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/string/string.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/string/string.tsx @@ -74,7 +74,7 @@ export class StringFormatEditor extends DefaultFormatEditor { + onChange={(e) => { this.onChange({ transform: e.target.value }); }} isInvalid={!!error} diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/truncate/truncate.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/truncate/truncate.tsx index 9b4d5a0f033a9..3881940a78627 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/truncate/truncate.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/truncate/truncate.tsx @@ -58,7 +58,7 @@ export class TruncateFormatEditor extends DefaultFormatEditor { + onChange={(e) => { if (e.target.checkValidity()) { this.onChange({ fieldLength: e.target.value ? Number(e.target.value) : null, diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/url/url.tsx b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/url/url.tsx index 5b706f1627bce..30acf09526f85 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/url/url.tsx +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/field_format_editor/editors/url/url.tsx @@ -151,7 +151,7 @@ export class UrlFormatEditor extends DefaultFormatEditor< { + onChange={(e) => { this.onChange({ width: e.target.value }); }} /> @@ -164,7 +164,7 @@ export class UrlFormatEditor extends DefaultFormatEditor< { + onChange={(e) => { this.onChange({ height: e.target.value }); }} /> @@ -201,7 +201,7 @@ export class UrlFormatEditor extends DefaultFormatEditor< text: type.text, }; })} - onChange={e => { + onChange={(e) => { this.onTypeChange(e.target.value); }} /> @@ -225,7 +225,7 @@ export class UrlFormatEditor extends DefaultFormatEditor< ) } checked={!formatParams.openLinkInCurrentTab} - onChange={e => { + onChange={(e) => { this.onChange({ openLinkInCurrentTab: !e.target.checked }); }} /> @@ -253,7 +253,7 @@ export class UrlFormatEditor extends DefaultFormatEditor< { + onChange={(e) => { this.onChange({ urlTemplate: e.target.value }); }} /> @@ -280,7 +280,7 @@ export class UrlFormatEditor extends DefaultFormatEditor< { + onChange={(e) => { this.onChange({ labelTemplate: e.target.value }); }} /> diff --git a/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_call_outs/__snapshots__/warning_call_out.test.tsx.snap b/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_call_outs/__snapshots__/warning_call_out.test.tsx.snap index c9b5c84939bc6..2652e6b8ddd04 100644 --- a/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_call_outs/__snapshots__/warning_call_out.test.tsx.snap +++ b/src/plugins/index_pattern_management/public/components/field_editor/components/scripting_call_outs/__snapshots__/warning_call_out.test.tsx.snap @@ -1,7 +1,9 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`ScriptingWarningCallOut should render normally 1`] = ` - + } > -

- +

+
{ public async updateBeatsData(beatsKBar?: string) { const beats = sortBy(await this.props.libs.beats.getAll(beatsKBar), 'id') || []; - const tags = await this.props.libs.tags.getTagsWithIds(flatten(beats.map(beat => beat.tags))); + const tags = await this.props.libs.tags.getTagsWithIds(flatten(beats.map((beat) => beat.tags))); this.setState({ tags, @@ -172,7 +172,7 @@ class BeatsPageComponent extends React.PureComponent { path={`/overview/enrolled_beats`} /> - {autocompleteProps => ( + {(autocompleteProps) => (
{ break; } }} - items={this.state.beats.map(beat => ({ + items={this.state.beats.map((beat) => ({ ...beat, - tags: (this.state.tags || []).filter(tag => beat.tags.includes(tag.id)), + tags: (this.state.tags || []).filter((tag) => beat.tags.includes(tag.id)), }))} ref={this.tableRef} type={BeatsTableType} @@ -348,7 +348,7 @@ class BeatsPageComponent extends React.PureComponent { const selectedIds = this.tableRef.current.state.selection.map((beat: any) => beat.id); const beats: CMBeat[] = []; selectedIds.forEach((id: any) => { - const beat = this.props.containers.beats.state.list.find(b => b.id === id); + const beat = this.props.containers.beats.state.list.find((b) => b.id === id); if (beat) { beats.push(beat); } diff --git a/x-pack/plugins/beats_management/public/pages/tag/create.tsx b/x-pack/plugins/beats_management/public/pages/tag/create.tsx index 65fe8bf5d52c1..881bb433b1d9a 100644 --- a/x-pack/plugins/beats_management/public/pages/tag/create.tsx +++ b/x-pack/plugins/beats_management/public/pages/tag/create.tsx @@ -72,7 +72,7 @@ class TagCreatePageComponent extends React.PureComponent< total: this.state.configuration_blocks.length, }} onTagChange={(field: string, value: string | number) => - this.setState(oldState => ({ + this.setState((oldState) => ({ tag: { ...oldState.tag, [field]: value }, })) } @@ -82,13 +82,13 @@ class TagCreatePageComponent extends React.PureComponent< }); }} onConfigAddOrEdit={(block: ConfigurationBlock) => { - this.setState(previousState => ({ + this.setState((previousState) => ({ configuration_blocks: previousState.configuration_blocks.concat([block]), })); }} onConfigRemoved={(block: ConfigurationBlock) => { - this.setState(previousState => { - const selectedIndex = previousState.configuration_blocks.findIndex(c => { + this.setState((previousState) => { + const selectedIndex = previousState.configuration_blocks.findIndex((c) => { return isEqual(block, c); }); const blocks = [...previousState.configuration_blocks]; @@ -141,7 +141,7 @@ class TagCreatePageComponent extends React.PureComponent< ); } const createBlocksResponse = await this.props.libs.configBlocks.upsert( - this.state.configuration_blocks.map(block => ({ ...block, tag: this.state.tag.id })) + this.state.configuration_blocks.map((block) => ({ ...block, tag: this.state.tag.id })) ); const creationError = createBlocksResponse.results.reduce( (err: string, resp) => (!err ? (err = resp.error ? resp.error.message : '') : err), @@ -155,7 +155,7 @@ class TagCreatePageComponent extends React.PureComponent< }; private getNumExclusiveConfigurationBlocks = () => this.state.configuration_blocks - .map(({ type }) => UNIQUENESS_ENFORCING_TYPES.some(uniqueType => uniqueType === type)) + .map(({ type }) => UNIQUENESS_ENFORCING_TYPES.some((uniqueType) => uniqueType === type)) .reduce((acc, cur) => (cur ? acc + 1 : acc), 0); } diff --git a/x-pack/plugins/beats_management/public/pages/tag/edit.tsx b/x-pack/plugins/beats_management/public/pages/tag/edit.tsx index 918ae0bb6fcb2..10d7f7bbd7193 100644 --- a/x-pack/plugins/beats_management/public/pages/tag/edit.tsx +++ b/x-pack/plugins/beats_management/public/pages/tag/edit.tsx @@ -88,15 +88,15 @@ class TagEditPageComponent extends React.PureComponent< await this.loadAttachedBeats(); }} onTagChange={(field: string, value: string | number) => - this.setState(oldState => ({ + this.setState((oldState) => ({ tag: { ...oldState.tag, [field]: value }, })) } attachedBeats={ - (this.state.attachedBeats || []).map(beat => ({ + (this.state.attachedBeats || []).map((beat) => ({ ...beat, tags: flatten( - beat.tags.map(tagId => this.state.beatsTags.filter(tag => tag.id === tagId)) + beat.tags.map((tagId) => this.state.beatsTags.filter((tag) => tag.id === tagId)) ), })) as any } @@ -186,7 +186,7 @@ class TagEditPageComponent extends React.PureComponent< private loadAttachedBeats = async () => { const beats = await this.props.libs.beats.getBeatsWithTag(this.props.match.params.tagid); const beatsTags = await this.props.libs.tags.getTagsWithIds( - flatten(beats.map(beat => beat.tags)) + flatten(beats.map((beat) => beat.tags)) ); this.setState({ attachedBeats: beats, @@ -199,7 +199,7 @@ class TagEditPageComponent extends React.PureComponent< }; private getNumExclusiveConfigurationBlocks = () => this.state.configuration_blocks.list - .map(({ type }) => UNIQUENESS_ENFORCING_TYPES.some(uniqueType => uniqueType === type)) + .map(({ type }) => UNIQUENESS_ENFORCING_TYPES.some((uniqueType) => uniqueType === type)) .reduce((acc, cur) => (cur ? acc + 1 : acc), 0); } diff --git a/x-pack/plugins/beats_management/public/pages/walkthrough/initial/index.tsx b/x-pack/plugins/beats_management/public/pages/walkthrough/initial/index.tsx index a78bf3fa7cf8e..5b307692e8a4c 100644 --- a/x-pack/plugins/beats_management/public/pages/walkthrough/initial/index.tsx +++ b/x-pack/plugins/beats_management/public/pages/walkthrough/initial/index.tsx @@ -17,7 +17,7 @@ type Props = AppPageProps & { intl: InjectedIntl; }; -const InitialWalkthroughPageComponent: React.FC = props => { +const InitialWalkthroughPageComponent: React.FC = (props) => { if (props.location.pathname === '/walkthrough/initial') { return ( { total: this.state.configuration_blocks.length, }} onTagChange={(field: string, value: string | number) => - this.setState(oldState => ({ + this.setState((oldState) => ({ tag: { ...oldState.tag, [field]: value }, })) } @@ -63,13 +63,13 @@ export class InitialTagPage extends Component { }); }} onConfigAddOrEdit={(block: ConfigurationBlock) => { - this.setState(previousState => ({ + this.setState((previousState) => ({ configuration_blocks: previousState.configuration_blocks.concat([block]), })); }} onConfigRemoved={(block: ConfigurationBlock) => { - this.setState(previousState => { - const selectedIndex = previousState.configuration_blocks.findIndex(c => { + this.setState((previousState) => { + const selectedIndex = previousState.configuration_blocks.findIndex((c) => { return isEqual(block, c); }); const blocks = [...previousState.configuration_blocks]; @@ -121,7 +121,7 @@ export class InitialTagPage extends Component { ); } const createBlocksResponse = await this.props.libs.configBlocks.upsert( - this.state.configuration_blocks.map(block => ({ ...block, tag: this.state.tag.id })) + this.state.configuration_blocks.map((block) => ({ ...block, tag: this.state.tag.id })) ); const creationError = createBlocksResponse.results.reduce( (err: string, resp) => (!err ? (err = resp.error ? resp.error.message : '') : err), diff --git a/x-pack/plugins/beats_management/public/router.tsx b/x-pack/plugins/beats_management/public/router.tsx index ec7aceaa6d747..c23d0dd4aca99 100644 --- a/x-pack/plugins/beats_management/public/router.tsx +++ b/x-pack/plugins/beats_management/public/router.tsx @@ -62,7 +62,7 @@ export class AppRouter extends Component { {/* License check (UI displays when license exists but is expired) */} {get(this.props.libs.framework.info, 'license.expired', true) && ( + render={(props) => !props.location.pathname.includes('/error') ? ( ) : null @@ -73,7 +73,7 @@ export class AppRouter extends Component { {/* Ensure security is eanabled for elastic and kibana */} {!get(this.props.libs.framework.info, 'security.enabled', true) && ( + render={(props) => !props.location.pathname.includes('/error') ? ( ) : null @@ -86,7 +86,7 @@ export class AppRouter extends Component { ['beats_admin'].concat(this.props.libs.framework.info.settings.defaultUserRoles) ) && ( + render={(props) => !props.location.pathname.includes('/error') ? ( ) : null @@ -97,7 +97,7 @@ export class AppRouter extends Component { {/* If there are no beats or tags yet, redirect to the walkthrough */} {countOfEverything === 0 && ( + render={(props) => !props.location.pathname.includes('/walkthrough') ? ( ) : null diff --git a/x-pack/plugins/beats_management/public/utils/random_eui_color.ts b/x-pack/plugins/beats_management/public/utils/random_eui_color.ts index 5c358941f4bc3..edc3e2863a89a 100644 --- a/x-pack/plugins/beats_management/public/utils/random_eui_color.ts +++ b/x-pack/plugins/beats_management/public/utils/random_eui_color.ts @@ -8,8 +8,8 @@ import { sample } from 'lodash'; export const randomEUIColor = (euiVars: any) => { const rgb = sample( Object.keys(euiVars) - .filter(key => key.startsWith('euiColorVis')) - .map(key => (euiVars as any)[key]) + .filter((key) => key.startsWith('euiColorVis')) + .map((key) => (euiVars as any)[key]) ); const matchedrgb = rgb.match( diff --git a/x-pack/plugins/canvas/__tests__/fixtures/function_specs.ts b/x-pack/plugins/canvas/__tests__/fixtures/function_specs.ts index edf11f5a25c08..09b5e29cba87e 100644 --- a/x-pack/plugins/canvas/__tests__/fixtures/function_specs.ts +++ b/x-pack/plugins/canvas/__tests__/fixtures/function_specs.ts @@ -7,4 +7,4 @@ import { functions as browserFns } from '../../canvas_plugin_src/functions/browser'; import { ExpressionFunction } from '../../../../../src/plugins/expressions'; -export const functionSpecs = browserFns.map(fn => new ExpressionFunction(fn())); +export const functionSpecs = browserFns.map((fn) => new ExpressionFunction(fn())); diff --git a/x-pack/plugins/canvas/__tests__/fixtures/kibana.js b/x-pack/plugins/canvas/__tests__/fixtures/kibana.js index 4503adcec0c2c..e32041cd99f1a 100644 --- a/x-pack/plugins/canvas/__tests__/fixtures/kibana.js +++ b/x-pack/plugins/canvas/__tests__/fixtures/kibana.js @@ -24,10 +24,10 @@ export class Plugin { elasticsearch: mockElasticsearch, }, config: () => ({ - get: key => get(config, key), - has: key => has(config, key), + get: (key) => get(config, key), + has: (key) => has(config, key), }), - route: def => this.routes.push(def), + route: (def) => this.routes.push(def), }; const { init } = this.props; diff --git a/x-pack/plugins/canvas/__tests__/helpers/function_wrapper.js b/x-pack/plugins/canvas/__tests__/helpers/function_wrapper.js index 4f078169f699f..dc07932e70e0f 100644 --- a/x-pack/plugins/canvas/__tests__/helpers/function_wrapper.js +++ b/x-pack/plugins/canvas/__tests__/helpers/function_wrapper.js @@ -9,7 +9,7 @@ import { mapValues } from 'lodash'; // It takes a function spec and passes in default args into the spec fn export const functionWrapper = (fnSpec, mockReduxStore) => { const spec = fnSpec(); - const defaultArgs = mapValues(spec.args, argSpec => { + const defaultArgs = mapValues(spec.args, (argSpec) => { return argSpec.default; }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/elements/index.ts b/x-pack/plugins/canvas/canvas_plugin_src/elements/index.ts index ec3b8a7798be1..961b0cd034248 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/elements/index.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/elements/index.ts @@ -66,7 +66,7 @@ const initializeElementFactories = [metricElementInitializer]; export const initializeElements: SetupInitializer = (core, plugins) => { const specs = [ ...elementSpecs, - ...initializeElementFactories.map(factory => factory(core, plugins)), + ...initializeElementFactories.map((factory) => factory(core, plugins)), ]; return applyElementStrings(specs); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/location.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/location.ts index 1e13ebdee3e4b..4a01df3b0ac50 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/location.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/location.ts @@ -24,7 +24,7 @@ export function location(): ExpressionFunctionDefinition<'location', null, {}, P args: {}, help, fn: () => { - return new Promise(resolve => { + return new Promise((resolve) => { function createLocation(geoposition: Position) { const { latitude, longitude } = geoposition.coords; return resolve({ diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.test.js index 27ea290fb4dcc..71b6af6739408 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.test.js @@ -31,7 +31,7 @@ describe('markdown', () => { it('compiles and concatenates handlebars expressions using context', () => { let expectedContent = 'Columns:'; - testTable.columns.map(col => (expectedContent += ` ${col.name}`)); + testTable.columns.map((col) => (expectedContent += ` ${col.name}`)); const result = fn(testTable, { content: ['Columns:', '{{#each columns}} {{name}}{{/each}}'], diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.ts index e94b9f201a174..41323a82f4ee0 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/browser/markdown.ts @@ -62,7 +62,7 @@ export function markdown(): ExpressionFunctionDefinition< }, }, fn: (input, args) => { - const compileFunctions = args.content.map(str => + const compileFunctions = args.content.map((str) => Handlebars.compile(String(str), { knownHelpersOnly: true }) ); const ctx = { @@ -76,7 +76,7 @@ export function markdown(): ExpressionFunctionDefinition< type: 'render', as: 'markdown', value: { - content: compileFunctions.map(fn => fn(ctx)).join(''), + content: compileFunctions.map((fn) => fn(ctx)).join(''), font: args.font, openLinksInNewTab: args.openLinksInNewTab, }, diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__tests__/progress.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__tests__/progress.js index d53fe94d4a838..17f9defa15dc3 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__tests__/progress.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/__tests__/progress.js @@ -18,9 +18,7 @@ describe('progress', () => { it('returns a render as progress', () => { const result = fn(0.2); - expect(result) - .to.have.property('type', 'render') - .and.to.have.property('as', 'progress'); + expect(result).to.have.property('type', 'render').and.to.have.property('as', 'progress'); }); it('sets the progress to context', () => { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/alterColumn.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/alterColumn.ts index e6739a71b1608..68c1957c808a3 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/alterColumn.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/alterColumn.ts @@ -51,7 +51,7 @@ export function alterColumn(): ExpressionFunctionDefinition< return input; } - const column = input.columns.find(col => col.name === args.column); + const column = input.columns.find((col) => col.name === args.column); if (!column) { throw errors.columnNotFound(args.column); } @@ -94,7 +94,7 @@ export function alterColumn(): ExpressionFunctionDefinition< })(); } - const rows = input.rows.map(row => ({ + const rows = input.rows.map((row) => ({ ...omit(row, column.name), [name]: handler(row[column.name]), })); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/columns.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/columns.ts index 71c5376428a79..63d3102a19e9a 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/columns.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/columns.ts @@ -43,27 +43,27 @@ export function columns(): ExpressionFunctionDefinition< let result = { ...input }; if (exclude) { - const fields = exclude.split(',').map(field => field.trim()); - const cols = contextColumns.filter(col => !fields.includes(col.name)); - const rows = cols.length > 0 ? contextRows.map(row => omit(row, fields)) : []; + const fields = exclude.split(',').map((field) => field.trim()); + const cols = contextColumns.filter((col) => !fields.includes(col.name)); + const rows = cols.length > 0 ? contextRows.map((row) => omit(row, fields)) : []; result = { rows, columns: cols, ...rest }; } if (include) { - const fields = include.split(',').map(field => field.trim()); + const fields = include.split(',').map((field) => field.trim()); // const columns = result.columns.filter(col => fields.includes(col.name)); // Include columns in the order the user specified const cols: DatatableColumn[] = []; - fields.forEach(field => { + fields.forEach((field) => { const column = find(result.columns, { name: field }); if (column) { cols.push(column); } }); - const rows = cols.length > 0 ? result.rows.map(row => pick(row, fields)) : []; + const rows = cols.length > 0 ? result.rows.map((row) => pick(row, fields)) : []; result = { rows, columns: cols, ...rest }; } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/context.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/context.ts index d1302a1e579a1..bc87d6793e2f0 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/context.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/context.ts @@ -14,6 +14,6 @@ export function context(): ExpressionFunctionDefinition<'context', unknown, {}, name: 'context', help, args: {}, - fn: obj => obj, + fn: (obj) => obj, }; } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/do.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/do.ts index 5f0c848d76708..0fe45243ce721 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/do.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/do.ts @@ -23,6 +23,6 @@ export function doFn(): ExpressionFunctionDefinition<'do', unknown, Arguments, u help: argHelp.fn, }, }, - fn: context => context, + fn: (context) => context, }; } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/dropdownControl.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/dropdownControl.ts index 29a277283494a..7231f01671e02 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/dropdownControl.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/dropdownControl.ts @@ -53,7 +53,7 @@ export function dropdownControl(): ExpressionFunctionDefinition< let choices = []; if (input.rows[0][valueColumn]) { - choices = uniq(input.rows.map(row => row[valueColumn])).sort(); + choices = uniq(input.rows.map((row) => row[valueColumn])).sort(); } const column = filterColumn || valueColumn; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.test.js index 2f44655f60e44..179be8aff2e19 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.test.js @@ -8,29 +8,29 @@ import { functionWrapper } from '../../../__tests__/helpers/function_wrapper'; import { testTable } from './__tests__/fixtures/test_tables'; import { filterrows } from './filterrows'; -const inStock = datatable => datatable.rows[0].in_stock; +const inStock = (datatable) => datatable.rows[0].in_stock; const returnFalse = () => false; describe('filterrows', () => { const fn = functionWrapper(filterrows); it('returns a datable', () => { - return fn(testTable, { fn: inStock }).then(result => { + return fn(testTable, { fn: inStock }).then((result) => { expect(result).toHaveProperty('type', 'datatable'); }); }); it('keeps rows that evaluate to true and removes rows that evaluate to false', () => { - const inStockRows = testTable.rows.filter(row => row.in_stock); + const inStockRows = testTable.rows.filter((row) => row.in_stock); - return fn(testTable, { fn: inStock }).then(result => { + return fn(testTable, { fn: inStock }).then((result) => { expect(result.columns).toEqual(testTable.columns); expect(result.rows).toEqual(inStockRows); }); }); it('returns datatable with no rows when no rows meet function condition', () => { - return fn(testTable, { fn: returnFalse }).then(result => { + return fn(testTable, { fn: returnFalse }).then((result) => { expect(result.rows).toEqual([]); }); }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.ts index 17d5211588238..1f8b9f4c238cf 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/filterrows.ts @@ -35,7 +35,7 @@ export function filterrows(): ExpressionFunctionDefinition< }, }, fn(input, { fn }) { - const checks = input.rows.map(row => + const checks = input.rows.map((row) => fn({ ...input, rows: [row], @@ -43,9 +43,9 @@ export function filterrows(): ExpressionFunctionDefinition< ); return Promise.all(checks) - .then(results => input.rows.filter((row, i) => results[i])) + .then((results) => input.rows.filter((row, i) => results[i])) .then( - rows => + (rows) => ({ ...input, rows, diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/join_rows.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/join_rows.ts index 7f8a7b525180c..fd2b8c6e5d5e4 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/join_rows.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/join_rows.ts @@ -56,7 +56,7 @@ export function joinRows(): ExpressionFunctionDefinition<'joinRows', Datatable, }, }, fn: (input, { column, separator, quote, distinct }) => { - const columnMatch = input.columns.find(col => col.name === column); + const columnMatch = input.columns.find((col) => col.name === column); if (!columnMatch) { throw errors.columnNotFound(column); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.test.js index b170ebafd61c0..e5ef06d1503ee 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.test.js @@ -8,13 +8,13 @@ import { functionWrapper } from '../../../__tests__/helpers/function_wrapper'; import { testTable, emptyTable } from './__tests__/fixtures/test_tables'; import { mapColumn } from './mapColumn'; -const pricePlusTwo = datatable => Promise.resolve(datatable.rows[0].price + 2); +const pricePlusTwo = (datatable) => Promise.resolve(datatable.rows[0].price + 2); describe('mapColumn', () => { const fn = functionWrapper(mapColumn); it('returns a datatable with a new column with the values from mapping a function over each row in a datatable', () => { - return fn(testTable, { name: 'pricePlusTwo', expression: pricePlusTwo }).then(result => { + return fn(testTable, { name: 'pricePlusTwo', expression: pricePlusTwo }).then((result) => { const arbitraryRowIndex = 2; expect(result.type).toBe('datatable'); @@ -28,7 +28,7 @@ describe('mapColumn', () => { }); it('overwrites existing column with the new column if an existing column name is provided', () => { - return fn(testTable, { name: 'name', expression: pricePlusTwo }).then(result => { + return fn(testTable, { name: 'name', expression: pricePlusTwo }).then((result) => { const nameColumnIndex = result.columns.findIndex(({ name }) => name === 'name'); const arbitraryRowIndex = 4; @@ -41,7 +41,7 @@ describe('mapColumn', () => { }); it('adds a column to empty tables', () => { - return fn(emptyTable, { name: 'name', expression: pricePlusTwo }).then(result => { + return fn(emptyTable, { name: 'name', expression: pricePlusTwo }).then((result) => { expect(result.type).toBe('datatable'); expect(result.columns).toHaveLength(1); expect(result.columns[0]).toHaveProperty('name', 'name'); @@ -51,7 +51,7 @@ describe('mapColumn', () => { describe('expression', () => { it('maps null values to the new column', () => { - return fn(testTable, { name: 'empty' }).then(result => { + return fn(testTable, { name: 'empty' }).then((result) => { const emptyColumnIndex = result.columns.findIndex(({ name }) => name === 'empty'); const arbitraryRowIndex = 8; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.ts index d8b15a65252e6..7dd309cba5c64 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/mapColumn.ts @@ -45,18 +45,18 @@ export function mapColumn(): ExpressionFunctionDefinition< const expression = args.expression || (() => Promise.resolve(null)); const columns = [...input.columns]; - const rowPromises = input.rows.map(row => { + const rowPromises = input.rows.map((row) => { return expression({ type: 'datatable', columns, rows: [row], - }).then(val => ({ + }).then((val) => ({ ...row, [args.name]: val, })); }); - return Promise.all(rowPromises).then(rows => { + return Promise.all(rowPromises).then((rows) => { const existingColumnIndex = columns.findIndex(({ name }) => name === args.name); const type = rows.length ? getType(rows[0][args.name]) : 'null'; const newColumn = { name: args.name, type }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/math.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/math.ts index dfbb37be0797c..7f84dc54d8092 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/math.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/math.ts @@ -43,7 +43,7 @@ export function math(): ExpressionFunctionDefinition<'math', Input, Arguments, n const mathContext = isDatatable(input) ? pivotObjectArray( input.rows, - input.columns.map(col => col.name) + input.columns.map((col) => col.name) ) : { value: input }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.test.js index f1cccd1d8dda4..4ef6583096213 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.test.js @@ -56,7 +56,7 @@ describe('pie', () => { describe('seriesStyle', () => { it('sets the color for a specific series', () => { const result = fn(testPie, { seriesStyle: [seriesStyle] }).value; - const seriesIndex = result.data.findIndex(series => series.label === seriesStyle.label); + const seriesIndex = result.data.findIndex((series) => series.label === seriesStyle.label); const resultSeries = result.data[seriesIndex]; expect(resultSeries).toHaveProperty('color', seriesStyle.color); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.ts index 36f1bf85b97e7..6cb64a43ea582 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/pie.ts @@ -141,7 +141,7 @@ export function pie(): ExpressionFunctionDefinition<'pie', PointSeries, Argument const data: PieData[] = map(groupBy(input.rows, 'color'), (series, label = '') => { const item: PieData = { label, - data: series.map(point => point.size || 1), + data: series.map((point) => point.size || 1), }; const style = seriesStyles[label]; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot.test.js index 6ce2978b75d56..d983cb7429863 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot.test.js @@ -66,7 +66,7 @@ describe('plot', () => { describe('seriesStyle', () => { it('sets the seriesStyle for a specific series', () => { const result = fn(testPlot, { seriesStyle: [seriesStyle] }).value; - const seriesIndex = result.data.findIndex(series => series.label === seriesStyle.label); + const seriesIndex = result.data.findIndex((series) => series.label === seriesStyle.label); const resultSeries = result.data[seriesIndex]; expect(resultSeries.lines).toHaveProperty('lineWidth', seriesStyle.lines); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_tick_hash.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_tick_hash.ts index 64fa1b259ade6..4839db047c871 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_tick_hash.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/get_tick_hash.ts @@ -20,7 +20,7 @@ export const getTickHash = (columns: PointSeriesColumns, rows: DatatableRow[]) = }; if (get(columns, 'x.type') === 'string') { - sortBy(rows, ['x']).forEach(row => { + sortBy(rows, ['x']).forEach((row) => { if (!ticks.x.hash[row.x]) { ticks.x.hash[row.x] = ticks.x.counter++; } @@ -30,7 +30,7 @@ export const getTickHash = (columns: PointSeriesColumns, rows: DatatableRow[]) = if (get(columns, 'y.type') === 'string') { sortBy(rows, ['y']) .reverse() - .forEach(row => { + .forEach((row) => { if (!ticks.y.hash[row.y]) { ticks.y.hash[row.y] = ticks.y.counter++; } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.ts index 34e5d9f600d8d..e8214ca8eaf9f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.ts @@ -96,7 +96,7 @@ export function plot(): ExpressionFunctionDefinition<'plot', PointSeries, Argume return { ...flotStyle, label, - data: series.map(point => { + data: series.map((point) => { const attrs: { size?: number; text?: string; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.test.js index 59c76e594a40a..2dfb9eeea76bc 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.test.js @@ -11,7 +11,7 @@ import { ply } from './ply'; const errors = getFunctionErrors().ply; -const averagePrice = datatable => { +const averagePrice = (datatable) => { const average = datatable.rows.reduce((sum, row) => sum + row.price, 0) / datatable.rows.length; return Promise.resolve({ @@ -21,8 +21,8 @@ const averagePrice = datatable => { }); }; -const doublePrice = datatable => { - const newRows = datatable.rows.map(row => ({ double_price: row.price * 2 })); +const doublePrice = (datatable) => { + const newRows = datatable.rows.map((row) => ({ double_price: row.price * 2 })); return Promise.resolve({ type: 'datatable', @@ -31,7 +31,7 @@ const doublePrice = datatable => { }); }; -const rowCount = datatable => { +const rowCount = (datatable) => { return Promise.resolve({ type: 'datatable', columns: [{ name: 'row_count', type: 'number' }], @@ -50,7 +50,7 @@ describe('ply', () => { const arbitaryRowIndex = 0; return fn(testTable, { by: ['name', 'in_stock'], expression: [averagePrice, rowCount] }).then( - result => { + (result) => { expect(result.type).toBe('datatable'); expect(result.columns).toEqual([ { name: 'name', type: 'string' }, @@ -66,12 +66,12 @@ describe('ply', () => { describe('missing args', () => { it('returns the original datatable if both args are missing', () => { - return fn(testTable).then(result => expect(result).toEqual(testTable)); + return fn(testTable).then((result) => expect(result).toEqual(testTable)); }); describe('by', () => { it('passes the entire context into the expression when no columns are provided', () => { - return fn(testTable, { expression: [rowCount] }).then(result => + return fn(testTable, { expression: [rowCount] }).then((result) => expect(result).toEqual({ type: 'datatable', rows: [{ row_count: testTable.rows.length }], @@ -95,7 +95,7 @@ describe('ply', () => { it('returns the original datatable grouped by the specified columns', () => { const arbitaryRowIndex = 6; - return fn(testTable, { by: ['price', 'quantity'] }).then(result => { + return fn(testTable, { by: ['price', 'quantity'] }).then((result) => { expect(result.columns[0]).toHaveProperty('name', 'price'); expect(result.columns[1]).toHaveProperty('name', 'quantity'); expect(result.rows[arbitaryRowIndex]).toHaveProperty('price'); @@ -104,7 +104,7 @@ describe('ply', () => { }); it('throws when row counts do not match across resulting datatables', () => { - return fn(testTable, { by: ['name'], expression: [doublePrice, rowCount] }).catch(e => + return fn(testTable, { by: ['name'], expression: [doublePrice, rowCount] }).catch((e) => expect(e.message).toBe(errors.rowCountMismatch().message) ); }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.ts index 391ff20461fb4..a541fbc89c634 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/ply.ts @@ -47,8 +47,8 @@ export function ply(): ExpressionFunctionDefinition<'ply', Datatable, Arguments, let originalDatatables: Datatable[]; if (args.by) { - byColumns = args.by.map(by => { - const column = input.columns.find(col => col.name === by); + byColumns = args.by.map((by) => { + const column = input.columns.find((col) => col.name === by); if (!column) { throw errors.columnNotFound(by); @@ -57,9 +57,9 @@ export function ply(): ExpressionFunctionDefinition<'ply', Datatable, Arguments, return column; }); - const keyedDatatables = groupBy(input.rows, row => JSON.stringify(pick(row, args.by))); + const keyedDatatables = groupBy(input.rows, (row) => JSON.stringify(pick(row, args.by))); - originalDatatables = Object.values(keyedDatatables).map(rows => ({ + originalDatatables = Object.values(keyedDatatables).map((rows) => ({ ...input, rows, })); @@ -67,11 +67,11 @@ export function ply(): ExpressionFunctionDefinition<'ply', Datatable, Arguments, originalDatatables = [input]; } - const datatablePromises = originalDatatables.map(originalDatatable => { + const datatablePromises = originalDatatables.map((originalDatatable) => { let expressionResultPromises = []; if (args.expression) { - expressionResultPromises = args.expression.map(expression => + expressionResultPromises = args.expression.map((expression) => expression(originalDatatable) ); } else { @@ -81,13 +81,13 @@ export function ply(): ExpressionFunctionDefinition<'ply', Datatable, Arguments, return Promise.all(expressionResultPromises).then(combineAcross); }); - return Promise.all(datatablePromises).then(newDatatables => { + return Promise.all(datatablePromises).then((newDatatables) => { // Here we're just merging each for the by splits, so it doesn't actually matter if the rows are the same length const columns = combineColumns([byColumns].concat(map(newDatatables, 'columns'))); const rows = flatten( newDatatables.map((dt, i) => { const byColumnValues = pick(originalDatatables[i].rows[0], args.by); - return dt.rows.map(row => ({ + return dt.rows.map((row) => ({ ...byColumnValues, ...row, })); @@ -107,8 +107,8 @@ export function ply(): ExpressionFunctionDefinition<'ply', Datatable, Arguments, function combineColumns(arrayOfColumnsArrays: DatatableColumn[][]) { return arrayOfColumnsArrays.reduce((resultingColumns, columns) => { if (columns) { - columns.forEach(column => { - if (resultingColumns.find(resultingColumn => resultingColumn.name === column.name)) { + columns.forEach((column) => { + if (resultingColumns.find((resultingColumn) => resultingColumn.name === column.name)) { return; } else { resultingColumns.push(column); @@ -128,7 +128,7 @@ function combineAcross(datatableArray: Datatable[]) { const targetRowLength = referenceTable.rows.length; // Sanity check - datatableArray.forEach(datatable => { + datatableArray.forEach((datatable) => { if (datatable.rows.length !== targetRowLength) { throw errors.rowCountMismatch(); } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/rowCount.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/rowCount.ts index d1027f784c9a9..d6425c7db8544 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/rowCount.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/rowCount.ts @@ -18,6 +18,6 @@ export function rowCount(): ExpressionFunctionDefinition<'rowCount', Datatable, inputTypes: ['datatable'], help, args: {}, - fn: input => input.rows.length, + fn: (input) => input.rows.length, }; } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.test.js index e38bb76edabe2..ff11669db05f7 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.test.js @@ -16,8 +16,8 @@ describe('staticColumn', () => { expect(result.type).toBe('datatable'); expect(result.columns).toEqual([...testTable.columns, { name: 'foo', type: 'string' }]); - expect(result.rows.every(row => typeof row.foo === 'string')).toBe(true); - expect(result.rows.every(row => row.foo === 'bar')).toBe(true); + expect(result.rows.every((row) => typeof row.foo === 'string')).toBe(true); + expect(result.rows.every((row) => row.foo === 'bar')).toBe(true); }); it('overwrites an existing column if provided an existing column name', () => { @@ -25,8 +25,8 @@ describe('staticColumn', () => { expect(result.type).toBe('datatable'); expect(result.columns).toEqual(testTable.columns); - expect(result.rows.every(row => typeof row.name === 'string')).toBe(true); - expect(result.rows.every(row => row.name === 'John')).toBe(true); + expect(result.rows.every((row) => typeof row.name === 'string')).toBe(true); + expect(result.rows.every((row) => row.name === 'John')).toBe(true); }); it('adds a column with null values', () => { @@ -34,7 +34,7 @@ describe('staticColumn', () => { expect(result.type).toBe('datatable'); expect(result.columns).toEqual([...testTable.columns, { name: 'empty', type: 'null' }]); - expect(result.rows.every(row => row.empty === null)).toBe(true); + expect(result.rows.every((row) => row.empty === null)).toBe(true); }); it('adds a column to empty tables', () => { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.ts index 228d879c91a9c..9dd38dd57c677 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/staticColumn.ts @@ -45,7 +45,7 @@ export function staticColumn(): ExpressionFunctionDefinition< }, }, fn: (input, args) => { - const rows = input.rows.map(row => ({ ...row, [args.name]: args.value })); + const rows = input.rows.map((row) => ({ ...row, [args.name]: args.value })); const type = getType(args.value) as DatatableColumnType; const columns = [...input.columns]; const existingColumnIndex = columns.findIndex(({ name }) => name === args.name); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/switch.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/switch.test.js index 7fd83d6a2b742..7ecccdd5ee544 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/switch.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/switch.test.js @@ -9,7 +9,7 @@ import { switchFn } from './switch'; describe('switch', () => { const fn = functionWrapper(switchFn); - const getter = value => () => value; + const getter = (value) => () => value; const mockCases = [ { type: 'case', @@ -37,7 +37,7 @@ describe('switch', () => { result: 5, }, ]; - const nonMatchingCases = mockCases.filter(c => !c.matches); + const nonMatchingCases = mockCases.filter((c) => !c.matches); describe('spec', () => { it('is a function', () => { @@ -80,7 +80,7 @@ describe('switch', () => { it('should return the first match', async () => { const context = 'foo'; const args = { case: mockCases.map(getter) }; - const firstMatch = mockCases.find(c => c.matches); + const firstMatch = mockCases.find((c) => c.matches); expect(await fn(context, args)).toBe(firstMatch.result); }); }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/timefilter.test.js b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/timefilter.test.js index 834b9d195856c..2edbba278ffde 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/timefilter.test.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/timefilter.test.js @@ -14,11 +14,11 @@ const errors = getFunctionErrors().timefilter; let clock = null; -beforeEach(function() { +beforeEach(function () { clock = sinon.useFakeTimers(); }); -afterEach(function() { +afterEach(function () { clock.restore(); }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/esdocs.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/esdocs.ts index 1eb0a7c74780c..2b229b8957ec1 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/esdocs.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/esdocs.ts @@ -93,12 +93,12 @@ export function esdocs(): ExpressionFunctionDefinition< } if (fields) { - const allFields = fields.split(',').map(field => field.trim()); - allFields.forEach(field => (query = query.field(field))); + const allFields = fields.split(',').map((field) => field.trim()); + allFields.forEach((field) => (query = query.field(field))); } if (sort) { - const [sortField, sortOrder] = sort.split(',').map(str => str.trim()); + const [sortField, sortOrder] = sort.split(',').map((str) => str.trim()); if (sortField) { query.order(`"${sortField}"`, sortOrder === 'asc'); } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/pointseries/index.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/pointseries/index.ts index 17f0af4c9689e..54e48c8abf04b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/server/pointseries/index.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/server/pointseries/index.ts @@ -81,7 +81,7 @@ export function pointseries(): ExpressionFunctionDefinition< fn: (input, args) => { const errors = getFunctionErrors().pointseries; // Note: can't replace pivotObjectArray with datatableToMathContext, lose name of non-numeric columns - const columnNames = input.columns.map(col => col.name); + const columnNames = input.columns.map((col) => col.name); const mathScope = pivotObjectArray(input.rows, columnNames); const autoQuoteColumn = (col: string | null) => { if (!col || !columnNames.includes(col)) { @@ -97,7 +97,7 @@ export function pointseries(): ExpressionFunctionDefinition< // Separates args into dimensions and measures arrays // by checking if arg is a column reference (dimension) - keysOf(args).forEach(argName => { + keysOf(args).forEach((argName) => { const mathExp = autoQuoteColumn(args[argName]); if (mathExp != null && mathExp.trim() !== '') { @@ -175,7 +175,7 @@ export function pointseries(): ExpressionFunctionDefinition< // Measures // First group up all of the distinct dimensioned bits. Each of these will be reduced to just 1 value // for each measure - const measureKeys = groupBy(rows, row => + const measureKeys = groupBy(rows, (row) => dimensions .map(({ name }) => { const value = args[name]; @@ -185,13 +185,13 @@ export function pointseries(): ExpressionFunctionDefinition< ); // Then compute that 1 value for each measure - Object.values(measureKeys).forEach(valueRows => { + Object.values(measureKeys).forEach((valueRows) => { const subtable = { type: 'datatable', columns: input.columns, rows: valueRows }; const subScope = pivotObjectArray( subtable.rows, - subtable.columns.map(col => col.name) + subtable.columns.map((col) => col.name) ); - const measureValues = measureNames.map(measure => { + const measureValues = measureNames.map((measure) => { try { const ev = evaluate(args[measure], subScope); if (Array.isArray(ev)) { @@ -205,14 +205,14 @@ export function pointseries(): ExpressionFunctionDefinition< } }); - valueRows.forEach(row => { + valueRows.forEach((row) => { Object.assign(results[row[PRIMARY_KEY]], zipObject(measureNames, measureValues)); }); }); // It only makes sense to uniq the rows in a point series as 2 values can not exist in the exact same place at the same time. const resultingRows = uniqBy( - Object.values(results).map(row => omit(row, PRIMARY_KEY)), + Object.values(results).map((row) => omit(row, PRIMARY_KEY)), JSON.stringify ); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/advanced_filter/component/advanced_filter.tsx b/x-pack/plugins/canvas/canvas_plugin_src/renderers/advanced_filter/component/advanced_filter.tsx index 3e94c0d7476f4..e4d4510d40f53 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/advanced_filter/component/advanced_filter.tsx +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/advanced_filter/component/advanced_filter.tsx @@ -22,7 +22,7 @@ export interface Props { export const AdvancedFilter: FunctionComponent = ({ value = '', onChange, commit }) => ( { + onSubmit={(e) => { e.preventDefault(); commit(value); }} @@ -35,7 +35,7 @@ export const AdvancedFilter: FunctionComponent = ({ value = '', onChange, className="canvasAdvancedFilter__input" placeholder={strings.getInputPlaceholder()} value={value} - onChange={e => onChange(e.target.value)} + onChange={(e) => onChange(e.target.value)} /> diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/dropdown_filter/component/dropdown_filter.tsx b/x-pack/plugins/canvas/canvas_plugin_src/renderers/dropdown_filter/component/dropdown_filter.tsx index 68fccb39f413e..9cade90bd5870 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/dropdown_filter/component/dropdown_filter.tsx +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/dropdown_filter/component/dropdown_filter.tsx @@ -37,7 +37,7 @@ export const DropdownFilter: FunctionComponent = ({ let options = [ { value: '%%CANVAS_MATCH_ALL%%', text: `-- ${strings.getMatchAllOptionLabel()} --` }, ]; - options = options.concat(choices.map(choice => ({ value: choice, text: choice }))); + options = options.concat(choices.map((choice) => ({ value: choice, text: choice }))); const changeHandler = (e: FocusEvent | ChangeEvent) => { if (e && e.target) { @@ -47,7 +47,7 @@ export const DropdownFilter: FunctionComponent = ({ } }; - const dropdownOptions = options.map(option => { + const dropdownOptions = options.map((option) => { const { text } = option; const optionValue = option.value; const selected = optionValue === value; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/embeddable.tsx b/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/embeddable.tsx index 0ddfa1b41be70..1d4207ac0ae50 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/embeddable.tsx +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/embeddable.tsx @@ -71,7 +71,7 @@ export const embeddableRendererFactory = (core: CoreStart, plugins: StartDeps) = if (!embeddablesRegistry[uniqueId]) { const factory = Array.from(plugins.embeddable.getEmbeddableFactories()).find( - embeddableFactory => embeddableFactory.type === embeddableType + (embeddableFactory) => embeddableFactory.type === embeddableType ) as EmbeddableFactory; if (!factory) { @@ -84,7 +84,7 @@ export const embeddableRendererFactory = (core: CoreStart, plugins: StartDeps) = embeddablesRegistry[uniqueId] = embeddableObject; ReactDOM.unmountComponentAtNode(domNode); - const subscription = embeddableObject.getInput$().subscribe(function(updatedInput) { + const subscription = embeddableObject.getInput$().subscribe(function (updatedInput) { const updatedExpression = embeddableInputToExpression(updatedInput, embeddableType); if (updatedExpression) { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/input_type_to_expression/visualization.test.ts b/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/input_type_to_expression/visualization.test.ts index 306020293abe6..07f828755e46f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/input_type_to_expression/visualization.test.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/embeddable/input_type_to_expression/visualization.test.ts @@ -63,8 +63,8 @@ describe('toExpression', () => { const colors = ast.chain[0].arguments.colors as Ast[]; - const aColor = colors.find(color => color.chain[0].arguments.label[0] === 'a'); - const bColor = colors.find(color => color.chain[0].arguments.label[0] === 'b'); + const aColor = colors.find((color) => color.chain[0].arguments.label[0] === 'a'); + const bColor = colors.find((color) => color.chain[0].arguments.label[0] === 'b'); expect(aColor?.chain[0].arguments.color[0]).toBe(colorMap.a); expect(bColor?.chain[0].arguments.color[0]).toBe(colorMap.b); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/error/index.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/error/index.js index 971792ae4bfab..b7e3fc300a189 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/error/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/error/index.js @@ -21,7 +21,7 @@ export const error = () => ({ render(domNode, config, handlers) { const draw = () => { const buttonSize = Math.min(domNode.clientHeight, domNode.clientWidth); - const button = handleClick => ( + const button = (handleClick) => ( ( + .addDecorator((story) => (
({ }; config.options.series.pie.label.formatter = labelFormatter; - const legendFormatter = label => { + const legendFormatter = (label) => { const labelSpan = document.createElement('span'); Object.assign(labelSpan.style, config.font.spec); labelSpan.textContent = label; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/plugins/pie.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/plugins/pie.js index 042cbe83fb10f..2c77f860fd14f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/plugins/pie.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/pie/plugins/pie.js @@ -89,7 +89,7 @@ function init(plot) { // add hook to determine if pie plugin in enabled, and then perform necessary operations - plot.hooks.processOptions.push(function(plot, options) { + plot.hooks.processOptions.push(function (plot, options) { if (options.series.pie.show) { options.grid.show = false; @@ -123,7 +123,7 @@ function init(plot) { } }); - plot.hooks.bindEvents.push(function(plot, eventHolder) { + plot.hooks.bindEvents.push(function (plot, eventHolder) { const options = plot.getOptions(); if (options.series.pie.show) { if (options.grid.hoverable) { @@ -136,21 +136,21 @@ function init(plot) { } }); - plot.hooks.processDatapoints.push(function(plot, series, data, datapoints) { + plot.hooks.processDatapoints.push(function (plot, series, data, datapoints) { const options = plot.getOptions(); if (options.series.pie.show) { processDatapoints(plot, series, data, datapoints); } }); - plot.hooks.drawOverlay.push(function(plot, octx) { + plot.hooks.drawOverlay.push(function (plot, octx) { const options = plot.getOptions(); if (options.series.pie.show) { drawOverlay(plot, octx); } }); - plot.hooks.draw.push(function(plot, newCtx) { + plot.hooks.draw.push(function (plot, newCtx) { const options = plot.getOptions(); if (options.series.pie.show) { draw(plot, newCtx); @@ -263,12 +263,7 @@ function init(plot) { const canvasWidth = plot.getPlaceholder().width(); const canvasHeight = plot.getPlaceholder().height(); - const legendWidth = - target - .children() - .filter('.legend') - .children() - .width() || 0; + const legendWidth = target.children().filter('.legend').children().width() || 0; ctx = newCtx; @@ -351,10 +346,7 @@ function init(plot) { function clear() { ctx.clearRect(0, 0, canvasWidth, canvasHeight); - target - .children() - .filter('.pieLabel, .pieLabelBackground') - .remove(); + target.children().filter('.pieLabel, .pieLabelBackground').remove(); } function drawShadow() { @@ -867,7 +859,7 @@ const options = { }, label: { show: 'auto', - formatter: function(label, slice) { + formatter: function (label, slice) { return ( "
drawPoint(point)); + series.data.forEach((point) => drawPoint(point)); } } } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/text.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/text.js index 65dc7517453a1..2c603a62c1d76 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/text.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/plot/plugins/text.js @@ -14,10 +14,10 @@ const options = { numbers: {}, }; -const xAlign = function(x) { +const xAlign = function (x) { return x; }; -const yAlign = function(y) { +const yAlign = function (y) { return y; }; //const horizontalShift = 1; @@ -28,7 +28,7 @@ function processOptions(/*plot, options*/) { function draw(plot, ctx) { $('.valueLabel', plot.getPlaceholder()).remove(); - plot.getData().forEach(function(series) { + plot.getData().forEach(function (series) { const show = get(series.numbers, 'show'); if (!show) { return; @@ -59,12 +59,9 @@ function draw(plot, ctx) { if (typeof text === 'undefined') { return; } - const textNode = $('
') - .text(String(text)) - .addClass('valueLabel') - .css({ - position: 'absolute', - }); + const textNode = $('
').text(String(text)).addClass('valueLabel').css({ + position: 'absolute', + }); plot.getPlaceholder().append(textNode); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/progress/index.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/progress/index.js index 576a7f00cfa45..67d0abb65837d 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/progress/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/progress/index.js @@ -30,7 +30,7 @@ export const progress = () => ({ const initialViewBox = shapeSvg .getAttribute('viewBox') .split(' ') - .map(v => parseInt(v, 10)); + .map((v) => parseInt(v, 10)); let [minX, minY, width, height] = initialViewBox; if (shape !== 'horizontalBar') { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/repeat_image.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/repeat_image.js index 31f6d1056095e..2e48c8a2d5ec3 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/repeat_image.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/repeat_image.js @@ -41,7 +41,7 @@ export const repeatImage = () => ({ } const img = new Image(); - img.onload = function() { + img.onload = function () { setSize(img); if (settings.max && settings.count > settings.max) { settings.count = settings.max; @@ -54,7 +54,7 @@ export const repeatImage = () => ({ } const emptyImage = new Image(); - emptyImage.onload = function() { + emptyImage.onload = function () { setSize(emptyImage); times(settings.max - settings.count, () => container.append(emptyImage.cloneNode(true))); finish(); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/reveal_image/index.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/reveal_image/index.js index a15345fed08bd..96c8d80794c0c 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/reveal_image/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/reveal_image/index.js @@ -23,7 +23,7 @@ export const revealImage = () => ({ domNode.className = 'revealImage'; // set up the overlay image - img.onload = function() { + img.onload = function () { setSize(); finish(); }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/shape/index.js b/x-pack/plugins/canvas/canvas_plugin_src/renderers/shape/index.js index 1c9c76a74974a..02c86afd7182b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/shape/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/shape/index.js @@ -40,7 +40,7 @@ export const shape = () => ({ const initialViewBox = shapeSvg .getAttribute('viewBox') .split(' ') - .map(v => parseInt(v, 10)); + .map((v) => parseInt(v, 10)); const draw = () => { const width = domNode.offsetWidth; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/__examples__/time_filter.stories.tsx b/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/__examples__/time_filter.stories.tsx index c854ea8267bf5..abc4be44c4b2e 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/__examples__/time_filter.stories.tsx +++ b/x-pack/plugins/canvas/canvas_plugin_src/renderers/time_filter/components/__examples__/time_filter.stories.tsx @@ -23,7 +23,7 @@ const timeRanges = [ ]; storiesOf('renderers/TimeFilter', module) - .addDecorator(story => ( + .addDecorator((story) => (
{ public state = defaultValues; - _onValueChange: (argValue: ExpressionAstExpression) => void = argValue => { + _onValueChange: (argValue: ExpressionAstExpression) => void = (argValue) => { action('onValueChange')(argValue); this.setState({ argValue }); }; @@ -46,13 +46,13 @@ class Interactive extends React.Component<{}, typeof defaultValues> { } storiesOf('arguments/AxisConfig', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('extended', () => ); storiesOf('arguments/AxisConfig/components', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('extended disabled', () => ( diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/axis_config/__examples__/simple_template.stories.tsx b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/axis_config/__examples__/simple_template.stories.tsx index 1446fe2933f8a..14d61f13ea488 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/axis_config/__examples__/simple_template.stories.tsx +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/axis_config/__examples__/simple_template.stories.tsx @@ -20,7 +20,7 @@ class Interactive extends React.Component<{}, typeof defaultValues> { public render() { return ( { + onValueChange={(argValue) => { action('onValueChange')(argValue); this.setState({ argValue }); }} @@ -31,13 +31,13 @@ class Interactive extends React.Component<{}, typeof defaultValues> { } storiesOf('arguments/AxisConfig', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('simple', () => ); storiesOf('arguments/AxisConfig/components', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('simple template', () => ( diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/__tests__/get_form_object.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/__tests__/get_form_object.js index dbc129094acff..cb8e999489fbf 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/__tests__/get_form_object.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/__tests__/get_form_object.js @@ -20,14 +20,14 @@ describe('getFormObject', () => { it('number', () => { expect(getFormObject) .withArgs('2') - .to.throwException(e => { + .to.throwException((e) => { expect(e.message).to.be('Cannot render scalar values or complex math expressions'); }); }); it('complex expression', () => { expect(getFormObject) .withArgs('mean(field * 3)') - .to.throwException(e => { + .to.throwException((e) => { expect(e.message).to.be('Cannot render scalar values or complex math expressions'); }); }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/index.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/index.js index 8c1a4aad5d0f3..56849d6fe0c41 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/datacolumn/index.js @@ -17,7 +17,7 @@ import { SimpleMathFunction } from './simple_math_function'; import { getFormObject } from './get_form_object'; const { DataColumn: strings } = ArgumentStrings; -const maybeQuoteValue = val => (val.match(/\s/) ? `'${val}'` : val); +const maybeQuoteValue = (val) => (val.match(/\s/) ? `'${val}'` : val); // TODO: Garbage, we could make a much nicer math form that can handle way more. class DatacolumnArgInput extends Component { @@ -51,7 +51,7 @@ class DatacolumnArgInput extends Component { const allowedTypes = typeInstance.options.allowedTypes || false; const onlyShowMathFunctions = typeInstance.options.onlyMath || false; - const valueNotSet = val => !val || val.length === 0; + const valueNotSet = (val) => !val || val.length === 0; const updateFunctionValue = () => { const fn = this.inputRefs.fn.value; @@ -79,11 +79,12 @@ class DatacolumnArgInput extends Component { onValueChange(`${fn}(${maybeQuoteValue(column)})`); }; - const column = columns.map(col => col.name).find(colName => colName === mathValue.column) || ''; + const column = + columns.map((col) => col.name).find((colName) => colName === mathValue.column) || ''; const options = [{ value: '', text: 'select column', disabled: true }]; - sortBy(columns, 'name').forEach(column => { + sortBy(columns, 'name').forEach((column) => { if (allowedTypes && !allowedTypes.includes(column.type)) { return; } @@ -96,7 +97,7 @@ class DatacolumnArgInput extends Component { (this.inputRefs.fn = ref)} + inputRef={(ref) => (this.inputRefs.fn = ref)} onlymath={onlyShowMathFunctions} onChange={updateFunctionValue} /> @@ -106,7 +107,7 @@ class DatacolumnArgInput extends Component { compressed options={options} value={column} - inputRef={ref => (this.inputRefs.column = ref)} + inputRef={(ref) => (this.inputRefs.column = ref)} onChange={updateFunctionValue} /> @@ -117,7 +118,7 @@ class DatacolumnArgInput extends Component { const EnhancedDatacolumnArgInput = compose( withPropsOnChange(['argValue', 'columns'], ({ argValue, columns }) => ({ - mathValue: (argValue => { + mathValue: ((argValue) => { if (getType(argValue) !== 'string') { return { error: 'argValue is not a string type' }; } @@ -132,7 +133,7 @@ const EnhancedDatacolumnArgInput = compose( })), createStatefulPropHoc('mathValue', 'setMathValue'), withHandlers({ - setMathFunction: ({ mathValue, setMathValue }) => fn => setMathValue({ ...mathValue, fn }), + setMathFunction: ({ mathValue, setMathValue }) => (fn) => setMathValue({ ...mathValue, fn }), }) )(DatacolumnArgInput); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/date_format/index.ts b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/date_format/index.ts index 655a362fe6d33..fce9b21fa0387 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/date_format/index.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/date_format/index.ts @@ -30,7 +30,7 @@ export const dateFormatInitializer: SetupInitializer ({ + const dateFormats = Object.values(formatMap).map((format) => ({ value: format, text: moment.utc(moment()).format(format), })); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/filter_group.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/filter_group.js index 1659b0757cbd8..4a09fd5540d30 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/filter_group.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/filter_group.js @@ -29,15 +29,15 @@ const FilterGroupInput = ({ onValueChange, argValue, argId, filterGroups }) => { const choices = [{ text: 'No group', value: '' }].concat( argValueChoice, - filterGroups.map(f => ({ text: f })) + filterGroups.map((f) => ({ text: f })) ); - const handleSelectGroup = ev => { + const handleSelectGroup = (ev) => { const selected = ev.target.value; onValueChange(selected); }; - const handleAddGroup = ev => { + const handleAddGroup = (ev) => { // stop the form from submitting ev.preventDefault(); // set the new value @@ -56,7 +56,7 @@ const FilterGroupInput = ({ onValueChange, argValue, argId, filterGroups }) => { compressed type="text" value={inputValue} - onChange={ev => setInputValue(ev.target.value)} + onChange={(ev) => setInputValue(ev.target.value)} /> diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/image_upload/index.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/image_upload/index.js index a3c327da2e4dc..d7c7cd9e1a32f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/image_upload/index.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/image_upload/index.js @@ -58,7 +58,7 @@ class ImageUpload extends React.Component { this._isMounted = false; } - updateAST = assetId => { + updateAST = (assetId) => { this.props.onValueChange({ type: 'expression', chain: [ @@ -73,7 +73,7 @@ class ImageUpload extends React.Component { }); }; - handleUpload = files => { + handleUpload = (files) => { const { onAssetAdd } = this.props; const [file] = files; @@ -82,8 +82,8 @@ class ImageUpload extends React.Component { this.setState({ loading: true }); // start loading indicator encode(file) - .then(dataurl => onAssetAdd('dataurl', dataurl)) - .then(assetId => { + .then((dataurl) => onAssetAdd('dataurl', dataurl)) + .then((assetId) => { this.updateAST(assetId); // this component can go away when onValueChange is called, check for _isMounted @@ -92,7 +92,7 @@ class ImageUpload extends React.Component { } }; - changeUrlType = optionId => { + changeUrlType = (optionId) => { this.setState({ urlType: optionId }); }; @@ -140,7 +140,7 @@ class ImageUpload extends React.Component { link: ( (this.inputRefs.srcUrlText = ref)} + inputRef={(ref) => (this.inputRefs.srcUrlText = ref)} onSubmit={this.setSrcUrl} /> ), diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/index.ts b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/index.ts index bd84a2eb97d24..2f9a21d8a009f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/index.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/index.ts @@ -53,5 +53,5 @@ export const args = [ export const initializers = [dateFormatInitializer, numberFormatInitializer]; export const initializeArgs: SetupInitializer = (core, plugins) => { - return [...args, ...initializers.map(initializer => initializer(core, plugins))]; + return [...args, ...initializers.map((initializer) => initializer(core, plugins))]; }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/number.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/number.js index aae96f1266a36..f9c2f5eb21a2a 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/number.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/number.js @@ -27,7 +27,7 @@ const NumberArgInput = ({ updateValue, value, confirm, commit, argId }) => ( compressed id={argId} value={Number(value)} - onChange={confirm ? updateValue : ev => commit(Number(ev.target.value))} + onChange={confirm ? updateValue : (ev) => commit(Number(ev.target.value))} /> {confirm && ( diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.js index d60dc13f0105b..eddaa20a4800e 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/palette.js @@ -26,7 +26,7 @@ const PaletteArgInput = ({ onValueChange, argValue, renderError }) => { throwNotParsed(); } try { - const colors = chain[0].arguments._.map(astObj => { + const colors = chain[0].arguments._.map((astObj) => { if (getType(astObj) !== 'string') { throwNotParsed(); } diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/percentage.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/percentage.js index 5fa2ca42ca78a..746d1ff7a9d18 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/percentage.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/percentage.js @@ -13,7 +13,7 @@ import { ArgumentStrings } from '../../../i18n'; const { Percentage: strings } = ArgumentStrings; const PercentageArgInput = ({ onValueChange, argValue }) => { - const handleChange = ev => { + const handleChange = (ev) => { return onValueChange(ev.target.value / 100); }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/range.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/range.js index b3d1670c5d711..d23d6560f0124 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/range.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/range.js @@ -14,7 +14,7 @@ const { Range: strings } = ArgumentStrings; const RangeArgInput = ({ typeInstance, onValueChange, argValue }) => { const { min, max, step } = typeInstance.options; - const handleChange = ev => { + const handleChange = (ev) => { return onValueChange(Number(ev.target.value)); }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/select.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/select.js index 478acd41d797f..d218ca39b7f72 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/select.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/select.js @@ -14,7 +14,7 @@ const { Select: strings } = ArgumentStrings; const SelectArgInput = ({ typeInstance, onValueChange, argValue, argId }) => { const choices = typeInstance.options.choices.map(({ value, name }) => ({ value, text: name })); - const handleChange = ev => { + const handleChange = (ev) => { // Get the value from the choices passed in since it could be a number or // boolean, but ev.target.value is always a string const { value } = choices[ev.target.selectedIndex]; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/string.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/string.js index dc31497a7da78..53c4c8bee5282 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/string.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/string.js @@ -22,7 +22,7 @@ const StringArgInput = ({ updateValue, value, confirm, commit, argId }) => ( compressed id={argId} value={value} - onChange={confirm ? updateValue : ev => commit(ev.target.value)} + onChange={confirm ? updateValue : (ev) => commit(ev.target.value)} /> {confirm && ( diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/textarea.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/textarea.js index a0af71585eed0..3bbdd165541ff 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/textarea.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/arguments/textarea.js @@ -30,7 +30,7 @@ const TextAreaArgInput = ({ updateValue, value, confirm, commit, renderError, ar rows={10} value={value} resize="none" - onChange={confirm ? updateValue : ev => commit(ev.target.value)} + onChange={confirm ? updateValue : (ev) => commit(ev.target.value)} /> diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/esdocs.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/esdocs.js index 282ec17e94c9b..7384986fa5c2b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/esdocs.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/esdocs.js @@ -59,12 +59,12 @@ const EsdocsDatasource = ({ args, updateArgs, defaultIndex }) => { if (commas.length === 0) { return []; } - return commas.split(',').map(str => str.trim()); + return commas.split(',').map((str) => str.trim()); }; const getSortBy = () => { const commas = getSimpleArg('sort', args)[0] || ', DESC'; - return commas.split(',').map(str => str.trim()); + return commas.split(',').map((str) => str.trim()); }; const fields = getFields(); @@ -88,7 +88,7 @@ const EsdocsDatasource = ({ args, updateArgs, defaultIndex }) => { helpText={strings.getIndexLabel()} display="rowCompressed" > - setArg('index', index)} /> + setArg('index', index)} /> { > setArg('fields', fields.join(', '))} + onChange={(fields) => setArg('fields', fields.join(', '))} selected={fields} /> @@ -114,14 +114,14 @@ const EsdocsDatasource = ({ args, updateArgs, defaultIndex }) => { setArg('sort', [field, sortOrder].join(', '))} + onChange={(field) => setArg('sort', [field, sortOrder].join(', '))} /> setArg('sort', [sortField, e.target.value].join(', '))} + onChange={(e) => setArg('sort', [sortField, e.target.value].join(', '))} options={sortOptions} compressed /> @@ -140,7 +140,7 @@ const EsdocsDatasource = ({ args, updateArgs, defaultIndex }) => { > setArg(getArgName(), e.target.value)} + onChange={(e) => setArg(getArgName(), e.target.value)} compressed /> diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/essql.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/essql.js index 44e335dd7b41f..958898893d7eb 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/essql.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/essql.js @@ -49,7 +49,7 @@ class EssqlDatasource extends PureComponent { }); }; - onChange = e => { + onChange = (e) => { const { value } = e.target; this.props.setInvalid(!value.trim()); this.setArg(this.getArgName(), value); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/timelion.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/timelion.js index b36f1a747f120..c5126ab3e969f 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/timelion.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/timelion.js @@ -99,7 +99,7 @@ const TimelionDatasource = ({ args, updateArgs, defaultIndex }) => { setArg(argName, e.target.value)} + onChange={(e) => setArg(argName, e.target.value)} rows={15} /> @@ -115,7 +115,7 @@ const TimelionDatasource = ({ args, updateArgs, defaultIndex }) => { setArg('interval', e.target.value)} + onChange={(e) => setArg('interval', e.target.value)} />
diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/index.ts b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/index.ts index fdcaf21982050..34877f2fd551b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/index.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/index.ts @@ -54,5 +54,5 @@ export const viewSpecs = [ export const viewInitializers = [metricInitializer]; export const initializeViews: SetupInitializer = (core, plugins) => { - return [...viewSpecs, ...viewInitializers.map(initializer => initializer(core, plugins))]; + return [...viewSpecs, ...viewInitializers.map((initializer) => initializer(core, plugins))]; }; diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/pie.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/pie.js index 783140b0c8b9e..f1b6a48d1e7b0 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/pie.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/pie.js @@ -90,6 +90,6 @@ export const pie = () => ({ if (getState(context) !== 'ready') { return { labels: [] }; } - return { labels: uniq(map(getValue(context).rows, 'color').filter(v => v !== undefined)) }; + return { labels: uniq(map(getValue(context).rows, 'color').filter((v) => v !== undefined)) }; }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/plot.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/plot.js index 6e000336a6b34..1449bddf322b5 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/plot.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/plot.js @@ -72,6 +72,6 @@ export const plot = () => ({ if (getState(context) !== 'ready') { return { labels: [] }; } - return { labels: uniq(map(getValue(context).rows, 'color').filter(v => v !== undefined)) }; + return { labels: uniq(map(getValue(context).rows, 'color').filter((v) => v !== undefined)) }; }, }); diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/progress.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/progress.js index ae68c9c5c6031..c36334e18704b 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/progress.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/progress.js @@ -22,7 +22,7 @@ export const progress = () => ({ help: strings.getShapeHelp(), argType: 'select', options: { - choices: Object.keys(shapes).map(key => ({ + choices: Object.keys(shapes).map((key) => ({ value: key, //turns camel into title case name: key[0].toUpperCase() + key.slice(1).replace(/([A-Z])/g, ' $1'), diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/table.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/table.js index 03a13b3f8fe21..73324feddcab0 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/views/table.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/views/table.js @@ -24,7 +24,7 @@ export const table = () => ({ argType: 'select', default: 10, options: { - choices: ['', 5, 10, 25, 50, 100].map(v => ({ name: String(v), value: v })), + choices: ['', 5, 10, 25, 50, 100].map((v) => ({ name: String(v), value: v })), }, }, { diff --git a/x-pack/plugins/canvas/common/lib/autocomplete.test.ts b/x-pack/plugins/canvas/common/lib/autocomplete.test.ts index 31d213f4853ff..f7a773f6ca36a 100644 --- a/x-pack/plugins/canvas/common/lib/autocomplete.test.ts +++ b/x-pack/plugins/canvas/common/lib/autocomplete.test.ts @@ -18,7 +18,7 @@ describe('autocomplete', () => { it('should return function definition for plot', () => { const expression = 'plot '; const def = getFnArgDefAtPosition(functionSpecs, expression, expression.length); - const plotFn = functionSpecs.find(spec => spec.name === 'plot'); + const plotFn = functionSpecs.find((spec) => spec.name === 'plot'); expect(def.fnDef).toBe(plotFn); }); }); @@ -34,7 +34,7 @@ describe('autocomplete', () => { it('should suggest arguments', () => { const expression = 'plot '; const suggestions = getAutocompleteSuggestions(functionSpecs, expression, expression.length); - const plotFn = functionSpecs.find(spec => spec.name === 'plot'); + const plotFn = functionSpecs.find((spec) => spec.name === 'plot'); expect(suggestions.length).toBe(Object.keys(plotFn!.args).length); expect(suggestions[0].start).toBe(expression.length); expect(suggestions[0].end).toBe(expression.length); @@ -43,7 +43,7 @@ describe('autocomplete', () => { it('should suggest values', () => { const expression = 'shape shape='; const suggestions = getAutocompleteSuggestions(functionSpecs, expression, expression.length); - const shapeFn = functionSpecs.find(spec => spec.name === 'shape'); + const shapeFn = functionSpecs.find((spec) => spec.name === 'shape'); expect(suggestions.length).toBe(shapeFn!.args.shape.options.length); expect(suggestions[0].start).toBe(expression.length); expect(suggestions[0].end).toBe(expression.length); @@ -85,14 +85,14 @@ describe('autocomplete', () => { expect(suggestions[0].fnDef.inputTypes).toEqual(['datatable']); const withReturnOnly = suggestions.findIndex( - suggestion => + (suggestion) => suggestion.fnDef.type === 'datatable' && suggestion.fnDef.inputTypes && !(suggestion.fnDef.inputTypes as string[]).includes('datatable') ); const withNeither = suggestions.findIndex( - suggestion => + (suggestion) => suggestion.fnDef.type !== 'datatable' && (!suggestion.fnDef.inputTypes || !(suggestion.fnDef.inputTypes as string[]).includes('datatable')) @@ -111,7 +111,7 @@ describe('autocomplete', () => { expression, expression.length - 1 ); - const ltFn = functionSpecs.find(spec => spec.name === 'lt'); + const ltFn = functionSpecs.find((spec) => spec.name === 'lt'); expect(suggestions.length).toBe(Object.keys(ltFn!.args).length); expect(suggestions[0].start).toBe(expression.length - 1); expect(suggestions[0].end).toBe(expression.length - 1); @@ -124,7 +124,7 @@ describe('autocomplete', () => { expression, expression.length - 1 ); - const shapeFn = functionSpecs.find(spec => spec.name === 'shape'); + const shapeFn = functionSpecs.find((spec) => spec.name === 'shape'); expect(suggestions.length).toBe(shapeFn!.args.shape.options.length); expect(suggestions[0].start).toBe(expression.length - 1); expect(suggestions[0].end).toBe(expression.length - 1); @@ -137,7 +137,7 @@ describe('autocomplete', () => { expression, expression.length - 1 ); - const shapeFn = functionSpecs.find(spec => spec.name === 'shape'); + const shapeFn = functionSpecs.find((spec) => spec.name === 'shape'); expect(suggestions.length).toBe(shapeFn!.args.shape.options.length); expect(suggestions[0].start).toBe(expression.length - '"ar"'.length); expect(suggestions[0].end).toBe(expression.length); @@ -146,32 +146,32 @@ describe('autocomplete', () => { it('should prioritize functions that match the previous function type', () => { const expression = 'plot | '; const suggestions = getAutocompleteSuggestions(functionSpecs, expression, expression.length); - const renderIndex = suggestions.findIndex(suggestion => suggestion.text.includes('render')); - const anyIndex = suggestions.findIndex(suggestion => suggestion.text.includes('any')); + const renderIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('render')); + const anyIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('any')); expect(renderIndex).toBeLessThan(anyIndex); }); it('should alphabetize functions', () => { const expression = ''; const suggestions = getAutocompleteSuggestions(functionSpecs, expression, expression.length); - const metricIndex = suggestions.findIndex(suggestion => suggestion.text.includes('metric')); - const anyIndex = suggestions.findIndex(suggestion => suggestion.text.includes('any')); + const metricIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('metric')); + const anyIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('any')); expect(anyIndex).toBeLessThan(metricIndex); }); it('should prioritize unnamed arguments', () => { const expression = 'case '; const suggestions = getAutocompleteSuggestions(functionSpecs, expression, expression.length); - const whenIndex = suggestions.findIndex(suggestion => suggestion.text.includes('when')); - const thenIndex = suggestions.findIndex(suggestion => suggestion.text.includes('then')); + const whenIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('when')); + const thenIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('then')); expect(whenIndex).toBeLessThan(thenIndex); }); it('should alphabetize arguments', () => { const expression = 'plot '; const suggestions = getAutocompleteSuggestions(functionSpecs, expression, expression.length); - const yaxisIndex = suggestions.findIndex(suggestion => suggestion.text.includes('yaxis')); - const defaultStyleIndex = suggestions.findIndex(suggestion => + const yaxisIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('yaxis')); + const defaultStyleIndex = suggestions.findIndex((suggestion) => suggestion.text.includes('defaultStyle') ); expect(defaultStyleIndex).toBeLessThan(yaxisIndex); diff --git a/x-pack/plugins/canvas/common/lib/autocomplete.ts b/x-pack/plugins/canvas/common/lib/autocomplete.ts index 5ee4d2104a0f7..982aee1ea19c8 100644 --- a/x-pack/plugins/canvas/common/lib/autocomplete.ts +++ b/x-pack/plugins/canvas/common/lib/autocomplete.ts @@ -200,7 +200,7 @@ export function getAutocompleteSuggestions( item. The context function for `formatnumber` is the return of `math "divide(value, 2)"`. */ function getFnArgAtPosition(ast: ExpressionASTWithMeta, position: number): FnArgAtPosition { - const fnIndex = ast.node.chain.findIndex(fn => fn.start <= position && position <= fn.end); + const fnIndex = ast.node.chain.findIndex((fn) => fn.start <= position && position <= fn.end); const fn = ast.node.chain[fnIndex]; for (const [argName, argValues] of Object.entries(fn.node.arguments)) { for (let argIndex = 0; argIndex < argValues.length; argIndex++) { @@ -285,7 +285,7 @@ function getFnNameSuggestions( return aScore > bScore ? -1 : 1; }); - return fnDefs.map(fnDef => { + return fnDefs.map((fnDef) => { return { type: 'function', text: `${fnDef.name} `, start, end: end - MARKER.length, fnDef }; }); } @@ -325,7 +325,7 @@ function getSubFnNameSuggestions( return aScore > bScore ? -1 : 1; }); - return fnDefs.map(fnDef => { + return fnDefs.map((fnDef) => { return { type: 'function', text: fnDef.name + ' ', start, end: end - MARKER.length, fnDef }; }); } @@ -402,7 +402,7 @@ function getArgNameSuggestions( // Filter the list of args by those which aren't already present (unless they allow multi) const argEntries = Object.entries(fn.arguments).map<[string, ExpressionArgASTWithMeta[]]>( ([name, values]) => { - return [name, values.filter(value => !value.text.includes(MARKER))]; + return [name, values.filter((value) => !value.text.includes(MARKER))]; } ); @@ -422,7 +422,7 @@ function getArgNameSuggestions( .map(([name, arg]) => ({ name, ...arg })) .sort(unnamedArgComparator); - return argDefs.map(argDef => { + return argDefs.map((argDef) => { return { type: 'argument', text: argDef.name + '=', @@ -464,7 +464,7 @@ function getArgValueSuggestions( suggestions.push(argDef.default); } - return uniq(suggestions).map(value => { + return uniq(suggestions).map((value) => { const text = maybeQuote(value) + ' '; return { start, end: end - MARKER.length, type: 'value', text }; }); diff --git a/x-pack/plugins/canvas/common/lib/datatable/query.js b/x-pack/plugins/canvas/common/lib/datatable/query.js index 63945ce7690f9..ec7530ca47a5b 100644 --- a/x-pack/plugins/canvas/common/lib/datatable/query.js +++ b/x-pack/plugins/canvas/common/lib/datatable/query.js @@ -13,17 +13,17 @@ export function queryDatatable(datatable, query) { } if (query.and) { - query.and.forEach(filter => { + query.and.forEach((filter) => { // handle exact matches if (filter.filterType === 'exactly') { - datatable.rows = datatable.rows.filter(row => { + datatable.rows = datatable.rows.filter((row) => { return row[filter.column] === filter.value; }); } // handle time filters if (filter.filterType === 'time') { - const columnNames = datatable.columns.map(col => col.name); + const columnNames = datatable.columns.map((col) => col.name); // remove row if no column match if (!columnNames.includes(filter.column)) { @@ -31,7 +31,7 @@ export function queryDatatable(datatable, query) { return; } - datatable.rows = datatable.rows.filter(row => { + datatable.rows = datatable.rows.filter((row) => { const fromTime = new Date(filter.from).getTime(); const toTime = new Date(filter.to).getTime(); const rowTime = new Date(row[filter.column]).getTime(); diff --git a/x-pack/plugins/canvas/common/lib/dataurl.ts b/x-pack/plugins/canvas/common/lib/dataurl.ts index eddc8da1a51aa..ea5a26b27e423 100644 --- a/x-pack/plugins/canvas/common/lib/dataurl.ts +++ b/x-pack/plugins/canvas/common/lib/dataurl.ts @@ -55,7 +55,7 @@ export function encode(data: any | null, type = 'text/plain') { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => resolve(reader.result as string); - reader.onerror = err => reject(err); + reader.onerror = (err) => reject(err); reader.readAsDataURL(data); }); } diff --git a/x-pack/plugins/canvas/common/lib/get_field_type.ts b/x-pack/plugins/canvas/common/lib/get_field_type.ts index aaea95334e62e..db817393a1cdb 100644 --- a/x-pack/plugins/canvas/common/lib/get_field_type.ts +++ b/x-pack/plugins/canvas/common/lib/get_field_type.ts @@ -19,6 +19,6 @@ export function getFieldType(columns: DatatableColumn[], field?: string): string return 'null'; } const realField = unquoteString(field); - const column = columns.find(dataTableColumn => dataTableColumn.name === realField); + const column = columns.find((dataTableColumn) => dataTableColumn.name === realField); return column ? column.type : 'null'; } diff --git a/x-pack/plugins/canvas/common/lib/hex_to_rgb.ts b/x-pack/plugins/canvas/common/lib/hex_to_rgb.ts index 586666e633e84..d05536ededae3 100644 --- a/x-pack/plugins/canvas/common/lib/hex_to_rgb.ts +++ b/x-pack/plugins/canvas/common/lib/hex_to_rgb.ts @@ -10,12 +10,12 @@ export const hexToRgb = (hex: string) => { const shorthandMatches = shorthandHexColor.exec(hex); if (shorthandMatches) { - return shorthandMatches.slice(1, 4).map(mappedHex => parseInt(mappedHex + mappedHex, 16)); + return shorthandMatches.slice(1, 4).map((mappedHex) => parseInt(mappedHex + mappedHex, 16)); } const hexMatches = hexColor.exec(hex); if (hexMatches) { - return hexMatches.slice(1, 4).map(slicedHex => parseInt(slicedHex, 16)); + return hexMatches.slice(1, 4).map((slicedHex) => parseInt(slicedHex, 16)); } return null; diff --git a/x-pack/plugins/canvas/common/lib/pivot_object_array.ts b/x-pack/plugins/canvas/common/lib/pivot_object_array.ts index f13a2a2af8844..c098b7772ef11 100644 --- a/x-pack/plugins/canvas/common/lib/pivot_object_array.ts +++ b/x-pack/plugins/canvas/common/lib/pivot_object_array.ts @@ -20,6 +20,6 @@ export function pivotObjectArray< throw new Error('Columns should be an array of strings'); } - const columnValues = map(columnNames, name => map(rows, name)); + const columnValues = map(columnNames, (name) => map(rows, name)); return zipObject(columnNames, columnValues); } diff --git a/x-pack/plugins/canvas/i18n/elements/apply_strings.ts b/x-pack/plugins/canvas/i18n/elements/apply_strings.ts index 4464ed5dbf185..5e5115abb0194 100644 --- a/x-pack/plugins/canvas/i18n/elements/apply_strings.ts +++ b/x-pack/plugins/canvas/i18n/elements/apply_strings.ts @@ -16,7 +16,7 @@ import { getElementStrings } from './index'; export const applyElementStrings = (elements: ElementFactory[]) => { const elementStrings = getElementStrings(); - return elements.map(spec => { + return elements.map((spec) => { const result = spec(); const { name } = result; const strings = elementStrings[name]; diff --git a/x-pack/plugins/canvas/i18n/elements/element_strings.test.ts b/x-pack/plugins/canvas/i18n/elements/element_strings.test.ts index 1eff73c1525b1..e1e35a5b6b0dd 100644 --- a/x-pack/plugins/canvas/i18n/elements/element_strings.test.ts +++ b/x-pack/plugins/canvas/i18n/elements/element_strings.test.ts @@ -11,27 +11,27 @@ const elementSpecs = initializeElements(coreMock.createSetup() as any, {} as any describe('ElementStrings', () => { const elementStrings = getElementStrings(); - const elementNames = elementSpecs.map(spec => spec().name); + const elementNames = elementSpecs.map((spec) => spec().name); const stringKeys = Object.keys(elementStrings); test('All element names should exist in the strings definition', () => { - elementNames.forEach(name => expect(stringKeys).toContain(name)); + elementNames.forEach((name) => expect(stringKeys).toContain(name)); }); test('All string definitions should correspond to an existing element', () => { - stringKeys.forEach(key => expect(elementNames).toContain(key)); + stringKeys.forEach((key) => expect(elementNames).toContain(key)); }); const strings = Object.values(elementStrings); test('All elements should have a displayName string defined', () => { - strings.forEach(value => { + strings.forEach((value) => { expect(value).toHaveProperty('displayName'); }); }); test('All elements should have a help string defined', () => { - strings.forEach(value => { + strings.forEach((value) => { expect(value).toHaveProperty('help'); }); }); diff --git a/x-pack/plugins/canvas/i18n/functions/dict/alter_column.ts b/x-pack/plugins/canvas/i18n/functions/dict/alter_column.ts index cc601b0ea0e31..f201e73d717eb 100644 --- a/x-pack/plugins/canvas/i18n/functions/dict/alter_column.ts +++ b/x-pack/plugins/canvas/i18n/functions/dict/alter_column.ts @@ -18,7 +18,7 @@ export const help: FunctionHelp> = { values: { list: Object.values(DATATABLE_COLUMN_TYPES) .slice(0, -1) - .map(type => `\`${type}\``) + .map((type) => `\`${type}\``) .join(', '), end: Object.values(DATATABLE_COLUMN_TYPES).slice(-1)[0], mapColumnFn: '`mapColumn`', diff --git a/x-pack/plugins/canvas/i18n/functions/dict/axis_config.ts b/x-pack/plugins/canvas/i18n/functions/dict/axis_config.ts index 15708dd949b22..7cf0ec6c58761 100644 --- a/x-pack/plugins/canvas/i18n/functions/dict/axis_config.ts +++ b/x-pack/plugins/canvas/i18n/functions/dict/axis_config.ts @@ -38,7 +38,7 @@ export const help: FunctionHelp> = { values: { list: Object.values(Position) .slice(0, -1) - .map(position => `\`"${position}"\``) + .map((position) => `\`"${position}"\``) .join(', '), end: Object.values(Position).slice(-1)[0], }, diff --git a/x-pack/plugins/canvas/i18n/functions/dict/pie.ts b/x-pack/plugins/canvas/i18n/functions/dict/pie.ts index 1a93cdee05749..2e4bfc88a273a 100644 --- a/x-pack/plugins/canvas/i18n/functions/dict/pie.ts +++ b/x-pack/plugins/canvas/i18n/functions/dict/pie.ts @@ -41,7 +41,7 @@ export const help: FunctionHelp> = { 'The legend position. For example, {positions}, or {BOOLEAN_FALSE}. When {BOOLEAN_FALSE}, the legend is hidden.', values: { positions: Object.values(Position) - .map(position => `\`"${position}"\``) + .map((position) => `\`"${position}"\``) .join(', '), BOOLEAN_FALSE, }, diff --git a/x-pack/plugins/canvas/i18n/functions/dict/plot.ts b/x-pack/plugins/canvas/i18n/functions/dict/plot.ts index 3d4624bd2495e..068156f14c91b 100644 --- a/x-pack/plugins/canvas/i18n/functions/dict/plot.ts +++ b/x-pack/plugins/canvas/i18n/functions/dict/plot.ts @@ -33,7 +33,7 @@ export const help: FunctionHelp> = { 'The legend position. For example, {positions}, or {BOOLEAN_FALSE}. When {BOOLEAN_FALSE}, the legend is hidden.', values: { positions: Object.values(Position) - .map(position => `\`"${position}"\``) + .map((position) => `\`"${position}"\``) .join(', '), BOOLEAN_FALSE, }, diff --git a/x-pack/plugins/canvas/i18n/functions/dict/progress.ts b/x-pack/plugins/canvas/i18n/functions/dict/progress.ts index 7e441df9bd246..1880c5dc807f0 100644 --- a/x-pack/plugins/canvas/i18n/functions/dict/progress.ts +++ b/x-pack/plugins/canvas/i18n/functions/dict/progress.ts @@ -48,7 +48,7 @@ export const help: FunctionHelp> = { values: { list: Object.values(Shape) .slice(0, -1) - .map(shape => `\`"${shape}"\``) + .map((shape) => `\`"${shape}"\``) .join(', '), end: `\`"${Object.values(Shape).slice(-1)[0]}"\``, }, diff --git a/x-pack/plugins/canvas/i18n/functions/dict/reveal_image.ts b/x-pack/plugins/canvas/i18n/functions/dict/reveal_image.ts index f210ec8c1d882..410ca29d7b4d4 100644 --- a/x-pack/plugins/canvas/i18n/functions/dict/reveal_image.ts +++ b/x-pack/plugins/canvas/i18n/functions/dict/reveal_image.ts @@ -39,7 +39,7 @@ export const help: FunctionHelp> = { values: { list: Object.values(Position) .slice(0, -1) - .map(position => `\`"${position}"\``) + .map((position) => `\`"${position}"\``) .join(', '), end: Object.values(Position).slice(-1)[0], }, diff --git a/x-pack/plugins/canvas/i18n/templates/apply_strings.ts b/x-pack/plugins/canvas/i18n/templates/apply_strings.ts index 4ddd3a61543c2..01775e9daeb51 100644 --- a/x-pack/plugins/canvas/i18n/templates/apply_strings.ts +++ b/x-pack/plugins/canvas/i18n/templates/apply_strings.ts @@ -18,7 +18,7 @@ import { TagStrings } from '../../i18n'; export const applyTemplateStrings = (templates: CanvasTemplate[]) => { const templateStrings = getTemplateStrings(); - return templates.map(template => { + return templates.map((template) => { const { name: templateName } = template; const strings = templateStrings[templateName]; @@ -36,7 +36,7 @@ export const applyTemplateStrings = (templates: CanvasTemplate[]) => { } if (template.tags) { - template.tags = template.tags.map(tag => { + template.tags = template.tags.map((tag) => { if (TagStrings[tag]) { return TagStrings[tag](); } diff --git a/x-pack/plugins/canvas/i18n/templates/template_strings.test.ts b/x-pack/plugins/canvas/i18n/templates/template_strings.test.ts index eeeb06732d397..4f7b61e13fe69 100644 --- a/x-pack/plugins/canvas/i18n/templates/template_strings.test.ts +++ b/x-pack/plugins/canvas/i18n/templates/template_strings.test.ts @@ -11,7 +11,7 @@ import { TagStrings } from '../tags'; describe('TemplateStrings', () => { const templateStrings = getTemplateStrings(); - const templateNames = templateSpecs.map(template => template().name); + const templateNames = templateSpecs.map((template) => template().name); const stringKeys = Object.keys(templateStrings); test('All template names should exist in the strings definition', () => { @@ -19,19 +19,19 @@ describe('TemplateStrings', () => { }); test('All string definitions should correspond to an existing template', () => { - stringKeys.forEach(key => expect(templateNames).toContain(key)); + stringKeys.forEach((key) => expect(templateNames).toContain(key)); }); const strings = Object.values(templateStrings); test('All templates should have a name string defined', () => { - strings.forEach(value => { + strings.forEach((value) => { expect(value).toHaveProperty('name'); }); }); test('All templates should have a help string defined', () => { - strings.forEach(value => { + strings.forEach((value) => { expect(value).toHaveProperty('help'); }); }); @@ -39,7 +39,7 @@ describe('TemplateStrings', () => { test('All templates should have tags that are defined', () => { const tagNames = Object.keys(TagStrings); - templateSpecs.forEach(template => { + templateSpecs.forEach((template) => { template().tags.forEach((tagName: string) => expect(tagNames).toContain(tagName)); }); }); diff --git a/x-pack/plugins/canvas/public/application.tsx b/x-pack/plugins/canvas/public/application.tsx index d97e4944da13a..1cd0bc250feb2 100644 --- a/x-pack/plugins/canvas/public/application.tsx +++ b/x-pack/plugins/canvas/public/application.tsx @@ -115,7 +115,7 @@ export const initializeCanvas = async ( href: getDocumentationLinks().canvas, }, ], - content: domNode => { + content: (domNode) => { ReactDOM.render(, domNode); return () => ReactDOM.unmountComponentAtNode(domNode); }, diff --git a/x-pack/plugins/canvas/public/apps/export/export/index.js b/x-pack/plugins/canvas/public/apps/export/export/index.js index dafcb9f4c2510..95c46d9e1c8ae 100644 --- a/x-pack/plugins/canvas/public/apps/export/export/index.js +++ b/x-pack/plugins/canvas/public/apps/export/export/index.js @@ -11,12 +11,12 @@ import { getWorkpad, getSelectedPageIndex } from '../../../state/selectors/workp import { LoadWorkpad } from './load_workpad'; import { ExportApp as Component } from './export_app'; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ workpad: getWorkpad(state), selectedPageIndex: getSelectedPageIndex(state), }); -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ initializeWorkpad() { dispatch(initializeWorkpad()); }, diff --git a/x-pack/plugins/canvas/public/apps/export/routes.js b/x-pack/plugins/canvas/public/apps/export/routes.js index a0eafe3e3ffe9..33e375115aa19 100644 --- a/x-pack/plugins/canvas/public/apps/export/routes.js +++ b/x-pack/plugins/canvas/public/apps/export/routes.js @@ -18,7 +18,7 @@ export const routes = [ { name: 'exportWorkpad', path: '/pdf/:id/page/:page', - action: dispatch => async ({ params, router }) => { + action: (dispatch) => async ({ params, router }) => { // load workpad if given a new id via url param const fetchedWorkpad = await workpadService.get(params.id); const pageNumber = parseInt(params.page, 10); diff --git a/x-pack/plugins/canvas/public/apps/home/home_app/index.js b/x-pack/plugins/canvas/public/apps/home/home_app/index.js index f26b3510c7682..f78ee1f8a18af 100644 --- a/x-pack/plugins/canvas/public/apps/home/home_app/index.js +++ b/x-pack/plugins/canvas/public/apps/home/home_app/index.js @@ -8,7 +8,7 @@ import { connect } from 'react-redux'; import { resetWorkpad } from '../../../state/actions/workpad'; import { HomeApp as Component } from './home_app'; -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ onLoad() { dispatch(resetWorkpad()); }, diff --git a/x-pack/plugins/canvas/public/apps/workpad/routes.js b/x-pack/plugins/canvas/public/apps/workpad/routes.js index 4e3920bf34f67..a330020b741ac 100644 --- a/x-pack/plugins/canvas/public/apps/workpad/routes.js +++ b/x-pack/plugins/canvas/public/apps/workpad/routes.js @@ -25,7 +25,7 @@ export const routes = [ { name: 'createWorkpad', path: '/create', - action: dispatch => async ({ router }) => { + action: (dispatch) => async ({ router }) => { const newWorkpad = getDefaultWorkpad(); try { await workpadService.create(newWorkpad); diff --git a/x-pack/plugins/canvas/public/apps/workpad/workpad_app/index.js b/x-pack/plugins/canvas/public/apps/workpad/workpad_app/index.js index f0a5325baf3c0..ac50cd3fb99b6 100644 --- a/x-pack/plugins/canvas/public/apps/workpad/workpad_app/index.js +++ b/x-pack/plugins/canvas/public/apps/workpad/workpad_app/index.js @@ -15,7 +15,7 @@ import { withElementsLoadedTelemetry } from './workpad_telemetry'; export { WORKPAD_CONTAINER_ID } from './workpad_app'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const appReady = getAppReady(state); return { @@ -25,7 +25,7 @@ const mapStateToProps = state => { }; }; -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ deselectElement(ev) { ev && ev.stopPropagation(); dispatch(selectToplevelNodes([])); diff --git a/x-pack/plugins/canvas/public/apps/workpad/workpad_app/workpad_telemetry.tsx b/x-pack/plugins/canvas/public/apps/workpad/workpad_app/workpad_telemetry.tsx index 5f3f114092e61..47b461f22ad65 100644 --- a/x-pack/plugins/canvas/public/apps/workpad/workpad_app/workpad_telemetry.tsx +++ b/x-pack/plugins/canvas/public/apps/workpad/workpad_app/workpad_telemetry.tsx @@ -57,10 +57,10 @@ function areAllElementsInResolvedArgs(workpad: Workpad, resolvedArgs: ResolvedAr const resolvedArgsElements = Object.keys(resolvedArgs); const workpadElements = workpad.pages.reduce((reduction, page) => { - return [...reduction, ...page.elements.map(element => element.id)]; + return [...reduction, ...page.elements.map((element) => element.id)]; }, []); - return workpadElements.every(element => resolvedArgsElements.includes(element)); + return workpadElements.every((element) => resolvedArgsElements.includes(element)); } export const withUnconnectedElementsLoadedTelemetry =

( diff --git a/x-pack/plugins/canvas/public/components/app/app.js b/x-pack/plugins/canvas/public/components/app/app.js index 16484afc8620b..5eb62f4bab950 100644 --- a/x-pack/plugins/canvas/public/components/app/app.js +++ b/x-pack/plugins/canvas/public/components/app/app.js @@ -65,7 +65,7 @@ export class App extends React.PureComponent { loadingMessage={strings.getLoadingMessage()} onRouteChange={this.props.onRouteChange} onLoad={() => this.props.setAppReady(true)} - onError={err => this.props.setAppError(err)} + onError={(err) => this.props.setAppError(err)} />

); diff --git a/x-pack/plugins/canvas/public/components/app/index.js b/x-pack/plugins/canvas/public/components/app/index.js index 750132dadb97d..a1e3b9c09554a 100644 --- a/x-pack/plugins/canvas/public/components/app/index.js +++ b/x-pack/plugins/canvas/public/components/app/index.js @@ -12,7 +12,7 @@ import { withKibana } from '../../../../../../src/plugins/kibana_react/public'; import { App as Component } from './app'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { // appReady could be an error object const appState = getAppReady(state); @@ -22,7 +22,7 @@ const mapStateToProps = state => { }; }; -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ setAppReady: () => async () => { try { // set app state to ready @@ -31,7 +31,7 @@ const mapDispatchToProps = dispatch => ({ dispatch(appError(e)); } }, - setAppError: payload => dispatch(appError(payload)), + setAppError: (payload) => dispatch(appError(payload)), }); const mergeProps = (stateProps, dispatchProps, ownProps) => { @@ -46,7 +46,7 @@ const mergeProps = (stateProps, dispatchProps, ownProps) => { export const App = compose( connect(mapStateToProps, mapDispatchToProps, mergeProps), withKibana, - withProps(props => ({ + withProps((props) => ({ onRouteChange: props.kibana.services.canvas.navLink.updatePath, })) )(Component); diff --git a/x-pack/plugins/canvas/public/components/arg_add_popover/arg_add_popover.tsx b/x-pack/plugins/canvas/public/components/arg_add_popover/arg_add_popover.tsx index 9c66043454585..c26fdb8c46d0f 100644 --- a/x-pack/plugins/canvas/public/components/arg_add_popover/arg_add_popover.tsx +++ b/x-pack/plugins/canvas/public/components/arg_add_popover/arg_add_popover.tsx @@ -45,7 +45,7 @@ export const ArgAddPopover = ({ options }: Props) => { button={button} > {({ closePopover }: PopoverChildrenProps) => - options.map(opt => ( + options.map((opt) => ( { +export const AdvancedFailureComponent = (props) => { const { onValueChange, defaultValue, @@ -26,7 +26,7 @@ export const AdvancedFailureComponent = props => { argId, } = props; - const valueChange = ev => { + const valueChange = (ev) => { ev.preventDefault(); resetErrorState(); // when setting a new value, attempt to reset the error state @@ -36,7 +36,7 @@ export const AdvancedFailureComponent = props => { } }; - const confirmReset = ev => { + const confirmReset = (ev) => { ev.preventDefault(); resetErrorState(); // when setting a new value, attempt to reset the error state onValueChange(fromExpression(defaultValue, 'argument')); @@ -61,7 +61,7 @@ export const AdvancedFailureComponent = props => {
- valueChange(e)} size="s" type="submit"> + valueChange(e)} size="s" type="submit"> {strings.getApplyButtonLabel()} {defaultValue && defaultValue.length && ( @@ -91,7 +91,7 @@ export const AdvancedFailure = compose( })), createStatefulPropHoc('argExpression', 'updateArgExpression'), withPropsOnChange(['argExpression'], ({ argExpression }) => ({ - valid: (function() { + valid: (function () { try { fromExpression(argExpression, 'argument'); return true; diff --git a/x-pack/plugins/canvas/public/components/arg_form/arg_form.js b/x-pack/plugins/canvas/public/components/arg_form/arg_form.js index cff38431deb15..dfd99b18646a6 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/arg_form.js +++ b/x-pack/plugins/canvas/public/components/arg_form/arg_form.js @@ -80,7 +80,7 @@ class ArgFormComponent extends PureComponent { }); }, error: hasError, - setLabel: label => this._isMounted && setLabel(label), + setLabel: (label) => this._isMounted && setLabel(label), resetErrorState: () => { resetErrorState(); this._isMounted && setRenderError(false); diff --git a/x-pack/plugins/canvas/public/components/arg_form/arg_label.js b/x-pack/plugins/canvas/public/components/arg_form/arg_label.js index 4324eed0892a5..fa0391952d151 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/arg_label.js +++ b/x-pack/plugins/canvas/public/components/arg_form/arg_label.js @@ -9,7 +9,7 @@ import PropTypes from 'prop-types'; import { EuiFormRow, EuiAccordion, EuiText, EuiToolTip, EuiIcon } from '@elastic/eui'; // This is what is being generated by render() from the Arg class. It is called in FunctionForm -export const ArgLabel = props => { +export const ArgLabel = (props) => { const { argId, className, label, help, expandable, children, simpleArg, initialIsOpen } = props; return ( diff --git a/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.js b/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.js index 947c3741c735b..7cd30a8987739 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.js +++ b/x-pack/plugins/canvas/public/components/arg_form/arg_template_form.js @@ -47,7 +47,7 @@ class ArgTemplateFormComponent extends React.Component { _domNode = null; - _renderTemplate = domNode => { + _renderTemplate = (domNode) => { const { template, argumentProps, handlers } = this.props; if (template) { return template(domNode, argumentProps, handlers); @@ -72,7 +72,7 @@ class ArgTemplateFormComponent extends React.Component { return ( { + render={(domNode) => { this._domNode = domNode; this._renderTemplate(domNode); }} diff --git a/x-pack/plugins/canvas/public/components/arg_form/index.js b/x-pack/plugins/canvas/public/components/arg_form/index.js index 017ecae3103da..b6e30f9e52c60 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/index.js +++ b/x-pack/plugins/canvas/public/components/arg_form/index.js @@ -25,7 +25,7 @@ export const ArgForm = compose( } }, }), - connect(state => ({ workpad: getWorkpadInfo(state), assets: getAssets(state) })) + connect((state) => ({ workpad: getWorkpadInfo(state), assets: getAssets(state) })) )(Component); ArgForm.propTypes = { diff --git a/x-pack/plugins/canvas/public/components/arg_form/pending_arg_value.js b/x-pack/plugins/canvas/public/components/arg_form/pending_arg_value.js index 516ac729935e7..f9a855554db7d 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/pending_arg_value.js +++ b/x-pack/plugins/canvas/public/components/arg_form/pending_arg_value.js @@ -33,7 +33,7 @@ export class PendingArgValue extends React.PureComponent { setResolvedArgValue(null); } else { argResolver(argValue) - .then(val => setResolvedArgValue(val != null ? val : null)) + .then((val) => setResolvedArgValue(val != null ? val : null)) .catch(() => setResolvedArgValue(null)); // swallow error, it's not important } } diff --git a/x-pack/plugins/canvas/public/components/asset_manager/__examples__/asset.examples.tsx b/x-pack/plugins/canvas/public/components/asset_manager/__examples__/asset.examples.tsx index 728f228d989fb..9a6147050bdbb 100644 --- a/x-pack/plugins/canvas/public/components/asset_manager/__examples__/asset.examples.tsx +++ b/x-pack/plugins/canvas/public/components/asset_manager/__examples__/asset.examples.tsx @@ -27,7 +27,7 @@ const MARKER: AssetType = { }; storiesOf('components/Assets/Asset', module) - .addDecorator(story =>
{story()}
) + .addDecorator((story) =>
{story()}
) .add('airplane', () => ( void; } -export const Asset: FunctionComponent = props => { +export const Asset: FunctionComponent = (props) => { const { asset, onCreate, onCopy, onDelete } = props; const createImage = ( diff --git a/x-pack/plugins/canvas/public/components/asset_manager/asset_manager.tsx b/x-pack/plugins/canvas/public/components/asset_manager/asset_manager.tsx index c27f0c002c3d1..cb177591fd650 100644 --- a/x-pack/plugins/canvas/public/components/asset_manager/asset_manager.tsx +++ b/x-pack/plugins/canvas/public/components/asset_manager/asset_manager.tsx @@ -104,7 +104,7 @@ export class AssetManager extends PureComponent { private handleFileUpload = (files: FileList | null) => { if (files == null) return; this.setState({ isLoading: true }); - Promise.all(Array.from(files).map(file => this.props.onAssetAdd(file))).finally(() => { + Promise.all(Array.from(files).map((file) => this.props.onAssetAdd(file))).finally(() => { this.setState({ isLoading: false }); }); }; diff --git a/x-pack/plugins/canvas/public/components/asset_manager/asset_modal.tsx b/x-pack/plugins/canvas/public/components/asset_manager/asset_modal.tsx index 8637db8e9f962..c02fc440abb0b 100644 --- a/x-pack/plugins/canvas/public/components/asset_manager/asset_modal.tsx +++ b/x-pack/plugins/canvas/public/components/asset_manager/asset_modal.tsx @@ -52,7 +52,7 @@ interface Props { onAssetDelete: (asset: AssetType) => void; } -export const AssetModal: FunctionComponent = props => { +export const AssetModal: FunctionComponent = (props) => { const { assetValues, isLoading, @@ -114,7 +114,7 @@ export const AssetModal: FunctionComponent = props => { {assetValues.length ? ( - {assetValues.map(asset => ( + {assetValues.map((asset) => ( { const [type, subtype] = get(file, 'type', '').split('/'); if (type === 'image' && VALID_IMAGE_TYPES.indexOf(subtype) >= 0) { - return encode(file).then(dataurl => { + return encode(file).then((dataurl) => { const dataurlType = 'dataurl'; const existingId = findExistingAsset(dataurlType, dataurl, assetValues); if (existingId) { diff --git a/x-pack/plugins/canvas/public/components/asset_picker/asset_picker.tsx b/x-pack/plugins/canvas/public/components/asset_picker/asset_picker.tsx index 0d7e90c500695..4489e877abf88 100644 --- a/x-pack/plugins/canvas/public/components/asset_picker/asset_picker.tsx +++ b/x-pack/plugins/canvas/public/components/asset_picker/asset_picker.tsx @@ -46,7 +46,7 @@ export class AssetPicker extends PureComponent { return ( - {assets.map(asset => ( + {assets.map((asset) => ( { + onKeyDown = (e) => { const { ESCAPE, TAB, ENTER, UP, DOWN, LEFT, RIGHT } = keyCodes; const { keyCode } = e; const { items } = this.props; @@ -222,14 +222,14 @@ export class Autocomplete extends React.Component {
(this.containerRef = ref)} + ref={(ref) => (this.containerRef = ref)} role="listbox" > {header} {items.map((item, i) => (
(this.itemRefs[i] = ref)} + ref={(ref) => (this.itemRefs[i] = ref)} className={ 'autocompleteItem' + (this.state.selectedIndex === i ? ' autocompleteItem--isActive' : '') diff --git a/x-pack/plugins/canvas/public/components/color_manager/__examples__/color_manager.stories.tsx b/x-pack/plugins/canvas/public/components/color_manager/__examples__/color_manager.stories.tsx index 005a2541cbc2e..672580416c286 100644 --- a/x-pack/plugins/canvas/public/components/color_manager/__examples__/color_manager.stories.tsx +++ b/x-pack/plugins/canvas/public/components/color_manager/__examples__/color_manager.stories.tsx @@ -22,7 +22,7 @@ class Interactive extends React.Component<{}, { hasButtons: boolean; value: stri hasButtons={this.state.hasButtons} onAddColor={action('onAddColor')} onRemoveColor={action('onRemoveColor')} - onChange={value => this.setState({ value })} + onChange={(value) => this.setState({ value })} value={this.state.value} />

diff --git a/x-pack/plugins/canvas/public/components/color_manager/color_manager.tsx b/x-pack/plugins/canvas/public/components/color_manager/color_manager.tsx index c9db9a9ba3468..8855bffc5e771 100644 --- a/x-pack/plugins/canvas/public/components/color_manager/color_manager.tsx +++ b/x-pack/plugins/canvas/public/components/color_manager/color_manager.tsx @@ -75,7 +75,7 @@ export const ColorManager: FunctionComponent = ({ value={value} isInvalid={!validColor && value.length > 0} placeholder={strings.getCodePlaceholder()} - onChange={e => onChange(e.target.value)} + onChange={(e) => onChange(e.target.value)} /> {buttons} diff --git a/x-pack/plugins/canvas/public/components/color_palette/__examples__/color_palette.stories.tsx b/x-pack/plugins/canvas/public/components/color_palette/__examples__/color_palette.stories.tsx index 14cd5e6d13b4f..0aef14104030e 100644 --- a/x-pack/plugins/canvas/public/components/color_palette/__examples__/color_palette.stories.tsx +++ b/x-pack/plugins/canvas/public/components/color_palette/__examples__/color_palette.stories.tsx @@ -21,7 +21,7 @@ class Interactive extends React.Component<{}, { value: string }> { return ( this.setState({ value })} + onChange={(value) => this.setState({ value })} value={this.state.value} /> ); diff --git a/x-pack/plugins/canvas/public/components/color_palette/color_palette.tsx b/x-pack/plugins/canvas/public/components/color_palette/color_palette.tsx index 90f3f8860b4ae..09bc08f9ae541 100644 --- a/x-pack/plugins/canvas/public/components/color_palette/color_palette.tsx +++ b/x-pack/plugins/canvas/public/components/color_palette/color_palette.tsx @@ -42,14 +42,14 @@ export const ColorPalette: FunctionComponent = ({ return null; } - colors = colors.filter(color => { + colors = colors.filter((color) => { return tinycolor(color).isValid(); }); return (

- {color => { + {(color) => { const match = tinycolor.equals(color, value); const icon = match ? ( diff --git a/x-pack/plugins/canvas/public/components/color_picker/__examples__/color_picker.stories.tsx b/x-pack/plugins/canvas/public/components/color_picker/__examples__/color_picker.stories.tsx index a2825b210ee33..0a7ed75ee728e 100644 --- a/x-pack/plugins/canvas/public/components/color_picker/__examples__/color_picker.stories.tsx +++ b/x-pack/plugins/canvas/public/components/color_picker/__examples__/color_picker.stories.tsx @@ -28,11 +28,11 @@ class Interactive extends React.Component<
this.setState({ colors: this.state.colors.concat(value) })} - onRemoveColor={value => - this.setState({ colors: this.state.colors.filter(color => color !== value) }) + onAddColor={(value) => this.setState({ colors: this.state.colors.concat(value) })} + onRemoveColor={(value) => + this.setState({ colors: this.state.colors.filter((color) => color !== value) }) } - onChange={value => this.setState({ value })} + onChange={(value) => this.setState({ value })} hasButtons={this.state.hasButtons} value={this.state.value} /> diff --git a/x-pack/plugins/canvas/public/components/color_picker/color_picker.tsx b/x-pack/plugins/canvas/public/components/color_picker/color_picker.tsx index 2cd93b6f0e5c7..2bf17301b7b38 100644 --- a/x-pack/plugins/canvas/public/components/color_picker/color_picker.tsx +++ b/x-pack/plugins/canvas/public/components/color_picker/color_picker.tsx @@ -29,7 +29,7 @@ export const ColorPicker: FunctionComponent = ({ const tc = tinycolor(value); const isValidColor = tc.isValid(); - colors = colors.filter(color => { + colors = colors.filter((color) => { return tinycolor(color).isValid(); }); @@ -37,7 +37,7 @@ export const ColorPicker: FunctionComponent = ({ let canAdd = false; if (isValidColor) { - const match = colors.filter(color => tinycolor.equals(value, color)); + const match = colors.filter((color) => tinycolor.equals(value, color)); canRemove = match.length > 0; canAdd = match.length === 0; } diff --git a/x-pack/plugins/canvas/public/components/color_picker_popover/__examples__/color_picker_popover.stories.tsx b/x-pack/plugins/canvas/public/components/color_picker_popover/__examples__/color_picker_popover.stories.tsx index 83923d1f0da1f..63854b8045e93 100644 --- a/x-pack/plugins/canvas/public/components/color_picker_popover/__examples__/color_picker_popover.stories.tsx +++ b/x-pack/plugins/canvas/public/components/color_picker_popover/__examples__/color_picker_popover.stories.tsx @@ -27,7 +27,7 @@ class Interactive extends React.Component<
this.setState({ value })} + onChange={(value) => this.setState({ value })} onAddColor={action('onAddColor')} onRemoveColor={action('onRemoveColor')} value={this.state.value} diff --git a/x-pack/plugins/canvas/public/components/confirm_modal/confirm_modal.tsx b/x-pack/plugins/canvas/public/components/confirm_modal/confirm_modal.tsx index f4b0264911734..1be587c31528f 100644 --- a/x-pack/plugins/canvas/public/components/confirm_modal/confirm_modal.tsx +++ b/x-pack/plugins/canvas/public/components/confirm_modal/confirm_modal.tsx @@ -20,7 +20,7 @@ interface Props { className?: string; } -export const ConfirmModal: FunctionComponent = props => { +export const ConfirmModal: FunctionComponent = (props) => { const { isOpen, title, diff --git a/x-pack/plugins/canvas/public/components/custom_element_modal/custom_element_modal.tsx b/x-pack/plugins/canvas/public/components/custom_element_modal/custom_element_modal.tsx index 56bd0bf5e9f2a..8f73939de69a6 100644 --- a/x-pack/plugins/canvas/public/components/custom_element_modal/custom_element_modal.tsx +++ b/x-pack/plugins/canvas/public/components/custom_element_modal/custom_element_modal.tsx @@ -137,7 +137,7 @@ export class CustomElementModal extends PureComponent { + onChange={(e) => e.target.value.length <= MAX_NAME_LENGTH && this._handleChange('name', e.target.value) } @@ -154,7 +154,7 @@ export class CustomElementModal extends PureComponent { + onChange={(e) => e.target.value.length <= MAX_DESCRIPTION_LENGTH && this._handleChange('description', e.target.value) } diff --git a/x-pack/plugins/canvas/public/components/datasource/datasource_component.js b/x-pack/plugins/canvas/public/components/datasource/datasource_component.js index 285b69f057cd8..de9d192e4608c 100644 --- a/x-pack/plugins/canvas/public/components/datasource/datasource_component.js +++ b/x-pack/plugins/canvas/public/components/datasource/datasource_component.js @@ -51,7 +51,7 @@ export class DatasourceComponent extends PureComponent { state = { defaultIndex: '' }; componentDidMount() { - getDefaultIndex().then(defaultIndex => this.setState({ defaultIndex })); + getDefaultIndex().then((defaultIndex) => this.setState({ defaultIndex })); } componentDidUpdate(prevProps) { @@ -71,7 +71,7 @@ export class DatasourceComponent extends PureComponent { type: 'function', }); - setSelectedDatasource = value => { + setSelectedDatasource = (value) => { const { datasource, resetArgs, @@ -88,7 +88,7 @@ export class DatasourceComponent extends PureComponent { // otherwise, clear the arguments, the form will update them updateArgs && updateArgs({}); } - selectDatasource && selectDatasource(datasources.find(d => d.name === value)); + selectDatasource && selectDatasource(datasources.find((d) => d.name === value)); setSelecting(false); }; diff --git a/x-pack/plugins/canvas/public/components/datasource/datasource_selector.js b/x-pack/plugins/canvas/public/components/datasource/datasource_selector.js index 153a8a7ef75e6..528c37e46caeb 100644 --- a/x-pack/plugins/canvas/public/components/datasource/datasource_selector.js +++ b/x-pack/plugins/canvas/public/components/datasource/datasource_selector.js @@ -10,7 +10,7 @@ import { EuiCard, EuiIcon } from '@elastic/eui'; export const DatasourceSelector = ({ onSelect, datasources, current }) => (
- {datasources.map(d => ( + {datasources.map((d) => ( ({ +const mapStateToProps = (state) => ({ element: getSelectedElement(state), pageId: getSelectedPage(state), functionDefinitions: getServerFunctions(state), }); -const mapDispatchToProps = dispatch => ({ - dispatchArgumentAtIndex: props => arg => dispatch(setArgumentAtIndex({ ...props, arg })), - dispatchAstAtIndex: ({ index, element, pageId }) => ast => { +const mapDispatchToProps = (dispatch) => ({ + dispatchArgumentAtIndex: (props) => (arg) => dispatch(setArgumentAtIndex({ ...props, arg })), + dispatchAstAtIndex: ({ index, element, pageId }) => (ast) => { dispatch(flushContext(element.id)); dispatch(setAstAtIndex(index, ast, element, pageId)); }, @@ -32,8 +32,8 @@ const mergeProps = (stateProps, dispatchProps, ownProps) => { const { element, pageId, functionDefinitions } = stateProps; const { dispatchArgumentAtIndex, dispatchAstAtIndex } = dispatchProps; - const getDataTableFunctionsByName = name => - functionDefinitions.find(fn => fn.name === name && fn.type === 'datatable'); + const getDataTableFunctionsByName = (name) => + functionDefinitions.find((fn) => fn.name === name && fn.type === 'datatable'); // find the matching datasource from the expression AST const datasourceAst = get(element, 'ast.chain', []) diff --git a/x-pack/plugins/canvas/public/components/datatable/datatable.js b/x-pack/plugins/canvas/public/components/datatable/datatable.js index e0cd3378ff65c..2b7c7464f7b84 100644 --- a/x-pack/plugins/canvas/public/components/datatable/datatable.js +++ b/x-pack/plugins/canvas/public/components/datatable/datatable.js @@ -10,7 +10,7 @@ import PropTypes from 'prop-types'; import moment from 'moment'; import { Paginate } from '../paginate'; -const getIcon = type => { +const getIcon = (type) => { if (type === null) { return; } @@ -36,9 +36,9 @@ const getIcon = type => { return ; }; -const getColumnName = col => (typeof col === 'string' ? col : col.name); +const getColumnName = (col) => (typeof col === 'string' ? col : col.name); -const getColumnType = col => col.type || null; +const getColumnType = (col) => col.type || null; const getFormattedValue = (val, type) => { if (type === 'date') { @@ -56,7 +56,7 @@ export const Datatable = ({ datatable, perPage, paginate, showHeader }) => ( {!showHeader ? null : (
- {datatable.columns.map(col => ( + {datatable.columns.map((col) => ( {rows.map((row, i) => ( - {datatable.columns.map(col => ( + {datatable.columns.map((col) => ( diff --git a/x-pack/plugins/canvas/public/components/dom_preview/dom_preview.js b/x-pack/plugins/canvas/public/components/dom_preview/dom_preview.js index 172792b429fcd..808008e5664d6 100644 --- a/x-pack/plugins/canvas/public/components/dom_preview/dom_preview.js +++ b/x-pack/plugins/canvas/public/components/dom_preview/dom_preview.js @@ -86,13 +86,13 @@ export class DomPreview extends React.Component { render() { return (
{ + ref={(container) => { this._container = container; }} className="dom-preview" >
{ + ref={(content) => { this._content = content; }} /> diff --git a/x-pack/plugins/canvas/public/components/element_card/__examples__/element_card.stories.tsx b/x-pack/plugins/canvas/public/components/element_card/__examples__/element_card.stories.tsx index efb28d34d719e..1ed3e0788c313 100644 --- a/x-pack/plugins/canvas/public/components/element_card/__examples__/element_card.stories.tsx +++ b/x-pack/plugins/canvas/public/components/element_card/__examples__/element_card.stories.tsx @@ -11,7 +11,7 @@ import { ElementCard } from '../element_card'; import { elasticLogo } from '../../../lib/elastic_logo'; storiesOf('components/Elements/ElementCard', module) - .addDecorator(story => ( + .addDecorator((story) => (
({ +const mapStateToProps = (state) => ({ elementStats: getElementStats(state), }); diff --git a/x-pack/plugins/canvas/public/components/element_content/index.js b/x-pack/plugins/canvas/public/components/element_content/index.js index 3d7cca95e10b7..a138c3acb8ec7 100644 --- a/x-pack/plugins/canvas/public/components/element_content/index.js +++ b/x-pack/plugins/canvas/public/components/element_content/index.js @@ -12,7 +12,7 @@ import { getSelectedPage, getPageById } from '../../state/selectors/workpad'; import { withKibana } from '../../../../../../src/plugins/kibana_react/public'; import { ElementContent as Component } from './element_content'; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ backgroundColor: getPageById(state, getSelectedPage(state)).style.background, }); diff --git a/x-pack/plugins/canvas/public/components/element_share_container/element_share_container.js b/x-pack/plugins/canvas/public/components/element_share_container/element_share_container.js index ab023aef9520f..3429c40073443 100644 --- a/x-pack/plugins/canvas/public/components/element_share_container/element_share_container.js +++ b/x-pack/plugins/canvas/public/components/element_share_container/element_share_container.js @@ -91,7 +91,7 @@ export class ElementShareContainer extends React.PureComponent { data-shared-item={shouldTrackComplete ? this.state.renderComplete : undefined} data-render-complete={shouldTrackComplete ? this.state.renderComplete : undefined} className={this.props.className} - ref={ref => (this.sharedItemRef = ref)} + ref={(ref) => (this.sharedItemRef = ref)} > {this.props.children}
diff --git a/x-pack/plugins/canvas/public/components/element_wrapper/element_wrapper.js b/x-pack/plugins/canvas/public/components/element_wrapper/element_wrapper.js index 56a8a148bf915..845fc5927d839 100644 --- a/x-pack/plugins/canvas/public/components/element_wrapper/element_wrapper.js +++ b/x-pack/plugins/canvas/public/components/element_wrapper/element_wrapper.js @@ -9,7 +9,7 @@ import PropTypes from 'prop-types'; import { Positionable } from '../positionable'; import { ElementContent } from '../element_content'; -export const ElementWrapper = props => { +export const ElementWrapper = (props) => { const { renderable, transformMatrix, width, height, state, handlers } = props; return ( diff --git a/x-pack/plugins/canvas/public/components/element_wrapper/index.js b/x-pack/plugins/canvas/public/components/element_wrapper/index.js index 85882377b7684..390c349ab2ee6 100644 --- a/x-pack/plugins/canvas/public/components/element_wrapper/index.js +++ b/x-pack/plugins/canvas/public/components/element_wrapper/index.js @@ -59,14 +59,14 @@ export const ElementWrapper = compose( connectAdvanced(selectorFactory), withPropsOnChange( (props, nextProps) => !isEqual(props.element, nextProps.element), - props => { + (props) => { const { element, createHandlers } = props; const handlers = createHandlers(element); // this removes element and createHandlers from passed props return { handlers }; } ), - mapProps(props => { + mapProps((props) => { // remove element and createHandlers from props passed to component // eslint-disable-next-line no-unused-vars const { element, createHandlers, selectedPage, ...restProps } = props; diff --git a/x-pack/plugins/canvas/public/components/element_wrapper/lib/handlers.js b/x-pack/plugins/canvas/public/components/element_wrapper/lib/handlers.js index 8ea90974e2c53..33e8eacd902dd 100644 --- a/x-pack/plugins/canvas/public/components/element_wrapper/lib/handlers.js +++ b/x-pack/plugins/canvas/public/components/element_wrapper/lib/handlers.js @@ -11,12 +11,12 @@ import { fetchEmbeddableRenderable, } from '../../../state/actions/embeddable'; -export const createHandlers = dispatch => { +export const createHandlers = (dispatch) => { let isComplete = false; let oldElement; let completeFn = () => {}; - return element => { + return (element) => { // reset isComplete when element changes if (!isEqual(oldElement, element)) { isComplete = false; diff --git a/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.tsx b/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.tsx index 35eedde59a014..df9dad3e7f678 100644 --- a/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.tsx +++ b/x-pack/plugins/canvas/public/components/embeddable_flyout/flyout.tsx @@ -30,7 +30,7 @@ export class AddEmbeddableFlyout extends React.Component { const embeddableFactories = this.props.getEmbeddableFactories(); // Find the embeddable type from the saved object type - const found = Array.from(embeddableFactories).find(embeddableFactory => { + const found = Array.from(embeddableFactories).find((embeddableFactory) => { return Boolean( embeddableFactory.savedObjectMetaData && embeddableFactory.savedObjectMetaData.type === savedObjectType @@ -46,11 +46,11 @@ export class AddEmbeddableFlyout extends React.Component { const embeddableFactories = this.props.getEmbeddableFactories(); const availableSavedObjects = Array.from(embeddableFactories) - .filter(factory => { + .filter((factory) => { return this.props.availableEmbeddables.includes(factory.type); }) - .map(factory => factory.savedObjectMetaData) - .filter>(function( + .map((factory) => factory.savedObjectMetaData) + .filter>(function ( maybeSavedObjectMetaData ): maybeSavedObjectMetaData is SavedObjectMetaData<{}> { return maybeSavedObjectMetaData !== undefined; diff --git a/x-pack/plugins/canvas/public/components/enhance/error_boundary.tsx b/x-pack/plugins/canvas/public/components/enhance/error_boundary.tsx index e24ae57cbc606..134efe61c9dcb 100644 --- a/x-pack/plugins/canvas/public/components/enhance/error_boundary.tsx +++ b/x-pack/plugins/canvas/public/components/enhance/error_boundary.tsx @@ -27,7 +27,7 @@ interface ComponentProps extends Props { children: (props: Props) => ReactChildren; } -const ErrorBoundaryComponent: FunctionComponent = props => ( +const ErrorBoundaryComponent: FunctionComponent = (props) => ( {props.children({ error: props.error, @@ -68,7 +68,7 @@ export const errorBoundaryHoc = compose( this.props.setErrorInfo(errorInfo); }, }), - mapProps>(props => + mapProps>((props) => omit(props, ['setError', 'setErrorInfo']) ) ); diff --git a/x-pack/plugins/canvas/public/components/enhance/stateful_prop.js b/x-pack/plugins/canvas/public/components/enhance/stateful_prop.js index 9e035db80b4d9..1f865f9b9c6b7 100644 --- a/x-pack/plugins/canvas/public/components/enhance/stateful_prop.js +++ b/x-pack/plugins/canvas/public/components/enhance/stateful_prop.js @@ -7,10 +7,10 @@ import React from 'react'; import PropTypes from 'prop-types'; -const getDisplayName = Comp => Comp.displayName || Comp.name || 'UnnamedComponent'; +const getDisplayName = (Comp) => Comp.displayName || Comp.name || 'UnnamedComponent'; export function createStatefulPropHoc(fieldname, updater = 'updateValue') { - return Comp => { + return (Comp) => { class WrappedControlledInput extends React.PureComponent { constructor(props) { super(props); @@ -24,7 +24,7 @@ export function createStatefulPropHoc(fieldname, updater = 'updateValue') { this.setState({ value: nextProps[fieldname] }); } - handleChange = ev => { + handleChange = (ev) => { if (ev.target) { this.setState({ value: ev.target.value }); } else { diff --git a/x-pack/plugins/canvas/public/components/es_field_select/es_field_select.js b/x-pack/plugins/canvas/public/components/es_field_select/es_field_select.js index 11c8ab88a4cba..16c94a44299a4 100644 --- a/x-pack/plugins/canvas/public/components/es_field_select/es_field_select.js +++ b/x-pack/plugins/canvas/public/components/es_field_select/es_field_select.js @@ -11,14 +11,14 @@ import { get } from 'lodash'; export const ESFieldSelect = ({ value, fields = [], onChange, onFocus, onBlur }) => { const selectedOption = value ? [{ label: value }] : []; - const options = fields.map(field => ({ label: field })); + const options = fields.map((field) => ({ label: field })); return ( onChange(get(field, 'label', null))} - onSearchChange={searchValue => { + onSearchChange={(searchValue) => { // resets input when user starts typing if (searchValue) { onChange(null); diff --git a/x-pack/plugins/canvas/public/components/es_field_select/index.js b/x-pack/plugins/canvas/public/components/es_field_select/index.js index 2dc2484083241..e2e86a2a4aea3 100644 --- a/x-pack/plugins/canvas/public/components/es_field_select/index.js +++ b/x-pack/plugins/canvas/public/components/es_field_select/index.js @@ -19,7 +19,7 @@ export const ESFieldSelect = compose( componentDidUpdate({ index }) { const { value, onChange, setFields } = this.props; if (this.props.index !== index) { - getFields(this.props.index).then(fields => { + getFields(this.props.index).then((fields) => { setFields(fields); }); } diff --git a/x-pack/plugins/canvas/public/components/es_fields_select/es_fields_select.js b/x-pack/plugins/canvas/public/components/es_fields_select/es_fields_select.js index ca2cac5a64793..0b067d94c8a9b 100644 --- a/x-pack/plugins/canvas/public/components/es_fields_select/es_fields_select.js +++ b/x-pack/plugins/canvas/public/components/es_fields_select/es_fields_select.js @@ -9,11 +9,11 @@ import PropTypes from 'prop-types'; import { EuiComboBox } from '@elastic/eui'; export const ESFieldsSelect = ({ selected, fields, onChange, onFocus, onBlur }) => { - const options = fields.map(value => ({ + const options = fields.map((value) => ({ label: value, })); - const selectedOptions = selected.map(value => ({ + const selectedOptions = selected.map((value) => ({ label: value, })); @@ -21,7 +21,7 @@ export const ESFieldsSelect = ({ selected, fields, onChange, onFocus, onBlur }) onChange(values.map(({ label }) => label))} + onChange={(values) => onChange(values.map(({ label }) => label))} className="canvasFieldsSelect" onFocus={onFocus} onBlur={onBlur} diff --git a/x-pack/plugins/canvas/public/components/es_fields_select/index.js b/x-pack/plugins/canvas/public/components/es_fields_select/index.js index aa607a9ebea4a..13b6f4558e6be 100644 --- a/x-pack/plugins/canvas/public/components/es_fields_select/index.js +++ b/x-pack/plugins/canvas/public/components/es_fields_select/index.js @@ -21,7 +21,7 @@ export const ESFieldsSelect = compose( if (this.props.index !== index) { getFields(this.props.index).then((fields = []) => { setFields(fields); - onChange(selected.filter(option => fields.includes(option))); + onChange(selected.filter((option) => fields.includes(option))); }); } }, diff --git a/x-pack/plugins/canvas/public/components/es_index_select/es_index_select.js b/x-pack/plugins/canvas/public/components/es_index_select/es_index_select.js index 8f1a4932a5e6c..9bd4966b91891 100644 --- a/x-pack/plugins/canvas/public/components/es_index_select/es_index_select.js +++ b/x-pack/plugins/canvas/public/components/es_index_select/es_index_select.js @@ -13,13 +13,13 @@ const defaultIndex = '_all'; export const ESIndexSelect = ({ value, loading, indices, onChange, onFocus, onBlur }) => { const selectedOption = value !== defaultIndex ? [{ label: value }] : []; - const options = indices.map(index => ({ label: index })); + const options = indices.map((index) => ({ label: index })); return ( onChange(get(index, 'label', defaultIndex))} - onSearchChange={searchValue => { + onSearchChange={(searchValue) => { // resets input when user starts typing if (searchValue) { onChange(defaultIndex); @@ -31,7 +31,7 @@ export const ESIndexSelect = ({ value, loading, indices, onChange, onFocus, onBl options={options} singleSelection={{ asPlainText: true }} isClearable={false} - onCreateOption={input => onChange(input || defaultIndex)} + onCreateOption={(input) => onChange(input || defaultIndex)} compressed /> ); diff --git a/x-pack/plugins/canvas/public/components/expression/expression.js b/x-pack/plugins/canvas/public/components/expression/expression.js index f2b7259f8f1f8..37cf1b821d9fd 100644 --- a/x-pack/plugins/canvas/public/components/expression/expression.js +++ b/x-pack/plugins/canvas/public/components/expression/expression.js @@ -28,7 +28,7 @@ const { useRef } = React; const shortcut = (ref, cmd, callback) => ( { + handler={(command) => { const isInputActive = ref.current && ref.current.editor && ref.current.editor.hasTextFocus(); if (isInputActive && command === cmd) { callback(); diff --git a/x-pack/plugins/canvas/public/components/expression/index.js b/x-pack/plugins/canvas/public/components/expression/index.js index c2b559fe03230..4480169dd037d 100644 --- a/x-pack/plugins/canvas/public/components/expression/index.js +++ b/x-pack/plugins/canvas/public/components/expression/index.js @@ -21,13 +21,13 @@ import { setExpression, flushContext } from '../../state/actions/elements'; import { ElementNotSelected } from './element_not_selected'; import { Expression as Component } from './expression'; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ pageId: getSelectedPage(state), element: getSelectedElement(state), }); -const mapDispatchToProps = dispatch => ({ - setExpression: (elementId, pageId) => expression => { +const mapDispatchToProps = (dispatch) => ({ + setExpression: (elementId, pageId) => (expression) => { // destroy the context cache dispatch(flushContext(elementId)); @@ -82,14 +82,14 @@ export const Expression = compose( toggleCompactView: ({ isCompact, setCompact }) => () => { setCompact(!isCompact); }, - updateValue: ({ setFormState }) => expression => { + updateValue: ({ setFormState }) => (expression) => { setFormState({ expression, dirty: true, }); }, - setExpression: ({ setExpression, setFormState }) => exp => { - setFormState(prev => ({ + setExpression: ({ setExpression, setFormState }) => (exp) => { + setFormState((prev) => ({ ...prev, dirty: false, })); @@ -98,7 +98,7 @@ export const Expression = compose( }), expressionLifecycle, withPropsOnChange(['formState'], ({ formState }) => ({ - error: (function() { + error: (function () { try { // TODO: We should merge the advanced UI input and this into a single validated expression input. fromExpression(formState.expression); @@ -108,5 +108,5 @@ export const Expression = compose( } })(), })), - branch(props => !props.element, renderComponent(ElementNotSelected)) + branch((props) => !props.element, renderComponent(ElementNotSelected)) )(Component); diff --git a/x-pack/plugins/canvas/public/components/file_upload/file_upload.tsx b/x-pack/plugins/canvas/public/components/file_upload/file_upload.tsx index 2650b5ebb8fb3..993ee8bde2653 100644 --- a/x-pack/plugins/canvas/public/components/file_upload/file_upload.tsx +++ b/x-pack/plugins/canvas/public/components/file_upload/file_upload.tsx @@ -18,7 +18,7 @@ interface Props { onUpload: () => void; } -export const FileUpload: FunctionComponent = props => ( +export const FileUpload: FunctionComponent = (props) => ( ); diff --git a/x-pack/plugins/canvas/public/components/font_picker/font_picker.tsx b/x-pack/plugins/canvas/public/components/font_picker/font_picker.tsx index 01685cf78d563..4340430829342 100644 --- a/x-pack/plugins/canvas/public/components/font_picker/font_picker.tsx +++ b/x-pack/plugins/canvas/public/components/font_picker/font_picker.tsx @@ -20,14 +20,14 @@ interface Props { value?: FontValue; } -export const FontPicker: FunctionComponent = props => { +export const FontPicker: FunctionComponent = (props) => { const { value, onSelect } = props; // While fonts are strongly-typed, we also support custom fonts someone might type in. // So let's cast the fonts and allow for additions. const displayedFonts: DisplayedFont[] = fonts; - if (value && !fonts.find(font => font.value === value)) { + if (value && !fonts.find((font) => font.value === value)) { const label = (value.indexOf(',') >= 0 ? value.split(',')[0] : value).replace(/['"]/g, ''); displayedFonts.push({ value, label }); displayedFonts.sort((a, b) => a.label.localeCompare(b.label)); @@ -36,7 +36,7 @@ export const FontPicker: FunctionComponent = props => { return ( ({ + options={displayedFonts.map((font) => ({ value: font.value, inputDisplay:
{font.label}
, }))} diff --git a/x-pack/plugins/canvas/public/components/fullscreen/index.js b/x-pack/plugins/canvas/public/components/fullscreen/index.js index 8087644b51655..f6404d4097699 100644 --- a/x-pack/plugins/canvas/public/components/fullscreen/index.js +++ b/x-pack/plugins/canvas/public/components/fullscreen/index.js @@ -8,7 +8,7 @@ import { connect } from 'react-redux'; import { getFullscreen } from '../../state/selectors/app'; import { Fullscreen as Component } from './fullscreen'; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ isFullscreen: getFullscreen(state), }); diff --git a/x-pack/plugins/canvas/public/components/function_form/function_form.js b/x-pack/plugins/canvas/public/components/function_form/function_form.js index 5c8b745d17bd7..8c9f8847d8eed 100644 --- a/x-pack/plugins/canvas/public/components/function_form/function_form.js +++ b/x-pack/plugins/canvas/public/components/function_form/function_form.js @@ -22,7 +22,7 @@ function checkState(state) { // alternate render paths based on expression state const branches = [ // if no expressionType was provided, render the ArgTypeUnknown component - branch(props => !props.expressionType, renderComponent(FunctionUnknown)), + branch((props) => !props.expressionType, renderComponent(FunctionUnknown)), // if the expressionType is in a pending state, render ArgTypeContextPending branch(checkState('pending'), renderComponent(FunctionFormContextPending)), // if the expressionType is in an error state, render ArgTypeContextError diff --git a/x-pack/plugins/canvas/public/components/function_form/function_form_component.js b/x-pack/plugins/canvas/public/components/function_form/function_form_component.js index a076cc8dd714c..8503acf21bc1c 100644 --- a/x-pack/plugins/canvas/public/components/function_form/function_form_component.js +++ b/x-pack/plugins/canvas/public/components/function_form/function_form_component.js @@ -7,7 +7,7 @@ import React from 'react'; import PropTypes from 'prop-types'; -export const FunctionFormComponent = props => { +export const FunctionFormComponent = (props) => { const passedProps = { argResolver: props.argResolver, args: props.args, diff --git a/x-pack/plugins/canvas/public/components/function_form/index.js b/x-pack/plugins/canvas/public/components/function_form/index.js index 774214cf68cec..2b563c30bf50e 100644 --- a/x-pack/plugins/canvas/public/components/function_form/index.js +++ b/x-pack/plugins/canvas/public/components/function_form/index.js @@ -39,8 +39,8 @@ const mapDispatchToProps = (dispatch, { expressionIndex }) => ({ addArgumentValueAtIndex({ index: expressionIndex, element, pageId, argName, value: argValue }) ); }, - updateContext: element => () => dispatch(fetchContext(expressionIndex, element)), - setArgument: (element, pageId) => (argName, valueIndex) => value => { + updateContext: (element) => () => dispatch(fetchContext(expressionIndex, element)), + setArgument: (element, pageId) => (argName, valueIndex) => (value) => { dispatch( setArgumentAtIndex({ index: expressionIndex, diff --git a/x-pack/plugins/canvas/public/components/function_form_list/function_form_list.js b/x-pack/plugins/canvas/public/components/function_form_list/function_form_list.js index ae2e6404f0bb8..529b40b3dcbe5 100644 --- a/x-pack/plugins/canvas/public/components/function_form_list/function_form_list.js +++ b/x-pack/plugins/canvas/public/components/function_form_list/function_form_list.js @@ -9,7 +9,7 @@ import PropTypes from 'prop-types'; import { FunctionForm } from '../function_form'; export const FunctionFormList = ({ functionFormItems }) => { - const argTypeComponents = functionFormItems.map(functionFormProps => { + const argTypeComponents = functionFormItems.map((functionFormProps) => { return ( { +const functionFormItems = withProps((props) => { const selectedElement = props.element; const FunctionFormChain = get(selectedElement, 'ast.chain', []); @@ -47,7 +47,7 @@ const functionFormItems = withProps(props => { args: argType.arguments, argType: argType.function, argTypeDef: argTypeDef, - argResolver: argAst => interpretAst(argAst, prevContext), + argResolver: (argAst) => interpretAst(argAst, prevContext), contextExpression: getExpression(prevContext), expressionIndex: i, // preserve the index in the AST nextArgType: nextArg && nextArg.function, diff --git a/x-pack/plugins/canvas/public/components/item_grid/__examples__/item_grid.stories.tsx b/x-pack/plugins/canvas/public/components/item_grid/__examples__/item_grid.stories.tsx index 94340888eafc8..42ff96c8cea15 100644 --- a/x-pack/plugins/canvas/public/components/item_grid/__examples__/item_grid.stories.tsx +++ b/x-pack/plugins/canvas/public/components/item_grid/__examples__/item_grid.stories.tsx @@ -12,17 +12,17 @@ import { ItemGrid } from '../item_grid'; storiesOf('components/ItemGrid', module) .add('simple grid', () => ( -
{item}
} /> +
{item}
} /> )) .add('icon grid', () => ( } + children={(item) => } /> )) .add('color dot grid', () => ( - {item => } + {(item) => } )) .add('complex grid', () => ( @@ -35,7 +35,7 @@ storiesOf('components/ItemGrid', module) ] as Array<{ color: string; icon: IconType }> } > - {item => ( + {(item) => ( diff --git a/x-pack/plugins/canvas/public/components/keyboard_shortcuts_doc/keyboard_shortcuts_doc.tsx b/x-pack/plugins/canvas/public/components/keyboard_shortcuts_doc/keyboard_shortcuts_doc.tsx index 1c94969292b59..02aa78b5dfe00 100644 --- a/x-pack/plugins/canvas/public/components/keyboard_shortcuts_doc/keyboard_shortcuts_doc.tsx +++ b/x-pack/plugins/canvas/public/components/keyboard_shortcuts_doc/keyboard_shortcuts_doc.tsx @@ -55,7 +55,9 @@ const getDescriptionListItems = (shortcuts: ShortcutMap[]): DescriptionListItem[ {getPrettyShortcut(shortcut) .split(/( )/g) - .map(key => (key === ' ' ? key : {key}))} + .map((key) => + key === ' ' ? key : {key} + )} ); return acc; diff --git a/x-pack/plugins/canvas/public/components/link/link.js b/x-pack/plugins/canvas/public/components/link/link.js index ce709243ceebf..d973164190592 100644 --- a/x-pack/plugins/canvas/public/components/link/link.js +++ b/x-pack/plugins/canvas/public/components/link/link.js @@ -12,7 +12,7 @@ import { ComponentStrings } from '../../../i18n'; const { Link: strings } = ComponentStrings; -const isModifiedEvent = ev => !!(ev.metaKey || ev.altKey || ev.ctrlKey || ev.shiftKey); +const isModifiedEvent = (ev) => !!(ev.metaKey || ev.altKey || ev.ctrlKey || ev.shiftKey); export class Link extends React.PureComponent { static propTypes = { @@ -27,7 +27,7 @@ export class Link extends React.PureComponent { router: PropTypes.object, }; - navigateTo = (name, params) => ev => { + navigateTo = (name, params) => (ev) => { if (this.props.onClick) { this.props.onClick(ev); } diff --git a/x-pack/plugins/canvas/public/components/page_config/index.js b/x-pack/plugins/canvas/public/components/page_config/index.js index a51e6b4b5d987..7770154c8e477 100644 --- a/x-pack/plugins/canvas/public/components/page_config/index.js +++ b/x-pack/plugins/canvas/public/components/page_config/index.js @@ -14,7 +14,7 @@ import { PageConfig as Component } from './page_config'; const { PageConfig: strings } = ComponentStrings; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const pageIndex = getSelectedPageIndex(state); const page = getPages(state)[pageIndex]; return { page, pageIndex }; @@ -25,7 +25,7 @@ const mapDispatchToProps = { stylePage, setPageTransition }; const mergeProps = (stateProps, dispatchProps) => { return { pageIndex: stateProps.pageIndex, - setBackground: background => { + setBackground: (background) => { const itsTheNewStyle = { ...stateProps.page.style, background }; dispatchProps.stylePage(stateProps.page.id, itsTheNewStyle); }, @@ -37,7 +37,7 @@ const mergeProps = (stateProps, dispatchProps) => { text: displayName, })) ), - setTransition: name => { + setTransition: (name) => { dispatchProps.setPageTransition(stateProps.page.id, { name }); }, }; diff --git a/x-pack/plugins/canvas/public/components/page_config/page_config.js b/x-pack/plugins/canvas/public/components/page_config/page_config.js index 583bf1427aab1..51a4762fca501 100644 --- a/x-pack/plugins/canvas/public/components/page_config/page_config.js +++ b/x-pack/plugins/canvas/public/components/page_config/page_config.js @@ -57,7 +57,7 @@ export const PageConfig = ({ value={transition ? transition.name : ''} options={transitions} compressed - onChange={e => setTransition(e.target.value)} + onChange={(e) => setTransition(e.target.value)} /> {transition ? ( diff --git a/x-pack/plugins/canvas/public/components/page_manager/index.js b/x-pack/plugins/canvas/public/components/page_manager/index.js index ef5de3feb575c..a198b7b8c3d8c 100644 --- a/x-pack/plugins/canvas/public/components/page_manager/index.js +++ b/x-pack/plugins/canvas/public/components/page_manager/index.js @@ -12,7 +12,7 @@ import { getSelectedPage, getWorkpad, getPages, isWriteable } from '../../state/ import { DEFAULT_WORKPAD_CSS } from '../../../common/lib/constants'; import { PageManager as Component } from './page_manager'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const { id, css } = getWorkpad(state); return { @@ -24,11 +24,11 @@ const mapStateToProps = state => { }; }; -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ addPage: () => dispatch(pageActions.addPage()), movePage: (id, position) => dispatch(pageActions.movePage(id, position)), - duplicatePage: id => dispatch(pageActions.duplicatePage(id)), - removePage: id => dispatch(pageActions.removePage(id)), + duplicatePage: (id) => dispatch(pageActions.duplicatePage(id)), + removePage: (id) => dispatch(pageActions.removePage(id)), }); export const PageManager = compose( diff --git a/x-pack/plugins/canvas/public/components/page_manager/page_manager.js b/x-pack/plugins/canvas/public/components/page_manager/page_manager.js index 2208d7f363f5e..3e2ff9dfe2b22 100644 --- a/x-pack/plugins/canvas/public/components/page_manager/page_manager.js +++ b/x-pack/plugins/canvas/public/components/page_manager/page_manager.js @@ -94,7 +94,7 @@ export class PageManager extends React.PureComponent { } }; - confirmDelete = pageId => { + confirmDelete = (pageId) => { this._isMounted && this.props.setDeleteId(pageId); }; @@ -133,13 +133,13 @@ export class PageManager extends React.PureComponent { return ( - {provided => ( + {(provided) => (
{ + ref={(el) => { if (page.id === selectedPage) { this.activePageRef = el; } @@ -194,12 +194,12 @@ export class PageManager extends React.PureComponent { - {provided => ( + {(provided) => (
{ + ref={(el) => { this.pageListRef = el; provided.innerRef(el); }} @@ -219,7 +219,10 @@ export class PageManager extends React.PureComponent { content="Add a new page to this workpad" position="left" > - diff --git a/x-pack/plugins/canvas/public/components/page_preview/page_controls.js b/x-pack/plugins/canvas/public/components/page_preview/page_controls.js index 727794e72ee15..1251f441f1082 100644 --- a/x-pack/plugins/canvas/public/components/page_preview/page_controls.js +++ b/x-pack/plugins/canvas/public/components/page_preview/page_controls.js @@ -13,12 +13,12 @@ import { ComponentStrings } from '../../../i18n'; const { PagePreviewPageControls: strings } = ComponentStrings; export const PageControls = ({ pageId, onDelete, onDuplicate }) => { - const handleDuplicate = ev => { + const handleDuplicate = (ev) => { ev.preventDefault(); onDuplicate(pageId); }; - const handleDelete = ev => { + const handleDelete = (ev) => { ev.preventDefault(); onDelete(pageId); }; diff --git a/x-pack/plugins/canvas/public/components/paginate/paginate.js b/x-pack/plugins/canvas/public/components/paginate/paginate.js index 52e744ec769e8..8dfa616ed8d14 100644 --- a/x-pack/plugins/canvas/public/components/paginate/paginate.js +++ b/x-pack/plugins/canvas/public/components/paginate/paginate.js @@ -6,7 +6,7 @@ import PropTypes from 'prop-types'; -export const Paginate = props => { +export const Paginate = (props) => { return props.children({ rows: props.partialRows, perPage: props.perPage, @@ -14,7 +14,7 @@ export const Paginate = props => { totalPages: props.totalPages, nextPageEnabled: props.nextPageEnabled, prevPageEnabled: props.prevPageEnabled, - setPage: num => props.setPage(num), + setPage: (num) => props.setPage(num), nextPage: props.nextPage, prevPage: props.prevPage, }); diff --git a/x-pack/plugins/canvas/public/components/palette_picker/palette_picker.js b/x-pack/plugins/canvas/public/components/palette_picker/palette_picker.js index e5808dd623530..ca2a499feb84c 100644 --- a/x-pack/plugins/canvas/public/components/palette_picker/palette_picker.js +++ b/x-pack/plugins/canvas/public/components/palette_picker/palette_picker.js @@ -13,7 +13,7 @@ import { PaletteSwatch } from '../palette_swatch'; import { palettes } from '../../../common/lib/palettes'; export const PalettePicker = ({ onChange, value, anchorPosition, ariaLabel }) => { - const button = handleClick => ( + const button = (handleClick) => ( diff --git a/x-pack/plugins/canvas/public/components/palette_swatch/palette_swatch.js b/x-pack/plugins/canvas/public/components/palette_swatch/palette_swatch.js index fcc34c8d85448..71d16260e00c7 100644 --- a/x-pack/plugins/canvas/public/components/palette_swatch/palette_swatch.js +++ b/x-pack/plugins/canvas/public/components/palette_swatch/palette_swatch.js @@ -11,7 +11,7 @@ export const PaletteSwatch = ({ colors, gradient }) => { let colorBoxes; if (!gradient) { - colorBoxes = colors.map(color => ( + colorBoxes = colors.map((color) => (
{ // Throw if there is more than one child React.Children.only(children); // This could probably be made nicer by having just one child - const wrappedChildren = React.Children.map(children, child => { + const wrappedChildren = React.Children.map(children, (child) => { const newStyle = { width, height, diff --git a/x-pack/plugins/canvas/public/components/render_to_dom/render_to_dom.js b/x-pack/plugins/canvas/public/components/render_to_dom/render_to_dom.js index cb9912e717173..db393a8dde4f9 100644 --- a/x-pack/plugins/canvas/public/components/render_to_dom/render_to_dom.js +++ b/x-pack/plugins/canvas/public/components/render_to_dom/render_to_dom.js @@ -28,7 +28,7 @@ export class RenderToDom extends React.Component { render() { const { domNode, setDomNode, style } = this.props; - const linkRef = refNode => { + const linkRef = (refNode) => { if (!domNode && refNode) { // Initialize the domNode property. This should only happen once, even if config changes. setDomNode(refNode); diff --git a/x-pack/plugins/canvas/public/components/render_with_fn/index.js b/x-pack/plugins/canvas/public/components/render_with_fn/index.js index 473aaaf9d1ac6..37c49624a3940 100644 --- a/x-pack/plugins/canvas/public/components/render_with_fn/index.js +++ b/x-pack/plugins/canvas/public/components/render_with_fn/index.js @@ -20,7 +20,7 @@ export const RenderWithFn = compose( }) ), withKibana, - withProps(props => ({ + withProps((props) => ({ onError: props.kibana.services.canvas.notify.error, })) )(Component); diff --git a/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.js b/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.js index ce27e99256fc6..763cbd5e53eb1 100644 --- a/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.js +++ b/x-pack/plugins/canvas/public/components/render_with_fn/render_with_fn.js @@ -94,7 +94,7 @@ export class RenderWithFn extends React.Component { } }; - _resetRenderTarget = domNode => { + _resetRenderTarget = (domNode) => { const { handlers } = this.props; if (!domNode) { @@ -122,7 +122,7 @@ export class RenderWithFn extends React.Component { return div; }; - _shouldFullRerender = prevProps => { + _shouldFullRerender = (prevProps) => { // required to stop re-renders on element move, anything that should // cause a re-render needs to be checked here // TODO: fix props passed in to remove this check @@ -146,7 +146,7 @@ export class RenderWithFn extends React.Component { > { + render={(domNode) => { this._domNode = domNode; this._callRenderFn(); }} diff --git a/x-pack/plugins/canvas/public/components/router/router.js b/x-pack/plugins/canvas/public/components/router/router.js index 40c9c469e5505..dd275b3949f34 100644 --- a/x-pack/plugins/canvas/public/components/router/router.js +++ b/x-pack/plugins/canvas/public/components/router/router.js @@ -43,7 +43,7 @@ export class Router extends React.PureComponent { let firstLoad = true; // when the component in the route changes, render it - router.onPathChange(route => { + router.onPathChange((route) => { const { pathname } = route.location; const { component } = route.meta; @@ -64,7 +64,7 @@ export class Router extends React.PureComponent { router .execute() .then(() => onLoad()) - .catch(err => onError(err)); + .catch((err) => onError(err)); } const appState = getAppState(); diff --git a/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/element_controls.stories.tsx b/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/element_controls.stories.tsx index 5210210ebaa74..ec0304dd63726 100644 --- a/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/element_controls.stories.tsx +++ b/x-pack/plugins/canvas/public/components/saved_elements_modal/__examples__/element_controls.stories.tsx @@ -10,7 +10,7 @@ import { action } from '@storybook/addon-actions'; import { ElementControls } from '../element_controls'; storiesOf('components/SavedElementsModal/ElementControls', module) - .addDecorator(story => ( + .addDecorator((story) => (
( + .addDecorator((story) => (
{} }: Props) => { {Object.keys(shapes) .sort() - .map(shapeKey => ( + .map((shapeKey) => ( onChange(shapeKey)}> diff --git a/x-pack/plugins/canvas/public/components/shape_picker_popover/__examples__/shape_picker_popover.stories.tsx b/x-pack/plugins/canvas/public/components/shape_picker_popover/__examples__/shape_picker_popover.stories.tsx index 389ee7791baba..4e3d8ae219d29 100644 --- a/x-pack/plugins/canvas/public/components/shape_picker_popover/__examples__/shape_picker_popover.stories.tsx +++ b/x-pack/plugins/canvas/public/components/shape_picker_popover/__examples__/shape_picker_popover.stories.tsx @@ -20,7 +20,7 @@ class Interactive extends React.Component<{}, { value: string }> { return ( this.setState({ value })} + onChange={(value) => this.setState({ value })} value={this.state.value} /> ); diff --git a/x-pack/plugins/canvas/public/components/sidebar/element_settings/index.tsx b/x-pack/plugins/canvas/public/components/sidebar/element_settings/index.tsx index b5e44b4996537..b8d5882234899 100644 --- a/x-pack/plugins/canvas/public/components/sidebar/element_settings/index.tsx +++ b/x-pack/plugins/canvas/public/components/sidebar/element_settings/index.tsx @@ -21,7 +21,7 @@ interface StateProps { element: PositionedElement | undefined; } -const renderIfElement: React.FunctionComponent = props => { +const renderIfElement: React.FunctionComponent = (props) => { if (props.element) { return ; } diff --git a/x-pack/plugins/canvas/public/components/sidebar/sidebar_content.js b/x-pack/plugins/canvas/public/components/sidebar/sidebar_content.js index f333705a1a3c6..a9b6b80b9ff01 100644 --- a/x-pack/plugins/canvas/public/components/sidebar/sidebar_content.js +++ b/x-pack/plugins/canvas/public/components/sidebar/sidebar_content.js @@ -18,7 +18,7 @@ import { ElementSettings } from './element_settings'; const { SidebarContent: strings } = ComponentStrings; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ selectedToplevelNodes: getSelectedToplevelNodes(state), selectedElementId: getSelectedElementId(state), }); diff --git a/x-pack/plugins/canvas/public/components/sidebar_header/__examples__/sidebar_header.stories.tsx b/x-pack/plugins/canvas/public/components/sidebar_header/__examples__/sidebar_header.stories.tsx index 11c66906a6ef6..5cd9133febc39 100644 --- a/x-pack/plugins/canvas/public/components/sidebar_header/__examples__/sidebar_header.stories.tsx +++ b/x-pack/plugins/canvas/public/components/sidebar_header/__examples__/sidebar_header.stories.tsx @@ -17,7 +17,7 @@ const handlers = { }; storiesOf('components/Sidebar/SidebarHeader', module) - .addDecorator(story =>
{story()}
) + .addDecorator((story) =>
{story()}
) .add('default', () => ) .add('with layer controls', () => ( diff --git a/x-pack/plugins/canvas/public/components/sidebar_header/index.js b/x-pack/plugins/canvas/public/components/sidebar_header/index.js index ac282962afb54..aa67de1f55506 100644 --- a/x-pack/plugins/canvas/public/components/sidebar_header/index.js +++ b/x-pack/plugins/canvas/public/components/sidebar_header/index.js @@ -23,33 +23,33 @@ import { SidebarHeader as Component } from './sidebar_header'; /* * TODO: this is all copied from interactive_workpad_page and workpad_shortcuts */ -const mapStateToProps = state => { +const mapStateToProps = (state) => { const pageId = getSelectedPage(state); const nodes = getNodes(state, pageId); const selectedToplevelNodes = getSelectedToplevelNodes(state); const selectedPrimaryShapeObjects = selectedToplevelNodes - .map(id => nodes.find(s => s.id === id)) - .filter(shape => shape); + .map((id) => nodes.find((s) => s.id === id)) + .filter((shape) => shape); const selectedPersistentPrimaryNodes = flatten( - selectedPrimaryShapeObjects.map(shape => - nodes.find(n => n.id === shape.id) // is it a leaf or a persisted group? + selectedPrimaryShapeObjects.map((shape) => + nodes.find((n) => n.id === shape.id) // is it a leaf or a persisted group? ? [shape.id] - : nodes.filter(s => s.parent === shape.id).map(s => s.id) + : nodes.filter((s) => s.parent === shape.id).map((s) => s.id) ) ); const selectedNodeIds = flatten(selectedPersistentPrimaryNodes.map(crawlTree(nodes))); return { pageId, - selectedNodes: selectedNodeIds.map(id => nodes.find(s => s.id === id)), + selectedNodes: selectedNodeIds.map((id) => nodes.find((s) => s.id === id)), }; }; -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ insertNodes: (selectedNodes, pageId) => dispatch(insertNodes(selectedNodes, pageId)), removeNodes: (nodeIds, pageId) => dispatch(removeElements(nodeIds, pageId)), - selectToplevelNodes: nodes => - dispatch(selectToplevelNodes(nodes.filter(e => !e.position.parent).map(e => e.id))), + selectToplevelNodes: (nodes) => + dispatch(selectToplevelNodes(nodes.filter((e) => !e.position.parent).map((e) => e.id))), elementLayer: (pageId, elementId, movement) => { dispatch(elementLayer({ pageId, elementId, movement })); }, diff --git a/x-pack/plugins/canvas/public/components/text_style_picker/text_style_picker.js b/x-pack/plugins/canvas/public/components/text_style_picker/text_style_picker.js index 179455e15b36e..48d52abb03125 100644 --- a/x-pack/plugins/canvas/public/components/text_style_picker/text_style_picker.js +++ b/x-pack/plugins/canvas/public/components/text_style_picker/text_style_picker.js @@ -85,9 +85,9 @@ export const TextStylePicker = ({ }); }; - const onAlignmentChange = optionId => doChange('align', optionId); + const onAlignmentChange = (optionId) => doChange('align', optionId); - const onStyleChange = optionId => { + const onStyleChange = (optionId) => { let prop; let value; @@ -106,14 +106,14 @@ export const TextStylePicker = ({
- doChange('family', value)} /> + doChange('family', value)} /> doChange('size', Number(e.target.value))} - options={fontSizes.map(size => ({ text: String(size), value: size }))} + onChange={(e) => doChange('size', Number(e.target.value))} + options={fontSizes.map((size) => ({ text: String(size), value: size }))} prepend="Size" /> @@ -125,7 +125,7 @@ export const TextStylePicker = ({ doChange('color', value)} + onChange={(value) => doChange('color', value)} colors={colors} ariaLabel={strings.getFontColorLabel()} /> diff --git a/x-pack/plugins/canvas/public/components/tool_tip_shortcut/__examples__/tool_tip_shortcut.stories.tsx b/x-pack/plugins/canvas/public/components/tool_tip_shortcut/__examples__/tool_tip_shortcut.stories.tsx index 01aaeb2388d6c..e9669b3014889 100644 --- a/x-pack/plugins/canvas/public/components/tool_tip_shortcut/__examples__/tool_tip_shortcut.stories.tsx +++ b/x-pack/plugins/canvas/public/components/tool_tip_shortcut/__examples__/tool_tip_shortcut.stories.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { ToolTipShortcut } from '../tool_tip_shortcut'; storiesOf('components/ToolTipShortcut', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('with shortcut', () => ) diff --git a/x-pack/plugins/canvas/public/components/toolbar/index.js b/x-pack/plugins/canvas/public/components/toolbar/index.js index 294a44ba0415a..16860063f8a45 100644 --- a/x-pack/plugins/canvas/public/components/toolbar/index.js +++ b/x-pack/plugins/canvas/public/components/toolbar/index.js @@ -19,7 +19,7 @@ import { import { Toolbar as Component } from './toolbar'; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ workpadName: getWorkpadName(state), workpadId: getWorkpad(state).id, totalPages: getWorkpad(state).pages.length, @@ -35,15 +35,15 @@ export const Toolbar = compose( router: PropTypes.object, }), withHandlers({ - nextPage: props => () => { + nextPage: (props) => () => { const pageNumber = Math.min(props.selectedPageNumber + 1, props.totalPages); props.router.navigateTo('loadWorkpad', { id: props.workpadId, page: pageNumber }); }, - previousPage: props => () => { + previousPage: (props) => () => { const pageNumber = Math.max(1, props.selectedPageNumber - 1); props.router.navigateTo('loadWorkpad', { id: props.workpadId, page: pageNumber }); }, }), - withState('tray', 'setTray', props => props.tray), + withState('tray', 'setTray', (props) => props.tray), withState('showWorkpadManager', 'setShowWorkpadManager', false) )(Component); diff --git a/x-pack/plugins/canvas/public/components/workpad/index.js b/x-pack/plugins/canvas/public/components/workpad/index.js index fca663f8532d8..72c4588e43c03 100644 --- a/x-pack/plugins/canvas/public/components/workpad/index.js +++ b/x-pack/plugins/canvas/public/components/workpad/index.js @@ -23,7 +23,7 @@ import { trackCanvasUiMetric, METRIC_TYPE } from '../../lib/ui_metric'; import { LAUNCHED_FULLSCREEN, LAUNCHED_FULLSCREEN_AUTOPLAY } from '../../../common/lib/constants'; import { Workpad as Component } from './workpad'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const { width, height, id: workpadId, css: workpadCss } = getWorkpad(state); return { pages: getPages(state), @@ -51,7 +51,7 @@ const mergeProps = (stateProps, dispatchProps, ownProps) => { ...ownProps, ...stateProps, ...dispatchProps, - setFullscreen: value => { + setFullscreen: (value) => { dispatchProps.setFullscreen(value); if (value === true) { @@ -93,7 +93,7 @@ export const Workpad = compose( return { getAnimation }; }), withHandlers({ - onPageChange: props => pageNumber => { + onPageChange: (props) => (pageNumber) => { if (pageNumber === props.selectedPageNumber) { return; } @@ -108,11 +108,11 @@ export const Workpad = compose( }), withHandlers({ onTransitionEnd: ({ setTransition }) => () => setTransition(null), - nextPage: props => () => { + nextPage: (props) => () => { const pageNumber = Math.min(props.selectedPageNumber + 1, props.pages.length); props.onPageChange(pageNumber); }, - previousPage: props => () => { + previousPage: (props) => () => { const pageNumber = Math.max(1, props.selectedPageNumber - 1); props.onPageChange(pageNumber); }, diff --git a/x-pack/plugins/canvas/public/components/workpad_config/index.js b/x-pack/plugins/canvas/public/components/workpad_config/index.js index aa3bbdce97863..913cf7093e726 100644 --- a/x-pack/plugins/canvas/public/components/workpad_config/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_config/index.js @@ -12,7 +12,7 @@ import { getWorkpad } from '../../state/selectors/workpad'; import { DEFAULT_WORKPAD_CSS } from '../../../common/lib/constants'; import { WorkpadConfig as Component } from './workpad_config'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const workpad = getWorkpad(state); return { @@ -26,9 +26,9 @@ const mapStateToProps = state => { }; const mapDispatchToProps = { - setSize: size => sizeWorkpad(size), - setName: name => setName(name), - setWorkpadCSS: css => setWorkpadCSS(css), + setSize: (size) => sizeWorkpad(size), + setName: (name) => setName(name), + setWorkpadCSS: (css) => setWorkpadCSS(css), }; export const WorkpadConfig = connect(mapStateToProps, mapDispatchToProps)(Component); diff --git a/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.js b/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.js index 7dfc378432b57..45758c9965653 100644 --- a/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.js +++ b/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.js @@ -76,7 +76,7 @@ export class WorkpadConfig extends PureComponent { - setName(e.target.value)} /> + setName(e.target.value)} /> @@ -86,7 +86,7 @@ export class WorkpadConfig extends PureComponent { setSize({ width: Number(e.target.value), height: size.height })} + onChange={(e) => setSize({ width: Number(e.target.value), height: size.height })} value={size.width} /> @@ -107,7 +107,7 @@ export class WorkpadConfig extends PureComponent { setSize({ height: Number(e.target.value), width: size.width })} + onChange={(e) => setSize({ height: Number(e.target.value), width: size.width })} value={size.height} /> @@ -152,7 +152,7 @@ export class WorkpadConfig extends PureComponent { aria-label={strings.getGlobalCSSTooltip()} value={css} compressed - onChange={e => this.setState({ css: e.target.value })} + onChange={(e) => this.setState({ css: e.target.value })} rows={10} /> diff --git a/x-pack/plugins/canvas/public/components/workpad_header/edit_menu/index.ts b/x-pack/plugins/canvas/public/components/workpad_header/edit_menu/index.ts index a8bb7177dbd24..5debb675af659 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/edit_menu/index.ts +++ b/x-pack/plugins/canvas/public/components/workpad_header/edit_menu/index.ts @@ -67,7 +67,7 @@ const mapStateToProps = (state: State) => { selectedPrimaryShapeObjects.map((shape: PositionedElement) => nodes.find((n: PositionedElement) => n.id === shape.id) // is it a leaf or a persisted group? ? [shape.id] - : nodes.filter((s: PositionedElement) => s.position.parent === shape.id).map(s => s.id) + : nodes.filter((s: PositionedElement) => s.position.parent === shape.id).map((s) => s.id) ) ); const selectedNodeIds = flatten(selectedPersistentPrimaryNodes.map(crawlTree(nodes))); @@ -75,7 +75,7 @@ const mapStateToProps = (state: State) => { return { pageId, selectedToplevelNodes, - selectedNodes: selectedNodeIds.map((id: string) => nodes.find(s => s.id === id)), + selectedNodes: selectedNodeIds.map((id: string) => nodes.find((s) => s.id === id)), state, }; }; @@ -86,7 +86,9 @@ const mapDispatchToProps = (dispatch: Dispatch) => ({ removeNodes: (nodeIds: string[], pageId: string) => dispatch(removeElements(nodeIds, pageId)), selectToplevelNodes: (nodes: PositionedElement[]) => dispatch( - selectToplevelNodes(nodes.filter((e: PositionedElement) => !e.position.parent).map(e => e.id)) + selectToplevelNodes( + nodes.filter((e: PositionedElement) => !e.position.parent).map((e) => e.id) + ) ), elementLayer: (pageId: string, elementId: string, movement: number) => { dispatch(elementLayer({ pageId, elementId, movement })); diff --git a/x-pack/plugins/canvas/public/components/workpad_header/fullscreen_control/index.js b/x-pack/plugins/canvas/public/components/workpad_header/fullscreen_control/index.js index fc0bd4c74ba24..42396b87d2c73 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/fullscreen_control/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_header/fullscreen_control/index.js @@ -27,7 +27,7 @@ import { FullscreenControl as Component } from './fullscreen_control'; // TODO: a lot of this is borrowed code from `/components/workpad/index.js`. // We should consider extracting the next/prev page logic into to a shared lib file. -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ workpadId: getWorkpad(state).id, pages: getPages(state), selectedPageNumber: getSelectedPageIndex(state) + 1, @@ -35,12 +35,12 @@ const mapStateToProps = state => ({ autoplayEnabled: getAutoplay(state).enabled, }); -const mapDispatchToProps = dispatch => ({ - setFullscreen: value => { +const mapDispatchToProps = (dispatch) => ({ + setFullscreen: (value) => { dispatch(setFullscreen(value)); value && dispatch(selectToplevelNodes([])); }, - enableAutoplay: enabled => dispatch(enableAutoplay(enabled)), + enableAutoplay: (enabled) => dispatch(enableAutoplay(enabled)), fetchAllRenderables: () => dispatch(fetchAllRenderables()), }); @@ -49,7 +49,7 @@ const mergeProps = (stateProps, dispatchProps, ownProps) => { ...ownProps, ...stateProps, ...dispatchProps, - setFullscreen: value => { + setFullscreen: (value) => { dispatchProps.setFullscreen(value); if (value === true) { @@ -89,7 +89,7 @@ export const FullscreenControl = compose( return { getAnimation }; }), withHandlers({ - onPageChange: props => pageNumber => { + onPageChange: (props) => (pageNumber) => { if (pageNumber === props.selectedPageNumber) { return; } @@ -104,11 +104,11 @@ export const FullscreenControl = compose( }), withHandlers({ onTransitionEnd: ({ setTransition }) => () => setTransition(null), - nextPage: props => () => { + nextPage: (props) => () => { const pageNumber = Math.min(props.selectedPageNumber + 1, props.pages.length); props.onPageChange(pageNumber); }, - previousPage: props => () => { + previousPage: (props) => () => { const pageNumber = Math.max(1, props.selectedPageNumber - 1); props.onPageChange(pageNumber); }, diff --git a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/index.ts b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/index.ts index 1ed39b62cccad..64712f0df8d6c 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/index.ts +++ b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/flyout/index.ts @@ -33,7 +33,7 @@ const { WorkpadHeaderShareMenu: strings } = ComponentStrings; const getUnsupportedRenderers = (state: State) => { const renderers: string[] = []; const expressions = getRenderedWorkpadExpressions(state); - expressions.forEach(expression => { + expressions.forEach((expression) => { if (!renderFunctionNames.includes(expression)) { renderers.push(expression); } @@ -71,7 +71,7 @@ export const ShareWebsiteFlyout = compose onCopy: () => { kibana.services.canvas.notify.info(strings.getCopyShareConfigMessage()); }, - onDownload: type => { + onDownload: (type) => { switch (type) { case 'share': downloadRenderedWorkpad(renderedWorkpad); @@ -83,7 +83,7 @@ export const ShareWebsiteFlyout = compose const basePath = kibana.services.http.basePath.get(); arrayBufferFetch .post(`${basePath}${API_ROUTE_SHAREABLE_ZIP}`, JSON.stringify(renderedWorkpad)) - .then(blob => downloadZippedRuntime(blob.data)) + .then((blob) => downloadZippedRuntime(blob.data)) .catch((err: Error) => { kibana.services.canvas.notify.error(err, { title: strings.getShareableZipErrorTitle(workpad.name), diff --git a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/index.ts b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/index.ts index 9a8936ada6d1e..17fcc50334a8f 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/index.ts +++ b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/index.ts @@ -46,7 +46,7 @@ export const ShareMenu = compose( withKibana, withProps( ({ workpad, pageCount, kibana }: Props & WithKibanaProps): ComponentProps => ({ - getExportUrl: type => { + getExportUrl: (type) => { if (type === 'pdf') { const pdfUrl = getPdfUrl(workpad, { pageCount }, kibana.services.http.basePath); return getAbsoluteUrl(pdfUrl); @@ -54,7 +54,7 @@ export const ShareMenu = compose( throw new Error(strings.getUnknownExportErrorMessage(type)); }, - onCopy: type => { + onCopy: (type) => { switch (type) { case 'pdf': kibana.services.canvas.notify.info(strings.getCopyPDFMessage()); @@ -66,7 +66,7 @@ export const ShareMenu = compose( throw new Error(strings.getUnknownExportErrorMessage(type)); } }, - onExport: type => { + onExport: (type) => { switch (type) { case 'pdf': return createPdf(workpad, { pageCount }, kibana.services.http.basePath) diff --git a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/utils.test.ts b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/utils.test.ts index 6c7d7ddd0a793..63e7c26cebb04 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/share_menu/utils.test.ts +++ b/x-pack/plugins/canvas/public/components/workpad_header/share_menu/utils.test.ts @@ -12,7 +12,7 @@ import { fetch } from '../../../../common/lib/fetch'; import { IBasePath } from 'kibana/public'; const basePath = ({ - prepend: jest.fn().mockImplementation(s => `basepath/s/spacey/${s}`), + prepend: jest.fn().mockImplementation((s) => `basepath/s/spacey/${s}`), get: () => 'basepath/s/spacey', serverBasePath: `basepath`, } as unknown) as IBasePath; diff --git a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/auto_refresh_controls.tsx b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/auto_refresh_controls.tsx index cfd599b1d9f3f..d2e76f0afb3e7 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/auto_refresh_controls.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/auto_refresh_controls.tsx @@ -151,7 +151,7 @@ export const AutoRefreshControls = ({ refreshInterval, setRefresh, disableInterv
- setRefresh(value)} /> + setRefresh(value)} />
); diff --git a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/custom_interval.tsx b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/custom_interval.tsx index ab34f332dc126..cda5733cfcf47 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/custom_interval.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/custom_interval.tsx @@ -30,7 +30,7 @@ export const CustomInterval = ({ gutterSize, buttonSize, onSubmit, defaultValue return ( { + onSubmit={(ev) => { ev.preventDefault(); if (!isInvalid && refreshInterval) { onSubmit(refreshInterval); diff --git a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/kiosk_controls.tsx b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/kiosk_controls.tsx index e63eed9f9df53..391a17c39523c 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/kiosk_controls.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/kiosk_controls.tsx @@ -118,7 +118,7 @@ export const KioskControls = ({ autoplayInterval, onSetInterval }: Props) => { - onSetInterval(value)} /> + onSetInterval(value)} /> ); diff --git a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/view_menu.tsx b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/view_menu.tsx index b6f108cda37f6..af0a9ed460b8f 100644 --- a/x-pack/plugins/canvas/public/components/workpad_header/view_menu/view_menu.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_header/view_menu/view_menu.tsx @@ -180,7 +180,7 @@ export const ViewMenu: FunctionComponent = ({ content: ( setRefresh(val)} + setRefresh={(val) => setRefresh(val)} disableInterval={() => disableInterval()} /> ), diff --git a/x-pack/plugins/canvas/public/components/workpad_loader/index.js b/x-pack/plugins/canvas/public/components/workpad_loader/index.js index 8b190338db49e..ab07d5d722405 100644 --- a/x-pack/plugins/canvas/public/components/workpad_loader/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_loader/index.js @@ -20,7 +20,7 @@ import { WorkpadLoader as Component } from './workpad_loader'; const { WorkpadLoader: strings } = ComponentStrings; const { WorkpadLoader: errors } = ErrorStrings; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ workpadId: getWorkpad(state).id, canUserWrite: canUserWrite(state), }); @@ -37,7 +37,7 @@ export const WorkpadLoader = compose( })), withHandlers(({ kibana }) => ({ // Workpad creation via navigation - createWorkpad: props => async workpad => { + createWorkpad: (props) => async (workpad) => { // workpad data uploaded, create and load it if (workpad != null) { try { @@ -55,7 +55,7 @@ export const WorkpadLoader = compose( }, // Workpad search - findWorkpads: ({ setWorkpads }) => async text => { + findWorkpads: ({ setWorkpads }) => async (text) => { try { const workpads = await workpadService.find(text); setWorkpads(workpads); @@ -65,10 +65,10 @@ export const WorkpadLoader = compose( }, // Workpad import/export methods - downloadWorkpad: () => workpadId => downloadWorkpad(workpadId), + downloadWorkpad: () => (workpadId) => downloadWorkpad(workpadId), // Clone workpad given an id - cloneWorkpad: props => async workpadId => { + cloneWorkpad: (props) => async (workpadId) => { try { const workpad = await workpadService.get(workpadId); workpad.name = strings.getClonedWorkpadName(workpad.name); @@ -81,20 +81,20 @@ export const WorkpadLoader = compose( }, // Remove workpad given an array of id - removeWorkpads: props => async workpadIds => { + removeWorkpads: (props) => async (workpadIds) => { const { setWorkpads, workpads, workpadId: loadedWorkpad } = props; - const removeWorkpads = workpadIds.map(id => + const removeWorkpads = workpadIds.map((id) => workpadService .remove(id) .then(() => ({ id, err: null })) - .catch(err => ({ + .catch((err) => ({ id, err, })) ); - return Promise.all(removeWorkpads).then(results => { + return Promise.all(removeWorkpads).then((results) => { let redirectHome = false; const [passes, errored] = results.reduce( @@ -135,8 +135,8 @@ export const WorkpadLoader = compose( }); }, })), - withProps(props => ({ - formatDate: date => { + withProps((props) => ({ + formatDate: (date) => { const dateFormat = props.kibana.services.uiSettings.get('dateFormat'); return date && moment(date).format(dateFormat); }, diff --git a/x-pack/plugins/canvas/public/components/workpad_loader/workpad_loader.js b/x-pack/plugins/canvas/public/components/workpad_loader/workpad_loader.js index 41719e6d6b820..28cfac11e76bd 100644 --- a/x-pack/plugins/canvas/public/components/workpad_loader/workpad_loader.js +++ b/x-pack/plugins/canvas/public/components/workpad_loader/workpad_loader.js @@ -87,14 +87,14 @@ export class WorkpadLoader extends React.PureComponent { }; // create new workpad from uploaded JSON - onUpload = async workpad => { + onUpload = async (workpad) => { this.setState({ createPending: true }); await this.props.createWorkpad(workpad); this._isMounted && this.setState({ createPending: false }); }; // clone existing workpad - cloneWorkpad = async workpad => { + cloneWorkpad = async (workpad) => { this.setState({ createPending: true }); await this.props.cloneWorkpad(workpad.id); this._isMounted && this.setState({ createPending: false }); @@ -108,7 +108,7 @@ export class WorkpadLoader extends React.PureComponent { removeWorkpads = () => { const { selectedWorkpads } = this.state; - this.props.removeWorkpads(selectedWorkpads.map(({ id }) => id)).then(remainingIds => { + this.props.removeWorkpads(selectedWorkpads.map(({ id }) => id)).then((remainingIds) => { const remainingWorkpads = remainingIds.length > 0 ? selectedWorkpads.filter(({ id }) => remainingIds.includes(id)) @@ -127,7 +127,7 @@ export class WorkpadLoader extends React.PureComponent { this.state.selectedWorkpads.forEach(({ id }) => this.props.downloadWorkpad(id)); }; - onSelectionChange = selectedWorkpads => { + onSelectionChange = (selectedWorkpads) => { this.setState({ selectedWorkpads }); }; @@ -145,7 +145,7 @@ export class WorkpadLoader extends React.PureComponent { const actions = [ { - render: workpad => ( + render: (workpad) => ( @@ -202,7 +202,7 @@ export class WorkpadLoader extends React.PureComponent { sortable: true, dataType: 'date', width: '20%', - render: date => this.props.formatDate(date), + render: (date) => this.props.formatDate(date), }, { field: '@timestamp', @@ -210,7 +210,7 @@ export class WorkpadLoader extends React.PureComponent { sortable: true, dataType: 'date', width: '20%', - render: date => this.props.formatDate(date), + render: (date) => this.props.formatDate(date), }, { name: '', actions, width: '5%' }, ]; @@ -374,7 +374,7 @@ export class WorkpadLoader extends React.PureComponent { return ( - {pagination => ( + {(pagination) => ( @@ -387,7 +387,7 @@ export class WorkpadLoader extends React.PureComponent { )} { + onChange={(text) => { pagination.setPage(0); this.props.findWorkpads(text); }} diff --git a/x-pack/plugins/canvas/public/components/workpad_loader/workpad_search.js b/x-pack/plugins/canvas/public/components/workpad_loader/workpad_search.js index c2d16949870ea..c72807681306f 100644 --- a/x-pack/plugins/canvas/public/components/workpad_loader/workpad_search.js +++ b/x-pack/plugins/canvas/public/components/workpad_loader/workpad_search.js @@ -23,7 +23,7 @@ export class WorkpadSearch extends React.PureComponent { triggerChange = debounce(this.props.onChange, 150); - setSearchText = ev => { + setSearchText = (ev) => { const text = ev.target.value; this.setState({ searchText: text }); this.triggerChange(text); diff --git a/x-pack/plugins/canvas/public/components/workpad_page/integration_utils.js b/x-pack/plugins/canvas/public/components/workpad_page/integration_utils.js index 731656dd4e095..648ad161ca92a 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/integration_utils.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/integration_utils.js @@ -14,7 +14,7 @@ import { matrixToAngle } from '../../lib/aeroelastic/matrix'; import { isGroupId, elementToShape } from './utils'; export * from './utils'; -const shapeToElement = shape => ({ +const shapeToElement = (shape) => ({ left: shape.transformMatrix[12] - shape.a, top: shape.transformMatrix[13] - shape.b, width: shape.a * 2, @@ -26,7 +26,7 @@ const shapeToElement = shape => ({ const globalPositionUpdates = (setMultiplePositions, { shapes, gestureEnd }, unsortedElements) => { const ascending = (a, b) => (a.id < b.id ? -1 : 1); - const relevant = s => s.type !== 'annotation' && s.subtype !== 'adHocGroup'; + const relevant = (s) => s.type !== 'annotation' && s.subtype !== 'adHocGroup'; const elements = unsortedElements.filter(relevant).sort(ascending); const repositionings = shapes .filter(relevant) @@ -62,26 +62,26 @@ const globalPositionUpdates = (setMultiplePositions, { shapes, gestureEnd }, uns return repositionings; }; -const dedupe = (d, i, a) => a.findIndex(s => s.id === d.id) === i; +const dedupe = (d, i, a) => a.findIndex((s) => s.id === d.id) === i; -const missingParentCheck = groups => { - const idMap = arrayToMap(groups.map(g => g.id)); - groups.forEach(g => { +const missingParentCheck = (groups) => { + const idMap = arrayToMap(groups.map((g) => g.id)); + groups.forEach((g) => { if (g.parent && !idMap[g.parent]) { g.parent = null; } }); }; -export const shapesForNodes = nodes => { +export const shapesForNodes = (nodes) => { const rawShapes = nodes .map(elementToShape) // filtering to eliminate residual element of a possible group that had been deleted in Redux - .filter((d, i, a) => !isGroupId(d.id) || a.find(s => s.parent === d.id)) + .filter((d, i, a) => !isGroupId(d.id) || a.find((s) => s.parent === d.id)) .filter(dedupe); missingParentCheck(rawShapes); const getLocalMatrix = getLocalTransformMatrix(rawShapes); - return rawShapes.map(s => ({ ...s, localTransformMatrix: getLocalMatrix(s) })); + return rawShapes.map((s) => ({ ...s, localTransformMatrix: getLocalMatrix(s) })); }; const updateGlobalPositionsInRedux = (setMultiplePositions, scene, unsortedElements) => { @@ -91,17 +91,17 @@ const updateGlobalPositionsInRedux = (setMultiplePositions, scene, unsortedEleme } }; -export const globalStateUpdater = (dispatch, globalState) => state => { +export const globalStateUpdater = (dispatch, globalState) => (state) => { const nextScene = state.currentScene; const page = getSelectedPage(globalState); const elements = getNodes(globalState, page); const shapes = nextScene.shapes; - const persistableGroups = shapes.filter(s => s.subtype === 'persistentGroup').filter(dedupe); - const persistedGroups = elements.filter(e => isGroupId(e.id)).filter(dedupe); + const persistableGroups = shapes.filter((s) => s.subtype === 'persistentGroup').filter(dedupe); + const persistedGroups = elements.filter((e) => isGroupId(e.id)).filter(dedupe); - persistableGroups.forEach(g => { + persistableGroups.forEach((g) => { if ( - !persistedGroups.find(p => { + !persistedGroups.find((p) => { if (!p.id) { throw new Error('Element has no id'); } @@ -123,12 +123,13 @@ export const globalStateUpdater = (dispatch, globalState) => state => { const elementsToRemove = persistedGroups.filter( // list elements for removal if they're not in the persistable set, or if there's no longer an associated element // the latter of which shouldn't happen, so it's belts and braces - p => - !persistableGroups.find(g => p.id === g.id) || !elements.find(e => e.position.parent === p.id) + (p) => + !persistableGroups.find((g) => p.id === g.id) || + !elements.find((e) => e.position.parent === p.id) ); updateGlobalPositionsInRedux( - positions => dispatch(setMultiplePositions(positions.map(p => ({ ...p, pageId: page })))), + (positions) => dispatch(setMultiplePositions(positions.map((p) => ({ ...p, pageId: page })))), nextScene, elements ); @@ -137,7 +138,7 @@ export const globalStateUpdater = (dispatch, globalState) => state => { // remove elements for groups that were ungrouped dispatch( removeElements( - elementsToRemove.map(e => e.id), + elementsToRemove.map((e) => e.id), page ) ); @@ -149,9 +150,9 @@ export const globalStateUpdater = (dispatch, globalState) => state => { dispatch( selectToplevelNodes( flatten( - selectedPrimaryShapes.map(n => - n.startsWith('group') && (shapes.find(s => s.id === n) || {}).subtype === 'adHocGroup' - ? shapes.filter(s => s.type !== 'annotation' && s.parent === n).map(s => s.id) + selectedPrimaryShapes.map((n) => + n.startsWith('group') && (shapes.find((s) => s.id === n) || {}).subtype === 'adHocGroup' + ? shapes.filter((s) => s.type !== 'annotation' && s.parent === n).map((s) => s.id) : [n] ) ) @@ -160,10 +161,10 @@ export const globalStateUpdater = (dispatch, globalState) => state => { } }; -export const crawlTree = shapes => shapeId => { - const rec = shapeId => [ +export const crawlTree = (shapes) => (shapeId) => { + const rec = (shapeId) => [ shapeId, - ...flatten(shapes.filter(s => s.position.parent === shapeId).map(s => rec(s.id))), + ...flatten(shapes.filter((s) => s.position.parent === shapeId).map((s) => rec(s.id))), ]; return rec(shapeId); }; diff --git a/x-pack/plugins/canvas/public/components/workpad_page/utils.js b/x-pack/plugins/canvas/public/components/workpad_page/utils.js index 04b1e02d422de..0289d96f91f0b 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/utils.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/utils.js @@ -6,9 +6,9 @@ import { multiply, rotateZ, translate } from '../../lib/aeroelastic/matrix'; -export const isGroupId = id => id.startsWith('group'); +export const isGroupId = (id) => id.startsWith('group'); -const headerData = id => +const headerData = (id) => isGroupId(id) ? { id, type: 'group', subtype: 'persistentGroup' } : { id, type: 'rectangleElement', subtype: '' }; diff --git a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/event_handlers.js b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/event_handlers.js index 2d0f8ee5aa0aa..21f4a5b68b6c9 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/event_handlers.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/event_handlers.js @@ -33,7 +33,7 @@ const setupHandler = (commit, canvasOrigin, zoomScale) => { commit('cursorPosition', {}); } }; - window.onmouseup = e => { + window.onmouseup = (e) => { e.stopPropagation(); const { clientX, clientY, altKey, metaKey, shiftKey, ctrlKey } = e; const { x, y } = localMousePosition(canvasOrigin, clientX, clientY, zoomScale); @@ -81,7 +81,7 @@ const handleMouseDown = (commit, e, canvasOrigin, zoomScale, allowDrag = true) = }; export const eventHandlers = { - onMouseDown: props => e => + onMouseDown: (props) => (e) => handleMouseDown( props.commit, e, @@ -89,8 +89,9 @@ export const eventHandlers = { props.zoomScale, props.canDragElement(e.target) ), - onMouseMove: props => e => handleMouseMove(props.commit, e, props.canvasOrigin, props.zoomScale), - onMouseLeave: props => e => handleMouseLeave(props.commit, e), - onWheel: props => e => handleMouseMove(props.commit, e, props.canvasOrigin), + onMouseMove: (props) => (e) => + handleMouseMove(props.commit, e, props.canvasOrigin, props.zoomScale), + onMouseLeave: (props) => (e) => handleMouseLeave(props.commit, e), + onWheel: (props) => (e) => handleMouseMove(props.commit, e, props.canvasOrigin), resetHandler: () => () => resetHandler(), }; diff --git a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/index.js b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/index.js index 2500a412c0fac..41f78165a7394 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/index.js @@ -76,7 +76,7 @@ function closest(s) { // If you interact with an embeddable panel, only the header should be draggable // This function will determine if an element is an embeddable body or not -const isEmbeddableBody = element => { +const isEmbeddableBody = (element) => { const hasClosest = typeof element.closest === 'function'; if (hasClosest) { @@ -94,7 +94,7 @@ const isEmbeddableBody = element => { // Some elements in an embeddable may be portaled out of the embeddable container. // We do not want clicks on those to trigger drags, etc, in the workpad. This function // will check to make sure the clicked item is actually in the container -const isInWorkpad = element => { +const isInWorkpad = (element) => { const hasClosest = typeof element.closest === 'function'; const workpadContainerSelector = '.canvasWorkpadContainer'; @@ -114,7 +114,7 @@ const componentLayoutState = ({ width, }) => { const shapes = shapesForNodes(elements); - const selectedShapes = selectedToplevelNodes.filter(e => shapes.find(s => s.id === e)); + const selectedShapes = selectedToplevelNodes.filter((e) => shapes.find((s) => s.id === e)); const newState = { primaryUpdate: null, currentScene: { @@ -145,13 +145,13 @@ const mapStateToProps = (state, ownProps) => { const selectedToplevelNodes = state.transient.selectedToplevelNodes; const nodes = getNodes(state, ownProps.pageId); const selectedPrimaryShapeObjects = selectedToplevelNodes - .map(id => nodes.find(s => s.id === id)) - .filter(shape => shape); + .map((id) => nodes.find((s) => s.id === id)) + .filter((shape) => shape); const selectedPersistentPrimaryNodes = flatten( - selectedPrimaryShapeObjects.map(shape => - nodes.find(n => n.id === shape.id) // is it a leaf or a persisted group? + selectedPrimaryShapeObjects.map((shape) => + nodes.find((n) => n.id === shape.id) // is it a leaf or a persisted group? ? [shape.id] - : nodes.filter(s => s.parent === shape.id).map(s => s.id) + : nodes.filter((s) => s.parent === shape.id).map((s) => s.id) ) ); const selectedNodeIds = flatten(selectedPersistentPrimaryNodes.map(crawlTree(nodes))); @@ -160,23 +160,25 @@ const mapStateToProps = (state, ownProps) => { isEditable: !getFullscreen(state) && isWriteable(state) && canUserWrite(state), elements: nodes, selectedToplevelNodes, - selectedNodes: selectedNodeIds.map(id => nodes.find(s => s.id === id)), + selectedNodes: selectedNodeIds.map((id) => nodes.find((s) => s.id === id)), pageStyle: getPageById(state, ownProps.pageId).style, zoomScale: getZoomScale(state), }; }; -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ dispatch, insertNodes: (selectedNodes, pageId) => dispatch(insertNodes(selectedNodes, pageId)), removeNodes: (nodeIds, pageId) => dispatch(removeElements(nodeIds, pageId)), - selectToplevelNodes: nodes => - dispatch(selectToplevelNodes(nodes.filter(e => !e.position.parent).map(e => e.id))), + selectToplevelNodes: (nodes) => + dispatch(selectToplevelNodes(nodes.filter((e) => !e.position.parent).map((e) => e.id))), elementLayer: (pageId, elementId, movement) => dispatch(elementLayer({ pageId, elementId, movement })), - setMultiplePositions: pageId => repositionedNodes => + setMultiplePositions: (pageId) => (repositionedNodes) => dispatch( - setMultiplePositions(repositionedNodes.map(node => ({ ...node, pageId, elementId: node.id }))) + setMultiplePositions( + repositionedNodes.map((node) => ({ ...node, pageId, elementId: node.id })) + ) ), }); @@ -226,8 +228,8 @@ export const InteractivePage = compose( }; }), withProps(({ aeroStore, elements }) => { - const elementLookup = new Map(elements.map(element => [element.id, element])); - const elementsToRender = aeroStore.getCurrentState().currentScene.shapes.map(shape => { + const elementLookup = new Map(elements.map((element) => [element.id, element])); + const elementsToRender = aeroStore.getCurrentState().currentScene.shapes.map((shape) => { const element = elementLookup.get(shape.id); return element ? { ...shape, width: shape.a * 2, height: shape.b * 2, filter: element.filter } @@ -240,7 +242,7 @@ export const InteractivePage = compose( })), withProps((...props) => ({ ...props, - canDragElement: element => { + canDragElement: (element) => { return !isEmbeddableBody(element) && isInWorkpad(element); const hasClosest = typeof element.closest === 'function'; diff --git a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/interactive_workpad_page.js b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/interactive_workpad_page.js index 68f47f35c6fa1..152da323e89ea 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/interactive_workpad_page.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/workpad_interactive_page/interactive_workpad_page.js @@ -71,7 +71,7 @@ export class InteractiveWorkpadPage extends PureComponent {
{ + ref={(node) => { if (!canvasOrigin && node && node.getBoundingClientRect) { saveCanvasOrigin(() => () => node.getBoundingClientRect()); } @@ -92,7 +92,7 @@ export class InteractiveWorkpadPage extends PureComponent { {shortcuts} {elements - .map(node => { + .map((node) => { if (node.type === 'annotation') { const props = { key: node.id, @@ -127,7 +127,7 @@ export class InteractiveWorkpadPage extends PureComponent { return ; } }) - .filter(element => !!element)} + .filter((element) => !!element)}
); } diff --git a/x-pack/plugins/canvas/public/components/workpad_page/workpad_static_page/static_workpad_page.js b/x-pack/plugins/canvas/public/components/workpad_page/workpad_static_page/static_workpad_page.js index 9e8962755e00b..aa620b812f76d 100644 --- a/x-pack/plugins/canvas/public/components/workpad_page/workpad_static_page/static_workpad_page.js +++ b/x-pack/plugins/canvas/public/components/workpad_page/workpad_static_page/static_workpad_page.js @@ -25,8 +25,8 @@ export class StaticWorkpadPage extends PureComponent { style={{ ...pageStyle, ...animationStyle, height, width }} > {elements - .filter(node => !isGroupId(node.id)) - .map(element => ( + .filter((node) => !isGroupId(node.id)) + .map((element) => ( ))}
diff --git a/x-pack/plugins/canvas/public/components/workpad_templates/index.js b/x-pack/plugins/canvas/public/components/workpad_templates/index.js index a17b77b74e499..73bcf017475b6 100644 --- a/x-pack/plugins/canvas/public/components/workpad_templates/index.js +++ b/x-pack/plugins/canvas/public/components/workpad_templates/index.js @@ -22,7 +22,7 @@ export const WorkpadTemplates = compose( withKibana, withHandlers(({ kibana }) => ({ // Clone workpad given an id - cloneWorkpad: props => workpad => { + cloneWorkpad: (props) => (workpad) => { workpad.id = getId('workpad'); workpad.name = `My Canvas Workpad - ${workpad.name}`; // Remove unneeded fields @@ -32,7 +32,7 @@ export const WorkpadTemplates = compose( return workpadService .create(workpad) .then(() => props.router.navigateTo('loadWorkpad', { id: workpad.id, page: 1 })) - .catch(err => + .catch((err) => kibana.services.canvas.notify.error(err, { title: `Couldn't clone workpad template` }) ); }, diff --git a/x-pack/plugins/canvas/public/components/workpad_templates/workpad_templates.js b/x-pack/plugins/canvas/public/components/workpad_templates/workpad_templates.js index a9a157f5675f8..80ee5a0396704 100644 --- a/x-pack/plugins/canvas/public/components/workpad_templates/workpad_templates.js +++ b/x-pack/plugins/canvas/public/components/workpad_templates/workpad_templates.js @@ -51,7 +51,7 @@ export class WorkpadTemplates extends React.PureComponent { onSearch = ({ queryText }) => this.setState(extractSearch(queryText)); - cloneTemplate = template => this.props.cloneWorkpad(template).then(() => this.props.onClose()); + cloneTemplate = (template) => this.props.cloneWorkpad(template).then(() => this.props.onClose()); renderWorkpadTable = ({ rows, pageNumber, totalPages, setPage }) => { const { sortField, sortDirection } = this.state; @@ -90,7 +90,7 @@ export class WorkpadTemplates extends React.PureComponent { sortable: false, dataType: 'string', width: '30%', - render: tags => , + render: (tags) => , }, ]; @@ -148,7 +148,7 @@ export class WorkpadTemplates extends React.PureComponent { const filteredTemplates = sortedTemplates.filter(({ name = '', help = '', tags = [] }) => { const tagMatch = filterTags.length - ? filterTags.every(filterTag => tags.indexOf(filterTag) > -1) + ? filterTags.every((filterTag) => tags.indexOf(filterTag) > -1) : true; const lowercaseSearch = searchTerm.toLowerCase(); @@ -162,7 +162,7 @@ export class WorkpadTemplates extends React.PureComponent { return ( - {pagination => ( + {(pagination) => ( {this.renderSearch()} diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/extended_template.examples.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/extended_template.examples.tsx index 51a1608df67ae..5fdc88ed62406 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/extended_template.examples.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/extended_template.examples.tsx @@ -27,7 +27,7 @@ const defaultValues: Arguments = { class Interactive extends React.Component<{}, Arguments> { public state = defaultValues; - _getArgValue: (arg: T) => Arguments[T] = arg => { + _getArgValue: (arg: T) => Arguments[T] = (arg) => { return this.state[arg]; }; @@ -50,18 +50,18 @@ class Interactive extends React.Component<{}, Arguments> { } } -const getArgValue: (arg: T) => Arguments[T] = arg => { +const getArgValue: (arg: T) => Arguments[T] = (arg) => { return defaultValues[arg]; }; storiesOf('arguments/ContainerStyle', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('extended', () => ); storiesOf('arguments/ContainerStyle/components', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('appearance form', () => ( diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/simple_template.examples.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/simple_template.examples.tsx index 71d95603cfebd..4ef17fbe87616 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/simple_template.examples.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/__examples__/simple_template.examples.tsx @@ -19,7 +19,7 @@ const defaultValues: Arguments = { class Interactive extends React.Component<{}, Arguments> { public state = defaultValues; - _getArgValue: (arg: T) => Arguments[T] = arg => { + _getArgValue: (arg: T) => Arguments[T] = (arg) => { return this.state[arg]; }; @@ -39,18 +39,18 @@ class Interactive extends React.Component<{}, Arguments> { } } -const getArgValue: (arg: T) => Arguments[T] = arg => { +const getArgValue: (arg: T) => Arguments[T] = (arg) => { return defaultValues[arg]; }; storiesOf('arguments/ContainerStyle', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('simple', () => ); storiesOf('arguments/ContainerStyle/components', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('simple template', () => ( diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/border_form.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/border_form.tsx index 929eaeb02f3c7..c833ed3e99aa1 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/border_form.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/border_form.tsx @@ -79,7 +79,7 @@ export const BorderForm: FunctionComponent = ({ namedChange('borderWidth')(Number(e.target.value))} + onChange={(e) => namedChange('borderWidth')(Number(e.target.value))} />
@@ -89,7 +89,7 @@ export const BorderForm: FunctionComponent = ({ ({ + options={Object.values(BorderStyle).map((style) => ({ value: style, inputDisplay:
, }))} @@ -103,7 +103,7 @@ export const BorderForm: FunctionComponent = ({ namedChange('borderRadius')(e.target.value)} + onChange={(e) => namedChange('borderRadius')(e.target.value)} /> diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/simple_template.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/simple_template.tsx index cb7a5d606c7d9..3e002ead22d4b 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/simple_template.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/container_style/simple_template.tsx @@ -27,7 +27,7 @@ export const SimpleTemplate: FunctionComponent = ({ getArgValue, setArgVa
setArgValue('backgroundColor', color)} + onChange={(color) => setArgValue('backgroundColor', color)} colors={workpad.colors} anchorPosition="leftCenter" ariaLabel={strings.getDisplayName()} diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/font.js b/x-pack/plugins/canvas/public/expression_types/arg_types/font.js index 46a97f7c15d74..3e88d60b40d5f 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/font.js +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/font.js @@ -14,7 +14,7 @@ import { ArgTypesStrings } from '../../../i18n'; const { Font: strings } = ArgTypesStrings; -export const FontArgInput = props => { +export const FontArgInput = (props) => { const { onValueChange, argValue, workpad } = props; const chain = get(argValue, 'chain.0', {}); const chainArgs = get(chain, 'arguments', {}); @@ -27,7 +27,7 @@ export const FontArgInput = props => { const newValue = set( argValue, ['chain', 0, 'arguments'], - mapValues(newSpec, v => [v]) + mapValues(newSpec, (v) => [v]) ); return onValueChange(newValue); } diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/extended_template.examples.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/extended_template.examples.tsx index 7e00bd4f33a8a..4a300b3de8923 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/extended_template.examples.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/extended_template.examples.tsx @@ -44,7 +44,7 @@ class Interactive extends React.Component<{}, { argValue: ExpressionAstExpressio return ( { + onValueChange={(argValue) => { action('onValueChange')(argValue); this.setState({ argValue }); }} @@ -61,14 +61,14 @@ class Interactive extends React.Component<{}, { argValue: ExpressionAstExpressio } storiesOf('arguments/SeriesStyle', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .addDecorator(withKnobs) .add('extended', () => ); storiesOf('arguments/SeriesStyle/components', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('extended: defaults', () => ( diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/simple_template.examples.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/simple_template.examples.tsx index 037b15d5c51e9..f9b175e84ec8e 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/simple_template.examples.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/__examples__/simple_template.examples.tsx @@ -35,7 +35,7 @@ class Interactive extends React.Component<{}, { argValue: ExpressionAstExpressio return ( { + onValueChange={(argValue) => { action('onValueChange')(argValue); this.setState({ argValue }); }} @@ -49,13 +49,13 @@ class Interactive extends React.Component<{}, { argValue: ExpressionAstExpressio } storiesOf('arguments/SeriesStyle', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('simple', () => ); storiesOf('arguments/SeriesStyle/components', module) - .addDecorator(story => ( + .addDecorator((story) => (
{story()}
)) .add('simple: no labels', () => ( diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/extended_template.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/extended_template.tsx index 615179a3f6f68..e0fe6e60c1dab 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/extended_template.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/extended_template.tsx @@ -35,7 +35,7 @@ export interface Props { }; } -export const ExtendedTemplate: FunctionComponent = props => { +export const ExtendedTemplate: FunctionComponent = (props) => { const { typeInstance, onValueChange, labels, argValue } = props; const chain = get(argValue, 'chain.0', {}); const chainArgs = get(chain, 'arguments', {}); @@ -47,7 +47,7 @@ export const ExtendedTemplate: FunctionComponent = props => { } const fields = get(typeInstance, 'options.include', []); - const hasPropFields = fields.some(field => ['lines', 'bars', 'points'].indexOf(field) !== -1); + const hasPropFields = fields.some((field) => ['lines', 'bars', 'points'].indexOf(field) !== -1); const handleChange: (key: T, val: ChangeEvent) => void = ( argName, @@ -70,7 +70,7 @@ export const ExtendedTemplate: FunctionComponent = props => { ]; const labelOptions = [{ value: '', text: strings.getSelectSeriesOption() }]; - labels.sort().forEach(val => labelOptions.push({ value: val, text: val })); + labels.sort().forEach((val) => labelOptions.push({ value: val, text: val })); return (
@@ -81,7 +81,7 @@ export const ExtendedTemplate: FunctionComponent = props => { compressed value={selectedSeries} options={labelOptions} - onChange={ev => handleChange('label', ev)} + onChange={(ev) => handleChange('label', ev)} /> @@ -98,7 +98,7 @@ export const ExtendedTemplate: FunctionComponent = props => { value={get(chainArgs, 'lines.0', 0)} options={values} compressed - onChange={ev => handleChange('lines', ev)} + onChange={(ev) => handleChange('lines', ev)} /> @@ -110,7 +110,7 @@ export const ExtendedTemplate: FunctionComponent = props => { value={get(chainArgs, 'bars.0', 0)} options={values} compressed - onChange={ev => handleChange('bars', ev)} + onChange={(ev) => handleChange('bars', ev)} /> @@ -122,7 +122,7 @@ export const ExtendedTemplate: FunctionComponent = props => { value={get(chainArgs, 'points.0', 0)} options={values} compressed - onChange={ev => handleChange('points', ev)} + onChange={(ev) => handleChange('points', ev)} /> diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/simple_template.tsx b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/simple_template.tsx index 226122cf0b25f..eb51492155a3b 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/simple_template.tsx +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/series_style/simple_template.tsx @@ -32,7 +32,7 @@ interface Props { workpad: CanvasWorkpad; } -export const SimpleTemplate: FunctionComponent = props => { +export const SimpleTemplate: FunctionComponent = (props) => { const { typeInstance, argValue, onValueChange, labels, workpad } = props; const { name } = typeInstance; const chain = get(argValue, 'chain.0', {}); @@ -74,7 +74,7 @@ export const SimpleTemplate: FunctionComponent = props => { handleChange('color', val)} + onChange={(val) => handleChange('color', val)} value={color} ariaLabel={strings.getColorLabel()} /> diff --git a/x-pack/plugins/canvas/public/expression_types/datasource.js b/x-pack/plugins/canvas/public/expression_types/datasource.js index 0539486146136..ffcea83551914 100644 --- a/x-pack/plugins/canvas/public/expression_types/datasource.js +++ b/x-pack/plugins/canvas/public/expression_types/datasource.js @@ -41,7 +41,7 @@ class DatasourceWrapper extends React.PureComponent { render() { return ( { + render={(domNode) => { this.domNode = domNode; this.callRenderFn(); }} diff --git a/x-pack/plugins/canvas/public/expression_types/function_form.js b/x-pack/plugins/canvas/public/expression_types/function_form.js index 299b57e4854c1..7056f87bcfa05 100644 --- a/x-pack/plugins/canvas/public/expression_types/function_form.js +++ b/x-pack/plugins/canvas/public/expression_types/function_form.js @@ -80,16 +80,16 @@ export class FunctionForm extends BaseForm { const { args, argTypeDef } = data; // Don't instaniate these until render time, to give the registries a chance to populate. - const argInstances = this.args.map(argSpec => new Arg(argSpec)); + const argInstances = this.args.map((argSpec) => new Arg(argSpec)); if (!isPlainObject(args)) { throw new Error(`Form "${this.name}" expects "args" object`); } // get a mapping of arg values from the expression and from the renderable's schema - const argNames = uniq(argInstances.map(arg => arg.name).concat(Object.keys(args))); - const dataArgs = argNames.map(argName => { - const arg = argInstances.find(arg => arg.name === argName); + const argNames = uniq(argInstances.map((arg) => arg.name).concat(Object.keys(args))); + const dataArgs = argNames.map((argName) => { + const arg = argInstances.find((arg) => arg.name === argName); // if arg is not multi, only preserve the last value found // otherwise, leave the value alone (including if the arg is not defined) @@ -104,10 +104,10 @@ export class FunctionForm extends BaseForm { try { // allow a hook to override the data args - const resolvedDataArgs = dataArgs.map(d => ({ ...d, ...this.resolveArg(d, props) })); + const resolvedDataArgs = dataArgs.map((d) => ({ ...d, ...this.resolveArg(d, props) })); - const argumentForms = compact(resolvedDataArgs.map(d => this.renderArg(props, d))); - const addableArgs = compact(resolvedDataArgs.map(d => this.getAddableArg(props, d))); + const argumentForms = compact(resolvedDataArgs.map((d) => this.renderArg(props, d))); + const addableArgs = compact(resolvedDataArgs.map((d) => this.getAddableArg(props, d))); if (!addableArgs.length && !argumentForms.length) { return null; diff --git a/x-pack/plugins/canvas/public/expression_types/model.js b/x-pack/plugins/canvas/public/expression_types/model.js index 9ae71dfc0ac18..95c8b27a71048 100644 --- a/x-pack/plugins/canvas/public/expression_types/model.js +++ b/x-pack/plugins/canvas/public/expression_types/model.js @@ -48,7 +48,7 @@ export class Model extends FunctionForm { // if argument is missing from modelArgs, mark it as skipped const argName = get(dataArg, 'arg.name'); - const modelArg = modelArgs.find(modelArg => { + const modelArg = modelArgs.find((modelArg) => { if (Array.isArray(modelArg)) { return modelArg[0] === argName; } diff --git a/x-pack/plugins/canvas/public/functions/__tests__/asset.js b/x-pack/plugins/canvas/public/functions/__tests__/asset.js index 208af754e9105..c21faf9a2e227 100644 --- a/x-pack/plugins/canvas/public/functions/__tests__/asset.js +++ b/x-pack/plugins/canvas/public/functions/__tests__/asset.js @@ -17,7 +17,7 @@ describe.skip('asset', () => { const throwsErr = () => { return fn(null, { id: 'boo' }); }; - expect(throwsErr).to.throwException(err => { + expect(throwsErr).to.throwException((err) => { expect(err.message).to.be('Could not get the asset by ID: boo'); }); }); diff --git a/x-pack/plugins/canvas/public/functions/filters.ts b/x-pack/plugins/canvas/public/functions/filters.ts index 16d0bb0fff708..78cd742b44b26 100644 --- a/x-pack/plugins/canvas/public/functions/filters.ts +++ b/x-pack/plugins/canvas/public/functions/filters.ts @@ -37,7 +37,7 @@ function getFiltersByGroup(allFilters: string[], groups?: string[], ungrouped = return allFilters.filter((filter: string) => { const ast = fromExpression(filter); const expGroups = get(ast, 'chain[0].arguments.filterGroup', []); - return expGroups.length > 0 && expGroups.every(expGroup => groups.includes(expGroup)); + return expGroups.length > 0 && expGroups.every((expGroup) => groups.includes(expGroup)); }); } diff --git a/x-pack/plugins/canvas/public/functions/timelion.ts b/x-pack/plugins/canvas/public/functions/timelion.ts index 7e38e6e710b81..abb294d9cc110 100644 --- a/x-pack/plugins/canvas/public/functions/timelion.ts +++ b/x-pack/plugins/canvas/public/functions/timelion.ts @@ -94,7 +94,7 @@ export function timelionFunctionFactory(initialize: InitializeArguments): () => fn: (input, args): Promise => { // Timelion requires a time range. Use the time range from the timefilter element in the // workpad, if it exists. Otherwise fall back on the function args. - const timeFilter = input.and.find(and => and.filterType === 'time'); + const timeFilter = input.and.find((and) => and.filterType === 'time'); const range = timeFilter ? { min: timeFilter.from, max: timeFilter.to } : parseDateMath({ from: args.from, to: args.to }, args.timezone, initialize.timefilter); @@ -121,11 +121,15 @@ export function timelionFunctionFactory(initialize: InitializeArguments): () => method: 'POST', responseType: 'json', data: body, - }).then(resp => { + }).then((resp) => { const seriesList = resp.data.sheet[0].list; const rows = flatten( seriesList.map((series: { data: any[]; label: string }) => - series.data.map(row => ({ '@timestamp': row[0], value: row[1], label: series.label })) + series.data.map((row) => ({ + '@timestamp': row[0], + value: row[1], + label: series.label, + })) ) ) as DatatableRow[]; diff --git a/x-pack/plugins/canvas/public/lib/__tests__/history_provider.js b/x-pack/plugins/canvas/public/lib/__tests__/history_provider.js index 82cb468be3c54..99d8305768240 100644 --- a/x-pack/plugins/canvas/public/lib/__tests__/history_provider.js +++ b/x-pack/plugins/canvas/public/lib/__tests__/history_provider.js @@ -130,16 +130,16 @@ describe.skip('historyProvider', () => { teardownFn(); }); - it('should call handler on state change', done => { - createOnceHandler(history, done, loc => { + it('should call handler on state change', (done) => { + createOnceHandler(history, done, (loc) => { expect(loc).to.be.a('object'); }); history.push({}); }); - it('should pass location object to handler', done => { - createOnceHandler(history, done, location => { + it('should pass location object to handler', (done) => { + createOnceHandler(history, done, (location) => { expect(location.pathname).to.be.a('string'); expect(location.hash).to.be.a('string'); expect(location.state).to.be.an('object'); @@ -149,7 +149,7 @@ describe.skip('historyProvider', () => { history.push(state); }); - it('should pass decompressed state to handler', done => { + it('should pass decompressed state to handler', (done) => { createOnceHandler(history, done, ({ state: curState }) => { expect(curState).to.eql(state); }); @@ -157,7 +157,7 @@ describe.skip('historyProvider', () => { history.push(state); }); - it('should pass in the previous location object to handler', done => { + it('should pass in the previous location object to handler', (done) => { createOnceHandler(history, done, (location, prevLocation) => { expect(prevLocation.pathname).to.be.a('string'); expect(prevLocation.hash).to.be.a('string'); diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/__fixtures__/typescript/typespec_tests.ts b/x-pack/plugins/canvas/public/lib/aeroelastic/__fixtures__/typescript/typespec_tests.ts index 38d5233b662cd..cb46a3d6be402 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/__fixtures__/typescript/typespec_tests.ts +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/__fixtures__/typescript/typespec_tests.ts @@ -185,7 +185,7 @@ import { // typings:expect-error plain = undefined; // it's undefined // typings:expect-error - plain = a => a; // it's a function + plain = (a) => a; // it's a function // typings:expect-error plain = [new Date()]; // it's a time // typings:expect-error diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/common.js b/x-pack/plugins/canvas/public/lib/aeroelastic/common.js index 97f0e04ea6eb8..357c80488a08b 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/common.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/common.js @@ -8,10 +8,10 @@ import { select } from './select'; // serves as reminder that we start with the state // todo remove it as we add TS annotations (State) -const state = d => d; +const state = (d) => d; -const getScene = state => state.currentScene; +const getScene = (state) => state.currentScene; export const scene = select(getScene)(state); -const getPrimaryUpdate = state => state.primaryUpdate; +const getPrimaryUpdate = (state) => state.primaryUpdate; export const primaryUpdate = select(getPrimaryUpdate)(state); diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js b/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js index 33cd95875302a..9b4ab8470da87 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/functional.js @@ -12,7 +12,7 @@ * @param {*[][]} arrays * @returns *[] */ -export const flatten = arrays => [].concat(...arrays); +export const flatten = (arrays) => [].concat(...arrays); /** * identity @@ -20,7 +20,7 @@ export const flatten = arrays => [].concat(...arrays); * @param d * @returns d */ -export const identity = d => d; +export const identity = (d) => d; /** * map @@ -32,7 +32,7 @@ export const identity = d => d; * @param {Function} fun * @returns {function(*): *} */ -export const map = fun => array => array.map(value => fun(value)); +export const map = (fun) => (array) => array.map((value) => fun(value)); /** * disjunctiveUnion @@ -44,8 +44,8 @@ export const map = fun => array => array.map(value => fun(value)); */ export const disjunctiveUnion = (keyFun, set1, set2) => set1 - .filter(s1 => !set2.find(s2 => keyFun(s2) === keyFun(s1))) - .concat(set2.filter(s2 => !set1.find(s1 => keyFun(s1) === keyFun(s2)))); + .filter((s1) => !set2.find((s2) => keyFun(s2) === keyFun(s1))) + .concat(set2.filter((s2) => !set1.find((s1) => keyFun(s1) === keyFun(s2)))); /** * @@ -70,16 +70,16 @@ export const shallowEqual = (a, b) => { return true; }; -export const not = fun => (...args) => !fun(...args); +export const not = (fun) => (...args) => !fun(...args); export const removeDuplicates = (idFun, a) => - a.filter((d, i) => a.findIndex(s => idFun(s) === idFun(d)) === i); + a.filter((d, i) => a.findIndex((s) => idFun(s) === idFun(d)) === i); -export const arrayToMap = a => Object.assign({}, ...a.map(d => ({ [d]: true }))); +export const arrayToMap = (a) => Object.assign({}, ...a.map((d) => ({ [d]: true }))); export const subMultitree = (pk, fk, elements, inputRoots) => { - const getSubgraphs = roots => { - const children = flatten(roots.map(r => elements.filter(e => fk(e) === pk(r)))); + const getSubgraphs = (roots) => { + const children = flatten(roots.map((r) => elements.filter((e) => fk(e) === pk(r)))); if (children.length) { return [...roots, ...getSubgraphs(children, elements)]; } else { diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/geometry.js b/x-pack/plugins/canvas/public/lib/aeroelastic/geometry.js index de4510e385974..6c0ebc00c7899 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/geometry.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/geometry.js @@ -26,7 +26,7 @@ import { dotProduct } from './matrix2d'; const cornerScreenPositions = (transformMatrix, a, b) => // for unknown perf gain, this could be cached per shape - [TOP_LEFT, TOP_RIGHT, BOTTOM_RIGHT, BOTTOM_LEFT].map(corner => + [TOP_LEFT, TOP_RIGHT, BOTTOM_RIGHT, BOTTOM_LEFT].map((corner) => mvMultiply(transformMatrix, componentProduct(corner, [a, b, 0, 1])) ); @@ -127,9 +127,9 @@ const shapesAtPoint = (shapes, x, y) => // viewer. But that's not the case. So we maximize the Z value to tell what's on top. export const shapesAt = (shapes, { x, y }) => shapesAtPoint(shapes, x, y) - .filter(shape => shape.inside) + .filter((shape) => shape.inside) .sort((shape1, shape2) => shape2.z - shape1.z || shape2.index - shape1.index) // stable sort: DOM insertion order!!! - .map(shape => shape.shape); // decreasing order, ie. from front (closest to viewer) to back + .map((shape) => shape.shape); // decreasing order, ie. from front (closest to viewer) to back const getExtremum = (transformMatrix, a, b) => normalize(mvMultiply(transformMatrix, [a, b, 0, 1])); diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/gestures.js b/x-pack/plugins/canvas/public/lib/aeroelastic/gestures.js index ba78db9dc670a..ede7affc850b6 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/gestures.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/gestures.js @@ -25,20 +25,20 @@ const appleKeyboard = Boolean( * (we could turn gesture.js into a factory, with this state root - primaryUpdate - being passed...) */ -const primaryUpdate = state => state.primaryUpdate; +const primaryUpdate = (state) => state.primaryUpdate; -const gestureStatePrev = select(scene => scene.gestureState)(scene); +const gestureStatePrev = select((scene) => scene.gestureState)(scene); /** * Gestures - derived selectors for transient state */ // dispatch the various types of actions -const rawCursorPosition = select(action => +const rawCursorPosition = select((action) => action.type === 'cursorPosition' ? action.payload : null )(primaryUpdate); -const mouseButtonEvent = select(action => (action.type === 'mouseEvent' ? action.payload : null))( +const mouseButtonEvent = select((action) => (action.type === 'mouseEvent' ? action.payload : null))( primaryUpdate ); @@ -46,16 +46,16 @@ const keyFromMouse = select(({ type, payload: { altKey, metaKey, shiftKey, ctrlK type === 'cursorPosition' || type === 'mouseEvent' ? { altKey, metaKey, shiftKey, ctrlKey } : {} )(primaryUpdate); -export const metaHeld = select(appleKeyboard ? e => e.metaKey : e => e.altKey)(keyFromMouse); -export const optionHeld = select(appleKeyboard ? e => e.altKey : e => e.ctrlKey)(keyFromMouse); -export const shiftHeld = select(e => e.shiftKey)(keyFromMouse); +export const metaHeld = select(appleKeyboard ? (e) => e.metaKey : (e) => e.altKey)(keyFromMouse); +export const optionHeld = select(appleKeyboard ? (e) => e.altKey : (e) => e.ctrlKey)(keyFromMouse); +export const shiftHeld = select((e) => e.shiftKey)(keyFromMouse); export const cursorPosition = select(({ cursor }, position) => position || cursor)( gestureStatePrev, rawCursorPosition ); -export const mouseButton = select(next => { +export const mouseButton = select((next) => { if (!next) { return { down: false, up: false, uid: null }; } @@ -74,7 +74,7 @@ export const mouseIsDown = select(({ mouseIsDown }, next) => )(gestureStatePrev, mouseButtonEvent); export const gestureEnd = select( - action => + (action) => action && (action.type === 'actionEvent' || (action.type === 'mouseEvent' && action.payload.event === 'mouseUp')) @@ -128,9 +128,9 @@ const mouseButtonState = select( } )(gestureStatePrev, mouseIsDown, cursorPosition); -export const mouseDowned = select(state => state.buttonState === 'downed')(mouseButtonState); +export const mouseDowned = select((state) => state.buttonState === 'downed')(mouseButtonState); -export const dragging = select(state => state.buttonState === 'dragging')(mouseButtonState); +export const dragging = select((state) => state.buttonState === 'dragging')(mouseButtonState); export const dragVector = select(({ buttonState, downX, downY }, { x, y }) => ({ down: buttonState !== 'up', @@ -140,7 +140,7 @@ export const dragVector = select(({ buttonState, downX, downY }, { x, y }) => ({ y1: y, }))(mouseButtonState, cursorPosition); -export const actionEvent = select(action => +export const actionEvent = select((action) => action.type === 'actionEvent' ? action.payload : null )(primaryUpdate); diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/layout_functions.js b/x-pack/plugins/canvas/public/lib/aeroelastic/layout_functions.js index d3da1b5553958..c2c6f77fb167c 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/layout_functions.js +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/layout_functions.js @@ -138,7 +138,7 @@ const shapeAABB = (shape, prevOuter) => return extend(prevInner, cornerPoint, cornerPoint); }, prevOuter); -const shapesAABB = shapes => +const shapesAABB = (shapes) => shapes.reduce( (prevOuter, shape) => extend(prevOuter, ...shapeAABB(shape, prevOuter)), identityAABB() @@ -167,7 +167,7 @@ export const draggingShape = ({ draggedShape, shapes }, hoveredShape, down, mous // the currently dragged shape is considered in-focus; if no dragging is going on, then the hovered shape export const getFocusedShape = (draggedShape, hoveredShape) => draggedShape || hoveredShape; // focusedShapes has updated position etc. information while focusedShape may have stale position -export const getAlterSnapGesture = metaHeld => (metaHeld ? ['relax'] : []); +export const getAlterSnapGesture = (metaHeld) => (metaHeld ? ['relax'] : []); const initialTransformTuple = { deltaX: 0, @@ -196,38 +196,38 @@ export const getMouseTransformState = (prev, dragging, { x0, y0, x1, y1 }) => { } }; -export const getMouseTransformGesture = tuple => +export const getMouseTransformGesture = (tuple) => [tuple] - .filter(tpl => tpl.transform) + .filter((tpl) => tpl.transform) .map(({ transform, cumulativeTransform }) => ({ transform, cumulativeTransform })); -export const getLocalTransformMatrix = shapes => shape => { +export const getLocalTransformMatrix = (shapes) => (shape) => { if (!shape.parent) { return shape.transformMatrix; } return multiply( - invert(shapes.find(s => s.id === shape.parent).transformMatrix), + invert(shapes.find((s) => s.id === shape.parent).transformMatrix), shape.transformMatrix ); }; export const getSelectedShapeObjects = (scene, shapes) => - (scene.selectedShapes || []).map(s => shapes.find(ss => ss.id === s)); + (scene.selectedShapes || []).map((s) => shapes.find((ss) => ss.id === s)); -const contentShape = allShapes => shape => +const contentShape = (allShapes) => (shape) => shape.type === 'annotation' - ? contentShape(allShapes)(allShapes.find(s => s.id === shape.parent)) + ? contentShape(allShapes)(allShapes.find((s) => s.id === shape.parent)) : shape; const getContentShapes = (allShapes, shapes) => { // fixme no need to export, why doesn't linter or highlighter complain? - const idMap = arrayToMap(allShapes.map(shape => shape.id)); - return shapes.filter(shape => idMap[shape.id]).map(contentShape(allShapes)); + const idMap = arrayToMap(allShapes.map((shape) => shape.id)); + return shapes.filter((shape) => idMap[shape.id]).map(contentShape(allShapes)); }; -const primaryShape = shape => (shape.type === 'annotation' ? shape.parent : shape.id); +const primaryShape = (shape) => (shape.type === 'annotation' ? shape.parent : shape.id); -const rotationManipulation = config => ({ +const rotationManipulation = (config) => ({ shape, directShape, cursorPosition: { x, y }, @@ -265,7 +265,7 @@ const minimumSize = (min, { a, b, baseAB }, vector) => { ]; }; -const centeredResizeManipulation = config => ({ gesture, shape, directShape }) => { +const centeredResizeManipulation = (config) => ({ gesture, shape, directShape }) => { const transform = gesture.cumulativeTransform; // scaling such that the center remains in place (ie. the other side of the shape can grow/shrink) if (!shape || !directShape) { @@ -293,7 +293,7 @@ const centeredResizeManipulation = config => ({ gesture, shape, directShape }) = }; }; -const asymmetricResizeManipulation = config => ({ gesture, shape, directShape }) => { +const asymmetricResizeManipulation = (config) => ({ gesture, shape, directShape }) => { const transform = gesture.cumulativeTransform; // scaling such that the center remains in place (ie. the other side of the shape can grow/shrink) if (!shape || !directShape) { @@ -333,7 +333,7 @@ const asymmetricResizeManipulation = config => ({ gesture, shape, directShape }) const directShapeTranslateManipulation = (cumulativeTransforms, directShapes) => { const shapes = directShapes - .map(shape => shape.type !== 'annotation' && shape.id) + .map((shape) => shape.type !== 'annotation' && shape.id) .filter(identity); return [{ cumulativeTransforms, shapes }]; }; @@ -347,13 +347,13 @@ const rotationAnnotationManipulation = ( alterSnapGesture ) => { const shapeIds = directShapes.map( - shape => + (shape) => shape.type === 'annotation' && shape.subtype === config.rotationHandleName && shape.parent ); - const shapes = shapeIds.map(id => id && allShapes.find(shape => shape.id === id)); + const shapes = shapeIds.map((id) => id && allShapes.find((shape) => shape.id === id)); const tuples = flatten( shapes.map((shape, i) => - directTransforms.map(transform => ({ + directTransforms.map((transform) => ({ transform, shape, directShape: directShapes[i], @@ -373,19 +373,19 @@ const resizeAnnotationManipulation = ( manipulator ) => { const shapeIds = directShapes.map( - shape => + (shape) => shape.type === 'annotation' && shape.subtype === config.resizeHandleName && shape.parent ); - const shapes = shapeIds.map(id => id && allShapes.find(shape => shape.id === id)); + const shapes = shapeIds.map((id) => id && allShapes.find((shape) => shape.id === id)); const tuples = flatten( shapes.map((shape, i) => - transformGestures.map(gesture => ({ gesture, shape, directShape: directShapes[i] })) + transformGestures.map((gesture) => ({ gesture, shape, directShape: directShapes[i] })) ) ); return tuples.map(manipulator); }; -const fromScreen = currentTransform => transform => { +const fromScreen = (currentTransform) => (transform) => { const isTranslate = transform[12] !== 0 || transform[13] !== 0; if (isTranslate) { const composite = compositeComponent(currentTransform); @@ -397,7 +397,7 @@ const fromScreen = currentTransform => transform => { } }; -const horizontalToIndex = horizontal => (horizontal ? 0 : 1); +const horizontalToIndex = (horizontal) => (horizontal ? 0 : 1); const anchorAABB = (aabb, anchorDirection, horizontal) => { const dimension = horizontalToIndex(horizontal); @@ -421,13 +421,13 @@ export const getAlignDistributeTransformIntents = ( } const group = selectedShapes[0]; - const children = shapes.filter(s => s.parent === group.id && s.type !== 'annotation'); + const children = shapes.filter((s) => s.parent === group.id && s.type !== 'annotation'); if (alignAction && children.length > 1) { const { controlledAnchor, horizontal } = alignAction; const groupBoundingBox = shapeAABB(group, identityAABB()); const groupAnchor = anchorAABB(groupBoundingBox, controlledAnchor, horizontal); - const results = children.map(c => { + const results = children.map((c) => { const childBoundingBox = shapeAABB(c, identityAABB()); const childAnchor = anchorAABB(childBoundingBox, controlledAnchor, horizontal); const delta = groupAnchor - childAnchor; @@ -443,16 +443,16 @@ export const getAlignDistributeTransformIntents = ( const groupBoundingBox = shapeAABB(group, identityAABB()); const groupAnchor = anchorAABB(groupBoundingBox, -1, horizontal); const dimension = horizontalToIndex(horizontal); - const childrenBoxes2D = children.map(c => shapeAABB(c, identityAABB())); - const childrenAnchors = childrenBoxes2D.map(childBoundingBox => + const childrenBoxes2D = children.map((c) => shapeAABB(c, identityAABB())); + const childrenAnchors = childrenBoxes2D.map((childBoundingBox) => anchorAABB(childBoundingBox, -1, horizontal) ); - const childrenBoxes1D = childrenBoxes2D.map(box2D => [ + const childrenBoxes1D = childrenBoxes2D.map((box2D) => [ box2D[0][dimension], box2D[1][dimension], ]); - const childrenCenters = childrenBoxes1D.map(box1D => (box1D[1] + box1D[0]) / 2); - const childrenSizes = childrenBoxes1D.map(box1D => box1D[1] - box1D[0]); + const childrenCenters = childrenBoxes1D.map((box1D) => (box1D[1] + box1D[0]) / 2); + const childrenSizes = childrenBoxes1D.map((box1D) => box1D[1] - box1D[0]); const totalChildrenSize = childrenSizes.reduce((a, b) => a + b, 0); const groupSize = horizontal ? 2 * A : 2 * B; const totalFreeSpace = groupSize - totalChildrenSize; @@ -488,14 +488,14 @@ export const getAlignDistributeTransformIntents = ( return []; }; -const shapeApplyLocalTransforms = intents => shape => { +const shapeApplyLocalTransforms = (intents) => (shape) => { const transformIntents = flatten( intents .map( - intent => + (intent) => intent.transforms && intent.transforms.length && - intent.shapes.find(id => id === shape.id) && + intent.shapes.find((id) => id === shape.id) && intent.transforms.map(fromScreen(shape.localTransformMatrix)) ) .filter(identity) @@ -503,10 +503,10 @@ const shapeApplyLocalTransforms = intents => shape => { const sizeIntents = flatten( intents .map( - intent => + (intent) => intent.sizes && intent.sizes.length && - intent.shapes.find(id => id === shape.id) && + intent.shapes.find((id) => id === shape.id) && intent.sizes ) .filter(identity) @@ -514,10 +514,10 @@ const shapeApplyLocalTransforms = intents => shape => { const cumulativeTransformIntents = flatten( intents .map( - intent => + (intent) => intent.cumulativeTransforms && intent.cumulativeTransforms.length && - intent.shapes.find(id => id === shape.id) && + intent.shapes.find((id) => id === shape.id) && intent.cumulativeTransforms.map(fromScreen(shape.localTransformMatrix)) ) .filter(identity) @@ -525,10 +525,10 @@ const shapeApplyLocalTransforms = intents => shape => { const cumulativeSizeIntents = flatten( intents .map( - intent => + (intent) => intent.cumulativeSizes && intent.cumulativeSizes.length && - intent.shapes.find(id => id === shape.id) && + intent.shapes.find((id) => id === shape.id) && intent.cumulativeSizes ) .filter(identity) @@ -581,7 +581,7 @@ const getUpstreamTransforms = (shapes, shape) => shape.parent ? getUpstreamTransforms( shapes, - shapes.find(s => s.id === shape.parent) + shapes.find((s) => s.id === shape.parent) ).concat([shape.localTransformMatrix]) : [shape.localTransformMatrix]; @@ -589,19 +589,19 @@ const getUpstreams = (shapes, shape) => shape.parent ? getUpstreams( shapes, - shapes.find(s => s.id === shape.parent) + shapes.find((s) => s.id === shape.parent) ).concat([shape]) : [shape]; -const snappedA = shape => shape.a + (shape.snapResizeVector ? shape.snapResizeVector[0] : 0); -const snappedB = shape => shape.b + (shape.snapResizeVector ? shape.snapResizeVector[1] : 0); +const snappedA = (shape) => shape.a + (shape.snapResizeVector ? shape.snapResizeVector[0] : 0); +const snappedB = (shape) => shape.b + (shape.snapResizeVector ? shape.snapResizeVector[1] : 0); const cascadeUnsnappedTransforms = (shapes, shape) => { if (!shape.parent) { return shape.localTransformMatrix; } // boost for common case of toplevel shape const upstreams = getUpstreams(shapes, shape); - const upstreamTransforms = upstreams.map(s => { + const upstreamTransforms = upstreams.map((s) => { return s.localTransformMatrix; }); const cascadedTransforms = reduceTransforms(upstreamTransforms); @@ -609,7 +609,7 @@ const cascadeUnsnappedTransforms = (shapes, shape) => { }; const cascadeTransforms = (shapes, shape) => { - const cascade = s => + const cascade = (s) => s.snapDeltaMatrix ? multiply(s.localTransformMatrix, s.snapDeltaMatrix) : s.localTransformMatrix; @@ -622,7 +622,7 @@ const cascadeTransforms = (shapes, shape) => { return cascadedTransforms; }; -const shapeCascadeProperties = shapes => shape => { +const shapeCascadeProperties = (shapes) => (shape) => { return { ...shape, transformMatrix: cascadeTransforms(shapes, shape), @@ -631,7 +631,7 @@ const shapeCascadeProperties = shapes => shape => { }; }; -export const cascadeProperties = shapes => shapes.map(shapeCascadeProperties(shapes)); +export const cascadeProperties = (shapes) => shapes.map(shapeCascadeProperties(shapes)); const alignmentGuides = (config, shapes, guidedShapes, draggedShape) => { const result = {}; @@ -747,8 +747,8 @@ const alignmentGuides = (config, shapes, guidedShapes, draggedShape) => { return Object.values(result); }; -const isHorizontal = constraint => constraint.dimension === 'horizontal'; -const isVertical = constraint => constraint.dimension === 'vertical'; +const isHorizontal = (constraint) => constraint.dimension === 'horizontal'; +const isVertical = (constraint) => constraint.dimension === 'vertical'; const closestConstraint = (prev = { distance: Infinity }, next) => next.distance < prev.distance ? { constraint: next, distance: next.distance } : prev; @@ -760,7 +760,7 @@ const directionalConstraint = (constraints, filterFun) => { }; const rotationAnnotation = (config, shapes, selectedShapes, shape, i) => { - const foundShape = shapes.find(s => shape.id === s.id); + const foundShape = shapes.find((s) => shape.id === s.id); if (!foundShape) { return false; } @@ -770,7 +770,7 @@ const rotationAnnotation = (config, shapes, selectedShapes, shape, i) => { config, shapes, selectedShapes, - shapes.find(s => foundShape.parent === s.id), + shapes.find((s) => foundShape.parent === s.id), i ); } @@ -857,11 +857,11 @@ const resizeEdgeAnnotations = (config, parent, a, b) => ([[x0, y0], [x1, y1]]) = }; }; -const groupedShape = properShape => shape => shape.parent === properShape.id; +const groupedShape = (properShape) => (shape) => shape.parent === properShape.id; const magic = (config, shape, shapes) => { const epsilon = config.rotationEpsilon; const integralOf = Math.PI * 2; - const isIntegerMultiple = s => { + const isIntegerMultiple = (s) => { const zRotation = matrixToAngle(s.localTransformMatrix); const ratio = zRotation / integralOf; return Math.abs(Math.round(ratio) - ratio) < epsilon; @@ -879,11 +879,11 @@ const magic = (config, shape, shapes) => { }; function resizeAnnotation(config, shapes, selectedShapes, shape) { - const foundShape = shapes.find(s => shape.id === s.id); + const foundShape = shapes.find((s) => shape.id === s.id); const properShape = foundShape && (foundShape.subtype === config.resizeHandleName - ? shapes.find(s => shape.parent === s.id) + ? shapes.find((s) => shape.parent === s.id) : foundShape); if (!foundShape) { return []; @@ -894,7 +894,7 @@ function resizeAnnotation(config, shapes, selectedShapes, shape) { const result = foundShape.interactive ? resizeAnnotationsFunction(config, { shapes, - selectedShapes: [shapes.find(s => shape.parent === s.id)], + selectedShapes: [shapes.find((s) => shape.parent === s.id)], }) : []; return result; @@ -904,7 +904,7 @@ function resizeAnnotation(config, shapes, selectedShapes, shape) { config, shapes, selectedShapes, - shapes.find(s => foundShape.parent === s.id) + shapes.find((s) => foundShape.parent === s.id) ); } @@ -917,7 +917,7 @@ function resizeAnnotation(config, shapes, selectedShapes, shape) { magic( config, properShape, - shapes.filter(s => s.type !== 'annotation') + shapes.filter((s) => s.type !== 'annotation') )); const resizeVertices = allowResize ? resizeVertexTuples : []; const resizePoints = resizeVertices.map(resizePointAnnotations(config, shape, a, b)); @@ -929,14 +929,14 @@ export function resizeAnnotationsFunction(config, { shapes, selectedShapes }) { const shapesToAnnotate = selectedShapes; return flatten( shapesToAnnotate - .map(shape => { + .map((shape) => { return resizeAnnotation(config, shapes, selectedShapes, shape); }) .filter(identity) ); } -const crystallizeConstraint = shape => { +const crystallizeConstraint = (shape) => { const result = { ...shape }; if (shape.snapDeltaMatrix) { result.localTransformMatrix = multiply(shape.localTransformMatrix, shape.snapDeltaMatrix); @@ -950,7 +950,9 @@ const crystallizeConstraint = shape => { return result; }; -const translateShapeSnap = (horizontalConstraint, verticalConstraint, draggedElement) => shape => { +const translateShapeSnap = (horizontalConstraint, verticalConstraint, draggedElement) => ( + shape +) => { const constrainedX = horizontalConstraint && horizontalConstraint.constrained === shape.id; const constrainedY = verticalConstraint && verticalConstraint.constrained === shape.id; const snapOffsetX = constrainedX ? -horizontalConstraint.signedDistance : 0; @@ -983,7 +985,7 @@ const resizeShapeSnap = ( symmetric, horizontalPosition, verticalPosition -) => shape => { +) => (shape) => { const constrainedShape = draggedElement && shape.id === draggedElement.id; const constrainedX = horizontalConstraint && horizontalConstraint.constrained === shape.id; const constrainedY = verticalConstraint && verticalConstraint.constrained === shape.id; @@ -1025,10 +1027,10 @@ const resizeShapeSnap = ( const dissolveGroups = (groupsToDissolve, shapes, selectedShapes) => { return { shapes: shapes - .filter(s => !groupsToDissolve.find(g => s.id === g.id)) - .map(shape => { + .filter((s) => !groupsToDissolve.find((g) => s.id === g.id)) + .map((shape) => { const preexistingGroupParent = groupsToDissolve.find( - groupShape => groupShape.id === shape.parent + (groupShape) => groupShape.id === shape.parent ); // if linked, dissociate from group parent return preexistingGroupParent @@ -1037,29 +1039,29 @@ const dissolveGroups = (groupsToDissolve, shapes, selectedShapes) => { parent: null, localTransformMatrix: multiply( // pulling preexistingGroupParent from `shapes` to get fresh matrices - shapes.find(s => s.id === preexistingGroupParent.id).localTransformMatrix, // reinstate the group offset onto the child + shapes.find((s) => s.id === preexistingGroupParent.id).localTransformMatrix, // reinstate the group offset onto the child shape.localTransformMatrix ), } : shape; }), - selectedShapes: selectedShapes.filter(s => !groupsToDissolve.find(g => g.id === s.id)), + selectedShapes: selectedShapes.filter((s) => !groupsToDissolve.find((g) => g.id === s.id)), }; }; -const hasNoParentWithin = shapes => shape => !shapes.some(g => shape.parent === g.id); +const hasNoParentWithin = (shapes) => (shape) => !shapes.some((g) => shape.parent === g.id); const asYetUngroupedShapes = (preexistingAdHocGroups, selectedShapes) => selectedShapes.filter(hasNoParentWithin(preexistingAdHocGroups)); -const idMatch = shape => s => s.id === shape.id; +const idMatch = (shape) => (s) => s.id === shape.id; -const idsMatch = selectedShapes => shape => selectedShapes.find(idMatch(shape)); +const idsMatch = (selectedShapes) => (shape) => selectedShapes.find(idMatch(shape)); const axisAlignedBoundingBoxShape = (config, shapesToBox) => { const axisAlignedBoundingBox = shapesAABB(shapesToBox); const { a, b, localTransformMatrix, rigTransform } = projectAABB(axisAlignedBoundingBox); - const id = getId(config.groupName, shapesToBox.map(s => s.id).join('|')); + const id = getId(config.groupName, shapesToBox.map((s) => s.id).join('|')); const aabbShape = { id, type: config.groupName, @@ -1073,7 +1075,7 @@ const axisAlignedBoundingBoxShape = (config, shapesToBox) => { return aabbShape; }; -const resetChild = s => { +const resetChild = (s) => { if (s.childBaseAB) { s.childBaseAB = null; s.baseLocalTransformMatrix = null; @@ -1089,14 +1091,14 @@ const childScaler = ({ a, b }, baseAB) => { return groupScale; }; -const resizeChild = groupScale => s => { +const resizeChild = (groupScale) => (s) => { const childBaseAB = s.childBaseAB || [s.a, s.b]; const impliedScale = scale(...childBaseAB, 1); const inverseImpliedScale = invert(impliedScale); const baseLocalTransformMatrix = s.baseLocalTransformMatrix || s.localTransformMatrix; const normalizedBaseLocalTransformMatrix = multiply(baseLocalTransformMatrix, impliedScale); const T = multiply(groupScale, normalizedBaseLocalTransformMatrix); - const backScaler = groupScale.map(d => Math.abs(d)); + const backScaler = groupScale.map((d) => Math.abs(d)); const inverseBackScaler = invert(backScaler); const abTuple = mvMultiply(multiply(backScaler, impliedScale), [1, 1, 1, 1]); s.localTransformMatrix = multiply(T, multiply(inverseImpliedScale, inverseBackScaler)); @@ -1113,14 +1115,14 @@ const resizeGroup = (shapes, rootElement) => { } const depths = {}; - const ancestorsLength = shape => (shape.parent ? ancestorsLength(idMap[shape.parent]) + 1 : 0); + const ancestorsLength = (shape) => (shape.parent ? ancestorsLength(idMap[shape.parent]) + 1 : 0); for (const shape of shapes) { depths[shape.id] = ancestorsLength(shape); } const resizedParents = { [rootElement.id]: rootElement }; const sortedShapes = shapes.slice().sort((a, b) => depths[a.id] - depths[b.id]); - const parentResized = s => Boolean(s.childBaseAB || s.baseAB); + const parentResized = (s) => Boolean(s.childBaseAB || s.baseAB); for (const shape of sortedShapes) { const parent = resizedParents[shape.parent]; if (parent) { @@ -1137,32 +1139,32 @@ const resizeGroup = (shapes, rootElement) => { const getLeafs = (descendCondition, allShapes, shapes) => removeDuplicates( - s => s.id, + (s) => s.id, flatten( - shapes.map(shape => - descendCondition(shape) ? allShapes.filter(s => s.parent === shape.id) : shape + shapes.map((shape) => + descendCondition(shape) ? allShapes.filter((s) => s.parent === shape.id) : shape ) ) ); const preserveCurrentGroups = (shapes, selectedShapes) => ({ shapes, selectedShapes }); -export const getConfiguration = scene => scene.configuration; +export const getConfiguration = (scene) => scene.configuration; -export const getShapes = scene => scene.shapes; +export const getShapes = (scene) => scene.shapes; export const getHoveredShapes = (config, shapes, cursorPosition) => shapesAt( shapes.filter( // second AND term excludes intra-group element hover (and therefore drag & drop), todo: remove this current limitation - s => + (s) => (s.type !== 'annotation' || s.interactive) && (config.intraGroupManipulation || !s.parent || s.type === 'annotation') ), cursorPosition ); -export const getHoveredShape = hoveredShapes => (hoveredShapes.length ? hoveredShapes[0] : null); +export const getHoveredShape = (hoveredShapes) => (hoveredShapes.length ? hoveredShapes[0] : null); const singleSelect = (prev, config, hoveredShapes, metaHeld, uid, _, boxHighlightedShapes) => { // cycle from top ie. from zero after the cursor position changed ie. !sameLocation @@ -1193,7 +1195,7 @@ const multiSelect = ( ) => { const shapes = hoveredShapes.length > 0 - ? disjunctiveUnion(shape => shape.id, selectedShapeObjects, hoveredShapes.slice(0, 1)) // ie. depthIndex of 0, if any + ? disjunctiveUnion((shape) => shape.id, selectedShapeObjects, hoveredShapes.slice(0, 1)) // ie. depthIndex of 0, if any : []; return { shapes, @@ -1205,16 +1207,16 @@ const multiSelect = ( }; export const getGroupingTuple = (config, shapes, selectedShapes) => { - const childOfGroup = shape => shape.parent && shape.parent.startsWith(config.groupName); - const isAdHocGroup = shape => + const childOfGroup = (shape) => shape.parent && shape.parent.startsWith(config.groupName); + const isAdHocGroup = (shape) => shape.type === config.groupName && shape.subtype === config.adHocGroupName; const preexistingAdHocGroups = shapes.filter(isAdHocGroup); const matcher = idsMatch(selectedShapes); - const selectedFn = shape => matcher(shape) && shape.type !== 'annotation'; + const selectedFn = (shape) => matcher(shape) && shape.type !== 'annotation'; const freshSelectedShapes = shapes.filter(selectedFn); const freshNonSelectedShapes = shapes.filter(not(selectedFn)); - const isGroup = shape => shape.type === config.groupName; - const isOrBelongsToGroup = shape => isGroup(shape) || childOfGroup(shape); + const isGroup = (shape) => shape.type === config.groupName; + const isOrBelongsToGroup = (shape) => isGroup(shape) || childOfGroup(shape); const someSelectedShapesAreGrouped = selectedShapes.some(isOrBelongsToGroup); const selectionOutsideGroup = !someSelectedShapesAreGrouped; return { @@ -1234,16 +1236,16 @@ export const getGrouping = (config, shapes, selectedShapes, groupAction, tuple) } = tuple; if (groupAction === 'group') { const selectedAdHocGroupsToPersist = selectedShapes.filter( - s => s.subtype === config.adHocGroupName + (s) => s.subtype === config.adHocGroupName ); return { - shapes: shapes.map(s => + shapes: shapes.map((s) => s.subtype === config.adHocGroupName ? { ...s, subtype: config.persistentGroupName } : s ), selectedShapes: selectedShapes - .filter(selected => selected.subtype !== config.adHocGroupName) + .filter((selected) => selected.subtype !== config.adHocGroupName) .concat( - selectedAdHocGroupsToPersist.map(shape => ({ + selectedAdHocGroupsToPersist.map((shape) => ({ ...shape, subtype: config.persistentGroupName, })) @@ -1253,7 +1255,7 @@ export const getGrouping = (config, shapes, selectedShapes, groupAction, tuple) if (groupAction === 'ungroup') { return dissolveGroups( - selectedShapes.filter(s => s.subtype === config.persistentGroupName), + selectedShapes.filter((s) => s.subtype === config.persistentGroupName), shapes, asYetUngroupedShapes(preexistingAdHocGroups, freshSelectedShapes) ); @@ -1277,10 +1279,10 @@ export const getGrouping = (config, shapes, selectedShapes, groupAction, tuple) ? { shapes: [ ...resizeGroup( - shapes.filter(s => s.type !== 'annotation'), + shapes.filter((s) => s.type !== 'annotation'), elements[0] ), - ...shapes.filter(s => s.type === 'annotation'), + ...shapes.filter((s) => s.type === 'annotation'), ], selectedShapes, } @@ -1294,21 +1296,21 @@ export const getGrouping = (config, shapes, selectedShapes, groupAction, tuple) // group together the multiple items const group = axisAlignedBoundingBoxShape(config, freshSelectedShapes); const selectedLeafShapes = getLeafs( - shape => shape.subtype === config.adHocGroupName, + (shape) => shape.subtype === config.adHocGroupName, shapes, freshSelectedShapes ); - const parentedSelectedShapes = selectedLeafShapes.map(shape => ({ + const parentedSelectedShapes = selectedLeafShapes.map((shape) => ({ ...shape, parent: group.id, localTransformMatrix: multiply(group.rigTransform, shape.transformMatrix), })); - const nonGroupGraphConstituent = s => - s.subtype !== config.adHocGroupName && !parentedSelectedShapes.find(ss => s.id === ss.id); - const dissociateFromParentIfAny = s => + const nonGroupGraphConstituent = (s) => + s.subtype !== config.adHocGroupName && !parentedSelectedShapes.find((ss) => s.id === ss.id); + const dissociateFromParentIfAny = (s) => s.parent && s.parent.startsWith(config.groupName) && - preexistingAdHocGroups.find(ahg => ahg.id === s.parent) + preexistingAdHocGroups.find((ahg) => ahg.id === s.parent) ? { ...s, parent: null } : s; const allTerminalShapes = parentedSelectedShapes.concat( @@ -1338,7 +1340,7 @@ export const getCursor = (config, shape, draggedPrimaryShape) => { } }; -export const getSelectedShapesPrev = scene => scene.selectionState; +export const getSelectedShapesPrev = (scene) => scene.selectionState; export const getSelectionStateFull = ( prev, @@ -1362,7 +1364,7 @@ export const getSelectionStateFull = ( up && prev.boxHighlightedShapes.length ? prev.shapes .concat(prev.boxHighlightedShapes) - .filter((d, i, a) => a.findIndex(dd => dd.id === d.id) === i) + .filter((d, i, a) => a.findIndex((dd) => dd.id === d.id) === i) : prev.shapes, down, uid, @@ -1382,7 +1384,7 @@ export const getSelectionStateFull = ( ); }; -export const getSelectedShapes = selectionTuple => selectionTuple.shapes; +export const getSelectedShapes = (selectionTuple) => selectionTuple.shapes; export const getSelectionState = ({ uid, depthIndex, down, metaHeld, boxHighlightedShapes }) => ({ uid, @@ -1392,7 +1394,7 @@ export const getSelectionState = ({ uid, depthIndex, down, metaHeld, boxHighligh boxHighlightedShapes, }); -export const getSelectedPrimaryShapeIds = shapes => shapes.map(primaryShape); +export const getSelectedPrimaryShapeIds = (shapes) => shapes.map(primaryShape); export const getResizeManipulator = (config, toggle) => (toggle ? centeredResizeManipulation : asymmetricResizeManipulation)(config); @@ -1407,12 +1409,12 @@ export const getTransformIntents = ( manipulator ) => [ ...directShapeTranslateManipulation( - transformGestures.map(g => g.cumulativeTransform), + transformGestures.map((g) => g.cumulativeTransform), directShapes ), ...rotationAnnotationManipulation( config, - transformGestures.map(g => g.transform), + transformGestures.map((g) => g.transform), directShapes, shapes, cursorPosition, @@ -1422,14 +1424,14 @@ export const getTransformIntents = ( ]; export const getDraggedPrimaryShape = (shapes, draggedShape) => - draggedShape && shapes.find(shape => shape.id === primaryShape(draggedShape)); + draggedShape && shapes.find((shape) => shape.id === primaryShape(draggedShape)); export const getAlignmentGuideAnnotations = (config, shapes, draggedPrimaryShape, draggedShape) => { const guidedShapes = draggedPrimaryShape - ? [shapes.find(s => s.id === draggedPrimaryShape.id)].filter(identity) + ? [shapes.find((s) => s.id === draggedPrimaryShape.id)].filter(identity) : []; return guidedShapes.length - ? alignmentGuides(config, shapes, guidedShapes, draggedShape).map(shape => ({ + ? alignmentGuides(config, shapes, guidedShapes, draggedShape).map((shape) => ({ ...shape, id: config.alignmentGuideName + '_' + shape.id, type: 'annotation', @@ -1441,7 +1443,7 @@ export const getAlignmentGuideAnnotations = (config, shapes, draggedPrimaryShape : []; }; -const borderAnnotation = (subtype, lift) => shape => ({ +const borderAnnotation = (subtype, lift) => (shape) => ({ ...shape, id: subtype + '_' + shape.id, type: 'annotation', @@ -1452,16 +1454,18 @@ const borderAnnotation = (subtype, lift) => shape => ({ }); export const getAdHocChildrenAnnotations = (config, { shapes }) => { - const adHocGroups = shapes.filter(s => s.subtype === config.adHocGroupName); + const adHocGroups = shapes.filter((s) => s.subtype === config.adHocGroupName); return shapes - .filter(s => s.type !== 'annotation' && s.parent && adHocGroups.find(p => p.id === s.parent)) + .filter( + (s) => s.type !== 'annotation' && s.parent && adHocGroups.find((p) => p.id === s.parent) + ) .map(borderAnnotation(config.getAdHocChildAnnotationName, config.hoverLift)); }; export const getHoverAnnotations = (config, shapes, selectedPrimaryShapeIds, draggedShape) => shapes .filter( - shape => + (shape) => shape && shape.type !== 'annotation' && selectedPrimaryShapeIds.indexOf(shape.id) === -1 && @@ -1481,7 +1485,7 @@ export const getSnappedShapes = ( alterSnapGesture, symmetricManipulation ) => { - const contentShapes = shapes.filter(shape => shape.type !== 'annotation'); + const contentShapes = shapes.filter((shape) => shape.type !== 'annotation'); const subtype = draggedShape && draggedShape.subtype; // snapping doesn't come into play if there's no dragging, or it's not a resize drag or translate drag on a // leaf element or a group element: @@ -1513,7 +1517,7 @@ export const getSnappedShapes = ( }; export const getConstrainedShapesWithPreexistingAnnotations = (snapped, transformed) => - snapped.concat(transformed.filter(s => s.type === 'annotation')); + snapped.concat(transformed.filter((s) => s.type === 'annotation')); export const getGroupAction = (action, mouseIsDown) => { const event = action && action.event; @@ -1567,14 +1571,16 @@ const distributions = { distributeVertically: { type: 'distributeVerticallyAction', horizontal: false }, }; -export const getAlignAction = action => alignments[action && action.event] || null; -export const getDistributeAction = action => distributions[action && action.event] || null; +export const getAlignAction = (action) => alignments[action && action.event] || null; +export const getDistributeAction = (action) => distributions[action && action.event] || null; export const getGroupedSelectedShapes = ({ selectedShapes }) => selectedShapes; -export const getGroupedSelectedPrimaryShapeIds = selectedShapes => selectedShapes.map(primaryShape); +export const getGroupedSelectedPrimaryShapeIds = (selectedShapes) => + selectedShapes.map(primaryShape); -export const getGroupedSelectedShapeIds = selectedShapes => selectedShapes.map(shape => shape.id); +export const getGroupedSelectedShapeIds = (selectedShapes) => + selectedShapes.map((shape) => shape.id); export const getRotationAnnotations = (config, { shapes, selectedShapes }) => { const shapesToAnnotate = selectedShapes; @@ -1598,7 +1604,7 @@ export const getDragboxHighlighted = (box, shapes) => { } const filter = insideAABB(box); return shapes.filter( - s => s.type !== 'annotation' && !s.parent && filter(s.transformMatrix, s.a, s.b) + (s) => s.type !== 'annotation' && !s.parent && filter(s.transformMatrix, s.a, s.b) ); }; @@ -1639,7 +1645,7 @@ export const getAnnotatedShapes = ( dragBoxAnnotation ); // remove preexisting annotations - const contentShapes = shapes.filter(shape => shape.type !== 'annotation'); + const contentShapes = shapes.filter((shape) => shape.type !== 'annotation'); return contentShapes.concat(annotations); // add current annotations }; // collection of shapes themselves diff --git a/x-pack/plugins/canvas/public/lib/aeroelastic/select.ts b/x-pack/plugins/canvas/public/lib/aeroelastic/select.ts index a7dfa91bc3e11..ee8a2b21f3cef 100644 --- a/x-pack/plugins/canvas/public/lib/aeroelastic/select.ts +++ b/x-pack/plugins/canvas/public/lib/aeroelastic/select.ts @@ -10,5 +10,5 @@ export const select = (fun: PlainFun): Selector => (...fns: Resolve[]) => { let prevId: ActionId = NaN; let cache: Json = null; const old = (object: State): boolean => prevId === (prevId = object.primaryUpdate.payload.uid); - return (obj: State) => (old(obj) ? cache : (cache = fun(...fns.map(f => f(obj))))); + return (obj: State) => (old(obj) ? cache : (cache = fun(...fns.map((f) => f(obj))))); }; diff --git a/x-pack/plugins/canvas/public/lib/arg_helpers.js b/x-pack/plugins/canvas/public/lib/arg_helpers.js index b674e158f3e34..9e4c93ed5f274 100644 --- a/x-pack/plugins/canvas/public/lib/arg_helpers.js +++ b/x-pack/plugins/canvas/public/lib/arg_helpers.js @@ -19,7 +19,7 @@ import { getType } from '@kbn/interpreter/common'; const allowedTypes = ['string', 'number', 'boolean']; const badType = () => new Error(`Arg setting helpers only support ${allowedTypes.join(',')}`); -const isAllowed = type => includes(allowedTypes, type); +const isAllowed = (type) => includes(allowedTypes, type); export function validateArg(value) { const type = getType(value); @@ -33,7 +33,7 @@ export function getSimpleArg(name, args) { if (!args[name]) { return []; } - return args[name].map(astVal => { + return args[name].map((astVal) => { if (!isAllowed(getType(astVal))) { throw badType(); } diff --git a/x-pack/plugins/canvas/public/lib/build_bool_array.js b/x-pack/plugins/canvas/public/lib/build_bool_array.js index 2dc6447753526..f1cab93ceebbb 100644 --- a/x-pack/plugins/canvas/public/lib/build_bool_array.js +++ b/x-pack/plugins/canvas/public/lib/build_bool_array.js @@ -6,11 +6,11 @@ import { getESFilter } from './get_es_filter'; -const compact = arr => (Array.isArray(arr) ? arr.filter(val => Boolean(val)) : []); +const compact = (arr) => (Array.isArray(arr) ? arr.filter((val) => Boolean(val)) : []); export function buildBoolArray(canvasQueryFilterArray) { return compact( - canvasQueryFilterArray.map(clause => { + canvasQueryFilterArray.map((clause) => { try { return getESFilter(clause); } catch (e) { diff --git a/x-pack/plugins/canvas/public/lib/build_embeddable_filters.ts b/x-pack/plugins/canvas/public/lib/build_embeddable_filters.ts index 9aa7477523c9a..c847bfb6516bf 100644 --- a/x-pack/plugins/canvas/public/lib/build_embeddable_filters.ts +++ b/x-pack/plugins/canvas/public/lib/build_embeddable_filters.ts @@ -18,7 +18,7 @@ const TimeFilterType = 'time'; function getTimeRangeFromFilters(filters: ExpressionValueFilter[]): TimeRange | undefined { const timeFilter = filters.find( - filter => filter.filterType !== undefined && filter.filterType === TimeFilterType + (filter) => filter.filterType !== undefined && filter.filterType === TimeFilterType ); return timeFilter !== undefined && timeFilter.from !== undefined && timeFilter.to !== undefined @@ -30,7 +30,7 @@ function getTimeRangeFromFilters(filters: ExpressionValueFilter[]): TimeRange | } export function getQueryFilters(filters: ExpressionValueFilter[]): DataFilter[] { - const dataFilters = filters.map(filter => ({ ...filter, type: filter.filterType })); + const dataFilters = filters.map((filter) => ({ ...filter, type: filter.filterType })); return buildBoolArray(dataFilters).map(esFilters.buildQueryFilter); } diff --git a/x-pack/plugins/canvas/public/lib/clone_subgraphs.js b/x-pack/plugins/canvas/public/lib/clone_subgraphs.js index 101492657b47b..e4dfa1cefcaba 100644 --- a/x-pack/plugins/canvas/public/lib/clone_subgraphs.js +++ b/x-pack/plugins/canvas/public/lib/clone_subgraphs.js @@ -7,13 +7,13 @@ import { arrayToMap } from './aeroelastic/functional'; import { getId } from './get_id'; -export const cloneSubgraphs = nodes => { - const idMap = arrayToMap(nodes.map(n => n.id)); +export const cloneSubgraphs = (nodes) => { + const idMap = arrayToMap(nodes.map((n) => n.id)); // We simultaneously provide unique id values for all elements (across all pages) // AND ensure that parent-child relationships are retained (via matching id values within page) - Object.keys(idMap).forEach(key => (idMap[key] = getId(key.split('-')[0]))); // new group names to which we can map + Object.keys(idMap).forEach((key) => (idMap[key] = getId(key.split('-')[0]))); // new group names to which we can map // must return elements in the same order, for several reasons - const newNodes = nodes.map(element => ({ + const newNodes = nodes.map((element) => ({ ...element, id: idMap[element.id], position: { diff --git a/x-pack/plugins/canvas/public/lib/custom_element_service.ts b/x-pack/plugins/canvas/public/lib/custom_element_service.ts index 8952802dc2f2b..25c3b78a2746e 100644 --- a/x-pack/plugins/canvas/public/lib/custom_element_service.ts +++ b/x-pack/plugins/canvas/public/lib/custom_element_service.ts @@ -10,7 +10,7 @@ import { fetch } from '../../common/lib/fetch'; import { CustomElement } from '../../types'; import { platformService } from '../services'; -const getApiPath = function() { +const getApiPath = function () { const basePath = platformService.getService().coreStart.http.basePath.get(); return `${basePath}${API_ROUTE_CUSTOM_ELEMENT}`; }; diff --git a/x-pack/plugins/canvas/public/lib/doc_title.js b/x-pack/plugins/canvas/public/lib/doc_title.js index 3f75d18df14d2..ce31a58fa359c 100644 --- a/x-pack/plugins/canvas/public/lib/doc_title.js +++ b/x-pack/plugins/canvas/public/lib/doc_title.js @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export const setDocTitle = title => (document.title = `${title} - Kibana`); +export const setDocTitle = (title) => (document.title = `${title} - Kibana`); diff --git a/x-pack/plugins/canvas/public/lib/element_handler_creators.ts b/x-pack/plugins/canvas/public/lib/element_handler_creators.ts index a8744b4820842..d280c62888df0 100644 --- a/x-pack/plugins/canvas/public/lib/element_handler_creators.ts +++ b/x-pack/plugins/canvas/public/lib/element_handler_creators.ts @@ -95,8 +95,9 @@ export const basicHandlerCreators = { ) .catch((error: Error) => notifyService.getService().warning(error, { - title: `Custom element '${customElement.displayName || - customElement.id}' was not saved`, + title: `Custom element '${ + customElement.displayName || customElement.id + }' was not saved`, }) ); } @@ -186,7 +187,7 @@ export const layerHandlerCreators = { export const positionHandlerCreators = { shiftUp: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.top -= ELEMENT_SHIFT_OFFSET; return element; }) @@ -194,7 +195,7 @@ export const positionHandlerCreators = { }, shiftDown: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.top += ELEMENT_SHIFT_OFFSET; return element; }) @@ -202,7 +203,7 @@ export const positionHandlerCreators = { }, shiftLeft: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.left -= ELEMENT_SHIFT_OFFSET; return element; }) @@ -210,7 +211,7 @@ export const positionHandlerCreators = { }, shiftRight: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.left += ELEMENT_SHIFT_OFFSET; return element; }) @@ -218,7 +219,7 @@ export const positionHandlerCreators = { }, nudgeUp: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.top -= ELEMENT_NUDGE_OFFSET; return element; }) @@ -226,7 +227,7 @@ export const positionHandlerCreators = { }, nudgeDown: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.top += ELEMENT_NUDGE_OFFSET; return element; }) @@ -234,7 +235,7 @@ export const positionHandlerCreators = { }, nudgeLeft: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.left -= ELEMENT_NUDGE_OFFSET; return element; }) @@ -242,7 +243,7 @@ export const positionHandlerCreators = { }, nudgeRight: ({ selectedNodes, setMultiplePositions }: Props) => (): void => { setMultiplePositions( - selectedNodes.map(element => { + selectedNodes.map((element) => { element.position.left += ELEMENT_NUDGE_OFFSET; return element; }) diff --git a/x-pack/plugins/canvas/public/lib/es_service.ts b/x-pack/plugins/canvas/public/lib/es_service.ts index 184f4f3c8af7c..496751a874b21 100644 --- a/x-pack/plugins/canvas/public/lib/es_service.ts +++ b/x-pack/plugins/canvas/public/lib/es_service.ts @@ -15,16 +15,16 @@ import { platformService } from '../services'; const { esService: strings } = ErrorStrings; -const getApiPath = function() { +const getApiPath = function () { const basePath = platformService.getService().coreStart.http.basePath.get(); return basePath + API_ROUTE; }; -const getSavedObjectsClient = function() { +const getSavedObjectsClient = function () { return platformService.getService().coreStart.savedObjects.client; }; -const getAdvancedSettings = function() { +const getAdvancedSettings = function () { return platformService.getService().coreStart.uiSettings; }; @@ -33,7 +33,7 @@ export const getFields = (index = '_all') => { .get(`${getApiPath()}/es_fields?index=${index}`) .then(({ data: mapping }: { data: object }) => Object.keys(mapping) - .filter(field => !field.startsWith('_')) // filters out meta fields + .filter((field) => !field.startsWith('_')) // filters out meta fields .sort() ) .catch((err: Error) => @@ -51,8 +51,8 @@ export const getIndices = () => searchFields: ['title'], perPage: 1000, }) - .then(resp => { - return resp.savedObjects.map(savedObject => { + .then((resp) => { + return resp.savedObjects.map((savedObject) => { return savedObject.attributes.title; }); }) @@ -66,8 +66,8 @@ export const getDefaultIndex = () => { return defaultIndexId ? getSavedObjectsClient() .get('index-pattern', defaultIndexId) - .then(defaultIndex => defaultIndex.attributes.title) - .catch(err => + .then((defaultIndex) => defaultIndex.attributes.title) + .catch((err) => notifyService .getService() .error(err, { title: strings.getDefaultIndexFetchErrorMessage() }) diff --git a/x-pack/plugins/canvas/public/lib/extract_search.js b/x-pack/plugins/canvas/public/lib/extract_search.js index 9ad0a6cd8f0c3..1d472b1c9dbb4 100644 --- a/x-pack/plugins/canvas/public/lib/extract_search.js +++ b/x-pack/plugins/canvas/public/lib/extract_search.js @@ -6,12 +6,12 @@ // EUI helper // extracts search text and array of selected tags from EuiSearchBar -export const extractSearch = queryText => { +export const extractSearch = (queryText) => { const filterTags = []; const searchTerms = []; const parts = queryText.split(' '); - parts.forEach(part => { + parts.forEach((part) => { if (part.indexOf(':') >= 0) { const [key, value] = part.split(':'); if (key === 'tag') { diff --git a/x-pack/plugins/canvas/public/lib/find_existing_asset.js b/x-pack/plugins/canvas/public/lib/find_existing_asset.js index 470d7797e6feb..2a6f48c31cd24 100644 --- a/x-pack/plugins/canvas/public/lib/find_existing_asset.js +++ b/x-pack/plugins/canvas/public/lib/find_existing_asset.js @@ -6,7 +6,7 @@ export const findExistingAsset = (type, content, assets) => { const existingId = Object.keys(assets).find( - assetId => assets[assetId].type === type && assets[assetId].value === content + (assetId) => assets[assetId].type === type && assets[assetId].value === content ); return existingId; }; diff --git a/x-pack/plugins/canvas/public/lib/find_expression_type.js b/x-pack/plugins/canvas/public/lib/find_expression_type.js index 2cd7c5efb74e9..4b09ba1ac8dd4 100644 --- a/x-pack/plugins/canvas/public/lib/find_expression_type.js +++ b/x-pack/plugins/canvas/public/lib/find_expression_type.js @@ -13,7 +13,7 @@ const expressionTypes = ['view', 'model', 'transform', 'datasource']; export function findExpressionType(name, type) { const checkTypes = expressionTypes.filter( - expressionType => type == null || expressionType === type + (expressionType) => type == null || expressionType === type ); const matches = checkTypes.reduce((acc, checkType) => { diff --git a/x-pack/plugins/canvas/public/lib/history_provider.js b/x-pack/plugins/canvas/public/lib/history_provider.js index 4ff9f0b9d4605..649f101126012 100644 --- a/x-pack/plugins/canvas/public/lib/history_provider.js +++ b/x-pack/plugins/canvas/public/lib/history_provider.js @@ -125,7 +125,7 @@ function wrapHistoryInstance(history) { const prevLocationObj = locationFormat(prevLocation, action, wrappedHistory.parse); // execute all listeners - historyState.onChange.forEach(fn => fn.call(null, locationObj, prevLocationObj)); + historyState.onChange.forEach((fn) => fn.call(null, locationObj, prevLocationObj)); // track the updated location historyState.prevLocation = wrappedHistory.getLocation(); @@ -136,7 +136,7 @@ function wrapHistoryInstance(history) { let instances = new WeakMap(); -const getHistoryInstance = win => { +const getHistoryInstance = (win) => { // if no window object, use memory module if (typeof win === 'undefined' || !win.history) { return createMemoryHistory(); diff --git a/x-pack/plugins/canvas/public/lib/keymap.ts b/x-pack/plugins/canvas/public/lib/keymap.ts index 7976c8ed5c5da..7ca93f440087e 100644 --- a/x-pack/plugins/canvas/public/lib/keymap.ts +++ b/x-pack/plugins/canvas/public/lib/keymap.ts @@ -37,20 +37,20 @@ const getShortcuts = ( // handle shift modifier if (modifiers.includes('shift')) { - macShortcuts = macShortcuts.map(shortcut => `shift+${shortcut}`); - shortcuts = shortcuts.map(shortcut => `shift+${shortcut}`); + macShortcuts = macShortcuts.map((shortcut) => `shift+${shortcut}`); + shortcuts = shortcuts.map((shortcut) => `shift+${shortcut}`); } // handle alt modifier if (modifiers.includes('alt') || modifiers.includes('option')) { - macShortcuts = macShortcuts.map(shortcut => `option+${shortcut}`); - shortcuts = shortcuts.map(shortcut => `alt+${shortcut}`); + macShortcuts = macShortcuts.map((shortcut) => `option+${shortcut}`); + shortcuts = shortcuts.map((shortcut) => `alt+${shortcut}`); } // handle ctrl modifier if (modifiers.includes('ctrl') || modifiers.includes('command')) { - macShortcuts = macShortcuts.map(shortcut => `command+${shortcut}`); - shortcuts = shortcuts.map(shortcut => `ctrl+${shortcut}`); + macShortcuts = macShortcuts.map((shortcut) => `command+${shortcut}`); + shortcuts = shortcuts.map((shortcut) => `ctrl+${shortcut}`); } return { diff --git a/x-pack/plugins/canvas/public/lib/load_expression_types.js b/x-pack/plugins/canvas/public/lib/load_expression_types.js index 82699eb5b88fa..23a14d079c091 100644 --- a/x-pack/plugins/canvas/public/lib/load_expression_types.js +++ b/x-pack/plugins/canvas/public/lib/load_expression_types.js @@ -9,5 +9,5 @@ import { argTypeRegistry } from '../expression_types'; export function loadExpressionTypes() { // register default args, arg types, and expression types - argTypeSpecs.forEach(expFn => argTypeRegistry.register(expFn)); + argTypeSpecs.forEach((expFn) => argTypeRegistry.register(expFn)); } diff --git a/x-pack/plugins/canvas/public/lib/load_transitions.js b/x-pack/plugins/canvas/public/lib/load_transitions.js index 915d63142bbf7..c4d91533435b8 100644 --- a/x-pack/plugins/canvas/public/lib/load_transitions.js +++ b/x-pack/plugins/canvas/public/lib/load_transitions.js @@ -8,5 +8,5 @@ import { transitions } from '../transitions'; import { transitionsRegistry } from './transitions_registry'; export function loadTransitions() { - transitions.forEach(spec => transitionsRegistry.register(spec)); + transitions.forEach((spec) => transitionsRegistry.register(spec)); } diff --git a/x-pack/plugins/canvas/public/lib/monaco_language_def.ts b/x-pack/plugins/canvas/public/lib/monaco_language_def.ts index 5dac7fcc9bc50..7bd9ea7b6ef9a 100644 --- a/x-pack/plugins/canvas/public/lib/monaco_language_def.ts +++ b/x-pack/plugins/canvas/public/lib/monaco_language_def.ts @@ -95,7 +95,7 @@ export const language: Language = { }; export function registerLanguage(functions: ExpressionFunction[]) { - language.keywords = functions.map(fn => fn.name); + language.keywords = functions.map((fn) => fn.name); monaco.languages.register({ id: LANGUAGE_ID }); monaco.languages.setMonarchTokensProvider(LANGUAGE_ID, language); diff --git a/x-pack/plugins/canvas/public/lib/parse_single_function_chain.js b/x-pack/plugins/canvas/public/lib/parse_single_function_chain.js index fb67379550b1d..4b23ba0941e88 100644 --- a/x-pack/plugins/canvas/public/lib/parse_single_function_chain.js +++ b/x-pack/plugins/canvas/public/lib/parse_single_function_chain.js @@ -17,7 +17,7 @@ export function parseSingleFunctionChain(filterString) { throw new Error('Could not find function name in chain'); } - const args = mapValues(get(ast, 'chain[0].arguments'), val => { + const args = mapValues(get(ast, 'chain[0].arguments'), (val) => { // TODO Check for literals only return map(val, 'value'); }); diff --git a/x-pack/plugins/canvas/public/lib/router_provider.js b/x-pack/plugins/canvas/public/lib/router_provider.js index 42960baa00de1..b518241585a10 100644 --- a/x-pack/plugins/canvas/public/lib/router_provider.js +++ b/x-pack/plugins/canvas/public/lib/router_provider.js @@ -23,7 +23,7 @@ export function routerProvider(routes) { const componentListeners = []; // assume any string starting with a / is a path - const isPath = str => typeof str === 'string' && str.substr(0, 1) === '/'; + const isPath = (str) => typeof str === 'string' && str.substr(0, 1) === '/'; // helper to get the current state in history const getState = (name, params, state) => { @@ -36,7 +36,7 @@ export function routerProvider(routes) { // helper to append appState to a given url path const appendAppState = (path, appState = getCurrentAppState()) => { - const newUrl = modifyUrl(path, parts => { + const newUrl = modifyUrl(path, (parts) => { parts.query = assignAppState(parts.query, appState); }); @@ -78,7 +78,7 @@ export function routerProvider(routes) { history[method](currentState, newPath); }, onPathChange(fn) { - const execOnMatch = location => { + const execOnMatch = (location) => { const { pathname } = location; const match = this.match(pathname); diff --git a/x-pack/plugins/canvas/public/lib/run_interpreter.ts b/x-pack/plugins/canvas/public/lib/run_interpreter.ts index df338f40e08d9..bd00cad4fcbe7 100644 --- a/x-pack/plugins/canvas/public/lib/run_interpreter.ts +++ b/x-pack/plugins/canvas/public/lib/run_interpreter.ts @@ -12,7 +12,7 @@ import { CanvasStartDeps, CanvasSetupDeps } from '../plugin'; let expressionsStarting: Promise | undefined; -export const initInterpreter = function( +export const initInterpreter = function ( expressionsStart: CanvasStartDeps['expressions'], expressionsSetup: CanvasSetupDeps['expressions'] ) { @@ -29,7 +29,7 @@ async function startExpressions( return expressionsStart; } -export const resetInterpreter = function() { +export const resetInterpreter = function () { expressionsStarting = undefined; }; diff --git a/x-pack/plugins/canvas/public/lib/template.js b/x-pack/plugins/canvas/public/lib/template.js index b7bf4c608d18d..d548d707e7aa0 100644 --- a/x-pack/plugins/canvas/public/lib/template.js +++ b/x-pack/plugins/canvas/public/lib/template.js @@ -25,7 +25,7 @@ export function Template(config) { // Tags for categorizing the template this.tags = config.tags || []; - this.tags.forEach(tag => { + this.tags.forEach((tag) => { if (!tagsRegistry.get(tag)) { tagsRegistry.register(() => ({ name: tag, color: '#666666' })); } diff --git a/x-pack/plugins/canvas/public/lib/template_from_react_component.tsx b/x-pack/plugins/canvas/public/lib/template_from_react_component.tsx index f5059dfa04b95..17e2712c44b8d 100644 --- a/x-pack/plugins/canvas/public/lib/template_from_react_component.tsx +++ b/x-pack/plugins/canvas/public/lib/template_from_react_component.tsx @@ -16,7 +16,7 @@ interface Props { } export const templateFromReactComponent = (Component: ComponentType) => { - const WrappedComponent: FunctionComponent = props => ( + const WrappedComponent: FunctionComponent = (props) => ( {({ error }: { error: Error }) => { if (error) { diff --git a/x-pack/plugins/canvas/public/lib/window_error_handler.js b/x-pack/plugins/canvas/public/lib/window_error_handler.js index 75307816b4371..b4dd850b56c44 100644 --- a/x-pack/plugins/canvas/public/lib/window_error_handler.js +++ b/x-pack/plugins/canvas/public/lib/window_error_handler.js @@ -15,7 +15,7 @@ function showError(err) { const close = document.createElement('a'); close.textContent = 'close'; - close.onclick = ev => { + close.onclick = (ev) => { ev.preventDefault(); body.removeChild(notice); }; @@ -29,11 +29,7 @@ function showError(err) { if (err.stack) { const stack = document.createElement('pre'); - stack.textContent = err.stack - .split('\n') - .slice(0, 2) - .concat('...') - .join('\n'); + stack.textContent = err.stack.split('\n').slice(0, 2).concat('...').join('\n'); notice.appendChild(stack); } @@ -54,7 +50,7 @@ window.canvasInitErrorHandler = () => { console.log(message); const isKnownError = message.includes('ResizeObserver loop') || - Object.keys(knownErrors).find(errorName => { + Object.keys(knownErrors).find((errorName) => { return err.constructor.name === errorName || message.indexOf(errorName) >= 0; }); if (isKnownError) { diff --git a/x-pack/plugins/canvas/public/lib/workpad_service.js b/x-pack/plugins/canvas/public/lib/workpad_service.js index e6628399f53c2..1ac2aa222927b 100644 --- a/x-pack/plugins/canvas/public/lib/workpad_service.js +++ b/x-pack/plugins/canvas/public/lib/workpad_service.js @@ -30,7 +30,7 @@ const validKeys = [ 'width', ]; -const sanitizeWorkpad = function(workpad) { +const sanitizeWorkpad = function (workpad) { const workpadKeys = Object.keys(workpad); for (const key of workpadKeys) { @@ -42,17 +42,17 @@ const sanitizeWorkpad = function(workpad) { return workpad; }; -const getApiPath = function() { +const getApiPath = function () { const basePath = platformService.getService().coreStart.http.basePath.get(); return `${basePath}${API_ROUTE_WORKPAD}`; }; -const getApiPathStructures = function() { +const getApiPathStructures = function () { const basePath = platformService.getService().coreStart.http.basePath.get(); return `${basePath}${API_ROUTE_WORKPAD_STRUCTURES}`; }; -const getApiPathAssets = function() { +const getApiPathAssets = function () { const basePath = platformService.getService().coreStart.http.basePath.get(); return `${basePath}${API_ROUTE_WORKPAD_ASSETS}`; }; diff --git a/x-pack/plugins/canvas/public/plugin_api.ts b/x-pack/plugins/canvas/public/plugin_api.ts index 738b319d29c0b..4314c77456527 100644 --- a/x-pack/plugins/canvas/public/plugin_api.ts +++ b/x-pack/plugins/canvas/public/plugin_api.ts @@ -57,32 +57,32 @@ export function getPluginApi( const api: CanvasApi = { // Functions, types and renderers are registered directly to expression plugin - addFunctions: fns => { - fns.forEach(fn => { + addFunctions: (fns) => { + fns.forEach((fn) => { expressionsPluginSetup.registerFunction(fn); }); }, - addTypes: types => { - types.forEach(type => { + addTypes: (types) => { + types.forEach((type) => { expressionsPluginSetup.registerType(type as any); }); }, - addRenderers: renderers => { + addRenderers: (renderers) => { renderers.forEach((r: any) => { expressionsPluginSetup.registerRenderer(r); }); }, // All these others are local to canvas, and they will only register on start - addElements: elements => registries.elements.push(...elements), - addTransformUIs: transforms => registries.transformUIs.push(...transforms), - addDatasourceUIs: datasources => registries.datasourceUIs.push(...datasources), - addModelUIs: models => registries.modelUIs.push(...models), - addViewUIs: views => registries.viewUIs.push(...views), - addArgumentUIs: args => registries.argumentUIs.push(...args), - addTemplates: templates => registries.templates.push(...templates), - addTagUIs: tags => registries.tagUIs.push(...tags), - addTransitions: transitions => registries.transitions.push(...transitions), + addElements: (elements) => registries.elements.push(...elements), + addTransformUIs: (transforms) => registries.transformUIs.push(...transforms), + addDatasourceUIs: (datasources) => registries.datasourceUIs.push(...datasources), + addModelUIs: (models) => registries.modelUIs.push(...models), + addViewUIs: (views) => registries.viewUIs.push(...views), + addArgumentUIs: (args) => registries.argumentUIs.push(...args), + addTemplates: (templates) => registries.templates.push(...templates), + addTagUIs: (tags) => registries.tagUIs.push(...tags), + addTransitions: (transitions) => registries.transitions.push(...transitions), }; return { api, registries }; diff --git a/x-pack/plugins/canvas/public/state/actions/elements.js b/x-pack/plugins/canvas/public/state/actions/elements.js index 5ec8eb6137f2b..47fbc782f90d3 100644 --- a/x-pack/plugins/canvas/public/state/actions/elements.js +++ b/x-pack/plugins/canvas/public/state/actions/elements.js @@ -55,7 +55,7 @@ function getBareElement(el, includeId = false) { export const elementLayer = createAction('elementLayer'); -export const setMultiplePositions = createAction('setMultiplePosition', repositionedElements => ({ +export const setMultiplePositions = createAction('setMultiplePosition', (repositionedElements) => ({ repositionedElements, })); @@ -103,7 +103,7 @@ export const fetchContext = createThunk( chain: astChain, }, prevContextValue - ).then(value => { + ).then((value) => { dispatch( args.setValue({ path: contextPath, @@ -122,17 +122,17 @@ const fetchRenderableWithContextFn = ({ dispatch }, element, ast, context) => { }) ); - const getAction = renderable => + const getAction = (renderable) => args.setValue({ path: argumentPath, value: renderable, }); return runInterpreter(ast, context, { castToRender: true }) - .then(renderable => { + .then((renderable) => { dispatch(getAction(renderable)); }) - .catch(err => { + .catch((err) => { services.notify.getService().error(err); dispatch(getAction(err)); }); @@ -162,25 +162,25 @@ export const fetchAllRenderables = createThunk( function fetchElementsOnPages(pages) { const elements = []; - pages.forEach(page => { - page.elements.forEach(element => { + pages.forEach((page) => { + page.elements.forEach((element) => { elements.push(element); }); }); - const renderablePromises = elements.map(element => { + const renderablePromises = elements.map((element) => { const ast = element.ast || safeElementFromExpression(element.expression); const argumentPath = [element.id, 'expressionRenderable']; return runInterpreter(ast, null, { castToRender: true }) - .then(renderable => ({ path: argumentPath, value: renderable })) - .catch(err => { + .then((renderable) => ({ path: argumentPath, value: renderable })) + .catch((err) => { services.notify.getService().error(err); return { path: argumentPath, value: err }; }); }); - return Promise.all(renderablePromises).then(renderables => { + return Promise.all(renderablePromises).then((renderables) => { dispatch(args.setValues(renderables)); }); } @@ -203,17 +203,17 @@ export const insertNodes = createThunk('insertNodes', ({ dispatch, type }, eleme const _insertNodes = createAction(type); const newElements = elements.map(cloneDeep); // move the root element so users can see that it was added - newElements.forEach(newElement => { + newElements.forEach((newElement) => { newElement.position.top = newElement.position.top + 10; newElement.position.left = newElement.position.left + 10; }); dispatch(_insertNodes({ pageId, elements: newElements })); // refresh all elements just once per `insertNodes call` if there's a filter on any, otherwise just render the new element - if (elements.some(element => element.filter)) { + if (elements.some((element) => element.filter)) { dispatch(fetchAllRenderables()); } else { - newElements.forEach(newElement => dispatch(fetchRenderable(newElement))); + newElements.forEach((newElement) => dispatch(fetchRenderable(newElement))); } }); @@ -224,15 +224,17 @@ export const removeElements = createThunk( // todo consider doing the group membership collation in aeroelastic, or the Redux reducer, when adding templates const allElements = getNodes(state, pageId); - const allRoots = rootElementIds.map(id => allElements.find(e => id === e.id)).filter(d => d); + const allRoots = rootElementIds + .map((id) => allElements.find((e) => id === e.id)) + .filter((d) => d); const elementIds = subMultitree( - e => e.id, - e => e.position.parent, + (e) => e.id, + (e) => e.position.parent, allElements, allRoots - ).map(e => e.id); + ).map((e) => e.id); - const shouldRefresh = elementIds.some(elementId => { + const shouldRefresh = elementIds.some((elementId) => { const element = getNodeById(state, elementId, pageId); const filterIsApplied = element.filter && element.filter.length > 0; return filterIsApplied; @@ -275,7 +277,7 @@ function setExpressionFn({ dispatch, getState }, expression, elementId, pageId, // TODO: find a way to extract a list of filter renderers from the functions registry if ( updatedElement.filter && - !['dropdownControl', 'timefilterControl', 'exactly'].some(filter => + !['dropdownControl', 'timefilterControl', 'exactly'].some((filter) => updatedElement.expression.includes(filter) ) ) { diff --git a/x-pack/plugins/canvas/public/state/actions/embeddable.ts b/x-pack/plugins/canvas/public/state/actions/embeddable.ts index 3604d7e3c2141..e2cf588ec20a9 100644 --- a/x-pack/plugins/canvas/public/state/actions/embeddable.ts +++ b/x-pack/plugins/canvas/public/state/actions/embeddable.ts @@ -24,12 +24,12 @@ export const updateEmbeddableExpression = createAction State }, elementId: string) => { - const pageWithElement = getState().persistent.workpad.pages.find(page => { - return page.elements.find(element => element.id === elementId) !== undefined; + const pageWithElement = getState().persistent.workpad.pages.find((page) => { + return page.elements.find((element) => element.id === elementId) !== undefined; }); if (pageWithElement) { - const element = pageWithElement.elements.find(el => el.id === elementId); + const element = pageWithElement.elements.find((el) => el.id === elementId); dispatch(fetchRenderable(element)); } } diff --git a/x-pack/plugins/canvas/public/state/initial_state.js b/x-pack/plugins/canvas/public/state/initial_state.js index bfa68b33908e0..13021893e72e8 100644 --- a/x-pack/plugins/canvas/public/state/initial_state.js +++ b/x-pack/plugins/canvas/public/state/initial_state.js @@ -8,7 +8,7 @@ import { get } from 'lodash'; import { platformService } from '../services'; import { getDefaultWorkpad } from './defaults'; -export const getInitialState = path => { +export const getInitialState = (path) => { const state = { app: {}, // Kibana stuff in here assets: {}, // assets end up here diff --git a/x-pack/plugins/canvas/public/state/middleware/app_ready.js b/x-pack/plugins/canvas/public/state/middleware/app_ready.js index a86f67b5e1cc4..0b2fce4227197 100644 --- a/x-pack/plugins/canvas/public/state/middleware/app_ready.js +++ b/x-pack/plugins/canvas/public/state/middleware/app_ready.js @@ -7,7 +7,7 @@ import { isAppReady } from '../selectors/app'; import { appReady as readyAction } from '../actions/app'; -export const appReady = ({ dispatch, getState }) => next => action => { +export const appReady = ({ dispatch, getState }) => (next) => (action) => { // execute the action next(action); diff --git a/x-pack/plugins/canvas/public/state/middleware/breadcrumbs.js b/x-pack/plugins/canvas/public/state/middleware/breadcrumbs.js index b949e7025acbf..864e61b5a8f96 100644 --- a/x-pack/plugins/canvas/public/state/middleware/breadcrumbs.js +++ b/x-pack/plugins/canvas/public/state/middleware/breadcrumbs.js @@ -7,7 +7,7 @@ import { getWorkpad } from '../selectors/workpad'; import { getBaseBreadcrumb, getWorkpadBreadcrumb, setBreadcrumb } from '../../lib/breadcrumbs'; -export const breadcrumbs = ({ getState }) => next => action => { +export const breadcrumbs = ({ getState }) => (next) => (action) => { // capture the current workpad const currentWorkpad = getWorkpad(getState()); diff --git a/x-pack/plugins/canvas/public/state/middleware/element_stats.js b/x-pack/plugins/canvas/public/state/middleware/element_stats.js index 17ab9393734e0..1c19f26102996 100644 --- a/x-pack/plugins/canvas/public/state/middleware/element_stats.js +++ b/x-pack/plugins/canvas/public/state/middleware/element_stats.js @@ -7,7 +7,7 @@ import { setElementStats } from '../actions/transient'; import { getAllElements, getElementCounts, getElementStats } from '../selectors/workpad'; -export const elementStats = ({ dispatch, getState }) => next => action => { +export const elementStats = ({ dispatch, getState }) => (next) => (action) => { // execute the action next(action); diff --git a/x-pack/plugins/canvas/public/state/middleware/es_persist.js b/x-pack/plugins/canvas/public/state/middleware/es_persist.js index a197cdf893244..e0db595552198 100644 --- a/x-pack/plugins/canvas/public/state/middleware/es_persist.js +++ b/x-pack/plugins/canvas/public/state/middleware/es_persist.js @@ -40,9 +40,9 @@ export const esPersistMiddleware = ({ getState }) => { setRefreshInterval, // used to set refresh time interval which is a transient value ...Object.values(resolvedArgsActions), // no resolved args affect persisted values ...Object.values(transientActions), // no transient actions cause persisted state changes - ].map(a => a.toString()); + ].map((a) => a.toString()); - return next => action => { + return (next) => (action) => { // if the action is in the skipped list, do not persist if (skippedActions.indexOf(action.type) >= 0) { return next(action); @@ -58,7 +58,7 @@ export const esPersistMiddleware = ({ getState }) => { return; } - const notifyError = err => { + const notifyError = (err) => { const statusCode = err.response && err.response.status; switch (statusCode) { case 400: diff --git a/x-pack/plugins/canvas/public/state/middleware/fullscreen.js b/x-pack/plugins/canvas/public/state/middleware/fullscreen.js index 92ac35173b196..dfaf0a5e87b32 100644 --- a/x-pack/plugins/canvas/public/state/middleware/fullscreen.js +++ b/x-pack/plugins/canvas/public/state/middleware/fullscreen.js @@ -9,7 +9,7 @@ import { setFullscreen as setAppStateFullscreen } from '../../lib/app_state'; import { setFullscreen as setFullscreenAction } from '../actions/transient'; import { getFullscreen } from '../selectors/app'; -export const fullscreen = ({ getState }) => next => action => { +export const fullscreen = ({ getState }) => (next) => (action) => { // execute the default action next(action); diff --git a/x-pack/plugins/canvas/public/state/middleware/history.js b/x-pack/plugins/canvas/public/state/middleware/history.js index 206c86e93de91..28eb12e4b68da 100644 --- a/x-pack/plugins/canvas/public/state/middleware/history.js +++ b/x-pack/plugins/canvas/public/state/middleware/history.js @@ -22,8 +22,8 @@ function getHistoryState(state) { export const historyMiddleware = ({ dispatch, getState }) => { // iterate over routes, injecting redux to action handlers - const reduxInject = routes => { - return routes.map(route => { + const reduxInject = (routes) => { + return routes.map((route) => { if (route.children) { return { ...route, @@ -96,7 +96,7 @@ export const historyMiddleware = ({ dispatch, getState }) => { } }); - return next => action => { + return (next) => (action) => { const oldState = getState(); // deal with history actions diff --git a/x-pack/plugins/canvas/public/state/middleware/resolved_args.js b/x-pack/plugins/canvas/public/state/middleware/resolved_args.js index 7dd0404cd5a19..d47a320392039 100644 --- a/x-pack/plugins/canvas/public/state/middleware/resolved_args.js +++ b/x-pack/plugins/canvas/public/state/middleware/resolved_args.js @@ -11,17 +11,17 @@ import { clearValues } from '../actions/resolved_args'; * This middleware is responsible for keeping the resolved_args collection in transient state * synced with the elements represented by the workpad. */ -export const resolvedArgs = ({ dispatch, getState }) => next => action => { +export const resolvedArgs = ({ dispatch, getState }) => (next) => (action) => { // Get the Element IDs that are present before the action. - const startElementIds = getAllElements(getState()).map(element => element.id); + const startElementIds = getAllElements(getState()).map((element) => element.id); // execute the action next(action); // Get the Element IDs after the action... - const resolvedElementIds = getAllElements(getState()).map(element => element.id); + const resolvedElementIds = getAllElements(getState()).map((element) => element.id); // ...and get a list of IDs that are no longer present. - const deadIds = startElementIds.filter(id => !resolvedElementIds.includes(id)); + const deadIds = startElementIds.filter((id) => !resolvedElementIds.includes(id)); // If we have some dead elements, we need to clear them from resolved_args collection // in transient state. diff --git a/x-pack/plugins/canvas/public/state/middleware/workpad_autoplay.ts b/x-pack/plugins/canvas/public/state/middleware/workpad_autoplay.ts index 700905213f54c..1fdfcacaa2244 100644 --- a/x-pack/plugins/canvas/public/state/middleware/workpad_autoplay.ts +++ b/x-pack/plugins/canvas/public/state/middleware/workpad_autoplay.ts @@ -14,7 +14,7 @@ import { routerProvider } from '../../lib/router_provider'; import { setAutoplayInterval } from '../../lib/app_state'; import { createTimeInterval } from '../../lib/time_interval'; -export const workpadAutoplay: Middleware<{}, State> = ({ getState }) => next => { +export const workpadAutoplay: Middleware<{}, State> = ({ getState }) => (next) => { let playTimeout: number | undefined; let displayInterval = 0; @@ -62,7 +62,7 @@ export const workpadAutoplay: Middleware<{}, State> = ({ getState }) => next => } } - return action => { + return (action) => { next(action); const isFullscreen = getFullscreen(getState()); diff --git a/x-pack/plugins/canvas/public/state/middleware/workpad_refresh.ts b/x-pack/plugins/canvas/public/state/middleware/workpad_refresh.ts index f638c42ec2de0..54ebec0dfbbb6 100644 --- a/x-pack/plugins/canvas/public/state/middleware/workpad_refresh.ts +++ b/x-pack/plugins/canvas/public/state/middleware/workpad_refresh.ts @@ -16,7 +16,7 @@ import { getRefreshInterval } from '../selectors/workpad'; import { setRefreshInterval as setAppStateRefreshInterval } from '../../lib/app_state'; import { createTimeInterval } from '../../lib/time_interval'; -export const workpadRefresh: Middleware<{}, State> = ({ dispatch, getState }) => next => { +export const workpadRefresh: Middleware<{}, State> = ({ dispatch, getState }) => (next) => { let refreshTimeout: number | undefined; let refreshInterval = 0; @@ -52,7 +52,7 @@ export const workpadRefresh: Middleware<{}, State> = ({ dispatch, getState }) => } } - return action => { + return (action) => { const previousRefreshInterval = getRefreshInterval(getState()); next(action); diff --git a/x-pack/plugins/canvas/public/state/middleware/workpad_update.js b/x-pack/plugins/canvas/public/state/middleware/workpad_update.js index 76d699c68a19d..88c5b502b3bad 100644 --- a/x-pack/plugins/canvas/public/state/middleware/workpad_update.js +++ b/x-pack/plugins/canvas/public/state/middleware/workpad_update.js @@ -11,7 +11,7 @@ import { getWorkpadName, isWriteable } from '../selectors/workpad'; import { getWindow } from '../../lib/get_window'; import { setDocTitle } from '../../lib/doc_title'; -export const workpadUpdate = ({ dispatch, getState }) => next => action => { +export const workpadUpdate = ({ dispatch, getState }) => (next) => (action) => { const oldIsWriteable = isWriteable(getState()); const oldName = getWorkpadName(getState()); diff --git a/x-pack/plugins/canvas/public/state/reducers/__tests__/fixtures/action_creator.js b/x-pack/plugins/canvas/public/state/reducers/__tests__/fixtures/action_creator.js index b95186cdce99e..1e734c8261e4d 100644 --- a/x-pack/plugins/canvas/public/state/reducers/__tests__/fixtures/action_creator.js +++ b/x-pack/plugins/canvas/public/state/reducers/__tests__/fixtures/action_creator.js @@ -4,6 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -export const actionCreator = type => { +export const actionCreator = (type) => { return (payload, error = null, meta = null) => ({ type, payload, error, meta }); }; diff --git a/x-pack/plugins/canvas/public/state/reducers/app.js b/x-pack/plugins/canvas/public/state/reducers/app.js index 8027bac4e1b09..18c8ba995ac69 100644 --- a/x-pack/plugins/canvas/public/state/reducers/app.js +++ b/x-pack/plugins/canvas/public/state/reducers/app.js @@ -9,7 +9,7 @@ import { appReady, appError } from '../actions/app'; export const appReducer = handleActions( { - [appReady]: appState => ({ ...appState, ready: true }), + [appReady]: (appState) => ({ ...appState, ready: true }), [appError]: (appState, { payload }) => ({ ...appState, ready: payload }), }, {} diff --git a/x-pack/plugins/canvas/public/state/reducers/elements.js b/x-pack/plugins/canvas/public/state/reducers/elements.js index 630694a860aad..5d6bba1ab7406 100644 --- a/x-pack/plugins/canvas/public/state/reducers/elements.js +++ b/x-pack/plugins/canvas/public/state/reducers/elements.js @@ -11,28 +11,28 @@ import * as actions from '../actions/elements'; const { assign, push, del, set } = immutable; -const getLocation = type => (type === 'group' ? 'groups' : 'elements'); +const getLocation = (type) => (type === 'group' ? 'groups' : 'elements'); const firstOccurrence = (element, index, array) => array.indexOf(element) === index; const getLocationFromIds = (workpadState, pageId, nodeId) => { - const page = workpadState.pages.find(p => p.id === pageId); + const page = workpadState.pages.find((p) => p.id === pageId); const groups = page == null ? [] : page.groups || []; - return groups.find(e => e.id === nodeId) ? 'groups' : 'elements'; + return groups.find((e) => e.id === nodeId) ? 'groups' : 'elements'; }; function getPageIndexById(workpadState, pageId) { - return get(workpadState, 'pages', []).findIndex(page => page.id === pageId); + return get(workpadState, 'pages', []).findIndex((page) => page.id === pageId); } function getNodeIndexById(page, nodeId, location) { - return page[location].findIndex(node => node.id === nodeId); + return page[location].findIndex((node) => node.id === nodeId); } export function assignNodeProperties(workpadState, pageId, nodeId, props) { const pageIndex = getPageIndexById(workpadState, pageId); const location = getLocationFromIds(workpadState, pageId, nodeId); const nodesPath = `pages.${pageIndex}.${location}`; - const nodeIndex = get(workpadState, nodesPath, []).findIndex(node => node.id === nodeId); + const nodeIndex = get(workpadState, nodesPath, []).findIndex((node) => node.id === nodeId); if (pageIndex === -1 || nodeIndex === -1) { return workpadState; @@ -47,7 +47,7 @@ function moveNodeLayer(workpadState, pageId, nodeId, movement, location) { const nodes = get(workpadState, ['pages', pageIndex, location]); const from = nodeIndex; - const to = (function() { + const to = (function () { if (movement < Infinity && movement > -Infinity) { return nodeIndex + movement; } @@ -88,8 +88,8 @@ const trimElement = ({ id, position, expression, filter }) => ({ }); const getPageWithElementId = (workpad, elementId) => { - const matchingPage = workpad.pages.find(page => - page.elements.map(element => element.id).includes(elementId) + const matchingPage = workpad.pages.find((page) => + page.elements.map((element) => element.id).includes(elementId) ); if (matchingPage) { @@ -131,7 +131,7 @@ export const elementsReducer = handleActions( if ( // don't add a group that is already persisted workpadState.pages[pageIndex][getLocation(element.position.type)].find( - e => e.id === element.id + (e) => e.id === element.id ) ) { return workpadState; @@ -165,7 +165,7 @@ export const elementsReducer = handleActions( const nodeIndices = elementIds .filter(firstOccurrence) - .map(nodeId => { + .map((nodeId) => { const location = getLocationFromIds(workpadState, pageId, nodeId); return { location, diff --git a/x-pack/plugins/canvas/public/state/reducers/embeddable.ts b/x-pack/plugins/canvas/public/state/reducers/embeddable.ts index 9969c38cfa767..8642239fa10d3 100644 --- a/x-pack/plugins/canvas/public/state/reducers/embeddable.ts +++ b/x-pack/plugins/canvas/public/state/reducers/embeddable.ts @@ -29,15 +29,15 @@ export const embeddableReducer = handleActions< const { elementId, embeddableExpression } = payload; // Find the element - const pageWithElement = workpadState.pages.find(page => { - return page.elements.find(element => element.id === elementId) !== undefined; + const pageWithElement = workpadState.pages.find((page) => { + return page.elements.find((element) => element.id === elementId) !== undefined; }); if (!pageWithElement) { return workpadState; } - const element = pageWithElement.elements.find(elem => elem.id === elementId); + const element = pageWithElement.elements.find((elem) => elem.id === elementId); if (!element) { return workpadState; @@ -48,7 +48,7 @@ export const embeddableReducer = handleActions< const searchForFunction = newAst.chain[0].function; // Find the first matching function in the existing ASt - const existingAstFunction = existingAst.chain.find(f => f.function === searchForFunction); + const existingAstFunction = existingAst.chain.find((f) => f.function === searchForFunction); if (!existingAstFunction) { return workpadState; diff --git a/x-pack/plugins/canvas/public/state/reducers/pages.js b/x-pack/plugins/canvas/public/state/reducers/pages.js index 50a28475ef5bc..afcca8f54b5aa 100644 --- a/x-pack/plugins/canvas/public/state/reducers/pages.js +++ b/x-pack/plugins/canvas/public/state/reducers/pages.js @@ -22,7 +22,7 @@ const setPageIndex = (workpadState, index) => : set(workpadState, 'page', index); function getPageIndexById(workpadState, id) { - return workpadState.pages.findIndex(page => page.id === id); + return workpadState.pages.findIndex((page) => page.id === id); } function addPage(workpadState, payload, srcIndex = workpadState.pages.length - 1) { @@ -39,8 +39,8 @@ function clonePage(page) { return { ...page, id: getId('page'), - groups: newNodes.filter(n => isGroupId(n.id)), - elements: newNodes.filter(n => !isGroupId(n.id)), + groups: newNodes.filter((n) => isGroupId(n.id)), + elements: newNodes.filter((n) => !isGroupId(n.id)), }; } @@ -59,7 +59,7 @@ export const pagesReducer = handleActions( }, [actions.duplicatePage]: (workpadState, { payload }) => { - const srcPage = workpadState.pages.find(page => page.id === payload); + const srcPage = workpadState.pages.find((page) => page.id === payload); // if the page id is invalid, don't change the state if (!srcPage) { @@ -103,7 +103,7 @@ export const pagesReducer = handleActions( // adjust the selected page index and return the new state const selectedId = workpadState.pages[workpadState.page].id; - const newSelectedIndex = newState.pages.findIndex(page => page.id === selectedId); + const newSelectedIndex = newState.pages.findIndex((page) => page.id === selectedId); newState = set(newState, 'page', newSelectedIndex); // changes to the page require navigation @@ -144,12 +144,12 @@ export const pagesReducer = handleActions( }, [actions.stylePage]: (workpadState, { payload }) => { - const pageIndex = workpadState.pages.findIndex(page => page.id === payload.pageId); + const pageIndex = workpadState.pages.findIndex((page) => page.id === payload.pageId); return set(workpadState, `pages.${pageIndex}.style`, payload.style); }, [actions.setPageTransition]: (workpadState, { payload }) => { - const pageIndex = workpadState.pages.findIndex(page => page.id === payload.pageId); + const pageIndex = workpadState.pages.findIndex((page) => page.id === payload.pageId); return set(workpadState, `pages.${pageIndex}.transition`, payload.transition); }, }, diff --git a/x-pack/plugins/canvas/public/state/reducers/resolved_args.js b/x-pack/plugins/canvas/public/state/reducers/resolved_args.js index fa0be7702765d..0b020069aa8bc 100644 --- a/x-pack/plugins/canvas/public/state/reducers/resolved_args.js +++ b/x-pack/plugins/canvas/public/state/reducers/resolved_args.js @@ -102,11 +102,11 @@ export const resolvedArgsReducer = handleActions( }, transientState); }, - [actions.inFlightActive]: transientState => { + [actions.inFlightActive]: (transientState) => { return set(transientState, 'inFlight', true); }, - [actions.inFlightComplete]: transientState => { + [actions.inFlightComplete]: (transientState) => { return set(transientState, 'inFlight', false); }, diff --git a/x-pack/plugins/canvas/public/state/reducers/transient.js b/x-pack/plugins/canvas/public/state/reducers/transient.js index 0b89dfd3c9564..c6a4466eeb145 100644 --- a/x-pack/plugins/canvas/public/state/reducers/transient.js +++ b/x-pack/plugins/canvas/public/state/reducers/transient.js @@ -18,14 +18,14 @@ export const transientReducer = handleActions( { // clear all the resolved args when restoring the history // TODO: we shouldn't need to reset the resolved args for history - [restoreHistory]: transientState => set(transientState, 'resolvedArgs', {}), + [restoreHistory]: (transientState) => set(transientState, 'resolvedArgs', {}), [removeElements]: (transientState, { payload: { elementIds } }) => { const { selectedToplevelNodes } = transientState; return del( { ...transientState, - selectedToplevelNodes: selectedToplevelNodes.filter(n => elementIds.indexOf(n) < 0), + selectedToplevelNodes: selectedToplevelNodes.filter((n) => elementIds.indexOf(n) < 0), }, ['resolvedArgs', elementIds] ); @@ -57,15 +57,15 @@ export const transientReducer = handleActions( }; }, - [pageActions.setPage]: transientState => { + [pageActions.setPage]: (transientState) => { return { ...transientState, selectedToplevelNodes: [] }; }, - [pageActions.addPage]: transientState => { + [pageActions.addPage]: (transientState) => { return { ...transientState, selectedToplevelNodes: [] }; }, - [pageActions.duplicatePage]: transientState => { + [pageActions.duplicatePage]: (transientState) => { return { ...transientState, selectedToplevelNodes: [] }; }, diff --git a/x-pack/plugins/canvas/public/state/selectors/__tests__/workpad.js b/x-pack/plugins/canvas/public/state/selectors/__tests__/workpad.js index cf22a2c81c35f..5fdc662c592cc 100644 --- a/x-pack/plugins/canvas/public/state/selectors/__tests__/workpad.js +++ b/x-pack/plugins/canvas/public/state/selectors/__tests__/workpad.js @@ -175,7 +175,7 @@ describe('workpad selectors', () => { it('returns all elements on the page', () => { const { elements } = state.persistent.workpad.pages[0]; - const expected = elements.map(element => ({ + const expected = elements.map((element) => ({ ...element, ast: asts[element.id], })); diff --git a/x-pack/plugins/canvas/public/state/selectors/workpad.ts b/x-pack/plugins/canvas/public/state/selectors/workpad.ts index ae5c0fee52062..4b3431e59a34e 100644 --- a/x-pack/plugins/canvas/public/state/selectors/workpad.ts +++ b/x-pack/plugins/canvas/public/state/selectors/workpad.ts @@ -74,12 +74,12 @@ export function getPages(state: State): State['persistent']['workpad']['pages'] export function getPageById(state: State, id: string): CanvasPage | undefined { const pages = getPages(state); - return pages.find(page => page.id === id); + return pages.find((page) => page.id === id); } export function getPageIndexById(state: State, id: string): number { const pages = getPages(state); - return pages.findIndex(page => page.id === id); + return pages.findIndex((page) => page.id === id); } export function getWorkpadName(state: State): string { @@ -151,7 +151,7 @@ export function getElementCounts(state: State) { .filter( (maybeResolvedArg): maybeResolvedArg is ResolvedArgType => maybeResolvedArg !== undefined ) - .forEach(resolvedArg => { + .forEach((resolvedArg) => { const { expressionRenderable } = resolvedArg; if (!expressionRenderable) { @@ -224,7 +224,7 @@ function extractFilterGroups( if (fn === 'filters') { // we have a filter function, extract groups from args return groups.concat( - buildGroupValues(args, argValue => { + buildGroupValues(args, (argValue) => { // this only handles simple values if (argValue !== null && typeof argValue !== 'object') { return argValue; @@ -234,7 +234,7 @@ function extractFilterGroups( } else { // dig into other functions, looking for filters function return groups.concat( - buildGroupValues(args, argValue => { + buildGroupValues(args, (argValue) => { // recursively collect filter groups if (argValue !== null && typeof argValue === 'object' && argValue.type === 'expression') { return extractFilterGroups(argValue); @@ -268,7 +268,7 @@ export function getGlobalFilterGroups(state: State) { | ExpressionAstFunction | ExpressionAstExpression; const groups = extractFilterGroups(expressionAst); - groups.forEach(group => { + groups.forEach((group) => { if (!acc.includes(String(group))) { acc.push(String(group)); } @@ -318,7 +318,7 @@ export function getElements( // due to https://github.com/elastic/kibana-canvas/issues/260 // TODO: remove this once it's been in the wild a bit if (!withAst) { - return elements.map(el => omit(el, ['ast'])); + return elements.map((el) => omit(el, ['ast'])); } return elements.map(appendAst); @@ -354,7 +354,7 @@ export function getNodesForPage(page: CanvasPage, withAst: boolean): CanvasEleme // due to https://github.com/elastic/kibana-canvas/issues/260 // TODO: remove this once it's been in the wild a bit if (!withAst) { - return elements.map(el => omit(el, ['ast'])); + return elements.map((el) => omit(el, ['ast'])); } return elements.map(appendAst); @@ -384,7 +384,7 @@ export function getElementById( id: string | null, pageId?: string ): PositionedElement | undefined { - const element = getElements(state, pageId, true).find(el => el.id === id); + const element = getElements(state, pageId, true).find((el) => el.id === id); if (element) { return appendAst(element); } @@ -396,7 +396,7 @@ export function getNodeById( pageId: string ): PositionedElement | undefined { // do we need to pass a truthy empty array instead of `true`? - const group = getNodes(state, pageId, true).find(el => el.id === id); + const group = getNodes(state, pageId, true).find((el) => el.id === id); if (group) { return appendAst(group); } @@ -437,11 +437,11 @@ export function getAutoplay(state: State): State['transient']['autoplay'] { export function getRenderedWorkpad(state: State) { const currentPages = getPages(state); const args = state.transient.resolvedArgs; - const renderedPages = currentPages.map(page => { + const renderedPages = currentPages.map((page) => { const { elements, ...rest } = page; return { ...rest, - elements: elements.map(element => { + elements: elements.map((element) => { const { id, position } = element; const arg = args[id]; if (!arg) { @@ -470,8 +470,8 @@ export function getRenderedWorkpadExpressions(state: State) { const { pages } = workpad; const expressions: string[] = []; - pages.forEach(page => - page.elements.forEach(element => { + pages.forEach((page) => + page.elements.forEach((element) => { if (element && element.expressionRenderable) { const { value } = element.expressionRenderable; if (value) { diff --git a/x-pack/plugins/canvas/public/state/store.js b/x-pack/plugins/canvas/public/state/store.js index 891f30ca4114f..4995db0ae84a5 100644 --- a/x-pack/plugins/canvas/public/state/store.js +++ b/x-pack/plugins/canvas/public/state/store.js @@ -29,7 +29,7 @@ export function createStore(initialState) { export function destroyStore() { if (store) { // Replace reducer so that anything that gets fired after navigating away doesn't really do anything - store.replaceReducer(state => state); + store.replaceReducer((state) => state); } store = undefined; } diff --git a/x-pack/plugins/canvas/scripts/_helpers.js b/x-pack/plugins/canvas/scripts/_helpers.js index 0f4b07d988308..7f386edc49117 100644 --- a/x-pack/plugins/canvas/scripts/_helpers.js +++ b/x-pack/plugins/canvas/scripts/_helpers.js @@ -6,19 +6,19 @@ const { resolve } = require('path'); -exports.runGulpTask = function(name) { +exports.runGulpTask = function (name) { process.chdir(resolve(__dirname, '../../..')); process.argv.splice(1, 1, require.resolve('gulp/bin/gulp'), name); require('gulp/bin/gulp'); }; -exports.runKibanaScript = function(name, args = []) { +exports.runKibanaScript = function (name, args = []) { process.chdir(resolve(__dirname, '../../../..')); process.argv.splice(2, 0, ...args); require('../../../../scripts/' + name); // eslint-disable-line import/no-dynamic-require }; -exports.runXPackScript = function(name, args = []) { +exports.runXPackScript = function (name, args = []) { process.chdir(resolve(__dirname, '../../..')); process.argv.splice(2, 0, ...args); require('../../../scripts/' + name); // eslint-disable-line import/no-dynamic-require diff --git a/x-pack/plugins/canvas/server/collectors/collector.ts b/x-pack/plugins/canvas/server/collectors/collector.ts index 88e5e43dc2af1..e266e9826a47d 100644 --- a/x-pack/plugins/canvas/server/collectors/collector.ts +++ b/x-pack/plugins/canvas/server/collectors/collector.ts @@ -35,7 +35,7 @@ export function registerCanvasUsageCollector( isReady: () => true, fetch: async (callCluster: CallCluster) => { const collectorResults = await Promise.all( - collectors.map(collector => collector(kibanaIndex, callCluster)) + collectors.map((collector) => collector(kibanaIndex, callCluster)) ); return collectorResults.reduce( diff --git a/x-pack/plugins/canvas/server/collectors/collector_helpers.ts b/x-pack/plugins/canvas/server/collectors/collector_helpers.ts index 73de691dae05f..a6b04661f3da1 100644 --- a/x-pack/plugins/canvas/server/collectors/collector_helpers.ts +++ b/x-pack/plugins/canvas/server/collectors/collector_helpers.ts @@ -27,8 +27,8 @@ export function collectFns(ast: ExpressionAstNode, cb: (functionName: string) => cb(cFunction); // recurse the arguments and update the set along the way - Object.keys(cArguments).forEach(argName => { - cArguments[argName].forEach(subAst => { + Object.keys(cArguments).forEach((argName) => { + cArguments[argName].forEach((subAst) => { if (subAst != null) { collectFns(subAst, cb); } diff --git a/x-pack/plugins/canvas/server/collectors/custom_element_collector.test.ts b/x-pack/plugins/canvas/server/collectors/custom_element_collector.test.ts index f09bb704b09e3..ae65eb42bb20d 100644 --- a/x-pack/plugins/canvas/server/collectors/custom_element_collector.test.ts +++ b/x-pack/plugins/canvas/server/collectors/custom_element_collector.test.ts @@ -10,7 +10,7 @@ import { TelemetryCustomElementDocument } from '../../types'; function mockCustomElement(...nodeExpressions: string[]): TelemetryCustomElementDocument { return { content: JSON.stringify({ - selectedNodes: nodeExpressions.map(expression => ({ + selectedNodes: nodeExpressions.map((expression) => ({ expression, })), }), diff --git a/x-pack/plugins/canvas/server/collectors/custom_element_collector.ts b/x-pack/plugins/canvas/server/collectors/custom_element_collector.ts index ae71600d24e4b..3ada8e7b4efdc 100644 --- a/x-pack/plugins/canvas/server/collectors/custom_element_collector.ts +++ b/x-pack/plugins/canvas/server/collectors/custom_element_collector.ts @@ -60,7 +60,7 @@ export function summarizeCustomElements( const functionSet = new Set(); const parsedContents: TelemetryCustomElement[] = customElements - .map(element => element.content) + .map((element) => element.content) .map(parseJsonOrNull) .filter(isCustomElement); @@ -76,8 +76,8 @@ export function summarizeCustomElements( let totalElements = 0; - parsedContents.map(contents => { - contents.selectedNodes.map(node => { + parsedContents.map((contents) => { + contents.selectedNodes.map((node) => { const ast = parseExpression(node.expression); collectFns(ast, (cFunction: string) => { functionSet.add(cFunction); @@ -114,7 +114,7 @@ const customElementCollector: TelemetryCollector = async function customElementC const esResponse = await callCluster('search', customElementParams); if (get(esResponse, 'hits.hits.length') > 0) { - const customElements = esResponse.hits.hits.map(hit => hit._source[CUSTOM_ELEMENT_TYPE]); + const customElements = esResponse.hits.hits.map((hit) => hit._source[CUSTOM_ELEMENT_TYPE]); return summarizeCustomElements(customElements); } diff --git a/x-pack/plugins/canvas/server/collectors/workpad_collector.ts b/x-pack/plugins/canvas/server/collectors/workpad_collector.ts index b14a35ded4781..3d394afaeba50 100644 --- a/x-pack/plugins/canvas/server/collectors/workpad_collector.ts +++ b/x-pack/plugins/canvas/server/collectors/workpad_collector.ts @@ -59,7 +59,7 @@ export function summarizeWorkpads(workpadDocs: CanvasWorkpad[]): WorkpadTelemetr } // make a summary of info about each workpad - const workpadsInfo = workpadDocs.map(workpad => { + const workpadsInfo = workpadDocs.map((workpad) => { let pages = { count: 0 }; try { pages = { count: workpad.pages.length }; @@ -72,9 +72,9 @@ export function summarizeWorkpads(workpadDocs: CanvasWorkpad[]): WorkpadTelemetr [] ); const functionCounts = workpad.pages.reduce((accum, page) => { - return page.elements.map(element => { + return page.elements.map((element) => { const ast = parseExpression(element.expression); - collectFns(ast, cFunction => { + collectFns(ast, (cFunction) => { functionSet.add(cFunction); }); return ast.chain.length; // get the number of parts in the expression @@ -159,7 +159,7 @@ export function summarizeWorkpads(workpadDocs: CanvasWorkpad[]): WorkpadTelemetr }; } -const workpadCollector: TelemetryCollector = async function(kibanaIndex, callCluster) { +const workpadCollector: TelemetryCollector = async function (kibanaIndex, callCluster) { const searchParams: SearchParams = { size: 10000, // elasticsearch index.max_result_window default value index: kibanaIndex, @@ -171,7 +171,7 @@ const workpadCollector: TelemetryCollector = async function(kibanaIndex, callClu const esResponse = await callCluster('search', searchParams); if (get(esResponse, 'hits.hits.length') > 0) { - const workpads = esResponse.hits.hits.map(hit => hit._source[CANVAS_TYPE]); + const workpads = esResponse.hits.hits.map((hit) => hit._source[CANVAS_TYPE]); return summarizeWorkpads(workpads); } diff --git a/x-pack/plugins/canvas/server/lib/build_bool_array.js b/x-pack/plugins/canvas/server/lib/build_bool_array.js index 2dc6447753526..f1cab93ceebbb 100644 --- a/x-pack/plugins/canvas/server/lib/build_bool_array.js +++ b/x-pack/plugins/canvas/server/lib/build_bool_array.js @@ -6,11 +6,11 @@ import { getESFilter } from './get_es_filter'; -const compact = arr => (Array.isArray(arr) ? arr.filter(val => Boolean(val)) : []); +const compact = (arr) => (Array.isArray(arr) ? arr.filter((val) => Boolean(val)) : []); export function buildBoolArray(canvasQueryFilterArray) { return compact( - canvasQueryFilterArray.map(clause => { + canvasQueryFilterArray.map((clause) => { try { return getESFilter(clause); } catch (e) { diff --git a/x-pack/plugins/canvas/server/lib/format_response.js b/x-pack/plugins/canvas/server/lib/format_response.js index d52e2819465fe..a317ca8be56f8 100644 --- a/x-pack/plugins/canvas/server/lib/format_response.js +++ b/x-pack/plugins/canvas/server/lib/format_response.js @@ -5,7 +5,7 @@ */ import boom from 'boom'; -export const formatResponse = esErrors => resp => { +export const formatResponse = (esErrors) => (resp) => { if (resp.isBoom) { return resp; } // can't wrap it if it's already a boom error diff --git a/x-pack/plugins/canvas/server/lib/normalize_type.js b/x-pack/plugins/canvas/server/lib/normalize_type.js index 07f1cac0f7819..fda2fbe631646 100644 --- a/x-pack/plugins/canvas/server/lib/normalize_type.js +++ b/x-pack/plugins/canvas/server/lib/normalize_type.js @@ -24,7 +24,7 @@ export function normalizeType(type) { null: ['null'], }; - const normalizedType = Object.keys(normalTypes).find(t => normalTypes[t].includes(type)); + const normalizedType = Object.keys(normalTypes).find((t) => normalTypes[t].includes(type)); if (normalizedType) { return normalizedType; diff --git a/x-pack/plugins/canvas/server/lib/query_es_sql.js b/x-pack/plugins/canvas/server/lib/query_es_sql.js index f7907e2cffb26..442703b00ea3a 100644 --- a/x-pack/plugins/canvas/server/lib/query_es_sql.js +++ b/x-pack/plugins/canvas/server/lib/query_es_sql.js @@ -24,12 +24,12 @@ export const queryEsSQL = (elasticsearchClient, { count, query, filter, timezone }, }, }) - .then(res => { + .then((res) => { const columns = res.columns.map(({ name, type }) => { return { name: sanitizeName(name), type: normalizeType(type) }; }); const columnNames = map(columns, 'name'); - const rows = res.rows.map(row => zipObject(columnNames, row)); + const rows = res.rows.map((row) => zipObject(columnNames, row)); if (!!res.cursor) { elasticsearchClient('transport.request', { @@ -38,7 +38,7 @@ export const queryEsSQL = (elasticsearchClient, { count, query, filter, timezone body: { cursor: res.cursor, }, - }).catch(e => { + }).catch((e) => { throw new Error(`Unexpected error from Elasticsearch: ${e.message}`); }); } @@ -49,7 +49,7 @@ export const queryEsSQL = (elasticsearchClient, { count, query, filter, timezone rows, }; }) - .catch(e => { + .catch((e) => { if (e.message.indexOf('parsing_exception') > -1) { throw new Error( `Couldn't parse Elasticsearch SQL query. You may need to add double quotes to names containing special characters. Check your query and try again. Error: ${e.message}` diff --git a/x-pack/plugins/canvas/server/lib/sanitize_name.js b/x-pack/plugins/canvas/server/lib/sanitize_name.js index 623b64ca04ae8..295315c3ceb2e 100644 --- a/x-pack/plugins/canvas/server/lib/sanitize_name.js +++ b/x-pack/plugins/canvas/server/lib/sanitize_name.js @@ -7,7 +7,7 @@ export function sanitizeName(name) { // blacklisted characters const blacklist = ['(', ')']; - const pattern = blacklist.map(v => escapeRegExp(v)).join('|'); + const pattern = blacklist.map((v) => escapeRegExp(v)).join('|'); const regex = new RegExp(pattern, 'g'); return name.replace(regex, '_'); } diff --git a/x-pack/plugins/canvas/server/routes/catch_error_handler.ts b/x-pack/plugins/canvas/server/routes/catch_error_handler.ts index 4717d8762ffe2..6c684449be5ca 100644 --- a/x-pack/plugins/canvas/server/routes/catch_error_handler.ts +++ b/x-pack/plugins/canvas/server/routes/catch_error_handler.ts @@ -8,7 +8,7 @@ import { RequestHandler } from 'src/core/server'; export const catchErrorHandler: ( fn: RequestHandler -) => RequestHandler = fn => { +) => RequestHandler = (fn) => { return async (context, request, response) => { try { return await fn(context, request, response); diff --git a/x-pack/plugins/canvas/server/routes/custom_elements/find.ts b/x-pack/plugins/canvas/server/routes/custom_elements/find.ts index 964618adf165d..bd5f226bda57c 100644 --- a/x-pack/plugins/canvas/server/routes/custom_elements/find.ts +++ b/x-pack/plugins/canvas/server/routes/custom_elements/find.ts @@ -50,7 +50,7 @@ export function initializeFindCustomElementsRoute(deps: RouteInitializerDeps) { return response.ok({ body: { total: customElements.total, - customElements: customElements.saved_objects.map(hit => ({ + customElements: customElements.saved_objects.map((hit) => ({ id: hit.id, ...hit.attributes, })), diff --git a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts index 5ebf20095bf3e..e13b19610213e 100644 --- a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts +++ b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.ts @@ -36,8 +36,8 @@ export function initializeESFieldsRoute(deps: RouteInitializerDeps) { fields: fields || '*', }; - const esFields = await callAsCurrentUser('fieldCaps', config).then(resp => { - return mapValues(resp.fields, types => { + const esFields = await callAsCurrentUser('fieldCaps', config).then((resp) => { + return mapValues(resp.fields, (types) => { if (keys(types).length > 1) { return 'conflict'; } diff --git a/x-pack/plugins/canvas/server/routes/workpad/find.ts b/x-pack/plugins/canvas/server/routes/workpad/find.ts index ec5c068a1fa24..b17d5d7d4bb39 100644 --- a/x-pack/plugins/canvas/server/routes/workpad/find.ts +++ b/x-pack/plugins/canvas/server/routes/workpad/find.ts @@ -41,7 +41,7 @@ export function initializeFindWorkpadsRoute(deps: RouteInitializerDeps) { return response.ok({ body: { total: workpads.total, - workpads: workpads.saved_objects.map(hit => ({ id: hit.id, ...hit.attributes })), + workpads: workpads.saved_objects.map((hit) => ({ id: hit.id, ...hit.attributes })), }, }); } catch (error) { diff --git a/x-pack/plugins/canvas/server/routes/workpad/get.ts b/x-pack/plugins/canvas/server/routes/workpad/get.ts index 7dc1252063e90..e4c0d162782f0 100644 --- a/x-pack/plugins/canvas/server/routes/workpad/get.ts +++ b/x-pack/plugins/canvas/server/routes/workpad/get.ts @@ -34,7 +34,7 @@ export function initializeGetWorkpadRoute(deps: RouteInitializerDeps) { workpad.attributes.pages && workpad.attributes.pages.length ) { - workpad.attributes.pages.forEach(page => { + workpad.attributes.pages.forEach((page) => { const elements = (page.elements || []).filter( ({ id: pageId }) => !pageId.startsWith('group') ); diff --git a/x-pack/plugins/canvas/server/sample_data/load_sample_data.ts b/x-pack/plugins/canvas/server/sample_data/load_sample_data.ts index 6eda02ef41722..f58111000859a 100644 --- a/x-pack/plugins/canvas/server/sample_data/load_sample_data.ts +++ b/x-pack/plugins/canvas/server/sample_data/load_sample_data.ts @@ -19,7 +19,7 @@ export function loadSampleData( // @ts-ignore: Untyped local function updateCanvasWorkpadTimestamps(savedObjects) { // @ts-ignore: Untyped local - return savedObjects.map(savedObject => { + return savedObjects.map((savedObject) => { if (savedObject.type === 'canvas-workpad') { savedObject.attributes['@timestamp'] = nowTimestamp; savedObject.attributes['@created'] = nowTimestamp; diff --git a/x-pack/plugins/canvas/server/saved_objects/migrations/remove_attributes_id.ts b/x-pack/plugins/canvas/server/saved_objects/migrations/remove_attributes_id.ts index 893a73d7b5913..306224ce05bbf 100644 --- a/x-pack/plugins/canvas/server/saved_objects/migrations/remove_attributes_id.ts +++ b/x-pack/plugins/canvas/server/saved_objects/migrations/remove_attributes_id.ts @@ -6,7 +6,7 @@ import { SavedObjectMigrationFn } from 'src/core/server'; -export const removeAttributesId: SavedObjectMigrationFn = doc => { +export const removeAttributesId: SavedObjectMigrationFn = (doc) => { if (typeof doc.attributes === 'object' && doc.attributes !== null) { delete (doc.attributes as any).id; } diff --git a/x-pack/plugins/canvas/shareable_runtime/__mocks__/supported_renderers.js b/x-pack/plugins/canvas/shareable_runtime/__mocks__/supported_renderers.js index 051082107a2e6..6792568583617 100644 --- a/x-pack/plugins/canvas/shareable_runtime/__mocks__/supported_renderers.js +++ b/x-pack/plugins/canvas/shareable_runtime/__mocks__/supported_renderers.js @@ -27,12 +27,12 @@ const renderers = [ * Mock all of the render functions to return a `div` containing * a predictable string. */ -export const renderFunctions = renderers.map(fn => () => ({ +export const renderFunctions = renderers.map((fn) => () => ({ name: fn, displayName: fn, help: fn, reuseDomNode: true, - render: domNode => { + render: (domNode) => { ReactDOM.render(
{fn} mock
, domNode); }, })); diff --git a/x-pack/plugins/canvas/shareable_runtime/api/__tests__/shareable.test.tsx b/x-pack/plugins/canvas/shareable_runtime/api/__tests__/shareable.test.tsx index a55c87c2d74a2..d99c9b190f83d 100644 --- a/x-pack/plugins/canvas/shareable_runtime/api/__tests__/shareable.test.tsx +++ b/x-pack/plugins/canvas/shareable_runtime/api/__tests__/shareable.test.tsx @@ -14,7 +14,7 @@ jest.mock('../../supported_renderers'); describe('Canvas Shareable Workpad API', () => { // Mock the AJAX load of the workpad. - beforeEach(function() { + beforeEach(function () { // @ts-ignore Applying a global in Jest is alright. global.fetch = jest.fn().mockImplementation(() => { const p = new Promise((resolve, _reject) => { diff --git a/x-pack/plugins/canvas/shareable_runtime/api/shareable.tsx b/x-pack/plugins/canvas/shareable_runtime/api/shareable.tsx index 11289d3c37970..96acee401d52d 100644 --- a/x-pack/plugins/canvas/shareable_runtime/api/shareable.tsx +++ b/x-pack/plugins/canvas/shareable_runtime/api/shareable.tsx @@ -63,7 +63,7 @@ const VALID_ATTRIBUTES = ['url', 'page', 'height', 'width', 'autoplay', 'interva // Collect and then remove valid data attributes. const getAttributes = (element: Element, attributes: string[]) => { const result: { [key: string]: string } = {}; - attributes.forEach(attribute => { + attributes.forEach((attribute) => { const key = `${PREFIX}-${attribute}`; const value = element.getAttribute(key); @@ -150,7 +150,7 @@ const updateArea = async (area: Element) => { export const share = () => { const shareAreas = document.querySelectorAll(`[${SHAREABLE}]`); const validAreas = Array.from(shareAreas).filter( - area => area.getAttribute(SHAREABLE) === 'canvas' + (area) => area.getAttribute(SHAREABLE) === 'canvas' ); validAreas.forEach(updateArea); diff --git a/x-pack/plugins/canvas/shareable_runtime/components/app.tsx b/x-pack/plugins/canvas/shareable_runtime/components/app.tsx index 1779ec4846cb7..fdc64d32cf8e5 100644 --- a/x-pack/plugins/canvas/shareable_runtime/components/app.tsx +++ b/x-pack/plugins/canvas/shareable_runtime/components/app.tsx @@ -29,7 +29,7 @@ interface Props { export const App: FC = ({ workpad, stage }) => { const renderers: { [key: string]: RendererSpec } = {}; - renderFunctions.forEach(fn => { + renderFunctions.forEach((fn) => { const func = fn(); renderers[func.name] = func; }); diff --git a/x-pack/plugins/canvas/shareable_runtime/components/canvas.tsx b/x-pack/plugins/canvas/shareable_runtime/components/canvas.tsx index 7d7067da09ee6..b1eb9af6fc4a1 100644 --- a/x-pack/plugins/canvas/shareable_runtime/components/canvas.tsx +++ b/x-pack/plugins/canvas/shareable_runtime/components/canvas.tsx @@ -66,8 +66,9 @@ export const CanvasComponent = ({ const { height: stageHeight, width: stageWidth, page } = stage; const { height: workpadHeight, width: workpadWidth } = workpad; const ratio = Math.max(workpadWidth / stageWidth, workpadHeight / stageHeight); - const transform = `scale3d(${stageHeight / (stageHeight * ratio)}, ${stageWidth / - (stageWidth * ratio)}, 1)`; + const transform = `scale3d(${stageHeight / (stageHeight * ratio)}, ${ + stageWidth / (stageWidth * ratio) + }, 1)`; const pageStyle = { height: workpadHeight, diff --git a/x-pack/plugins/canvas/shareable_runtime/components/footer/settings/__tests__/settings.test.tsx b/x-pack/plugins/canvas/shareable_runtime/components/footer/settings/__tests__/settings.test.tsx index 66515eb3421d5..34dacc7956253 100644 --- a/x-pack/plugins/canvas/shareable_runtime/components/footer/settings/__tests__/settings.test.tsx +++ b/x-pack/plugins/canvas/shareable_runtime/components/footer/settings/__tests__/settings.test.tsx @@ -77,9 +77,7 @@ describe('', () => { expect(takeMountedSnapshot(portal(wrapper))).toMatchSnapshot(); // Click the Hide Toolbar switch - portal(wrapper) - .find('button[data-test-subj="hideToolbarSwitch"]') - .simulate('click'); + portal(wrapper).find('button[data-test-subj="hideToolbarSwitch"]').simulate('click'); portal(wrapper).update(); diff --git a/x-pack/plugins/canvas/shareable_runtime/index.ts b/x-pack/plugins/canvas/shareable_runtime/index.ts index 8b29b23c4442f..11ada0a468cb2 100644 --- a/x-pack/plugins/canvas/shareable_runtime/index.ts +++ b/x-pack/plugins/canvas/shareable_runtime/index.ts @@ -15,7 +15,7 @@ const css = require.context( true, /\.\/plugins\/(?!canvas).*light\.css/ ); -css.keys().forEach(filename => { +css.keys().forEach((filename) => { css(filename); }); @@ -24,4 +24,4 @@ const uiStyles = require.context( false, /[\/\\](?!mixins|variables|_|\.|bootstrap_(light|dark))[^\/\\]+\.less/ ); -uiStyles.keys().forEach(key => uiStyles(key)); +uiStyles.keys().forEach((key) => uiStyles(key)); diff --git a/x-pack/plugins/canvas/shareable_runtime/postcss.config.js b/x-pack/plugins/canvas/shareable_runtime/postcss.config.js index 2e83c8b33e26e..10baaddfc9b05 100644 --- a/x-pack/plugins/canvas/shareable_runtime/postcss.config.js +++ b/x-pack/plugins/canvas/shareable_runtime/postcss.config.js @@ -12,7 +12,7 @@ module.exports = { plugins: [ prefixer({ prefix: '.kbnCanvas', - transform: function(prefix, selector, prefixedSelector) { + transform: function (prefix, selector, prefixedSelector) { if (selector === 'body' || selector === 'html') { return prefix; } else { diff --git a/x-pack/plugins/canvas/shareable_runtime/supported_renderers.js b/x-pack/plugins/canvas/shareable_runtime/supported_renderers.js index 526bf3c9d6fb9..6238aaf5c2fe4 100644 --- a/x-pack/plugins/canvas/shareable_runtime/supported_renderers.js +++ b/x-pack/plugins/canvas/shareable_runtime/supported_renderers.js @@ -43,4 +43,4 @@ export const renderFunctions = [ text, ]; -export const renderFunctionNames = renderFunctions.map(fn => fn.name); +export const renderFunctionNames = renderFunctions.map((fn) => fn.name); diff --git a/x-pack/plugins/canvas/shareable_runtime/test/context.tsx b/x-pack/plugins/canvas/shareable_runtime/test/context.tsx index 9361655d4af6e..b9738359ba5b5 100644 --- a/x-pack/plugins/canvas/shareable_runtime/test/context.tsx +++ b/x-pack/plugins/canvas/shareable_runtime/test/context.tsx @@ -59,7 +59,7 @@ export const Context = ({ }: Props) => { const renderers: { [key: string]: RendererSpec } = {}; - renderFunctions.forEach(rendererFn => { + renderFunctions.forEach((rendererFn) => { const renderer = rendererFn(); renderers[renderer.name] = renderer; }); diff --git a/x-pack/plugins/canvas/shareable_runtime/test/interactions.ts b/x-pack/plugins/canvas/shareable_runtime/test/interactions.ts index 1c5b78929aaa5..360b9fdce51a1 100644 --- a/x-pack/plugins/canvas/shareable_runtime/test/interactions.ts +++ b/x-pack/plugins/canvas/shareable_runtime/test/interactions.ts @@ -8,7 +8,7 @@ import { ReactWrapper } from 'enzyme'; import { getSettingsTrigger, getPortal, getContextMenuItems } from './selectors'; import { waitFor } from './utils'; -export const openSettings = async function(wrapper: ReactWrapper) { +export const openSettings = async function (wrapper: ReactWrapper) { getSettingsTrigger(wrapper).simulate('click'); try { @@ -16,19 +16,15 @@ export const openSettings = async function(wrapper: ReactWrapper) { await waitFor(() => { wrapper.update(); - return getPortal(wrapper) - .find('EuiPanel') - .exists(); + return getPortal(wrapper).find('EuiPanel').exists(); }); } catch (e) { throw new Error('Settings Panel did not open in given time'); } }; -export const selectMenuItem = async function(wrapper: ReactWrapper, menuItemIndex: number) { - getContextMenuItems(wrapper) - .at(menuItemIndex) - .simulate('click'); +export const selectMenuItem = async function (wrapper: ReactWrapper, menuItemIndex: number) { + getContextMenuItems(wrapper).at(menuItemIndex).simulate('click'); try { // When the menu item is clicked, wait for all of the context menus to be there diff --git a/x-pack/plugins/canvas/shareable_runtime/test/selectors.ts b/x-pack/plugins/canvas/shareable_runtime/test/selectors.ts index 852c4ec9aadac..8068ccbbab83a 100644 --- a/x-pack/plugins/canvas/shareable_runtime/test/selectors.ts +++ b/x-pack/plugins/canvas/shareable_runtime/test/selectors.ts @@ -19,22 +19,16 @@ export const getToolbarPanel = (wrapper: ReactWrapper) => wrapper.find('ToolbarSettings > ToolbarSettingsComponent'); export const getToolbarCheckbox = (wrapper: ReactWrapper) => - getToolbarPanel(wrapper) - .find('EuiSwitch') - .find('button'); + getToolbarPanel(wrapper).find('EuiSwitch').find('button'); export const getAutoplayPanel = (wrapper: ReactWrapper) => wrapper.find('AutoplaySettings > AutoplaySettingsComponent'); export const getAutoplayCheckbox = (wrapper: ReactWrapper) => - getAutoplayPanel(wrapper) - .find('EuiSwitch') - .find('button'); + getAutoplayPanel(wrapper).find('EuiSwitch').find('button'); export const getAutoplayTextField = (wrapper: ReactWrapper) => - getAutoplayPanel(wrapper) - .find('EuiFieldText') - .find('input[type="text"]'); + getAutoplayPanel(wrapper).find('EuiFieldText').find('input[type="text"]'); export const getAutoplaySubmit = (wrapper: ReactWrapper) => getAutoplayPanel(wrapper).find('EuiButton'); diff --git a/x-pack/plugins/canvas/shareable_runtime/test/utils.ts b/x-pack/plugins/canvas/shareable_runtime/test/utils.ts index 4e18f2af1b06a..fe3c1be9ba154 100644 --- a/x-pack/plugins/canvas/shareable_runtime/test/utils.ts +++ b/x-pack/plugins/canvas/shareable_runtime/test/utils.ts @@ -8,7 +8,7 @@ import { ReactWrapper } from 'enzyme'; import { Component } from 'react'; export const tick = (ms = 0) => - new Promise(resolve => { + new Promise((resolve) => { setTimeout(resolve, ms); }); diff --git a/x-pack/plugins/canvas/tasks/mocks/downloadWorkpad.js b/x-pack/plugins/canvas/tasks/mocks/downloadWorkpad.js index 3571448c11aa9..ca8d1c10d870f 100644 --- a/x-pack/plugins/canvas/tasks/mocks/downloadWorkpad.js +++ b/x-pack/plugins/canvas/tasks/mocks/downloadWorkpad.js @@ -3,11 +3,11 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -export const downloadWorkpad = async workpadId => console.log(`Download workpad ${workpadId}`); +export const downloadWorkpad = async (workpadId) => console.log(`Download workpad ${workpadId}`); -export const downloadRenderedWorkpad = async renderedWorkpad => +export const downloadRenderedWorkpad = async (renderedWorkpad) => console.log(`Download workpad ${renderedWorkpad.id}`); -export const downloadRuntime = async basePath => console.log(`Download run time at ${basePath}`); +export const downloadRuntime = async (basePath) => console.log(`Download run time at ${basePath}`); -export const downloadZippedRuntime = async data => console.log(`Downloading data ${data}`); +export const downloadZippedRuntime = async (data) => console.log(`Downloading data ${data}`); diff --git a/x-pack/plugins/canvas/tasks/mocks/uiNotify.js b/x-pack/plugins/canvas/tasks/mocks/uiNotify.js index ad313bc69da45..d29e66e8287eb 100644 --- a/x-pack/plugins/canvas/tasks/mocks/uiNotify.js +++ b/x-pack/plugins/canvas/tasks/mocks/uiNotify.js @@ -5,9 +5,9 @@ */ const notifierProto = { - error: msg => `error: ${msg}`, - warning: msg => `warning: ${msg}`, - info: msg => `info: ${msg}`, + error: (msg) => `error: ${msg}`, + warning: (msg) => `warning: ${msg}`, + info: (msg) => `info: ${msg}`, }; export class Notifier { diff --git a/x-pack/plugins/canvas/tasks/mocks/uiNotifyFormatMsg.js b/x-pack/plugins/canvas/tasks/mocks/uiNotifyFormatMsg.js index 480a750e0a9ce..4df51dd284933 100644 --- a/x-pack/plugins/canvas/tasks/mocks/uiNotifyFormatMsg.js +++ b/x-pack/plugins/canvas/tasks/mocks/uiNotifyFormatMsg.js @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export const formatMsg = str => str; +export const formatMsg = (str) => str; diff --git a/x-pack/plugins/case/common/api/saved_object.ts b/x-pack/plugins/case/common/api/saved_object.ts index fac8edd0ebea1..73fe767dd717e 100644 --- a/x-pack/plugins/case/common/api/saved_object.ts +++ b/x-pack/plugins/case/common/api/saved_object.ts @@ -12,7 +12,7 @@ export const NumberFromString = new rt.Type( 'NumberFromString', rt.number.is, (u, c) => - either.chain(rt.string.validate(u, c), s => { + either.chain(rt.string.validate(u, c), (s) => { const n = +s; return isNaN(n) ? rt.failure(u, c, 'cannot parse to a number') : rt.success(n); }), diff --git a/x-pack/plugins/case/common/constants.ts b/x-pack/plugins/case/common/constants.ts index 855a5c3d63507..819d4110e168d 100644 --- a/x-pack/plugins/case/common/constants.ts +++ b/x-pack/plugins/case/common/constants.ts @@ -25,7 +25,7 @@ export const CASE_USER_ACTIONS_URL = `${CASE_DETAILS_URL}/user_actions`; * Action routes */ -export const ACTION_URL = '/api/action'; -export const ACTION_TYPES_URL = '/api/action/types'; +export const ACTION_URL = '/api/actions'; +export const ACTION_TYPES_URL = '/api/actions/list_action_types'; export const SUPPORTED_CONNECTORS = ['.servicenow', '.jira']; diff --git a/x-pack/plugins/case/server/plugin.ts b/x-pack/plugins/case/server/plugin.ts index 670e6ec797a9f..9cf045da3e700 100644 --- a/x-pack/plugins/case/server/plugin.ts +++ b/x-pack/plugins/case/server/plugin.ts @@ -21,7 +21,7 @@ import { import { CaseConfigureService, CaseService, CaseUserActionService } from './services'; function createConfig$(context: PluginInitializerContext) { - return context.config.create().pipe(map(config => config)); + return context.config.create().pipe(map((config) => config)); } export interface PluginsSetup { @@ -36,9 +36,7 @@ export class CasePlugin { } public async setup(core: CoreSetup, plugins: PluginsSetup) { - const config = await createConfig$(this.initializerContext) - .pipe(first()) - .toPromise(); + const config = await createConfig$(this.initializerContext).pipe(first()).toPromise(); if (!config.enabled) { return; diff --git a/x-pack/plugins/case/server/routes/api/__fixtures__/create_mock_so_repository.ts b/x-pack/plugins/case/server/routes/api/__fixtures__/create_mock_so_repository.ts index e83dafc68ee69..eade232593c8e 100644 --- a/x-pack/plugins/case/server/routes/api/__fixtures__/create_mock_so_repository.ts +++ b/x-pack/plugins/case/server/routes/api/__fixtures__/create_mock_so_repository.ts @@ -31,13 +31,13 @@ export const createMockSavedObjectsRepository = ({ return { saved_objects: objects.map(({ id, type }) => { if (type === CASE_COMMENT_SAVED_OBJECT) { - const result = caseCommentSavedObject.filter(s => s.id === id); + const result = caseCommentSavedObject.filter((s) => s.id === id); if (!result.length) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } return result; } - const result = caseSavedObject.filter(s => s.id === id); + const result = caseSavedObject.filter((s) => s.id === id); if (!result.length) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } @@ -49,11 +49,11 @@ export const createMockSavedObjectsRepository = ({ return { saved_objects: objects.map(({ id, type, attributes }) => { if (type === CASE_COMMENT_SAVED_OBJECT) { - if (!caseCommentSavedObject.find(s => s.id === id)) { + if (!caseCommentSavedObject.find((s) => s.id === id)) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } } else if (type === CASE_SAVED_OBJECT) { - if (!caseSavedObject.find(s => s.id === id)) { + if (!caseSavedObject.find((s) => s.id === id)) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } } @@ -70,20 +70,20 @@ export const createMockSavedObjectsRepository = ({ }), get: jest.fn((type, id) => { if (type === CASE_COMMENT_SAVED_OBJECT) { - const result = caseCommentSavedObject.filter(s => s.id === id); + const result = caseCommentSavedObject.filter((s) => s.id === id); if (!result.length) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } return result[0]; } - const result = caseSavedObject.filter(s => s.id === id); + const result = caseSavedObject.filter((s) => s.id === id); if (!result.length) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } return result[0]; }), - find: jest.fn(findArgs => { + find: jest.fn((findArgs) => { if (findArgs.hasReference && findArgs.hasReference.id === 'bad-guy') { throw SavedObjectsErrorHelpers.createBadRequestError('Error thrown for testing'); } @@ -169,7 +169,7 @@ export const createMockSavedObjectsRepository = ({ }), update: jest.fn((type, id, attributes) => { if (type === CASE_COMMENT_SAVED_OBJECT) { - if (!caseCommentSavedObject.find(s => s.id === id)) { + if (!caseCommentSavedObject.find((s) => s.id === id)) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } caseCommentSavedObject = [ @@ -183,7 +183,7 @@ export const createMockSavedObjectsRepository = ({ }, ]; } else if (type === CASE_SAVED_OBJECT) { - if (!caseSavedObject.find(s => s.id === id)) { + if (!caseSavedObject.find((s) => s.id === id)) { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } } @@ -207,14 +207,14 @@ export const createMockSavedObjectsRepository = ({ }; }), delete: jest.fn((type: string, id: string) => { - let result = caseSavedObject.filter(s => s.id === id); + let result = caseSavedObject.filter((s) => s.id === id); if (type === CASE_COMMENT_SAVED_OBJECT) { - result = caseCommentSavedObject.filter(s => s.id === id); + result = caseCommentSavedObject.filter((s) => s.id === id); } if (type === CASE_CONFIGURE_SAVED_OBJECT) { - result = caseConfigureSavedObject.filter(s => s.id === id); + result = caseConfigureSavedObject.filter((s) => s.id === id); } if (type === CASE_COMMENT_SAVED_OBJECT && id === 'bad-guy') { diff --git a/x-pack/plugins/case/server/routes/api/cases/comments/delete_all_comments.ts b/x-pack/plugins/case/server/routes/api/cases/comments/delete_all_comments.ts index e9bcb9690ebd8..e06b3a33dfc72 100644 --- a/x-pack/plugins/case/server/routes/api/cases/comments/delete_all_comments.ts +++ b/x-pack/plugins/case/server/routes/api/cases/comments/delete_all_comments.ts @@ -32,7 +32,7 @@ export function initDeleteAllCommentsApi({ caseService, router, userActionServic caseId: request.params.case_id, }); await Promise.all( - comments.saved_objects.map(comment => + comments.saved_objects.map((comment) => caseService.deleteComment({ client, commentId: comment.id, @@ -42,7 +42,7 @@ export function initDeleteAllCommentsApi({ caseService, router, userActionServic await userActionService.postUserActions({ client, - actions: comments.saved_objects.map(comment => + actions: comments.saved_objects.map((comment) => buildCommentUserActionItem({ action: 'delete', actionAt: deleteDate, diff --git a/x-pack/plugins/case/server/routes/api/cases/comments/delete_comment.ts b/x-pack/plugins/case/server/routes/api/cases/comments/delete_comment.ts index 72ef400415d0f..df08af025df03 100644 --- a/x-pack/plugins/case/server/routes/api/cases/comments/delete_comment.ts +++ b/x-pack/plugins/case/server/routes/api/cases/comments/delete_comment.ts @@ -39,7 +39,7 @@ export function initDeleteCommentApi({ caseService, router, userActionService }: throw Boom.notFound(`This comment ${request.params.comment_id} does not exist anymore.`); } - const caseRef = myComment.references.find(c => c.type === CASE_SAVED_OBJECT); + const caseRef = myComment.references.find((c) => c.type === CASE_SAVED_OBJECT); if (caseRef == null || (caseRef != null && caseRef.id !== request.params.case_id)) { throw Boom.notFound( `This comment ${request.params.comment_id} does not exist in ${request.params.case_id}).` diff --git a/x-pack/plugins/case/server/routes/api/cases/comments/get_comment.test.ts b/x-pack/plugins/case/server/routes/api/cases/comments/get_comment.test.ts index b5a7d6367ea4b..24a03b217ab7c 100644 --- a/x-pack/plugins/case/server/routes/api/cases/comments/get_comment.test.ts +++ b/x-pack/plugins/case/server/routes/api/cases/comments/get_comment.test.ts @@ -41,7 +41,7 @@ describe('GET comment', () => { const response = await routeHandler(theContext, request, kibanaResponseFactory); expect(response.status).toEqual(200); - const myPayload = mockCaseComments.find(s => s.id === 'mock-comment-1'); + const myPayload = mockCaseComments.find((s) => s.id === 'mock-comment-1'); expect(myPayload).not.toBeUndefined(); if (myPayload != null) { expect(response.payload).toEqual(flattenCommentSavedObject(myPayload)); diff --git a/x-pack/plugins/case/server/routes/api/cases/comments/patch_comment.ts b/x-pack/plugins/case/server/routes/api/cases/comments/patch_comment.ts index 90661a7d3897d..1aca27bbf1853 100644 --- a/x-pack/plugins/case/server/routes/api/cases/comments/patch_comment.ts +++ b/x-pack/plugins/case/server/routes/api/cases/comments/patch_comment.ts @@ -57,7 +57,7 @@ export function initPatchCommentApi({ throw Boom.notFound(`This comment ${query.id} does not exist anymore.`); } - const caseRef = myComment.references.find(c => c.type === CASE_SAVED_OBJECT); + const caseRef = myComment.references.find((c) => c.type === CASE_SAVED_OBJECT); if (caseRef == null || (caseRef != null && caseRef.id !== caseId)) { throw Boom.notFound(`This comment ${query.id} does not exist in ${caseId}).`); } diff --git a/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.test.ts b/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.test.ts index 09692ff73b94b..d7a01ef069867 100644 --- a/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.test.ts +++ b/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.test.ts @@ -39,7 +39,7 @@ describe('GET connectors', () => { const res = await routeHandler(context, req, kibanaResponseFactory); expect(res.status).toEqual(200); expect(res.payload).toEqual( - getActions().filter(action => action.actionTypeId === '.servicenow') + getActions().filter((action) => action.actionTypeId === '.servicenow') ); }); diff --git a/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.ts b/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.ts index 43167d56de015..d86e1777e920d 100644 --- a/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.ts +++ b/x-pack/plugins/case/server/routes/api/cases/configure/get_connectors.ts @@ -31,7 +31,7 @@ export function initCaseConfigureGetActionConnector({ caseService, router }: Rou throw Boom.notFound('Action client have not been found'); } - const results = (await actionsClient.getAll()).filter(action => + const results = (await actionsClient.getAll()).filter((action) => SUPPORTED_CONNECTORS.includes(action.actionTypeId) ); return response.ok({ body: results }); diff --git a/x-pack/plugins/case/server/routes/api/cases/configure/post_configure.ts b/x-pack/plugins/case/server/routes/api/cases/configure/post_configure.ts index 5c1693e728c37..a49a6c9ec5b76 100644 --- a/x-pack/plugins/case/server/routes/api/cases/configure/post_configure.ts +++ b/x-pack/plugins/case/server/routes/api/cases/configure/post_configure.ts @@ -38,7 +38,7 @@ export function initPostCaseConfigure({ caseConfigureService, caseService, route if (myCaseConfigure.saved_objects.length > 0) { await Promise.all( - myCaseConfigure.saved_objects.map(cc => + myCaseConfigure.saved_objects.map((cc) => caseConfigureService.delete({ client, caseConfigureId: cc.id }) ) ); diff --git a/x-pack/plugins/case/server/routes/api/cases/delete_cases.ts b/x-pack/plugins/case/server/routes/api/cases/delete_cases.ts index 20591637a6c23..9f57663c85f6f 100644 --- a/x-pack/plugins/case/server/routes/api/cases/delete_cases.ts +++ b/x-pack/plugins/case/server/routes/api/cases/delete_cases.ts @@ -25,7 +25,7 @@ export function initDeleteCasesApi({ caseService, router, userActionService }: R try { const client = context.core.savedObjects.client; await Promise.all( - request.query.ids.map(id => + request.query.ids.map((id) => caseService.deleteCase({ client, caseId: id, @@ -33,7 +33,7 @@ export function initDeleteCasesApi({ caseService, router, userActionService }: R ) ); const comments = await Promise.all( - request.query.ids.map(id => + request.query.ids.map((id) => caseService.getAllCaseComments({ client, caseId: id, @@ -41,9 +41,9 @@ export function initDeleteCasesApi({ caseService, router, userActionService }: R ) ); - if (comments.some(c => c.saved_objects.length > 0)) { + if (comments.some((c) => c.saved_objects.length > 0)) { await Promise.all( - comments.map(c => + comments.map((c) => Promise.all( c.saved_objects.map(({ id }) => caseService.deleteComment({ @@ -60,7 +60,7 @@ export function initDeleteCasesApi({ caseService, router, userActionService }: R await userActionService.postUserActions({ client, - actions: request.query.ids.map(id => + actions: request.query.ids.map((id) => buildCaseUserActionItem({ action: 'create', actionAt: deleteDate, diff --git a/x-pack/plugins/case/server/routes/api/cases/find_cases.ts b/x-pack/plugins/case/server/routes/api/cases/find_cases.ts index cbe26ebe2f642..db57315388c5e 100644 --- a/x-pack/plugins/case/server/routes/api/cases/find_cases.ts +++ b/x-pack/plugins/case/server/routes/api/cases/find_cases.ts @@ -19,7 +19,7 @@ import { CASES_URL } from '../../../../common/constants'; import { getConnectorId } from './helpers'; const combineFilters = (filters: string[], operator: 'OR' | 'AND'): string => - filters?.filter(i => i !== '').join(` ${operator} `); + filters?.filter((i) => i !== '').join(` ${operator} `); const getStatusFilter = (status: 'open' | 'closed', appendFilter?: string) => `${CASE_SAVED_OBJECT}.attributes.status: ${status}${ @@ -35,7 +35,7 @@ const buildFilter = ( ? Array.isArray(filters) ? // Be aware of the surrounding parenthesis (as string inside literal) around filters. `(${filters - .map(filter => `${CASE_SAVED_OBJECT}.attributes.${field}: ${filter}`) + .map((filter) => `${CASE_SAVED_OBJECT}.attributes.${field}: ${filter}`) ?.join(` ${operator} `)})` : `${CASE_SAVED_OBJECT}.attributes.${field}: ${filters}` : ''; @@ -102,7 +102,7 @@ export function initFindCasesApi({ caseService, caseConfigureService, router }: caseConfigureService.find({ client }), ]); const totalCommentsFindByCases = await Promise.all( - cases.saved_objects.map(c => + cases.saved_objects.map((c) => caseService.getAllCaseComments({ client, caseId: c.id, @@ -119,8 +119,8 @@ export function initFindCasesApi({ caseService, caseConfigureService, router }: (acc, itemFind) => { if (itemFind.saved_objects.length > 0) { const caseId = - itemFind.saved_objects[0].references.find(r => r.type === CASE_SAVED_OBJECT)?.id ?? - null; + itemFind.saved_objects[0].references.find((r) => r.type === CASE_SAVED_OBJECT) + ?.id ?? null; if (caseId != null) { return [...acc, { caseId, totalComments: itemFind.total }]; } diff --git a/x-pack/plugins/case/server/routes/api/cases/get_case.test.ts b/x-pack/plugins/case/server/routes/api/cases/get_case.test.ts index 6c0b5bdff418d..ed291c2cbf726 100644 --- a/x-pack/plugins/case/server/routes/api/cases/get_case.test.ts +++ b/x-pack/plugins/case/server/routes/api/cases/get_case.test.ts @@ -45,7 +45,7 @@ describe('GET case', () => { ); const response = await routeHandler(theContext, request, kibanaResponseFactory); - const savedObject = (mockCases.find(s => s.id === 'mock-id-1') as unknown) as SavedObject< + const savedObject = (mockCases.find((s) => s.id === 'mock-id-1') as unknown) as SavedObject< CaseAttributes >; expect(response.status).toEqual(200); diff --git a/x-pack/plugins/case/server/routes/api/cases/helpers.ts b/x-pack/plugins/case/server/routes/api/cases/helpers.ts index b02bc0b4e10a2..78b108b00d4a7 100644 --- a/x-pack/plugins/case/server/routes/api/cases/helpers.ts +++ b/x-pack/plugins/case/server/routes/api/cases/helpers.ts @@ -24,12 +24,12 @@ export const compareArrays = ({ addedItems: [], deletedItems: [], }; - originalValue.forEach(origVal => { + originalValue.forEach((origVal) => { if (!updatedValue.includes(origVal)) { result.deletedItems = [...result.deletedItems, origVal]; } }); - updatedValue.forEach(updatedVal => { + updatedValue.forEach((updatedVal) => { if (!originalValue.includes(updatedVal)) { result.addedItems = [...result.addedItems, updatedVal]; } diff --git a/x-pack/plugins/case/server/routes/api/cases/patch_cases.ts b/x-pack/plugins/case/server/routes/api/cases/patch_cases.ts index 6d2a5f943cea9..0c722cf56ada3 100644 --- a/x-pack/plugins/case/server/routes/api/cases/patch_cases.ts +++ b/x-pack/plugins/case/server/routes/api/cases/patch_cases.ts @@ -46,15 +46,15 @@ export function initPatchCasesApi({ const [myCases, myCaseConfigure] = await Promise.all([ caseService.getCases({ client, - caseIds: query.cases.map(q => q.id), + caseIds: query.cases.map((q) => q.id), }), caseConfigureService.find({ client }), ]); const caseConfigureConnectorId = getConnectorId(myCaseConfigure); let nonExistingCases: CasePatchRequest[] = []; - const conflictedCases = query.cases.filter(q => { - const myCase = myCases.saved_objects.find(c => c.id === q.id); + const conflictedCases = query.cases.filter((q) => { + const myCase = myCases.saved_objects.find((c) => c.id === q.id); if (myCase && myCase.error) { nonExistingCases = [...nonExistingCases, q]; @@ -65,24 +65,24 @@ export function initPatchCasesApi({ if (nonExistingCases.length > 0) { throw Boom.notFound( `These cases ${nonExistingCases - .map(c => c.id) + .map((c) => c.id) .join(', ')} do not exist. Please check you have the correct ids.` ); } if (conflictedCases.length > 0) { throw Boom.conflict( `These cases ${conflictedCases - .map(c => c.id) + .map((c) => c.id) .join(', ')} has been updated. Please refresh before saving additional updates.` ); } - const updateCases: CasePatchRequest[] = query.cases.map(thisCase => { - const currentCase = myCases.saved_objects.find(c => c.id === thisCase.id); + const updateCases: CasePatchRequest[] = query.cases.map((thisCase) => { + const currentCase = myCases.saved_objects.find((c) => c.id === thisCase.id); return currentCase != null ? getCaseToUpdate(currentCase.attributes, thisCase) : { id: thisCase.id, version: thisCase.version }; }); - const updateFilterCases = updateCases.filter(updateCase => { + const updateFilterCases = updateCases.filter((updateCase) => { const { id, version, ...updateCaseAttributes } = updateCase; return Object.keys(updateCaseAttributes).length > 0; }); @@ -91,7 +91,7 @@ export function initPatchCasesApi({ const updatedDt = new Date().toISOString(); const updatedCases = await caseService.patchCases({ client, - cases: updateFilterCases.map(thisCase => { + cases: updateFilterCases.map((thisCase) => { const { id: caseId, version, ...updateCaseAttributes } = thisCase; let closedInfo = {}; if (updateCaseAttributes.status && updateCaseAttributes.status === 'closed') { @@ -119,11 +119,11 @@ export function initPatchCasesApi({ }); const returnUpdatedCase = myCases.saved_objects - .filter(myCase => - updatedCases.saved_objects.some(updatedCase => updatedCase.id === myCase.id) + .filter((myCase) => + updatedCases.saved_objects.some((updatedCase) => updatedCase.id === myCase.id) ) - .map(myCase => { - const updatedCase = updatedCases.saved_objects.find(c => c.id === myCase.id); + .map((myCase) => { + const updatedCase = updatedCases.saved_objects.find((c) => c.id === myCase.id); return flattenCaseSavedObject({ savedObject: { ...myCase, diff --git a/x-pack/plugins/case/server/routes/api/cases/push_case.ts b/x-pack/plugins/case/server/routes/api/cases/push_case.ts index 871e78495c5dd..3379bbd318d5b 100644 --- a/x-pack/plugins/case/server/routes/api/cases/push_case.ts +++ b/x-pack/plugins/case/server/routes/api/cases/push_case.ts @@ -100,7 +100,7 @@ export function initPushCaseUserActionApi({ connector_id: myCase.attributes.connector_id ?? caseConfigureConnectorId, }; - if (!connectors.some(connector => connector.id === updateConnectorId.connector_id)) { + if (!connectors.some((connector) => connector.id === updateConnectorId.connector_id)) { throw Boom.notFound('Connector not found or set to none'); } @@ -127,8 +127,8 @@ export function initPushCaseUserActionApi({ caseService.patchComments({ client, comments: comments.saved_objects - .filter(comment => comment.attributes.pushed_at == null) - .map(comment => ({ + .filter((comment) => comment.attributes.pushed_at == null) + .map((comment) => ({ commentId: comment.id, updatedAttributes: { pushed_at: pushedDate, @@ -174,9 +174,9 @@ export function initPushCaseUserActionApi({ attributes: { ...myCase.attributes, ...updatedCase?.attributes }, references: myCase.references, }, - comments: comments.saved_objects.map(origComment => { + comments: comments.saved_objects.map((origComment) => { const updatedComment = updatedComments.saved_objects.find( - c => c.id === origComment.id + (c) => c.id === origComment.id ); return { ...origComment, diff --git a/x-pack/plugins/case/server/routes/api/cases/user_actions/get_all_user_actions.ts b/x-pack/plugins/case/server/routes/api/cases/user_actions/get_all_user_actions.ts index c90979f60d23f..eb51582900252 100644 --- a/x-pack/plugins/case/server/routes/api/cases/user_actions/get_all_user_actions.ts +++ b/x-pack/plugins/case/server/routes/api/cases/user_actions/get_all_user_actions.ts @@ -31,11 +31,12 @@ export function initGetAllUserActionsApi({ userActionService, router }: RouteDep }); return response.ok({ body: CaseUserActionsResponseRt.encode( - userActions.saved_objects.map(ua => ({ + userActions.saved_objects.map((ua) => ({ ...ua.attributes, action_id: ua.id, - case_id: ua.references.find(r => r.type === CASE_SAVED_OBJECT)?.id ?? '', - comment_id: ua.references.find(r => r.type === CASE_COMMENT_SAVED_OBJECT)?.id ?? null, + case_id: ua.references.find((r) => r.type === CASE_SAVED_OBJECT)?.id ?? '', + comment_id: + ua.references.find((r) => r.type === CASE_COMMENT_SAVED_OBJECT)?.id ?? null, })) ), }); diff --git a/x-pack/plugins/case/server/routes/api/utils.ts b/x-pack/plugins/case/server/routes/api/utils.ts index b65205734d569..fb199442f9425 100644 --- a/x-pack/plugins/case/server/routes/api/utils.ts +++ b/x-pack/plugins/case/server/routes/api/utils.ts @@ -111,7 +111,7 @@ export const flattenCaseSavedObjects = ( flattenCaseSavedObject({ savedObject, totalComment: - totalCommentByCase.find(tc => tc.caseId === savedObject.id)?.totalComments ?? 0, + totalCommentByCase.find((tc) => tc.caseId === savedObject.id)?.totalComments ?? 0, caseConfigureConnectorId, }), ]; diff --git a/x-pack/plugins/case/server/services/index.ts b/x-pack/plugins/case/server/services/index.ts index cdc5fd21a8138..2ca3e4e9ec223 100644 --- a/x-pack/plugins/case/server/services/index.ts +++ b/x-pack/plugins/case/server/services/index.ts @@ -150,7 +150,7 @@ export class CaseService { try { this.log.debug(`Attempting to GET cases ${caseIds.join(', ')}`); return await client.bulkGet( - caseIds.map(caseId => ({ type: CASE_SAVED_OBJECT, id: caseId })) + caseIds.map((caseId) => ({ type: CASE_SAVED_OBJECT, id: caseId })) ); } catch (error) { this.log.debug(`Error on GET cases ${caseIds.join(', ')}: ${error}`); @@ -264,9 +264,9 @@ export class CaseService { }, patchCases: async ({ client, cases }: PatchCasesArgs) => { try { - this.log.debug(`Attempting to UPDATE case ${cases.map(c => c.caseId).join(', ')}`); + this.log.debug(`Attempting to UPDATE case ${cases.map((c) => c.caseId).join(', ')}`); return await client.bulkUpdate( - cases.map(c => ({ + cases.map((c) => ({ type: CASE_SAVED_OBJECT, id: c.caseId, attributes: c.updatedAttributes, @@ -274,7 +274,7 @@ export class CaseService { })) ); } catch (error) { - this.log.debug(`Error on UPDATE case ${cases.map(c => c.caseId).join(', ')}: ${error}`); + this.log.debug(`Error on UPDATE case ${cases.map((c) => c.caseId).join(', ')}: ${error}`); throw error; } }, @@ -297,10 +297,10 @@ export class CaseService { patchComments: async ({ client, comments }: PatchComments) => { try { this.log.debug( - `Attempting to UPDATE comments ${comments.map(c => c.commentId).join(', ')}` + `Attempting to UPDATE comments ${comments.map((c) => c.commentId).join(', ')}` ); return await client.bulkUpdate( - comments.map(c => ({ + comments.map((c) => ({ type: CASE_COMMENT_SAVED_OBJECT, id: c.commentId, attributes: c.updatedAttributes, @@ -309,7 +309,7 @@ export class CaseService { ); } catch (error) { this.log.debug( - `Error on UPDATE comments ${comments.map(c => c.commentId).join(', ')}: ${error}` + `Error on UPDATE comments ${comments.map((c) => c.commentId).join(', ')}: ${error}` ); throw error; } diff --git a/x-pack/plugins/case/server/services/reporters/read_reporters.ts b/x-pack/plugins/case/server/services/reporters/read_reporters.ts index 4af5b41fc4dd4..2d09dbf7b9890 100644 --- a/x-pack/plugins/case/server/services/reporters/read_reporters.ts +++ b/x-pack/plugins/case/server/services/reporters/read_reporters.ts @@ -16,7 +16,7 @@ export const convertToReporters = (caseObjects: Array item.username === caseObj.attributes.created_by.username) + !accum.some((item) => item.username === caseObj.attributes.created_by.username) ) { return [...accum, caseObj.attributes.created_by]; } else { diff --git a/x-pack/plugins/case/server/services/user_actions/helpers.ts b/x-pack/plugins/case/server/services/user_actions/helpers.ts index af50b3b394325..228b42b4c638f 100644 --- a/x-pack/plugins/case/server/services/user_actions/helpers.ts +++ b/x-pack/plugins/case/server/services/user_actions/helpers.ts @@ -138,11 +138,11 @@ export const buildCaseUserActions = ({ updatedCases: Array>; }): UserActionItem[] => updatedCases.reduce((acc, updatedItem) => { - const originalItem = originalCases.find(oItem => oItem.id === updatedItem.id); + const originalItem = originalCases.find((oItem) => oItem.id === updatedItem.id); if (originalItem != null) { let userActions: UserActionItem[] = []; const updatedFields = Object.keys(updatedItem.attributes) as UserActionField; - updatedFields.forEach(field => { + updatedFields.forEach((field) => { if (userActionFieldsAllowed.includes(field)) { const origValue = get(originalItem, ['attributes', field]); const updatedValue = get(updatedItem, ['attributes', field]); diff --git a/x-pack/plugins/case/server/services/user_actions/index.ts b/x-pack/plugins/case/server/services/user_actions/index.ts index 0e9babf9d81af..476a151498c34 100644 --- a/x-pack/plugins/case/server/services/user_actions/index.ts +++ b/x-pack/plugins/case/server/services/user_actions/index.ts @@ -66,7 +66,7 @@ export class CaseUserActionService { try { this.log.debug(`Attempting to POST a new case user action`); return await client.bulkCreate( - actions.map(action => ({ type: CASE_USER_ACTION_SAVED_OBJECT, ...action })) + actions.map((action) => ({ type: CASE_USER_ACTION_SAVED_OBJECT, ...action })) ); } catch (error) { this.log.debug(`Error on POST a new case user action: ${error}`); diff --git a/x-pack/plugins/console_extensions/server/plugin.ts b/x-pack/plugins/console_extensions/server/plugin.ts index 2a08c258f4bbd..8e95d618b30ab 100644 --- a/x-pack/plugins/console_extensions/server/plugin.ts +++ b/x-pack/plugins/console_extensions/server/plugin.ts @@ -32,7 +32,7 @@ export class ConsoleExtensionsServerPlugin implements Plugin addProcessorDefinition(processor)); + processors.forEach((processor) => addProcessorDefinition(processor)); this.log.debug('Added processor definition extensions.'); } } diff --git a/x-pack/plugins/cross_cluster_replication/common/services/utils.ts b/x-pack/plugins/cross_cluster_replication/common/services/utils.ts index dda6732254cc3..7171c50e52f88 100644 --- a/x-pack/plugins/cross_cluster_replication/common/services/utils.ts +++ b/x-pack/plugins/cross_cluster_replication/common/services/utils.ts @@ -11,7 +11,7 @@ export const arrify = (val: any): any[] => (Array.isArray(val) ? val : [val]); * @param {number} time Time in millisecond to wait */ export const wait = (time = 1000) => (data: any): Promise => { - return new Promise(resolve => { + return new Promise((resolve) => { setTimeout(() => resolve(data), time); }); }; diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_add.test.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_add.test.js index db1430d157183..728a9921ea903 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_add.test.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_add.test.js @@ -195,7 +195,7 @@ describe('Create Auto-follow pattern', () => { }); test('should not allow invalid characters', () => { - const expectInvalidChar = char => { + const expectInvalidChar = (char) => { form.setComboBoxValue('indexPatternInput', `with${char}space`); expect(form.getErrorsMessages()).toContain( `Remove the character ${char} from the index pattern.` diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_list.test.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_list.test.js index 0a7eaf647b020..0da241c4c1357 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_list.test.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/auto_follow_pattern_list.test.js @@ -274,11 +274,7 @@ describe('', () => { test('should have a "settings" section', () => { actions.clickAutoFollowPatternAt(0); - expect( - find('settingsSection') - .find('h3') - .text() - ).toEqual('Settings'); + expect(find('settingsSection').find('h3').text()).toEqual('Settings'); expect(exists('settingsValues')).toBe(true); }); @@ -369,7 +365,7 @@ describe('', () => { expect(exists('autoFollowPatternDetail.errors')).toBe(true); expect(exists('autoFollowPatternDetail.titleErrors')).toBe(true); - expect(find('autoFollowPatternDetail.recentError').map(error => error.text())).toEqual([ + expect(find('autoFollowPatternDetail.recentError').map((error) => error.text())).toEqual([ 'April 16th, 2020 8:00:00 PM: bar', ]); }); diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_index_add.test.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_index_add.test.js index 4c99339e16952..f5305f43e7f8c 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_index_add.test.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_index_add.test.js @@ -120,7 +120,7 @@ describe('Create Follower index', () => { test('should not allow invalid characters', () => { actions.clickSaveForm(); // Make all errors visible - const expectInvalidChar = char => { + const expectInvalidChar = (char) => { form.setInputValue('leaderIndexInput', `with${char}`); expect(form.getErrorsMessages()).toContain( `Remove the characters ${char} from your leader index.` @@ -149,7 +149,7 @@ describe('Create Follower index', () => { test('should not allow invalid characters', () => { actions.clickSaveForm(); // Make all errors visible - const expectInvalidChar = char => { + const expectInvalidChar = (char) => { form.setInputValue('followerIndexInput', `with${char}`); expect(form.getErrorsMessages()).toContain( `Remove the characters ${char} from your name.` @@ -235,7 +235,7 @@ describe('Create Follower index', () => { }; test('should have a toggle to activate advanced settings', () => { - const expectDoesNotExist = testSubject => { + const expectDoesNotExist = (testSubject) => { try { expect(exists(testSubject)).toBe(false); } catch { @@ -243,7 +243,7 @@ describe('Create Follower index', () => { } }; - const expectDoesExist = testSubject => { + const expectDoesExist = (testSubject) => { try { expect(exists(testSubject)).toBe(true); } catch { diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_indices_list.test.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_indices_list.test.js index ad9f2db2ce91c..e96beda7243d6 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_indices_list.test.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/follower_indices_list.test.js @@ -190,7 +190,7 @@ describe('', () => { expect(contextMenu.length).toBe(1); const contextMenuButtons = contextMenu.find('button'); - const buttonsLabel = contextMenuButtons.map(btn => btn.text()); + const buttonsLabel = contextMenuButtons.map((btn) => btn.text()); expect(buttonsLabel).toEqual([ 'Pause replication', @@ -206,7 +206,7 @@ describe('', () => { const contextMenu = find('contextMenu'); const contextMenuButtons = contextMenu.find('button'); - const buttonsLabel = contextMenuButtons.map(btn => btn.text()); + const buttonsLabel = contextMenuButtons.map((btn) => btn.text()); expect(buttonsLabel).toEqual([ 'Resume replication', 'Edit follower index', @@ -250,7 +250,7 @@ describe('', () => { const buttonLabels = component .find('.euiContextMenuPanel') .find('.euiContextMenuItem') - .map(button => button.text()); + .map((button) => button.text()); expect(buttonLabels).toEqual([ 'Pause replication', @@ -266,7 +266,7 @@ describe('', () => { const buttonLabels = component .find('.euiContextMenuPanel') .find('.euiContextMenuItem') - .map(button => button.text()); + .map((button) => button.text()); expect(buttonLabels).toEqual([ 'Resume replication', @@ -326,11 +326,7 @@ describe('', () => { test('should have a "settings" section', () => { actions.clickFollowerIndexAt(0); - expect( - find('followerIndexDetail.settingsSection') - .find('h3') - .text() - ).toEqual('Settings'); + expect(find('followerIndexDetail.settingsSection').find('h3').text()).toEqual('Settings'); expect(exists('followerIndexDetail.settingsValues')).toBe(true); }); diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_add.helpers.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_add.helpers.js index 1cb4e7c7725df..e240b5b304c33 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_add.helpers.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_add.helpers.js @@ -12,13 +12,13 @@ import { routing } from '../../../app/services/routing'; const testBedConfig = { store: ccrStore, memoryRouter: { - onRouter: router => (routing.reactRouter = router), + onRouter: (router) => (routing.reactRouter = router), }, }; const initTestBed = registerTestBed(AutoFollowPatternAdd, testBedConfig); -export const setup = props => { +export const setup = (props) => { const testBed = initTestBed(props); // User actions diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_edit.helpers.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_edit.helpers.js index 9cad61893c409..c32f6a54114c7 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_edit.helpers.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_edit.helpers.js @@ -14,7 +14,7 @@ import { AUTO_FOLLOW_PATTERN_EDIT_NAME } from './constants'; const testBedConfig = { store: ccrStore, memoryRouter: { - onRouter: router => (routing.reactRouter = router), + onRouter: (router) => (routing.reactRouter = router), // The auto-follow pattern id to fetch is read from the router ":id" param // so we first set it in our initial entries initialEntries: [`/${AUTO_FOLLOW_PATTERN_EDIT_NAME}`], @@ -25,7 +25,7 @@ const testBedConfig = { const initTestBed = registerTestBed(AutoFollowPatternEdit, testBedConfig); -export const setup = props => { +export const setup = (props) => { const testBed = initTestBed(props); // User actions diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_list.helpers.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_list.helpers.js index 2c2ab642e83c8..87cf6a13ba011 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_list.helpers.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/auto_follow_pattern_list.helpers.js @@ -12,13 +12,13 @@ import { routing } from '../../../app/services/routing'; const testBedConfig = { store: ccrStore, memoryRouter: { - onRouter: router => (routing.reactRouter = router), + onRouter: (router) => (routing.reactRouter = router), }, }; const initTestBed = registerTestBed(AutoFollowPatternList, testBedConfig); -export const setup = props => { +export const setup = (props) => { const testBed = initTestBed(props); const EUI_TABLE = 'autoFollowPatternListTable'; diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_add.helpers.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_add.helpers.js index 856b09f3f3cba..9778b595111a2 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_add.helpers.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_add.helpers.js @@ -12,13 +12,13 @@ import { routing } from '../../../app/services/routing'; const testBedConfig = { store: ccrStore, memoryRouter: { - onRouter: router => (routing.reactRouter = router), + onRouter: (router) => (routing.reactRouter = router), }, }; const initTestBed = registerTestBed(FollowerIndexAdd, testBedConfig); -export const setup = props => { +export const setup = (props) => { const testBed = initTestBed(props); // User actions diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_edit.helpers.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_edit.helpers.js index 893d01f151bc2..993cde86ada22 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_edit.helpers.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_edit.helpers.js @@ -14,7 +14,7 @@ import { FOLLOWER_INDEX_EDIT_NAME } from './constants'; const testBedConfig = { store: ccrStore, memoryRouter: { - onRouter: router => (routing.reactRouter = router), + onRouter: (router) => (routing.reactRouter = router), // The follower index id to fetch is read from the router ":id" param // so we first set it in our initial entries initialEntries: [`/${FOLLOWER_INDEX_EDIT_NAME}`], @@ -25,7 +25,7 @@ const testBedConfig = { const initTestBed = registerTestBed(FollowerIndexEdit, testBedConfig); -export const setup = props => { +export const setup = (props) => { const testBed = initTestBed(props); // User actions diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_list.helpers.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_list.helpers.js index 5e9f7d1263cf7..16a4fa9cd3f3e 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_list.helpers.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/follower_index_list.helpers.js @@ -12,13 +12,13 @@ import { routing } from '../../../app/services/routing'; const testBedConfig = { store: ccrStore, memoryRouter: { - onRouter: router => (routing.reactRouter = router), + onRouter: (router) => (routing.reactRouter = router), }, }; const initTestBed = registerTestBed(FollowerIndicesList, testBedConfig); -export const setup = props => { +export const setup = (props) => { const testBed = initTestBed(props); const EUI_TABLE = 'followerIndexListTable'; @@ -39,10 +39,7 @@ export const setup = props => { const clickContextMenuButtonAt = (index = 0) => { const contextMenu = testBed.find('contextMenu'); - contextMenu - .find('button') - .at(index) - .simulate('click'); + contextMenu.find('button').at(index).simulate('click'); }; const openTableRowContextMenuAt = (index = 0) => { diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/home.helpers.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/home.helpers.js index 56dfa765bfa4f..26a0d86cdcbca 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/home.helpers.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/home.helpers.js @@ -15,7 +15,7 @@ const testBedConfig = { memoryRouter: { initialEntries: [`${BASE_PATH}/follower_indices`], componentRoutePath: `${BASE_PATH}/:section`, - onRouter: router => (routing.reactRouter = router), + onRouter: (router) => (routing.reactRouter = router), }, }; diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/http_requests.js b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/http_requests.js index e2bd54a92a1f1..e37ec0d40ee5b 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/http_requests.js +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/helpers/http_requests.js @@ -7,14 +7,14 @@ import sinon from 'sinon'; // Register helpers to mock HTTP Requests -const registerHttpRequestMockHelpers = server => { +const registerHttpRequestMockHelpers = (server) => { const mockResponse = (defaultResponse, response) => [ 200, { 'Content-Type': 'application/json' }, JSON.stringify({ ...defaultResponse, ...response }), ]; - const setLoadFollowerIndicesResponse = response => { + const setLoadFollowerIndicesResponse = (response) => { const defaultResponse = { indices: [] }; server.respondWith( @@ -24,7 +24,7 @@ const registerHttpRequestMockHelpers = server => { ); }; - const setLoadAutoFollowPatternsResponse = response => { + const setLoadAutoFollowPatternsResponse = (response) => { const defaultResponse = { patterns: [] }; server.respondWith( @@ -34,7 +34,7 @@ const registerHttpRequestMockHelpers = server => { ); }; - const setDeleteAutoFollowPatternResponse = response => { + const setDeleteAutoFollowPatternResponse = (response) => { const defaultResponse = { errors: [], itemsDeleted: [] }; server.respondWith( @@ -44,7 +44,7 @@ const registerHttpRequestMockHelpers = server => { ); }; - const setAutoFollowStatsResponse = response => { + const setAutoFollowStatsResponse = (response) => { const defaultResponse = { numberOfFailedFollowIndices: 0, numberOfFailedRemoteClusterStateRequests: 0, @@ -82,7 +82,7 @@ const registerHttpRequestMockHelpers = server => { } }; - const setGetAutoFollowPatternResponse = response => { + const setGetAutoFollowPatternResponse = (response) => { const defaultResponse = {}; server.respondWith( @@ -100,7 +100,7 @@ const registerHttpRequestMockHelpers = server => { ]); }; - const setGetFollowerIndexResponse = response => { + const setGetFollowerIndexResponse = (response) => { const defaultResponse = {}; server.respondWith( diff --git a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/mocks/track_ui_metric.mock.ts b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/mocks/track_ui_metric.mock.ts index 016e259343285..5460b482cd579 100644 --- a/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/mocks/track_ui_metric.mock.ts +++ b/x-pack/plugins/cross_cluster_replication/public/__jest__/client_integration/mocks/track_ui_metric.mock.ts @@ -8,6 +8,6 @@ jest.mock('../../../app/services/track_ui_metric', () => ({ ...jest.requireActual('../../../app/services/track_ui_metric'), trackUiMetric: jest.fn(), trackUserRequest: (request: Promise) => { - return request.then(response => response); + return request.then((response) => response); }, })); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_delete_provider.js b/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_delete_provider.js index f9c03165dcf97..4ed4bc45c7b19 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_delete_provider.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_delete_provider.js @@ -19,13 +19,13 @@ class AutoFollowPatternDeleteProviderUi extends PureComponent { ids: null, }; - onMouseOverModal = event => { + onMouseOverModal = (event) => { // This component can sometimes be used inside of an EuiToolTip, in which case mousing over // the modal can trigger the tooltip. Stopping propagation prevents this. event.stopPropagation(); }; - deleteAutoFollowPattern = id => { + deleteAutoFollowPattern = (id) => { this.setState({ isModalOpen: true, ids: arrify(id) }); }; @@ -91,7 +91,7 @@ class AutoFollowPatternDeleteProviderUi extends PureComponent { />

    - {ids.map(id => ( + {ids.map((id) => (
  • {id}
  • ))}
@@ -115,8 +115,8 @@ class AutoFollowPatternDeleteProviderUi extends PureComponent { } } -const mapDispatchToProps = dispatch => ({ - deleteAutoFollowPattern: id => dispatch(deleteAutoFollowPattern(id)), +const mapDispatchToProps = (dispatch) => ({ + deleteAutoFollowPattern: (id) => dispatch(deleteAutoFollowPattern(id)), }); export const AutoFollowPatternDeleteProvider = connect( diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_form.js b/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_form.js index c817637ae1854..7874f6ac649eb 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_form.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/auto_follow_pattern_form.js @@ -107,7 +107,7 @@ export class AutoFollowPatternForm extends PureComponent { })); }; - onFieldsChange = fields => { + onFieldsChange = (fields) => { this.setState(({ autoFollowPattern }) => ({ autoFollowPattern: { ...autoFollowPattern, @@ -119,14 +119,14 @@ export class AutoFollowPatternForm extends PureComponent { this.onFieldsErrorChange(errors); }; - onFieldsErrorChange = errors => + onFieldsErrorChange = (errors) => this.setState(({ fieldsErrors }) => updateFormErrors(errors, fieldsErrors)); - onClusterChange = remoteCluster => { + onClusterChange = (remoteCluster) => { this.onFieldsChange({ remoteCluster }); }; - onCreateLeaderIndexPattern = indexPattern => { + onCreateLeaderIndexPattern = (indexPattern) => { const error = validateLeaderIndexPattern(indexPattern); if (error) { @@ -152,13 +152,13 @@ export class AutoFollowPatternForm extends PureComponent { this.onFieldsChange({ leaderIndexPatterns: newLeaderIndexPatterns }); }; - onLeaderIndexPatternChange = indexPatterns => { + onLeaderIndexPatternChange = (indexPatterns) => { this.onFieldsChange({ leaderIndexPatterns: indexPatterns.map(({ label }) => label), }); }; - onLeaderIndexPatternInputChange = leaderIndexPattern => { + onLeaderIndexPatternInputChange = (leaderIndexPattern) => { const isEmpty = !leaderIndexPattern || !leaderIndexPattern.trim(); const { autoFollowPattern: { leaderIndexPatterns }, @@ -205,7 +205,7 @@ export class AutoFollowPatternForm extends PureComponent { isFormValid() { return Object.values(this.state.fieldsErrors).every( - error => error === undefined || error === null + (error) => error === undefined || error === null ); } @@ -306,7 +306,7 @@ export class AutoFollowPatternForm extends PureComponent { this.onFieldsChange({ name: e.target.value })} + onChange={(e) => this.onFieldsChange({ name: e.target.value })} fullWidth disabled={!isNew} data-test-subj="nameInput" @@ -329,7 +329,7 @@ export class AutoFollowPatternForm extends PureComponent { defaultMessage="Auto-follow patterns capture indices on remote clusters." /> ), - remoteClusterNotConnectedNotEditable: name => ({ + remoteClusterNotConnectedNotEditable: (name) => ({ title: ( ), }), - remoteClusterDoesNotExist: name => ( + remoteClusterDoesNotExist: (name) => ( @@ -547,7 +551,9 @@ export class AutoFollowPatternForm extends PureComponent { this.onFieldsChange({ followIndexPatternSuffix: e.target.value })} + onChange={(e) => + this.onFieldsChange({ followIndexPatternSuffix: e.target.value }) + } fullWidth data-test-subj="suffixInput" /> diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/advanced_settings_fields.js b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/advanced_settings_fields.js index 81c7ca396c511..d423dd0b1f58d 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/advanced_settings_fields.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/advanced_settings_fields.js @@ -309,7 +309,7 @@ export const emptyAdvancedSettings = advancedSettingsFields.reduce((obj, advance }, {}); export function areAdvancedSettingsEdited(followerIndex) { - return advancedSettingsFields.some(advancedSetting => { + return advancedSettingsFields.some((advancedSetting) => { const { field } = advancedSetting; return followerIndex[field] !== emptyAdvancedSettings[field]; }); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/follower_index_form.js b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/follower_index_form.js index d824efd56cef1..28673c55fd031 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/follower_index_form.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_form/follower_index_form.js @@ -71,7 +71,7 @@ const getEmptyFollowerIndex = (remoteClusterName = '') => ({ /** * State transitions: fields update */ -export const updateFields = fields => ({ followerIndex }) => ({ +export const updateFields = (fields) => ({ followerIndex }) => ({ followerIndex: { ...followerIndex, ...fields, @@ -81,7 +81,7 @@ export const updateFields = fields => ({ followerIndex }) => ({ /** * State transitions: errors update */ -export const updateFormErrors = errors => ({ fieldsErrors }) => ({ +export const updateFormErrors = (errors) => ({ fieldsErrors }) => ({ fieldsErrors: { ...fieldsErrors, ...errors, @@ -147,7 +147,7 @@ export class FollowerIndexForm extends PureComponent { })); }; - onFieldsChange = fields => { + onFieldsChange = (fields) => { this.setState(updateFields(fields)); const newFields = { @@ -162,7 +162,7 @@ export class FollowerIndexForm extends PureComponent { } }; - getFieldsErrors = newFields => { + getFieldsErrors = (newFields) => { return Object.keys(newFields).reduce((errors, field) => { const validator = fieldToValidatorMap[field]; const value = newFields[field]; @@ -201,10 +201,10 @@ export class FollowerIndexForm extends PureComponent { this.validateIndexName(name); }; - validateIndexName = async name => { + validateIndexName = async (name) => { try { const indices = await loadIndices(); - const doesExist = indices.some(index => index.name === name); + const doesExist = indices.some((index) => index.name === name); if (doesExist) { const error = { message: ( @@ -252,7 +252,7 @@ export class FollowerIndexForm extends PureComponent { } }; - onClusterChange = remoteCluster => { + onClusterChange = (remoteCluster) => { this.onFieldsChange({ remoteCluster }); }; @@ -260,7 +260,7 @@ export class FollowerIndexForm extends PureComponent { return this.state.followerIndex; }; - toggleAdvancedSettings = event => { + toggleAdvancedSettings = (event) => { // If the user edits the advanced settings but then hides them, we need to make sure the // edited values don't get sent to the API when the user saves, but we *do* want to restore // these values to the form when the user re-opens the advanced settings. @@ -298,7 +298,7 @@ export class FollowerIndexForm extends PureComponent { isFormValid() { return Object.values(this.state.fieldsErrors).every( - error => error === undefined || error === null + (error) => error === undefined || error === null ); } @@ -440,7 +440,7 @@ export class FollowerIndexForm extends PureComponent { defaultMessage="Replication requires a leader index on a remote cluster." /> ), - remoteClusterNotConnectedNotEditable: name => ({ + remoteClusterNotConnectedNotEditable: (name) => ({ title: ( ), }), - remoteClusterDoesNotExist: name => ( + remoteClusterDoesNotExist: (name) => ( - {advancedSettingsFields.map(advancedSetting => { + {advancedSettingsFields.map((advancedSetting) => { const { field, testSubject, diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_pause_provider.js b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_pause_provider.js index 5965bfd8cc603..9c1e8255d069c 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_pause_provider.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_pause_provider.js @@ -25,18 +25,18 @@ class FollowerIndexPauseProviderUi extends PureComponent { indices: [], }; - onMouseOverModal = event => { + onMouseOverModal = (event) => { // This component can sometimes be used inside of an EuiToolTip, in which case mousing over // the modal can trigger the tooltip. Stopping propagation prevents this. event.stopPropagation(); }; - pauseFollowerIndex = index => { + pauseFollowerIndex = (index) => { this.setState({ isModalOpen: true, indices: arrify(index) }); }; onConfirm = () => { - this.props.pauseFollowerIndex(this.state.indices.map(index => index.name)); + this.props.pauseFollowerIndex(this.state.indices.map((index) => index.name)); this.setState({ isModalOpen: false, indices: [] }); this.props.onConfirm && this.props.onConfirm(); }; @@ -65,7 +65,7 @@ class FollowerIndexPauseProviderUi extends PureComponent { values: { count: indices.length }, } ); - const hasCustomSettings = indices.some(index => !areAllSettingsDefault(index)); + const hasCustomSettings = indices.some((index) => !areAllSettingsDefault(index)); return ( @@ -118,7 +118,7 @@ class FollowerIndexPauseProviderUi extends PureComponent {

    - {indices.map(index => ( + {indices.map((index) => (
  • {index.name}
  • ))}
@@ -142,8 +142,8 @@ class FollowerIndexPauseProviderUi extends PureComponent { } } -const mapDispatchToProps = dispatch => ({ - pauseFollowerIndex: id => dispatch(pauseFollowerIndex(id)), +const mapDispatchToProps = (dispatch) => ({ + pauseFollowerIndex: (id) => dispatch(pauseFollowerIndex(id)), }); export const FollowerIndexPauseProvider = connect( diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_resume_provider.js b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_resume_provider.js index ed9bc015c87e2..6e4c019dab85c 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_resume_provider.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_resume_provider.js @@ -25,13 +25,13 @@ class FollowerIndexResumeProviderUi extends PureComponent { ids: null, }; - onMouseOverModal = event => { + onMouseOverModal = (event) => { // This component can sometimes be used inside of an EuiToolTip, in which case mousing over // the modal can trigger the tooltip. Stopping propagation prevents this. event.stopPropagation(); }; - resumeFollowerIndex = id => { + resumeFollowerIndex = (id) => { this.setState({ isModalOpen: true, ids: arrify(id) }); }; @@ -124,7 +124,7 @@ class FollowerIndexResumeProviderUi extends PureComponent {

    - {ids.map(id => ( + {ids.map((id) => (
  • {id}
  • ))}
@@ -148,8 +148,8 @@ class FollowerIndexResumeProviderUi extends PureComponent { } } -const mapDispatchToProps = dispatch => ({ - resumeFollowerIndex: id => dispatch(resumeFollowerIndex(id)), +const mapDispatchToProps = (dispatch) => ({ + resumeFollowerIndex: (id) => dispatch(resumeFollowerIndex(id)), }); export const FollowerIndexResumeProvider = connect( diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_unfollow_provider.js b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_unfollow_provider.js index f3b267a69b18c..68b6b970ad90b 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_unfollow_provider.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/follower_index_unfollow_provider.js @@ -24,13 +24,13 @@ class FollowerIndexUnfollowProviderUi extends PureComponent { ids: null, }; - onMouseOverModal = event => { + onMouseOverModal = (event) => { // This component can sometimes be used inside of an EuiToolTip, in which case mousing over // the modal can trigger the tooltip. Stopping propagation prevents this. event.stopPropagation(); }; - unfollowLeaderIndex = id => { + unfollowLeaderIndex = (id) => { this.setState({ isModalOpen: true, ids: arrify(id) }); }; @@ -110,7 +110,7 @@ class FollowerIndexUnfollowProviderUi extends PureComponent { />

    - {ids.map(id => ( + {ids.map((id) => (
  • {id}
  • ))}
@@ -134,8 +134,8 @@ class FollowerIndexUnfollowProviderUi extends PureComponent { } } -const mapDispatchToProps = dispatch => ({ - unfollowLeaderIndex: id => dispatch(unfollowLeaderIndex(id)), +const mapDispatchToProps = (dispatch) => ({ + unfollowLeaderIndex: (id) => dispatch(unfollowLeaderIndex(id)), }); export const FollowerIndexUnfollowProvider = connect( diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/form_entry_row.js b/x-pack/plugins/cross_cluster_replication/public/app/components/form_entry_row.js index afb0ae8a9c0c4..6c534db7fc7c5 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/form_entry_row.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/form_entry_row.js @@ -19,7 +19,7 @@ import { /** * State transitions: fields update */ -export const updateFields = newValues => ({ fields }) => ({ +export const updateFields = (newValues) => ({ fields }) => ({ fields: { ...fields, ...newValues, @@ -44,7 +44,7 @@ export class FormEntryRow extends PureComponent { testSubj: PropTypes.string, }; - onFieldChange = value => { + onFieldChange = (value) => { const { field, onValueUpdate, type } = this.props; const isNumber = type === 'number'; @@ -57,7 +57,7 @@ export class FormEntryRow extends PureComponent { onValueUpdate({ [field]: valueParsed }); }; - renderField = isInvalid => { + renderField = (isInvalid) => { const { value, type, disabled, isLoading, testSubj } = this.props; switch (type) { case 'number': @@ -65,7 +65,7 @@ export class FormEntryRow extends PureComponent { this.onFieldChange(e.target.value)} + onChange={(e) => this.onFieldChange(e.target.value)} disabled={disabled === true} isLoading={isLoading} fullWidth @@ -77,7 +77,7 @@ export class FormEntryRow extends PureComponent { this.onFieldChange(e.target.value)} + onChange={(e) => this.onFieldChange(e.target.value)} disabled={disabled === true} isLoading={isLoading} fullWidth diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_form_field.js b/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_form_field.js index 00d29ffdca3a6..7b06af890ae09 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_form_field.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_form_field.js @@ -28,7 +28,7 @@ const errorMessages = { defaultMessage="You need at least one remote cluster to create a follower index." /> ), - remoteClusterNotConnectedEditable: name => ({ + remoteClusterNotConnectedEditable: (name) => ({ title: ( c.name === clusterName); + const remoteCluster = remoteClusters.find((c) => c.name === clusterName); return remoteCluster && remoteCluster.isConnected ? { error: null } @@ -76,7 +76,7 @@ export class RemoteClustersFormField extends PureComponent { }; } - onRemoteClusterChange = cluster => { + onRemoteClusterChange = (cluster) => { const { onChange, onError } = this.props; const { error } = this.validateRemoteCluster(cluster); onChange(cluster); @@ -137,7 +137,7 @@ export class RemoteClustersFormField extends PureComponent { fullWidth options={remoteClustersOptions} value={hasClusters ? selected : ''} - onChange={e => { + onChange={(e) => { this.onRemoteClusterChange(e.target.value); }} hasNoInitialSelection={!hasClusters} @@ -252,7 +252,7 @@ export class RemoteClustersFormField extends PureComponent { ); }; - renderRemoteClusterDoesNotExist = name => { + renderRemoteClusterDoesNotExist = (name) => { const { currentUrl } = this.props; const title = i18n.translate( 'xpack.crossClusterReplication.remoteClustersFormField.remoteClusterNotFoundTitle', @@ -287,7 +287,7 @@ export class RemoteClustersFormField extends PureComponent { renderErrorMessage = () => { const { selected, remoteClusters, isEditable } = this.props; - const remoteCluster = remoteClusters.find(c => c.name === selected); + const remoteCluster = remoteClusters.find((c) => c.name === selected); const isSelectedRemoteClusterConnected = remoteCluster && remoteCluster.isConnected; let error; @@ -319,7 +319,7 @@ export class RemoteClustersFormField extends PureComponent { render() { const { remoteClusters, selected, isEditable, areErrorsVisible } = this.props; - const remoteCluster = remoteClusters.find(c => c.name === selected); + const remoteCluster = remoteClusters.find((c) => c.name === selected); const hasClusters = Boolean(remoteClusters.length); const isSelectedRemoteClusterConnected = remoteCluster && remoteCluster.isConnected; const isInvalid = areErrorsVisible && (!hasClusters || !isSelectedRemoteClusterConnected); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_provider.js b/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_provider.js index 5b26444a136b8..4690f02539886 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_provider.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/components/remote_clusters_provider.js @@ -19,7 +19,7 @@ export class RemoteClustersProvider extends PureComponent { } loadRemoteClusters() { - const sortClusterByName = remoteClusters => + const sortClusterByName = (remoteClusters) => remoteClusters.sort((a, b) => { if (a.name < b.name) { return -1; @@ -31,13 +31,13 @@ export class RemoteClustersProvider extends PureComponent { }); loadRemoteClusters() .then(sortClusterByName) - .then(remoteClusters => { + .then((remoteClusters) => { this.setState({ isLoading: false, remoteClusters, }); }) - .catch(error => { + .catch((error) => { this.setState({ isLoading: false, error, diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_add/auto_follow_pattern_add.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_add/auto_follow_pattern_add.container.js index 95ae14ab89f58..b34b831e07ca4 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_add/auto_follow_pattern_add.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_add/auto_follow_pattern_add.container.js @@ -13,12 +13,12 @@ import { AutoFollowPatternAdd as AutoFollowPatternAddView } from './auto_follow_ const scope = SECTIONS.AUTO_FOLLOW_PATTERN; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ apiStatus: getApiStatus(`${scope}-save`)(state), apiError: getApiError(`${scope}-save`)(state), }); -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ saveAutoFollowPattern: (id, autoFollowPattern) => dispatch(saveAutoFollowPattern(id, autoFollowPattern)), clearApiError: () => dispatch(clearApiError(scope)), diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_edit/auto_follow_pattern_edit.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_edit/auto_follow_pattern_edit.container.js index be470edc07537..4eb1054248737 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_edit/auto_follow_pattern_edit.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/auto_follow_pattern_edit/auto_follow_pattern_edit.container.js @@ -23,7 +23,7 @@ import { AutoFollowPatternEdit as AutoFollowPatternEditView } from './auto_follo const scope = SECTIONS.AUTO_FOLLOW_PATTERN; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ apiStatus: { get: getApiStatus(`${scope}-get`)(state), save: getApiStatus(`${scope}-save`)(state), @@ -36,9 +36,9 @@ const mapStateToProps = state => ({ autoFollowPattern: getSelectedAutoFollowPattern('edit')(state), }); -const mapDispatchToProps = dispatch => ({ - getAutoFollowPattern: id => dispatch(getAutoFollowPattern(id)), - selectAutoFollowPattern: id => dispatch(selectEditAutoFollowPattern(id)), +const mapDispatchToProps = (dispatch) => ({ + getAutoFollowPattern: (id) => dispatch(getAutoFollowPattern(id)), + selectAutoFollowPattern: (id) => dispatch(selectEditAutoFollowPattern(id)), saveAutoFollowPattern: (id, autoFollowPattern) => { // Strip out errors. const { active, remoteCluster, leaderIndexPatterns, followIndexPattern } = autoFollowPattern; diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_add/follower_index_add.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_add/follower_index_add.container.js index 16fcd876bef7f..7c667ccdd9ea8 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_add/follower_index_add.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_add/follower_index_add.container.js @@ -13,12 +13,12 @@ import { FollowerIndexAdd as FollowerIndexAddView } from './follower_index_add'; const scope = SECTIONS.FOLLOWER_INDEX; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ apiStatus: getApiStatus(`${scope}-save`)(state), apiError: getApiError(`${scope}-save`)(state), }); -const mapDispatchToProps = dispatch => ({ +const mapDispatchToProps = (dispatch) => ({ saveFollowerIndex: (id, followerIndex) => dispatch(saveFollowerIndex(id, followerIndex)), clearApiError: () => dispatch(clearApiError(`${scope}-save`)), }); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_edit/follower_index_edit.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_edit/follower_index_edit.container.js index 9bfbdda41fcd5..f870031f170db 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_edit/follower_index_edit.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/follower_index_edit/follower_index_edit.container.js @@ -23,7 +23,7 @@ import { FollowerIndexEdit as FollowerIndexEditView } from './follower_index_edi const scope = SECTIONS.FOLLOWER_INDEX; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ apiStatus: { get: getApiStatus(`${scope}-get`)(state), save: getApiStatus(`${scope}-save`)(state), @@ -36,9 +36,9 @@ const mapStateToProps = state => ({ followerIndex: getSelectedFollowerIndex('edit')(state), }); -const mapDispatchToProps = dispatch => ({ - getFollowerIndex: id => dispatch(getFollowerIndex(id)), - selectFollowerIndex: id => dispatch(selectEditFollowerIndex(id)), +const mapDispatchToProps = (dispatch) => ({ + getFollowerIndex: (id) => dispatch(getFollowerIndex(id)), + selectFollowerIndex: (id) => dispatch(selectEditFollowerIndex(id)), saveFollowerIndex: (id, followerIndex) => dispatch(saveFollowerIndex(id, followerIndex, true)), clearApiError: () => { dispatch(clearApiError(`${scope}-get`)); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/auto_follow_pattern_list.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/auto_follow_pattern_list.container.js index edd2d283e9bd5..9b06da54dd34c 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/auto_follow_pattern_list.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/auto_follow_pattern_list.container.js @@ -23,7 +23,7 @@ import { AutoFollowPatternList as AutoFollowPatternListView } from './auto_follo const scope = SECTIONS.AUTO_FOLLOW_PATTERN; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ autoFollowPatterns: getListAutoFollowPatterns(state), autoFollowPatternId: getSelectedAutoFollowPatternId('detail')(state), apiStatus: getApiStatus(scope)(state), @@ -31,9 +31,9 @@ const mapStateToProps = state => ({ isAuthorized: isApiAuthorized(scope)(state), }); -const mapDispatchToProps = dispatch => ({ - loadAutoFollowPatterns: inBackground => dispatch(loadAutoFollowPatterns(inBackground)), - selectAutoFollowPattern: id => dispatch(selectDetailAutoFollowPattern(id)), +const mapDispatchToProps = (dispatch) => ({ + loadAutoFollowPatterns: (inBackground) => dispatch(loadAutoFollowPatterns(inBackground)), + selectAutoFollowPattern: (id) => dispatch(selectDetailAutoFollowPattern(id)), loadAutoFollowStats: () => dispatch(loadAutoFollowStats()), }); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.container.js index d3a596c7422f2..941eba63fac4d 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.container.js @@ -17,14 +17,14 @@ import { AutoFollowPatternTable as AutoFollowPatternTableComponent } from './aut const scope = SECTIONS.AUTO_FOLLOW_PATTERN; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ apiStatusDelete: getApiStatus(`${scope}-delete`)(state), }); -const mapDispatchToProps = dispatch => ({ - selectAutoFollowPattern: name => dispatch(selectDetailAutoFollowPattern(name)), - pauseAutoFollowPattern: name => dispatch(pauseAutoFollowPattern(name)), - resumeAutoFollowPattern: name => dispatch(resumeAutoFollowPattern(name)), +const mapDispatchToProps = (dispatch) => ({ + selectAutoFollowPattern: (name) => dispatch(selectDetailAutoFollowPattern(name)), + pauseAutoFollowPattern: (name) => dispatch(pauseAutoFollowPattern(name)), + resumeAutoFollowPattern: (name) => dispatch(resumeAutoFollowPattern(name)), }); export const AutoFollowPatternTable = connect( diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.js index d682fdaadf818..273e2244a8cb1 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/auto_follow_pattern_table/auto_follow_pattern_table.js @@ -27,7 +27,7 @@ const getFilteredPatterns = (autoFollowPatterns, queryText) => { if (queryText) { const normalizedSearchText = queryText.toLowerCase(); - return autoFollowPatterns.filter(autoFollowPattern => { + return autoFollowPatterns.filter((autoFollowPattern) => { const { name, remoteCluster, @@ -107,7 +107,7 @@ export class AutoFollowPatternTable extends PureComponent { ), sortable: true, truncateText: false, - render: name => { + render: (name) => { return ( { @@ -130,7 +130,7 @@ export class AutoFollowPatternTable extends PureComponent { defaultMessage: 'Status', } ), - render: active => { + render: (active) => { const statusText = active ? i18n.translate( 'xpack.crossClusterReplication.autoFollowPatternList.table.statusTextActive', @@ -169,7 +169,7 @@ export class AutoFollowPatternTable extends PureComponent { defaultMessage: 'Leader patterns', } ), - render: leaderIndexPatterns => leaderIndexPatterns.join(', '), + render: (leaderIndexPatterns) => leaderIndexPatterns.join(', '), }, { field: 'followIndexPatternPrefix', @@ -217,7 +217,7 @@ export class AutoFollowPatternTable extends PureComponent { return ( { + onClick={(event) => { if (event.stopPropagation) { event.stopPropagation(); } @@ -270,7 +270,7 @@ export class AutoFollowPatternTable extends PureComponent { return ( - {deleteAutoFollowPattern => ( + {(deleteAutoFollowPattern) => ( deleteAutoFollowPattern(name)} data-test-subj="contextMenuDeleteButton" @@ -318,7 +318,7 @@ export class AutoFollowPatternTable extends PureComponent { }; const selection = { - onSelectionChange: selectedItems => + onSelectionChange: (selectedItems) => this.setState({ selectedItems: selectedItems.map(({ name }) => name) }), }; @@ -326,13 +326,11 @@ export class AutoFollowPatternTable extends PureComponent { toolsLeft: selectedItems.length ? ( - filteredAutoFollowPatterns.find(item => item.name === name) + patterns={this.state.selectedItems.map((name) => + filteredAutoFollowPatterns.find((item) => item.name === name) )} /> - ) : ( - undefined - ), + ) : undefined, onChange: this.onSearch, box: { incremental: true, diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/detail_panel/detail_panel.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/detail_panel/detail_panel.container.js index a5d72a5e7e136..dcf494bccf8ff 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/detail_panel/detail_panel.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/auto_follow_pattern_list/components/detail_panel/detail_panel.container.js @@ -16,7 +16,7 @@ import { SECTIONS } from '../../../../../constants'; const scope = SECTIONS.AUTO_FOLLOW_PATTERN; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ autoFollowPatternId: getSelectedAutoFollowPatternId('detail')(state), autoFollowPattern: getSelectedAutoFollowPattern('detail')(state), apiStatus: getApiStatus(scope)(state), diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/context_menu/context_menu.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/context_menu/context_menu.js index 4a66f7b717bac..6549905013025 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/context_menu/context_menu.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/context_menu/context_menu.js @@ -36,7 +36,7 @@ export class ContextMenu extends PureComponent { }; onButtonClick = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; @@ -47,7 +47,7 @@ export class ContextMenu extends PureComponent { }); }; - editFollowerIndex = id => { + editFollowerIndex = (id) => { const uri = routing.getFollowerIndexPath(id, '/edit', false); routing.navigate(uri); }; @@ -55,7 +55,7 @@ export class ContextMenu extends PureComponent { render() { const { followerIndices } = this.props; const followerIndicesLength = followerIndices.length; - const followerIndexNames = followerIndices.map(index => index.name); + const followerIndexNames = followerIndices.map((index) => index.name); const { iconSide = 'right', iconType = 'arrowDown', @@ -84,7 +84,7 @@ export class ContextMenu extends PureComponent { const pausedFollowerIndexNames = followerIndices .filter(({ isPaused }) => isPaused) - .map(index => index.name); + .map((index) => index.name); const activeFollowerIndices = followerIndices.filter(({ isPaused }) => !isPaused); return ( @@ -107,7 +107,7 @@ export class ContextMenu extends PureComponent { {activeFollowerIndices.length ? ( - {pauseFollowerIndex => ( + {(pauseFollowerIndex) => ( pauseFollowerIndex(activeFollowerIndices)} @@ -124,7 +124,7 @@ export class ContextMenu extends PureComponent { {pausedFollowerIndexNames.length ? ( - {resumeFollowerIndex => ( + {(resumeFollowerIndex) => ( resumeFollowerIndex(pausedFollowerIndexNames)} @@ -156,7 +156,7 @@ export class ContextMenu extends PureComponent { )} - {unfollowLeaderIndex => ( + {(unfollowLeaderIndex) => ( unfollowLeaderIndex(followerIndexNames)} diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/detail_panel/detail_panel.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/detail_panel/detail_panel.container.js index 46190c27b27e5..640b7a25ce06b 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/detail_panel/detail_panel.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/detail_panel/detail_panel.container.js @@ -16,7 +16,7 @@ import { SECTIONS } from '../../../../../constants'; const scope = SECTIONS.FOLLOWER_INDEX; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ followerIndexId: getSelectedFollowerIndexId('detail')(state), followerIndex: getSelectedFollowerIndex('detail')(state), apiStatus: getApiStatus(scope)(state), diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.container.js index 9c475082025f9..d1a175b92572e 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.container.js @@ -13,12 +13,12 @@ import { FollowerIndicesTable as FollowerIndicesTableComponent } from './followe const scope = SECTIONS.FOLLOWER_INDEX; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ apiStatusDelete: getApiStatus(`${scope}-delete`)(state), }); -const mapDispatchToProps = dispatch => ({ - selectFollowerIndex: name => dispatch(selectDetailFollowerIndex(name)), +const mapDispatchToProps = (dispatch) => ({ + selectFollowerIndex: (name) => dispatch(selectDetailFollowerIndex(name)), }); export const FollowerIndicesTable = connect( diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.js index e95b3b0356aba..ea4a35de2282a 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/components/follower_indices_table/follower_indices_table.js @@ -30,7 +30,7 @@ const getFilteredIndices = (followerIndices, queryText) => { if (queryText) { const normalizedSearchText = queryText.toLowerCase(); - return followerIndices.filter(followerIndex => { + return followerIndices.filter((followerIndex) => { const { name, remoteCluster, leaderIndex } = followerIndex; if (name.toLowerCase().includes(normalizedSearchText)) { @@ -96,7 +96,7 @@ export class FollowerIndicesTable extends PureComponent { }); }; - editFollowerIndex = id => { + editFollowerIndex = (id) => { const uri = routing.getFollowerIndexPath(id, '/edit', false); routing.navigate(uri); }; @@ -107,7 +107,7 @@ export class FollowerIndicesTable extends PureComponent { const actions = [ /* Pause or resume follower index */ { - render: followerIndex => { + render: (followerIndex) => { const { name, isPaused } = followerIndex; const label = isPaused ? i18n.translate( @@ -125,7 +125,7 @@ export class FollowerIndicesTable extends PureComponent { return isPaused ? ( - {resumeFollowerIndex => ( + {(resumeFollowerIndex) => ( resumeFollowerIndex(name)} data-test-subj="resumeButton"> {label} @@ -134,7 +134,7 @@ export class FollowerIndicesTable extends PureComponent { ) : ( - {pauseFollowerIndex => ( + {(pauseFollowerIndex) => ( pauseFollowerIndex(followerIndex)} data-test-subj="pauseButton" @@ -177,7 +177,7 @@ export class FollowerIndicesTable extends PureComponent { return ( - {unfollowLeaderIndex => ( + {(unfollowLeaderIndex) => ( unfollowLeaderIndex(name)} data-test-subj="unfollowButton"> {label} @@ -200,7 +200,7 @@ export class FollowerIndicesTable extends PureComponent { ), sortable: true, truncateText: false, - render: name => { + render: (name) => { return ( { @@ -224,7 +224,7 @@ export class FollowerIndicesTable extends PureComponent { ), truncateText: true, sortable: true, - render: isPaused => { + render: (isPaused) => { return isPaused ? ( this.setState({ selectedItems: newSelectedItems }), + onSelectionChange: (newSelectedItems) => this.setState({ selectedItems: newSelectedItems }), }; const search = { toolsLeft: selectedItems.length ? ( - ) : ( - undefined - ), + ) : undefined, onChange: this.onSearch, box: { incremental: true, diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/follower_indices_list.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/follower_indices_list.container.js index f49db53d9e304..0afb0536726a3 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/follower_indices_list.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/follower_indices_list/follower_indices_list.container.js @@ -19,7 +19,7 @@ import { FollowerIndicesList as FollowerIndicesListView } from './follower_indic const scope = SECTIONS.FOLLOWER_INDEX; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ followerIndices: getListFollowerIndices(state), followerIndexId: getSelectedFollowerIndexId('detail')(state), apiStatus: getApiStatus(scope)(state), @@ -27,9 +27,9 @@ const mapStateToProps = state => ({ isAuthorized: isApiAuthorized(scope)(state), }); -const mapDispatchToProps = dispatch => ({ - loadFollowerIndices: inBackground => dispatch(loadFollowerIndices(inBackground)), - selectFollowerIndex: id => dispatch(selectDetailFollowerIndex(id)), +const mapDispatchToProps = (dispatch) => ({ + loadFollowerIndices: (inBackground) => dispatch(loadFollowerIndices(inBackground)), + selectFollowerIndex: (id) => dispatch(selectDetailFollowerIndex(id)), }); export const FollowerIndicesList = connect( diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.container.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.container.js index 5b35436a483fe..c98eb4ba6ae17 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.container.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.container.js @@ -14,7 +14,7 @@ import { } from '../../store/selectors'; import { CrossClusterReplicationHome as CrossClusterReplicationHomeView } from './home'; -const mapStateToProps = state => ({ +const mapStateToProps = (state) => ({ autoFollowPatterns: getListAutoFollowPatterns(state), isAutoFollowApiAuthorized: isApiAuthorized(SECTIONS.AUTO_FOLLOW_PATTERN)(state), followerIndices: getListFollowerIndices(state), diff --git a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.js b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.js index bcd9dad114862..ec62dbc2d1603 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/sections/home/home.js @@ -59,7 +59,7 @@ export class CrossClusterReplicationHome extends PureComponent { }; } - onSectionChange = section => { + onSectionChange = (section) => { routing.navigate(`/${section}`); }; @@ -79,7 +79,7 @@ export class CrossClusterReplicationHome extends PureComponent { - {this.tabs.map(tab => ( + {this.tabs.map((tab) => ( this.onSectionChange(tab.id)} isSelected={tab.id === this.state.activeSection} diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/api.js b/x-pack/plugins/cross_cluster_replication/public/app/services/api.js index adff40ef29be6..72a4532bfafac 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/api.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/api.js @@ -43,17 +43,17 @@ export const getHttpClient = () => { // --- -const createIdString = ids => ids.map(id => encodeURIComponent(id)).join(','); +const createIdString = (ids) => ids.map((id) => encodeURIComponent(id)).join(','); /* Auto Follow Pattern */ export const loadAutoFollowPatterns = () => httpClient.get(`${API_BASE_PATH}/auto_follow_patterns`); -export const getAutoFollowPattern = id => +export const getAutoFollowPattern = (id) => httpClient.get(`${API_BASE_PATH}/auto_follow_patterns/${encodeURIComponent(id)}`); export const loadRemoteClusters = () => httpClient.get(API_REMOTE_CLUSTERS_BASE_PATH); -export const createAutoFollowPattern = autoFollowPattern => { +export const createAutoFollowPattern = (autoFollowPattern) => { const request = httpClient.post(`${API_BASE_PATH}/auto_follow_patterns`, { body: JSON.stringify(autoFollowPattern), }); @@ -68,16 +68,16 @@ export const updateAutoFollowPattern = (id, autoFollowPattern) => { return trackUserRequest(request, UIM_AUTO_FOLLOW_PATTERN_UPDATE); }; -export const deleteAutoFollowPattern = id => { +export const deleteAutoFollowPattern = (id) => { const ids = arrify(id); - const idString = ids.map(_id => encodeURIComponent(_id)).join(','); + const idString = ids.map((_id) => encodeURIComponent(_id)).join(','); const request = httpClient.delete(`${API_BASE_PATH}/auto_follow_patterns/${idString}`); const uiMetric = ids.length > 1 ? UIM_AUTO_FOLLOW_PATTERN_DELETE_MANY : UIM_AUTO_FOLLOW_PATTERN_DELETE; return trackUserRequest(request, uiMetric); }; -export const pauseAutoFollowPattern = id => { +export const pauseAutoFollowPattern = (id) => { const ids = arrify(id); const idString = ids.map(encodeURIComponent).join(','); const request = httpClient.post(`${API_BASE_PATH}/auto_follow_patterns/${idString}/pause`); @@ -87,7 +87,7 @@ export const pauseAutoFollowPattern = id => { return trackUserRequest(request, uiMetric); }; -export const resumeAutoFollowPattern = id => { +export const resumeAutoFollowPattern = (id) => { const ids = arrify(id); const idString = ids.map(encodeURIComponent).join(','); const request = httpClient.post(`${API_BASE_PATH}/auto_follow_patterns/${idString}/resume`); @@ -100,10 +100,10 @@ export const resumeAutoFollowPattern = id => { /* Follower Index */ export const loadFollowerIndices = () => httpClient.get(`${API_BASE_PATH}/follower_indices`); -export const getFollowerIndex = id => +export const getFollowerIndex = (id) => httpClient.get(`${API_BASE_PATH}/follower_indices/${encodeURIComponent(id)}`); -export const createFollowerIndex = followerIndex => { +export const createFollowerIndex = (followerIndex) => { const uiMetrics = [UIM_FOLLOWER_INDEX_CREATE]; const isUsingAdvancedSettings = !areAllSettingsDefault(followerIndex); if (isUsingAdvancedSettings) { @@ -115,7 +115,7 @@ export const createFollowerIndex = followerIndex => { return trackUserRequest(request, uiMetrics); }; -export const pauseFollowerIndex = id => { +export const pauseFollowerIndex = (id) => { const ids = arrify(id); const idString = createIdString(ids); const request = httpClient.put(`${API_BASE_PATH}/follower_indices/${idString}/pause`); @@ -123,7 +123,7 @@ export const pauseFollowerIndex = id => { return trackUserRequest(request, uiMetric); }; -export const resumeFollowerIndex = id => { +export const resumeFollowerIndex = (id) => { const ids = arrify(id); const idString = createIdString(ids); const request = httpClient.put(`${API_BASE_PATH}/follower_indices/${idString}/resume`); @@ -131,7 +131,7 @@ export const resumeFollowerIndex = id => { return trackUserRequest(request, uiMetric); }; -export const unfollowLeaderIndex = id => { +export const unfollowLeaderIndex = (id) => { const ids = arrify(id); const idString = createIdString(ids); const request = httpClient.put(`${API_BASE_PATH}/follower_indices/${idString}/unfollow`); @@ -189,10 +189,12 @@ export const loadIndices = () => { } abortController = new AbortController(); const { signal } = abortController; - return httpClient.get(`${API_INDEX_MANAGEMENT_BASE_PATH}/indices`, { signal }).then(response => { - abortController = null; - return response; - }); + return httpClient + .get(`${API_INDEX_MANAGEMENT_BASE_PATH}/indices`, { signal }) + .then((response) => { + abortController = null; + return response; + }); }; export const loadPermissions = () => httpClient.get(`${API_BASE_PATH}/permissions`); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_errors.js b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_errors.js index 70311d5ba1e4d..5433ee73282a0 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_errors.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_errors.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -export const parseAutoFollowError = error => { +export const parseAutoFollowError = (error) => { if (!error.leaderIndex) { return null; } @@ -27,7 +27,7 @@ export const parseAutoFollowError = error => { export const parseAutoFollowErrors = (recentAutoFollowErrors, maxErrorsToShow = 5) => recentAutoFollowErrors .map(parseAutoFollowError) - .filter(error => error !== null) + .filter((error) => error !== null) .reduce((byId, error) => { if (!byId[error.id]) { byId[error.id] = []; diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.js b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.js index 5d374ab3779e4..e717d130da2b0 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.js @@ -29,24 +29,22 @@ export const getPreviewIndicesFromAutoFollowPattern = ({ limit = 5, wildcardPlaceHolders = [ moment().format('YYYY-MM-DD'), - moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - moment() - .add(2, 'days') - .format('YYYY-MM-DD'), + moment().add(1, 'days').format('YYYY-MM-DD'), + moment().add(2, 'days').format('YYYY-MM-DD'), ], }) => { const indicesPreview = []; let indexPreview; let leaderIndexTemplate; - leaderIndexPatterns.forEach(leaderIndexPattern => { - wildcardPlaceHolders.forEach(placeHolder => { + leaderIndexPatterns.forEach((leaderIndexPattern) => { + wildcardPlaceHolders.forEach((placeHolder) => { leaderIndexTemplate = leaderIndexPattern.replace(/\*/g, placeHolder); indexPreview = getFollowPattern(prefix, suffix, leaderIndexTemplate); - if (!indicesPreview.some(_indexPreview => indexPreview.toString === _indexPreview.toString)) { + if ( + !indicesPreview.some((_indexPreview) => indexPreview.toString === _indexPreview.toString) + ) { indicesPreview.push(indexPreview); } }); @@ -58,7 +56,7 @@ export const getPreviewIndicesFromAutoFollowPattern = ({ }; }; -export const getPrefixSuffixFromFollowPattern = followPattern => { +export const getPrefixSuffixFromFollowPattern = (followPattern) => { let followIndexPatternPrefix; let followIndexPatternSuffix; diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.test.js b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.test.js index 56633549ef013..dc5b19799940d 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.test.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern.test.js @@ -29,14 +29,10 @@ describe('Auto-follo pattern service', () => { }); expect(hasMore).toBe(false); - expect(indicesPreview.map(preview => preview.toString)).toEqual([ + expect(indicesPreview.map((preview) => preview.toString)).toEqual([ `prefix_logstash-${moment().format('YYYY-MM-DD')}_suffix`, - `prefix_logstash-${moment() - .add(1, 'days') - .format('YYYY-MM-DD')}_suffix`, - `prefix_logstash-${moment() - .add(2, 'days') - .format('YYYY-MM-DD')}_suffix`, + `prefix_logstash-${moment().add(1, 'days').format('YYYY-MM-DD')}_suffix`, + `prefix_logstash-${moment().add(2, 'days').format('YYYY-MM-DD')}_suffix`, ]); }); @@ -50,18 +46,12 @@ describe('Auto-follo pattern service', () => { }); expect(hasMore).toBe(true); - expect(indicesPreview.map(preview => preview.toString)).toEqual([ + expect(indicesPreview.map((preview) => preview.toString)).toEqual([ `prefix_logstash-${moment().format('YYYY-MM-DD')}_suffix`, - `prefix_logstash-${moment() - .add(1, 'days') - .format('YYYY-MM-DD')}_suffix`, - `prefix_logstash-${moment() - .add(2, 'days') - .format('YYYY-MM-DD')}_suffix`, + `prefix_logstash-${moment().add(1, 'days').format('YYYY-MM-DD')}_suffix`, + `prefix_logstash-${moment().add(2, 'days').format('YYYY-MM-DD')}_suffix`, `prefix_other-${moment().format('YYYY-MM-DD')}_suffix`, - `prefix_other-${moment() - .add(1, 'days') - .format('YYYY-MM-DD')}_suffix`, + `prefix_other-${moment().add(1, 'days').format('YYYY-MM-DD')}_suffix`, ]); }); @@ -76,7 +66,7 @@ describe('Auto-follo pattern service', () => { wildcardPlaceHolders, }); - expect(indicesPreview.map(preview => preview.toString)).toEqual([ + expect(indicesPreview.map((preview) => preview.toString)).toEqual([ 'prefix_logstash-A_suffix', 'prefix_logstash-B_suffix', ]); diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern_validators.js b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern_validators.js index cf394d4b3c7d8..39d40389daa17 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern_validators.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/auto_follow_pattern_validators.js @@ -52,7 +52,7 @@ export const validateName = (name = '') => { return errorMsg; }; -export const validateLeaderIndexPattern = indexPattern => { +export const validateLeaderIndexPattern = (indexPattern) => { if (indexPattern) { const errors = indexPatterns.validate(indexPattern); @@ -100,7 +100,7 @@ export const validateLeaderIndexPattern = indexPattern => { return null; }; -export const validateLeaderIndexPatterns = indexPatterns => { +export const validateLeaderIndexPatterns = (indexPatterns) => { // We only need to check if a value has been provided, because validation for this field // has already been executed as the user has entered input into it. if (!indexPatterns.length) { @@ -117,7 +117,7 @@ export const validateLeaderIndexPatterns = indexPatterns => { return null; }; -export const validatePrefix = prefix => { +export const validatePrefix = (prefix) => { // If it's empty, it is valid if (!prefix || !prefix.trim()) { return null; @@ -161,7 +161,7 @@ export const validatePrefix = prefix => { return null; }; -export const validateSuffix = suffix => { +export const validateSuffix = (suffix) => { // If it's empty, it is valid if (!suffix || !suffix.trim()) { return null; @@ -200,7 +200,7 @@ export const validateAutoFollowPattern = (autoFollowPattern = {}) => { let error = null; let fieldValue; - Object.keys(autoFollowPattern).forEach(fieldName => { + Object.keys(autoFollowPattern).forEach((fieldName) => { fieldValue = autoFollowPattern[fieldName]; error = null; diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/follower_index_default_settings.js b/x-pack/plugins/cross_cluster_replication/public/app/services/follower_index_default_settings.js index 118a54887d404..7699b776620f4 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/follower_index_default_settings.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/follower_index_default_settings.js @@ -6,7 +6,7 @@ import { FOLLOWER_INDEX_ADVANCED_SETTINGS } from '../../../common/constants'; -export const getSettingDefault = name => { +export const getSettingDefault = (name) => { if (!FOLLOWER_INDEX_ADVANCED_SETTINGS[name]) { throw new Error(`Unknown setting ${name}`); } @@ -18,8 +18,8 @@ export const isSettingDefault = (name, value) => { return getSettingDefault(name) === value; }; -export const areAllSettingsDefault = settings => { - return Object.keys(FOLLOWER_INDEX_ADVANCED_SETTINGS).every(name => +export const areAllSettingsDefault = (settings) => { + return Object.keys(FOLLOWER_INDEX_ADVANCED_SETTINGS).every((name) => isSettingDefault(name, settings[name]) ); }; diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/get_remote_cluster_name.js b/x-pack/plugins/cross_cluster_replication/public/app/services/get_remote_cluster_name.js index bf144b7129475..4f47facf70b20 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/get_remote_cluster_name.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/get_remote_cluster_name.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -const getFirstConnectedCluster = clusters => { +const getFirstConnectedCluster = (clusters) => { for (let i = 0; i < clusters.length; i++) { if (clusters[i].isConnected) { return clusters[i]; @@ -16,7 +16,7 @@ const getFirstConnectedCluster = clusters => { }; export const getRemoteClusterName = (remoteClusters, selected) => { - return selected && remoteClusters.some(c => c.name === selected) + return selected && remoteClusters.some((c) => c.name === selected) ? selected : getFirstConnectedCluster(remoteClusters).name; }; diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/input_validation.js b/x-pack/plugins/cross_cluster_replication/public/app/services/input_validation.js index 7e2b45b625c1f..e702a47e91155 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/input_validation.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/input_validation.js @@ -8,17 +8,17 @@ import React from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; import { indices } from '../../../../../../src/plugins/es_ui_shared/public'; -const isEmpty = value => { +const isEmpty = (value) => { return !value || !value.trim().length; }; -const hasSpaces = value => (typeof value === 'string' ? value.includes(' ') : false); +const hasSpaces = (value) => (typeof value === 'string' ? value.includes(' ') : false); -const beginsWithPeriod = value => { +const beginsWithPeriod = (value) => { return value[0] === '.'; }; -const findIllegalCharacters = value => { +const findIllegalCharacters = (value) => { return indices.INDEX_ILLEGAL_CHARACTERS_VISIBLE.reduce((chars, char) => { if (value.includes(char)) { chars.push(char); @@ -28,7 +28,7 @@ const findIllegalCharacters = value => { }, []); }; -export const indexNameValidator = value => { +export const indexNameValidator = (value) => { if (isEmpty(value)) { return [ { return undefined; }; -export const leaderIndexValidator = value => { +export const leaderIndexValidator = (value) => { if (isEmpty(value)) { return [ +const isModifiedEvent = (event) => !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); -const isLeftClickEvent = event => event.button === 0; +const isLeftClickEvent = (event) => event.button === 0; const queryParamsFromObject = (params, encodeParams = false) => { if (!params) { @@ -48,7 +48,7 @@ class Routing { : to; const href = this._reactRouter.history.createHref(location); - const onClick = event => { + const onClick = (event) => { if (event.defaultPrevented) { return; } diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/track_ui_metric.ts b/x-pack/plugins/cross_cluster_replication/public/app/services/track_ui_metric.ts index aecc4eb83893f..b4307ed125bf2 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/track_ui_metric.ts +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/track_ui_metric.ts @@ -24,7 +24,7 @@ export function init(usageCollection: UsageCollectionSetup): void { */ export function trackUserRequest(request: Promise, actionType: string) { // Only track successful actions. - return request.then(response => { + return request.then((response) => { // It looks like we're using the wrong type here, added via // https://github.com/elastic/kibana/pull/41113/files#diff-e65a0a6696a9d723969afd871cbd60cdR19 // but we'll keep it for now to avoid discontinuity in our telemetry data. diff --git a/x-pack/plugins/cross_cluster_replication/public/app/services/utils.js b/x-pack/plugins/cross_cluster_replication/public/app/services/utils.js index 9769228098c12..06ce3962966e9 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/services/utils.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/services/utils.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -export const objectToArray = obj => Object.keys(obj).map(k => ({ ...obj[k], __id__: k })); +export const objectToArray = (obj) => Object.keys(obj).map((k) => ({ ...obj[k], __id__: k })); export const arrayToObject = (array, keyProp = 'id') => array.reduce((acc, item) => { diff --git a/x-pack/plugins/cross_cluster_replication/public/app/store/actions/api.js b/x-pack/plugins/cross_cluster_replication/public/app/store/actions/api.js index 4b97699ece2ff..6abb024b5dcce 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/store/actions/api.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/store/actions/api.js @@ -22,7 +22,10 @@ export const setApiError = ({ error, scope }) => ({ payload: { error, scope }, }); -export const clearApiError = scope => ({ type: t.API_ERROR_SET, payload: { error: null, scope } }); +export const clearApiError = (scope) => ({ + type: t.API_ERROR_SET, + payload: { error: null, scope }, +}); export const sendApiRequest = ({ label, diff --git a/x-pack/plugins/cross_cluster_replication/public/app/store/actions/auto_follow_pattern.js b/x-pack/plugins/cross_cluster_replication/public/app/store/actions/auto_follow_pattern.js index 52a22cb17d0a9..ea6801b55458d 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/store/actions/auto_follow_pattern.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/store/actions/auto_follow_pattern.js @@ -22,12 +22,12 @@ import { getSelectedAutoFollowPatternId } from '../selectors'; const { AUTO_FOLLOW_PATTERN: scope } = SECTIONS; -export const selectDetailAutoFollowPattern = id => ({ +export const selectDetailAutoFollowPattern = (id) => ({ type: t.AUTO_FOLLOW_PATTERN_SELECT_DETAIL, payload: id, }); -export const selectEditAutoFollowPattern = id => ({ +export const selectEditAutoFollowPattern = (id) => ({ type: t.AUTO_FOLLOW_PATTERN_SELECT_EDIT, payload: id, }); @@ -40,7 +40,7 @@ export const loadAutoFollowPatterns = (isUpdating = false) => handler: async () => await loadAutoFollowPatternsRequest(), }); -export const getAutoFollowPattern = id => +export const getAutoFollowPattern = (id) => sendApiRequest({ label: t.AUTO_FOLLOW_PATTERN_GET, scope: `${scope}-get`, @@ -82,7 +82,7 @@ export const saveAutoFollowPattern = (id, autoFollowPattern, isUpdating = false) }, }); -export const deleteAutoFollowPattern = id => +export const deleteAutoFollowPattern = (id) => sendApiRequest({ label: t.AUTO_FOLLOW_PATTERN_DELETE, scope: `${scope}-delete`, @@ -144,13 +144,13 @@ export const deleteAutoFollowPattern = id => }, }); -export const pauseAutoFollowPattern = id => +export const pauseAutoFollowPattern = (id) => sendApiRequest({ label: t.AUTO_FOLLOW_PATTERN_PAUSE, scope: `${scope}-pause`, status: API_STATUS.UPDATING, handler: () => pauseAutoFollowPatternRequest(id), - onSuccess: response => { + onSuccess: (response) => { /** * We can have 1 or more auto-follow pattern pause operations * that can fail or succeed. We will show 1 toast notification for each. @@ -200,13 +200,13 @@ export const pauseAutoFollowPattern = id => }, }); -export const resumeAutoFollowPattern = id => +export const resumeAutoFollowPattern = (id) => sendApiRequest({ label: t.AUTO_FOLLOW_PATTERN_RESUME, scope: `${scope}-resume`, status: API_STATUS.UPDATING, handler: () => resumeAutoFollowPatternRequest(id), - onSuccess: response => { + onSuccess: (response) => { /** * We can have 1 or more auto-follow pattern resume operations * that can fail or succeed. We will show 1 toast notification for each. diff --git a/x-pack/plugins/cross_cluster_replication/public/app/store/actions/follower_index.js b/x-pack/plugins/cross_cluster_replication/public/app/store/actions/follower_index.js index d081e0444eb58..61d0ed1d51c72 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/store/actions/follower_index.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/store/actions/follower_index.js @@ -23,12 +23,12 @@ import { getSelectedFollowerIndexId } from '../selectors'; const { FOLLOWER_INDEX: scope } = SECTIONS; -export const selectDetailFollowerIndex = id => ({ +export const selectDetailFollowerIndex = (id) => ({ type: t.FOLLOWER_INDEX_SELECT_DETAIL, payload: id, }); -export const selectEditFollowerIndex = id => ({ +export const selectEditFollowerIndex = (id) => ({ type: t.FOLLOWER_INDEX_SELECT_EDIT, payload: id, }); @@ -41,7 +41,7 @@ export const loadFollowerIndices = (isUpdating = false) => handler: async () => await loadFollowerIndicesRequest(), }); -export const getFollowerIndex = id => +export const getFollowerIndex = (id) => sendApiRequest({ label: t.FOLLOWER_INDEX_GET, scope: `${scope}-get`, @@ -83,7 +83,7 @@ export const saveFollowerIndex = (name, followerIndex, isUpdating = false) => }, }); -export const pauseFollowerIndex = id => +export const pauseFollowerIndex = (id) => sendApiRequest({ label: t.FOLLOWER_INDEX_PAUSE, status: API_STATUS.SAVING, @@ -142,7 +142,7 @@ export const pauseFollowerIndex = id => }, }); -export const resumeFollowerIndex = id => +export const resumeFollowerIndex = (id) => sendApiRequest({ label: t.FOLLOWER_INDEX_RESUME, status: API_STATUS.SAVING, @@ -202,7 +202,7 @@ export const resumeFollowerIndex = id => }, }); -export const unfollowLeaderIndex = id => +export const unfollowLeaderIndex = (id) => sendApiRequest({ label: t.FOLLOWER_INDEX_UNFOLLOW, status: API_STATUS.DELETING, diff --git a/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/auto_follow_pattern.js b/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/auto_follow_pattern.js index bd082f1b0372b..c09c02698106b 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/auto_follow_pattern.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/auto_follow_pattern.js @@ -14,17 +14,17 @@ const initialState = { selectedEditId: null, }; -const success = action => `${action}_SUCCESS`; +const success = (action) => `${action}_SUCCESS`; const setActiveForIds = (ids, byId, active) => { const shallowCopyByIds = { ...byId }; - ids.forEach(id => { + ids.forEach((id) => { shallowCopyByIds[id].active = active; }); return shallowCopyByIds; }; -const parseAutoFollowPattern = autoFollowPattern => { +const parseAutoFollowPattern = (autoFollowPattern) => { // Extract prefix and suffix from follow index pattern const { followIndexPatternPrefix, followIndexPatternSuffix } = getPrefixSuffixFromFollowPattern( autoFollowPattern.followIndexPattern @@ -56,7 +56,7 @@ export const reducer = (state = initialState, action) => { case success(t.AUTO_FOLLOW_PATTERN_DELETE): { const byId = { ...state.byId }; const { itemsDeleted } = action.payload; - itemsDeleted.forEach(id => delete byId[id]); + itemsDeleted.forEach((id) => delete byId[id]); return { ...state, byId }; } case success(t.AUTO_FOLLOW_PATTERN_PAUSE): { diff --git a/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/follower_index.js b/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/follower_index.js index fe69a465257ef..3fbc2ca967ec0 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/follower_index.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/follower_index.js @@ -13,9 +13,9 @@ const initialState = { selectedEditId: null, }; -const success = action => `${action}_SUCCESS`; +const success = (action) => `${action}_SUCCESS`; -const parseFollowerIndex = followerIndex => { +const parseFollowerIndex = (followerIndex) => { // Extract status into boolean return { ...followerIndex, isPaused: followerIndex.status === 'paused' }; }; @@ -42,7 +42,7 @@ export const reducer = (state = initialState, action) => { case success(t.FOLLOWER_INDEX_UNFOLLOW): { const byId = { ...state.byId }; const { itemsUnfollowed } = action.payload; - itemsUnfollowed.forEach(id => delete byId[id]); + itemsUnfollowed.forEach((id) => delete byId[id]); return { ...state, byId }; } default: diff --git a/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/stats.js b/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/stats.js index 4cacfe1b759a5..39d3b1c4d8e4f 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/stats.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/store/reducers/stats.js @@ -11,7 +11,7 @@ const initialState = { autoFollow: null, }; -const success = action => `${action}_SUCCESS`; +const success = (action) => `${action}_SUCCESS`; export const reducer = (state = initialState, action) => { switch (action.type) { diff --git a/x-pack/plugins/cross_cluster_replication/public/app/store/selectors/index.js b/x-pack/plugins/cross_cluster_replication/public/app/store/selectors/index.js index 7dbc5a327bc66..eb0b88b95bbfc 100644 --- a/x-pack/plugins/cross_cluster_replication/public/app/store/selectors/index.js +++ b/x-pack/plugins/cross_cluster_replication/public/app/store/selectors/index.js @@ -9,12 +9,13 @@ import { objectToArray } from '../../services/utils'; import { API_STATUS } from '../../constants'; // Api -export const getApiState = state => state.api; -export const getApiStatus = scope => - createSelector(getApiState, apiState => apiState.status[scope] || API_STATUS.IDLE); -export const getApiError = scope => createSelector(getApiState, apiState => apiState.error[scope]); -export const isApiAuthorized = scope => - createSelector(getApiError(scope), error => { +export const getApiState = (state) => state.api; +export const getApiStatus = (scope) => + createSelector(getApiState, (apiState) => apiState.status[scope] || API_STATUS.IDLE); +export const getApiError = (scope) => + createSelector(getApiState, (apiState) => apiState.error[scope]); +export const isApiAuthorized = (scope) => + createSelector(getApiError(scope), (error) => { if (!error) { return true; } @@ -22,20 +23,20 @@ export const isApiAuthorized = scope => }); // Stats -export const getStatsState = state => state.stats; +export const getStatsState = (state) => state.stats; export const getAutoFollowStats = createSelector( getStatsState, - statsState => statsState.autoFollow + (statsState) => statsState.autoFollow ); // Auto-follow pattern -export const getAutoFollowPatternState = state => state.autoFollowPattern; +export const getAutoFollowPatternState = (state) => state.autoFollowPattern; export const getAutoFollowPatterns = createSelector( getAutoFollowPatternState, - autoFollowPatternsState => autoFollowPatternsState.byId + (autoFollowPatternsState) => autoFollowPatternsState.byId ); export const getSelectedAutoFollowPatternId = (view = 'detail') => - createSelector(getAutoFollowPatternState, autoFollowPatternsState => + createSelector(getAutoFollowPatternState, (autoFollowPatternsState) => view === 'detail' ? autoFollowPatternsState.selectedDetailId : autoFollowPatternsState.selectedEditId @@ -59,22 +60,23 @@ export const getSelectedAutoFollowPattern = (view = 'detail') => return autoFollowPattern ? { ...autoFollowPattern, errors } : null; } ); -export const getListAutoFollowPatterns = createSelector(getAutoFollowPatterns, autoFollowPatterns => - objectToArray(autoFollowPatterns) +export const getListAutoFollowPatterns = createSelector( + getAutoFollowPatterns, + (autoFollowPatterns) => objectToArray(autoFollowPatterns) ); // Follower index -export const getFollowerIndexState = state => state.followerIndex; +export const getFollowerIndexState = (state) => state.followerIndex; export const getFollowerIndices = createSelector( getFollowerIndexState, - followerIndexState => followerIndexState.byId + (followerIndexState) => followerIndexState.byId ); export const getSelectedFollowerIndexId = (view = 'detail') => - createSelector(getFollowerIndexState, followerIndexState => + createSelector(getFollowerIndexState, (followerIndexState) => view === 'detail' ? followerIndexState.selectedDetailId : followerIndexState.selectedEditId ); export const getSelectedFollowerIndex = (view = 'detail') => - createSelector(getFollowerIndexState, followerIndexState => { + createSelector(getFollowerIndexState, (followerIndexState) => { const propId = view === 'detail' ? 'selectedDetailId' : 'selectedEditId'; if (!followerIndexState[propId]) { @@ -82,6 +84,6 @@ export const getSelectedFollowerIndex = (view = 'detail') => } return followerIndexState.byId[followerIndexState[propId]]; }); -export const getListFollowerIndices = createSelector(getFollowerIndices, followerIndices => +export const getListFollowerIndices = createSelector(getFollowerIndices, (followerIndices) => objectToArray(followerIndices) ); diff --git a/x-pack/plugins/cross_cluster_replication/public/plugin.ts b/x-pack/plugins/cross_cluster_replication/public/plugin.ts index 561da838a4202..e748822ab8ae7 100644 --- a/x-pack/plugins/cross_cluster_replication/public/plugin.ts +++ b/x-pack/plugins/cross_cluster_replication/public/plugin.ts @@ -65,7 +65,7 @@ export class CrossClusterReplicationPlugin implements Plugin { licensing.license$ .pipe(first()) .toPromise() - .then(license => { + .then((license) => { const licenseStatus = license.check(PLUGIN.ID, PLUGIN.minimumLicenseType); const isLicenseOk = licenseStatus.state === 'valid'; const config = this.initializerContext.config.get(); diff --git a/x-pack/plugins/cross_cluster_replication/server/plugin.ts b/x-pack/plugins/cross_cluster_replication/server/plugin.ts index 7ef085a21ac1a..f30378d874a9a 100644 --- a/x-pack/plugins/cross_cluster_replication/server/plugin.ts +++ b/x-pack/plugins/cross_cluster_replication/server/plugin.ts @@ -57,7 +57,7 @@ const ccrDataEnricher = async (indicesList: Index[], callWithRequest: APICaller) 'transport.request', params ); - return indicesList.map(index => { + return indicesList.map((index) => { const isFollowerIndex = !!followerIndices.find( (followerIndex: { follower_index: string }) => { return followerIndex.follower_index === index.name; @@ -92,7 +92,7 @@ export class CrossClusterReplicationServerPlugin implements Plugin { + .then((config) => { // remoteClusters.isUiEnabled is driven by the xpack.remote_clusters.ui.enabled setting. // The CCR UI depends upon the Remote Clusters UI (e.g. by cross-linking to it), so if // the Remote Clusters UI is disabled we can't show the CCR UI. diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_delete_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_delete_route.ts index ed2633a4a469e..085e01a836942 100644 --- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_delete_route.ts +++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_delete_route.ts @@ -44,7 +44,7 @@ export const registerDeleteRoute = ({ }; await Promise.all( - ids.map(_id => + ids.map((_id) => context .crossClusterReplication!.client.callAsCurrentUser('ccr.deleteAutoFollowPattern', { id: _id, diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_pause_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_pause_route.ts index 325939709e751..ca224b9ae3627 100644 --- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_pause_route.ts +++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_pause_route.ts @@ -43,13 +43,13 @@ export const registerPauseRoute = ({ }; await Promise.all( - ids.map(_id => + ids.map((_id) => context .crossClusterReplication!.client.callAsCurrentUser('ccr.pauseAutoFollowPattern', { id: _id, }) .then(() => itemsPaused.push(_id)) - .catch(err => { + .catch((err) => { errors.push({ id: _id, error: formatError(err) }); }) ) diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_resume_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_resume_route.ts index f5e917773704c..c5f3e2190260e 100644 --- a/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_resume_route.ts +++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/auto_follow_pattern/register_resume_route.ts @@ -49,7 +49,7 @@ export const registerResumeRoute = ({ id: _id, }) .then(() => itemsResumed.push(_id)) - .catch(err => { + .catch((err) => { errors.push({ id: _id, error: formatError(err) }); }) ) diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_pause_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_pause_route.ts index 7432ea7ca5c82..bf6f026e70849 100644 --- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_pause_route.ts +++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_pause_route.ts @@ -47,7 +47,7 @@ export const registerPauseRoute = ({ id: _id, }) .then(() => itemsPaused.push(_id)) - .catch(err => { + .catch((err) => { errors.push({ id: _id, error: formatError(err) }); }) ) diff --git a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_resume_route.ts b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_resume_route.ts index ca8f3a9f5fe9d..03f21df2e856e 100644 --- a/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_resume_route.ts +++ b/x-pack/plugins/cross_cluster_replication/server/routes/api/follower_index/register_resume_route.ts @@ -47,7 +47,7 @@ export const registerResumeRoute = ({ id: _id, }) .then(() => itemsResumed.push(_id)) - .catch(err => { + .catch((err) => { errors.push({ id: _id, error: formatError(err) }); }) ) diff --git a/x-pack/plugins/cross_cluster_replication/server/services/license.ts b/x-pack/plugins/cross_cluster_replication/server/services/license.ts index bfd357867c3e2..5424092a01ee5 100644 --- a/x-pack/plugins/cross_cluster_replication/server/services/license.ts +++ b/x-pack/plugins/cross_cluster_replication/server/services/license.ts @@ -37,7 +37,7 @@ export class License { { pluginId, minimumLicenseType, defaultErrorMessage }: SetupSettings, { licensing, logger }: { licensing: LicensingPluginSetup; logger: Logger } ) { - licensing.license$.subscribe(license => { + licensing.license$.subscribe((license) => { const { state, message } = license.check(pluginId, minimumLicenseType); const hasRequiredLicense = state === 'valid'; diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/collect_config_container.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/collect_config_container.tsx index dc19fccf5c92f..6d6803510a281 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/collect_config_container.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/collect_config_container.tsx @@ -85,7 +85,7 @@ export class CollectConfigContainer extends React.Component< keepRange={config.useCurrentDateRange} isLoading={isLoading} error={error} - onDashboardSelect={dashboardId => { + onDashboardSelect={(dashboardId) => { onConfig({ ...config, dashboardId }); if (this.state.error) { this.setState({ error: undefined }); diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.story.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.story.tsx index f3a966a73509c..37f82e449ff72 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.story.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.story.tsx @@ -27,9 +27,9 @@ const InteractiveDemo: React.FC = () => { dashboards={dashboards} currentFilters={currentFilters} keepRange={keepRange} - onDashboardSelect={id => setActiveDashboardId(id)} - onCurrentFiltersToggle={() => setCurrentFilters(old => !old)} - onKeepRangeToggle={() => setKeepRange(old => !old)} + onDashboardSelect={(id) => setActiveDashboardId(id)} + onCurrentFiltersToggle={() => setCurrentFilters((old) => !old)} + onKeepRangeToggle={() => setKeepRange((old) => !old)} onSearchChange={() => {}} isLoading={false} /> @@ -44,7 +44,7 @@ storiesOf( console.log('onDashboardSelect', e)} + onDashboardSelect={(e) => console.log('onDashboardSelect', e)} onSearchChange={() => {}} isLoading={false} /> @@ -53,7 +53,7 @@ storiesOf( console.log('onDashboardSelect', e)} + onDashboardSelect={(e) => console.log('onDashboardSelect', e)} onCurrentFiltersToggle={() => console.log('onCurrentFiltersToggle')} onKeepRangeToggle={() => console.log('onKeepRangeToggle')} onSearchChange={() => {}} diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.tsx index a41a5fb718219..c9ecc74f1391c 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/components/dashboard_drilldown_config/dashboard_drilldown_config.tsx @@ -37,7 +37,7 @@ export const DashboardDrilldownConfig: React.FC = isLoading, error, }) => { - const selectedTitle = dashboards.find(item => item.value === activeDashboardId)?.label || ''; + const selectedTitle = dashboards.find((item) => item.value === activeDashboardId)?.label || ''; return ( <> diff --git a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.tsx b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.tsx index 21afa6e822dc5..7ff84a75dd52c 100644 --- a/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.tsx +++ b/x-pack/plugins/dashboard_enhanced/public/services/drilldowns/dashboard_to_dashboard_drilldown/drilldown.tsx @@ -38,7 +38,7 @@ export class DashboardToDashboardDrilldown public readonly euiIcon = 'dashboardApp'; - private readonly ReactCollectConfig: React.FC = props => ( + private readonly ReactCollectConfig: React.FC = (props) => ( ); @@ -93,7 +93,7 @@ export class DashboardToDashboardDrilldown const existingFilters = (config.useCurrentFilters ? currentFilters - : currentFilters?.filter(f => esFilters.isFilterPinned(f))) ?? []; + : currentFilters?.filter((f) => esFilters.isFilterPinned(f))) ?? []; // if useCurrentDashboardDataRange is enabled, then preserve current time range // if undefined is passed, then destination dashboard will figure out time range itself diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts index 211e0ad9a26c4..47cfb8cc61d00 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts @@ -34,7 +34,7 @@ describe('Kuery conjunction suggestions', () => { const suggestions = await getSuggestions(querySuggestionsArgs, mockKueryNode({ text })); expect(suggestions.length).toBe(2); - expect(suggestions.map(suggestion => suggestion.text)).toEqual(['and ', 'or ']); + expect(suggestions.map((suggestion) => suggestion.text)).toEqual(['and ', 'or ']); }); test('should suggest to insert the suggestion at the end of the string', async () => { @@ -43,8 +43,8 @@ describe('Kuery conjunction suggestions', () => { const suggestions = await getSuggestions(querySuggestionsArgs, mockKueryNode({ text, end })); expect(suggestions.length).toBe(2); - expect(suggestions.map(suggestion => suggestion.start)).toEqual([end, end]); - expect(suggestions.map(suggestion => suggestion.end)).toEqual([end, end]); + expect(suggestions.map((suggestion) => suggestion.start)).toEqual([end, end]); + expect(suggestions.map((suggestion) => suggestion.end)).toEqual([end, end]); }); test('should have descriptions', async () => { @@ -54,7 +54,7 @@ describe('Kuery conjunction suggestions', () => { expect(typeof suggestions).toBe('object'); expect(Object.keys(suggestions).length).toBe(2); - suggestions.forEach(suggestion => { + suggestions.forEach((suggestion) => { expect(typeof suggestion).toBe('object'); expect(suggestion).toHaveProperty('description'); }); diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.tsx b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.tsx index fedb43812d3d0..db5378982d646 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.tsx +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.tsx @@ -59,7 +59,7 @@ const conjunctions: Record = { ), }; -export const setupGetConjunctionSuggestions: KqlQuerySuggestionProvider = core => { +export const setupGetConjunctionSuggestions: KqlQuerySuggestionProvider = (core) => { return (querySuggestionsArgs, { text, end }) => { let suggestions: QuerySuggestion[] | [] = []; diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.test.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.test.ts index 2e12ae672f367..8751f7aee8123 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.test.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.test.ts @@ -110,7 +110,7 @@ describe('Kuery field suggestions', () => { mockKueryNode({ prefix, suffix }) ); expect(suggestions.length).toBeGreaterThan(0); - suggestions.forEach(suggestion => { + suggestions.forEach((suggestion) => { expect(suggestion).toHaveProperty('description'); }); }); diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.tsx b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.tsx index ca045c929f6a1..a8b5cc98c614f 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.tsx +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.tsx @@ -30,24 +30,26 @@ const getDescription = (field: IFieldType) => { const keywordComparator = (first: IFieldType, second: IFieldType) => { const extensions = ['raw', 'keyword']; - if (extensions.map(ext => `${first.name}.${ext}`).includes(second.name)) { + if (extensions.map((ext) => `${first.name}.${ext}`).includes(second.name)) { return 1; - } else if (extensions.map(ext => `${second.name}.${ext}`).includes(first.name)) { + } else if (extensions.map((ext) => `${second.name}.${ext}`).includes(first.name)) { return -1; } return first.name.localeCompare(second.name); }; -export const setupGetFieldSuggestions: KqlQuerySuggestionProvider = core => { +export const setupGetFieldSuggestions: KqlQuerySuggestionProvider = ( + core +) => { return ({ indexPatterns }, { start, end, prefix, suffix, nestedPath = '' }) => { const allFields = flatten( - indexPatterns.map(indexPattern => { + indexPatterns.map((indexPattern) => { return indexPattern.fields.filter(indexPatternsUtils.isFilterable); }) ); const search = `${prefix}${suffix}`.trim().toLowerCase(); - const matchingFields = allFields.filter(field => { + const matchingFields = allFields.filter((field) => { return ( (!nestedPath || (nestedPath && @@ -60,7 +62,7 @@ export const setupGetFieldSuggestions: KqlQuerySuggestionProvider { + const suggestions: QuerySuggestionField[] = sortedFields.map((field) => { const remainingPath = field.subType && field.subType.nested ? field.subType.nested.path.slice(nestedPath ? nestedPath.length + 1 : 0) diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/index.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/index.ts index 46fa7c68cee3e..546dc6361826a 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/index.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/index.ts @@ -51,7 +51,7 @@ export const setupKqlQuerySuggestionProvider = (core: CoreSetup): QuerySuggestio } }; - return querySuggestionsArgs => { + return (querySuggestionsArgs) => { const { query, selectionStart, selectionEnd } = querySuggestionsArgs; const cursoredQuery = `${query.substr(0, selectionStart)}${cursorSymbol}${query.substr( selectionEnd @@ -59,6 +59,6 @@ export const setupKqlQuerySuggestionProvider = (core: CoreSetup): QuerySuggestio return Promise.all( getSuggestionsByType(cursoredQuery, querySuggestionsArgs) - ).then(suggestionsByType => dedup(flatten(suggestionsByType))); + ).then((suggestionsByType) => dedup(flatten(suggestionsByType))); }; }; diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.ts index a00082f8c7d7c..2ddb3966bb560 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/lib/escape_kuery.ts @@ -28,8 +28,5 @@ function escapeNot(str: string) { // See the Space rule in kuery.peg function escapeWhitespace(str: string) { - return str - .replace(/\t/g, '\\t') - .replace(/\r/g, '\\r') - .replace(/\n/g, '\\n'); + return str.replace(/\t/g, '\\t').replace(/\r/g, '\\r').replace(/\n/g, '\\n'); } diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.test.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.test.ts index f7ffe1c2fec68..183ef2858a2b2 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.test.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.test.ts @@ -76,7 +76,7 @@ describe('Kuery operator suggestions', () => { expect(suggestions.length).toBeGreaterThan(0); - suggestions.forEach(suggestion => { + suggestions.forEach((suggestion) => { expect(suggestion).toHaveProperty('description'); }); }); diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.tsx b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.tsx index 14c42d73f8d0b..47990db82f1a2 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.tsx +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.tsx @@ -148,21 +148,21 @@ const getDescription = (operator: string) =>

{getOperatorByName(operator).des export const setupGetOperatorSuggestions: KqlQuerySuggestionProvider = () => { return ({ indexPatterns }, { end, fieldName, nestedPath }) => { const allFields = flatten( - indexPatterns.map(indexPattern => { + indexPatterns.map((indexPattern) => { return indexPattern.fields.slice(); }) ); const fullFieldName = nestedPath ? `${nestedPath}.${fieldName}` : fieldName; const fields = allFields - .filter(field => field.name === fullFieldName) - .map(field => { - const matchingOperators = Object.keys(operators).filter(operator => { + .filter((field) => field.name === fullFieldName) + .map((field) => { + const matchingOperators = Object.keys(operators).filter((operator) => { const { fieldTypes } = getOperatorByName(operator); return !fieldTypes || fieldTypes.includes(field.type); }); - const suggestions = matchingOperators.map(operator => ({ + const suggestions = matchingOperators.map((operator) => ({ type: QuerySuggestionTypes.Operator, text: operator + ' ', description: getDescription(operator), diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/sort_prefix_first.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/sort_prefix_first.ts index 03e1a9099f1ab..a8e2a83c57f75 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/sort_prefix_first.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/sort_prefix_first.ts @@ -12,7 +12,7 @@ export function sortPrefixFirst(array: any[], prefix?: string | number, property } const lowerCasePrefix = ('' + prefix).toLowerCase(); - const partitions = partition(array, entry => { + const partitions = partition(array, (entry) => { const value = ('' + (property ? entry[property] : entry)).toLowerCase(); return value.startsWith(lowerCasePrefix); diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.ts index bfd1e13ad9c39..6f9ba4d00109d 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.ts @@ -15,22 +15,22 @@ import { const wrapAsSuggestions = (start: number, end: number, query: string, values: string[]) => values - .filter(value => value.toLowerCase().includes(query.toLowerCase())) - .map(value => ({ + .filter((value) => value.toLowerCase().includes(query.toLowerCase())) + .map((value) => ({ type: QuerySuggestionTypes.Value, text: `${value} `, start, end, })); -export const setupGetValueSuggestions: KqlQuerySuggestionProvider = core => { +export const setupGetValueSuggestions: KqlQuerySuggestionProvider = (core) => { return async ( { indexPatterns, boolFilter, signal }, { start, end, prefix, suffix, fieldName, nestedPath } ): Promise => { const allFields = flatten( - indexPatterns.map(indexPattern => - indexPattern.fields.map(field => ({ + indexPatterns.map((indexPattern) => + indexPattern.fields.map((field) => ({ ...field, indexPattern, })) @@ -38,20 +38,20 @@ export const setupGetValueSuggestions: KqlQuerySuggestionProvider = core => { ); const fullFieldName = nestedPath ? `${nestedPath}.${fieldName}` : fieldName; - const fields = allFields.filter(field => field.name === fullFieldName); + const fields = allFields.filter((field) => field.name === fullFieldName); const query = `${prefix}${suffix}`.trim(); const { getValueSuggestions } = getAutocompleteService(); const data = await Promise.all( - fields.map(field => + fields.map((field) => getValueSuggestions({ indexPattern: field.indexPattern, field, query, boolFilter, signal, - }).then(valueSuggestions => { - const quotedValues = valueSuggestions.map(value => + }).then((valueSuggestions) => { + const quotedValues = valueSuggestions.map((value) => typeof value === 'string' ? `"${escapeQuotes(value)}"` : `${value}` ); diff --git a/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts b/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts index 1e554d3ff2d86..8df3114a8472a 100644 --- a/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts +++ b/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts @@ -11,7 +11,7 @@ import { CoreStart } from 'kibana/public'; jest.useFakeTimers(); -const flushPromises = () => new Promise(resolve => setImmediate(resolve)); +const flushPromises = () => new Promise((resolve) => setImmediate(resolve)); const mockSearch = jest.fn(); let searchInterceptor: EnhancedSearchInterceptor; let mockCoreStart: MockedKeys; diff --git a/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts b/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts index 472d39179b468..a4cf324f9d475 100644 --- a/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts +++ b/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts @@ -34,7 +34,7 @@ export class EnhancedSearchInterceptor extends SearchInterceptor { */ public runBeyondTimeout = () => { this.hideToast(); - this.timeoutSubscriptions.forEach(subscription => subscription.unsubscribe()); + this.timeoutSubscriptions.forEach((subscription) => subscription.unsubscribe()); this.timeoutSubscriptions.clear(); }; diff --git a/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts b/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts index bf502889ffa4f..15f2ca10af7f7 100644 --- a/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts +++ b/x-pack/plugins/data_enhanced/server/search/es_search_strategy.ts @@ -45,7 +45,7 @@ export const enhancedEsSearchStrategyProvider: TSearchStrategyProvider = async id => { + const cancel: ISearchCancel = async (id) => { const method = 'DELETE'; const path = encodeURI(`/_async_search/${id}`); await caller('transport.request', { method, path }); diff --git a/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.test.tsx b/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.test.tsx index 152eaf18f16c1..0f7f0cb22760b 100644 --- a/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.test.tsx +++ b/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.test.tsx @@ -136,7 +136,7 @@ test('Can delete multiple drilldowns', async () => { const checkboxes = screen.getAllByLabelText(/Select this drilldown/i); expect(checkboxes).toHaveLength(3); - checkboxes.forEach(checkbox => fireEvent.click(checkbox)); + checkboxes.forEach((checkbox) => fireEvent.click(checkbox)); expect(screen.queryByText(/Create/i)).not.toBeInTheDocument(); fireEvent.click(screen.getByText(/Delete \(3\)/i)); diff --git a/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx b/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx index ba273e7d578ff..3c9d2d2a86fb1 100644 --- a/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx +++ b/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/connected_flyout_manage_drilldowns.tsx @@ -115,7 +115,7 @@ export function createFlyoutManageDrilldowns({ function resolveInitialDrilldownWizardConfig(): DrilldownWizardConfig | undefined { if (route !== Routes.Edit) return undefined; if (!currentEditId) return undefined; - const drilldownToEdit = drilldowns?.find(d => d.eventId === currentEditId); + const drilldownToEdit = drilldowns?.find((d) => d.eventId === currentEditId); if (!drilldownToEdit) return undefined; return { @@ -200,11 +200,11 @@ export function createFlyoutManageDrilldowns({ showWelcomeMessage={shouldShowWelcomeMessage} onWelcomeHideClick={onHideWelcomeMessage} drilldowns={drilldowns.map(mapToDrilldownToDrilldownListItem)} - onDelete={ids => { + onDelete={(ids) => { setCurrentEditId(null); deleteDrilldown(ids); }} - onEdit={id => { + onEdit={(id) => { setCurrentEditId(id); setRoute(Routes.Edit); }} @@ -228,7 +228,7 @@ function useCompatibleActionFactoriesForCurrentContext factory.isCompatible(context)) + actionFactories.map((factory) => factory.isCompatible(context)) ); if (canceled) return; setCompatibleActionFactories(actionFactories.filter((_, i) => compatibility[i])); diff --git a/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/test_data.ts b/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/test_data.ts index 47a04222286cb..c9cb0b0eb1cb3 100644 --- a/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/test_data.ts +++ b/x-pack/plugins/drilldowns/public/components/connected_flyout_manage_drilldowns/test_data.ts @@ -48,8 +48,8 @@ class MockDynamicActionManager implements PublicMethodsOf const state = this.state.get(); let events = state.events; - eventIds.forEach(id => { - events = events.filter(e => e.eventId !== id); + eventIds.forEach((id) => { + events = events.filter((e) => e.eventId !== id); }); this.state.set({ @@ -65,7 +65,7 @@ class MockDynamicActionManager implements PublicMethodsOf ) { const state = this.state.get(); const events = state.events; - const idx = events.findIndex(e => e.eventId === eventId); + const idx = events.findIndex((e) => e.eventId === eventId); const event = { eventId, action, diff --git a/x-pack/plugins/drilldowns/public/components/form_drilldown_wizard/form_drilldown_wizard.tsx b/x-pack/plugins/drilldowns/public/components/form_drilldown_wizard/form_drilldown_wizard.tsx index 3bed81a971921..38168377b02bd 100644 --- a/x-pack/plugins/drilldowns/public/components/form_drilldown_wizard/form_drilldown_wizard.tsx +++ b/x-pack/plugins/drilldowns/public/components/form_drilldown_wizard/form_drilldown_wizard.tsx @@ -45,7 +45,7 @@ export const FormDrilldownWizard: React.FC = ({ placeholder={txtUntitledDrilldown} value={name} disabled={onNameChange === noopFn} - onChange={event => onNameChange(event.target.value)} + onChange={(event) => onNameChange(event.target.value)} data-test-subj="drilldownNameInput" /> @@ -60,8 +60,8 @@ export const FormDrilldownWizard: React.FC = ({ actionFactories={actionFactories} currentActionFactory={currentActionFactory} config={actionConfig} - onActionFactoryChange={actionFactory => onActionFactoryChange(actionFactory)} - onConfigChange={config => onActionConfigChange(config)} + onActionFactoryChange={(actionFactory) => onActionFactoryChange(actionFactory)} + onConfigChange={(config) => onActionConfigChange(config)} context={actionFactoryContext} /> diff --git a/x-pack/plugins/drilldowns/public/components/list_manage_drilldowns/list_manage_drilldowns.tsx b/x-pack/plugins/drilldowns/public/components/list_manage_drilldowns/list_manage_drilldowns.tsx index ab51c0a829ed3..cd41a3d6ec23a 100644 --- a/x-pack/plugins/drilldowns/public/components/list_manage_drilldowns/list_manage_drilldowns.tsx +++ b/x-pack/plugins/drilldowns/public/components/list_manage_drilldowns/list_manage_drilldowns.tsx @@ -92,8 +92,8 @@ export function ListManageDrilldowns({ isSelectable={true} responsive={false} selection={{ - onSelectionChange: selection => { - setSelectedDrilldowns(selection.map(drilldown => drilldown.id)); + onSelectionChange: (selection) => { + setSelectedDrilldowns(selection.map((drilldown) => drilldown.id)); }, selectableMessage: () => txtSelectDrilldown, }} diff --git a/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.ts b/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.ts index dcb44323f6d11..e93674ba650a7 100644 --- a/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.ts +++ b/x-pack/plugins/embeddable_enhanced/public/embeddables/embeddable_action_storage.ts @@ -78,7 +78,7 @@ export class EmbeddableActionStorage extends AbstractActionStorage { public async remove(eventId: string) { const input = this.embbeddable.getInput(); const events = input.enhancements?.dynamicActions?.events || []; - const index = events.findIndex(event => eventId === event.eventId); + const index = events.findIndex((event) => eventId === event.eventId); if (index === -1) { throw new Error( @@ -94,7 +94,7 @@ export class EmbeddableActionStorage extends AbstractActionStorage { public async read(eventId: string): Promise { const input = this.embbeddable.getInput(); const events = input.enhancements?.dynamicActions?.events || []; - const event = events.find(ev => eventId === ev.eventId); + const event = events.find((ev) => eventId === ev.eventId); if (!event) { throw new Error( diff --git a/x-pack/plugins/embeddable_enhanced/public/plugin.ts b/x-pack/plugins/embeddable_enhanced/public/plugin.ts index d48c4f9e860cc..d26acb4459a71 100644 --- a/x-pack/plugins/embeddable_enhanced/public/plugin.ts +++ b/x-pack/plugins/embeddable_enhanced/public/plugin.ts @@ -126,7 +126,7 @@ export class EmbeddableEnhancedPlugin uiActions: this.uiActions!, }); - dynamicActions.start().catch(error => { + dynamicActions.start().catch((error) => { /* eslint-disable */ console.log('Failed to start embeddable dynamic actions', embeddable); console.error(error); @@ -134,7 +134,7 @@ export class EmbeddableEnhancedPlugin }); const stop = () => { - dynamicActions.stop().catch(error => { + dynamicActions.stop().catch((error) => { /* eslint-disable */ console.log('Failed to stop embeddable dynamic actions', embeddable); console.error(error); diff --git a/x-pack/plugins/encrypted_saved_objects/server/config.test.ts b/x-pack/plugins/encrypted_saved_objects/server/config.test.ts index 8f74c461a2a9b..db07f0f9ce2c0 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/config.test.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/config.test.ts @@ -54,9 +54,7 @@ describe('createConfig$()', () => { mockRandomBytes.mockReturnValue('ab'.repeat(16)); const contextMock = coreMock.createPluginInitializerContext({}); - const config = await createConfig$(contextMock) - .pipe(first()) - .toPromise(); + const config = await createConfig$(contextMock).pipe(first()).toPromise(); expect(config).toEqual({ config: { encryptionKey: 'ab'.repeat(16) }, usingEphemeralEncryptionKey: true, @@ -75,9 +73,7 @@ describe('createConfig$()', () => { const contextMock = coreMock.createPluginInitializerContext({ encryptionKey: 'supersecret', }); - const config = await createConfig$(contextMock) - .pipe(first()) - .toPromise(); + const config = await createConfig$(contextMock).pipe(first()).toPromise(); expect(config).toEqual({ config: { encryptionKey: 'supersecret' }, usingEphemeralEncryptionKey: false, diff --git a/x-pack/plugins/encrypted_saved_objects/server/config.ts b/x-pack/plugins/encrypted_saved_objects/server/config.ts index 2f01850520724..9c751a9c67f52 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/config.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/config.ts @@ -21,7 +21,7 @@ export const ConfigSchema = schema.object({ export function createConfig$(context: PluginInitializerContext) { return context.config.create>().pipe( - map(config => { + map((config) => { const logger = context.logger.get('config'); let encryptionKey = config.encryptionKey; diff --git a/x-pack/plugins/encrypted_saved_objects/server/crypto/index.mock.ts b/x-pack/plugins/encrypted_saved_objects/server/crypto/index.mock.ts index de0a089ab8c66..11a0cd6f33307 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/crypto/index.mock.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/crypto/index.mock.ts @@ -21,7 +21,7 @@ export const encryptedSavedObjectsServiceMock = { attrs: T, action: (attrs: T, attrName: string, shouldExpose: boolean) => void ) { - const registration = registrations.find(r => r.type === descriptor.type); + const registration = registrations.find((r) => r.type === descriptor.type); if (!registration) { return attrs; } @@ -40,7 +40,7 @@ export const encryptedSavedObjectsServiceMock = { } mock.isRegistered.mockImplementation( - type => registrations.findIndex(r => r.type === type) >= 0 + (type) => registrations.findIndex((r) => r.type === type) >= 0 ); mock.encryptAttributes.mockImplementation(async (descriptor, attrs) => processAttributes( diff --git a/x-pack/plugins/encrypted_saved_objects/server/mocks.ts b/x-pack/plugins/encrypted_saved_objects/server/mocks.ts index d5550703cf761..38ac8f254315e 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/mocks.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/mocks.ts @@ -18,7 +18,7 @@ function createEncryptedSavedObjectsSetupMock() { function createEncryptedSavedObjectsStartMock() { return { isEncryptionError: jest.fn(), - getClient: jest.fn(opts => createEncryptedSavedObjectsClienttMock(opts)), + getClient: jest.fn((opts) => createEncryptedSavedObjectsClienttMock(opts)), } as jest.Mocked; } diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts index 8a4e78288e411..7098f611defa0 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts @@ -450,7 +450,7 @@ describe('#bulkUpdate', () => { ]; const mockedResponse = { - saved_objects: docs.map(doc => ({ + saved_objects: docs.map((doc) => ({ ...doc, attributes: { ...doc.attributes, @@ -465,7 +465,7 @@ describe('#bulkUpdate', () => { await expect( wrapper.bulkUpdate( - docs.map(doc => ({ ...doc })), + docs.map((doc) => ({ ...doc })), {} ) ).resolves.toEqual({ @@ -558,7 +558,7 @@ describe('#bulkUpdate', () => { const options = { namespace }; mockBaseClient.bulkUpdate.mockResolvedValue({ - saved_objects: docs.map(doc => ({ ...doc, references: undefined })), + saved_objects: docs.map((doc) => ({ ...doc, references: undefined })), }); await expect(wrapper.bulkUpdate(docs, options)).resolves.toEqual({ diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts index 7ba8ef3eaad8b..bdc2b6cb2e667 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts @@ -94,7 +94,7 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon // NodeJS thread pool. If it turns out to be a problem, we can consider switching to the // sequential processing. const encryptedObjects = await Promise.all( - objects.map(async object => { + objects.map(async (object) => { if (!this.options.service.isRegistered(object.type)) { return object; } @@ -137,7 +137,7 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon // NodeJS thread pool. If it turns out to be a problem, we can consider switching to the // sequential processing. const encryptedObjects = await Promise.all( - objects.map(async object => { + objects.map(async (object) => { const { type, id, attributes } = object; if (!this.options.service.isRegistered(type)) { return object; diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts index 9ab3e85cc8624..af00050183b77 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts @@ -62,7 +62,7 @@ export function setupSavedObjects({ }) ); - return clientOpts => { + return (clientOpts) => { const internalRepositoryAndTypeRegistryPromise = getStartServices().then( ([core]) => [ diff --git a/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts b/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts index 66c16d0ddf383..0144e573fc146 100644 --- a/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts +++ b/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts @@ -301,9 +301,7 @@ describe('queryEventsBySavedObject', () => { }, }); - const start = moment() - .subtract(1, 'days') - .toISOString(); + const start = moment().subtract(1, 'days').toISOString(); await clusterClientAdapter.queryEventsBySavedObject( 'index-name', @@ -374,12 +372,8 @@ describe('queryEventsBySavedObject', () => { }, }); - const start = moment() - .subtract(1, 'days') - .toISOString(); - const end = moment() - .add(1, 'days') - .toISOString(); + const start = moment().subtract(1, 'days').toISOString(); + const end = moment().add(1, 'days').toISOString(); await clusterClientAdapter.queryEventsBySavedObject( 'index-name', diff --git a/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts b/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts index c0ff87234c09d..7fd239ca49369 100644 --- a/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts +++ b/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts @@ -206,7 +206,7 @@ export class ClusterClientAdapter { page, per_page: perPage, total, - data: hits.map(hit => hit._source) as IEvent[], + data: hits.map((hit) => hit._source) as IEvent[], }; } catch (err) { throw new Error( diff --git a/x-pack/plugins/event_log/server/es/documents.test.ts b/x-pack/plugins/event_log/server/es/documents.test.ts index c08d0ac978bc9..2feb6e3b84f91 100644 --- a/x-pack/plugins/event_log/server/es/documents.test.ts +++ b/x-pack/plugins/event_log/server/es/documents.test.ts @@ -24,7 +24,7 @@ describe('getIndexTemplate()', () => { const indexTemplate = getIndexTemplate(esNames); expect(indexTemplate.index_patterns).toEqual([esNames.indexPatternWithVersion]); expect(indexTemplate.settings.number_of_shards).toBeGreaterThanOrEqual(0); - expect(indexTemplate.settings.number_of_replicas).toBeGreaterThanOrEqual(0); + expect(indexTemplate.settings.auto_expand_replicas).toBe('0-1'); expect(indexTemplate.settings['index.lifecycle.name']).toBe(esNames.ilmPolicy); expect(indexTemplate.settings['index.lifecycle.rollover_alias']).toBe(esNames.alias); expect(indexTemplate.mappings).toMatchObject({}); diff --git a/x-pack/plugins/event_log/server/es/documents.ts b/x-pack/plugins/event_log/server/es/documents.ts index 91b3db554964f..0dc7301568207 100644 --- a/x-pack/plugins/event_log/server/es/documents.ts +++ b/x-pack/plugins/event_log/server/es/documents.ts @@ -13,7 +13,7 @@ export function getIndexTemplate(esNames: EsNames) { index_patterns: [esNames.indexPatternWithVersion], settings: { number_of_shards: 1, - number_of_replicas: 1, + auto_expand_replicas: '0-1', 'index.lifecycle.name': esNames.ilmPolicy, 'index.lifecycle.rollover_alias': esNames.alias, }, diff --git a/x-pack/plugins/event_log/server/event_log_client.test.ts b/x-pack/plugins/event_log/server/event_log_client.test.ts index 17c073c4b27f9..16e5fa69d36f6 100644 --- a/x-pack/plugins/event_log/server/event_log_client.test.ts +++ b/x-pack/plugins/event_log/server/event_log_client.test.ts @@ -172,12 +172,8 @@ describe('EventLogStart', () => { }; esContext.esAdapter.queryEventsBySavedObject.mockResolvedValue(result); - const start = moment() - .subtract(1, 'days') - .toISOString(); - const end = moment() - .add(1, 'days') - .toISOString(); + const start = moment().subtract(1, 'days').toISOString(); + const end = moment().add(1, 'days').toISOString(); expect( await eventLogClient.findEventsBySavedObject('saved-object-type', 'saved-object-id', { diff --git a/x-pack/plugins/event_log/server/lib/delay.ts b/x-pack/plugins/event_log/server/lib/delay.ts index a37569baaf692..1c64141c15fb2 100644 --- a/x-pack/plugins/event_log/server/lib/delay.ts +++ b/x-pack/plugins/event_log/server/lib/delay.ts @@ -5,5 +5,5 @@ */ export async function delay(millis: number) { - await new Promise(resolve => setTimeout(resolve, millis)); + await new Promise((resolve) => setTimeout(resolve, millis)); } diff --git a/x-pack/plugins/event_log/server/lib/ready_signal.test.ts b/x-pack/plugins/event_log/server/lib/ready_signal.test.ts index 6f1d92034c06f..c216651ee94b1 100644 --- a/x-pack/plugins/event_log/server/lib/ready_signal.test.ts +++ b/x-pack/plugins/event_log/server/lib/ready_signal.test.ts @@ -13,7 +13,7 @@ describe('ReadySignal', () => { readySignal = createReadySignal(); }); - test('works as expected', async done => { + test('works as expected', async (done) => { let value = 41; timeoutSet(100, async () => { diff --git a/x-pack/plugins/event_log/server/lib/ready_signal.ts b/x-pack/plugins/event_log/server/lib/ready_signal.ts index 2ea8e655089da..58879649b83cb 100644 --- a/x-pack/plugins/event_log/server/lib/ready_signal.ts +++ b/x-pack/plugins/event_log/server/lib/ready_signal.ts @@ -12,7 +12,7 @@ export interface ReadySignal { export function createReadySignal(): ReadySignal { let resolver: (value: T) => void; - const promise = new Promise(resolve => { + const promise = new Promise((resolve) => { resolver = resolve; }); diff --git a/x-pack/plugins/event_log/server/routes/find.ts b/x-pack/plugins/event_log/server/routes/find.ts index f8e1c842ae436..e03aef7c757f6 100644 --- a/x-pack/plugins/event_log/server/routes/find.ts +++ b/x-pack/plugins/event_log/server/routes/find.ts @@ -29,7 +29,7 @@ export const findRoute = (router: IRouter) => { query: findOptionsSchema, }, }, - router.handleLegacyErrors(async function( + router.handleLegacyErrors(async function ( context: RequestHandlerContext, req: KibanaRequest, FindOptionsType, unknown>, res: KibanaResponseFactory diff --git a/x-pack/plugins/features/common/feature.ts b/x-pack/plugins/features/common/feature.ts index ef32a8a80a0bd..1b405094d9eda 100644 --- a/x-pack/plugins/features/common/feature.ts +++ b/x-pack/plugins/features/common/feature.ts @@ -133,7 +133,7 @@ export class Feature { constructor(protected readonly config: RecursiveReadonly) { this.subFeatures = (config.subFeatures ?? []).map( - subFeatureConfig => new SubFeature(subFeatureConfig) + (subFeatureConfig) => new SubFeature(subFeatureConfig) ); } diff --git a/x-pack/plugins/features/public/features_api_client.test.ts b/x-pack/plugins/features/public/features_api_client.test.ts index e3a25ad57425c..95f0c2d527d34 100644 --- a/x-pack/plugins/features/public/features_api_client.test.ts +++ b/x-pack/plugins/features/public/features_api_client.test.ts @@ -32,7 +32,7 @@ describe('Features API Client', () => { const client = new FeaturesAPIClient(coreSetup.http); const result = await client.getFeatures(); - expect(result.map(f => f.id)).toEqual([ + expect(result.map((f) => f.id)).toEqual([ 'feature-a', 'feature-b', 'feature-c', diff --git a/x-pack/plugins/features/public/features_api_client.ts b/x-pack/plugins/features/public/features_api_client.ts index b93c9bf917d79..50cc54a197f56 100644 --- a/x-pack/plugins/features/public/features_api_client.ts +++ b/x-pack/plugins/features/public/features_api_client.ts @@ -12,6 +12,6 @@ export class FeaturesAPIClient { public async getFeatures() { const features = await this.http.get('/api/features'); - return features.map(config => new Feature(config)); + return features.map((config) => new Feature(config)); } } diff --git a/x-pack/plugins/features/server/feature_registry.test.ts b/x-pack/plugins/features/server/feature_registry.test.ts index 2039f8f6acda2..75022922917b3 100644 --- a/x-pack/plugins/features/server/feature_registry.test.ts +++ b/x-pack/plugins/features/server/feature_registry.test.ts @@ -353,7 +353,7 @@ describe('FeatureRegistry', () => { ); }); - ['contains space', 'contains_invalid()_chars', ''].forEach(prohibitedChars => { + ['contains space', 'contains_invalid()_chars', ''].forEach((prohibitedChars) => { it(`prevents features from being registered with a navLinkId of "${prohibitedChars}"`, () => { const featureRegistry = new FeatureRegistry(); expect(() => @@ -396,7 +396,7 @@ describe('FeatureRegistry', () => { }); }); - ['catalogue', 'management', 'navLinks', `doesn't match valid regex`].forEach(prohibitedId => { + ['catalogue', 'management', 'navLinks', `doesn't match valid regex`].forEach((prohibitedId) => { it(`prevents features from being registered with an ID of "${prohibitedId}"`, () => { const featureRegistry = new FeatureRegistry(); expect(() => diff --git a/x-pack/plugins/features/server/feature_registry.ts b/x-pack/plugins/features/server/feature_registry.ts index 6140b7ac87ce0..12aafd226f754 100644 --- a/x-pack/plugins/features/server/feature_registry.ts +++ b/x-pack/plugins/features/server/feature_registry.ts @@ -32,14 +32,14 @@ export class FeatureRegistry { public getAll(): Feature[] { this.locked = true; - return Object.values(this.features).map(featureConfig => new Feature(featureConfig)); + return Object.values(this.features).map((featureConfig) => new Feature(featureConfig)); } } function applyAutomaticPrivilegeGrants(feature: FeatureConfig): FeatureConfig { const allPrivilege = feature.privileges?.all; const readPrivilege = feature.privileges?.read; - const reservedPrivileges = (feature.reserved?.privileges ?? []).map(rp => rp.privilege); + const reservedPrivileges = (feature.reserved?.privileges ?? []).map((rp) => rp.privilege); applyAutomaticAllPrivilegeGrants(allPrivilege, ...reservedPrivileges); applyAutomaticReadPrivilegeGrants(readPrivilege); @@ -50,7 +50,7 @@ function applyAutomaticPrivilegeGrants(feature: FeatureConfig): FeatureConfig { function applyAutomaticAllPrivilegeGrants( ...allPrivileges: Array ) { - allPrivileges.forEach(allPrivilege => { + allPrivileges.forEach((allPrivilege) => { if (allPrivilege) { allPrivilege.savedObject.all = uniq([...allPrivilege.savedObject.all, 'telemetry']); allPrivilege.savedObject.read = uniq([...allPrivilege.savedObject.read, 'config', 'url']); @@ -61,7 +61,7 @@ function applyAutomaticAllPrivilegeGrants( function applyAutomaticReadPrivilegeGrants( ...readPrivileges: Array ) { - readPrivileges.forEach(readPrivilege => { + readPrivileges.forEach((readPrivilege) => { if (readPrivilege) { readPrivilege.savedObject.read = uniq([...readPrivilege.savedObject.read, 'config', 'url']); } diff --git a/x-pack/plugins/features/server/feature_schema.ts b/x-pack/plugins/features/server/feature_schema.ts index 403d9586bf160..7497548cf8904 100644 --- a/x-pack/plugins/features/server/feature_schema.ts +++ b/x-pack/plugins/features/server/feature_schema.ts @@ -34,53 +34,33 @@ const privilegeSchema = Joi.object({ api: Joi.array().items(Joi.string()), app: Joi.array().items(Joi.string()), savedObject: Joi.object({ - all: Joi.array() - .items(Joi.string()) - .required(), - read: Joi.array() - .items(Joi.string()) - .required(), + all: Joi.array().items(Joi.string()).required(), + read: Joi.array().items(Joi.string()).required(), }).required(), - ui: Joi.array() - .items(Joi.string().regex(uiCapabilitiesRegex)) - .required(), + ui: Joi.array().items(Joi.string().regex(uiCapabilitiesRegex)).required(), }); const subFeaturePrivilegeSchema = Joi.object({ - id: Joi.string() - .regex(subFeaturePrivilegePartRegex) - .required(), + id: Joi.string().regex(subFeaturePrivilegePartRegex).required(), name: Joi.string().required(), - includeIn: Joi.string() - .allow('all', 'read', 'none') - .required(), + includeIn: Joi.string().allow('all', 'read', 'none').required(), management: managementSchema, catalogue: catalogueSchema, api: Joi.array().items(Joi.string()), app: Joi.array().items(Joi.string()), savedObject: Joi.object({ - all: Joi.array() - .items(Joi.string()) - .required(), - read: Joi.array() - .items(Joi.string()) - .required(), + all: Joi.array().items(Joi.string()).required(), + read: Joi.array().items(Joi.string()).required(), }).required(), - ui: Joi.array() - .items(Joi.string().regex(uiCapabilitiesRegex)) - .required(), + ui: Joi.array().items(Joi.string().regex(uiCapabilitiesRegex)).required(), }); const subFeatureSchema = Joi.object({ name: Joi.string().required(), privilegeGroups: Joi.array().items( Joi.object({ - groupType: Joi.string() - .valid('mutually_exclusive', 'independent') - .required(), - privileges: Joi.array() - .items(subFeaturePrivilegeSchema) - .min(1), + groupType: Joi.string().valid('mutually_exclusive', 'independent').required(), + privileges: Joi.array().items(subFeaturePrivilegeSchema).min(1), }) ), }); @@ -99,9 +79,7 @@ const schema = Joi.object({ icon: Joi.string(), description: Joi.string(), navLinkId: Joi.string().regex(uiCapabilitiesRegex), - app: Joi.array() - .items(Joi.string()) - .required(), + app: Joi.array().items(Joi.string()).required(), management: managementSchema, catalogue: catalogueSchema, privileges: Joi.object({ @@ -112,9 +90,7 @@ const schema = Joi.object({ .required(), subFeatures: Joi.when('privileges', { is: null, - then: Joi.array() - .items(subFeatureSchema) - .max(0), + then: Joi.array().items(subFeatureSchema).max(0), otherwise: Joi.array().items(subFeatureSchema), }), privilegesTooltip: Joi.string(), @@ -123,9 +99,7 @@ const schema = Joi.object({ privileges: Joi.array() .items( Joi.object({ - id: Joi.string() - .regex(reservedFeaturePrrivilegePartRegex) - .required(), + id: Joi.string().regex(reservedFeaturePrrivilegePartRegex).required(), privilege: privilegeSchema.required(), }) ) @@ -143,7 +117,7 @@ export function validateFeature(feature: FeatureConfig) { const unseenApps = new Set(app); - const managementSets = Object.entries(management).map(entry => [ + const managementSets = Object.entries(management).map((entry) => [ entry[0], new Set(entry[1]), ]) as Array<[string, Set]>; @@ -153,7 +127,7 @@ export function validateFeature(feature: FeatureConfig) { const unseenCatalogue = new Set(catalogue); function validateAppEntry(privilegeId: string, entry: string[] = []) { - entry.forEach(privilegeApp => unseenApps.delete(privilegeApp)); + entry.forEach((privilegeApp) => unseenApps.delete(privilegeApp)); const unknownAppEntries = difference(entry, app); if (unknownAppEntries.length > 0) { @@ -166,7 +140,7 @@ export function validateFeature(feature: FeatureConfig) { } function validateCatalogueEntry(privilegeId: string, entry: string[] = []) { - entry.forEach(privilegeCatalogue => unseenCatalogue.delete(privilegeCatalogue)); + entry.forEach((privilegeCatalogue) => unseenCatalogue.delete(privilegeCatalogue)); const unknownCatalogueEntries = difference(entry || [], catalogue); if (unknownCatalogueEntries.length > 0) { @@ -184,7 +158,7 @@ export function validateFeature(feature: FeatureConfig) { ) { Object.entries(managementEntry).forEach(([managementSectionId, managementSectionEntry]) => { if (unseenManagement.has(managementSectionId)) { - managementSectionEntry.forEach(entry => { + managementSectionEntry.forEach((entry) => { unseenManagement.get(managementSectionId)!.delete(entry); if (unseenManagement.get(managementSectionId)?.size === 0) { unseenManagement.delete(managementSectionId); @@ -219,7 +193,7 @@ export function validateFeature(feature: FeatureConfig) { privilegeEntries.push(...Object.entries(feature.privileges)); } if (feature.reserved) { - feature.reserved.privileges.forEach(reservedPrivilege => { + feature.reserved.privileges.forEach((reservedPrivilege) => { privilegeEntries.push([reservedPrivilege.id, reservedPrivilege.privilege]); }); } @@ -241,9 +215,9 @@ export function validateFeature(feature: FeatureConfig) { }); const subFeatureEntries = feature.subFeatures ?? []; - subFeatureEntries.forEach(subFeature => { - subFeature.privilegeGroups.forEach(subFeaturePrivilegeGroup => { - subFeaturePrivilegeGroup.privileges.forEach(subFeaturePrivilege => { + subFeatureEntries.forEach((subFeature) => { + subFeature.privilegeGroups.forEach((subFeaturePrivilegeGroup) => { + subFeaturePrivilegeGroup.privileges.forEach((subFeaturePrivilege) => { validateAppEntry(subFeaturePrivilege.id, subFeaturePrivilege.app); validateCatalogueEntry(subFeaturePrivilege.id, subFeaturePrivilege.catalogue); validateManagementEntry(subFeaturePrivilege.id, subFeaturePrivilege.management); @@ -274,7 +248,7 @@ export function validateFeature(feature: FeatureConfig) { if (unseenManagement.size > 0) { const ungrantedManagement = Array.from(unseenManagement.entries()).reduce((acc, entry) => { const values = Array.from(entry[1].values()).map( - managementPage => `${entry[0]}.${managementPage}` + (managementPage) => `${entry[0]}.${managementPage}` ); return [...acc, ...values]; }, [] as string[]); diff --git a/x-pack/plugins/features/server/oss_features.test.ts b/x-pack/plugins/features/server/oss_features.test.ts index 72beff02173d2..c38f2afc88389 100644 --- a/x-pack/plugins/features/server/oss_features.test.ts +++ b/x-pack/plugins/features/server/oss_features.test.ts @@ -11,7 +11,7 @@ import { Feature } from '.'; describe('buildOSSFeatures', () => { it('returns features including timelion', () => { expect( - buildOSSFeatures({ savedObjectTypes: ['foo', 'bar'], includeTimelion: true }).map(f => f.id) + buildOSSFeatures({ savedObjectTypes: ['foo', 'bar'], includeTimelion: true }).map((f) => f.id) ).toMatchInlineSnapshot(` Array [ "discover", @@ -28,7 +28,9 @@ Array [ it('returns features excluding timelion', () => { expect( - buildOSSFeatures({ savedObjectTypes: ['foo', 'bar'], includeTimelion: false }).map(f => f.id) + buildOSSFeatures({ savedObjectTypes: ['foo', 'bar'], includeTimelion: false }).map( + (f) => f.id + ) ).toMatchInlineSnapshot(` Array [ "discover", @@ -43,7 +45,7 @@ Array [ }); const features = buildOSSFeatures({ savedObjectTypes: ['foo', 'bar'], includeTimelion: true }); - features.forEach(featureConfig => { + features.forEach((featureConfig) => { it(`returns the ${featureConfig.id} feature augmented with appropriate sub feature privileges`, () => { const privileges = []; for (const featurePrivilege of featurePrivilegeIterator(new Feature(featureConfig), { diff --git a/x-pack/plugins/features/server/plugin.test.ts b/x-pack/plugins/features/server/plugin.test.ts index 3d7cf19e58b0e..79fd012337b00 100644 --- a/x-pack/plugins/features/server/plugin.test.ts +++ b/x-pack/plugins/features/server/plugin.test.ts @@ -39,7 +39,7 @@ describe('Features Plugin', () => { const { getFeatures } = await plugin.start(coreStart); - expect(getFeatures().map(f => f.id)).toMatchInlineSnapshot(` + expect(getFeatures().map((f) => f.id)).toMatchInlineSnapshot(` Array [ "baz", "discover", @@ -67,7 +67,7 @@ describe('Features Plugin', () => { const { getFeatures } = await plugin.start(coreStart); - expect(getFeatures().map(f => f.id)).toMatchInlineSnapshot(` + expect(getFeatures().map((f) => f.id)).toMatchInlineSnapshot(` Array [ "baz", "discover", @@ -88,8 +88,8 @@ describe('Features Plugin', () => { const { getFeatures } = await plugin.start(coreStart); const soTypes = - getFeatures().find(f => f.id === 'savedObjectsManagement')?.privileges?.all.savedObject.all || - []; + getFeatures().find((f) => f.id === 'savedObjectsManagement')?.privileges?.all.savedObject + .all || []; expect(soTypes.includes('foo')).toBe(true); expect(soTypes.includes('bar')).toBe(false); diff --git a/x-pack/plugins/features/server/plugin.ts b/x-pack/plugins/features/server/plugin.ts index e3480eda9fe7d..bfae416471c2f 100644 --- a/x-pack/plugins/features/server/plugin.ts +++ b/x-pack/plugins/features/server/plugin.ts @@ -83,8 +83,8 @@ export class Plugin { const registry = savedObjects.getTypeRegistry(); const savedObjectTypes = registry .getAllTypes() - .filter(t => !t.hidden) - .map(t => t.name); + .filter((t) => !t.hidden) + .map((t) => t.name); this.logger.debug( `Registering OSS features with SO types: ${savedObjectTypes.join(', ')}. "includeTimelion": ${ diff --git a/x-pack/plugins/features/server/routes/index.test.ts b/x-pack/plugins/features/server/routes/index.test.ts index 67b28b27f931f..c2e8cd6129d80 100644 --- a/x-pack/plugins/features/server/routes/index.test.ts +++ b/x-pack/plugins/features/server/routes/index.test.ts @@ -74,7 +74,7 @@ describe('GET /api/features', () => { const [call] = mockResponse.ok.mock.calls; const body = call[0]!.body as FeatureConfig[]; - const features = body.map(feature => ({ id: feature.id, order: feature.order })); + const features = body.map((feature) => ({ id: feature.id, order: feature.order })); expect(features).toEqual([ { id: 'feature_3', @@ -103,7 +103,7 @@ describe('GET /api/features', () => { const [call] = mockResponse.ok.mock.calls; const body = call[0]!.body as FeatureConfig[]; - const features = body.map(feature => ({ id: feature.id, order: feature.order })); + const features = body.map((feature) => ({ id: feature.id, order: feature.order })); expect(features).toEqual([ { @@ -133,7 +133,7 @@ describe('GET /api/features', () => { const [call] = mockResponse.ok.mock.calls; const body = call[0]!.body as FeatureConfig[]; - const features = body.map(feature => ({ id: feature.id, order: feature.order })); + const features = body.map((feature) => ({ id: feature.id, order: feature.order })); expect(features).toEqual([ { @@ -163,7 +163,7 @@ describe('GET /api/features', () => { const [call] = mockResponse.ok.mock.calls; const body = call[0]!.body as FeatureConfig[]; - const features = body.map(feature => ({ id: feature.id, order: feature.order })); + const features = body.map((feature) => ({ id: feature.id, order: feature.order })); expect(features).toEqual([ { diff --git a/x-pack/plugins/features/server/routes/index.ts b/x-pack/plugins/features/server/routes/index.ts index d07b488693091..147d34d124fca 100644 --- a/x-pack/plugins/features/server/routes/index.ts +++ b/x-pack/plugins/features/server/routes/index.ts @@ -31,7 +31,7 @@ export function defineRoutes({ router, featureRegistry }: RouteDefinitionParams) return response.ok({ body: allFeatures .filter( - feature => + (feature) => request.query.ignoreValidLicenses || !feature.validLicenses || !feature.validLicenses.length || @@ -42,7 +42,7 @@ export function defineRoutes({ router, featureRegistry }: RouteDefinitionParams) (f1, f2) => (f1.order ?? Number.MAX_SAFE_INTEGER) - (f2.order ?? Number.MAX_SAFE_INTEGER) ) - .map(feature => feature.toRaw()), + .map((feature) => feature.toRaw()), }); } ); diff --git a/x-pack/plugins/features/server/ui_capabilities_for_features.ts b/x-pack/plugins/features/server/ui_capabilities_for_features.ts index e6ff3ad4383d2..e41035e9365ce 100644 --- a/x-pack/plugins/features/server/ui_capabilities_for_features.ts +++ b/x-pack/plugins/features/server/ui_capabilities_for_features.ts @@ -42,14 +42,14 @@ function getCapabilitiesFromFeature(feature: Feature): FeatureCapabilities { const featurePrivileges = Object.values(feature.privileges ?? {}); if (feature.subFeatures) { featurePrivileges.push( - ...feature.subFeatures.map(sf => sf.privilegeGroups.map(pg => pg.privileges)).flat(2) + ...feature.subFeatures.map((sf) => sf.privilegeGroups.map((pg) => pg.privileges)).flat(2) ); } if (feature.reserved?.privileges) { - featurePrivileges.push(...feature.reserved.privileges.map(rp => rp.privilege)); + featurePrivileges.push(...feature.reserved.privileges.map((rp) => rp.privilege)); } - featurePrivileges.forEach(privilege => { + featurePrivileges.forEach((privilege) => { UIFeatureCapabilities[feature.id] = { ...UIFeatureCapabilities[feature.id], ...privilege.ui.reduce( @@ -74,7 +74,7 @@ function buildCapabilities(...allFeatureCapabilities: FeatureCapabilities[]): UI ...acc, }; - ELIGIBLE_FLAT_MERGE_KEYS.forEach(key => { + ELIGIBLE_FLAT_MERGE_KEYS.forEach((key) => { mergedFeatureCapabilities[key] = { ...mergedFeatureCapabilities[key], ...capabilities[key], diff --git a/x-pack/plugins/file_upload/public/components/index_settings.js b/x-pack/plugins/file_upload/public/components/index_settings.js index 8a745f035a8ee..cb1e639e0fede 100644 --- a/x-pack/plugins/file_upload/public/components/index_settings.js +++ b/x-pack/plugins/file_upload/public/components/index_settings.js @@ -58,7 +58,7 @@ export class IndexSettings extends Component { } } - _setIndexName = async name => { + _setIndexName = async (name) => { const errorMessage = await this._isIndexNameAndPatternValid(name); return this.setState({ indexName: name, @@ -72,7 +72,7 @@ export class IndexSettings extends Component { this.props.setIndexName(name); }; - _isIndexNameAndPatternValid = async name => { + _isIndexNameAndPatternValid = async (name) => { const { indexNameList, indexPatternList } = this.state; const nameAlreadyInUse = [...indexNameList, ...indexPatternList].includes(name); if (nameAlreadyInUse) { @@ -113,7 +113,7 @@ export class IndexSettings extends Component { ({ + options={indexTypes.map((indexType) => ({ text: indexType, value: indexType, }))} diff --git a/x-pack/plugins/file_upload/public/components/json_index_file_picker.js b/x-pack/plugins/file_upload/public/components/json_index_file_picker.js index 67086883a9a32..4728efc5b8915 100644 --- a/x-pack/plugins/file_upload/public/components/json_index_file_picker.js +++ b/x-pack/plugins/file_upload/public/components/json_index_file_picker.js @@ -13,8 +13,8 @@ import { MAX_FILE_SIZE } from '../../common/constants/file_import'; import _ from 'lodash'; const ACCEPTABLE_FILETYPES = ['json', 'geojson']; -const acceptedFileTypeString = ACCEPTABLE_FILETYPES.map(type => `.${type}`).join(','); -const acceptedFileTypeStringMessage = ACCEPTABLE_FILETYPES.map(type => `.${type}`).join(', '); +const acceptedFileTypeString = ACCEPTABLE_FILETYPES.map((type) => `.${type}`).join(','); +const acceptedFileTypeStringMessage = ACCEPTABLE_FILETYPES.map((type) => `.${type}`).join(', '); export class JsonIndexFilePicker extends Component { state = { @@ -35,7 +35,7 @@ export class JsonIndexFilePicker extends Component { getFileParseActive = () => this._isMounted && this.state.fileParseActive; - _fileHandler = fileList => { + _fileHandler = (fileList) => { const fileArr = Array.from(fileList); this.props.resetFileAndIndexSettings(); this.setState({ @@ -168,7 +168,7 @@ export class JsonIndexFilePicker extends Component { onFileUpload, setFileProgress: this.setFileProgress, getFileParseActive: this.getFileParseActive, - }).catch(err => { + }).catch((err) => { if (this._isMounted) { this.setState({ fileParseActive: false, diff --git a/x-pack/plugins/file_upload/public/components/json_upload_and_parse.js b/x-pack/plugins/file_upload/public/components/json_upload_and_parse.js index bcfb75e05a17f..453d4f84f7e0e 100644 --- a/x-pack/plugins/file_upload/public/components/json_upload_and_parse.js +++ b/x-pack/plugins/file_upload/public/components/json_upload_and_parse.js @@ -284,9 +284,9 @@ export class JsonUploadAndParse extends Component { {...{ onFileUpload, fileRef, - setIndexName: indexName => this.setState({ indexName }), - setFileRef: fileRef => this.setState({ fileRef }), - setParsedFile: parsedFile => this.setState({ parsedFile }), + setIndexName: (indexName) => this.setState({ indexName }), + setFileRef: (fileRef) => this.setState({ fileRef }), + setParsedFile: (parsedFile) => this.setState({ parsedFile }), transformDetails, resetFileAndIndexSettings: this._resetFileAndIndexSettings, }} @@ -294,10 +294,10 @@ export class JsonUploadAndParse extends Component { this.setState({ indexName })} + setIndexName={(indexName) => this.setState({ indexName })} indexTypes={indexTypes} - setSelectedIndexType={selectedIndexType => this.setState({ selectedIndexType })} - setHasIndexErrors={hasIndexErrors => this.setState({ hasIndexErrors })} + setSelectedIndexType={(selectedIndexType) => this.setState({ selectedIndexType })} + setHasIndexErrors={(hasIndexErrors) => this.setState({ hasIndexErrors })} /> )} diff --git a/x-pack/plugins/file_upload/public/util/file_parser.js b/x-pack/plugins/file_upload/public/util/file_parser.js index 2a0cef25f1678..e396b2b688a07 100644 --- a/x-pack/plugins/file_upload/public/util/file_parser.js +++ b/x-pack/plugins/file_upload/public/util/file_parser.js @@ -46,7 +46,7 @@ export const fileHandler = async ({ // Set up feature tracking let featuresProcessed = 0; - const onFeatureRead = feature => { + const onFeatureRead = (feature) => { // TODO: Add handling and tracking for cleanAndValidate fails featuresProcessed++; return cleanAndValidate(feature); @@ -58,7 +58,7 @@ export const fileHandler = async ({ prevFileReader = fileReader; const filePromise = new Promise((resolve, reject) => { - const onStreamComplete = fileResults => { + const onStreamComplete = (fileResults) => { if (!featuresProcessed) { reject( new Error( diff --git a/x-pack/plugins/file_upload/public/util/file_parser.test.js b/x-pack/plugins/file_upload/public/util/file_parser.test.js index fd467addfba82..5fbac6c7706a4 100644 --- a/x-pack/plugins/file_upload/public/util/file_parser.test.js +++ b/x-pack/plugins/file_upload/public/util/file_parser.test.js @@ -7,8 +7,8 @@ import { fileHandler } from './file_parser'; jest.mock('./pattern_reader', () => ({})); -const cleanAndValidate = jest.fn(a => a); -const setFileProgress = jest.fn(a => a); +const cleanAndValidate = jest.fn((a) => a); +const setFileProgress = jest.fn((a) => a); const getFileReader = () => { const fileReader = { @@ -24,7 +24,7 @@ const getPatternReader = () => { writeDataToPatternStream: jest.fn(), abortStream: jest.fn(), }; - require('./pattern_reader').PatternReader = function() { + require('./pattern_reader').PatternReader = function () { this.writeDataToPatternStream = () => patternReader.writeDataToPatternStream(); this.abortStream = () => patternReader.abortStream(); }; diff --git a/x-pack/plugins/file_upload/public/util/geo_json_clean_and_validate.test.js b/x-pack/plugins/file_upload/public/util/geo_json_clean_and_validate.test.js index 872df0cddca3c..e86a0fb4284d5 100644 --- a/x-pack/plugins/file_upload/public/util/geo_json_clean_and_validate.test.js +++ b/x-pack/plugins/file_upload/public/util/geo_json_clean_and_validate.test.js @@ -79,13 +79,13 @@ describe('geo_json_clean_and_validate', () => { // Confirm invalid geometry let geoJson = reader.read(badFeaturesGeoJson); let isSimpleOrValid; - geoJson.features.forEach(feature => { + geoJson.features.forEach((feature) => { isSimpleOrValid = feature.geometry.isSimple() || feature.geometry.isValid(); expect(isSimpleOrValid).toEqual(false); }); // Confirm changes to object - const cleanedFeatures = geoJson.features.map(feature => ({ + const cleanedFeatures = geoJson.features.map((feature) => ({ ...feature, geometry: cleanGeometry(feature), })); @@ -95,7 +95,7 @@ describe('geo_json_clean_and_validate', () => { // Confirm now valid features geometry geoJson = reader.read({ ...badFeaturesGeoJson, features: cleanedFeatures }); - geoJson.features.forEach(feature => { + geoJson.features.forEach((feature) => { isSimpleOrValid = feature.geometry.isSimple() || feature.geometry.isValid(); expect(isSimpleOrValid).toEqual(true); }); diff --git a/x-pack/plugins/file_upload/public/util/indexing_service.js b/x-pack/plugins/file_upload/public/util/indexing_service.js index bfaea00bc6694..eb22b0228b48a 100644 --- a/x-pack/plugins/file_upload/public/util/indexing_service.js +++ b/x-pack/plugins/file_upload/public/util/indexing_service.js @@ -217,7 +217,7 @@ async function getIndexPatternId(name) { const indexPatternSavedObjects = savedObjectSearch.savedObjects; if (indexPatternSavedObjects) { - const ip = indexPatternSavedObjects.find(i => i.attributes.title === name); + const ip = indexPatternSavedObjects.find((i) => i.attributes.title === name); return ip !== undefined ? ip.id : undefined; } else { return undefined; @@ -239,7 +239,7 @@ export const getExistingIndexPatternNames = async () => { fields: ['id', 'title', 'type', 'fields'], perPage: 10000, }) - .then(({ savedObjects }) => savedObjects.map(savedObject => savedObject.get('title'))); + .then(({ savedObjects }) => savedObjects.map((savedObject) => savedObject.get('title'))); return indexPatterns ? indexPatterns.map(({ name }) => name) : []; }; diff --git a/x-pack/plugins/file_upload/public/util/indexing_service.test.js b/x-pack/plugins/file_upload/public/util/indexing_service.test.js index f993ed0e1fd64..072079d3bbdd0 100644 --- a/x-pack/plugins/file_upload/public/util/indexing_service.test.js +++ b/x-pack/plugins/file_upload/public/util/indexing_service.test.js @@ -20,7 +20,7 @@ describe('indexing_service', () => { 'is.not.just.one.period', // name can't be . 'x'.repeat(255), // Cannot be longer than 255 bytes ]; - validNames.forEach(validName => { + validNames.forEach((validName) => { it(`Should validate index pattern: "${validName}"`, () => { const isValid = checkIndexPatternValid(validName); expect(isValid).toEqual(true); @@ -48,7 +48,7 @@ describe('indexing_service', () => { 'x'.repeat(256), // Cannot be longer than 255 bytes 'ü'.repeat(128), // Cannot be longer than 255 bytes (using 2 byte char) ]; - inValidNames.forEach(inValidName => { + inValidNames.forEach((inValidName) => { it(`Should invalidate index pattern: "${inValidName}"`, () => { const isValid = checkIndexPatternValid(inValidName); expect(isValid).toEqual(false); diff --git a/x-pack/plugins/file_upload/public/util/pattern_reader.js b/x-pack/plugins/file_upload/public/util/pattern_reader.js index 152e0f7e54580..bb7a0cab49884 100644 --- a/x-pack/plugins/file_upload/public/util/pattern_reader.js +++ b/x-pack/plugins/file_upload/public/util/pattern_reader.js @@ -21,7 +21,7 @@ export class PatternReader { _registerFeaturePatternHandler(featurePatternCallback) { this._oboeStream.node({ - 'features.*': feature => { + 'features.*': (feature) => { if (!feature.geometry || !feature.geometry.type) { // Only add this error once // TODO: Give feedback on which features failed @@ -48,7 +48,7 @@ export class PatternReader { } _registerStreamCompleteHandler(streamCompleteCallback) { - this._oboeStream.done(parsedGeojson => { + this._oboeStream.done((parsedGeojson) => { streamCompleteCallback({ parsedGeojson, errors: this.getErrors() }); }); } diff --git a/x-pack/plugins/file_upload/public/util/size_limited_chunking.test.js b/x-pack/plugins/file_upload/public/util/size_limited_chunking.test.js index 40f81d30725da..2fac441e8139d 100644 --- a/x-pack/plugins/file_upload/public/util/size_limited_chunking.test.js +++ b/x-pack/plugins/file_upload/public/util/size_limited_chunking.test.js @@ -14,7 +14,7 @@ describe('size_limited_chunking', () => { // Confirm valid geometry const chunkLimit = 100; const chunkedArr = sizeLimitedChunking(testArr, chunkLimit); - chunkedArr.forEach(sizeLimitedArr => { + chunkedArr.forEach((sizeLimitedArr) => { const arrByteSize = new Blob(sizeLimitedArr, { type: 'application/json' }).size; // Chunk size should be less than chunk limit diff --git a/x-pack/plugins/file_upload/server/client/call_with_request_factory.js b/x-pack/plugins/file_upload/server/client/call_with_request_factory.js deleted file mode 100644 index bef6c369fd9ac..0000000000000 --- a/x-pack/plugins/file_upload/server/client/call_with_request_factory.js +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { once } from 'lodash'; -import { getDataClient } from '../kibana_server_services'; - -const callWithRequest = once(() => getDataClient()); - -export const callWithRequestFactory = request => { - return (...args) => { - return ( - callWithRequest() - .asScoped(request) - // @ts-ignore - .callAsCurrentUser(...args) - ); - }; -}; diff --git a/x-pack/plugins/file_upload/server/kibana_server_services.js b/x-pack/plugins/file_upload/server/kibana_server_services.js index 104e49015ba80..703b55543fe07 100644 --- a/x-pack/plugins/file_upload/server/kibana_server_services.js +++ b/x-pack/plugins/file_upload/server/kibana_server_services.js @@ -4,15 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -let dataClient; - -export const setElasticsearchClientServices = elasticsearch => { - ({ dataClient } = elasticsearch); -}; -export const getDataClient = () => dataClient; - let internalRepository; -export const setInternalRepository = createInternalRepository => { +export const setInternalRepository = (createInternalRepository) => { internalRepository = createInternalRepository(); }; export const getInternalRepository = () => internalRepository; diff --git a/x-pack/plugins/file_upload/server/plugin.js b/x-pack/plugins/file_upload/server/plugin.js index a11516d03f068..08dd8762ab49d 100644 --- a/x-pack/plugins/file_upload/server/plugin.js +++ b/x-pack/plugins/file_upload/server/plugin.js @@ -5,7 +5,7 @@ */ import { initRoutes } from './routes/file_upload'; -import { setElasticsearchClientServices, setInternalRepository } from './kibana_server_services'; +import { setInternalRepository } from './kibana_server_services'; import { registerFileUploadUsageCollector, fileUploadTelemetryMappingsType } from './telemetry'; export class FileUploadPlugin { @@ -15,7 +15,6 @@ export class FileUploadPlugin { setup(core, plugins) { core.savedObjects.registerType(fileUploadTelemetryMappingsType); - setElasticsearchClientServices(core.elasticsearch); this.router = core.http.createRouter(); registerFileUploadUsageCollector(plugins.usageCollection); } diff --git a/x-pack/plugins/file_upload/server/routes/file_upload.js b/x-pack/plugins/file_upload/server/routes/file_upload.js index d75f03132b404..c7f3e2a621161 100644 --- a/x-pack/plugins/file_upload/server/routes/file_upload.js +++ b/x-pack/plugins/file_upload/server/routes/file_upload.js @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { callWithRequestFactory } from '../client/call_with_request_factory'; import { importDataProvider } from '../models/import_data'; import { updateTelemetry } from '../telemetry/telemetry'; import { MAX_BYTES } from '../../common/constants/file_import'; @@ -86,7 +85,7 @@ const finishValidationAndProcessReq = () => { let resp; try { const validIdReqData = idConditionalValidation(body, boolHasId); - const callWithRequest = callWithRequestFactory(req); + const callWithRequest = con.core.elasticsearch.dataClient.callAsCurrentUser; const { importData: importDataFunc } = importDataProvider(callWithRequest); const { index, settings, mappings, ingestPipeline, data } = validIdReqData; @@ -115,7 +114,7 @@ const finishValidationAndProcessReq = () => { }; }; -export const initRoutes = router => { +export const initRoutes = (router) => { router.post( { path: `${IMPORT_ROUTE}{id?}`, diff --git a/x-pack/plugins/graph/public/angular/graph_client_workspace.js b/x-pack/plugins/graph/public/angular/graph_client_workspace.js index bcd31716b6d64..cfa125fcc49ee 100644 --- a/x-pack/plugins/graph/public/angular/graph_client_workspace.js +++ b/x-pack/plugins/graph/public/angular/graph_client_workspace.js @@ -11,7 +11,7 @@ import d3 from 'd3'; // Pluggable function to handle the comms with a server. Default impl here is // for use outside of Kibana server with direct access to elasticsearch -let graphExplorer = function(indexName, typeName, request, responseHandler) { +let graphExplorer = function (indexName, typeName, request, responseHandler) { const dataForServer = JSON.stringify(request); $.ajax({ type: 'POST', @@ -20,12 +20,12 @@ let graphExplorer = function(indexName, typeName, request, responseHandler) { contentType: 'application/json;charset=utf-8', async: true, data: dataForServer, - success: function(data) { + success: function (data) { responseHandler(data); }, }); }; -let searcher = function(indexName, request, responseHandler) { +let searcher = function (indexName, request, responseHandler) { const dataForServer = JSON.stringify(request); $.ajax({ type: 'POST', @@ -34,7 +34,7 @@ let searcher = function(indexName, request, responseHandler) { contentType: 'application/json;charset=utf-8', //Not sure why this was necessary - worked without elsewhere async: true, data: dataForServer, - success: function(data) { + success: function (data) { responseHandler(data); }, }); @@ -46,14 +46,14 @@ function AddNodeOperation(node, owner) { const self = this; const vm = owner; self.node = node; - self.undo = function() { + self.undo = function () { vm.arrRemove(vm.nodes, self.node); vm.arrRemove(vm.selectedNodes, self.node); self.node.isSelected = false; delete vm.nodesMap[self.node.id]; }; - self.redo = function() { + self.redo = function () { vm.nodes.push(self.node); vm.nodesMap[self.node.id] = self.node; }; @@ -63,11 +63,11 @@ function AddEdgeOperation(edge, owner) { const self = this; const vm = owner; self.edge = edge; - self.undo = function() { + self.undo = function () { vm.arrRemove(vm.edges, self.edge); delete vm.edgesMap[self.edge.id]; }; - self.redo = function() { + self.redo = function () { vm.edges.push(self.edge); vm.edgesMap[self.edge.id] = self.edge; }; @@ -84,10 +84,10 @@ function GroupOperation(receiver, orphan) { const self = this; self.receiver = receiver; self.orphan = orphan; - self.undo = function() { + self.undo = function () { self.orphan.parent = undefined; }; - self.redo = function() { + self.redo = function () { self.orphan.parent = self.receiver; }; } @@ -96,10 +96,10 @@ function UnGroupOperation(parent, child) { const self = this; self.parent = parent; self.child = child; - self.undo = function() { + self.undo = function () { self.child.parent = self.parent; }; - self.redo = function() { + self.redo = function () { self.child.parent = undefined; }; } @@ -135,7 +135,7 @@ function GraphWorkspace(options) { searcher = options.searchProxy; } - this.addUndoLogEntry = function(undoOperations) { + this.addUndoLogEntry = function (undoOperations) { self.undoLog.push(undoOperations); if (self.undoLog.length > 50) { //Remove the oldest @@ -144,29 +144,29 @@ function GraphWorkspace(options) { self.redoLog = []; }; - this.undo = function() { + this.undo = function () { const lastOps = this.undoLog.pop(); if (lastOps) { this.stopLayout(); this.redoLog.push(lastOps); - lastOps.forEach(ops => ops.undo()); + lastOps.forEach((ops) => ops.undo()); this.runLayout(); } }; - this.redo = function() { + this.redo = function () { const lastOps = this.redoLog.pop(); if (lastOps) { this.stopLayout(); this.undoLog.push(lastOps); - lastOps.forEach(ops => ops.redo()); + lastOps.forEach((ops) => ops.redo()); this.runLayout(); } }; //Determines if 2 nodes are connected via an edge - this.areLinked = function(a, b) { + this.areLinked = function (a, b) { if (a === b) return true; - this.edges.forEach(e => { + this.edges.forEach((e) => { if (e.source === a && e.target === b) { return true; } @@ -179,9 +179,9 @@ function GraphWorkspace(options) { //======== Selection functions ======== - this.selectAll = function() { + this.selectAll = function () { self.selectedNodes = []; - self.nodes.forEach(node => { + self.nodes.forEach((node) => { if (node.parent === undefined) { node.isSelected = true; self.selectedNodes.push(node); @@ -191,16 +191,16 @@ function GraphWorkspace(options) { }); }; - this.selectNone = function() { + this.selectNone = function () { self.selectedNodes = []; - self.nodes.forEach(node => { + self.nodes.forEach((node) => { node.isSelected = false; }); }; - this.selectInvert = function() { + this.selectInvert = function () { self.selectedNodes = []; - self.nodes.forEach(node => { + self.nodes.forEach((node) => { if (node.parent !== undefined) { return; } @@ -211,8 +211,8 @@ function GraphWorkspace(options) { }); }; - this.selectNodes = function(nodes) { - nodes.forEach(node => { + this.selectNodes = function (nodes) { + nodes.forEach((node) => { node.isSelected = true; if (self.selectedNodes.indexOf(node) < 0) { self.selectedNodes.push(node); @@ -220,14 +220,14 @@ function GraphWorkspace(options) { }); }; - this.selectNode = function(node) { + this.selectNode = function (node) { node.isSelected = true; if (self.selectedNodes.indexOf(node) < 0) { self.selectedNodes.push(node); } }; - this.deleteSelection = function() { + this.deleteSelection = function () { let allAndGrouped = self.returnUnpackedGroupeds(self.selectedNodes); // Nothing selected so process all nodes @@ -236,7 +236,7 @@ function GraphWorkspace(options) { } const undoOperations = []; - allAndGrouped.forEach(node => { + allAndGrouped.forEach((node) => { //We set selected to false because despite being deleted, node objects sit in an undo log node.isSelected = false; delete self.nodesMap[node.id]; @@ -245,10 +245,10 @@ function GraphWorkspace(options) { self.arrRemoveAll(self.nodes, allAndGrouped); self.arrRemoveAll(self.selectedNodes, allAndGrouped); - const danglingEdges = self.edges.filter(function(edge) { + const danglingEdges = self.edges.filter(function (edge) { return self.nodes.indexOf(edge.source) < 0 || self.nodes.indexOf(edge.target) < 0; }); - danglingEdges.forEach(edge => { + danglingEdges.forEach((edge) => { delete self.edgesMap[edge.id]; undoOperations.push(new ReverseOperation(new AddEdgeOperation(edge, self))); }); @@ -257,9 +257,9 @@ function GraphWorkspace(options) { self.runLayout(); }; - this.selectNeighbours = function() { + this.selectNeighbours = function () { const newSelections = []; - self.edges.forEach(edge => { + self.edges.forEach((edge) => { if (!edge.topSrc.isSelected) { if (self.selectedNodes.indexOf(edge.topTarget) >= 0) { if (newSelections.indexOf(edge.topSrc) < 0) { @@ -275,37 +275,37 @@ function GraphWorkspace(options) { } } }); - newSelections.forEach(newlySelectedNode => { + newSelections.forEach((newlySelectedNode) => { self.selectedNodes.push(newlySelectedNode); newlySelectedNode.isSelected = true; }); }; - this.selectNone = function() { - self.selectedNodes.forEach(node => { + this.selectNone = function () { + self.selectedNodes.forEach((node) => { node.isSelected = false; }); self.selectedNodes = []; }; - this.deselectNode = function(node) { + this.deselectNode = function (node) { node.isSelected = false; self.arrRemove(self.selectedNodes, node); }; - this.getAllSelectedNodes = function() { + this.getAllSelectedNodes = function () { return this.returnUnpackedGroupeds(self.selectedNodes); }; - this.colorSelected = function(colorNum) { - self.getAllSelectedNodes().forEach(node => { + this.colorSelected = function (colorNum) { + self.getAllSelectedNodes().forEach((node) => { node.color = colorNum; }); }; - this.getSelectionsThatAreGrouped = function() { + this.getSelectionsThatAreGrouped = function () { const result = []; - self.selectedNodes.forEach(node => { + self.selectedNodes.forEach((node) => { if (node.numChildren > 0) { result.push(node); } @@ -313,13 +313,13 @@ function GraphWorkspace(options) { return result; }; - this.ungroupSelection = function() { - self.getSelectionsThatAreGrouped().forEach(node => { + this.ungroupSelection = function () { + self.getSelectionsThatAreGrouped().forEach((node) => { self.ungroup(node); }); }; - this.toggleNodeSelection = function(node) { + this.toggleNodeSelection = function (node) { if (node.isSelected) { self.deselectNode(node); } else { @@ -329,7 +329,7 @@ function GraphWorkspace(options) { return node.isSelected; }; - this.returnUnpackedGroupeds = function(topLevelNodeArray) { + this.returnUnpackedGroupeds = function (topLevelNodeArray) { //Gather any grouped nodes that are part of this top-level selection const result = topLevelNodeArray.slice(); @@ -371,7 +371,7 @@ function GraphWorkspace(options) { // ======= Miscellaneous functions - this.clearGraph = function() { + this.clearGraph = function () { this.stopLayout(); this.nodes = []; this.edges = []; @@ -398,9 +398,9 @@ function GraphWorkspace(options) { } }; - this.getNeighbours = function(node) { + this.getNeighbours = function (node) { const neighbourNodes = []; - self.edges.forEach(edge => { + self.edges.forEach((edge) => { if (edge.topSrc === edge.topTarget) { return; } @@ -419,7 +419,7 @@ function GraphWorkspace(options) { }; //Creates a query that represents a node - either simple term query or boolean if grouped - this.buildNodeQuery = function(topLevelNode) { + this.buildNodeQuery = function (topLevelNode) { let containedNodes = [topLevelNode]; containedNodes = self.returnUnpackedGroupeds(containedNodes); if (containedNodes.length === 1) { @@ -431,7 +431,7 @@ function GraphWorkspace(options) { }; } const termsByField = {}; - containedNodes.forEach(node => { + containedNodes.forEach((node) => { let termsList = termsByField[node.data.field]; if (!termsList) { termsList = []; @@ -465,20 +465,20 @@ function GraphWorkspace(options) { //====== Layout functions ======== - this.stopLayout = function() { + this.stopLayout = function () { if (this.force) { this.force.stop(); } this.force = null; }; - this.runLayout = function() { + this.runLayout = function () { this.stopLayout(); // The set of nodes and edges we present to the d3 layout algorithms // is potentially a reduced set of nodes if the client has used any // grouping of nodes into parent nodes. const effectiveEdges = []; - self.edges.forEach(edge => { + self.edges.forEach((edge) => { let topSrc = edge.source; let topTarget = edge.target; while (topSrc.parent !== undefined) { @@ -497,12 +497,12 @@ function GraphWorkspace(options) { }); } }); - const visibleNodes = self.nodes.filter(function(n) { + const visibleNodes = self.nodes.filter(function (n) { return n.parent === undefined; }); //reset then roll-up all the counts const allNodes = self.nodes; - allNodes.forEach(node => { + allNodes.forEach((node) => { node.numChildren = 0; }); @@ -527,11 +527,11 @@ function GraphWorkspace(options) { .theta(0.99) .alpha(0.5) .size([800, 600]) - .on('tick', function() { + .on('tick', function () { const nodeArray = self.nodes; let hasRollups = false; //Update the position of all "top level nodes" - nodeArray.forEach(n => { + nodeArray.forEach((n) => { //Code to support roll-ups if (n.parent === undefined) { n.kx = n.x; @@ -541,7 +541,7 @@ function GraphWorkspace(options) { } }); if (hasRollups) { - nodeArray.forEach(n => { + nodeArray.forEach((n) => { //Code to support roll-ups if (n.parent !== undefined) { // Is a grouped node - inherit parent's position so edges point into parent @@ -568,9 +568,9 @@ function GraphWorkspace(options) { //========Grouping functions========== //Merges all selected nodes into node - this.groupSelections = function(node) { + this.groupSelections = function (node) { const ops = []; - self.nodes.forEach(function(otherNode) { + self.nodes.forEach(function (otherNode) { if (otherNode !== node && otherNode.isSelected && otherNode.parent === undefined) { otherNode.parent = node; otherNode.isSelected = false; @@ -584,10 +584,10 @@ function GraphWorkspace(options) { self.runLayout(); }; - this.mergeNeighbours = function(node) { + this.mergeNeighbours = function (node) { const neighbours = self.getNeighbours(node); const ops = []; - neighbours.forEach(function(otherNode) { + neighbours.forEach(function (otherNode) { if (otherNode !== node && otherNode.parent === undefined) { otherNode.parent = node; otherNode.isSelected = false; @@ -599,14 +599,14 @@ function GraphWorkspace(options) { self.runLayout(); }; - this.mergeSelections = function(targetNode) { + this.mergeSelections = function (targetNode) { if (!targetNode) { console.log('Error - merge called on undefined target'); return; } const selClone = self.selectedNodes.slice(); const ops = []; - selClone.forEach(function(otherNode) { + selClone.forEach(function (otherNode) { if (otherNode !== targetNode && otherNode.parent === undefined) { otherNode.parent = targetNode; otherNode.isSelected = false; @@ -618,9 +618,9 @@ function GraphWorkspace(options) { self.runLayout(); }; - this.ungroup = function(node) { + this.ungroup = function (node) { const ops = []; - self.nodes.forEach(function(other) { + self.nodes.forEach(function (other) { if (other.parent === node) { other.parent = undefined; ops.push(new UnGroupOperation(node, other)); @@ -630,20 +630,20 @@ function GraphWorkspace(options) { self.runLayout(); }; - this.unblacklist = function(node) { + this.unblacklist = function (node) { self.arrRemove(self.blacklistedNodes, node); }; - this.blacklistSelection = function() { + this.blacklistSelection = function () { const selection = self.getAllSelectedNodes(); const danglingEdges = []; - self.edges.forEach(function(edge) { + self.edges.forEach(function (edge) { if (selection.indexOf(edge.source) >= 0 || selection.indexOf(edge.target) >= 0) { delete self.edgesMap[edge.id]; danglingEdges.push(edge); } }); - selection.forEach(node => { + selection.forEach((node) => { delete self.nodesMap[node.id]; self.blacklistedNodes.push(node); node.isSelected = false; @@ -656,7 +656,7 @@ function GraphWorkspace(options) { // A "simple search" operation that requires no parameters from the client. // Performs numHops hops pulling in field-specific number of terms each time - this.simpleSearch = function(searchTerm, fieldsChoice, numHops) { + this.simpleSearch = function (searchTerm, fieldsChoice, numHops) { const qs = { query_string: { query: searchTerm, @@ -665,7 +665,7 @@ function GraphWorkspace(options) { return this.search(qs, fieldsChoice, numHops); }; - this.search = function(query, fieldsChoice, numHops) { + this.search = function (query, fieldsChoice, numHops) { if (!fieldsChoice) { fieldsChoice = self.options.vertex_fields; } @@ -734,7 +734,7 @@ function GraphWorkspace(options) { self.callElasticsearch(request); }; - this.buildControls = function() { + this.buildControls = function () { //This is an object managed by the client that may be subject to change const guiSettingsObj = self.options.exploreControls; @@ -753,11 +753,11 @@ function GraphWorkspace(options) { return controls; }; - this.makeNodeId = function(field, term) { + this.makeNodeId = function (field, term) { return field + '..' + term; }; - this.makeEdgeId = function(srcId, targetId) { + this.makeEdgeId = function (srcId, targetId) { let id = srcId + '->' + targetId; if (srcId > targetId) { id = targetId + '->' + srcId; @@ -766,7 +766,7 @@ function GraphWorkspace(options) { }; //======= Adds new nodes retrieved from an elasticsearch search ======== - this.mergeGraph = function(newData) { + this.mergeGraph = function (newData) { this.stopLayout(); if (!newData.nodes) { @@ -785,7 +785,7 @@ function GraphWorkspace(options) { //Remove nodes we already have const dedupedNodes = []; - newData.nodes.forEach(node => { + newData.nodes.forEach((node) => { //Assign an ID node.id = self.makeNodeId(node.field, node.term); if (!this.nodesMap[node.id]) { @@ -801,7 +801,7 @@ function GraphWorkspace(options) { this.options.nodeLabeller(dedupedNodes); } - dedupedNodes.forEach(dedupedNode => { + dedupedNodes.forEach((dedupedNode) => { let label = dedupedNode.term; if (dedupedNode.label) { label = dedupedNode.label; @@ -827,7 +827,7 @@ function GraphWorkspace(options) { this.nodesMap[node.id] = node; }); - newData.edges.forEach(edge => { + newData.edges.forEach((edge) => { const src = newData.nodes[edge.source]; const target = newData.nodes[edge.target]; edge.id = this.makeEdgeId(src.id, target.id); @@ -867,7 +867,7 @@ function GraphWorkspace(options) { this.runLayout(); }; - this.mergeIds = function(parentId, childId) { + this.mergeIds = function (parentId, childId) { const parent = self.getNode(parentId); const child = self.getNode(childId); if (child.isSelected) { @@ -879,16 +879,16 @@ function GraphWorkspace(options) { self.runLayout(); }; - this.getNode = function(nodeId) { + this.getNode = function (nodeId) { return this.nodesMap[nodeId]; }; - this.getEdge = function(edgeId) { + this.getEdge = function (edgeId) { return this.edgesMap[edgeId]; }; //======= Expand functions to request new additions to the graph - this.expandSelecteds = function(targetOptions = {}) { + this.expandSelecteds = function (targetOptions = {}) { let startNodes = self.getAllSelectedNodes(); if (startNodes.length === 0) { startNodes = self.nodes; @@ -897,19 +897,19 @@ function GraphWorkspace(options) { self.expand(clone, targetOptions); }; - this.expandGraph = function() { + this.expandGraph = function () { self.expandSelecteds(); }; //Find new nodes to link to existing selected nodes - this.expandNode = function(node) { + this.expandNode = function (node) { self.expand(self.returnUnpackedGroupeds([node]), {}); }; // A manual expand function where the client provides the list // of existing nodes that are the start points and some options // about what targets are of interest. - this.expand = function(startNodes, targetOptions) { + this.expand = function (startNodes, targetOptions) { //============================= const nodesByField = {}; const excludeNodesByField = {}; @@ -983,7 +983,7 @@ function GraphWorkspace(options) { } //Identify target fields - targetFields.forEach(targetField => { + targetFields.forEach((targetField) => { const fieldName = targetField.name; // Sometimes the target field is disabled from loading new hops so we need to use the last valid figure const hopSize = targetField.hopSize > 0 ? targetField.hopSize : targetField.lastValidHopSize; @@ -1005,13 +1005,13 @@ function GraphWorkspace(options) { }, }; self.lastRequest = JSON.stringify(request, null, '\t'); - graphExplorer(self.options.indexName, request, function(data) { + graphExplorer(self.options.indexName, request, function (data) { self.lastResponse = JSON.stringify(data, null, '\t'); const edges = []; //Label fields with a field number for CSS styling - data.vertices.forEach(node => { - targetFields.some(fieldDef => { + data.vertices.forEach((node) => { + targetFields.some((fieldDef) => { if (node.field === fieldDef.name) { node.color = fieldDef.color; node.icon = fieldDef.icon; @@ -1026,7 +1026,7 @@ function GraphWorkspace(options) { const minLineSize = 2; const maxLineSize = 10; let maxEdgeWeight = 0.00000001; - data.connections.forEach(edge => { + data.connections.forEach((edge) => { maxEdgeWeight = Math.max(maxEdgeWeight, edge.weight); edges.push({ source: edge.source, @@ -1046,11 +1046,11 @@ function GraphWorkspace(options) { //===== End expand graph ======================== }; - this.trimExcessNewEdges = function(newNodes, newEdges) { + this.trimExcessNewEdges = function (newNodes, newEdges) { let trimmedEdges = []; const maxNumEdgesToReturn = 5; //Trim here to just the new edges that are most interesting. - newEdges.forEach(edge => { + newEdges.forEach((edge) => { const src = newNodes[edge.source]; const target = newNodes[edge.target]; const srcId = src.field + '..' + src.term; @@ -1080,7 +1080,7 @@ function GraphWorkspace(options) { }); if (trimmedEdges.length > maxNumEdgesToReturn) { //trim to only the most interesting ones - trimmedEdges.sort(function(a, b) { + trimmedEdges.sort(function (a, b) { return b.weight - a.weight; }); trimmedEdges = trimmedEdges.splice(0, maxNumEdgesToReturn); @@ -1088,13 +1088,13 @@ function GraphWorkspace(options) { return trimmedEdges; }; - this.getQuery = function(startNodes, loose) { + this.getQuery = function (startNodes, loose) { const shoulds = []; let nodes = startNodes; if (!startNodes) { nodes = self.nodes; } - nodes.forEach(node => { + nodes.forEach((node) => { if (node.parent === undefined) { shoulds.push(self.buildNodeQuery(node)); } @@ -1107,7 +1107,7 @@ function GraphWorkspace(options) { }; }; - this.getSelectedOrAllNodes = function() { + this.getSelectedOrAllNodes = function () { let startNodes = self.getAllSelectedNodes(); if (startNodes.length === 0) { startNodes = self.nodes; @@ -1115,8 +1115,8 @@ function GraphWorkspace(options) { return startNodes; }; - this.getSelectedOrAllTopNodes = function() { - return self.getSelectedOrAllNodes().filter(function(node) { + this.getSelectedOrAllTopNodes = function () { + return self.getSelectedOrAllNodes().filter(function (node) { return node.parent === undefined; }); }; @@ -1135,7 +1135,7 @@ function GraphWorkspace(options) { * @param maxNewEdges Max number of new edges added. Avoid adding too many new edges * at once into the graph otherwise disorientating */ - this.fillInGraph = function(maxNewEdges = 10) { + this.fillInGraph = function (maxNewEdges = 10) { let nodesForLinking = self.getSelectedOrAllTopNodes(); const maxNumVerticesSearchable = 100; @@ -1161,7 +1161,7 @@ function GraphWorkspace(options) { // the first 2 nodes in the array will therefore be labelled "0|1" const shoulds = []; const filterMap = {}; - nodesForLinking.forEach(function(node, nodeNum) { + nodesForLinking.forEach(function (node, nodeNum) { const nodeQuery = self.buildNodeQuery(node); shoulds.push(nodeQuery); filterMap[nodeNum] = nodeQuery; @@ -1186,10 +1186,10 @@ function GraphWorkspace(options) { }; // Search for connections between the selected nodes. - searcher(self.options.indexName, searchReq, function(data) { + searcher(self.options.indexName, searchReq, function (data) { const numDocsMatched = data.hits.total; const buckets = data.aggregations.matrix.buckets; - const vertices = nodesForLinking.map(function(existingNode) { + const vertices = nodesForLinking.map(function (existingNode) { return { field: existingNode.data.field, term: existingNode.data.term, @@ -1202,11 +1202,11 @@ function GraphWorkspace(options) { let maxEdgeWeight = 0; // Turn matrix array of results into a map const keyedBuckets = {}; - buckets.forEach(function(bucket) { + buckets.forEach(function (bucket) { keyedBuckets[bucket.key] = bucket; }); - buckets.forEach(function(bucket) { + buckets.forEach(function (bucket) { // We calibrate line thickness based on % of max weight of // all edges (including the edges we may already have in the workspace) const ids = bucket.key.split('|'); @@ -1232,7 +1232,7 @@ function GraphWorkspace(options) { }); const backFilledMinLineSize = 2; const backFilledMaxLineSize = 5; - buckets.forEach(function(bucket) { + buckets.forEach(function (bucket) { if (bucket.doc_count < parseInt(self.options.exploreControls.minDocCount)) { return; } @@ -1263,7 +1263,7 @@ function GraphWorkspace(options) { }); // Trim the array of connections so that we don't add too many at once - disorientating for users otherwise if (connections.length > maxNewEdges) { - connections = connections.sort(function(a, b) { + connections = connections.sort(function (a, b) { return b.weight - a.weight; }); connections = connections.slice(0, maxNewEdges); @@ -1287,11 +1287,11 @@ function GraphWorkspace(options) { // We use a free-text search on the index's configured default field (typically '_all') // to drill-down into docs that should be linked but aren't via the exact terms // we have in the workspace - this.getLikeThisButNotThisQuery = function(startNodes) { + this.getLikeThisButNotThisQuery = function (startNodes) { const likeQueries = []; const txtsByFieldType = {}; - startNodes.forEach(node => { + startNodes.forEach((node) => { let txt = txtsByFieldType[node.data.field]; if (txt) { txt = txt + ' ' + node.label; @@ -1317,11 +1317,11 @@ function GraphWorkspace(options) { const excludeNodesByField = {}; const allExistingNodes = self.nodes; - allExistingNodes.forEach(existingNode => { + allExistingNodes.forEach((existingNode) => { addTermToFieldList(excludeNodesByField, existingNode.data.field, existingNode.data.term); }); const blacklistedNodes = self.blacklistedNodes; - blacklistedNodes.forEach(blacklistedNode => { + blacklistedNodes.forEach((blacklistedNode) => { addTermToFieldList( excludeNodesByField, blacklistedNode.data.field, @@ -1331,7 +1331,7 @@ function GraphWorkspace(options) { //Create negative boosting queries to avoid matching what you already have in the workspace. const notExistingNodes = []; - Object.keys(excludeNodesByField).forEach(fieldName => { + Object.keys(excludeNodesByField).forEach((fieldName) => { const termsQuery = {}; termsQuery[fieldName] = excludeNodesByField[fieldName]; notExistingNodes.push({ @@ -1359,7 +1359,7 @@ function GraphWorkspace(options) { return result; }; - this.getSelectedIntersections = function(callback) { + this.getSelectedIntersections = function (callback) { if (self.selectedNodes.length === 0) { return self.getAllIntersections(callback, self.nodes); } @@ -1372,7 +1372,7 @@ function GraphWorkspace(options) { return self.getAllIntersections(callback, self.getAllSelectedNodes()); }; - this.jLHScore = function(subsetFreq, subsetSize, supersetFreq, supersetSize) { + this.jLHScore = function (subsetFreq, subsetSize, supersetFreq, supersetSize) { const subsetProbability = subsetFreq / subsetSize; const supersetProbability = supersetFreq / supersetSize; @@ -1392,13 +1392,13 @@ function GraphWorkspace(options) { // Determines union/intersection stats for neighbours of a node. // TODO - could move server-side as a graph API function? - this.getAllIntersections = function(callback, nodes) { + this.getAllIntersections = function (callback, nodes) { //Ensure these are all top-level nodes only - nodes = nodes.filter(function(n) { + nodes = nodes.filter(function (n) { return n.parent === undefined; }); - const allQueries = nodes.map(function(node) { + const allQueries = nodes.map(function (node) { return self.buildNodeQuery(node); }); @@ -1436,7 +1436,7 @@ function GraphWorkspace(options) { request.aggs.sources.filters.filters['bg' + n] = query; request.aggs.sources.aggs.targets.filters.filters['fg' + n] = query; }); - searcher(self.options.indexName, request, function(data) { + searcher(self.options.indexName, request, function (data) { const termIntersects = []; const fullDocCounts = []; const allDocCount = data.aggregations.all.doc_count; @@ -1499,7 +1499,7 @@ function GraphWorkspace(options) { termIntersects.push(termIntersect); }); }); - termIntersects.sort(function(a, b) { + termIntersects.sort(function (a, b) { if (b.mergeConfidence !== a.mergeConfidence) { return b.mergeConfidence - a.mergeConfidence; } @@ -1520,14 +1520,14 @@ function GraphWorkspace(options) { // Internal utility function for calling the Graph API and handling the response // by merging results into existing nodes in this workspace. - this.callElasticsearch = function(request) { + this.callElasticsearch = function (request) { self.lastRequest = JSON.stringify(request, null, '\t'); - graphExplorer(self.options.indexName, request, function(data) { + graphExplorer(self.options.indexName, request, function (data) { self.lastResponse = JSON.stringify(data, null, '\t'); const edges = []; //Label the nodes with field number for CSS styling - data.vertices.forEach(node => { - self.options.vertex_fields.some(fieldDef => { + data.vertices.forEach((node) => { + self.options.vertex_fields.some((fieldDef) => { if (node.field === fieldDef.name) { node.color = fieldDef.color; node.icon = fieldDef.icon; @@ -1542,10 +1542,10 @@ function GraphWorkspace(options) { const minLineSize = 2; const maxLineSize = 10; let maxEdgeWeight = 0.00000001; - data.connections.forEach(edge => { + data.connections.forEach((edge) => { maxEdgeWeight = Math.max(maxEdgeWeight, edge.weight); }); - data.connections.forEach(edge => { + data.connections.forEach((edge) => { edges.push({ source: edge.source, target: edge.target, diff --git a/x-pack/plugins/graph/public/angular/graph_client_workspace.test.js b/x-pack/plugins/graph/public/angular/graph_client_workspace.test.js index 7ffb16d986a21..fe6a782373eb2 100644 --- a/x-pack/plugins/graph/public/angular/graph_client_workspace.test.js +++ b/x-pack/plugins/graph/public/angular/graph_client_workspace.test.js @@ -6,16 +6,16 @@ import { createWorkspace } from './graph_client_workspace'; -describe('graphui-workspace', function() { - describe('createWorkspace()', function() { +describe('graphui-workspace', function () { + describe('createWorkspace()', function () { // var fooResource=null; let mockedResult = null; let init = null; - beforeEach(function() { + beforeEach(function () { //Setup logic here // fooResource={"foo":"bar"}; - init = function() { - const callNodeProxy = function(indexName, query, responseHandler) { + init = function () { + const callNodeProxy = function (indexName, query, responseHandler) { responseHandler(mockedResult); }; const options = { @@ -45,11 +45,11 @@ describe('graphui-workspace', function() { }; }; }); - it('initializeWorkspace', function() { + it('initializeWorkspace', function () { const { workspace } = init(); expect(workspace.nodes.length).toEqual(0); }); - it('simpleSearch', function() { + it('simpleSearch', function () { //Test that a graph is loaded from a free-text search const { workspace } = init(); @@ -91,7 +91,7 @@ describe('graphui-workspace', function() { expect(nodeD).toBe(undefined); }); - it('expandTest', function() { + it('expandTest', function () { //Test that a graph can be expanded const { workspace } = init(); @@ -155,7 +155,7 @@ describe('graphui-workspace', function() { expect(workspace.edges.length).toEqual(2); }); - it('selectionTest', function() { + it('selectionTest', function () { //Test selections on a graph const { workspace } = init(); // graph is a1->a2 and b1->b2 @@ -237,7 +237,7 @@ describe('graphui-workspace', function() { expect(workspace.selectedNodes.length).toEqual(2); }); - it('undoRedoDeletes', function() { + it('undoRedoDeletes', function () { const { workspace } = init(); // graph is a1->a2 mockedResult = { @@ -293,7 +293,7 @@ describe('graphui-workspace', function() { expect(workspace.nodes.length).toEqual(2); }); - it('undoRedoGroupings', function() { + it('undoRedoGroupings', function () { const { workspace } = init(); // graph is a1->a2 mockedResult = { diff --git a/x-pack/plugins/graph/public/app.js b/x-pack/plugins/graph/public/app.js index d4199fbd092b4..08b13e9d5c541 100644 --- a/x-pack/plugins/graph/public/app.js +++ b/x-pack/plugins/graph/public/app.js @@ -57,15 +57,15 @@ export function initGraphApp(angularModule, deps) { const app = angularModule; - app.directive('vennDiagram', function(reactDirective) { + app.directive('vennDiagram', function (reactDirective) { return reactDirective(VennDiagram); }); - app.directive('graphVisualization', function(reactDirective) { + app.directive('graphVisualization', function (reactDirective) { return reactDirective(GraphVisualization); }); - app.directive('graphListing', function(reactDirective) { + app.directive('graphListing', function (reactDirective) { return reactDirective(Listing, [ ['coreStart', { watchDepth: 'reference' }], ['createItem', { watchDepth: 'reference' }], @@ -81,7 +81,7 @@ export function initGraphApp(angularModule, deps) { ]); }); - app.directive('graphApp', function(reactDirective) { + app.directive('graphApp', function (reactDirective) { return reactDirective( GraphApp, [ @@ -102,33 +102,33 @@ export function initGraphApp(angularModule, deps) { ); }); - app.directive('graphVisualization', function(reactDirective) { + app.directive('graphVisualization', function (reactDirective) { return reactDirective(GraphVisualization, undefined, { restrict: 'A' }); }); - app.config(function($routeProvider) { + app.config(function ($routeProvider) { $routeProvider .when('/home', { template: listingTemplate, badge: getReadonlyBadge, - controller: function($location, $scope) { + controller: function ($location, $scope) { $scope.listingLimit = savedObjects.settings.getListingLimit(); $scope.initialPageSize = savedObjects.settings.getPerPage(); $scope.create = () => { $location.url(getNewPath()); }; - $scope.find = search => { + $scope.find = (search) => { return findSavedWorkspace( { savedObjectsClient, basePath: coreStart.http.basePath }, search, $scope.listingLimit ); }; - $scope.editItem = workspace => { + $scope.editItem = (workspace) => { $location.url(getEditPath(workspace)); }; - $scope.getViewUrl = workspace => getEditUrl(addBasePath, workspace); - $scope.delete = workspaces => + $scope.getViewUrl = (workspace) => getEditUrl(addBasePath, workspace); + $scope.delete = (workspaces) => deleteSavedWorkspace( savedObjectsClient, workspaces.map(({ id }) => id) @@ -143,9 +143,9 @@ export function initGraphApp(angularModule, deps) { template: appTemplate, badge: getReadonlyBadge, resolve: { - savedWorkspace: function($rootScope, $route, $location) { + savedWorkspace: function ($rootScope, $route, $location) { return $route.current.params.id - ? getSavedWorkspace(savedObjectsClient, $route.current.params.id).catch(function(e) { + ? getSavedWorkspace(savedObjectsClient, $route.current.params.id).catch(function (e) { toastNotifications.addError(e, { title: i18n.translate('xpack.graph.missingWorkspaceErrorMessage', { defaultMessage: "Couldn't load graph with ID", @@ -160,16 +160,16 @@ export function initGraphApp(angularModule, deps) { }) : getSavedWorkspace(savedObjectsClient); }, - indexPatterns: function() { + indexPatterns: function () { return savedObjectsClient .find({ type: 'index-pattern', fields: ['title', 'type'], perPage: 10000, }) - .then(response => response.savedObjects); + .then((response) => response.savedObjects); }, - GetIndexPatternProvider: function() { + GetIndexPatternProvider: function () { return indexPatterns; }, }, @@ -180,7 +180,7 @@ export function initGraphApp(angularModule, deps) { }); //======== Controller for basic UI ================== - app.controller('graphuiPlugin', function($scope, $route, $location) { + app.controller('graphuiPlugin', function ($scope, $route, $location) { function handleError(err) { const toastTitle = i18n.translate('xpack.graph.errorToastTitle', { defaultMessage: 'Graph Error', @@ -214,7 +214,7 @@ export function initGraphApp(angularModule, deps) { $scope.loading = true; return coreStart.http .post('../api/graph/graphExplore', request) - .then(function(data) { + .then(function (data) { const response = data.resp; if (response.timed_out) { toastNotifications.addWarning( @@ -233,7 +233,7 @@ export function initGraphApp(angularModule, deps) { } //Helper function for the graphClientWorkspace to perform a query - const callSearchNodeProxy = function(indexName, query, responseHandler) { + const callSearchNodeProxy = function (indexName, query, responseHandler) { const request = { body: JSON.stringify({ index: indexName, @@ -243,7 +243,7 @@ export function initGraphApp(angularModule, deps) { $scope.loading = true; coreStart.http .post('../api/graph/searchProxy', request) - .then(function(data) { + .then(function (data) { const response = data.resp; responseHandler(response); }) @@ -268,10 +268,10 @@ export function initGraphApp(angularModule, deps) { indexName: indexPattern, vertex_fields: [], // Here we have the opportunity to look up labels for nodes... - nodeLabeller: function() { + nodeLabeller: function () { // console.log(newNodes); }, - changeHandler: function() { + changeHandler: function () { //Allows DOM to update with graph layout changes. $scope.$apply(); }, @@ -281,10 +281,10 @@ export function initGraphApp(angularModule, deps) { }; $scope.workspace = createWorkspace(options); }, - setLiveResponseFields: fields => { + setLiveResponseFields: (fields) => { $scope.liveResponseFields = fields; }, - setUrlTemplates: urlTemplates => { + setUrlTemplates: (urlTemplates) => { $scope.urlTemplates = urlTemplates; }, getWorkspace: () => { @@ -302,7 +302,7 @@ export function initGraphApp(angularModule, deps) { $scope.workspaceInitialized = true; }, savePolicy: graphSavePolicy, - changeUrl: newUrl => { + changeUrl: (newUrl) => { $scope.$evalAsync(() => { $location.url(newUrl); }); @@ -326,8 +326,8 @@ export function initGraphApp(angularModule, deps) { const allSavingDisabled = graphSavePolicy === 'none'; $scope.spymode = 'request'; $scope.colors = colorChoices; - $scope.isColorDark = color => isColorDark(...hexToRgb(color)); - $scope.nodeClick = function(n, $event) { + $scope.isColorDark = (color) => isColorDark(...hexToRgb(color)); + $scope.nodeClick = function (n, $event) { //Selection logic - shift key+click helps selects multiple nodes // Without the shift key we deselect all prior selections (perhaps not // a great idea for touch devices with no concept of shift key) @@ -344,14 +344,14 @@ export function initGraphApp(angularModule, deps) { } }; - $scope.clickEdge = function(edge) { + $scope.clickEdge = function (edge) { $scope.workspace.getAllIntersections($scope.handleMergeCandidatesCallback, [ edge.topSrc, edge.topTarget, ]); }; - $scope.submit = function(searchTerm) { + $scope.submit = function (searchTerm) { $scope.workspaceInitialized = true; const numHops = 2; if (searchTerm.startsWith('{')) { @@ -372,28 +372,28 @@ export function initGraphApp(angularModule, deps) { $scope.workspace.simpleSearch(searchTerm, $scope.liveResponseFields, numHops); }; - $scope.selectSelected = function(node) { + $scope.selectSelected = function (node) { $scope.detail = { latestNodeSelection: node, }; return ($scope.selectedSelectedVertex = node); }; - $scope.isSelectedSelected = function(node) { + $scope.isSelectedSelected = function (node) { return $scope.selectedSelectedVertex === node; }; - $scope.openUrlTemplate = function(template) { + $scope.openUrlTemplate = function (template) { const url = template.url; const newUrl = url.replace(urlTemplateRegex, template.encoder.encode($scope.workspace)); window.open(newUrl, '_blank'); }; - $scope.aceLoaded = editor => { + $scope.aceLoaded = (editor) => { editor.$blockScrolling = Infinity; }; - $scope.setDetail = function(data) { + $scope.setDetail = function (data) { $scope.detail = data; }; @@ -421,7 +421,7 @@ export function initGraphApp(angularModule, deps) { }), confirmModalOptions ) - .then(isConfirmed => { + .then((isConfirmed) => { if (isConfirmed) { callback(); } @@ -429,7 +429,7 @@ export function initGraphApp(angularModule, deps) { } $scope.confirmWipeWorkspace = canWipeWorkspace; - $scope.performMerge = function(parentId, childId) { + $scope.performMerge = function (parentId, childId) { let found = true; while (found) { found = false; @@ -448,9 +448,9 @@ export function initGraphApp(angularModule, deps) { $scope.detail = null; }; - $scope.handleMergeCandidatesCallback = function(termIntersects) { + $scope.handleMergeCandidatesCallback = function (termIntersects) { const mergeCandidates = []; - termIntersects.forEach(ti => { + termIntersects.forEach((ti) => { mergeCandidates.push({ id1: ti.id1, id2: ti.id2, @@ -477,8 +477,8 @@ export function initGraphApp(angularModule, deps) { tooltip: i18n.translate('xpack.graph.topNavMenu.newWorkspaceTooltip', { defaultMessage: 'Create a new workspace', }), - run: function() { - canWipeWorkspace(function() { + run: function () { + canWipeWorkspace(function () { $scope.$evalAsync(() => { if ($location.url() === '/workspace/') { $route.reload(); @@ -516,7 +516,7 @@ export function initGraphApp(angularModule, deps) { }); } }, - disableButton: function() { + disableButton: function () { return allSavingDisabled || !hasFieldsSelector(store.getState()); }, run: () => { @@ -530,7 +530,7 @@ export function initGraphApp(angularModule, deps) { } $scope.topNavMenu.push({ key: 'inspect', - disableButton: function() { + disableButton: function () { return $scope.workspace === null; }, label: i18n.translate('xpack.graph.topNavMenu.inspectLabel', { @@ -550,7 +550,7 @@ export function initGraphApp(angularModule, deps) { $scope.topNavMenu.push({ key: 'settings', - disableButton: function() { + disableButton: function () { return datasourceSelector(store.getState()).type === 'none'; }, label: i18n.translate('xpack.graph.topNavMenu.settingsLabel', { @@ -605,7 +605,7 @@ export function initGraphApp(angularModule, deps) { }; $scope.closeMenus = () => { - _.forOwn($scope.menus, function(_, key) { + _.forOwn($scope.menus, function (_, key) { $scope.menus[key] = false; }); }; diff --git a/x-pack/plugins/graph/public/application.ts b/x-pack/plugins/graph/public/application.ts index 7c0fb867b9ada..b46bc88500e0a 100644 --- a/x-pack/plugins/graph/public/application.ts +++ b/x-pack/plugins/graph/public/application.ts @@ -77,7 +77,7 @@ export const renderApp = ({ appBasePath, element, ...deps }: GraphDependencies) true ); - const licenseSubscription = deps.licensing.license$.subscribe(license => { + const licenseSubscription = deps.licensing.license$.subscribe((license) => { const info = checkLicense(license); const licenseAllowsToShowThisPage = info.showAppLink && info.enableAppLink; diff --git a/x-pack/plugins/graph/public/components/field_manager/field_editor.tsx b/x-pack/plugins/graph/public/components/field_manager/field_editor.tsx index 211458e67d05b..cd2227bf6a18c 100644 --- a/x-pack/plugins/graph/public/components/field_manager/field_editor.tsx +++ b/x-pack/plugins/graph/public/components/field_manager/field_editor.tsx @@ -215,7 +215,7 @@ export function FieldEditor({ })} > { + onChange={(choices) => { // value is always defined because it's an unclearable single selection const newFieldName = choices[0].value!; @@ -260,7 +260,7 @@ export function FieldEditor({ > { + onChange={(newColor) => { updateProp('color', newColor); }} compressed @@ -286,7 +286,7 @@ export function FieldEditor({ ); }} - options={iconChoices.map(currentIcon => ({ + options={iconChoices.map((currentIcon) => ({ label: currentIcon.label, value: currentIcon, }))} @@ -296,7 +296,7 @@ export function FieldEditor({ value: icon, }, ]} - onChange={choices => { + onChange={(choices) => { updateProp('icon', choices[0].value!); }} compressed @@ -378,7 +378,7 @@ function toOptions( currentField: WorkspaceField ): Array<{ label: string; value: string; type: ButtonHTMLAttributes['type'] }> { return fields - .filter(field => !field.selected || field === currentField) + .filter((field) => !field.selected || field === currentField) .map(({ name, type }) => ({ label: name, value: name, diff --git a/x-pack/plugins/graph/public/components/field_manager/field_manager.test.tsx b/x-pack/plugins/graph/public/components/field_manager/field_manager.test.tsx index ac656ebdd9512..f213fe6b509bf 100644 --- a/x-pack/plugins/graph/public/components/field_manager/field_manager.test.tsx +++ b/x-pack/plugins/graph/public/components/field_manager/field_manager.test.tsx @@ -76,28 +76,13 @@ describe('field_manager', () => { ); - getInstance = () => - instance - .find(FieldManager) - .dive() - .dive() - .dive(); + getInstance = () => instance.find(FieldManager).dive().dive().dive(); }); it('should list editors for all selected fields', () => { expect(getInstance().find(FieldEditor).length).toEqual(2); - expect( - getInstance() - .find(FieldEditor) - .at(0) - .prop('field').name - ).toEqual('field1'); - expect( - getInstance() - .find(FieldEditor) - .at(1) - .prop('field').name - ).toEqual('field2'); + expect(getInstance().find(FieldEditor).at(0).prop('field').name).toEqual('field1'); + expect(getInstance().find(FieldEditor).at(1).prop('field').name).toEqual('field2'); }); it('should show selected non-aggregatable fields in picker, but hide unselected ones', () => { @@ -122,11 +107,9 @@ describe('field_manager', () => { ).toEqual(['field1', 'field2', 'field3']); act(() => { - getInstance() - .find(FieldPicker) - .dive() - .find(EuiSelectable) - .prop('onChange')([{ checked: 'on', label: 'field3' }]); + getInstance().find(FieldPicker).dive().find(EuiSelectable).prop('onChange')([ + { checked: 'on', label: 'field3' }, + ]); }); expect(dispatchSpy).toHaveBeenCalledWith({ @@ -139,12 +122,8 @@ describe('field_manager', () => { it('should deselect field', () => { act(() => { - getInstance() - .find(FieldEditor) - .at(0) - .dive() - .find(EuiContextMenu) - .prop('panels')![0].items![2].onClick!({} as any); + getInstance().find(FieldEditor).at(0).dive().find(EuiContextMenu).prop('panels')![0].items![2] + .onClick!({} as any); }); expect(dispatchSpy).toHaveBeenCalledWith({ @@ -157,12 +136,8 @@ describe('field_manager', () => { it('should show remove non-aggregatable fields from picker after deselection', () => { act(() => { - getInstance() - .find(FieldEditor) - .at(1) - .dive() - .find(EuiContextMenu) - .prop('panels')![0].items![2].onClick!({} as any); + getInstance().find(FieldEditor).at(1).dive().find(EuiContextMenu).prop('panels')![0].items![2] + .onClick!({} as any); }); expect( getInstance() @@ -198,12 +173,8 @@ describe('field_manager', () => { }); expect( - getInstance() - .find(FieldEditor) - .at(0) - .dive() - .find(EuiContextMenu) - .prop('panels')![0].items![1].name + getInstance().find(FieldEditor).at(0).dive().find(EuiContextMenu).prop('panels')![0].items![1] + .name ).toEqual('Enable field'); }); @@ -231,37 +202,26 @@ describe('field_manager', () => { }); expect( - getInstance() - .find(FieldEditor) - .at(1) - .dive() - .find(EuiContextMenu) - .prop('panels')![0].items![1].name + getInstance().find(FieldEditor).at(1).dive().find(EuiContextMenu).prop('panels')![0].items![1] + .name ).toEqual('Disable field'); }); it('should change color', () => { - const fieldEditor = getInstance() - .find(FieldEditor) - .at(1) - .dive(); + const fieldEditor = getInstance().find(FieldEditor).at(1).dive(); const getDisplayForm = () => shallow(fieldEditor.find(EuiContextMenu).prop('panels')![1].content as ReactElement); act(() => { - getDisplayForm() - .find(EuiColorPicker) - .prop('onChange')!('#aaa', { + getDisplayForm().find(EuiColorPicker).prop('onChange')!('#aaa', { rgba: [170, 170, 170, 1], hex: '#aaa', isValid: true, }); }); fieldEditor.update(); - getDisplayForm() - .find(EuiButton) - .prop('onClick')!({} as any); + getDisplayForm().find(EuiButton).prop('onClick')!({} as any); expect(dispatchSpy).toHaveBeenCalledWith({ type: 'x-pack/graph/fields/UPDATE_FIELD_PROPERTIES', diff --git a/x-pack/plugins/graph/public/components/field_manager/field_manager.tsx b/x-pack/plugins/graph/public/components/field_manager/field_manager.tsx index 9bca5b82e58aa..d0e44542674ef 100644 --- a/x-pack/plugins/graph/public/components/field_manager/field_manager.tsx +++ b/x-pack/plugins/graph/public/components/field_manager/field_manager.tsx @@ -40,7 +40,7 @@ export function FieldManagerComponent(props: { }) { return ( - {props.selectedFields.map(field => ( + {props.selectedFields.map((field) => ( @@ -58,7 +58,7 @@ export const FieldManager = connect( allFields: fieldsSelector(state), selectedFields: selectedFieldsSelector(state), }), - dispatch => + (dispatch) => bindActionCreators( { updateFieldProperties, diff --git a/x-pack/plugins/graph/public/components/field_manager/field_picker.tsx b/x-pack/plugins/graph/public/components/field_manager/field_picker.tsx index f2dc9ba0c6490..ae32e8d2ce6d6 100644 --- a/x-pack/plugins/graph/public/components/field_manager/field_picker.tsx +++ b/x-pack/plugins/graph/public/components/field_manager/field_picker.tsx @@ -88,8 +88,8 @@ export function FieldPicker({ }} searchable options={fieldOptions} - onChange={newOptions => { - newOptions.forEach(option => { + onChange={(newOptions) => { + newOptions.forEach((option) => { if (option.checked === 'on' && !fieldMap[option.label].selected) { selectField(option.label); } else if (option.checked !== 'on' && fieldMap[option.label].selected) { @@ -119,8 +119,8 @@ function toOptions( // don't show non-aggregatable fields, except for the case when they are already selected. // this is necessary to ensure backwards compatibility with existing workspaces that might // contain non-aggregatable fields. - .filter(field => isExplorable(field) || field.selected) - .map(field => ({ + .filter((field) => isExplorable(field) || field.selected) + .map((field) => ({ label: field.name, prepend: , checked: field.selected ? 'on' : undefined, diff --git a/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.test.tsx b/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.test.tsx index be3ebee9f0e23..1dd83f17ac8d4 100644 --- a/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.test.tsx +++ b/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.test.tsx @@ -136,10 +136,7 @@ describe('graph_visualization', () => { edges={edges} /> ); - instance - .find('.gphNode') - .first() - .simulate('click', {}); + instance.find('.gphNode').first().simulate('click', {}); expect(nodeClickSpy).toHaveBeenCalledWith(nodes[0], {}); }); @@ -153,10 +150,7 @@ describe('graph_visualization', () => { edges={edges} /> ); - instance - .find('.gphEdge') - .first() - .simulate('click'); + instance.find('.gphEdge').first().simulate('click'); expect(edgeClickSpy).toHaveBeenCalledWith(edges[0]); }); }); diff --git a/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.tsx b/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.tsx index 162e4d01db6a4..8561989c8a6bf 100644 --- a/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.tsx +++ b/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.tsx @@ -36,7 +36,7 @@ export interface GraphVisualizationProps { } function registerZooming(element: SVGSVGElement) { - const blockScroll = function() { + const blockScroll = function () { (d3.event as Event).preventDefault(); }; d3.select(element) @@ -69,7 +69,7 @@ export function GraphVisualization({ height="100%" pointerEvents="all" id="graphSvg" - ref={element => { + ref={(element) => { if (element && svgRoot.current !== element) { svgRoot.current = element; registerZooming(element); @@ -79,7 +79,7 @@ export function GraphVisualization({ {edges && - edges.map(edge => ( + edges.map((edge) => ( {nodes && nodes - .filter(node => !node.parent) - .map(node => ( + .filter((node) => !node.parent) + .map((node) => ( { + onClick={(e) => { nodeClick(node, e); }} - onMouseDown={e => { + onMouseDown={(e) => { // avoid selecting text when selecting nodes if (e.ctrlKey || e.shiftKey) { e.preventDefault(); diff --git a/x-pack/plugins/graph/public/components/guidance_panel/guidance_panel.tsx b/x-pack/plugins/graph/public/components/guidance_panel/guidance_panel.tsx index 4404ea494b288..583be123a48ce 100644 --- a/x-pack/plugins/graph/public/components/guidance_panel/guidance_panel.tsx +++ b/x-pack/plugins/graph/public/components/guidance_panel/guidance_panel.tsx @@ -217,7 +217,7 @@ export const GuidancePanel = connect( hasFields: hasFieldsSelector(state), }; }, - dispatch => ({ + (dispatch) => ({ onIndexPatternSelected: (indexPattern: IndexPatternSavedObject) => { dispatch( requestDatasource({ diff --git a/x-pack/plugins/graph/public/components/helpers.ts b/x-pack/plugins/graph/public/components/helpers.ts index e53f7f5b12713..db1d1e78f254a 100644 --- a/x-pack/plugins/graph/public/components/helpers.ts +++ b/x-pack/plugins/graph/public/components/helpers.ts @@ -5,5 +5,5 @@ */ export function isEqual(a: T, b: T) { - return (Object.keys(a) as Array).every(key => a[key] === b[key]); + return (Object.keys(a) as Array).every((key) => a[key] === b[key]); } diff --git a/x-pack/plugins/graph/public/components/save_modal.tsx b/x-pack/plugins/graph/public/components/save_modal.tsx index c4459fb1a794f..265d8155e46d6 100644 --- a/x-pack/plugins/graph/public/components/save_modal.tsx +++ b/x-pack/plugins/graph/public/components/save_modal.tsx @@ -37,7 +37,7 @@ export function SaveModal({ const [dataConsent, setDataConsent] = useState(false); return ( { + onSave={(props) => { onSave({ ...props, newDescription, dataConsent }); }} onClose={onClose} @@ -58,7 +58,7 @@ export function SaveModal({ { + onChange={(e) => { setDescription(e.target.value); }} fullWidth @@ -80,7 +80,7 @@ export function SaveModal({ defaultMessage: 'Save graph content', })} checked={dataConsent} - onChange={e => { + onChange={(e) => { setDataConsent(e.target.checked); }} /> diff --git a/x-pack/plugins/graph/public/components/search_bar.test.tsx b/x-pack/plugins/graph/public/components/search_bar.test.tsx index 10778124e2011..100122af943e1 100644 --- a/x-pack/plugins/graph/public/components/search_bar.test.tsx +++ b/x-pack/plugins/graph/public/components/search_bar.test.tsx @@ -24,7 +24,7 @@ import { Provider } from 'react-redux'; jest.mock('ui/new_platform'); jest.mock('../services/source_modal', () => ({ openSourceModal: jest.fn() })); -const waitForIndexPatternFetch = () => new Promise(r => setTimeout(r)); +const waitForIndexPatternFetch = () => new Promise((r) => setTimeout(r)); function wrapSearchBarInContext(testProps: OuterSearchBarProps) { const services = { diff --git a/x-pack/plugins/graph/public/components/search_bar.tsx b/x-pack/plugins/graph/public/components/search_bar.tsx index ab6d94a78ceec..a74e0ccfb46b5 100644 --- a/x-pack/plugins/graph/public/components/search_bar.tsx +++ b/x-pack/plugins/graph/public/components/search_bar.tsx @@ -97,7 +97,7 @@ export function SearchBarComponent(props: SearchBarProps) { return ( { + onSubmit={(e) => { e.preventDefault(); if (!isLoading && currentIndexPattern) { onQuerySubmit(queryToString(query, currentIndexPattern)); @@ -185,7 +185,7 @@ export const SearchBar = connect( datasource.current.type === 'indexpattern' ? datasource.current : undefined, }; }, - dispatch => ({ + (dispatch) => ({ onIndexPatternSelected: (indexPattern: IndexPatternSavedObject) => { dispatch( requestDatasource({ diff --git a/x-pack/plugins/graph/public/components/settings/advanced_settings_form.tsx b/x-pack/plugins/graph/public/components/settings/advanced_settings_form.tsx index 5231f7ddad6df..191655ec7bc17 100644 --- a/x-pack/plugins/graph/public/components/settings/advanced_settings_form.tsx +++ b/x-pack/plugins/graph/public/components/settings/advanced_settings_form.tsx @@ -31,7 +31,7 @@ export function AdvancedSettingsForm({ } function getNumberUpdater>(key: K) { - return function({ target: { valueAsNumber } }: { target: { valueAsNumber: number } }) { + return function ({ target: { valueAsNumber } }: { target: { valueAsNumber: number } }) { updateSetting(key, Number.isNaN(valueAsNumber) ? 1 : valueAsNumber); }; } @@ -125,7 +125,7 @@ export function AdvancedSettingsForm({ { defaultMessage: 'No diversification' } )} singleSelection={{ asPlainText: true }} - options={allFields.map(field => ({ label: field.name, value: field }))} + options={allFields.map((field) => ({ label: field.name, value: field }))} selectedOptions={ advancedSettings.sampleDiversityField ? [ @@ -136,7 +136,7 @@ export function AdvancedSettingsForm({ ] : [] } - onChange={choices => { + onChange={(choices) => { updateSetting( 'sampleDiversityField', choices.length === 1 ? choices[0].value : undefined diff --git a/x-pack/plugins/graph/public/components/settings/blacklist_form.tsx b/x-pack/plugins/graph/public/components/settings/blacklist_form.tsx index f7ae04ef9dbcc..68cdcc1fbb7b1 100644 --- a/x-pack/plugins/graph/public/components/settings/blacklist_form.tsx +++ b/x-pack/plugins/graph/public/components/settings/blacklist_form.tsx @@ -48,7 +48,7 @@ export function BlacklistForm({ {blacklistedNodes && unblacklistNode && blacklistedNodes.length > 0 && ( <> - {blacklistedNodes.map(node => ( + {blacklistedNodes.map((node) => ( } key={getListKey(node)} @@ -77,7 +77,7 @@ export function BlacklistForm({ size="s" fill onClick={() => { - blacklistedNodes.forEach(node => { + blacklistedNodes.forEach((node) => { unblacklistNode(node); }); }} diff --git a/x-pack/plugins/graph/public/components/settings/settings.test.tsx b/x-pack/plugins/graph/public/components/settings/settings.test.tsx index 0109e1f5a5ac7..b392a26ecf0d3 100644 --- a/x-pack/plugins/graph/public/components/settings/settings.test.tsx +++ b/x-pack/plugins/graph/public/components/settings/settings.test.tsx @@ -148,7 +148,7 @@ describe('settings', () => { act(() => { instance .find(EuiTab) - .findWhere(node => node.key() === tab) + .findWhere((node) => node.key() === tab) .prop('onClick')!({}); }); instance.update(); @@ -185,7 +185,7 @@ describe('settings', () => { }); it('should switch tab to blacklist', () => { - expect(instance.find(EuiListGroupItem).map(item => item.prop('label'))).toEqual([ + expect(instance.find(EuiListGroupItem).map((item) => item.prop('label'))).toEqual([ 'blacklisted node 1', 'blacklisted node 2', ]); @@ -219,25 +219,19 @@ describe('settings', () => { instance.update(); - expect(instance.find(EuiListGroupItem).map(item => item.prop('label'))).toEqual([ + expect(instance.find(EuiListGroupItem).map((item) => item.prop('label'))).toEqual([ 'blacklisted node 3', ]); }); it('should delete node', () => { - instance - .find(EuiListGroupItem) - .at(0) - .prop('extraAction')!.onClick!({} as any); + instance.find(EuiListGroupItem).at(0).prop('extraAction')!.onClick!({} as any); expect(angularProps.unblacklistNode).toHaveBeenCalledWith(angularProps.blacklistedNodes![0]); }); it('should delete all nodes', () => { - instance - .find('[data-test-subj="graphUnblacklistAll"]') - .find(EuiButton) - .simulate('click'); + instance.find('[data-test-subj="graphUnblacklistAll"]').find(EuiButton).simulate('click'); expect(angularProps.unblacklistNode).toHaveBeenCalledWith(angularProps.blacklistedNodes![0]); expect(angularProps.unblacklistNode).toHaveBeenCalledWith(angularProps.blacklistedNodes![1]); @@ -251,11 +245,9 @@ describe('settings', () => { function insert(formIndex: number, label: string, value: string) { act(() => { - templateForm(formIndex) - .find({ label }) - .first() - .find(EuiFieldText) - .prop('onChange')!({ target: { value } } as React.ChangeEvent); + templateForm(formIndex).find({ label }).first().find(EuiFieldText).prop('onChange')!({ + target: { value }, + } as React.ChangeEvent); }); instance.update(); } @@ -265,12 +257,7 @@ describe('settings', () => { }); it('should switch tab to url templates', () => { - expect( - instance - .find(EuiAccordion) - .at(0) - .prop('buttonContent') - ).toEqual('template'); + expect(instance.find(EuiAccordion).at(0).prop('buttonContent')).toEqual('template'); }); it('should delete url template', () => { @@ -283,9 +270,7 @@ describe('settings', () => { it('should update url template', () => { insert(0, 'Title', 'Updated title'); act(() => { - templateForm(0) - .find('form') - .simulate('submit'); + templateForm(0).find('form').simulate('submit'); }); expect(dispatchSpy).toHaveBeenCalledWith( saveTemplate({ index: 0, template: { ...initialTemplate, description: 'Updated title' } }) @@ -302,9 +287,7 @@ describe('settings', () => { insert(1, 'Title', 'Title'); act(() => { - templateForm(1) - .find('form') - .simulate('submit'); + templateForm(1).find('form').simulate('submit'); }); expect(dispatchSpy).toHaveBeenCalledWith( saveTemplate({ diff --git a/x-pack/plugins/graph/public/components/settings/settings.tsx b/x-pack/plugins/graph/public/components/settings/settings.tsx index d6613cc1e0b9a..3baf6b6a0a2e3 100644 --- a/x-pack/plugins/graph/public/components/settings/settings.tsx +++ b/x-pack/plugins/graph/public/components/settings/settings.tsx @@ -123,7 +123,7 @@ export const Settings = connect + (dispatch) => bindActionCreators( { updateSettings, diff --git a/x-pack/plugins/graph/public/components/settings/url_template_form.tsx b/x-pack/plugins/graph/public/components/settings/url_template_form.tsx index e92d06c3b93a5..ba0017a16f393 100644 --- a/x-pack/plugins/graph/public/components/settings/url_template_form.tsx +++ b/x-pack/plugins/graph/public/components/settings/url_template_form.tsx @@ -100,7 +100,7 @@ export function UrlTemplateForm(props: UrlTemplateFormProps) { encoder: currentTemplate.encoder.type === 'kql' ? currentTemplate.encoder - : outlinkEncoders.find(enc => enc.type === 'kql')!, + : outlinkEncoders.find((enc) => enc.type === 'kql')!, }); setAutoformatUrl(false); } @@ -131,13 +131,13 @@ export function UrlTemplateForm(props: UrlTemplateFormProps) { 'gphUrlTemplateList__accordion--isOpen': open, })} buttonClassName="gphUrlTemplateList__accordionbutton" - onToggle={isOpen => { + onToggle={(isOpen) => { setOpen(isOpen); }} paddingSize="m" > { + onSubmit={(e) => { e.preventDefault(); onSubmit(currentTemplate); if (!isUpdateForm(props)) { @@ -157,7 +157,7 @@ export function UrlTemplateForm(props: UrlTemplateFormProps) { fullWidth value={currentTemplate.description} isInvalid={touched.description && !currentTemplate.description} - onChange={e => setValue('description', e.target.value)} + onChange={(e) => setValue('description', e.target.value)} placeholder={i18n.translate( 'xpack.graph.settings.drillDowns.urlDescriptionInputPlaceholder', { defaultMessage: 'Search on Google' } @@ -212,11 +212,11 @@ export function UrlTemplateForm(props: UrlTemplateFormProps) { fullWidth placeholder="https://www.google.co.uk/#q={{gquery}}" value={currentTemplate.url} - onChange={e => { + onChange={(e) => { setValue('url', e.target.value); setAutoformatUrl(false); }} - onPaste={e => { + onPaste={(e) => { e.preventDefault(); const pastedUrl = e.clipboardData.getData('text/plain'); if (isKibanaUrl(pastedUrl)) { @@ -238,14 +238,14 @@ export function UrlTemplateForm(props: UrlTemplateFormProps) { fullWidth singleSelection={{ asPlainText: true }} isClearable={false} - options={outlinkEncoders.map(encoder => ({ label: encoder.title, value: encoder }))} + options={outlinkEncoders.map((encoder) => ({ label: encoder.title, value: encoder }))} selectedOptions={[ { label: currentTemplate.encoder.title, value: currentTemplate.encoder, }, ]} - onChange={choices => { + onChange={(choices) => { // choices[0].value can't be null because `isClearable` is set to false above setValue('encoder', choices[0].value!); }} @@ -258,7 +258,7 @@ export function UrlTemplateForm(props: UrlTemplateFormProps) { })} >

- {urlTemplateIconChoices.map(icon => ( + {urlTemplateIconChoices.map((icon) => ( formId !== id)); + setUncommittedForms(uncommittedForms.filter((formId) => formId !== id)); } return ( @@ -39,7 +39,7 @@ export function UrlTemplateList({ key={getListKey(template)} id={getListKey(template)} initialTemplate={template} - onSubmit={newTemplate => { + onSubmit={(newTemplate) => { saveTemplate({ index, template: newTemplate }); }} onRemove={() => { @@ -48,11 +48,11 @@ export function UrlTemplateList({ /> ))} - {uncommittedForms.map(id => ( + {uncommittedForms.map((id) => ( { + onSubmit={(newTemplate) => { saveTemplate({ index: -1, template: newTemplate }); removeUncommittedForm(id); }} diff --git a/x-pack/plugins/graph/public/components/settings/use_list_keys.test.tsx b/x-pack/plugins/graph/public/components/settings/use_list_keys.test.tsx index 08821c39a58c4..c80296feccdd4 100644 --- a/x-pack/plugins/graph/public/components/settings/use_list_keys.test.tsx +++ b/x-pack/plugins/graph/public/components/settings/use_list_keys.test.tsx @@ -36,7 +36,7 @@ describe('use_list_keys', () => { }); expect(instance.find('li').length).toEqual(5); - instance.find('li').forEach(el => { + instance.find('li').forEach((el) => { expect(ids.has(el.key())).toEqual(true); }); }); @@ -72,7 +72,7 @@ describe('use_list_keys', () => { }); expect(instance.find('li').length).toEqual(4); - instance.find('li').forEach(el => { + instance.find('li').forEach((el) => { expect(ids.has(el.key())).toEqual(true); }); }); @@ -80,7 +80,7 @@ describe('use_list_keys', () => { function collectIds(instance: ReactWrapper) { const ids = new Set(); - instance.find('li').forEach(el => { + instance.find('li').forEach((el) => { ids.add(el.key()); }); return ids; diff --git a/x-pack/plugins/graph/public/components/settings/use_list_keys.ts b/x-pack/plugins/graph/public/components/settings/use_list_keys.ts index 790d1d77615a5..ecf81d53056d4 100644 --- a/x-pack/plugins/graph/public/components/settings/use_list_keys.ts +++ b/x-pack/plugins/graph/public/components/settings/use_list_keys.ts @@ -30,7 +30,7 @@ export function useListKeys(list: T[]) { const idStore = useRef>(new Map()); const currentIdMap = useMemo(() => { const newMap: Map = new Map(); - list.forEach(item => { + list.forEach((item) => { if (idStore.current.has(item)) { newMap.set(item, idStore.current.get(item)!); } else { diff --git a/x-pack/plugins/graph/public/components/source_picker.tsx b/x-pack/plugins/graph/public/components/source_picker.tsx index 9172f6ba1c65c..acc965eaf3276 100644 --- a/x-pack/plugins/graph/public/components/source_picker.tsx +++ b/x-pack/plugins/graph/public/components/source_picker.tsx @@ -42,7 +42,7 @@ export function SourcePicker({ name: i18n.translate('xpack.graph.sourceModal.savedObjectType.indexPattern', { defaultMessage: 'Index pattern', }), - showSavedObject: indexPattern => !indexPattern.attributes.type, + showSavedObject: (indexPattern) => !indexPattern.attributes.type, includeFields: ['type'], }, ]} diff --git a/x-pack/plugins/graph/public/helpers/as_observable.ts b/x-pack/plugins/graph/public/helpers/as_observable.ts index 48372521babaf..f095002ef25cc 100644 --- a/x-pack/plugins/graph/public/helpers/as_observable.ts +++ b/x-pack/plugins/graph/public/helpers/as_observable.ts @@ -26,7 +26,7 @@ interface Props { export function asAngularSyncedObservable(collectProps: () => Props, angularDigest: () => void) { const boundCollectProps = () => { const collectedProps = collectProps(); - Object.keys(collectedProps).forEach(key => { + Object.keys(collectedProps).forEach((key) => { const currentValue = collectedProps[key]; if (typeof currentValue === 'function') { collectedProps[key] = (...args: unknown[]) => { diff --git a/x-pack/plugins/graph/public/helpers/kql_encoder.ts b/x-pack/plugins/graph/public/helpers/kql_encoder.ts index a12917fb93daa..3cdf8d91352c2 100644 --- a/x-pack/plugins/graph/public/helpers/kql_encoder.ts +++ b/x-pack/plugins/graph/public/helpers/kql_encoder.ts @@ -15,7 +15,7 @@ function escapeQuotes(str: string) { export function asKQL(workspace: Workspace, joinBy: 'and' | 'or') { const nodes = workspace.returnUnpackedGroupeds(workspace.getSelectedOrAllNodes()); const clauses = nodes.map( - node => `"${escapeQuotes(node.data.field)}" : "${escapeQuotes(node.data.term)}"` + (node) => `"${escapeQuotes(node.data.field)}" : "${escapeQuotes(node.data.term)}"` ); const expression = clauses.join(` ${joinBy} `); diff --git a/x-pack/plugins/graph/public/helpers/outlink_encoders.ts b/x-pack/plugins/graph/public/helpers/outlink_encoders.ts index 437641f3f2e8a..3590150fb7305 100644 --- a/x-pack/plugins/graph/public/helpers/outlink_encoders.ts +++ b/x-pack/plugins/graph/public/helpers/outlink_encoders.ts @@ -152,7 +152,7 @@ export const outlinkEncoders: OutlinkEncoder[] = [ const luceneChars = '+-&|!(){}[]^"~*?:\\'; q = q .split('') - .map(char => (luceneChars.includes(char) ? `\\${char}` : char)) + .map((char) => (luceneChars.includes(char) ? `\\${char}` : char)) .join(''); return encodeURIComponent(q); }, diff --git a/x-pack/plugins/graph/public/helpers/saved_workspace_utils.ts b/x-pack/plugins/graph/public/helpers/saved_workspace_utils.ts index 2933e94b86e86..421a72c989757 100644 --- a/x-pack/plugins/graph/public/helpers/saved_workspace_utils.ts +++ b/x-pack/plugins/graph/public/helpers/saved_workspace_utils.ts @@ -74,10 +74,10 @@ export function findSavedWorkspace( perPage: size, searchFields: ['title^3', 'description'], }) - .then(resp => { + .then((resp) => { return { total: resp.total, - hits: resp.savedObjects.map(hit => mapHits(hit, urlFor(basePath, hit.id))), + hits: resp.savedObjects.map((hit) => mapHits(hit, urlFor(basePath, hit.id))), }; }); } diff --git a/x-pack/plugins/graph/public/helpers/style_choices.ts b/x-pack/plugins/graph/public/helpers/style_choices.ts index 46fec39bfce06..f228c9f052b6b 100644 --- a/x-pack/plugins/graph/public/helpers/style_choices.ts +++ b/x-pack/plugins/graph/public/helpers/style_choices.ts @@ -167,12 +167,12 @@ export const iconChoices = [ ]; export const getSuitableIcon = (fieldName: string) => - iconChoices.find(choice => choice.patterns.some(pattern => pattern.test(fieldName))) || + iconChoices.find((choice) => choice.patterns.some((pattern) => pattern.test(fieldName))) || iconChoices[0]; export const iconChoicesByClass: Partial> = {}; -iconChoices.forEach(icon => { +iconChoices.forEach((icon) => { iconChoicesByClass[icon.class] = icon; }); @@ -251,7 +251,7 @@ export const urlTemplateIconChoices = [ ]; export const urlTemplateIconChoicesByClass: Partial> = {}; -urlTemplateIconChoices.forEach(icon => { +urlTemplateIconChoices.forEach((icon) => { urlTemplateIconChoicesByClass[icon.class] = icon; }); diff --git a/x-pack/plugins/graph/public/plugin.ts b/x-pack/plugins/graph/public/plugin.ts index 9d6d083b3e4b9..e97735c50388f 100644 --- a/x-pack/plugins/graph/public/plugin.ts +++ b/x-pack/plugins/graph/public/plugin.ts @@ -107,7 +107,7 @@ export class GraphPlugin if (this.licensing === null) { throw new Error('Start called before setup'); } - this.licensing.license$.subscribe(license => { + this.licensing.license$.subscribe((license) => { toggleNavLink(checkLicense(license), core.chrome.navLinks); }); } diff --git a/x-pack/plugins/graph/public/services/fetch_top_nodes.ts b/x-pack/plugins/graph/public/services/fetch_top_nodes.ts index d7df3513dba8d..f1f701498372b 100644 --- a/x-pack/plugins/graph/public/services/fetch_top_nodes.ts +++ b/x-pack/plugins/graph/public/services/fetch_top_nodes.ts @@ -55,7 +55,7 @@ function getTopTermsResult(response: TopTermsAggResponse, fieldName: string) { return []; } return response.aggregations.sample[createTopTermsAggName(fieldName)].buckets.map( - bucket => bucket.key + (bucket) => bucket.key ); } @@ -91,7 +91,7 @@ export async function fetchTopNodes( ) { const aggs = fields .map(({ name }) => name) - .map(fieldName => createTopTermsSubAgg(fieldName)) + .map((fieldName) => createTopTermsSubAgg(fieldName)) .reduce((allAggs, subAgg) => ({ ...allAggs, ...subAgg })); const body = createSamplerSearchBody(aggs); @@ -105,7 +105,7 @@ export async function fetchTopNodes( fields.forEach(({ name }) => { const topTerms = getTopTermsResult(response, name); - const fieldNodes = topTerms.map(term => createServerResultNode(name, term, fields)); + const fieldNodes = topTerms.map((term) => createServerResultNode(name, term, fields)); nodes.push(...fieldNodes); }); diff --git a/x-pack/plugins/graph/public/services/persistence/deserialize.ts b/x-pack/plugins/graph/public/services/persistence/deserialize.ts index 06106ed4c4f3f..6fd720a60edc0 100644 --- a/x-pack/plugins/graph/public/services/persistence/deserialize.ts +++ b/x-pack/plugins/graph/public/services/persistence/deserialize.ts @@ -42,7 +42,7 @@ function deserializeUrlTemplate({ iconClass, ...serializableProps }: SerializedUrlTemplate) { - const encoder = outlinkEncoders.find(outlinkEncoder => outlinkEncoder.id === encoderID); + const encoder = outlinkEncoders.find((outlinkEncoder) => outlinkEncoder.id === encoderID); if (!encoder) { return; } @@ -68,7 +68,7 @@ export function lookupIndexPattern( ) { const serializedWorkspaceState: SerializedWorkspaceState = JSON.parse(savedWorkspace.wsState); const indexPattern = indexPatterns.find( - pattern => pattern.attributes.title === serializedWorkspaceState.indexPattern + (pattern) => pattern.attributes.title === serializedWorkspaceState.indexPattern ); if (indexPattern) { @@ -84,7 +84,7 @@ export function mapFields(indexPattern: IndexPattern): WorkspaceField[] { return indexPattern .getNonScriptedFields() .filter( - field => !blockedFieldNames.includes(field.name) && !indexPatternsUtils.isNestedField(field) + (field) => !blockedFieldNames.includes(field.name) && !indexPatternsUtils.isNestedField(field) ) .map((field, index) => ({ name: field.name, @@ -113,8 +113,8 @@ function getFieldsWithWorkspaceSettings( const allFields = mapFields(indexPattern); // merge in selected information into all fields - selectedFields.forEach(serializedField => { - const workspaceField = allFields.find(field => field.name === serializedField.name); + selectedFields.forEach((serializedField) => { + const workspaceField = allFields.find((field) => field.name === serializedField.name); if (!workspaceField) { return; } @@ -132,8 +132,8 @@ function getBlacklistedNodes( serializedWorkspaceState: SerializedWorkspaceState, allFields: WorkspaceField[] ) { - return serializedWorkspaceState.blacklist.map(serializedNode => { - const currentField = allFields.find(field => field.name === serializedNode.field)!; + return serializedWorkspaceState.blacklist.map((serializedNode) => { + const currentField = allFields.find((field) => field.name === serializedNode.field)!; return { x: 0, y: 0, @@ -169,16 +169,16 @@ function getNodesAndEdges( allFields: WorkspaceField[] ): GraphData { return { - nodes: persistedWorkspaceState.vertices.map(serializedNode => ({ + nodes: persistedWorkspaceState.vertices.map((serializedNode) => ({ ...serializedNode, id: '', - icon: allFields.find(field => field.name === serializedNode.field)!.icon, + icon: allFields.find((field) => field.name === serializedNode.field)!.icon, data: { field: serializedNode.field, term: serializedNode.term, }, })), - edges: persistedWorkspaceState.links.map(serializedEdge => ({ + edges: persistedWorkspaceState.links.map((serializedEdge) => ({ ...serializedEdge, id: '', })), @@ -210,7 +210,7 @@ export function savedWorkspaceToAppState( indexPattern, persistedWorkspaceState.selectedFields ); - const selectedFields = allFields.filter(field => field.selected); + const selectedFields = allFields.filter((field) => field.selected); workspaceInstance.options.vertex_fields = selectedFields; // ================== advanced settings ============================= @@ -224,7 +224,7 @@ export function savedWorkspaceToAppState( // restore reference to sample diversity field const serializedField = advancedSettings.sampleDiversityField; advancedSettings.sampleDiversityField = allFields.find( - field => field.name === serializedField.name + (field) => field.name === serializedField.name ); } diff --git a/x-pack/plugins/graph/public/services/persistence/saved_workspace_references.ts b/x-pack/plugins/graph/public/services/persistence/saved_workspace_references.ts index 0948d7a88fce8..c92c831242ad2 100644 --- a/x-pack/plugins/graph/public/services/persistence/saved_workspace_references.ts +++ b/x-pack/plugins/graph/public/services/persistence/saved_workspace_references.ts @@ -53,7 +53,7 @@ export function injectReferences( return; } const indexPatternReference = references.find( - reference => reference.name === state.indexPatternRefName + (reference) => reference.name === state.indexPatternRefName ); if (!indexPatternReference) { // Throw an error as "indexPatternRefName" means the reference exists within diff --git a/x-pack/plugins/graph/public/services/persistence/serialize.ts b/x-pack/plugins/graph/public/services/persistence/serialize.ts index cc6af1b9222f1..6cbebc995d84a 100644 --- a/x-pack/plugins/graph/public/services/persistence/serialize.ts +++ b/x-pack/plugins/graph/public/services/persistence/serialize.ts @@ -97,13 +97,13 @@ export function appStateToSavedWorkspace( canSaveData: boolean ) { const blacklist: SerializedNode[] = canSaveData - ? workspace.blacklistedNodes.map(node => serializeNode(node)) + ? workspace.blacklistedNodes.map((node) => serializeNode(node)) : []; const vertices: SerializedNode[] = canSaveData - ? workspace.nodes.map(node => serializeNode(node, workspace.nodes)) + ? workspace.nodes.map((node) => serializeNode(node, workspace.nodes)) : []; const links: SerializedEdge[] = canSaveData - ? workspace.edges.map(edge => serializeEdge(edge, workspace.nodes)) + ? workspace.edges.map((edge) => serializeEdge(edge, workspace.nodes)) : []; const mappedUrlTemplates = urlTemplates.map(serializeUrlTemplate); diff --git a/x-pack/plugins/graph/public/services/save_modal.tsx b/x-pack/plugins/graph/public/services/save_modal.tsx index 94b5de3be13ac..730fe7b065e47 100644 --- a/x-pack/plugins/graph/public/services/save_modal.tsx +++ b/x-pack/plugins/graph/public/services/save_modal.tsx @@ -60,7 +60,7 @@ export function openSaveModal({ isTitleDuplicateConfirmed, onTitleDuplicate, }; - return saveWorkspace(saveOptions, dataConsent, services).then(response => { + return saveWorkspace(saveOptions, dataConsent, services).then((response) => { // If the save wasn't successful, put the original values back. if (!('id' in response) || !Boolean(response.id)) { workspace.title = currentTitle; diff --git a/x-pack/plugins/graph/public/services/source_modal.tsx b/x-pack/plugins/graph/public/services/source_modal.tsx index 20a5b6d0786bd..d5ffe4c0c9651 100644 --- a/x-pack/plugins/graph/public/services/source_modal.tsx +++ b/x-pack/plugins/graph/public/services/source_modal.tsx @@ -26,7 +26,7 @@ export function openSourceModal( { + onIndexPatternSelected={(indexPattern) => { onSelected(indexPattern); modalRef.close(); }} diff --git a/x-pack/plugins/graph/public/state_management/advanced_settings.ts b/x-pack/plugins/graph/public/state_management/advanced_settings.ts index e6325c1e7fd68..27c784ba71ee1 100644 --- a/x-pack/plugins/graph/public/state_management/advanced_settings.ts +++ b/x-pack/plugins/graph/public/state_management/advanced_settings.ts @@ -52,7 +52,7 @@ export const syncSettingsSaga = ({ getWorkspace, notifyAngular }: GraphStoreDepe notifyAngular(); } - return function*() { + return function* () { yield takeLatest(updateSettings.match, syncSettings); }; }; diff --git a/x-pack/plugins/graph/public/state_management/datasource.sagas.ts b/x-pack/plugins/graph/public/state_management/datasource.sagas.ts index 018b3b42b9157..f468ce5beb21c 100644 --- a/x-pack/plugins/graph/public/state_management/datasource.sagas.ts +++ b/x-pack/plugins/graph/public/state_management/datasource.sagas.ts @@ -50,7 +50,7 @@ export const datasourceSaga = ({ } } - return function*() { + return function* () { yield takeLatest(requestDatasource.match, fetchFields); }; }; diff --git a/x-pack/plugins/graph/public/state_management/datasource.test.ts b/x-pack/plugins/graph/public/state_management/datasource.test.ts index 84f3741604e20..13b7080d776a2 100644 --- a/x-pack/plugins/graph/public/state_management/datasource.test.ts +++ b/x-pack/plugins/graph/public/state_management/datasource.test.ts @@ -12,7 +12,7 @@ import { fieldsSelector } from './fields'; import { updateSettings } from './advanced_settings'; import { IndexPattern } from '../../../../../src/plugins/data/public'; -const waitForPromise = () => new Promise(r => setTimeout(r)); +const waitForPromise = () => new Promise((r) => setTimeout(r)); describe('datasource saga', () => { let env: MockedGraphEnvironment; diff --git a/x-pack/plugins/graph/public/state_management/datasource.ts b/x-pack/plugins/graph/public/state_management/datasource.ts index fac4f0da1edb0..4f86b6b0fd072 100644 --- a/x-pack/plugins/graph/public/state_management/datasource.ts +++ b/x-pack/plugins/graph/public/state_management/datasource.ts @@ -57,7 +57,7 @@ export const datasourceReducer = reducerWithInitialState(initia current: newDatasource, loading: true, })) - .case(datasourceLoaded, datasource => ({ + .case(datasourceLoaded, (datasource) => ({ ...datasource, loading: false, })) @@ -66,5 +66,5 @@ export const datasourceReducer = reducerWithInitialState(initia export const datasourceSelector = (state: GraphState) => state.datasource; export const hasDatasourceSelector = createSelector( datasourceSelector, - datasource => datasource.current.type !== 'none' + (datasource) => datasource.current.type !== 'none' ); diff --git a/x-pack/plugins/graph/public/state_management/fields.ts b/x-pack/plugins/graph/public/state_management/fields.ts index 865de323332c4..a54f9fd07b166 100644 --- a/x-pack/plugins/graph/public/state_management/fields.ts +++ b/x-pack/plugins/graph/public/state_management/fields.ts @@ -33,7 +33,7 @@ export const fieldsReducer = reducerWithInitialState(initialFields) .case(setDatasource, () => initialFields) .case(loadFields, (_currentFields, newFields) => { const newFieldMap: Record = {}; - newFields.forEach(field => { + newFields.forEach((field) => { newFieldMap[field.name] = field; }); @@ -51,16 +51,16 @@ export const fieldsReducer = reducerWithInitialState(initialFields) .build(); export const fieldMapSelector = (state: GraphState) => state.fields; -export const fieldsSelector = createSelector(fieldMapSelector, fields => Object.values(fields)); -export const selectedFieldsSelector = createSelector(fieldsSelector, fields => - fields.filter(field => field.selected) +export const fieldsSelector = createSelector(fieldMapSelector, (fields) => Object.values(fields)); +export const selectedFieldsSelector = createSelector(fieldsSelector, (fields) => + fields.filter((field) => field.selected) ); -export const liveResponseFieldsSelector = createSelector(selectedFieldsSelector, fields => - fields.filter(field => field.hopSize && field.hopSize > 0) +export const liveResponseFieldsSelector = createSelector(selectedFieldsSelector, (fields) => + fields.filter((field) => field.hopSize && field.hopSize > 0) ); export const hasFieldsSelector = createSelector( selectedFieldsSelector, - fields => fields.length > 0 + (fields) => fields.length > 0 ); /** @@ -72,7 +72,7 @@ export const updateSaveButtonSaga = ({ notifyAngular }: GraphStoreDependencies) function* notify(): IterableIterator { notifyAngular(); } - return function*() { + return function* () { yield takeLatest(matchesOne(selectField, deselectField), notify); }; }; @@ -94,7 +94,7 @@ export const syncFieldsSaga = ({ getWorkspace, setLiveResponseFields }: GraphSto workspace.options.vertex_fields = selectedFieldsSelector(currentState); setLiveResponseFields(liveResponseFieldsSelector(currentState)); } - return function*() { + return function* () { yield takeEvery( matchesOne(loadFields, selectField, deselectField, updateFieldProperties), syncFields @@ -116,7 +116,7 @@ export const syncNodeStyleSaga = ({ getWorkspace, notifyAngular }: GraphStoreDep } const newColor = action.payload.fieldProperties.color; if (newColor) { - workspace.nodes.forEach(function(node) { + workspace.nodes.forEach(function (node) { if (node.data.field === action.payload.fieldName) { node.color = newColor; } @@ -125,7 +125,7 @@ export const syncNodeStyleSaga = ({ getWorkspace, notifyAngular }: GraphStoreDep const newIcon = action.payload.fieldProperties.icon; if (newIcon) { - workspace.nodes.forEach(function(node) { + workspace.nodes.forEach(function (node) { if (node.data.field === action.payload.fieldName) { node.icon = newIcon; } @@ -137,7 +137,7 @@ export const syncNodeStyleSaga = ({ getWorkspace, notifyAngular }: GraphStoreDep workspace.options.vertex_fields = selectedFields; } - return function*() { + return function* () { yield takeLatest(updateFieldProperties.match, syncNodeStyle); }; }; diff --git a/x-pack/plugins/graph/public/state_management/helpers.ts b/x-pack/plugins/graph/public/state_management/helpers.ts index 215691d454484..05773e545ec5e 100644 --- a/x-pack/plugins/graph/public/state_management/helpers.ts +++ b/x-pack/plugins/graph/public/state_management/helpers.ts @@ -25,4 +25,4 @@ export type InferActionType = X extends ActionCreator ? T : never; * @param actionCreators The action creators to create a unified matcher for */ export const matchesOne = (...actionCreators: Array>) => (action: AnyAction) => - actionCreators.some(actionCreator => actionCreator.match(action)); + actionCreators.some((actionCreator) => actionCreator.match(action)); diff --git a/x-pack/plugins/graph/public/state_management/meta_data.ts b/x-pack/plugins/graph/public/state_management/meta_data.ts index 560216568f65f..5ed2b68e22c86 100644 --- a/x-pack/plugins/graph/public/state_management/meta_data.ts +++ b/x-pack/plugins/graph/public/state_management/meta_data.ts @@ -53,7 +53,7 @@ export const syncBreadcrumbSaga = ({ chrome, changeUrl }: GraphStoreDependencies }, }); } - return function*() { + return function* () { // initial sync yield call(syncBreadcrumb); yield takeLatest(updateMetaData.match, syncBreadcrumb); diff --git a/x-pack/plugins/graph/public/state_management/mocks.ts b/x-pack/plugins/graph/public/state_management/mocks.ts index 02a5830ffd6be..5a0269d691de2 100644 --- a/x-pack/plugins/graph/public/state_management/mocks.ts +++ b/x-pack/plugins/graph/public/state_management/mocks.ts @@ -103,7 +103,7 @@ export function createMockGraphStore({ store.dispatch = jest.fn(store.dispatch); - sagas.forEach(sagaCreator => { + sagas.forEach((sagaCreator) => { sagaMiddleware.run(sagaCreator(mockedDeps)); }); diff --git a/x-pack/plugins/graph/public/state_management/persistence.test.ts b/x-pack/plugins/graph/public/state_management/persistence.test.ts index 285bf2d6a0ea9..efad5f95fd839 100644 --- a/x-pack/plugins/graph/public/state_management/persistence.test.ts +++ b/x-pack/plugins/graph/public/state_management/persistence.test.ts @@ -15,7 +15,7 @@ import { lookupIndexPattern, appStateToSavedWorkspace } from '../services/persis import { settingsSelector } from './advanced_settings'; import { openSaveModal } from '../services/save_modal'; -const waitForPromise = () => new Promise(r => setTimeout(r)); +const waitForPromise = () => new Promise((r) => setTimeout(r)); jest.mock('../services/persistence', () => ({ lookupIndexPattern: jest.fn(() => ({ id: '123', attributes: { title: 'test-pattern' } })), diff --git a/x-pack/plugins/graph/public/state_management/persistence.ts b/x-pack/plugins/graph/public/state_management/persistence.ts index 8dd1386f70e6e..cd2c6680c1fd2 100644 --- a/x-pack/plugins/graph/public/state_management/persistence.ts +++ b/x-pack/plugins/graph/public/state_management/persistence.ts @@ -87,7 +87,7 @@ export const loadingSaga = ({ getWorkspace()!.runLayout(); } - return function*() { + return function* () { yield takeLatest(loadSavedWorkspace.match, deserializeWorkspace); }; }; @@ -119,7 +119,7 @@ export const savingSaga = (deps: GraphStoreDependencies) => { } } - return function*() { + return function* () { yield takeLatest(saveWorkspace.match, persistWorkspace); }; }; diff --git a/x-pack/plugins/graph/public/state_management/url_templates.ts b/x-pack/plugins/graph/public/state_management/url_templates.ts index d9f95a498ea5b..19de52d444209 100644 --- a/x-pack/plugins/graph/public/state_management/url_templates.ts +++ b/x-pack/plugins/graph/public/state_management/url_templates.ts @@ -35,7 +35,7 @@ function generateDefaultTemplate( datasource: IndexpatternDatasource, addBasePath: (url: string) => string ): UrlTemplate { - const appPath = modifyUrl('/', parsed => { + const appPath = modifyUrl('/', (parsed) => { parsed.query._a = rison.encode({ columns: ['_source'], index: datasource.id, @@ -78,7 +78,7 @@ export const urlTemplatesReducer = (addBasePath: (url: string) => string) => if (datasource.type === 'none') { return initialTemplates; } - const customTemplates = templates.filter(template => !template.isDefault); + const customTemplates = templates.filter((template) => !template.isDefault); return [...customTemplates, generateDefaultTemplate(datasource, addBasePath)]; }) .case(loadTemplates, (_currentTemplates, newTemplates) => newTemplates) @@ -90,7 +90,7 @@ export const urlTemplatesReducer = (addBasePath: (url: string) => string) => : templates.map((template, index) => (index === indexToUpdate ? newTemplate : template)); }) .case(removeTemplate, (templates, templateToDelete) => - templates.filter(template => template !== templateToDelete) + templates.filter((template) => template !== templateToDelete) ) .build(); @@ -108,7 +108,7 @@ export const syncTemplatesSaga = ({ setUrlTemplates, notifyAngular }: GraphStore notifyAngular(); } - return function*() { + return function* () { yield takeEvery( matchesOne(loadTemplates, saveTemplate, removeTemplate, requestDatasource, setDatasource), syncTemplates diff --git a/x-pack/plugins/graph/public/state_management/workspace.ts b/x-pack/plugins/graph/public/state_management/workspace.ts index b18b8185ceeca..7c28d09c6424f 100644 --- a/x-pack/plugins/graph/public/state_management/workspace.ts +++ b/x-pack/plugins/graph/public/state_management/workspace.ts @@ -60,7 +60,7 @@ export const fillWorkspaceSaga = ({ } } - return function*() { + return function* () { yield takeLatest(fillWorkspace.match, fetchNodes); }; }; diff --git a/x-pack/plugins/graph/server/routes/explore.ts b/x-pack/plugins/graph/server/routes/explore.ts index ceced840bdbc6..cb4a6a3577915 100644 --- a/x-pack/plugins/graph/server/routes/explore.ts +++ b/x-pack/plugins/graph/server/routes/explore.ts @@ -57,7 +57,7 @@ export function registerExploreRoute({ error, 'body.error.root_cause', [] as Array<{ type: string; reason: string }> - ).find(cause => { + ).find((cause) => { return ( cause.reason.includes('Fielddata is disabled on text fields') || cause.reason.includes('No support for examining floating point') || diff --git a/x-pack/plugins/graph/server/sample_data/register_sample_data.ts b/x-pack/plugins/graph/server/sample_data/register_sample_data.ts index 9a05b656b61a4..d11f5ce7bb489 100644 --- a/x-pack/plugins/graph/server/sample_data/register_sample_data.ts +++ b/x-pack/plugins/graph/server/sample_data/register_sample_data.ts @@ -25,7 +25,7 @@ export function registerSampleData( throw new Error('License state has to be initialized before registering sample data'); } let registered = false; - licenseUpdates.subscribe(licenseInformation => { + licenseUpdates.subscribe((licenseInformation) => { if (!registered && licenseInformation.showAppLink) { registered = true; registerEcommerceSampleDataLink(sampleDataRegistry); diff --git a/x-pack/plugins/grokdebugger/public/components/grok_debugger/grok_debugger.js b/x-pack/plugins/grokdebugger/public/components/grok_debugger/grok_debugger.js index c27f3314e60ae..83be5520943b1 100644 --- a/x-pack/plugins/grokdebugger/public/components/grok_debugger/grok_debugger.js +++ b/x-pack/plugins/grokdebugger/public/components/grok_debugger/grok_debugger.js @@ -37,17 +37,17 @@ export class GrokDebuggerComponent extends React.Component { this.grokdebuggerRequest = new GrokdebuggerRequest(); } - onRawEventChange = rawEvent => { + onRawEventChange = (rawEvent) => { this.setState({ rawEvent }); this.grokdebuggerRequest.rawEvent = rawEvent.trimEnd(); }; - onPatternChange = pattern => { + onPatternChange = (pattern) => { this.setState({ pattern }); this.grokdebuggerRequest.pattern = pattern.trimEnd(); }; - onCustomPatternsChange = customPatterns => { + onCustomPatternsChange = (customPatterns) => { this.setState({ customPatterns }); customPatterns = customPatterns.trim(); @@ -58,7 +58,7 @@ export class GrokDebuggerComponent extends React.Component { return; } - customPatterns.split('\n').forEach(customPattern => { + customPatterns.split('\n').forEach((customPattern) => { // Patterns are defined like so: // patternName patternDefinition // For example: diff --git a/x-pack/plugins/grokdebugger/public/plugin.js b/x-pack/plugins/grokdebugger/public/plugin.js index 5f1534df9f0ae..6ac600c9dc97b 100644 --- a/x-pack/plugins/grokdebugger/public/plugin.js +++ b/x-pack/plugins/grokdebugger/public/plugin.js @@ -28,7 +28,7 @@ export class Plugin { }, }); - plugins.licensing.license$.subscribe(license => { + plugins.licensing.license$.subscribe((license) => { if (!license.isActive && !devTool.isDisabled()) { devTool.disable(); } else if (devTool.isDisabled()) { diff --git a/x-pack/plugins/grokdebugger/public/services/grokdebugger/grokdebugger_service.js b/x-pack/plugins/grokdebugger/public/services/grokdebugger/grokdebugger_service.js index e26c9c5091e14..207093e72ca2c 100644 --- a/x-pack/plugins/grokdebugger/public/services/grokdebugger/grokdebugger_service.js +++ b/x-pack/plugins/grokdebugger/public/services/grokdebugger/grokdebugger_service.js @@ -17,10 +17,10 @@ export class GrokdebuggerService { .post(`${ROUTES.API_ROOT}/simulate`, { body: JSON.stringify(grokdebuggerRequest.upstreamJSON), }) - .then(response => { + .then((response) => { return GrokdebuggerResponse.fromUpstreamJSON(response); }) - .catch(e => { + .catch((e) => { throw e.body.message; }); } diff --git a/x-pack/plugins/grokdebugger/server/plugin.js b/x-pack/plugins/grokdebugger/server/plugin.js index 06ddd92aefac9..49298fd1e5ab7 100644 --- a/x-pack/plugins/grokdebugger/server/plugin.js +++ b/x-pack/plugins/grokdebugger/server/plugin.js @@ -18,7 +18,7 @@ export class Plugin { setup(coreSetup, plugins) { const framework = new KibanaFramework(coreSetup); - plugins.licensing.license$.subscribe(license => { + plugins.licensing.license$.subscribe((license) => { framework.setLicense(license); }); diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/components/edit_policy.test.js b/x-pack/plugins/index_lifecycle_management/__jest__/components/edit_policy.test.js index bf4de823f1833..c249a45fe8ed2 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/components/edit_policy.test.js +++ b/x-pack/plugins/index_lifecycle_management/__jest__/components/edit_policy.test.js @@ -35,7 +35,7 @@ import { maximumDocumentsRequiredMessage, } from '../../public/application/store/selectors/lifecycle'; -initHttp(axios.create({ adapter: axiosXhrAdapter }), path => path); +initHttp(axios.create({ adapter: axiosXhrAdapter }), (path) => path); initUiMetric({ reportUiStats: () => {} }); initNotification({ addDanger: () => {}, @@ -59,9 +59,7 @@ const policies = []; for (let i = 0; i < 105; i++) { policies.push({ version: i, - modified_date: moment() - .subtract(i, 'days') - .valueOf(), + modified_date: moment().subtract(i, 'days').valueOf(), linkedIndices: i % 2 === 0 ? [`index${i}`] : null, name: `testy${i}`, policy: { @@ -80,7 +78,7 @@ const activatePhase = (rendered, phase) => { const expectedErrorMessages = (rendered, expectedErrorMessages) => { const errorMessages = rendered.find('.euiFormErrorText'); expect(errorMessages.length).toBe(expectedErrorMessages.length); - expectedErrorMessages.forEach(expectedErrorMessage => { + expectedErrorMessages.forEach((expectedErrorMessage) => { let foundErrorMessage; for (let i = 0; i < errorMessages.length; i++) { if (errorMessages.at(i).text() === expectedErrorMessage) { @@ -90,7 +88,7 @@ const expectedErrorMessages = (rendered, expectedErrorMessages) => { expect(foundErrorMessage).toBe(true); }); }; -const noRollover = rendered => { +const noRollover = (rendered) => { findTestSubject(rendered, 'rolloverSwitch').simulate('click'); rendered.update(); }; @@ -112,7 +110,7 @@ const setPhaseIndexPriority = (rendered, phase, priority) => { priorityInput.simulate('change', { target: { value: priority } }); rendered.update(); }; -const save = rendered => { +const save = (rendered) => { const saveButton = findTestSubject(rendered, 'savePolicyButton'); saveButton.simulate('click'); rendered.update(); diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/components/policy_table.test.js b/x-pack/plugins/index_lifecycle_management/__jest__/components/policy_table.test.js index 78c5c181eea62..52a9f28817e3a 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/components/policy_table.test.js +++ b/x-pack/plugins/index_lifecycle_management/__jest__/components/policy_table.test.js @@ -19,7 +19,7 @@ import { PolicyTable } from '../../public/application/sections/policy_table'; import { init as initHttp } from '../../public/application/services/http'; import { init as initUiMetric } from '../../public/application/services/ui_metric'; -initHttp(axios.create({ adapter: axiosXhrAdapter }), path => path); +initHttp(axios.create({ adapter: axiosXhrAdapter }), (path) => path); initUiMetric({ reportUiStats: () => {} }); let server = null; @@ -29,9 +29,7 @@ const policies = []; for (let i = 0; i < 105; i++) { policies.push({ version: i, - modified_date: moment() - .subtract(i, 'days') - .valueOf(), + modified_date: moment().subtract(i, 'days').valueOf(), linkedIndices: i % 2 === 0 ? [`index${i}`] : null, name: `testy${i}`, }); @@ -39,20 +37,20 @@ for (let i = 0; i < 105; i++) { jest.mock(''); let component = null; -const snapshot = rendered => { +const snapshot = (rendered) => { expect(rendered).toMatchSnapshot(); }; -const mountedSnapshot = rendered => { +const mountedSnapshot = (rendered) => { expect(takeMountedSnapshot(rendered)).toMatchSnapshot(); }; -const names = rendered => { +const names = (rendered) => { return findTestSubject(rendered, 'policyTablePolicyNameLink'); }; -const namesText = rendered => { - return names(rendered).map(button => button.text()); +const namesText = (rendered) => { + return names(rendered).map((button) => button.text()); }; -const testSort = headerName => { +const testSort = (headerName) => { const rendered = mountWithIntl(component); const nameHeader = findTestSubject(rendered, `policyTableHeaderCell-${headerName}`).find( 'button' @@ -64,7 +62,7 @@ const testSort = headerName => { rendered.update(); snapshot(namesText(rendered)); }; -const openContextMenu = buttonIndex => { +const openContextMenu = (buttonIndex) => { const rendered = mountWithIntl(component); const actionsButton = findTestSubject(rendered, 'policyActionsContextMenuButton'); actionsButton.at(buttonIndex).simulate('click'); diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/extend_index_management.test.js b/x-pack/plugins/index_lifecycle_management/__jest__/extend_index_management.test.js index 900de27ca36ab..b5d9b91e8c412 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/extend_index_management.test.js +++ b/x-pack/plugins/index_lifecycle_management/__jest__/extend_index_management.test.js @@ -23,7 +23,7 @@ import { init as initUiMetric } from '../public/application/services/ui_metric'; // We need to init the http with a mock for any tests that depend upon the http service. // For example, add_lifecycle_confirm_modal makes an API request in its componentDidMount // lifecycle method. If we don't mock this, CI will fail with "Call retries were exceeded". -initHttp(axios.create({ adapter: axiosXhrAdapter }), path => path); +initHttp(axios.create({ adapter: axiosXhrAdapter }), (path) => path); initUiMetric({ reportUiStats: () => {} }); jest.mock('../../../plugins/index_management/public', async () => { diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.container.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.container.js index 1f2468e79ebd3..d4605ceb43499 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.container.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.container.js @@ -12,7 +12,7 @@ import { PHASE_COLD, PHASE_HOT, PHASE_ROLLOVER_ENABLED } from '../../../../const import { ColdPhase as PresentationComponent } from './cold_phase'; export const ColdPhase = connect( - state => ({ + (state) => ({ phaseData: getPhase(state, PHASE_COLD), hotPhaseRolloverEnabled: getPhase(state, PHASE_HOT)[PHASE_ROLLOVER_ENABLED], }), diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.js index 02cd1a968b617..d5c0744e5eb07 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/cold_phase/cold_phase.js @@ -89,7 +89,7 @@ export class ColdPhase extends PureComponent { } id={`${PHASE_COLD}-${PHASE_ENABLED}`} checked={phaseData[PHASE_ENABLED]} - onChange={e => { + onChange={(e) => { setPhaseData(PHASE_ENABLED, e.target.checked); }} aria-controls="coldPhaseContent" @@ -146,7 +146,7 @@ export class ColdPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_REPLICA_COUNT, e.target.value); }} min={0} @@ -187,7 +187,7 @@ export class ColdPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_FREEZE_ENABLED, e.target.checked); }} label={freezeLabel} diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.container.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.container.js index 74ec9b2c98ed9..84bd17e3637e8 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.container.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.container.js @@ -11,7 +11,7 @@ import { PHASE_DELETE, PHASE_HOT, PHASE_ROLLOVER_ENABLED } from '../../../../con import { DeletePhase as PresentationComponent } from './delete_phase'; export const DeletePhase = connect( - state => ({ + (state) => ({ phaseData: getPhase(state, PHASE_DELETE), hotPhaseRolloverEnabled: getPhase(state, PHASE_HOT)[PHASE_ROLLOVER_ENABLED], }), diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.js index 146b5c36847db..3b3e489d38f7d 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/delete_phase/delete_phase.js @@ -63,7 +63,7 @@ export class DeletePhase extends PureComponent { } id={`${PHASE_DELETE}-${PHASE_ENABLED}`} checked={phaseData[PHASE_ENABLED]} - onChange={e => { + onChange={(e) => { setPhaseData(PHASE_ENABLED, e.target.checked); }} aria-controls="deletePhaseContent" diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.container.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.container.js index 818af79466f6b..5f1451afdcc31 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.container.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.container.js @@ -12,11 +12,11 @@ import { PHASE_HOT, PHASE_WARM, WARM_PHASE_ON_ROLLOVER } from '../../../../const import { HotPhase as PresentationComponent } from './hot_phase'; export const HotPhase = connect( - state => ({ + (state) => ({ phaseData: getPhase(state, PHASE_HOT), }), { setPhaseData: (key, value) => setPhaseData(PHASE_HOT, key, value), - setWarmPhaseOnRollover: value => setPhaseData(PHASE_WARM, WARM_PHASE_ON_ROLLOVER, value), + setWarmPhaseOnRollover: (value) => setPhaseData(PHASE_WARM, WARM_PHASE_ON_ROLLOVER, value), } )(PresentationComponent); diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.js index 475d26bb2e3c0..b420442198712 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/hot_phase/hot_phase.js @@ -100,7 +100,7 @@ export class HotPhase extends PureComponent { { + onChange={async (e) => { const { checked } = e.target; setPhaseData(PHASE_ROLLOVER_ENABLED, checked); setWarmPhaseOnRollover(checked); @@ -130,7 +130,7 @@ export class HotPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_ROLLOVER_MAX_SIZE_STORED, e.target.value); }} min={1} @@ -153,7 +153,7 @@ export class HotPhase extends PureComponent { } )} value={phaseData[PHASE_ROLLOVER_MAX_SIZE_STORED_UNITS]} - onChange={e => { + onChange={(e) => { setPhaseData(PHASE_ROLLOVER_MAX_SIZE_STORED_UNITS, e.target.value); }} options={[ @@ -216,7 +216,7 @@ export class HotPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_ROLLOVER_MAX_DOCUMENTS, e.target.value); }} min={1} @@ -239,7 +239,7 @@ export class HotPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_ROLLOVER_MAX_AGE, e.target.value); }} min={1} @@ -262,7 +262,7 @@ export class HotPhase extends PureComponent { } )} value={phaseData[PHASE_ROLLOVER_MAX_AGE_UNITS]} - onChange={e => { + onChange={(e) => { setPhaseData(PHASE_ROLLOVER_MAX_AGE_UNITS, e.target.value); }} options={[ diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/min_age_input.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/min_age_input.js index 2300979851329..bfe1bbb04338c 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/min_age_input.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/min_age_input.js @@ -68,7 +68,7 @@ function getUnitsAriaLabelForPhase(phase) { } } -export const MinAgeInput = props => { +export const MinAgeInput = (props) => { const { rolloverEnabled, errors, phaseData, phase, setPhaseData, isShowingErrors } = props; let daysOptionLabel; @@ -166,7 +166,7 @@ export const MinAgeInput = props => { { + onChange={async (e) => { setPhaseData(PHASE_ROLLOVER_MINIMUM_AGE, e.target.value); }} min={0} @@ -178,7 +178,7 @@ export const MinAgeInput = props => { setPhaseData(PHASE_ROLLOVER_MINIMUM_AGE_UNITS, e.target.value)} + onChange={(e) => setPhaseData(PHASE_ROLLOVER_MINIMUM_AGE_UNITS, e.target.value)} options={[ { value: 'd', diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.container.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.container.js index a92959a5b31cf..0ddfcbb940aa4 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.container.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.container.js @@ -11,7 +11,7 @@ import { fetchNodes } from '../../../../store/actions'; import { NodeAllocation as PresentationComponent } from './node_allocation'; export const NodeAllocation = connect( - state => ({ + (state) => ({ nodeOptions: getNodeOptions(state), }), { diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.js index 528aa85beaecc..95c1878776688 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/node_allocation/node_allocation.js @@ -92,7 +92,7 @@ export class NodeAllocation extends Component { id={`${phase}-${PHASE_NODE_ATTRS}`} value={phaseData[PHASE_NODE_ATTRS] || ' '} options={nodeOptions} - onChange={e => { + onChange={(e) => { setPhaseData(PHASE_NODE_ATTRS, e.target.value); }} /> diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/set_priority_input.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/set_priority_input.js index 09db792b689da..bdcc1e23b4230 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/set_priority_input.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/set_priority_input.js @@ -11,7 +11,7 @@ import { PHASE_INDEX_PRIORITY } from '../../../constants'; import { LearnMoreLink, OptionalLabel } from '../../components'; import { ErrableFormRow } from '../form_errors'; -export const SetPriorityInput = props => { +export const SetPriorityInput = (props) => { const { errors, phaseData, phase, setPhaseData, isShowingErrors } = props; return ( @@ -55,7 +55,7 @@ export const SetPriorityInput = props => { { + onChange={(e) => { setPhaseData(PHASE_INDEX_PRIORITY, e.target.value); }} min={0} diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.container.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.container.js index e25360b94e029..d13ad31228860 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.container.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.container.js @@ -12,7 +12,7 @@ import { PHASE_WARM, PHASE_HOT, PHASE_ROLLOVER_ENABLED } from '../../../../const import { WarmPhase as PresentationComponent } from './warm_phase'; export const WarmPhase = connect( - state => ({ + (state) => ({ phaseData: getPhase(state, PHASE_WARM), hotPhaseRolloverEnabled: getPhase(state, PHASE_HOT)[PHASE_ROLLOVER_ENABLED], }), diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.js index 133e6b617c71e..55aec88c8bcab 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/warm_phase/warm_phase.js @@ -108,7 +108,7 @@ export class WarmPhase extends PureComponent { } id={`${PHASE_WARM}-${PHASE_ENABLED}`} checked={phaseData[PHASE_ENABLED]} - onChange={e => { + onChange={(e) => { setPhaseData(PHASE_ENABLED, e.target.checked); }} aria-controls="warmPhaseContent" @@ -127,7 +127,7 @@ export class WarmPhase extends PureComponent { label={moveToWarmPhaseOnRolloverLabel} id={`${PHASE_WARM}-${WARM_PHASE_ON_ROLLOVER}`} checked={phaseData[WARM_PHASE_ON_ROLLOVER]} - onChange={e => { + onChange={(e) => { setPhaseData(WARM_PHASE_ON_ROLLOVER, e.target.checked); }} /> @@ -184,7 +184,7 @@ export class WarmPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_REPLICA_COUNT, e.target.value); }} min={0} @@ -225,7 +225,7 @@ export class WarmPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_SHRINK_ENABLED, e.target.checked); }} label={shrinkLabel} @@ -254,7 +254,7 @@ export class WarmPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_PRIMARY_SHARD_COUNT, e.target.value); }} min={1} @@ -294,7 +294,7 @@ export class WarmPhase extends PureComponent { label={forcemergeLabel} aria-label={forcemergeLabel} checked={phaseData[PHASE_FORCE_MERGE_ENABLED]} - onChange={e => { + onChange={(e) => { setPhaseData(PHASE_FORCE_MERGE_ENABLED, e.target.checked); }} aria-controls="forcemergeContent" @@ -318,7 +318,7 @@ export class WarmPhase extends PureComponent { { + onChange={(e) => { setPhaseData(PHASE_FORCE_MERGE_SEGMENTS, e.target.value); }} min={1} diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.container.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.container.js index 3e4ec06fa43e7..1c6ced8953211 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.container.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.container.js @@ -29,7 +29,7 @@ import { findFirstError } from '../../services/find_errors'; import { EditPolicy as PresentationComponent } from './edit_policy'; export const EditPolicy = connect( - state => { + (state) => { const errors = validateLifecycle(state); const firstError = findFirstError(errors); return { diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.js index 040ce189ba2e6..94186b7fc79d7 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/edit_policy.js @@ -63,10 +63,10 @@ export class EditPolicy extends Component { }; } - selectPolicy = policyName => { + selectPolicy = (policyName) => { const { setSelectedPolicy, policies } = this.props; - const selectedPolicy = policies.find(policy => { + const selectedPolicy = policies.find((policy) => { return policy.name === policyName; }); @@ -125,7 +125,7 @@ export class EditPolicy extends Component { } }; - showNodeDetailsFlyout = selectedNodeAttrsForDetails => { + showNodeDetailsFlyout = (selectedNodeAttrsForDetails) => { this.setState({ isShowingNodeDetailsFlyout: true, selectedNodeAttrsForDetails }); }; @@ -222,7 +222,7 @@ export class EditPolicy extends Component { data-test-subj="saveAsNewSwitch" style={{ maxWidth: '100%' }} checked={saveAsNewPolicy} - onChange={async e => { + onChange={async (e) => { await setSaveAsNewPolicy(e.target.checked); }} label={ @@ -271,7 +271,7 @@ export class EditPolicy extends Component { { + onChange={async (e) => { await setSelectedPolicyName(e.target.value); }} /> diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form_errors.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form_errors.js index 4b50e19f9baaa..28ebad209ad96 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form_errors.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form_errors.js @@ -15,7 +15,7 @@ export const ErrableFormRow = ({ errorKey, isShowingErrors, errors, children, .. {...rest} > - {Children.map(children, child => + {Children.map(children, (child) => cloneElement(child, { isInvalid: isShowingErrors && errors[errorKey].length > 0, }) diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/add_policy_to_template_confirm_modal.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/add_policy_to_template_confirm_modal.js index 6129678edf3b7..8e53569047d8f 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/add_policy_to_template_confirm_modal.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/add_policy_to_template_confirm_modal.js @@ -108,7 +108,7 @@ export class AddPolicyToTemplateConfirmModal extends Component { } getSelectedTemplate() { const { templates, templateName } = this.state; - return find(templates, template => template.name === templateName); + return find(templates, (template) => template.name === templateName); } renderForm() { const { templates, templateName, templateError } = this.state; @@ -143,7 +143,7 @@ export class AddPolicyToTemplateConfirmModal extends Component { { + onChange={(e) => { this.setState({ templateError: null, templateName: e.target.value }); }} /> @@ -170,7 +170,7 @@ export class AddPolicyToTemplateConfirmModal extends Component { > { + onChange={(e) => { this.setState({ aliasName: e.target.value }); }} /> diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.container.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.container.js index 7db980abeba8a..8bd78774d2d55 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.container.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.container.js @@ -25,28 +25,28 @@ import { import { PolicyTable as PresentationComponent } from './policy_table'; -const mapDispatchToProps = dispatch => { +const mapDispatchToProps = (dispatch) => { return { - policyFilterChanged: filter => { + policyFilterChanged: (filter) => { dispatch(policyFilterChanged({ filter })); }, - policyPageChanged: pageNumber => { + policyPageChanged: (pageNumber) => { dispatch(policyPageChanged({ pageNumber })); }, - policyPageSizeChanged: pageSize => { + policyPageSizeChanged: (pageSize) => { dispatch(policyPageSizeChanged({ pageSize })); }, policySortChanged: (sortField, isSortAscending) => { dispatch(policySortChanged({ sortField, isSortAscending })); }, - fetchPolicies: withIndices => { + fetchPolicies: (withIndices) => { dispatch(fetchPolicies(withIndices)); }, }; }; export const PolicyTable = connect( - state => ({ + (state) => ({ totalNumberOfPolicies: getPolicies(state).length, policies: getPageOfPolicies(state), pager: getPolicyPager(state), diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.js index d406d86bc6ce7..d9d74becf9e5d 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/policy_table/components/policy_table/policy_table.js @@ -141,7 +141,7 @@ export class PolicyTable extends Component { this.props.fetchPolicies(true); this.setState({ renderDeleteConfirmModal: null, policyToDelete: null }); }; - onSort = column => { + onSort = (column) => { const { sortField, isSortAscending, policySortChanged } = this.props; const newIsSortAscending = sortField === column ? !isSortAscending : true; policySortChanged(column, newIsSortAscending); @@ -286,22 +286,22 @@ export class PolicyTable extends Component { }; return flattenPanelTree(panelTree); } - togglePolicyPopover = policy => { + togglePolicyPopover = (policy) => { if (this.isPolicyPopoverOpen(policy)) { this.closePolicyPopover(policy); } else { this.openPolicyPopover(policy); } }; - isPolicyPopoverOpen = policy => { + isPolicyPopoverOpen = (policy) => { return this.state.policyPopover === policy.name; }; - closePolicyPopover = policy => { + closePolicyPopover = (policy) => { if (this.isPolicyPopoverOpen(policy)) { this.setState({ policyPopover: null }); } }; - openPolicyPopover = policy => { + openPolicyPopover = (policy) => { this.setState({ policyPopover: policy.name }); }; buildRowCells(policy) { @@ -374,7 +374,7 @@ export class PolicyTable extends Component { buildRows() { const { policies = [] } = this.props; - return policies.map(policy => { + return policies.map((policy) => { const { name } = policy; return {this.buildRowCells(policy)}; }); @@ -394,7 +394,7 @@ export class PolicyTable extends Component { ); } - onItemSelectionChanged = selectedPolicies => { + onItemSelectionChanged = (selectedPolicies) => { this.setState({ selectedPolicies }); }; @@ -455,7 +455,7 @@ export class PolicyTable extends Component { { + onChange={(event) => { policyFilterChanged(event.target.value); }} data-test-subj="policyTableFilterInput" diff --git a/x-pack/plugins/index_lifecycle_management/public/application/services/api.js b/x-pack/plugins/index_lifecycle_management/public/application/services/api.js index 1cb2089ab66db..386df63111a89 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/services/api.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/services/api.js @@ -43,28 +43,28 @@ export async function deletePolicy(policyName) { return response; } -export const retryLifecycleForIndex = async indexNames => { +export const retryLifecycleForIndex = async (indexNames) => { const response = await sendPost(`index/retry`, { indexNames }); // Only track successful actions. trackUiMetric('count', UIM_INDEX_RETRY_STEP); return response; }; -export const removeLifecycleForIndex = async indexNames => { +export const removeLifecycleForIndex = async (indexNames) => { const response = await sendPost(`index/remove`, { indexNames }); // Only track successful actions. trackUiMetric('count', UIM_POLICY_DETACH_INDEX); return response; }; -export const addLifecyclePolicyToIndex = async body => { +export const addLifecyclePolicyToIndex = async (body) => { const response = await sendPost(`index/add`, body); // Only track successful actions. trackUiMetric('count', UIM_POLICY_ATTACH_INDEX); return response; }; -export const addLifecyclePolicyToTemplate = async body => { +export const addLifecyclePolicyToTemplate = async (body) => { const response = await sendPost(`template`, body); // Only track successful actions. trackUiMetric('count', UIM_POLICY_ATTACH_INDEX_TEMPLATE); diff --git a/x-pack/plugins/index_lifecycle_management/public/application/services/filter_items.js b/x-pack/plugins/index_lifecycle_management/public/application/services/filter_items.js index 6d2e3dae57f46..dcc9036463b82 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/services/filter_items.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/services/filter_items.js @@ -6,9 +6,9 @@ export const filterItems = (fields, filter = '', items = []) => { const lowerFilter = filter.toLowerCase(); - return items.filter(item => { + return items.filter((item) => { const actualFields = fields || Object.keys(item); - const indexOfMatch = actualFields.findIndex(field => { + const indexOfMatch = actualFields.findIndex((field) => { const normalizedField = String(item[field]).toLowerCase(); return normalizedField.includes(lowerFilter); }); diff --git a/x-pack/plugins/index_lifecycle_management/public/application/services/flatten_panel_tree.js b/x-pack/plugins/index_lifecycle_management/public/application/services/flatten_panel_tree.js index e060e22965cb3..2bb3903a6ef45 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/services/flatten_panel_tree.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/services/flatten_panel_tree.js @@ -8,7 +8,7 @@ export const flattenPanelTree = (tree, array = []) => { array.push(tree); if (tree.items) { - tree.items.forEach(item => { + tree.items.forEach((item) => { if (item.panel) { flattenPanelTree(item.panel, array); item.panel = item.panel.id; diff --git a/x-pack/plugins/index_lifecycle_management/public/application/services/sort_table.js b/x-pack/plugins/index_lifecycle_management/public/application/services/sort_table.js index 8e9896dac0b07..1b1446bb735c1 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/services/sort_table.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/services/sort_table.js @@ -6,8 +6,8 @@ import { sortBy } from 'lodash'; -const stringSort = fieldName => item => item[fieldName]; -const arraySort = fieldName => item => (item[fieldName] || []).length; +const stringSort = (fieldName) => (item) => item[fieldName]; +const arraySort = (fieldName) => (item) => (item[fieldName] || []).length; const sorters = { version: stringSort('version'), diff --git a/x-pack/plugins/index_lifecycle_management/public/application/services/ui_metric.ts b/x-pack/plugins/index_lifecycle_management/public/application/services/ui_metric.ts index ca987441c7ce9..d71e38d0b31de 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/services/ui_metric.ts +++ b/x-pack/plugins/index_lifecycle_management/public/application/services/ui_metric.ts @@ -51,7 +51,7 @@ export function getUiMetricsForPhases(phases: any): any { }; // We only care about whether the user has interacted with the priority of *any* phase at all. - return [PHASE_HOT, PHASE_WARM, PHASE_COLD].some(phase => { + return [PHASE_HOT, PHASE_WARM, PHASE_COLD].some((phase) => { // If the priority is different than the default, we'll consider it a user interaction, // even if the user has set it to undefined. return ( diff --git a/x-pack/plugins/index_lifecycle_management/public/application/store/actions/nodes.js b/x-pack/plugins/index_lifecycle_management/public/application/store/actions/nodes.js index b665a847851b3..f2520abc7a441 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/store/actions/nodes.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/store/actions/nodes.js @@ -14,7 +14,7 @@ export const setSelectedPrimaryShardCount = createAction('SET_SELECTED_PRIMARY_S export const setSelectedReplicaCount = createAction('SET_SELECTED_REPLICA_COUNT'); export const fetchedNodes = createAction('FETCHED_NODES'); let fetchingNodes = false; -export const fetchNodes = () => async dispatch => { +export const fetchNodes = () => async (dispatch) => { try { if (!fetchingNodes) { fetchingNodes = true; @@ -38,7 +38,7 @@ export const fetchedNodeDetails = createAction( details, }) ); -export const fetchNodeDetails = selectedNodeAttrs => async dispatch => { +export const fetchNodeDetails = (selectedNodeAttrs) => async (dispatch) => { let details; try { details = await loadNodeDetails(selectedNodeAttrs); diff --git a/x-pack/plugins/index_lifecycle_management/public/application/store/actions/policies.js b/x-pack/plugins/index_lifecycle_management/public/application/store/actions/policies.js index b6064af6e38b2..aa20c0eb1d326 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/store/actions/policies.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/store/actions/policies.js @@ -22,7 +22,7 @@ export const policyPageChanged = createAction('POLICY_PAGE_CHANGED'); export const policySortDirectionChanged = createAction('POLICY_SORT_DIRECTION_CHANGED'); export const policyFilterChanged = createAction('POLICY_FILTER_CHANGED'); -export const fetchPolicies = (withIndices, callback) => async dispatch => { +export const fetchPolicies = (withIndices, callback) => async (dispatch) => { let policies; try { policies = await loadPolicies(withIndices); diff --git a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/general.js b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/general.js index d0f0973ad81f2..2d01749be3087 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/general.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/general.js @@ -4,6 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -export const getBootstrapEnabled = state => state.general.bootstrapEnabled; -export const getIndexName = state => state.general.indexName; -export const getAliasName = state => state.general.aliasName; +export const getBootstrapEnabled = (state) => state.general.bootstrapEnabled; +export const getIndexName = (state) => state.general.indexName; +export const getAliasName = (state) => state.general.aliasName; diff --git a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/lifecycle.js b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/lifecycle.js index 750a7feb19c3d..789de0f528b1b 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/lifecycle.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/lifecycle.js @@ -209,7 +209,7 @@ export const policyNameAlreadyUsedErrorMessage = i18n.translate( defaultMessage: 'That policy name is already used.', } ); -export const validateLifecycle = state => { +export const validateLifecycle = (state) => { // This method of deep copy does not always work but it should be fine here const errors = JSON.parse(JSON.stringify(ERROR_STRUCTURE)); const policyName = getSelectedPolicyName(state); @@ -236,7 +236,7 @@ export const validateLifecycle = state => { ) { errors[STRUCTURE_POLICY_NAME].push(policyNameMustBeDifferentErrorMessage); } else if (getSelectedOriginalPolicyName(state) !== getSelectedPolicyName(state)) { - const policyNames = getPolicies(state).map(policy => policy.name); + const policyNames = getPolicies(state).map((policy) => policy.name); if (policyNames.includes(getSelectedPolicyName(state))) { errors[STRUCTURE_POLICY_NAME].push(policyNameAlreadyUsedErrorMessage); } @@ -254,7 +254,7 @@ export const validateLifecycle = state => { return errors; }; -export const getLifecycle = state => { +export const getLifecycle = (state) => { const policyName = getSelectedPolicyName(state); const phases = Object.entries(getPhases(state)).reduce((accum, [phaseName, phase]) => { // Hot is ALWAYS enabled diff --git a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/nodes.js b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/nodes.js index a92b7154a51fd..63d849217f59e 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/nodes.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/nodes.js @@ -6,14 +6,14 @@ import { createSelector } from 'reselect'; -export const getNodes = state => state.nodes.nodes; +export const getNodes = (state) => state.nodes.nodes; -export const getNodeOptions = createSelector([state => getNodes(state)], nodes => { +export const getNodeOptions = createSelector([(state) => getNodes(state)], (nodes) => { if (!nodes) { return null; } - const options = Object.keys(nodes).map(attrs => ({ + const options = Object.keys(nodes).map((attrs) => ({ text: `${attrs} (${nodes[attrs].length})`, value: attrs, })); @@ -26,14 +26,14 @@ export const getNodeOptions = createSelector([state => getNodes(state)], nodes = } }); -export const getSelectedPrimaryShardCount = state => state.nodes.selectedPrimaryShardCount; +export const getSelectedPrimaryShardCount = (state) => state.nodes.selectedPrimaryShardCount; -export const getSelectedReplicaCount = state => +export const getSelectedReplicaCount = (state) => state.nodes.selectedReplicaCount !== undefined ? state.nodes.selectedReplicaCount : 1; -export const getSelectedNodeAttrs = state => state.nodes.selectedNodeAttrs; +export const getSelectedNodeAttrs = (state) => state.nodes.selectedNodeAttrs; -export const getNodesFromSelectedNodeAttrs = state => { +export const getNodesFromSelectedNodeAttrs = (state) => { const nodes = getNodes(state)[getSelectedNodeAttrs(state)]; if (nodes) { return nodes.length; diff --git a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/policies.js b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/policies.js index 591a1cb3d3699..a3aef8679817d 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/policies.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/store/selectors/policies.js @@ -42,23 +42,23 @@ import { defaultEmptyHotPhase, } from '../defaults'; -export const getPolicies = state => state.policies.policies; +export const getPolicies = (state) => state.policies.policies; export const getPolicyByName = (state, name) => - getPolicies(state).find(policy => policy.name === name) || {}; -export const getIsNewPolicy = state => state.policies.selectedPolicy.isNew; -export const getSelectedPolicy = state => state.policies.selectedPolicy; -export const getIsSelectedPolicySet = state => state.policies.selectedPolicySet; -export const getSelectedOriginalPolicyName = state => state.policies.originalPolicyName; -export const getPolicyFilter = state => state.policies.filter; -export const getPolicySort = state => state.policies.sort; -export const getPolicyCurrentPage = state => state.policies.currentPage; -export const getPolicyPageSize = state => state.policies.pageSize; -export const isPolicyListLoaded = state => state.policies.isLoaded; + getPolicies(state).find((policy) => policy.name === name) || {}; +export const getIsNewPolicy = (state) => state.policies.selectedPolicy.isNew; +export const getSelectedPolicy = (state) => state.policies.selectedPolicy; +export const getIsSelectedPolicySet = (state) => state.policies.selectedPolicySet; +export const getSelectedOriginalPolicyName = (state) => state.policies.originalPolicyName; +export const getPolicyFilter = (state) => state.policies.filter; +export const getPolicySort = (state) => state.policies.sort; +export const getPolicyCurrentPage = (state) => state.policies.currentPage; +export const getPolicyPageSize = (state) => state.policies.pageSize; +export const isPolicyListLoaded = (state) => state.policies.isLoaded; const getFilteredPolicies = createSelector(getPolicies, getPolicyFilter, (policies, filter) => { return filterItems(['name'], filter, policies); }); -export const getTotalPolicies = createSelector(getFilteredPolicies, filteredPolicies => { +export const getTotalPolicies = createSelector(getFilteredPolicies, (filteredPolicies) => { return filteredPolicies.length; }); export const getPolicyPager = createSelector( @@ -80,16 +80,16 @@ export const getPageOfPolicies = createSelector( return pagedPolicies; } ); -export const getSaveAsNewPolicy = state => state.policies.selectedPolicy.saveAsNew; +export const getSaveAsNewPolicy = (state) => state.policies.selectedPolicy.saveAsNew; -export const getSelectedPolicyName = state => { +export const getSelectedPolicyName = (state) => { if (!getSaveAsNewPolicy(state)) { return getSelectedOriginalPolicyName(state); } return state.policies.selectedPolicy.name; }; -export const getPhases = state => state.policies.selectedPolicy.phases; +export const getPhases = (state) => state.policies.selectedPolicy.phases; export const getPhase = (state, phase) => getPhases(state)[phase]; @@ -100,7 +100,7 @@ export const getPhaseData = (state, phase, key) => { return getPhase(state, phase)[key]; }; -export const splitSizeAndUnits = field => { +export const splitSizeAndUnits = (field) => { let size; let units; @@ -116,8 +116,8 @@ export const splitSizeAndUnits = field => { }; }; -export const isNumber = value => typeof value === 'number'; -export const isEmptyObject = obj => { +export const isNumber = (value) => typeof value === 'number'; +export const isEmptyObject = (obj) => { return !obj || (Object.entries(obj).length === 0 && obj.constructor === Object); }; @@ -166,7 +166,7 @@ const phaseFromES = (phase, phaseName, defaultEmptyPolicy) => { if (actions.allocate) { const allocate = actions.allocate; if (allocate.require) { - Object.entries(allocate.require).forEach(entry => { + Object.entries(allocate.require).forEach((entry) => { policy[PHASE_NODE_ATTRS] = entry.join(':'); }); // checking for null or undefined here @@ -198,7 +198,7 @@ const phaseFromES = (phase, phaseName, defaultEmptyPolicy) => { return policy; }; -export const policyFromES = policy => { +export const policyFromES = (policy) => { const { name, policy: { phases }, diff --git a/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/add_lifecycle_confirm_modal.js b/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/add_lifecycle_confirm_modal.js index 143895150172d..110998a7e9354 100644 --- a/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/add_lifecycle_confirm_modal.js +++ b/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/add_lifecycle_confirm_modal.js @@ -82,7 +82,7 @@ export class AddLifecyclePolicyConfirmModal extends Component { ); } }; - renderAliasFormElement = selectedPolicy => { + renderAliasFormElement = (selectedPolicy) => { const { selectedAlias } = this.state; const { index } = this.props; const showAliasSelect = @@ -118,7 +118,7 @@ export class AddLifecyclePolicyConfirmModal extends Component { ); } - const aliasOptions = aliases.map(alias => { + const aliasOptions = aliases.map((alias) => { return { text: alias, value: alias, @@ -145,7 +145,7 @@ export class AddLifecyclePolicyConfirmModal extends Component { { + onChange={(e) => { this.setState({ selectedAlias: e.target.value }); }} /> @@ -155,7 +155,7 @@ export class AddLifecyclePolicyConfirmModal extends Component { renderForm() { const { policies, selectedPolicyName, policyError } = this.state; const selectedPolicy = selectedPolicyName - ? policies.find(policy => policy.name === selectedPolicyName) + ? policies.find((policy) => policy.name === selectedPolicyName) : null; const options = policies.map(({ name }) => { @@ -188,7 +188,7 @@ export class AddLifecyclePolicyConfirmModal extends Component { { + onChange={(e) => { this.setState({ policyError: null, selectedPolicyName: e.target.value }); }} /> diff --git a/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/remove_lifecycle_confirm_modal.js b/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/remove_lifecycle_confirm_modal.js index 4e0d2383c7d79..048ed44bd58b2 100644 --- a/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/remove_lifecycle_confirm_modal.js +++ b/x-pack/plugins/index_lifecycle_management/public/extend_index_management/components/remove_lifecycle_confirm_modal.js @@ -100,7 +100,7 @@ export class RemoveLifecyclePolicyConfirmModal extends Component {

    - {indexNames.map(indexName => ( + {indexNames.map((indexName) => (
  • {indexName}
  • ))}
diff --git a/x-pack/plugins/index_lifecycle_management/public/extend_index_management/index.js b/x-pack/plugins/index_lifecycle_management/public/extend_index_management/index.js index 40ff04408002f..43f8332f4b6bd 100644 --- a/x-pack/plugins/index_lifecycle_management/public/extend_index_management/index.js +++ b/x-pack/plugins/index_lifecycle_management/public/extend_index_management/index.js @@ -17,7 +17,7 @@ import { RemoveLifecyclePolicyConfirmModal } from './components/remove_lifecycle const stepPath = 'ilm.step'; export const retryLifecycleActionExtension = ({ indices }) => { - const allHaveErrors = every(indices, index => { + const allHaveErrors = every(indices, (index) => { return index.ilm && index.ilm.failed_step; }); if (!allHaveErrors) { @@ -35,14 +35,14 @@ export const retryLifecycleActionExtension = ({ indices }) => { 'xpack.indexLifecycleMgmt.retryIndexLifecycleAction.retriedLifecycleMessage', { defaultMessage: 'Called retry lifecycle step for: {indexNames}', - values: { indexNames: indexNames.map(indexName => `"${indexName}"`).join(', ') }, + values: { indexNames: indexNames.map((indexName) => `"${indexName}"`).join(', ') }, } ), }; }; export const removeLifecyclePolicyActionExtension = ({ indices, reloadIndices }) => { - const allHaveIlm = every(indices, index => { + const allHaveIlm = every(indices, (index) => { return index.ilm && index.ilm.managed; }); if (!allHaveIlm) { @@ -50,7 +50,7 @@ export const removeLifecyclePolicyActionExtension = ({ indices, reloadIndices }) } const indexNames = indices.map(({ name }) => name); return { - renderConfirmModal: closeModal => { + renderConfirmModal: (closeModal) => { return ( } const indexName = index.name; return { - renderConfirmModal: closeModal => { + renderConfirmModal: (closeModal) => { return ( }; }; -export const ilmBannerExtension = indices => { +export const ilmBannerExtension = (indices) => { const { Query } = EuiSearchBar; if (!indices.length) { return null; } - const indicesWithLifecycleErrors = indices.filter(index => { + const indicesWithLifecycleErrors = indices.filter((index) => { return get(index, stepPath) === 'ERROR'; }); const numIndicesWithLifecycleErrors = indicesWithLifecycleErrors.length; @@ -123,12 +123,12 @@ export const ilmBannerExtension = indices => { }; }; -export const ilmSummaryExtension = index => { +export const ilmSummaryExtension = (index) => { return ; }; -export const ilmFilterExtension = indices => { - const hasIlm = any(indices, index => index.ilm && index.ilm.managed); +export const ilmFilterExtension = (indices) => { + const hasIlm = any(indices, (index) => index.ilm && index.ilm.managed); if (!hasIlm) { return []; } else { @@ -193,7 +193,7 @@ export const ilmFilterExtension = indices => { } }; -export const addAllExtensions = extensionsService => { +export const addAllExtensions = (extensionsService) => { extensionsService.addAction(retryLifecycleActionExtension); extensionsService.addAction(removeLifecyclePolicyActionExtension); extensionsService.addAction(addLifecyclePolicyActionExtension); diff --git a/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_fetch_route.ts b/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_fetch_route.ts index a2dc67cb77afe..865d4f488e926 100644 --- a/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_fetch_route.ts +++ b/x-pack/plugins/index_lifecycle_management/server/routes/api/templates/register_fetch_route.ts @@ -21,7 +21,7 @@ function isReservedSystemTemplate(templateName: string, indexPatterns: string[]) return ( templateName.startsWith('kibana_index_template') || (templateName.startsWith('.') && - indexPatterns.every(pattern => { + indexPatterns.every((pattern) => { return !pattern.includes('*'); })) ); diff --git a/x-pack/plugins/index_lifecycle_management/server/services/license.ts b/x-pack/plugins/index_lifecycle_management/server/services/license.ts index 31d3654c51e3e..2d863e283d440 100644 --- a/x-pack/plugins/index_lifecycle_management/server/services/license.ts +++ b/x-pack/plugins/index_lifecycle_management/server/services/license.ts @@ -35,7 +35,7 @@ export class License { { pluginId, minimumLicenseType, defaultErrorMessage }: SetupSettings, { licensing, logger }: { licensing: LicensingPluginSetup; logger: Logger } ) { - licensing.license$.subscribe(license => { + licensing.license$.subscribe((license) => { const { state, message } = license.check(pluginId, minimumLicenseType); const hasRequiredLicense = state === 'valid'; diff --git a/x-pack/plugins/index_management/__jest__/client_integration/helpers/home.helpers.ts b/x-pack/plugins/index_management/__jest__/client_integration/helpers/home.helpers.ts index a323fdf714d8d..57b925b8c6fc1 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/helpers/home.helpers.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/helpers/home.helpers.ts @@ -73,10 +73,7 @@ export const setup = async (): Promise => { const selectDetailsTab = (tab: 'summary' | 'settings' | 'mappings' | 'aliases') => { const tabs = ['summary', 'settings', 'mappings', 'aliases']; - testBed - .find('templateDetails.tab') - .at(tabs.indexOf(tab)) - .simulate('click'); + testBed.find('templateDetails.tab').at(tabs.indexOf(tab)).simulate('click'); }; const clickReloadButton = () => { @@ -101,10 +98,7 @@ export const setup = async (): Promise => { clickActionMenu(templateName); - component - .find('.euiContextMenuItem') - .at(actions.indexOf(action)) - .simulate('click'); + component.find('.euiContextMenuItem').at(actions.indexOf(action)).simulate('click'); }; const clickTemplateAt = async (index: number) => { @@ -143,9 +137,7 @@ export const setup = async (): Promise => { const indexDetailsTabs = ['settings', 'mappings', 'stats', 'edit_settings']; const { find, component } = testBed; await act(async () => { - find('detailPanelTab') - .at(indexDetailsTabs.indexOf(tab)) - .simulate('click'); + find('detailPanelTab').at(indexDetailsTabs.indexOf(tab)).simulate('click'); }); component.update(); }; diff --git a/x-pack/plugins/index_management/__jest__/client_integration/helpers/template_form.helpers.ts b/x-pack/plugins/index_management/__jest__/client_integration/helpers/template_form.helpers.ts index e0cffb7f0969a..21713428c4316 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/helpers/template_form.helpers.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/helpers/template_form.helpers.ts @@ -34,10 +34,7 @@ export const formSetup = async (initTestBed: SetupFunc) => { }; const clickEditButtonAtField = (index: number) => { - testBed - .find('editFieldButton') - .at(index) - .simulate('click'); + testBed.find('editFieldButton').at(index).simulate('click'); }; const clickEditFieldUpdateButton = () => { @@ -45,10 +42,7 @@ export const formSetup = async (initTestBed: SetupFunc) => { }; const deleteMappingsFieldAt = (index: number) => { - testBed - .find('removeFieldButton') - .at(index) - .simulate('click'); + testBed.find('removeFieldButton').at(index).simulate('click'); testBed.find('confirmModalConfirmButton').simulate('click'); }; @@ -143,11 +137,7 @@ export const formSetup = async (initTestBed: SetupFunc) => { const selectSummaryTab = (tab: 'summary' | 'request') => { const tabs = ['summary', 'request']; - testBed - .find('summaryTabContent') - .find('.euiTab') - .at(tabs.indexOf(tab)) - .simulate('click'); + testBed.find('summaryTabContent').find('.euiTab').at(tabs.indexOf(tab)).simulate('click'); }; const addMappingField = async (name: string, type: string) => { diff --git a/x-pack/plugins/index_management/__jest__/client_integration/home.test.ts b/x-pack/plugins/index_management/__jest__/client_integration/home.test.ts index 4c5cfcd826844..f5af11330a6d8 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/home.test.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/home.test.ts @@ -13,7 +13,7 @@ import { API_BASE_PATH } from '../../common/constants'; const { setup } = pageHelpers.home; const removeWhiteSpaceOnArrayValues = (array: any[]) => - array.map(value => { + array.map((value) => { if (!value.trim) { return value; } @@ -216,7 +216,7 @@ describe('', () => { const { rows } = table.getMetaData('templateTable'); expect(rows.length).toEqual( - templates.filter(template => !template.name.startsWith('.')).length + templates.filter((template) => !template.name.startsWith('.')).length ); expect(exists('systemTemplatesSwitch')).toBe(true); @@ -446,7 +446,7 @@ describe('', () => { await actions.clickTemplateAt(0); expect(find('templateDetails.tab').length).toBe(4); - expect(find('templateDetails.tab').map(t => t.text())).toEqual([ + expect(find('templateDetails.tab').map((t) => t.text())).toEqual([ 'Summary', 'Settings', 'Mappings', @@ -549,9 +549,7 @@ describe('', () => { component.update(); - find('indexTableIndexNameLink') - .at(0) - .simulate('click'); + find('indexTableIndexNameLink').at(0).simulate('click'); }); test('should encode indexName when loading settings in detail panel', async () => { diff --git a/x-pack/plugins/index_management/__jest__/client_integration/template_create.test.tsx b/x-pack/plugins/index_management/__jest__/client_integration/template_create.test.tsx index ec810faf687be..05abe284fab32 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/template_create.test.tsx +++ b/x-pack/plugins/index_management/__jest__/client_integration/template_create.test.tsx @@ -259,7 +259,7 @@ describe('', () => { expect( find('summaryTabContent') .find('.euiTab') - .map(t => t.text()) + .map((t) => t.text()) ).toEqual(['Summary', 'Request']); }); diff --git a/x-pack/plugins/index_management/__jest__/components/index_table.test.js b/x-pack/plugins/index_management/__jest__/components/index_table.test.js index 5e3edc78da5a8..ffd3cbb83c2ce 100644 --- a/x-pack/plugins/index_management/__jest__/components/index_table.test.js +++ b/x-pack/plugins/index_management/__jest__/components/index_table.test.js @@ -75,7 +75,7 @@ const status = (rendered, row = 0) => { .text(); }; -const snapshot = rendered => { +const snapshot = (rendered) => { expect(rendered).toMatchSnapshot(); }; const openMenuAndClickButton = (rendered, rowIndex, buttonIndex) => { @@ -108,11 +108,11 @@ const testAction = (buttonIndex, done, rowIndex = 0) => { openMenuAndClickButton(rendered, rowIndex, buttonIndex); snapshot(status(rendered, rowIndex)); }; -const names = rendered => { +const names = (rendered) => { return findTestSubject(rendered, 'indexTableIndexNameLink'); }; -const namesText = rendered => { - return names(rendered).map(button => button.text()); +const namesText = (rendered) => { + return names(rendered).map((button) => button.text()); }; describe('index table', () => { @@ -203,14 +203,14 @@ describe('index table', () => { snapshot( rendered .find('.euiPagination .euiPaginationButton .euiButtonEmpty__content > span') - .map(span => span.text()) + .map((span) => span.text()) ); const switchControl = rendered.find('.euiSwitch__button'); switchControl.simulate('click'); snapshot( rendered .find('.euiPagination .euiPaginationButton .euiButtonEmpty__content > span') - .map(span => span.text()) + .map((span) => span.text()) ); }); test('should filter based on content of search input', () => { @@ -247,7 +247,7 @@ describe('index table', () => { const actionButton = findTestSubject(rendered, 'indexActionsContextMenuButton'); actionButton.simulate('click'); rendered.update(); - snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map(span => span.text())); + snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map((span) => span.text())); }); test('should show the right context menu options when one index is selected and closed', () => { const rendered = mountWithIntl(component); @@ -257,7 +257,7 @@ describe('index table', () => { const actionButton = findTestSubject(rendered, 'indexActionsContextMenuButton'); actionButton.simulate('click'); rendered.update(); - snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map(span => span.text())); + snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map((span) => span.text())); }); test('should show the right context menu options when one open and one closed index is selected', () => { const rendered = mountWithIntl(component); @@ -268,7 +268,7 @@ describe('index table', () => { const actionButton = findTestSubject(rendered, 'indexActionsContextMenuButton'); actionButton.simulate('click'); rendered.update(); - snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map(span => span.text())); + snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map((span) => span.text())); }); test('should show the right context menu options when more than one open index is selected', () => { const rendered = mountWithIntl(component); @@ -279,7 +279,7 @@ describe('index table', () => { const actionButton = findTestSubject(rendered, 'indexActionsContextMenuButton'); actionButton.simulate('click'); rendered.update(); - snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map(span => span.text())); + snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map((span) => span.text())); }); test('should show the right context menu options when more than one closed index is selected', () => { const rendered = mountWithIntl(component); @@ -290,18 +290,18 @@ describe('index table', () => { const actionButton = findTestSubject(rendered, 'indexActionsContextMenuButton'); actionButton.simulate('click'); rendered.update(); - snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map(span => span.text())); + snapshot(findTestSubject(rendered, 'indexTableContextMenuButton').map((span) => span.text())); }); - test('flush button works from context menu', done => { + test('flush button works from context menu', (done) => { testAction(8, done); }); - test('clear cache button works from context menu', done => { + test('clear cache button works from context menu', (done) => { testAction(7, done); }); - test('refresh button works from context menu', done => { + test('refresh button works from context menu', (done) => { testAction(6, done); }); - test('force merge button works from context menu', done => { + test('force merge button works from context menu', (done) => { const rendered = mountWithIntl(component); const rowIndex = 0; openMenuAndClickButton(rendered, rowIndex, 5); @@ -322,8 +322,8 @@ describe('index table', () => { }); // Commenting the following 2 tests as it works in the browser (status changes to "closed" or "open") but the // snapshot say the contrary. Need to be investigated. - test('close index button works from context menu', done => { - const modifiedIndices = indices.map(index => { + test('close index button works from context menu', (done) => { + const modifiedIndices = indices.map((index) => { return { ...index, status: index.name === 'testy0' ? 'close' : index.status, @@ -337,8 +337,8 @@ describe('index table', () => { ]); testAction(4, done); }); - test('open index button works from context menu', done => { - const modifiedIndices = indices.map(index => { + test('open index button works from context menu', (done) => { + const modifiedIndices = indices.map((index) => { return { ...index, status: index.name === 'testy1' ? 'open' : index.status, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/text_datatype.test.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/text_datatype.test.tsx index e708bf1b4de66..581624e312206 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/text_datatype.test.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/datatypes/text_datatype.test.tsx @@ -370,7 +370,7 @@ describe.skip('Mappings editor: text datatype', () => { const subSelectOptions = indexAnalyzerSelects .at(1) .find('option') - .map(wrapper => wrapper.text()); + .map((wrapper) => wrapper.text()); expect(subSelectOptions).toEqual(customAnalyzers); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/mappings_editor.helpers.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/mappings_editor.helpers.tsx index 28fe2bfdc0711..bef2d5c79be99 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/mappings_editor.helpers.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/mappings_editor.helpers.tsx @@ -40,7 +40,7 @@ jest.mock('@elastic/eui', () => ({ { + onChange={(e) => { props.onChange(e.target.value); }} /> @@ -108,7 +108,7 @@ const createActions = (testBed: TestBed) => { ): Promise => { const fields = find( fieldName ? (`${fieldName}.fieldsList.fieldsListItem` as TestSubjects) : 'fieldsListItem' - ).map(wrapper => wrapper); // convert to Array for our for of loop below + ).map((wrapper) => wrapper); // convert to Array for our for of loop below for (const field of fields) { const { hasChildren, testSubjectField } = await expandField(field); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/mappings_editor.test.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/mappings_editor.test.tsx index 07f72d7cbf54a..0743211a2b7bf 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/mappings_editor.test.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/mappings_editor.test.tsx @@ -279,7 +279,7 @@ describe.skip('Mappings editor: core', () => { * Mapped fields */ // Test that root-level mappings "properties" are rendered as root-level "DOM tree items" - const fields = find('fieldsListItem.fieldName').map(item => item.text()); + const fields = find('fieldsListItem.fieldName').map((item) => item.text()); expect(fields).toEqual(Object.keys(defaultMappings.properties).sort()); /** diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx index 99c6fc37c4219..19eec0f0a9f9d 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx @@ -24,7 +24,7 @@ interface Props { const stringifyJson = (json: GenericObject) => Object.keys(json).length ? JSON.stringify(json, null, 2) : '{\n\n}'; -const formSerializer: SerializerFunc = formData => { +const formSerializer: SerializerFunc = (formData) => { const { dynamicMapping: { enabled: dynamicMappingsEnabled, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form_schema.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form_schema.tsx index 9d777cdccf83d..c06340fd9ae14 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form_schema.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form_schema.tsx @@ -26,7 +26,7 @@ const fieldPathComboBoxConfig = { type: FIELD_TYPES.COMBO_BOX, defaultValue: [], serializer: (options: ComboBoxOption[]): string[] => options.map(({ label }) => label), - deserializer: (values: string[]): ComboBoxOption[] => values.map(value => ({ label: value })), + deserializer: (values: string[]): ComboBoxOption[] => values.map((value) => ({ label: value })), }; export const configurationFormSchema: FormSchema = { diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/dynamic_mapping_section/dynamic_mapping_section.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/dynamic_mapping_section/dynamic_mapping_section.tsx index c1a2b195a3f57..05d871ccfac71 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/dynamic_mapping_section/dynamic_mapping_section.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/dynamic_mapping_section/dynamic_mapping_section.tsx @@ -52,7 +52,7 @@ export const DynamicMappingSection = () => ( } > - {formData => { + {(formData) => { const { 'dynamicMapping.enabled': enabled, 'dynamicMapping.date_detection': dateDetection, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/source_field_section/source_field_section.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/source_field_section/source_field_section.tsx index 4278598dfc7c1..d195f1abfc444 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/source_field_section/source_field_section.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/source_field_section/source_field_section.tsx @@ -78,7 +78,7 @@ export const SourceFieldSection = () => { } )} selectedOptions={value as ComboBoxOption[]} - onChange={newValue => { + onChange={(newValue) => { setValue(newValue); }} onCreateOption={(searchValue: string) => { @@ -109,7 +109,7 @@ export const SourceFieldSection = () => { } )} selectedOptions={value as ComboBoxOption[]} - onChange={newValue => { + onChange={(newValue) => { setValue(newValue); }} onCreateOption={(searchValue: string) => { @@ -154,7 +154,7 @@ export const SourceFieldSection = () => { } > - {formData => { + {(formData) => { const { 'sourceField.enabled': enabled } = formData; if (enabled === undefined) { diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields_header.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields_header.tsx index a4e746aa4037d..56c01510376be 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields_header.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields_header.tsx @@ -46,7 +46,7 @@ export const DocumentFieldsHeader = React.memo(({ searchValue, onSearchChange }: } )} value={searchValue} - onChange={e => { + onChange={(e) => { // Temporary fix until EUI fixes the contract // See my comment https://github.com/elastic/eui/pull/2723/files#r366725059 if (typeof e === 'string') { diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/analyzer_parameter.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/analyzer_parameter.tsx index 569af5d21cdb0..dc52a362008c6 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/analyzer_parameter.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/analyzer_parameter.tsx @@ -50,7 +50,7 @@ const getCustomAnalyzers = (indexSettings: IndexSettings): SelectOption[] | unde // We wrap inside a try catch as the index settings are written in JSON // and who knows what the user has entered. try { - return Object.keys(settings.analysis!.analyzer).map(value => ({ value, text: value })); + return Object.keys(settings.analysis!.analyzer).map((value) => ({ value, text: value })); } catch { return undefined; } @@ -156,7 +156,7 @@ export const AnalyzerParameter = ({ return ( - {field => ( + {(field) => (
{ - const subscription = form.subscribe(updateData => { + const subscription = form.subscribe((updateData) => { const formData = updateData.data.raw; const value = formData.sub ? formData.sub : formData.main; onChange(value); @@ -102,7 +102,7 @@ export const AnalyzerParameterSelects = ({ - {field => renderSelect(field, options)} + {(field) => renderSelect(field, options)} {subOptions && ( @@ -115,7 +115,7 @@ export const AnalyzerParameterSelects = ({ label: subOptions.label, }} > - {field => renderSelect(field, subOptions.options)} + {(field) => renderSelect(field, subOptions.options)} )} diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/dynamic_parameter.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/dynamic_parameter.tsx index 975a6cd9bba4f..1882802b27487 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/dynamic_parameter.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/dynamic_parameter.tsx @@ -79,7 +79,7 @@ export const DynamicParameter = ({ defaultToggleValue }: Props) => { formFieldPath="dynamic_toggle" defaultToggleValue={defaultToggleValue} > - {isOn => { + {(isOn) => { return isOn === false ? ( { const defaultValueArray = - defaultValue !== undefined ? defaultValue.split('||').map(value => ({ label: value })) : []; - const defaultValuesInOptions = defaultValueArray.filter(defaultFormat => + defaultValue !== undefined ? defaultValue.split('||').map((value) => ({ label: value })) : []; + const defaultValuesInOptions = defaultValueArray.filter((defaultFormat) => ALL_DATE_FORMAT_OPTIONS.includes(defaultFormat) ); @@ -57,7 +57,7 @@ export const FormatParameter = ({ defaultValue, defaultToggleValue }: Props) => defaultToggleValue={defaultToggleValue} > - {formatField => { + {(formatField) => { return ( )} options={comboBoxOptions} selectedOptions={formatField.value as ComboBoxOption[]} - onChange={value => { + onChange={(value) => { formatField.setValue(value); }} onCreateOption={(searchValue: string) => { diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/index_parameter.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/index_parameter.tsx index 3e91e97eef618..59ed0f3a0a2e5 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/index_parameter.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/index_parameter.tsx @@ -53,8 +53,6 @@ export const IndexParameter = ({ }, }} /> - ) : ( - undefined - )} + ) : undefined} ); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/path_parameter.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/path_parameter.tsx index 44c19c12db88b..ae5ffaae3552b 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/path_parameter.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/path_parameter.tsx @@ -70,7 +70,7 @@ export const PathParameter = ({ field, allFields }: Props) => { deserializer: getDeserializer(allFields), }} > - {pathField => { + {(pathField) => { const error = pathField.getErrorsMessages(); const isInvalid = error ? Boolean(error.length) : false; @@ -123,7 +123,7 @@ export const PathParameter = ({ field, allFields }: Props) => { singleSelection={{ asPlainText: true }} options={suggestedFields} selectedOptions={pathField.value as AliasOption[]} - onChange={value => pathField.setValue(value)} + onChange={(value) => pathField.setValue(value)} isClearable={false} fullWidth /> diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/subtype_parameter.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/subtype_parameter.tsx index f955c68a6c8d5..cfa8b60653d4c 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/subtype_parameter.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/subtype_parameter.tsx @@ -47,8 +47,8 @@ export const SubTypeParameter = ({ // Field sub type (if any) const subTypeOptions = typeDefinition - .subTypes!.types.map(_subType => TYPE_DEFINITION[_subType]) - .map(_subType => ({ value: _subType.value, label: _subType.label })); + .subTypes!.types.map((_subType) => TYPE_DEFINITION[_subType]) + .map((_subType) => ({ value: _subType.value, label: _subType.label })); const defaultValueSubType = typeDefinition.subTypes!.types.includes(defaultValueType as SubType) ? defaultValueType // we use the default value provided @@ -64,7 +64,7 @@ export const SubTypeParameter = ({ label: typeDefinition.subTypes!.label, }} > - {subTypeField => { + {(subTypeField) => { return ( { defaultToggleValue={defaultToggleValue} > - {formData => ( + {(formData) => ( <> ( path="type" config={getFieldConfig('type')}> - {typeField => { + {(typeField) => { const error = typeField.getErrorsMessages(); const isInvalid = error ? Boolean(error.length) : false; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/create_field/create_field.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/create_field/create_field.tsx index 718d00ea461c0..230e6615bc4a4 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/create_field/create_field.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/create_field/create_field.tsx @@ -51,7 +51,7 @@ export const CreateField = React.memo(function CreateFieldComponent({ }); useEffect(() => { - const subscription = form.subscribe(updatedFieldForm => { + const subscription = form.subscribe((updatedFieldForm) => { dispatch({ type: 'fieldForm.update', value: updatedFieldForm }); }); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/delete_field_provider.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/delete_field_provider.tsx index 64ed3a6f87117..80e3e9bec605a 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/delete_field_provider.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/delete_field_provider.tsx @@ -54,9 +54,9 @@ export const DeleteFieldProvider = ({ children }: Props) => { ); } - const deleteField: DeleteFieldFunc = field => { + const deleteField: DeleteFieldFunc = (field) => { const aliases = getAllDescendantAliases(field, fields) - .map(id => byId[id].path.join(' > ')) + .map((id) => byId[id].path.join(' > ')) .sort(); const hasAliases = Boolean(aliases.length); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field.tsx index 33c4a21775d69..e8e41955a5e80 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field.tsx @@ -64,7 +64,7 @@ export const EditField = React.memo(({ form, field, allFields, exitEdit }: Props return ( - {updateField => ( + {(updateField) => ( { }); useEffect(() => { - const subscription = form.subscribe(updatedFieldForm => { + const subscription = form.subscribe((updatedFieldForm) => { dispatch({ type: 'fieldForm.update', value: updatedFieldForm }); }); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_form_row.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_form_row.tsx index 1c079c8d5cf87..c0e68b082c310 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_form_row.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_form_row.tsx @@ -100,7 +100,7 @@ export const EditFieldFormRow = React.memo( defaultValue: initialVisibleState, }} > - {field => { + {(field) => { return ( - {formData => { + {(formData) => { setIsContentVisible(formData[formFieldPath]); return renderContent(); }} diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/update_field_provider.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/update_field_provider.tsx index 88e08bc7098cb..e31d12689e7e0 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/update_field_provider.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/update_field_provider.tsx @@ -62,7 +62,7 @@ export const UpdateFieldProvider = ({ children }: Props) => { setState({ isModalOpen: false }); }; - const updateField: UpdateFieldFunc = field => { + const updateField: UpdateFieldFunc = (field) => { const previousField = byId[field.id]; const willDeleteChildFields = (oldType: DataType, newType: DataType): boolean => { @@ -102,7 +102,7 @@ export const UpdateFieldProvider = ({ children }: Props) => { if (requiresConfirmation) { aliasesToDelete = aliasesOnFieldAndDescendants.filter( // We will only delete aliases that points to possible children, *NOT* the field itself - id => aliasesOnField.includes(id) === false + (id) => aliasesOnField.includes(id) === false ); } } @@ -112,7 +112,7 @@ export const UpdateFieldProvider = ({ children }: Props) => { isModalOpen: true, field, aliases: Boolean(aliasesToDelete.length) - ? aliasesToDelete.map(id => byId[id].path.join(' > ')).sort() + ? aliasesToDelete.map((id) => byId[id].path.join(' > ')).sort() : undefined, }); return; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/numeric_type.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/numeric_type.tsx index 89af480d79a20..3d78205934eea 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/numeric_type.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/numeric_type.tsx @@ -47,7 +47,7 @@ export const NumericType = ({ field }: Props) => { {/* scaling_factor */} - {formData => + {(formData) => formData.subType === 'scaled_float' ? ( { - {formData => + {(formData) => formData.subType === 'date_range' ? ( { - {formData => + {(formData) => formData.subType === 'date_range' ? ( ) : null diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/text_type.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/text_type.tsx index 73032ad31461e..c4ed11097b609 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/text_type.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/text_type.tsx @@ -182,7 +182,7 @@ export const TextType = React.memo(({ field }: Props) => { defaultToggleValue={getDefaultToggleValue('position_increment_gap', field.source)} > - {formData => { + {(formData) => { return ( <> - {deleteField => ( + {(deleteField) => (
    - {aliases.map(aliasPath => ( + {aliases.map((aliasPath) => (
  • {aliasPath}
  • diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result_item.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result_item.tsx index 614b7cb56bef6..ab8b90b6be3b5 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result_item.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/search_fields/search_result_item.tsx @@ -68,7 +68,7 @@ export const SearchResultItem = React.memo(function FieldListItemFlatComponent({ - {deleteField => ( + {(deleteField) => ( ( - {openModal => ( + {(openModal) => ( {i18n.translate('xpack.idxMgmt.mappingsEditor.loadFromJsonButtonLabel', { defaultMessage: 'Load JSON', diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.test.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.test.tsx index fdd45889353d4..86bc0900f1678 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.test.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.test.tsx @@ -29,7 +29,7 @@ import { LoadMappingsProvider } from './load_mappings_provider'; const ComponentToTest = ({ onJson }: { onJson: () => void }) => ( - {openModal => ( + {(openModal) => ( diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.tsx index 6bc360a1ec70e..a50572df9004e 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.tsx @@ -134,7 +134,7 @@ export const LoadMappingsProvider = ({ onJson, children }: Props) => { state.json !== undefined && state.errors !== undefined ? 'validationResult' : 'json'; const i18nTexts = getTexts(view, state.errors?.length); - const onJsonUpdate: OnJsonEditorUpdateHandler = jsonUpdateData => { + const onJsonUpdate: OnJsonEditorUpdateHandler = (jsonUpdateData) => { jsonContent.current = jsonUpdateData; }; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx index 31ebce067b3b9..e6b7eeb12b4c8 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx @@ -22,7 +22,7 @@ interface Props { const stringifyJson = (json: { [key: string]: any }) => Array.isArray(json) ? JSON.stringify(json, null, 2) : '[\n\n]'; -const formSerializer: SerializerFunc = formData => { +const formSerializer: SerializerFunc = (formData) => { const { dynamicTemplates } = formData; let parsedTemplates; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/data_types_definition.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/data_types_definition.tsx index 4206fe8b696da..edfb6903a8585 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/data_types_definition.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/data_types_definition.tsx @@ -852,7 +852,7 @@ export const MAIN_DATA_TYPE_DEFINITION: { export const SUB_TYPE_MAP_TO_MAIN = Object.entries(MAIN_DATA_TYPE_DEFINITION).reduce( (acc, [type, definition]) => { if ({}.hasOwnProperty.call(definition, 'subTypes')) { - definition.subTypes!.types.forEach(subType => { + definition.subTypes!.types.forEach((subType) => { acc[subType] = type; }); } diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/field_options.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/field_options.tsx index 710e637de8b08..d16bf68b80e5d 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/field_options.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/field_options.tsx @@ -244,7 +244,7 @@ const DATE_FORMATS = [ { label: 'year_month_day', strict: true }, ]; -const STRICT_DATE_FORMAT_OPTIONS = DATE_FORMATS.filter(format => format.strict).map( +const STRICT_DATE_FORMAT_OPTIONS = DATE_FORMATS.filter((format) => format.strict).map( ({ label }) => ({ label: `strict_${label}`, }) diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/parameters_definition.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/parameters_definition.tsx index 1b9372e4b50c4..c7529ff272e22 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/parameters_definition.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/constants/parameters_definition.tsx @@ -225,15 +225,15 @@ export const PARAMETERS_DEFINITION: { [key in ParameterName]: ParameterDefinitio min: { fieldConfig: { defaultValue: 0.01, - serializer: value => (value === '' ? '' : toInt(value) / 100), - deserializer: value => Math.round(value * 100), + serializer: (value) => (value === '' ? '' : toInt(value) / 100), + deserializer: (value) => Math.round(value * 100), } as FieldConfig, }, max: { fieldConfig: { defaultValue: 1, - serializer: value => (value === '' ? '' : toInt(value) / 100), - deserializer: value => Math.round(value * 100), + serializer: (value) => (value === '' ? '' : toInt(value) / 100), + deserializer: (value) => Math.round(value * 100), } as FieldConfig, }, }, @@ -582,7 +582,7 @@ export const PARAMETERS_DEFINITION: { [key in ParameterName]: ParameterDefinitio serializer: (format: ComboBoxOption[]): string | undefined => format.length ? format.map(({ label }) => label).join('||') : undefined, deserializer: (formats: string): ComboBoxOption[] | undefined => - formats.split('||').map(format => ({ label: format })), + formats.split('||').map((format) => ({ label: format })), helpText: ( (value === '' ? '' : toInt(value)), + serializer: (value) => (value === '' ? '' : toInt(value)), } as FieldConfig, }, max_chars: { fieldConfig: { type: FIELD_TYPES.NUMBER, defaultValue: 5, - serializer: value => (value === '' ? '' : toInt(value)), + serializer: (value) => (value === '' ? '' : toInt(value)), } as FieldConfig, }, }, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/error_reporter.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/error_reporter.ts index e9beee1071597..405324920419e 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/error_reporter.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/error_reporter.ts @@ -10,7 +10,7 @@ import { Reporter } from 'io-ts/lib/Reporter'; export type ReporterResult = Array<{ path: string[]; message: string }>; const failure = (validation: ValidationError[]): ReporterResult => { - return validation.map(e => { + return validation.map((e) => { const path: string[] = []; let validationName = ''; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/extract_mappings_definition.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/extract_mappings_definition.ts index 817b0f4a4d3d0..1fd8329ae4b40 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/extract_mappings_definition.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/extract_mappings_definition.ts @@ -9,7 +9,7 @@ import { GenericObject } from '../types'; import { validateMappingsConfiguration, VALID_MAPPINGS_PARAMETERS } from './mappings_validator'; const isMappingDefinition = (obj: GenericObject): boolean => { - const areAllKeysValid = Object.keys(obj).every(key => VALID_MAPPINGS_PARAMETERS.includes(key)); + const areAllKeysValid = Object.keys(obj).every((key) => VALID_MAPPINGS_PARAMETERS.includes(key)); if (!areAllKeysValid) { return false; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.test.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.test.ts index d67c267dda6ae..a3feaf21e6493 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.test.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.test.ts @@ -11,7 +11,7 @@ describe('Mappings configuration validator', () => { it('should convert non object to empty object', () => { const tests = ['abc', 123, [], null, undefined]; - tests.forEach(testValue => { + tests.forEach((testValue) => { const { value, errors } = validateMappings(testValue as any); expect(isPlainObject(value)).toBe(true); expect(errors).toBe(undefined); @@ -93,7 +93,7 @@ describe('Properties validator', () => { it('should convert non object to empty object', () => { const tests = ['abc', 123, [], null, undefined]; - tests.forEach(testValue => { + tests.forEach((testValue) => { const { value, errors } = validateProperties(testValue as any); expect(isPlainObject(value)).toBe(true); expect(errors).toEqual([]); @@ -127,7 +127,7 @@ describe('Properties validator', () => { }); expect(errors).toEqual( - ['prop2', 'prop3', 'prop4', 'prop5', 'prop6.prop2'].map(fieldPath => ({ + ['prop2', 'prop3', 'prop4', 'prop5', 'prop6.prop2'].map((fieldPath) => ({ code: 'ERR_FIELD', fieldPath, })) @@ -348,9 +348,9 @@ describe('Properties validator', () => { expect(value.goodField2).toEqual(properties.goodField2); expect(value.goodField3).toEqual(properties.goodField3); - const allWrongParameters = Object.keys(properties.wrongField).filter(v => v !== 'type'); + const allWrongParameters = Object.keys(properties.wrongField).filter((v) => v !== 'type'); expect(errors).toEqual( - allWrongParameters.map(paramName => ({ + allWrongParameters.map((paramName) => ({ code: 'ERR_PARAMETER', fieldPath: 'wrongField', paramName, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts index 78d638e398593..f0d90be9472f6 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts @@ -149,7 +149,7 @@ const parseFields = ( if (Boolean(parametersRemoved.length)) { acc.errors = [ ...acc.errors, - ...parametersRemoved.map(paramName => ({ + ...parametersRemoved.map((paramName) => ({ code: 'ERR_PARAMETER' as 'ERR_PARAMETER', fieldPath, paramName, @@ -232,13 +232,13 @@ export const validateMappingsConfiguration = ( const isSchemaInvalid = isLeft(result); const unknownConfigurationParameters = Object.keys(mappingsConfiguration).filter( - key => mappingsConfigurationSchemaKeys.includes(key) === false + (key) => mappingsConfigurationSchemaKeys.includes(key) === false ); const unknownSourceConfigurationParameters = mappingsConfiguration._source !== undefined ? Object.keys(mappingsConfiguration._source).filter( - key => sourceConfigurationSchemaKeys.includes(key) === false + (key) => sourceConfigurationSchemaKeys.includes(key) === false ) : []; @@ -247,7 +247,7 @@ export const validateMappingsConfiguration = ( * To keep the logic simple we will strip out the parameters that contain errors */ const errors = errorReporter.report(result); - errors.forEach(error => { + errors.forEach((error) => { const configurationName = error.path[0]; configurationRemoved.add(configurationName); delete copyOfMappingsConfig[configurationName]; @@ -255,7 +255,7 @@ export const validateMappingsConfiguration = ( } if (unknownConfigurationParameters.length > 0) { - unknownConfigurationParameters.forEach(configName => configurationRemoved.add(configName)); + unknownConfigurationParameters.forEach((configName) => configurationRemoved.add(configName)); } if (unknownSourceConfigurationParameters.length > 0) { @@ -266,7 +266,7 @@ export const validateMappingsConfiguration = ( copyOfMappingsConfig = pick(copyOfMappingsConfig, mappingsConfigurationSchemaKeys); const errors: MappingsValidationError[] = toArray(ordString)(configurationRemoved) - .map(configName => ({ + .map((configName) => ({ code: 'ERR_CONFIG', configName, })) diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/search_fields.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/search_fields.tsx index 618d106b0e7a1..b937962a0944d 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/search_fields.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/search_fields.tsx @@ -160,7 +160,7 @@ const getSearchMetadata = (searchData: SearchData, fieldData: FieldData): Search // Execute all the regEx and sort them with the one that has the most // characters match first. const arrayMatch = searchRegexArray - .map(regex => regex.exec(fieldData.path)) + .map((regex) => regex.exec(fieldData.path)) .filter(Boolean) .sort((a, b) => b![0].length - a![0].length); @@ -239,7 +239,7 @@ export const searchFields = (term: string, fields: NormalizedFields['byId']): Se } return Object.values(fields) - .map(field => ({ + .map((field) => ({ field, metadata: getSearchMetadata(searchData, { name: field.source.name, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/utils.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/utils.ts index 6a1fd51a5af64..14f5858cb95d9 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/utils.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/utils.ts @@ -111,7 +111,7 @@ const replaceAliasPathByAliasId = ( Object.entries(byId).forEach(([id, field]) => { if (field.source.type === 'alias') { const aliasTargetField = Object.values(byId).find( - _field => _field.path.join('.') === field.source.path + (_field) => _field.path.join('.') === field.source.path ); if (aliasTargetField) { @@ -292,7 +292,7 @@ const replaceAliasIdByAliasPath = ( Object.entries(aliases).forEach(([targetId, aliasesIds]) => { const path = updatedById[targetId] ? updatedById[targetId].path.join('.') : ''; - aliasesIds.forEach(id => { + aliasesIds.forEach((id) => { const aliasField = updatedById[id]; if (!aliasField) { return; @@ -313,7 +313,7 @@ export const deNormalize = ({ rootLevelFields, byId, aliases }: NormalizedFields const serializedFieldsById = replaceAliasIdByAliasPath(aliases, byId); const deNormalizePaths = (ids: string[], to: Fields = {}) => { - ids.forEach(id => { + ids.forEach((id) => { const { source, childFields, childFieldsName } = serializedFieldsById[id]; const { name, ...normalizedField } = source; const field: Omit = normalizedField; @@ -356,8 +356,8 @@ export const updateFieldsPathAfterFieldNameChange = ( if (_field.hasChildFields || _field.hasMultiFields) { _field - .childFields!.map(fieldId => byId[fieldId]) - .forEach(childField => { + .childFields!.map((fieldId) => byId[fieldId]) + .forEach((childField) => { updateFieldPath(childField, [..._paths, name]); }); } @@ -381,8 +381,8 @@ export const getAllChildFields = ( const getChildFields = (_field: NormalizedField, to: NormalizedField[] = []) => { if (_field.hasChildFields || _field.hasMultiFields) { _field - .childFields!.map(fieldId => byId[fieldId]) - .forEach(childField => { + .childFields!.map((fieldId) => byId[fieldId]) + .forEach((childField) => { to.push(childField); getChildFields(childField, to); }); @@ -411,13 +411,13 @@ export const getAllDescendantAliases = ( } if (hasAliases) { - fields.aliases[field.id].forEach(id => { + fields.aliases[field.id].forEach((id) => { aliasesIds.push(id); }); } if (field.childFields) { - field.childFields.forEach(id => { + field.childFields.forEach((id) => { if (!fields.byId[id]) { return; } @@ -455,14 +455,14 @@ export const filterTypesForMultiField = ( options: ComboBoxOption[] ): ComboBoxOption[] => options.filter( - option => TYPE_NOT_ALLOWED_MULTIFIELD.includes(option.value as MainType) === false + (option) => TYPE_NOT_ALLOWED_MULTIFIELD.includes(option.value as MainType) === false ); export const filterTypesForNonRootFields = ( options: ComboBoxOption[] ): ComboBoxOption[] => options.filter( - option => TYPE_ONLY_ALLOWED_AT_ROOT_LEVEL.includes(option.value as MainType) === false + (option) => TYPE_ONLY_ALLOWED_AT_ROOT_LEVEL.includes(option.value as MainType) === false ); /** @@ -484,7 +484,7 @@ export const buildFieldTreeFromIds = ( byId: NormalizedFields['byId'], render: (field: NormalizedField) => JSX.Element | string ): TreeItem[] => - fieldsIds.map(id => { + fieldsIds.map((id) => { const field = byId[id]; const children = field.childFields ? buildFieldTreeFromIds(field.childFields, byId, render) diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/validators.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/validators.ts index 279d4612f3df1..43498b2bb9e72 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/validators.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/validators.ts @@ -17,11 +17,11 @@ export const validateUniqueName = ( const validator: ValidationFunc = ({ value }) => { const existingNames = parentId ? Object.values(byId) - .filter(field => field.parentId === parentId) - .map(field => field.source.name) - : rootLevelFields.map(fieldId => byId[fieldId].source.name); + .filter((field) => field.parentId === parentId) + .map((field) => field.source.name) + : rootLevelFields.map((fieldId) => byId[fieldId].source.name); - if (existingNames.filter(name => name !== initialName).includes(value as string)) { + if (existingNames.filter((name) => name !== initialName).includes(value as string)) { return { message: i18n.translate('xpack.idxMgmt.mappingsEditor.existNamesValidationErrorMessage', { defaultMessage: 'There is already a field with this name.', diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_state.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_state.tsx index 280ea5c3dd28c..029b154761ea4 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_state.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_state.tsx @@ -143,7 +143,7 @@ export const MappingsState = React.memo(({ children, onChange, value }: Props) = validate: async () => { const configurationFormValidator = state.configuration.submitForm !== undefined - ? new Promise(async resolve => { + ? new Promise(async (resolve) => { const { isValid } = await state.configuration.submitForm!(); resolve(isValid); }) @@ -151,7 +151,7 @@ export const MappingsState = React.memo(({ children, onChange, value }: Props) = const templatesFormValidator = state.templates.submitForm !== undefined - ? new Promise(async resolve => { + ? new Promise(async (resolve) => { const { isValid } = await state.templates.submitForm!(); resolve(isValid); }) @@ -164,7 +164,7 @@ export const MappingsState = React.memo(({ children, onChange, value }: Props) = } return Promise.all(promisesToValidate).then( - validationArray => validationArray.every(Boolean) && state.fieldsJsonEditor.isValid + (validationArray) => validationArray.every(Boolean) && state.fieldsJsonEditor.isValid ); }, isValid: state.isValid, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/reducer.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/reducer.ts index 61ba010fbc7b0..e0311fc86a3b0 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/reducer.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/reducer.ts @@ -180,7 +180,7 @@ const updateAliasesReferences = ( */ if (previousTargetPath && updatedAliases[previousTargetPath]) { updatedAliases[previousTargetPath] = updatedAliases[previousTargetPath].filter( - id => id !== field.id + (id) => id !== field.id ); } @@ -217,7 +217,7 @@ const removeFieldFromMap = (fieldId: string, fields: NormalizedFields): Normaliz if (parentField) { // If the parent exist, update its childFields Array - const childFields = parentField.childFields!.filter(childId => childId !== fieldId); + const childFields = parentField.childFields!.filter((childId) => childId !== fieldId); updatedById[parentId] = { ...parentField, @@ -233,7 +233,7 @@ const removeFieldFromMap = (fieldId: string, fields: NormalizedFields): Normaliz } else { // If there are no parentId it means that we have deleted a top level field // We need to update the root level fields Array - rootLevelFields = rootLevelFields.filter(childId => childId !== fieldId); + rootLevelFields = rootLevelFields.filter((childId) => childId !== fieldId); } let updatedFields = { @@ -410,7 +410,7 @@ export const reducer = (state: State, action: Action): State => { const allChildFields = getAllChildFields(field, state.fields.byId); // Remove all of its children - allChildFields!.forEach(childField => { + allChildFields!.forEach((childField) => { updatedFields = removeFieldFromMap(childField.id, updatedFields); }); } @@ -423,7 +423,7 @@ export const reducer = (state: State, action: Action): State => { const targetId = field.source.path as string; updatedFields.aliases = { ...updatedFields.aliases, - [targetId]: updatedFields.aliases[targetId].filter(aliasId => aliasId !== id), + [targetId]: updatedFields.aliases[targetId].filter((aliasId) => aliasId !== id), }; } @@ -491,7 +491,7 @@ export const reducer = (state: State, action: Action): State => { ...updatedFields.aliases, [previousField.source.path as string]: updatedFields.aliases[ previousField.source.path as string - ].filter(aliasId => aliasId !== fieldToEdit), + ].filter((aliasId) => aliasId !== fieldToEdit), }; } else { const nextTypeCanHaveAlias = !PARAMETERS_DEFINITION.path.targetTypesNotAllowed.includes( @@ -499,7 +499,7 @@ export const reducer = (state: State, action: Action): State => { ); if (!nextTypeCanHaveAlias && updatedFields.aliases[fieldToEdit]) { - updatedFields.aliases[fieldToEdit].forEach(aliasId => { + updatedFields.aliases[fieldToEdit].forEach((aliasId) => { updatedFields = removeFieldFromMap(aliasId, updatedFields); }); delete updatedFields.aliases[fieldToEdit]; @@ -508,7 +508,7 @@ export const reducer = (state: State, action: Action): State => { if (shouldDeleteChildFields && previousField.childFields) { const allChildFields = getAllChildFields(previousField, updatedFields.byId); - allChildFields!.forEach(childField => { + allChildFields!.forEach((childField) => { updatedFields = removeFieldFromMap(childField.id, updatedFields); }); } diff --git a/x-pack/plugins/index_management/public/application/components/template_delete_modal.tsx b/x-pack/plugins/index_management/public/application/components/template_delete_modal.tsx index b80e51d8d139f..a87412ef92950 100644 --- a/x-pack/plugins/index_management/public/application/components/template_delete_modal.tsx +++ b/x-pack/plugins/index_management/public/application/components/template_delete_modal.tsx @@ -164,7 +164,7 @@ export const TemplateDeleteModal = ({ /> } checked={isDeleteConfirmed} - onChange={e => setIsDeleteConfirmed(e.target.checked)} + onChange={(e) => setIsDeleteConfirmed(e.target.checked)} /> )} diff --git a/x-pack/plugins/index_management/public/application/components/template_form/steps/step_review.tsx b/x-pack/plugins/index_management/public/application/components/template_form/steps/step_review.tsx index 0cb2ae9fbcd92..7b266034bc336 100644 --- a/x-pack/plugins/index_management/public/application/components/template_form/steps/step_review.tsx +++ b/x-pack/plugins/index_management/public/application/components/template_form/steps/step_review.tsx @@ -77,7 +77,7 @@ export const StepReview: React.FunctionComponent = ({ template, updat const numIndexPatterns = indexPatterns!.length; - const hasWildCardIndexPattern = Boolean(indexPatterns!.find(pattern => pattern === '*')); + const hasWildCardIndexPattern = Boolean(indexPatterns!.find((pattern) => pattern === '*')); const SummaryTab = () => (
    diff --git a/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx b/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx index f6193bc71aa91..0cdfaae70f151 100644 --- a/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx +++ b/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx @@ -87,7 +87,7 @@ export const TemplateForm: React.FunctionComponent = ({ const onStepValidityChange = useCallback( (isValid: boolean | undefined) => { - setValidation(prev => ({ + setValidation((prev) => ({ ...prev, [currentStep]: { isValid, diff --git a/x-pack/plugins/index_management/public/application/components/template_form/template_steps.tsx b/x-pack/plugins/index_management/public/application/components/template_form/template_steps.tsx index f36742c43af16..7a31c74c1a9c2 100644 --- a/x-pack/plugins/index_management/public/application/components/template_form/template_steps.tsx +++ b/x-pack/plugins/index_management/public/application/components/template_form/template_steps.tsx @@ -37,7 +37,7 @@ export const TemplateSteps: React.FunctionComponent = ({ updateCurrentStep, isCurrentStepValid, }) => { - const steps = [1, 2, 3, 4, 5].map(step => { + const steps = [1, 2, 3, 4, 5].map((step) => { return { title: stepNamesMap[step], isComplete: currentStep > step, diff --git a/x-pack/plugins/index_management/public/application/lib/ace.js b/x-pack/plugins/index_management/public/application/lib/ace.js index 3b37c8fb8870e..58e0100202cf5 100644 --- a/x-pack/plugins/index_management/public/application/lib/ace.js +++ b/x-pack/plugins/index_management/public/application/lib/ace.js @@ -7,10 +7,10 @@ import brace from 'brace'; import 'brace/ext/language_tools'; -const splitTokens = line => { +const splitTokens = (line) => { return line.split(/\s+/); }; -const wordCompleter = words => { +const wordCompleter = (words) => { return { identifierRegexps: [ /[a-zA-Z_0-9\.\$\-\u00A2-\uFFFF]/, // adds support for dot character @@ -31,7 +31,7 @@ const wordCompleter = words => { const endQuote = secondFullToken === '""' ? '' : '"'; callback( null, - words.map(word => { + words.map((word) => { return { caption: ` ${word}`, value: `${startQuote}${word}${endQuote}`, diff --git a/x-pack/plugins/index_management/public/application/lib/flatten_object.js b/x-pack/plugins/index_management/public/application/lib/flatten_object.js index dd85698b9175e..a1bb52cc8ffc7 100644 --- a/x-pack/plugins/index_management/public/application/lib/flatten_object.js +++ b/x-pack/plugins/index_management/public/application/lib/flatten_object.js @@ -11,7 +11,7 @@ export const flattenObject = (nestedObj, flattenArrays) => { const flatObj = {}; const dot = '.'; (function flattenObj(obj) { - _.keys(obj).forEach(function(key) { + _.keys(obj).forEach(function (key) { stack.push(key); if (!flattenArrays && Array.isArray(obj[key])) flatObj[stack.join(dot)] = obj[key]; else if (_.isObject(obj[key])) flattenObj(obj[key]); diff --git a/x-pack/plugins/index_management/public/application/lib/flatten_panel_tree.js b/x-pack/plugins/index_management/public/application/lib/flatten_panel_tree.js index e060e22965cb3..2bb3903a6ef45 100644 --- a/x-pack/plugins/index_management/public/application/lib/flatten_panel_tree.js +++ b/x-pack/plugins/index_management/public/application/lib/flatten_panel_tree.js @@ -8,7 +8,7 @@ export const flattenPanelTree = (tree, array = []) => { array.push(tree); if (tree.items) { - tree.items.forEach(item => { + tree.items.forEach((item) => { if (item.panel) { flattenPanelTree(item.panel, array); item.panel = item.panel.id; diff --git a/x-pack/plugins/index_management/public/application/sections/home/home.tsx b/x-pack/plugins/index_management/public/application/sections/home/home.tsx index 5d8e32031ea10..8e8616d24be20 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/home.tsx +++ b/x-pack/plugins/index_management/public/application/sections/home/home.tsx @@ -92,7 +92,7 @@ export const IndexManagementHome: React.FunctionComponent - {tabs.map(tab => ( + {tabs.map((tab) => ( onSectionChange(tab.id)} isSelected={tab.id === section} diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/detail_panel.container.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/detail_panel.container.js index 5c5b73542f7e4..c183bdb0020ca 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/detail_panel.container.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/detail_panel.container.js @@ -23,7 +23,7 @@ import { refreshIndices, } from '../../../../store/actions'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const indexName = getDetailPanelIndexName(state); return { panelType: getDetailPanelType(state), @@ -32,27 +32,27 @@ const mapStateToProps = state => { }; }; -const mapDispatchToProps = dispatch => { +const mapDispatchToProps = (dispatch) => { return { - clearCacheIndex: indexName => { + clearCacheIndex: (indexName) => { dispatch(clearCacheIndices({ indexNames: [indexName] })); }, - closeIndex: indexName => { + closeIndex: (indexName) => { dispatch(closeIndices({ indexNames: [indexName] })); }, - flushIndex: indexName => { + flushIndex: (indexName) => { dispatch(flushIndices({ indexNames: [indexName] })); }, - openIndex: indexName => { + openIndex: (indexName) => { dispatch(openIndices({ indexNames: [indexName] })); }, - refreshIndex: indexName => { + refreshIndex: (indexName) => { dispatch(refreshIndices({ indexNames: [indexName] })); }, - forcemergeIndex: indexName => { + forcemergeIndex: (indexName) => { dispatch(forcemergeIndices({ indexNames: [indexName] })); }, - deleteIndex: indexName => { + deleteIndex: (indexName) => { dispatch(deleteIndices({ indexNames: [indexName] })); }, closeDetailPanel: () => dispatch(closeDetailPanel()), diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.container.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.container.js index c8d06a8dd2eec..a25b8abbc222b 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.container.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.container.js @@ -14,7 +14,7 @@ import { getIndexStatusByIndexName, } from '../../../../../store/selectors'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const indexName = getDetailPanelIndexName(state); return { error: getDetailPanelError(state), diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.js index 4f2d0b3de96b7..5f105a2002761 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/edit_settings_json/edit_settings_json.js @@ -45,7 +45,7 @@ export class EditSettingsJson extends React.PureComponent { const newSettings = { ...filteredDefaults, ...flattenedSettings }; //store these to be used as autocomplete values later this.settingsKeys = Object.keys(newSettings); - readOnlySettings.forEach(e => delete newSettings[e]); + readOnlySettings.forEach((e) => delete newSettings[e]); //can't change codec on open index if (isOpen) { delete newSettings['index.codec']; @@ -80,7 +80,7 @@ export class EditSettingsJson extends React.PureComponent { const json = this.editor.getValue(); const settings = JSON.parse(json); //don't set if the values have not changed - Object.keys(this.originalSettings).forEach(key => { + Object.keys(this.originalSettings).forEach((key) => { if (_.isEqual(this.originalSettings[key], settings[key])) { delete settings[key]; } @@ -148,7 +148,7 @@ export class EditSettingsJson extends React.PureComponent {
    { + ref={(aceDiv) => { this.aceDiv = aceDiv; }} /> diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/show_json/show_json.container.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/show_json/show_json.container.js index d47661479eaab..39c16ef155fd3 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/show_json/show_json.container.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/show_json/show_json.container.js @@ -16,7 +16,7 @@ import { getIndexStatusByIndexName, } from '../../../../../store/selectors'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const indexName = getDetailPanelIndexName(state); return { error: getDetailPanelError(state), diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/summary/summary.container.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/summary/summary.container.js index 58dc55a384bae..ea85837c19b2a 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/summary/summary.container.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/detail_panel/summary/summary.container.js @@ -9,7 +9,7 @@ import { Summary as PresentationComponent } from './summary'; import { getIndexByIndexName, getDetailPanelIndexName } from '../../../../../store/selectors'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const indexName = getDetailPanelIndexName(state); return { indexName, diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.container.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.container.js index 9ad31d563eb86..e715173f35f5a 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.container.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.container.js @@ -34,7 +34,7 @@ const mapStateToProps = (state, ownProps) => { const indexStatusByName = {}; const { indexNames } = ownProps; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { indexStatusByName[indexName] = getIndexStatusByIndexName(state, indexName); }); @@ -72,7 +72,7 @@ const mapDispatchToProps = (dispatch, { indexNames }) => { unfreezeIndices: () => { dispatch(unfreezeIndices({ indexNames })); }, - forcemergeIndices: maxNumSegments => { + forcemergeIndices: (maxNumSegments) => { dispatch(forcemergeIndices({ indexNames, maxNumSegments })); }, showSettings: () => { diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.js index a351d39b123a8..effd80c39f0d1 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_actions_context_menu/index_actions_context_menu.js @@ -43,7 +43,7 @@ export class IndexActionsContextMenu extends Component { }); this.props.resetSelection && this.props.resetSelection(); }; - confirmAction = isActionConfirmed => { + confirmAction = (isActionConfirmed) => { this.setState({ isActionConfirmed }); }; panels({ services: { extensionsService } }) { @@ -66,11 +66,11 @@ export class IndexActionsContextMenu extends Component { unfreezeIndices, hasSystemIndex, } = this.props; - const allOpen = all(indexNames, indexName => { + const allOpen = all(indexNames, (indexName) => { return indexStatusByName[indexName] === INDEX_OPEN; }); - const allFrozen = all(indices, index => index.isFrozen); - const allUnfrozen = all(indices, index => !index.isFrozen); + const allFrozen = all(indices, (index) => index.isFrozen); + const allUnfrozen = all(indices, (index) => !index.isFrozen); const selectedIndexCount = indexNames.length; const items = []; if (!detailPanel && selectedIndexCount === 1) { @@ -210,7 +210,7 @@ export class IndexActionsContextMenu extends Component { this.setState({ renderConfirmModal: this.renderConfirmDeleteModal }); }, }); - extensionsService.actions.forEach(actionExtension => { + extensionsService.actions.forEach((actionExtension) => { const actionExtensionDefinition = actionExtension({ indices, reloadIndices, @@ -242,7 +242,7 @@ export class IndexActionsContextMenu extends Component { } } }); - items.forEach(item => { + items.forEach((item) => { item['data-test-subj'] = 'indexTableContextMenuButton'; }); const panelTree = { @@ -257,12 +257,12 @@ export class IndexActionsContextMenu extends Component { } onButtonClick = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; - closePopoverAndExecute = func => { + closePopoverAndExecute = (func) => { this.setState({ isPopoverOpen: false, renderConfirmModal: false, @@ -341,7 +341,7 @@ export class IndexActionsContextMenu extends Component {

      - {indexNames.map(indexName => ( + {indexNames.map((indexName) => (
    • {indexName}
    • ))}
    @@ -384,7 +384,7 @@ export class IndexActionsContextMenu extends Component { helpText={helpText} > { + onChange={(event) => { this.setState({ forcemergeSegments: event.target.value }); }} min={1} @@ -413,7 +413,7 @@ export class IndexActionsContextMenu extends Component {

      - {indexNames.map(indexName => ( + {indexNames.map((indexName) => (
    • {indexName}
    • ))}
    @@ -438,7 +438,7 @@ export class IndexActionsContextMenu extends Component {

      - {indexNames.map(indexName => ( + {indexNames.map((indexName) => (
    • {indexName} {isSystemIndexByName[indexName] ? ( @@ -484,7 +484,7 @@ export class IndexActionsContextMenu extends Component { /> } checked={isActionConfirmed} - onChange={e => this.confirmAction(e.target.checked)} + onChange={(e) => this.confirmAction(e.target.checked)} /> @@ -572,7 +572,7 @@ export class IndexActionsContextMenu extends Component {

        - {indexNames.map(indexName => ( + {indexNames.map((indexName) => (
      • {indexName} {isSystemIndexByName[indexName] ? ( @@ -618,7 +618,7 @@ export class IndexActionsContextMenu extends Component { /> } checked={isActionConfirmed} - onChange={e => this.confirmAction(e.target.checked)} + onChange={(e) => this.confirmAction(e.target.checked)} /> @@ -668,7 +668,7 @@ export class IndexActionsContextMenu extends Component {

          - {indexNames.map(indexName => ( + {indexNames.map((indexName) => (
        • {indexName}
        • ))}
        @@ -701,7 +701,7 @@ export class IndexActionsContextMenu extends Component { render() { return ( - {appDependencies => { + {(appDependencies) => { const { indexNames } = this.props; const selectedIndexCount = indexNames.length; const { diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.container.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.container.js index f6250a7a6e25c..44d811f490d9d 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.container.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.container.js @@ -34,7 +34,7 @@ import { import { IndexTable as PresentationComponent } from './index_table'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { return { allIndices: getIndicesAsArray(state), isDetailPanelOpen: isDetailPanelOpen(state), @@ -51,27 +51,27 @@ const mapStateToProps = state => { }; }; -const mapDispatchToProps = dispatch => { +const mapDispatchToProps = (dispatch) => { return { - filterChanged: filter => { + filterChanged: (filter) => { dispatch(filterChanged({ filter })); }, - pageChanged: pageNumber => { + pageChanged: (pageNumber) => { dispatch(pageChanged({ pageNumber })); }, - pageSizeChanged: pageSize => { + pageSizeChanged: (pageSize) => { dispatch(pageSizeChanged({ pageSize })); }, sortChanged: (sortField, isSortAscending) => { dispatch(sortChanged({ sortField, isSortAscending })); }, - showHiddenIndicesChanged: showHiddenIndices => { + showHiddenIndicesChanged: (showHiddenIndices) => { dispatch(showHiddenIndicesChanged({ showHiddenIndices })); }, toggleChanged: (toggleName, toggleValue) => { dispatch(toggleChanged({ toggleName, toggleValue })); }, - openDetailPanel: indexName => { + openDetailPanel: (indexName) => { dispatch(openDetailPanel({ indexName })); }, closeDetailPanel: () => { diff --git a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.js b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.js index 799f3a6bcb535..0d005b2864863 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.js +++ b/x-pack/plugins/index_management/public/application/sections/home/index_list/index_table/index_table.js @@ -72,15 +72,15 @@ export class IndexTable extends Component { static getDerivedStateFromProps(props, state) { // Deselct any indices which no longer exist, e.g. they've been deleted. const { selectedIndicesMap } = state; - const indexNames = props.indices.map(index => index.name); + const indexNames = props.indices.map((index) => index.name); const selectedIndexNames = Object.keys(selectedIndicesMap); - const missingIndexNames = selectedIndexNames.filter(selectedIndexName => { + const missingIndexNames = selectedIndexNames.filter((selectedIndexName) => { return !indexNames.includes(selectedIndexName); }); if (missingIndexNames.length) { const newMap = { ...selectedIndicesMap }; - missingIndexNames.forEach(missingIndexName => delete newMap[missingIndexName]); + missingIndexNames.forEach((missingIndexName) => delete newMap[missingIndexName]); return { selectedIndicesMap: newMap }; } @@ -127,7 +127,7 @@ export class IndexTable extends Component { componentWillUnmount() { clearInterval(this.interval); } - onSort = column => { + onSort = (column) => { const { sortField, isSortAscending, sortChanged } = this.props; const newIsSortAscending = sortField === column ? !isSortAscending : true; @@ -164,7 +164,7 @@ export class IndexTable extends Component { this.setState({ filterError: null }); } }; - getFilters = extensionsService => { + getFilters = (extensionsService) => { const { allIndices } = this.props; return extensionsService.filters.reduce((accum, filterExtension) => { const filtersToAdd = filterExtension(allIndices); @@ -186,7 +186,7 @@ export class IndexTable extends Component { }); }; - toggleItem = name => { + toggleItem = (name) => { this.setState(({ selectedIndicesMap }) => { const newMap = { ...selectedIndicesMap }; if (newMap[name]) { @@ -200,13 +200,13 @@ export class IndexTable extends Component { }); }; - isItemSelected = name => { + isItemSelected = (name) => { return !!this.state.selectedIndicesMap[name]; }; areAllItemsSelected = () => { const { indices } = this.props; - const indexOfUnselectedItem = indices.findIndex(index => !this.isItemSelected(index.name)); + const indexOfUnselectedItem = indices.findIndex((index) => !this.isItemSelected(index.name)); return indexOfUnselectedItem === -1; }; @@ -253,7 +253,7 @@ export class IndexTable extends Component { } buildRowCells(index, appServices) { - return Object.keys(HEADERS).map(fieldName => { + return Object.keys(HEADERS).map((fieldName) => { const { name } = index; const value = index[fieldName]; @@ -351,7 +351,7 @@ export class IndexTable extends Component { buildRows(appServices) { const { indices = [], detailPanelIndexName } = this.props; - return indices.map(index => { + return indices.map((index) => { const { name } = index; return ( { + onItemSelectionChanged = (selectedIndices) => { this.setState({ selectedIndices }); }; @@ -406,7 +406,7 @@ export class IndexTable extends Component { id={`checkboxToggles-${name}`} data-test-subj={`checkboxToggles-${name}`} checked={toggleNameToVisibleMap[name]} - onChange={event => toggleChanged(name, event.target.checked)} + onChange={(event) => toggleChanged(name, event.target.checked)} label={label} /> @@ -470,7 +470,7 @@ export class IndexTable extends Component { {(indicesLoading && allIndices.length === 0) || indicesError ? null : ( - {extensionsService.toggles.map(toggle => { + {extensionsService.toggles.map((toggle) => { return this.renderToggleControl(toggle); })} @@ -478,7 +478,7 @@ export class IndexTable extends Component { id="checkboxShowHiddenIndices" data-test-subj="indexTableIncludeHiddenIndicesToggle" checked={showHiddenIndices} - onChange={event => showHiddenIndicesChanged(event.target.checked)} + onChange={(event) => showHiddenIndicesChanged(event.target.checked)} label={ = ({ {managedTemplateCallout} - {TABS.map(tab => ( + {TABS.map((tab) => ( { uiMetricService.trackMetric('click', tabToUiMetricMap[tab.id]); @@ -192,7 +192,7 @@ export const TemplateDetails: React.FunctionComponent = ({ {templateToDelete && templateToDelete.length > 0 ? ( { + callback={(data) => { if (data && data.hasDeletedTemplates) { reload(); } else { @@ -247,7 +247,7 @@ export const TemplateDetails: React.FunctionComponent = ({ data-test-subj="manageTemplateButton" iconType="arrowDown" iconSide="right" - onClick={() => setIsPopOverOpen(prev => !prev)} + onClick={() => setIsPopOverOpen((prev) => !prev)} > (templates ? templates.filter(template => !template.name.startsWith('.')) : []), + () => (templates ? templates.filter((template) => !template.name.startsWith('.')) : []), [templates] ); @@ -128,7 +128,7 @@ export const TemplateList: React.FunctionComponent setShowSystemTemplates(event.target.checked)} + onChange={(event) => setShowSystemTemplates(event.target.checked)} label={ = ({ values={{ count: selection.length }} /> - ) : ( - undefined - ), + ) : undefined, toolsRight: [ = ({ {templatesToDelete && templatesToDelete.length > 0 ? ( { + callback={(data) => { if (data && data.hasDeletedTemplates) { reload(); } else { diff --git a/x-pack/plugins/index_management/public/application/store/actions/clear_cache_indices.js b/x-pack/plugins/index_management/public/application/store/actions/clear_cache_indices.js index 2200b21ba39c2..4f606e0bf76a2 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/clear_cache_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/clear_cache_indices.js @@ -13,7 +13,7 @@ import { notificationService } from '../../services/notification'; import { clearRowStatus, reloadIndices } from '../actions'; export const clearCacheIndicesStart = createAction('INDEX_MANAGEMENT_CLEAR_CACHE_INDICES_START'); -export const clearCacheIndices = ({ indexNames }) => async dispatch => { +export const clearCacheIndices = ({ indexNames }) => async (dispatch) => { dispatch(clearCacheIndicesStart({ indexNames })); try { await request(indexNames); diff --git a/x-pack/plugins/index_management/public/application/store/actions/close_indices.js b/x-pack/plugins/index_management/public/application/store/actions/close_indices.js index b1016fe054c95..8ba42c9af41b0 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/close_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/close_indices.js @@ -11,7 +11,7 @@ import { notificationService } from '../../services/notification'; import { clearRowStatus, reloadIndices } from '../actions'; export const closeIndicesStart = createAction('INDEX_MANAGEMENT_CLOSE_INDICES_START'); -export const closeIndices = ({ indexNames }) => async dispatch => { +export const closeIndices = ({ indexNames }) => async (dispatch) => { dispatch(closeIndicesStart({ indexNames })); try { await request(indexNames); diff --git a/x-pack/plugins/index_management/public/application/store/actions/delete_indices.js b/x-pack/plugins/index_management/public/application/store/actions/delete_indices.js index df3c134f3ca76..491054602918c 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/delete_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/delete_indices.js @@ -11,7 +11,7 @@ import { notificationService } from '../../services/notification'; import { clearRowStatus } from '../actions'; export const deleteIndicesSuccess = createAction('INDEX_MANAGEMENT_DELETE_INDICES_SUCCESS'); -export const deleteIndices = ({ indexNames }) => async dispatch => { +export const deleteIndices = ({ indexNames }) => async (dispatch) => { try { await request(indexNames); } catch (error) { diff --git a/x-pack/plugins/index_management/public/application/store/actions/edit_index_settings.js b/x-pack/plugins/index_management/public/application/store/actions/edit_index_settings.js index 0e0d36d1ec0e2..8d220a150e415 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/edit_index_settings.js +++ b/x-pack/plugins/index_management/public/application/store/actions/edit_index_settings.js @@ -9,7 +9,7 @@ import { loadIndexSettings as request } from '../../services'; import { notificationService } from '../../services/notification'; import { loadIndexDataSuccess } from './load_index_data'; -export const editIndexSettings = ({ indexName }) => async dispatch => { +export const editIndexSettings = ({ indexName }) => async (dispatch) => { let indexSettings; try { indexSettings = await request(indexName); diff --git a/x-pack/plugins/index_management/public/application/store/actions/extension_action.js b/x-pack/plugins/index_management/public/application/store/actions/extension_action.js index 277a71999492f..63f8f134aa76f 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/extension_action.js +++ b/x-pack/plugins/index_management/public/application/store/actions/extension_action.js @@ -8,11 +8,9 @@ import { reloadIndices } from '../actions'; import { notificationService } from '../../services/notification'; import { httpService } from '../../services/http'; -export const performExtensionAction = ({ - requestMethod, - indexNames, - successMessage, -}) => async dispatch => { +export const performExtensionAction = ({ requestMethod, indexNames, successMessage }) => async ( + dispatch +) => { try { await requestMethod(indexNames, httpService.httpClient); } catch (error) { diff --git a/x-pack/plugins/index_management/public/application/store/actions/flush_indices.js b/x-pack/plugins/index_management/public/application/store/actions/flush_indices.js index 15e92bb965923..b77144e9614ce 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/flush_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/flush_indices.js @@ -12,7 +12,7 @@ import { notificationService } from '../../services/notification'; export const flushIndicesStart = createAction('INDEX_MANAGEMENT_FLUSH_INDICES_START'); -export const flushIndices = ({ indexNames }) => async dispatch => { +export const flushIndices = ({ indexNames }) => async (dispatch) => { dispatch(flushIndicesStart({ indexNames })); try { await request(indexNames); diff --git a/x-pack/plugins/index_management/public/application/store/actions/forcemerge_indices.js b/x-pack/plugins/index_management/public/application/store/actions/forcemerge_indices.js index aa8753cbee905..757d133f38f32 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/forcemerge_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/forcemerge_indices.js @@ -12,7 +12,7 @@ import { notificationService } from '../../services/notification'; export const forcemergeIndicesStart = createAction('INDEX_MANAGEMENT_FORCEMERGE_INDICES_START'); -export const forcemergeIndices = ({ indexNames, maxNumSegments }) => async dispatch => { +export const forcemergeIndices = ({ indexNames, maxNumSegments }) => async (dispatch) => { dispatch(forcemergeIndicesStart({ indexNames })); try { await request(indexNames, maxNumSegments); diff --git a/x-pack/plugins/index_management/public/application/store/actions/freeze_indices.js b/x-pack/plugins/index_management/public/application/store/actions/freeze_indices.js index 801390206841d..52ec78aaa3460 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/freeze_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/freeze_indices.js @@ -12,7 +12,7 @@ import { notificationService } from '../../services/notification'; export const freezeIndicesStart = createAction('INDEX_MANAGEMENT_FREEZE_INDICES_START'); -export const freezeIndices = ({ indexNames }) => async dispatch => { +export const freezeIndices = ({ indexNames }) => async (dispatch) => { dispatch(freezeIndicesStart({ indexNames })); try { await request(indexNames); diff --git a/x-pack/plugins/index_management/public/application/store/actions/load_index_data.js b/x-pack/plugins/index_management/public/application/store/actions/load_index_data.js index 26189962d88f1..0472db84400fc 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/load_index_data.js +++ b/x-pack/plugins/index_management/public/application/store/actions/load_index_data.js @@ -10,7 +10,7 @@ import { notificationService } from '../../services/notification'; export const loadIndexDataSuccess = createAction('INDEX_MANAGEMENT_LOAD_INDEX_DATA_SUCCESS'); -export const loadIndexData = ({ indexName, dataType }) => async dispatch => { +export const loadIndexData = ({ indexName, dataType }) => async (dispatch) => { let data; try { data = await request(dataType, indexName); diff --git a/x-pack/plugins/index_management/public/application/store/actions/load_indices.js b/x-pack/plugins/index_management/public/application/store/actions/load_indices.js index f53ff8adc2b85..98134396043f8 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/load_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/load_indices.js @@ -11,7 +11,7 @@ export const loadIndicesStart = createAction('INDEX_MANAGEMENT_LOAD_INDICES_STAR export const loadIndicesSuccess = createAction('INDEX_MANAGEMENT_LOAD_INDICES_SUCCESS'); export const loadIndicesError = createAction('INDEX_MANAGEMENT_LOAD_INDICES_ERROR'); -export const loadIndices = () => async dispatch => { +export const loadIndices = () => async (dispatch) => { dispatch(loadIndicesStart()); let indices; try { diff --git a/x-pack/plugins/index_management/public/application/store/actions/open_indices.js b/x-pack/plugins/index_management/public/application/store/actions/open_indices.js index 76819c100c3c9..16c39b04f71da 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/open_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/open_indices.js @@ -12,7 +12,7 @@ import { notificationService } from '../../services/notification'; export const openIndicesStart = createAction('INDEX_MANAGEMENT_OPEN_INDICES_START'); -export const openIndices = ({ indexNames }) => async dispatch => { +export const openIndices = ({ indexNames }) => async (dispatch) => { dispatch(openIndicesStart({ indexNames })); try { await request(indexNames); diff --git a/x-pack/plugins/index_management/public/application/store/actions/refresh_indices.js b/x-pack/plugins/index_management/public/application/store/actions/refresh_indices.js index d1c2e1be10545..0a937accab7ad 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/refresh_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/refresh_indices.js @@ -12,7 +12,7 @@ import { clearRowStatus, reloadIndices } from '../actions'; import { notificationService } from '../../services/notification'; export const refreshIndicesStart = createAction('INDEX_MANAGEMENT_REFRESH_INDICES_START'); -export const refreshIndices = ({ indexNames }) => async dispatch => { +export const refreshIndices = ({ indexNames }) => async (dispatch) => { dispatch(refreshIndicesStart({ indexNames })); try { await request(indexNames); diff --git a/x-pack/plugins/index_management/public/application/store/actions/reload_indices.js b/x-pack/plugins/index_management/public/application/store/actions/reload_indices.js index b70eb33e32c73..11329ece8f59f 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/reload_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/reload_indices.js @@ -12,7 +12,7 @@ import { loadIndices } from './load_indices'; import { notificationService } from '../../services/notification'; export const reloadIndicesSuccess = createAction('INDEX_MANAGEMENT_RELOAD_INDICES_SUCCESS'); -export const reloadIndices = indexNames => async (dispatch, getState) => { +export const reloadIndices = (indexNames) => async (dispatch, getState) => { let indices; indexNames = indexNames || getIndexNamesForCurrentPage(getState()); try { diff --git a/x-pack/plugins/index_management/public/application/store/actions/unfreeze_indices.js b/x-pack/plugins/index_management/public/application/store/actions/unfreeze_indices.js index f22d7a0067401..953379ca71c5d 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/unfreeze_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/unfreeze_indices.js @@ -12,7 +12,7 @@ import { notificationService } from '../../services/notification'; export const unfreezeIndicesStart = createAction('INDEX_MANAGEMENT_UNFREEZE_INDICES_START'); -export const unfreezeIndices = ({ indexNames }) => async dispatch => { +export const unfreezeIndices = ({ indexNames }) => async (dispatch) => { dispatch(unfreezeIndicesStart({ indexNames })); try { await request(indexNames); diff --git a/x-pack/plugins/index_management/public/application/store/actions/update_index_settings.js b/x-pack/plugins/index_management/public/application/store/actions/update_index_settings.js index 3e92829611780..384edbffdbaf1 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/update_index_settings.js +++ b/x-pack/plugins/index_management/public/application/store/actions/update_index_settings.js @@ -17,7 +17,7 @@ export const updateIndexSettingsError = createAction( 'INDEX_MANAGEMENT_UPDATE_INDEX_SETTINGS_ERROR' ); -export const updateIndexSettings = ({ indexName, settings }) => async dispatch => { +export const updateIndexSettings = ({ indexName, settings }) => async (dispatch) => { if (Object.keys(settings).length !== 0) { try { const { error, message } = await request(indexName, settings); diff --git a/x-pack/plugins/index_management/public/application/store/middlewares/sync_url_hash_query_param.js.ts b/x-pack/plugins/index_management/public/application/store/middlewares/sync_url_hash_query_param.js.ts index 6dd2efe935141..145b4b6c9a8bc 100644 --- a/x-pack/plugins/index_management/public/application/store/middlewares/sync_url_hash_query_param.js.ts +++ b/x-pack/plugins/index_management/public/application/store/middlewares/sync_url_hash_query_param.js.ts @@ -8,7 +8,7 @@ import { Middleware } from 'redux'; // @ts-ignore import { showHiddenIndicesChanged } from '../actions'; -export const syncUrlHashQueryParam: Middleware = () => next => action => { +export const syncUrlHashQueryParam: Middleware = () => (next) => (action) => { if (action.type === String(showHiddenIndicesChanged)) { const { url, query } = q.parseUrl(window.location.hash); if (action.payload.showHiddenIndices) { diff --git a/x-pack/plugins/index_management/public/application/store/reducers/detail_panel.js b/x-pack/plugins/index_management/public/application/store/reducers/detail_panel.js index c38971a633954..d28623636f5a8 100644 --- a/x-pack/plugins/index_management/public/application/store/reducers/detail_panel.js +++ b/x-pack/plugins/index_management/public/application/store/reducers/detail_panel.js @@ -29,7 +29,7 @@ import { deleteIndicesSuccess } from '../actions/delete_indices'; const defaultState = {}; -export const getDetailPanelReducer = uiMetricService => +export const getDetailPanelReducer = (uiMetricService) => handleActions( { [deleteIndicesSuccess](state, action) { diff --git a/x-pack/plugins/index_management/public/application/store/reducers/indices.js b/x-pack/plugins/index_management/public/application/store/reducers/indices.js index 7007c8c42bffb..4bea9ba464888 100644 --- a/x-pack/plugins/index_management/public/application/store/reducers/indices.js +++ b/x-pack/plugins/index_management/public/application/store/reducers/indices.js @@ -20,7 +20,7 @@ const byId = handleActions( const { indexNames } = action.payload; const newState = {}; - Object.values(state).forEach(index => { + Object.values(state).forEach((index) => { if (!indexNames.includes(index.name)) { newState[index.name] = index; } @@ -31,7 +31,7 @@ const byId = handleActions( [loadIndicesSuccess](state, action) { const { indices } = action.payload; const newState = {}; - indices.forEach(index => { + indices.forEach((index) => { newState[index.name] = index; }); @@ -41,7 +41,7 @@ const byId = handleActions( const { indices } = action.payload; const newState = {}; - indices.forEach(index => { + indices.forEach((index) => { newState[index.name] = index; }); @@ -59,7 +59,7 @@ const allIds = handleActions( [deleteIndicesSuccess](state, action) { const { indexNames } = action.payload; const newState = []; - state.forEach(indexName => { + state.forEach((indexName) => { if (!indexNames.includes(indexName)) { newState.push(indexName); } @@ -68,7 +68,7 @@ const allIds = handleActions( }, [loadIndicesSuccess](state, action) { const { indices } = action.payload; - return indices.map(index => index.name); + return indices.map((index) => index.name); }, [reloadIndicesSuccess](state) { // the set of IDs should never change when refreshing indexes. diff --git a/x-pack/plugins/index_management/public/application/store/reducers/row_status.js b/x-pack/plugins/index_management/public/application/store/reducers/row_status.js index 31d3e3c6e082c..875a6c6c2edc3 100644 --- a/x-pack/plugins/index_management/public/application/store/reducers/row_status.js +++ b/x-pack/plugins/index_management/public/application/store/reducers/row_status.js @@ -31,7 +31,7 @@ export const rowStatus = handleActions( [clearRowStatus](state, action) { const { indexNames } = action.payload; const newState = { ...state }; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { delete newState[indexName]; }); return newState; @@ -40,7 +40,7 @@ export const rowStatus = handleActions( const { indexNames } = action.payload; const statuses = {}; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { statuses[indexName] = INDEX_CLOSING; }); @@ -53,7 +53,7 @@ export const rowStatus = handleActions( const { indexNames } = action.payload; const statuses = {}; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { statuses[indexName] = INDEX_OPENING; }); @@ -66,7 +66,7 @@ export const rowStatus = handleActions( const { indexNames } = action.payload; const statuses = {}; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { statuses[indexName] = INDEX_REFRESHING; }); @@ -79,7 +79,7 @@ export const rowStatus = handleActions( const { indexNames } = action.payload; const statuses = {}; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { statuses[indexName] = INDEX_FLUSHING; }); @@ -92,7 +92,7 @@ export const rowStatus = handleActions( const { indexNames } = action.payload; const statuses = {}; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { statuses[indexName] = INDEX_FORCEMERGING; }); @@ -105,7 +105,7 @@ export const rowStatus = handleActions( const { indexNames } = action.payload; const statuses = {}; - indexNames.forEach(indexName => { + indexNames.forEach((indexName) => { statuses[indexName] = INDEX_CLEARING_CACHE; }); diff --git a/x-pack/plugins/index_management/public/application/store/selectors/index.js b/x-pack/plugins/index_management/public/application/store/selectors/index.js index 0f481c55782b0..c1011680d4da2 100644 --- a/x-pack/plugins/index_management/public/application/store/selectors/index.js +++ b/x-pack/plugins/index_management/public/application/store/selectors/index.js @@ -13,42 +13,42 @@ import { sortTable } from '../../services'; // TODO: Refactor and export all the app selectors through the app dependencies context let extensionsService; -export const setExtensionsService = _extensionsService => { +export const setExtensionsService = (_extensionsService) => { extensionsService = _extensionsService; }; // End hack -export const getDetailPanelData = state => state.detailPanel.data; -export const getDetailPanelError = state => state.detailPanel.error; -export const getDetailPanelType = state => state.detailPanel.panelType; -export const isDetailPanelOpen = state => !!getDetailPanelType(state); -export const getDetailPanelIndexName = state => state.detailPanel.indexName; -export const getIndices = state => state.indices.byId; -export const indicesLoading = state => state.indices.loading; -export const indicesError = state => state.indices.error; -export const getIndicesAsArray = state => Object.values(state.indices.byId); +export const getDetailPanelData = (state) => state.detailPanel.data; +export const getDetailPanelError = (state) => state.detailPanel.error; +export const getDetailPanelType = (state) => state.detailPanel.panelType; +export const isDetailPanelOpen = (state) => !!getDetailPanelType(state); +export const getDetailPanelIndexName = (state) => state.detailPanel.indexName; +export const getIndices = (state) => state.indices.byId; +export const indicesLoading = (state) => state.indices.loading; +export const indicesError = (state) => state.indices.error; +export const getIndicesAsArray = (state) => Object.values(state.indices.byId); export const getIndicesByName = (state, indexNames) => { const indices = getIndices(state); - return indexNames.map(indexName => indices[indexName]); + return indexNames.map((indexName) => indices[indexName]); }; export const getIndexByIndexName = (state, name) => getIndices(state)[name]; -export const getFilteredIds = state => state.indices.filteredIds; -export const getRowStatuses = state => state.rowStatus; -export const getTableState = state => state.tableState; -export const getAllIds = state => state.indices.allIds; +export const getFilteredIds = (state) => state.indices.filteredIds; +export const getRowStatuses = (state) => state.rowStatus; +export const getTableState = (state) => state.tableState; +export const getAllIds = (state) => state.indices.allIds; export const getIndexStatusByIndexName = (state, indexName) => { const indices = getIndices(state); const { status } = indices[indexName] || {}; return status; }; -export const getIsSystemIndexByName = indexNames => { +export const getIsSystemIndexByName = (indexNames) => { return indexNames.reduce((obj, indexName) => { obj[indexName] = indexName.startsWith('.'); return obj; }, {}); }; -export const hasSystemIndex = indexNames => { - return Boolean(indexNames.find(indexName => indexName.startsWith('.'))); +export const hasSystemIndex = (indexNames) => { + return Boolean(indexNames.find((indexName) => indexName.startsWith('.'))); }; const defaultFilterFields = ['name']; @@ -67,8 +67,8 @@ const filterByToggles = (indices, toggleNameToVisibleMap) => { return indices; } // An index is visible if ANY applicable toggle is visible. - return indices.filter(index => { - return toggleNames.some(toggleName => { + return indices.filter((index) => { + return toggleNames.some((toggleName) => { if (!togglesByName[toggleName].matchIndex(index)) { return true; } @@ -84,18 +84,18 @@ const getFilteredIndices = createSelector( getAllIds, getTableState, (indices, allIds, tableState) => { - let indexArray = allIds.map(indexName => indices[indexName]); + let indexArray = allIds.map((indexName) => indices[indexName]); indexArray = filterByToggles(indexArray, tableState.toggleNameToVisibleMap); const systemFilteredIndexes = tableState.showHiddenIndices ? indexArray - : indexArray.filter(index => !(index.name + '').startsWith('.') && !index.hidden); + : indexArray.filter((index) => !(index.name + '').startsWith('.') && !index.hidden); const filter = tableState.filter || EuiSearchBar.Query.MATCH_ALL; return EuiSearchBar.Query.execute(filter, systemFilteredIndexes, { defaultFields: defaultFilterFields, }); } ); -export const getTotalItems = createSelector(getFilteredIndices, filteredIndices => { +export const getTotalItems = createSelector(getFilteredIndices, (filteredIndices) => { return Object.keys(filteredIndices).length; }); @@ -119,7 +119,7 @@ export const getPageOfIndices = createSelector( ); const { firstItemIndex, lastItemIndex } = pager; const pagedIndexes = sortedIndexes.slice(firstItemIndex, lastItemIndex + 1); - return pagedIndexes.map(index => { + return pagedIndexes.map((index) => { const status = indexStatusLabels[rowStatuses[index.name]] || // user friendly version of row status rowStatuses[index.name] || // row status @@ -133,19 +133,19 @@ export const getPageOfIndices = createSelector( } ); -export const getIndexNamesForCurrentPage = createSelector(getPageOfIndices, pageOfIndices => { - return pageOfIndices.map(index => index.name); +export const getIndexNamesForCurrentPage = createSelector(getPageOfIndices, (pageOfIndices) => { + return pageOfIndices.map((index) => index.name); }); -export const getHasNextPage = createSelector(getPager, pager => { +export const getHasNextPage = createSelector(getPager, (pager) => { return pager.hasNextPage; }); -export const getHasPreviousPage = createSelector(getPager, pager => { +export const getHasPreviousPage = createSelector(getPager, (pager) => { return pager.hasPreviousPage; }); -export const getCurrentPage = createSelector(getPager, pager => { +export const getCurrentPage = createSelector(getPager, (pager) => { return pager.currentPage; }); diff --git a/x-pack/plugins/index_management/public/application/store/store.js b/x-pack/plugins/index_management/public/application/store/store.js index 26a9ff8f997f9..d2f24d50941c6 100644 --- a/x-pack/plugins/index_management/public/application/store/store.js +++ b/x-pack/plugins/index_management/public/application/store/store.js @@ -13,7 +13,7 @@ import { syncUrlHashQueryParam } from './middlewares'; export function indexManagementStore(services) { const toggleNameToVisibleMap = {}; - services.extensionsService.toggles.forEach(toggleExtension => { + services.extensionsService.toggles.forEach((toggleExtension) => { toggleNameToVisibleMap[toggleExtension.name] = false; }); const initialState = { tableState: { ...defaultTableState, toggleNameToVisibleMap } }; diff --git a/x-pack/plugins/index_management/public/plugin.ts b/x-pack/plugins/index_management/public/plugin.ts index 5fb8ce7207729..94d9bccdc63ca 100644 --- a/x-pack/plugins/index_management/public/plugin.ts +++ b/x-pack/plugins/index_management/public/plugin.ts @@ -52,7 +52,7 @@ export class IndexMgmtUIPlugin { id: PLUGIN.id, title: i18n.translate('xpack.idxMgmt.appTitle', { defaultMessage: 'Index Management' }), order: 0, - mount: async params => { + mount: async (params) => { const { mountManagementSection } = await import('./application/mount_management_section'); const services = { httpService, diff --git a/x-pack/plugins/index_management/server/lib/fetch_indices.ts b/x-pack/plugins/index_management/server/lib/fetch_indices.ts index 1f62680a41cbc..b52a63a414967 100644 --- a/x-pack/plugins/index_management/server/lib/fetch_indices.ts +++ b/x-pack/plugins/index_management/server/lib/fetch_indices.ts @@ -71,7 +71,7 @@ async function fetchIndicesCall( }); // The two responses should be equal in the number of indices returned - return catHits.map(hit => { + return catHits.map((hit) => { const index = indices[hit.index]; const aliases = Object.keys(index.aliases); diff --git a/x-pack/plugins/index_management/server/services/license.ts b/x-pack/plugins/index_management/server/services/license.ts index 31d3654c51e3e..2d863e283d440 100644 --- a/x-pack/plugins/index_management/server/services/license.ts +++ b/x-pack/plugins/index_management/server/services/license.ts @@ -35,7 +35,7 @@ export class License { { pluginId, minimumLicenseType, defaultErrorMessage }: SetupSettings, { licensing, logger }: { licensing: LicensingPluginSetup; logger: Logger } ) { - licensing.license$.subscribe(license => { + licensing.license$.subscribe((license) => { const { state, message } = license.check(pluginId, minimumLicenseType); const hasRequiredLicense = state === 'valid'; diff --git a/x-pack/plugins/infra/common/http_api/source_api.ts b/x-pack/plugins/infra/common/http_api/source_api.ts index 218f8cebc9869..2c7d15d317cac 100644 --- a/x-pack/plugins/infra/common/http_api/source_api.ts +++ b/x-pack/plugins/infra/common/http_api/source_api.ts @@ -17,14 +17,14 @@ export const TimestampFromString = new rt.Type( (input, context) => pipe( rt.string.validate(input, context), - chain(stringInput => { + chain((stringInput) => { const momentValue = moment(stringInput); return momentValue.isValid() ? rt.success(momentValue.valueOf()) : rt.failure(stringInput, context); }) ), - output => new Date(output).toISOString() + (output) => new Date(output).toISOString() ); /** diff --git a/x-pack/plugins/infra/common/inventory_models/index.ts b/x-pack/plugins/infra/common/inventory_models/index.ts index d9fd8fa465b7a..1ddf92516c409 100644 --- a/x-pack/plugins/infra/common/inventory_models/index.ts +++ b/x-pack/plugins/infra/common/inventory_models/index.ts @@ -18,7 +18,7 @@ export { metrics } from './metrics'; export const inventoryModels = [host, pod, container, awsEC2, awsS3, awsRDS, awsSQS]; export const findInventoryModel = (type: InventoryItemType) => { - const model = inventoryModels.find(m => m.id === type); + const model = inventoryModels.find((m) => m.id === type); if (!model) { throw new Error( i18n.translate('xpack.infra.inventoryModels.findInventoryModel.error', { diff --git a/x-pack/plugins/infra/common/inventory_models/shared/components/metrics_and_groupby_toolbar_items.tsx b/x-pack/plugins/infra/common/inventory_models/shared/components/metrics_and_groupby_toolbar_items.tsx index 4a4accc6edfed..fcb29e3eb1c02 100644 --- a/x-pack/plugins/infra/common/inventory_models/shared/components/metrics_and_groupby_toolbar_items.tsx +++ b/x-pack/plugins/infra/common/inventory_models/shared/components/metrics_and_groupby_toolbar_items.tsx @@ -28,7 +28,7 @@ interface Props extends ToolbarProps { export const MetricsAndGroupByToolbarItems = (props: Props) => { const metricOptions = useMemo( () => - props.metricTypes.map(toMetricOpt).filter(v => v) as Array<{ text: string; value: string }>, + props.metricTypes.map(toMetricOpt).filter((v) => v) as Array<{ text: string; value: string }>, [props.metricTypes] ); diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx index 4151fd8d6cf49..f4c7332a88e1d 100644 --- a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression.tsx @@ -66,7 +66,7 @@ const defaultExpression = { timeUnit: 'm', } as MetricExpression; -export const Expressions: React.FC = props => { +export const Expressions: React.FC = (props) => { const { setAlertParams, alertParams, errors, alertsContext } = props; const { source, createDerivedIndexPattern } = useSourceViaHttp({ sourceId: 'default', @@ -155,7 +155,7 @@ export const Expressions: React.FC = props => { const updateTimeSize = useCallback( (ts: number | undefined) => { const criteria = - alertParams.criteria?.map(c => ({ + alertParams.criteria?.map((c) => ({ ...c, timeSize: ts, })) || []; @@ -168,7 +168,7 @@ export const Expressions: React.FC = props => { const updateTimeUnit = useCallback( (tu: string) => { const criteria = - alertParams.criteria?.map(c => ({ + alertParams.criteria?.map((c) => ({ ...c, timeUnit: tu, })) || []; @@ -183,7 +183,7 @@ export const Expressions: React.FC = props => { if (md && md.currentOptions?.metrics) { setAlertParams( 'criteria', - md.currentOptions.metrics.map(metric => ({ + md.currentOptions.metrics.map((metric) => ({ metric: metric.field, comparator: Comparator.GT, threshold: [], @@ -322,7 +322,7 @@ export const Expressions: React.FC = props => { } checked={alertParams.alertOnNoData} - onChange={e => setAlertParams('alertOnNoData', e.target.checked)} + onChange={(e) => setAlertParams('alertOnNoData', e.target.checked)} /> diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.tsx b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.tsx index 99f5aa972758d..64a5792689d52 100644 --- a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.tsx @@ -120,7 +120,7 @@ export const ExpressionChart: React.FC = ({ const series = { ...firstSeries, - rows: firstSeries.rows.map(row => { + rows: firstSeries.rows.map((row) => { const newRow: MetricsExplorerRow = { ...row }; thresholds.forEach((thresholdValue, index) => { newRow[getMetricId(metric, `threshold_${index}`)] = thresholdValue; @@ -161,7 +161,7 @@ export const ExpressionChart: React.FC = ({ ({ + dataValues={thresholds.map((threshold) => ({ dataValue: threshold, }))} style={{ diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx index be0f5f88a2b55..653b9e1d5c308 100644 --- a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx @@ -56,7 +56,7 @@ const StyledExpression = euiStyled.div` padding: 0 4px; `; -export const ExpressionRow: React.FC = props => { +export const ExpressionRow: React.FC = (props) => { const [isExpanded, setRowState] = useState(true); const toggleRowState = useCallback(() => setRowState(!isExpanded), [isExpanded]); const { @@ -102,7 +102,7 @@ export const ExpressionRow: React.FC = props => { ); const updateThreshold = useCallback( - t => { + (t) => { if (t.join() !== expression.threshold.join()) { setAlertParams(expressionId, { ...expression, threshold: t }); } @@ -136,7 +136,7 @@ export const ExpressionRow: React.FC = props => { ({ + fields={fields.map((f) => ({ normalizedType: f.type, name: f.name, }))} diff --git a/x-pack/plugins/infra/public/components/alerting/inventory/expression.tsx b/x-pack/plugins/infra/public/components/alerting/inventory/expression.tsx index 97c0bb98962d4..f4fab113cdd17 100644 --- a/x-pack/plugins/infra/public/components/alerting/inventory/expression.tsx +++ b/x-pack/plugins/infra/public/components/alerting/inventory/expression.tsx @@ -85,7 +85,7 @@ const defaultExpression = { timeUnit: 'm', } as InventoryMetricConditions; -export const Expressions: React.FC = props => { +export const Expressions: React.FC = (props) => { const { setAlertParams, alertParams, errors, alertsContext } = props; const { source, createDerivedIndexPattern } = useSourceViaHttp({ sourceId: 'default', @@ -155,7 +155,7 @@ export const Expressions: React.FC = props => { const updateTimeSize = useCallback( (ts: number | undefined) => { - const criteria = alertParams.criteria.map(c => ({ + const criteria = alertParams.criteria.map((c) => ({ ...c, timeSize: ts, })); @@ -167,7 +167,7 @@ export const Expressions: React.FC = props => { const updateTimeUnit = useCallback( (tu: string) => { - const criteria = alertParams.criteria.map(c => ({ + const criteria = alertParams.criteria.map((c) => ({ ...c, timeUnit: tu, })); @@ -357,7 +357,7 @@ const StyledExpression = euiStyled.div` padding: 0 4px; `; -export const ExpressionRow: React.FC = props => { +export const ExpressionRow: React.FC = (props) => { const { setAlertParams, expression, errors, expressionId, remove, canDelete } = props; const { metric, comparator = Comparator.GT, threshold = [] } = expression; @@ -376,7 +376,7 @@ export const ExpressionRow: React.FC = props => { ); const updateThreshold = useCallback( - t => { + (t) => { if (t.join() !== expression.threshold.join()) { setAlertParams(expressionId, { ...expression, threshold: t }); } @@ -422,10 +422,10 @@ export const ExpressionRow: React.FC = props => { v?.value === metric)?.text || '', + text: ofFields.find((v) => v?.value === metric)?.text || '', }} metrics={ - ofFields.filter(m => m !== undefined && m.value !== undefined) as Array<{ + ofFields.filter((m) => m !== undefined && m.value !== undefined) as Array<{ value: SnapshotMetricType; text: string; }> diff --git a/x-pack/plugins/infra/public/components/alerting/inventory/metric.tsx b/x-pack/plugins/infra/public/components/alerting/inventory/metric.tsx index 2c72c658ce093..ff859a95a3d9d 100644 --- a/x-pack/plugins/infra/public/components/alerting/inventory/metric.tsx +++ b/x-pack/plugins/infra/public/components/alerting/inventory/metric.tsx @@ -49,7 +49,7 @@ export const MetricExpression = ({ metric, metrics, errors, onChange, popupPosit value: '', }; - const availablefieldsOptions = metrics.map(m => { + const availablefieldsOptions = metrics.map((m) => { return { label: m.text, value: m.value }; }, []); @@ -99,10 +99,10 @@ export const MetricExpression = ({ metric, metrics, errors, onChange, popupPosit options={availablefieldsOptions} noSuggestions={!availablefieldsOptions.length} selectedOptions={ - metric ? availablefieldsOptions.filter(a => a.value === metric.value) : [] + metric ? availablefieldsOptions.filter((a) => a.value === metric.value) : [] } renderOption={(o: any) => o.label} - onChange={selectedOptions => { + onChange={(selectedOptions) => { if (selectedOptions.length > 0) { onChange(selectedOptions[0].value as SnapshotMetricType); setAggFieldPopoverOpen(false); diff --git a/x-pack/plugins/infra/public/components/alerting/inventory/node_type.tsx b/x-pack/plugins/infra/public/components/alerting/inventory/node_type.tsx index 1623fc4e24dcb..9c215b89f4634 100644 --- a/x-pack/plugins/infra/public/components/alerting/inventory/node_type.tsx +++ b/x-pack/plugins/infra/public/components/alerting/inventory/node_type.tsx @@ -75,11 +75,11 @@ export const NodeTypeExpression = ({ data-test-subj="forExpressionSelect" value={value} fullWidth - onChange={e => { + onChange={(e) => { onChange(e.target.value as InventoryItemType); setAggTypePopoverOpen(false); }} - options={Object.values(options).map(o => o)} + options={Object.values(options).map((o) => o)} />
    diff --git a/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/criterion.tsx b/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/criterion.tsx index e8cafecd94db1..66bde380a6d9e 100644 --- a/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/criterion.tsx +++ b/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/criterion.tsx @@ -81,7 +81,7 @@ const getCompatibleComparatorsForField = (fieldInfo: IFieldType | undefined) => }; const getFieldInfo = (fields: IFieldType[], fieldName: string): IFieldType | undefined => { - return fields.find(field => { + return fields.find((field) => { return field.name === fieldName; }); }; @@ -109,7 +109,7 @@ export const Criterion: React.FC = ({ const [isComparatorPopoverOpen, setIsComparatorPopoverOpen] = useState(false); const fieldOptions = useMemo(() => { - return fields.map(field => { + return fields.map((field) => { return { value: field.name, text: field.name }; }); }, [fields]); @@ -123,7 +123,7 @@ export const Criterion: React.FC = ({ }, [fieldInfo]); const handleFieldChange = useCallback( - e => { + (e) => { const fieldName = e.target.value; const nextFieldInfo = getFieldInfo(fields, fieldName); // If the field information we're dealing with has changed, reset the comparator and value. @@ -219,7 +219,7 @@ export const Criterion: React.FC = ({ + onChange={(e) => updateCriterion(idx, { comparator: e.target.value as Comparator }) } options={compatibleComparatorOptions} @@ -232,7 +232,7 @@ export const Criterion: React.FC = ({ { + onChange={(e) => { const number = parseInt(e.target.value, 10); updateCriterion(idx, { value: number ? number : undefined }); }} @@ -241,7 +241,7 @@ export const Criterion: React.FC = ({ updateCriterion(idx, { value: e.target.value })} + onChange={(e) => updateCriterion(idx, { value: e.target.value })} /> )} diff --git a/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/document_count.tsx b/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/document_count.tsx index f80781f5a68d7..ff6a8e7e55fd6 100644 --- a/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/document_count.tsx +++ b/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/document_count.tsx @@ -86,7 +86,7 @@ export const DocumentCount: React.FC = ({ comparator, value, updateCount, updateCount({ comparator: e.target.value as Comparator })} + onChange={(e) => updateCount({ comparator: e.target.value as Comparator })} options={getComparatorOptions()} />
    @@ -118,7 +118,7 @@ export const DocumentCount: React.FC = ({ comparator, value, updateCount, { + onChange={(e) => { const number = parseInt(e.target.value, 10); updateCount({ value: number ? number : undefined }); }} diff --git a/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/editor.tsx b/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/editor.tsx index 06855cc7e765d..cc87167b10a96 100644 --- a/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/editor.tsx +++ b/x-pack/plugins/infra/public/components/alerting/logs/expression_editor/editor.tsx @@ -57,7 +57,7 @@ const DEFAULT_EXPRESSION = { timeUnit: 'm', }; -export const ExpressionEditor: React.FC = props => { +export const ExpressionEditor: React.FC = (props) => { const isInternal = props.alertsContext.metadata?.isInternal; const [sourceId] = useSourceId(); @@ -78,7 +78,7 @@ export const ExpressionEditor: React.FC = props => { ); }; -export const SourceStatusWrapper: React.FC = props => { +export const SourceStatusWrapper: React.FC = (props) => { const { initialize, isLoadingSourceStatus, @@ -121,7 +121,7 @@ export const SourceStatusWrapper: React.FC = props => { ); }; -export const Editor: React.FC = props => { +export const Editor: React.FC = (props) => { const { setAlertParams, alertParams, errors } = props; const [timeSize, setTimeSize] = useState(1); const [timeUnit, setTimeUnit] = useState('m'); @@ -137,7 +137,7 @@ export const Editor: React.FC = props => { const supportedFields = useMemo(() => { if (sourceStatus?.logIndexFields) { - return sourceStatus.logIndexFields.filter(field => { + return sourceStatus.logIndexFields.filter((field) => { return (field.type === 'string' || field.type === 'number') && field.searchable; }); } else { @@ -146,7 +146,7 @@ export const Editor: React.FC = props => { }, [sourceStatus]); const updateCount = useCallback( - countParams => { + (countParams) => { const nextCountParams = { ...alertParams.count, ...countParams }; setAlertParams('count', nextCountParams); }, @@ -187,7 +187,7 @@ export const Editor: React.FC = props => { }, [alertParams, setAlertParams]); const removeCriterion = useCallback( - idx => { + (idx) => { const nextCriteria = alertParams?.criteria?.filter((criterion, index) => { return index !== idx; }); diff --git a/x-pack/plugins/infra/public/components/auto_sizer.tsx b/x-pack/plugins/infra/public/components/auto_sizer.tsx index 284b5295111c6..af67e38a341a6 100644 --- a/x-pack/plugins/infra/public/components/auto_sizer.tsx +++ b/x-pack/plugins/infra/public/components/auto_sizer.tsx @@ -55,8 +55,8 @@ export class AutoSizer extends React.PureComponent { - entries.forEach(entry => { + this.resizeObserver = new ResizeObserver((entries) => { + entries.forEach((entry) => { if (entry.target === this.element) { this.measure(entry); } diff --git a/x-pack/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx b/x-pack/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx index 6bbd67ce932c6..96bba1b813746 100644 --- a/x-pack/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx +++ b/x-pack/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx @@ -304,11 +304,13 @@ const withUnfocused = (state: AutocompleteFieldState) => ({ isFocused: false, }); -const FixedEuiFieldSearch: React.FC & - EuiFieldSearchProps & { - inputRef?: (element: HTMLInputElement | null) => void; - onSearch: (value: string) => void; - }> = EuiFieldSearch as any; +const FixedEuiFieldSearch: React.FC< + React.InputHTMLAttributes & + EuiFieldSearchProps & { + inputRef?: (element: HTMLInputElement | null) => void; + onSearch: (value: string) => void; + } +> = EuiFieldSearch as any; const AutocompleteContainer = euiStyled.div` position: relative; @@ -323,6 +325,6 @@ const SuggestionsPanel = euiStyled(EuiPanel).attrs(() => ({ margin-top: 2px; overflow-x: hidden; overflow-y: scroll; - z-index: ${props => props.theme.eui.euiZLevel1}; + z-index: ${(props) => props.theme.eui.euiZLevel1}; max-height: 322px; `; diff --git a/x-pack/plugins/infra/public/components/autocomplete_field/suggestion_item.tsx b/x-pack/plugins/infra/public/components/autocomplete_field/suggestion_item.tsx index fb0c1127df3d1..f14494a8abc49 100644 --- a/x-pack/plugins/infra/public/components/autocomplete_field/suggestion_item.tsx +++ b/x-pack/plugins/infra/public/components/autocomplete_field/suggestion_item.tsx @@ -17,7 +17,7 @@ interface Props { suggestion: QuerySuggestion; } -export const SuggestionItem: React.FC = props => { +export const SuggestionItem: React.FC = (props) => { const { isSelected, onClick, onMouseEnter, suggestion } = props; return ( @@ -40,10 +40,10 @@ const SuggestionItemContainer = euiStyled.div<{ }>` display: flex; flex-direction: row; - font-size: ${props => props.theme.eui.euiFontSizeS}; - height: ${props => props.theme.eui.euiSizeXL}; + font-size: ${(props) => props.theme.eui.euiFontSizeS}; + height: ${(props) => props.theme.eui.euiSizeXL}; white-space: nowrap; - background-color: ${props => + background-color: ${(props) => props.isSelected ? props.theme.eui.euiColorLightestShade : 'transparent'}; `; @@ -52,24 +52,24 @@ const SuggestionItemField = euiStyled.div` cursor: pointer; display: flex; flex-direction: row; - height: ${props => props.theme.eui.euiSizeXL}; - padding: ${props => props.theme.eui.euiSizeXS}; + height: ${(props) => props.theme.eui.euiSizeXL}; + padding: ${(props) => props.theme.eui.euiSizeXS}; `; const SuggestionItemIconField = euiStyled(SuggestionItemField)<{ suggestionType: QuerySuggestionTypes; }>` - background-color: ${props => + background-color: ${(props) => transparentize(0.9, getEuiIconColor(props.theme, props.suggestionType))}; - color: ${props => getEuiIconColor(props.theme, props.suggestionType)}; + color: ${(props) => getEuiIconColor(props.theme, props.suggestionType)}; flex: 0 0 auto; justify-content: center; - width: ${props => props.theme.eui.euiSizeXL}; + width: ${(props) => props.theme.eui.euiSizeXL}; `; const SuggestionItemTextField = euiStyled(SuggestionItemField)` flex: 2 0 0; - font-family: ${props => props.theme.eui.euiCodeFontFamily}; + font-family: ${(props) => props.theme.eui.euiCodeFontFamily}; `; const SuggestionItemDescriptionField = euiStyled(SuggestionItemField)` @@ -79,7 +79,7 @@ const SuggestionItemDescriptionField = euiStyled(SuggestionItemField)` display: inline; span { - font-family: ${props => props.theme.eui.euiCodeFontFamily}; + font-family: ${(props) => props.theme.eui.euiCodeFontFamily}; } } `; diff --git a/x-pack/plugins/infra/public/components/eui/toolbar/toolbar.tsx b/x-pack/plugins/infra/public/components/eui/toolbar/toolbar.tsx index 8446587e8671d..912550b90b9b9 100644 --- a/x-pack/plugins/infra/public/components/eui/toolbar/toolbar.tsx +++ b/x-pack/plugins/infra/public/components/eui/toolbar/toolbar.tsx @@ -16,5 +16,5 @@ export const Toolbar = euiStyled(EuiPanel).attrs(() => ({ border-right: none; border-left: none; border-radius: 0; - padding: ${props => props.theme.eui.euiSizeS} ${props => props.theme.eui.euiSizeL}; + padding: ${(props) => props.theme.eui.euiSizeS} ${(props) => props.theme.eui.euiSizeL}; `; diff --git a/x-pack/plugins/infra/public/components/loading_overlay_wrapper.tsx b/x-pack/plugins/infra/public/components/loading_overlay_wrapper.tsx index 599969d9b15a8..3b22ee24cee07 100644 --- a/x-pack/plugins/infra/public/components/loading_overlay_wrapper.tsx +++ b/x-pack/plugins/infra/public/components/loading_overlay_wrapper.tsx @@ -10,10 +10,12 @@ import React from 'react'; import { euiStyled } from '../../../observability/public'; -export const LoadingOverlayWrapper: React.FC & { - isLoading: boolean; - loadingChildren?: React.ReactNode; -}> = ({ children, isLoading, loadingChildren, ...rest }) => { +export const LoadingOverlayWrapper: React.FC< + React.HTMLAttributes & { + isLoading: boolean; + loadingChildren?: React.ReactNode; + } +> = ({ children, isLoading, loadingChildren, ...rest }) => { return ( {children} @@ -32,7 +34,7 @@ const RelativeDiv = euiStyled.div` const OverlayDiv = euiStyled.div` align-items: center; - background-color: ${props => transparentize(0.3, props.theme.eui.euiColorEmptyShade)}; + background-color: ${(props) => transparentize(0.3, props.theme.eui.euiColorEmptyShade)}; display: flex; height: 100%; justify-content: center; @@ -40,5 +42,5 @@ const OverlayDiv = euiStyled.div` position: absolute; top: 0; width: 100%; - z-index: ${props => props.theme.eui.euiZLevel1}; + z-index: ${(props) => props.theme.eui.euiZLevel1}; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/recreate_job_button.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/recreate_job_button.tsx index 74e8d197ef455..4f7b5bc135a18 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/recreate_job_button.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/recreate_job_button.tsx @@ -8,7 +8,7 @@ import { EuiButton, PropsOf } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import React from 'react'; -export const RecreateJobButton: React.FunctionComponent> = props => ( +export const RecreateJobButton: React.FunctionComponent> = (props) => ( { onChangeSelectedIndices( - indices.map(index => { + indices.map((index) => { return index.name === indexName ? { ...index, isSelected } : index; }) ); @@ -39,7 +39,7 @@ export const AnalysisSetupIndicesForm: React.FunctionComponent<{ const changeDatasetFilter = useCallback( (indexName: string, datasetFilter) => { onChangeSelectedIndices( - indices.map(index => { + indices.map((index) => { return index.name === indexName ? { ...index, datasetFilter } : index; }) ); @@ -74,7 +74,7 @@ export const AnalysisSetupIndicesForm: React.FunctionComponent<{ labelType="legend" > <> - {indices.map(index => ( + {indices.map((index) => ( setStartTime(selectedDateToParam(date))} + onChange={(date) => setStartTime(selectedDateToParam(date))} placeholder={startTimeDefaultDescription} maxDate={now} /> @@ -132,20 +132,12 @@ export const AnalysisSetupTimerangeForm: React.FunctionComponent<{ disabled={disabled} showTimeSelect selected={endTimeValue} - onChange={date => setEndTime(selectedDateToParam(date))} + onChange={(date) => setEndTime(selectedDateToParam(date))} placeholder={endTimeDefaultDescription} openToDate={now} minDate={startTimeValue} - minTime={ - selectedEndTimeIsToday - ? now - : moment() - .hour(0) - .minutes(0) - } - maxTime={moment() - .hour(23) - .minutes(59)} + minTime={selectedEndTimeIsToday ? now : moment().hour(0).minutes(0)} + maxTime={moment().hour(23).minutes(59)} /> @@ -155,7 +147,7 @@ export const AnalysisSetupTimerangeForm: React.FunctionComponent<{ }; const getStartTimeValidationErrorMessages = (validationErrors: TimeRangeValidationError[]) => - validationErrors.flatMap(validationError => { + validationErrors.flatMap((validationError) => { switch (validationError.error) { case 'INVALID_TIME_RANGE': return [ @@ -169,7 +161,7 @@ const getStartTimeValidationErrorMessages = (validationErrors: TimeRangeValidati }); const getEndTimeValidationErrorMessages = (validationErrors: TimeRangeValidationError[]) => - validationErrors.flatMap(validationError => { + validationErrors.flatMap((validationError) => { switch (validationError.error) { case 'INVALID_TIME_RANGE': return [ diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_dataset_filter.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_dataset_filter.tsx index b37c68f837876..d3ed8aeaf6155 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_dataset_filter.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_dataset_filter.tsx @@ -42,7 +42,7 @@ export const IndexSetupDatasetFilter: React.FC<{ const selectableOptions: EuiSelectableOption[] = useMemo( () => - availableDatasets.map(datasetName => ({ + availableDatasets.map((datasetName) => ({ label: datasetName, checked: datasetFilter.type === 'includeSome' && datasetFilter.datasets.includes(datasetName) diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_row.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_row.tsx index 2eb67e0c0ce76..92774dbd6838b 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_row.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/index_setup_row.tsx @@ -62,7 +62,7 @@ export const IndexSetupRow: React.FC<{ }; const formatValidationError = (errors: ValidationUIError[]): React.ReactNode => { - return errors.map(error => { + return errors.map((error) => { switch (error.error) { case 'INDEX_NOT_FOUND': return ( diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/user_management_link.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/user_management_link.tsx index e045e78471513..49ab25297c687 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/user_management_link.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/user_management_link.tsx @@ -9,7 +9,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; import React from 'react'; import { useLinkProps } from '../../../hooks/use_link_props'; -export const UserManagementLink: React.FunctionComponent = props => { +export const UserManagementLink: React.FunctionComponent = (props) => { const linkProps = useLinkProps({ app: 'kibana', hash: '/management/security/users', diff --git a/x-pack/plugins/infra/public/components/logging/log_customization_menu.tsx b/x-pack/plugins/infra/public/components/logging/log_customization_menu.tsx index febfdddfcfb0e..84074568bcfef 100644 --- a/x-pack/plugins/infra/public/components/logging/log_customization_menu.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_customization_menu.tsx @@ -32,7 +32,7 @@ export class LogCustomizationMenu extends React.Component<{}, LogCustomizationMe }; public toggleVisibility = () => { - this.setState(state => ({ + this.setState((state) => ({ isShown: !state.isShown, })); }; diff --git a/x-pack/plugins/infra/public/components/logging/log_entry_flyout/log_entry_actions_menu.tsx b/x-pack/plugins/infra/public/components/logging/log_entry_flyout/log_entry_actions_menu.tsx index a8597b7073c95..69c969ad65f4d 100644 --- a/x-pack/plugins/infra/public/components/logging/log_entry_flyout/log_entry_actions_menu.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_entry_flyout/log_entry_actions_menu.tsx @@ -99,7 +99,7 @@ const getUptimeLink = (logItem: LogEntriesItem): LinkDescriptor | undefined => { const { field, value } = fieldItem; try { const parsedValue = decodeOrThrow(rt.array(rt.string))(JSON.parse(value)); - return acc.concat(parsedValue.map(val => `${field}:${val}`)); + return acc.concat(parsedValue.map((val) => `${field}:${val}`)); } catch (e) { return acc.concat([`${field}:${value}`]); } diff --git a/x-pack/plugins/infra/public/components/logging/log_highlights_menu.tsx b/x-pack/plugins/infra/public/components/logging/log_highlights_menu.tsx index f51ed693e7d80..608a22a79c473 100644 --- a/x-pack/plugins/infra/public/components/logging/log_highlights_menu.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_highlights_menu.tsx @@ -51,8 +51,8 @@ export const LogHighlightsMenu: React.FC = ({ const debouncedOnChange = useMemo(() => debounce(onChange, 275), [onChange]); const setHighlightTerm = useCallback( - valueOrUpdater => - _setHighlightTerm(previousHighlightTerm => { + (valueOrUpdater) => + _setHighlightTerm((previousHighlightTerm) => { const newHighlightTerm = typeof valueOrUpdater === 'function' ? valueOrUpdater(previousHighlightTerm) @@ -67,7 +67,7 @@ export const LogHighlightsMenu: React.FC = ({ [debouncedOnChange] ); const changeHighlightTerm = useCallback( - e => { + (e) => { const value = e.target.value; setHighlightTerm(value); }, @@ -168,7 +168,7 @@ const ActiveHighlightsIndicator = euiStyled(EuiIcon).attrs(({ theme }) => ({ size: 'm', color: theme.eui.euiColorAccent, }))` - padding-left: ${props => props.theme.eui.paddingSizes.xs}; + padding-left: ${(props) => props.theme.eui.paddingSizes.xs}; `; const LogHighlightsMenuContent = euiStyled.div` diff --git a/x-pack/plugins/infra/public/components/logging/log_minimap/density_chart.tsx b/x-pack/plugins/infra/public/components/logging/log_minimap/density_chart.tsx index 2bdb1f91a6dde..0528d59f0b3d5 100644 --- a/x-pack/plugins/infra/public/components/logging/log_minimap/density_chart.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_minimap/density_chart.tsx @@ -31,20 +31,16 @@ export const DensityChart: React.FC = ({ return null; } - const yScale = scaleTime() - .domain([start, end]) - .range([0, height]); + const yScale = scaleTime().domain([start, end]).range([0, height]); - const xMax = max(buckets.map(bucket => bucket.entriesCount)) || 0; - const xScale = scaleLinear() - .domain([0, xMax]) - .range([0, width]); + const xMax = max(buckets.map((bucket) => bucket.entriesCount)) || 0; + const xScale = scaleLinear().domain([0, xMax]).range([0, width]); const path = area() .x0(xScale(0)) - .x1(bucket => xScale(bucket.entriesCount)) - .y0(bucket => yScale(bucket.start)) - .y1(bucket => yScale(bucket.end)) + .x1((bucket) => xScale(bucket.entriesCount)) + .y0((bucket) => yScale(bucket.start)) + .y1((bucket) => yScale(bucket.end)) .curve(curveMonotoneY); const firstBucket = buckets[0]; @@ -69,14 +65,14 @@ export const DensityChart: React.FC = ({ }; const DensityChartPositiveBackground = euiStyled.rect` - fill: ${props => + fill: ${(props) => props.theme.darkMode ? props.theme.eui.euiColorLightShade : props.theme.eui.euiColorLightestShade}; `; const PositiveAreaPath = euiStyled.path` - fill: ${props => + fill: ${(props) => props.theme.darkMode ? props.theme.eui.euiColorMediumShade : props.theme.eui.euiColorLightShade}; diff --git a/x-pack/plugins/infra/public/components/logging/log_minimap/highlighted_interval.tsx b/x-pack/plugins/infra/public/components/logging/log_minimap/highlighted_interval.tsx index 975e83e0075ff..2869f8d0087c2 100644 --- a/x-pack/plugins/infra/public/components/logging/log_minimap/highlighted_interval.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_minimap/highlighted_interval.tsx @@ -53,13 +53,13 @@ export const HighlightedInterval: React.FC = ({ HighlightedInterval.displayName = 'HighlightedInterval'; const HighlightTargetMarker = euiStyled.line` - stroke: ${props => props.theme.eui.euiColorPrimary}; + stroke: ${(props) => props.theme.eui.euiColorPrimary}; stroke-width: 1; `; const HighlightPolygon = euiStyled.polygon` - fill: ${props => props.theme.eui.euiColorPrimary}; + fill: ${(props) => props.theme.eui.euiColorPrimary}; fill-opacity: 0.3; - stroke: ${props => props.theme.eui.euiColorPrimary}; + stroke: ${(props) => props.theme.eui.euiColorPrimary}; stroke-width: 1; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_minimap/log_minimap.tsx b/x-pack/plugins/infra/public/components/logging/log_minimap/log_minimap.tsx index c67674d198a3f..496d4ebf924a3 100644 --- a/x-pack/plugins/infra/public/components/logging/log_minimap/log_minimap.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_minimap/log_minimap.tsx @@ -59,7 +59,7 @@ export class LogMinimap extends React.Component = event => { + public handleClick: React.MouseEventHandler = (event) => { const minimapTop = event.currentTarget.getBoundingClientRect().top; const clickedYPosition = event.clientY - minimapTop; @@ -80,7 +80,7 @@ export class LogMinimap extends React.Component = event => { + private updateTimeCursor: React.MouseEventHandler = (event) => { const svgPosition = event.currentTarget.getBoundingClientRect(); const timeCursorY = event.clientY - svgPosition.top; @@ -157,14 +157,14 @@ export class LogMinimap extends React.Component props.theme.eui.euiColorMediumShade}; + stroke: ${(props) => props.theme.eui.euiColorMediumShade}; stroke-width: 1px; `; const TimeCursor = euiStyled.line` pointer-events: none; stroke-width: 1px; - stroke: ${props => + stroke: ${(props) => props.theme.darkMode ? props.theme.eui.euiColorDarkestShade : props.theme.eui.euiColorDarkShade}; @@ -172,7 +172,7 @@ const TimeCursor = euiStyled.line` const MinimapWrapper = euiStyled.svg` cursor: pointer; - fill: ${props => props.theme.eui.euiColorEmptyShade}; + fill: ${(props) => props.theme.eui.euiColorEmptyShade}; & ${TimeCursor} { visibility: hidden; } diff --git a/x-pack/plugins/infra/public/components/logging/log_minimap/search_marker.tsx b/x-pack/plugins/infra/public/components/logging/log_minimap/search_marker.tsx index 18d4a3bbfc8b3..6271627589394 100644 --- a/x-pack/plugins/infra/public/components/logging/log_minimap/search_marker.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_minimap/search_marker.tsx @@ -27,13 +27,13 @@ export class SearchMarker extends React.PureComponent = evt => { + public handleClick: React.MouseEventHandler = (evt) => { evt.stopPropagation(); this.props.jumpToTarget(this.props.bucket.representativeKey); }; - public handleMouseEnter: React.MouseEventHandler = evt => { + public handleMouseEnter: React.MouseEventHandler = (evt) => { this.setState({ hoveredPosition: evt.currentTarget.getBoundingClientRect(), }); @@ -102,13 +102,13 @@ const fadeInAnimation = keyframes` `; const SearchMarkerGroup = euiStyled.g` - animation: ${fadeInAnimation} ${props => props.theme.eui.euiAnimSpeedExtraSlow} ease-in both; + animation: ${fadeInAnimation} ${(props) => props.theme.eui.euiAnimSpeedExtraSlow} ease-in both; `; const SearchMarkerBackgroundRect = euiStyled.rect` - fill: ${props => props.theme.eui.euiColorAccent}; + fill: ${(props) => props.theme.eui.euiColorAccent}; opacity: 0; - transition: opacity ${props => props.theme.eui.euiAnimSpeedNormal} ease-in; + transition: opacity ${(props) => props.theme.eui.euiAnimSpeedNormal} ease-in; cursor: pointer; ${SearchMarkerGroup}:hover & { @@ -117,5 +117,5 @@ const SearchMarkerBackgroundRect = euiStyled.rect` `; const SearchMarkerForegroundRect = euiStyled.rect` - fill: ${props => props.theme.eui.euiColorAccent}; + fill: ${(props) => props.theme.eui.euiColorAccent}; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_minimap/search_markers.tsx b/x-pack/plugins/infra/public/components/logging/log_minimap/search_markers.tsx index 1e254d999036e..41323ff14dd32 100644 --- a/x-pack/plugins/infra/public/components/logging/log_minimap/search_markers.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_minimap/search_markers.tsx @@ -31,13 +31,11 @@ export class SearchMarkers extends React.PureComponent { return null; } - const yScale = scaleTime() - .domain([start, end]) - .range([0, height]); + const yScale = scaleTime().domain([start, end]).range([0, height]); return ( - {buckets.map(bucket => ( + {buckets.map((bucket) => ( = ({ end, height, start, tickCount, width }) => { - const yScale = scaleTime() - .domain([start, end]) - .range([0, height]); + const yScale = scaleTime().domain([start, end]).range([0, height]); const ticks = yScale.ticks(tickCount); const formatTick = yScale.tickFormat(tickCount, getTimeLabelFormat(start, end)); @@ -48,14 +46,14 @@ TimeRuler.displayName = 'TimeRuler'; const TimeRulerTickLabel = euiStyled.text` font-size: 9px; - line-height: ${props => props.theme.eui.euiLineHeight}; - fill: ${props => props.theme.eui.textColors.subdued}; + line-height: ${(props) => props.theme.eui.euiLineHeight}; + fill: ${(props) => props.theme.eui.textColors.subdued}; user-select: none; pointer-events: none; `; const TimeRulerGridLine = euiStyled.line` - stroke: ${props => + stroke: ${(props) => props.theme.darkMode ? props.theme.eui.euiColorDarkestShade : props.theme.eui.euiColorDarkShade}; diff --git a/x-pack/plugins/infra/public/components/logging/log_search_controls/log_search_input.tsx b/x-pack/plugins/infra/public/components/logging/log_search_controls/log_search_input.tsx index a5277260d56e0..248dce8f6bf8c 100644 --- a/x-pack/plugins/infra/public/components/logging/log_search_controls/log_search_input.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_search_controls/log_search_input.tsx @@ -32,7 +32,7 @@ export const LogSearchInput = class extends React.PureComponent< query: '', }; - public handleSubmit: React.FormEventHandler = evt => { + public handleSubmit: React.FormEventHandler = (evt) => { evt.preventDefault(); const { query } = this.state; @@ -44,7 +44,7 @@ export const LogSearchInput = class extends React.PureComponent< } }; - public handleChangeQuery: React.ChangeEventHandler = evt => { + public handleChangeQuery: React.ChangeEventHandler = (evt) => { this.setState({ query: evt.target.value, }); @@ -81,6 +81,6 @@ const PlainSearchField = euiStyled(EuiFieldSearch)` box-shadow: none; &:focus { - box-shadow: inset 0 -2px 0 0 ${props => props.theme.eui.euiColorPrimary}; + box-shadow: inset 0 -2px 0 0 ${(props) => props.theme.eui.euiColorPrimary}; } `; diff --git a/x-pack/plugins/infra/public/components/logging/log_statusbar.tsx b/x-pack/plugins/infra/public/components/logging/log_statusbar.tsx index 8a0f1290c2af3..64dda6ce74d89 100644 --- a/x-pack/plugins/infra/public/components/logging/log_statusbar.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_statusbar.tsx @@ -13,11 +13,11 @@ export const LogStatusbar = euiStyled(EuiFlexGroup).attrs(() => ({ gutterSize: 'none', justifyContent: 'flexEnd', }))` - padding: ${props => props.theme.eui.euiSizeS}; - border-top: ${props => props.theme.eui.euiBorderThin}; + padding: ${(props) => props.theme.eui.euiSizeS}; + border-top: ${(props) => props.theme.eui.euiBorderThin}; max-height: 48px; min-height: 48px; - background-color: ${props => props.theme.eui.euiColorEmptyShade}; + background-color: ${(props) => props.theme.eui.euiColorEmptyShade}; flex-direction: row; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/column_headers.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/column_headers.tsx index c713839a1bba8..71e1aacb734c1 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/column_headers.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/column_headers.tsx @@ -31,7 +31,7 @@ export const LogColumnHeaders: React.FunctionComponent<{ const { firstVisiblePosition } = useContext(LogPositionState.Context); return ( - {columnConfigurations.map(columnConfiguration => { + {columnConfigurations.map((columnConfiguration) => { if (isTimestampLogColumnConfiguration(columnConfiguration)) { return ( ({ justify-content: flex-start; overflow: hidden; padding-right: ${ASSUMED_SCROLLBAR_WIDTH}px; - border-bottom: ${props => props.theme.eui.euiBorderThin}; - box-shadow: 0 2px 2px -1px ${props => transparentize(0.3, props.theme.eui.euiColorLightShade)}; + border-bottom: ${(props) => props.theme.eui.euiBorderThin}; + box-shadow: 0 2px 2px -1px ${(props) => transparentize(0.3, props.theme.eui.euiColorLightShade)}; position: relative; z-index: 1; `; @@ -104,10 +104,10 @@ const LogColumnHeaderWrapper = euiStyled(LogEntryColumn).attrs(() => ({ `; const LogColumnHeaderContent = euiStyled(LogEntryColumnContent)` - color: ${props => props.theme.eui.euiTitleColor}; - font-size: ${props => props.theme.eui.euiFontSizeS}; - font-weight: ${props => props.theme.eui.euiFontWeightSemiBold}; - line-height: ${props => props.theme.eui.euiLineHeight}; + color: ${(props) => props.theme.eui.euiTitleColor}; + font-size: ${(props) => props.theme.eui.euiFontSizeS}; + font-weight: ${(props) => props.theme.eui.euiFontWeightSemiBold}; + line-height: ${(props) => props.theme.eui.euiLineHeight}; text-overflow: clip; white-space: pre; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/highlighting.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/highlighting.tsx index a6cb8def4f6c4..2af99e30ce44f 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/highlighting.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/highlighting.tsx @@ -10,27 +10,27 @@ import { euiStyled } from '../../../../../observability/public'; import { chooseLightOrDarkColor, tintOrShade } from '../../../utils/styles'; export const ActiveHighlightMarker = euiStyled.mark` - color: ${props => + color: ${(props) => chooseLightOrDarkColor( props.theme.eui.euiColorAccent, props.theme.eui.euiColorEmptyShade, props.theme.eui.euiColorDarkestShade )}; - background-color: ${props => props.theme.eui.euiColorAccent}; - outline: 1px solid ${props => props.theme.eui.euiColorAccent}; + background-color: ${(props) => props.theme.eui.euiColorAccent}; + outline: 1px solid ${(props) => props.theme.eui.euiColorAccent}; }; `; export const HighlightMarker = euiStyled.mark` - color: ${props => + color: ${(props) => chooseLightOrDarkColor( tintOrShade(props.theme.eui.euiTextColor, props.theme.eui.euiColorAccent, 0.7, 0.5), props.theme.eui.euiColorEmptyShade, props.theme.eui.euiColorDarkestShade )}; - background-color: ${props => + background-color: ${(props) => tintOrShade(props.theme.eui.euiTextColor, props.theme.eui.euiColorAccent, 0.7, 0.5)}; - outline: 1px solid ${props => + outline: 1px solid ${(props) => tintOrShade(props.theme.eui.euiTextColor, props.theme.eui.euiColorAccent, 0.7, 0.5)}; }; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/jump_to_tail.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/jump_to_tail.tsx index 50595cfe971d8..78caa8054860f 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/jump_to_tail.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/jump_to_tail.tsx @@ -44,11 +44,11 @@ export class LogTextStreamJumpToTail extends React.PureComponent` align-items: center; display: flex; - min-height: ${props => props.theme.eui.euiSizeXXL}; - width: ${props => props.width}px; + min-height: ${(props) => props.theme.eui.euiSizeXXL}; + width: ${(props) => props.width}px; position: fixed; bottom: 0; - background-color: ${props => props.theme.eui.euiColorEmptyShade}; + background-color: ${(props) => props.theme.eui.euiColorEmptyShade}; `; const MessageWrapper = euiStyled.div` diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/loading_item_view.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/loading_item_view.tsx index 5598528c0e0f5..eb187a7af03f6 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/loading_item_view.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/loading_item_view.tsx @@ -97,10 +97,10 @@ const LoadingItemViewExtra = euiStyled(EuiFlexGroup)` `; const ProgressEntryWrapper = euiStyled.div<{ position: Position }>` - padding-left: ${props => props.theme.eui.euiSizeS}; - padding-top: ${props => + padding-left: ${(props) => props.theme.eui.euiSizeS}; + padding-top: ${(props) => props.position === 'start' ? props.theme.eui.euiSizeL : props.theme.eui.euiSizeM}; - padding-bottom: ${props => + padding-bottom: ${(props) => props.position === 'end' ? props.theme.eui.euiSizeL : props.theme.eui.euiSizeM}; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_actions_column.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_actions_column.tsx index 976e4165eb6d5..1ac2e00abca70 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_actions_column.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_actions_column.tsx @@ -113,7 +113,7 @@ const ActionsColumnContent = euiStyled(LogEntryColumnContent)` `; const ButtonWrapper = euiStyled.div` - background: ${props => props.theme.eui.euiColorPrimary}; + background: ${(props) => props.theme.eui.euiColorPrimary}; border-radius: 50%; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_column.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_column.tsx index b0518b96e758c..51488f088e75a 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_column.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_column.tsx @@ -32,10 +32,10 @@ export const LogEntryColumn = euiStyled.div.attrs(() => ({ }))` align-items: stretch; display: flex; - flex-basis: ${props => props.baseWidth || '0%'}; + flex-basis: ${(props) => props.baseWidth || '0%'}; flex-direction: row; - flex-grow: ${props => props.growWeight || 0}; - flex-shrink: ${props => props.shrinkWeight || 0}; + flex-grow: ${(props) => props.growWeight || 0}; + flex-shrink: ${(props) => props.shrinkWeight || 0}; overflow: hidden; `; @@ -69,10 +69,10 @@ export const getColumnWidths = ( [column.timestampColumn.id]: { growWeight: 0, shrinkWeight: 0, - baseWidth: `${Math.ceil( - characterWidth * formattedDateWidth * DATE_COLUMN_SLACK_FACTOR - ) + - 2 * COLUMN_PADDING}px`, + baseWidth: `${ + Math.ceil(characterWidth * formattedDateWidth * DATE_COLUMN_SLACK_FACTOR) + + 2 * COLUMN_PADDING + }px`, }, }; } else if (isMessageLogColumnConfiguration(column)) { @@ -90,8 +90,9 @@ export const getColumnWidths = ( [column.fieldColumn.id]: { growWeight: 1, shrinkWeight: 0, - baseWidth: `${Math.ceil(characterWidth * FIELD_COLUMN_MIN_WIDTH_CHARACTERS) + - 2 * COLUMN_PADDING}px`, + baseWidth: `${ + Math.ceil(characterWidth * FIELD_COLUMN_MIN_WIDTH_CHARACTERS) + 2 * COLUMN_PADDING + }px`, }, }; } diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_field_column.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_field_column.tsx index c73c9674f9683..4e9611f7a8d2f 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_field_column.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_field_column.tsx @@ -78,7 +78,7 @@ interface LogEntryColumnContentProps { const FieldColumnContent = euiStyled(LogEntryColumnContent)` text-overflow: ellipsis; - ${props => + ${(props) => props.wrapMode === 'long' ? longWrappedContentStyle : props.wrapMode === 'pre-wrapped' diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_message_column.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_message_column.tsx index 0fe0cbdfac593..f83a0a222d3dc 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_message_column.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_message_column.tsx @@ -52,7 +52,7 @@ interface MessageColumnContentProps { const MessageColumnContent = euiStyled(LogEntryColumnContent)` text-overflow: ellipsis; - ${props => + ${(props) => props.wrapMode === 'long' ? longWrappedContentStyle : props.wrapMode === 'pre-wrapped' @@ -68,7 +68,7 @@ const formatMessageSegments = ( messageSegments.map((messageSegment, index) => formatMessageSegment( messageSegment, - highlights.map(highlight => { + highlights.map((highlight) => { if (isHighlightMessageColumn(highlight)) { const segment = highlight.message[index]; if (isHighlightFieldSegment(segment)) { diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_row.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_row.tsx index 5c20df000ae51..0d971151dd95c 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_row.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_row.tsx @@ -120,7 +120,7 @@ export const LogEntryRow = memo( isHighlighted={isHighlighted} scale={scale} > - {columnConfigurations.map(columnConfiguration => { + {columnConfigurations.map((columnConfiguration) => { if (isTimestampLogColumnConfiguration(columnConfiguration)) { const column = logEntryColumnsById[columnConfiguration.timestampColumn.id]; const columnWidth = columnWidths[columnConfiguration.timestampColumn.id]; @@ -209,15 +209,15 @@ export const LogEntryRowWrapper = euiStyled.div.attrs(() => ({ role: 'row', }))` align-items: stretch; - color: ${props => props.theme.eui.euiTextColor}; + color: ${(props) => props.theme.eui.euiTextColor}; display: flex; flex-direction: row; flex-wrap: nowrap; justify-content: flex-start; overflow: hidden; - ${props => monospaceTextStyle(props.scale)}; - ${props => (props.isHighlighted ? highlightedContentStyle : '')} + ${(props) => monospaceTextStyle(props.scale)}; + ${(props) => (props.isHighlighted ? highlightedContentStyle : '')} &:hover { ${hoveredContentStyle} diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_timestamp_column.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_timestamp_column.tsx index cf9c75a361b55..5f07a6a1f78d6 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_timestamp_column.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_timestamp_column.tsx @@ -24,7 +24,7 @@ export const LogEntryTimestampColumn = memo( ); const TimestampColumnContent = euiStyled(LogEntryColumnContent)` - color: ${props => props.theme.eui.euiColorDarkShade}; + color: ${(props) => props.theme.eui.euiColorDarkShade}; overflow: hidden; text-overflow: clip; white-space: pre; diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/scrollable_log_text_stream_view.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/scrollable_log_text_stream_view.tsx index f89aaf12db1bc..74d1878fc89c2 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/scrollable_log_text_stream_view.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/scrollable_log_text_stream_view.tsx @@ -201,7 +201,7 @@ export class ScrollableLogTextStreamView extends React.PureComponent< isLocked={isScrollLocked} entriesCount={items.length} > - {registerChild => + {(registerChild) => items.length > 0 ? ( <> + onExtendRange={(newDateExpression) => updateDateRange({ startDateExpression: newDateExpression }) } /> @@ -232,7 +232,7 @@ export class ScrollableLogTextStreamView extends React.PureComponent< register={registerChild} registrationKey={getStreamItemId(item)} > - {itemMeasureRef => ( + {(itemMeasureRef) => ( + onExtendRange={(newDateExpression) => updateDateRange({ endDateExpression: newDateExpression }) } onStreamStart={() => startLiveStreaming()} diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/text_styles.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/text_styles.tsx index 0eb6140c0de84..7fc97f949f068 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/text_styles.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/text_styles.tsx @@ -12,8 +12,8 @@ import { TextScale } from '../../../../common/log_text_scale'; export type WrapMode = 'none' | 'pre-wrapped' | 'long'; export const monospaceTextStyle = (scale: TextScale) => css` - font-family: ${props => props.theme.eui.euiCodeFontFamily}; - font-size: ${props => { + font-family: ${(props) => props.theme.eui.euiCodeFontFamily}; + font-size: ${(props) => { switch (scale) { case 'large': return props.theme.eui.euiFontSizeM; @@ -25,15 +25,15 @@ export const monospaceTextStyle = (scale: TextScale) => css` return props.theme.eui.euiFontSize; } }}; - line-height: ${props => props.theme.eui.euiLineHeight}; + line-height: ${(props) => props.theme.eui.euiLineHeight}; `; export const hoveredContentStyle = css` - background-color: ${props => props.theme.eui.euiFocusBackgroundColor}; + background-color: ${(props) => props.theme.eui.euiFocusBackgroundColor}; `; export const highlightedContentStyle = css` - background-color: ${props => props.theme.eui.euiColorHighlight}; + background-color: ${(props) => props.theme.eui.euiColorHighlight}; `; export const longWrappedContentStyle = css` @@ -104,5 +104,5 @@ const MonospaceCharacterDimensionsProbe = euiStyled.div.attrs(() => ({ padding: 0; margin: 0; - ${props => monospaceTextStyle(props.scale)}; + ${(props) => monospaceTextStyle(props.scale)}; `; diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/vertical_scroll_panel.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/vertical_scroll_panel.tsx index 199f24f5d3f53..9b8fecc7fb111 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/vertical_scroll_panel.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/vertical_scroll_panel.tsx @@ -262,7 +262,7 @@ const ScrollPanelWrapper = euiStyled.div` overflow-x: hidden; overflow-y: scroll; position: relative; - padding-right: ${props => props.scrollbarOffset || 0}px; + padding-right: ${(props) => props.scrollbarOffset || 0}px; & * { overflow-anchor: none; diff --git a/x-pack/plugins/infra/public/components/navigation/app_navigation.tsx b/x-pack/plugins/infra/public/components/navigation/app_navigation.tsx index b229fb4a6b494..eae39c9d1b253 100644 --- a/x-pack/plugins/infra/public/components/navigation/app_navigation.tsx +++ b/x-pack/plugins/infra/public/components/navigation/app_navigation.tsx @@ -22,9 +22,9 @@ export const AppNavigation = ({ 'aria-label': label, children }: AppNavigationPr ); const Nav = euiStyled.nav` - background: ${props => props.theme.eui.euiColorEmptyShade}; - border-bottom: ${props => props.theme.eui.euiBorderThin}; - padding: ${props => + background: ${(props) => props.theme.eui.euiColorEmptyShade}; + border-bottom: ${(props) => props.theme.eui.euiBorderThin}; + padding: ${(props) => `${props.theme.eui.euiSize} ${props.theme.eui.euiSizeL} ${props.theme.eui.euiSize} ${props.theme.eui.euiSizeL}`}; .euiTabs { padding-left: 3px; diff --git a/x-pack/plugins/infra/public/components/navigation/routed_tabs.tsx b/x-pack/plugins/infra/public/components/navigation/routed_tabs.tsx index d9ea44e2f1f6a..29db3c893a460 100644 --- a/x-pack/plugins/infra/public/components/navigation/routed_tabs.tsx +++ b/x-pack/plugins/infra/public/components/navigation/routed_tabs.tsx @@ -27,7 +27,7 @@ const noop = () => {}; export const RoutedTabs = ({ tabs }: RoutedTabsProps) => { return ( - {tabs.map(tab => { + {tabs.map((tab) => { return ; })} diff --git a/x-pack/plugins/infra/public/components/page.tsx b/x-pack/plugins/infra/public/components/page.tsx index b51afdd8ca803..67e82310f0807 100644 --- a/x-pack/plugins/infra/public/components/page.tsx +++ b/x-pack/plugins/infra/public/components/page.tsx @@ -19,7 +19,7 @@ export const PageContent = euiStyled.div` flex: 1 0 0%; display: flex; flex-direction: row; - background-color: ${props => props.theme.eui.euiColorEmptyShade}; + background-color: ${(props) => props.theme.eui.euiColorEmptyShade}; `; export const FlexPage = euiStyled(EuiPage)` diff --git a/x-pack/plugins/infra/public/components/saved_views/create_modal.tsx b/x-pack/plugins/infra/public/components/saved_views/create_modal.tsx index 9b8907a1ff9e1..de5241c65ef45 100644 --- a/x-pack/plugins/infra/public/components/saved_views/create_modal.tsx +++ b/x-pack/plugins/infra/public/components/saved_views/create_modal.tsx @@ -31,8 +31,8 @@ interface Props { export const SavedViewCreateModal = ({ close, save, isInvalid }: Props) => { const [viewName, setViewName] = useState(''); const [includeTime, setIncludeTime] = useState(false); - const onCheckChange = useCallback(e => setIncludeTime(e.target.checked), []); - const textChange = useCallback(e => setViewName(e.target.value), []); + const onCheckChange = useCallback((e) => setIncludeTime(e.target.checked), []); + const textChange = useCallback((e) => setViewName(e.target.value), []); const saveView = useCallback(() => { save(viewName, includeTime); diff --git a/x-pack/plugins/infra/public/components/source_configuration/add_log_column_popover.tsx b/x-pack/plugins/infra/public/components/source_configuration/add_log_column_popover.tsx index 3c96d505dce4d..9f55126a1440a 100644 --- a/x-pack/plugins/infra/public/components/source_configuration/add_log_column_popover.tsx +++ b/x-pack/plugins/infra/public/components/source_configuration/add_log_column_popover.tsx @@ -58,7 +58,7 @@ export const AddLogColumnButtonAndPopover: React.FunctionComponent<{ }, }, }, - ...availableFields.map(field => ({ + ...availableFields.map((field) => ({ optionProps: { 'data-test-subj': `addFieldLogColumn addFieldLogColumn:${field}`, // this key works around EuiSelectable using a lowercased label as @@ -79,7 +79,7 @@ export const AddLogColumnButtonAndPopover: React.FunctionComponent<{ ); const availableOptions = useMemo( - () => availableColumnOptions.map(availableColumnOption => availableColumnOption.optionProps), + () => availableColumnOptions.map((availableColumnOption) => availableColumnOption.optionProps), [availableColumnOptions] ); @@ -88,7 +88,7 @@ export const AddLogColumnButtonAndPopover: React.FunctionComponent<{ closePopover(); const selectedOptionIndex = selectedOptions.findIndex( - selectedOption => selectedOption.checked === 'on' + (selectedOption) => selectedOption.checked === 'on' ); const selectedOption = availableColumnOptions[selectedOptionIndex]; diff --git a/x-pack/plugins/infra/public/components/source_configuration/indices_configuration_form_state.ts b/x-pack/plugins/infra/public/components/source_configuration/indices_configuration_form_state.ts index eab1651f498e5..bb4da5cab203a 100644 --- a/x-pack/plugins/infra/public/components/source_configuration/indices_configuration_form_state.ts +++ b/x-pack/plugins/infra/public/components/source_configuration/indices_configuration_form_state.ts @@ -45,7 +45,7 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.name), name: 'name', - onChange: name => setFormStateChanges(changes => ({ ...changes, name })), + onChange: (name) => setFormStateChanges((changes) => ({ ...changes, name })), value: formState.name, }), [formState.name] @@ -55,7 +55,7 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.logAlias), name: 'logAlias', - onChange: logAlias => setFormStateChanges(changes => ({ ...changes, logAlias })), + onChange: (logAlias) => setFormStateChanges((changes) => ({ ...changes, logAlias })), value: formState.logAlias, }), [formState.logAlias] @@ -65,7 +65,7 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.metricAlias), name: 'metricAlias', - onChange: metricAlias => setFormStateChanges(changes => ({ ...changes, metricAlias })), + onChange: (metricAlias) => setFormStateChanges((changes) => ({ ...changes, metricAlias })), value: formState.metricAlias, }), [formState.metricAlias] @@ -75,8 +75,8 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.containerField), name: `containerField`, - onChange: containerField => - setFormStateChanges(changes => ({ ...changes, containerField })), + onChange: (containerField) => + setFormStateChanges((changes) => ({ ...changes, containerField })), value: formState.containerField, }), [formState.containerField] @@ -86,7 +86,7 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.hostField), name: `hostField`, - onChange: hostField => setFormStateChanges(changes => ({ ...changes, hostField })), + onChange: (hostField) => setFormStateChanges((changes) => ({ ...changes, hostField })), value: formState.hostField, }), [formState.hostField] @@ -96,7 +96,7 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.podField), name: `podField`, - onChange: podField => setFormStateChanges(changes => ({ ...changes, podField })), + onChange: (podField) => setFormStateChanges((changes) => ({ ...changes, podField })), value: formState.podField, }), [formState.podField] @@ -106,8 +106,8 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.tiebreakerField), name: `tiebreakerField`, - onChange: tiebreakerField => - setFormStateChanges(changes => ({ ...changes, tiebreakerField })), + onChange: (tiebreakerField) => + setFormStateChanges((changes) => ({ ...changes, tiebreakerField })), value: formState.tiebreakerField, }), [formState.tiebreakerField] @@ -117,8 +117,8 @@ export const useIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.timestampField), name: `timestampField`, - onChange: timestampField => - setFormStateChanges(changes => ({ ...changes, timestampField })), + onChange: (timestampField) => + setFormStateChanges((changes) => ({ ...changes, timestampField })), value: formState.timestampField, }), [formState.timestampField] diff --git a/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_form_state.tsx b/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_form_state.tsx index 0b6a92ed98507..b7e7cb08ec633 100644 --- a/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_form_state.tsx +++ b/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_form_state.tsx @@ -68,9 +68,9 @@ export const useLogColumnsConfigurationFormState = ({ formState.logColumns.map( (logColumn): LogColumnConfigurationProps => { const remove = () => - setFormStateChanges(changes => ({ + setFormStateChanges((changes) => ({ ...changes, - logColumns: formState.logColumns.filter(item => item !== logColumn), + logColumns: formState.logColumns.filter((item) => item !== logColumn), })); if (isTimestampLogColumnConfiguration(logColumn)) { @@ -99,7 +99,7 @@ export const useLogColumnsConfigurationFormState = ({ const addLogColumn = useCallback( (logColumnConfiguration: LogColumnConfiguration) => - setFormStateChanges(changes => ({ + setFormStateChanges((changes) => ({ ...changes, logColumns: [...formState.logColumns, logColumnConfiguration], })), @@ -111,7 +111,7 @@ export const useLogColumnsConfigurationFormState = ({ if (destinationIndex >= 0 && sourceIndex <= formState.logColumns.length - 1) { const newLogColumns = [...formState.logColumns]; newLogColumns.splice(destinationIndex, 0, newLogColumns.splice(sourceIndex, 1)[0]); - setFormStateChanges(changes => ({ + setFormStateChanges((changes) => ({ ...changes, logColumns: newLogColumns, })); diff --git a/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_panel.tsx b/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_panel.tsx index 9ccd28f149ec7..46ab1e65c29d1 100644 --- a/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_panel.tsx +++ b/x-pack/plugins/infra/public/components/source_configuration/log_columns_configuration_panel.tsx @@ -85,7 +85,7 @@ export const LogColumnsConfigurationPanel: React.FunctionComponent - {provided => ( + {(provided) => ( = props => ( +const LogColumnConfigurationPanel: React.FunctionComponent = ( + props +) => ( <> {props.logColumnConfigurationProps.type === 'timestamp' ? ( diff --git a/x-pack/plugins/infra/public/components/source_configuration/source_configuration_settings.tsx b/x-pack/plugins/infra/public/components/source_configuration/source_configuration_settings.tsx index 7f248cd103003..43bdc1f4cedcc 100644 --- a/x-pack/plugins/infra/public/components/source_configuration/source_configuration_settings.tsx +++ b/x-pack/plugins/infra/public/components/source_configuration/source_configuration_settings.tsx @@ -46,7 +46,7 @@ export const SourceConfigurationSettings = ({ } = useContext(Source.Context); const availableFields = useMemo( - () => (source && source.status ? source.status.indexFields.map(field => field.name) : []), + () => (source && source.status ? source.status.indexFields.map((field) => field.name) : []), [source] ); diff --git a/x-pack/plugins/infra/public/components/toolbar_panel.ts b/x-pack/plugins/infra/public/components/toolbar_panel.ts index 65cde03ec98e7..686b563068d60 100644 --- a/x-pack/plugins/infra/public/components/toolbar_panel.ts +++ b/x-pack/plugins/infra/public/components/toolbar_panel.ts @@ -15,5 +15,5 @@ export const ToolbarPanel = euiStyled(EuiPanel).attrs(() => ({ border-right: none; border-left: none; border-radius: 0; - padding: ${props => `12px ${props.theme.eui.paddingSizes.m}`}; + padding: ${(props) => `12px ${props.theme.eui.paddingSizes.m}`}; `; diff --git a/x-pack/plugins/infra/public/compose_libs.ts b/x-pack/plugins/infra/public/compose_libs.ts index debd83f43d52c..f2060983e95eb 100644 --- a/x-pack/plugins/infra/public/compose_libs.ts +++ b/x-pack/plugins/infra/public/compose_libs.ts @@ -40,7 +40,7 @@ export function composeLibs(core: CoreStart) { headers: undefined, asResponse: true, }) - .then(res => { + .then((res) => { if (!res.response) { return reject(); } diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_cleanup.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_cleanup.ts index 21ae7804292dd..6fa2ac175ace6 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_cleanup.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_cleanup.ts @@ -23,7 +23,7 @@ export const callDeleteJobs = async ( method: 'POST', body: JSON.stringify( deleteJobsRequestPayloadRT.encode({ - jobIds: jobTypes.map(jobType => getJobId(spaceId, sourceId, jobType)), + jobIds: jobTypes.map((jobType) => getJobId(spaceId, sourceId, jobType)), }) ), }); @@ -53,7 +53,7 @@ export const callStopDatafeeds = async ( method: 'POST', body: JSON.stringify( stopDatafeedsRequestPayloadRT.encode({ - datafeedIds: jobTypes.map(jobType => getDatafeedId(spaceId, sourceId, jobType)), + datafeedIds: jobTypes.map((jobType) => getDatafeedId(spaceId, sourceId, jobType)), }) ), }); diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_jobs_summary_api.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_jobs_summary_api.ts index c3c119f51ff7d..dbd75a646b532 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_jobs_summary_api.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/ml_get_jobs_summary_api.ts @@ -22,7 +22,7 @@ export const callJobsSummaryAPI = async ( method: 'POST', body: JSON.stringify( fetchJobStatusRequestPayloadRT.encode({ - jobIds: jobTypes.map(jobType => getJobId(spaceId, sourceId, jobType)), + jobIds: jobTypes.map((jobType) => getJobId(spaceId, sourceId, jobType)), }) ), }); diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx index 7bee10c3bfaa7..9116900ec2196 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx @@ -33,7 +33,7 @@ export const useLogAnalysisCapabilities = () => { fold(throwErrors(createPlainError), identity) ); }, - onResolve: response => { + onResolve: (response) => { setMlCapabilities(response); }, }, diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_cleanup.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_cleanup.tsx index a37d18cc33cfd..522616f83d0cb 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_cleanup.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_cleanup.tsx @@ -39,10 +39,10 @@ const waitUntilJobsAreDeleted = async ( sourceId: string, jobTypes: JobType[] ) => { - const moduleJobIds = jobTypes.map(jobType => getJobId(spaceId, sourceId, jobType)); + const moduleJobIds = jobTypes.map((jobType) => getJobId(spaceId, sourceId, jobType)); while (true) { const { jobIds: jobIdsBeingDeleted } = await callGetJobDeletionTasks(); - const needToWait = jobIdsBeingDeleted.some(jobId => moduleJobIds.includes(jobId)); + const needToWait = jobIdsBeingDeleted.some((jobId) => moduleJobIds.includes(jobId)); if (needToWait) { await timeout(1000); @@ -52,4 +52,4 @@ const waitUntilJobsAreDeleted = async ( } }; -const timeout = (ms: number) => new Promise(res => setTimeout(res, ms)); +const timeout = (ms: number) => new Promise((res) => setTimeout(res, ms)); diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx index cecfea28100ad..a70758e3aefd7 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx @@ -27,7 +27,7 @@ export const useLogAnalysisModule = ({ dispatchModuleStatus({ type: 'fetchingJobStatuses' }); return await moduleDescriptor.getJobSummary(spaceId, sourceId); }, - onResolve: jobResponse => { + onResolve: (jobResponse) => { dispatchModuleStatus({ type: 'fetchedJobStatuses', payload: jobResponse, diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_configuration.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_configuration.ts index ba2185ff83784..353580f454aa3 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_configuration.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_configuration.ts @@ -48,5 +48,5 @@ export const isJobConfigurationOutdated = ( }; const isSubset = (subset: Set, superset: Set) => { - return Array.from(subset).every(subsetElement => superset.has(subsetElement)); + return Array.from(subset).every((subsetElement) => superset.has(subsetElement)); }; diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_definition.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_definition.tsx index ea0cd32c0b93e..1f643d0e5eb34 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_definition.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_definition.tsx @@ -42,7 +42,7 @@ export const useLogAnalysisModuleDefinition = ({ createPromise: async () => { return await moduleDescriptor.getModuleDefinition(); }, - onResolve: response => { + onResolve: (response) => { setModuleDefinition(response); }, onReject: () => { diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx index b5530f9ebf72e..0d478ddd0407a 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx @@ -98,7 +98,7 @@ const createStatusReducer = (jobTypes: JobType[]) => ( {} as Record ); const nextSetupStatus: SetupStatus = Object.values(nextJobStatus).every( - jobState => jobState === 'started' + (jobState) => jobState === 'started' ) ? { type: 'succeeded' } : { @@ -106,10 +106,10 @@ const createStatusReducer = (jobTypes: JobType[]) => ( reasons: [ ...Object.values(datafeedSetupResults) .filter(hasError) - .map(datafeed => datafeed.error.msg), + .map((datafeed) => datafeed.error.msg), ...Object.values(jobSetupResults) .filter(hasError) - .map(job => job.error.msg), + .map((job) => job.error.msg), ], }; @@ -201,7 +201,7 @@ const hasSuccessfullyCreatedJob = (jobId: string) => ( jobSetupResponses: SetupMlModuleResponsePayload['jobs'] ) => jobSetupResponses.filter( - jobSetupResponse => + (jobSetupResponse) => jobSetupResponse.id === jobId && jobSetupResponse.success && !jobSetupResponse.error ).length > 0; @@ -209,7 +209,7 @@ const hasSuccessfullyStartedDatafeed = (datafeedId: string) => ( datafeedSetupResponses: SetupMlModuleResponsePayload['datafeeds'] ) => datafeedSetupResponses.filter( - datafeedSetupResponse => + (datafeedSetupResponse) => datafeedSetupResponse.id === datafeedId && datafeedSetupResponse.success && datafeedSetupResponse.started && @@ -218,7 +218,7 @@ const hasSuccessfullyStartedDatafeed = (datafeedId: string) => ( const getJobStatus = (jobId: string) => (jobSummaries: FetchJobStatusResponsePayload): JobStatus => jobSummaries - .filter(jobSummary => jobSummary.id === jobId) + .filter((jobSummary) => jobSummary.id === jobId) .map( (jobSummary): JobStatus => { if (jobSummary.jobState === 'failed' || jobSummary.datafeedState === '') { diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_setup_state.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_setup_state.ts index 9f757497aff81..e6fe8f4e92cc4 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_setup_state.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_setup_state.ts @@ -52,7 +52,7 @@ export const useAnalysisSetupState = ({ ); const [validatedIndices, setValidatedIndices] = useState( - sourceConfiguration.indices.map(indexName => ({ + sourceConfiguration.indices.map((indexName) => ({ name: indexName, validity: 'unknown' as const, })) @@ -60,8 +60,8 @@ export const useAnalysisSetupState = ({ const updateIndicesWithValidationErrors = useCallback( (validationErrors: ValidationIndicesError[]) => - setValidatedIndices(availableIndices => - availableIndices.map(previousAvailableIndex => { + setValidatedIndices((availableIndices) => + availableIndices.map((previousAvailableIndex) => { const indexValiationErrors = validationErrors.filter( ({ index }) => index === previousAvailableIndex.name ); @@ -96,8 +96,8 @@ export const useAnalysisSetupState = ({ const updateIndicesWithAvailableDatasets = useCallback( (availableDatasets: Array<{ indexName: string; datasets: string[] }>) => - setValidatedIndices(availableIndices => - availableIndices.map(previousAvailableIndex => { + setValidatedIndices((availableIndices) => + availableIndices.map((previousAvailableIndex) => { if (previousAvailableIndex.validity !== 'valid') { return previousAvailableIndex; } @@ -112,7 +112,7 @@ export const useAnalysisSetupState = ({ // filter out datasets that have disappeared if this index' datasets were updated const newDatasetFilter: DatasetFilter = availableDatasetsForIndex.length > 0 - ? filterDatasetFilter(previousAvailableIndex.datasetFilter, dataset => + ? filterDatasetFilter(previousAvailableIndex.datasetFilter, (dataset) => newAvailableDatasets.includes(dataset) ) : previousAvailableIndex.datasetFilter; @@ -128,22 +128,22 @@ export const useAnalysisSetupState = ({ ); const validIndexNames = useMemo( - () => validatedIndices.filter(index => index.validity === 'valid').map(index => index.name), + () => validatedIndices.filter((index) => index.validity === 'valid').map((index) => index.name), [validatedIndices] ); const selectedIndexNames = useMemo( () => validatedIndices - .filter(index => index.validity === 'valid' && index.isSelected) - .map(i => i.name), + .filter((index) => index.validity === 'valid' && index.isSelected) + .map((i) => i.name), [validatedIndices] ); const datasetFilter = useMemo( () => validatedIndices - .flatMap(validatedIndex => + .flatMap((validatedIndex) => validatedIndex.validity === 'valid' ? validatedIndex.datasetFilter : { type: 'includeAll' as const } diff --git a/x-pack/plugins/infra/public/containers/logs/log_entries/index.ts b/x-pack/plugins/infra/public/containers/logs/log_entries/index.ts index b9a5c4068e166..a6d66d47975c0 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_entries/index.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_entries/index.ts @@ -98,8 +98,8 @@ export const logEntriesInitialState: LogEntriesStateParams = { }; const cleanDuplicateItems = (entriesA: LogEntry[], entriesB: LogEntry[]) => { - const ids = new Set(entriesB.map(item => item.id)); - return entriesA.filter(item => !ids.has(item.id)); + const ids = new Set(entriesB.map((item) => item.id)); + return entriesA.filter((item) => !ids.has(item.id)); }; const shouldFetchNewEntries = ({ @@ -280,7 +280,7 @@ const useFetchEntriesEffect = ( (async () => { if (props.isStreaming && !state.isLoadingMore && !state.isReloading) { if (startedStreaming) { - await new Promise(res => setTimeout(res, LIVE_STREAM_INTERVAL)); + await new Promise((res) => setTimeout(res, LIVE_STREAM_INTERVAL)); } else { const endTimestamp = Date.now(); props.jumpToTargetPosition({ tiebreaker: 0, time: endTimestamp }); @@ -335,7 +335,7 @@ const useFetchEntriesEffect = ( export const useLogEntriesState: ( props: LogEntriesProps -) => [LogEntriesStateParams, LogEntriesCallbacks] = props => { +) => [LogEntriesStateParams, LogEntriesCallbacks] = (props) => { const [state, dispatch] = useReducer(logEntriesStateReducer, logEntriesInitialState); const { fetchNewerEntries, checkForNewEntries } = useFetchEntriesEffect(state, dispatch, props); diff --git a/x-pack/plugins/infra/public/containers/logs/log_filter/log_filter_state.ts b/x-pack/plugins/infra/public/containers/logs/log_filter/log_filter_state.ts index dd1ba585061fe..7c903f59002dc 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_filter/log_filter_state.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_filter/log_filter_state.ts @@ -48,7 +48,7 @@ export const useLogFilterState: (props: { const setLogFilterQueryDraft = useMemo(() => { const setDraft = (payload: KueryFilterQuery) => - setState(prevState => ({ ...prevState, filterQueryDraft: payload })); + setState((prevState) => ({ ...prevState, filterQueryDraft: payload })); return (expression: string) => setDraft({ kind: 'kuery', @@ -57,7 +57,7 @@ export const useLogFilterState: (props: { }, []); const applyLogFilterQuery = useMemo(() => { const applyQuery = (payload: SerializedFilterQuery) => - setState(prevState => ({ + setState((prevState) => ({ ...prevState, filterQueryDraft: payload.query, filterQuery: payload, diff --git a/x-pack/plugins/infra/public/containers/logs/log_filter/with_log_filter_url_state.tsx b/x-pack/plugins/infra/public/containers/logs/log_filter/with_log_filter_url_state.tsx index d1da6c715cfc5..24c3f104c2369 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_filter/with_log_filter_url_state.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_filter/with_log_filter_url_state.tsx @@ -17,12 +17,12 @@ export const WithLogFilterUrlState: React.FC = () => { urlState={filterQueryAsKuery} urlStateKey="logFilter" mapToUrlState={mapToFilterQuery} - onChange={urlState => { + onChange={(urlState) => { if (urlState) { applyLogFilterQuery(urlState.expression); } }} - onInitialize={urlState => { + onInitialize={(urlState) => { if (urlState) { applyLogFilterQuery(urlState.expression); } diff --git a/x-pack/plugins/infra/public/containers/logs/log_flyout.tsx b/x-pack/plugins/infra/public/containers/logs/log_flyout.tsx index b0981f9b3c41f..0489892e58f2a 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_flyout.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_flyout.tsx @@ -41,7 +41,7 @@ export const useLogFlyout = () => { } return await fetchLogEntriesItem({ sourceId, id: flyoutId }); }, - onResolve: response => { + onResolve: (response) => { if (response) { const { data } = response; setFlyoutItem(data || null); @@ -94,7 +94,7 @@ export const WithFlyoutOptionsUrlState = () => { }} urlStateKey="flyoutOptions" mapToUrlState={mapToUrlState} - onChange={newUrlState => { + onChange={(newUrlState) => { if (newUrlState && newUrlState.flyoutId) { setFlyoutId(newUrlState.flyoutId); } @@ -108,7 +108,7 @@ export const WithFlyoutOptionsUrlState = () => { setFlyoutVisibility(false); } }} - onInitialize={initialUrlState => { + onInitialize={(initialUrlState) => { if (initialUrlState && initialUrlState.flyoutId) { setFlyoutId(initialUrlState.flyoutId); } diff --git a/x-pack/plugins/infra/public/containers/logs/log_highlights/log_entry_highlights.tsx b/x-pack/plugins/infra/public/containers/logs/log_highlights/log_entry_highlights.tsx index 7701850443768..dbeb8c71c11eb 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_highlights/log_entry_highlights.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_highlights/log_entry_highlights.tsx @@ -42,7 +42,7 @@ export const useLogEntryHighlights = ( highlightTerms, }); }, - onResolve: response => { + onResolve: (response) => { setLogEntryHighlights(response.data); }, }, @@ -55,7 +55,7 @@ export const useLogEntryHighlights = ( useEffect(() => { if ( - highlightTerms.filter(highlightTerm => highlightTerm.length > 0).length && + highlightTerms.filter((highlightTerm) => highlightTerm.length > 0).length && startTimestamp && endTimestamp ) { diff --git a/x-pack/plugins/infra/public/containers/logs/log_highlights/log_summary_highlights.ts b/x-pack/plugins/infra/public/containers/logs/log_highlights/log_summary_highlights.ts index 41ee63bf0e23d..6d982ee004ccc 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_highlights/log_summary_highlights.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_highlights/log_summary_highlights.ts @@ -43,7 +43,7 @@ export const useLogSummaryHighlights = ( highlightTerms, }); }, - onResolve: response => { + onResolve: (response) => { setLogSummaryHighlights(response.data); }, }, @@ -60,7 +60,7 @@ export const useLogSummaryHighlights = ( useEffect(() => { if ( - highlightTerms.filter(highlightTerm => highlightTerm.length > 0).length && + highlightTerms.filter((highlightTerm) => highlightTerm.length > 0).length && startTimestamp && endTimestamp ) { diff --git a/x-pack/plugins/infra/public/containers/logs/log_summary/log_summary.tsx b/x-pack/plugins/infra/public/containers/logs/log_summary/log_summary.tsx index 94723125cc0ec..b83be77656863 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_summary/log_summary.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_summary/log_summary.tsx @@ -23,7 +23,7 @@ export const useLogSummary = ( const bucketSize = useBucketSize(startTimestamp, endTimestamp); useCancellableEffect( - getIsCancelled => { + (getIsCancelled) => { if (startTimestamp === null || endTimestamp === null || bucketSize === null) { return; } @@ -34,7 +34,7 @@ export const useLogSummary = ( endTimestamp, bucketSize, query: filterQuery, - }).then(response => { + }).then((response) => { if (!getIsCancelled()) { setLogSummaryBuckets(response.data.buckets); } diff --git a/x-pack/plugins/infra/public/containers/logs/with_log_textview.tsx b/x-pack/plugins/infra/public/containers/logs/with_log_textview.tsx index fef7eb19fcf90..ad669e3fe7264 100644 --- a/x-pack/plugins/infra/public/containers/logs/with_log_textview.tsx +++ b/x-pack/plugins/infra/public/containers/logs/with_log_textview.tsx @@ -26,7 +26,7 @@ export const WithLogTextviewUrlState = () => { urlState={urlState} urlStateKey="logTextview" mapToUrlState={mapToUrlState} - onChange={newUrlState => { + onChange={(newUrlState) => { if (newUrlState && newUrlState.textScale) { setTextScale(newUrlState.textScale); } @@ -34,7 +34,7 @@ export const WithLogTextviewUrlState = () => { setTextWrap(newUrlState.wrap); } }} - onInitialize={newUrlState => { + onInitialize={(newUrlState) => { if (newUrlState && newUrlState.textScale) { setTextScale(newUrlState.textScale); } diff --git a/x-pack/plugins/infra/public/containers/logs/with_stream_items.ts b/x-pack/plugins/infra/public/containers/logs/with_stream_items.ts index 5c0e245448ce5..2b8986820d5a4 100644 --- a/x-pack/plugins/infra/public/containers/logs/with_stream_items.ts +++ b/x-pack/plugins/infra/public/containers/logs/with_stream_items.ts @@ -29,7 +29,7 @@ export const WithStreamItems: React.FunctionComponent<{ () => logEntries.isReloading ? [] - : logEntries.entries.map(logEntry => + : logEntries.entries.map((logEntry) => createLogEntryStreamItem(logEntry, logEntryHighlightsById[logEntry.id] || []) ), diff --git a/x-pack/plugins/infra/public/containers/metrics_explorer/with_metrics_explorer_options_url_state.tsx b/x-pack/plugins/infra/public/containers/metrics_explorer/with_metrics_explorer_options_url_state.tsx index 04f518aa9080f..b0823f8717a84 100644 --- a/x-pack/plugins/infra/public/containers/metrics_explorer/with_metrics_explorer_options_url_state.tsx +++ b/x-pack/plugins/infra/public/containers/metrics_explorer/with_metrics_explorer_options_url_state.tsx @@ -81,7 +81,7 @@ function isMetricExplorerOptions(subject: any): subject is MetricsExplorerOption field: t.string, rate: t.boolean, color: t.keyof( - Object.fromEntries(values(MetricsExplorerColor).map(c => [c, null])) as Record + Object.fromEntries(values(MetricsExplorerColor).map((c) => [c, null])) as Record ), label: t.string, }); @@ -114,13 +114,13 @@ function isMetricExplorerOptions(subject: any): subject is MetricsExplorerOption function isMetricExplorerChartOptions(subject: any): subject is MetricsExplorerChartOptions { const ChartOptions = t.type({ yAxisMode: t.keyof( - Object.fromEntries(values(MetricsExplorerYAxisMode).map(v => [v, null])) as Record< + Object.fromEntries(values(MetricsExplorerYAxisMode).map((v) => [v, null])) as Record< string, null > ), type: t.keyof( - Object.fromEntries(values(MetricsExplorerChartType).map(v => [v, null])) as Record< + Object.fromEntries(values(MetricsExplorerChartType).map((v) => [v, null])) as Record< string, null > diff --git a/x-pack/plugins/infra/public/containers/source/source.tsx b/x-pack/plugins/infra/public/containers/source/source.tsx index c2206769ef0ef..96bbd858c3a4b 100644 --- a/x-pack/plugins/infra/public/containers/source/source.tsx +++ b/x-pack/plugins/infra/public/containers/source/source.tsx @@ -54,7 +54,7 @@ export const useSource = ({ sourceId }: { sourceId: string }) => { }, }); }, - onResolve: response => { + onResolve: (response) => { setSource(response.data.source); }, }, @@ -82,7 +82,7 @@ export const useSource = ({ sourceId }: { sourceId: string }) => { }, }); }, - onResolve: response => { + onResolve: (response) => { if (response.data) { setSource(response.data.createSource.source); } @@ -112,7 +112,7 @@ export const useSource = ({ sourceId }: { sourceId: string }) => { }, }); }, - onResolve: response => { + onResolve: (response) => { if (response.data) { setSource(response.data.updateSource.source); } @@ -134,7 +134,7 @@ export const useSource = ({ sourceId }: { sourceId: string }) => { loadSourceRequest.state, createSourceConfigurationRequest.state, updateSourceConfigurationRequest.state, - ].some(state => state === 'pending'), + ].some((state) => state === 'pending'), [ loadSourceRequest.state, createSourceConfigurationRequest.state, diff --git a/x-pack/plugins/infra/public/containers/with_kuery_autocompletion.tsx b/x-pack/plugins/infra/public/containers/with_kuery_autocompletion.tsx index 98e59227bc6f0..a04897d9c738d 100644 --- a/x-pack/plugins/infra/public/containers/with_kuery_autocompletion.tsx +++ b/x-pack/plugins/infra/public/containers/with_kuery_autocompletion.tsx @@ -85,7 +85,7 @@ class WithKueryAutocompletionComponent extends React.Component< boolFilter: [], })) || []; - this.setState(state => + this.setState((state) => state.currentRequest && state.currentRequest.expression !== expression && state.currentRequest.cursorPosition !== cursorPosition diff --git a/x-pack/plugins/infra/public/hooks/use_bulk_get_saved_object.tsx b/x-pack/plugins/infra/public/hooks/use_bulk_get_saved_object.tsx index 2c553b57dcd48..2a70edc9b9a57 100644 --- a/x-pack/plugins/infra/public/hooks/use_bulk_get_saved_object.tsx +++ b/x-pack/plugins/infra/public/hooks/use_bulk_get_saved_object.tsx @@ -24,7 +24,7 @@ export const useBulkGetSavedObject = (type: string) => { if (!savedObjectsClient) { throw new Error('Saved objects client is unavailable'); } - const d = await savedObjectsClient.bulkGet(ids.map(i => ({ type, id: i }))); + const d = await savedObjectsClient.bulkGet(ids.map((i) => ({ type, id: i }))); setError(null); setLoading(false); setData(d); diff --git a/x-pack/plugins/infra/public/hooks/use_find_saved_object.tsx b/x-pack/plugins/infra/public/hooks/use_find_saved_object.tsx index 2b704e7984415..8b0ab45f6e6d1 100644 --- a/x-pack/plugins/infra/public/hooks/use_find_saved_object.tsx +++ b/x-pack/plugins/infra/public/hooks/use_find_saved_object.tsx @@ -48,7 +48,7 @@ export const useFindSavedObject = ({ type, }); - return objects.savedObjects.filter(o => o.attributes.name === name).length > 0; + return objects.savedObjects.filter((o) => o.attributes.name === name).length > 0; }; return { diff --git a/x-pack/plugins/infra/public/hooks/use_http_request.tsx b/x-pack/plugins/infra/public/hooks/use_http_request.tsx index 0a0c876bb63ce..943aa059d5951 100644 --- a/x-pack/plugins/infra/public/hooks/use_http_request.tsx +++ b/x-pack/plugins/infra/public/hooks/use_http_request.tsx @@ -16,7 +16,7 @@ export function useHTTPRequest( pathname: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD', body?: string | null, - decode: (response: any) => Response = response => response, + decode: (response: any) => Response = (response) => response, fetch?: HttpHandler, toastWarning?: (input: ToastInput) => void ) { @@ -37,7 +37,7 @@ export function useHTTPRequest( body, }); }, - onResolve: resp => setResponse(decode(resp)), + onResolve: (resp) => setResponse(decode(resp)), onReject: (e: unknown) => { const err = e as IHttpFetchError; setError(err); diff --git a/x-pack/plugins/infra/public/hooks/use_saved_view.ts b/x-pack/plugins/infra/public/hooks/use_saved_view.ts index 4b12b6c51ea0e..60869d8267b8c 100644 --- a/x-pack/plugins/infra/public/hooks/use_saved_view.ts +++ b/x-pack/plugins/infra/public/hooks/use_saved_view.ts @@ -65,7 +65,7 @@ export const useSavedView = (defaultViewState: ViewState, viewType: s ]; savedObjects.forEach( - o => + (o) => o.type === viewType && items.push({ ...o.attributes, diff --git a/x-pack/plugins/infra/public/pages/error.tsx b/x-pack/plugins/infra/public/pages/error.tsx index b8b598ba1a98b..c34af31ce28a7 100644 --- a/x-pack/plugins/infra/public/pages/error.tsx +++ b/x-pack/plugins/infra/public/pages/error.tsx @@ -21,7 +21,7 @@ import { ColumnarPage, PageContent } from '../components/page'; const DetailPageContent = euiStyled(PageContent)` overflow: auto; - background-color: ${props => props.theme.eui.euiColorLightestShade}; + background-color: ${(props) => props.theme.eui.euiColorLightestShade}; `; interface Props { diff --git a/x-pack/plugins/infra/public/pages/link_to/link_to_logs.tsx b/x-pack/plugins/infra/public/pages/link_to/link_to_logs.tsx index 04d5c454a92cc..7a77b1525aea3 100644 --- a/x-pack/plugins/infra/public/pages/link_to/link_to_logs.tsx +++ b/x-pack/plugins/infra/public/pages/link_to/link_to_logs.tsx @@ -18,9 +18,9 @@ interface LinkToPageProps { }; } -const ITEM_TYPES = inventoryModels.map(m => m.id).join('|'); +const ITEM_TYPES = inventoryModels.map((m) => m.id).join('|'); -export const LinkToLogsPage: React.FC = props => { +export const LinkToLogsPage: React.FC = (props) => { return ( ; } -const ITEM_TYPES = inventoryModels.map(m => m.id).join('|'); +const ITEM_TYPES = inventoryModels.map((m) => m.id).join('|'); -export const LinkToMetricsPage: React.FC = props => { +export const LinkToMetricsPage: React.FC = (props) => { return ( - renderHook(props => useHostIpToName(props.ipAddress, props.indexPattern), { + renderHook((props) => useHostIpToName(props.ipAddress, props.indexPattern), { initialProps: { ipAddress: '127.0.0.1', indexPattern: 'metricbest-*' }, }); diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/module_descriptor.ts b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/module_descriptor.ts index 45cdd28bd943b..8d9b9130f74a4 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/module_descriptor.ts +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/module_descriptor.ts @@ -39,7 +39,7 @@ const getJobSummary = async (spaceId: string, sourceId: string) => { const response = await callJobsSummaryAPI(spaceId, sourceId, logEntryCategoriesJobTypes); const jobIds = Object.values(getJobIds(spaceId, sourceId)); - return response.filter(jobSummary => jobIds.includes(jobSummary.id)); + return response.filter((jobSummary) => jobIds.includes(jobSummary.id)); }; const getModuleDefinition = async () => { diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx index e304a8835e99c..73468dea5d949 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx @@ -89,7 +89,7 @@ export const LogEntryCategoriesResultsContent: React.FunctionComponent = () => { const handleQueryTimeRangeChange = useCallback( ({ start: startTime, end: endTime }: { start: string; end: string }) => { - setCategoryQueryTimeRange(previousQueryParameters => ({ + setCategoryQueryTimeRange((previousQueryParameters) => ({ ...previousQueryParameters, timeRange: stringToNumericTimeRange({ startTime, endTime }), lastChangedTime: Date.now(), diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/anomaly_severity_indicator_list.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/anomaly_severity_indicator_list.tsx index 6035c032bdece..dafaa37006be0 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/anomaly_severity_indicator_list.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/anomaly_severity_indicator_list.tsx @@ -14,7 +14,7 @@ export const AnomalySeverityIndicatorList: React.FunctionComponent<{ datasets: LogEntryCategoryDataset[]; }> = ({ datasets }) => (
      - {datasets.map(dataset => { + {datasets.map((dataset) => { const datasetLabel = getFriendlyNameForPartitionId(dataset.name); return (
    • diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/category_expression.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/category_expression.tsx index f6cf62421e2d5..be8281ce54556 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/category_expression.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/category_expression.tsx @@ -48,12 +48,12 @@ export const RegularExpressionRepresentation: React.FunctionComponent<{ }); const CategoryPattern = euiStyled.span` - font-family: ${props => props.theme.eui.euiCodeFontFamily}; + font-family: ${(props) => props.theme.eui.euiCodeFontFamily}; word-break: break-all; `; const CategoryPatternWildcard = euiStyled.span` - color: ${props => props.theme.eui.euiColorMediumShade}; + color: ${(props) => props.theme.eui.euiColorMediumShade}; `; const CategoryPatternSegment = euiStyled.span` diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_action_list.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_action_list.tsx index a3705cb28ed05..2321dafaead1c 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_action_list.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_action_list.tsx @@ -18,7 +18,7 @@ export const DatasetActionsList: React.FunctionComponent<{ timeRange: TimeRange; }> = ({ categorizationJobId, categoryId, datasets, timeRange }) => (
        - {datasets.map(dataset => { + {datasets.map((dataset) => { const datasetLabel = getFriendlyNameForPartitionId(dataset.name); return (
      • diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_list.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_list.tsx index 6918ae0914cc6..748c82cc5cd5a 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_list.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_list.tsx @@ -14,7 +14,7 @@ export const DatasetsList: React.FunctionComponent<{ datasets: LogEntryCategoryDataset[]; }> = ({ datasets }) => (
          - {datasets.map(dataset => { + {datasets.map((dataset) => { const datasetLabel = getFriendlyNameForPartitionId(dataset.name); return (
        • diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_selector.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_selector.tsx index c2087e9032f59..ab938ff1d1374 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_selector.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/datasets_selector.tsx @@ -20,7 +20,7 @@ export const DatasetsSelector: React.FunctionComponent<{ }> = ({ availableDatasets, isLoading = false, onChangeDatasetSelection, selectedDatasets }) => { const options = useMemo( () => - availableDatasets.map(dataset => ({ + availableDatasets.map((dataset) => ({ value: dataset, label: getFriendlyNameForPartitionId(dataset), })), diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/log_entry_count_sparkline.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/log_entry_count_sparkline.tsx index 7a29ea9aa0ebc..42d6509802ed4 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/log_entry_count_sparkline.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/log_entry_count_sparkline.tsx @@ -19,7 +19,7 @@ export const LogEntryCountSparkline: React.FunctionComponent<{ const metric = useMemo( () => histograms - .find(histogram => histogram.histogramId === 'history') + .find((histogram) => histogram.histogramId === 'history') ?.buckets?.map(({ startTime: timestamp, logEntryCount: value }) => ({ timestamp, value, @@ -28,7 +28,7 @@ export const LogEntryCountSparkline: React.FunctionComponent<{ ); const referenceCount = useMemo( () => - histograms.find(histogram => histogram.histogramId === 'reference')?.buckets?.[0] + histograms.find((histogram) => histogram.histogramId === 'reference')?.buckets?.[0] ?.logEntryCount ?? 0, [histograms] ); diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/top_categories_table.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/top_categories_table.tsx index 811dcba7ff3ef..4fd8aa3cdc1dd 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/top_categories_table.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/top_categories/top_categories_table.tsx @@ -155,7 +155,7 @@ const createColumns = ( { actions: [ { - render: category => ( + render: (category) => ( Object.values(logAnalysisModule.jobStatus).some( - currentJobStatus => currentJobStatus === 'stopped' + (currentJobStatus) => currentJobStatus === 'stopped' ), [logAnalysisModule.jobStatus] ); diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_quality.ts b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_quality.ts index 031479e66386f..51e049d576235 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_quality.ts +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_quality.ts @@ -14,9 +14,9 @@ export const useLogEntryCategoriesQuality = ({ jobSummaries }: { jobSummaries: J () => jobSummaries .filter( - jobSummary => jobSummary.fullJob?.model_size_stats?.categorization_status === 'warn' + (jobSummary) => jobSummary.fullJob?.model_size_stats?.categorization_status === 'warn' ) - .map(jobSummary => ({ + .map((jobSummary) => ({ type: 'categoryQualityWarning', jobId: jobSummary.id, reasons: jobSummary.fullJob?.model_size_stats diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_results.ts b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_results.ts index 2282582dc2bd6..123b188046b85 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_results.ts +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_results.ts @@ -54,7 +54,7 @@ export const useLogEntryCategoriesResults = ({ onResolve: ({ data: { categories } }) => { setTopLogEntryCategories(categories); }, - onReject: error => { + onReject: (error) => { if ( error instanceof Error && !(error instanceof CanceledPromiseError) && @@ -76,7 +76,7 @@ export const useLogEntryCategoriesResults = ({ onResolve: ({ data: { datasets } }) => { setLogEntryCategoryDatasets(datasets); }, - onReject: error => { + onReject: (error) => { if ( error instanceof Error && !(error instanceof CanceledPromiseError) && diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/module_descriptor.ts b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/module_descriptor.ts index dfd427138aaa6..6ca306f39e947 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/module_descriptor.ts +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/module_descriptor.ts @@ -38,7 +38,7 @@ const getJobSummary = async (spaceId: string, sourceId: string) => { const response = await callJobsSummaryAPI(spaceId, sourceId, logEntryRateJobTypes); const jobIds = Object.values(getJobIds(spaceId, sourceId)); - return response.filter(jobSummary => jobIds.includes(jobSummary.id)); + return response.filter((jobSummary) => jobIds.includes(jobSummary.id)); }; const getModuleDefinition = async () => { diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/anomalies/chart.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/anomalies/chart.tsx index 46e41f227c08d..79ab4475ee5a3 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/anomalies/chart.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/anomalies/chart.tsx @@ -80,7 +80,7 @@ export const AnomaliesChart: React.FunctionComponent<{ numeral(value.toPrecision(3)).format('0[.][00]a')} // https://github.com/adamwdraper/Numeral-js/issues/194 + tickFormat={(value) => numeral(value.toPrecision(3)).format('0[.][00]a')} // https://github.com/adamwdraper/Numeral-js/issues/194 /> = ({ isLoading, results, setTimeRange, timeRange, viewSetupForReconfiguration, jobId }) => { const hasAnomalies = useMemo(() => { return results && results.histogramBuckets - ? results.histogramBuckets.some(bucket => { - return bucket.partitions.some(partition => { + ? results.histogramBuckets.some((bucket) => { + return bucket.partitions.some((partition) => { return partition.anomalies.length > 0; }); }) diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/helpers/data_formatters.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/helpers/data_formatters.tsx index e8e4c18e7420c..5f578eb1932e6 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/helpers/data_formatters.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/helpers/data_formatters.tsx @@ -20,7 +20,7 @@ export const getLogEntryRatePartitionedSeries = (results: LogEntryRateResults) = (buckets, bucket) => { return [ ...buckets, - ...bucket.partitions.map(partition => ({ + ...bucket.partitions.map((partition) => ({ group: getFriendlyNameForPartitionId(partition.partitionId), time: bucket.startTime, value: partition.averageActualLogEntryRate, @@ -136,7 +136,7 @@ export const getAnnotationsForAll = (results: LogEntryRateResults) => { } const severityCategory = getSeverityCategoryForScore( Math.max( - ...maxAnomalyScoresByPartition.map(partitionScore => partitionScore.maximumAnomalyScore) + ...maxAnomalyScoresByPartition.map((partitionScore) => partitionScore.maximumAnomalyScore) ) ); if (!severityCategory) { diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/log_rate/bar_chart.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/log_rate/bar_chart.tsx index 263c888ca6000..498a9f88176f8 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/log_rate/bar_chart.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/sections/log_rate/bar_chart.tsx @@ -70,7 +70,7 @@ export const LogEntryRateBarChart: React.FunctionComponent<{ numeral(value.toPrecision(3)).format('0[.][00]a')} // https://github.com/adamwdraper/Numeral-js/issues/194 + tickFormat={(value) => numeral(value.toPrecision(3)).format('0[.][00]a')} // https://github.com/adamwdraper/Numeral-js/issues/194 /> Object.values(logAnalysisModule.jobStatus).some( - currentJobStatus => currentJobStatus === 'stopped' + (currentJobStatus) => currentJobStatus === 'stopped' ), [logAnalysisModule.jobStatus] ); diff --git a/x-pack/plugins/infra/public/pages/logs/settings/add_log_column_popover.tsx b/x-pack/plugins/infra/public/pages/logs/settings/add_log_column_popover.tsx index 6e68debceac70..551d200f1895d 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/add_log_column_popover.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/add_log_column_popover.tsx @@ -63,7 +63,7 @@ export const AddLogColumnButtonAndPopover: React.FunctionComponent<{ }, }, }, - ...availableFields.map(field => ({ + ...availableFields.map((field) => ({ optionProps: { 'data-test-subj': `addFieldLogColumn addFieldLogColumn:${field}`, // this key works around EuiSelectable using a lowercased label as @@ -84,7 +84,7 @@ export const AddLogColumnButtonAndPopover: React.FunctionComponent<{ ); const availableOptions = useMemo( - () => availableColumnOptions.map(availableColumnOption => availableColumnOption.optionProps), + () => availableColumnOptions.map((availableColumnOption) => availableColumnOption.optionProps), [availableColumnOptions] ); @@ -93,7 +93,7 @@ export const AddLogColumnButtonAndPopover: React.FunctionComponent<{ closePopover(); const selectedOptionIndex = selectedOptions.findIndex( - selectedOption => selectedOption.checked === 'on' + (selectedOption) => selectedOption.checked === 'on' ); const selectedOption = availableColumnOptions[selectedOptionIndex]; diff --git a/x-pack/plugins/infra/public/pages/logs/settings/indices_configuration_form_state.ts b/x-pack/plugins/infra/public/pages/logs/settings/indices_configuration_form_state.ts index a97e38884a5bd..bf52243f89e59 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/indices_configuration_form_state.ts +++ b/x-pack/plugins/infra/public/pages/logs/settings/indices_configuration_form_state.ts @@ -42,7 +42,7 @@ export const useLogIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.name), name: 'name', - onChange: name => setFormStateChanges(changes => ({ ...changes, name })), + onChange: (name) => setFormStateChanges((changes) => ({ ...changes, name })), value: formState.name, }), [formState.name] @@ -52,7 +52,7 @@ export const useLogIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.logAlias), name: 'logAlias', - onChange: logAlias => setFormStateChanges(changes => ({ ...changes, logAlias })), + onChange: (logAlias) => setFormStateChanges((changes) => ({ ...changes, logAlias })), value: formState.logAlias, }), [formState.logAlias] @@ -62,8 +62,8 @@ export const useLogIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.tiebreakerField), name: `tiebreakerField`, - onChange: tiebreakerField => - setFormStateChanges(changes => ({ ...changes, tiebreakerField })), + onChange: (tiebreakerField) => + setFormStateChanges((changes) => ({ ...changes, tiebreakerField })), value: formState.tiebreakerField, }), [formState.tiebreakerField] @@ -73,8 +73,8 @@ export const useLogIndicesConfigurationFormState = ({ createInputFieldProps({ errors: validateInputFieldNotEmpty(formState.timestampField), name: `timestampField`, - onChange: timestampField => - setFormStateChanges(changes => ({ ...changes, timestampField })), + onChange: (timestampField) => + setFormStateChanges((changes) => ({ ...changes, timestampField })), value: formState.timestampField, }), [formState.timestampField] diff --git a/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_form_state.tsx b/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_form_state.tsx index 0beccffe5f4e8..45c52617c77fc 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_form_state.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_form_state.tsx @@ -66,9 +66,9 @@ export const useLogColumnsConfigurationFormState = ({ formState.logColumns.map( (logColumn): LogColumnConfigurationProps => { const remove = () => - setFormStateChanges(changes => ({ + setFormStateChanges((changes) => ({ ...changes, - logColumns: formState.logColumns.filter(item => item !== logColumn), + logColumns: formState.logColumns.filter((item) => item !== logColumn), })); if (isTimestampLogColumnConfiguration(logColumn)) { @@ -97,7 +97,7 @@ export const useLogColumnsConfigurationFormState = ({ const addLogColumn = useCallback( (logColumnConfiguration: LogColumnConfiguration) => - setFormStateChanges(changes => ({ + setFormStateChanges((changes) => ({ ...changes, logColumns: [...formState.logColumns, logColumnConfiguration], })), @@ -109,7 +109,7 @@ export const useLogColumnsConfigurationFormState = ({ if (destinationIndex >= 0 && sourceIndex <= formState.logColumns.length - 1) { const newLogColumns = [...formState.logColumns]; newLogColumns.splice(destinationIndex, 0, newLogColumns.splice(sourceIndex, 1)[0]); - setFormStateChanges(changes => ({ + setFormStateChanges((changes) => ({ ...changes, logColumns: newLogColumns, })); diff --git a/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_panel.tsx b/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_panel.tsx index 777f611ef33f7..3f109e7383c0e 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_panel.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/log_columns_configuration_panel.tsx @@ -84,7 +84,7 @@ export const LogColumnsConfigurationPanel: React.FunctionComponent - {provided => ( + {(provided) => ( = props => ( +const LogColumnConfigurationPanel: React.FunctionComponent = ( + props +) => ( <> {props.logColumnConfigurationProps.type === 'timestamp' ? ( diff --git a/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_settings.tsx b/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_settings.tsx index 363b1b7627104..34c4202ab8b65 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_settings.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_settings.tsx @@ -41,7 +41,7 @@ export const LogsSettingsPage = () => { } = useLogSourceContext(); const availableFields = useMemo( - () => sourceStatus?.logIndexFields.map(field => field.name) ?? [], + () => sourceStatus?.logIndexFields.map((field) => field.name) ?? [], [sourceStatus] ); diff --git a/x-pack/plugins/infra/public/pages/logs/stream/page_toolbar.tsx b/x-pack/plugins/infra/public/pages/logs/stream/page_toolbar.tsx index 88e6ea8be4325..9fc49073d5ee1 100644 --- a/x-pack/plugins/infra/public/pages/logs/stream/page_toolbar.tsx +++ b/x-pack/plugins/infra/public/pages/logs/stream/page_toolbar.tsx @@ -101,7 +101,7 @@ export const LogsToolbar = () => { onChange={setHighlightTerms} isLoading={loadLogEntryHighlightsRequest.state === 'pending'} activeHighlights={ - highlightTerms.filter(highlightTerm => highlightTerm.length > 0).length > 0 + highlightTerms.filter((highlightTerm) => highlightTerm.length > 0).length > 0 } goToPreviousHighlight={goToPreviousHighlight} goToNextHighlight={goToNextHighlight} diff --git a/x-pack/plugins/infra/public/pages/logs/stream/page_view_log_in_context.tsx b/x-pack/plugins/infra/public/pages/logs/stream/page_view_log_in_context.tsx index 9e0f7d5035aaf..b6e6710a0b3b4 100644 --- a/x-pack/plugins/infra/public/pages/logs/stream/page_view_log_in_context.tsx +++ b/x-pack/plugins/infra/public/pages/logs/stream/page_view_log_in_context.tsx @@ -39,7 +39,7 @@ export const PageViewLogInContext: React.FC = () => { const streamItems = useMemo( () => - entries.map(entry => ({ + entries.map((entry) => ({ kind: 'logEntry' as const, logEntry: entry, highlights: [], diff --git a/x-pack/plugins/infra/public/pages/metrics/index.tsx b/x-pack/plugins/infra/public/pages/metrics/index.tsx index 91362d9098e34..35a6cadc786f6 100644 --- a/x-pack/plugins/infra/public/pages/metrics/index.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/index.tsx @@ -109,7 +109,7 @@ export const InfrastructurePage = ({ match }: RouteComponentProps) => { ( + render={(props) => ( {({ configuration, createDerivedIndexPattern }) => ( diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx index e89d533c9f10a..8b5b191ccfdd9 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/layout.tsx @@ -133,13 +133,13 @@ const MainContainer = euiStyled.div` `; const TopActionContainer = euiStyled.div` - padding: ${props => `12px ${props.theme.eui.paddingSizes.m}`}; + padding: ${(props) => `12px ${props.theme.eui.paddingSizes.m}`}; `; const BottomActionContainer = euiStyled.div` - background-color: ${props => props.theme.eui.euiPageBackgroundColor}; - padding: ${props => props.theme.eui.paddingSizes.m} ${props => - props.theme.eui.paddingSizes.m} ${props => props.theme.eui.paddingSizes.s}; + background-color: ${(props) => props.theme.eui.euiPageBackgroundColor}; + padding: ${(props) => props.theme.eui.paddingSizes.m} ${(props) => + props.theme.eui.paddingSizes.m} ${(props) => props.theme.eui.paddingSizes.s}; position: absolute; left: 0; bottom: 4px; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/nodes_overview.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/nodes_overview.tsx index 966a327f40bc1..db5949f916ff4 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/nodes_overview.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/nodes_overview.tsx @@ -37,8 +37,8 @@ interface Props { } export const calculateBoundsFromNodes = (nodes: SnapshotNode[]): InfraWaffleMapBounds => { - const maxValues = nodes.map(node => node.metric.max); - const minValues = nodes.map(node => node.metric.value); + const maxValues = nodes.map((node) => node.metric.max); + const minValues = nodes.map((node) => node.metric.value); // if there is only one value then we need to set the bottom range to zero for min // otherwise the legend will look silly since both values are the same for top and // bottom. @@ -136,7 +136,7 @@ export const NodesOverview = ({ }; const TableContainer = euiStyled.div` - padding: ${props => props.theme.eui.paddingSizes.l}; + padding: ${(props) => props.theme.eui.paddingSizes.l}; `; const MapContainer = euiStyled.div` diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/table_view.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/table_view.tsx index 0557343e735f9..3b68ad314f7df 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/table_view.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/table_view.tsx @@ -50,7 +50,7 @@ export const TableView = (props: Props) => { const closePopoverFor = useCallback( (id: string) => () => { if (openPopovers.includes(id)) { - setOpenPopovers(openPopovers.filter(subject => subject !== id)); + setOpenPopovers(openPopovers.filter((subject) => subject !== id)); } }, [openPopovers] @@ -79,7 +79,7 @@ export const TableView = (props: Props) => { // For the table we need to create a UniqueID that takes into to account the groupings // as well as the node name. There is the possibility that a node can be present in two // different groups and be on the screen at the same time. - const uniqueID = [...item.node.path.map(p => p.value), item.node.name].join(':'); + const uniqueID = [...item.node.path.map((p) => p.value), item.node.name].join(':'); return ( { }, ]; - const items = nodes.map(node => { + const items = nodes.map((node) => { const name = last(node.path); return { name: (name && name.label) || 'unknown', diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/toolbars/toolbar.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/toolbars/toolbar.tsx index 6a68599aee38c..e9ffc56d8c47f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/toolbars/toolbar.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/toolbars/toolbar.tsx @@ -42,7 +42,7 @@ const wrapToolbarItems = ( ) => { return ( - {props => ( + {(props) => ( <> diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/custom_field_panel.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/custom_field_panel.tsx index 090d53f1ff737..4cb8a9dd6624f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/custom_field_panel.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/custom_field_panel.tsx @@ -33,12 +33,12 @@ export const CustomFieldPanel = class extends React.PureComponent const { fields, currentOptions } = this.props; const options = fields .filter( - f => + (f) => f.aggregatable && f.type === 'string' && - !(currentOptions && currentOptions.some(o => o.field === f.name)) + !(currentOptions && currentOptions.some((o) => o.field === f.name)) ) - .map(f => ({ label: f.name })); + .map((f) => ({ label: f.name })); const isSubmitDisabled = !this.state.selectedOptions.length; return (
          diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/gradient_legend.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/gradient_legend.tsx index 87f7e4cbff11e..953d94e51aad0 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/gradient_legend.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/gradient_legend.tsx @@ -39,7 +39,7 @@ export const GradientLegend: React.FC = ({ legend, bounds, formatter }) = const maxValue = legend.rules.reduce((acc, rule) => { return acc < rule.value ? rule.value : acc; }, 0); - const colorStops = legend.rules.map(rule => { + const colorStops = legend.rules.map((rule) => { const percent = (rule.value / maxValue) * 100; return `${rule.color} ${percent}%`; }); @@ -69,7 +69,7 @@ const GradientLegendTick = euiStyled.div` const GradientLegendTickLine = euiStyled.div` position: absolute; - background-color: ${props => props.theme.eui.euiBorderColor}; + background-color: ${(props) => props.theme.eui.euiBorderColor}; width: 1px; left: 0; top: 15px; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_name.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_name.tsx index 308460203b132..75a023d49d4aa 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_name.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_name.tsx @@ -66,11 +66,11 @@ interface InnerProps { } const Inner = euiStyled.div` - border: 1px solid ${props => props.theme.eui.euiBorderColor}; - background-color: ${props => + border: 1px solid ${(props) => props.theme.eui.euiBorderColor}; + background-color: ${(props) => props.isChild ? props.theme.eui.euiColorLightestShade : props.theme.eui.euiColorEmptyShade}; border-radius: 4px; - box-shadow: 0px 2px 0px 0px ${props => props.theme.eui.euiBorderColor}; + box-shadow: 0px 2px 0px 0px ${(props) => props.theme.eui.euiBorderColor}; display: flex; align-items: center; justify-content: center; @@ -87,7 +87,7 @@ const Name = euiStyled.div` const Count = euiStyled.div` flex: 0 0 auto; - border-left: 1px solid ${props => props.theme.eui.euiBorderColor}; + border-left: 1px solid ${(props) => props.theme.eui.euiBorderColor}; padding: 6px 10px; font-size: 0.85em; font-weight: normal; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_groups.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_groups.tsx index 6b3f22007f580..760dae169d000 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_groups.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_groups.tsx @@ -26,12 +26,12 @@ interface Props { currentTime: number; } -export const GroupOfGroups: React.FC = props => { +export const GroupOfGroups: React.FC = (props) => { return ( - {props.group.groups.map(group => ( + {props.group.groups.map((group) => ( props.theme.eui.euiBorderColor}; + border: 1px solid ${(props) => props.theme.eui.euiBorderColor}; box-shadow: 0 1px 7px rgba(0, 0, 0, 0.1); `; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_nodes.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_nodes.tsx index fc438ed4ca0a2..a6c9efb5e17d1 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_nodes.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/group_of_nodes.tsx @@ -42,7 +42,7 @@ export const GroupOfNodes: React.FC = ({ - {group.nodes.map(node => ( + {group.nodes.map((node) => ( props.theme.eui.euiBorderColor}; + border: 1px solid ${(props) => props.theme.eui.euiBorderColor}; box-shadow: 0 1px 7px rgba(0, 0, 0, 0.1); `; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/legend_controls.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/legend_controls.tsx index e5ee19e48884c..7929cf8292cb6 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/legend_controls.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/legend_controls.tsx @@ -55,7 +55,7 @@ const PALETTE_NAMES: InventoryColorPalette[] = [ 'negative', ]; -const PALETTE_OPTIONS = PALETTE_NAMES.map(name => ({ text: PALETTES[name], value: name })); +const PALETTE_OPTIONS = PALETTE_NAMES.map((name) => ({ text: PALETTES[name], value: name })); export const LegendControls = ({ autoBounds, @@ -99,7 +99,7 @@ export const LegendControls = ({ const handleReverseColors = useCallback( (e: EuiSwitchEvent) => { - setLegendOptions(previous => ({ ...previous, reverseColors: e.target.checked })); + setLegendOptions((previous) => ({ ...previous, reverseColors: e.target.checked })); }, [setLegendOptions] ); @@ -140,15 +140,15 @@ export const LegendControls = ({ }, [autoBounds, boundsOverride, options]); const handleStepsChange = useCallback( - e => { - setLegendOptions(previous => ({ ...previous, steps: parseInt(e.target.value, 10) })); + (e) => { + setLegendOptions((previous) => ({ ...previous, steps: parseInt(e.target.value, 10) })); }, [setLegendOptions] ); const handlePaletteChange = useCallback( - e => { - setLegendOptions(previous => ({ ...previous, palette: e.target.value })); + (e) => { + setLegendOptions((previous) => ({ ...previous, palette: e.target.value })); }, [setLegendOptions] ); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/map.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/map.tsx index eee8c69091ef0..5838317f07100 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/map.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/map.tsx @@ -47,7 +47,7 @@ export const Map: React.FC = ({ return ( measureRef(el)} data-test-subj="waffleMap"> - {groupsWithLayout.map(group => { + {groupsWithLayout.map((group) => { if (isWaffleMapGroupWithGroups(group)) { return ( { + (e) => { setLabel(e.target.value); }, [setLabel] @@ -103,7 +103,7 @@ export const CustomMetricForm = withTheme( ); const handleAggregationChange = useCallback( - e => { + (e) => { const value = e.target.value; const aggValue: SnapshotCustomAggregation = SnapshotCustomAggregationRT.is(value) ? value @@ -114,10 +114,10 @@ export const CustomMetricForm = withTheme( ); const fieldOptions = fields - .filter(f => f.aggregatable && f.type === 'number' && !(field && field === f.name)) - .map(f => ({ label: f.name })); + .filter((f) => f.aggregatable && f.type === 'number' && !(field && field === f.name)) + .map((f) => ({ label: f.name })); - const aggregationOptions = SNAPSHOT_CUSTOM_AGGREGATIONS.map(k => ({ + const aggregationOptions = SNAPSHOT_CUSTOM_AGGREGATIONS.map((k) => ({ text: AGGREGATION_LABELS[k as SnapshotCustomAggregation], value: k, })); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/index.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/index.tsx index 0cf1faec06c11..aae787c8c0395 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/index.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/index.tsx @@ -84,7 +84,7 @@ export const WaffleMetricControls = ({ onChange({ type: options[0].value as SnapshotMetricType }); } // Filter out the deleted metric from the editbale. - const newMetrics = editModeCustomMetrics.filter(v => v.id !== m.id); + const newMetrics = editModeCustomMetrics.filter((v) => v.id !== m.id); setEditModeCustomMetrics(newMetrics); }, [editModeCustomMetrics, metric, onChange, options] @@ -92,7 +92,9 @@ export const WaffleMetricControls = ({ const handleEditCustomMetric = useCallback( (currentMetric: SnapshotCustomMetricInput) => { - const newMetrics = customMetrics.map(m => (m.id === currentMetric.id && currentMetric) || m); + const newMetrics = customMetrics.map( + (m) => (m.id === currentMetric.id && currentMetric) || m + ); onChangeCustomMetrics(newMetrics); setModeToPick(); setEditCustomMetric(void 0); @@ -125,7 +127,7 @@ export const WaffleMetricControls = ({ const id = SnapshotCustomMetricInputRT.is(metric) && metric.id ? metric.id : metric.type; const currentLabel = SnapshotCustomMetricInputRT.is(metric) ? getCustomMetricLabel(metric) - : options.find(o => o.value === id)?.text; + : options.find((o) => o.value === id)?.text; if (!currentLabel) { return null; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_context_menu.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_context_menu.tsx index 1cdef493aee4f..7ab90297ebbb3 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_context_menu.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_context_menu.tsx @@ -36,7 +36,7 @@ export const MetricsContextMenu = ({ const handleClick = useCallback( (val: string) => { if (!SnapshotMetricTypeRT.is(val)) { - const selectedMetric = customMetrics.find(m => m.id === val); + const selectedMetric = customMetrics.find((m) => m.id === val); if (selectedMetric) { onChange(selectedMetric); } @@ -53,12 +53,12 @@ export const MetricsContextMenu = ({ id: 0, title: '', items: [ - ...options.map(o => { + ...options.map((o) => { const icon = o.value === id ? 'check' : 'empty'; const panel = { name: o.text, onClick: () => handleClick(o.value), icon }; return panel; }), - ...customMetrics.map(m => { + ...customMetrics.map((m) => { const icon = m.id === id ? 'check' : 'empty'; const panel = { name: getCustomMetricLabel(m), diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_edit_mode.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_edit_mode.tsx index 4d1bc906de0b9..89edaacdb8a1d 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_edit_mode.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/metric_control/metrics_edit_mode.tsx @@ -26,12 +26,12 @@ export const MetricsEditMode = withTheme( ({ theme, customMetrics, options, onEdit, onDelete }: Props) => { return (
          - {options.map(option => ( + {options.map((option) => (
          {option.text}
          ))} - {customMetrics.map(metric => ( + {customMetrics.map((metric) => ( { } private togglePopover = () => { - this.setState(prevState => ({ isPopoverOpen: !prevState.isPopoverOpen })); + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen })); }; private closePopover = () => { @@ -119,7 +119,7 @@ const SquareOuter = euiStyled.div` left: 4px; bottom: 4px; right: 4px; - background-color: ${props => darken(0.1, props.color)}; + background-color: ${(props) => darken(0.1, props.color)}; border-radius: 3px; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.2); `; @@ -132,7 +132,7 @@ const SquareInner = euiStyled.div` bottom: 2px; left: 0; border-radius: 3px; - background-color: ${props => props.color}; + background-color: ${(props) => props.color}; `; const ValueInner = euiStyled.button` @@ -152,8 +152,8 @@ const ValueInner = euiStyled.button` border: none; &:focus { outline: none !important; - border: ${params => params.theme.eui.euiFocusRingSize} solid - ${params => params.theme.eui.euiFocusRingColor}; + border: ${(params) => params.theme.eui.euiFocusRingSize} solid + ${(params) => params.theme.eui.euiFocusRingColor}; box-shadow: none; } `; @@ -165,7 +165,7 @@ const SquareTextContent = euiStyled.div` text-overflow: ellipsis; white-space: nowrap; flex: 1 0 auto; - color: ${props => readableColor(props.color)}; + color: ${(props) => readableColor(props.color)}; `; const Value = euiStyled(SquareTextContent)` diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/palette_preview.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/palette_preview.tsx index cfcdad2d8927c..18f15ba7ab81f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/palette_preview.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/palette_preview.tsx @@ -19,7 +19,7 @@ export const PalettePreview = ({ steps, palette, reverse }: Props) => { const colors = getColorPalette(palette, steps, reverse); return ( - {colors.map(color => ( + {colors.map((color) => ( ))} @@ -31,11 +31,11 @@ const Swatch = euiStyled.div` height: 12px; flex: 0 0 auto; &:first-child { - border-radius: ${props => props.theme.eui.euiBorderRadius} 0 0 ${props => + border-radius: ${(props) => props.theme.eui.euiBorderRadius} 0 0 ${(props) => props.theme.eui.euiBorderRadius}; } &:last-child { - border-radius: 0 ${props => props.theme.eui.euiBorderRadius} ${props => + border-radius: 0 ${(props) => props.theme.eui.euiBorderRadius} ${(props) => props.theme.eui.euiBorderRadius} 0; `; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/stepped_gradient_legend.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/stepped_gradient_legend.tsx index 2facef521c393..fadf6b139a3e8 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/stepped_gradient_legend.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/stepped_gradient_legend.tsx @@ -51,14 +51,14 @@ const TickLabel = ({ value, bounds, formatter }: TickProps) => { }; const GradientStep = euiStyled.div` - height: ${props => props.theme.eui.paddingSizes.s}; + height: ${(props) => props.theme.eui.paddingSizes.s}; flex: 1 1 auto; &:first-child { - border-radius: ${props => props.theme.eui.euiBorderRadius} 0 0 ${props => + border-radius: ${(props) => props.theme.eui.euiBorderRadius} 0 0 ${(props) => props.theme.eui.euiBorderRadius}; } &:last-child { - border-radius: 0 ${props => props.theme.eui.euiBorderRadius} ${props => + border-radius: 0 ${(props) => props.theme.eui.euiBorderRadius} ${(props) => props.theme.eui.euiBorderRadius} 0; } `; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_accounts_controls.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_accounts_controls.tsx index 5ac6320510257..565b22a77ea5d 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_accounts_controls.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_accounts_controls.tsx @@ -28,7 +28,7 @@ export const WaffleAccountsControls = (props: Props) => { setIsOpen(false); }, [setIsOpen]); - const currentLabel = options.find(o => o.value === accountId); + const currentLabel = options.find((o) => o.value === accountId); const changeAccount = useCallback( (val: string) => { @@ -47,7 +47,7 @@ export const WaffleAccountsControls = (props: Props) => { { id: 0, title: '', - items: options.map(o => { + items: options.map((o) => { const icon = o.value === accountId ? 'check' : 'empty'; const panel = { name: o.name, onClick: () => changeAccount(o.value), icon }; return panel; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_group_by_controls.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_group_by_controls.tsx index cc09ce226b2fe..8d2f289621b12 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_group_by_controls.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_group_by_controls.tsx @@ -44,7 +44,7 @@ export const WaffleGroupByControls = class extends React.PureComponent ({ + const customOptions = this.props.customOptions.map((option) => ({ ...option, toolTipContent: option.text, })); @@ -80,8 +80,8 @@ export const WaffleGroupByControls = class extends React.PureComponent { - const icon = groupBy.some(g => g.field === o.field) ? 'check' : 'empty'; + ...options.map((o) => { + const icon = groupBy.some((g) => g.field === o.field) ? 'check' : 'empty'; const panel = { name: o.text, onClick: this.handleClick(o.field), @@ -116,11 +116,11 @@ export const WaffleGroupByControls = class extends React.PureComponent 0 ? ( groupBy - .map(g => options.find(o => o.field === g.field)) - .filter(o => o != null) + .map((g) => options.find((o) => o.field === g.field)) + .filter((o) => o != null) // In this map the `o && o.field` is totally unnecessary but Typescript is // too stupid to realize that the filter above prevents the next map from being null - .map(o => ( + .map((o) => ( {o && o.text} @@ -153,8 +153,8 @@ export const WaffleGroupByControls = class extends React.PureComponent () => { const { groupBy } = this.props; - this.props.onChange(groupBy.filter(g => g.field !== field)); - const options = this.props.customOptions.filter(g => g.field !== field); + this.props.onChange(groupBy.filter((g) => g.field !== field)); + const options = this.props.customOptions.filter((g) => g.field !== field); this.props.onChangeCustomOptions(options); // We need to close the panel after we rmeove the pill icon otherwise // it will remain open because the click is still captured by the EuiFilterButton @@ -166,7 +166,7 @@ export const WaffleGroupByControls = class extends React.PureComponent { - this.setState(state => ({ isPopoverOpen: !state.isPopoverOpen })); + this.setState((state) => ({ isPopoverOpen: !state.isPopoverOpen })); }; private handleCustomField = (field: string) => { @@ -184,7 +184,7 @@ export const WaffleGroupByControls = class extends React.PureComponent () => { const { groupBy } = this.props; - if (groupBy.some(g => g.field === field)) { + if (groupBy.some((g) => g.field === field)) { this.handleRemove(field)(); } else if (this.props.groupBy.length < 2) { this.props.onChange([...groupBy, { field }]); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_region_controls.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_region_controls.tsx index 9c28f0798b519..575b1f9a73aa4 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_region_controls.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_region_controls.tsx @@ -27,7 +27,7 @@ export const WaffleRegionControls = (props: Props) => { setIsOpen(false); }, [setIsOpen]); - const currentLabel = options.find(o => region === o); + const currentLabel = options.find((o) => region === o); const changeRegion = useCallback( (val: string) => { @@ -46,7 +46,7 @@ export const WaffleRegionControls = (props: Props) => { { id: 0, title: '', - items: options.map(o => { + items: options.map((o) => { const icon = o === region ? 'check' : 'empty'; const panel = { name: o, onClick: () => changeRegion(o), icon }; return panel; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.ts index f6cbb59779039..63d9d08796f05 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.ts @@ -50,7 +50,7 @@ export const useWaffleFilters = () => { const applyFilterQueryFromKueryExpression = useCallback( (expression: string) => { - setState(previous => ({ + setState((previous) => ({ ...previous, kind: 'kuery', expression, diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.ts index 1e99e909cbb3d..975e33cf2415f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.ts @@ -54,68 +54,69 @@ export const useWaffleOptions = () => { useEffect(() => setUrlState(state), [setUrlState, state]); const changeMetric = useCallback( - (metric: SnapshotMetricInput) => setState(previous => ({ ...previous, metric })), + (metric: SnapshotMetricInput) => setState((previous) => ({ ...previous, metric })), [setState] ); const changeGroupBy = useCallback( - (groupBy: SnapshotGroupBy) => setState(previous => ({ ...previous, groupBy })), + (groupBy: SnapshotGroupBy) => setState((previous) => ({ ...previous, groupBy })), [setState] ); const changeNodeType = useCallback( - (nodeType: InventoryItemType) => setState(previous => ({ ...previous, nodeType })), + (nodeType: InventoryItemType) => setState((previous) => ({ ...previous, nodeType })), [setState] ); - const changeView = useCallback((view: string) => setState(previous => ({ ...previous, view })), [ - setState, - ]); + const changeView = useCallback( + (view: string) => setState((previous) => ({ ...previous, view })), + [setState] + ); const changeCustomOptions = useCallback( (customOptions: Array<{ text: string; field: string }>) => - setState(previous => ({ ...previous, customOptions })), + setState((previous) => ({ ...previous, customOptions })), [setState] ); const changeAutoBounds = useCallback( - (autoBounds: boolean) => setState(previous => ({ ...previous, autoBounds })), + (autoBounds: boolean) => setState((previous) => ({ ...previous, autoBounds })), [setState] ); const changeBoundsOverride = useCallback( (boundsOverride: { min: number; max: number }) => - setState(previous => ({ ...previous, boundsOverride })), + setState((previous) => ({ ...previous, boundsOverride })), [setState] ); const changeAccount = useCallback( - (accountId: string) => setState(previous => ({ ...previous, accountId })), + (accountId: string) => setState((previous) => ({ ...previous, accountId })), [setState] ); const changeRegion = useCallback( - (region: string) => setState(previous => ({ ...previous, region })), + (region: string) => setState((previous) => ({ ...previous, region })), [setState] ); const changeCustomMetrics = useCallback( (customMetrics: SnapshotCustomMetricInput[]) => { - setState(previous => ({ ...previous, customMetrics })); + setState((previous) => ({ ...previous, customMetrics })); }, [setState] ); const changeLegend = useCallback( (legend: WaffleLegendOptions) => { - setState(previous => ({ ...previous, legend })); + setState((previous) => ({ ...previous, legend })); }, [setState] ); const changeSort = useCallback( (sort: WaffleSortOption) => { - setState(previous => ({ ...previous, sort })); + setState((previous) => ({ ...previous, sort })); }, [setState] ); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_time.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_time.ts index db3abd37b58dd..91cf405dcc759 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_time.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_time.ts @@ -31,16 +31,16 @@ export const useWaffleTime = () => { const { currentTime, isAutoReloading } = urlState; const startAutoReload = useCallback(() => { - setState(previous => ({ ...previous, isAutoReloading: true })); + setState((previous) => ({ ...previous, isAutoReloading: true })); }, [setState]); const stopAutoReload = useCallback(() => { - setState(previous => ({ ...previous, isAutoReloading: false })); + setState((previous) => ({ ...previous, isAutoReloading: false })); }, [setState]); const jumpToTime = useCallback( (time: number) => { - setState(previous => ({ ...previous, currentTime: time })); + setState((previous) => ({ ...previous, currentTime: time })); }, [setState] ); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/apply_wafflemap_layout.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/apply_wafflemap_layout.ts index 68600ac5d2ce4..5b749fab5839f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/apply_wafflemap_layout.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/apply_wafflemap_layout.ts @@ -66,14 +66,14 @@ export function applyWaffleMapLayout( const largestCount = getLargestCount(groups); return sortBy(groups, getTotalItemsOfGroup) .reverse() - .map(group => { + .map((group) => { if (isWaffleMapGroupWithGroups(group)) { const columns = getColumns(largestCount, width, height); const groupOfNodes = group.groups; const subGroups = sortBy(groupOfNodes, getTotalItemsOfGroup) .reverse() .filter(isWaffleMapGroupWithNodes) - .map(subGroup => { + .map((subGroup) => { return { ...subGroup, count: subGroup.nodes.length, diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/color_from_value.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/color_from_value.ts index 9cdd2032b73d9..c6a7eaf5fdc63 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/color_from_value.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/color_from_value.ts @@ -117,7 +117,7 @@ export const calculateGradientColor = ( } return acc; }, first(sortedRules)); - const endRule = sortedRules.filter(r => r !== startRule).find(r => r.value >= normValue); + const endRule = sortedRules.filter((r) => r !== startRule).find((r) => r.value >= normValue); if (!endRule) { return startRule.color; } diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/nodes_to_wafflemap.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/nodes_to_wafflemap.ts index 469b54b2d9d68..a6a356a78be44 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/nodes_to_wafflemap.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/nodes_to_wafflemap.ts @@ -16,7 +16,7 @@ import { isWaffleMapGroupWithGroups, isWaffleMapGroupWithNodes } from './type_gu import { SnapshotNodePath, SnapshotNode } from '../../../../../common/http_api/snapshot_api'; export function createId(path: SnapshotNodePath[]) { - return path.map(p => p.value).join('/'); + return path.map((p) => p.value).join('/'); } function findOrCreateGroupWithNodes( @@ -31,16 +31,16 @@ function findOrCreateGroupWithNodes( */ if (path.length === 2) { const parentId = first(path).value; - const existingParentGroup = groups.find(g => g.id === parentId); + const existingParentGroup = groups.find((g) => g.id === parentId); if (isWaffleMapGroupWithGroups(existingParentGroup)) { - const existingSubGroup = existingParentGroup.groups.find(g => g.id === id); + const existingSubGroup = existingParentGroup.groups.find((g) => g.id === id); if (isWaffleMapGroupWithNodes(existingSubGroup)) { return existingSubGroup; } } } const lastPath = last(path); - const existingGroup = groups.find(g => g.id === id); + const existingGroup = groups.find((g) => g.id === id); if (isWaffleMapGroupWithNodes(existingGroup)) { return existingGroup; } @@ -65,7 +65,7 @@ function findOrCreateGroupWithGroups( ): InfraWaffleMapGroupOfGroups { const id = path.length === 0 ? '__all__' : createId(path); const lastPath = last(path); - const existingGroup = groups.find(g => g.id === id); + const existingGroup = groups.find((g) => g.id === id); if (isWaffleMapGroupWithGroups(existingGroup)) { return existingGroup; } @@ -90,7 +90,7 @@ export function createWaffleMapNode(node: SnapshotNode): InfraWaffleMapNode { throw new Error('There must be at least one node path item'); } return { - pathId: node.path.map(p => p.value).join('/'), + pathId: node.path.map((p) => p.value).join('/'), path: node.path, id: nodePathItem.value, ip: nodePathItem.ip, diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/chart_section_vis.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/chart_section_vis.tsx index 7bf5dd6caae48..6a4d6521855a9 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/chart_section_vis.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/chart_section_vis.tsx @@ -117,7 +117,7 @@ export const ChartSectionVis = ({ /> {metric && - metric.series.map(series => ( + metric.series.map((series) => ( - {metric.series.map(series => { + {metric.series.map((series) => { const lastDataPoint = last(series.data); if (!lastDataPoint) { return null; @@ -67,7 +67,7 @@ export const GaugesSectionVis = ({ ); const value = formatterFn(lastDataPoint.value || 0); const name = getChartName(seriesOverrides, series.id, series.id); - const dataMax = max(series.data.map(d => d.value || 0)); + const dataMax = max(series.data.map((d) => d.value || 0)); const gaugeMax = get(seriesOverrides, [series.id, 'gaugeMax'], dataMax); return ( diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/metadata_details.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/metadata_details.tsx index 7ca69dd56251d..656378fbc0610 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/metadata_details.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/metadata_details.tsx @@ -83,7 +83,7 @@ const FIELDS = [ ] as FieldDef[]; const getLabelForField = ({ field }: FieldDef) => { - const fieldDef = FIELDS.find(f => f.field === field); + const fieldDef = FIELDS.find((f) => f.field === field); if (!fieldDef) return field; return fieldDef.label; }; @@ -115,13 +115,13 @@ export const MetadataDetails = (props: Props) => { const filteredFields = useMemo(() => { if (props.fields && props.fields.length) { return props.fields - .map(field => { - const fieldDef = FIELDS.find(f => f.field === field); + .map((field) => { + const fieldDef = FIELDS.find((f) => f.field === field); if (fieldDef) { return fieldDef; } }) - .filter(f => f) as FieldDef[]; + .filter((f) => f) as FieldDef[]; } else { return FIELDS; } @@ -150,7 +150,7 @@ export const MetadataDetails = (props: Props) => { ) : null} - {fields.map(field => ( + {fields.map((field) => (
          {getLabelForField(field)}
          @@ -164,17 +164,17 @@ export const MetadataDetails = (props: Props) => { }; const MetadataContainer = euiStyled.div` -border-top: ${props => props.theme.eui.euiBorderWidthThin} solid ${props => +border-top: ${(props) => props.theme.eui.euiBorderWidthThin} solid ${(props) => props.theme.eui.euiBorderColor}; -border-bottom: ${props => props.theme.eui.euiBorderWidthThin} solid ${props => +border-bottom: ${(props) => props.theme.eui.euiBorderWidthThin} solid ${(props) => props.theme.eui.euiBorderColor}; -padding: ${props => props.theme.eui.paddingSizes.m} 0; -margin-bottom: ${props => props.theme.eui.paddingSizes.m}; +padding: ${(props) => props.theme.eui.paddingSizes.m} 0; +margin-bottom: ${(props) => props.theme.eui.paddingSizes.m}; display: flex; `; const Controls = euiStyled.div` flex-grow: 0; -margin-right: ${props => props.theme.eui.paddingSizes.m}; +margin-right: ${(props) => props.theme.eui.paddingSizes.m}; min-width: 0px; `; diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/section.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/section.tsx index 68003737a1f14..5e040c536985b 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/section.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/section.tsx @@ -37,7 +37,7 @@ export const Section: FunctionComponent = ({ if (!isValidElement(child)) { return accumulatedChildren; } - const metric = metrics?.find(m => m.id === child.props.id) ?? null; + const metric = metrics?.find((m) => m.id === child.props.id) ?? null; if (metric === null) { return accumulatedChildren; } @@ -61,7 +61,7 @@ export const Section: FunctionComponent = ({ [] ); - const childrenWithProps = Children.map(children, child => + const childrenWithProps = Children.map(children, (child) => isValidElement(child) ? cloneElement(child, { metrics, diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/sub_section.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/sub_section.tsx index 7b269adc96638..4c75003616117 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/sub_section.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/sub_section.tsx @@ -23,13 +23,13 @@ export const SubSection: FunctionComponent = ({ isLiveStreaming, stopLiveStreaming, }) => { - const metric = useMemo(() => metrics?.find(m => m.id === id), [id, metrics]); + const metric = useMemo(() => metrics?.find((m) => m.id === id), [id, metrics]); if (!children || !metric) { return null; } - const childrenWithProps = Children.map(children, child => { + const childrenWithProps = Children.map(children, (child) => { if (isValidElement(child)) { return cloneElement(child, { metric, diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/hooks/use_metrics_time.ts b/x-pack/plugins/infra/public/pages/metrics/metric_detail/hooks/use_metrics_time.ts index 98803ef2e69c6..5f695f31fc180 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/hooks/use_metrics_time.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/hooks/use_metrics_time.ts @@ -20,11 +20,7 @@ const parseRange = (range: MetricsTimeInput) => { const parsedTo = dateMath.parse(range.to.toString(), { roundUp: true }); return { ...range, - from: - (parsedFrom && parsedFrom.valueOf()) || - moment() - .subtract(1, 'hour') - .valueOf(), + from: (parsedFrom && parsedFrom.valueOf()) || moment().subtract(1, 'hour').valueOf(), to: (parsedTo && parsedTo.valueOf()) || moment().valueOf(), }; }; diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/index.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/index.tsx index 197a735f7fd1f..4ae96f733382f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/index.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/index.tsx @@ -23,7 +23,7 @@ import { useLinkProps } from '../../../hooks/use_link_props'; const DetailPageContent = euiStyled(PageContent)` overflow: auto; - background-color: ${props => props.theme.eui.euiColorLightestShade}; + background-color: ${(props) => props.theme.eui.euiColorLightestShade}; `; interface Props { @@ -65,7 +65,7 @@ export const MetricDetail = withMetricPageProviders( const addNavItem = React.useCallback( (item: NavItem) => { - if (!sideNav.some(n => n.id === item.id)) { + if (!sideNav.some((n) => n.id === item.id)) { setSideNav([item, ...sideNav]); } }, diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/lib/get_filtered_metrics.ts b/x-pack/plugins/infra/public/pages/metrics/metric_detail/lib/get_filtered_metrics.ts index 57ff182f01963..7dc2f2b0ccd1f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/lib/get_filtered_metrics.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/lib/get_filtered_metrics.ts @@ -13,13 +13,13 @@ export const getFilteredMetrics = ( metadata: Array ) => { const metricMetadata = metadata - .filter(data => data && data.source === 'metrics') - .map(data => data && data.name); - return requiredMetrics.filter(metric => { + .filter((data) => data && data.source === 'metrics') + .map((data) => data && data.name); + return requiredMetrics.filter((metric) => { const metricModelCreator = metrics.tsvb[metric]; // We just need to get a dummy version of the model so we can filter // using the `requires` attribute. const metricModel = metricModelCreator('@timestamp', 'test', '>=1m'); - return metricMetadata.some(m => m && metricModel.requires.includes(m)); + return metricMetadata.some((m) => m && metricModel.requires.includes(m)); }); }; diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/aggregation.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/aggregation.tsx index 8d397d9f96b59..02d3d2c583a7f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/aggregation.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/aggregation.tsx @@ -53,7 +53,7 @@ export const MetricsExplorerAggregationPicker = ({ options, onChange }: Props) = }; const handleChange = useCallback( - e => { + (e) => { const aggregation = (metricsExplorerAggregationRT.is(e.target.value) && e.target.value) || 'avg'; onChange(aggregation); @@ -71,7 +71,7 @@ export const MetricsExplorerAggregationPicker = ({ options, onChange }: Props) = placeholder={placeholder} fullWidth value={options.aggregation} - options={METRIC_EXPLORER_AGGREGATIONS.map(k => ({ + options={METRIC_EXPLORER_AGGREGATIONS.map((k) => ({ text: AGGREGATION_LABELS[k as MetricsExplorerAggregation], value: k, }))} diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/chart_options.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/chart_options.tsx index ba28075ededb6..d21454dba5178 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/chart_options.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/chart_options.tsx @@ -103,7 +103,7 @@ export const MetricsExplorerChartOptions = ({ chartOptions, onChange }: Props) = ); const handleStackChange = useCallback( - e => { + (e) => { onChange({ ...chartOptions, stack: e.target.checked, diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/charts.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/charts.tsx index 2929a7316bd79..b9595548debf2 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/charts.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/charts.tsx @@ -81,7 +81,7 @@ export const MetricsExplorerCharts = ({ return (
          - {data.series.map(series => ( + {data.series.map((series) => ( { const handleChange = useCallback( (selectedOptions: Array<{ label: string }>) => { - const groupBy = selectedOptions.map(option => option.label); + const groupBy = selectedOptions.map((option) => option.label); onChange(groupBy); }, [onChange] ); const selectedOptions = Array.isArray(options.groupBy) - ? options.groupBy.map(field => ({ label: field })) + ? options.groupBy.map((field) => ({ label: field })) : options.groupBy ? [{ label: options.groupBy }] : []; @@ -44,8 +44,8 @@ export const MetricsExplorerGroupBy = ({ options, onChange, fields }: Props) => singleSelection={false} selectedOptions={selectedOptions} options={fields - .filter(f => f.aggregatable && f.type === 'string') - .map(f => ({ label: f.name }))} + .filter((f) => f.aggregatable && f.type === 'string') + .map((f) => ({ label: f.name }))} onChange={handleChange} isClearable={true} /> diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/calculate_domain.ts b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/calculate_domain.ts index 5cfc8c366b444..85cdbb6731c59 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/calculate_domain.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/calculate_domain.ts @@ -29,13 +29,13 @@ export const calculateDomain = ( .map((m, index) => { return (row[getMetricId(m, index)] as number) || null; }) - .filter(v => isNumber(v)); + .filter((v) => isNumber(v)); const minValue = getMin(rowValues); // For stacked domains we want to add 10% head room so the charts have // enough room to draw the 2 pixel line as well. const maxValue = stacked ? sum(rowValues) * 1.1 : getMax(rowValues); return acc.concat([minValue || null, maxValue || null]); }, [] as Array) - .filter(v => isNumber(v)); + .filter((v) => isNumber(v)); return { min: getMin(values) || 0, max: getMax(values) || 0 }; }; diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/metrics.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/metrics.tsx index 612735e2ba772..8be03a7096f08 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/metrics.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/metrics.tsx @@ -41,7 +41,7 @@ export const MetricsExplorerMetrics = ({ options, onChange, fields, autoFocus = ); const handleChange = useCallback( - selectedOptions => { + (selectedOptions) => { onChange( selectedOptions.map((opt: SelectedOption, index: number) => ({ aggregation: options.aggregation, @@ -53,10 +53,10 @@ export const MetricsExplorerMetrics = ({ options, onChange, fields, autoFocus = [onChange, options.aggregation, colors] ); - const comboOptions = fields.map(field => ({ label: field.name, value: field.name })); + const comboOptions = fields.map((field) => ({ label: field.name, value: field.name })); const selectedOptions = options.metrics - .filter(m => m.aggregation !== 'count') - .map(metric => ({ + .filter((m) => m.aggregation !== 'count') + .map((metric) => ({ label: metric.field || '', value: metric.field || '', color: colorTransformer(metric.color || MetricsExplorerColor.color0), diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/series_chart.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/series_chart.tsx index 223318da8cf46..9b594ef5e630f 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/series_chart.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/series_chart.tsx @@ -46,11 +46,11 @@ export const MetricsExplorerAreaChart = ({ metric, id, series, type, stack, opac colorTransformer(MetricsExplorerColor.color0); const yAccessors = Array.isArray(id) - ? id.map(i => getMetricId(metric, i)).slice(id.length - 1, id.length) + ? id.map((i) => getMetricId(metric, i)).slice(id.length - 1, id.length) : [getMetricId(metric, id)]; const y0Accessors = Array.isArray(id) && id.length > 1 - ? id.map(i => getMetricId(metric, i)).slice(0, 1) + ? id.map((i) => getMetricId(metric, i)).slice(0, 1) : undefined; const chartId = `series-${series.id}-${yAccessors.join('-')}`; @@ -89,7 +89,7 @@ export const MetricsExplorerBarChart = ({ metric, id, series, stack }: Props) => colorTransformer(MetricsExplorerColor.color0); const yAccessors = Array.isArray(id) - ? id.map(i => getMetricId(metric, i)).slice(id.length - 1, id.length) + ? id.map((i) => getMetricId(metric, i)).slice(id.length - 1, id.length) : [getMetricId(metric, id)]; const chartId = `series-${series.id}-${yAccessors.join('-')}`; diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.test.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.test.tsx index f0734f76cfacd..e312fe2dc1d9d 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.test.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.test.tsx @@ -16,7 +16,7 @@ import { } from '../../../../utils/fixtures/metrics_explorer'; const renderUseMetricsExplorerStateHook = () => - renderHook(props => useMetricsExplorerState(props.source, props.derivedIndexPattern), { + renderHook((props) => useMetricsExplorerState(props.source, props.derivedIndexPattern), { initialProps: { source, derivedIndexPattern }, wrapper: ({ children }) => ( diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.ts b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.ts index 936c6e456beb7..66cc77a576f99 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.ts @@ -102,8 +102,8 @@ export const useMetricsExplorerState = ( aggregation === 'count' ? [{ aggregation }] : options.metrics - .filter(metric => metric.aggregation !== 'count') - .map(metric => ({ + .filter((metric) => metric.aggregation !== 'count') + .map((metric) => ({ ...metric, aggregation, })); diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.test.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.test.tsx index f0b2627288d45..b33fe5c232f01 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.test.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.test.tsx @@ -31,7 +31,7 @@ const renderUseMetricsExplorerDataHook = () => { return {children}; }; return renderHook( - props => + (props) => useMetricsExplorerData( props.options, props.source, diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts index 3a767b94d00c7..5ed710414718a 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts @@ -64,7 +64,7 @@ export function useMetricsExplorerData( metrics: options.aggregation === 'count' ? [{ aggregation: 'count' }] - : options.metrics.map(metric => ({ + : options.metrics.map((metric) => ({ aggregation: metric.aggregation, field: metric.field, })), diff --git a/x-pack/plugins/infra/public/utils/datemath.ts b/x-pack/plugins/infra/public/utils/datemath.ts index 7331a2450956f..f2bd5d94ac2c3 100644 --- a/x-pack/plugins/infra/public/utils/datemath.ts +++ b/x-pack/plugins/infra/public/utils/datemath.ts @@ -218,8 +218,8 @@ export function convertDate(value: number, from: Unit, to: Unit): number { } const ratioScale = getRatioScale(from, to); - const fromIdx = ratioScale.findIndex(ratio => ratio[0] === from); - const toIdx = ratioScale.findIndex(ratio => ratio[0] === to); + const fromIdx = ratioScale.findIndex((ratio) => ratio[0] === from); + const toIdx = ratioScale.findIndex((ratio) => ratio[0] === to); let convertedValue = value; @@ -246,7 +246,7 @@ export function normalizeDate(amount: number, unit: Unit): { amount: number; uni const nextUnit = dateMath.unitsAsc[dateMath.unitsAsc.indexOf(unit) + 1]; const ratioScale = getRatioScale(unit, nextUnit); - const ratio = ratioScale.find(r => r[0] === unit)![1]; + const ratio = ratioScale.find((r) => r[0] === unit)![1]; const newAmount = amount / ratio; diff --git a/x-pack/plugins/infra/public/utils/enzyme_helpers.tsx b/x-pack/plugins/infra/public/utils/enzyme_helpers.tsx index 12770492697b6..3e1d437ae3f0e 100644 --- a/x-pack/plugins/infra/public/utils/enzyme_helpers.tsx +++ b/x-pack/plugins/infra/public/utils/enzyme_helpers.tsx @@ -44,7 +44,7 @@ export const mountHook = ( const hookValueCallback = jest.fn(); let component!: ReactWrapper; - const act: ReactHookWrapper['act'] = actor => { + const act: ReactHookWrapper['act'] = (actor) => { reactAct(() => { actor(getLastHookValue(), (args: Args) => component.setProps(args)); component.update(); @@ -63,7 +63,7 @@ export const mountHook = ( hookValueCallback(body(props)); return null; }; - const TestComponent: React.FunctionComponent = args => + const TestComponent: React.FunctionComponent = (args) => WrapperComponent ? ( diff --git a/x-pack/plugins/infra/public/utils/loading_state/loading_result.ts b/x-pack/plugins/infra/public/utils/loading_state/loading_result.ts index e48b04743c811..bd4a78fc77d5e 100644 --- a/x-pack/plugins/infra/public/utils/loading_state/loading_result.ts +++ b/x-pack/plugins/infra/public/utils/loading_state/loading_result.ts @@ -81,7 +81,7 @@ export const createFailureResult = ( }); export const createFailureResultReducer = ( - convertErrorToString: (error: ErrorPayload) => string = error => `${error}` + convertErrorToString: (error: ErrorPayload) => string = (error) => `${error}` ) => ( state: LoadingResult, { params, error }: { params: Parameters; error: ErrorPayload } diff --git a/x-pack/plugins/infra/public/utils/map_timepicker_quickranges_to_datepicker_ranges.ts b/x-pack/plugins/infra/public/utils/map_timepicker_quickranges_to_datepicker_ranges.ts index 68fac1ef6c084..ce36848205cf5 100644 --- a/x-pack/plugins/infra/public/utils/map_timepicker_quickranges_to_datepicker_ranges.ts +++ b/x-pack/plugins/infra/public/utils/map_timepicker_quickranges_to_datepicker_ranges.ts @@ -11,7 +11,7 @@ export const mapKibanaQuickRangesToDatePickerRanges = ( timepickerQuickRanges: TimePickerQuickRange[] | undefined ): EuiSuperDatePickerCommonRange[] => timepickerQuickRanges - ? timepickerQuickRanges.map(r => ({ + ? timepickerQuickRanges.map((r) => ({ start: r.from, end: r.to, label: r.display, diff --git a/x-pack/plugins/infra/public/utils/triggers_actions_context.tsx b/x-pack/plugins/infra/public/utils/triggers_actions_context.tsx index 4ca4aedb4a08b..1cff3663280fd 100644 --- a/x-pack/plugins/infra/public/utils/triggers_actions_context.tsx +++ b/x-pack/plugins/infra/public/utils/triggers_actions_context.tsx @@ -19,7 +19,7 @@ interface Props { triggersActionsUI: TriggersAndActionsUIPublicPluginSetup; } -export const TriggersActionsProvider: React.FC = props => { +export const TriggersActionsProvider: React.FC = (props) => { return ( { activeSpaceRT.decode(activeSpace), fold( () => 'default', - decodedActiveSpace => decodedActiveSpace.space.id + (decodedActiveSpace) => decodedActiveSpace.space.id ) ); }; diff --git a/x-pack/plugins/infra/public/utils/use_tracked_promise.ts b/x-pack/plugins/infra/public/utils/use_tracked_promise.ts index e9a966b97e4dd..9951b62fa64a3 100644 --- a/x-pack/plugins/infra/public/utils/use_tracked_promise.ts +++ b/x-pack/plugins/infra/public/utils/use_tracked_promise.ts @@ -99,7 +99,7 @@ export const useTrackedPromise = ( const previousPendingPromises = pendingPromises.current; const cancelPreviousPendingPromises = () => { - previousPendingPromises.forEach(promise => promise.cancel()); + previousPendingPromises.forEach((promise) => promise.cancel()); }; const newPromise = createPromise(...args); @@ -123,8 +123,8 @@ export const useTrackedPromise = ( rejectCancellationPromise(new SilentCanceledPromiseError()); }, promise: newCancelablePromise.then( - value => { - setPromiseState(previousPromiseState => + (value) => { + setPromiseState((previousPromiseState) => previousPromiseState.state === 'pending' && previousPromiseState.promise === newCancelablePromise ? { @@ -141,7 +141,7 @@ export const useTrackedPromise = ( // remove itself from the list of pending promises pendingPromises.current = pendingPromises.current.filter( - pendingPromise => pendingPromise.promise !== newPendingPromise.promise + (pendingPromise) => pendingPromise.promise !== newPendingPromise.promise ); if (onResolve) { @@ -150,9 +150,9 @@ export const useTrackedPromise = ( return value; }, - value => { + (value) => { if (!(value instanceof SilentCanceledPromiseError)) { - setPromiseState(previousPromiseState => + setPromiseState((previousPromiseState) => previousPromiseState.state === 'pending' && previousPromiseState.promise === newCancelablePromise ? { @@ -170,7 +170,7 @@ export const useTrackedPromise = ( // remove itself from the list of pending promises pendingPromises.current = pendingPromises.current.filter( - pendingPromise => pendingPromise.promise !== newPendingPromise.promise + (pendingPromise) => pendingPromise.promise !== newPendingPromise.promise ); if (onReject) { @@ -201,7 +201,7 @@ export const useTrackedPromise = ( */ useEffect( () => () => { - pendingPromises.current.forEach(promise => promise.cancelSilently()); + pendingPromises.current.forEach((promise) => promise.cancelSilently()); }, [] ); diff --git a/x-pack/plugins/infra/public/utils/use_visibility_state.ts b/x-pack/plugins/infra/public/utils/use_visibility_state.ts index f4d8b572e4f7f..69068a630dbe5 100644 --- a/x-pack/plugins/infra/public/utils/use_visibility_state.ts +++ b/x-pack/plugins/infra/public/utils/use_visibility_state.ts @@ -11,7 +11,7 @@ export const useVisibilityState = (initialState: boolean) => { const hide = useCallback(() => setIsVisible(false), []); const show = useCallback(() => setIsVisible(true), []); - const toggle = useCallback(() => setIsVisible(state => !state), []); + const toggle = useCallback(() => setIsVisible((state) => !state), []); return useMemo( () => ({ diff --git a/x-pack/plugins/infra/server/graphql/sources/resolvers.ts b/x-pack/plugins/infra/server/graphql/sources/resolvers.ts index cffab4ba4f6f0..15c4a6677946d 100644 --- a/x-pack/plugins/infra/server/graphql/sources/resolvers.ts +++ b/x-pack/plugins/infra/server/graphql/sources/resolvers.ts @@ -191,10 +191,10 @@ const compactObject = (obj: T): CompactObject => const decodeLogColumns = (logColumns?: UpdateSourceLogColumnInput[] | null) => logColumns - ? logColumns.map(logColumn => + ? logColumns.map((logColumn) => pipe( SavedSourceConfigurationColumnRuntimeType.decode(logColumn), - fold(errors => { + fold((errors) => { throw new UserInputError(failure(errors).join('\n')); }, identity) ) diff --git a/x-pack/plugins/infra/server/kibana.index.ts b/x-pack/plugins/infra/server/kibana.index.ts index b4301b3edf367..e47f27117b309 100644 --- a/x-pack/plugins/infra/server/kibana.index.ts +++ b/x-pack/plugins/infra/server/kibana.index.ts @@ -19,9 +19,7 @@ export const getConfigSchema = (Joi: typeof JoiNamespace) => { fields: Joi.object({ container: Joi.string(), host: Joi.string(), - message: Joi.array() - .items(Joi.string()) - .single(), + message: Joi.array().items(Joi.string()).single(), pod: Joi.string(), tiebreaker: Joi.string(), timestamp: Joi.string(), diff --git a/x-pack/plugins/infra/server/lib/adapters/fields/framework_fields_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/fields/framework_fields_adapter.ts index 8119c06dedaef..8a9389ed585eb 100644 --- a/x-pack/plugins/infra/server/lib/adapters/fields/framework_fields_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/fields/framework_fields_adapter.ts @@ -23,7 +23,7 @@ export class FrameworkFieldsAdapter implements FieldsAdapter { const response = await indexPatternsService.getFieldsForWildcard({ pattern: indices, }); - return response.map(field => ({ + return response.map((field) => ({ ...field, displayable: true, })); diff --git a/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts index b8513541be7ae..939498305eb98 100644 --- a/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts @@ -139,7 +139,7 @@ export class InfraKibanaLogEntriesAdapter implements LogEntriesAdapter { date_range: { field: sourceConfiguration.fields.timestamp, format: TIMESTAMP_FORMAT, - ranges: bucketIntervalStarts.map(bucketIntervalStart => ({ + ranges: bucketIntervalStarts.map((bucketIntervalStart) => ({ from: bucketIntervalStart.getTime(), to: bucketIntervalStart.getTime() + bucketSize, })), @@ -183,7 +183,7 @@ export class InfraKibanaLogEntriesAdapter implements LogEntriesAdapter { return pipe( LogSummaryResponseRuntimeType.decode(response), - map(logSummaryResponse => + map((logSummaryResponse) => logSummaryResponse.aggregations.count_by_date.buckets.map( convertDateRangeBucketToSummaryBucket ) @@ -227,7 +227,7 @@ export class InfraKibanaLogEntriesAdapter implements LogEntriesAdapter { } function mapHitsToLogEntryDocuments(hits: SortedSearchHit[], fields: string[]): LogEntryDocument[] { - return hits.map(hit => { + return hits.map((hit) => { const logFields = fields.reduce<{ [fieldName: string]: JsonValue }>( (flattenedFields, field) => { if (has(hit._source, field)) { @@ -253,7 +253,7 @@ const convertDateRangeBucketToSummaryBucket = ( entriesCount: bucket.doc_count, start: bucket.from || 0, end: bucket.to || 0, - topEntryKeys: bucket.top_hits_by_key.hits.hits.map(hit => ({ + topEntryKeys: bucket.top_hits_by_key.hits.hits.map((hit) => ({ tiebreaker: hit.sort[1], time: hit.sort[0], })), diff --git a/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts index 62f324e01f8d9..5718d49ae79d6 100644 --- a/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/metrics/kibana_metrics_adapter.ts @@ -51,15 +51,15 @@ export class KibanaMetricsAdapter implements InfraMetricsAdapter { ); } - const requests = options.metrics.map(metricId => + const requests = options.metrics.map((metricId) => this.makeTSVBRequest(metricId, options, nodeField, requestContext, rawRequest) ); return Promise.all(requests) - .then(results => { - return results.map(result => { + .then((results) => { + return results.map((result) => { const metricIds = Object.keys(result).filter( - k => !['type', 'uiRestrictions'].includes(k) + (k) => !['type', 'uiRestrictions'].includes(k) ); return metricIds.map((id: string) => { @@ -76,18 +76,18 @@ export class KibanaMetricsAdapter implements InfraMetricsAdapter { const panel = result[id]; return { id, - series: panel.series.map(series => { + series: panel.series.map((series) => { return { id: series.id, label: series.label, - data: series.data.map(point => ({ timestamp: point[0], value: point[1] })), + data: series.data.map((point) => ({ timestamp: point[0], value: point[1] })), }; }), }; }); }); }) - .then(result => flatten(result)); + .then((result) => flatten(result)); } async makeTSVBRequest( diff --git a/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts index 635f6ff9762c5..9bc58604f12a5 100644 --- a/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts @@ -50,8 +50,8 @@ export class InfraElasticsearchSourceStatusAdapter implements InfraSourceStatusA terminate_after: 1, }) .then( - response => response._shards.total > 0, - err => { + (response) => response._shards.total > 0, + (err) => { if (err.status === 404) { return false; } diff --git a/x-pack/plugins/infra/server/lib/alerting/common/utils.ts b/x-pack/plugins/infra/server/lib/alerting/common/utils.ts index 5ca65b667ae11..100260c499673 100644 --- a/x-pack/plugins/infra/server/lib/alerting/common/utils.ts +++ b/x-pack/plugins/infra/server/lib/alerting/common/utils.ts @@ -8,7 +8,7 @@ import { schema } from '@kbn/config-schema'; export const oneOfLiterals = (arrayOfLiterals: Readonly) => schema.string({ - validate: value => + validate: (value) => arrayOfLiterals.includes(value) ? undefined : `must be one of ${arrayOfLiterals.join(' | ')}`, }); diff --git a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts index cc8a35f6e47a1..b36de2a3bd091 100644 --- a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts @@ -41,29 +41,29 @@ export const createInventoryMetricThresholdExecutor = ( ); const results = await Promise.all( - criteria.map(c => evaluateCondtion(c, nodeType, source.configuration, services, filterQuery)) + criteria.map((c) => evaluateCondtion(c, nodeType, source.configuration, services, filterQuery)) ); const invenotryItems = Object.keys(results[0]); for (const item of invenotryItems) { const alertInstance = services.alertInstanceFactory(`${alertId}-${item}`); // AND logic; all criteria must be across the threshold - const shouldAlertFire = results.every(result => result[item].shouldFire); + const shouldAlertFire = results.every((result) => result[item].shouldFire); // AND logic; because we need to evaluate all criteria, if one of them reports no data then the // whole alert is in a No Data/Error state - const isNoData = results.some(result => result[item].isNoData); - const isError = results.some(result => result[item].isError); + const isNoData = results.some((result) => result[item].isNoData); + const isError = results.some((result) => result[item].isError); if (shouldAlertFire) { alertInstance.scheduleActions(FIRED_ACTIONS.id, { group: item, item, - valueOf: mapToConditionsLookup(results, result => + valueOf: mapToConditionsLookup(results, (result) => formatMetric(result[item].metric, result[item].currentValue) ), - thresholdOf: mapToConditionsLookup(criteria, c => c.threshold), - metricOf: mapToConditionsLookup(criteria, c => c.metric), + thresholdOf: mapToConditionsLookup(criteria, (c) => c.threshold), + metricOf: mapToConditionsLookup(criteria, (c) => c.metric), }); } @@ -102,21 +102,18 @@ const evaluateCondtion = async ( metric, { to: Date.now(), - from: moment() - .subtract(condition.timeSize, condition.timeUnit) - .toDate() - .getTime(), + from: moment().subtract(condition.timeSize, condition.timeUnit).toDate().getTime(), interval: condition.timeUnit, }, sourceConfiguration, filterQuery ); - threshold = threshold.map(n => convertMetricValue(metric, n)); + threshold = threshold.map((n) => convertMetricValue(metric, n)); const comparisonFunction = comparatorMap[comparator]; - return mapValues(currentValues, value => ({ + return mapValues(currentValues, (value) => ({ shouldFire: value !== undefined && value !== null && comparisonFunction(value, threshold), metric, currentValue: value, @@ -196,8 +193,8 @@ const convertMetricValue = (metric: SnapshotMetricType, value: number) => { } }; const converters: Record number> = { - cpu: n => Number(n) / 100, - memory: n => Number(n) / 100, + cpu: (n) => Number(n) / 100, + memory: (n) => Number(n) / 100, }; const formatMetric = (metric: SnapshotMetricType, value: number) => { diff --git a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts index cdec04ab81a8e..eedaf4202b37d 100644 --- a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts @@ -26,7 +26,7 @@ const checkValueAgainstComparatorMap: { }; export const createLogThresholdExecutor = (alertUUID: string, libs: InfraBackendLibs) => - async function({ services, params }: AlertExecutorOptions) { + async function ({ services, params }: AlertExecutorOptions) { const { count, criteria } = params as LogDocumentCountAlertParams; const { alertInstanceFactory, savedObjectsClient, callCluster } = services; const { sources } = libs; @@ -90,10 +90,10 @@ const getESQuery = ( const positiveComparators = getPositiveComparators(); const negativeComparators = getNegativeComparators(); - const positiveCriteria = criteria.filter(criterion => + const positiveCriteria = criteria.filter((criterion) => positiveComparators.includes(criterion.comparator) ); - const negativeCriteria = criteria.filter(criterion => + const negativeCriteria = criteria.filter((criterion) => negativeComparators.includes(criterion.comparator) ); // Positive assertions (things that "must" match) @@ -122,7 +122,7 @@ type Filter = { const buildFiltersForCriteria = (criteria: LogDocumentCountAlertParams['criteria']) => { let filters: Filter[] = []; - criteria.forEach(criterion => { + criteria.forEach((criterion) => { const criterionQuery = buildCriterionQuery(criterion); if (criterionQuery) { filters = [...filters, criterionQuery]; diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts index 9738acd13eb6e..d1cb60112aa42 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts @@ -66,7 +66,7 @@ const getCurrentValueFromAggregations = ( const getParsedFilterQuery: ( filterQuery: string | undefined -) => Record | Array> = filterQuery => { +) => Record | Array> = (filterQuery) => { if (!filterQuery) return {}; return JSON.parse(filterQuery).bool; }; @@ -194,7 +194,7 @@ const getMetric: ( timefield: string, groupBy: string | undefined | string[], filterQuery: string | undefined -) => Promise> = async function( +) => Promise> = async function ( { callCluster }, params, index, @@ -212,10 +212,10 @@ const getMetric: ( ) => response.aggregations?.groupings?.buckets || []; const afterKeyHandler = createAfterKeyHandler( 'aggs.groupings.composite.after', - response => response.aggregations?.groupings?.after_key + (response) => response.aggregations?.groupings?.after_key ); const compositeBuckets = (await getAllCompositeData( - body => callCluster('search', { body, index }), + (body) => callCluster('search', { body, index }), searchBody, bucketSelector, afterKeyHandler @@ -224,7 +224,7 @@ const getMetric: ( (result, bucket) => ({ ...result, [Object.values(bucket.key) - .map(value => value) + .map((value) => value) .join(', ')]: getCurrentValueFromAggregations(bucket, aggType), }), {} @@ -254,7 +254,7 @@ const comparatorMap = { }; export const createMetricThresholdExecutor = (libs: InfraBackendLibs, alertId: string) => - async function({ services, params }: AlertExecutorOptions) { + async function ({ services, params }: AlertExecutorOptions) { const { criteria, groupBy, filterQuery, sourceId, alertOnNoData } = params as { criteria: MetricExpressionParams[]; groupBy: string | undefined | string[]; @@ -269,7 +269,7 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs, alertId: s ); const config = source.configuration; const alertResults = await Promise.all( - criteria.map(criterion => { + criteria.map((criterion) => { return (async () => { const currentValues = await getMetric( services, @@ -281,7 +281,7 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs, alertId: s ); const { threshold, comparator } = criterion; const comparisonFunction = comparatorMap[comparator]; - return mapValues(currentValues, value => ({ + return mapValues(currentValues, (value) => ({ ...criterion, metric: criterion.metric ?? DOCUMENT_COUNT_I18N, currentValue: value, @@ -300,11 +300,11 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs, alertId: s const alertInstance = services.alertInstanceFactory(`${alertId}-${group}`); // AND logic; all criteria must be across the threshold - const shouldAlertFire = alertResults.every(result => result[group].shouldFire); + const shouldAlertFire = alertResults.every((result) => result[group].shouldFire); // AND logic; because we need to evaluate all criteria, if one of them reports no data then the // whole alert is in a No Data/Error state - const isNoData = alertResults.some(result => result[group].isNoData); - const isError = alertResults.some(result => result[group].isError); + const isNoData = alertResults.some((result) => result[group].isNoData); + const isError = alertResults.some((result) => result[group].isError); const nextState = isError ? AlertStates.ERROR @@ -316,18 +316,18 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs, alertId: s let reason; if (nextState === AlertStates.ALERT) { - reason = alertResults.map(result => buildFiredAlertReason(result[group])).join('\n'); + reason = alertResults.map((result) => buildFiredAlertReason(result[group])).join('\n'); } if (alertOnNoData) { if (nextState === AlertStates.NO_DATA) { reason = alertResults - .filter(result => result[group].isNoData) - .map(result => buildNoDataAlertReason(result[group])) + .filter((result) => result[group].isNoData) + .map((result) => buildNoDataAlertReason(result[group])) .join('\n'); } else if (nextState === AlertStates.ERROR) { reason = alertResults - .filter(result => result[group].isError) - .map(result => buildErrorAlertReason(result[group].metric)) + .filter((result) => result[group].isError) + .map((result) => buildErrorAlertReason(result[group].metric)) .join('\n'); } } diff --git a/x-pack/plugins/infra/server/lib/alerting/register_alert_types.ts b/x-pack/plugins/infra/server/lib/alerting/register_alert_types.ts index 44d30d7281f20..ae74ed82038fd 100644 --- a/x-pack/plugins/infra/server/lib/alerting/register_alert_types.ts +++ b/x-pack/plugins/infra/server/lib/alerting/register_alert_types.ts @@ -16,7 +16,7 @@ const registerAlertTypes = (alertingPlugin: PluginSetupContract, libs: InfraBack alertingPlugin.registerType(registerMetricInventoryThresholdAlertType(libs)); const registerFns = [registerLogThresholdAlertType]; - registerFns.forEach(fn => { + registerFns.forEach((fn) => { fn(alertingPlugin, libs); }); } diff --git a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts index 15bfbce6d512e..9b3e31f4da87a 100644 --- a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts +++ b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts @@ -143,7 +143,7 @@ export class InfraLogEntriesDomain { params ); - const entries = documents.map(doc => { + const entries = documents.map((doc) => { return { id: doc.id, cursor: doc.cursor, @@ -218,7 +218,7 @@ export class InfraLogEntriesDomain { const requiredFields = getRequiredFields(configuration, messageFormattingRules); const summaries = await Promise.all( - highlightQueries.map(async highlightQueryPhrase => { + highlightQueries.map(async (highlightQueryPhrase) => { const highlightQuery = createHighlightQueryDsl(highlightQueryPhrase, requiredFields); const query = filterQuery ? { diff --git a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/message.ts b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/message.ts index 58cffc7584979..b8cadaa06f61b 100644 --- a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/message.ts +++ b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/message.ts @@ -74,7 +74,7 @@ const compileExistsCondition = (condition: LogMessageFormattingCondition) => ? { conditionFields: condition.exists, fulfillsCondition: (fields: Fields) => - condition.exists.every(fieldName => fieldName in fields), + condition.exists.every((fieldName) => fieldName in fields), } : null; diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts index f17d665e209ec..d0a6ae0fc9357 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts @@ -108,7 +108,7 @@ export class LogEntryCategoriesAnalysis { const topLogEntryCategoriesSpan = finalizeTopLogEntryCategoriesSpan(); return { - data: topLogEntryCategories.map(topCategory => ({ + data: topLogEntryCategories.map((topCategory) => ({ ...topCategory, regularExpression: logEntryCategoriesById[topCategory.categoryId]?._source.regex ?? '', histograms: categoryHistogramsById[topCategory.categoryId] ?? [], @@ -183,7 +183,9 @@ export class LogEntryCategoriesAnalysis { const logEntryDatasetsSpan = finalizeLogEntryDatasetsSpan(); return { - data: logEntryDatasetBuckets.map(logEntryDatasetBucket => logEntryDatasetBucket.key.dataset), + data: logEntryDatasetBuckets.map( + (logEntryDatasetBucket) => logEntryDatasetBucket.key.dataset + ), timing: { spans: [logEntryDatasetsSpan, ...esSearchSpans], }, @@ -297,7 +299,7 @@ export class LogEntryCategoriesAnalysis { } const topLogEntryCategories = topLogEntryCategoriesResponse.aggregations.terms_category_id.buckets.map( - topCategoryBucket => { + (topCategoryBucket) => { const maximumAnomalyScoresByDataset = topCategoryBucket.filter_record.terms_dataset.buckets.reduce< Record >( @@ -312,7 +314,7 @@ export class LogEntryCategoriesAnalysis { categoryId: parseCategoryId(topCategoryBucket.key), logEntryCount: topCategoryBucket.filter_model_plot.sum_actual.value ?? 0, datasets: topCategoryBucket.filter_model_plot.terms_dataset.buckets - .map(datasetBucket => ({ + .map((datasetBucket) => ({ name: datasetBucket.key, maximumAnomalyScore: maximumAnomalyScoresByDataset[datasetBucket.key] ?? 0, })) @@ -403,7 +405,7 @@ export class LogEntryCategoriesAnalysis { ) ) .then(decodeOrThrow(logEntryCategoryHistogramsResponseRT)) - .then(response => ({ + .then((response) => ({ histogramId, histogramBuckets: response.aggregations.filters_categories.buckets, })) @@ -435,7 +437,7 @@ export class LogEntryCategoriesAnalysis { ...(innerAccumulatedHistograms[categoryId] ?? []), { histogramId, - buckets: categoryBucket.histogram_timestamp.buckets.map(bucket => ({ + buckets: categoryBucket.histogram_timestamp.buckets.map((bucket) => ({ bucketDuration: categoryBucket.histogram_timestamp.meta.bucketDuration, logEntryCount: bucket.sum_actual.value, startTime: bucket.key, @@ -518,7 +520,7 @@ export class LogEntryCategoriesAnalysis { const esSearchSpan = finalizeEsSearchSpan(); return { - examples: hits.map(hit => ({ + examples: hits.map((hit) => ({ dataset: hit._source.event?.dataset ?? '', message: hit._source.message ?? '', timestamp: hit.sort[0], diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_rate_analysis.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_rate_analysis.ts index f60f758053c47..28c1674841973 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_rate_analysis.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_rate_analysis.ts @@ -68,7 +68,7 @@ export class LogEntryRateAnalysis { const { after_key: afterKey, buckets: latestBatchBuckets } = pipe( logRateModelPlotResponseRT.decode(mlModelPlotResponse), - map(response => response.aggregations.timestamp_partition_buckets), + map((response) => response.aggregations.timestamp_partition_buckets), fold(throwErrors(createPlainError), identity) ); diff --git a/x-pack/plugins/infra/server/lib/snapshot/create_timerange_with_interval.ts b/x-pack/plugins/infra/server/lib/snapshot/create_timerange_with_interval.ts index c75ee6d644044..924d12bec0c5c 100644 --- a/x-pack/plugins/infra/server/lib/snapshot/create_timerange_with_interval.ts +++ b/x-pack/plugins/infra/server/lib/snapshot/create_timerange_with_interval.ts @@ -47,16 +47,16 @@ const aggregationsToModules = async ( const uniqueFields = Object.values(aggregations) .reduce>((fields, agg) => { if (SnapshotModelMetricAggRT.is(agg)) { - return uniq(fields.concat(Object.values(agg).map(a => a?.field))); + return uniq(fields.concat(Object.values(agg).map((a) => a?.field))); } return fields; }, []) - .filter(v => v) as string[]; + .filter((v) => v) as string[]; const fields = await Promise.all( uniqueFields.map( - async field => + async (field) => await getDatasetForField(client, field as string, options.sourceConfiguration.metricAlias) ) ); - return fields.filter(f => f) as string[]; + return fields.filter((f) => f) as string[]; }; diff --git a/x-pack/plugins/infra/server/lib/snapshot/query_helpers.ts b/x-pack/plugins/infra/server/lib/snapshot/query_helpers.ts index 82a393079745f..916c2795c0745 100644 --- a/x-pack/plugins/infra/server/lib/snapshot/query_helpers.ts +++ b/x-pack/plugins/infra/server/lib/snapshot/query_helpers.ts @@ -35,7 +35,7 @@ export const getFieldByNodeType = (options: InfraSnapshotRequestOptions) => { export const getGroupedNodesSources = (options: InfraSnapshotRequestOptions) => { const fields = findInventoryFields(options.nodeType, options.sourceConfiguration.fields); - const sources: GroupBySource[] = options.groupBy.map(gb => { + const sources: GroupBySource[] = options.groupBy.map((gb) => { return { [`${gb.field}`]: { terms: { field: gb.field } } }; }); sources.push({ diff --git a/x-pack/plugins/infra/server/lib/snapshot/response_helpers.ts b/x-pack/plugins/infra/server/lib/snapshot/response_helpers.ts index 12f284c363bd5..031eb881c91aa 100644 --- a/x-pack/plugins/infra/server/lib/snapshot/response_helpers.ts +++ b/x-pack/plugins/infra/server/lib/snapshot/response_helpers.ts @@ -90,7 +90,7 @@ export const getNodePath = ( options: InfraSnapshotRequestOptions ): SnapshotNodePath[] => { const node = groupBucket.key; - const path = options.groupBy.map(gb => { + const path = options.groupBy.map((gb) => { return { value: node[`${gb.field}`], label: node[`${gb.field}`] } as SnapshotNodePath; }); const ip = getIPFromBucket(options.nodeType, groupBucket); @@ -158,9 +158,9 @@ const getMetricValueFromBucket = (type: SnapshotMetricType, bucket: InfraSnapsho }; function calculateMax(buckets: InfraSnapshotMetricsBucket[], type: SnapshotMetricType) { - return max(buckets.map(bucket => getMetricValueFromBucket(type, bucket))) || 0; + return max(buckets.map((bucket) => getMetricValueFromBucket(type, bucket))) || 0; } function calculateAvg(buckets: InfraSnapshotMetricsBucket[], type: SnapshotMetricType) { - return sum(buckets.map(bucket => getMetricValueFromBucket(type, bucket))) / buckets.length || 0; + return sum(buckets.map((bucket) => getMetricValueFromBucket(type, bucket))) / buckets.length || 0; } diff --git a/x-pack/plugins/infra/server/lib/snapshot/snapshot.ts b/x-pack/plugins/infra/server/lib/snapshot/snapshot.ts index 4057ed246ccaf..7dd1c3de5be5b 100644 --- a/x-pack/plugins/infra/server/lib/snapshot/snapshot.ts +++ b/x-pack/plugins/infra/server/lib/snapshot/snapshot.ts @@ -60,7 +60,7 @@ const bucketSelector = ( const handleAfterKey = createAfterKeyHandler( 'body.aggregations.nodes.composite.after', - input => input?.aggregations?.nodes?.after_key + (input) => input?.aggregations?.nodes?.after_key ); const callClusterFactory = (search: ESSearchClient) => (opts: any) => @@ -176,7 +176,7 @@ const mergeNodeBuckets = ( ): SnapshotNode[] => { const nodeMetricsForLookup = getNodeMetricsForLookup(nodeMetricsBuckets); - return nodeGroupByBuckets.map(node => { + return nodeGroupByBuckets.map((node) => { return { path: getNodePath(node, options), metric: getNodeMetrics(nodeMetricsForLookup[node.key.id], options), diff --git a/x-pack/plugins/infra/server/lib/sources/sources.ts b/x-pack/plugins/infra/server/lib/sources/sources.ts index 50f725cc6e099..65acc2b2756bd 100644 --- a/x-pack/plugins/infra/server/lib/sources/sources.ts +++ b/x-pack/plugins/infra/server/lib/sources/sources.ts @@ -42,7 +42,7 @@ export class InfraSources { ): Promise { const staticDefaultSourceConfiguration = await this.getStaticDefaultSourceConfiguration(); const savedSourceConfiguration = await this.getInternalSourceConfiguration(sourceId) - .then(internalSourceConfiguration => ({ + .then((internalSourceConfiguration) => ({ id: sourceId, version: undefined, updatedAt: undefined, @@ -52,9 +52,9 @@ export class InfraSources { internalSourceConfiguration ), })) - .catch(err => + .catch((err) => err instanceof NotFoundError - ? this.getSavedSourceConfiguration(savedObjectsClient, sourceId).then(result => ({ + ? this.getSavedSourceConfiguration(savedObjectsClient, sourceId).then((result) => ({ ...result, configuration: mergeSourceConfiguration( staticDefaultSourceConfiguration, @@ -63,7 +63,7 @@ export class InfraSources { })) : Promise.reject(err) ) - .catch(err => + .catch((err) => savedObjectsClient.errors.isNotFoundError(err) ? Promise.resolve({ id: sourceId, @@ -85,7 +85,7 @@ export class InfraSources { savedObjectsClient ); - return savedSourceConfigurations.map(savedSourceConfiguration => ({ + return savedSourceConfigurations.map((savedSourceConfiguration) => ({ ...savedSourceConfiguration, configuration: mergeSourceConfiguration( staticDefaultSourceConfiguration, @@ -242,14 +242,14 @@ const mergeSourceConfiguration = ( export const convertSavedObjectToSavedSourceConfiguration = (savedObject: unknown) => pipe( SourceConfigurationSavedObjectRuntimeType.decode(savedObject), - map(savedSourceConfiguration => ({ + map((savedSourceConfiguration) => ({ id: savedSourceConfiguration.id, version: savedSourceConfiguration.version, updatedAt: savedSourceConfiguration.updated_at, origin: 'stored' as 'stored', configuration: savedSourceConfiguration.attributes, })), - fold(errors => { + fold((errors) => { throw new Error(failure(errors).join('\n')); }, identity) ); diff --git a/x-pack/plugins/infra/server/plugin.ts b/x-pack/plugins/infra/server/plugin.ts index 496c2b32373a8..a265d53fc1bf8 100644 --- a/x-pack/plugins/infra/server/plugin.ts +++ b/x-pack/plugins/infra/server/plugin.ts @@ -89,8 +89,8 @@ export class InfraServerPlugin { } async setup(core: CoreSetup, plugins: InfraServerPluginDeps) { - await new Promise(resolve => { - this.config$.subscribe(configValue => { + await new Promise((resolve) => { + this.config$.subscribe((configValue) => { this.config = configValue; resolve(); }); diff --git a/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts b/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts index dcac23d1a3d9d..b4288dae0c221 100644 --- a/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts +++ b/x-pack/plugins/infra/server/routes/inventory_metadata/lib/get_cloud_metadata.ts @@ -90,7 +90,7 @@ export const getCloudMetadata = async ( const accounts: InventoryCloudAccount[] = []; if (response.aggregations && response.aggregations.accounts) { - response.aggregations.accounts.buckets.forEach(b => { + response.aggregations.accounts.buckets.forEach((b) => { if (b.accountNames.buckets.length) { accounts.push({ value: b.key, @@ -102,7 +102,7 @@ export const getCloudMetadata = async ( } return { accounts, - projects: projectBuckets.map(b => b.key), - regions: regionBuckets.map(b => b.key), + projects: projectBuckets.map((b) => b.key), + regions: regionBuckets.map((b) => b.key), }; }; diff --git a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_categories.ts b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_categories.ts index 6852a102afc86..d335774c85f38 100644 --- a/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_categories.ts +++ b/x-pack/plugins/infra/server/routes/log_analysis/results/log_entry_categories.ts @@ -60,7 +60,7 @@ export const initGetLogEntryCategoriesRoute = ({ endTime, categoryCount, datasets ?? [], - histograms.map(histogram => ({ + histograms.map((histogram) => ({ bucketCount: histogram.bucketCount, endTime: histogram.timeRange.endTime, id: histogram.id, diff --git a/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts b/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts index d772c000986fc..ba83f7e3f02fa 100644 --- a/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts +++ b/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts @@ -33,7 +33,7 @@ export const initValidateLogAnalysisDatasetsRoute = ({ } = request.body; const datasets = await Promise.all( - indices.map(async indexName => { + indices.map(async (indexName) => { const indexDatasets = await logEntries.getLogEntryDatasets( requestContext, timestampField, diff --git a/x-pack/plugins/infra/server/routes/log_analysis/validation/indices.ts b/x-pack/plugins/infra/server/routes/log_analysis/validation/indices.ts index 54ae0b4529daa..9b8219e514c13 100644 --- a/x-pack/plugins/infra/server/routes/log_analysis/validation/indices.ts +++ b/x-pack/plugins/infra/server/routes/log_analysis/validation/indices.ts @@ -40,10 +40,10 @@ export const initValidateLogAnalysisIndicesRoute = ({ framework }: InfraBackendL // Query each pattern individually, to map correctly the errors await Promise.all( - indices.map(async index => { + indices.map(async (index) => { const fieldCaps = await framework.callWithRequest(requestContext, 'fieldCaps', { allow_no_indices: true, - fields: fields.map(field => field.name), + fields: fields.map((field) => field.name), ignore_unavailable: true, index, }); @@ -68,7 +68,7 @@ export const initValidateLogAnalysisIndicesRoute = ({ framework }: InfraBackendL } else { const fieldTypes = Object.keys(fieldMetadata); - if (!fieldTypes.every(fieldType => validTypes.includes(fieldType))) { + if (!fieldTypes.every((fieldType) => validTypes.includes(fieldType))) { errors.push({ error: `FIELD_NOT_VALID`, index, diff --git a/x-pack/plugins/infra/server/routes/log_entries/highlights.ts b/x-pack/plugins/infra/server/routes/log_entries/highlights.ts index 9a61c8fa5aa9b..c95032f56987d 100644 --- a/x-pack/plugins/infra/server/routes/log_entries/highlights.ts +++ b/x-pack/plugins/infra/server/routes/log_entries/highlights.ts @@ -44,7 +44,7 @@ export const initLogEntriesHighlightsRoute = ({ framework, logEntries }: InfraBa if ('center' in payload) { entriesPerHighlightTerm = await Promise.all( - highlightTerms.map(highlightTerm => + highlightTerms.map((highlightTerm) => logEntries.getLogEntriesAround(requestContext, sourceId, { startTimestamp, endTimestamp, @@ -64,7 +64,7 @@ export const initLogEntriesHighlightsRoute = ({ framework, logEntries }: InfraBa } entriesPerHighlightTerm = await Promise.all( - highlightTerms.map(highlightTerm => + highlightTerms.map((highlightTerm) => logEntries.getLogEntries(requestContext, sourceId, { startTimestamp, endTimestamp, @@ -79,7 +79,7 @@ export const initLogEntriesHighlightsRoute = ({ framework, logEntries }: InfraBa return response.ok({ body: logEntriesHighlightsResponseRT.encode({ - data: entriesPerHighlightTerm.map(entries => ({ + data: entriesPerHighlightTerm.map((entries) => ({ entries, topCursor: entries[0].cursor, bottomCursor: entries[entries.length - 1].cursor, diff --git a/x-pack/plugins/infra/server/routes/log_entries/summary_highlights.ts b/x-pack/plugins/infra/server/routes/log_entries/summary_highlights.ts index d92cddcdc415d..20f572787e5a4 100644 --- a/x-pack/plugins/infra/server/routes/log_entries/summary_highlights.ts +++ b/x-pack/plugins/infra/server/routes/log_entries/summary_highlights.ts @@ -60,7 +60,7 @@ export const initLogEntriesSummaryHighlightsRoute = ({ return response.ok({ body: logEntriesSummaryHighlightsResponseRT.encode({ - data: bucketsPerHighlightTerm.map(buckets => ({ + data: bucketsPerHighlightTerm.map((buckets) => ({ start: startTimestamp, end: endTimestamp, buckets, diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts b/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts index 54a1ca0aaa7e0..82427a833a20c 100644 --- a/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts +++ b/x-pack/plugins/infra/server/routes/metadata/lib/get_cloud_metric_metadata.ts @@ -43,7 +43,7 @@ export const getCloudMetricsMetadata = async ( }, }, ], - should: CLOUD_METRICS_MODULES.map(module => ({ match: { 'event.module': module } })), + should: CLOUD_METRICS_MODULES.map((module) => ({ match: { 'event.module': module } })), }, }, size: 0, diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts b/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts index 751e494164756..8a21a97631fbb 100644 --- a/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts +++ b/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts @@ -61,11 +61,11 @@ export const getNodeInfo = async ( }, }, }; - if (!CLOUD_METRICS_MODULES.some(m => startsWith(nodeType, m))) { + if (!CLOUD_METRICS_MODULES.some((m) => startsWith(nodeType, m))) { set( params, 'body.query.bool.must_not', - CLOUD_METRICS_MODULES.map(module => ({ match: { 'event.module': module } })) + CLOUD_METRICS_MODULES.map((module) => ({ match: { 'event.module': module } })) ); } const response = await framework.callWithRequest<{ _source: InfraMetadataInfo }, {}>( diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/pick_feature_name.ts b/x-pack/plugins/infra/server/routes/metadata/lib/pick_feature_name.ts index 8b6bb49d9f645..9076451b534ee 100644 --- a/x-pack/plugins/infra/server/routes/metadata/lib/pick_feature_name.ts +++ b/x-pack/plugins/infra/server/routes/metadata/lib/pick_feature_name.ts @@ -8,7 +8,7 @@ import { InfraMetadataAggregationBucket } from '../../../lib/adapters/framework' export const pickFeatureName = (buckets: InfraMetadataAggregationBucket[]): string[] => { if (buckets) { - const metadata = buckets.map(bucket => bucket.key); + const metadata = buckets.map((bucket) => bucket.key); return metadata; } else { return []; diff --git a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_groupings.ts b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_groupings.ts index a6510b2ba1478..f4f877c188d0d 100644 --- a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_groupings.ts +++ b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_groupings.ts @@ -60,7 +60,7 @@ export const getGroupings = async ( }, }, }, - ...groupBy.map(field => ({ exists: { field } })), + ...groupBy.map((field) => ({ exists: { field } })), ]; const params = { allowNoIndices: true, @@ -72,8 +72,8 @@ export const getGroupings = async ( bool: { should: [ ...options.metrics - .filter(m => m.field) - .map(m => ({ + .filter((m) => m.field) + .map((m) => ({ exists: { field: m.field }, })), ], @@ -83,7 +83,7 @@ export const getGroupings = async ( aggs: { groupingsCount: { cardinality: { - script: { source: groupBy.map(field => `doc['${field}'].value`).join('+') }, + script: { source: groupBy.map((field) => `doc['${field}'].value`).join('+') }, }, }, groupings: { @@ -136,7 +136,7 @@ export const getGroupings = async ( const { groupings, groupingsCount } = response.aggregations; const { after_key: afterKey } = groupings; return { - series: groupings.buckets.map(bucket => { + series: groupings.buckets.map((bucket) => { const keys = Object.values(bucket.key); const id = keys.join(' / '); return { id, keys, rows: [], columns: [] }; diff --git a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/populate_series_with_tsvb_data.ts b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/populate_series_with_tsvb_data.ts index ea77050112e19..ce4a9c71b74e6 100644 --- a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/populate_series_with_tsvb_data.ts +++ b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/populate_series_with_tsvb_data.ts @@ -48,7 +48,7 @@ export const populateSeriesWithTSVBData = ( const filters: JsonObject[] = isGroupBySet ? isArray(options.groupBy) ? options.groupBy - .filter(f => f) + .filter((f) => f) .map((field, index) => ({ match: { [field as string]: series.keys?.[index] || '' } })) : [{ match: { [options.groupBy as string]: series.id } }] : []; @@ -76,8 +76,8 @@ export const populateSeriesWithTSVBData = ( // Create the TSVB model based on the request options const model = createMetricModel(options); const modules = await Promise.all( - uniq(options.metrics.filter(m => m.field)).map( - async m => await getDatasetForField(client, m.field as string, options.indexPattern) + uniq(options.metrics.filter((m) => m.field)).map( + async (m) => await getDatasetForField(client, m.field as string, options.indexPattern) ) ); @@ -88,7 +88,7 @@ export const populateSeriesWithTSVBData = ( timestampField: options.timerange.field, timerange: options.timerange, }, - modules.filter(m => m) as string[] + modules.filter((m) => m) as string[] ); if (calculatedInterval) { @@ -133,15 +133,15 @@ export const populateSeriesWithTSVBData = ( (currentTimestamps, tsvbSeries) => union( currentTimestamps, - tsvbSeries.data.map(row => row[0]) + tsvbSeries.data.map((row) => row[0]) ).sort(), [] as number[] ); // Combine the TSVB series for multiple metrics. - const rows = timestamps.map(timestamp => { + const rows = timestamps.map((timestamp) => { return tsvbResults.custom.series.reduce( (currentRow, tsvbSeries) => { - const matches = tsvbSeries.data.find(d => d[0] === timestamp); + const matches = tsvbSeries.data.find((d) => d[0] === timestamp); if (matches) { return { ...currentRow, [tsvbSeries.id]: matches[1] }; } diff --git a/x-pack/plugins/infra/server/usage/usage_collector.ts b/x-pack/plugins/infra/server/usage/usage_collector.ts index 26578bfd2b794..7be7364c331fa 100644 --- a/x-pack/plugins/infra/server/usage/usage_collector.ts +++ b/x-pack/plugins/infra/server/usage/usage_collector.ts @@ -79,7 +79,7 @@ export class UsageCollector { // only keep the newest BUCKET_NUMBER buckets const cutoff = this.getBucket() - this.BUCKET_SIZE * (this.BUCKET_NUMBER - 1); - keys.forEach(key => { + keys.forEach((key) => { if (parseInt(key, 10) < cutoff) { delete this.counters[key]; } diff --git a/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts b/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts index 43e109b009f48..a3d674b324ae8 100644 --- a/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts +++ b/x-pack/plugins/infra/server/utils/calculate_metric_interval.ts @@ -80,7 +80,7 @@ export const calculateMetricInterval = async ( return; } - const intervals = resp.aggregations.modules.buckets.map(a => a.period.value).filter(v => !!v); + const intervals = resp.aggregations.modules.buckets.map((a) => a.period.value).filter((v) => !!v); if (!intervals.length) { return; } diff --git a/x-pack/plugins/ingest_manager/README.md b/x-pack/plugins/ingest_manager/README.md index 9641c56097422..f0c2466b25b04 100644 --- a/x-pack/plugins/ingest_manager/README.md +++ b/x-pack/plugins/ingest_manager/README.md @@ -10,6 +10,17 @@ - [Integration tests](server/integration_tests/router.test.ts) - Both EPM and Fleet require `ingestManager` be enabled. They are not standalone features. +## Fleet Requirements + +Fleet needs to have Elasticsearch API keys enabled, and also to have TLS enabled on kibana, (if you want to run Kibana without TLS you can provide the following config flag `--xpack.ingestManager.fleet.tlsCheckDisabled=false`) + +Also you need to configure the hosts your agent is going to use to comunication with Elasticsearch and Kibana (Not needed if you use Elastic cloud). You can use the following flags: + +``` +--xpack.ingestManager.fleet.elasticsearch.host=http://localhost:9200 +--xpack.ingestManager.fleet.kibana.host=http://localhost:5601 +``` + ## Development ### Getting started diff --git a/x-pack/plugins/ingest_manager/common/services/agent_status.ts b/x-pack/plugins/ingest_manager/common/services/agent_status.ts index d12f1001d1ece..cc1c2da710516 100644 --- a/x-pack/plugins/ingest_manager/common/services/agent_status.ts +++ b/x-pack/plugins/ingest_manager/common/services/agent_status.ts @@ -42,23 +42,23 @@ export function getAgentStatus(agent: Agent, now: number = Date.now()): AgentSta } export function buildKueryForOnlineAgents() { - return `(${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_PERMANENT} and ${AGENT_SAVED_OBJECT_TYPE}.last_checkin >= now-${(4 * - AGENT_POLLING_THRESHOLD_MS) / - 1000}s) or (${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_TEMPORARY} and ${AGENT_SAVED_OBJECT_TYPE}.last_checkin >= now-${(3 * - AGENT_POLLING_THRESHOLD_MS) / - 1000}s) or (${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_EPHEMERAL} and ${AGENT_SAVED_OBJECT_TYPE}.last_checkin >= now-${(3 * - AGENT_POLLING_THRESHOLD_MS) / - 1000}s)`; + return `(${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_PERMANENT} and ${AGENT_SAVED_OBJECT_TYPE}.last_checkin >= now-${ + (4 * AGENT_POLLING_THRESHOLD_MS) / 1000 + }s) or (${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_TEMPORARY} and ${AGENT_SAVED_OBJECT_TYPE}.last_checkin >= now-${ + (3 * AGENT_POLLING_THRESHOLD_MS) / 1000 + }s) or (${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_EPHEMERAL} and ${AGENT_SAVED_OBJECT_TYPE}.last_checkin >= now-${ + (3 * AGENT_POLLING_THRESHOLD_MS) / 1000 + }s)`; } export function buildKueryForOfflineAgents() { - return `${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_TEMPORARY} AND ${AGENT_SAVED_OBJECT_TYPE}.last_checkin < now-${(3 * - AGENT_POLLING_THRESHOLD_MS) / - 1000}s`; + return `${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_TEMPORARY} AND ${AGENT_SAVED_OBJECT_TYPE}.last_checkin < now-${ + (3 * AGENT_POLLING_THRESHOLD_MS) / 1000 + }s`; } export function buildKueryForErrorAgents() { - return `${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_PERMANENT} AND ${AGENT_SAVED_OBJECT_TYPE}.last_checkin < now-${(4 * - AGENT_POLLING_THRESHOLD_MS) / - 1000}s`; + return `${AGENT_SAVED_OBJECT_TYPE}.type:${AGENT_TYPE_PERMANENT} AND ${AGENT_SAVED_OBJECT_TYPE}.last_checkin < now-${ + (4 * AGENT_POLLING_THRESHOLD_MS) / 1000 + }s`; } diff --git a/x-pack/plugins/ingest_manager/common/services/datasource_to_agent_datasource.ts b/x-pack/plugins/ingest_manager/common/services/datasource_to_agent_datasource.ts index 620b663451ea3..2a8b687675bf9 100644 --- a/x-pack/plugins/ingest_manager/common/services/datasource_to_agent_datasource.ts +++ b/x-pack/plugins/ingest_manager/common/services/datasource_to_agent_datasource.ts @@ -18,8 +18,8 @@ export const storedDatasourceToAgentDatasource = ( enabled, use_output: DEFAULT_OUTPUT.name, // TODO: hardcoded to default output for now inputs: inputs - .filter(input => input.enabled) - .map(input => { + .filter((input) => input.enabled) + .map((input) => { const fullInput = { ...input, ...Object.entries(input.config || {}).reduce((acc, [key, { value }]) => { @@ -27,8 +27,8 @@ export const storedDatasourceToAgentDatasource = ( return acc; }, {} as { [k: string]: any }), streams: input.streams - .filter(stream => stream.enabled) - .map(stream => { + .filter((stream) => stream.enabled) + .map((stream) => { const fullStream = { ...stream, ...stream.agent_stream, diff --git a/x-pack/plugins/ingest_manager/common/services/package_to_config.ts b/x-pack/plugins/ingest_manager/common/services/package_to_config.ts index e7a912ddf1741..dc0f73b47c599 100644 --- a/x-pack/plugins/ingest_manager/common/services/package_to_config.ts +++ b/x-pack/plugins/ingest_manager/common/services/package_to_config.ts @@ -28,7 +28,7 @@ export const packageToConfigDatasourceInputs = (packageInfo: PackageInfo): Datas // Create datasource input property if (packageDatasource?.inputs?.length) { // Map each package datasource input to agent config datasource input - packageDatasource.inputs.forEach(packageInput => { + packageDatasource.inputs.forEach((packageInput) => { // Reduces registry var def into config object entry const varsReducer = ( configObject: DatasourceConfigRecord, @@ -46,7 +46,7 @@ export const packageToConfigDatasourceInputs = (packageInfo: PackageInfo): Datas // Map each package input stream into datasource input stream const streams: DatasourceInputStream[] = packageInput.streams - ? packageInput.streams.map(packageStream => { + ? packageInput.streams.map((packageStream) => { const stream: DatasourceInputStream = { id: `${packageInput.type}-${packageStream.dataset}`, enabled: packageStream.enabled === false ? false : true, @@ -61,7 +61,7 @@ export const packageToConfigDatasourceInputs = (packageInfo: PackageInfo): Datas const input: DatasourceInput = { type: packageInput.type, - enabled: streams.length ? !!streams.find(stream => stream.enabled) : true, + enabled: streams.length ? !!streams.find((stream) => stream.enabled) : true, streams, }; diff --git a/x-pack/plugins/ingest_manager/dev_docs/api_keys.md b/x-pack/plugins/ingest_manager/dev_docs/api_keys.md index 95d7ba1963531..2143c585f5a15 100644 --- a/x-pack/plugins/ingest_manager/dev_docs/api_keys.md +++ b/x-pack/plugins/ingest_manager/dev_docs/api_keys.md @@ -2,11 +2,11 @@ Fleet uses 3 types of API Keys: -1. Enrollment API Keys - A long lived token with optional rules around assignment of policy when enrolling. It is used to enroll N agents. +1. Enrollment Token - A long lived token with optional rules around assignment of policy when enrolling. It is used to enroll N agents. -2. Access API Keys - Generated during enrollment and hidden from the user. This token is used to communicate with Kibana and is unique to each agent. This allows a single agent to be revoked without affecting other agents or their data ingestion ability. +2. Access Token - Generated during enrollment and hidden from the user. This token is used to communicate with Kibana and is unique to each agent. This allows a single agent to be revoked without affecting other agents or their data ingestion ability. -3. Output API Keys - This is used by the agent to ship data to ES. At the moment this is one token per unique output cluster per policy due to the scale needed from ES tokens not currently being supported. Once ES can accept the levels of scale needed, we would like to move to one token per agent. +3. Output API Keys - This is used by the agent to ship data to ES. This token is unique per agent. ### FAQ diff --git a/x-pack/plugins/ingest_manager/dev_docs/fleet_agents_interactions_detailed.md b/x-pack/plugins/ingest_manager/dev_docs/fleet_agents_interactions_detailed.md index ac7005063da9d..d563712fdf0a6 100644 --- a/x-pack/plugins/ingest_manager/dev_docs/fleet_agents_interactions_detailed.md +++ b/x-pack/plugins/ingest_manager/dev_docs/fleet_agents_interactions_detailed.md @@ -4,7 +4,7 @@ Fleet workflow: -- an agent enroll to fleet using an enrollmentAPiKey +- an agent enroll to fleet using an enrollment token. - Every n seconds agent is polling the checkin API to send events and check for new configuration ### Agent enrollment @@ -12,7 +12,7 @@ Fleet workflow: An agent must enroll using the REST Api provided by fleet. When an agent enroll Fleet: -- verify the API Key is a valid ES API key +- verify the Enrollment token is a valid ES API key - retrieve the Saved Object (SO) associated to this api key id (this SO contains the configuration|policy id) - create an ES ApiKey unique to the agent for accessing kibana during checkin - create an ES ApiKey per output to send logs and metrics to the output @@ -26,7 +26,7 @@ Agent are going to poll the checkin API to send events and check for new configr When an agent checkin fleet: -- verify the access API Key is a valid ES API key +- verify the access token is a valid ES API key - retrieve the agent (SO associated to this api key id) - Insert events SO - If the Agent configuration has been updated since last checkin diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx index 5a06a9a879441..2b80ab9f0068e 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx @@ -9,12 +9,12 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { EuiText, EuiLink } from '@elastic/eui'; import { AlphaFlyout } from './alpha_flyout'; -const Message = styled(EuiText).attrs(props => ({ +const Message = styled(EuiText).attrs((props) => ({ color: 'subdued', textAlign: 'center', size: 's', }))` - padding: ${props => props.theme.eui.paddingSizes.m}; + padding: ${(props) => props.theme.eui.paddingSizes.m}; `; export const AlphaMessaging: React.FC<{}> = () => { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/enrollment_instructions/manual/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/enrollment_instructions/manual/index.tsx index 5d2938f3e9fa0..78f4f73cf18be 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/enrollment_instructions/manual/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/enrollment_instructions/manual/index.tsx @@ -42,7 +42,7 @@ export const ManualInstructions: React.FunctionComponent = ({ - {copy => ( + {(copy) => ( props.theme.eui.euiBorderThin}; - background-color: ${props => props.theme.eui.euiPageBackgroundColor}; + border-bottom: ${(props) => props.theme.eui.euiBorderThin}; + background-color: ${(props) => props.theme.eui.euiPageBackgroundColor}; `; const Wrapper = styled.div<{ maxWidth?: number }>` - max-width: ${props => props.maxWidth || 1200}px; + max-width: ${(props) => props.maxWidth || 1200}px; margin-left: auto; margin-right: auto; - padding-top: ${props => props.theme.eui.paddingSizes.xl}; - padding-left: ${props => props.theme.eui.paddingSizes.m}; - padding-right: ${props => props.theme.eui.paddingSizes.m}; + padding-top: ${(props) => props.theme.eui.paddingSizes.xl}; + padding-left: ${(props) => props.theme.eui.paddingSizes.m}; + padding-right: ${(props) => props.theme.eui.paddingSizes.m}; `; const Tabs = styled(EuiTabs)` @@ -66,7 +66,7 @@ export const Header: React.FC = ({ - {tabs.map(props => ( + {tabs.map((props) => ( {props.name} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/package_icon.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/package_icon.tsx index de0dd75f635cf..7c32dfe39a0b4 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/package_icon.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/package_icon.tsx @@ -7,8 +7,9 @@ import React from 'react'; import { EuiIcon, EuiIconProps } from '@elastic/eui'; import { usePackageIconType, UsePackageIconType } from '../hooks'; -export const PackageIcon: React.FunctionComponent> = ({ packageName, version, icons, tryApi, ...euiIconProps }) => { +export const PackageIcon: React.FunctionComponent< + UsePackageIconType & Omit +> = ({ packageName, version, icons, tryApi, ...euiIconProps }) => { const iconType = usePackageIconType({ packageName, version, icons, tryApi }); return ; }; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/search_bar.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/search_bar.tsx index 579a59cb909c6..9069cc0f73806 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/search_bar.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/search_bar.tsx @@ -67,7 +67,7 @@ export const SearchBar: React.FunctionComponent = ({ } onInputChange={onChangeSearch} onItemClick={onAutocompleteClick} - suggestions={suggestions.map(suggestion => { + suggestions={suggestions.map((suggestion) => { return { ...suggestion, // For type @@ -124,7 +124,7 @@ function useSuggestions(fieldPrefix: string, search: string) { selectionEnd: query.length, }) ) - .filter(suggestion => { + .filter((suggestion) => { if (suggestion.type === 'conjunction') { return true; } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx index 9863463e68a01..cbd0b056eaaf1 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx @@ -110,7 +110,7 @@ export const SettingFlyout: React.FunctionComponent = ({ onClose }) => { }, ]} idSelected={'enabled'} - onChange={id => {}} + onChange={(id) => {}} legend={{ children: ( @@ -149,7 +149,7 @@ export const SettingFlyout: React.FunctionComponent = ({ onClose }) => { }, ]} idSelected={'enabled'} - onChange={id => {}} + onChange={(id) => {}} legend={{ children: ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_breadcrumbs.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_breadcrumbs.tsx index 207c757fd5b16..0c858cd2b305d 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_breadcrumbs.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_breadcrumbs.tsx @@ -215,13 +215,13 @@ const breadcrumbGetters: { export function useBreadcrumbs(page: Page, values: DynamicPagePathValues = {}) { const { chrome, http } = useCore(); - const breadcrumbs: ChromeBreadcrumb[] = breadcrumbGetters[page](values).map(breadcrumb => ({ + const breadcrumbs: ChromeBreadcrumb[] = breadcrumbGetters[page](values).map((breadcrumb) => ({ ...breadcrumb, href: breadcrumb.href ? http.basePath.prepend(`${BASE_PATH}#${breadcrumb.href}`) : undefined, })); const docTitle: string[] = [...breadcrumbs] .reverse() - .map(breadcrumb => breadcrumb.text as string); + .map((breadcrumb) => breadcrumb.text as string); chrome.docTitle.change(docTitle); chrome.setBreadcrumbs(breadcrumbs); } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_fleet_status.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_fleet_status.tsx index ef40c171b9ca3..8290dfb8691cf 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_fleet_status.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_fleet_status.tsx @@ -31,20 +31,20 @@ export const FleetStatusProvider: React.FC = ({ children }) => { }); async function sendGetStatus() { try { - setState(s => ({ ...s, isLoading: true })); + setState((s) => ({ ...s, isLoading: true })); const res = await sendGetFleetStatus(); if (res.error) { throw res.error; } - setState(s => ({ + setState((s) => ({ ...s, isLoading: false, isReady: res.data?.isReady ?? false, missingRequirements: res.data?.missing_requirements, })); } catch (error) { - setState(s => ({ ...s, isLoading: true })); + setState((s) => ({ ...s, isLoading: true })); } } useEffect(() => { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_input.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_input.ts index c535dc899638d..630adaefa7424 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_input.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_input.ts @@ -34,7 +34,7 @@ export function useComboInput(defaultValue = []) { setValue([...value, newVal]); }, onChange: (newVals: any[]) => { - setValue(newVals.map(val => val.label)); + setValue(newVals.map((val) => val.label)); }, }, value, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_package_icon_type.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_package_icon_type.ts index 5f231b5cc9ec9..011e0c69f2683 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_package_icon_type.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_package_icon_type.ts @@ -39,7 +39,9 @@ export const usePackageIconType = ({ setIconType(CACHED_ICONS.get(pkgKey) || ''); return; } - const svgIcons = (paramIcons || iconList)?.filter(iconDef => iconDef.type === 'image/svg+xml'); + const svgIcons = (paramIcons || iconList)?.filter( + (iconDef) => iconDef.type === 'image/svg+xml' + ); const localIconSrc = Array.isArray(svgIcons) && svgIcons[0]?.src; if (localIconSrc) { CACHED_ICONS.set(pkgKey, toImage(localIconSrc)); @@ -47,7 +49,7 @@ export const usePackageIconType = ({ return; } - const euiLogoIcon = ICON_TYPES.find(key => key.toLowerCase() === `logo${packageName}`); + const euiLogoIcon = ICON_TYPES.find((key) => key.toLowerCase() === `logo${packageName}`); if (euiLogoIcon) { CACHED_ICONS.set(pkgKey, euiLogoIcon); setIconType(euiLogoIcon); @@ -56,8 +58,8 @@ export const usePackageIconType = ({ if (tryApi && !paramIcons && !iconList) { sendGetPackageInfoByKey(pkgKey) - .catch(error => undefined) // Ignore API errors - .then(res => { + .catch((error) => undefined) // Ignore API errors + .then((res) => { CACHED_ICONS.delete(pkgKey); setIconList(res?.data?.response?.icons); }); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx index fbe7c736e2df4..72b12260a1a12 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx @@ -18,14 +18,14 @@ interface Props { } const Container = styled.div` - min-height: calc(100vh - ${props => props.theme.eui.euiHeaderChildSize}); - background: ${props => props.theme.eui.euiColorEmptyShade}; + min-height: calc(100vh - ${(props) => props.theme.eui.euiHeaderChildSize}); + background: ${(props) => props.theme.eui.euiColorEmptyShade}; `; const Nav = styled.nav` - background: ${props => props.theme.eui.euiColorEmptyShade}; - border-bottom: ${props => props.theme.eui.euiBorderThin}; - padding: ${props => + background: ${(props) => props.theme.eui.euiColorEmptyShade}; + border-bottom: ${(props) => props.theme.eui.euiBorderThin}; + padding: ${(props) => `${props.theme.eui.euiSize} ${props.theme.eui.euiSizeL} ${props.theme.eui.euiSize} ${props.theme.eui.euiSizeL}`}; .euiTabs { padding-left: 3px; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/with_header.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/with_header.tsx index d5ce5e17ad84e..ac7f85bf5f594 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/with_header.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/with_header.tsx @@ -9,7 +9,7 @@ import { EuiPage, EuiPageBody, EuiSpacer } from '@elastic/eui'; import { Header, HeaderProps } from '../components'; const Page = styled(EuiPage)` - background: ${props => props.theme.eui.euiColorEmptyShade}; + background: ${(props) => props.theme.eui.euiColorEmptyShade}; `; interface Props extends HeaderProps { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/without_header.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/without_header.tsx index cad98c5a0a7e1..08f6244242a3d 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/without_header.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/without_header.tsx @@ -8,7 +8,7 @@ import styled from 'styled-components'; import { EuiPage, EuiPageBody, EuiSpacer } from '@elastic/eui'; const Page = styled(EuiPage)` - background: ${props => props.theme.eui.euiColorEmptyShade}; + background: ${(props) => props.theme.eui.euiColorEmptyShade}; `; interface Props { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_form.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_form.tsx index c55d6009074b0..30996931ba67a 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_form.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_form.tsx @@ -32,7 +32,7 @@ interface ValidationResults { const StyledEuiAccordion = styled(EuiAccordion)` .ingest-active-button { - color: ${props => props.theme.eui.euiColorPrimary}; + color: ${(props) => props.theme.eui.euiColorPrimary}; } `; @@ -143,7 +143,7 @@ export const AgentConfigForm: React.FunctionComponent = ({ updateAgentConfig({ [name]: e.target.value })} + onChange={(e) => updateAgentConfig({ [name]: e.target.value })} isInvalid={Boolean(touchedFields[name] && validation[name])} onBlur={() => setTouchedFields({ ...touchedFields, [name]: true })} placeholder={placeholder} @@ -202,7 +202,7 @@ export const AgentConfigForm: React.FunctionComponent = ({ onCreateOption={(value: string) => { updateAgentConfig({ namespace: value }); }} - onChange={selectedOptions => { + onChange={(selectedOptions) => { updateAgentConfig({ namespace: (selectedOptions.length ? selectedOptions[0] : '') as string, }); @@ -254,7 +254,7 @@ export const AgentConfigForm: React.FunctionComponent = ({ }, { logs: false, metrics: false } )} - onChange={id => { + onChange={(id) => { if (id !== 'logs' && id !== 'metrics') { return; } @@ -265,7 +265,7 @@ export const AgentConfigForm: React.FunctionComponent = ({ const previousValues = agentConfig.monitoring_enabled || []; updateAgentConfig({ monitoring_enabled: hasLogs - ? previousValues.filter(type => type !== id) + ? previousValues.filter((type) => type !== id) : [...previousValues, id], }); }} @@ -289,7 +289,7 @@ export const AgentConfigForm: React.FunctionComponent = ({ /> - {deleteAgentConfigPrompt => { + {(deleteAgentConfigPrompt) => { return ( props.theme.eui.textColors.danger}; + color: ${(props) => props.theme.eui.textColors.danger}; `; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/datasource_delete_provider.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/datasource_delete_provider.tsx index df679d33e0324..86186f7f0a6dd 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/datasource_delete_provider.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/datasource_delete_provider.tsx @@ -89,8 +89,8 @@ export const DatasourceDeleteProvider: React.FunctionComponent = ({ try { const { data } = await sendDeleteDatasource({ datasourceIds: datasources }); - const successfulResults = data?.filter(result => result.success) || []; - const failedResults = data?.filter(result => !result.success) || []; + const successfulResults = data?.filter((result) => result.success) || []; + const failedResults = data?.filter((result) => !result.success) || []; if (successfulResults.length) { const hasMultipleSuccesses = successfulResults.length > 1; @@ -133,7 +133,7 @@ export const DatasourceDeleteProvider: React.FunctionComponent = ({ } if (onSuccessCallback.current) { - onSuccessCallback.current(successfulResults.map(result => result.id)); + onSuccessCallback.current(successfulResults.map((result) => result.id)); } } catch (e) { notifications.toasts.addDanger( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_config.tsx index 36e987d007679..6eed7e74d6bc6 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_config.tsx @@ -42,7 +42,7 @@ export const DatasourceInputConfig: React.FunctionComponent<{ const advancedVars: RegistryVarsEntry[] = []; if (packageInputVars) { - packageInputVars.forEach(varDef => { + packageInputVars.forEach((varDef) => { if (isAdvancedVar(varDef)) { advancedVars.push(varDef); } else { @@ -95,7 +95,7 @@ export const DatasourceInputConfig: React.FunctionComponent<{ - {requiredVars.map(varDef => { + {requiredVars.map((varDef) => { const { name: varName, type: varType } = varDef; const value = datasourceInput.vars![varName].value; return ( @@ -139,7 +139,7 @@ export const DatasourceInputConfig: React.FunctionComponent<{
          {isShowingAdvanced - ? advancedVars.map(varDef => { + ? advancedVars.map((varDef) => { const { name: varName, type: varType } = varDef; const value = datasourceInput.vars![varName].value; return ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_panel.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_panel.tsx index 586fc6b1d4138..db704d8b1d0f3 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_panel.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_panel.tsx @@ -25,8 +25,8 @@ import { DatasourceInputConfig } from './datasource_input_config'; import { DatasourceInputStreamConfig } from './datasource_input_stream_config'; const FlushHorizontalRule = styled(EuiHorizontalRule)` - margin-left: -${props => props.theme.eui.paddingSizes.m}; - margin-right: -${props => props.theme.eui.paddingSizes.m}; + margin-left: -${(props) => props.theme.eui.paddingSizes.m}; + margin-right: -${(props) => props.theme.eui.paddingSizes.m}; width: auto; `; @@ -84,11 +84,11 @@ export const DatasourceInputPanel: React.FunctionComponent<{
          } checked={datasourceInput.enabled} - onChange={e => { + onChange={(e) => { const enabled = e.target.checked; updateDatasourceInput({ enabled, - streams: datasourceInput.streams.map(stream => ({ + streams: datasourceInput.streams.map((stream) => ({ ...stream, enabled, })), @@ -107,7 +107,7 @@ export const DatasourceInputPanel: React.FunctionComponent<{ count: ( - {datasourceInput.streams.filter(stream => stream.enabled).length} + {datasourceInput.streams.filter((stream) => stream.enabled).length} ), @@ -168,9 +168,9 @@ export const DatasourceInputPanel: React.FunctionComponent<{ {/* Per-stream configuration */} {isShowingStreams ? ( - {packageInput.streams.map(packageInputStream => { + {packageInput.streams.map((packageInputStream) => { const datasourceInputStream = datasourceInput.streams.find( - stream => stream.dataset === packageInputStream.dataset + (stream) => stream.dataset === packageInputStream.dataset ); return datasourceInputStream ? ( @@ -179,7 +179,7 @@ export const DatasourceInputPanel: React.FunctionComponent<{ datasourceInputStream={datasourceInputStream} updateDatasourceInputStream={(updatedStream: Partial) => { const indexOfUpdatedStream = datasourceInput.streams.findIndex( - stream => stream.dataset === packageInputStream.dataset + (stream) => stream.dataset === packageInputStream.dataset ); const newStreams = [...datasourceInput.streams]; newStreams[indexOfUpdatedStream] = { @@ -196,7 +196,7 @@ export const DatasourceInputPanel: React.FunctionComponent<{ updatedInput.enabled = true; } else if ( datasourceInput.enabled && - !newStreams.find(stream => stream.enabled) + !newStreams.find((stream) => stream.enabled) ) { updatedInput.enabled = false; } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_stream_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_stream_config.tsx index 7e32936a6fffa..978ad83cd5c3c 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_stream_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_stream_config.tsx @@ -43,7 +43,7 @@ export const DatasourceInputStreamConfig: React.FunctionComponent<{ const advancedVars: RegistryVarsEntry[] = []; if (packageInputStream.vars && packageInputStream.vars.length) { - packageInputStream.vars.forEach(varDef => { + packageInputStream.vars.forEach((varDef) => { if (isAdvancedVar(varDef)) { advancedVars.push(varDef); } else { @@ -81,7 +81,7 @@ export const DatasourceInputStreamConfig: React.FunctionComponent<{ } checked={datasourceInputStream.enabled} - onChange={e => { + onChange={(e) => { const enabled = e.target.checked; updateDatasourceInputStream({ enabled, @@ -99,7 +99,7 @@ export const DatasourceInputStreamConfig: React.FunctionComponent<{ - {requiredVars.map(varDef => { + {requiredVars.map((varDef) => { const { name: varName, type: varType } = varDef; const value = datasourceInputStream.vars![varName].value; return ( @@ -143,7 +143,7 @@ export const DatasourceInputStreamConfig: React.FunctionComponent<{
          {isShowingAdvanced - ? advancedVars.map(varDef => { + ? advancedVars.map((varDef) => { const { name: varName, type: varType } = varDef; const value = datasourceInputStream.vars![varName].value; return ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_var_field.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_var_field.tsx index 846a807f9240d..f5f21f685f180 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_var_field.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/components/datasource_input_var_field.tsx @@ -35,7 +35,7 @@ export const DatasourceInputVarField: React.FunctionComponent<{ onChange([...value, newVal]); }} onChange={(newVals: any[]) => { - onChange(newVals.map(val => val.label)); + onChange(newVals.map((val) => val.label)); }} onBlur={() => setIsDirty(true)} /> @@ -54,7 +54,7 @@ export const DatasourceInputVarField: React.FunctionComponent<{ showGutter: false, }} value={value} - onChange={newVal => onChange(newVal)} + onChange={(newVal) => onChange(newVal)} onBlur={() => setIsDirty(true)} /> ); @@ -63,7 +63,7 @@ export const DatasourceInputVarField: React.FunctionComponent<{ onChange(e.target.value)} + onChange={(e) => onChange(e.target.value)} onBlur={() => setIsDirty(true)} /> ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.test.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.test.ts index b970a7d222001..992ace3530f40 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.test.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.test.ts @@ -314,18 +314,18 @@ describe('Ingest Manager - validateDatasource()', () => { }); it('returns no errors for disabled inputs', () => { - const disabledInputs = invalidDatasource.inputs.map(input => ({ ...input, enabled: false })); + const disabledInputs = invalidDatasource.inputs.map((input) => ({ ...input, enabled: false })); expect(validateDatasource({ ...validDatasource, inputs: disabledInputs }, mockPackage)).toEqual( noErrorsValidationResults ); }); it('returns only datasource and input-level errors for disabled streams', () => { - const inputsWithDisabledStreams = invalidDatasource.inputs.map(input => + const inputsWithDisabledStreams = invalidDatasource.inputs.map((input) => input.streams ? { ...input, - streams: input.streams.map(stream => ({ ...stream, enabled: false })), + streams: input.streams.map((stream) => ({ ...stream, enabled: false })), } : input ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.ts index 3a712b072dac1..61273e1fb3db9 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/services/validate_datasource.ts @@ -76,7 +76,7 @@ export const validateDatasource = ( }, {} as Record); // Validate each datasource input with either its own config fields or streams - datasource.inputs.forEach(input => { + datasource.inputs.forEach((input) => { if (!input.vars && !input.streams) { return; } @@ -109,7 +109,7 @@ export const validateDatasource = ( // Validate each input stream with config fields if (input.streams.length) { - input.streams.forEach(stream => { + input.streams.forEach((stream) => { if (!stream.vars) { return; } @@ -121,7 +121,7 @@ export const validateDatasource = ( const streamVarsByName = ( ( registryInputsByType[input.type].streams.find( - registryStream => registryStream.dataset === stream.dataset + (registryStream) => registryStream.dataset === stream.dataset ) || {} ).vars || [] ).reduce((vars, registryVar) => { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_configure_datasource.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_configure_datasource.tsx index 118c7e30f13f4..58a98f86de426 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_configure_datasource.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_configure_datasource.tsx @@ -37,8 +37,10 @@ export const StepConfigureDatasource: React.FunctionComponent<{ packageInfo.datasources[0].inputs && packageInfo.datasources[0].inputs.length ? ( - {packageInfo.datasources[0].inputs.map(packageInput => { - const datasourceInput = datasource.inputs.find(input => input.type === packageInput.type); + {packageInfo.datasources[0].inputs.map((packageInput) => { + const datasourceInput = datasource.inputs.find( + (input) => input.type === packageInput.type + ); return datasourceInput ? ( ) => { const indexOfUpdatedInput = datasource.inputs.findIndex( - input => input.type === packageInput.type + (input) => input.type === packageInput.type ); const newInputs = [...datasource.inputs]; newInputs[indexOfUpdatedInput] = { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_define_datasource.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_define_datasource.tsx index c4d602c2c2081..3b22756409330 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_define_datasource.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_define_datasource.tsx @@ -41,8 +41,8 @@ export const StepDefineDatasource: React.FunctionComponent<{ // Existing datasources on the agent config using the package name, retrieve highest number appended to datasource name const dsPackageNamePattern = new RegExp(`${packageInfo.name}-(\\d+)`); const dsWithMatchingNames = (agentConfig.datasources as Datasource[]) - .filter(ds => Boolean(ds.name.match(dsPackageNamePattern))) - .map(ds => parseInt(ds.name.match(dsPackageNamePattern)![1], 10)) + .filter((ds) => Boolean(ds.name.match(dsPackageNamePattern))) + .map((ds) => parseInt(ds.name.match(dsPackageNamePattern)![1], 10)) .sort(); updateDatasource({ @@ -83,7 +83,7 @@ export const StepDefineDatasource: React.FunctionComponent<{ > + onChange={(e) => updateDatasource({ name: e.target.value, }) @@ -112,7 +112,7 @@ export const StepDefineDatasource: React.FunctionComponent<{ > + onChange={(e) => updateDatasource({ description: e.target.value, }) diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_config.tsx index 6cbe56e628903..22cb219f911f6 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_config.tsx @@ -115,7 +115,7 @@ export const StepSelectConfig: React.FunctionComponent<{ checked: selectedConfigId === id ? 'on' : undefined, }; })} - renderOption={option => ( + renderOption={(option) => ( {option.label} @@ -148,8 +148,8 @@ export const StepSelectConfig: React.FunctionComponent<{ ), }} height={240} - onChange={options => { - const selectedOption = options.find(option => option.checked === 'on'); + onChange={(options) => { + const selectedOption = options.find((option) => option.checked === 'on'); if (selectedOption) { setSelectedConfigId(selectedOption.key); } else { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_package.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_package.tsx index 8dabb3bc98110..12f5bf9eec1d0 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_package.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_datasource_page/step_select_package.tsx @@ -131,8 +131,8 @@ export const StepSelectPackage: React.FunctionComponent<{ ), }} height={240} - onChange={options => { - const selectedOption = options.find(option => option.checked === 'on'); + onChange={(options) => { + const selectedOption = options.find((option) => option.checked === 'on'); if (selectedOption) { setSelectedPkgKey(selectedOption.key); } else { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/datasources_table.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/datasources_table.tsx index 3ad862c5e43fd..316b7eed491b9 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/datasources_table.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/datasources/datasources_table.tsx @@ -67,7 +67,7 @@ export const DatasourcesTable: React.FunctionComponent = ({ ] => { const namespacesValues: string[] = []; const inputTypesValues: string[] = []; - const mappedDatasources = originalDatasources.map(datasource => { + const mappedDatasources = originalDatasources.map((datasource) => { if (datasource.namespace && !namespacesValues.includes(datasource.namespace)) { namespacesValues.push(datasource.namespace); } @@ -84,7 +84,7 @@ export const DatasourcesTable: React.FunctionComponent = ({ streamSummary.total += input.streams.length; streamSummary.enabled += input.enabled - ? input.streams.filter(stream => stream.enabled).length + ? input.streams.filter((stream) => stream.enabled).length : 0; return streamSummary; @@ -233,7 +233,7 @@ export const DatasourcesTable: React.FunctionComponent = ({ // /> // , - {deleteDatasourcePrompt => { + {(deleteDatasourcePrompt) => { return ( ( agentConfig={agentConfig} updateAgentConfig={updateAgentConfig} withSysMonitoring={withSysMonitoring} - updateSysMonitoring={newValue => setWithSysMonitoring(newValue)} + updateSysMonitoring={(newValue) => setWithSysMonitoring(newValue)} validation={validation} isEditing={true} onDelete={() => { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/index.tsx index f80b981b69d3b..3f886645b5339 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/index.tsx @@ -35,7 +35,7 @@ import { ConfigSettingsView } from './components/settings'; const Divider = styled.div` width: 0; height: 100%; - border-left: ${props => props.theme.eui.euiBorderThin}; + border-left: ${(props) => props.theme.eui.euiBorderThin}; `; export const AgentConfigDetailsPage: React.FunctionComponent = () => { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/edit_datasource_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/edit_datasource_page/index.tsx index 92be20a2761e2..7be955bc9f4f3 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/edit_datasource_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/edit_datasource_page/index.tsx @@ -105,11 +105,11 @@ export const EditDatasourcePage: React.FunctionComponent = () => { // Remove `agent_stream` from all stream info, we assign this after saving const newDatasource = { ...restOfDatasource, - inputs: inputs.map(input => { + inputs: inputs.map((input) => { const { streams, ...restOfInput } = input; return { ...restOfInput, - streams: streams.map(stream => { + streams: streams.map((stream) => { const { agent_stream, ...restOfStream } = stream; return restOfStream; }), diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx index 9f582e7e2fbe6..349ebe1151c80 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx @@ -76,7 +76,7 @@ export const CreateAgentConfigFlyout: React.FunctionComponent = ({ onClos agentConfig={agentConfig} updateAgentConfig={updateAgentConfig} withSysMonitoring={withSysMonitoring} - updateSysMonitoring={newValue => setWithSysMonitoring(newValue)} + updateSysMonitoring={(newValue) => setWithSysMonitoring(newValue)} validation={validation} /> diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/index.tsx index ff3124d574857..5b4066e53f0c8 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/index.tsx @@ -249,7 +249,7 @@ export const AgentConfigListPage: React.FunctionComponent<{}> = () => { // If Fleet is not enabled, then remove the `agents` column if (!isFleetEnabled) { - return cols.filter(col => ('field' in col ? col.field !== 'agents' : true)); + return cols.filter((col) => ('field' in col ? col.field !== 'agents' : true)); } return cols; @@ -303,7 +303,7 @@ export const AgentConfigListPage: React.FunctionComponent<{}> = () => { { + onChange={(newSearch) => { setPagination({ ...pagination, currentPage: 1, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/components/data_stream_row_actions.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/components/data_stream_row_actions.tsx index ac47387cd7ab3..b87ae4c4561ff 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/components/data_stream_row_actions.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/components/data_stream_row_actions.tsx @@ -68,7 +68,7 @@ export const DataStreamRowActions = memo<{ datastream: DataStream }>(({ datastre panels.push({ id: 1, title: panelTitle, - items: dashboards.map(dashboard => { + items: dashboards.map((dashboard) => { return { icon: 'dashboardApp', href: useKibanaLink(`/dashboard/${dashboard.id || ''}`), diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx index 09873a3cdaa87..e1583d2e426bc 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx @@ -194,7 +194,7 @@ export const DataStreamListPage: React.FunctionComponent<{}> = () => { }; if (dataStreamsData && dataStreamsData.data_streams.length) { - dataStreamsData.data_streams.forEach(stream => { + dataStreamsData.data_streams.forEach((stream) => { const { dataset, type, namespace, package: pkg } = stream; if (!filterOptions.dataset.includes(dataset)) { filterOptions.dataset.push(dataset); @@ -270,7 +270,7 @@ export const DataStreamListPage: React.FunctionComponent<{}> = () => { defaultMessage: 'Dataset', }), multiSelect: 'or', - options: filterOptions.dataset.map(option => ({ + options: filterOptions.dataset.map((option) => ({ value: option, name: option, })), @@ -282,7 +282,7 @@ export const DataStreamListPage: React.FunctionComponent<{}> = () => { defaultMessage: 'Type', }), multiSelect: 'or', - options: filterOptions.type.map(option => ({ + options: filterOptions.type.map((option) => ({ value: option, name: option, })), @@ -294,7 +294,7 @@ export const DataStreamListPage: React.FunctionComponent<{}> = () => { defaultMessage: 'Namespace', }), multiSelect: 'or', - options: filterOptions.namespace.map(option => ({ + options: filterOptions.namespace.map((option) => ({ value: option, name: option, })), @@ -306,7 +306,7 @@ export const DataStreamListPage: React.FunctionComponent<{}> = () => { defaultMessage: 'Integration', }), multiSelect: 'or', - options: filterOptions.package.map(option => ({ + options: filterOptions.package.map((option) => ({ value: option, name: option, })), diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/assets_facet_group.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/assets_facet_group.tsx index 219896dd27ef7..ac74b09ab4391 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/assets_facet_group.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/assets_facet_group.tsx @@ -32,11 +32,11 @@ import { export function AssetsFacetGroup({ assets }: { assets: AssetsGroupedByServiceByType }) { const FirstHeaderRow = styled(EuiFlexGroup)` - padding: 0 0 ${props => props.theme.eui.paddingSizes.m} 0; + padding: 0 0 ${(props) => props.theme.eui.paddingSizes.m} 0; `; const HeaderRow = styled(EuiFlexGroup)` - padding: ${props => props.theme.eui.paddingSizes.m} 0; + padding: ${(props) => props.theme.eui.paddingSizes.m} 0; `; const FacetGroup = styled(EuiFacetGroup)` @@ -78,7 +78,7 @@ export function AssetsFacetGroup({ assets }: { assets: AssetsGroupedByServiceByT const iconType = type in AssetIcons && AssetIcons[type]; const iconNode = iconType ? : ''; const FacetButton = styled(EuiFacetButton)` - padding: '${props => props.theme.eui.paddingSizes.xs} 0'; + padding: '${(props) => props.theme.eui.paddingSizes.xs} 0'; height: 'unset'; `; return ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icon_panel.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icon_panel.tsx index 684b158b5da86..7e4337f59d650 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icon_panel.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icon_panel.tsx @@ -15,11 +15,11 @@ export function IconPanel({ iconType }: { iconType: IconType }) { position: absolute; text-align: center; vertical-align: middle; - padding: ${props => props.theme.eui.spacerSizes.xl}; + padding: ${(props) => props.theme.eui.spacerSizes.xl}; svg, img { - height: ${props => props.theme.eui.euiKeyPadMenuSize}; - width: ${props => props.theme.eui.euiKeyPadMenuSize}; + height: ${(props) => props.theme.eui.euiKeyPadMenuSize}; + width: ${(props) => props.theme.eui.euiKeyPadMenuSize}; } } `; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icons.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icons.tsx index 64223efefaab8..acdcd5b9a3406 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icons.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/icons.tsx @@ -8,7 +8,7 @@ import React from 'react'; import styled from 'styled-components'; export const StyledAlert = styled(EuiIcon)` - color: ${props => props.theme.eui.euiColorWarning}; + color: ${(props) => props.theme.eui.euiColorWarning}; padding: 0 5px; `; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/nav_button_back.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/nav_button_back.tsx index 0c01bb72b339a..3fcf9758368de 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/nav_button_back.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/nav_button_back.tsx @@ -9,7 +9,7 @@ import styled from 'styled-components'; export function NavButtonBack({ href, text }: { href: string; text: string }) { const ButtonEmpty = styled(EuiButtonEmpty)` - margin-right: ${props => props.theme.eui.spacerSizes.xl}; + margin-right: ${(props) => props.theme.eui.spacerSizes.xl}; `; return ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/package_list_grid.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/package_list_grid.tsx index 2f06d1d8703c2..dbf454acd2b74 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/package_list_grid.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/package_list_grid.tsx @@ -65,9 +65,9 @@ export function PackageListGrid({ gridContent = ; } else { const filteredList = searchTerm - ? list.filter(item => + ? list.filter((item) => (localSearchRef.current!.search(searchTerm) as PackageList) - .map(match => match[searchIdField]) + .map((match) => match[searchIdField]) .includes(item[searchIdField]) ) : list; @@ -123,7 +123,7 @@ function GridColumn({ list }: GridColumnProps) { return ( {list.length ? ( - list.map(item => ( + list.map((item) => ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/requirements.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/requirements.tsx index f60d2d83ed45e..3d6cd2bc61e72 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/requirements.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/requirements.tsx @@ -16,11 +16,11 @@ export interface RequirementsProps { } const FlexGroup = styled(EuiFlexGroup)` - padding: 0 0 ${props => props.theme.eui.paddingSizes.m} 0; + padding: 0 0 ${(props) => props.theme.eui.paddingSizes.m} 0; margin: 0; `; const StyledVersion = styled(Version)` - font-size: ${props => props.theme.eui.euiFontSizeXS}; + font-size: ${(props) => props.theme.eui.euiFontSizeXS}; `; export function Requirements(props: RequirementsProps) { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/version.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/version.tsx index 537f6201dea06..d15eee55b9f75 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/version.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/components/version.tsx @@ -9,7 +9,7 @@ import styled from 'styled-components'; import { RequirementVersion } from '../../../types'; const CodeText = styled.span` - font-family: ${props => props.theme.eui.euiCodeFontFamily}; + font-family: ${(props) => props.theme.eui.euiCodeFontFamily}; `; export function Version({ className, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_local_search.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_local_search.tsx index c81dc15f569fa..4cfae0eac5442 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_local_search.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_local_search.tsx @@ -16,7 +16,7 @@ export function useLocalSearch(packageList: PackageList) { useEffect(() => { const localSearch = new LocalSearch(searchIdField); - fieldsToSearch.forEach(field => localSearch.addIndex(field)); + fieldsToSearch.forEach((field) => localSearch.addIndex(field)); localSearch.addDocuments(packageList); localSearchRef.current = localSearch; }, [packageList]); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_package_install.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_package_install.tsx index 36b81e786b935..2342a79932c85 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_package_install.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/hooks/use_package_install.tsx @@ -181,8 +181,8 @@ export const [ useUninstallPackage, ] = createContainer( usePackageInstall, - value => value.installPackage, - value => value.setPackageInstallStatus, - value => value.getPackageInstallStatus, - value => value.uninstallPackage + (value) => value.installPackage, + (value) => value.setPackageInstallStatus, + (value) => value.getPackageInstallStatus, + (value) => value.uninstallPackage ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/content_collapse.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/content_collapse.tsx index 9d5614debb42b..482c5970ce93d 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/content_collapse.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/content_collapse.tsx @@ -9,10 +9,10 @@ import styled from 'styled-components'; const BottomFade = styled.div` width: 100%; - background: ${props => + background: ${(props) => `linear-gradient(${props.theme.eui.euiColorEmptyShade}00 0%, ${props.theme.eui.euiColorEmptyShade} 100%)`}; - margin-top: -${props => parseInt(props.theme.eui.spacerSizes.xl, 10) * 2}px; - height: ${props => parseInt(props.theme.eui.spacerSizes.xl, 10) * 2}px; + margin-top: -${(props) => parseInt(props.theme.eui.spacerSizes.xl, 10) * 2}px; + height: ${(props) => parseInt(props.theme.eui.spacerSizes.xl, 10) * 2}px; position: absolute; `; const ContentCollapseContainer = styled.div` @@ -20,11 +20,11 @@ const ContentCollapseContainer = styled.div` `; const CollapseButtonContainer = styled.div` display: inline-block; - background-color: ${props => props.theme.eui.euiColorEmptyShade}; + background-color: ${(props) => props.theme.eui.euiColorEmptyShade}; position: absolute; left: 50%; transform: translateX(-50%); - top: ${props => parseInt(props.theme.eui.euiButtonHeight, 10) / 2}px; + top: ${(props) => parseInt(props.theme.eui.euiButtonHeight, 10) / 2}px; `; const CollapseButtonTop = styled(EuiButtonEmpty)` float: right; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/header.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/header.tsx index 5c2d1373d0b0e..318bab6c44951 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/header.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/header.tsx @@ -21,7 +21,7 @@ const FullWidthNavRow = styled(EuiPage)` `; const Text = styled.span` - margin-right: ${props => props.theme.eui.euiSizeM}; + margin-right: ${(props) => props.theme.eui.euiSizeM}; `; type HeaderProps = PackageInfo & { iconType?: IconType }; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/index.tsx index 0c91413f6e210..505687068cf42 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/index.tsx @@ -27,7 +27,7 @@ export function Detail() { const [info, setInfo] = useState(null); const setPackageInstallStatus = useSetPackageInstallStatus(); useEffect(() => { - sendGetPackageInfoByKey(pkgkey).then(response => { + sendGetPackageInfoByKey(pkgkey).then((response) => { const packageInfo = response.data?.response; const title = packageInfo?.title; const name = packageInfo?.name; @@ -53,13 +53,13 @@ export function Detail() { } const FullWidthHeader = styled(EuiPage)` - border-bottom: ${props => props.theme.eui.euiBorderThin}; - padding-bottom: ${props => props.theme.eui.paddingSizes.xl}; + border-bottom: ${(props) => props.theme.eui.euiBorderThin}; + padding-bottom: ${(props) => props.theme.eui.paddingSizes.xl}; `; const FullWidthContent = styled(EuiPage)` - background-color: ${props => props.theme.eui.euiColorEmptyShade}; - padding-top: ${props => parseInt(props.theme.eui.paddingSizes.xl, 10) * 1.25}px; + background-color: ${(props) => props.theme.eui.euiColorEmptyShade}; + padding-top: ${(props) => parseInt(props.theme.eui.paddingSizes.xl, 10) * 1.25}px; flex-grow: 1; `; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/readme.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/readme.tsx index 72e2d779c39be..c8fa2184d8f9b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/readme.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/readme.tsx @@ -33,7 +33,7 @@ export function Readme({ ); useEffect(() => { - sendGetFileByPath(readmePath).then(res => { + sendGetFileByPath(readmePath).then((res) => { setMarkdown(res.data || ''); }); }, [readmePath]); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/screenshots.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/screenshots.tsx index 10cf9c97723c0..696af14604c5b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/screenshots.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/screenshots.tsx @@ -34,10 +34,10 @@ export function Screenshots(props: ScreenshotProps) { const ScreenshotsContainer = styled(EuiFlexGroup)` background: linear-gradient(360deg, rgba(0, 0, 0, 0.2) 0%, rgba(0, 0, 0, 0) 100%), - ${styledProps => styledProps.theme.eui.euiColorPrimary}; - padding: ${styledProps => getPadding(styledProps)}; + ${(styledProps) => styledProps.theme.eui.euiColorPrimary}; + padding: ${(styledProps) => getPadding(styledProps)}; flex: 0 0 auto; - border-radius: ${styledProps => styledProps.theme.eui.euiBorderRadius}; + border-radius: ${(styledProps) => styledProps.theme.eui.euiBorderRadius}; `; // fixes ie11 problems with nested flex items diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx index 4d4dba2a64e5a..5d24c180268a7 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx @@ -17,12 +17,12 @@ import { InstallationButton } from './installation_button'; import { UpdateIcon } from '../../components/icons'; const SettingsTitleCell = styled.td` - padding-right: ${props => props.theme.eui.spacerSizes.xl}; - padding-bottom: ${props => props.theme.eui.spacerSizes.m}; + padding-right: ${(props) => props.theme.eui.spacerSizes.xl}; + padding-bottom: ${(props) => props.theme.eui.spacerSizes.m}; `; const UpdatesAvailableMsgContainer = styled.span` - padding-left: ${props => props.theme.eui.spacerSizes.s}; + padding-left: ${(props) => props.theme.eui.spacerSizes.s}; `; const NoteLabel = () => ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/side_nav_links.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/side_nav_links.tsx index 65a437269ec6a..1aa491498c466 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/side_nav_links.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/side_nav_links.tsx @@ -38,7 +38,7 @@ export function SideNavLinks({ name, version, active }: NavLinkProps) { const Link = styled(EuiButtonEmpty).attrs({ href: getHref('integration_details', { pkgkey: `${name}-${version}`, panel }), })` - font-weight: ${p => + font-weight: ${(p) => active === panel ? p.theme.eui.euiFontWeightSemiBold : p.theme.eui.euiFontWeightRegular}; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/category_facets.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/category_facets.tsx index 52730664aac05..8ce43b0b62f40 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/category_facets.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/category_facets.tsx @@ -24,7 +24,7 @@ export function CategoryFacets({ {isLoading ? ( ) : ( - categories.map(category => ( + categories.map((category) => ( { const { uiSettings } = useCore(); const IS_DARK_THEME = uiSettings.get('theme:darkMode'); - const Illustration = styled(EuiImage).attrs(props => ({ + const Illustration = styled(EuiImage).attrs((props) => ({ alt: i18n.translate('xpack.ingestManager.epm.illustrationAltText', { defaultMessage: 'Illustration of an Elastic integration', }), diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/index.tsx index 84ad3593a5bf1..e00b63e29019e 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/index.tsx @@ -70,11 +70,11 @@ function InstalledPackages() { const allInstalledPackages = allPackages && allPackages.response - ? allPackages.response.filter(pkg => pkg.status === 'installed') + ? allPackages.response.filter((pkg) => pkg.status === 'installed') : []; const updatablePackages = allInstalledPackages.filter( - item => 'savedObject' in item && item.version > item.savedObject.attributes.version + (item) => 'savedObject' in item && item.version > item.savedObject.attributes.version ); const categories = [ diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/search_packages.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/search_packages.tsx index adffdefd30a4f..99df334884a1f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/search_packages.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/home/search_packages.tsx @@ -26,8 +26,8 @@ export function SearchPackages({ searchTerm, localSearchRef, allPackages }: Sear if (!localSearchRef.current) return
          Still fetching matches. Try again in a moment.
          ; const matches = localSearchRef.current.search(searchTerm) as PackageList; - const matchingIds = matches.map(match => match[searchIdField]); - const filtered = allPackages.filter(item => matchingIds.includes(item[searchIdField])); + const matchingIds = matches.map((match) => match[searchIdField]); + const filtered = allPackages.filter((item) => matchingIds.includes(item[searchIdField])); return ; } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx index 37fb556b94282..34a7ad8eb1efc 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx @@ -60,7 +60,7 @@ export const AgentDetailsActionMenu: React.FunctionComponent<{ /> , - {unenrollAgentsPrompt => ( + {(unenrollAgentsPrompt) => ( { + keyParts.forEach((keyPart) => { if (!metadataPart[keyPart]) { metadataPart[keyPart] = {}; } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/metadata_flyout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/metadata_flyout.tsx index aa6da36f8fb6c..96c09677a677f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/metadata_flyout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/metadata_flyout.tsx @@ -26,7 +26,7 @@ interface Props { export const AgentMetadataFlyout: React.FunctionComponent = ({ agent, flyout }) => { const mapMetadata = (obj: { [key: string]: string } | undefined) => { - return Object.keys(obj || {}).map(key => ({ + return Object.keys(obj || {}).map((key) => ({ title: key, description: obj ? obj[key] : '', })); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx index 2ebc495d5dda7..1a7681584ff15 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx @@ -31,7 +31,7 @@ import { AgentEventsTable, AgentDetailsActionMenu, AgentDetailsContent } from '. const Divider = styled.div` width: 0; height: 100%; - border-left: ${props => props.theme.eui.euiBorderThin}; + border-left: ${(props) => props.theme.eui.euiBorderThin}; `; export const AgentDetailsPage: React.FunctionComponent = () => { @@ -140,9 +140,7 @@ export const AgentDetailsPage: React.FunctionComponent = () => {
          ))}
          - ) : ( - undefined - ), + ) : undefined, [agentConfigData, agentData, getHref, isAgentConfigLoading] ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/index.tsx index 56cc0028f0cf9..d5b8b393e7ed9 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/index.tsx @@ -123,7 +123,7 @@ const RowActions = React.memo<{ agent: Agent; onReassignClick: () => void; refre , - {unenrollAgentsPrompt => ( + {(unenrollAgentsPrompt) => ( = () => { // Remove a config id from current search const removeConfigFilter = (configId: string) => { - setSelectedConfigs(selectedConfigs.filter(config => config !== configId)); + setSelectedConfigs(selectedConfigs.filter((config) => config !== configId)); }; // Agent enrollment flyout state @@ -196,7 +196,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { kuery = `(${kuery}) and`; } kuery = `${kuery} ${AGENT_SAVED_OBJECT_TYPE}.config_id : (${selectedConfigs - .map(config => `"${config}"`) + .map((config) => `"${config}"`) .join(' or ')})`; } @@ -206,7 +206,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { } kuery = selectedStatus - .map(status => { + .map((status) => { switch (status) { case 'online': return AgentStatusKueryHelper.buildKueryForOnlineAgents(); @@ -271,7 +271,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { defaultMessage: 'Configuration', }), render: (configId: string, agent: Agent) => { - const configName = agentConfigs.find(p => p.id === configId)?.name; + const configName = agentConfigs.find((p) => p.id === configId)?.name; return ( @@ -376,7 +376,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { /> ); - const agentToReassign = agentToReassignId && agents.find(a => a.id === agentToReassignId); + const agentToReassign = agentToReassignId && agents.find((a) => a.id === agentToReassignId); return ( <> @@ -401,7 +401,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { { + onChange={(newSearch) => { setPagination({ ...pagination, currentPage: 1, @@ -441,7 +441,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { checked={selectedStatus.includes(status) ? 'on' : undefined} onClick={() => { if (selectedStatus.includes(status)) { - setSelectedStatus([...selectedStatus.filter(s => s !== status)]); + setSelectedStatus([...selectedStatus.filter((s) => s !== status)]); } else { setSelectedStatus([...selectedStatus, status]); } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx index a8cebfdf899a6..6e7427c6ab55e 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx @@ -36,7 +36,7 @@ export const EnrollmentStepAgentConfig: React.FC = ({ agentConfigs, onKey } return enrollmentAPIKeysRequest.data.list.filter( - key => key.config_id === selectedState.agentConfigId + (key) => key.config_id === selectedState.agentConfigId ); }, [enrollmentAPIKeysRequest.data, selectedState.agentConfigId]); @@ -65,12 +65,12 @@ export const EnrollmentStepAgentConfig: React.FC = ({ agentConfigs, onKey /> } - options={agentConfigs.map(config => ({ + options={agentConfigs.map((config) => ({ value: config.id, text: config.name, }))} value={selectedState.agentConfigId || undefined} - onChange={e => + onChange={(e) => setSelectedState({ agentConfigId: e.target.value, enrollmentAPIKeyId: undefined, @@ -101,7 +101,7 @@ export const EnrollmentStepAgentConfig: React.FC = ({ agentConfigs, onKey ({ + options={filteredEnrollmentAPIKeys.map((key) => ({ value: key.id, text: key.name, }))} @@ -114,7 +114,7 @@ export const EnrollmentStepAgentConfig: React.FC = ({ agentConfigs, onKey /> } - onChange={e => { + onChange={(e) => { setSelectedState({ ...selectedState, enrollmentAPIKeyId: e.target.value, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx index 2c103ade31f5b..abb8212e4c83a 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx @@ -100,12 +100,12 @@ export const AgentReassignConfigFlyout: React.FunctionComponent = ({ onCl > ({ + options={agentConfigs.map((config) => ({ value: config.id, text: config.name, }))} value={selectedAgentConfigId} - onChange={e => setSelectedAgentConfigId(e.target.value)} + onChange={(e) => setSelectedAgentConfigId(e.target.value)} /> diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx index fd6b80310a874..cc12ea19fbecf 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx @@ -31,7 +31,7 @@ const REFRESH_INTERVAL_MS = 5000; const Divider = styled.div` width: 0; height: 100%; - border-left: ${props => props.theme.eui.euiBorderThin}; + border-left: ${(props) => props.theme.eui.euiBorderThin}; height: 45px; `; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/components/new_enrollment_key_flyout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/components/new_enrollment_key_flyout.tsx index b9c07c800635d..5ab4ed978819f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/components/new_enrollment_key_flyout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/components/new_enrollment_key_flyout.tsx @@ -80,7 +80,7 @@ export const NewEnrollmentTokenFlyout: React.FunctionComponent = ({ onClose, agentConfigs = [], }) => { - const configDefaultValue = agentConfigs.find(config => config.is_default)?.id; + const configDefaultValue = agentConfigs.find((config) => config.is_default)?.id; const form = useCreateApiKeyForm(configDefaultValue, () => { onClose(); }); @@ -110,7 +110,7 @@ export const NewEnrollmentTokenFlyout: React.FunctionComponent = ({ required={true} defaultValue={configDefaultValue} {...form.configIdInput.props} - options={agentConfigs.map(config => ({ value: config.id, text: config.name }))} + options={agentConfigs.map((config) => ({ value: config.id, text: config.name }))} /> diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/index.tsx index add495ce0c194..800d4abfd45ed 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/index.tsx @@ -178,7 +178,7 @@ export const EnrollmentTokenListPage: React.FunctionComponent<{}> = () => { defaultMessage: 'Config', }), render: (configId: string) => { - const config = agentConfigs.find(c => c.id === configId); + const config = agentConfigs.find((c) => c.id === configId); return <>{config ? config.name : configId}; }, }, @@ -246,7 +246,7 @@ export const EnrollmentTokenListPage: React.FunctionComponent<{}> = () => { { + onChange={(newSearch) => { setPagination({ ...pagination, currentPage: 1, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/datastream_section.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/datastream_section.tsx index 94d1395700ab5..87906afb4122a 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/datastream_section.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/datastream_section.tsx @@ -29,7 +29,7 @@ export const OverviewDatastreamSection: React.FC = () => { let sizeBytes = 0; const namespaces = new Set(); if (datastreamRequest.data) { - datastreamRequest.data.data_streams.forEach(val => { + datastreamRequest.data.data_streams.forEach((val) => { namespaces.add(val.namespace); sizeBytes += val.size_in_bytes; }); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx index b73fa3559c954..b4669b0a0569b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx @@ -24,10 +24,11 @@ export const OverviewIntegrationSection: React.FC = () => { const packagesRequest = useGetPackages(); const res = packagesRequest.data?.response; const total = res?.length ?? 0; - const installed = res?.filter(p => p.status === InstallationStatus.installed)?.length ?? 0; + const installed = res?.filter((p) => p.status === InstallationStatus.installed)?.length ?? 0; const updatablePackages = - res?.filter(item => 'savedObject' in item && item.version > item.savedObject.attributes.version) - ?.length ?? 0; + res?.filter( + (item) => 'savedObject' in item && item.version > item.savedObject.attributes.version + )?.length ?? 0; return ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_panel.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_panel.tsx index 41d7a7a5f0bc3..2e75d1e4690d6 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_panel.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_panel.tsx @@ -7,20 +7,22 @@ import styled from 'styled-components'; import { EuiPanel } from '@elastic/eui'; -export const OverviewPanel = styled(EuiPanel).attrs(props => ({ +export const OverviewPanel = styled(EuiPanel).attrs((props) => ({ paddingSize: 'm', }))` header { display: flex; align-items: center; justify-content: space-between; - border-bottom: 1px solid ${props => props.theme.eui.euiColorLightShade}; - margin: -${props => props.theme.eui.paddingSizes.m} -${props => props.theme.eui.paddingSizes.m} - ${props => props.theme.eui.paddingSizes.m}; - padding: ${props => props.theme.eui.paddingSizes.s} ${props => props.theme.eui.paddingSizes.m}; + border-bottom: 1px solid ${(props) => props.theme.eui.euiColorLightShade}; + margin: -${(props) => props.theme.eui.paddingSizes.m} -${(props) => + props.theme.eui.paddingSizes.m} + ${(props) => props.theme.eui.paddingSizes.m}; + padding: ${(props) => props.theme.eui.paddingSizes.s} + ${(props) => props.theme.eui.paddingSizes.m}; } h2 { - padding: ${props => props.theme.eui.paddingSizes.xs} 0; + padding: ${(props) => props.theme.eui.paddingSizes.xs} 0; } `; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_stats.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_stats.tsx index 04de22c34fe6f..d3bfc5398e7b2 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_stats.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_stats.tsx @@ -7,13 +7,13 @@ import styled from 'styled-components'; import { EuiDescriptionList } from '@elastic/eui'; -export const OverviewStats = styled(EuiDescriptionList).attrs(props => ({ +export const OverviewStats = styled(EuiDescriptionList).attrs((props) => ({ compressed: true, textStyle: 'reverse', type: 'column', }))` & > * { - margin-top: ${props => props.theme.eui.paddingSizes.s} !important; + margin-top: ${(props) => props.theme.eui.paddingSizes.s} !important; &:first-child, &:nth-child(2) { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx index 93db262714cef..ca4151fa5c46f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx @@ -25,7 +25,7 @@ import { OverviewDatastreamSection } from './components/datastream_section'; const AlphaBadge = styled(EuiBetaBadge)` vertical-align: top; - margin-left: ${props => props.theme.eui.paddingSizes.s}; + margin-left: ${(props) => props.theme.eui.paddingSizes.s}; `; export const IngestManagerOverview: React.FunctionComponent = () => { diff --git a/x-pack/plugins/ingest_manager/server/routes/agent/acks_handlers.ts b/x-pack/plugins/ingest_manager/server/routes/agent/acks_handlers.ts index 13dcea75f31d0..83d894295c312 100644 --- a/x-pack/plugins/ingest_manager/server/routes/agent/acks_handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/agent/acks_handlers.ts @@ -14,7 +14,7 @@ import { AcksService } from '../../services/agents'; import { AgentEvent } from '../../../common/types/models'; import { PostAgentAcksResponse } from '../../../common/types/rest_spec'; -export const postAgentAcksHandlerBuilder = function( +export const postAgentAcksHandlerBuilder = function ( ackService: AcksService ): RequestHandler< TypeOf, @@ -30,7 +30,7 @@ export const postAgentAcksHandlerBuilder = function( // validate that all events are for the authorized agent obtained from the api key const notAuthorizedAgentEvent = agentEvents.filter( - agentEvent => agentEvent.agent_id !== agent.id + (agentEvent) => agentEvent.agent_id !== agent.id ); if (notAuthorizedAgentEvent && notAuthorizedAgentEvent.length > 0) { diff --git a/x-pack/plugins/ingest_manager/server/routes/agent/actions_handlers.ts b/x-pack/plugins/ingest_manager/server/routes/agent/actions_handlers.ts index 8eb427e5739b0..81893b1e78338 100644 --- a/x-pack/plugins/ingest_manager/server/routes/agent/actions_handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/agent/actions_handlers.ts @@ -13,7 +13,7 @@ import { ActionsService } from '../../services/agents'; import { NewAgentAction } from '../../../common/types/models'; import { PostNewAgentActionResponse } from '../../../common/types/rest_spec'; -export const postNewAgentActionHandlerBuilder = function( +export const postNewAgentActionHandlerBuilder = function ( actionsService: ActionsService ): RequestHandler< TypeOf, diff --git a/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts b/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts index 5820303e2a1a7..ae833b55137cc 100644 --- a/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts @@ -188,7 +188,7 @@ export const postAgentCheckinHandler: RequestHandler< const body: PostAgentCheckinResponse = { action: 'checkin', success: true, - actions: actions.map(a => ({ + actions: actions.map((a) => ({ agent_id: agent.id, type: a.type, data: a.data, @@ -277,7 +277,7 @@ export const getAgentsHandler: RequestHandler< }); const body: GetAgentsResponse = { - list: agents.map(agent => ({ + list: agents.map((agent) => ({ ...agent, status: AgentService.getAgentStatus(agent), })), diff --git a/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts b/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts index 666d46f030780..9b36edd0a961c 100644 --- a/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts @@ -98,7 +98,7 @@ export const getListHandler: RequestHandler = async (context, request, response) const packageSavedObjects = await getPackageSavedObjects(context.core.savedObjects.client); const packageMetadata: any = {}; - const dataStreamsPromises = (indexResults as any[]).map(async result => { + const dataStreamsPromises = (indexResults as any[]).map(async (result) => { const { key: indexName, dataset: { buckets: datasetBuckets }, @@ -113,7 +113,7 @@ export const getListHandler: RequestHandler = async (context, request, response) const pkg = datasetBuckets.length ? datasetBuckets[0].key.split('.')[0] : indexName.split('-')[1].split('.')[0]; - const pkgSavedObject = packageSavedObjects.saved_objects.filter(p => p.id === pkg); + const pkgSavedObject = packageSavedObjects.saved_objects.filter((p) => p.id === pkg); // if // - the datastream is associated with a package @@ -123,7 +123,7 @@ export const getListHandler: RequestHandler = async (context, request, response) // then pick the dashboards from the package saved object const dashboards = pkgSavedObject[0].attributes?.installed?.filter( - o => o.type === KibanaAssetType.dashboard + (o) => o.type === KibanaAssetType.dashboard ) || []; // and then pick the human-readable titles from the dashboard saved objects const enhancedDashboards = await getEnhancedDashboards( @@ -169,7 +169,7 @@ const getEnhancedDashboards = async ( savedObjectsClient: SavedObjectsClientContract, dashboards: any[] ) => { - const dashboardsPromises = dashboards.map(async db => { + const dashboardsPromises = dashboards.map(async (db) => { const dbSavedObject: any = await getKibanaSavedObject( savedObjectsClient, KibanaAssetType.dashboard, diff --git a/x-pack/plugins/ingest_manager/server/saved_objects/index.ts b/x-pack/plugins/ingest_manager/server/saved_objects/index.ts index ad808a10400e2..703ddb521c831 100644 --- a/x-pack/plugins/ingest_manager/server/saved_objects/index.ts +++ b/x-pack/plugins/ingest_manager/server/saved_objects/index.ts @@ -262,7 +262,7 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { }; export function registerSavedObjects(savedObjects: SavedObjectsServiceSetup) { - Object.values(savedObjectTypes).forEach(type => { + Object.values(savedObjectTypes).forEach((type) => { savedObjects.registerType(type); }); } diff --git a/x-pack/plugins/ingest_manager/server/saved_objects/migrations/agent_config_v790.ts b/x-pack/plugins/ingest_manager/server/saved_objects/migrations/agent_config_v790.ts index 05ef2bb397fd9..0c850f2c25fbf 100644 --- a/x-pack/plugins/ingest_manager/server/saved_objects/migrations/agent_config_v790.ts +++ b/x-pack/plugins/ingest_manager/server/saved_objects/migrations/agent_config_v790.ts @@ -12,10 +12,9 @@ type Pre790AgentConfig = Exclude & { updated_on: string; }; -export const migrateAgentConfigToV790: SavedObjectMigrationFn< - Pre790AgentConfig, - AgentConfig -> = doc => { +export const migrateAgentConfigToV790: SavedObjectMigrationFn = ( + doc +) => { const updatedAgentConfig = cloneDeep(doc); updatedAgentConfig.attributes.updated_at = doc.attributes.updated_on; diff --git a/x-pack/plugins/ingest_manager/server/saved_objects/migrations/datasources_v790.ts b/x-pack/plugins/ingest_manager/server/saved_objects/migrations/datasources_v790.ts index 1f16af6f83065..0d1fb6f21a1ae 100644 --- a/x-pack/plugins/ingest_manager/server/saved_objects/migrations/datasources_v790.ts +++ b/x-pack/plugins/ingest_manager/server/saved_objects/migrations/datasources_v790.ts @@ -13,10 +13,9 @@ type Pre790Datasource = Exclude< 'created_at' | 'created_by' | 'updated_at' | 'updated_by' >; -export const migrateDatasourcesToV790: SavedObjectMigrationFn< - Pre790Datasource, - Datasource -> = doc => { +export const migrateDatasourcesToV790: SavedObjectMigrationFn = ( + doc +) => { const updatedDatasource = cloneDeep(doc); const defDate = new Date().toISOString(); diff --git a/x-pack/plugins/ingest_manager/server/services/agent_config.ts b/x-pack/plugins/ingest_manager/server/services/agent_config.ts index 07c69ae132833..62b568b812216 100644 --- a/x-pack/plugins/ingest_manager/server/services/agent_config.ts +++ b/x-pack/plugins/ingest_manager/server/services/agent_config.ts @@ -165,7 +165,7 @@ class AgentConfigService { }); return { - items: agentConfigs.saved_objects.map(agentConfigSO => { + items: agentConfigs.saved_objects.map((agentConfigSO) => { return { id: agentConfigSO.id, ...agentConfigSO.attributes, @@ -238,7 +238,7 @@ class AgentConfigService { ...oldAgentConfig, datasources: uniq( [...((oldAgentConfig.datasources || []) as string[])].filter( - dsId => !datasourceIds.includes(dsId) + (dsId) => !datasourceIds.includes(dsId) ) ), }, @@ -340,8 +340,8 @@ class AgentConfigService { ), }, datasources: (config.datasources as Datasource[]) - .filter(datasource => datasource.enabled) - .map(ds => storedDatasourceToAgentDatasource(ds)), + .filter((datasource) => datasource.enabled) + .map((ds) => storedDatasourceToAgentDatasource(ds)), revision: config.revision, ...(config.monitoring_enabled && config.monitoring_enabled.length > 0 ? { diff --git a/x-pack/plugins/ingest_manager/server/services/agents/acks.ts b/x-pack/plugins/ingest_manager/server/services/agents/acks.ts index 24c3b322aad7f..81ba9754e8aa4 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/acks.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/acks.ts @@ -40,8 +40,8 @@ export async function acknowledgeAgentActions( } const actionIds = agentEvents - .map(event => event.action_id) - .filter(actionId => actionId !== undefined) as string[]; + .map((event) => event.action_id) + .filter((actionId) => actionId !== undefined) as string[]; let actions; try { @@ -101,7 +101,7 @@ function buildUpdateAgentActionSentAt( actionsIds: string[], sentAt: string = new Date().toISOString() ) { - return actionsIds.map(actionId => ({ + return actionsIds.map((actionId) => ({ type: AGENT_ACTION_SAVED_OBJECT_TYPE, id: actionId, attributes: { @@ -119,7 +119,7 @@ export async function saveAgentEvents( events: AgentEvent[] ): Promise> { const objects: Array> = events.map( - eventData => { + (eventData) => { return { attributes: { ...eventData, diff --git a/x-pack/plugins/ingest_manager/server/services/agents/actions.ts b/x-pack/plugins/ingest_manager/server/services/agents/actions.ts index 1bb177e54282d..236ad7df466b4 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/actions.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/actions.ts @@ -35,7 +35,7 @@ export async function getAgentActionsForCheckin( }); return Promise.all( - res.saved_objects.map(async so => { + res.saved_objects.map(async (so) => { // Get decrypted actions return savedObjectToAgentAction( await appContextService @@ -55,7 +55,7 @@ export async function getAgentActionByIds( ) { const actions = ( await soClient.bulkGet( - actionIds.map(actionId => ({ + actionIds.map((actionId) => ({ id: actionId, type: AGENT_ACTION_SAVED_OBJECT_TYPE, })) @@ -63,7 +63,7 @@ export async function getAgentActionByIds( ).saved_objects.map(savedObjectToAgentAction); return Promise.all( - actions.map(async action => { + actions.map(async (action) => { // Get decrypted actions return savedObjectToAgentAction( await appContextService diff --git a/x-pack/plugins/ingest_manager/server/services/agents/checkin.ts b/x-pack/plugins/ingest_manager/server/services/agents/checkin.ts index 2c8b1d5bb6078..20b62eee9a317 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/checkin.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/checkin.ts @@ -100,7 +100,9 @@ async function processEventsForCheckin( if (isErrorOrState(event)) { // Remove any global or specific to a stream event - const existingEventIndex = updatedErrorEvents.findIndex(e => e.stream_id === event.stream_id); + const existingEventIndex = updatedErrorEvents.findIndex( + (e) => e.stream_id === event.stream_id + ); if (existingEventIndex >= 0) { updatedErrorEvents.splice(existingEventIndex, 1); } @@ -126,7 +128,7 @@ async function createEventsForAgent( events: NewAgentEvent[] ) { const objects: Array> = events.map( - eventData => { + (eventData) => { return { attributes: { ...eventData, @@ -172,7 +174,7 @@ export function shouldCreateConfigAction(agent: Agent, actions: AgentAction[]): return false; } - const isActionAlreadyGenerated = !!actions.find(action => { + const isActionAlreadyGenerated = !!actions.find((action) => { if (!action.data || action.type !== 'CONFIG_CHANGE') { return false; } diff --git a/x-pack/plugins/ingest_manager/server/services/agents/crud.ts b/x-pack/plugins/ingest_manager/server/services/agents/crud.ts index 43fd5a3ce0ac9..c78a9ff8bb7b5 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/crud.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/crud.ts @@ -41,8 +41,9 @@ export async function listAgents( if (showInactive === false) { const agentActiveCondition = `${AGENT_SAVED_OBJECT_TYPE}.attributes.active:true AND not ${AGENT_SAVED_OBJECT_TYPE}.attributes.type:${AGENT_TYPE_EPHEMERAL}`; - const recentlySeenEphemeralAgent = `${AGENT_SAVED_OBJECT_TYPE}.attributes.active:true AND ${AGENT_SAVED_OBJECT_TYPE}.attributes.type:${AGENT_TYPE_EPHEMERAL} AND ${AGENT_SAVED_OBJECT_TYPE}.attributes.last_checkin > ${Date.now() - - 3 * AGENT_POLLING_THRESHOLD_MS}`; + const recentlySeenEphemeralAgent = `${AGENT_SAVED_OBJECT_TYPE}.attributes.active:true AND ${AGENT_SAVED_OBJECT_TYPE}.attributes.type:${AGENT_TYPE_EPHEMERAL} AND ${AGENT_SAVED_OBJECT_TYPE}.attributes.last_checkin > ${ + Date.now() - 3 * AGENT_POLLING_THRESHOLD_MS + }`; filters.push(`(${agentActiveCondition}) OR (${recentlySeenEphemeralAgent})`); } diff --git a/x-pack/plugins/ingest_manager/server/services/agents/events.ts b/x-pack/plugins/ingest_manager/server/services/agents/events.ts index 947f79bbea094..b6d87c9ca5b2f 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/events.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/events.ts @@ -37,7 +37,7 @@ export async function getAgentEvents( searchFields: ['agent_id'], }); - const items: AgentEvent[] = saved_objects.map(so => { + const items: AgentEvent[] = saved_objects.map((so) => { return { id: so.id, ...so.attributes, diff --git a/x-pack/plugins/ingest_manager/server/services/agents/status.ts b/x-pack/plugins/ingest_manager/server/services/agents/status.ts index f570243164aa9..63388db890ea5 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/status.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/status.ts @@ -30,7 +30,7 @@ export async function getAgentStatusForConfig( undefined, AgentStatusKueryHelper.buildKueryForErrorAgents(), AgentStatusKueryHelper.buildKueryForOfflineAgents(), - ].map(kuery => + ].map((kuery) => listAgents(soClient, { showInactive: false, perPage: 0, diff --git a/x-pack/plugins/ingest_manager/server/services/agents/update.ts b/x-pack/plugins/ingest_manager/server/services/agents/update.ts index fd57e83d7421e..ec7a42ff11b7a 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/update.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/update.ts @@ -31,7 +31,7 @@ export async function updateAgentsForConfigId( hasMore = false; break; } - const agentUpdate = agents.map(agent => ({ + const agentUpdate = agents.map((agent) => ({ id: agent.id, type: AGENT_SAVED_OBJECT_TYPE, attributes: { config_newest_revision: config.revision }, diff --git a/x-pack/plugins/ingest_manager/server/services/api_keys/index.ts b/x-pack/plugins/ingest_manager/server/services/api_keys/index.ts index 57362e6b4b0de..7d8d372a89ac4 100644 --- a/x-pack/plugins/ingest_manager/server/services/api_keys/index.ts +++ b/x-pack/plugins/ingest_manager/server/services/api_keys/index.ts @@ -104,9 +104,7 @@ export function parseApiKeyFromHeaders(headers: KibanaRequest['headers']) { } export function parseApiKey(apiKey: string) { - const apiKeyId = Buffer.from(apiKey, 'base64') - .toString('utf8') - .split(':')[0]; + const apiKeyId = Buffer.from(apiKey, 'base64').toString('utf8').split(':')[0]; return { apiKey, diff --git a/x-pack/plugins/ingest_manager/server/services/datasource.ts b/x-pack/plugins/ingest_manager/server/services/datasource.ts index 8f9b4825ab5d7..c3dba0700bdaf 100644 --- a/x-pack/plugins/ingest_manager/server/services/datasource.ts +++ b/x-pack/plugins/ingest_manager/server/services/datasource.ts @@ -77,7 +77,7 @@ class DatasourceService { ids: string[] ): Promise { const datasourceSO = await soClient.bulkGet( - ids.map(id => ({ + ids.map((id) => ({ id, type: SAVED_OBJECT_TYPE, })) @@ -86,7 +86,7 @@ class DatasourceService { return null; } - return datasourceSO.saved_objects.map(so => ({ + return datasourceSO.saved_objects.map((so) => ({ id: so.id, ...so.attributes, })); @@ -112,7 +112,7 @@ class DatasourceService { }); return { - items: datasources.saved_objects.map(datasourceSO => { + items: datasources.saved_objects.map((datasourceSO) => { return { id: datasourceSO.id, ...datasourceSO.attributes, @@ -215,14 +215,14 @@ class DatasourceService { pkgInfo: PackageInfo, inputs: DatasourceInput[] ): Promise { - const inputsPromises = inputs.map(input => _assignPackageStreamToInput(pkgInfo, input)); + const inputsPromises = inputs.map((input) => _assignPackageStreamToInput(pkgInfo, input)); return Promise.all(inputsPromises); } } async function _assignPackageStreamToInput(pkgInfo: PackageInfo, input: DatasourceInput) { - const streamsPromises = input.streams.map(stream => + const streamsPromises = input.streams.map((stream) => _assignPackageStreamToStream(pkgInfo, input, stream) ); @@ -244,13 +244,13 @@ async function _assignPackageStreamToStream( throw new Error('Stream template not found, no datasource'); } - const inputFromPkg = datasource.inputs.find(pkgInput => pkgInput.type === input.type); + const inputFromPkg = datasource.inputs.find((pkgInput) => pkgInput.type === input.type); if (!inputFromPkg) { throw new Error(`Stream template not found, unable to found input ${input.type}`); } const streamFromPkg = inputFromPkg.streams.find( - pkgStream => pkgStream.dataset === stream.dataset + (pkgStream) => pkgStream.dataset === stream.dataset ); if (!streamFromPkg) { throw new Error(`Stream template not found, unable to found stream ${stream.dataset}`); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ilm/install.ts b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ilm/install.ts index 60a85e367079f..1d06bf23a8c0f 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ilm/install.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ilm/install.ts @@ -19,7 +19,7 @@ export async function installILMPolicy( ); if (!ilmPaths.length) return; await Promise.all( - ilmPaths.map(async path => { + ilmPaths.map(async (path) => { const body = Registry.getAsset(path).toString('utf-8'); const { file } = Registry.pathParts(path); const name = file.substr(0, file.lastIndexOf('.')); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ingest_pipeline/install.ts b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ingest_pipeline/install.ts index 2bbb555ef7393..bdf6ecfcdb9aa 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ingest_pipeline/install.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ingest_pipeline/install.ts @@ -39,7 +39,7 @@ export const installPipelines = async ( } return acc; }, []); - return Promise.all(pipelines).then(results => results.flat()); + return Promise.all(pipelines).then((results) => results.flat()); } return []; }; @@ -48,7 +48,7 @@ export function rewriteIngestPipeline( pipeline: string, substitutions: RewriteSubstitution[] ): string { - substitutions.forEach(sub => { + substitutions.forEach((sub) => { const { source, target, templateFunction } = sub; // This fakes the use of the golang text/template expression {{SomeTemplateFunction 'some-param'}} // cf. https://github.com/elastic/beats/blob/master/filebeat/fileset/fileset.go#L294 @@ -84,7 +84,7 @@ export async function installPipelinesForDataset({ let pipelines: any[] = []; const substitutions: RewriteSubstitution[] = []; - pipelinePaths.forEach(path => { + pipelinePaths.forEach((path) => { const { name, extension } = getNameAndExtension(path); const nameForInstallation = getPipelineNameForInstallation({ pipelineName: name, @@ -105,14 +105,14 @@ export async function installPipelinesForDataset({ }); }); - pipelines = pipelines.map(pipeline => { + pipelines = pipelines.map((pipeline) => { return { ...pipeline, contentForInstallation: rewriteIngestPipeline(pipeline.content, substitutions), }; }); - const installationPromises = pipelines.map(async pipeline => { + const installationPromises = pipelines.map(async (pipeline) => { return installPipeline({ callCluster, pipeline }); }); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/install.ts b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/install.ts index 2c452f16cc104..c600c8ba3efb8 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/install.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/install.ts @@ -54,7 +54,7 @@ const installPreBuiltTemplates = async ( pkgVersion, (entry: Registry.ArchiveEntry) => isTemplate(entry) ); - const templateInstallPromises = templatePaths.map(async path => { + const templateInstallPromises = templatePaths.map(async (path) => { const { file } = Registry.pathParts(path); const templateName = file.substr(0, file.lastIndexOf('.')); const content = JSON.parse(Registry.getAsset(path).toString('utf8')); @@ -104,7 +104,7 @@ const installPreBuiltComponentTemplates = async ( pkgVersion, (entry: Registry.ArchiveEntry) => isComponentTemplate(entry) ); - const templateInstallPromises = templatePaths.map(async path => { + const templateInstallPromises = templatePaths.map(async (path) => { const { file } = Registry.pathParts(path); const templateName = file.substr(0, file.lastIndexOf('.')); const content = JSON.parse(Registry.getAsset(path).toString('utf8')); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts index 65b5ae636612c..85d4a85e245c2 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts @@ -63,7 +63,7 @@ export function generateMappings(fields: Field[]): IndexTemplateMappings { // TODO: this can happen when the fields property in fields.yml is present but empty // Maybe validation should be moved to fields/field.ts if (fields) { - fields.forEach(field => { + fields.forEach((field) => { // If type is not defined, assume keyword const type = field.type || 'keyword'; @@ -314,11 +314,11 @@ const queryIndicesFromTemplates = async ( callCluster: CallESAsCurrentUser, templates: TemplateRef[] ): Promise => { - const indexPromises = templates.map(template => { + const indexPromises = templates.map((template) => { return getIndices(callCluster, template); }); const indexObjects = await Promise.all(indexPromises); - return indexObjects.filter(item => item !== undefined).flat(); + return indexObjects.filter((item) => item !== undefined).flat(); }; const getIndices = async ( @@ -329,7 +329,7 @@ const getIndices = async ( const res = await callCluster('search', getIndexQuery(templateName)); const indices: any[] = res?.aggregations?.index.buckets; if (indices) { - return indices.map(index => ({ + return indices.map((index) => ({ indexName: index.key, indexTemplate, })); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/fields/field.ts b/x-pack/plugins/ingest_manager/server/services/epm/fields/field.ts index abaf7ab5b0dfc..e7c0eca2a9613 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/fields/field.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/fields/field.ts @@ -105,8 +105,8 @@ export function expandFields(fields: Fields): Fields { */ function dedupFields(fields: Fields): Fields { const dedupedFields: Fields = []; - fields.forEach(field => { - const found = dedupedFields.find(f => { + fields.forEach((field) => { + const found = dedupedFields.find((f) => { return f.name === field.name; }); if (found) { @@ -185,7 +185,7 @@ function dedupFields(fields: Fields): Fields { function validateFields(fields: Fields, allFields: Fields): Fields { const validatedFields: Fields = []; - fields.forEach(field => { + fields.forEach((field) => { if (field.type === 'alias') { if (field.path && getField(allFields, field.path.split('.'))) { validatedFields.push(field); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.test.ts b/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.test.ts index f1660fbc01591..d083b40e40fd5 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.test.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.test.ts @@ -64,7 +64,7 @@ describe('creating index patterns from yaml fields', () => { describe('dedupFields', () => { const deduped = dedupeFields(dupeFields); const checkIfDup = (field: Field) => { - return deduped.filter(item => item.name === field.name); + return deduped.filter((item) => item.name === field.name); }; test('there there is one field object with name of "1"', () => { expect(checkIfDup({ name: '1' }).length).toBe(1); @@ -80,7 +80,7 @@ describe('creating index patterns from yaml fields', () => { }); // existing field takes precendence test('the new merged field has correct attributes', () => { - const mergedField = deduped.find(field => field.name === '1'); + const mergedField = deduped.find((field) => field.name === '1'); expect(mergedField?.searchable).toBe(true); expect(mergedField?.aggregatable).toBe(true); expect(mergedField?.analyzed).toBe(true); @@ -153,7 +153,7 @@ describe('creating index patterns from yaml fields', () => { { fields: [{ name: 'testField', type: 'constant_keyword' }], expect: 'string' }, ]; - tests.forEach(test => { + tests.forEach((test) => { const res = test.fields.map(transformField); expect(res[0].type).toBe(test.expect); }); @@ -261,7 +261,7 @@ describe('creating index patterns from yaml fields', () => { { fields: [{ name }], expect: undefined, attr: 'lang' }, { fields: [{ name, script: 'doc[]' }], expect: 'painless', attr: 'lang' }, ]; - tests.forEach(test => { + tests.forEach((test) => { const res = test.fields.map(transformField); expect(res[0][test.attr]).toBe(test.expect); }); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.ts b/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.ts index d220ecfc62bb8..f321e2d614a04 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/kibana/index_pattern/install.ts @@ -88,7 +88,7 @@ export async function installIndexPatterns( ); if (pkgName && pkgVersion) { // add this package to the array if it doesn't already exist - const foundPkg = installedPackages.find(pkg => pkg.pkgName === pkgName); + const foundPkg = installedPackages.find((pkg) => pkg.pkgName === pkgName); // this may be removed if we add the packged to saved objects before installing index patterns // otherwise this is a first time install // TODO: handle update case when versions are different @@ -97,7 +97,7 @@ export async function installIndexPatterns( } } // get each package's registry info - const installedPackagesFetchInfoPromise = installedPackages.map(pkg => + const installedPackagesFetchInfoPromise = installedPackages.map((pkg) => Registry.fetchInfo(pkg.pkgName, pkg.pkgVersion) ); const installedPackagesInfo = await Promise.all(installedPackagesFetchInfoPromise); @@ -108,7 +108,7 @@ export async function installIndexPatterns( IndexPatternType.metrics, IndexPatternType.events, ]; - indexPatternTypes.forEach(async indexPatternType => { + indexPatternTypes.forEach(async (indexPatternType) => { // if this is an update because a package is being unisntalled (no pkgkey argument passed) and no other packages are installed, remove the index pattern if (!pkgName && installedPackages.length === 0) { try { @@ -140,8 +140,8 @@ export const getAllDatasetFieldsByType = async ( const datasetsPromises = packages.reduce>>((acc, pkg) => { if (pkg.datasets) { // filter out datasets by datasetType - const matchingDatasets = pkg.datasets.filter(dataset => dataset.type === datasetType); - matchingDatasets.forEach(dataset => acc.push(loadFieldsFromYaml(pkg, dataset.path))); + const matchingDatasets = pkg.datasets.filter((dataset) => dataset.type === datasetType); + matchingDatasets.forEach((dataset) => acc.push(loadFieldsFromYaml(pkg, dataset.path))); } return acc; }, []); @@ -329,7 +329,7 @@ export const flattenFields = (allFields: Fields): Fields => { // helper function to call flatten() and rename the fields const renameAndFlatten = (field: Field, fields: Fields, acc: Fields): Fields => { const flattenedFields = flatten(fields); - flattenedFields.forEach(nestedField => { + flattenedFields.forEach((nestedField) => { acc.push({ ...nestedField, name: `${field.name}.${nestedField.name}`, @@ -372,7 +372,7 @@ export const ensureDefaultIndices = async (callCluster: CallESAsCurrentUser) => // that no matching indices exist https://github.com/elastic/kibana/issues/62343 const logger = appContextService.getLogger(); return Promise.all( - Object.keys(IndexPatternType).map(async indexPattern => { + Object.keys(IndexPatternType).map(async (indexPattern) => { const defaultIndexPatternName = indexPattern + INDEX_PATTERN_PLACEHOLDER_SUFFIX; const indexExists = await callCluster('indices.exists', { index: defaultIndexPatternName }); if (!indexExists) { diff --git a/x-pack/plugins/ingest_manager/server/services/epm/packages/assets.ts b/x-pack/plugins/ingest_manager/server/services/epm/packages/assets.ts index 50d347c69cc24..c6f7a1f6b97aa 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/packages/assets.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/packages/assets.ts @@ -62,7 +62,7 @@ export async function getAssetsData( // Gather all asset data const assets = getAssets(packageInfo, filter, datasetName); - const entries: Registry.ArchiveEntry[] = assets.map(registryPath => { + const entries: Registry.ArchiveEntry[] = assets.map((registryPath) => { const archivePath = registryPathToArchivePath(registryPath); const buffer = Registry.getAsset(archivePath); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/packages/get.ts b/x-pack/plugins/ingest_manager/server/services/epm/packages/get.ts index 6db08e344b3da..7d5e6d6e88387 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/packages/get.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/packages/get.ts @@ -26,8 +26,8 @@ export async function getPackages( } & Registry.SearchParams ) { const { savedObjectsClient } = options; - const registryItems = await Registry.fetchList({ category: options.category }).then(items => { - return items.map(item => + const registryItems = await Registry.fetchList({ category: options.category }).then((items) => { + return items.map((item) => Object.assign({}, item, { title: item.title || nameAsTitle(item.name) }) ); }); @@ -35,9 +35,11 @@ export async function getPackages( const packageSavedObjects = await getPackageSavedObjects(savedObjectsClient); // filter out any internal packages - const savedObjectsVisible = packageSavedObjects.saved_objects.filter(o => !o.attributes.internal); + const savedObjectsVisible = packageSavedObjects.saved_objects.filter( + (o) => !o.attributes.internal + ); const packageList = registryItems - .map(item => + .map((item) => createInstallableFrom( item, savedObjectsVisible.find(({ id }) => id === item.name) @@ -99,7 +101,7 @@ export async function getInstallationObject(options: { const { savedObjectsClient, pkgName } = options; return savedObjectsClient .get(PACKAGES_SAVED_OBJECT_TYPE, pkgName) - .catch(e => undefined); + .catch((e) => undefined); } export async function getInstallation(options: { diff --git a/x-pack/plugins/ingest_manager/server/services/epm/packages/install.ts b/x-pack/plugins/ingest_manager/server/services/epm/packages/install.ts index 79a5e98b9507d..dddb21bc4e075 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/packages/install.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/packages/install.ts @@ -140,7 +140,7 @@ export async function installPackage(options: { const toSaveESIndexPatterns = generateESIndexPatterns(registryPackageInfo.datasets); // get template refs to save - const installedTemplateRefs = installedTemplates.map(template => ({ + const installedTemplateRefs = installedTemplates.map((template) => ({ id: template.templateName, type: IngestAssetType.IndexTemplate, })); @@ -191,13 +191,13 @@ export async function installKibanaAssets(options: { // Only install Kibana assets during package installation. const kibanaAssetTypes = Object.values(KibanaAssetType); - const installationPromises = kibanaAssetTypes.map(async assetType => + const installationPromises = kibanaAssetTypes.map(async (assetType) => installKibanaSavedObjects({ savedObjectsClient, pkgName, pkgVersion, assetType }) ); // installKibanaSavedObjects returns AssetReference[], so .map creates AssetReference[][] // call .flat to flatten into one dimensional array - return Promise.all(installationPromises).then(results => results.flat()); + return Promise.all(installationPromises).then((results) => results.flat()); } export async function saveInstallationReferences(options: { diff --git a/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts b/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts index 23e63f0a89a5e..9b506a2d055a7 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts @@ -119,7 +119,7 @@ export async function deleteAssetsByType({ installedObjects: AssetReference[]; assetType: ElasticsearchAssetType; }) { - const toDelete = installedObjects.filter(asset => asset.type === assetType); + const toDelete = installedObjects.filter((asset) => asset.type === assetType); try { await deleteAssets(toDelete, savedObjectsClient, callCluster); } catch (err) { diff --git a/x-pack/plugins/ingest_manager/server/services/epm/registry/extract.ts b/x-pack/plugins/ingest_manager/server/services/epm/registry/extract.ts index feed2236f06eb..1f708c5edbcc7 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/registry/extract.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/registry/extract.ts @@ -22,7 +22,7 @@ export async function untarBuffer( const inflateStream = tar.list().on('entry', (entry: tar.FileStat) => { const path = entry.header.path || ''; if (!filter({ path })) return; - streamToBuffer(entry).then(entryBuffer => onEntry({ buffer: entryBuffer, path })); + streamToBuffer(entry).then((entryBuffer) => onEntry({ buffer: entryBuffer, path })); }); return new Promise((resolve, reject) => { diff --git a/x-pack/plugins/ingest_manager/server/services/epm/registry/streams.ts b/x-pack/plugins/ingest_manager/server/services/epm/registry/streams.ts index e174c5f2e4d72..97d6f7b40a588 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/registry/streams.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/registry/streams.ts @@ -23,7 +23,7 @@ export function streamToString(stream: NodeJS.ReadableStream): Promise { export function streamToBuffer(stream: NodeJS.ReadableStream): Promise { return new Promise((resolve, reject) => { const chunks: Buffer[] = []; - stream.on('data', chunk => chunks.push(Buffer.from(chunk))); + stream.on('data', (chunk) => chunks.push(Buffer.from(chunk))); stream.on('end', () => resolve(Buffer.concat(chunks))); stream.on('error', reject); }); diff --git a/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/linux.ts b/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/linux.ts index 0bb68c40bc580..50421070e1202 100644 --- a/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/linux.ts +++ b/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/linux.ts @@ -6,7 +6,7 @@ import { InstallTemplateFunction } from './types'; -export const linuxInstallTemplate: InstallTemplateFunction = variables => { +export const linuxInstallTemplate: InstallTemplateFunction = (variables) => { const artifact = `elastic-agent-${variables.kibanaVersion}-linux-x86_64`; return `#!/bin/sh diff --git a/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/macos.ts b/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/macos.ts index 11bb58d184d33..921c31ebe238f 100644 --- a/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/macos.ts +++ b/x-pack/plugins/ingest_manager/server/services/install_script/install_templates/macos.ts @@ -6,7 +6,7 @@ import { InstallTemplateFunction } from './types'; -export const macosInstallTemplate: InstallTemplateFunction = variables => { +export const macosInstallTemplate: InstallTemplateFunction = (variables) => { const artifact = `elastic-agent-${variables.kibanaVersion}-darwin-x86_64`; return `#!/bin/sh diff --git a/x-pack/plugins/ingest_manager/server/services/output.ts b/x-pack/plugins/ingest_manager/server/services/output.ts index ce6f1f2e27130..618fefd80edaf 100644 --- a/x-pack/plugins/ingest_manager/server/services/output.ts +++ b/x-pack/plugins/ingest_manager/server/services/output.ts @@ -122,7 +122,7 @@ class OutputService { }); return { - items: outputs.saved_objects.map(outputSO => { + items: outputs.saved_objects.map((outputSO) => { return { id: outputSO.id, ...outputSO.attributes, diff --git a/x-pack/plugins/ingest_manager/server/services/setup.ts b/x-pack/plugins/ingest_manager/server/services/setup.ts index 6481b0753bab5..b6e1bca7b9d05 100644 --- a/x-pack/plugins/ingest_manager/server/services/setup.ts +++ b/x-pack/plugins/ingest_manager/server/services/setup.ts @@ -81,7 +81,7 @@ export async function setupIngestManager( } for (const installedPackage of installedPackages) { const packageShouldBeInstalled = DEFAULT_AGENT_CONFIGS_PACKAGES.some( - packageName => installedPackage.name === packageName + (packageName) => installedPackage.name === packageName ); if (!packageShouldBeInstalled) { continue; diff --git a/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/pipelines_list.helpers.ts b/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/pipelines_list.helpers.ts index 0f9745981c18b..03ffe361bb5a6 100644 --- a/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/pipelines_list.helpers.ts +++ b/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/pipelines_list.helpers.ts @@ -67,10 +67,7 @@ const createActions = (testBed: TestBed) => { clickActionMenu(pipelineName); - component - .find('.euiContextMenuItem') - .at(actions.indexOf(action)) - .simulate('click'); + component.find('.euiContextMenuItem').at(actions.indexOf(action)).simulate('click'); }; return { diff --git a/x-pack/plugins/ingest_pipelines/kibana.json b/x-pack/plugins/ingest_pipelines/kibana.json index ec02c5f80edf9..cb24133b1f6ba 100644 --- a/x-pack/plugins/ingest_pipelines/kibana.json +++ b/x-pack/plugins/ingest_pipelines/kibana.json @@ -3,15 +3,7 @@ "version": "8.0.0", "server": true, "ui": true, - "requiredPlugins": [ - "licensing", - "management" - ], - "optionalPlugins": [ - "usageCollection" - ], - "configPath": [ - "xpack", - "ingest_pipelines" - ] + "requiredPlugins": ["licensing", "management"], + "optionalPlugins": ["security", "usageCollection"], + "configPath": ["xpack", "ingest_pipelines"] } diff --git a/x-pack/plugins/ingest_pipelines/public/application/app.tsx b/x-pack/plugins/ingest_pipelines/public/application/app.tsx index 98b49bafd6ed6..f4ac640722120 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/app.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/app.tsx @@ -50,7 +50,7 @@ export const App: FunctionComponent = () => { return ( `cluster.${privilege}`)} + privileges={APP_CLUSTER_REQUIRED_PRIVILEGES.map((privilege) => `cluster.${privilege}`)} > {({ isLoading, hasPrivileges, privilegesMissing }) => { if (isLoading) { diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form.tsx index d9cbee248a788..73bc1cfaa2cf5 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form.tsx @@ -127,7 +127,7 @@ export const PipelineForm: React.FunctionComponent = ({ setIsRequestVisible(prevIsRequestVisible => !prevIsRequestVisible)} + onClick={() => setIsRequestVisible((prevIsRequestVisible) => !prevIsRequestVisible)} > {isRequestVisible ? ( = ({ {/* ES request flyout */} {isRequestVisible ? ( setIsRequestVisible(prevIsRequestVisible => !prevIsRequestVisible)} + closeFlyout={() => setIsRequestVisible((prevIsRequestVisible) => !prevIsRequestVisible)} /> ) : null} @@ -155,7 +155,7 @@ export const PipelineForm: React.FunctionComponent = ({ {isTestingPipeline ? ( { - setIsTestingPipeline(prevIsTestingPipeline => !prevIsTestingPipeline); + setIsTestingPipeline((prevIsTestingPipeline) => !prevIsTestingPipeline); }} /> ) : null} diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_fields.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_fields.tsx index dfdd9ea2f748e..9fb5ab55a34ce 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_fields.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_fields.tsx @@ -60,7 +60,7 @@ export const PipelineFormFields: React.FunctionComponent = ({ /> } checked={isVersionVisible} - onChange={e => setIsVersionVisible(e.target.checked)} + onChange={(e) => setIsVersionVisible(e.target.checked)} data-test-subj="versionToggle" /> @@ -205,7 +205,7 @@ export const PipelineFormFields: React.FunctionComponent = ({ /> } checked={isOnFailureEditorVisible} - onChange={e => setIsOnFailureEditorVisible(e.target.checked)} + onChange={(e) => setIsOnFailureEditorVisible(e.target.checked)} data-test-subj="onFailureToggle" /> diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_provider.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_provider.tsx index 57abea2309aa1..e6482a9fc12c2 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_provider.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_form_provider.tsx @@ -9,7 +9,9 @@ import React from 'react'; import { PipelineForm as PipelineFormUI, PipelineFormProps } from './pipeline_form'; import { TestConfigContextProvider } from './test_config_context'; -export const PipelineFormProvider: React.FunctionComponent = passThroughProps => { +export const PipelineFormProvider: React.FunctionComponent = ( + passThroughProps +) => { return ( diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/pipeline_test_flyout.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/pipeline_test_flyout.tsx index ea96ead9a3aab..da5e6cf77364c 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/pipeline_test_flyout.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/pipeline_test_flyout.tsx @@ -154,7 +154,7 @@ export const PipelineTestFlyout: React.FunctionComponent !executeOutput && tabId === 'output'} + getIsDisabled={(tabId) => !executeOutput && tabId === 'output'} /> diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/pipeline_test_tabs.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/pipeline_test_tabs.tsx index f720b80122702..4d378db169574 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/pipeline_test_tabs.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/pipeline_test_tabs.tsx @@ -44,7 +44,7 @@ export const Tabs: React.FunctionComponent = ({ return ( - {tabs.map(tab => ( + {tabs.map((tab) => ( onTabChange(tab.id)} isSelected={tab.id === selectedTab} diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/tab_output.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/tab_output.tsx index bcaf186e62129..f7c349a379c68 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/tab_output.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/pipeline_test_flyout/tabs/tab_output.tsx @@ -76,7 +76,7 @@ export const OutputTab: React.FunctionComponent = ({ /> } checked={cachedVerbose} - onChange={e => onEnableVerbose(e.target.checked)} + onChange={(e) => onEnableVerbose(e.target.checked)} /> diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/schema.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/schema.tsx index e122307ca9485..5435f43a78acf 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/schema.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_form/schema.tsx @@ -104,7 +104,7 @@ export const pipelineFormSchema: FormSchema = { }} /> ), - serializer: value => { + serializer: (value) => { const result = parseJson(value); // If an empty array was passed, strip out this value entirely. if (!result.length) { @@ -115,7 +115,7 @@ export const pipelineFormSchema: FormSchema = { deserializer: stringifyJson, validations: [ { - validator: validationArg => { + validator: (validationArg) => { if (!validationArg.value) { return; } diff --git a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_clone/pipelines_clone.tsx b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_clone/pipelines_clone.tsx index b3b1217caf834..4c857dc9c74f7 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_clone/pipelines_clone.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_clone/pipelines_clone.tsx @@ -21,7 +21,7 @@ export interface ParamProps { * This section is a wrapper around the create section where we receive a pipeline name * to load and set as the source pipeline for the {@link PipelinesCreate} form. */ -export const PipelinesClone: FunctionComponent> = props => { +export const PipelinesClone: FunctionComponent> = (props) => { const { sourceName } = props.match.params; const { services } = useKibana(); diff --git a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/delete_modal.tsx b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/delete_modal.tsx index c7736a6c19ba1..390863146fac4 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/delete_modal.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/delete_modal.tsx @@ -114,7 +114,7 @@ export const PipelineDeleteModal = ({

            - {pipelinesToDelete.map(name => ( + {pipelinesToDelete.map((name) => (
          • {name}
          • ))}
          diff --git a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/details_flyout.tsx b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/details_flyout.tsx index 39789bb38ed41..3122aa6da7396 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/details_flyout.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/details_flyout.tsx @@ -89,7 +89,7 @@ export const PipelineDetailsFlyout: FunctionComponent = ({ defaultMessage: 'Manage pipeline', } )} - onClick={() => setShowPopover(previousBool => !previousBool)} + onClick={() => setShowPopover((previousBool) => !previousBool)} iconType="arrowUp" iconSide="right" fill diff --git a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/main.tsx b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/main.tsx index 948290b169134..ccb50376dddb7 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/main.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/main.tsx @@ -61,7 +61,7 @@ export const PipelinesList: React.FunctionComponent = ({ useEffect(() => { if (pipelineNameFromLocation && data?.length) { - const pipeline = data.find(p => p.name === pipelineNameFromLocation); + const pipeline = data.find((p) => p.name === pipelineNameFromLocation); setSelectedPipeline(pipeline); setShowFlyout(true); } @@ -201,7 +201,7 @@ export const PipelinesList: React.FunctionComponent = ({ {renderFlyout()} {pipelinesToDelete?.length > 0 ? ( { + callback={(deleteResponse) => { if (deleteResponse?.hasDeletedPipelines) { // reload pipelines list sendRequest(); diff --git a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/table.tsx b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/table.tsx index e5c708b5c0e53..541a2b486b5a7 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/table.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/sections/pipelines_list/table.tsx @@ -57,7 +57,7 @@ export const PipelineTable: FunctionComponent = ({ selection.length > 0 ? ( onDeletePipelineClick(selection.map(pipeline => pipeline.name))} + onClick={() => onDeletePipelineClick(selection.map((pipeline) => pipeline.name))} color="danger" > = ({ values={{ count: selection.length }} /> - ) : ( - undefined - ), + ) : undefined, toolsRight: [ encodeURIComponent(name)).join(',')}`, + path: `${API_BASE_PATH}/${names.map((name) => encodeURIComponent(name)).join(',')}`, method: 'delete', }); diff --git a/x-pack/plugins/ingest_pipelines/public/plugin.ts b/x-pack/plugins/ingest_pipelines/public/plugin.ts index d537f8d68d7e4..2c1ffdd31aafe 100644 --- a/x-pack/plugins/ingest_pipelines/public/plugin.ts +++ b/x-pack/plugins/ingest_pipelines/public/plugin.ts @@ -27,7 +27,7 @@ export class IngestPipelinesPlugin implements Plugin { title: i18n.translate('xpack.ingestPipelines.appTitle', { defaultMessage: 'Ingest Node Pipelines', }), - mount: async params => { + mount: async (params) => { const { mountManagementSection } = await import('./application/mount_management_section'); return await mountManagementSection(coreSetup, params); diff --git a/x-pack/plugins/ingest_pipelines/server/plugin.ts b/x-pack/plugins/ingest_pipelines/server/plugin.ts index b27ca417c3e3c..8a2eb2f5dfb6a 100644 --- a/x-pack/plugins/ingest_pipelines/server/plugin.ts +++ b/x-pack/plugins/ingest_pipelines/server/plugin.ts @@ -25,7 +25,7 @@ export class IngestPipelinesPlugin implements Plugin { this.apiRoutes = new ApiRoutes(); } - public setup({ http, elasticsearch }: CoreSetup, { licensing }: Dependencies) { + public setup({ http }: CoreSetup, { licensing, security }: Dependencies) { this.logger.debug('ingest_pipelines: setup'); const router = http.createRouter(); @@ -47,6 +47,9 @@ export class IngestPipelinesPlugin implements Plugin { this.apiRoutes.setup({ router, license: this.license, + config: { + isSecurityEnabled: security !== undefined && security.license.isEnabled(), + }, lib: { isEsError, }, diff --git a/x-pack/plugins/ingest_pipelines/server/routes/api/delete.ts b/x-pack/plugins/ingest_pipelines/server/routes/api/delete.ts index 4664b49a08a50..8ef9387010eb6 100644 --- a/x-pack/plugins/ingest_pipelines/server/routes/api/delete.ts +++ b/x-pack/plugins/ingest_pipelines/server/routes/api/delete.ts @@ -31,10 +31,10 @@ export const registerDeleteRoute = ({ router, license }: RouteDependencies): voi }; await Promise.all( - pipelineNames.map(pipelineName => { + pipelineNames.map((pipelineName) => { return callAsCurrentUser('ingest.deletePipeline', { id: pipelineName }) .then(() => response.itemsDeleted.push(pipelineName)) - .catch(e => + .catch((e) => response.errors.push({ name: pipelineName, error: e, diff --git a/x-pack/plugins/ingest_pipelines/server/routes/api/privileges.ts b/x-pack/plugins/ingest_pipelines/server/routes/api/privileges.ts index 2e1c11928959f..b5c781fa9ad24 100644 --- a/x-pack/plugins/ingest_pipelines/server/routes/api/privileges.ts +++ b/x-pack/plugins/ingest_pipelines/server/routes/api/privileges.ts @@ -15,19 +15,13 @@ const extractMissingPrivileges = (privilegesObject: { [key: string]: boolean } = return privileges; }, []); -export const registerPrivilegesRoute = ({ license, router }: RouteDependencies) => { +export const registerPrivilegesRoute = ({ license, router, config }: RouteDependencies) => { router.get( { path: `${API_BASE_PATH}/privileges`, validate: false, }, license.guardApiRoute(async (ctx, req, res) => { - const { - core: { - elasticsearch: { dataClient }, - }, - } = ctx; - const privilegesResult: Privileges = { hasAllPrivileges: true, missingPrivileges: { @@ -35,6 +29,17 @@ export const registerPrivilegesRoute = ({ license, router }: RouteDependencies) }, }; + // Skip the privileges check if security is not enabled + if (!config.isSecurityEnabled) { + return res.ok({ body: privilegesResult }); + } + + const { + core: { + elasticsearch: { dataClient }, + }, + } = ctx; + try { const { has_all_requested: hasAllPrivileges, cluster } = await dataClient.callAsCurrentUser( 'transport.request', @@ -55,7 +60,7 @@ export const registerPrivilegesRoute = ({ license, router }: RouteDependencies) return res.ok({ body: privilegesResult }); } catch (e) { - return res.internalError(e); + return res.internalError({ body: e }); } }) ); diff --git a/x-pack/plugins/ingest_pipelines/server/services/license.ts b/x-pack/plugins/ingest_pipelines/server/services/license.ts index 0a4748bd0ace0..9b68acd073c4a 100644 --- a/x-pack/plugins/ingest_pipelines/server/services/license.ts +++ b/x-pack/plugins/ingest_pipelines/server/services/license.ts @@ -35,7 +35,7 @@ export class License { { pluginId, minimumLicenseType, defaultErrorMessage }: SetupSettings, { licensing, logger }: { licensing: LicensingPluginSetup; logger: Logger } ) { - licensing.license$.subscribe(license => { + licensing.license$.subscribe((license) => { const { state, message } = license.check(pluginId, minimumLicenseType); const hasRequiredLicense = state === 'valid'; diff --git a/x-pack/plugins/ingest_pipelines/server/types.ts b/x-pack/plugins/ingest_pipelines/server/types.ts index 0135ae8e2f07d..ba5c5da35cf81 100644 --- a/x-pack/plugins/ingest_pipelines/server/types.ts +++ b/x-pack/plugins/ingest_pipelines/server/types.ts @@ -6,16 +6,21 @@ import { IRouter } from 'src/core/server'; import { LicensingPluginSetup } from '../../licensing/server'; +import { SecurityPluginSetup } from '../../security/server'; import { License } from './services'; import { isEsError } from './lib'; export interface Dependencies { + security: SecurityPluginSetup; licensing: LicensingPluginSetup; } export interface RouteDependencies { router: IRouter; license: License; + config: { + isSecurityEnabled: boolean; + }; lib: { isEsError: typeof isEsError; }; diff --git a/x-pack/plugins/lens/public/app_plugin/app.test.tsx b/x-pack/plugins/lens/public/app_plugin/app.test.tsx index 0608c978ad0dc..1762965478292 100644 --- a/x-pack/plugins/lens/public/app_plugin/app.test.tsx +++ b/x-pack/plugins/lens/public/app_plugin/app.test.tsx @@ -133,8 +133,8 @@ describe('Lens App', () => { }, }, indexPatterns: { - get: jest.fn(id => { - return new Promise(resolve => resolve({ id })); + get: jest.fn((id) => { + return new Promise((resolve) => resolve({ id })); }), }, }, @@ -176,7 +176,7 @@ describe('Lens App', () => { core = coreMock.createStart({ basePath: '/testbasepath' }); core.uiSettings.get.mockImplementation( - jest.fn(type => { + jest.fn((type) => { if (type === 'timepicker:timeDefaults') { return { from: 'now-7d', to: 'now' }; } else if (type === 'search:queryLanguage') { @@ -391,7 +391,7 @@ describe('Lens App', () => { return (inst .find('[data-test-subj="lnsApp_topNav"]') .prop('config') as TopNavMenuData[]).find( - button => button.testId === 'lnsApp_saveButton' + (button) => button.testId === 'lnsApp_saveButton' )!; } diff --git a/x-pack/plugins/lens/public/app_plugin/app.tsx b/x-pack/plugins/lens/public/app_plugin/app.tsx index 718f49413a082..a77fbbb597564 100644 --- a/x-pack/plugins/lens/public/app_plugin/app.tsx +++ b/x-pack/plugins/lens/public/app_plugin/app.tsx @@ -101,7 +101,7 @@ export function App({ const filterSubscription = data.query.filterManager.getUpdates$().subscribe({ next: () => { - setState(s => ({ ...s, filters: data.query.filterManager.getFilters() })); + setState((s) => ({ ...s, filters: data.query.filterManager.getFilters() })); trackUiEvent('app_filters_updated'); }, }); @@ -109,7 +109,7 @@ export function App({ const timeSubscription = data.query.timefilter.timefilter.getTimeUpdate$().subscribe({ next: () => { const currentRange = data.query.timefilter.timefilter.getTime(); - setState(s => ({ + setState((s) => ({ ...s, dateRange: { fromDate: currentRange.from, @@ -130,7 +130,7 @@ export function App({ core.chrome.setBreadcrumbs([ { href: core.http.basePath.prepend(`/app/visualize#/`), - onClick: e => { + onClick: (e) => { core.application.navigateToApp('visualize', { path: '/' }); e.preventDefault(); }, @@ -148,19 +148,19 @@ export function App({ useEffect(() => { if (docId && (!state.persistedDoc || state.persistedDoc.id !== docId)) { - setState(s => ({ ...s, isLoading: true })); + setState((s) => ({ ...s, isLoading: true })); docStorage .load(docId) - .then(doc => { + .then((doc) => { getAllIndexPatterns( doc.state.datasourceMetaData.filterableIndexPatterns, data.indexPatterns, core.notifications ) - .then(indexPatterns => { + .then((indexPatterns) => { // Don't overwrite any pinned filters data.query.filterManager.setAppFilters(doc.state.filters); - setState(s => ({ + setState((s) => ({ ...s, isLoading: false, persistedDoc: doc, @@ -170,13 +170,13 @@ export function App({ })); }) .catch(() => { - setState(s => ({ ...s, isLoading: false })); + setState((s) => ({ ...s, isLoading: false })); redirectTo(); }); }) .catch(() => { - setState(s => ({ ...s, isLoading: false })); + setState((s) => ({ ...s, isLoading: false })); core.notifications.toasts.addDanger( i18n.translate('xpack.lens.app.docLoadingError', { @@ -229,7 +229,7 @@ export function App({ .then(({ id }) => { // Prevents unnecessary network request and disables save button const newDoc = { ...doc, id }; - setState(s => ({ + setState((s) => ({ ...s, isSaveModalVisible: false, persistedDoc: newDoc, @@ -239,7 +239,7 @@ export function App({ redirectTo(id, saveProps.returnToOrigin, state.originatingApp, newlyCreated); } }) - .catch(e => { + .catch((e) => { // eslint-disable-next-line no-console console.dir(e); trackUiEvent('save_failed'); @@ -248,7 +248,7 @@ export function App({ defaultMessage: 'Error saving document', }) ); - setState(s => ({ ...s, isSaveModalVisible: false })); + setState((s) => ({ ...s, isSaveModalVisible: false })); }); }; @@ -311,7 +311,7 @@ export function App({ emphasize: !state.originatingApp || !lastKnownDoc?.id, run: () => { if (isSaveable && lastKnownDoc) { - setState(s => ({ ...s, isSaveModalVisible: true })); + setState((s) => ({ ...s, isSaveModalVisible: true })); } }, testId: 'lnsApp_saveButton', @@ -320,7 +320,7 @@ export function App({ ]} data-test-subj="lnsApp_topNav" screenTitle={'lens'} - onQuerySubmit={payload => { + onQuerySubmit={(payload) => { const { dateRange, query } = payload; if ( @@ -333,7 +333,7 @@ export function App({ trackUiEvent('app_query_change'); } - setState(s => ({ + setState((s) => ({ ...s, dateRange: { fromDate: dateRange.from, @@ -350,14 +350,14 @@ export function App({ showFilterBar={true} showSaveQuery={core.application.capabilities.visualize.saveQuery as boolean} savedQuery={state.savedQuery} - onSaved={savedQuery => { - setState(s => ({ ...s, savedQuery })); + onSaved={(savedQuery) => { + setState((s) => ({ ...s, savedQuery })); }} - onSavedQueryUpdated={savedQuery => { + onSavedQueryUpdated={(savedQuery) => { const savedQueryFilters = savedQuery.attributes.filters || []; const globalFilters = data.query.filterManager.getGlobalFilters(); data.query.filterManager.setFilters([...globalFilters, ...savedQueryFilters]); - setState(s => ({ + setState((s) => ({ ...s, savedQuery: { ...savedQuery }, // Shallow query for reference issues dateRange: savedQuery.attributes.timefilter @@ -370,7 +370,7 @@ export function App({ }} onClearSavedQuery={() => { data.query.filterManager.setFilters(data.query.filterManager.getGlobalFilters()); - setState(s => ({ + setState((s) => ({ ...s, savedQuery: undefined, filters: data.query.filterManager.getGlobalFilters(), @@ -401,7 +401,7 @@ export function App({ onError, onChange: ({ filterableIndexPatterns, doc }) => { if (!_.isEqual(state.persistedDoc, doc)) { - setState(s => ({ ...s, lastKnownDoc: doc })); + setState((s) => ({ ...s, lastKnownDoc: doc })); } // Update the cached index patterns if the user made a change to any of them @@ -409,16 +409,16 @@ export function App({ state.indexPatternsForTopNav.length !== filterableIndexPatterns.length || filterableIndexPatterns.find( ({ id }) => - !state.indexPatternsForTopNav.find(indexPattern => indexPattern.id === id) + !state.indexPatternsForTopNav.find((indexPattern) => indexPattern.id === id) ) ) { getAllIndexPatterns( filterableIndexPatterns, data.indexPatterns, core.notifications - ).then(indexPatterns => { + ).then((indexPatterns) => { if (indexPatterns) { - setState(s => ({ ...s, indexPatternsForTopNav: indexPatterns })); + setState((s) => ({ ...s, indexPatternsForTopNav: indexPatterns })); } }); } @@ -430,8 +430,8 @@ export function App({ {lastKnownDoc && state.isSaveModalVisible && ( runSave(props)} - onClose={() => setState(s => ({ ...s, isSaveModalVisible: false }))} + onSave={(props) => runSave(props)} + onClose={() => setState((s) => ({ ...s, isSaveModalVisible: false }))} documentInfo={{ id: lastKnownDoc.id, title: lastKnownDoc.title || '', diff --git a/x-pack/plugins/lens/public/datatable_visualization/expression.test.tsx b/x-pack/plugins/lens/public/datatable_visualization/expression.test.tsx index ea8eeaee8b2f0..ac43593213687 100644 --- a/x-pack/plugins/lens/public/datatable_visualization/expression.test.tsx +++ b/x-pack/plugins/lens/public/datatable_visualization/expression.test.tsx @@ -66,7 +66,7 @@ describe('datatable_expression', () => { x as IFieldFormat} + formatFactory={(x) => x as IFieldFormat} onClickValue={onClickValue} getType={jest.fn()} /> @@ -87,16 +87,13 @@ describe('datatable_expression', () => { }, }} args={args} - formatFactory={x => x as IFieldFormat} + formatFactory={(x) => x as IFieldFormat} onClickValue={onClickValue} getType={jest.fn(() => ({ type: 'buckets' } as IAggType))} /> ); - wrapper - .find('[data-test-subj="lensDatatableFilterOut"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="lensDatatableFilterOut"]').first().simulate('click'); expect(onClickValue).toHaveBeenCalledWith({ data: [ @@ -125,16 +122,13 @@ describe('datatable_expression', () => { }, }} args={args} - formatFactory={x => x as IFieldFormat} + formatFactory={(x) => x as IFieldFormat} onClickValue={onClickValue} getType={jest.fn(() => ({ type: 'buckets' } as IAggType))} /> ); - wrapper - .find('[data-test-subj="lensDatatableFilterFor"]') - .at(3) - .simulate('click'); + wrapper.find('[data-test-subj="lensDatatableFilterFor"]').at(3).simulate('click'); expect(onClickValue).toHaveBeenCalledWith({ data: [ @@ -166,9 +160,9 @@ describe('datatable_expression', () => { x as IFieldFormat} + formatFactory={(x) => x as IFieldFormat} onClickValue={onClickValue} - getType={jest.fn(type => + getType={jest.fn((type) => type === 'count' ? ({ type: 'metrics' } as IAggType) : ({ type: 'buckets' } as IAggType) )} /> diff --git a/x-pack/plugins/lens/public/datatable_visualization/expression.tsx b/x-pack/plugins/lens/public/datatable_visualization/expression.tsx index d897290d5a13c..1fd01654d8149 100644 --- a/x-pack/plugins/lens/public/datatable_visualization/expression.tsx +++ b/x-pack/plugins/lens/public/datatable_visualization/expression.tsx @@ -156,7 +156,7 @@ export function DatatableComponent(props: DatatableRenderProps) { const [firstTable] = Object.values(props.data.tables); const formatters: Record> = {}; - firstTable.columns.forEach(column => { + firstTable.columns.forEach((column) => { formatters[column.id] = props.formatFactory(column.formatHint); }); @@ -166,7 +166,7 @@ export function DatatableComponent(props: DatatableRenderProps) { const isDateHistogram = col.meta?.type === 'date_histogram'; const timeFieldName = negate && isDateHistogram ? undefined : col?.meta?.aggConfigParams?.field; - const rowIndex = firstTable.rows.findIndex(row => row[field] === value); + const rowIndex = firstTable.rows.findIndex((row) => row[field] === value); const data: LensFilterEvent['data'] = { negate, @@ -186,15 +186,17 @@ export function DatatableComponent(props: DatatableRenderProps) { ); const bucketColumns = firstTable.columns - .filter(col => { + .filter((col) => { return col?.meta?.type && props.getType(col.meta.type)?.type === 'buckets'; }) - .map(col => col.id); + .map((col) => col.id); const isEmpty = firstTable.rows.length === 0 || (bucketColumns.length && - firstTable.rows.every(row => bucketColumns.every(col => typeof row[col] === 'undefined'))); + firstTable.rows.every((row) => + bucketColumns.every((col) => typeof row[col] === 'undefined') + )); if (isEmpty) { return ; @@ -207,10 +209,10 @@ export function DatatableComponent(props: DatatableRenderProps) { data-test-subj="lnsDataTable" tableLayout="auto" columns={props.args.columns.columnIds - .map(field => { - const col = firstTable.columns.find(c => c.id === field); + .map((field) => { + const col = firstTable.columns.find((c) => c.id === field); const filterable = bucketColumns.includes(field); - const colIndex = firstTable.columns.findIndex(c => c.id === field); + const colIndex = firstTable.columns.findIndex((c) => c.id === field); return { field, name: (col && col.name) || '', diff --git a/x-pack/plugins/lens/public/datatable_visualization/visualization.tsx b/x-pack/plugins/lens/public/datatable_visualization/visualization.tsx index ed0512ba220eb..e4b371143594a 100644 --- a/x-pack/plugins/lens/public/datatable_visualization/visualization.tsx +++ b/x-pack/plugins/lens/public/datatable_visualization/visualization.tsx @@ -46,12 +46,12 @@ export const datatableVisualization: Visualization< }, getLayerIds(state) { - return state.layers.map(l => l.layerId); + return state.layers.map((l) => l.layerId); }, clearLayer(state) { return { - layers: state.layers.map(l => newLayerState(l.layerId)), + layers: state.layers.map((l) => newLayerState(l.layerId)), }; }, @@ -74,7 +74,7 @@ export const datatableVisualization: Visualization< ); }, - getPersistableState: state => state, + getPersistableState: (state) => state, getSuggestions({ table, @@ -101,7 +101,7 @@ export const datatableVisualization: Visualization< operations: table.label || table.columns - .map(col => col.operation.label) + .map((col) => col.operation.label) .join( i18n.translate('xpack.lens.datatable.conjunctionSign', { defaultMessage: ' & ', @@ -121,7 +121,7 @@ export const datatableVisualization: Visualization< layers: [ { layerId: table.layerId, - columns: table.columns.map(col => col.columnId), + columns: table.columns.map((col) => col.columnId), }, ], }, @@ -133,7 +133,7 @@ export const datatableVisualization: Visualization< }, getConfiguration({ state, frame, layerId }) { - const layer = state.layers.find(l => l.layerId === layerId); + const layer = state.layers.find((l) => l.layerId === layerId); if (!layer) { return { groups: [] }; } @@ -163,7 +163,7 @@ export const datatableVisualization: Visualization< setDimension({ prevState, layerId, columnId }) { return { ...prevState, - layers: prevState.layers.map(l => { + layers: prevState.layers.map((l) => { if (l.layerId !== layerId || l.columns.includes(columnId)) { return l; } @@ -174,11 +174,11 @@ export const datatableVisualization: Visualization< removeDimension({ prevState, layerId, columnId }) { return { ...prevState, - layers: prevState.layers.map(l => + layers: prevState.layers.map((l) => l.layerId === layerId ? { ...l, - columns: l.columns.filter(c => c !== columnId), + columns: l.columns.filter((c) => c !== columnId), } : l ), @@ -189,7 +189,7 @@ export const datatableVisualization: Visualization< const layer = state.layers[0]; const datasource = frame.datasourceLayers[layer.layerId]; const operations = layer.columns - .map(columnId => ({ columnId, operation: datasource.getOperationForColumnId(columnId) })) + .map((columnId) => ({ columnId, operation: datasource.getOperationForColumnId(columnId) })) .filter((o): o is { columnId: string; operation: Operation } => !!o.operation); return { @@ -207,7 +207,7 @@ export const datatableVisualization: Visualization< type: 'function', function: 'lens_datatable_columns', arguments: { - columnIds: operations.map(o => o.columnId), + columnIds: operations.map((o) => o.columnId), }, }, ], diff --git a/x-pack/plugins/lens/public/debounced_component/debounced_component.test.tsx b/x-pack/plugins/lens/public/debounced_component/debounced_component.test.tsx index 447d9118c2930..929dd8e434afe 100644 --- a/x-pack/plugins/lens/public/debounced_component/debounced_component.test.tsx +++ b/x-pack/plugins/lens/public/debounced_component/debounced_component.test.tsx @@ -25,7 +25,7 @@ describe('debouncedComponent', () => { component.setProps({ title: 'yall' }); expect(component.text()).toEqual('there'); await act(async () => { - await new Promise(r => setTimeout(r, 1)); + await new Promise((r) => setTimeout(r, 1)); }); expect(component.text()).toEqual('yall'); }); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.test.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.test.tsx index 157a871e202f7..648bb5c03cb39 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.test.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.test.tsx @@ -22,7 +22,7 @@ describe('chart_switch', () => { return { ...createMockVisualization(), id, - getVisualizationTypeId: jest.fn(_state => id), + getVisualizationTypeId: jest.fn((_state) => id), visualizationTypes: [ { icon: 'empty', @@ -33,7 +33,7 @@ describe('chart_switch', () => { initialize: jest.fn((_frame, state?: unknown) => { return state || `${id} initial state`; }), - getSuggestions: jest.fn(options => { + getSuggestions: jest.fn((options) => { return [ { score: 1, @@ -70,8 +70,8 @@ describe('chart_switch', () => { label: 'C3', }, ], - getVisualizationTypeId: jest.fn(state => state.type), - getSuggestions: jest.fn(options => { + getVisualizationTypeId: jest.fn((state) => state.type), + getSuggestions: jest.fn((options) => { if (options.subVisualizationId === 'subvisC2') { return []; } @@ -144,18 +144,12 @@ describe('chart_switch', () => { } function showFlyout(component: ReactWrapper) { - component - .find('[data-test-subj="lnsChartSwitchPopover"]') - .first() - .simulate('click'); + component.find('[data-test-subj="lnsChartSwitchPopover"]').first().simulate('click'); } function switchTo(subType: string, component: ReactWrapper) { showFlyout(component); - component - .find(`[data-test-subj="lnsChartSwitchPopover_${subType}"]`) - .first() - .simulate('click'); + component.find(`[data-test-subj="lnsChartSwitchPopover_${subType}"]`).first().simulate('click'); } function getMenuItem(subType: string, component: ReactWrapper) { @@ -566,7 +560,7 @@ describe('chart_switch', () => { showFlyout(component); const allDisplayed = ['visA', 'visB', 'subvisC1', 'subvisC2', 'subvisC3'].every( - subType => component.find(`[data-test-subj="lnsChartSwitchPopover_${subType}"]`).length > 0 + (subType) => component.find(`[data-test-subj="lnsChartSwitchPopover_${subType}"]`).length > 0 ); expect(allDisplayed).toBeTruthy(); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.tsx index 81eb82dfdbab4..e212cb70d1855 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/chart_switch.tsx @@ -172,14 +172,14 @@ export function ChartSwitch(props: Props) { () => flyoutOpen && flatten( - Object.values(props.visualizationMap).map(v => - v.visualizationTypes.map(t => ({ + Object.values(props.visualizationMap).map((v) => + v.visualizationTypes.map((t) => ({ visualizationId: v.id, ...t, icon: t.largeIcon || t.icon, })) ) - ).map(visualizationType => ({ + ).map((visualizationType) => ({ ...visualizationType, selection: getSelection(visualizationType.visualizationId, visualizationType.id), })), @@ -223,7 +223,7 @@ export function ChartSwitch(props: Props) { })} - {(visualizationTypes || []).map(v => ( + {(visualizationTypes || []).map((v) => ( {v.label}} @@ -269,7 +269,7 @@ function getTopSuggestion( activeVisualizationId: props.visualizationId, visualizationState: props.visualizationState, subVisualizationId, - }).filter(suggestion => { + }).filter((suggestion) => { // don't use extended versions of current data table on switching between visualizations // to avoid confusing the user. return ( @@ -282,8 +282,8 @@ function getTopSuggestion( // charts since that allows you to switch from A to B and back // to A with the greatest chance of preserving your original state. return ( - suggestions.find(s => s.changeType === 'unchanged') || - suggestions.find(s => s.changeType === 'reduced') || + suggestions.find((s) => s.changeType === 'unchanged') || + suggestions.find((s) => s.changeType === 'reduced') || suggestions[0] ); } diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx index e5d3e93258c0a..0d86a051b0faa 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx @@ -79,7 +79,7 @@ function LayerPanels( props.dispatch({ type: 'UPDATE_STATE', subType: 'UPDATE_ALL_STATES', - updater: prevState => { + updater: (prevState) => { return { ...prevState, datasourceStates: { @@ -104,7 +104,7 @@ function LayerPanels( return ( - {layerIds.map(layerId => ( + {layerIds.map((layerId) => ( + updater: (state) => removeLayer({ activeVisualization, layerId, @@ -157,7 +157,7 @@ function LayerPanels( dispatch({ type: 'UPDATE_STATE', subType: 'ADD_LAYER', - updater: state => + updater: (state) => appendLayer({ activeVisualization, generateId, diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_popover.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_popover.tsx index 36db13b74ac4f..f89b6ef32d3f7 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_popover.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_popover.tsx @@ -26,7 +26,7 @@ export function DimensionPopover({ trigger: React.ReactElement; panel: React.ReactElement; }) { - const noMatch = popoverState.isOpen ? !groups.some(d => d.accessors.includes(accessor)) : false; + const noMatch = popoverState.isOpen ? !groups.some((d) => d.accessors.includes(accessor)) : false; return ( id === opts.layerId); + .every((id) => id === opts.layerId); trackUiEvent(isOnlyLayer ? 'layer_cleared' : 'layer_removed'); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx index 81476e8fa3708..814b7fc644c9c 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx @@ -81,7 +81,7 @@ export function LayerPanel( }; const { groups } = activeVisualization.getConfiguration(layerVisualizationConfigProps); - const isEmptyLayer = !groups.some(d => d.accessors.length > 0); + const isEmptyLayer = !groups.some((d) => d.accessors.length > 0); return ( @@ -120,9 +120,9 @@ export function LayerPanel( const removed = datasourcePublicAPI .getTableSpec() .map(({ columnId }) => columnId) - .filter(columnId => !nextTable.has(columnId)); + .filter((columnId) => !nextTable.has(columnId)); let nextVisState = props.visualizationState; - removed.forEach(columnId => { + removed.forEach((columnId) => { nextVisState = activeVisualization.removeDimension({ layerId, columnId, @@ -158,7 +158,7 @@ export function LayerPanel( } > <> - {group.accessors.map(accessor => ( + {group.accessors.map((accessor) => ( { + onDrop={(droppedItem) => { layerDatasource.onDrop({ ...layerDatasourceDropProps, droppedItem, @@ -268,7 +268,7 @@ export function LayerPanel( filterOperations: group.filterOperations, }) } - onDrop={droppedItem => { + onDrop={(droppedItem) => { const dropSuccess = layerDatasource.onDrop({ ...layerDatasourceDropProps, droppedItem, diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/data_panel_wrapper.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/data_panel_wrapper.tsx index cd0aee732793e..afb2719f28e89 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/data_panel_wrapper.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/data_panel_wrapper.tsx @@ -27,7 +27,7 @@ interface DataPanelWrapperProps { export const DataPanelWrapper = memo((props: DataPanelWrapperProps) => { const setDatasourceState: StateSetter = useMemo( - () => updater => { + () => (updater) => { props.dispatch({ type: 'UPDATE_DATASOURCE_STATE', updater, @@ -78,7 +78,7 @@ export const DataPanelWrapper = memo((props: DataPanelWrapperProps) => { title={i18n.translate('xpack.lens.dataPanelWrapper.switchDatasource', { defaultMessage: 'Switch to datasource', })} - items={Object.keys(props.datasourceMap).map(datasourceId => ( + items={Object.keys(props.datasourceMap).map((datasourceId) => ( { testDatasource: { ...mockDatasource, initialize: () => - new Promise(resolve => { + new Promise((resolve) => { databaseInitialized = resolve; }), }, @@ -474,9 +474,11 @@ describe('editor_frame', () => { it('should render individual expression for each given layer', async () => { mockDatasource.toExpression.mockReturnValue('datasource'); mockDatasource2.toExpression.mockImplementation((_state, layerId) => `datasource_${layerId}`); - mockDatasource.initialize.mockImplementation(initialState => Promise.resolve(initialState)); + mockDatasource.initialize.mockImplementation((initialState) => Promise.resolve(initialState)); mockDatasource.getLayers.mockReturnValue(['first']); - mockDatasource2.initialize.mockImplementation(initialState => Promise.resolve(initialState)); + mockDatasource2.initialize.mockImplementation((initialState) => + Promise.resolve(initialState) + ); mockDatasource2.getLayers.mockReturnValue(['second', 'third']); await act(async () => { @@ -772,9 +774,11 @@ describe('editor_frame', () => { }); it('should create a separate datasource public api for each layer', async () => { - mockDatasource.initialize.mockImplementation(initialState => Promise.resolve(initialState)); + mockDatasource.initialize.mockImplementation((initialState) => Promise.resolve(initialState)); mockDatasource.getLayers.mockReturnValue(['first']); - mockDatasource2.initialize.mockImplementation(initialState => Promise.resolve(initialState)); + mockDatasource2.initialize.mockImplementation((initialState) => + Promise.resolve(initialState) + ); mockDatasource2.getLayers.mockReturnValue(['second', 'third']); const datasource1State = { datasource1: '' }; @@ -872,10 +876,7 @@ describe('editor_frame', () => { function switchTo(subType: string) { act(() => { - instance - .find('[data-test-subj="lnsChartSwitchPopover"]') - .last() - .simulate('click'); + instance.find('[data-test-subj="lnsChartSwitchPopover"]').last().simulate('click'); }); instance.update(); @@ -1149,7 +1150,7 @@ describe('editor_frame', () => { instance .find('[data-test-subj="lnsSuggestion"]') .find(EuiPanel) - .map(el => el.parents(EuiToolTip).prop('content')) + .map((el) => el.parents(EuiToolTip).prop('content')) ).toEqual([ 'Current', 'Suggestion1', @@ -1200,10 +1201,7 @@ describe('editor_frame', () => { instance.update(); act(() => { - instance - .find('[data-test-subj="lnsSuggestion"]') - .at(2) - .simulate('click'); + instance.find('[data-test-subj="lnsSuggestion"]').at(2).simulate('click'); }); expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(1); @@ -1266,10 +1264,7 @@ describe('editor_frame', () => { instance.update(); act(() => { - instance - .find('[data-test-subj="lnsWorkspace"]') - .last() - .simulate('drop'); + instance.find('[data-test-subj="lnsWorkspace"]').last().simulate('drop'); }); expect(mockVisualization.getConfiguration).toHaveBeenCalledWith( @@ -1340,10 +1335,7 @@ describe('editor_frame', () => { instance.update(); act(() => { - instance - .find(DragDrop) - .filter('[data-test-subj="mockVisA"]') - .prop('onDrop')!({ + instance.find(DragDrop).filter('[data-test-subj="mockVisA"]').prop('onDrop')!({ indexPatternId: '1', field: {}, }); @@ -1439,10 +1431,7 @@ describe('editor_frame', () => { instance.update(); act(() => { - instance - .find(DragDrop) - .filter('[data-test-subj="lnsWorkspace"]') - .prop('onDrop')!({ + instance.find(DragDrop).filter('[data-test-subj="lnsWorkspace"]').prop('onDrop')!({ indexPatternId: '1', field: {}, }); @@ -1464,7 +1453,7 @@ describe('editor_frame', () => { const onChange = jest.fn(); mockDatasource.initialize.mockReturnValue( - new Promise(resolve => { + new Promise((resolve) => { resolver = resolve; }) ); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/editor_frame.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/editor_frame.tsx index 06d417ad18d54..90405b98afe65 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/editor_frame.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/editor_frame.tsx @@ -73,7 +73,7 @@ export function EditorFrame(props: EditorFrameProps) { ) { datasource .initialize(state.datasourceStates[datasourceId].state || undefined) - .then(datasourceState => { + .then((datasourceState) => { if (!isUnmounted) { dispatch({ type: 'UPDATE_DATASOURCE_STATE', @@ -93,13 +93,13 @@ export function EditorFrame(props: EditorFrameProps) { const datasourceLayers: Record = {}; Object.keys(props.datasourceMap) - .filter(id => state.datasourceStates[id] && !state.datasourceStates[id].isLoading) - .forEach(id => { + .filter((id) => state.datasourceStates[id] && !state.datasourceStates[id].isLoading) + .forEach((id) => { const datasourceState = state.datasourceStates[id].state; const datasource = props.datasourceMap[id]; const layers = datasource.getLayers(datasourceState); - layers.forEach(layer => { + layers.forEach((layer) => { datasourceLayers[layer] = props.datasourceMap[id].getPublicAPI({ state: datasourceState, layerId: layer, @@ -140,7 +140,7 @@ export function EditorFrame(props: EditorFrameProps) { }); } - layerIds.forEach(layerId => { + layerIds.forEach((layerId) => { const layerDatasourceId = Object.entries(props.datasourceMap).find( ([datasourceId, datasource]) => state.datasourceStates[datasourceId] && diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts index 9d4f8587577a3..ee28ccfe1bf53 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts @@ -25,7 +25,7 @@ export function prependDatasourceExpression( const state = datasourceStates[datasourceId].state; const layers = datasource.getLayers(datasourceStates[datasourceId].state); - layers.forEach(layerId => { + layers.forEach((layerId) => { const result = datasource.toExpression(state, layerId); if (result) { datasourceExpressions.push([layerId, result]); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/save.test.ts b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/save.test.ts index 9c7ed265f3539..d72e5c57ce56e 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/save.test.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/save.test.ts @@ -10,12 +10,12 @@ import { esFilters, IIndexPattern, IFieldType } from '../../../../../../src/plug describe('save editor frame state', () => { const mockVisualization = createMockVisualization(); - mockVisualization.getPersistableState.mockImplementation(x => x); + mockVisualization.getPersistableState.mockImplementation((x) => x); const mockDatasource = createMockDatasource('a'); const mockIndexPattern = ({ id: 'indexpattern' } as unknown) as IIndexPattern; const mockField = ({ name: '@timestamp' } as unknown) as IFieldType; - mockDatasource.getPersistableState.mockImplementation(x => x); + mockDatasource.getPersistableState.mockImplementation((x) => x); const saveArgs: Props = { activeDatasources: { indexpattern: mockDatasource, @@ -46,12 +46,12 @@ describe('save editor frame state', () => { it('transforms from internal state to persisted doc format', async () => { const datasource = createMockDatasource('a'); - datasource.getPersistableState.mockImplementation(state => ({ + datasource.getPersistableState.mockImplementation((state) => ({ stuff: `${state}_datasource_persisted`, })); const visualization = createMockVisualization(); - visualization.getPersistableState.mockImplementation(state => ({ + visualization.getPersistableState.mockImplementation((state) => ({ things: `${state}_vis_persisted`, })); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.ts b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.ts index 949ae1f43448e..263f7cd65f43d 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_helpers.ts @@ -73,7 +73,7 @@ export function getSuggestions({ return (field ? datasource.getDatasourceSuggestionsForField(datasourceState, field) : datasource.getDatasourceSuggestionsFromCurrentState(datasourceState) - ).map(suggestion => ({ ...suggestion, datasourceId })); + ).map((suggestion) => ({ ...suggestion, datasourceId })); }) ); @@ -82,7 +82,7 @@ export function getSuggestions({ return _.flatten( Object.entries(visualizationMap).map(([visualizationId, visualization]) => _.flatten( - datasourceTableSuggestions.map(datasourceSuggestion => { + datasourceTableSuggestions.map((datasourceSuggestion) => { const table = datasourceSuggestion.table; const currentVisualizationState = visualizationId === activeVisualizationId ? visualizationState : undefined; diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.test.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.test.tsx index 240bdff40b51c..6b0f0338d4015 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.test.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.test.tsx @@ -95,7 +95,7 @@ describe('suggestion_panel', () => { wrapper .find('[data-test-subj="lnsSuggestion"]') .find(EuiPanel) - .map(el => el.parents(EuiToolTip).prop('content')) + .map((el) => el.parents(EuiToolTip).prop('content')) ).toEqual(['Current', 'Suggestion1', 'Suggestion2']); }); @@ -157,39 +157,27 @@ describe('suggestion_panel', () => { const wrapper = mount(); act(() => { - wrapper - .find('[data-test-subj="lnsSuggestion"]') - .at(2) - .simulate('click'); + wrapper.find('[data-test-subj="lnsSuggestion"]').at(2).simulate('click'); }); wrapper.update(); - expect( - wrapper - .find('[data-test-subj="lnsSuggestion"]') - .at(2) - .prop('className') - ).toContain('lnsSuggestionPanel__button-isSelected'); + expect(wrapper.find('[data-test-subj="lnsSuggestion"]').at(2).prop('className')).toContain( + 'lnsSuggestionPanel__button-isSelected' + ); }); it('should rollback suggestion if current panel is clicked', () => { const wrapper = mount(); act(() => { - wrapper - .find('[data-test-subj="lnsSuggestion"]') - .at(2) - .simulate('click'); + wrapper.find('[data-test-subj="lnsSuggestion"]').at(2).simulate('click'); }); wrapper.update(); act(() => { - wrapper - .find('[data-test-subj="lnsSuggestion"]') - .at(0) - .simulate('click'); + wrapper.find('[data-test-subj="lnsSuggestion"]').at(0).simulate('click'); }); wrapper.update(); @@ -204,10 +192,7 @@ describe('suggestion_panel', () => { const wrapper = mount(); act(() => { - wrapper - .find('button[data-test-subj="lnsSuggestion"]') - .at(1) - .simulate('click'); + wrapper.find('button[data-test-subj="lnsSuggestion"]').at(1).simulate('click'); }); wrapper.update(); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.tsx index 867214d15578a..0f0885d696ba4 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/suggestion_panel.tsx @@ -171,7 +171,7 @@ export function SuggestionPanel({ activeVisualizationId: currentVisualizationId, visualizationState: currentVisualizationState, }) - .map(suggestion => ({ + .map((suggestion) => ({ ...suggestion, previewExpression: preparePreviewExpression( suggestion, @@ -181,7 +181,7 @@ export function SuggestionPanel({ frame ), })) - .filter(suggestion => !suggestion.hide) + .filter((suggestion) => !suggestion.hide) .slice(0, MAX_SUGGESTIONS_DISPLAYED); const newStateExpression = @@ -368,7 +368,7 @@ function getPreviewExpression( visualizableState.keptLayerIds ); const changedLayers = datasource.getLayers(visualizableState.datasourceState); - changedLayers.forEach(layerId => { + changedLayers.forEach((layerId) => { if (updatedLayerApis[layerId]) { updatedLayerApis[layerId] = datasource.getPublicAPI({ layerId, diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.test.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.test.tsx index a20626ebaaad7..59b5f358e190f 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.test.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.test.tsx @@ -348,7 +348,7 @@ describe('workspace_panel', () => { .mockReturnValueOnce('datasource') .mockReturnValueOnce('datasource second'); - expressionRendererMock = jest.fn(_arg => ); + expressionRendererMock = jest.fn((_arg) => ); await act(async () => { instance = mount( @@ -404,7 +404,7 @@ describe('workspace_panel', () => { .mockReturnValueOnce('datasource') .mockReturnValueOnce('datasource second'); - expressionRendererMock = jest.fn(_arg => ); + expressionRendererMock = jest.fn((_arg) => ); await act(async () => { instance = mount( { expect(expressionRendererMock).toHaveBeenCalledTimes(1); - expressionRendererMock.mockImplementation(_ => { + expressionRendererMock.mockImplementation((_) => { return ; }); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.tsx index b000fc7fa0176..44dd9f8364870 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel.tsx @@ -86,7 +86,7 @@ export function InnerWorkspacePanel({ } const hasData = Object.values(framePublicAPI.datasourceLayers).some( - datasource => datasource.getTableSpec().length > 0 + (datasource) => datasource.getTableSpec().length > 0 ); const suggestions = getSuggestions({ @@ -101,7 +101,7 @@ export function InnerWorkspacePanel({ field: dragDropContext.dragging, }); - return suggestions.find(s => s.visualizationId === activeVisualizationId) || suggestions[0]; + return suggestions.find((s) => s.visualizationId === activeVisualizationId) || suggestions[0]; }, [dragDropContext.dragging]); const [localState, setLocalState] = useState({ @@ -123,7 +123,7 @@ export function InnerWorkspacePanel({ }); } catch (e) { // Most likely an error in the expression provided by a datasource or visualization - setLocalState(s => ({ ...s, expressionBuildError: e.toString() })); + setLocalState((s) => ({ ...s, expressionBuildError: e.toString() })); } }, [ activeVisualization, @@ -138,7 +138,7 @@ export function InnerWorkspacePanel({ useEffect(() => { // reset expression error if component attempts to run it again if (expression && localState.expressionBuildError) { - setLocalState(s => ({ + setLocalState((s) => ({ ...s, expressionBuildError: undefined, })); @@ -256,7 +256,7 @@ export function InnerWorkspacePanel({ { - setLocalState(prevState => ({ + setLocalState((prevState) => ({ ...prevState, expandError: !prevState.expandError, })); diff --git a/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.test.tsx b/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.test.tsx index 4e5b32ad7f7a3..69447b3b9a9b8 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.test.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.test.tsx @@ -40,7 +40,7 @@ describe('embeddable', () => { beforeEach(() => { mountpoint = document.createElement('div'); - expressionRenderer = jest.fn(_props => null); + expressionRenderer = jest.fn((_props) => null); trigger = { exec: jest.fn() }; getTrigger = jest.fn(() => trigger); }); diff --git a/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.tsx b/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.tsx index 796cf5b32e3ba..bbd2b18907e9b 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.tsx @@ -96,7 +96,7 @@ export class Embeddable extends AbstractEmbeddable this.onContainerStateChanged(input)); + this.subscription = this.getInput$().subscribe((input) => this.onContainerStateChanged(input)); this.onContainerStateChanged(initialInput); this.autoRefreshFetchSubscription = timefilter @@ -119,7 +119,7 @@ export class Embeddable extends AbstractEmbeddable !filter.meta.disabled) + ? containerState.filters.filter((filter) => !filter.meta.disabled) : undefined; if ( !_.isEqual(containerState.timeRange, this.currentContext.timeRange) || diff --git a/x-pack/plugins/lens/public/editor_frame_service/embeddable/expression_wrapper.tsx b/x-pack/plugins/lens/public/editor_frame_service/embeddable/expression_wrapper.tsx index 41706121830cb..296dcef3e70b9 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/embeddable/expression_wrapper.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/embeddable/expression_wrapper.tsx @@ -55,7 +55,7 @@ export function ExpressionWrapper({ padding="m" expression={expression} searchContext={{ ...context }} - renderError={error =>
          {error}
          } + renderError={(error) =>
          {error}
          } onEvent={handleEvent} />
          diff --git a/x-pack/plugins/lens/public/editor_frame_service/format_column.ts b/x-pack/plugins/lens/public/editor_frame_service/format_column.ts index dfb725fef49bb..b95139a00ec57 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/format_column.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/format_column.ts @@ -68,7 +68,7 @@ export const formatColumn: ExpressionFunctionDefinition< fn(input, { format, columnId, decimals }: FormatColumn) { return { ...input, - columns: input.columns.map(col => { + columns: input.columns.map((col) => { if (col.id === columnId) { if (supportedFormats[format]) { return { diff --git a/x-pack/plugins/lens/public/editor_frame_service/merge_tables.test.ts b/x-pack/plugins/lens/public/editor_frame_service/merge_tables.test.ts index 243441f2c8ab3..b3da722de5f34 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/merge_tables.test.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/merge_tables.test.ts @@ -87,24 +87,8 @@ describe('lens_merge_tables', () => { {} as any ); - expect( - moment - .duration( - moment() - .startOf('week') - .diff(dateRange!.fromDate) - ) - .asDays() - ).toEqual(0); + expect(moment.duration(moment().startOf('week').diff(dateRange!.fromDate)).asDays()).toEqual(0); - expect( - moment - .duration( - moment() - .endOf('week') - .diff(dateRange!.toDate) - ) - .asDays() - ).toEqual(0); + expect(moment.duration(moment().endOf('week').diff(dateRange!.toDate)).asDays()).toEqual(0); }); }); diff --git a/x-pack/plugins/lens/public/editor_frame_service/mocks.tsx b/x-pack/plugins/lens/public/editor_frame_service/mocks.tsx index e684fe8b3b5d6..9c0825b3c2d27 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/mocks.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/mocks.tsx @@ -20,7 +20,7 @@ export function createMockVisualization(): jest.Mocked { return { id: 'TEST_VIS', clearLayer: jest.fn((state, _layerId) => state), - getLayerIds: jest.fn(_state => ['layer1']), + getLayerIds: jest.fn((_state) => ['layer1']), visualizationTypes: [ { icon: 'empty', @@ -28,13 +28,13 @@ export function createMockVisualization(): jest.Mocked { label: 'TEST', }, ], - getVisualizationTypeId: jest.fn(_state => 'empty'), - getDescription: jest.fn(_state => ({ label: '' })), + getVisualizationTypeId: jest.fn((_state) => 'empty'), + getDescription: jest.fn((_state) => ({ label: '' })), switchVisualizationType: jest.fn((_, x) => x), - getPersistableState: jest.fn(_state => _state), - getSuggestions: jest.fn(_options => []), + getPersistableState: jest.fn((_state) => _state), + getSuggestions: jest.fn((_options) => []), initialize: jest.fn((_frame, _state?) => ({})), - getConfiguration: jest.fn(props => ({ + getConfiguration: jest.fn((props) => ({ groups: [ { groupId: 'a', @@ -70,7 +70,7 @@ export function createMockDatasource(id: string): DatasourceMock { id: 'mockindexpattern', clearLayer: jest.fn((state, _layerId) => state), getDatasourceSuggestionsForField: jest.fn((_state, _item) => []), - getDatasourceSuggestionsFromCurrentState: jest.fn(_state => []), + getDatasourceSuggestionsFromCurrentState: jest.fn((_state) => []), getPersistableState: jest.fn(), getPublicAPI: jest.fn().mockReturnValue(publicAPIMock), initialize: jest.fn((_state?) => Promise.resolve()), @@ -79,9 +79,9 @@ export function createMockDatasource(id: string): DatasourceMock { toExpression: jest.fn((_frame, _state) => null), insertLayer: jest.fn((_state, _newLayerId) => {}), removeLayer: jest.fn((_state, _layerId) => {}), - removeColumn: jest.fn(props => {}), - getLayers: jest.fn(_state => []), - getMetaData: jest.fn(_state => ({ filterableIndexPatterns: [] })), + removeColumn: jest.fn((props) => {}), + getLayers: jest.fn((_state) => []), + getMetaData: jest.fn((_state) => ({ filterableIndexPatterns: [] })), renderDimensionTrigger: jest.fn(), renderDimensionEditor: jest.fn(), @@ -121,7 +121,7 @@ export function createExpressionRendererMock(): jest.Mock< React.ReactElement, [ReactExpressionRendererProps] > { - return jest.fn(_ => ); + return jest.fn((_) => ); } export function createMockSetupDependencies() { diff --git a/x-pack/plugins/lens/public/editor_frame_service/service.tsx b/x-pack/plugins/lens/public/editor_frame_service/service.tsx index a815e70c58629..f57acf3bef62d 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/service.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/service.tsx @@ -46,7 +46,7 @@ async function collectAsyncDefinitions( ) { const resolvedDefinitions = await Promise.all(definitions); const definitionMap: Record = {}; - resolvedDefinitions.forEach(definition => { + resolvedDefinitions.forEach((definition) => { definitionMap[definition.id] = definition; }); @@ -84,10 +84,10 @@ export class EditorFrameService { } return { - registerDatasource: datasource => { + registerDatasource: (datasource) => { this.datasources.push(datasource as Datasource); }, - registerVisualization: visualization => { + registerVisualization: (visualization) => { this.visualizations.push(visualization as Visualization); }, }; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/change_indexpattern.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/change_indexpattern.tsx index 99cc22cc6e890..851a9f4653fec 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/change_indexpattern.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/change_indexpattern.tsx @@ -38,7 +38,7 @@ export function ChangeIndexPattern({ }) { const [isPopoverOpen, setPopoverIsOpen] = useState(false); - const createTrigger = function() { + const createTrigger = function () { const { label, title, ...rest } = trigger; return ( { + onChange={(choices) => { const choice = (choices.find(({ checked }) => checked) as unknown) as { value: string; }; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.test.tsx index 5e3b32f6961e6..187ccb8c47563 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.test.tsx @@ -284,13 +284,13 @@ describe('IndexPattern Data Panel', () => { describe('loading existence data', () => { function testProps() { const setState = jest.fn(); - core.http.post.mockImplementation(async path => { + core.http.post.mockImplementation(async (path) => { const parts = ((path as unknown) as string).split('/'); const indexPatternTitle = parts[parts.length - 1]; return { indexPatternTitle: `${indexPatternTitle}_testtitle`, existingFieldNames: ['field_1', 'field_2'].map( - fieldName => `${indexPatternTitle}_${fieldName}` + (fieldName) => `${indexPatternTitle}_${fieldName}` ), }; }); @@ -489,7 +489,7 @@ describe('IndexPattern Data Panel', () => { let overlapCount = 0; const props = testProps(); - core.http.post.mockImplementation(path => { + core.http.post.mockImplementation((path) => { if (queryCount) { ++overlapCount; } @@ -500,7 +500,7 @@ describe('IndexPattern Data Panel', () => { const result = Promise.resolve({ indexPatternTitle, existingFieldNames: ['field_1', 'field_2'].map( - fieldName => `${indexPatternTitle}_${fieldName}` + (fieldName) => `${indexPatternTitle}_${fieldName}` ), }); @@ -540,7 +540,7 @@ describe('IndexPattern Data Panel', () => { ); - expect(wrapper.find(FieldItem).map(fieldItem => fieldItem.prop('field').name)).toEqual([ + expect(wrapper.find(FieldItem).map((fieldItem) => fieldItem.prop('field').name)).toEqual([ 'Records', 'bytes', 'client', @@ -561,7 +561,7 @@ describe('IndexPattern Data Panel', () => { } as ChangeEvent); }); - expect(wrapper.find(FieldItem).map(fieldItem => fieldItem.prop('field').name)).toEqual([ + expect(wrapper.find(FieldItem).map((fieldItem) => fieldItem.prop('field').name)).toEqual([ 'memory', ]); }); @@ -571,17 +571,11 @@ describe('IndexPattern Data Panel', () => { ); - wrapper - .find('[data-test-subj="lnsIndexPatternFiltersToggle"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="lnsIndexPatternFiltersToggle"]').first().simulate('click'); - wrapper - .find('[data-test-subj="typeFilter-number"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="typeFilter-number"]').first().simulate('click'); - expect(wrapper.find(FieldItem).map(fieldItem => fieldItem.prop('field').name)).toEqual([ + expect(wrapper.find(FieldItem).map((fieldItem) => fieldItem.prop('field').name)).toEqual([ 'bytes', 'memory', ]); @@ -592,21 +586,12 @@ describe('IndexPattern Data Panel', () => { ); - wrapper - .find('[data-test-subj="lnsIndexPatternFiltersToggle"]') - .first() - .simulate('click'); - - wrapper - .find('[data-test-subj="typeFilter-number"]') - .first() - .simulate('click'); - wrapper - .find('[data-test-subj="typeFilter-number"]') - .first() - .simulate('click'); - - expect(wrapper.find(FieldItem).map(fieldItem => fieldItem.prop('field').name)).toEqual([ + wrapper.find('[data-test-subj="lnsIndexPatternFiltersToggle"]').first().simulate('click'); + + wrapper.find('[data-test-subj="typeFilter-number"]').first().simulate('click'); + wrapper.find('[data-test-subj="typeFilter-number"]').first().simulate('click'); + + expect(wrapper.find(FieldItem).map((fieldItem) => fieldItem.prop('field').name)).toEqual([ 'Records', 'bytes', 'client', @@ -627,17 +612,11 @@ describe('IndexPattern Data Panel', () => { } as ChangeEvent); }); - wrapper - .find('[data-test-subj="lnsIndexPatternFiltersToggle"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="lnsIndexPatternFiltersToggle"]').first().simulate('click'); - wrapper - .find('[data-test-subj="typeFilter-number"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="typeFilter-number"]').first().simulate('click'); - expect(wrapper.find(FieldItem).map(fieldItem => fieldItem.prop('field').name)).toEqual([ + expect(wrapper.find(FieldItem).map((fieldItem) => fieldItem.prop('field').name)).toEqual([ 'memory', ]); }); @@ -653,7 +632,7 @@ describe('IndexPattern Data Panel', () => { ...defaultProps.indexPatterns, '1': { ...defaultProps.indexPatterns['1'], - fields: defaultProps.indexPatterns['1'].fields.map(field => ({ + fields: defaultProps.indexPatterns['1'].fields.map((field) => ({ ...field, exists: field.type === 'number', })), @@ -675,7 +654,7 @@ describe('IndexPattern Data Panel', () => { }; const wrapper = shallowWithIntl(); - expect(wrapper.find(FieldItem).map(fieldItem => fieldItem.prop('field').name)).toEqual([ + expect(wrapper.find(FieldItem).map((fieldItem) => fieldItem.prop('field').name)).toEqual([ 'Records', 'bytes', 'memory', @@ -693,7 +672,7 @@ describe('IndexPattern Data Panel', () => { } as ChangeEvent); }); - expect(wrapper.find(FieldItem).map(fieldItem => fieldItem.prop('field').name)).toEqual([ + expect(wrapper.find(FieldItem).map((fieldItem) => fieldItem.prop('field').name)).toEqual([ 'memory', ]); }); @@ -701,15 +680,11 @@ describe('IndexPattern Data Panel', () => { it('should allow removing the filter for data', () => { const wrapper = mountWithIntl(); - wrapper - .find('[data-test-subj="lnsIndexPatternFiltersToggle"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="lnsIndexPatternFiltersToggle"]').first().simulate('click'); - wrapper - .find('[data-test-subj="lnsEmptyFilter"]') - .first() - .prop('onChange')!({} as ChangeEvent); + wrapper.find('[data-test-subj="lnsEmptyFilter"]').first().prop('onChange')!( + {} as ChangeEvent + ); expect(emptyFieldsTestProps.onToggleEmptyFields).toHaveBeenCalled(); }); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx index b013f2b9d22a6..ae5632ddae84e 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx @@ -95,7 +95,7 @@ export function IndexPatternDataPanel({ const onToggleEmptyFields = useCallback( (showEmptyFields?: boolean) => { - setState(prevState => ({ + setState((prevState) => ({ ...prevState, showEmptyFields: showEmptyFields === undefined ? !prevState.showEmptyFields : showEmptyFields, @@ -106,12 +106,12 @@ export function IndexPatternDataPanel({ const indexPatternList = uniq( Object.values(state.layers) - .map(l => l.indexPatternId) + .map((l) => l.indexPatternId) .concat(currentIndexPatternId) ) .sort((a, b) => a.localeCompare(b)) - .filter(id => !!indexPatterns[id]) - .map(id => ({ + .filter((id) => !!indexPatterns[id]) + .map((id) => ({ id, title: indexPatterns[id].title, timeFieldName: indexPatterns[id].timeFieldName, @@ -141,7 +141,7 @@ export function IndexPatternDataPanel({ filters, dateRange.fromDate, dateRange.toDate, - indexPatternList.map(x => `${x.title}:${x.timeFieldName}`).join(','), + indexPatternList.map((x) => `${x.title}:${x.timeFieldName}`).join(','), ]} /> @@ -232,7 +232,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ const currentIndexPattern = indexPatterns[currentIndexPatternId]; const allFields = currentIndexPattern.fields; const fieldByName = indexBy(allFields, 'name'); - const clearLocalState = () => setLocalState(s => ({ ...s, nameFilter: '', typeFilter: [] })); + const clearLocalState = () => setLocalState((s) => ({ ...s, nameFilter: '', typeFilter: [] })); const lazyScroll = () => { if (scrollContainer) { @@ -255,10 +255,10 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ }, [localState.nameFilter, localState.typeFilter, currentIndexPatternId, showEmptyFields]); const availableFieldTypes = uniq(allFields.map(({ type }) => type)).filter( - type => type in fieldTypeNames + (type) => type in fieldTypeNames ); - const displayedFields = allFields.filter(field => { + const displayedFields = allFields.filter((field) => { if (!supportedFieldTypes.has(field.type)) { return false; } @@ -289,9 +289,9 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ return true; }); - const specialFields = displayedFields.filter(f => f.type === 'document'); + const specialFields = displayedFields.filter((f) => f.type === 'document'); const paginatedFields = displayedFields - .filter(f => f.type !== 'document') + .filter((f) => f.type !== 'document') .sort(sortFields) .slice(0, pageSize); const hilight = localState.nameFilter.toLowerCase(); @@ -354,7 +354,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ 'Search the list of fields in the index pattern for the provided text', })} value={localState.nameFilter} - onChange={e => { + onChange={(e) => { setLocalState({ ...localState, nameFilter: e.target.value }); }} aria-label={i18n.translate('xpack.lens.indexPatterns.filterByNameAriaLabel', { @@ -380,7 +380,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ icon={} isSelected={localState.typeFilter.length ? true : false} onClick={() => { - setLocalState(s => ({ + setLocalState((s) => ({ ...s, isTypeFilterOpen: !localState.isTypeFilterOpen, })); @@ -394,7 +394,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ ( + items={(availableFieldTypes as DataType[]).map((type) => ( { trackUiEvent('indexpattern_type_filter_toggled'); - setLocalState(s => ({ + setLocalState((s) => ({ ...s, typeFilter: localState.typeFilter.includes(type) - ? localState.typeFilter.filter(t => t !== type) + ? localState.typeFilter.filter((t) => t !== type) : [...localState.typeFilter, type], })); }} @@ -434,7 +434,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({
{ + ref={(el) => { if (el && !el.dataset.dynamicScroll) { el.dataset.dynamicScroll = 'true'; setScrollContainer(el); @@ -443,7 +443,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ onScroll={lazyScroll} >
- {specialFields.map(field => ( + {specialFields.map((field) => ( )} - {paginatedFields.map(field => { + {paginatedFields.map((field) => { const overallField = fieldByName[field.name]; return ( c !== inner); + const result = columnOrder.filter((c) => c !== inner); const outerPosition = result.indexOf(outer); result.splice(outerPosition + 1, 0, inner); @@ -130,7 +130,7 @@ export function BucketNestingEditor({ ...aggColumns.map(({ value, text }) => ({ value, text })), ]} value={prevColumn} - onChange={e => setColumns(nestColumn(layer.columnOrder, e.target.value, columnId))} + onChange={(e) => setColumns(nestColumn(layer.columnOrder, e.target.value, columnId))} /> diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.test.tsx index 9df79aa9e0908..a9e9efa8d1039 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.test.tsx @@ -751,7 +751,7 @@ describe('IndexPatternDimensionEditorPanel', () => { indexPatterns: { 1: { ...state.indexPatterns['1'], - fields: state.indexPatterns['1'].fields.filter(field => field.name !== 'memory'), + fields: state.indexPatterns['1'].fields.filter((field) => field.name !== 'memory'), }, }, }; @@ -865,7 +865,7 @@ describe('IndexPatternDimensionEditorPanel', () => { expect(options![0]['data-test-subj']).not.toContain('Incompatible'); - options![1].options!.map(operation => + options![1].options!.map((operation) => expect(operation['data-test-subj']).toContain('Incompatible') ); }); @@ -950,10 +950,9 @@ describe('IndexPatternDimensionEditorPanel', () => { ); act(() => { - wrapper - .find('[data-test-subj="lns-indexPatternDimension-min"]') - .first() - .prop('onClick')!({} as React.MouseEvent<{}, MouseEvent>); + wrapper.find('[data-test-subj="lns-indexPatternDimension-min"]').first().prop('onClick')!( + {} as React.MouseEvent<{}, MouseEvent> + ); }); expect(changeColumn).toHaveBeenCalledWith({ diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx index 583832aafcbe8..1e8f73b19a3b0 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx @@ -63,13 +63,13 @@ const getOperationFieldSupportMatrix = (props: Props): OperationFieldSupportMatr const filteredOperationsByMetadata = getAvailableOperationsByMetadata( currentIndexPattern - ).filter(operation => props.filterOperations(operation.operationMetaData)); + ).filter((operation) => props.filterOperations(operation.operationMetaData)); const supportedOperationsByField: Partial> = {}; const supportedFieldsByOperation: Partial> = {}; filteredOperationsByMetadata.forEach(({ operations }) => { - operations.forEach(operation => { + operations.forEach((operation) => { if (supportedOperationsByField[operation.field]) { supportedOperationsByField[operation.field]!.push(operation.operationType); } else { diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/field_select.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/field_select.tsx index 8651751ea365b..6544d70311511 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/field_select.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/field_select.tsx @@ -65,12 +65,12 @@ export function FieldSelect({ const [specialFields, normalFields] = _.partition( fields, - field => fieldMap[field].type === 'document' + (field) => fieldMap[field].type === 'document' ); function fieldNamesToOptions(items: string[]) { return items - .map(field => ({ + .map((field) => ({ label: field, value: { type: 'field', @@ -86,7 +86,7 @@ export function FieldSelect({ fieldExists(existingFields, currentIndexPattern.title, field), compatible: isCompatibleWithCurrentOperation(field), })) - .filter(field => showEmptyFields || field.exists) + .filter((field) => showEmptyFields || field.exists) .sort((a, b) => { if (a.compatible && !b.compatible) { return -1; @@ -153,7 +153,7 @@ export function FieldSelect({ : []) as unknown) as EuiComboBoxOptionOption[] } singleSelection={{ asPlainText: true }} - onChange={choices => { + onChange={(choices) => { if (choices.length === 0) { onDeleteColumn(); return; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/format_selector.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/format_selector.tsx index ed68a93c51ca2..b3b0190b9c400 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/format_selector.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/format_selector.tsx @@ -88,7 +88,7 @@ export function FormatSelector(props: FormatSelectorProps) { ] : [defaultOption] } - onChange={choices => { + onChange={(choices) => { if (choices.length === 0) { return; } @@ -117,7 +117,7 @@ export function FormatSelector(props: FormatSelectorProps) { value={state.decimalPlaces} min={0} max={20} - onChange={e => { + onChange={(e) => { setState({ decimalPlaces: Number(e.target.value) }); onChange({ id: (selectedColumn.params as { format: { id: string } }).format.id, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.tsx index e26c338b6e240..6bd4263014b13 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.tsx @@ -48,7 +48,7 @@ function asOperationOptions(operationTypes: OperationType[], compatibleWithCurre operationPanels[opType2].displayName ); }) - .map(operationType => ({ + .map((operationType) => ({ operationType, compatibleWithCurrentField, })); @@ -76,7 +76,7 @@ export function PopoverEditor(props: PopoverEditorProps) { const fieldMap: Record = useMemo(() => { const fields: Record = {}; - currentIndexPattern.fields.forEach(field => { + currentIndexPattern.fields.forEach((field) => { fields[field.name] = field; }); return fields; @@ -205,7 +205,7 @@ export function PopoverEditor(props: PopoverEditorProps) { }) ); }} - onChoose={choice => { + onChoose={(choice) => { let column: IndexPatternColumn; if ( !incompatibleSelectedOperationType && @@ -313,7 +313,7 @@ export function PopoverEditor(props: PopoverEditorProps) { compressed data-test-subj="indexPattern-label-edit" value={selectedColumn.label} - onChange={e => { + onChange={(e) => { setState( changeColumn({ state, @@ -334,7 +334,7 @@ export function PopoverEditor(props: PopoverEditorProps) { { + setColumns={(columnOrder) => { setState({ ...state, layers: { @@ -352,7 +352,7 @@ export function PopoverEditor(props: PopoverEditorProps) { {selectedColumn && selectedColumn.dataType === 'number' ? ( { + onChange={(newFormat) => { setState( updateColumnParam({ state, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/field_item.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/field_item.test.tsx index 6a4a2bd2ba77b..511ba3c0442c7 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/field_item.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/field_item.test.tsx @@ -114,7 +114,7 @@ describe('IndexPattern Field Item', () => { let resolveFunction: (arg: unknown) => void; core.http.post.mockImplementation(() => { - return new Promise(resolve => { + return new Promise((resolve) => { resolveFunction = resolve; }); }); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx index 5f0fa95ad0022..81eb53cd10002 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx @@ -125,7 +125,7 @@ export function FieldItem(props: FieldItemProps) { return; } - setState(s => ({ ...s, isLoading: true })); + setState((s) => ({ ...s, isLoading: true })); core.http .post(`/api/lens/index_stats/${indexPattern.title}/field`, { @@ -143,7 +143,7 @@ export function FieldItem(props: FieldItemProps) { }), }) .then((results: FieldStatsResponse) => { - setState(s => ({ + setState((s) => ({ ...s, isLoading: false, totalDocuments: results.totalDocuments, @@ -154,7 +154,7 @@ export function FieldItem(props: FieldItemProps) { })); }) .catch(() => { - setState(s => ({ ...s, isLoading: false })); + setState((s) => ({ ...s, isLoading: false })); }); } @@ -193,7 +193,7 @@ export function FieldItem(props: FieldItemProps) { onClick={() => { togglePopover(); }} - onKeyPress={event => { + onKeyPress={(event) => { if (event.key === 'ENTER') { togglePopover(); } @@ -331,7 +331,7 @@ function FieldItemPopoverContents(props: State & FieldItemProps) { id: 'histogram', }, ]} - onChange={optionId => { + onChange={(optionId) => { setShowingHistogram(optionId === 'histogram'); }} idSelected={showingHistogram ? 'histogram' : 'topValues'} @@ -444,7 +444,7 @@ function FieldItemPopoverContents(props: State & FieldItemProps) { id="key" position={Position.Left} showOverlappingTicks={true} - tickFormat={d => formatter.convert(d)} + tickFormat={(d) => formatter.convert(d)} /> - {props.topValues.buckets.map(topValue => { + {props.topValues.buckets.map((topValue) => { const formatted = formatter.convert(topValue.key); return (
diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx index b8f0460f2a9ab..c94dd621b9d19 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern.tsx @@ -86,7 +86,7 @@ export function uniqueLabels(layers: Record) { return uniqueLabel; }; - Object.values(layers).forEach(layer => { + Object.values(layers).forEach((layer) => { if (!layer.columns) { return; } @@ -180,8 +180,8 @@ export function getIndexPatternDatasource({ return { filterableIndexPatterns: _.uniq( Object.values(state.layers) - .map(layer => layer.indexPatternId) - .map(indexPatternId => ({ + .map((layer) => layer.indexPatternId) + .map((indexPatternId) => ({ id: indexPatternId, title: state.indexPatterns[indexPatternId].title, })) @@ -282,7 +282,7 @@ export function getIndexPatternDatasource({ render( { + onChangeIndexPattern={(indexPatternId) => { changeLayerIndexPattern({ savedObjectsClient, indexPatternId, @@ -309,7 +309,7 @@ export function getIndexPatternDatasource({ datasourceId: 'indexpattern', getTableSpec: () => { - return state.layers[layerId].columnOrder.map(colId => ({ columnId: colId })); + return state.layers[layerId].columnOrder.map((colId) => ({ columnId: colId })); }, getOperationForColumnId: (columnId: string) => { const layer = state.layers[layerId]; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.test.tsx index f26fd39a60c0e..5eca55cbfcbda 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.test.tsx @@ -1308,7 +1308,7 @@ describe('IndexPattern Data Source suggestions', () => { ...state, indexPatterns: { 1: { ...state.indexPatterns['1'], timeFieldName: undefined } }, }); - suggestions.forEach(suggestion => expect(suggestion.table.columns.length).toBe(1)); + suggestions.forEach((suggestion) => expect(suggestion.table.columns.length).toBe(1)); }); it('returns simplified versions of table with more than 2 columns', () => { @@ -1616,9 +1616,9 @@ function isTableWithBucketColumns( columnIds: string[], numBuckets: number ) { - expect(suggestion.table.columns.map(column => column.columnId)).toEqual(columnIds); + expect(suggestion.table.columns.map((column) => column.columnId)).toEqual(columnIds); expect( - suggestion.table.columns.slice(0, numBuckets).every(column => column.operation.isBucketed) + suggestion.table.columns.slice(0, numBuckets).every((column) => column.operation.isBucketed) ).toBeTruthy(); } @@ -1627,6 +1627,6 @@ function isTableWithMetricColumns( columnIds: string[] ) { expect(suggestion.table.isMultiRow).toEqual(false); - expect(suggestion.table.columns.map(column => column.columnId)).toEqual(columnIds); - expect(suggestion.table.columns.every(column => !column.operation.isBucketed)).toBeTruthy(); + expect(suggestion.table.columns.map((column) => column.columnId)).toEqual(columnIds); + expect(suggestion.table.columns.every((column) => !column.operation.isBucketed)).toBeTruthy(); } diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts index 487c1bf759fc2..89e2c753f4c76 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/indexpattern_suggestions.ts @@ -55,7 +55,7 @@ function buildSuggestion({ // It's fairly easy to accidentally introduce a mismatch between // columnOrder and columns, so this is a safeguard to ensure the // two match up. - const layers = _.mapValues(updatedState.layers, layer => ({ + const layers = _.mapValues(updatedState.layers, (layer) => ({ ...layer, columns: _.pick, Record>( layer.columns, @@ -65,7 +65,7 @@ function buildSuggestion({ const columnOrder = layers[layerId].columnOrder; const columnMap = layers[layerId].columns; - const isMultiRow = Object.values(columnMap).some(column => column.isBucketed); + const isMultiRow = Object.values(columnMap).some((column) => column.isBucketed); return { state: { @@ -74,7 +74,7 @@ function buildSuggestion({ }, table: { - columns: columnOrder.map(columnId => ({ + columns: columnOrder.map((columnId) => ({ columnId, operation: columnToOperation(columnMap[columnId]), })), @@ -94,7 +94,7 @@ export function getDatasourceSuggestionsForField( field: IndexPatternField ): IndexPatternSugestion[] { const layers = Object.keys(state.layers); - const layerIds = layers.filter(id => state.layers[id].indexPatternId === indexPatternId); + const layerIds = layers.filter((id) => state.layers[id].indexPatternId === indexPatternId); if (layerIds.length === 0) { // The field we're suggesting on does not match any existing layer. @@ -108,7 +108,7 @@ export function getDatasourceSuggestionsForField( // The field we're suggesting on matches an existing layer. In this case we find the layer with // the fewest configured columns and try to add the field to this table. If this layer does not // contain any layers yet, behave as if there is no layer. - const mostEmptyLayerId = _.min(layerIds, layerId => state.layers[layerId].columnOrder.length); + const mostEmptyLayerId = _.min(layerIds, (layerId) => state.layers[layerId].columnOrder.length); if (state.layers[mostEmptyLayerId].columnOrder.length === 0) { return getEmptyLayerSuggestionsForField(state, mostEmptyLayerId, indexPatternId, field); } else { @@ -121,7 +121,7 @@ function getBucketOperation(field: IndexPatternField) { // We allow numeric bucket types in some cases, but it's generally not the right suggestion, // so we eliminate it here. if (field.type !== 'number') { - return getOperationTypesForField(field).find(op => op === 'date_histogram' || op === 'terms'); + return getOperationTypesForField(field).find((op) => op === 'date_histogram' || op === 'terms'); } } @@ -135,7 +135,7 @@ function getExistingLayerSuggestionsForField( const operations = getOperationTypesForField(field); const usableAsBucketOperation = getBucketOperation(field); const fieldInUse = Object.values(layer.columns).some( - column => hasField(column) && column.sourceField === field.name + (column) => hasField(column) && column.sourceField === field.name ); const suggestions: IndexPatternSugestion[] = []; @@ -238,7 +238,7 @@ function addFieldAsBucketOperation( } const oldDateHistogramIndex = layer.columnOrder.findIndex( - columnId => layer.columns[columnId].operationType === 'date_histogram' + (columnId) => layer.columns[columnId].operationType === 'date_histogram' ); const oldDateHistogramId = oldDateHistogramIndex > -1 ? layer.columnOrder[oldDateHistogramIndex] : null; @@ -256,7 +256,7 @@ function addFieldAsBucketOperation( } else if (operation === 'date_histogram') { // Replace date histogram with new date histogram delete updatedColumns[oldDateHistogramId]; - updatedColumnOrder = layer.columnOrder.map(columnId => + updatedColumnOrder = layer.columnOrder.map((columnId) => columnId !== oldDateHistogramId ? columnId : newColumnId ); } @@ -351,7 +351,7 @@ function createNewLayerWithMetricAggregation( indexPattern: IndexPattern, field: IndexPatternField ): IndexPatternLayer { - const dateField = indexPattern.fields.find(f => f.name === indexPattern.timeFieldName)!; + const dateField = indexPattern.fields.find((f) => f.name === indexPattern.timeFieldName)!; const column = getMetricColumn(indexPattern, layerId, field); @@ -427,7 +427,7 @@ export function getDatasourceSuggestionsFromCurrentState( const indexPattern = state.indexPatterns[layer.indexPatternId]; const [buckets, metrics] = separateBucketColumns(layer); const timeDimension = layer.columnOrder.find( - columnId => + (columnId) => layer.columns[columnId].isBucketed && layer.columns[columnId].dataType === 'date' ); const timeField = indexPattern.fields.find( @@ -493,7 +493,7 @@ function createChangedNestingSuggestion(state: IndexPatternPrivateState, layerId function getMetricColumn(indexPattern: IndexPattern, layerId: string, field: IndexPatternField) { const operationDefinitionsMap = _.indexBy(operationDefinitions, 'type'); const [column] = getOperationTypesForField(field) - .map(type => + .map((type) => operationDefinitionsMap[type].buildColumn({ field, indexPattern, @@ -502,7 +502,7 @@ function getMetricColumn(indexPattern: IndexPattern, layerId: string, field: Ind suggestedPriority: 0, }) ) - .filter(op => (op.dataType === 'number' || op.dataType === 'document') && !op.isBucketed); + .filter((op) => (op.dataType === 'number' || op.dataType === 'document') && !op.isBucketed); return column; } @@ -561,14 +561,14 @@ function createAlternativeMetricSuggestions( ) { const layer = state.layers[layerId]; const suggestions: Array> = []; - layer.columnOrder.forEach(columnId => { + layer.columnOrder.forEach((columnId) => { const column = layer.columns[columnId]; if (!hasField(column)) { return; } const field = indexPattern.fields.find(({ name }) => column.sourceField === name)!; const alternativeMetricOperations = getOperationTypesForField(field) - .map(op => + .map((op) => buildColumn({ op, columns: layer.columns, @@ -579,7 +579,7 @@ function createAlternativeMetricSuggestions( }) ) .filter( - fullOperation => + (fullOperation) => fullOperation.operationType !== column.operationType && !fullOperation.isBucketed ); if (alternativeMetricOperations.length === 0) { @@ -662,12 +662,12 @@ function createSimplifiedTableSuggestions(state: IndexPatternPrivateState, layer }) ) .concat( - availableMetricColumns.map(columnId => { + availableMetricColumns.map((columnId) => { // build suggestions with only metrics return { ...layer, columnOrder: [columnId] }; }) ) - .map(updatedLayer => { + .map((updatedLayer) => { return buildSuggestion({ state, layerId, @@ -695,5 +695,5 @@ function getMetricSuggestionTitle(layer: IndexPatternLayer, onlyMetric: boolean) } function separateBucketColumns(layer: IndexPatternLayer) { - return partition(layer.columnOrder, columnId => layer.columns[columnId].isBucketed); + return partition(layer.columnOrder, (columnId) => layer.columns[columnId].isBucketed); } diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/layerpanel.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/layerpanel.test.tsx index 4dd29d7925916..0d16e2d054a77 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/layerpanel.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/layerpanel.test.tsx @@ -183,17 +183,13 @@ describe('Layer Data Panel', () => { }); function getIndexPatternPickerList(instance: ShallowWrapper) { - return instance - .find(ChangeIndexPattern) - .first() - .dive() - .find(EuiSelectable); + return instance.find(ChangeIndexPattern).first().dive().find(EuiSelectable); } function selectIndexPatternPickerOption(instance: ShallowWrapper, selectedLabel: string) { const options: Array<{ label: string; checked?: 'on' | 'off' }> = getIndexPatternPickerOptions( instance - ).map(option => + ).map((option) => option.label === selectedLabel ? { ...option, checked: 'on' } : { ...option, checked: undefined } @@ -202,16 +198,13 @@ describe('Layer Data Panel', () => { } function getIndexPatternPickerOptions(instance: ShallowWrapper) { - return getIndexPatternPickerList(instance) - .dive() - .find(EuiSelectableList) - .prop('options'); + return getIndexPatternPickerList(instance).dive().find(EuiSelectableList).prop('options'); } it('should list all index patterns', () => { const instance = shallow(); - expect(getIndexPatternPickerOptions(instance)!.map(option => option.label)).toEqual([ + expect(getIndexPatternPickerOptions(instance)!.map((option) => option.label)).toEqual([ 'my-fake-index-pattern', 'my-fake-restricted-pattern', 'my-compatible-pattern', diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/loader.test.ts b/x-pack/plugins/lens/public/indexpattern_datasource/loader.test.ts index cacf729ba0caf..b54ad3651471d 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/loader.test.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/loader.test.ts @@ -147,7 +147,7 @@ function indexPatternSavedObject({ id }: { id: keyof typeof sampleIndexPatterns attributes: { title: pattern.title, timeFieldName: pattern.timeFieldName, - fields: JSON.stringify(pattern.fields.filter(f => f.type !== 'document')), + fields: JSON.stringify(pattern.fields.filter((f) => f.type !== 'document')), }, }; } @@ -256,12 +256,14 @@ describe('loader', () => { } as unknown) as Pick, }); - expect(cache.foo.fields.find(f => f.name === 'bytes')!.aggregationRestrictions).toEqual({ + expect(cache.foo.fields.find((f) => f.name === 'bytes')!.aggregationRestrictions).toEqual({ sum: { agg: 'sum' }, }); - expect(cache.foo.fields.find(f => f.name === 'timestamp')!.aggregationRestrictions).toEqual({ - date_histogram: { agg: 'date_histogram', fixed_interval: 'm' }, - }); + expect(cache.foo.fields.find((f) => f.name === 'timestamp')!.aggregationRestrictions).toEqual( + { + date_histogram: { agg: 'date_histogram', fixed_interval: 'm' }, + } + ); }); }); @@ -549,7 +551,7 @@ describe('loader', () => { return { indexPatternTitle, existingFieldNames: ['field_1', 'field_2'].map( - fieldName => `${indexPatternTitle}_${fieldName}` + (fieldName) => `${indexPatternTitle}_${fieldName}` ), }; }); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/loader.ts b/x-pack/plugins/lens/public/indexpattern_datasource/loader.ts index 23faab768eba6..c34f4c1d23148 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/loader.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/loader.ts @@ -46,14 +46,14 @@ export async function loadIndexPatterns({ savedObjectsClient: SavedObjectsClient; cache: Record; }) { - const missingIds = patterns.filter(id => !cache[id]); + const missingIds = patterns.filter((id) => !cache[id]); if (missingIds.length === 0) { return cache; } const resp = await savedObjectsClient.bulkGet( - missingIds.map(id => ({ id, type: 'index-pattern' })) + missingIds.map((id) => ({ id, type: 'index-pattern' })) ); return resp.savedObjects.reduce( @@ -81,7 +81,7 @@ export async function loadInitialState({ const requiredPatterns = _.unique( state ? Object.values(state.layers) - .map(l => l.indexPatternId) + .map((l) => l.indexPatternId) .concat(state.currentIndexPatternId) : [defaultIndexPatternId || indexPatternRefs[0].id] ); @@ -134,10 +134,10 @@ export async function changeIndexPattern({ patterns: [id], }); - setState(s => ({ + setState((s) => ({ ...s, layers: isSingleEmptyLayer(state.layers) - ? _.mapValues(state.layers, layer => updateLayerIndexPattern(layer, indexPatterns[id])) + ? _.mapValues(state.layers, (layer) => updateLayerIndexPattern(layer, indexPatterns[id])) : state.layers, indexPatterns: { ...s.indexPatterns, @@ -174,7 +174,7 @@ export async function changeLayerIndexPattern({ patterns: [indexPatternId], }); - setState(s => ({ + setState((s) => ({ ...s, layers: { ...s.layers, @@ -201,7 +201,7 @@ async function loadIndexPatternRefs( }); return result.savedObjects - .map(o => ({ + .map((o) => ({ id: String(o.id), title: (o.attributes as { title: string }).title, })) @@ -224,7 +224,7 @@ export async function syncExistingFields({ dslQuery: object; }) { const emptinessInfo = await Promise.all( - indexPatterns.map(pattern => { + indexPatterns.map((pattern) => { const body: Record = { dslQuery, fromDate: dateRange.fromDate, @@ -241,7 +241,7 @@ export async function syncExistingFields({ }) ); - setState(state => ({ + setState((state) => ({ ...state, existingFields: emptinessInfo.reduce((acc, info) => { acc[info.indexPatternTitle] = booleanMap(info.existingFieldNames); @@ -273,7 +273,7 @@ function fromSavedObject( title: attributes.title, fields: (JSON.parse(attributes.fields) as IFieldType[]) .filter( - field => + (field) => !indexPatternsUtils.isNestedField(field) && (!!field.aggregatable || !!field.scripted) ) .concat(documentField) as IndexPatternField[], @@ -294,7 +294,7 @@ function fromSavedObject( const aggs = Object.keys(typeMeta.aggs); newFields.forEach((field, index) => { const restrictionsObj: IndexPatternField['aggregationRestrictions'] = {}; - aggs.forEach(agg => { + aggs.forEach((agg) => { const restriction = typeMeta.aggs && typeMeta.aggs[agg] && typeMeta.aggs[agg][field.name]; if (restriction) { restrictionsObj[agg] = restriction; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx index 9491ca9ea3787..09faa4bb70447 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/cardinality.tsx @@ -40,7 +40,7 @@ export const cardinalityOperation: OperationDefinition { - const newField = newIndexPattern.fields.find(field => field.name === column.sourceField); + const newField = newIndexPattern.fields.find((field) => field.name === column.sourceField); return Boolean( newField && diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.test.tsx index e3b6061248f3b..e665e8b8dd326 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.test.tsx @@ -251,7 +251,7 @@ describe('date_histogram', () => { }, }; const indexPattern = createMockedIndexPattern(); - const newDateField = indexPattern.fields.find(i => i.name === 'start_date')!; + const newDateField = indexPattern.fields.find((i) => i.name === 'start_date')!; const column = dateHistogramOperation.onFieldChange(oldColumn, indexPattern, newDateField); expect(column).toHaveProperty('sourceField', 'start_date'); @@ -271,7 +271,7 @@ describe('date_histogram', () => { }, }; const indexPattern = createMockedIndexPattern(); - const newDateField = indexPattern.fields.find(i => i.name === 'start_date')!; + const newDateField = indexPattern.fields.find((i) => i.name === 'start_date')!; const column = dateHistogramOperation.onFieldChange(oldColumn, indexPattern, newDateField); expect(column).toHaveProperty('sourceField', 'start_date'); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx index 6161df1167afe..6e007c12acf42 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/date_histogram.tsx @@ -78,7 +78,7 @@ export const dateHistogramOperation: OperationDefinition { - const newField = newIndexPattern.fields.find(field => field.name === column.sourceField); + const newField = newIndexPattern.fields.find((field) => field.name === column.sourceField); return Boolean( newField && @@ -88,7 +88,7 @@ export const dateHistogramOperation: OperationDefinition { - const newField = newIndexPattern.fields.find(field => field.name === column.sourceField); + const newField = newIndexPattern.fields.find((field) => field.name === column.sourceField); if ( newField && newField.aggregationRestrictions && @@ -138,7 +138,7 @@ export const dateHistogramOperation: OperationDefinition currentField.name === currentColumn.sourceField + (currentField) => currentField.name === currentColumn.sourceField ); const intervalIsRestricted = field!.aggregationRestrictions && field!.aggregationRestrictions.date_histogram; @@ -216,7 +216,7 @@ export const dateHistogramOperation: OperationDefinition { + onChange={(e) => { setInterval({ ...interval, value: e.target.value, @@ -228,7 +228,7 @@ export const dateHistogramOperation: OperationDefinition { + onChange={(e) => { setInterval({ ...interval, unit: e.target.value, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx index 3da635dc13d10..3ede847a5e257 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/metrics.tsx @@ -41,7 +41,7 @@ function buildMetricOperation>({ } }, isTransferable: (column, newIndexPattern) => { - const newField = newIndexPattern.fields.find(field => field.name === column.sourceField); + const newField = newIndexPattern.fields.find((field) => field.name === column.sourceField); return Boolean( newField && @@ -91,7 +91,7 @@ export const minOperation = buildMetricOperation({ displayName: i18n.translate('xpack.lens.indexPattern.min', { defaultMessage: 'Minimum', }), - ofName: name => + ofName: (name) => i18n.translate('xpack.lens.indexPattern.minOf', { defaultMessage: 'Minimum of {name}', values: { name }, @@ -103,7 +103,7 @@ export const maxOperation = buildMetricOperation({ displayName: i18n.translate('xpack.lens.indexPattern.max', { defaultMessage: 'Maximum', }), - ofName: name => + ofName: (name) => i18n.translate('xpack.lens.indexPattern.maxOf', { defaultMessage: 'Maximum of {name}', values: { name }, @@ -116,7 +116,7 @@ export const averageOperation = buildMetricOperation({ displayName: i18n.translate('xpack.lens.indexPattern.avg', { defaultMessage: 'Average', }), - ofName: name => + ofName: (name) => i18n.translate('xpack.lens.indexPattern.avgOf', { defaultMessage: 'Average of {name}', values: { name }, @@ -129,7 +129,7 @@ export const sumOperation = buildMetricOperation({ displayName: i18n.translate('xpack.lens.indexPattern.sum', { defaultMessage: 'Sum', }), - ofName: name => + ofName: (name) => i18n.translate('xpack.lens.indexPattern.sumOf', { defaultMessage: 'Sum of {name}', values: { name }, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.test.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.test.tsx index 8f6130e74b5b8..89d02708a900c 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.test.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.test.tsx @@ -100,7 +100,7 @@ describe('terms', () => { }, }; const indexPattern = createMockedIndexPattern(); - const newDateField = indexPattern.fields.find(i => i.name === 'dest')!; + const newDateField = indexPattern.fields.find((i) => i.name === 'dest')!; const column = termsOperation.onFieldChange(oldColumn, indexPattern, newDateField); expect(column).toHaveProperty('sourceField', 'dest'); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.tsx index 7eb10456b2a6e..1ab58cb11c598 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/terms.tsx @@ -64,7 +64,7 @@ export const termsOperation: OperationDefinition = { } }, isTransferable: (column, newIndexPattern) => { - const newField = newIndexPattern.fields.find(field => field.name === column.sourceField); + const newField = newIndexPattern.fields.find((field) => field.name === column.sourceField); return Boolean( newField && diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.ts b/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.ts index dbcd4eac7fd59..a04f71a9095c5 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/operations.ts @@ -63,7 +63,7 @@ function getSortScoreByPriority(a: GenericOperationDefinition, b: GenericOperati export function getOperationTypesForField(field: IndexPatternField): OperationType[] { return operationDefinitions .filter( - operationDefinition => + (operationDefinition) => 'getPossibleOperationForField' in operationDefinition && operationDefinition.getPossibleOperationForField(field) ) @@ -133,8 +133,8 @@ export function getAvailableOperationsByMetadata(indexPattern: IndexPattern) { } }; - operationDefinitions.sort(getSortScoreByPriority).forEach(operationDefinition => { - indexPattern.fields.forEach(field => { + operationDefinitions.sort(getSortScoreByPriority).forEach((operationDefinition) => { + indexPattern.fields.forEach((field) => { addToMap( { type: 'field', diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/rename_columns.ts b/x-pack/plugins/lens/public/indexpattern_datasource/rename_columns.ts index 248eb12ec8026..bf938a3e05ef6 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/rename_columns.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/rename_columns.ts @@ -44,7 +44,7 @@ export const renameColumns: ExpressionFunctionDefinition< return { type: 'kibana_datatable', - rows: data.rows.map(row => { + rows: data.rows.map((row) => { const mappedRow: Record = {}; Object.entries(idMap).forEach(([fromId, toId]) => { mappedRow[toId.id] = row[fromId]; @@ -60,7 +60,7 @@ export const renameColumns: ExpressionFunctionDefinition< return mappedRow; }), - columns: data.columns.map(column => { + columns: data.columns.map((column) => { const mappedItem = idMap[column.id]; if (!mappedItem) { diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/state_helpers.ts b/x-pack/plugins/lens/public/indexpattern_datasource/state_helpers.ts index a2d64e8f2eb8f..a34d0c4187485 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/state_helpers.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/state_helpers.ts @@ -52,7 +52,7 @@ function adjustColumnReferencesForChangedColumn( columnId: string ) { const newColumns = { ...columns }; - Object.keys(newColumns).forEach(currentColumnId => { + Object.keys(newColumns).forEach((currentColumnId) => { if (currentColumnId !== columnId) { const currentColumn = newColumns[currentColumnId]; const operationDefinition = operationDefinitionMap[currentColumn.operationType]; @@ -156,16 +156,16 @@ export function updateLayerIndexPattern( layer: IndexPatternLayer, newIndexPattern: IndexPattern ): IndexPatternLayer { - const keptColumns: IndexPatternLayer['columns'] = _.pick(layer.columns, column => + const keptColumns: IndexPatternLayer['columns'] = _.pick(layer.columns, (column) => isColumnTransferable(column, newIndexPattern) ); - const newColumns: IndexPatternLayer['columns'] = _.mapValues(keptColumns, column => { + const newColumns: IndexPatternLayer['columns'] = _.mapValues(keptColumns, (column) => { const operationDefinition = operationDefinitionMap[column.operationType]; return operationDefinition.transfer ? operationDefinition.transfer(column, newIndexPattern) : column; }); - const newColumnOrder = layer.columnOrder.filter(columnId => newColumns[columnId]); + const newColumnOrder = layer.columnOrder.filter((columnId) => newColumns[columnId]); return { ...layer, diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/to_expression.ts b/x-pack/plugins/lens/public/indexpattern_datasource/to_expression.ts index 1dde03ca8ee9b..e507bee2a898d 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/to_expression.ts +++ b/x-pack/plugins/lens/public/indexpattern_datasource/to_expression.ts @@ -25,7 +25,7 @@ function getExpressionForLayer( return operationDefinitionMap[column.operationType].toEsAggsConfig(column, columnId); } - const columnEntries = columnOrder.map(colId => [colId, columns[colId]] as const); + const columnEntries = columnOrder.map((colId) => [colId, columns[colId]] as const); const bucketsCount = columnEntries.filter(([, entry]) => entry.isBucketed).length; const metricsCount = columnEntries.length - bucketsCount; @@ -88,7 +88,7 @@ function getExpressionForLayer( }); const allDateHistogramFields = Object.values(columns) - .map(column => + .map((column) => column.operationType === dateHistogramOperation.type ? column.sourceField : null ) .filter((field): field is string => Boolean(field)); diff --git a/x-pack/plugins/lens/public/lens_ui_telemetry/factory.ts b/x-pack/plugins/lens/public/lens_ui_telemetry/factory.ts index 10b052c66efed..cb517acff4f7a 100644 --- a/x-pack/plugins/lens/public/lens_ui_telemetry/factory.ts +++ b/x-pack/plugins/lens/public/lens_ui_telemetry/factory.ts @@ -102,9 +102,7 @@ export class LensReportManager { } private trackTo(target: Record>, name: string) { - const date = moment() - .utc() - .format('YYYY-MM-DD'); + const date = moment().utc().format('YYYY-MM-DD'); if (!target[date]) { target[date] = { [name]: 1, diff --git a/x-pack/plugins/lens/public/metric_visualization/auto_scale.tsx b/x-pack/plugins/lens/public/metric_visualization/auto_scale.tsx index 18c6ec6536e96..c75da2f34d98d 100644 --- a/x-pack/plugins/lens/public/metric_visualization/auto_scale.tsx +++ b/x-pack/plugins/lens/public/metric_visualization/auto_scale.tsx @@ -61,10 +61,10 @@ export class AutoScale extends React.Component { return ( - {resizeRef => ( + {(resizeRef) => (
{ + ref={(el) => { this.setParent(el); resizeRef(el); }} diff --git a/x-pack/plugins/lens/public/metric_visualization/metric_expression.test.tsx b/x-pack/plugins/lens/public/metric_visualization/metric_expression.test.tsx index 2406e7cd42ebc..27f971c2ba11a 100644 --- a/x-pack/plugins/lens/public/metric_visualization/metric_expression.test.tsx +++ b/x-pack/plugins/lens/public/metric_visualization/metric_expression.test.tsx @@ -57,7 +57,7 @@ describe('metric_expression', () => { const { data, args } = sampleArgs(); expect( - shallow( x as IFieldFormat} />) + shallow( x as IFieldFormat} />) ).toMatchInlineSnapshot(` { x as IFieldFormat} + formatFactory={(x) => x as IFieldFormat} /> ) ).toMatchInlineSnapshot(` diff --git a/x-pack/plugins/lens/public/metric_visualization/metric_suggestions.test.ts b/x-pack/plugins/lens/public/metric_visualization/metric_suggestions.test.ts index 173119714189d..ecb1f07214ac6 100644 --- a/x-pack/plugins/lens/public/metric_visualization/metric_suggestions.test.ts +++ b/x-pack/plugins/lens/public/metric_visualization/metric_suggestions.test.ts @@ -80,7 +80,7 @@ describe('metric_suggestions', () => { layerId: 'l1', changeType: 'unchanged', }, - ] as TableSuggestion[]).map(table => + ] as TableSuggestion[]).map((table) => expect(getSuggestions({ table, keptLayerIds: ['l1'] })).toEqual([]) ) ); diff --git a/x-pack/plugins/lens/public/metric_visualization/metric_visualization.tsx b/x-pack/plugins/lens/public/metric_visualization/metric_visualization.tsx index 04a1c3865f22d..e565d2fa8b293 100644 --- a/x-pack/plugins/lens/public/metric_visualization/metric_visualization.tsx +++ b/x-pack/plugins/lens/public/metric_visualization/metric_visualization.tsx @@ -88,7 +88,7 @@ export const metricVisualization: Visualization = { ); }, - getPersistableState: state => state, + getPersistableState: (state) => state, getConfiguration(props) { return { diff --git a/x-pack/plugins/lens/public/native_renderer/native_renderer.tsx b/x-pack/plugins/lens/public/native_renderer/native_renderer.tsx index 08464dd65f67e..8146caaf95ced 100644 --- a/x-pack/plugins/lens/public/native_renderer/native_renderer.tsx +++ b/x-pack/plugins/lens/public/native_renderer/native_renderer.tsx @@ -23,6 +23,6 @@ export interface NativeRendererProps extends HTMLAttributes { export function NativeRenderer({ render, nativeProps, tag, ...rest }: NativeRendererProps) { return React.createElement(tag || 'div', { ...rest, - ref: el => el && render(el, nativeProps), + ref: (el) => el && render(el, nativeProps), }); } diff --git a/x-pack/plugins/lens/public/pie_visualization/pie_visualization.tsx b/x-pack/plugins/lens/public/pie_visualization/pie_visualization.tsx index 78e13bc51588c..4f0c081d8be00 100644 --- a/x-pack/plugins/lens/public/pie_visualization/pie_visualization.tsx +++ b/x-pack/plugins/lens/public/pie_visualization/pie_visualization.tsx @@ -57,13 +57,13 @@ export const pieVisualization: Visualization l.layerId); + return state.layers.map((l) => l.layerId); }, clearLayer(state) { return { shape: state.shape, - layers: state.layers.map(l => newLayerState(l.layerId)), + layers: state.layers.map((l) => newLayerState(l.layerId)), }; }, @@ -91,12 +91,12 @@ export const pieVisualization: Visualization state, + getPersistableState: (state) => state, getSuggestions: suggestions, getConfiguration({ state, frame, layerId }) { - const layer = state.layers.find(l => l.layerId === layerId); + const layer = state.layers.find((l) => l.layerId === layerId); if (!layer) { return { groups: [] }; } @@ -105,7 +105,7 @@ export const pieVisualization: Visualization columnId) - .filter(columnId => columnId !== layer.metric); + .filter((columnId) => columnId !== layer.metric); // When we add a column it could be empty, and therefore have no order const sortedColumns = Array.from(new Set(originalOrder.concat(layer.groups))); @@ -171,10 +171,10 @@ export const pieVisualization: Visualization l.groups.length === 1) + prevState.shape === 'donut' && prevState.layers.every((l) => l.groups.length === 1) ? 'pie' : prevState.shape, - layers: prevState.layers.map(l => { + layers: prevState.layers.map((l) => { if (l.layerId !== layerId) { return l; } @@ -188,7 +188,7 @@ export const pieVisualization: Visualization { + layers: prevState.layers.map((l) => { if (l.layerId !== layerId) { return l; } @@ -196,7 +196,7 @@ export const pieVisualization: Visualization c !== columnId) }; + return { ...l, groups: l.groups.filter((c) => c !== columnId) }; }), }; }, diff --git a/x-pack/plugins/lens/public/pie_visualization/render_function.test.tsx b/x-pack/plugins/lens/public/pie_visualization/render_function.test.tsx index a914efcead005..2e29513ba548b 100644 --- a/x-pack/plugins/lens/public/pie_visualization/render_function.test.tsx +++ b/x-pack/plugins/lens/public/pie_visualization/render_function.test.tsx @@ -17,7 +17,7 @@ describe('PieVisualization component', () => { let convertSpy: jest.Mock; beforeEach(() => { - convertSpy = jest.fn(x => x); + convertSpy = jest.fn((x) => x); getFormatSpy = jest.fn(); getFormatSpy.mockReturnValue({ convert: convertSpy }); }); @@ -114,10 +114,9 @@ describe('PieVisualization component', () => { test('it calls filter callback with the given context', () => { const defaultArgs = getDefaultArgs(); const component = shallow(); - component - .find(Settings) - .first() - .prop('onElementClick')!([[[{ groupByRollup: 6, value: 6 }], {} as SeriesIdentifier]]); + component.find(Settings).first().prop('onElementClick')!([ + [[{ groupByRollup: 6, value: 6 }], {} as SeriesIdentifier], + ]); expect(defaultArgs.onClickValue.mock.calls[0][0]).toMatchInlineSnapshot(` Object { diff --git a/x-pack/plugins/lens/public/pie_visualization/render_function.tsx b/x-pack/plugins/lens/public/pie_visualization/render_function.tsx index d812803272f3e..be74ec352287f 100644 --- a/x-pack/plugins/lens/public/pie_visualization/render_function.tsx +++ b/x-pack/plugins/lens/public/pie_visualization/render_function.tsx @@ -61,7 +61,7 @@ export function PieComponent( } = props.args; if (!hideLabels) { - firstTable.columns.forEach(column => { + firstTable.columns.forEach((column) => { formatters[column.id] = props.formatFactory(column.formatHint); }); } @@ -70,7 +70,7 @@ export function PieComponent( // [bucket, subtotal, bucket, count] // But the user only configured [bucket, bucket, count] const columnGroups: ColumnGroups = []; - firstTable.columns.forEach(col => { + firstTable.columns.forEach((col) => { if (groups.includes(col.id)) { columnGroups.push({ col, @@ -115,7 +115,7 @@ export function PieComponent( ? { ...fillLabel, textColor: euiDarkVars.euiTextColor } : fillLabel, shape: { - fillColor: d => { + fillColor: (d) => { // Color is determined by round-robin on the index of the innermost slice // This has to be done recursively until we get to the slice index let parentIndex = 0; @@ -134,9 +134,7 @@ export function PieComponent( } const lighten = (d.depth - 1) / (columnGroups.length * 2); - return color(outputColor, 'hsl') - .lighten(lighten) - .hex(); + return color(outputColor, 'hsl').lighten(lighten).hex(); }, }, }; @@ -179,7 +177,7 @@ export function PieComponent( config.linkLabel = { maxCount: 0 }; } } - const metricColumn = firstTable.columns.find(c => c.id === metric)!; + const metricColumn = firstTable.columns.find((c) => c.id === metric)!; const percentFormatter = props.formatFactory({ id: 'percent', params: { @@ -196,14 +194,14 @@ export function PieComponent( const reverseGroups = [...columnGroups].reverse(); - const hasNegative = firstTable.rows.some(row => { + const hasNegative = firstTable.rows.some((row) => { const value = row[metricColumn.id]; return typeof value === 'number' && value < 0; }); const isEmpty = firstTable.rows.length === 0 || - firstTable.rows.every(row => - groups.every(colId => !row[colId] || typeof row[colId] === 'undefined') + firstTable.rows.every((row) => + groups.every((colId) => !row[colId] || typeof row[colId] === 'undefined') ); if (isEmpty) { @@ -237,7 +235,7 @@ export function PieComponent( (legendDisplay === 'default' && columnGroups.length > 1 && shape !== 'treemap')) } legendMaxDepth={nestedLegend ? undefined : 1 /* Color is based only on first layer */} - onElementClick={args => { + onElementClick={(args) => { const context = getFilterContext( args[0][0] as LayerValue[], columnGroups.map(({ col }) => col.id), diff --git a/x-pack/plugins/lens/public/pie_visualization/render_helpers.ts b/x-pack/plugins/lens/public/pie_visualization/render_helpers.ts index 3f7494661c049..aafbb477bab22 100644 --- a/x-pack/plugins/lens/public/pie_visualization/render_helpers.ts +++ b/x-pack/plugins/lens/public/pie_visualization/render_helpers.ts @@ -20,7 +20,7 @@ export function getSliceValueWithFallback( // Sometimes there is missing data for outer groups // When there is missing data, we fall back to the next groups // This creates a sunburst effect - const hasMetric = reverseGroups.find(group => group.metrics.length && d[group.metrics[0].id]); + const hasMetric = reverseGroups.find((group) => group.metrics.length && d[group.metrics[0].id]); return hasMetric ? d[hasMetric.metrics[0].id] || Number.EPSILON : Number.EPSILON; } @@ -29,7 +29,7 @@ export function getFilterContext( layerColumnIds: string[], table: KibanaDatatable ): LensFilterEvent['data'] { - const matchingIndex = table.rows.findIndex(row => + const matchingIndex = table.rows.findIndex((row) => clickedLayers.every((layer, index) => { const columnId = layerColumnIds[index]; return row[columnId] === layer.groupByRollup; @@ -38,7 +38,7 @@ export function getFilterContext( return { data: clickedLayers.map((clickedLayer, index) => ({ - column: table.columns.findIndex(col => col.id === layerColumnIds[index]), + column: table.columns.findIndex((col) => col.id === layerColumnIds[index]), row: matchingIndex, value: clickedLayer.groupByRollup, table, diff --git a/x-pack/plugins/lens/public/pie_visualization/settings_widget.tsx b/x-pack/plugins/lens/public/pie_visualization/settings_widget.tsx index bb63ceceb2b1b..e5fde12f74b42 100644 --- a/x-pack/plugins/lens/public/pie_visualization/settings_widget.tsx +++ b/x-pack/plugins/lens/public/pie_visualization/settings_widget.tsx @@ -132,7 +132,7 @@ export function SettingsWidget(props: VisualizationLayerWidgetProps { + onChange={(option) => { setState({ ...state, layers: [{ ...layer, categoryDisplay: option }], @@ -152,7 +152,7 @@ export function SettingsWidget(props: VisualizationLayerWidgetProps { + onChange={(option) => { setState({ ...state, layers: [{ ...layer, numberDisplay: option }], @@ -175,7 +175,7 @@ export function SettingsWidget(props: VisualizationLayerWidgetProps { + onChange={(e) => { setState({ ...state, layers: [{ ...layer, percentDecimals: Number(e.currentTarget.value) }], @@ -197,7 +197,7 @@ export function SettingsWidget(props: VisualizationLayerWidgetProps value === layer.legendDisplay)!.id} - onChange={optionId => { + onChange={(optionId) => { setState({ ...state, layers: [ diff --git a/x-pack/plugins/lens/public/pie_visualization/suggestions.ts b/x-pack/plugins/lens/public/pie_visualization/suggestions.ts index 16c8fda3807db..5d85ac3bbd56a 100644 --- a/x-pack/plugins/lens/public/pie_visualization/suggestions.ts +++ b/x-pack/plugins/lens/public/pie_visualization/suggestions.ts @@ -15,7 +15,7 @@ function shouldReject({ table, keptLayerIds }: SuggestionRequest 1 || (keptLayerIds.length && table.layerId !== keptLayerIds[0]) || table.changeType === 'reorder' || - table.columns.some(col => col.operation.dataType === 'date') + table.columns.some((col) => col.operation.dataType === 'date') ); } @@ -30,7 +30,7 @@ export function suggestions({ return []; } - const [groups, metrics] = partition(table.columns, col => col.operation.isBucketed); + const [groups, metrics] = partition(table.columns, (col) => col.operation.isBucketed); if ( groups.length === 0 || @@ -62,12 +62,12 @@ export function suggestions({ ? { ...state.layers[0], layerId: table.layerId, - groups: groups.map(col => col.columnId), + groups: groups.map((col) => col.columnId), metric: metrics[0].columnId, } : { layerId: table.layerId, - groups: groups.map(col => col.columnId), + groups: groups.map((col) => col.columnId), metric: metrics[0].columnId, numberDisplay: 'percent', categoryDisplay: 'default', @@ -113,7 +113,7 @@ export function suggestions({ ? { ...state.layers[0], layerId: table.layerId, - groups: groups.map(col => col.columnId), + groups: groups.map((col) => col.columnId), metric: metrics[0].columnId, categoryDisplay: state.layers[0].categoryDisplay === 'inside' @@ -122,7 +122,7 @@ export function suggestions({ } : { layerId: table.layerId, - groups: groups.map(col => col.columnId), + groups: groups.map((col) => col.columnId), metric: metrics[0].columnId, numberDisplay: 'percent', categoryDisplay: 'default', diff --git a/x-pack/plugins/lens/public/pie_visualization/to_expression.ts b/x-pack/plugins/lens/public/pie_visualization/to_expression.ts index 4a7272b26a63f..cf9d311dfd504 100644 --- a/x-pack/plugins/lens/public/pie_visualization/to_expression.ts +++ b/x-pack/plugins/lens/public/pie_visualization/to_expression.ts @@ -21,7 +21,7 @@ function expressionHelper( const layer = state.layers[0]; const datasource = frame.datasourceLayers[layer.layerId]; const operations = layer.groups - .map(columnId => ({ columnId, operation: datasource.getOperationForColumnId(columnId) })) + .map((columnId) => ({ columnId, operation: datasource.getOperationForColumnId(columnId) })) .filter((o): o is { columnId: string; operation: Operation } => !!o.operation); if (!layer.metric || !operations.length) { return null; @@ -36,7 +36,7 @@ function expressionHelper( arguments: { shape: [state.shape], hideLabels: [isPreview], - groups: operations.map(o => o.columnId), + groups: operations.map((o) => o.columnId), metric: [layer.metric], numberDisplay: [layer.numberDisplay], categoryDisplay: [layer.categoryDisplay], diff --git a/x-pack/plugins/lens/public/xy_visualization/state_helpers.ts b/x-pack/plugins/lens/public/xy_visualization/state_helpers.ts index eb7fd688bab5a..6efcfcab1ff7f 100644 --- a/x-pack/plugins/lens/public/xy_visualization/state_helpers.ts +++ b/x-pack/plugins/lens/public/xy_visualization/state_helpers.ts @@ -12,11 +12,11 @@ export function isHorizontalSeries(seriesType: SeriesType) { } export function isHorizontalChart(layers: Array<{ seriesType: SeriesType }>) { - return layers.every(l => isHorizontalSeries(l.seriesType)); + return layers.every((l) => isHorizontalSeries(l.seriesType)); } export function getIconForSeries(type: SeriesType): EuiIconType { - const definition = visualizationTypes.find(t => t.id === type); + const definition = visualizationTypes.find((t) => t.id === type); if (!definition) { throw new Error(`Unknown series type ${type}`); diff --git a/x-pack/plugins/lens/public/xy_visualization/to_expression.test.ts b/x-pack/plugins/lens/public/xy_visualization/to_expression.test.ts index 6bc379ea33bca..e9e0cfed909fb 100644 --- a/x-pack/plugins/lens/public/xy_visualization/to_expression.test.ts +++ b/x-pack/plugins/lens/public/xy_visualization/to_expression.test.ts @@ -25,7 +25,7 @@ describe('#toExpression', () => { { columnId: 'c' }, ]); - mockDatasource.publicAPIMock.getOperationForColumnId.mockImplementation(col => { + mockDatasource.publicAPIMock.getOperationForColumnId.mockImplementation((col) => { return { label: `col_${col}`, dataType: 'number' } as Operation; }); diff --git a/x-pack/plugins/lens/public/xy_visualization/to_expression.ts b/x-pack/plugins/lens/public/xy_visualization/to_expression.ts index d28a803790822..e02d135d9a455 100644 --- a/x-pack/plugins/lens/public/xy_visualization/to_expression.ts +++ b/x-pack/plugins/lens/public/xy_visualization/to_expression.ts @@ -41,10 +41,10 @@ export const toExpression = (state: State, frame: FramePublicAPI): Ast | null => } const metadata: Record> = {}; - state.layers.forEach(layer => { + state.layers.forEach((layer) => { metadata[layer.layerId] = {}; const datasource = frame.datasourceLayers[layer.layerId]; - datasource.getTableSpec().forEach(column => { + datasource.getTableSpec().forEach((column) => { const operation = frame.datasourceLayers[layer.layerId].getOperationForColumnId( column.columnId ); @@ -59,7 +59,7 @@ export function toPreviewExpression(state: State, frame: FramePublicAPI) { return toExpression( { ...state, - layers: state.layers.map(layer => ({ ...layer, hide: true })), + layers: state.layers.map((layer) => ({ ...layer, hide: true })), // hide legend for preview legend: { ...state.legend, @@ -133,14 +133,14 @@ export const buildExpression = ( ], }, ], - layers: validLayers.map(layer => { + layers: validLayers.map((layer) => { const columnToLabel: Record = {}; if (frame) { const datasource = frame.datasourceLayers[layer.layerId]; layer.accessors .concat(layer.splitAccessor ? [layer.splitAccessor] : []) - .forEach(accessor => { + .forEach((accessor) => { const operation = datasource.getOperationForColumnId(accessor); if (operation?.label) { columnToLabel[accessor] = operation.label; diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx b/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx index 5e85680cc2b2c..0ea44e469f8dd 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx @@ -28,7 +28,7 @@ function updateLayer(state: State, layer: UnwrapArray, index: n export function LayerContextMenu(props: VisualizationLayerWidgetProps) { const { state, layerId } = props; const horizontalOnly = isHorizontalChart(state.layers); - const index = state.layers.findIndex(l => l.layerId === layerId); + const index = state.layers.findIndex((l) => l.layerId === layerId); const layer = state.layers[index]; if (!layer) { @@ -49,14 +49,14 @@ export function LayerContextMenu(props: VisualizationLayerWidgetProps) { className="eui-displayInlineBlock" data-test-subj="lnsXY_seriesType" options={visualizationTypes - .filter(t => isHorizontalSeries(t.id as SeriesType) === horizontalOnly) - .map(t => ({ + .filter((t) => isHorizontalSeries(t.id as SeriesType) === horizontalOnly) + .map((t) => ({ id: t.id, label: t.label, iconType: t.icon || 'empty', }))} idSelected={layer.seriesType} - onChange={seriesType => { + onChange={(seriesType) => { trackUiEvent('xy_change_layer_display'); props.setState( updateLayer(state, { ...layer, seriesType: seriesType as SeriesType }, index) diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_expression.test.tsx b/x-pack/plugins/lens/public/xy_visualization/xy_expression.test.tsx index 346351f2e7ee2..b2d9f6acfc9f5 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_expression.test.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/xy_expression.test.tsx @@ -281,7 +281,7 @@ describe('xy_expression', () => { let convertSpy: jest.Mock; beforeEach(() => { - convertSpy = jest.fn(x => x); + convertSpy = jest.fn((x) => x); getFormatSpy = jest.fn(); getFormatSpy.mockReturnValue({ convert: convertSpy }); }); @@ -618,10 +618,7 @@ describe('xy_expression', () => { /> ); - wrapper - .find(Settings) - .first() - .prop('onBrushEnd')!({ x: [1585757732783, 1585758880838] }); + wrapper.find(Settings).first().prop('onBrushEnd')!({ x: [1585757732783, 1585758880838] }); expect(onSelectRange).toHaveBeenCalledWith({ column: 0, @@ -671,10 +668,9 @@ describe('xy_expression', () => { /> ); - wrapper - .find(Settings) - .first() - .prop('onElementClick')!([[geometry, series as XYChartSeriesIdentifier]]); + wrapper.find(Settings).first().prop('onElementClick')!([ + [geometry, series as XYChartSeriesIdentifier], + ]); expect(onClickValue).toHaveBeenCalledWith({ data: [ @@ -1188,10 +1184,7 @@ describe('xy_expression', () => { /> ); - const tickFormatter = instance - .find(Axis) - .first() - .prop('tickFormat'); + const tickFormatter = instance.find(Axis).first().prop('tickFormat'); if (!tickFormatter) { throw new Error('tickFormatter prop not found'); diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_expression.tsx b/x-pack/plugins/lens/public/xy_visualization/xy_expression.tsx index 8b7229cd808aa..4ad2b2f22c98a 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_expression.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/xy_expression.tsx @@ -156,7 +156,7 @@ export const getXyChartRenderer = (dependencies: { }); function getIconForSeriesType(seriesType: SeriesType): IconType { - return visualizationTypes.find(c => c.id === seriesType)!.icon || 'empty'; + return visualizationTypes.find((c) => c.id === seriesType)!.icon || 'empty'; } const MemoizedChart = React.memo(XYChart); @@ -197,7 +197,7 @@ export function XYChart({ !accessors.length || !data.tables[layerId] || data.tables[layerId].rows.length === 0 || - data.tables[layerId].rows.every(row => typeof row[xAccessor] === 'undefined') + data.tables[layerId].rows.every((row) => typeof row[xAccessor] === 'undefined') ); }); @@ -225,8 +225,8 @@ export function XYChart({ const chartHasMoreThanOneSeries = filteredLayers.length > 1 || - filteredLayers.some(layer => layer.accessors.length > 1) || - filteredLayers.some(layer => layer.splitAccessor); + filteredLayers.some((layer) => layer.accessors.length > 1) || + filteredLayers.some((layer) => layer.splitAccessor); const shouldRotate = isHorizontalChart(filteredLayers); const xTitle = (xAxisColumn && xAxisColumn.name) || args.xTitle; @@ -240,7 +240,7 @@ export function XYChart({ for (const layer of filteredLayers) { if ( layer.xAccessor && - data.tables[layer.layerId].rows.some(row => row[layer.xAccessor!] !== firstRowValue) + data.tables[layer.layerId].rows.some((row) => row[layer.xAccessor!] !== firstRowValue) ) { return false; } @@ -261,7 +261,7 @@ export function XYChart({ return undefined; } - const isTimeViz = data.dateRange && filteredLayers.every(l => l.xScaleType === 'time'); + const isTimeViz = data.dateRange && filteredLayers.every((l) => l.xScaleType === 'time'); const xDomain = isTimeViz ? { @@ -293,7 +293,7 @@ export function XYChart({ const table = data.tables[filteredLayers[0].layerId]; const xAxisColumnIndex = table.columns.findIndex( - el => el.id === filteredLayers[0].xAccessor + (el) => el.id === filteredLayers[0].xAccessor ); const timeFieldName = table.columns[xAxisColumnIndex]?.meta?.aggConfigParams?.field; @@ -310,7 +310,7 @@ export function XYChart({ const xySeries = series as XYChartSeriesIdentifier; const xyGeometry = geometry as GeometryValue; - const layer = filteredLayers.find(l => + const layer = filteredLayers.find((l) => xySeries.seriesKeys.some((key: string | number) => l.accessors.includes(key.toString())) ); if (!layer) { @@ -322,9 +322,9 @@ export function XYChart({ const points = [ { row: table.rows.findIndex( - row => layer.xAccessor && row[layer.xAccessor] === xyGeometry.x + (row) => layer.xAccessor && row[layer.xAccessor] === xyGeometry.x ), - column: table.columns.findIndex(col => col.id === layer.xAccessor), + column: table.columns.findIndex((col) => col.id === layer.xAccessor), value: xyGeometry.x, }, ]; @@ -334,19 +334,19 @@ export function XYChart({ points.push({ row: table.rows.findIndex( - row => layer.splitAccessor && row[layer.splitAccessor] === pointValue + (row) => layer.splitAccessor && row[layer.splitAccessor] === pointValue ), - column: table.columns.findIndex(col => col.id === layer.splitAccessor), + column: table.columns.findIndex((col) => col.id === layer.splitAccessor), value: pointValue, }); } - const xAxisFieldName = table.columns.find(el => el.id === layer.xAccessor)?.meta + const xAxisFieldName = table.columns.find((el) => el.id === layer.xAccessor)?.meta ?.aggConfigParams?.field; const timeFieldName = xDomain && xAxisFieldName; const context: LensFilterEvent['data'] = { - data: points.map(point => ({ + data: points.map((point) => ({ row: point.row, column: point.column, value: point.value, @@ -364,7 +364,7 @@ export function XYChart({ title={xTitle} showGridLines={false} hide={filteredLayers[0].hide} - tickFormat={d => xAxisFormatter.convert(d)} + tickFormat={(d) => xAxisFormatter.convert(d)} /> yAxisFormatter.convert(d)} + tickFormat={(d) => yAxisFormatter.convert(d)} /> {filteredLayers.map( @@ -400,13 +400,13 @@ export function XYChart({ // For date histogram chart type, we're getting the rows that represent intervals without data. // To not display them in the legend, they need to be filtered out. const rows = table.rows.filter( - row => + (row) => xAccessor && typeof row[xAccessor] !== 'undefined' && !( splitAccessor && typeof row[splitAccessor] === 'undefined' && - accessors.every(accessor => typeof row[accessor] === 'undefined') + accessors.every((accessor) => typeof row[accessor] === 'undefined') ) ); @@ -422,7 +422,7 @@ export function XYChart({ enableHistogramMode: isHistogram && (seriesType.includes('stacked') || !splitAccessor), timeZone, name(d) { - const splitHint = table.columns.find(col => col.id === splitAccessor)?.formatHint; + const splitHint = table.columns.find((col) => col.id === splitAccessor)?.formatHint; // For multiple y series, the name of the operation is used on each, either: // * Key - Y name diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.test.ts b/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.test.ts index 722a07f581db5..c107d8d368248 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.test.ts +++ b/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.test.ts @@ -100,7 +100,7 @@ describe('xy_suggestions', () => { layerId: 'first', changeType: 'unchanged', }, - ] as TableSuggestion[]).map(table => + ] as TableSuggestion[]).map((table) => expect(getSuggestions({ table, keptLayerIds: [] })).toEqual([]) ) ); @@ -432,7 +432,7 @@ describe('xy_suggestions', () => { expect(rest).toHaveLength(visualizationTypes.length - 1); expect(suggestion.state.preferredSeriesType).toEqual('bar_horizontal'); - expect(suggestion.state.layers.every(l => l.seriesType === 'bar_horizontal')).toBeTruthy(); + expect(suggestion.state.layers.every((l) => l.seriesType === 'bar_horizontal')).toBeTruthy(); expect(suggestion.title).toEqual('Flip'); }); @@ -461,7 +461,7 @@ describe('xy_suggestions', () => { keptLayerIds: [], }); - const visibleSuggestions = suggestions.filter(suggestion => !suggestion.hide); + const visibleSuggestions = suggestions.filter((suggestion) => !suggestion.hide); expect(visibleSuggestions).toContainEqual( expect.objectContaining({ title: 'Stacked', diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.ts b/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.ts index 71cb8e0cbdc99..ffbd3b7e2c1f2 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.ts +++ b/x-pack/plugins/lens/public/xy_visualization/xy_suggestions.ts @@ -42,8 +42,8 @@ export function getSuggestions({ // We reject any datasource suggestions which have a column of an unknown type. !table.isMultiRow || table.columns.length <= 1 || - table.columns.every(col => col.operation.dataType !== 'number') || - table.columns.some(col => !columnSortOrder.hasOwnProperty(col.operation.dataType)) + table.columns.every((col) => col.operation.dataType !== 'number') || + table.columns.some((col) => !columnSortOrder.hasOwnProperty(col.operation.dataType)) ) { return []; } @@ -62,7 +62,7 @@ function getSuggestionForColumns( keptLayerIds: string[], currentState?: State ): VisualizationSuggestion | Array> | undefined { - const [buckets, values] = partition(table.columns, col => col.operation.isBucketed); + const [buckets, values] = partition(table.columns, (col) => col.operation.isBucketed); if (buckets.length === 1 || buckets.length === 2) { const [x, splitBy] = getBucketMappings(table, currentState); @@ -95,7 +95,7 @@ function getBucketMappings(table: TableSuggestion, currentState?: State) { const currentLayer = currentState && currentState.layers.find(({ layerId }) => layerId === table.layerId); - const buckets = table.columns.filter(col => col.operation.isBucketed); + const buckets = table.columns.filter((col) => col.operation.isBucketed); // reverse the buckets before prioritization to always use the most inner // bucket of the highest-prioritized group as x value (don't use nested // buckets as split series) @@ -182,7 +182,7 @@ function getSuggestionsForLayer({ if (!currentState && changeType === 'unchanged') { // Chart switcher needs to include every chart type return visualizationTypes - .map(visType => ({ + .map((visType) => ({ ...buildSuggestion({ ...options, seriesType: visType.id as SeriesType }), title: visType.label, hide: visType.id !== 'bar_stacked', @@ -251,12 +251,12 @@ function getSuggestionsForLayer({ // Combine all pre-built suggestions with hidden suggestions for remaining chart types return sameStateSuggestions.concat( visualizationTypes - .filter(visType => { + .filter((visType) => { return !sameStateSuggestions.find( - suggestion => suggestion.state.preferredSeriesType === visType.id + (suggestion) => suggestion.state.preferredSeriesType === visType.id ); }) - .map(visType => { + .map((visType) => { return { ...buildSuggestion({ ...options, seriesType: visType.id as SeriesType }), hide: true, @@ -331,7 +331,7 @@ function getSuggestionTitle( tableLabel: string | undefined ) { const yTitle = yValues - .map(col => col.operation.label) + .map((col) => col.operation.label) .join( i18n.translate('xpack.lens.xySuggestions.yAxixConjunctionSign', { defaultMessage: ' & ', @@ -385,12 +385,12 @@ function buildSuggestion({ seriesType, xAccessor: xValue.columnId, splitAccessor: splitBy?.columnId, - accessors: yValues.map(col => col.columnId), + accessors: yValues.map((col) => col.columnId), }; const keptLayers = currentState ? currentState.layers.filter( - layer => layer.layerId !== layerId && keptLayerIds.includes(layer.layerId) + (layer) => layer.layerId !== layerId && keptLayerIds.includes(layer.layerId) ) : []; @@ -425,5 +425,5 @@ function getScore( } function getExistingLayer(currentState: XYState | undefined, layerId: string) { - return currentState && currentState.layers.find(layer => layer.layerId === layerId); + return currentState && currentState.layers.find((layer) => layer.layerId === layerId); } diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_visualization.test.ts b/x-pack/plugins/lens/public/xy_visualization/xy_visualization.test.ts index d176905c65120..0a8e8bbe0c46f 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_visualization.test.ts +++ b/x-pack/plugins/lens/public/xy_visualization/xy_visualization.test.ts @@ -316,7 +316,7 @@ describe('xy_visualization', () => { layerId: 'first', }).groups; expect(options).toHaveLength(3); - expect(options.map(o => o.groupId)).toEqual(['x', 'y', 'breakdown']); + expect(options.map((o) => o.groupId)).toEqual(['x', 'y', 'breakdown']); }); it('should only accept bucketed operations for x', () => { @@ -325,7 +325,7 @@ describe('xy_visualization', () => { frame, layerId: 'first', }).groups; - const filterOperations = options.find(o => o.groupId === 'x')!.filterOperations; + const filterOperations = options.find((o) => o.groupId === 'x')!.filterOperations; const exampleOperation: Operation = { dataType: 'number', @@ -354,7 +354,7 @@ describe('xy_visualization', () => { frame, layerId: 'first', }).groups; - expect(options.find(o => o.groupId === 'x')?.supportsMoreColumns).toBe(false); + expect(options.find((o) => o.groupId === 'x')?.supportsMoreColumns).toBe(false); }); it('should allow number operations on y', () => { @@ -363,7 +363,7 @@ describe('xy_visualization', () => { frame, layerId: 'first', }).groups; - const filterOperations = options.find(o => o.groupId === 'y')!.filterOperations; + const filterOperations = options.find((o) => o.groupId === 'y')!.filterOperations; const exampleOperation: Operation = { dataType: 'number', isBucketed: false, @@ -375,7 +375,7 @@ describe('xy_visualization', () => { { ...exampleOperation, dataType: 'boolean' }, { ...exampleOperation, dataType: 'date' }, ]; - expect(ops.filter(filterOperations).map(x => x.dataType)).toEqual(['number']); + expect(ops.filter(filterOperations).map((x) => x.dataType)).toEqual(['number']); }); }); }); diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_visualization.tsx b/x-pack/plugins/lens/public/xy_visualization/xy_visualization.tsx index e91edf9cc0183..ffacfbf8555eb 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_visualization.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/xy_visualization.tsx @@ -27,11 +27,11 @@ const isBucketed = (op: OperationMetadata) => op.isBucketed; function getVisualizationType(state: State): VisualizationType | 'mixed' { if (!state.layers.length) { return ( - visualizationTypes.find(t => t.id === state.preferredSeriesType) ?? visualizationTypes[0] + visualizationTypes.find((t) => t.id === state.preferredSeriesType) ?? visualizationTypes[0] ); } - const visualizationType = visualizationTypes.find(t => t.id === state.layers[0].seriesType); - const seriesTypes = _.unique(state.layers.map(l => l.seriesType)); + const visualizationType = visualizationTypes.find((t) => t.id === state.layers[0].seriesType); + const seriesTypes = _.unique(state.layers.map((l) => l.seriesType)); return visualizationType && seriesTypes.length === 1 ? visualizationType : 'mixed'; } @@ -84,18 +84,18 @@ export const xyVisualization: Visualization = { }, getLayerIds(state) { - return state.layers.map(l => l.layerId); + return state.layers.map((l) => l.layerId); }, removeLayer(state, layerId) { return { ...state, - layers: state.layers.filter(l => l.layerId !== layerId), + layers: state.layers.filter((l) => l.layerId !== layerId), }; }, appendLayer(state, layerId) { - const usedSeriesTypes = _.uniq(state.layers.map(layer => layer.seriesType)); + const usedSeriesTypes = _.uniq(state.layers.map((layer) => layer.seriesType)); return { ...state, layers: [ @@ -111,7 +111,7 @@ export const xyVisualization: Visualization = { clearLayer(state, layerId) { return { ...state, - layers: state.layers.map(l => + layers: state.layers.map((l) => l.layerId !== layerId ? l : newLayerState(state.preferredSeriesType, layerId) ), }; @@ -134,7 +134,7 @@ export const xyVisualization: Visualization = { return { ...state, preferredSeriesType: seriesType as SeriesType, - layers: state.layers.map(layer => ({ ...layer, seriesType: seriesType as SeriesType })), + layers: state.layers.map((layer) => ({ ...layer, seriesType: seriesType as SeriesType })), }; }, @@ -159,10 +159,10 @@ export const xyVisualization: Visualization = { ); }, - getPersistableState: state => state, + getPersistableState: (state) => state, getConfiguration(props) { - const layer = props.state.layers.find(l => l.layerId === props.layerId)!; + const layer = props.state.layers.find((l) => l.layerId === props.layerId)!; return { groups: [ { @@ -204,7 +204,7 @@ export const xyVisualization: Visualization = { }, setDimension({ prevState, layerId, columnId, groupId }) { - const newLayer = prevState.layers.find(l => l.layerId === layerId); + const newLayer = prevState.layers.find((l) => l.layerId === layerId); if (!newLayer) { return prevState; } @@ -213,7 +213,7 @@ export const xyVisualization: Visualization = { newLayer.xAccessor = columnId; } if (groupId === 'y') { - newLayer.accessors = [...newLayer.accessors.filter(a => a !== columnId), columnId]; + newLayer.accessors = [...newLayer.accessors.filter((a) => a !== columnId), columnId]; } if (groupId === 'breakdown') { newLayer.splitAccessor = columnId; @@ -221,12 +221,12 @@ export const xyVisualization: Visualization = { return { ...prevState, - layers: prevState.layers.map(l => (l.layerId === layerId ? newLayer : l)), + layers: prevState.layers.map((l) => (l.layerId === layerId ? newLayer : l)), }; }, removeDimension({ prevState, layerId, columnId }) { - const newLayer = prevState.layers.find(l => l.layerId === layerId); + const newLayer = prevState.layers.find((l) => l.layerId === layerId); if (!newLayer) { return prevState; } @@ -236,18 +236,18 @@ export const xyVisualization: Visualization = { } else if (newLayer.splitAccessor === columnId) { delete newLayer.splitAccessor; } else if (newLayer.accessors.includes(columnId)) { - newLayer.accessors = newLayer.accessors.filter(a => a !== columnId); + newLayer.accessors = newLayer.accessors.filter((a) => a !== columnId); } return { ...prevState, - layers: prevState.layers.map(l => (l.layerId === layerId ? newLayer : l)), + layers: prevState.layers.map((l) => (l.layerId === layerId ? newLayer : l)), }; }, getLayerContextMenuIcon({ state, layerId }) { - const layer = state.layers.find(l => l.layerId === layerId); - return visualizationTypes.find(t => t.id === layer?.seriesType)?.icon; + const layer = state.layers.find((l) => l.layerId === layerId); + return visualizationTypes.find((t) => t.id === layer?.seriesType)?.icon; }, renderLayerContextMenu(domElement, props) { diff --git a/x-pack/plugins/lens/server/migrations.ts b/x-pack/plugins/lens/server/migrations.ts index eba7865028645..d24a3e92cbd9c 100644 --- a/x-pack/plugins/lens/server/migrations.ts +++ b/x-pack/plugins/lens/server/migrations.ts @@ -62,7 +62,7 @@ const removeLensAutoDate: SavedObjectMigrationFn = ( } try { const ast = fromExpression(expression); - const newChain: ExpressionFunctionAST[] = ast.chain.map(topNode => { + const newChain: ExpressionFunctionAST[] = ast.chain.map((topNode) => { if (topNode.function !== 'lens_merge_tables') { return topNode; } @@ -70,10 +70,10 @@ const removeLensAutoDate: SavedObjectMigrationFn = ( ...topNode, arguments: { ...topNode.arguments, - tables: (topNode.arguments.tables as Ast[]).map(middleNode => { + tables: (topNode.arguments.tables as Ast[]).map((middleNode) => { return { type: 'expression', - chain: middleNode.chain.map(node => { + chain: middleNode.chain.map((node) => { // Check for sub-expression in aggConfigs if ( node.function === 'esaggs' && @@ -120,7 +120,7 @@ const addTimeFieldToEsaggs: SavedObjectMigrationFn = try { const ast = fromExpression(expression); - const newChain: ExpressionFunctionAST[] = ast.chain.map(topNode => { + const newChain: ExpressionFunctionAST[] = ast.chain.map((topNode) => { if (topNode.function !== 'lens_merge_tables') { return topNode; } @@ -128,10 +128,10 @@ const addTimeFieldToEsaggs: SavedObjectMigrationFn = ...topNode, arguments: { ...topNode.arguments, - tables: (topNode.arguments.tables as Ast[]).map(middleNode => { + tables: (topNode.arguments.tables as Ast[]).map((middleNode) => { return { type: 'expression', - chain: middleNode.chain.map(node => { + chain: middleNode.chain.map((node) => { // Skip if there are any timeField arguments already, because that indicates // the fix is already applied if (node.function !== 'esaggs' || node.arguments.timeFields) { @@ -176,7 +176,7 @@ const addTimeFieldToEsaggs: SavedObjectMigrationFn = const removeInvalidAccessors: SavedObjectMigrationFn< LensDocShape, LensDocShape -> = doc => { +> = (doc) => { const newDoc = cloneDeep(doc); if (newDoc.attributes.visualizationType === 'lnsXY') { const datasourceLayers = newDoc.attributes.state.datasourceStates.indexpattern.layers || {}; @@ -190,7 +190,7 @@ const removeInvalidAccessors: SavedObjectMigrationFn< ...layer, xAccessor: datasource?.columns[layer.xAccessor] ? layer.xAccessor : undefined, splitAccessor: datasource?.columns[layer.splitAccessor] ? layer.splitAccessor : undefined, - accessors: layer.accessors.filter(accessor => !!datasource?.columns[accessor]), + accessors: layer.accessors.filter((accessor) => !!datasource?.columns[accessor]), }; }); } diff --git a/x-pack/plugins/lens/server/routes/existing_fields.test.ts b/x-pack/plugins/lens/server/routes/existing_fields.test.ts index ed1f85ab902f8..33541c7206c53 100644 --- a/x-pack/plugins/lens/server/routes/existing_fields.test.ts +++ b/x-pack/plugins/lens/server/routes/existing_fields.test.ts @@ -143,7 +143,7 @@ describe('buildFieldList', () => { it('uses field descriptors to determine the path', () => { const fields = buildFieldList(indexPattern, mappings, fieldDescriptors); - expect(fields.find(f => f.name === 'baz')).toMatchObject({ + expect(fields.find((f) => f.name === 'baz')).toMatchObject({ isAlias: false, isScript: false, name: 'baz', @@ -153,7 +153,7 @@ describe('buildFieldList', () => { it('uses aliases to determine the path', () => { const fields = buildFieldList(indexPattern, mappings, fieldDescriptors); - expect(fields.find(f => f.isAlias)).toMatchObject({ + expect(fields.find((f) => f.isAlias)).toMatchObject({ isAlias: true, isScript: false, name: '@bar', @@ -163,7 +163,7 @@ describe('buildFieldList', () => { it('supports scripted fields', () => { const fields = buildFieldList(indexPattern, mappings, fieldDescriptors); - expect(fields.find(f => f.isScript)).toMatchObject({ + expect(fields.find((f) => f.isScript)).toMatchObject({ isAlias: false, isScript: true, name: 'foo', diff --git a/x-pack/plugins/lens/server/routes/existing_fields.ts b/x-pack/plugins/lens/server/routes/existing_fields.ts index 3e91d17950061..4edd0d1fa68e8 100644 --- a/x-pack/plugins/lens/server/routes/existing_fields.ts +++ b/x-pack/plugins/lens/server/routes/existing_fields.ts @@ -171,7 +171,7 @@ export function buildFieldList( ): Field[] { const aliasMap = Object.entries(Object.values(mappings)[0].mappings.properties) .map(([name, v]) => ({ ...v, name })) - .filter(f => f.type === 'alias') + .filter((f) => f.type === 'alias') .reduce((acc, f) => { acc[f.name] = f.path; return acc; @@ -236,7 +236,7 @@ async function fetchIndexPatternStats({ }, }; - const scriptedFields = fields.filter(f => f.isScript); + const scriptedFields = fields.filter((f) => f.isScript); const result = await client.callAsCurrentUser('search', { index, body: { @@ -270,18 +270,18 @@ function exists(obj: unknown, path: string[], i = 0): boolean { } if (Array.isArray(obj)) { - return obj.some(child => exists(child, path, i)); + return obj.some((child) => exists(child, path, i)); } if (typeof obj === 'object') { // Because Elasticsearch flattens paths, dots in the field name are allowed // as JSON keys. For example, { 'a.b': 10 } const partialKeyMatches = Object.getOwnPropertyNames(obj) - .map(key => key.split('.')) - .filter(keyPaths => keyPaths.every((key, keyIndex) => key === path[keyIndex + i])); + .map((key) => key.split('.')) + .filter((keyPaths) => keyPaths.every((key, keyIndex) => key === path[keyIndex + i])); if (partialKeyMatches.length) { - return partialKeyMatches.every(keyPaths => { + return partialKeyMatches.every((keyPaths) => { return exists( (obj as Record)[keyPaths.join('.')], path, @@ -310,12 +310,12 @@ export function existingFields( break; } - missingFields.forEach(field => { + missingFields.forEach((field) => { if (exists(field.isScript ? doc.fields : doc._source, field.path)) { missingFields.delete(field); } }); } - return fields.filter(field => !missingFields.has(field)).map(f => f.name); + return fields.filter((field) => !missingFields.has(field)).map((f) => f.name); } diff --git a/x-pack/plugins/lens/server/routes/field_stats.ts b/x-pack/plugins/lens/server/routes/field_stats.ts index 5c91be9dfbd78..d7fcffa034a2a 100644 --- a/x-pack/plugins/lens/server/routes/field_stats.ts +++ b/x-pack/plugins/lens/server/routes/field_stats.ts @@ -149,7 +149,7 @@ export async function getNumberHistogram( const maxValue = minMaxResult.aggregations!.sample.max_value.value; const terms = minMaxResult.aggregations!.sample.top_values; const topValuesBuckets = { - buckets: terms.buckets.map(bucket => ({ + buckets: terms.buckets.map((bucket) => ({ count: bucket.doc_count, key: bucket.key, })), @@ -195,7 +195,7 @@ export async function getNumberHistogram( sampledDocuments: minMaxResult.aggregations!.sample.doc_count, sampledValues: minMaxResult.aggregations!.sample.sample_count.value!, histogram: { - buckets: histogramResult.aggregations!.sample.histo.buckets.map(bucket => ({ + buckets: histogramResult.aggregations!.sample.histo.buckets.map((bucket) => ({ count: bucket.doc_count, key: bucket.key, })), @@ -230,7 +230,7 @@ export async function getStringSamples( sampledDocuments: topValuesResult.aggregations!.sample.doc_count, sampledValues: topValuesResult.aggregations!.sample.sample_count.value!, topValues: { - buckets: topValuesResult.aggregations!.sample.top_values.buckets.map(bucket => ({ + buckets: topValuesResult.aggregations!.sample.top_values.buckets.map((bucket) => ({ count: bucket.doc_count, key: bucket.key, })), @@ -276,7 +276,7 @@ export async function getDateHistogram( return { totalDocuments: results.hits.total, histogram: { - buckets: results.aggregations!.histo.buckets.map(bucket => ({ + buckets: results.aggregations!.histo.buckets.map((bucket) => ({ count: bucket.doc_count, key: bucket.key, })), diff --git a/x-pack/plugins/lens/server/usage/collectors.ts b/x-pack/plugins/lens/server/usage/collectors.ts index 52de0df6fed13..3f033bd3b03d0 100644 --- a/x-pack/plugins/lens/server/usage/collectors.ts +++ b/x-pack/plugins/lens/server/usage/collectors.ts @@ -61,7 +61,7 @@ export function registerLensUsageCollector( } function addEvents(prevEvents: Record, newEvents: Record) { - Object.keys(newEvents).forEach(key => { + Object.keys(newEvents).forEach((key) => { prevEvents[key] = (prevEvents[key] || 0) + newEvents[key]; }); } @@ -88,19 +88,15 @@ async function getLatestTaskState(taskManager: TaskManagerStartContract) { } function getDataByDate(dates: Record>) { - const byDate = Object.keys(dates || {}).map(dateStr => parseInt(dateStr, 10)); + const byDate = Object.keys(dates || {}).map((dateStr) => parseInt(dateStr, 10)); const last30: Record = {}; const last90: Record = {}; - const last30Timestamp = moment() - .subtract(30, 'days') - .unix(); - const last90Timestamp = moment() - .subtract(90, 'days') - .unix(); + const last30Timestamp = moment().subtract(30, 'days').unix(); + const last90Timestamp = moment().subtract(90, 'days').unix(); - byDate.forEach(dateKey => { + byDate.forEach((dateKey) => { if (dateKey >= last30Timestamp) { addEvents(last30, dates[dateKey]); addEvents(last90, dates[dateKey]); diff --git a/x-pack/plugins/lens/server/usage/task.ts b/x-pack/plugins/lens/server/usage/task.ts index e1a0bf20f7b48..5a5d26fa2afde 100644 --- a/x-pack/plugins/lens/server/usage/task.ts +++ b/x-pack/plugins/lens/server/usage/task.ts @@ -140,15 +140,15 @@ export async function getDailyEvents( const byDateByType: Record> = {}; const suggestionsByDate: Record> = {}; - metrics.aggregations!.daily.buckets.forEach(daily => { + metrics.aggregations!.daily.buckets.forEach((daily) => { const byType: Record = byDateByType[daily.key] || {}; - daily.groups.buckets.regularEvents.names.buckets.forEach(bucket => { + daily.groups.buckets.regularEvents.names.buckets.forEach((bucket) => { byType[bucket.key] = (bucket.sums.value || 0) + (byType[daily.key] || 0); }); byDateByType[daily.key] = byType; const suggestionsByType: Record = suggestionsByDate[daily.key] || {}; - daily.groups.buckets.suggestionEvents.names.buckets.forEach(bucket => { + daily.groups.buckets.suggestionEvents.names.buckets.forEach((bucket) => { suggestionsByType[bucket.key] = (bucket.sums.value || 0) + (suggestionsByType[daily.key] || 0); }); @@ -208,7 +208,7 @@ export function telemetryTaskRunner( runAt: getNextMidnight(), }; }) - .catch(errMsg => logger.warn(`Error executing lens telemetry task: ${errMsg}`)); + .catch((errMsg) => logger.warn(`Error executing lens telemetry task: ${errMsg}`)); }, async cancel() {}, }; @@ -216,8 +216,5 @@ export function telemetryTaskRunner( } function getNextMidnight() { - return moment() - .add(1, 'day') - .startOf('day') - .toDate(); + return moment().add(1, 'day').startOf('day').toDate(); } diff --git a/x-pack/plugins/license_management/__mocks__/focus-trap-react.js b/x-pack/plugins/license_management/__mocks__/focus-trap-react.js index 6cc385e871b47..2e243aceccb15 100644 --- a/x-pack/plugins/license_management/__mocks__/focus-trap-react.js +++ b/x-pack/plugins/license_management/__mocks__/focus-trap-react.js @@ -6,4 +6,4 @@ import React from 'react'; -export default props =>
{props.children}
; +export default (props) =>
{props.children}
; diff --git a/x-pack/plugins/license_management/public/application/app.container.js b/x-pack/plugins/license_management/public/application/app.container.js index 248f4f63027c9..0c67cc636edd7 100644 --- a/x-pack/plugins/license_management/public/application/app.container.js +++ b/x-pack/plugins/license_management/public/application/app.container.js @@ -15,7 +15,7 @@ import { } from './store/reducers/license_management'; import { loadPermissions } from './store/actions/permissions'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { return { hasPermission: getPermission(state), permissionsLoading: isPermissionsLoading(state), diff --git a/x-pack/plugins/license_management/public/application/app.js b/x-pack/plugins/license_management/public/application/app.js index 1bc8e9cd563e2..46d0da5252ceb 100644 --- a/x-pack/plugins/license_management/public/application/app.js +++ b/x-pack/plugins/license_management/public/application/app.js @@ -85,7 +85,7 @@ export class App extends Component { ); } - const withTelemetry = Component => props => ; + const withTelemetry = (Component) => (props) => ; return ( diff --git a/x-pack/plugins/license_management/public/application/sections/license_dashboard/license_status/license_status.container.js b/x-pack/plugins/license_management/public/application/sections/license_dashboard/license_status/license_status.container.js index 696c53fc9ca6b..3425fe0339dc4 100644 --- a/x-pack/plugins/license_management/public/application/sections/license_dashboard/license_status/license_status.container.js +++ b/x-pack/plugins/license_management/public/application/sections/license_dashboard/license_status/license_status.container.js @@ -13,7 +13,7 @@ import { } from '../../../store/reducers/license_management'; import { i18n } from '@kbn/i18n'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { const { isActive, type } = getLicense(state); return { status: isActive diff --git a/x-pack/plugins/license_management/public/application/sections/license_dashboard/request_trial_extension/request_trial_extension.container.js b/x-pack/plugins/license_management/public/application/sections/license_dashboard/request_trial_extension/request_trial_extension.container.js index 580e8de0b304b..517cf9bb36a46 100644 --- a/x-pack/plugins/license_management/public/application/sections/license_dashboard/request_trial_extension/request_trial_extension.container.js +++ b/x-pack/plugins/license_management/public/application/sections/license_dashboard/request_trial_extension/request_trial_extension.container.js @@ -9,7 +9,7 @@ import { connect } from 'react-redux'; import { RequestTrialExtension as PresentationComponent } from './request_trial_extension'; import { shouldShowRequestTrialExtension } from '../../../store/reducers/license_management'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { return { shouldShowRequestTrialExtension: shouldShowRequestTrialExtension(state), }; diff --git a/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.container.js b/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.container.js index f171ce8ecf353..4e0c40bf9eb6b 100644 --- a/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.container.js +++ b/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.container.js @@ -15,7 +15,7 @@ import { } from '../../../store/reducers/license_management'; import { startBasicLicense, cancelStartBasicLicense } from '../../../store/actions/start_basic'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { return { shouldShowRevertToBasicLicense: shouldShowRevertToBasicLicense(state), licenseType: getLicenseType(state), diff --git a/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.js b/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.js index 2424e336fe6e6..a1a46d8616554 100644 --- a/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.js +++ b/x-pack/plugins/license_management/public/application/sections/license_dashboard/revert_to_basic/revert_to_basic.js @@ -62,7 +62,7 @@ export class RevertToBasic extends React.PureComponent { {firstLine}
    - {messages.map(message => ( + {messages.map((message) => (
  • {message}
  • ))}
diff --git a/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.container.js b/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.container.js index 7f95ba55db150..61fae1e49afe6 100644 --- a/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.container.js +++ b/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.container.js @@ -10,7 +10,7 @@ import { StartTrial as PresentationComponent } from './start_trial'; import { loadTrialStatus, startLicenseTrial } from '../../../store/actions/start_trial'; import { shouldShowStartTrial } from '../../../store/reducers/license_management'; -const mapStateToProps = state => { +const mapStateToProps = (state) => { return { shouldShowStartTrial: shouldShowStartTrial(state), }; diff --git a/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.tsx b/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.tsx index 25cbfb7242239..627eb0425c6d7 100644 --- a/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.tsx +++ b/x-pack/plugins/license_management/public/application/sections/license_dashboard/start_trial/start_trial.tsx @@ -266,7 +266,7 @@ export class StartTrial extends Component { ); return ( - {dependencies => ( + {(dependencies) => ( {this.acknowledgeModal(dependencies!.docLinks)} { +const mapStateToProps = (state) => { return { isInvalid: isInvalid(state), needsAcknowledgement: uploadNeedsAcknowledgement(state), diff --git a/x-pack/plugins/license_management/public/application/sections/upload_license/upload_license.js b/x-pack/plugins/license_management/public/application/sections/upload_license/upload_license.js index 49f2474f83911..95ada7ed2b1df 100644 --- a/x-pack/plugins/license_management/public/application/sections/upload_license/upload_license.js +++ b/x-pack/plugins/license_management/public/application/sections/upload_license/upload_license.js @@ -34,10 +34,10 @@ export class UploadLicense extends React.PureComponent { this.props.setBreadcrumb('upload'); this.props.addUploadErrorMessage(''); } - onOptInChange = isOptingInToTelemetry => { + onOptInChange = (isOptingInToTelemetry) => { this.setState({ isOptingInToTelemetry }); }; - send = acknowledge => { + send = (acknowledge) => { const file = this.file; const fr = new FileReader(); @@ -87,7 +87,7 @@ export class UploadLicense extends React.PureComponent { {firstLine}
    - {messages.map(message => ( + {messages.map((message) => (
  • {message}
  • ))}
@@ -110,7 +110,7 @@ export class UploadLicense extends React.PureComponent { } this.file = file; }; - submit = event => { + submit = (event) => { event.preventDefault(); if (this.file) { this.send(); diff --git a/x-pack/plugins/license_management/public/application/store/actions/start_basic.js b/x-pack/plugins/license_management/public/application/store/actions/start_basic.js index 93c722c1f8968..5ae93bf84c2f8 100644 --- a/x-pack/plugins/license_management/public/application/store/actions/start_basic.js +++ b/x-pack/plugins/license_management/public/application/store/actions/start_basic.js @@ -38,7 +38,7 @@ export const startBasicLicense = (currentLicenseType, ack) => async ( //messages coming back in arrays const messages = Object.values(acknowledge) .slice(1) - .map(item => { + .map((item) => { return item[0]; }); const first = i18n.translate( diff --git a/x-pack/plugins/license_management/public/application/store/reducers/license_management.js b/x-pack/plugins/license_management/public/application/store/reducers/license_management.js index c821b7bb294f9..ca7e51b106951 100644 --- a/x-pack/plugins/license_management/public/application/store/reducers/license_management.js +++ b/x-pack/plugins/license_management/public/application/store/reducers/license_management.js @@ -24,31 +24,31 @@ export const licenseManagement = combineReducers({ permissions, }); -export const getPermission = state => { +export const getPermission = (state) => { return state.permissions.hasPermission; }; -export const isPermissionsLoading = state => { +export const isPermissionsLoading = (state) => { return state.permissions.loading; }; -export const getPermissionsError = state => { +export const getPermissionsError = (state) => { return state.permissions.error; }; -export const getLicense = state => { +export const getLicense = (state) => { return state.license; }; -export const getLicenseType = state => { +export const getLicenseType = (state) => { return getLicense(state).type; }; -export const getExpirationMillis = state => { +export const getExpirationMillis = (state) => { return getLicense(state).expiryDateInMillis; }; -export const getExpirationDate = state => { +export const getExpirationDate = (state) => { //basic licenses do not expire if (getLicenseType(state) === 'basic') { return null; @@ -61,16 +61,16 @@ export const getExpirationDate = state => { } }; -export const getExpirationDateFormatted = state => { +export const getExpirationDateFormatted = (state) => { const expirationDate = getExpirationDate(state); return expirationDate ? expirationDate.format('LLL z') : null; }; -export const isExpired = state => { +export const isExpired = (state) => { return new Date().getTime() > getExpirationMillis(state); }; -export const isImminentExpiration = state => { +export const isImminentExpiration = (state) => { const now = new Date(); const expirationDate = getExpirationDate(state); return ( @@ -80,32 +80,32 @@ export const isImminentExpiration = state => { ); }; -export const shouldShowRevertToBasicLicense = state => { +export const shouldShowRevertToBasicLicense = (state) => { const { type } = getLicense(state); return type === 'trial' || isImminentExpiration(state) || isExpired(state); }; -export const uploadNeedsAcknowledgement = state => { +export const uploadNeedsAcknowledgement = (state) => { return !!state.uploadStatus.acknowledge; }; -export const isApplying = state => { +export const isApplying = (state) => { return !!state.uploadStatus.applying; }; -export const uploadMessages = state => { +export const uploadMessages = (state) => { return state.uploadStatus.messages; }; -export const isInvalid = state => { +export const isInvalid = (state) => { return !!state.uploadStatus.invalid; }; -export const getUploadErrorMessage = state => { +export const getUploadErrorMessage = (state) => { return state.uploadErrorMessage; }; -export const shouldShowStartTrial = state => { +export const shouldShowStartTrial = (state) => { const licenseType = getLicenseType(state); return ( state.trialStatus.canStartTrial && @@ -115,7 +115,7 @@ export const shouldShowStartTrial = state => { ); }; -export const shouldShowRequestTrialExtension = state => { +export const shouldShowRequestTrialExtension = (state) => { if (state.trialStatus.canStartTrial) { return false; } @@ -123,14 +123,14 @@ export const shouldShowRequestTrialExtension = state => { return (type !== 'platinum' && type !== 'enterprise') || isExpired(state); }; -export const startTrialError = state => { +export const startTrialError = (state) => { return state.trialStatus.startTrialError; }; -export const startBasicLicenseNeedsAcknowledgement = state => { +export const startBasicLicenseNeedsAcknowledgement = (state) => { return !!state.startBasicStatus.acknowledge; }; -export const getStartBasicMessages = state => { +export const getStartBasicMessages = (state) => { return state.startBasicStatus.messages; }; diff --git a/x-pack/plugins/licensing/common/license_update.test.ts b/x-pack/plugins/licensing/common/license_update.test.ts index 7e2410913f698..b0209e0717da2 100644 --- a/x-pack/plugins/licensing/common/license_update.test.ts +++ b/x-pack/plugins/licensing/common/license_update.test.ts @@ -11,7 +11,7 @@ import { ILicense } from './types'; import { createLicenseUpdate } from './license_update'; import { licenseMock } from './licensing.mock'; -const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const stop$ = new Subject(); describe('licensing update', () => { it('loads updates when triggered', async () => { @@ -94,7 +94,7 @@ describe('licensing update', () => { let firstCall = true; const fetcher = jest.fn().mockImplementation( () => - new Promise(resolve => { + new Promise((resolve) => { if (firstCall) { firstCall = false; setTimeout(() => resolve(licenseMock.createLicense()), delayMs); @@ -106,7 +106,7 @@ describe('licensing update', () => { const trigger$ = new Subject(); const { license$ } = createLicenseUpdate(trigger$, stop$, fetcher); const values: ILicense[] = []; - license$.subscribe(license => values.push(license)); + license$.subscribe((license) => values.push(license)); trigger$.next(); trigger$.next(); @@ -136,7 +136,7 @@ describe('licensing update', () => { const { license$ } = createLicenseUpdate(trigger$, stop$, fetcher); const values: ILicense[] = []; - license$.subscribe(license => values.push(license)); + license$.subscribe((license) => values.push(license)); stop$.next(); trigger$.next(); @@ -162,7 +162,7 @@ describe('licensing update', () => { const { license$, refreshManually } = createLicenseUpdate(trigger$, stop$, fetcher); let fromObservable; - license$.subscribe(license => (fromObservable = license)); + license$.subscribe((license) => (fromObservable = license)); const licenseResult = await refreshManually(); expect(licenseResult.uid).toBe('first'); diff --git a/x-pack/plugins/licensing/public/expired_banner.tsx b/x-pack/plugins/licensing/public/expired_banner.tsx index 9c42d3ff6997d..b261bfa9f345f 100644 --- a/x-pack/plugins/licensing/public/expired_banner.tsx +++ b/x-pack/plugins/licensing/public/expired_banner.tsx @@ -14,7 +14,7 @@ interface Props { uploadUrl: string; } -const ExpiredBanner: React.FunctionComponent = props => ( +const ExpiredBanner: React.FunctionComponent = (props) => ( { const { license$, refresh } = await plugin.setup(coreSetup); let fromObservable; - license$.subscribe(license => (fromObservable = license)); + license$.subscribe((license) => (fromObservable = license)); const licenseResult = await refresh(); expect(licenseResult.uid).toBe('first'); @@ -88,7 +88,7 @@ describe('licensing plugin', () => { expect(sessionStorage.getItem).toHaveBeenCalledWith(licensingSessionStorageKey); }); - it('observable receives updated licenses', async done => { + it('observable receives updated licenses', async (done) => { const types: LicenseType[] = ['gold', 'platinum']; const sessionStorage = coreMock.createStorage(); @@ -102,7 +102,7 @@ describe('licensing plugin', () => { const { license$, refresh } = await plugin.setup(coreSetup); let i = 0; - license$.subscribe(value => { + license$.subscribe((value) => { i++; if (i === 1) { expect(value.type).toBe('basic'); diff --git a/x-pack/plugins/licensing/public/plugin.ts b/x-pack/plugins/licensing/public/plugin.ts index 31910d81b3434..6435f3b17313c 100644 --- a/x-pack/plugins/licensing/public/plugin.ts +++ b/x-pack/plugins/licensing/public/plugin.ts @@ -75,7 +75,7 @@ export class LicensingPlugin implements Plugin { this.getSaved() ); - this.internalSubscription = license$.subscribe(license => { + this.internalSubscription = license$.subscribe((license) => { if (license.isAvailable) { this.prevSignature = license.signature; this.save(license); @@ -92,7 +92,7 @@ export class LicensingPlugin implements Plugin { }); this.removeInterceptor = core.http.intercept({ - response: async httpResponse => { + response: async (httpResponse) => { // we don't track license as anon users do not have one. if (core.http.anonymousPaths.isAnonymous(window.location.pathname)) return httpResponse; if (httpResponse.response) { diff --git a/x-pack/plugins/licensing/server/on_pre_response_handler.test.ts b/x-pack/plugins/licensing/server/on_pre_response_handler.test.ts index 9a588a9ac8460..5c768a00783a8 100644 --- a/x-pack/plugins/licensing/server/on_pre_response_handler.test.ts +++ b/x-pack/plugins/licensing/server/on_pre_response_handler.test.ts @@ -30,7 +30,7 @@ describe('createOnPreResponseHandler', () => { const license$ = new BehaviorSubject(licenseMock.createLicense({ signature: 'foo' })); const refresh = jest.fn().mockImplementation( () => - new Promise(resolve => { + new Promise((resolve) => { setTimeout(() => { license$.next(updatedLicense); resolve(); diff --git a/x-pack/plugins/licensing/server/plugin.test.ts b/x-pack/plugins/licensing/server/plugin.test.ts index c9fbb61e6cc19..1dacc9406004a 100644 --- a/x-pack/plugins/licensing/server/plugin.test.ts +++ b/x-pack/plugins/licensing/server/plugin.test.ts @@ -26,7 +26,7 @@ function buildRawLicense(options: Partial = {}): RawLicense { return Object.assign(defaultRawLicense, options); } -const flushPromises = (ms = 50) => new Promise(res => setTimeout(res, ms)); +const flushPromises = (ms = 50) => new Promise((res) => setTimeout(res, ms)); describe('licensing plugin', () => { describe('#setup', () => { diff --git a/x-pack/plugins/licensing/server/plugin.ts b/x-pack/plugins/licensing/server/plugin.ts index ee43ac0ce233c..51e778ba0aa46 100644 --- a/x-pack/plugins/licensing/server/plugin.ts +++ b/x-pack/plugins/licensing/server/plugin.ts @@ -123,7 +123,7 @@ export class LicensingPlugin implements Plugin + this.loggingSubscription = license$.subscribe((license) => this.logger.debug( 'Imported license information from Elasticsearch:' + [ diff --git a/x-pack/plugins/licensing/server/services/feature_usage_service.ts b/x-pack/plugins/licensing/server/services/feature_usage_service.ts index 47ffe3a3d9f54..0c6613d37f63a 100644 --- a/x-pack/plugins/licensing/server/services/feature_usage_service.ts +++ b/x-pack/plugins/licensing/server/services/feature_usage_service.ts @@ -36,7 +36,7 @@ export class FeatureUsageService { public setup(): FeatureUsageServiceSetup { return { - register: featureName => { + register: (featureName) => { if (this.features.includes(featureName)) { throw new Error(`Feature '${featureName}' has already been registered.`); } diff --git a/x-pack/plugins/lists/server/create_config.ts b/x-pack/plugins/lists/server/create_config.ts index 3158fabda935f..7e2e639ce7a35 100644 --- a/x-pack/plugins/lists/server/create_config.ts +++ b/x-pack/plugins/lists/server/create_config.ts @@ -12,10 +12,12 @@ import { ConfigType } from './config'; export const createConfig$ = ( context: PluginInitializerContext -): Observable> => { - return context.config.create().pipe(map(config => config)); +): Observable< + Readonly<{ + enabled: boolean; + listIndex: string; + listItemIndex: string; + }> +> => { + return context.config.create().pipe(map((config) => config)); }; diff --git a/x-pack/plugins/lists/server/plugin.ts b/x-pack/plugins/lists/server/plugin.ts index ed515757875be..dbda144239927 100644 --- a/x-pack/plugins/lists/server/plugin.ts +++ b/x-pack/plugins/lists/server/plugin.ts @@ -39,9 +39,7 @@ export class ListPlugin } public async setup(core: CoreSetup, plugins: PluginsSetup): Promise { - const config = await createConfig$(this.initializerContext) - .pipe(first()) - .toPromise(); + const config = await createConfig$(this.initializerContext).pipe(first()).toPromise(); this.logger.error( 'You have activated the lists values feature flag which is NOT currently supported for Elastic Security! You should turn this feature flag off immediately by un-setting "xpack.lists.enabled: true" in kibana.yml and restarting Kibana' diff --git a/x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_items_by_list.ts b/x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_items_by_list.ts index 8031f085c1635..31bf1ffacbbb2 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_items_by_list.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/delete_exception_list_items_by_list.ts @@ -46,7 +46,10 @@ export const getExceptionListItemIds = async ({ sortOrder: 'desc', }); while (foundExceptionListItems != null && foundExceptionListItems.data.length > 0) { - ids = [...ids, ...foundExceptionListItems.data.map(exceptionListItem => exceptionListItem.id)]; + ids = [ + ...ids, + ...foundExceptionListItems.data.map((exceptionListItem) => exceptionListItem.id), + ]; page += 1; foundExceptionListItems = await findExceptionListItem({ filter: undefined, @@ -76,7 +79,7 @@ export const deleteFoundExceptionListItems = async ({ namespaceType: NamespaceType; }): Promise => { const savedObjectType = getSavedObjectType({ namespaceType }); - ids.forEach(async id => { + ids.forEach(async (id) => { try { await savedObjectsClient.delete(savedObjectType, id); } catch (err) { diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils.ts b/x-pack/plugins/lists/server/services/exception_lists/utils.ts index 505ebc43afc5a..28dfb9c1cddaf 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/utils.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/utils.ts @@ -210,7 +210,7 @@ export const transformSavedObjectsToFounExceptionListItem = ({ savedObjectsFindResponse: SavedObjectsFindResponse; }): FoundExceptionListItemSchema => { return { - data: savedObjectsFindResponse.saved_objects.map(savedObject => + data: savedObjectsFindResponse.saved_objects.map((savedObject) => transformSavedObjectToExceptionListItem({ savedObject }) ), page: savedObjectsFindResponse.page, @@ -225,7 +225,7 @@ export const transformSavedObjectsToFounExceptionList = ({ savedObjectsFindResponse: SavedObjectsFindResponse; }): FoundExceptionListSchema => { return { - data: savedObjectsFindResponse.saved_objects.map(savedObject => + data: savedObjectsFindResponse.saved_objects.map((savedObject) => transformSavedObjectToExceptionList({ savedObject }) ), page: savedObjectsFindResponse.page, diff --git a/x-pack/plugins/lists/server/services/items/buffer_lines.test.ts b/x-pack/plugins/lists/server/services/items/buffer_lines.test.ts index 50e690a3185a8..9413bf9a3d84e 100644 --- a/x-pack/plugins/lists/server/services/items/buffer_lines.test.ts +++ b/x-pack/plugins/lists/server/services/items/buffer_lines.test.ts @@ -9,7 +9,7 @@ import { TestReadable } from '../../../common/test_readable.mock'; import { BufferLines } from './buffer_lines'; describe('buffer_lines', () => { - test('it can read a single line', done => { + test('it can read a single line', (done) => { const input = new TestReadable(); input.push('line one\n'); input.push(null); @@ -24,7 +24,7 @@ describe('buffer_lines', () => { }); }); - test('it can read two lines', done => { + test('it can read two lines', (done) => { const input = new TestReadable(); input.push('line one\n'); input.push('line two\n'); @@ -40,7 +40,7 @@ describe('buffer_lines', () => { }); }); - test('two identical lines are collapsed into just one line without duplicates', done => { + test('two identical lines are collapsed into just one line without duplicates', (done) => { const input = new TestReadable(); input.push('line one\n'); input.push('line one\n'); @@ -56,7 +56,7 @@ describe('buffer_lines', () => { }); }); - test('it can close out without writing any lines', done => { + test('it can close out without writing any lines', (done) => { const input = new TestReadable(); input.push(null); const bufferedLine = new BufferLines({ input }); @@ -70,12 +70,12 @@ describe('buffer_lines', () => { }); }); - test('it can read 200 lines', done => { + test('it can read 200 lines', (done) => { const input = new TestReadable(); const bufferedLine = new BufferLines({ input }); let linesToTest: string[] = []; const size200: string[] = new Array(200).fill(null).map((_, index) => `${index}\n`); - size200.forEach(element => input.push(element)); + size200.forEach((element) => input.push(element)); input.push(null); bufferedLine.on('lines', (lines: string[]) => { linesToTest = [...linesToTest, ...lines]; diff --git a/x-pack/plugins/lists/server/services/items/buffer_lines.ts b/x-pack/plugins/lists/server/services/items/buffer_lines.ts index fd8fe7077fd58..4ff84268f5e0c 100644 --- a/x-pack/plugins/lists/server/services/items/buffer_lines.ts +++ b/x-pack/plugins/lists/server/services/items/buffer_lines.ts @@ -17,7 +17,7 @@ export class BufferLines extends Readable { input, }); - readline.on('line', line => { + readline.on('line', (line) => { this.push(line); }); diff --git a/x-pack/plugins/lists/server/services/items/delete_list_item_by_value.ts b/x-pack/plugins/lists/server/services/items/delete_list_item_by_value.ts index ec29f14a0ff64..57aced5f3701c 100644 --- a/x-pack/plugins/lists/server/services/items/delete_list_item_by_value.ts +++ b/x-pack/plugins/lists/server/services/items/delete_list_item_by_value.ts @@ -33,7 +33,7 @@ export const deleteListItemByValue = async ({ type, value: [value], }); - const values = listItems.map(listItem => listItem.value); + const values = listItems.map((listItem) => listItem.value); const filter = getQueryFilterFromTypeValue({ listId, type, diff --git a/x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts b/x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts index 542c2bb12d8e5..b309779962889 100644 --- a/x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts +++ b/x-pack/plugins/lists/server/services/items/write_lines_to_bulk_list_items.ts @@ -33,7 +33,7 @@ export const importListItemsToStream = ({ user, meta, }: ImportListItemsToStreamOptions): Promise => { - return new Promise(resolve => { + return new Promise((resolve) => { const readBuffer = new BufferLines({ input: stream }); readBuffer.on('lines', async (lines: string[]) => { await writeBufferToItems({ @@ -85,7 +85,7 @@ export const writeBufferToItems = async ({ value: buffer, }); const duplicatesRemoved = buffer.filter( - bufferedValue => !items.some(item => item.value === bufferedValue) + (bufferedValue) => !items.some((item) => item.value === bufferedValue) ); const linesProcessed = duplicatesRemoved.length; const duplicatesFound = buffer.length - duplicatesRemoved.length; diff --git a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.test.ts b/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.test.ts index 2f04353e0989b..b1ab0dc2ad613 100644 --- a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.test.ts +++ b/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.test.ts @@ -33,7 +33,7 @@ describe('write_list_items_to_stream', () => { }); describe('exportListItemsToStream', () => { - test('It exports empty list items to the stream as an empty array', done => { + test('It exports empty list items to the stream as an empty array', (done) => { const options = getExportListItemsToStreamOptionsMock(); const firstResponse = getSearchListItemMock(); firstResponse.hits.hits = []; @@ -51,7 +51,7 @@ describe('write_list_items_to_stream', () => { }); }); - test('It exports single list item to the stream', done => { + test('It exports single list item to the stream', (done) => { const options = getExportListItemsToStreamOptionsMock(); exportListItemsToStream(options); @@ -66,7 +66,7 @@ describe('write_list_items_to_stream', () => { }); }); - test('It exports two list items to the stream', done => { + test('It exports two list items to the stream', (done) => { const options = getExportListItemsToStreamOptionsMock(); const firstResponse = getSearchListItemMock(); const secondResponse = getSearchListItemMock(); @@ -85,7 +85,7 @@ describe('write_list_items_to_stream', () => { }); }); - test('It exports two list items to the stream with two separate calls', done => { + test('It exports two list items to the stream with two separate calls', (done) => { const options = getExportListItemsToStreamOptionsMock(); const firstResponse = getSearchListItemMock(); @@ -209,7 +209,7 @@ describe('write_list_items_to_stream', () => { }); describe('writeResponseHitsToStream', () => { - test('it will push into the stream the mock response', done => { + test('it will push into the stream the mock response', (done) => { const options = getWriteResponseHitsToStreamOptionsMock(); writeResponseHitsToStream(options); @@ -224,7 +224,7 @@ describe('write_list_items_to_stream', () => { }); }); - test('it will push into the stream an empty mock response', done => { + test('it will push into the stream an empty mock response', (done) => { const options = getWriteResponseHitsToStreamOptionsMock(); options.response.hits.hits = []; writeResponseHitsToStream(options); @@ -241,7 +241,7 @@ describe('write_list_items_to_stream', () => { options.stream.end(); }); - test('it will push into the stream 2 mock responses', done => { + test('it will push into the stream 2 mock responses', (done) => { const options = getWriteResponseHitsToStreamOptionsMock(); const secondResponse = getSearchListItemMock(); options.response.hits.hits = [...options.response.hits.hits, ...secondResponse.hits.hits]; @@ -258,7 +258,7 @@ describe('write_list_items_to_stream', () => { }); }); - test('it will push an additional string given to it such as a new line character', done => { + test('it will push an additional string given to it such as a new line character', (done) => { const options = getWriteResponseHitsToStreamOptionsMock(); const secondResponse = getSearchListItemMock(); options.response.hits.hits = [...options.response.hits.hits, ...secondResponse.hits.hits]; diff --git a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts b/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts index b81e4a4fc73c2..10d8581ccdbc0 100644 --- a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts +++ b/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts @@ -143,7 +143,7 @@ export const writeResponseHitsToStream = ({ }: WriteResponseHitsToStreamOptions): void => { const stringToAppendOrEmpty = stringToAppend ?? ''; - response.hits.hits.forEach(hit => { + response.hits.hits.forEach((hit) => { if (hit._source.ip != null) { stream.push(`${hit._source.ip}${stringToAppendOrEmpty}`); } else if (hit._source.keyword != null) { diff --git a/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts b/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts index 2dc0f4fe7a821..f150a29c524a5 100644 --- a/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts +++ b/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts @@ -18,7 +18,7 @@ export const transformElasticToListItem = ({ response, type, }: TransformElasticToListItemOptions): ListItemArraySchema => { - return response.hits.hits.map(hit => { + return response.hits.hits.map((hit) => { const { _id, _source: { diff --git a/x-pack/plugins/logstash/public/application/components/pipeline_editor/pipeline_editor.js b/x-pack/plugins/logstash/public/application/components/pipeline_editor/pipeline_editor.js index e45820d56cc03..694e50cfe3e36 100644 --- a/x-pack/plugins/logstash/public/application/components/pipeline_editor/pipeline_editor.js +++ b/x-pack/plugins/logstash/public/application/components/pipeline_editor/pipeline_editor.js @@ -157,7 +157,7 @@ class PipelineEditorUi extends React.Component { }); }; - onPipelineChange = e => { + onPipelineChange = (e) => { this.setState({ pipeline: { ...this.state.pipeline, @@ -171,12 +171,12 @@ class PipelineEditorUi extends React.Component { this.handleSettingChange(settingName, isNaN(numberValue) ? value : numberValue); }; - handleMaxByteNumberChange = value => { + handleMaxByteNumberChange = (value) => { this.setState({ maxBytesNumber: parseInt(value, 10) }); this.handleSettingChange('queue.max_bytes', value + this.state.maxBytesUnit); }; - handleMaxByteUnitChange = value => { + handleMaxByteUnitChange = (value) => { this.setState({ maxBytesUnit: value }); this.handleSettingChange('queue.max_bytes', this.state.maxBytesNumber + value); }; @@ -192,7 +192,7 @@ class PipelineEditorUi extends React.Component { }); }; - notifyOnError = err => { + notifyOnError = (err) => { const { licenseService, toastNotifications } = this.props; return licenseService.checkValidity().then(() => { @@ -356,7 +356,7 @@ class PipelineEditorUi extends React.Component { > this.handleNumberChange('pipeline.workers', e.target.value)} + onChange={(e) => this.handleNumberChange('pipeline.workers', e.target.value)} value={this.state.pipeline.settings['pipeline.workers']} /> @@ -371,7 +371,7 @@ class PipelineEditorUi extends React.Component { > this.handleNumberChange('pipeline.batch.size', e.target.value)} + onChange={(e) => this.handleNumberChange('pipeline.batch.size', e.target.value)} value={this.state.pipeline.settings['pipeline.batch.size']} /> @@ -384,7 +384,7 @@ class PipelineEditorUi extends React.Component { > this.handleNumberChange('pipeline.batch.delay', e.target.value)} + onChange={(e) => this.handleNumberChange('pipeline.batch.delay', e.target.value)} value={this.state.pipeline.settings['pipeline.batch.delay']} /> @@ -399,7 +399,7 @@ class PipelineEditorUi extends React.Component { > this.handleSettingChange('queue.type', e.target.value)} + onChange={(e) => this.handleSettingChange('queue.type', e.target.value)} options={PIPELINE_EDITOR.QUEUE_TYPES} value={this.state.pipeline.settings['queue.type']} /> @@ -413,14 +413,14 @@ class PipelineEditorUi extends React.Component { > this.handleMaxByteNumberChange(e.target.value)} + onChange={(e) => this.handleMaxByteNumberChange(e.target.value)} value={this.state.maxBytesNumber} /> this.handleMaxByteUnitChange(e.target.value)} + onChange={(e) => this.handleMaxByteUnitChange(e.target.value)} options={PIPELINE_EDITOR.UNITS} value={this.state.maxBytesUnit} /> @@ -434,7 +434,9 @@ class PipelineEditorUi extends React.Component { > this.handleNumberChange('queue.checkpoint.writes', e.target.value)} + onChange={(e) => + this.handleNumberChange('queue.checkpoint.writes', e.target.value) + } value={this.state.pipeline.settings['queue.checkpoint.writes']} /> diff --git a/x-pack/plugins/logstash/public/application/components/pipeline_list/confirm_delete_modal.test.js b/x-pack/plugins/logstash/public/application/components/pipeline_list/confirm_delete_modal.test.js index a5052edf03403..bbf91f2c0b957 100644 --- a/x-pack/plugins/logstash/public/application/components/pipeline_list/confirm_delete_modal.test.js +++ b/x-pack/plugins/logstash/public/application/components/pipeline_list/confirm_delete_modal.test.js @@ -36,19 +36,13 @@ describe('ConfirmDeleteModal component', () => { it('calls cancel delete', () => { const wrapper = mountWithIntl(); - wrapper - .find('[data-test-subj="confirmModalCancelButton"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="confirmModalCancelButton"]').first().simulate('click'); expect(props.cancelDeletePipelines).toHaveBeenCalled(); }); it('calls deleteSelectedPipelines', () => { const wrapper = mountWithIntl(); - wrapper - .find('[data-test-subj="confirmModalConfirmButton"]') - .first() - .simulate('click'); + wrapper.find('[data-test-subj="confirmModalConfirmButton"]').first().simulate('click'); expect(props.deleteSelectedPipelines).toHaveBeenCalled(); }); diff --git a/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.js b/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.js index bf67c70547bf2..d5ef224e2b81d 100644 --- a/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.js +++ b/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.js @@ -108,7 +108,7 @@ class PipelineListUi extends React.Component { return pipelinesService .getPipelineList() - .then(pipelines => { + .then((pipelines) => { this.setState({ isLoading: false, isForbidden: false, @@ -124,7 +124,7 @@ class PipelineListUi extends React.Component { }); } }) - .catch(err => { + .catch((err) => { this.setState({ isLoading: false, message: this.getErrorPrompt(), @@ -159,7 +159,7 @@ class PipelineListUi extends React.Component { checkMonitoringAccess = () => { const { clusterService, monitoringService } = this.props; - clusterService.isClusterInfoAvailable().then(isAvailable => { + clusterService.isClusterInfoAvailable().then((isAvailable) => { this.setState({ showAddRoleAlert: !isAvailable, showEnableMonitoringAlert: !monitoringService.isMonitoringEnabled(), @@ -215,7 +215,7 @@ class PipelineListUi extends React.Component { const pipelineIds = selection.map(({ id }) => id); return pipelinesService .deletePipelines(pipelineIds) - .then(results => { + .then((results) => { const { numSuccesses, numErrors } = results; if (numSuccesses === 1 && numErrors === 0) { @@ -276,7 +276,7 @@ class PipelineListUi extends React.Component { this.loadPipelines(); }) - .catch(err => { + .catch((err) => { return licenseService.checkValidity().then(() => toastNotifications.addDanger(err)); }); }; @@ -285,7 +285,7 @@ class PipelineListUi extends React.Component { this.showDeletePipelinesModal(); }; - onSelectionChange = selection => this.setState({ selection }); + onSelectionChange = (selection) => this.setState({ selection }); render() { const { clonePipeline, createPipeline, isReadOnly, openPipeline } = this.props; diff --git a/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.test.js b/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.test.js index db0b1375c604d..019cd29f7a017 100644 --- a/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.test.js +++ b/x-pack/plugins/logstash/public/application/components/pipeline_list/pipeline_list.test.js @@ -19,9 +19,9 @@ describe('PipelineList component', () => { const getGetPipelineList = (isSuccess, result) => isSuccess ? () => Promise.resolve(result) : () => Promise.reject(result); - const getIsClusterInfoAvailable = isAvailable => () => Promise.resolve(isAvailable); + const getIsClusterInfoAvailable = (isAvailable) => () => Promise.resolve(isAvailable); - const getDeleteSelectedPipelines = isSuccess => + const getDeleteSelectedPipelines = (isSuccess) => isSuccess ? () => Promise.resolve({}) : () => Promise.reject({}); beforeEach(() => { diff --git a/x-pack/plugins/logstash/public/application/components/pipeline_list/pipelines_table.js b/x-pack/plugins/logstash/public/application/components/pipeline_list/pipelines_table.js index 9f59a6b7c8abc..b40cc3541eed0 100644 --- a/x-pack/plugins/logstash/public/application/components/pipeline_list/pipelines_table.js +++ b/x-pack/plugins/logstash/public/application/components/pipeline_list/pipelines_table.js @@ -38,7 +38,7 @@ function getColumns(openPipeline, clonePipeline) { name: i18n.translate('xpack.logstash.pipelinesTable.descriptionColumnLabel', { defaultMessage: 'Description', }), - render: description => {description}, + render: (description) => {description}, sortable: true, truncateText: true, }, @@ -47,7 +47,7 @@ function getColumns(openPipeline, clonePipeline) { name: i18n.translate('xpack.logstash.pipelinesTable.lastModifiedColumnLabel', { defaultMessage: 'Last modified', }), - render: lastModified => {lastModified}, + render: (lastModified) => {lastModified}, sortable: ({ lastModified }) => lastModified.valueOf(), }, { @@ -55,7 +55,7 @@ function getColumns(openPipeline, clonePipeline) { name: i18n.translate('xpack.logstash.pipelinesTable.modifiedByColumnLabel', { defaultMessage: 'Modified by', }), - render: username => {username}, + render: (username) => {username}, sortable: true, }, { diff --git a/x-pack/plugins/logstash/public/application/pipeline_edit_view.tsx b/x-pack/plugins/logstash/public/application/pipeline_edit_view.tsx index c1b465febcd9b..9b291e5261033 100644 --- a/x-pack/plugins/logstash/public/application/pipeline_edit_view.tsx +++ b/x-pack/plugins/logstash/public/application/pipeline_edit_view.tsx @@ -64,7 +64,7 @@ const useIsUpgraded = (upgradeService: any) => { const mounted = usePromise(); useLayoutEffect(() => { - mounted(upgradeService.executeUpgrade() as Promise).then(result => + mounted(upgradeService.executeUpgrade() as Promise).then((result) => setIsUpgraded(result) ); }, [mounted, upgradeService]); diff --git a/x-pack/plugins/logstash/public/models/pipeline/pipeline.js b/x-pack/plugins/logstash/public/models/pipeline/pipeline.js index 0f098bd599b1d..2b603f7aded02 100755 --- a/x-pack/plugins/logstash/public/models/pipeline/pipeline.js +++ b/x-pack/plugins/logstash/public/models/pipeline/pipeline.js @@ -89,7 +89,7 @@ export class Pipeline { }); } - isEqualTo = otherPipeline => { + isEqualTo = (otherPipeline) => { // We need to create a POJO copies because isEqual would return false // because of property getters const cleanPipeline = { diff --git a/x-pack/plugins/logstash/public/plugin.ts b/x-pack/plugins/logstash/public/plugin.ts index 7d4afc0a4ea13..70fdb420ca2d2 100644 --- a/x-pack/plugins/logstash/public/plugin.ts +++ b/x-pack/plugins/logstash/public/plugin.ts @@ -32,7 +32,7 @@ export class LogstashPlugin implements Plugin { public setup(core: CoreSetup, plugins: SetupDeps) { const logstashLicense$ = plugins.licensing.license$.pipe( - map(license => new LogstashLicenseService(license)) + map((license) => new LogstashLicenseService(license)) ); const managementApp = plugins.management.sections @@ -43,7 +43,7 @@ export class LogstashPlugin implements Plugin { defaultMessage: 'Logstash Pipelines', }), order: 1, - mount: async params => { + mount: async (params) => { const [coreStart] = await core.getStartServices(); const { renderApp } = await import('./application'); const isMonitoringEnabled = 'monitoring' in plugins; diff --git a/x-pack/plugins/logstash/public/services/cluster/cluster_service.js b/x-pack/plugins/logstash/public/services/cluster/cluster_service.js index 20f3b0d349c80..d1d04544031f2 100755 --- a/x-pack/plugins/logstash/public/services/cluster/cluster_service.js +++ b/x-pack/plugins/logstash/public/services/cluster/cluster_service.js @@ -13,7 +13,7 @@ export class ClusterService { } loadCluster() { - return this.http.get(`${ROUTES.API_ROOT}/cluster`).then(response => { + return this.http.get(`${ROUTES.API_ROOT}/cluster`).then((response) => { if (!response) { return; } @@ -23,7 +23,7 @@ export class ClusterService { isClusterInfoAvailable() { return this.loadCluster() - .then(cluster => Boolean(cluster)) + .then((cluster) => Boolean(cluster)) .catch(() => false); } } diff --git a/x-pack/plugins/logstash/public/services/monitoring/monitoring_service.js b/x-pack/plugins/logstash/public/services/monitoring/monitoring_service.js index 4db2838cb5354..9f57b09ee34b6 100755 --- a/x-pack/plugins/logstash/public/services/monitoring/monitoring_service.js +++ b/x-pack/plugins/logstash/public/services/monitoring/monitoring_service.js @@ -26,7 +26,7 @@ export class MonitoringService { return this.clusterService .loadCluster() - .then(cluster => { + .then((cluster) => { // This API call should live within the Monitoring plugin // https://github.com/elastic/kibana/issues/63931 const url = `${ROUTES.MONITORING_API_ROOT}/v1/clusters/${cluster.uuid}/logstash/pipeline_ids`; @@ -39,8 +39,8 @@ export class MonitoringService { }); return this.http.post(url, { body }); }) - .then(response => - response.map(pipeline => PipelineListItem.fromUpstreamMonitoringJSON(pipeline)) + .then((response) => + response.map((pipeline) => PipelineListItem.fromUpstreamMonitoringJSON(pipeline)) ) .catch(() => []); } diff --git a/x-pack/plugins/logstash/public/services/pipeline/pipeline_service.js b/x-pack/plugins/logstash/public/services/pipeline/pipeline_service.js index 7c3e18e745d82..85fa6ea8a93f0 100755 --- a/x-pack/plugins/logstash/public/services/pipeline/pipeline_service.js +++ b/x-pack/plugins/logstash/public/services/pipeline/pipeline_service.js @@ -14,7 +14,7 @@ export class PipelineService { } loadPipeline(id) { - return this.http.get(`${ROUTES.API_ROOT}/pipeline/${id}`).then(response => { + return this.http.get(`${ROUTES.API_ROOT}/pipeline/${id}`).then((response) => { return Pipeline.fromUpstreamJSON(response); }); } @@ -24,7 +24,7 @@ export class PipelineService { .put(`${ROUTES.API_ROOT}/pipeline/${pipelineModel.id}`, { body: JSON.stringify(pipelineModel.upstreamJSON), }) - .catch(e => { + .catch((e) => { throw e.message; }); } @@ -33,7 +33,7 @@ export class PipelineService { return this.http .delete(`${ROUTES.API_ROOT}/pipeline/${id}`) .then(() => this.pipelinesService.addToRecentlyDeleted(id)) - .catch(e => { + .catch((e) => { throw e.message; }); } diff --git a/x-pack/plugins/logstash/public/services/pipelines/pipelines_service.js b/x-pack/plugins/logstash/public/services/pipelines/pipelines_service.js index 00610a23f2717..c9bcb54691b64 100755 --- a/x-pack/plugins/logstash/public/services/pipelines/pipelines_service.js +++ b/x-pack/plugins/logstash/public/services/pipelines/pipelines_service.js @@ -23,8 +23,8 @@ export class PipelinesService { // Monitoring will report centrally-managed pipelines as well, including recently-deleted centrally-managed ones. // If there's a recently-deleted pipeline we're keeping track of BUT monitoring doesn't report it, that means // it's not running in Logstash any more. So we can stop tracking it as a recently-deleted pipeline. - const monitoringPipelineIds = monitoringPipelines.map(pipeline => pipeline.id); - this.getRecentlyDeleted().forEach(recentlyDeletedPipeline => { + const monitoringPipelineIds = monitoringPipelines.map((pipeline) => pipeline.id); + this.getRecentlyDeleted().forEach((recentlyDeletedPipeline) => { // We don't want to stop tracking the recently-deleted pipeline until Monitoring has had some // time to report on it. Otherwise, if we stop tracking first, *then* Monitoring reports it, we'll // still end up showing it in the list until Monitoring stops reporting it. @@ -43,10 +43,10 @@ export class PipelinesService { // Merge centrally-managed pipelines with pipelines reported by monitoring. Take care to dedupe // while merging because monitoring will (rightly) report centrally-managed pipelines as well, // including recently-deleted ones! - const managementPipelineIds = managementPipelines.map(pipeline => pipeline.id); + const managementPipelineIds = managementPipelines.map((pipeline) => pipeline.id); return managementPipelines.concat( monitoringPipelines.filter( - monitoringPipeline => + (monitoringPipeline) => !managementPipelineIds.includes(monitoringPipeline.id) && !this.isRecentlyDeleted(monitoringPipeline.id) ) @@ -56,8 +56,8 @@ export class PipelinesService { } getManagementPipelineList() { - return this.http.get(`${ROUTES.API_ROOT}/pipelines`).then(response => { - return response.pipelines.map(pipeline => PipelineListItem.fromUpstreamJSON(pipeline)); + return this.http.get(`${ROUTES.API_ROOT}/pipelines`).then((response) => { + return response.pipelines.map((pipeline) => PipelineListItem.fromUpstreamJSON(pipeline)); }); } @@ -75,7 +75,7 @@ export class PipelinesService { const body = JSON.stringify({ pipelineIds, }); - return this.http.post(`${ROUTES.API_ROOT}/pipelines/delete`, { body }).then(response => { + return this.http.post(`${ROUTES.API_ROOT}/pipelines/delete`, { body }).then((response) => { this.addToRecentlyDeleted(...pipelineIds); return response.results; }); @@ -83,8 +83,8 @@ export class PipelinesService { addToRecentlyDeleted(...pipelineIds) { const recentlyDeletedPipelines = this.getRecentlyDeleted(); - const recentlyDeletedPipelineIds = recentlyDeletedPipelines.map(pipeline => pipeline.id); - pipelineIds.forEach(pipelineId => { + const recentlyDeletedPipelineIds = recentlyDeletedPipelines.map((pipeline) => pipeline.id); + pipelineIds.forEach((pipelineId) => { if (!recentlyDeletedPipelineIds.includes(pipelineId)) { recentlyDeletedPipelines.push({ id: pipelineId, @@ -97,14 +97,14 @@ export class PipelinesService { removeFromRecentlyDeleted(...pipelineIds) { const recentlyDeletedPipelinesToKeep = this.getRecentlyDeleted().filter( - recentlyDeletedPipeline => !pipelineIds.includes(recentlyDeletedPipeline.id) + (recentlyDeletedPipeline) => !pipelineIds.includes(recentlyDeletedPipeline.id) ); this.setRecentlyDeleted(recentlyDeletedPipelinesToKeep); } isRecentlyDeleted(pipelineId) { return this.getRecentlyDeleted() - .map(pipeline => pipeline.id) + .map((pipeline) => pipeline.id) .includes(pipelineId); } diff --git a/x-pack/plugins/logstash/public/services/upgrade/upgrade_service.js b/x-pack/plugins/logstash/public/services/upgrade/upgrade_service.js index 7bd101ebee6b0..29e9ef6c1f6f4 100755 --- a/x-pack/plugins/logstash/public/services/upgrade/upgrade_service.js +++ b/x-pack/plugins/logstash/public/services/upgrade/upgrade_service.js @@ -14,8 +14,8 @@ export class UpgradeService { executeUpgrade() { return this.http .post(`${ROUTES.API_ROOT}/upgrade`) - .then(response => response.is_upgraded) - .catch(e => { + .then((response) => response.is_upgraded) + .catch((e) => { throw e.message; }); } diff --git a/x-pack/plugins/logstash/server/lib/check_license/check_license.test.ts b/x-pack/plugins/logstash/server/lib/check_license/check_license.test.ts index 324e0a22ff378..649764a034d63 100755 --- a/x-pack/plugins/logstash/server/lib/check_license/check_license.test.ts +++ b/x-pack/plugins/logstash/server/lib/check_license/check_license.test.ts @@ -6,7 +6,7 @@ import { licensingMock } from '../../../../licensing/server/mocks'; import { checkLicense } from './check_license'; -describe('check_license', function() { +describe('check_license', function () { describe('returns "valid": false & message when', () => { it('license information is not available', () => { const license = licensingMock.createLicenseMock(); diff --git a/x-pack/plugins/logstash/server/lib/check_license/check_license.ts b/x-pack/plugins/logstash/server/lib/check_license/check_license.ts index 4eef2eb9b0681..19606a508149d 100644 --- a/x-pack/plugins/logstash/server/lib/check_license/check_license.ts +++ b/x-pack/plugins/logstash/server/lib/check_license/check_license.ts @@ -8,7 +8,7 @@ import { i18n } from '@kbn/i18n'; import { CheckLicense } from '../../../../licensing/server'; -export const checkLicense: CheckLicense = license => { +export const checkLicense: CheckLicense = (license) => { if (!license.isAvailable) { return { valid: false, diff --git a/x-pack/plugins/logstash/server/routes/pipelines/delete.ts b/x-pack/plugins/logstash/server/routes/pipelines/delete.ts index ac3097ac0424b..e29d0128353b5 100644 --- a/x-pack/plugins/logstash/server/routes/pipelines/delete.ts +++ b/x-pack/plugins/logstash/server/routes/pipelines/delete.ts @@ -11,19 +11,19 @@ import { INDEX_NAMES } from '../../../common/constants'; import { checkLicense } from '../../lib/check_license'; async function deletePipelines(callWithRequest: APICaller, pipelineIds: string[]) { - const deletePromises = pipelineIds.map(pipelineId => { + const deletePromises = pipelineIds.map((pipelineId) => { return callWithRequest('delete', { index: INDEX_NAMES.PIPELINES, id: pipelineId, refresh: 'wait_for', }) - .then(success => ({ success })) - .catch(error => ({ error })); + .then((success) => ({ success })) + .catch((error) => ({ error })); }); const results = await Promise.all(deletePromises); - const successes = results.filter(result => Reflect.has(result, 'success')); - const errors = results.filter(result => Reflect.has(result, 'error')); + const successes = results.filter((result) => Reflect.has(result, 'success')); + const errors = results.filter((result) => Reflect.has(result, 'error')); return { numSuccesses: successes.length, diff --git a/x-pack/plugins/logstash/server/routes/pipelines/list.ts b/x-pack/plugins/logstash/server/routes/pipelines/list.ts index bc477a25a7988..594e2b8ed8b3c 100644 --- a/x-pack/plugins/logstash/server/routes/pipelines/list.ts +++ b/x-pack/plugins/logstash/server/routes/pipelines/list.ts @@ -40,7 +40,7 @@ export function registerPipelinesListRoute(router: IRouter) { const client = context.logstash!.esClient; const pipelinesHits = await fetchPipelines(client.callAsCurrentUser); - const pipelines = pipelinesHits.map(pipeline => { + const pipelines = pipelinesHits.map((pipeline) => { return PipelineListItem.fromUpstreamJSON(pipeline).downstreamJSON; }); diff --git a/x-pack/plugins/maps/common/migrations/add_field_meta_options.js b/x-pack/plugins/maps/common/migrations/add_field_meta_options.js index e425e2a6d5e48..ae926cfa8f475 100644 --- a/x-pack/plugins/maps/common/migrations/add_field_meta_options.js +++ b/x-pack/plugins/maps/common/migrations/add_field_meta_options.js @@ -18,9 +18,9 @@ export function addFieldMetaOptions({ attributes }) { } const layerList = JSON.parse(attributes.layerListJSON); - layerList.forEach(layerDescriptor => { + layerList.forEach((layerDescriptor) => { if (isVectorLayer(layerDescriptor) && _.has(layerDescriptor, 'style.properties')) { - Object.values(layerDescriptor.style.properties).forEach(stylePropertyDescriptor => { + Object.values(layerDescriptor.style.properties).forEach((stylePropertyDescriptor) => { if (stylePropertyDescriptor.type === STYLE_TYPE.DYNAMIC) { stylePropertyDescriptor.options.fieldMetaOptions = { isEnabled: false, // turn off field metadata to avoid changing behavior of existing saved objects diff --git a/x-pack/plugins/maps/common/migrations/ems_raster_tile_to_ems_vector_tile.js b/x-pack/plugins/maps/common/migrations/ems_raster_tile_to_ems_vector_tile.js index 091cfd8605cb6..4dcf4b99aeb8f 100644 --- a/x-pack/plugins/maps/common/migrations/ems_raster_tile_to_ems_vector_tile.js +++ b/x-pack/plugins/maps/common/migrations/ems_raster_tile_to_ems_vector_tile.js @@ -23,7 +23,7 @@ export function emsRasterTileToEmsVectorTile({ attributes }) { } const layerList = JSON.parse(attributes.layerListJSON); - layerList.forEach(layer => { + layerList.forEach((layer) => { if (isTileLayer(layer) && isEmsTileSource(layer)) { // Just need to switch layer type to migrate TILE layer to VECTOR_TILE layer layer.type = LAYER_TYPE.VECTOR_TILE; diff --git a/x-pack/plugins/maps/common/migrations/join_agg_key.ts b/x-pack/plugins/maps/common/migrations/join_agg_key.ts index 92e3172f218b9..4dc70d3c0fa22 100644 --- a/x-pack/plugins/maps/common/migrations/join_agg_key.ts +++ b/x-pack/plugins/maps/common/migrations/join_agg_key.ts @@ -96,7 +96,7 @@ export function migrateJoinAggKey({ }); }); - Object.keys(vectorLayerDescriptor.style.properties).forEach(key => { + Object.keys(vectorLayerDescriptor.style.properties).forEach((key) => { const style: any = vectorLayerDescriptor.style!.properties[key as VECTOR_STYLES]; if (_.get(style, 'options.field.origin') === FIELD_ORIGIN.JOIN) { const joinDescriptor = legacyJoinFields.get(style.options.field.name); diff --git a/x-pack/plugins/maps/common/migrations/migrate_symbol_style_descriptor.js b/x-pack/plugins/maps/common/migrations/migrate_symbol_style_descriptor.js index 0ae20ffd142c5..098e8dad68c00 100644 --- a/x-pack/plugins/maps/common/migrations/migrate_symbol_style_descriptor.js +++ b/x-pack/plugins/maps/common/migrations/migrate_symbol_style_descriptor.js @@ -18,7 +18,7 @@ export function migrateSymbolStyleDescriptor({ attributes }) { } const layerList = JSON.parse(attributes.layerListJSON); - layerList.forEach(layerDescriptor => { + layerList.forEach((layerDescriptor) => { if (!isVectorLayer(layerDescriptor) || !_.has(layerDescriptor, 'style.properties')) { return; } diff --git a/x-pack/plugins/maps/common/migrations/move_apply_global_query.js b/x-pack/plugins/maps/common/migrations/move_apply_global_query.js index 0d6b0052d2b0d..ceb19b059e0f8 100644 --- a/x-pack/plugins/maps/common/migrations/move_apply_global_query.js +++ b/x-pack/plugins/maps/common/migrations/move_apply_global_query.js @@ -22,7 +22,7 @@ export function moveApplyGlobalQueryToSources({ attributes }) { } const layerList = JSON.parse(attributes.layerListJSON); - layerList.forEach(layerDescriptor => { + layerList.forEach((layerDescriptor) => { const applyGlobalQuery = _.get(layerDescriptor, 'applyGlobalQuery', true); delete layerDescriptor.applyGlobalQuery; @@ -31,7 +31,7 @@ export function moveApplyGlobalQueryToSources({ attributes }) { } if (_.has(layerDescriptor, 'joins')) { - layerDescriptor.joins.forEach(joinDescriptor => { + layerDescriptor.joins.forEach((joinDescriptor) => { if (_.has(joinDescriptor, 'right')) { // joinDescriptor.right is ES_TERM_SOURCE source descriptor joinDescriptor.right.applyGlobalQuery = applyGlobalQuery; diff --git a/x-pack/plugins/maps/common/migrations/references.js b/x-pack/plugins/maps/common/migrations/references.js index 3980705fd7cfa..e0073c5f09a3d 100644 --- a/x-pack/plugins/maps/common/migrations/references.js +++ b/x-pack/plugins/maps/common/migrations/references.js @@ -65,7 +65,7 @@ export function extractReferences({ attributes, references = [] }) { } function findReference(targetName, references) { - const reference = references.find(reference => reference.name === targetName); + const reference = references.find((reference) => reference.name === targetName); if (!reference) { throw new Error(`Could not find reference "${targetName}"`); } @@ -78,7 +78,7 @@ export function injectReferences({ attributes, references }) { } const layerList = JSON.parse(attributes.layerListJSON); - layerList.forEach(layer => { + layerList.forEach((layer) => { // Inject index-pattern references into source descriptor if (doesSourceUseIndexPattern(layer) && _.has(layer, 'sourceDescriptor.indexPatternRefName')) { const reference = findReference(layer.sourceDescriptor.indexPatternRefName, references); @@ -88,7 +88,7 @@ export function injectReferences({ attributes, references }) { // Inject index-pattern references into join const joins = _.get(layer, 'joins', []); - joins.forEach(join => { + joins.forEach((join) => { if (_.has(join, 'right.indexPatternRefName')) { const reference = findReference(join.right.indexPatternRefName, references); join.right.indexPatternId = reference.id; diff --git a/x-pack/plugins/maps/common/migrations/top_hits_time_to_sort.js b/x-pack/plugins/maps/common/migrations/top_hits_time_to_sort.js index 055c867486f6c..6b7a5931255c5 100644 --- a/x-pack/plugins/maps/common/migrations/top_hits_time_to_sort.js +++ b/x-pack/plugins/maps/common/migrations/top_hits_time_to_sort.js @@ -18,7 +18,7 @@ export function topHitsTimeToSort({ attributes }) { } const layerList = JSON.parse(attributes.layerListJSON); - layerList.forEach(layerDescriptor => { + layerList.forEach((layerDescriptor) => { if (isEsDocumentSource(layerDescriptor)) { if (_.has(layerDescriptor, 'sourceDescriptor.topHitsTimeField')) { layerDescriptor.sourceDescriptor.sortField = diff --git a/x-pack/plugins/maps/public/actions/data_request_actions.ts b/x-pack/plugins/maps/public/actions/data_request_actions.ts index e615b31744f8d..e521fa5d0402b 100644 --- a/x-pack/plugins/maps/public/actions/data_request_actions.ts +++ b/x-pack/plugins/maps/public/actions/data_request_actions.ts @@ -66,7 +66,7 @@ export function clearDataRequests(layer: ILayer) { export function cancelAllInFlightRequests() { return (dispatch: Dispatch, getState: () => MapStoreState) => { - getLayerList(getState()).forEach(layer => { + getLayerList(getState()).forEach((layer) => { dispatch(clearDataRequests(layer)); }); }; @@ -126,7 +126,7 @@ function getDataRequestContext( export function syncDataForAllLayers() { return async (dispatch: Dispatch, getState: () => MapStoreState) => { - const syncPromises = getLayerList(getState()).map(async layer => { + const syncPromises = getLayerList(getState()).map(async (layer) => { return dispatch(syncDataForLayer(layer)); }); await Promise.all(syncPromises); diff --git a/x-pack/plugins/maps/public/actions/map_actions.js b/x-pack/plugins/maps/public/actions/map_actions.js index fa270954e6bae..4515c896e78a2 100644 --- a/x-pack/plugins/maps/public/actions/map_actions.js +++ b/x-pack/plugins/maps/public/actions/map_actions.js @@ -146,7 +146,7 @@ export function replaceLayerList(newLayerList) { }); } - newLayerList.forEach(layerDescriptor => { + newLayerList.forEach((layerDescriptor) => { dispatch(addLayer(layerDescriptor)); }); }; @@ -264,7 +264,7 @@ export function setTransientLayer(layerId) { } export function clearTransientLayerStateAndCloseFlyout() { - return async dispatch => { + return async (dispatch) => { await dispatch(updateFlyout(FLYOUT_STATE.NONE)); await dispatch(setSelectedLayer(null)); await dispatch(removeTransientLayer()); @@ -284,7 +284,7 @@ export function mapReady() { type: MAP_READY, }); - getWaitingForMapReadyLayerListRaw(getState()).forEach(layerDescriptor => { + getWaitingForMapReadyLayerListRaw(getState()).forEach((layerDescriptor) => { dispatch(addLayer(layerDescriptor)); }); @@ -376,7 +376,7 @@ export function disableScrollZoom() { } export function fitToLayerExtent(layerId) { - return async function(dispatch, getState) { + return async function (dispatch, getState) { const targetLayer = getLayerById(layerId, getState()); if (targetLayer) { @@ -390,7 +390,7 @@ export function fitToLayerExtent(layerId) { } export function fitToDataBounds() { - return async function(dispatch, getState) { + return async function (dispatch, getState) { const layerList = getFittableLayers(getState()); if (!layerList.length) { @@ -398,7 +398,7 @@ export function fitToDataBounds() { } const dataFilters = getDataFilters(getState()); - const boundsPromises = layerList.map(async layer => { + const boundsPromises = layerList.map(async (layer) => { return layer.getBounds(dataFilters); }); @@ -457,7 +457,7 @@ export function clearGoto() { } export function updateSourceProp(layerId, propName, value, newLayerType) { - return async dispatch => { + return async (dispatch) => { dispatch({ type: UPDATE_SOURCE_PROP, layerId, @@ -525,7 +525,7 @@ export function updateLayerAlpha(id, alpha) { } export function setLayerQuery(id, query) { - return dispatch => { + return (dispatch) => { dispatch({ type: UPDATE_LAYER_PROP, id, @@ -564,7 +564,7 @@ function removeLayerFromLayerList(layerId) { return; } - layerGettingRemoved.getInFlightRequestTokens().forEach(requestToken => { + layerGettingRemoved.getInFlightRequestTokens().forEach((requestToken) => { dispatch(cancelRequest(requestToken)); }); dispatch(cleanTooltipStateForLayer(layerId)); @@ -611,7 +611,7 @@ export function setRefreshConfig({ isPaused, interval }) { } export function triggerRefreshTimer() { - return async dispatch => { + return async (dispatch) => { dispatch({ type: TRIGGER_REFRESH_TIMER, }); @@ -643,7 +643,7 @@ export function clearMissingStyleProperties(layerId) { } export function updateLayerStyle(layerId, styleDescriptor) { - return dispatch => { + return (dispatch) => { dispatch({ type: UPDATE_LAYER_STYLE, layerId, @@ -672,7 +672,7 @@ export function updateLayerStyleForSelectedLayer(styleDescriptor) { } export function setJoinsForLayer(layer, joins) { - return async dispatch => { + return async (dispatch) => { await dispatch({ type: SET_JOINS, layer, @@ -685,7 +685,7 @@ export function setJoinsForLayer(layer, joins) { } export function updateDrawState(drawState) { - return dispatch => { + return (dispatch) => { if (drawState !== null) { dispatch({ type: SET_OPEN_TOOLTIPS, openTooltips: [] }); // tooltips just get in the way } @@ -722,7 +722,7 @@ export function setHiddenLayers(hiddenLayerIds) { if (!isMapReady) { dispatch({ type: SET_WAITING_FOR_READY_HIDDEN_LAYERS, hiddenLayerIds }); } else { - getLayerListRaw(getState()).forEach(layer => + getLayerListRaw(getState()).forEach((layer) => dispatch(setLayerVisibility(layer.id, !hiddenLayerIds.includes(layer.id))) ); } diff --git a/x-pack/plugins/maps/public/actions/tooltip_actions.ts b/x-pack/plugins/maps/public/actions/tooltip_actions.ts index ce74a63ac862d..98a121e6be7a3 100644 --- a/x-pack/plugins/maps/public/actions/tooltip_actions.ts +++ b/x-pack/plugins/maps/public/actions/tooltip_actions.ts @@ -76,15 +76,15 @@ export function cleanTooltipStateForLayer(layerId: string, layerFeatures: Featur return (dispatch: Dispatch, getState: () => MapStoreState) => { let featuresRemoved = false; const openTooltips = getOpenTooltips(getState()) - .map(tooltipState => { - const nextFeatures = tooltipState.features.filter(tooltipFeature => { + .map((tooltipState) => { + const nextFeatures = tooltipState.features.filter((tooltipFeature) => { if (tooltipFeature.layerId !== layerId) { // feature from another layer, keep it return true; } // Keep feature if it is still in layer - return layerFeatures.some(layerFeature => { + return layerFeatures.some((layerFeature) => { return layerFeature.properties![FEATURE_ID_PROPERTY_NAME] === tooltipFeature.id; }); }); @@ -95,7 +95,7 @@ export function cleanTooltipStateForLayer(layerId: string, layerFeatures: Featur return { ...tooltipState, features: nextFeatures }; }) - .filter(tooltipState => { + .filter((tooltipState) => { return tooltipState.features.length > 0; }); diff --git a/x-pack/plugins/maps/public/angular/services/gis_map_saved_object_loader.js b/x-pack/plugins/maps/public/angular/services/gis_map_saved_object_loader.js index 2dcec35960b08..ea48eecf4e421 100644 --- a/x-pack/plugins/maps/public/angular/services/gis_map_saved_object_loader.js +++ b/x-pack/plugins/maps/public/angular/services/gis_map_saved_object_loader.js @@ -15,7 +15,7 @@ import { getData, } from '../../kibana_services'; -export const getMapsSavedObjectLoader = _.once(function() { +export const getMapsSavedObjectLoader = _.once(function () { const services = { savedObjectsClient: getSavedObjectsClient(), indexPatterns: getIndexPatternService(), diff --git a/x-pack/plugins/maps/public/angular/services/saved_gis_map.js b/x-pack/plugins/maps/public/angular/services/saved_gis_map.js index 2de4432871347..ddb58b610f5f1 100644 --- a/x-pack/plugins/maps/public/angular/services/saved_gis_map.js +++ b/x-pack/plugins/maps/public/angular/services/saved_gis_map.js @@ -60,10 +60,10 @@ export function createSavedGisMapClass(services) { savedObject.layerListJSON = attributes.layerListJSON; const indexPatternIds = references - .filter(reference => { + .filter((reference) => { return reference.type === 'index-pattern'; }) - .map(reference => { + .map((reference) => { return reference.id; }); savedObject.indexPatternIds = _.uniq(indexPatternIds); diff --git a/x-pack/plugins/maps/public/classes/fields/ems_file_field.ts b/x-pack/plugins/maps/public/classes/fields/ems_file_field.ts index 7ed508199e64a..73d6c1ef9f790 100644 --- a/x-pack/plugins/maps/public/classes/fields/ems_file_field.ts +++ b/x-pack/plugins/maps/public/classes/fields/ems_file_field.ts @@ -35,7 +35,7 @@ export class EMSFileField extends AbstractField implements IField { // @ts-ignore const emsFields: any[] = emsFileLayer.getFieldsInLanguage(); // Map EMS field name to language specific label - const emsField = emsFields.find(field => field.name === this.getName()); + const emsField = emsFields.find((field) => field.name === this.getName()); return emsField ? emsField.description : this.getName(); } } diff --git a/x-pack/plugins/maps/public/classes/fields/kibana_region_field.ts b/x-pack/plugins/maps/public/classes/fields/kibana_region_field.ts index 9b619cf60a020..ce72f01adb5f8 100644 --- a/x-pack/plugins/maps/public/classes/fields/kibana_region_field.ts +++ b/x-pack/plugins/maps/public/classes/fields/kibana_region_field.ts @@ -33,7 +33,7 @@ export class KibanaRegionField extends AbstractField implements IField { const meta = await this._source.getVectorFileMeta(); // TODO remove any and @ts-ignore when vectorFileMeta type defined // @ts-ignore - const field: any = meta.fields.find(f => f.name === this.getName()); + const field: any = meta.fields.find((f) => f.name === this.getName()); return field ? field.description : this.getName(); } } diff --git a/x-pack/plugins/maps/public/classes/joins/inner_join.js b/x-pack/plugins/maps/public/classes/joins/inner_join.js index 13a2e05ab8eeb..5f8bc7385d04c 100644 --- a/x-pack/plugins/maps/public/classes/joins/inner_join.js +++ b/x-pack/plugins/maps/public/classes/joins/inner_join.js @@ -62,7 +62,7 @@ export class InnerJoin { // delete all dynamic properties for metric field const stylePropertyPrefix = getComputedFieldNamePrefix(metricPropertyKey); - Object.keys(feature.properties).forEach(featurePropertyKey => { + Object.keys(feature.properties).forEach((featurePropertyKey) => { if ( featurePropertyKey.length >= stylePropertyPrefix.length && featurePropertyKey.substring(0, stylePropertyPrefix.length) === stylePropertyPrefix diff --git a/x-pack/plugins/maps/public/classes/layers/blended_vector_layer/blended_vector_layer.ts b/x-pack/plugins/maps/public/classes/layers/blended_vector_layer/blended_vector_layer.ts index f4d60ffa65d31..a949853d431b2 100644 --- a/x-pack/plugins/maps/public/classes/layers/blended_vector_layer/blended_vector_layer.ts +++ b/x-pack/plugins/maps/public/classes/layers/blended_vector_layer/blended_vector_layer.ts @@ -56,7 +56,7 @@ function getClusterSource(documentSource: IESSource, documentStyle: IVectorStyle type: AGG_TYPE.COUNT, label: COUNT_PROP_LABEL, }, - ...documentStyle.getDynamicPropertiesArray().map(dynamicProperty => { + ...documentStyle.getDynamicPropertiesArray().map((dynamicProperty) => { return { type: getAggType(dynamicProperty), field: dynamicProperty.getFieldName(), diff --git a/x-pack/plugins/maps/public/classes/layers/layer.tsx b/x-pack/plugins/maps/public/classes/layers/layer.tsx index 8e1b6162683db..b9a35fc361aad 100644 --- a/x-pack/plugins/maps/public/classes/layers/layer.tsx +++ b/x-pack/plugins/maps/public/classes/layers/layer.tsx @@ -134,7 +134,7 @@ export class AbstractLayer implements ILayer { this._style = style; if (this._descriptor.__dataRequests) { this._dataRequests = this._descriptor.__dataRequests.map( - dataRequest => new DataRequest(dataRequest) + (dataRequest) => new DataRequest(dataRequest) ); } else { this._dataRequests = []; @@ -161,7 +161,7 @@ export class AbstractLayer implements ILayer { // @ts-ignore if (clonedDescriptor.joins) { // @ts-ignore - clonedDescriptor.joins.forEach(joinDescriptor => { + clonedDescriptor.joins.forEach((joinDescriptor) => { // right.id is uuid used to track requests in inspector // @ts-ignore joinDescriptor.right.id = uuid(); @@ -333,7 +333,7 @@ export class AbstractLayer implements ILayer { // @ts-ignore const mbStyle = mbMap.getStyle(); // @ts-ignore - mbStyle.layers.forEach(mbLayer => { + mbStyle.layers.forEach((mbLayer) => { // @ts-ignore if (this.ownsMbLayerId(mbLayer.id)) { // @ts-ignore @@ -341,7 +341,7 @@ export class AbstractLayer implements ILayer { } }); // @ts-ignore - Object.keys(mbStyle.sources).some(mbSourceId => { + Object.keys(mbStyle.sources).some((mbSourceId) => { // @ts-ignore if (this.ownsMbSourceId(mbSourceId)) { // @ts-ignore @@ -387,7 +387,7 @@ export class AbstractLayer implements ILayer { return []; } - const requestTokens = this._dataRequests.map(dataRequest => dataRequest.getRequestToken()); + const requestTokens = this._dataRequests.map((dataRequest) => dataRequest.getRequestToken()); // Compact removes all the undefineds // @ts-ignore @@ -399,11 +399,11 @@ export class AbstractLayer implements ILayer { } getDataRequest(id: string): DataRequest | undefined { - return this._dataRequests.find(dataRequest => dataRequest.getDataId() === id); + return this._dataRequests.find((dataRequest) => dataRequest.getDataId() === id); } isLayerLoading(): boolean { - return this._dataRequests.some(dataRequest => dataRequest.isLoading()); + return this._dataRequests.some((dataRequest) => dataRequest.isLoading()); } hasErrors(): boolean { diff --git a/x-pack/plugins/maps/public/classes/layers/layer_wizard_registry.ts b/x-pack/plugins/maps/public/classes/layers/layer_wizard_registry.ts index dc5849203ff37..7698fb7c0947e 100644 --- a/x-pack/plugins/maps/public/classes/layers/layer_wizard_registry.ts +++ b/x-pack/plugins/maps/public/classes/layers/layer_wizard_registry.ts @@ -40,7 +40,7 @@ export function registerLayerWizard(layerWizard: LayerWizard) { } export async function getLayerWizards(): Promise { - const promises = registry.map(async layerWizard => { + const promises = registry.map(async (layerWizard) => { return { ...layerWizard, // @ts-ignore diff --git a/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.test.ts b/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.test.ts index ce079d67c15e4..075d19dccdb68 100644 --- a/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.test.ts +++ b/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.test.ts @@ -18,7 +18,7 @@ jest.mock('../../../../kibana_services', () => { }); jest.mock('uuid/v4', () => { - return function() { + return function () { return '12345'; }; }); diff --git a/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/observability_layer_template.tsx b/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/observability_layer_template.tsx index 7326f8459b5c7..bfd78d5490059 100644 --- a/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/observability_layer_template.tsx +++ b/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/observability_layer_template.tsx @@ -29,7 +29,7 @@ export class ObservabilityLayerTemplate extends Component { + const selectedMetricOption = metricOptions.find((option) => { return option.value === this.state.metric; }); if (!selectedMetricOption) { diff --git a/x-pack/plugins/maps/public/classes/layers/vector_layer/vector_layer.js b/x-pack/plugins/maps/public/classes/layers/vector_layer/vector_layer.js index d32593f73c46c..a2a0e58e48fd2 100644 --- a/x-pack/plugins/maps/public/classes/layers/vector_layer/vector_layer.js +++ b/x-pack/plugins/maps/public/classes/layers/vector_layer/vector_layer.js @@ -69,7 +69,7 @@ export class VectorLayer extends AbstractLayer { if (this.getSource()) { this.getSource().destroy(); } - this.getJoins().forEach(joinSource => { + this.getJoins().forEach((joinSource) => { joinSource.destroy(); }); } @@ -79,7 +79,7 @@ export class VectorLayer extends AbstractLayer { } getValidJoins() { - return this.getJoins().filter(join => { + return this.getJoins().filter((join) => { return join.hasCompleteConfig(); }); } @@ -120,7 +120,9 @@ export class VectorLayer extends AbstractLayer { if ( this.getJoins().length && - !featureCollection.features.some(feature => feature.properties[FEATURE_VISIBLE_PROPERTY_NAME]) + !featureCollection.features.some( + (feature) => feature.properties[FEATURE_VISIBLE_PROPERTY_NAME] + ) ) { return { icon: noResultsIcon, @@ -173,7 +175,7 @@ export class VectorLayer extends AbstractLayer { _getJoinFields() { const joinFields = []; - this.getValidJoins().forEach(join => { + this.getValidJoins().forEach((join) => { const fields = join.getJoinFields(); joinFields.push(...fields); }); @@ -192,7 +194,7 @@ export class VectorLayer extends AbstractLayer { getIndexPatternIds() { const indexPatternIds = this.getSource().getIndexPatternIds(); - this.getValidJoins().forEach(join => { + this.getValidJoins().forEach((join) => { indexPatternIds.push(...join.getIndexPatternIds()); }); return indexPatternIds; @@ -200,7 +202,7 @@ export class VectorLayer extends AbstractLayer { getQueryableIndexPatternIds() { const indexPatternIds = this.getSource().getQueryableIndexPatternIds(); - this.getValidJoins().forEach(join => { + this.getValidJoins().forEach((join) => { indexPatternIds.push(...join.getQueryableIndexPatternIds()); }); return indexPatternIds; @@ -266,7 +268,7 @@ export class VectorLayer extends AbstractLayer { } async _syncJoins(syncContext, style) { - const joinSyncs = this.getValidJoins().map(async join => { + const joinSyncs = this.getValidJoins().map(async (join) => { await this._syncJoinStyleMeta(syncContext, join, style); await this._syncJoinFormatters(syncContext, join, style); return this._syncJoin({ join, ...syncContext }); @@ -279,7 +281,7 @@ export class VectorLayer extends AbstractLayer { const fieldNames = [ ...source.getFieldNames(), ...style.getSourceFieldNames(), - ...this.getValidJoins().map(join => join.getLeftField().getName()), + ...this.getValidJoins().map((join) => join.getLeftField().getName()), ]; return { @@ -299,7 +301,7 @@ export class VectorLayer extends AbstractLayer { //-- visibility of any of the features has changed let shouldUpdateStore = - sourceResult.refreshed || joinStates.some(joinState => joinState.dataHasChanged); + sourceResult.refreshed || joinStates.some((joinState) => joinState.dataHasChanged); if (!shouldUpdateStore) { return; @@ -393,7 +395,7 @@ export class VectorLayer extends AbstractLayer { style, sourceQuery: this.getQuery(), dataRequestId: SOURCE_META_ID_ORIGIN, - dynamicStyleProps: style.getDynamicPropertiesArray().filter(dynamicStyleProp => { + dynamicStyleProps: style.getDynamicPropertiesArray().filter((dynamicStyleProp) => { return ( dynamicStyleProp.getFieldOrigin() === FIELD_ORIGIN.SOURCE && dynamicStyleProp.isFieldMetaEnabled() @@ -412,7 +414,7 @@ export class VectorLayer extends AbstractLayer { dataRequestId: join.getSourceMetaDataRequestId(), dynamicStyleProps: this.getCurrentStyle() .getDynamicPropertiesArray() - .filter(dynamicStyleProp => { + .filter((dynamicStyleProp) => { const matchingField = joinSource.getMetricFieldForName( dynamicStyleProp.getField().getName() ); @@ -442,7 +444,7 @@ export class VectorLayer extends AbstractLayer { return; } - const dynamicStyleFields = dynamicStyleProps.map(dynamicStyleProp => { + const dynamicStyleFields = dynamicStyleProps.map((dynamicStyleProp) => { return `${dynamicStyleProp.getField().getName()}${dynamicStyleProp.getNumberOfCategories()}`; }); @@ -489,10 +491,10 @@ export class VectorLayer extends AbstractLayer { dataRequestId: SOURCE_FORMATTERS_ID_ORIGIN, fields: style .getDynamicPropertiesArray() - .filter(dynamicStyleProp => { + .filter((dynamicStyleProp) => { return dynamicStyleProp.getFieldOrigin() === FIELD_ORIGIN.SOURCE; }) - .map(dynamicStyleProp => { + .map((dynamicStyleProp) => { return dynamicStyleProp.getField(); }), ...syncContext, @@ -506,13 +508,13 @@ export class VectorLayer extends AbstractLayer { dataRequestId: join.getSourceFormattersDataRequestId(), fields: style .getDynamicPropertiesArray() - .filter(dynamicStyleProp => { + .filter((dynamicStyleProp) => { const matchingField = joinSource.getMetricFieldForName( dynamicStyleProp.getField().getName() ); return dynamicStyleProp.getFieldOrigin() === FIELD_ORIGIN.JOIN && !!matchingField; }) - .map(dynamicStyleProp => { + .map((dynamicStyleProp) => { return dynamicStyleProp.getField(); }), ...syncContext, @@ -524,7 +526,7 @@ export class VectorLayer extends AbstractLayer { return; } - const fieldNames = fields.map(field => { + const fieldNames = fields.map((field) => { return field.getName(); }); const nextMeta = { @@ -542,10 +544,10 @@ export class VectorLayer extends AbstractLayer { const formatters = {}; const promises = fields - .filter(field => { + .filter((field) => { return field.canValueBeFormatted(); }) - .map(async field => { + .map(async (field) => { formatters[field.getName()] = await source.createFieldFormatter(field); }); await Promise.all(promises); @@ -854,11 +856,7 @@ export class VectorLayer extends AbstractLayer { const tooltipProperty = tooltipsFromSource[i]; const matchingJoins = []; for (let j = 0; j < this.getJoins().length; j++) { - if ( - this.getJoins() - [j].getLeftField() - .getName() === tooltipProperty.getPropertyKey() - ) { + if (this.getJoins()[j].getLeftField().getName() === tooltipProperty.getPropertyKey()) { matchingJoins.push(this.getJoins()[j]); } } @@ -893,7 +891,7 @@ export class VectorLayer extends AbstractLayer { return; } - return featureCollection.features.find(feature => { + return featureCollection.features.find((feature) => { return feature.properties[FEATURE_ID_PROPERTY_NAME] === id; }); } diff --git a/x-pack/plugins/maps/public/classes/layers/vector_tile_layer/vector_tile_layer.js b/x-pack/plugins/maps/public/classes/layers/vector_tile_layer/vector_tile_layer.js index 4ffd0d93fd22a..6f616afb64041 100644 --- a/x-pack/plugins/maps/public/classes/layers/vector_tile_layer/vector_tile_layer.js +++ b/x-pack/plugins/maps/public/classes/layers/vector_tile_layer/vector_tile_layer.js @@ -117,7 +117,7 @@ export class VectorTileLayer extends TileLayer { if (!vectorStyle) { return []; } - return vectorStyle.layers.map(layer => this._generateMbId(layer.id)); + return vectorStyle.layers.map((layer) => this._generateMbId(layer.id)); } getMbSourceIds() { @@ -126,7 +126,7 @@ export class VectorTileLayer extends TileLayer { return []; } const sourceIds = Object.keys(vectorStyle.sources); - return sourceIds.map(sourceId => this._generateMbSourceId(sourceId)); + return sourceIds.map((sourceId) => this._generateMbSourceId(sourceId)); } ownsMbLayerId(mbLayerId) { @@ -145,7 +145,7 @@ export class VectorTileLayer extends TileLayer { _requiresPrevSourceCleanup(mbMap) { const sourceIdPrefix = this._generateMbSourceIdPrefix(); const mbStyle = mbMap.getStyle(); - return Object.keys(mbStyle.sources).some(mbSourceId => { + return Object.keys(mbStyle.sources).some((mbSourceId) => { const doesMbSourceBelongToLayer = this.ownsMbSourceId(mbSourceId); const doesMbSourceBelongToSource = mbSourceId.startsWith(sourceIdPrefix); return doesMbSourceBelongToLayer && !doesMbSourceBelongToSource; @@ -162,7 +162,7 @@ export class VectorTileLayer extends TileLayer { let initialBootstrapCompleted = false; const sourceIds = Object.keys(vectorStyle.sources); - sourceIds.forEach(sourceId => { + sourceIds.forEach((sourceId) => { if (initialBootstrapCompleted) { return; } @@ -197,7 +197,7 @@ export class VectorTileLayer extends TileLayer { addSpriteSheetToMapFromImageData(newJson, imageData, mbMap); //sync layers - vectorStyle.layers.forEach(layer => { + vectorStyle.layers.forEach((layer) => { const mbLayerId = this._generateMbId(layer.id); const mbLayer = mbMap.getLayer(mbLayerId); if (mbLayer) { @@ -242,7 +242,7 @@ export class VectorTileLayer extends TileLayer { return; } - opacityProps.forEach(opacityProp => { + opacityProps.forEach((opacityProp) => { if (mbLayer.paint && typeof mbLayer.paint[opacityProp] === 'number') { const newOpacity = mbLayer.paint[opacityProp] * this.getAlpha(); mbMap.setPaintProperty(mbLayerId, opacityProp, newOpacity); @@ -270,7 +270,7 @@ export class VectorTileLayer extends TileLayer { return; } - vectorStyle.layers.forEach(mbLayer => { + vectorStyle.layers.forEach((mbLayer) => { const mbLayerId = this._generateMbId(mbLayer.id); this.syncVisibilityWithMb(mbMap, mbLayerId); this._setLayerZoomRange(mbMap, mbLayer, mbLayerId); diff --git a/x-pack/plugins/maps/public/classes/sources/ems_file_source/create_source_editor.tsx b/x-pack/plugins/maps/public/classes/sources/ems_file_source/create_source_editor.tsx index b66918f93f521..e398af4acea3b 100644 --- a/x-pack/plugins/maps/public/classes/sources/ems_file_source/create_source_editor.tsx +++ b/x-pack/plugins/maps/public/classes/sources/ems_file_source/create_source_editor.tsx @@ -37,7 +37,7 @@ export class EMSFileCreateSourceEditor extends Component { const emsClient = getEMSClient(); // @ts-ignore const fileLayers: unknown[] = await emsClient.getFileLayers(); - const options = fileLayers.map(fileLayer => { + const options = fileLayers.map((fileLayer) => { return { // @ts-ignore value: fileLayer.getId(), diff --git a/x-pack/plugins/maps/public/classes/sources/ems_file_source/ems_file_source.tsx b/x-pack/plugins/maps/public/classes/sources/ems_file_source/ems_file_source.tsx index 5115da510cc5b..94f5bb0d2ba07 100644 --- a/x-pack/plugins/maps/public/classes/sources/ems_file_source/ems_file_source.tsx +++ b/x-pack/plugins/maps/public/classes/sources/ems_file_source/ems_file_source.tsx @@ -48,7 +48,7 @@ export class EMSFileSource extends AbstractVectorSource implements IEmsFileSourc constructor(descriptor: Partial, inspectorAdapters?: Adapters) { super(EMSFileSource.createDescriptor(descriptor), inspectorAdapters); this._descriptor = EMSFileSource.createDescriptor(descriptor); - this._tooltipFields = this._descriptor.tooltipProperties.map(propertyKey => + this._tooltipFields = this._descriptor.tooltipProperties.map((propertyKey) => this.createField({ fieldName: propertyKey }) ); } @@ -77,8 +77,10 @@ export class EMSFileSource extends AbstractVectorSource implements IEmsFileSourc const emsClient = getEMSClient(); // @ts-ignore const emsFileLayers = await emsClient.getFileLayers(); - // @ts-ignore - const emsFileLayer = emsFileLayers.find(fileLayer => fileLayer.getId() === this._descriptor.id); + const emsFileLayer = emsFileLayers.find( + // @ts-ignore + (fileLayer) => fileLayer.getId() === this._descriptor.id + ); if (!emsFileLayer) { throw new Error( i18n.translate('xpack.maps.source.emsFile.unableToFindIdErrorMessage', { @@ -104,7 +106,7 @@ export class EMSFileSource extends AbstractVectorSource implements IEmsFileSourc }); // @ts-ignore - const emsIdField = emsFileLayer._config.fields.find(field => { + const emsIdField = emsFileLayer._config.fields.find((field) => { return field.type === 'id'; }); featureCollection.features.forEach((feature: Feature, index: number) => { @@ -163,7 +165,7 @@ export class EMSFileSource extends AbstractVectorSource implements IEmsFileSourc // @ts-ignore const fields = emsFileLayer.getFieldsInLanguage(); // @ts-ignore - return fields.map(f => this.createField({ fieldName: f.name })); + return fields.map((f) => this.createField({ fieldName: f.name })); } canFormatFeatureProperties() { @@ -171,7 +173,7 @@ export class EMSFileSource extends AbstractVectorSource implements IEmsFileSourc } async filterAndFormatPropertiesToHtml(properties: unknown): Promise { - const promises = this._tooltipFields.map(field => { + const promises = this._tooltipFields.map((field) => { // @ts-ignore const value = properties[field.getName()]; return field.createTooltipProperty(value); diff --git a/x-pack/plugins/maps/public/classes/sources/ems_file_source/update_source_editor.tsx b/x-pack/plugins/maps/public/classes/sources/ems_file_source/update_source_editor.tsx index 806213b667ba4..daeb1f8bc6b2b 100644 --- a/x-pack/plugins/maps/public/classes/sources/ems_file_source/update_source_editor.tsx +++ b/x-pack/plugins/maps/public/classes/sources/ems_file_source/update_source_editor.tsx @@ -49,11 +49,11 @@ export class UpdateSourceEditor extends Component { // @ts-ignore const emsFiles = await emsClient.getFileLayers(); // @ts-ignore - const taregetEmsFile = emsFiles.find(emsFile => emsFile.getId() === this.props.layerId); + const taregetEmsFile = emsFiles.find((emsFile) => emsFile.getId() === this.props.layerId); // @ts-ignore const emsFields = taregetEmsFile.getFieldsInLanguage(); // @ts-ignore - fields = emsFields.map(field => this.props.source.createField({ fieldName: field.name })); + fields = emsFields.map((field) => this.props.source.createField({ fieldName: field.name })); } catch (e) { // When a matching EMS-config cannot be found, the source already will have thrown errors during the data request. // This will propagate to the vector-layer and be displayed in the UX diff --git a/x-pack/plugins/maps/public/classes/sources/ems_tms_source/ems_tms_source.js b/x-pack/plugins/maps/public/classes/sources/ems_tms_source/ems_tms_source.js index b20a3c80e0510..36c9e424a8b22 100644 --- a/x-pack/plugins/maps/public/classes/sources/ems_tms_source/ems_tms_source.js +++ b/x-pack/plugins/maps/public/classes/sources/ems_tms_source/ems_tms_source.js @@ -69,7 +69,7 @@ export class EMSTMSSource extends AbstractTMSSource { const emsClient = getEMSClient(); const emsTMSServices = await emsClient.getTMSServices(); const emsTileLayerId = this.getTileLayerId(); - const tmsService = emsTMSServices.find(tmsService => tmsService.getId() === emsTileLayerId); + const tmsService = emsTMSServices.find((tmsService) => tmsService.getId() === emsTileLayerId); if (!tmsService) { throw new Error( i18n.translate('xpack.maps.source.emsTile.errorMessage', { diff --git a/x-pack/plugins/maps/public/classes/sources/ems_tms_source/tile_service_select.js b/x-pack/plugins/maps/public/classes/sources/ems_tms_source/tile_service_select.js index 337fc7aa46693..4d5d6655609c1 100644 --- a/x-pack/plugins/maps/public/classes/sources/ems_tms_source/tile_service_select.js +++ b/x-pack/plugins/maps/public/classes/sources/ems_tms_source/tile_service_select.js @@ -36,7 +36,7 @@ export class TileServiceSelect extends React.Component { return; } - const emsTmsOptions = emsTMSServices.map(tmsService => { + const emsTmsOptions = emsTMSServices.map((tmsService) => { return { value: tmsService.getId(), text: tmsService.getDisplayName() ? tmsService.getDisplayName() : tmsService.getId(), @@ -51,7 +51,7 @@ export class TileServiceSelect extends React.Component { this.setState({ emsTmsOptions, hasLoaded: true }); }; - _onChange = e => { + _onChange = (e) => { const value = e.target.value; const isAutoSelect = value === AUTO_SELECT; this.props.onTileSelect({ diff --git a/x-pack/plugins/maps/public/classes/sources/es_agg_source/es_agg_source.js b/x-pack/plugins/maps/public/classes/sources/es_agg_source/es_agg_source.js index 22c8293132b42..97afac9ef1745 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_agg_source/es_agg_source.js +++ b/x-pack/plugins/maps/public/classes/sources/es_agg_source/es_agg_source.js @@ -15,7 +15,7 @@ export class AbstractESAggSource extends AbstractESSource { super(descriptor, inspectorAdapters); this._metricFields = []; if (this._descriptor.metrics) { - this._descriptor.metrics.forEach(aggDescriptor => { + this._descriptor.metrics.forEach((aggDescriptor) => { this._metricFields.push( ...esAggFieldsFactory(aggDescriptor, this, this.getOriginForField()) ); @@ -37,7 +37,7 @@ export class AbstractESAggSource extends AbstractESSource { } getMetricFieldForName(fieldName) { - return this.getMetricFields().find(metricField => { + return this.getMetricFields().find((metricField) => { return metricField.getName() === fieldName; }); } @@ -47,7 +47,7 @@ export class AbstractESAggSource extends AbstractESSource { } getMetricFields() { - const metrics = this._metricFields.filter(esAggField => esAggField.isValid()); + const metrics = this._metricFields.filter((esAggField) => esAggField.isValid()); return metrics.length === 0 ? esAggFieldsFactory({ type: AGG_TYPE.COUNT }, this, this.getOriginForField()) : metrics; @@ -80,7 +80,7 @@ export class AbstractESAggSource extends AbstractESSource { getValueAggsDsl(indexPattern) { const valueAggsDsl = {}; - this.getMetricFields().forEach(esAggMetric => { + this.getMetricFields().forEach((esAggMetric) => { const aggDsl = esAggMetric.getValueAggDsl(indexPattern); if (aggDsl) { valueAggsDsl[esAggMetric.getName()] = esAggMetric.getValueAggDsl(indexPattern); @@ -92,7 +92,7 @@ export class AbstractESAggSource extends AbstractESSource { async filterAndFormatPropertiesToHtmlForMetricFields(properties) { const metricFields = this.getMetricFields(); const tooltipPropertiesPromises = []; - metricFields.forEach(metricField => { + metricFields.forEach((metricField) => { let value; for (const key in properties) { if (properties.hasOwnProperty(key) && metricField.getName() === key) { diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/convert_to_geojson.js b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/convert_to_geojson.js index 121ce3c7ffe92..a95a8be4b24c8 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/convert_to_geojson.js +++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/convert_to_geojson.js @@ -16,10 +16,10 @@ export function convertCompositeRespToGeoJson(esResponse, renderAs) { return convertToGeoJson( esResponse, renderAs, - esResponse => { + (esResponse) => { return _.get(esResponse, 'aggregations.compositeSplit.buckets', []); }, - gridBucket => { + (gridBucket) => { return gridBucket.key.gridSplit; } ); @@ -29,10 +29,10 @@ export function convertRegularRespToGeoJson(esResponse, renderAs) { return convertToGeoJson( esResponse, renderAs, - esResponse => { + (esResponse) => { return _.get(esResponse, 'aggregations.gridSplit.buckets', []); }, - gridBucket => { + (gridBucket) => { return gridBucket.key; } ); diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/create_source_editor.js b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/create_source_editor.js index 77d2ffb8c577e..7661ad7020194 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/create_source_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/create_source_editor.js @@ -38,7 +38,7 @@ export class CreateSourceEditor extends Component { this._isMounted = true; } - onIndexPatternSelect = indexPatternId => { + onIndexPatternSelect = (indexPatternId) => { this.setState( { indexPatternId, @@ -47,7 +47,7 @@ export class CreateSourceEditor extends Component { ); }; - loadIndexPattern = indexPatternId => { + loadIndexPattern = (indexPatternId) => { this.setState( { isLoadingIndexPattern: true, @@ -58,7 +58,7 @@ export class CreateSourceEditor extends Component { ); }; - debouncedLoad = _.debounce(async indexPatternId => { + debouncedLoad = _.debounce(async (indexPatternId) => { if (!indexPatternId || indexPatternId.length === 0) { return; } @@ -93,7 +93,7 @@ export class CreateSourceEditor extends Component { } }, 300); - _onGeoFieldSelect = geoField => { + _onGeoFieldSelect = (geoField) => { this.setState( { geoField, @@ -102,7 +102,7 @@ export class CreateSourceEditor extends Component { ); }; - _onRequestTypeSelect = newValue => { + _onRequestTypeSelect = (newValue) => { this.setState( { requestType: newValue, diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js index 053af4bfebe61..e77fd93872612 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js +++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js @@ -95,7 +95,7 @@ export class ESGeoGridSource extends AbstractESAggSource { } getFieldNames() { - return this.getMetricFields().map(esAggMetricField => esAggMetricField.getName()); + return this.getMetricFields().map((esAggMetricField) => esAggMetricField.getName()); } isGeoGridPrecisionAware() { @@ -270,7 +270,7 @@ export class ESGeoGridSource extends AbstractESAggSource { const searchSource = await this.makeSearchSource(searchFilters, 0); let bucketsPerGrid = 1; - this.getMetricFields().forEach(metricField => { + this.getMetricFields().forEach((metricField) => { bucketsPerGrid += metricField.getBucketCount(); }); diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/render_as_select.tsx b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/render_as_select.tsx index 899f4a797ea75..8813264b21b05 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/render_as_select.tsx +++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/render_as_select.tsx @@ -41,7 +41,7 @@ export function RenderAsSelect(props: { } const selectedOptions = []; - const selectedOption = options.find(option => option.value === props.renderAs); + const selectedOption = options.find((option) => option.value === props.renderAs); if (selectedOption) { selectedOptions.push(selectedOption); } diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/resolution_editor.js b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/resolution_editor.js index b2314dd007509..28c24f58a0efc 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/resolution_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/resolution_editor.js @@ -41,7 +41,7 @@ export function ResolutionEditor({ resolution, onChange }) { onChange(e.target.value)} + onChange={(e) => onChange(e.target.value)} compressed /> diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/update_source_editor.js b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/update_source_editor.js index c0d6cba3a024a..ac7d809c40f61 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/update_source_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/update_source_editor.js @@ -54,26 +54,26 @@ export class UpdateSourceEditor extends Component { } this.setState({ - fields: indexPattern.fields.filter(field => !indexPatterns.isNestedField(field)), + fields: indexPattern.fields.filter((field) => !indexPatterns.isNestedField(field)), }); } - _onMetricsChange = metrics => { + _onMetricsChange = (metrics) => { this.props.onChange({ propName: 'metrics', value: metrics }); }; - _onResolutionChange = e => { + _onResolutionChange = (e) => { this.props.onChange({ propName: 'resolution', value: e }); }; - _onRequestTypeSelect = requestType => { + _onRequestTypeSelect = (requestType) => { this.props.onChange({ propName: 'requestType', value: requestType }); }; _renderMetricsPanel() { const metricsFilter = this.props.renderAs === RENDER_AS.HEATMAP - ? metric => { + ? (metric) => { //these are countable metrics, where blending heatmap color blobs make sense return isMetricCountable(metric.value); } diff --git a/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/create_source_editor.js b/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/create_source_editor.js index 78c16130891b8..f599ba93d40d6 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/create_source_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/create_source_editor.js @@ -38,7 +38,7 @@ export class CreateSourceEditor extends Component { this._isMounted = true; } - onIndexPatternSelect = indexPatternId => { + onIndexPatternSelect = (indexPatternId) => { this.setState( { indexPatternId, @@ -47,7 +47,7 @@ export class CreateSourceEditor extends Component { ); }; - loadIndexPattern = indexPatternId => { + loadIndexPattern = (indexPatternId) => { this.setState( { isLoadingIndexPattern: true, @@ -60,7 +60,7 @@ export class CreateSourceEditor extends Component { ); }; - debouncedLoad = _.debounce(async indexPatternId => { + debouncedLoad = _.debounce(async (indexPatternId) => { if (!indexPatternId || indexPatternId.length === 0) { return; } @@ -91,7 +91,7 @@ export class CreateSourceEditor extends Component { }); }, 300); - _onSourceGeoSelect = sourceGeoField => { + _onSourceGeoSelect = (sourceGeoField) => { this.setState( { sourceGeoField, @@ -100,7 +100,7 @@ export class CreateSourceEditor extends Component { ); }; - _onDestGeoSelect = destGeoField => { + _onDestGeoSelect = (destGeoField) => { this.setState( { destGeoField, diff --git a/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/update_source_editor.js b/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/update_source_editor.js index dea59a1c82f8a..344b6187bad48 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/update_source_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/update_source_editor.js @@ -50,11 +50,11 @@ export class UpdateSourceEditor extends Component { } this.setState({ - fields: indexPattern.fields.filter(field => !indexPatterns.isNestedField(field)), + fields: indexPattern.fields.filter((field) => !indexPatterns.isNestedField(field)), }); } - _onMetricsChange = metrics => { + _onMetricsChange = (metrics) => { this.props.onChange({ propName: 'metrics', value: metrics }); }; diff --git a/x-pack/plugins/maps/public/classes/sources/es_search_source/create_source_editor.js b/x-pack/plugins/maps/public/classes/sources/es_search_source/create_source_editor.js index 3a25bd90384e9..2f90b9b50d3d9 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_search_source/create_source_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/es_search_source/create_source_editor.js @@ -20,7 +20,7 @@ import { ScalingForm } from './scaling_form'; import { getTermsFields, supportsGeoTileAgg } from '../../../index_pattern_util'; function getGeoFields(fields) { - return fields.filter(field => { + return fields.filter((field) => { return ( !indexPatterns.isNestedField(field) && [ES_GEO_FIELD_TYPE.GEO_POINT, ES_GEO_FIELD_TYPE.GEO_SHAPE].includes(field.type) @@ -63,7 +63,7 @@ export class CreateSourceEditor extends Component { this._isMounted = true; } - _onIndexPatternSelect = indexPatternId => { + _onIndexPatternSelect = (indexPatternId) => { this.setState( { indexPatternId, @@ -72,7 +72,7 @@ export class CreateSourceEditor extends Component { ); }; - _loadIndexPattern = indexPatternId => { + _loadIndexPattern = (indexPatternId) => { this.setState( { isLoadingIndexPattern: true, @@ -82,7 +82,7 @@ export class CreateSourceEditor extends Component { ); }; - _debouncedLoad = _.debounce(async indexPatternId => { + _debouncedLoad = _.debounce(async (indexPatternId) => { if (!indexPatternId || indexPatternId.length === 0) { return; } @@ -114,7 +114,7 @@ export class CreateSourceEditor extends Component { if (geoFields.length) { // make default selection, prefer aggregatable field over the first available - const firstAggregatableGeoField = geoFields.find(geoField => { + const firstAggregatableGeoField = geoFields.find((geoField) => { return geoField.aggregatable; }); const defaultGeoFieldName = firstAggregatableGeoField @@ -124,7 +124,7 @@ export class CreateSourceEditor extends Component { } }, 300); - _onGeoFieldSelect = geoFieldName => { + _onGeoFieldSelect = (geoFieldName) => { // Respect previous scaling type selection unless newly selected geo field does not support clustering. const scalingType = this.state.scalingType === SCALING_TYPES.CLUSTERS && diff --git a/x-pack/plugins/maps/public/classes/sources/es_search_source/es_search_source.js b/x-pack/plugins/maps/public/classes/sources/es_search_source/es_search_source.js index 21fd8b205b033..51dd57ffad0d1 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_search_source/es_search_source.js +++ b/x-pack/plugins/maps/public/classes/sources/es_search_source/es_search_source.js @@ -38,7 +38,7 @@ function getDocValueAndSourceFields(indexPattern, fieldNames) { const docValueFields = []; const sourceOnlyFields = []; const scriptFields = {}; - fieldNames.forEach(fieldName => { + fieldNames.forEach((fieldName) => { const field = getField(indexPattern, fieldName); if (field.scripted) { scriptFields[field.name] = { @@ -87,7 +87,7 @@ export class ESSearchSource extends AbstractESSource { constructor(descriptor, inspectorAdapters) { super(ESSearchSource.createDescriptor(descriptor), inspectorAdapters); - this._tooltipFields = this._descriptor.tooltipProperties.map(property => + this._tooltipFields = this._descriptor.tooltipProperties.map((property) => this.createField({ fieldName: property }) ); } @@ -124,12 +124,12 @@ export class ESSearchSource extends AbstractESSource { try { const indexPattern = await this.getIndexPattern(); return indexPattern.fields - .filter(field => { + .filter((field) => { // Ensure fielddata is enabled for field. // Search does not request _source return field.aggregatable; }) - .map(field => { + .map((field) => { return this.createField({ fieldName: field.name }); }); } catch (error) { @@ -254,7 +254,7 @@ export class ESSearchSource extends AbstractESSource { // can not compare entityBuckets.length to totalEntities because totalEntities is an approximate const areEntitiesTrimmed = entityBuckets.length >= DEFAULT_MAX_BUCKETS_LIMIT; let areTopHitsTrimmed = false; - entityBuckets.forEach(entityBucket => { + entityBuckets.forEach((entityBucket) => { const total = _.get(entityBucket, 'entityHits.hits.total', 0); const hits = _.get(entityBucket, 'entityHits.hits.hits', []); // Reverse hits list so top documents by sort are drawn on top @@ -347,18 +347,18 @@ export class ESSearchSource extends AbstractESSource { registerCancelCallback ); - const unusedMetaFields = indexPattern.metaFields.filter(metaField => { + const unusedMetaFields = indexPattern.metaFields.filter((metaField) => { return !['_id', '_index'].includes(metaField); }); - const flattenHit = hit => { + const flattenHit = (hit) => { const properties = indexPattern.flattenHit(hit); // remove metaFields - unusedMetaFields.forEach(metaField => { + unusedMetaFields.forEach((metaField) => { delete properties[metaField]; }); return properties; }; - const epochMillisFields = searchFilters.fieldNames.filter(fieldName => { + const epochMillisFields = searchFilters.fieldNames.filter((fieldName) => { const field = getField(indexPattern, fieldName); return field.readFromDocValues && field.type === 'date'; }); @@ -425,7 +425,7 @@ export class ESSearchSource extends AbstractESSource { } const properties = indexPattern.flattenHit(hit); - indexPattern.metaFields.forEach(metaField => { + indexPattern.metaFields.forEach((metaField) => { if (!this._getTooltipPropertyNames().includes(metaField)) { delete properties[metaField]; } @@ -440,7 +440,7 @@ export class ESSearchSource extends AbstractESSource { properties._index, indexPattern ); - const tooltipProperties = this._tooltipFields.map(field => { + const tooltipProperties = this._tooltipFields.map((field) => { const value = propertyValues[field.getName()]; return field.createTooltipProperty(value); }); @@ -456,7 +456,7 @@ export class ESSearchSource extends AbstractESSource { async getLeftJoinFields() { const indexPattern = await this.getIndexPattern(); // Left fields are retrieved from _source. - return getSourceFields(indexPattern.fields).map(field => + return getSourceFields(indexPattern.fields).map((field) => this.createField({ fieldName: field.name }) ); } diff --git a/x-pack/plugins/maps/public/classes/sources/es_search_source/update_source_editor.js b/x-pack/plugins/maps/public/classes/sources/es_search_source/update_source_editor.js index 59b41c2a79532..95e48c9629f57 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_search_source/update_source_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/es_search_source/update_source_editor.js @@ -82,7 +82,7 @@ export class UpdateSourceEditor extends Component { //todo move this all to the source const rawTooltipFields = getSourceFields(indexPattern.fields); - const sourceFields = rawTooltipFields.map(field => { + const sourceFields = rawTooltipFields.map((field) => { return new ESDocField({ fieldName: field.name, source: this.props.source, @@ -94,19 +94,19 @@ export class UpdateSourceEditor extends Component { sourceFields: sourceFields, termFields: getTermsFields(indexPattern.fields), //todo change term fields to use fields sortFields: indexPattern.fields.filter( - field => field.sortable && !indexPatterns.isNestedField(field) + (field) => field.sortable && !indexPatterns.isNestedField(field) ), //todo change sort fields to use fields }); } - _onTooltipPropertiesChange = propertyNames => { + _onTooltipPropertiesChange = (propertyNames) => { this.props.onChange({ propName: 'tooltipProperties', value: propertyNames }); }; - _onSortFieldChange = sortField => { + _onSortFieldChange = (sortField) => { this.props.onChange({ propName: 'sortField', value: sortField }); }; - _onSortOrderChange = e => { + _onSortOrderChange = (e) => { this.props.onChange({ propName: 'sortOrder', value: e.target.value }); }; diff --git a/x-pack/plugins/maps/public/classes/sources/es_source/es_source.js b/x-pack/plugins/maps/public/classes/sources/es_source/es_source.js index 0302531117a6f..072f952fb8a13 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_source/es_source.js +++ b/x-pack/plugins/maps/public/classes/sources/es_source/es_source.js @@ -280,7 +280,7 @@ export class AbstractESSource extends AbstractVectorSource { registerCancelCallback, searchFilters ) { - const promises = dynamicStyleProps.map(dynamicStyleProp => { + const promises = dynamicStyleProps.map((dynamicStyleProp) => { return dynamicStyleProp.getFieldMetaRequest(); }); diff --git a/x-pack/plugins/maps/public/classes/sources/es_term_source/es_term_source.js b/x-pack/plugins/maps/public/classes/sources/es_term_source/es_term_source.js index a6c4afa71dbb2..8cc8dd5c4a080 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_term_source/es_term_source.js +++ b/x-pack/plugins/maps/public/classes/sources/es_term_source/es_term_source.js @@ -24,7 +24,7 @@ const TERMS_BUCKET_KEYS_TO_IGNORE = ['key', 'doc_count']; export function extractPropertiesMap(rawEsData, countPropertyName) { const propertiesMap = new Map(); - _.get(rawEsData, ['aggregations', TERMS_AGG_NAME, 'buckets'], []).forEach(termBucket => { + _.get(rawEsData, ['aggregations', TERMS_AGG_NAME, 'buckets'], []).forEach((termBucket) => { const properties = extractPropertiesFromBucket(termBucket, TERMS_BUCKET_KEYS_TO_IGNORE); if (countPropertyName) { properties[countPropertyName] = termBucket.doc_count; @@ -134,6 +134,6 @@ export class ESTermSource extends AbstractESAggSource { } getFieldNames() { - return this.getMetricFields().map(esAggMetricField => esAggMetricField.getName()); + return this.getMetricFields().map((esAggMetricField) => esAggMetricField.getName()); } } diff --git a/x-pack/plugins/maps/public/classes/sources/kibana_regionmap_source/kibana_regionmap_source.js b/x-pack/plugins/maps/public/classes/sources/kibana_regionmap_source/kibana_regionmap_source.js index fb5a2e4f42f1d..eeb34ed672221 100644 --- a/x-pack/plugins/maps/public/classes/sources/kibana_regionmap_source/kibana_regionmap_source.js +++ b/x-pack/plugins/maps/public/classes/sources/kibana_regionmap_source/kibana_regionmap_source.js @@ -51,7 +51,7 @@ export class KibanaRegionmapSource extends AbstractVectorSource { async getVectorFileMeta() { const regionList = getKibanaRegionList(); - const meta = regionList.find(source => source.name === this._descriptor.name); + const meta = regionList.find((source) => source.name === this._descriptor.name); if (!meta) { throw new Error( i18n.translate('xpack.maps.source.kbnRegionMap.noConfigErrorMessage', { @@ -79,7 +79,7 @@ export class KibanaRegionmapSource extends AbstractVectorSource { async getLeftJoinFields() { const vectorFileMeta = await this.getVectorFileMeta(); - return vectorFileMeta.fields.map(f => this.createField({ fieldName: f.name })); + return vectorFileMeta.fields.map((f) => this.createField({ fieldName: f.name })); } async getDisplayName() { diff --git a/x-pack/plugins/maps/public/classes/sources/tms_source/tms_source.js b/x-pack/plugins/maps/public/classes/sources/tms_source/tms_source.js index 13b8da11633bc..7fd83f1201846 100644 --- a/x-pack/plugins/maps/public/classes/sources/tms_source/tms_source.js +++ b/x-pack/plugins/maps/public/classes/sources/tms_source/tms_source.js @@ -12,7 +12,7 @@ export class AbstractTMSSource extends AbstractSource { } convertMarkdownLinkToObjectArr(markdown) { - return markdown.split('|').map(attribution => { + return markdown.split('|').map((attribution) => { attribution = attribution.trim(); //this assumes attribution is plain markdown link const extractLink = /\[(.*)\]\((.*)\)/; diff --git a/x-pack/plugins/maps/public/classes/sources/vector_source/vector_source.js b/x-pack/plugins/maps/public/classes/sources/vector_source/vector_source.js index 12e1780d9cad5..ccf6c7963c9b4 100644 --- a/x-pack/plugins/maps/public/classes/sources/vector_source/vector_source.js +++ b/x-pack/plugins/maps/public/classes/sources/vector_source/vector_source.js @@ -73,7 +73,7 @@ export class AbstractVectorSource extends AbstractSource { } _getTooltipPropertyNames() { - return this._tooltipFields.map(field => field.getName()); + return this._tooltipFields.map((field) => field.getName()); } isFilterByMapBounds() { diff --git a/x-pack/plugins/maps/public/classes/sources/wms_source/wms_create_source_editor.js b/x-pack/plugins/maps/public/classes/sources/wms_source/wms_create_source_editor.js index f676abc668341..df00faf43daa3 100644 --- a/x-pack/plugins/maps/public/classes/sources/wms_source/wms_create_source_editor.js +++ b/x-pack/plugins/maps/public/classes/sources/wms_source/wms_create_source_editor.js @@ -102,7 +102,7 @@ export class WMSCreateSourceEditor extends Component { }); }; - _handleServiceUrlChange = e => { + _handleServiceUrlChange = (e) => { this.setState( { serviceUrl: e.target.value, @@ -118,16 +118,16 @@ export class WMSCreateSourceEditor extends Component { ); }; - _handleLayersChange = e => { + _handleLayersChange = (e) => { this.setState({ layers: e.target.value }, this._previewIfPossible); }; - _handleLayerOptionsChange = selectedOptions => { + _handleLayerOptionsChange = (selectedOptions) => { this.setState( { selectedLayerOptions: selectedOptions, layers: selectedOptions - .map(selectedOption => { + .map((selectedOption) => { return selectedOption.value; }) .join(','), @@ -136,16 +136,16 @@ export class WMSCreateSourceEditor extends Component { ); }; - _handleStylesChange = e => { + _handleStylesChange = (e) => { this.setState({ styles: e.target.value }, this._previewIfPossible); }; - _handleStyleOptionsChange = selectedOptions => { + _handleStyleOptionsChange = (selectedOptions) => { this.setState( { selectedStyleOptions: selectedOptions, styles: selectedOptions - .map(selectedOption => { + .map((selectedOption) => { return selectedOption.value; }) .join(','), diff --git a/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/xyz_tms_editor.tsx b/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/xyz_tms_editor.tsx index 0ee0fbb23bcff..715ff0e4c2fdd 100644 --- a/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/xyz_tms_editor.tsx +++ b/x-pack/plugins/maps/public/classes/sources/xyz_tms_source/xyz_tms_editor.tsx @@ -81,7 +81,7 @@ export class XYZTMSEditor extends Component { this._handleTMSInputChange(e)} + onChange={(e) => this._handleTMSInputChange(e)} /> - tinycolor(color) - .darken() - .toHexString() - ), + ...DEFAULT_FILL_COLORS.map((color) => tinycolor(color).darken().toHexString()), // Explicitly add black & white as border color options '#000', '#FFF', @@ -61,7 +57,7 @@ export function getRGBColorRangeStrings(colorRampName, numberColors = GRADIENT_I } export function getHexColorRangeStrings(colorRampName, numberColors = GRADIENT_INTERVALS) { - return getRGBColorRangeStrings(colorRampName, numberColors).map(rgbColor => + return getRGBColorRangeStrings(colorRampName, numberColors).map((rgbColor) => chroma(rgbColor).hex() ); } @@ -99,7 +95,7 @@ export function getOrdinalColorRampStops(colorRampName, min, max) { }, []); } -export const COLOR_GRADIENTS = Object.keys(vislibColorMaps).map(colorRampName => ({ +export const COLOR_GRADIENTS = Object.keys(vislibColorMaps).map((colorRampName) => ({ value: colorRampName, inputDisplay: , })); @@ -132,12 +128,12 @@ const COLOR_PALETTES_CONFIGS = [ ]; export function getColorPalette(paletteId) { - const palette = COLOR_PALETTES_CONFIGS.find(palette => palette.id === paletteId); + const palette = COLOR_PALETTES_CONFIGS.find((palette) => palette.id === paletteId); return palette ? palette.colors : null; } -export const COLOR_PALETTES = COLOR_PALETTES_CONFIGS.map(palette => { - const paletteDisplay = palette.colors.map(color => { +export const COLOR_PALETTES = COLOR_PALETTES_CONFIGS.map((palette) => { + const paletteDisplay = palette.colors.map((color) => { const style = { backgroundColor: color, width: `${100 / palette.colors.length}%`, diff --git a/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_style_editor.js b/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_style_editor.js index a0f86dcf5130b..6d38a7985269e 100644 --- a/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_style_editor.js +++ b/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_style_editor.js @@ -16,7 +16,7 @@ import { } from './heatmap_constants'; export function HeatmapStyleEditor({ colorRampName, onHeatmapColorChange }) { - const onColorRampChange = selectedColorRampName => { + const onColorRampChange = (selectedColorRampName) => { onHeatmapColorChange({ colorRampName: selectedColorRampName, }); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_map_select.js b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_map_select.js index eadaf42ca694d..b7a80562f10ca 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_map_select.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_map_select.js @@ -65,7 +65,7 @@ export class ColorMapSelect extends Component { ); } - _onColorMapSelect = selectedValue => { + _onColorMapSelect = (selectedValue) => { const useCustomColorMap = selectedValue === CUSTOM_COLOR_MAP; this.props.onChange({ color: useCustomColorMap ? null : selectedValue, @@ -134,7 +134,9 @@ export class ColorMapSelect extends Component { if (this.props.useCustomColorMap) { valueOfSelected = CUSTOM_COLOR_MAP; } else { - valueOfSelected = this.props.colorMapOptions.find(option => option.value === this.props.color) + valueOfSelected = this.props.colorMapOptions.find( + (option) => option.value === this.props.color + ) ? this.props.color : ''; } diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops.js b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops.js index 20fd97a229352..4a632153c4596 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops.js @@ -22,7 +22,7 @@ export const ColorStops = ({ swatches, }) => { function getStopInput(stop, index) { - const onStopChange = newStopValue => { + const onStopChange = (newStopValue) => { const newColorStops = _.cloneDeep(colorStops); newColorStops[index].stop = newStopValue; onChange({ @@ -38,7 +38,7 @@ export const ColorStops = ({ } const rows = colorStops.map((colorStop, index) => { - const onColorChange = color => { + const onColorChange = (color) => { const newColorStops = _.cloneDeep(colorStops); newColorStops[index].color = color; onChange({ diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_ordinal.js b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_ordinal.js index 4e2d07b9dfea0..d52c769c95a7d 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_ordinal.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_ordinal.js @@ -57,7 +57,7 @@ export const ColorStopsOrdinal = ({ ); }; - const canDeleteStop = colorStops => { + const canDeleteStop = (colorStops) => { return colorStops.length > 1; }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_utils.js b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_utils.js index 3eaa6acf435dc..c8888b2e438f1 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_utils.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_stops_utils.js @@ -61,7 +61,7 @@ export function isOrdinalStopInvalid(stop) { export function isCategoricalStopsInvalid(colorStops) { const nonDefaults = colorStops.slice(1); // - const values = nonDefaults.map(stop => stop.stop); + const values = nonDefaults.map((stop) => stop.stop); const uniques = _.uniq(values); return values.length !== uniques.length; } diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/color/dynamic_color_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/color/dynamic_color_form.js index 460e7379920c4..fa13e1cf66664 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/color/dynamic_color_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/color/dynamic_color_form.js @@ -60,7 +60,7 @@ export function DynamicColorForm({ }); }; - const onColorMapTypeChange = async e => { + const onColorMapTypeChange = async (e) => { const colorMapType = e.target.value; onDynamicStyleChange(styleProperty.getStyleName(), { ...styleOptions, @@ -74,7 +74,7 @@ export function DynamicColorForm({ return null; } - return fields.find(field => { + return fields.find((field) => { return field.name === fieldName; }); }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/color/static_color_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/color/static_color_form.js index a295556ee3126..cfd7a8e41fe1c 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/color/static_color_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/color/static_color_form.js @@ -14,7 +14,7 @@ export function StaticColorForm({ styleProperty, swatches, }) { - const onColorChange = color => { + const onColorChange = (color) => { onStaticStyleChange(styleProperty.getStyleName(), { color }); }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/field_select.js b/x-pack/plugins/maps/public/classes/styles/vector/components/field_select.js index ed2e7a4eab7ec..51700a5e83394 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/field_select.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/field_select.js @@ -27,7 +27,7 @@ function renderOption(option, searchValue, contentClassName) { function groupFieldsByOrigin(fields) { const fieldsByOriginMap = new Map(); - fields.forEach(field => { + fields.forEach((field) => { if (fieldsByOriginMap.has(field.origin)) { const fieldsList = fieldsByOriginMap.get(field.origin); fieldsList.push(field); @@ -39,7 +39,7 @@ function groupFieldsByOrigin(fields) { function fieldsListToOptions(fieldsList) { return fieldsList - .map(field => { + .map((field) => { return { value: field, label: field.label }; }) .sort((a, b) => { @@ -73,7 +73,7 @@ function groupFieldsByOrigin(fields) { } export function FieldSelect({ fields, selectedFieldName, onChange, styleName, ...rest }) { - const onFieldChange = selectedFields => { + const onFieldChange = (selectedFields) => { onChange({ field: selectedFields.length > 0 ? selectedFields[0].value : null, }); @@ -81,7 +81,7 @@ export function FieldSelect({ fields, selectedFieldName, onChange, styleName, .. let selectedOption; if (selectedFieldName) { - selectedOption = fields.find(field => { + selectedOption = fields.find((field) => { return field.name === selectedFieldName; }); } diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/label/static_label_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/label/static_label_form.js index 3b7145fdfc884..399d9beddb47a 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/label/static_label_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/label/static_label_form.js @@ -9,7 +9,7 @@ import { i18n } from '@kbn/i18n'; import { EuiFieldText, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; export function StaticLabelForm({ onStaticStyleChange, staticDynamicSelect, styleProperty }) { - const onValueChange = event => { + const onValueChange = (event) => { onStaticStyleChange(styleProperty.getStyleName(), { value: event.target.value }); }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/legend/vector_style_legend.js b/x-pack/plugins/maps/public/classes/styles/vector/components/legend/vector_style_legend.js index a7e98c83468ae..f535385b1f756 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/legend/vector_style_legend.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/legend/vector_style_legend.js @@ -7,7 +7,7 @@ import React, { Fragment } from 'react'; export function VectorStyleLegend({ isLinesOnly, isPointsOnly, styles, symbolId }) { - return styles.map(style => { + return styles.map((style) => { return ( {style.renderLegendDetailRow({ diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/orientation/static_orientation_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/orientation/static_orientation_form.js index b28743f426262..0d24fb5a5f155 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/orientation/static_orientation_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/orientation/static_orientation_form.js @@ -9,7 +9,7 @@ import { ValidatedRange } from '../../../../../components/validated_range'; import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; export function StaticOrientationForm({ onStaticStyleChange, staticDynamicSelect, styleProperty }) { - const onOrientationChange = orientation => { + const onOrientationChange = (orientation) => { onStaticStyleChange(styleProperty.getStyleName(), { orientation }); }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/size/static_size_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/size/static_size_form.js index 90e540cc6802a..8845e113ec7ae 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/size/static_size_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/size/static_size_form.js @@ -10,7 +10,7 @@ import { i18n } from '@kbn/i18n'; import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; export function StaticSizeForm({ onStaticStyleChange, staticDynamicSelect, styleProperty }) { - const onSizeChange = size => { + const onSizeChange = (size) => { onStaticStyleChange(styleProperty.getStyleName(), { size }); }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/stop_input.js b/x-pack/plugins/maps/public/classes/styles/vector/components/stop_input.js index 93d9375972545..64a5f806e34c4 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/stop_input.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/stop_input.js @@ -45,15 +45,15 @@ export class StopInput extends Component { } }; - _onChange = selectedOptions => { + _onChange = (selectedOptions) => { this.props.onChange(_.get(selectedOptions, '[0].label', '')); }; - _onCreateOption = newValue => { + _onCreateOption = (newValue) => { this.props.onChange(newValue); }; - _onSearchChange = async searchValue => { + _onSearchChange = async (searchValue) => { this.setState( { isLoadingSuggestions: true, @@ -65,7 +65,7 @@ export class StopInput extends Component { ); }; - _loadSuggestions = _.debounce(async searchValue => { + _loadSuggestions = _.debounce(async (searchValue) => { let suggestions = []; try { suggestions = await this.props.getValueSuggestions(searchValue); @@ -81,7 +81,7 @@ export class StopInput extends Component { } }, 300); - _onFieldTextChange = event => { + _onFieldTextChange = (event) => { this.setState({ localFieldTextValue: event.target.value }); // onChange can cause UI lag, ensure smooth input typing by debouncing onChange this._debouncedOnFieldTextChange(); @@ -92,7 +92,7 @@ export class StopInput extends Component { }, 500); _renderSuggestionInput() { - const suggestionOptions = this.state.suggestions.map(suggestion => { + const suggestionOptions = this.state.suggestions.map((suggestion) => { return { label: `${suggestion}` }; }); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/style_map_select.js b/x-pack/plugins/maps/public/classes/styles/vector/components/style_map_select.js index 28d5454afa4ba..e285d91dcd7a4 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/style_map_select.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/style_map_select.js @@ -24,7 +24,7 @@ export class StyleMapSelect extends Component { }; } - _onMapSelect = selectedValue => { + _onMapSelect = (selectedValue) => { const useCustomMap = selectedValue === CUSTOM_MAP; this.props.onChange({ selectedMapId: useCustomMap ? null : selectedValue, @@ -71,7 +71,9 @@ export class StyleMapSelect extends Component { if (this.props.useCustomMap) { valueOfSelected = CUSTOM_MAP; } else { - valueOfSelected = this.props.options.find(option => option.value === this.props.selectedMapId) + valueOfSelected = this.props.options.find( + (option) => option.value === this.props.selectedMapId + ) ? this.props.selectedMapId : ''; } diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/style_prop_editor.js b/x-pack/plugins/maps/public/classes/styles/vector/components/style_prop_editor.js index 005bc11aa1bd8..e7df47bc6d4cb 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/style_prop_editor.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/style_prop_editor.js @@ -41,7 +41,7 @@ export class StylePropEditor extends Component { } }; - _onFieldMetaOptionsChange = fieldMetaOptions => { + _onFieldMetaOptionsChange = (fieldMetaOptions) => { const options = { ...this.props.styleProperty.getOptions(), fieldMetaOptions, diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/dynamic_icon_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/dynamic_icon_form.js index 6b79ac17f2e22..f9f8a67846470 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/dynamic_icon_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/dynamic_icon_form.js @@ -28,7 +28,7 @@ export function DynamicIconForm({ }); }; - const onIconMapChange = newOptions => { + const onIconMapChange = (newOptions) => { onDynamicStyleChange(styleProperty.getStyleName(), { ...styleOptions, ...newOptions, diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.js index a036423e71709..01c1719f5bcef 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.js @@ -34,12 +34,12 @@ export class IconSelect extends Component { }; _togglePopover = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; - _handleKeyboardActivity = e => { + _handleKeyboardActivity = (e) => { if (isKeyboardEvent(e)) { if (e.keyCode === keyCodes.ENTER) { e.preventDefault(); @@ -50,8 +50,8 @@ export class IconSelect extends Component { } }; - _onIconSelect = options => { - const selectedOption = options.find(option => { + _onIconSelect = (options) => { + const selectedOption = options.find((option) => { return option.checked === 'on'; }); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.js index 0da3074f55e49..81a44fcaadbd3 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.js @@ -21,7 +21,7 @@ function isDuplicateStop(targetStop, iconStops) { } export function getFirstUnusedSymbol(symbolOptions, iconStops) { - const firstUnusedPreferredIconId = PREFERRED_ICONS.find(iconId => { + const firstUnusedPreferredIconId = PREFERRED_ICONS.find((iconId) => { const isSymbolBeingUsed = iconStops.some(({ icon }) => { return icon === iconId; }); @@ -56,7 +56,7 @@ export function IconStops({ symbolOptions, }) { return iconStops.map(({ stop, icon }, index) => { - const onIconSelect = selectedIconId => { + const onIconSelect = (selectedIconId) => { const newIconStops = [...iconStops]; newIconStops[index] = { ...iconStops[index], @@ -64,7 +64,7 @@ export function IconStops({ }; onChange({ customMapStops: newIconStops }); }; - const onStopChange = newStopValue => { + const onStopChange = (newStopValue) => { const newIconStops = [...iconStops]; newIconStops[index] = { ...iconStops[index], diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/static_icon_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/static_icon_form.js index 9b00b2fe38d7b..56e5737f72449 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/static_icon_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/static_icon_form.js @@ -15,7 +15,7 @@ export function StaticIconForm({ styleProperty, symbolOptions, }) { - const onChange = selectedIconId => { + const onChange = (selectedIconId) => { onStaticStyleChange(styleProperty.getStyleName(), { value: selectedIconId }); }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/vector_style_symbolize_as_editor.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/vector_style_symbolize_as_editor.js index cf287e8b1fd5f..12b9fb846df58 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/vector_style_symbolize_as_editor.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/vector_style_symbolize_as_editor.js @@ -38,7 +38,7 @@ export function VectorStyleSymbolizeAsEditor({ return id === styleOptions.value; }); - const onSymbolizeAsChange = optionId => { + const onSymbolizeAsChange = (optionId) => { const styleDescriptor = { options: { value: optionId, diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/vector_style_editor.js b/x-pack/plugins/maps/public/classes/styles/vector/components/vector_style_editor.js index c46dc2cb4b73e..3424a972fed06 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/vector_style_editor.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/vector_style_editor.js @@ -56,7 +56,7 @@ export class VectorStyleEditor extends Component { } async _loadFields() { - const getFieldMeta = async field => { + const getFieldMeta = async (field) => { return { label: await field.getLabel(), name: field.getName(), @@ -75,13 +75,13 @@ export class VectorStyleEditor extends Component { this.setState({ fields: fieldsArrayAll, - ordinalAndCategoricalFields: fieldsArrayAll.filter(field => { + ordinalAndCategoricalFields: fieldsArrayAll.filter((field) => { return ( CATEGORICAL_DATA_TYPES.includes(field.type) || ORDINAL_DATA_TYPES.includes(field.type) ); }), - dateFields: fieldsArrayAll.filter(field => field.type === 'date'), - numberFields: fieldsArrayAll.filter(field => field.type === 'number'), + dateFields: fieldsArrayAll.filter((field) => field.type === 'date'), + numberFields: fieldsArrayAll.filter((field) => field.type === 'number'), }); } @@ -112,11 +112,11 @@ export class VectorStyleEditor extends Component { return [...this.state.dateFields, ...this.state.numberFields]; } - _handleSelectedFeatureChange = selectedFeature => { + _handleSelectedFeatureChange = (selectedFeature) => { this.setState({ selectedFeature }); }; - _onIsTimeAwareChange = event => { + _onIsTimeAwareChange = (event) => { this.props.onIsTimeAwareChange(event.target.checked); }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.test.js b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.test.js index f4c2b8d926075..afcdf1e3cfc5b 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.test.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.test.js @@ -20,7 +20,7 @@ import { mockField, MockLayer } from './__tests__/test_util'; const makeProperty = (options, field = mockField) => { return new DynamicColorProperty(options, VECTOR_STYLES.LINE_COLOR, field, new MockLayer(), () => { - return x => x + '_format'; + return (x) => x + '_format'; }); }; @@ -63,7 +63,7 @@ test('Should render ordinal legend with breaks', async () => { const component = shallow(legendRow); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -82,7 +82,7 @@ test('Should render categorical legend with breaks from default', async () => { const component = shallow(legendRow); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -117,7 +117,7 @@ test('Should render categorical legend with breaks from custom', async () => { }); function makeFeatures(foobarPropValues) { - return foobarPropValues.map(value => { + return foobarPropValues.map((value) => { return { type: 'Feature', properties: { @@ -194,7 +194,7 @@ describe('supportsFieldMeta', () => { test('should not support it when field does not', () => { const field = Object.create(mockField); - field.supportsFieldMeta = function() { + field.supportsFieldMeta = function () { return false; }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_icon_property.test.tsx b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_icon_property.test.tsx index c271943213027..505c08ac35ba7 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_icon_property.test.tsx +++ b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_icon_property.test.tsx @@ -54,7 +54,7 @@ test('Should render categorical legend with breaks', async () => { const legendRow = iconStyle.renderLegendDetailRow({ isPointsOnly: true, isLinesOnly: false }); const component = shallow(legendRow); - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); component.update(); expect(component).toMatchSnapshot(); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_style_property.js b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_style_property.js index 56a461a3bb147..82645b3a29319 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_style_property.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_style_property.js @@ -24,7 +24,7 @@ export class DynamicStyleProperty extends AbstractStyleProperty { this._getFieldFormatter = getFieldFormatter; } - getValueSuggestions = query => { + getValueSuggestions = (query) => { const field = this.getField(); const fieldSource = this._getFieldSource(); return fieldSource && field ? fieldSource.getValueSuggestions(field, query) : []; @@ -35,7 +35,7 @@ export class DynamicStyleProperty extends AbstractStyleProperty { return SOURCE_META_ID_ORIGIN; } - const join = this._layer.getValidJoins().find(join => { + const join = this._layer.getValidJoins().find((join) => { return join.getRightJoinSource().hasMatchingMetricField(fieldName); }); return join ? join.getSourceMetaDataRequestId() : null; @@ -258,7 +258,7 @@ export class DynamicStyleProperty extends AbstractStyleProperty { return null; } - const ordered = fieldMetaData[rootFieldName].buckets.map(bucket => { + const ordered = fieldMetaData[rootFieldName].buckets.map((bucket) => { return { key: bucket.key, count: bucket.doc_count, diff --git a/x-pack/plugins/maps/public/classes/styles/vector/symbol_utils.js b/x-pack/plugins/maps/public/classes/styles/vector/symbol_utils.js index c1c4375faaeb1..1672af8eccff8 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/symbol_utils.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/symbol_utils.js @@ -16,7 +16,7 @@ export const SMALL_MAKI_ICON_SIZE = 11; export const HALF_LARGE_MAKI_ICON_SIZE = Math.ceil(LARGE_MAKI_ICON_SIZE); export const SYMBOLS = {}; -maki.svgArray.forEach(svgString => { +maki.svgArray.forEach((svgString) => { const ID_FRAG = 'id="'; const index = svgString.indexOf(ID_FRAG); if (index !== -1) { @@ -32,7 +32,7 @@ maki.svgArray.forEach(svgString => { } }); -export const SYMBOL_OPTIONS = Object.keys(SYMBOLS).map(symbolId => { +export const SYMBOL_OPTIONS = Object.keys(SYMBOLS).map((symbolId) => { return { value: symbolId, label: symbolId, @@ -103,8 +103,8 @@ const ICON_PALETTES = [ // PREFERRED_ICONS is used to provide less random default icon values for forms that need default icon values export const PREFERRED_ICONS = []; -ICON_PALETTES.forEach(iconPalette => { - iconPalette.icons.forEach(iconId => { +ICON_PALETTES.forEach((iconPalette) => { + iconPalette.icons.forEach((iconId) => { if (!PREFERRED_ICONS.includes(iconId)) { PREFERRED_ICONS.push(iconId); } @@ -113,7 +113,7 @@ ICON_PALETTES.forEach(iconPalette => { export function getIconPaletteOptions(isDarkMode) { return ICON_PALETTES.map(({ id, icons }) => { - const iconsDisplay = icons.map(iconId => { + const iconsDisplay = icons.map((iconId) => { const style = { width: '10%', position: 'relative', diff --git a/x-pack/plugins/maps/public/classes/styles/vector/vector_style.js b/x-pack/plugins/maps/public/classes/styles/vector/vector_style.js index 5a4edd9c93a05..f3ed18bd1302e 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/vector_style.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/vector_style.js @@ -151,17 +151,17 @@ export class VectorStyle extends AbstractStyle { onStyleDescriptorChange(vectorStyleDescriptor); }; - const onIsTimeAwareChange = isTimeAware => { + const onIsTimeAwareChange = (isTimeAware) => { const vectorStyleDescriptor = VectorStyle.createDescriptor(rawProperties, isTimeAware); onStyleDescriptorChange(vectorStyleDescriptor); }; - const propertiesWithFieldMeta = this.getDynamicPropertiesArray().filter(dynamicStyleProp => { + const propertiesWithFieldMeta = this.getDynamicPropertiesArray().filter((dynamicStyleProp) => { return dynamicStyleProp.isFieldMetaEnabled(); }); const styleProperties = {}; - this.getAllStyleProperties().forEach(styleProperty => { + this.getAllStyleProperties().forEach((styleProperty) => { styleProperties[styleProperty.getStyleName()] = styleProperty; }); @@ -195,12 +195,12 @@ export class VectorStyle extends AbstractStyle { const originalProperties = this.getRawProperties(); const updatedProperties = {}; - const dynamicProperties = Object.keys(originalProperties).filter(key => { + const dynamicProperties = Object.keys(originalProperties).filter((key) => { const { type, options } = originalProperties[key] || {}; return type === STYLE_TYPE.DYNAMIC && options.field && options.field.name; }); - dynamicProperties.forEach(key => { + dynamicProperties.forEach((key) => { const dynamicProperty = originalProperties[key]; const fieldName = dynamicProperty && dynamicProperty.options.field && dynamicProperty.options.field.name; @@ -208,7 +208,7 @@ export class VectorStyle extends AbstractStyle { return; } - const matchingOrdinalField = nextFields.find(ordinalField => { + const matchingOrdinalField = nextFields.find((ordinalField) => { return fieldName === ordinalField.getName(); }); @@ -298,7 +298,7 @@ export class VectorStyle extends AbstractStyle { return styleMeta; } - dynamicProperties.forEach(dynamicProperty => { + dynamicProperties.forEach((dynamicProperty) => { const categoricalStyleMeta = dynamicProperty.pluckCategoricalStyleMetaFromFeatures(features); const ordinalStyleMeta = dynamicProperty.pluckOrdinalStyleMetaFromFeatures(features); const name = dynamicProperty.getField().getName(); @@ -319,7 +319,7 @@ export class VectorStyle extends AbstractStyle { getSourceFieldNames() { const fieldNames = []; - this.getDynamicPropertiesArray().forEach(styleProperty => { + this.getDynamicPropertiesArray().forEach((styleProperty) => { if (styleProperty.getFieldOrigin() === FIELD_ORIGIN.SOURCE) { fieldNames.push(styleProperty.getField().getName()); } @@ -338,7 +338,7 @@ export class VectorStyle extends AbstractStyle { getDynamicPropertiesArray() { const styleProperties = this.getAllStyleProperties(); return styleProperties.filter( - styleProperty => styleProperty.isDynamic() && styleProperty.isComplete() + (styleProperty) => styleProperty.isDynamic() && styleProperty.isComplete() ); } @@ -356,7 +356,7 @@ export class VectorStyle extends AbstractStyle { _getDynamicPropertyByFieldName(fieldName) { const dynamicProps = this.getDynamicPropertiesArray(); - return dynamicProps.find(dynamicProp => { + return dynamicProps.find((dynamicProp) => { return fieldName === dynamicProp.getField().getName(); }); } @@ -365,7 +365,7 @@ export class VectorStyle extends AbstractStyle { return this._styleMeta; } - _getFieldFormatter = fieldName => { + _getFieldFormatter = (fieldName) => { const dynamicProp = this._getDynamicPropertyByFieldName(fieldName); if (!dynamicProp) { return null; @@ -375,7 +375,7 @@ export class VectorStyle extends AbstractStyle { if (dynamicProp.getFieldOrigin() === FIELD_ORIGIN.SOURCE) { dataRequestId = SOURCE_FORMATTERS_ID_ORIGIN; } else { - const join = this._layer.getValidJoins().find(join => { + const join = this._layer.getValidJoins().find((join) => { return join.getRightJoinSource().hasMatchingMetricField(fieldName); }); if (join) { @@ -435,7 +435,7 @@ export class VectorStyle extends AbstractStyle { }; _getLegendDetailStyleProperties = () => { - return this.getDynamicPropertiesArray().filter(styleProperty => { + return this.getDynamicPropertiesArray().filter((styleProperty) => { const styleName = styleProperty.getStyleName(); if ([VECTOR_STYLES.ICON_ORIENTATION, VECTOR_STYLES.LABEL_TEXT].includes(styleName)) { return false; @@ -528,7 +528,7 @@ export class VectorStyle extends AbstractStyle { //this return-value is used in an optimization for style-updates with mapbox-gl. //`true` indicates the entire data needs to reset on the source (otherwise the style-rules will not be reapplied) //`false` indicates the data does not need to be reset on the store, because styles are re-evaluated if they use featureState - return dynamicStyleProps.some(dynamicStyleProp => !dynamicStyleProp.supportsMbFeatureState()); + return dynamicStyleProps.some((dynamicStyleProp) => !dynamicStyleProp.supportsMbFeatureState()); } arePointsSymbolizedAsCircles() { @@ -588,7 +588,7 @@ export class VectorStyle extends AbstractStyle { if (fieldDescriptor.origin === FIELD_ORIGIN.SOURCE) { return this._source.getFieldByName(fieldDescriptor.name); } else if (fieldDescriptor.origin === FIELD_ORIGIN.JOIN) { - const join = this._layer.getValidJoins().find(join => { + const join = this._layer.getValidJoins().find((join) => { return join.getRightJoinSource().hasMatchingMetricField(fieldDescriptor.name); }); return join ? join.getRightJoinSource().getMetricFieldForName(fieldDescriptor.name) : null; diff --git a/x-pack/plugins/maps/public/classes/util/get_feature_collection_bounds.ts b/x-pack/plugins/maps/public/classes/util/get_feature_collection_bounds.ts index 4247233b295e1..aa78d7064fb0a 100644 --- a/x-pack/plugins/maps/public/classes/util/get_feature_collection_bounds.ts +++ b/x-pack/plugins/maps/public/classes/util/get_feature_collection_bounds.ts @@ -19,7 +19,7 @@ export function getFeatureCollectionBounds( } const visibleFeatures = hasJoins - ? featureCollection.features.filter(feature => { + ? featureCollection.features.filter((feature) => { return feature.properties && feature.properties[FEATURE_VISIBLE_PROPERTY_NAME]; }) : featureCollection.features; diff --git a/x-pack/plugins/maps/public/components/geometry_filter_form.js b/x-pack/plugins/maps/public/components/geometry_filter_form.js index ac6461345e8bf..d5cdda3c1c324 100644 --- a/x-pack/plugins/maps/public/components/geometry_filter_form.js +++ b/x-pack/plugins/maps/public/components/geometry_filter_form.js @@ -41,17 +41,17 @@ export class GeometryFilterForm extends Component { relation: ES_SPATIAL_RELATIONS.INTERSECTS, }; - _onGeoFieldChange = selectedField => { + _onGeoFieldChange = (selectedField) => { this.setState({ selectedField }); }; - _onGeometryLabelChange = e => { + _onGeometryLabelChange = (e) => { this.setState({ geometryLabel: e.target.value, }); }; - _onRelationChange = e => { + _onRelationChange = (e) => { this.setState({ relation: e.target.value, }); @@ -78,11 +78,11 @@ export class GeometryFilterForm extends Component { const spatialRelations = this.props.isFilterGeometryClosed ? Object.values(ES_SPATIAL_RELATIONS) - : Object.values(ES_SPATIAL_RELATIONS).filter(relation => { + : Object.values(ES_SPATIAL_RELATIONS).filter((relation) => { // can not filter by within relation when filtering geometry is not closed return relation !== ES_SPATIAL_RELATIONS.WITHIN; }); - const options = spatialRelations.map(relation => { + const options = spatialRelations.map((relation) => { return { value: relation, text: getEsSpatialRelationLabel(relation), diff --git a/x-pack/plugins/maps/public/components/global_filter_checkbox.js b/x-pack/plugins/maps/public/components/global_filter_checkbox.js index a8c2908e75424..004bb73f357e1 100644 --- a/x-pack/plugins/maps/public/components/global_filter_checkbox.js +++ b/x-pack/plugins/maps/public/components/global_filter_checkbox.js @@ -8,7 +8,7 @@ import React from 'react'; import { EuiFormRow, EuiSwitch } from '@elastic/eui'; export function GlobalFilterCheckbox({ applyGlobalQuery, label, setApplyGlobalQuery }) { - const onApplyGlobalQueryChange = event => { + const onApplyGlobalQueryChange = (event) => { setApplyGlobalQuery(event.target.checked); }; diff --git a/x-pack/plugins/maps/public/components/map_listing.js b/x-pack/plugins/maps/public/components/map_listing.js index ee10fe30130f3..030b67185c106 100644 --- a/x-pack/plugins/maps/public/components/map_listing.js +++ b/x-pack/plugins/maps/public/components/map_listing.js @@ -58,7 +58,7 @@ export class MapListing extends React.Component { addHelpMenuToAppChrome(); } - debouncedFetch = _.debounce(async filter => { + debouncedFetch = _.debounce(async (filter) => { const response = await this.props.find(filter); if (!this._isMounted) { @@ -282,7 +282,7 @@ export class MapListing extends React.Component { })} fullWidth value={this.state.filter} - onChange={e => { + onChange={(e) => { this.setState( { filter: e.target.value, @@ -333,9 +333,9 @@ export class MapListing extends React.Component { let selection = false; if (!this.props.readOnly) { selection = { - onSelectionChange: selection => { + onSelectionChange: (selection) => { this.setState({ - selectedIds: selection.map(item => { + selectedIds: selection.map((item) => { return item.id; }), }); diff --git a/x-pack/plugins/maps/public/components/metric_editor.js b/x-pack/plugins/maps/public/components/metric_editor.js index d1affe2f42190..96b52d84653b2 100644 --- a/x-pack/plugins/maps/public/components/metric_editor.js +++ b/x-pack/plugins/maps/public/components/metric_editor.js @@ -29,13 +29,13 @@ function filterFieldsForAgg(fields, aggType) { metricAggFieldTypes.push('date'); } - return fields.filter(field => { + return fields.filter((field) => { return field.aggregatable && metricAggFieldTypes.includes(field.type); }); } export function MetricEditor({ fields, metricsFilter, metric, onChange, removeButton }) { - const onAggChange = metricAggregationType => { + const onAggChange = (metricAggregationType) => { const newMetricProps = { ...metric, type: metricAggregationType, @@ -44,7 +44,7 @@ export function MetricEditor({ fields, metricsFilter, metric, onChange, removeBu // unset field when new agg type does not support currently selected field. if (metric.field && metricAggregationType !== AGG_TYPE.COUNT) { const fieldsForNewAggType = filterFieldsForAgg(fields, metricAggregationType); - const found = fieldsForNewAggType.find(field => { + const found = fieldsForNewAggType.find((field) => { return field.name === metric.field; }); if (!found) { @@ -54,13 +54,13 @@ export function MetricEditor({ fields, metricsFilter, metric, onChange, removeBu onChange(newMetricProps); }; - const onFieldChange = fieldName => { + const onFieldChange = (fieldName) => { onChange({ ...metric, field: fieldName, }); }; - const onLabelChange = e => { + const onLabelChange = (e) => { onChange({ ...metric, label: e.target.value, diff --git a/x-pack/plugins/maps/public/components/metric_select.js b/x-pack/plugins/maps/public/components/metric_select.js index cf29583eeab44..2ebfcf99dece6 100644 --- a/x-pack/plugins/maps/public/components/metric_select.js +++ b/x-pack/plugins/maps/public/components/metric_select.js @@ -79,7 +79,7 @@ export function MetricSelect({ value, onChange, metricsFilter, ...rest }) { singleSelection={true} isClearable={false} options={options} - selectedOptions={AGG_OPTIONS.filter(option => { + selectedOptions={AGG_OPTIONS.filter((option) => { return value === option.value; })} onChange={onAggChange} diff --git a/x-pack/plugins/maps/public/components/metrics_editor.js b/x-pack/plugins/maps/public/components/metrics_editor.js index f81e56a83266d..6c5a9af8f0f02 100644 --- a/x-pack/plugins/maps/public/components/metrics_editor.js +++ b/x-pack/plugins/maps/public/components/metrics_editor.js @@ -15,7 +15,7 @@ import { AGG_TYPE } from '../../common/constants'; export function MetricsEditor({ fields, metrics, onChange, allowMultipleMetrics, metricsFilter }) { function renderMetrics() { return metrics.map((metric, index) => { - const onMetricChange = metric => { + const onMetricChange = (metric) => { onChange([...metrics.slice(0, index), metric, ...metrics.slice(index + 1)]); }; diff --git a/x-pack/plugins/maps/public/components/multi_index_geo_field_select.tsx b/x-pack/plugins/maps/public/components/multi_index_geo_field_select.tsx index 0e5b94f0c6427..c7a45df51f061 100644 --- a/x-pack/plugins/maps/public/components/multi_index_geo_field_select.tsx +++ b/x-pack/plugins/maps/public/components/multi_index_geo_field_select.tsx @@ -34,7 +34,7 @@ export function MultiIndexGeoFieldSelect({ fields, onChange, selectedField }: Pr function onFieldSelect(selectedOptionId: string) { const { indexPatternId, geoFieldName } = splitOptionId(selectedOptionId); - const newSelectedField = fields.find(field => { + const newSelectedField = fields.find((field) => { return field.indexPatternId === indexPatternId && field.geoFieldName === geoFieldName; }); onChange(newSelectedField); diff --git a/x-pack/plugins/maps/public/components/single_field_select.js b/x-pack/plugins/maps/public/components/single_field_select.js index aadc619b029a8..a4db361da9c62 100644 --- a/x-pack/plugins/maps/public/components/single_field_select.js +++ b/x-pack/plugins/maps/public/components/single_field_select.js @@ -17,7 +17,7 @@ function fieldsToOptions(fields) { } return fields - .map(field => { + .map((field) => { return { value: field, label: 'label' in field ? field.label : field.name, @@ -42,7 +42,7 @@ function renderOption(option, searchValue, contentClassName) { } export function SingleFieldSelect({ fields, onChange, value, placeholder, ...rest }) { - const onSelection = selectedOptions => { + const onSelection = (selectedOptions) => { onChange(_.get(selectedOptions, '0.value.name')); }; diff --git a/x-pack/plugins/maps/public/components/tooltip_selector/add_tooltip_field_popover.tsx b/x-pack/plugins/maps/public/components/tooltip_selector/add_tooltip_field_popover.tsx index 782e5e878164e..cbeb4e79a38d7 100644 --- a/x-pack/plugins/maps/public/components/tooltip_selector/add_tooltip_field_popover.tsx +++ b/x-pack/plugins/maps/public/components/tooltip_selector/add_tooltip_field_popover.tsx @@ -37,14 +37,14 @@ function getOptions(fields: FieldProps[], selectedFields: FieldProps[]): EuiSele } return fields - .filter(field => { + .filter((field) => { // remove selected fields - const isFieldSelected = !!selectedFields.find(selectedField => { + const isFieldSelected = !!selectedFields.find((selectedField) => { return field.name === selectedField.name; }); return !isFieldSelected; }) - .map(field => { + .map((field) => { return { value: field.name, prepend: @@ -107,10 +107,10 @@ export class AddTooltipFieldPopover extends Component { _onSelect = (options: EuiSelectableOption[]) => { const checkedFields: string[] = options - .filter(option => { + .filter((option) => { return option.checked === 'on'; }) - .map(option => { + .map((option) => { return option.value as string; }); diff --git a/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.test.tsx b/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.test.tsx index f3ac62717519d..a33add0f6e344 100644 --- a/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.test.tsx +++ b/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.test.tsx @@ -42,7 +42,7 @@ describe('TooltipSelector', () => { const component = shallow(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); expect(component).toMatchSnapshot(); diff --git a/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.tsx b/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.tsx index 34c58c4c8a183..6c07c322d5c49 100644 --- a/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.tsx +++ b/x-pack/plugins/maps/public/components/tooltip_selector/tooltip_selector.tsx @@ -117,7 +117,7 @@ export class TooltipSelector extends Component { }; _getTooltipFieldNames(): string[] { - return this.props.tooltipFields ? this.props.tooltipFields.map(field => field.getName()) : []; + return this.props.tooltipFields ? this.props.tooltipFields.map((field) => field.getName()) : []; } _onAdd = (properties: string[]) => { diff --git a/x-pack/plugins/maps/public/components/validated_range.js b/x-pack/plugins/maps/public/components/validated_range.js index f21dae7feb9b2..3fba45c930abe 100644 --- a/x-pack/plugins/maps/public/components/validated_range.js +++ b/x-pack/plugins/maps/public/components/validated_range.js @@ -34,7 +34,7 @@ export class ValidatedRange extends React.Component { return null; } - _onRangeChange = e => { + _onRangeChange = (e) => { const sanitizedValue = parseFloat(e.target.value, 10); let newValue = isNaN(sanitizedValue) ? '' : sanitizedValue; // work around for https://github.com/elastic/eui/issues/1458 diff --git a/x-pack/plugins/maps/public/connected_components/gis_map/view.js b/x-pack/plugins/maps/public/connected_components/gis_map/view.js index 621db4971b5d7..f733d08cf0b71 100644 --- a/x-pack/plugins/maps/public/connected_components/gis_map/view.js +++ b/x-pack/plugins/maps/public/connected_components/gis_map/view.js @@ -73,7 +73,7 @@ export class GisMap extends Component { } }; - _loadGeoFields = async nextIndexPatternIds => { + _loadGeoFields = async (nextIndexPatternIds) => { if (_.isEqual(nextIndexPatternIds, this._prevIndexPatternIds)) { // all ready loaded index pattern ids return; @@ -84,8 +84,8 @@ export class GisMap extends Component { const geoFields = []; try { const indexPatterns = await getIndexPatternsFromIds(nextIndexPatternIds); - indexPatterns.forEach(indexPattern => { - indexPattern.fields.forEach(field => { + indexPatterns.forEach((indexPattern) => { + indexPattern.fields.forEach((field) => { if ( !indexPatternsUtils.isNestedField(field) && (field.type === ES_GEO_FIELD_TYPE.GEO_POINT || diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/filter_editor/filter_editor.js b/x-pack/plugins/maps/public/connected_components/layer_panel/filter_editor/filter_editor.js index fba2ec05d0b1d..75b6b5d66f1de 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/filter_editor/filter_editor.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/filter_editor/filter_editor.js @@ -42,7 +42,7 @@ export class FilterEditor extends Component { // Filter only effects source so only load source indices. const indexPatternIds = this.props.layer.getSource().getIndexPatternIds(); const indexPatterns = []; - const getIndexPatternPromises = indexPatternIds.map(async indexPatternId => { + const getIndexPatternPromises = indexPatternIds.map(async (indexPatternId) => { try { const indexPattern = await getIndexPatternService().get(indexPatternId); indexPatterns.push(indexPattern); @@ -61,7 +61,7 @@ export class FilterEditor extends Component { }; _toggle = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; @@ -75,7 +75,7 @@ export class FilterEditor extends Component { this._close(); }; - _onApplyGlobalQueryChange = applyGlobalQuery => { + _onApplyGlobalQueryChange = (applyGlobalQuery) => { this.props.updateSourceProp(this.props.layer.getId(), 'applyGlobalQuery', applyGlobalQuery); }; diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/flyout_footer/index.js b/x-pack/plugins/maps/public/connected_components/layer_panel/flyout_footer/index.js index bd8b302c9ee17..c45c9c88a8716 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/flyout_footer/index.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/flyout_footer/index.js @@ -22,7 +22,7 @@ function mapStateToProps(state = {}) { }; } -const mapDispatchToProps = dispatch => { +const mapDispatchToProps = (dispatch) => { return { cancelLayerPanel: () => { dispatch(updateFlyout(FLYOUT_STATE.NONE)); diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/index.js b/x-pack/plugins/maps/public/connected_components/layer_panel/index.js index 8a18191ada1e8..ff088e9306a8c 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/index.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/index.js @@ -19,7 +19,7 @@ function mapStateToProps(state = {}) { function mapDispatchToProps(dispatch) { return { - fitToBounds: layerId => { + fitToBounds: (layerId) => { dispatch(fitToLayerExtent(layerId)); }, updateSourceProp: (id, propName, value, newLayerType) => diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join.js b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join.js index 0d26354e2449b..25083822a6183 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join.js @@ -58,12 +58,12 @@ export class Join extends Component { } this.setState({ - rightFields: indexPattern.fields.filter(field => !indexPatterns.isNestedField(field)), + rightFields: indexPattern.fields.filter((field) => !indexPatterns.isNestedField(field)), indexPattern, }); } - _onLeftFieldChange = leftField => { + _onLeftFieldChange = (leftField) => { this.props.onChange({ leftField: leftField, right: this.props.join.right, @@ -86,7 +86,7 @@ export class Join extends Component { }); }; - _onRightFieldChange = term => { + _onRightFieldChange = (term) => { this.props.onChange({ leftField: this.props.join.leftField, right: { @@ -96,7 +96,7 @@ export class Join extends Component { }); }; - _onMetricsChange = metrics => { + _onMetricsChange = (metrics) => { this.props.onChange({ leftField: this.props.join.leftField, right: { @@ -106,7 +106,7 @@ export class Join extends Component { }); }; - _onWhereQueryChange = whereQuery => { + _onWhereQueryChange = (whereQuery) => { this.props.onChange({ leftField: this.props.join.leftField, right: { @@ -116,7 +116,7 @@ export class Join extends Component { }); }; - _onApplyGlobalQueryChange = applyGlobalQuery => { + _onApplyGlobalQueryChange = (applyGlobalQuery) => { this.props.onChange({ leftField: this.props.join.leftField, right: { diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join_expression.js b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join_expression.js index 12ca2f3c514a0..60f8c8005fe4c 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join_expression.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/join_expression.js @@ -32,7 +32,7 @@ export class JoinExpression extends Component { }; _togglePopover = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; @@ -43,7 +43,7 @@ export class JoinExpression extends Component { }); }; - _onRightSourceChange = async indexPatternId => { + _onRightSourceChange = async (indexPatternId) => { try { const indexPattern = await getIndexPatternService().get(indexPatternId); this.props.onRightSourceChange({ @@ -55,7 +55,7 @@ export class JoinExpression extends Component { } }; - _onLeftFieldChange = selectedFields => { + _onLeftFieldChange = (selectedFields) => { this.props.onLeftFieldChange(_.get(selectedFields, '[0].value.name', null)); }; @@ -66,7 +66,7 @@ export class JoinExpression extends Component { return null; } - const options = leftFields.map(field => { + const options = leftFields.map((field) => { return { value: field, label: field.label, @@ -75,7 +75,7 @@ export class JoinExpression extends Component { let leftFieldOption; if (leftValue) { - leftFieldOption = options.find(option => { + leftFieldOption = options.find((option) => { const field = option.value; return field.name === leftValue; }); diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/metrics_expression.js b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/metrics_expression.js index 8c83743ac4c96..6b119ba6d850d 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/metrics_expression.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/metrics_expression.js @@ -25,7 +25,7 @@ export class MetricsExpression extends Component { }; _togglePopover = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/where_expression.js b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/where_expression.js index 7c9b4f7b7b9a4..d87761d3dabe8 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/where_expression.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/resources/where_expression.js @@ -16,7 +16,7 @@ export class WhereExpression extends Component { }; _togglePopover = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/view.js b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/view.js index 92e32885d43a8..900f5c9ff53ea 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/view.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/join_editor/view.js @@ -23,7 +23,7 @@ import { i18n } from '@kbn/i18n'; export function JoinEditor({ joins, layer, onChange, leftJoinFields, layerDisplayName }) { const renderJoins = () => { return joins.map((joinDescriptor, index) => { - const handleOnChange = updatedDescriptor => { + const handleOnChange = (updatedDescriptor) => { onChange(layer, [...joins.slice(0, index), updatedDescriptor, ...joins.slice(index + 1)]); }; diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/layer_settings/layer_settings.js b/x-pack/plugins/maps/public/connected_components/layer_panel/layer_settings/layer_settings.js index d84d05260f982..bc99285cfc7aa 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/layer_settings/layer_settings.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/layer_settings/layer_settings.js @@ -13,7 +13,7 @@ import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { ValidatedDualRange } from '../../../../../../../src/plugins/kibana_react/public'; export function LayerSettings(props) { - const onLabelChange = event => { + const onLabelChange = (event) => { const label = event.target.value; props.updateLabel(props.layerId, label); }; @@ -23,7 +23,7 @@ export function LayerSettings(props) { props.updateMaxZoom(props.layerId, Math.min(props.maxVisibilityZoom, parseInt(max, 10))); }; - const onAlphaChange = alpha => { + const onAlphaChange = (alpha) => { props.updateAlpha(props.layerId, alpha); }; diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/style_settings/index.js b/x-pack/plugins/maps/public/connected_components/layer_panel/style_settings/index.js index f024956f61cf8..aa04e1d6b2f31 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/style_settings/index.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/style_settings/index.js @@ -17,7 +17,7 @@ function mapStateToProps(state = {}) { function mapDispatchToProps(dispatch) { return { - updateStyleDescriptor: styleDescriptor => { + updateStyleDescriptor: (styleDescriptor) => { dispatch(updateLayerStyleForSelectedLayer(styleDescriptor)); }, }; diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/view.js b/x-pack/plugins/maps/public/connected_components/layer_panel/view.js index f8b7c417e67fd..f34c402a4d417 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/view.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/view.js @@ -83,7 +83,7 @@ export class LayerPanel extends React.Component { let leftJoinFields; try { const leftFieldsInstances = await this.props.selectedLayer.getLeftJoinFields(); - const leftFieldPromises = leftFieldsInstances.map(async field => { + const leftFieldPromises = leftFieldsInstances.map(async (field) => { return { name: field.getName(), label: await field.getLabel(), diff --git a/x-pack/plugins/maps/public/connected_components/layer_panel/view.test.js b/x-pack/plugins/maps/public/connected_components/layer_panel/view.test.js index 9f882cd467527..99893c1bc5bee 100644 --- a/x-pack/plugins/maps/public/connected_components/layer_panel/view.test.js +++ b/x-pack/plugins/maps/public/connected_components/layer_panel/view.test.js @@ -80,7 +80,7 @@ describe('LayerPanel', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -91,7 +91,7 @@ describe('LayerPanel', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.js b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.js index 825c1ad7e7da3..362186a8f5549 100644 --- a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.js +++ b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.js @@ -149,7 +149,7 @@ export class FeatureProperties extends React.Component { ); } - const rows = this.state.properties.map(tooltipProperty => { + const rows = this.state.properties.map((tooltipProperty) => { const label = tooltipProperty.getPropertyName(); return (
@@ -172,7 +172,7 @@ export class FeatureProperties extends React.Component { return (
{getColumnName(col)}   @@ -69,7 +69,7 @@ export const Datatable = ({ datatable, perPage, paginate, showHeader }) => (
{getFormattedValue(row[getColumnName(col)], getColumnType(col))}
(this._node = node)} + ref={(node) => (this._node = node)} > {rows}
diff --git a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.test.js b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.test.js index 10c3711392fb3..c6db9cd96a429 100644 --- a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.test.js +++ b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/feature_properties.test.js @@ -55,7 +55,7 @@ describe('FeatureProperties', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -74,7 +74,7 @@ describe('FeatureProperties', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -93,7 +93,7 @@ describe('FeatureProperties', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/features_tooltip.js b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/features_tooltip.js index 8a1b556d21c1f..e5b97947602b0 100644 --- a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/features_tooltip.js +++ b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/features_tooltip.js @@ -32,7 +32,7 @@ export class FeaturesTooltip extends React.Component { return null; } - _setCurrentFeature = feature => { + _setCurrentFeature = (feature) => { this.setState({ currentFeature: feature }); }; diff --git a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.js b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.js index 9d4b8bf356dca..6a249ad7b3592 100644 --- a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.js +++ b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.js @@ -64,7 +64,7 @@ export class TooltipHeader extends Component { countByLayerId.forEach((count, layerId) => { layers.push(this.props.findLayerById(layerId)); }); - const layerNamePromises = layers.map(layer => { + const layerNamePromises = layers.map((layer) => { return layer.getDisplayName(); }); const layerNames = await Promise.all(layerNamePromises); @@ -88,12 +88,12 @@ export class TooltipHeader extends Component { } }; - _onPageChange = pageNumber => { + _onPageChange = (pageNumber) => { this.setState({ pageNumber }); this.props.setCurrentFeature(this.state.filteredFeatures[pageNumber]); }; - _onLayerChange = e => { + _onLayerChange = (e) => { const newLayerId = e.target.value; if (this.state.selectedLayerId === newLayerId) { return; @@ -102,7 +102,7 @@ export class TooltipHeader extends Component { const filteredFeatures = newLayerId === ALL_LAYERS ? this.props.features - : this.props.features.filter(feature => { + : this.props.features.filter((feature) => { return feature.layerId === newLayerId; }); diff --git a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.test.js b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.test.js index 329e52b3519cf..342817f8171f2 100644 --- a/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.test.js +++ b/x-pack/plugins/maps/public/connected_components/map/features_tooltip/tooltip_header.test.js @@ -23,7 +23,7 @@ class MockLayer { const defaultProps = { onClose: () => {}, isLocked: false, - findLayerById: id => { + findLayerById: (id) => { return new MockLayer(id); }, setCurrentFeature: () => {}, @@ -42,7 +42,7 @@ describe('TooltipHeader', () => { const component = shallow(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -56,7 +56,7 @@ describe('TooltipHeader', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -83,7 +83,7 @@ describe('TooltipHeader', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -97,7 +97,7 @@ describe('TooltipHeader', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -128,7 +128,7 @@ describe('TooltipHeader', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -142,7 +142,7 @@ describe('TooltipHeader', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/draw_control/draw_control.js b/x-pack/plugins/maps/public/connected_components/map/mb/draw_control/draw_control.js index a69e06458a6a0..ac28a2d5d5a6d 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/draw_control/draw_control.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/draw_control/draw_control.js @@ -57,7 +57,7 @@ export class DrawControl extends React.Component { } }, 256); - _onDraw = e => { + _onDraw = (e) => { if (!e.features.length) { return; } diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/get_initial_view.ts b/x-pack/plugins/maps/public/connected_components/map/mb/get_initial_view.ts index 30e3b9b46916b..b9d446d390ffb 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/get_initial_view.ts +++ b/x-pack/plugins/maps/public/connected_components/map/mb/get_initial_view.ts @@ -24,7 +24,7 @@ export async function getInitialView( return await new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition( // success callback - pos => { + (pos) => { resolve({ lat: pos.coords.latitude, lon: pos.coords.longitude, diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/index.js b/x-pack/plugins/maps/public/connected_components/map/mb/index.js index a617ae92dea15..189d6bc1f0a43 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/index.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/index.js @@ -46,10 +46,10 @@ function mapStateToProps(state = {}) { function mapDispatchToProps(dispatch) { return { - extentChanged: e => { + extentChanged: (e) => { dispatch(mapExtentChanged(e)); }, - onMapReady: e => { + onMapReady: (e) => { dispatch(clearGoto()); dispatch(mapExtentChanged(e)); dispatch(mapReady()); diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/mb.utils.test.js b/x-pack/plugins/maps/public/connected_components/map/mb/mb.utils.test.js index 4774cdc556c24..376010f0df9ba 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/mb.utils.test.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/mb.utils.test.js @@ -18,14 +18,14 @@ class MockMbMap { } moveLayer(mbLayerId, nextMbLayerId) { - const indexOfLayerToMove = this._style.layers.findIndex(layer => { + const indexOfLayerToMove = this._style.layers.findIndex((layer) => { return layer.id === mbLayerId; }); const layerToMove = this._style.layers[indexOfLayerToMove]; this._style.layers.splice(indexOfLayerToMove, 1); - const indexOfNextLayer = this._style.layers.findIndex(layer => { + const indexOfNextLayer = this._style.layers.findIndex((layer) => { return layer.id === nextMbLayerId; }); @@ -37,7 +37,7 @@ class MockMbMap { } removeLayer(layerId) { - const layerToRemove = this._style.layers.findIndex(layer => { + const layerToRemove = this._style.layers.findIndex((layer) => { return layer.id === layerId; }); this._style.layers.splice(layerToRemove, 1); @@ -65,13 +65,13 @@ class MockLayer { } ownsMbLayerId(mbLayerId) { - return this._mbLayerIdsToSource.some(mbLayerToSource => { + return this._mbLayerIdsToSource.some((mbLayerToSource) => { return mbLayerToSource.id === mbLayerId; }); } ownsMbSourceId(mbSourceId) { - return this._mbSourceIds.some(id => mbSourceId === id); + return this._mbSourceIds.some((id) => mbSourceId === id); } } @@ -81,8 +81,8 @@ function getMockStyle(orderedMockLayerList) { layers: [], }; - orderedMockLayerList.forEach(mockLayer => { - mockLayer.getMbSourceIds().forEach(mbSourceId => { + orderedMockLayerList.forEach((mockLayer) => { + mockLayer.getMbSourceIds().forEach((mbSourceId) => { mockStyle.sources[mbSourceId] = {}; }); mockLayer.getMbLayersIdsToSource().forEach(({ id, source }) => { diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.js b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.js index 329d2b7fd2985..7c86d729577e2 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.js @@ -47,7 +47,7 @@ export class TooltipControl extends React.Component { }; _getLayerByMbLayerId(mbLayerId) { - return this.props.layerList.find(layer => { + return this.props.layerList.find((layer) => { const mbLayerIds = layer.getMbLayerIds(); return mbLayerIds.indexOf(mbLayerId) > -1; }); @@ -81,7 +81,7 @@ export class TooltipControl extends React.Component { return uniqueFeatures; } - _lockTooltip = e => { + _lockTooltip = (e) => { if (this.props.isDrawingFilter) { // ignore click events when in draw mode return; @@ -105,7 +105,7 @@ export class TooltipControl extends React.Component { }); }; - _updateHoverTooltipState = _.debounce(e => { + _updateHoverTooltipState = _.debounce((e) => { if (this.props.isDrawingFilter || this.props.hasLockedTooltips) { // ignore hover events when in draw mode or when there are locked tooltips return; @@ -144,7 +144,7 @@ export class TooltipControl extends React.Component { //For example: //a vector or heatmap layer will not add a source and layer to the mapbox-map, until that data is available. //during that data-fetch window, the app should not query for layers that do not exist. - return mbLayerIds.filter(mbLayerId => { + return mbLayerIds.filter((mbLayerId) => { return !!this.props.mbMap.getLayer(mbLayerId); }); } diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.test.js b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.test.js index 620d7cb9ff756..31964c3395417 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.test.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_control.test.js @@ -37,7 +37,7 @@ const mockMBMap = { on: (eventName, callback) => { mockMbMapHandlers[eventName] = callback; }, - off: eventName => { + off: (eventName) => { delete mockMbMapHandlers[eventName]; }, getLayer: () => {}, diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.js b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.js index 867c779bc4dba..03c2aeb2edd0a 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.js @@ -97,13 +97,13 @@ export class TooltipPopover extends Component { return await tooltipLayer.getSource().getPreIndexedShape(targetFeature.properties); }; - _findLayerById = layerId => { - return this.props.layerList.find(layer => { + _findLayerById = (layerId) => { + return this.props.layerList.find((layer) => { return layer.getId() === layerId; }); }; - _getLayerName = async layerId => { + _getLayerName = async (layerId) => { const layer = this._findLayerById(layerId); if (!layer) { return null; diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.test.js b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.test.js index bcef03c205b2b..205ca7337277d 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.test.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/tooltip_control/tooltip_popover.test.js @@ -23,7 +23,7 @@ const layerId = 'tfi3f'; const mockMbMapHandlers = {}; const mockMBMap = { - project: lonLatArray => { + project: (lonLatArray) => { const lonDistanceFromCenter = Math.abs(lonLatArray[0] - mapCenter[0]); const latDistanceFromCenter = Math.abs(lonLatArray[1] - mapCenter[1]); return { @@ -34,7 +34,7 @@ const mockMBMap = { on: (eventName, callback) => { mockMbMapHandlers[eventName] = callback; }, - off: eventName => { + off: (eventName) => { delete mockMbMapHandlers[eventName]; }, getBounds: () => { @@ -95,7 +95,7 @@ describe('TooltipPopover', () => { const component = shallow( { + renderTooltipContent={(props) => { return
Custom tooltip content
; }} /> diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/utils.js b/x-pack/plugins/maps/public/connected_components/map/mb/utils.js index adf109a087d27..a5934038f83df 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/utils.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/utils.js @@ -11,20 +11,20 @@ export function removeOrphanedSourcesAndLayers(mbMap, layerList, spatialFilterLa const mbStyle = mbMap.getStyle(); const mbLayerIdsToRemove = []; - mbStyle.layers.forEach(mbLayer => { + mbStyle.layers.forEach((mbLayer) => { // ignore mapbox layers from spatial filter layer if (spatialFilterLayer.ownsMbLayerId(mbLayer.id)) { return; } - const layer = layerList.find(layer => { + const layer = layerList.find((layer) => { return layer.ownsMbLayerId(mbLayer.id); }); if (!layer) { mbLayerIdsToRemove.push(mbLayer.id); } }); - mbLayerIdsToRemove.forEach(mbLayerId => mbMap.removeLayer(mbLayerId)); + mbLayerIdsToRemove.forEach((mbLayerId) => mbMap.removeLayer(mbLayerId)); const mbSourcesToRemove = []; for (const mbSourceId in mbStyle.sources) { @@ -34,7 +34,7 @@ export function removeOrphanedSourcesAndLayers(mbMap, layerList, spatialFilterLa return; } - const layer = layerList.find(layer => { + const layer = layerList.find((layer) => { return layer.ownsMbSourceId(mbSourceId); }); if (!layer) { @@ -42,7 +42,7 @@ export function removeOrphanedSourcesAndLayers(mbMap, layerList, spatialFilterLa } } } - mbSourcesToRemove.forEach(mbSourceId => mbMap.removeSource(mbSourceId)); + mbSourcesToRemove.forEach((mbSourceId) => mbMap.removeSource(mbSourceId)); } export function moveLayerToTop(mbMap, layer) { @@ -52,7 +52,7 @@ export function moveLayerToTop(mbMap, layer) { return; } - layer.getMbLayerIds().forEach(mbLayerId => { + layer.getMbLayerIds().forEach((mbLayerId) => { const mbLayer = mbMap.getLayer(mbLayerId); if (mbLayer) { mbMap.moveLayer(mbLayerId); @@ -73,8 +73,8 @@ export function syncLayerOrderForSingleLayer(mbMap, layerList) { const mbLayers = mbMap.getStyle().layers.slice(); const layerIds = []; - mbLayers.forEach(mbLayer => { - const layer = layerList.find(layer => layer.ownsMbLayerId(mbLayer.id)); + mbLayers.forEach((mbLayer) => { + const layer = layerList.find((layer) => layer.ownsMbLayerId(mbLayer.id)); if (layer) { layerIds.push(layer.getId()); } @@ -82,15 +82,15 @@ export function syncLayerOrderForSingleLayer(mbMap, layerList) { const currentLayerOrderLayerIds = _.uniq(layerIds); - const newLayerOrderLayerIdsUnfiltered = layerList.map(l => l.getId()); - const newLayerOrderLayerIds = newLayerOrderLayerIdsUnfiltered.filter(layerId => + const newLayerOrderLayerIdsUnfiltered = layerList.map((l) => l.getId()); + const newLayerOrderLayerIds = newLayerOrderLayerIdsUnfiltered.filter((layerId) => currentLayerOrderLayerIds.includes(layerId) ); let netPos = 0; let netNeg = 0; const movementArr = currentLayerOrderLayerIds.reduce((accu, id, idx) => { - const movement = newLayerOrderLayerIds.findIndex(newOId => newOId === id) - idx; + const movement = newLayerOrderLayerIds.findIndex((newOId) => newOId === id) - idx; movement > 0 ? netPos++ : movement < 0 && netNeg++; accu.push({ id, movement }); return accu; @@ -99,9 +99,9 @@ export function syncLayerOrderForSingleLayer(mbMap, layerList) { return; } const movedLayerId = - (netPos >= netNeg && movementArr.find(l => l.movement < 0).id) || - (netPos < netNeg && movementArr.find(l => l.movement > 0).id); - const nextLayerIdx = newLayerOrderLayerIds.findIndex(layerId => layerId === movedLayerId) + 1; + (netPos >= netNeg && movementArr.find((l) => l.movement < 0).id) || + (netPos < netNeg && movementArr.find((l) => l.movement > 0).id); + const nextLayerIdx = newLayerOrderLayerIds.findIndex((layerId) => layerId === movedLayerId) + 1; let nextMbLayerId; if (nextLayerIdx === newLayerOrderLayerIds.length) { @@ -109,13 +109,13 @@ export function syncLayerOrderForSingleLayer(mbMap, layerList) { } else { const foundLayer = mbLayers.find(({ id: mbLayerId }) => { const layerId = newLayerOrderLayerIds[nextLayerIdx]; - const layer = layerList.find(layer => layer.getId() === layerId); + const layer = layerList.find((layer) => layer.getId() === layerId); return layer.ownsMbLayerId(mbLayerId); }); nextMbLayerId = foundLayer.id; } - const movedLayer = layerList.find(layer => layer.getId() === movedLayerId); + const movedLayer = layerList.find((layer) => layer.getId() === movedLayerId); mbLayers.forEach(({ id: mbLayerId }) => { if (movedLayer.ownsMbLayerId(mbLayerId)) { mbMap.moveLayer(mbLayerId, nextMbLayerId); @@ -156,11 +156,11 @@ export async function loadSpriteSheetImageData(imgUrl) { if (isCrossOriginUrl(imgUrl)) { image.crossOrigin = 'Anonymous'; } - image.onload = el => { + image.onload = (el) => { const imgData = getImageData(el.currentTarget); resolve(imgData); }; - image.onerror = e => { + image.onerror = (e) => { reject(e); }; image.src = imgUrl; diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/view.js b/x-pack/plugins/maps/public/connected_components/map/mb/view.js index 800daec76989c..c4b28e33747ee 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/view.js +++ b/x-pack/plugins/maps/public/connected_components/map/mb/view.js @@ -113,7 +113,7 @@ export class MBMapContainer extends React.Component { async _createMbMapInstance() { const initialView = await getInitialView(this.props.goto, this.props.settings); - return new Promise(resolve => { + return new Promise((resolve) => { const mbStyle = { version: 8, sources: {}, @@ -151,7 +151,7 @@ export class MBMapContainer extends React.Component { } let emptyImage; - mbMap.on('styleimagemissing', e => { + mbMap.on('styleimagemissing', (e) => { if (emptyImage) { mbMap.addImage(e.id, emptyImage); } @@ -201,7 +201,7 @@ export class MBMapContainer extends React.Component { ); // Attach event only if view control is visible, which shows lat/lon if (!this.props.hideViewControl) { - const throttledSetMouseCoordinates = _.throttle(e => { + const throttledSetMouseCoordinates = _.throttle((e) => { this.props.setMouseCoordinates({ lat: e.lngLat.lat, lon: e.lngLat.lng, @@ -267,7 +267,7 @@ export class MBMapContainer extends React.Component { this.props.layerList, this.props.spatialFiltersLayer ); - this.props.layerList.forEach(layer => layer.syncLayerWithMB(this.state.mbMap)); + this.props.layerList.forEach((layer) => layer.syncLayerWithMB(this.state.mbMap)); syncLayerOrderForSingleLayer(this.state.mbMap, this.props.layerList); moveLayerToTop(this.state.mbMap, this.props.spatialFiltersLayer); }; diff --git a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/set_view_control.js b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/set_view_control.js index 2c10728f78e5c..87b636da543fc 100644 --- a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/set_view_control.js +++ b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/set_view_control/set_view_control.js @@ -49,15 +49,15 @@ export class SetViewControl extends Component { this.props.openSetView(); }; - _onLatChange = evt => { + _onLatChange = (evt) => { this._onChange('lat', evt); }; - _onLonChange = evt => { + _onLonChange = (evt) => { this._onChange('lon', evt); }; - _onZoomChange = evt => { + _onZoomChange = (evt) => { this._onChange('zoom', evt); }; diff --git a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/index.js b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/index.js index 7ed6f07a168ea..5812604a91b87 100644 --- a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/index.js +++ b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/index.js @@ -17,7 +17,7 @@ function mapStateToProps(state = {}) { function mapDispatchToProps(dispatch) { return { - initiateDraw: options => { + initiateDraw: (options) => { dispatch(updateDrawState(options)); }, cancelDraw: () => { diff --git a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/tools_control.js b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/tools_control.js index e7c125abe70c7..a06def086b861 100644 --- a/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/tools_control.js +++ b/x-pack/plugins/maps/public/connected_components/toolbar_overlay/tools_control/tools_control.js @@ -52,7 +52,7 @@ export class ToolsControl extends Component { }; _togglePopover = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; @@ -61,7 +61,7 @@ export class ToolsControl extends Component { this.setState({ isPopoverOpen: false }); }; - _initiateShapeDraw = options => { + _initiateShapeDraw = (options) => { this.props.initiateDraw({ drawType: DRAW_TYPE.POLYGON, ...options, @@ -69,7 +69,7 @@ export class ToolsControl extends Component { this._closePopover(); }; - _initiateBoundsDraw = options => { + _initiateBoundsDraw = (options) => { this.props.initiateDraw({ drawType: DRAW_TYPE.BOUNDS, ...options, @@ -77,7 +77,7 @@ export class ToolsControl extends Component { this._closePopover(); }; - _initiateDistanceDraw = options => { + _initiateDistanceDraw = (options) => { this.props.initiateDraw({ drawType: DRAW_TYPE.DISTANCE, ...options, diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.js b/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.js index 8f11d1b23376c..0e5048a1e9190 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.js +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.js @@ -28,7 +28,7 @@ export class AttributionControl extends React.Component { } _loadAttributions = async () => { - const attributionPromises = this.props.layerList.map(async layer => { + const attributionPromises = this.props.layerList.map(async (layer) => { try { return await layer.getAttributions(); } catch (error) { @@ -44,7 +44,7 @@ export class AttributionControl extends React.Component { for (let i = 0; i < attributions.length; i++) { for (let j = 0; j < attributions[i].length; j++) { const testAttr = attributions[i][j]; - const attr = uniqueAttributions.find(added => { + const attr = uniqueAttributions.find((added) => { return added.url === testAttr.url && added.label === testAttr.label; }); if (!attr) { diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.test.js b/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.test.js index 7ec64a94e8f47..2e85e8ab792d3 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.test.js +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/attribution_control/view.test.js @@ -24,7 +24,7 @@ describe('AttributionControl', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/index.js b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/index.js index 68e689d9c789e..fa7ddc4d31eaa 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/index.js +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/index.js @@ -11,7 +11,7 @@ import { getLayerList } from '../../../../selectors/map_selectors'; import { getIsReadOnly } from '../../../../selectors/ui_selectors'; const mapDispatchToProps = { - updateLayerOrder: newOrder => updateLayerOrder(newOrder), + updateLayerOrder: (newOrder) => updateLayerOrder(newOrder), }; function mapStateToProps(state = {}) { diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/index.js b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/index.js index da4107e747ce6..e4dc9bd84b517 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/index.js +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/index.js @@ -40,15 +40,15 @@ function mapStateToProps(state = {}, ownProps) { function mapDispatchToProps(dispatch) { return { - openLayerPanel: async layerId => { + openLayerPanel: async (layerId) => { await dispatch(removeTransientLayer()); await dispatch(setSelectedLayer(layerId)); dispatch(updateFlyout(FLYOUT_STATE.LAYER_PANEL)); }, - hideTOCDetails: layerId => { + hideTOCDetails: (layerId) => { dispatch(hideTOCDetails(layerId)); }, - showTOCDetails: layerId => { + showTOCDetails: (layerId) => { dispatch(showTOCDetails(layerId)); }, }; diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.test.tsx b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.test.tsx index 5eaba5330a3a7..c7ed5ec74ac7a 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.test.tsx +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.test.tsx @@ -79,7 +79,7 @@ describe('TOCEntryActionsPopover', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -92,7 +92,7 @@ describe('TOCEntryActionsPopover', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -104,7 +104,7 @@ describe('TOCEntryActionsPopover', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.tsx b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.tsx index 344e96e511f2e..5baac0a474ffa 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.tsx +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/toc_entry_actions_popover/toc_entry_actions_popover.tsx @@ -55,7 +55,7 @@ export class TOCEntryActionsPopover extends Component { } _togglePopover = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/view.test.js b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/view.test.js index fa200660d8e4c..90d756484c47f 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/view.test.js +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/toc_entry/view.test.js @@ -51,7 +51,7 @@ describe('TOCEntry', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -63,7 +63,7 @@ describe('TOCEntry', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -74,7 +74,7 @@ describe('TOCEntry', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -85,7 +85,7 @@ describe('TOCEntry', () => { const component = shallowWithIntl(); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); @@ -102,7 +102,7 @@ describe('TOCEntry', () => { ); // Ensure all promises resolve - await new Promise(resolve => process.nextTick(resolve)); + await new Promise((resolve) => process.nextTick(resolve)); // Ensure the state changes are reflected component.update(); diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/view.js b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/view.js index 49ccd503793e4..7414d810a8654 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/view.js +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/layer_toc/view.js @@ -28,7 +28,7 @@ export class LayerTOC extends React.Component { } // Layer list is displayed in reverse order so index needs to reversed to get back to original reference. - const reverseIndex = index => { + const reverseIndex = (index) => { return this.props.layerList.length - index - 1; }; @@ -49,7 +49,7 @@ export class LayerTOC extends React.Component { const reverseLayerList = [...this.props.layerList].reverse(); if (this.props.isReadOnly) { - return reverseLayerList.map(layer => { + return reverseLayerList.map((layer) => { return ; }); } diff --git a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/view.js b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/view.js index 180dc2e3933c3..9596a4df2cf17 100644 --- a/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/view.js +++ b/x-pack/plugins/maps/public/connected_components/widget_overlay/layer_control/view.js @@ -60,10 +60,10 @@ export function LayerControl({ isFlyoutOpen, }) { if (!isLayerTOCOpen) { - const hasErrors = layerList.some(layer => { + const hasErrors = layerList.some((layer) => { return layer.hasErrors(); }); - const isLoading = layerList.some(layer => { + const isLoading = layerList.some((layer) => { return layer.isLayerLoading(); }); diff --git a/x-pack/plugins/maps/public/elasticsearch_geo_utils.js b/x-pack/plugins/maps/public/elasticsearch_geo_utils.js index 419b169138ef1..b89fda29554ee 100644 --- a/x-pack/plugins/maps/public/elasticsearch_geo_utils.js +++ b/x-pack/plugins/maps/public/elasticsearch_geo_utils.js @@ -438,10 +438,10 @@ export function clamp(val, min, max) { export function extractFeaturesFromFilters(filters) { const features = []; filters - .filter(filter => { + .filter((filter) => { return filter.meta.key && filter.meta.type === SPATIAL_FILTER_TYPE; }) - .forEach(filter => { + .forEach((filter) => { let geometry; if (filter.geo_distance && filter.geo_distance[filter.meta.key]) { const distanceSplit = filter.geo_distance.distance.split('km'); diff --git a/x-pack/plugins/maps/public/elasticsearch_geo_utils.test.js b/x-pack/plugins/maps/public/elasticsearch_geo_utils.test.js index c0baf5e4bcb6e..05f6a9eec5bd5 100644 --- a/x-pack/plugins/maps/public/elasticsearch_geo_utils.test.js +++ b/x-pack/plugins/maps/public/elasticsearch_geo_utils.test.js @@ -24,7 +24,7 @@ import { indexPatterns } from '../../../../src/plugins/data/public'; const geoFieldName = 'location'; -const flattenHitMock = hit => { +const flattenHitMock = (hit) => { const properties = {}; for (const fieldName in hit._source) { if (hit._source.hasOwnProperty(fieldName)) { @@ -173,7 +173,7 @@ describe('hitsToGeoJson', () => { describe('dot in geoFieldName', () => { const indexPatternMock = { fields: { - getByName: name => { + getByName: (name) => { const fields = { ['my.location']: { type: 'geo_point', diff --git a/x-pack/plugins/maps/public/embeddable/map_embeddable.tsx b/x-pack/plugins/maps/public/embeddable/map_embeddable.tsx index 01cbece32c64c..c644481d4d92e 100644 --- a/x-pack/plugins/maps/public/embeddable/map_embeddable.tsx +++ b/x-pack/plugins/maps/public/embeddable/map_embeddable.tsx @@ -104,7 +104,7 @@ export class MapEmbeddable extends Embeddable this.onContainerStateChanged(input)); + this._subscription = this.getInput$().subscribe((input) => this.onContainerStateChanged(input)); } setRenderTooltipContent = (renderTooltipContent: RenderToolTipContent) => { @@ -149,7 +149,7 @@ export class MapEmbeddable extends Embeddable !filter.meta.disabled), + filters: filters.filter((filter) => !filter.meta.disabled), query, timeFilters: timeRange, refresh, diff --git a/x-pack/plugins/maps/public/embeddable/map_embeddable_factory.ts b/x-pack/plugins/maps/public/embeddable/map_embeddable_factory.ts index f33885c2a2462..46199d59af7b5 100644 --- a/x-pack/plugins/maps/public/embeddable/map_embeddable_factory.ts +++ b/x-pack/plugins/maps/public/embeddable/map_embeddable_factory.ts @@ -48,7 +48,7 @@ async function waitForMapDependencies(): Promise { return whenModulesLoadedPromise; } - whenModulesLoadedPromise = new Promise(async resolve => { + whenModulesLoadedPromise = new Promise(async (resolve) => { ({ // @ts-ignore getMapsSavedObjectLoader, @@ -111,7 +111,7 @@ export class MapEmbeddableFactory implements EmbeddableFactoryDefinition { ); } - const promises = queryableIndexPatternIds.map(async indexPatternId => { + const promises = queryableIndexPatternIds.map(async (indexPatternId) => { try { // @ts-ignore return await getIndexPatternService().get(indexPatternId); diff --git a/x-pack/plugins/maps/public/index_pattern_util.js b/x-pack/plugins/maps/public/index_pattern_util.js index bbea4a9e3ab2a..d695d1087a38d 100644 --- a/x-pack/plugins/maps/public/index_pattern_util.js +++ b/x-pack/plugins/maps/public/index_pattern_util.js @@ -10,7 +10,7 @@ import { ES_GEO_FIELD_TYPE } from '../common/constants'; export async function getIndexPatternsFromIds(indexPatternIds = []) { const promises = []; - indexPatternIds.forEach(id => { + indexPatternIds.forEach((id) => { const indexPatternPromise = getIndexPatternService().get(id); if (indexPatternPromise) { promises.push(indexPatternPromise); @@ -21,7 +21,7 @@ export async function getIndexPatternsFromIds(indexPatternIds = []) { } export function getTermsFields(fields) { - return fields.filter(field => { + return fields.filter((field) => { return ( field.aggregatable && !indexPatterns.isNestedField(field) && @@ -48,7 +48,7 @@ export function supportsGeoTileAgg(field) { // Returns filtered fields list containing only fields that exist in _source. export function getSourceFields(fields) { - return fields.filter(field => { + return fields.filter((field) => { // Multi fields are not stored in _source and only exist in index. const isMultiField = field.subType && field.subType.multi; return !isMultiField && !indexPatterns.isNestedField(field); diff --git a/x-pack/plugins/maps/public/inspector/views/map_details.js b/x-pack/plugins/maps/public/inspector/views/map_details.js index e84cf51ed34c1..29553c75592ca 100644 --- a/x-pack/plugins/maps/public/inspector/views/map_details.js +++ b/x-pack/plugins/maps/public/inspector/views/map_details.js @@ -43,7 +43,7 @@ class MapDetails extends Component { selectedTabId: DETAILS_TAB_ID, }; - onSelectedTabChanged = id => { + onSelectedTabChanged = (id) => { this.setState({ selectedTabId: id, }); diff --git a/x-pack/plugins/maps/public/kibana_services.js b/x-pack/plugins/maps/public/kibana_services.js index 4e874d45bf128..ba7be7a3b2464 100644 --- a/x-pack/plugins/maps/public/kibana_services.js +++ b/x-pack/plugins/maps/public/kibana_services.js @@ -10,51 +10,52 @@ export const SPATIAL_FILTER_TYPE = esFilters.FILTERS.SPATIAL_FILTER; const { getRequestInspectorStats, getResponseInspectorStats } = search; let indexPatternService; -export const setIndexPatternService = dataIndexPatterns => +export const setIndexPatternService = (dataIndexPatterns) => (indexPatternService = dataIndexPatterns); export const getIndexPatternService = () => indexPatternService; let autocompleteService; -export const setAutocompleteService = dataAutoComplete => (autocompleteService = dataAutoComplete); +export const setAutocompleteService = (dataAutoComplete) => + (autocompleteService = dataAutoComplete); export const getAutocompleteService = () => autocompleteService; let licenseId; -export const setLicenseId = latestLicenseId => (licenseId = latestLicenseId); +export const setLicenseId = (latestLicenseId) => (licenseId = latestLicenseId); export const getLicenseId = () => { return licenseId; }; let inspector; -export const setInspector = newInspector => (inspector = newInspector); +export const setInspector = (newInspector) => (inspector = newInspector); export const getInspector = () => { return inspector; }; let fileUploadPlugin; -export const setFileUpload = fileUpload => (fileUploadPlugin = fileUpload); +export const setFileUpload = (fileUpload) => (fileUploadPlugin = fileUpload); export const getFileUploadComponent = () => { return fileUploadPlugin.JsonUploadAndParse; }; let uiSettings; -export const setUiSettings = coreUiSettings => (uiSettings = coreUiSettings); +export const setUiSettings = (coreUiSettings) => (uiSettings = coreUiSettings); export const getUiSettings = () => uiSettings; let indexPatternSelectComponent; -export const setIndexPatternSelect = indexPatternSelect => +export const setIndexPatternSelect = (indexPatternSelect) => (indexPatternSelectComponent = indexPatternSelect); export const getIndexPatternSelectComponent = () => indexPatternSelectComponent; let coreHttp; -export const setHttp = http => (coreHttp = http); +export const setHttp = (http) => (coreHttp = http); export const getHttp = () => coreHttp; let dataTimeFilter; -export const setTimeFilter = timeFilter => (dataTimeFilter = timeFilter); +export const setTimeFilter = (timeFilter) => (dataTimeFilter = timeFilter); export const getTimeFilter = () => dataTimeFilter; let toast; -export const setToasts = notificationToast => (toast = notificationToast); +export const setToasts = (notificationToast) => (toast = notificationToast); export const getToasts = () => toast; export async function fetchSearchSourceAndRecordWithInspector({ @@ -72,7 +73,7 @@ export async function fetchSearchSourceAndRecordWithInspector({ let resp; try { inspectorRequest.stats(getRequestInspectorStats(searchSource)); - searchSource.getSearchRequestBody().then(body => { + searchSource.getSearchRequestBody().then((body) => { inspectorRequest.json(body); }); resp = await searchSource.fetch({ abortSignal }); @@ -86,62 +87,62 @@ export async function fetchSearchSourceAndRecordWithInspector({ } let savedObjectsClient; -export const setSavedObjectsClient = coreSavedObjectsClient => +export const setSavedObjectsClient = (coreSavedObjectsClient) => (savedObjectsClient = coreSavedObjectsClient); export const getSavedObjectsClient = () => savedObjectsClient; let chrome; -export const setCoreChrome = coreChrome => (chrome = coreChrome); +export const setCoreChrome = (coreChrome) => (chrome = coreChrome); export const getCoreChrome = () => chrome; let mapsCapabilities; -export const setMapsCapabilities = coreAppMapsCapabilities => +export const setMapsCapabilities = (coreAppMapsCapabilities) => (mapsCapabilities = coreAppMapsCapabilities); export const getMapsCapabilities = () => mapsCapabilities; let visualizations; -export const setVisualizations = visPlugin => (visualizations = visPlugin); +export const setVisualizations = (visPlugin) => (visualizations = visPlugin); export const getVisualizations = () => visualizations; let docLinks; -export const setDocLinks = coreDocLinks => (docLinks = coreDocLinks); +export const setDocLinks = (coreDocLinks) => (docLinks = coreDocLinks); export const getDocLinks = () => docLinks; let overlays; -export const setCoreOverlays = coreOverlays => (overlays = coreOverlays); +export const setCoreOverlays = (coreOverlays) => (overlays = coreOverlays); export const getCoreOverlays = () => overlays; let data; -export const setData = dataPlugin => (data = dataPlugin); +export const setData = (dataPlugin) => (data = dataPlugin); export const getData = () => data; let uiActions; -export const setUiActions = pluginUiActions => (uiActions = pluginUiActions); +export const setUiActions = (pluginUiActions) => (uiActions = pluginUiActions); export const getUiActions = () => uiActions; let core; -export const setCore = kibanaCore => (core = kibanaCore); +export const setCore = (kibanaCore) => (core = kibanaCore); export const getCore = () => core; let navigation; -export const setNavigation = pluginNavigation => (navigation = pluginNavigation); +export const setNavigation = (pluginNavigation) => (navigation = pluginNavigation); export const getNavigation = () => navigation; let coreI18n; -export const setCoreI18n = kibanaCoreI18n => (coreI18n = kibanaCoreI18n); +export const setCoreI18n = (kibanaCoreI18n) => (coreI18n = kibanaCoreI18n); export const getCoreI18n = () => coreI18n; let dataSearchService; -export const setSearchService = searchService => (dataSearchService = searchService); +export const setSearchService = (searchService) => (dataSearchService = searchService); export const getSearchService = () => dataSearchService; let kibanaVersion; -export const setKibanaVersion = version => (kibanaVersion = version); +export const setKibanaVersion = (version) => (kibanaVersion = version); export const getKibanaVersion = () => kibanaVersion; // xpack.maps.* kibana.yml settings from this plugin let mapAppConfig; -export const setMapAppConfig = config => (mapAppConfig = config); +export const setMapAppConfig = (config) => (mapAppConfig = config); export const getMapAppConfig = () => mapAppConfig; export const getEnabled = () => getMapAppConfig().enabled; @@ -152,7 +153,7 @@ export const getEnableVectorTiles = () => getMapAppConfig().enableVectorTiles; // map.* kibana.yml settings from maps_legacy plugin that are shared between OSS map visualizations and maps app let kibanaCommonConfig; -export const setKibanaCommonConfig = config => (kibanaCommonConfig = config); +export const setKibanaCommonConfig = (config) => (kibanaCommonConfig = config); export const getKibanaCommonConfig = () => kibanaCommonConfig; export const getIsEmsEnabled = () => getKibanaCommonConfig().includeElasticMapsService; diff --git a/x-pack/plugins/maps/public/reducers/map.js b/x-pack/plugins/maps/public/reducers/map.js index d0f4b07a2d90d..c5f3968b749f1 100644 --- a/x-pack/plugins/maps/public/reducers/map.js +++ b/x-pack/plugins/maps/public/reducers/map.js @@ -283,15 +283,15 @@ export function map(state = DEFAULT_MAP_STATE, action) { }, }; case SET_SELECTED_LAYER: - const selectedMatch = state.layerList.find(layer => layer.id === action.selectedLayerId); + const selectedMatch = state.layerList.find((layer) => layer.id === action.selectedLayerId); return { ...state, selectedLayerId: selectedMatch ? action.selectedLayerId : null }; case SET_TRANSIENT_LAYER: - const transientMatch = state.layerList.find(layer => layer.id === action.transientLayerId); + const transientMatch = state.layerList.find((layer) => layer.id === action.transientLayerId); return { ...state, __transientLayerId: transientMatch ? action.transientLayerId : null }; case UPDATE_LAYER_ORDER: return { ...state, - layerList: action.newLayerOrder.map(layerNumber => state.layerList[layerNumber]), + layerList: action.newLayerOrder.map((layerNumber) => state.layerList[layerNumber]), }; case UPDATE_LAYER_PROP: return updateLayerInList(state, action.id, action.propName, action.newValue); @@ -299,12 +299,12 @@ export function map(state = DEFAULT_MAP_STATE, action) { return updateLayerSourceDescriptorProp(state, action.layerId, action.propName, action.value); case SET_JOINS: const layerDescriptor = state.layerList.find( - descriptor => descriptor.id === action.layer.getId() + (descriptor) => descriptor.id === action.layer.getId() ); if (layerDescriptor) { const newLayerDescriptor = { ...layerDescriptor, joins: action.joins.slice() }; const index = state.layerList.findIndex( - descriptor => descriptor.id === action.layer.getId() + (descriptor) => descriptor.id === action.layer.getId() ); const newLayerList = state.layerList.slice(); newLayerList[index] = newLayerDescriptor; @@ -403,7 +403,7 @@ export function map(state = DEFAULT_MAP_STATE, action) { case SET_WAITING_FOR_READY_HIDDEN_LAYERS: return { ...state, - waitingForMapReadyLayerList: state.waitingForMapReadyLayerList.map(layer => ({ + waitingForMapReadyLayerList: state.waitingForMapReadyLayerList.map((layer) => ({ ...layer, visible: !action.hiddenLayerIds.includes(layer.id), })), @@ -418,7 +418,7 @@ function findDataRequest(layerDescriptor, dataRequestAction) { return; } - return layerDescriptor.__dataRequests.find(dataRequest => { + return layerDescriptor.__dataRequests.find((dataRequest) => { return dataRequest.dataId === dataRequestAction.dataId; }); } @@ -447,7 +447,7 @@ function updateSourceDataRequest(state, action) { if (!layerDescriptor) { return state; } - const dataRequest = layerDescriptor.__dataRequests.find(dataRequest => { + const dataRequest = layerDescriptor.__dataRequests.find((dataRequest) => { return dataRequest.dataId === SOURCE_DATA_ID_ORIGIN; }); if (!dataRequest) { @@ -517,7 +517,7 @@ function getValidDataRequest(state, action, checkRequestToken = true) { } function findLayerById(state, id) { - return state.layerList.find(layer => layer.id === id); + return state.layerList.find((layer) => layer.id === id); } function trackCurrentLayerState(state, layerId) { diff --git a/x-pack/plugins/maps/public/reducers/non_serializable_instances.js b/x-pack/plugins/maps/public/reducers/non_serializable_instances.js index bbefe09bb6e43..e567a62c0c7b6 100644 --- a/x-pack/plugins/maps/public/reducers/non_serializable_instances.js +++ b/x-pack/plugins/maps/public/reducers/non_serializable_instances.js @@ -76,14 +76,14 @@ export const registerCancelCallback = (requestToken, callback) => { }; }; -export const unregisterCancelCallback = requestToken => { +export const unregisterCancelCallback = (requestToken) => { return { type: UNREGISTER_CANCEL_CALLBACK, requestToken, }; }; -export const cancelRequest = requestToken => { +export const cancelRequest = (requestToken) => { return (dispatch, getState) => { if (!requestToken) { return; diff --git a/x-pack/plugins/maps/public/reducers/ui.ts b/x-pack/plugins/maps/public/reducers/ui.ts index 5f532fea018ea..ff521c92568b3 100644 --- a/x-pack/plugins/maps/public/reducers/ui.ts +++ b/x-pack/plugins/maps/public/reducers/ui.ts @@ -81,7 +81,7 @@ export function ui(state: MapUiState = DEFAULT_MAP_UI_STATE, action: any) { case HIDE_TOC_DETAILS: return { ...state, - openTOCDetails: state.openTOCDetails.filter(layerId => { + openTOCDetails: state.openTOCDetails.filter((layerId) => { return layerId !== action.layerId; }), }; diff --git a/x-pack/plugins/maps/public/selectors/map_selectors.ts b/x-pack/plugins/maps/public/selectors/map_selectors.ts index b0e1400d513fe..90cd4f08eecdf 100644 --- a/x-pack/plugins/maps/public/selectors/map_selectors.ts +++ b/x-pack/plugins/maps/public/selectors/map_selectors.ts @@ -66,7 +66,7 @@ function createLayerInstance( const joins: IJoin[] = []; const vectorLayerDescriptor = layerDescriptor as VectorLayerDescriptor; if (vectorLayerDescriptor.joins) { - vectorLayerDescriptor.joins.forEach(joinDescriptor => { + vectorLayerDescriptor.joins.forEach((joinDescriptor) => { const join = new InnerJoin(joinDescriptor, source); joins.push(join); }); @@ -183,7 +183,7 @@ export const getQuery = ({ map }: MapStoreState): MapQuery | undefined => map.ma export const getFilters = ({ map }: MapStoreState): Filter[] => map.mapState.filters; export const isUsingSearch = (state: MapStoreState): boolean => { - const filters = getFilters(state).filter(filter => !filter.meta.disabled); + const filters = getFilters(state).filter((filter) => !filter.meta.disabled); const queryString = _.get(getQuery(state), 'query', ''); return !!filters.length || !!queryString.length; }; @@ -212,7 +212,7 @@ export const getRefreshTimerLastTriggeredAt = ({ map }: MapStoreState): string | function getLayerDescriptor(state: MapStoreState, layerId: string) { const layerListRaw = getLayerListRaw(state); - return layerListRaw.find(layer => layer.id === layerId); + return layerListRaw.find((layer) => layer.id === layerId); } export function getDataRequestDescriptor(state: MapStoreState, layerId: string, dataId: string) { @@ -294,20 +294,20 @@ export const getLayerList = createSelector( getLayerListRaw, getInspectorAdapters, (layerDescriptorList, inspectorAdapters) => { - return layerDescriptorList.map(layerDescriptor => + return layerDescriptorList.map((layerDescriptor) => createLayerInstance(layerDescriptor, inspectorAdapters) ); } ); export function getLayerById(layerId: string, state: MapStoreState): ILayer | undefined { - return getLayerList(state).find(layer => { + return getLayerList(state).find((layer) => { return layerId === layer.getId(); }); } -export const getFittableLayers = createSelector(getLayerList, layerList => { - return layerList.filter(layer => { +export const getFittableLayers = createSelector(getLayerList, (layerList) => { + return layerList.filter((layer) => { // These are the only layer-types that implement bounding-box retrieval reliably // This will _not_ work if Maps will allow register custom layer types const isFittable = @@ -319,15 +319,15 @@ export const getFittableLayers = createSelector(getLayerList, layerList => { }); }); -export const getHiddenLayerIds = createSelector(getLayerListRaw, layers => - layers.filter(layer => !layer.visible).map(layer => layer.id) +export const getHiddenLayerIds = createSelector(getLayerListRaw, (layers) => + layers.filter((layer) => !layer.visible).map((layer) => layer.id) ); export const getSelectedLayer = createSelector( getSelectedLayerId, getLayerList, (selectedLayerId, layerList) => { - return layerList.find(layer => layer.getId() === selectedLayerId); + return layerList.find((layer) => layer.getId() === selectedLayerId); } ); @@ -345,7 +345,7 @@ export const getMapColors = createSelector( }, []) ); -export const getSelectedLayerJoinDescriptors = createSelector(getSelectedLayer, selectedLayer => { +export const getSelectedLayerJoinDescriptors = createSelector(getSelectedLayer, (selectedLayer) => { if (!selectedLayer || !('getJoins' in selectedLayer)) { return []; } @@ -356,18 +356,18 @@ export const getSelectedLayerJoinDescriptors = createSelector(getSelectedLayer, }); // Get list of unique index patterns used by all layers -export const getUniqueIndexPatternIds = createSelector(getLayerList, layerList => { +export const getUniqueIndexPatternIds = createSelector(getLayerList, (layerList) => { const indexPatternIds: string[] = []; - layerList.forEach(layer => { + layerList.forEach((layer) => { indexPatternIds.push(...layer.getIndexPatternIds()); }); return _.uniq(indexPatternIds).sort(); }); // Get list of unique index patterns, excluding index patterns from layers that disable applyGlobalQuery -export const getQueryableUniqueIndexPatternIds = createSelector(getLayerList, layerList => { +export const getQueryableUniqueIndexPatternIds = createSelector(getLayerList, (layerList) => { const indexPatternIds: string[] = []; - layerList.forEach(layer => { + layerList.forEach((layer) => { indexPatternIds.push(...layer.getQueryableIndexPatternIds()); }); return _.uniq(indexPatternIds); @@ -381,7 +381,7 @@ export const hasDirtyState = createSelector( return true; } - return layerListRaw.some(layerDescriptor => { + return layerListRaw.some((layerDescriptor) => { const trackedState = layerDescriptor[TRACKED_LAYER_DESCRIPTOR]; if (!trackedState) { return false; diff --git a/x-pack/plugins/maps/server/lib/get_index_pattern_settings.js b/x-pack/plugins/maps/server/lib/get_index_pattern_settings.js index 066996ef8a6b9..27b6ff0fc6a51 100644 --- a/x-pack/plugins/maps/server/lib/get_index_pattern_settings.js +++ b/x-pack/plugins/maps/server/lib/get_index_pattern_settings.js @@ -10,7 +10,7 @@ import { DEFAULT_MAX_RESULT_WINDOW, DEFAULT_MAX_INNER_RESULT_WINDOW } from '../. export function getIndexPatternSettings(indicesSettingsResp) { let maxResultWindow = Infinity; let maxInnerResultWindow = Infinity; - Object.values(indicesSettingsResp).forEach(indexSettings => { + Object.values(indicesSettingsResp).forEach((indexSettings) => { const indexMaxResultWindow = _.get( indexSettings, 'settings.index.max_result_window', diff --git a/x-pack/plugins/maps/server/maps_telemetry/maps_telemetry.ts b/x-pack/plugins/maps/server/maps_telemetry/maps_telemetry.ts index 6c62ceb347c85..463d3f3b3939d 100644 --- a/x-pack/plugins/maps/server/maps_telemetry/maps_telemetry.ts +++ b/x-pack/plugins/maps/server/maps_telemetry/maps_telemetry.ts @@ -36,7 +36,7 @@ interface ILayerTypeCount { } function getUniqueLayerCounts(layerCountsList: ILayerTypeCount[], mapsCount: number) { - const uniqueLayerTypes = _.uniq(_.flatten(layerCountsList.map(lTypes => Object.keys(lTypes)))); + const uniqueLayerTypes = _.uniq(_.flatten(layerCountsList.map((lTypes) => Object.keys(lTypes)))); return uniqueLayerTypes.reduce((accu: IStats, type: string) => { const typeCounts = layerCountsList.reduce( @@ -59,24 +59,24 @@ function getUniqueLayerCounts(layerCountsList: ILayerTypeCount[], mapsCount: num } function getIndexPatternsWithGeoFieldCount(indexPatterns: IIndexPattern[]) { - const fieldLists = indexPatterns.map(indexPattern => + const fieldLists = indexPatterns.map((indexPattern) => indexPattern.attributes && indexPattern.attributes.fields ? JSON.parse(indexPattern.attributes.fields) : [] ); - const fieldListsWithGeoFields = fieldLists.filter(fields => + const fieldListsWithGeoFields = fieldLists.filter((fields) => fields.some( (field: IFieldType) => field.type === ES_GEO_FIELD_TYPE.GEO_POINT || field.type === ES_GEO_FIELD_TYPE.GEO_SHAPE ) ); - const fieldListsWithGeoPointFields = fieldLists.filter(fields => + const fieldListsWithGeoPointFields = fieldLists.filter((fields) => fields.some((field: IFieldType) => field.type === ES_GEO_FIELD_TYPE.GEO_POINT) ); - const fieldListsWithGeoShapeFields = fieldLists.filter(fields => + const fieldListsWithGeoShapeFields = fieldLists.filter((fields) => fields.some((field: IFieldType) => field.type === ES_GEO_FIELD_TYPE.GEO_SHAPE) ); @@ -96,25 +96,25 @@ export function buildMapsTelemetry({ indexPatternSavedObjects: IIndexPattern[]; settings: SavedObjectAttribute; }): SavedObjectAttributes { - const layerLists = mapSavedObjects.map(savedMapObject => + const layerLists = mapSavedObjects.map((savedMapObject) => savedMapObject.attributes && savedMapObject.attributes.layerListJSON ? JSON.parse(savedMapObject.attributes.layerListJSON) : [] ); const mapsCount = layerLists.length; - const dataSourcesCount = layerLists.map(lList => { + const dataSourcesCount = layerLists.map((lList) => { // todo: not every source-descriptor has an id // @ts-ignore const sourceIdList = lList.map((layer: LayerDescriptor) => layer.sourceDescriptor.id); return _.uniq(sourceIdList).length; }); - const layersCount = layerLists.map(lList => lList.length); - const layerTypesCount = layerLists.map(lList => _.countBy(lList, 'type')); + const layersCount = layerLists.map((lList) => lList.length); + const layerTypesCount = layerLists.map((lList) => _.countBy(lList, 'type')); // Count of EMS Vector layers used - const emsLayersCount = layerLists.map(lList => + const emsLayersCount = layerLists.map((lList) => _(lList) .countBy((layer: LayerDescriptor) => { const isEmsFile = _.get(layer, 'sourceDescriptor.type') === SOURCE_TYPES.EMS_FILE; diff --git a/x-pack/plugins/maps/server/routes.js b/x-pack/plugins/maps/server/routes.js index de07472275c0c..766ba72b2dcef 100644 --- a/x-pack/plugins/maps/server/routes.js +++ b/x-pack/plugins/maps/server/routes.js @@ -87,7 +87,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const fileLayers = await emsClient.getFileLayers(); - const layer = fileLayers.find(layer => layer.getId() === request.query.id); + const layer = fileLayers.find((layer) => layer.getId() === request.query.id); if (!layer) { return null; } @@ -124,7 +124,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const tmsServices = await emsClient.getTMSServices(); - const tmsService = tmsServices.find(layer => layer.getId() === request.query.id); + const tmsService = tmsServices.find((layer) => layer.getId() === request.query.id); if (!tmsService) { return null; } @@ -155,8 +155,8 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { }; //rewrite the urls to the submanifest - const tileService = main.services.find(service => service.type === 'tms'); - const fileService = main.services.find(service => service.type === 'file'); + const tileService = main.services.find((service) => service.type === 'tms'); + const fileService = main.services.find((service) => service.type === 'file'); if (tileService) { proxiedManifest.services.push({ ...tileService, @@ -186,7 +186,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const file = await emsClient.getDefaultFileManifest(); - const layers = file.layers.map(layer => { + const layers = file.layers.map((layer) => { const newLayer = { ...layer }; const id = encodeURIComponent(layer.layer_id); const newUrl = `${EMS_FILES_DEFAULT_JSON_PATH}?id=${id}`; @@ -216,13 +216,13 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const tilesManifest = await emsClient.getDefaultTMSManifest(); - const newServices = tilesManifest.services.map(service => { + const newServices = tilesManifest.services.map((service) => { const newService = { ...service, }; newService.formats = []; - const rasterFormats = service.formats.filter(format => format.format === 'raster'); + const rasterFormats = service.formats.filter((format) => format.format === 'raster'); if (rasterFormats.length) { const newUrl = `${EMS_TILES_RASTER_STYLE_PATH}?id=${service.id}`; newService.formats.push({ @@ -230,7 +230,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { url: newUrl, }); } - const vectorFormats = service.formats.filter(format => format.format === 'vector'); + const vectorFormats = service.formats.filter((format) => format.format === 'vector'); if (vectorFormats.length) { const newUrl = `${EMS_TILES_VECTOR_STYLE_PATH}?id=${service.id}`; newService.formats.push({ @@ -269,7 +269,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const tmsServices = await emsClient.getTMSServices(); - const tmsService = tmsServices.find(layer => layer.getId() === request.query.id); + const tmsService = tmsServices.find((layer) => layer.getId() === request.query.id); if (!tmsService) { return null; } @@ -305,7 +305,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const tmsServices = await emsClient.getTMSServices(); - const tmsService = tmsServices.find(layer => layer.getId() === request.query.id); + const tmsService = tmsServices.find((layer) => layer.getId() === request.query.id); if (!tmsService) { return null; } @@ -355,7 +355,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const tmsServices = await emsClient.getTMSServices(); - const tmsService = tmsServices.find(layer => layer.getId() === request.query.id); + const tmsService = tmsServices.find((layer) => layer.getId() === request.query.id); if (!tmsService) { return null; } @@ -403,7 +403,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const tmsServices = await emsClient.getTMSServices(); - const tmsService = tmsServices.find(layer => layer.getId() === request.query.id); + const tmsService = tmsServices.find((layer) => layer.getId() === request.query.id); if (!tmsService) { return null; } @@ -455,7 +455,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { } const tmsServices = await emsClient.getTMSServices(); - const tmsService = tmsServices.find(layer => layer.getId() === request.params.id); + const tmsService = tmsServices.find((layer) => layer.getId() === request.params.id); if (!tmsService) { return null; } diff --git a/x-pack/plugins/maps/server/saved_objects/migrations.js b/x-pack/plugins/maps/server/saved_objects/migrations.js index 13b38353d6807..5f9576740db29 100644 --- a/x-pack/plugins/maps/server/saved_objects/migrations.js +++ b/x-pack/plugins/maps/server/saved_objects/migrations.js @@ -15,7 +15,7 @@ import { migrateJoinAggKey } from '../../common/migrations/join_agg_key'; export const migrations = { map: { - '7.2.0': doc => { + '7.2.0': (doc) => { const { attributes, references } = extractReferences(doc); return { @@ -24,7 +24,7 @@ export const migrations = { references, }; }, - '7.4.0': doc => { + '7.4.0': (doc) => { const attributes = emsRasterTileToEmsVectorTile(doc); return { @@ -32,7 +32,7 @@ export const migrations = { attributes, }; }, - '7.5.0': doc => { + '7.5.0': (doc) => { const attributes = topHitsTimeToSort(doc); return { @@ -40,7 +40,7 @@ export const migrations = { attributes, }; }, - '7.6.0': doc => { + '7.6.0': (doc) => { const attributesPhase1 = moveApplyGlobalQueryToSources(doc); const attributesPhase2 = addFieldMetaOptions({ attributes: attributesPhase1 }); @@ -49,7 +49,7 @@ export const migrations = { attributes: attributesPhase2, }; }, - '7.7.0': doc => { + '7.7.0': (doc) => { const attributesPhase1 = migrateSymbolStyleDescriptor(doc); const attributesPhase2 = migrateUseTopHitsToScalingType({ attributes: attributesPhase1 }); @@ -58,7 +58,7 @@ export const migrations = { attributes: attributesPhase2, }; }, - '7.8.0': doc => { + '7.8.0': (doc) => { const attributes = migrateJoinAggKey(doc); return { diff --git a/x-pack/plugins/ml/common/license/ml_license.ts b/x-pack/plugins/ml/common/license/ml_license.ts index 25b5b4992b227..e4367c9b921f4 100644 --- a/x-pack/plugins/ml/common/license/ml_license.ts +++ b/x-pack/plugins/ml/common/license/ml_license.ts @@ -31,7 +31,7 @@ export class MlLicense { license$: Observable, postInitFunctions?: Array<(lic: MlLicense) => void> ) { - this._licenseSubscription = license$.subscribe(async license => { + this._licenseSubscription = license$.subscribe(async (license) => { const { isEnabled: securityIsEnabled } = license.getFeature('security'); this._license = license; @@ -42,7 +42,7 @@ export class MlLicense { this._isFullLicense = isFullLicense(this._license); if (this._initialized === false && postInitFunctions !== undefined) { - postInitFunctions.forEach(f => f(this)); + postInitFunctions.forEach((f) => f(this)); } this._initialized = true; }); diff --git a/x-pack/plugins/ml/common/types/capabilities.ts b/x-pack/plugins/ml/common/types/capabilities.ts index 572217ce16eee..9216430ab7830 100644 --- a/x-pack/plugins/ml/common/types/capabilities.ts +++ b/x-pack/plugins/ml/common/types/capabilities.ts @@ -73,11 +73,11 @@ export function getPluginPrivileges() { return { user: { ui: userMlCapabilitiesKeys, - api: userMlCapabilitiesKeys.map(k => `ml:${k}`), + api: userMlCapabilitiesKeys.map((k) => `ml:${k}`), }, admin: { ui: allMlCapabilities, - api: allMlCapabilities.map(k => `ml:${k}`), + api: allMlCapabilities.map((k) => `ml:${k}`), }, }; } diff --git a/x-pack/plugins/ml/common/types/common.ts b/x-pack/plugins/ml/common/types/common.ts index 691b3e9eb1163..f04ff2539e4e9 100644 --- a/x-pack/plugins/ml/common/types/common.ts +++ b/x-pack/plugins/ml/common/types/common.ts @@ -11,7 +11,7 @@ export interface Dictionary { // converts a dictionary to an array. note this loses the dictionary `key` information. // however it's able to retain the type information of the dictionary elements. export function dictionaryToArray(dict: Dictionary): TValue[] { - return Object.keys(dict).map(key => dict[key]); + return Object.keys(dict).map((key) => dict[key]); } // A recursive partial type to allow passing nested partial attributes. diff --git a/x-pack/plugins/ml/common/util/job_utils.ts b/x-pack/plugins/ml/common/util/job_utils.ts index 3822e54ddd53c..1fef0e6e2ecba 100644 --- a/x-pack/plugins/ml/common/util/job_utils.ts +++ b/x-pack/plugins/ml/common/util/job_utils.ts @@ -178,7 +178,7 @@ export function isModelPlotEnabled( if (detectorHasPartitionField) { const partitionEntity = entityFields.find( - entityField => entityField.fieldName === detector.partition_field_name + (entityField) => entityField.fieldName === detector.partition_field_name ); isEnabled = partitionEntity?.fieldValue !== undefined && @@ -187,7 +187,7 @@ export function isModelPlotEnabled( if (isEnabled === true && detectorHasByField === true) { const byEntity = entityFields.find( - entityField => entityField.fieldName === detector.by_field_name + (entityField) => entityField.fieldName === detector.by_field_name ); isEnabled = byEntity?.fieldValue !== undefined && terms.indexOf(String(byEntity.fieldValue)) !== -1; @@ -349,7 +349,7 @@ export function basicJobValidation( // Analysis Configuration if (job.analysis_config.categorization_filters) { let v = true; - _.each(job.analysis_config.categorization_filters, d => { + _.each(job.analysis_config.categorization_filters, (d) => { try { new RegExp(d); } catch (e) { @@ -381,7 +381,7 @@ export function basicJobValidation( valid = false; } else { let v = true; - _.each(job.analysis_config.detectors, d => { + _.each(job.analysis_config.detectors, (d) => { if (_.isEmpty(d.function)) { v = false; } @@ -398,7 +398,7 @@ export function basicJobValidation( if (job.analysis_config.detectors.length >= 2) { // create an array of objects with a subset of the attributes // where we want to make sure they are not be the same across detectors - const compareSubSet = job.analysis_config.detectors.map(d => + const compareSubSet = job.analysis_config.detectors.map((d) => _.pick(d, [ 'function', 'field_name', @@ -479,8 +479,8 @@ export function basicJobValidation( return { messages, valid, - contains: id => messages.some(m => id === m.id), - find: id => messages.find(m => id === m.id), + contains: (id) => messages.some((m) => id === m.id), + find: (id) => messages.find((m) => id === m.id), }; } @@ -507,8 +507,8 @@ export function basicDatafeedValidation(datafeed: Datafeed): ValidationResults { return { messages, valid, - contains: id => messages.some(m => id === m.id), - find: id => messages.find(m => id === m.id), + contains: (id) => messages.some((m) => id === m.id), + find: (id) => messages.find((m) => id === m.id), }; } @@ -540,8 +540,8 @@ export function validateModelMemoryLimit(job: Job, limits: MlServerLimits): Vali return { valid, messages, - contains: id => messages.some(m => id === m.id), - find: id => messages.find(m => id === m.id), + contains: (id) => messages.some((m) => id === m.id), + find: (id) => messages.find((m) => id === m.id), }; } @@ -567,16 +567,16 @@ export function validateModelMemoryLimitUnits( return { valid, messages, - contains: id => messages.some(m => id === m.id), - find: id => messages.find(m => id === m.id), + contains: (id) => messages.some((m) => id === m.id), + find: (id) => messages.find((m) => id === m.id), }; } export function validateGroupNames(job: Job): ValidationResults { const { groups = [] } = job; const errorMessages: ValidationResults['messages'] = [ - ...(groups.some(group => !isJobIdValid(group)) ? [{ id: 'job_group_id_invalid' }] : []), - ...(groups.some(group => maxLengthValidator(JOB_ID_MAX_LENGTH)(group)) + ...(groups.some((group) => !isJobIdValid(group)) ? [{ id: 'job_group_id_invalid' }] : []), + ...(groups.some((group) => maxLengthValidator(JOB_ID_MAX_LENGTH)(group)) ? [{ id: 'job_group_id_invalid_max_length' }] : []), ]; @@ -586,8 +586,8 @@ export function validateGroupNames(job: Job): ValidationResults { return { valid, messages, - contains: id => messages.some(m => id === m.id), - find: id => messages.find(m => id === m.id), + contains: (id) => messages.some((m) => id === m.id), + find: (id) => messages.find((m) => id === m.id), }; } @@ -626,6 +626,6 @@ export function processCreatedBy(customSettings: CustomSettings) { export function splitIndexPatternNames(indexPatternName: string): string[] { return indexPatternName.includes(',') - ? indexPatternName.split(',').map(i => i.trim()) + ? indexPatternName.split(',').map((i) => i.trim()) : [indexPatternName]; } diff --git a/x-pack/plugins/ml/common/util/parse_interval.ts b/x-pack/plugins/ml/common/util/parse_interval.ts index 98a41be96941b..0f348f43d47b3 100644 --- a/x-pack/plugins/ml/common/util/parse_interval.ts +++ b/x-pack/plugins/ml/common/util/parse_interval.ts @@ -26,9 +26,7 @@ const SUPPORT_ZERO_DURATION_UNITS: SupportedUnits[] = ['ms', 's', 'm', 'h']; // 3. Fractional intervals e.g. 1.5h or 4.5d are not allowed, in line with the behaviour // of the Elasticsearch date histogram aggregation. export function parseInterval(interval: string): Duration | null { - const matches = String(interval) - .trim() - .match(INTERVAL_STRING_RE); + const matches = String(interval).trim().match(INTERVAL_STRING_RE); if (!Array.isArray(matches) || matches.length < 3) { return null; } diff --git a/x-pack/plugins/ml/common/util/string_utils.ts b/x-pack/plugins/ml/common/util/string_utils.ts index 9dd2ce3d74cd5..bd4ca02bf93cc 100644 --- a/x-pack/plugins/ml/common/util/string_utils.ts +++ b/x-pack/plugins/ml/common/util/string_utils.ts @@ -10,7 +10,7 @@ export function renderTemplate(str: string, data?: Record): stri const matches = str.match(/{{(.*?)}}/g); if (Array.isArray(matches) && data !== undefined) { - matches.forEach(v => { + matches.forEach((v) => { str = str.replace(v, data[v.replace(/{{|}}/g, '')]); }); } @@ -19,6 +19,6 @@ export function renderTemplate(str: string, data?: Record): stri } export function getMedianStringLength(strings: string[]) { - const sortedStringLengths = strings.map(s => s.length).sort((a, b) => a - b); + const sortedStringLengths = strings.map((s) => s.length).sort((a, b) => a - b); return sortedStringLengths[Math.floor(sortedStringLengths.length / 2)] || 0; } diff --git a/x-pack/plugins/ml/common/util/validation_utils.ts b/x-pack/plugins/ml/common/util/validation_utils.ts index 1ae5a899a4b4d..ee4be34c6f600 100644 --- a/x-pack/plugins/ml/common/util/validation_utils.ts +++ b/x-pack/plugins/ml/common/util/validation_utils.ts @@ -10,7 +10,7 @@ import { VALIDATION_STATUS } from '../constants/validation'; const contains = (arr: string[], str: string) => arr.indexOf(str) >= 0; export function getMostSevereMessageStatus(messages: Array<{ status: string }>): VALIDATION_STATUS { - const statuses = messages.map(m => m.status); + const statuses = messages.map((m) => m.status); return [VALIDATION_STATUS.INFO, VALIDATION_STATUS.WARNING, VALIDATION_STATUS.ERROR].reduce( (previous, current) => { return contains(statuses, current) ? current : previous; diff --git a/x-pack/plugins/ml/common/util/validators.ts b/x-pack/plugins/ml/common/util/validators.ts index 304d9a0029540..6f959c50219cf 100644 --- a/x-pack/plugins/ml/common/util/validators.ts +++ b/x-pack/plugins/ml/common/util/validators.ts @@ -13,7 +13,7 @@ import { ALLOWED_DATA_UNITS } from '../constants/validation'; export function maxLengthValidator( maxLength: number ): (value: string) => { maxLength: { requiredLength: number; actualLength: number } } | null { - return value => + return (value) => value && value.length > maxLength ? { maxLength: { @@ -31,7 +31,7 @@ export function maxLengthValidator( export function patternValidator( pattern: RegExp ): (value: string) => { pattern: { matchPattern: string } } | null { - return value => + return (value) => pattern.test(value) ? null : { @@ -48,7 +48,7 @@ export function patternValidator( export function composeValidators( ...validators: Array<(value: any) => { [key: string]: any } | null> ): (value: any) => { [key: string]: any } | null { - return value => { + return (value) => { const validationResult = validators.reduce((acc, validator) => { return { ...acc, diff --git a/x-pack/plugins/ml/public/application/app.tsx b/x-pack/plugins/ml/public/application/app.tsx index e9796fcbb0fe4..4b6ff8c64822b 100644 --- a/x-pack/plugins/ml/public/application/app.tsx +++ b/x-pack/plugins/ml/public/application/app.tsx @@ -78,7 +78,7 @@ export const renderApp = ( const mlLicense = setLicenseCache(deps.licensing); - appMountParams.onAppLeave(actions => actions.default()); + appMountParams.onAppLeave((actions) => actions.default()); ReactDOM.render(, appMountParams.element); diff --git a/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts b/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts index 1ca176d8d09ce..65ea03caef526 100644 --- a/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts +++ b/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts @@ -20,7 +20,7 @@ export function checkGetManagementMlJobsResolver() { ({ capabilities, isPlatinumOrTrialLicense, mlFeatureEnabledInSpace }) => { _capabilities = capabilities; // Loop through all capabilities to ensure they are all set to true. - const isManageML = Object.values(_capabilities).every(p => p === true); + const isManageML = Object.values(_capabilities).every((p) => p === true); if (isManageML === true && isPlatinumOrTrialLicense === true) { return resolve({ mlFeatureEnabledInSpace }); diff --git a/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx b/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx index ceaf986b0d54f..f341f129e4653 100644 --- a/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx +++ b/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx @@ -185,7 +185,7 @@ class AnnotationFlyoutUI extends Component { ); } }) - .catch(resp => { + .catch((resp) => { const toastNotifications = getToastNotifications(); if (typeof annotation._id === 'undefined') { toastNotifications.addDanger( @@ -339,7 +339,7 @@ class AnnotationFlyoutUI extends Component { } } -export const AnnotationFlyout: FC = props => { +export const AnnotationFlyout: FC = (props) => { const annotationProp = useObservable(annotation$); if (annotationProp === undefined) { diff --git a/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js b/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js index d9c32be41cd72..52d266cde1a2c 100644 --- a/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js +++ b/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js @@ -95,7 +95,7 @@ export class AnnotationsTable extends Component { maxAnnotations: ANNOTATIONS_TABLE_DEFAULT_QUERY_SIZE, }) .toPromise() - .then(resp => { + .then((resp) => { this.setState((prevState, props) => ({ annotations: resp.annotations[props.jobs[0].job_id] || [], errorMessage: undefined, @@ -103,7 +103,7 @@ export class AnnotationsTable extends Component { jobId: props.jobs[0].job_id, })); }) - .catch(resp => { + .catch((resp) => { console.log('Error loading list of annotations for jobs list:', resp); this.setState({ annotations: [], @@ -225,7 +225,7 @@ export class AnnotationsTable extends Component { window.open(`#/timeseriesexplorer${url}`, '_self'); }; - onMouseOverRow = record => { + onMouseOverRow = (record) => { if (this.mouseOverRecord !== undefined) { if (this.mouseOverRecord.rowId !== record.rowId) { // Mouse is over a different row, fire mouseleave on the previous record. @@ -354,7 +354,7 @@ export class AnnotationsTable extends Component { }, ]; - const jobIds = _.uniq(annotations.map(a => a.job_id)); + const jobIds = _.uniq(annotations.map((a) => a.job_id)); if (jobIds.length > 1) { columns.unshift({ field: 'job_id', @@ -373,7 +373,7 @@ export class AnnotationsTable extends Component { }), sortable: true, width: '60px', - render: key => { + render: (key) => { return {key}; }, }); @@ -382,7 +382,7 @@ export class AnnotationsTable extends Component { const actions = []; actions.push({ - render: annotation => { + render: (annotation) => { const editAnnotationsTooltipText = ( { + render: (annotation) => { const isDrillDownAvailable = isTimeSeriesViewJob(this.getJob(annotation.job_id)); const openInSingleMetricViewerTooltipText = isDrillDownAvailable ? ( { + const getRowProps = (item) => { return { onMouseOver: () => this.onMouseOverRow(item), onMouseLeave: () => this.onMouseLeaveRow(), diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js index 6728f019a6bd5..2a890f75fecd8 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js @@ -44,8 +44,8 @@ class AnomaliesTable extends Component { // Update the itemIdToExpandedRowMap state if a change to the table data has resulted // in an anomaly that was previously expanded no longer being in the data. const itemIdToExpandedRowMap = prevState.itemIdToExpandedRowMap; - const prevExpandedNotInData = Object.keys(itemIdToExpandedRowMap).find(rowId => { - const matching = nextProps.tableData.anomalies.find(anomaly => { + const prevExpandedNotInData = Object.keys(itemIdToExpandedRowMap).find((rowId) => { + const matching = nextProps.tableData.anomalies.find((anomaly) => { return anomaly.rowId === rowId; }); @@ -108,7 +108,7 @@ class AnomaliesTable extends Component { this.setState({ itemIdToExpandedRowMap }); }; - onMouseOverRow = record => { + onMouseOverRow = (record) => { if (this.mouseOverRecord !== undefined) { if (this.mouseOverRecord.rowId !== record.rowId) { // Mouse is over a different row, fire mouseleave on the previous record. @@ -132,7 +132,7 @@ class AnomaliesTable extends Component { } }; - setShowRuleEditorFlyoutFunction = func => { + setShowRuleEditorFlyoutFunction = (func) => { this.setState({ showRuleEditorFlyout: func, }); @@ -191,7 +191,7 @@ class AnomaliesTable extends Component { }, }; - const getRowProps = item => { + const getRowProps = (item) => { return { onMouseOver: () => this.onMouseOverRow(item), onMouseLeave: () => this.onMouseLeaveRow(), diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js index 8f79ce4a6c08a..af7c6c8e289f3 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js @@ -76,7 +76,7 @@ export function getColumns(

), - render: item => ( + render: (item) => ( toggleRow(item)} iconType={itemIdToExpandedRowMap[item.rowId] ? 'arrowDown' : 'arrowRight'} @@ -102,7 +102,7 @@ export function getColumns( }), dataType: 'date', scope: 'row', - render: date => renderTime(date, interval), + render: (date) => renderTime(date, interval), textOnly: true, sortable: true, }, @@ -131,7 +131,7 @@ export function getColumns( }, ]; - if (items.some(item => item.entityValue !== undefined)) { + if (items.some((item) => item.entityValue !== undefined)) { columns.push({ field: 'entityValue', 'data-test-subj': 'mlAnomaliesListColumnFoundFor', @@ -151,14 +151,14 @@ export function getColumns( }); } - if (items.some(item => item.influencers !== undefined)) { + if (items.some((item) => item.influencers !== undefined)) { columns.push({ field: 'influencers', 'data-test-subj': 'mlAnomaliesListColumnInfluencers', name: i18n.translate('xpack.ml.anomaliesTable.influencersColumnName', { defaultMessage: 'influenced by', }), - render: influencers => ( + render: (influencers) => ( item.actual !== undefined)) { + if (items.some((item) => item.actual !== undefined)) { columns.push({ field: 'actualSort', 'data-test-subj': 'mlAnomaliesListColumnActual', @@ -191,7 +191,7 @@ export function getColumns( }); } - if (items.some(item => item.typical !== undefined)) { + if (items.some((item) => item.typical !== undefined)) { columns.push({ field: 'typicalSort', 'data-test-subj': 'mlAnomaliesListColumnTypical', @@ -210,7 +210,7 @@ export function getColumns( // Assume that if we are showing typical, there will be an actual too, // so we can add a column to describe how actual compares to typical. - const nonTimeOfDayOrWeek = items.some(item => { + const nonTimeOfDayOrWeek = items.some((item) => { const summaryRecFunc = item.source.function; return summaryRecFunc !== 'time_of_day' && summaryRecFunc !== 'time_of_week'; }); @@ -241,7 +241,7 @@ export function getColumns( }); } - const showExamples = items.some(item => item.entityName === 'mlcategory'); + const showExamples = items.some((item) => item.entityName === 'mlcategory'); if (showExamples === true) { columns.push({ 'data-test-subj': 'mlAnomaliesListColumnCategoryExamples', @@ -250,7 +250,7 @@ export function getColumns( }), sortable: false, truncateText: true, - render: item => { + render: (item) => { const examples = _.get(examplesByJobId, [item.jobId, item.entityValue], []); return ( showLinksMenuForItem(item, showViewSeriesLink)); + const showLinks = items.some((item) => showLinksMenuForItem(item, showViewSeriesLink)); if (showLinks === true) { columns.push({ @@ -280,7 +280,7 @@ export function getColumns( name: i18n.translate('xpack.ml.anomaliesTable.actionsColumnName', { defaultMessage: 'actions', }), - render: item => { + render: (item) => { if (showLinksMenuForItem(item, showViewSeriesLink) === true) { return ( { + causes = sourceCauses.map((cause) => { const simplified = _.pick(cause, 'typical', 'actual', 'probability'); // Get the 'entity field name/value' to display in the cause - // For by and over, use by_field_name/value (over_field_name/value are in the top level fields) @@ -229,7 +229,7 @@ function getInfluencersItems(anomalyInfluencers, influencerFilter, numToDisplay) const items = []; for (let i = 0; i < numToDisplay; i++) { - Object.keys(anomalyInfluencers[i]).forEach(influencerFieldName => { + Object.keys(anomalyInfluencers[i]).forEach((influencerFieldName) => { const value = anomalyInfluencers[i][influencerFieldName]; items.push({ diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/influencers_cell.js b/x-pack/plugins/ml/public/application/components/anomalies_table/influencers_cell.js index f4b16dab5ef52..2e42606c048d7 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/influencers_cell.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/influencers_cell.js @@ -147,7 +147,7 @@ export class InfluencersCell extends Component { const recordInfluencers = this.props.influencers || []; const influencers = []; - recordInfluencers.forEach(influencer => { + recordInfluencers.forEach((influencer) => { _.each(influencer, (influencerFieldValue, influencerFieldName) => { influencers.push({ influencerFieldName, diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js b/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js index ef4f35591edf4..4850d583a626c 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js @@ -51,7 +51,7 @@ class LinksMenuUI extends Component { }; } - openCustomUrl = customUrl => { + openCustomUrl = (customUrl) => { const { anomaly, interval, isAggregatedData } = this.props; console.log('Anomalies Table - open customUrl for record:', anomaly); @@ -107,10 +107,10 @@ class LinksMenuUI extends Component { ml.results .getCategoryDefinition(jobId, categoryId) - .then(resp => { + .then((resp) => { // Prefix each of the terms with '+' so that the Elasticsearch Query String query // run in a drilldown Kibana dashboard has to match on all terms. - const termsArray = resp.terms.split(' ').map(term => `+${term}`); + const termsArray = resp.terms.split(' ').map((term) => `+${term}`); record.mlcategoryterms = termsArray.join(' '); record.mlcategoryregex = resp.regex; @@ -119,7 +119,7 @@ class LinksMenuUI extends Component { const urlPath = replaceStringTokens(customUrl.url_value, record, true); openCustomUrlWindow(urlPath, customUrl); }) - .catch(resp => { + .catch((resp) => { console.log('openCustomUrl(): error loading categoryDefinition:', resp); const { toasts } = this.props.kibana.services.notifications; toasts.addDanger( @@ -267,7 +267,7 @@ class LinksMenuUI extends Component { // categorization field is of mapping type text (preferred) or keyword. ml.results .getCategoryDefinition(record.job_id, categoryId) - .then(resp => { + .then((resp) => { let query = null; // Build query using categorization regex (if keyword type) or terms (if text type). // Check for terms or regex in case categoryId represents an anomaly from the absence of the @@ -327,7 +327,7 @@ class LinksMenuUI extends Component { path += '&_a=' + encodeURIComponent(_a); window.open(path, '_blank'); }) - .catch(resp => { + .catch((resp) => { console.log('viewExamples(): error loading categoryDefinition:', resp); const { toasts } = this.props.kibana.services.notifications; toasts.addDanger( @@ -344,7 +344,7 @@ class LinksMenuUI extends Component { function findFieldType(index) { getFieldTypeFromMapping(index, categorizationFieldName) - .then(resp => { + .then((resp) => { if (resp !== '') { createAndOpenUrl(index, resp); } else { @@ -363,7 +363,7 @@ class LinksMenuUI extends Component { }; onButtonClick = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isPopoverOpen: !prevState.isPopoverOpen, })); }; diff --git a/x-pack/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx b/x-pack/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx index 3ca191d6251cf..7897ef5cad0df 100644 --- a/x-pack/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx +++ b/x-pack/plugins/ml/public/application/components/chart_tooltip/chart_tooltip.tsx @@ -27,7 +27,7 @@ const Tooltip: FC<{ service: ChartTooltipService }> = React.memo(({ service }) = const refCallback = useRef(); useEffect(() => { - const subscription = service.tooltipState$.subscribe(tooltipState => { + const subscription = service.tooltipState$.subscribe((tooltipState) => { if (refCallback.current) { // update trigger refCallback.current(tooltipState.target); diff --git a/x-pack/plugins/ml/public/application/components/color_range_legend/color_range_legend.tsx b/x-pack/plugins/ml/public/application/components/color_range_legend/color_range_legend.tsx index d6f0d347a57ec..25af3f0ec2f7f 100644 --- a/x-pack/plugins/ml/public/application/components/color_range_legend/color_range_legend.tsx +++ b/x-pack/plugins/ml/public/application/components/color_range_legend/color_range_legend.tsx @@ -36,7 +36,7 @@ export const ColorRangeLegend: FC = ({ }) => { const d3Container = useRef(null); - const scale = d3.range(COLOR_RANGE_RESOLUTION + 1).map(d => ({ + const scale = d3.range(COLOR_RANGE_RESOLUTION + 1).map((d) => ({ offset: (d / COLOR_RANGE_RESOLUTION) * 100, stopColor: colorRange(d / COLOR_RANGE_RESOLUTION), })); @@ -59,9 +59,7 @@ export const ColorRangeLegend: FC = ({ const legendHeight = wrapperHeight - margin.top - margin.bottom; // remove, then redraw the legend - d3.select(d3Container.current) - .selectAll('*') - .remove(); + d3.select(d3Container.current).selectAll('*').remove(); const wrapper = d3 .select(d3Container.current) @@ -82,7 +80,7 @@ export const ColorRangeLegend: FC = ({ .attr('y2', '0%') .attr('spreadMethod', 'pad'); - scale.forEach(function(d) { + scale.forEach(function (d) { gradient .append('stop') .attr('offset', `${d.offset}%`) @@ -98,10 +96,7 @@ export const ColorRangeLegend: FC = ({ .attr('height', legendHeight) .style('fill', 'url(#mlColorRangeGradient)'); - const axisScale = d3.scale - .linear() - .domain([0, 1]) - .range([0, legendWidth]); + const axisScale = d3.scale.linear().domain([0, 1]).range([0, legendWidth]); // Using this formatter ensures we get e.g. `0` and not `0.0`, but still `0.1`, `0.2` etc. const tickFormat = d3.format(''); diff --git a/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.test.tsx b/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.test.tsx index e1861b887b2a9..83e7b82986cf8 100644 --- a/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.test.tsx +++ b/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.test.tsx @@ -26,7 +26,7 @@ describe('SelectInterval', () => { expect(defaultSelectedValue).toBe('auto'); }); - test('currently selected value is updated correctly on click', done => { + test('currently selected value is updated correctly on click', (done) => { const wrapper = mount( diff --git a/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.tsx b/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.tsx index cea3ef2a497b0..307900c6985ff 100644 --- a/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.tsx +++ b/x-pack/plugins/ml/public/application/components/controls/select_interval/select_interval.tsx @@ -47,7 +47,7 @@ const OPTIONS = [ function optionValueToInterval(value: string) { // Builds the corresponding interval object with the required display and val properties // from the specified value. - const option = OPTIONS.find(opt => opt.value === value); + const option = OPTIONS.find((opt) => opt.value === value); // Default to auto if supplied value doesn't map to one of the options. let interval: TableInterval = { display: OPTIONS[0].text, val: OPTIONS[0].value }; diff --git a/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.test.tsx b/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.test.tsx index e30c48c10a194..484a0c395f3f8 100644 --- a/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.test.tsx +++ b/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.test.tsx @@ -62,7 +62,7 @@ describe('SelectSeverity', () => { ); }); - test('state for currently selected value is updated correctly on click', done => { + test('state for currently selected value is updated correctly on click', (done) => { const wrapper = mount( diff --git a/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.tsx b/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.tsx index a03594a5f213e..b8333e72c9ffb 100644 --- a/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.tsx +++ b/x-pack/plugins/ml/public/application/components/controls/select_severity/select_severity.tsx @@ -67,7 +67,7 @@ export const SEVERITY_OPTIONS: TableSeverity[] = [ function optionValueToThreshold(value: number) { // Get corresponding threshold object with required display and val properties from the specified value. - let threshold = SEVERITY_OPTIONS.find(opt => opt.val === value); + let threshold = SEVERITY_OPTIONS.find((opt) => opt.val === value); // Default to warning if supplied value doesn't map to one of the options. if (threshold === undefined) { diff --git a/x-pack/plugins/ml/public/application/components/data_grid/common.ts b/x-pack/plugins/ml/public/application/components/data_grid/common.ts index d141b68b5d03f..44a2473f75937 100644 --- a/x-pack/plugins/ml/public/application/components/data_grid/common.ts +++ b/x-pack/plugins/ml/public/application/components/data_grid/common.ts @@ -55,8 +55,8 @@ export const euiDataGridToolbarSettings = { }; export const getFieldsFromKibanaIndexPattern = (indexPattern: IndexPattern): string[] => { - const allFields = indexPattern.fields.map(f => f.name); - const indexPatternFields: string[] = allFields.filter(f => { + const allFields = indexPattern.fields.map((f) => f.name); + const indexPatternFields: string[] = allFields.filter((f) => { if (indexPattern.metaFields.includes(f)) { return false; } @@ -78,7 +78,7 @@ export interface FieldTypes { } export const getDataGridSchemasFromFieldTypes = (fieldTypes: FieldTypes, resultsField: string) => { - return Object.keys(fieldTypes).map(field => { + return Object.keys(fieldTypes).map((field) => { // Built-in values are ['boolean', 'currency', 'datetime', 'numeric', 'json'] // To fall back to the default string schema it needs to be undefined. let schema; diff --git a/x-pack/plugins/ml/public/application/components/data_grid/data_grid.tsx b/x-pack/plugins/ml/public/application/components/data_grid/data_grid.tsx index aeb774a224021..618075a77d906 100644 --- a/x-pack/plugins/ml/public/application/components/data_grid/data_grid.tsx +++ b/x-pack/plugins/ml/public/application/components/data_grid/data_grid.tsx @@ -52,7 +52,7 @@ function isWithHeader(arg: any): arg is PropsWithHeader { type Props = PropsWithHeader | PropsWithoutHeader; export const DataGrid: FC = memo( - props => { + (props) => { const { columns, dataTestSubj, @@ -75,7 +75,7 @@ export const DataGrid: FC = memo( useEffect(() => { if (invalidSortingColumnns.length > 0) { - invalidSortingColumnns.forEach(columnId => { + invalidSortingColumnns.forEach((columnId) => { toastNotifications.addDanger( i18n.translate('xpack.ml.dataGrid.invalidSortingColumnError', { defaultMessage: `The column '{columnId}' cannot be used for sorting.`, diff --git a/x-pack/plugins/ml/public/application/components/data_grid/use_data_grid.ts b/x-pack/plugins/ml/public/application/components/data_grid/use_data_grid.ts index c7c4f46031b6e..7843bf2ea801b 100644 --- a/x-pack/plugins/ml/public/application/components/data_grid/use_data_grid.ts +++ b/x-pack/plugins/ml/public/application/components/data_grid/use_data_grid.ts @@ -37,15 +37,15 @@ export const useDataGrid = ( const [pagination, setPagination] = useState(defaultPagination); const [sortingColumns, setSortingColumns] = useState([]); - const onChangeItemsPerPage: OnChangeItemsPerPage = useCallback(pageSize => { - setPagination(p => { + const onChangeItemsPerPage: OnChangeItemsPerPage = useCallback((pageSize) => { + setPagination((p) => { const pageIndex = Math.floor((p.pageSize * p.pageIndex) / pageSize); return { pageIndex, pageSize }; }); }, []); const onChangePage: OnChangePage = useCallback( - pageIndex => setPagination(p => ({ ...p, pageIndex })), + (pageIndex) => setPagination((p) => ({ ...p, pageIndex })), [] ); @@ -54,7 +54,7 @@ export const useDataGrid = ( // Column visibility const [visibleColumns, setVisibleColumns] = useState([]); - const columnIds = columns.map(c => c.id); + const columnIds = columns.map((c) => c.id); const filteredColumnIds = defaultVisibleColumnsFilter !== undefined ? columnIds.filter(defaultVisibleColumnsFilter) @@ -69,10 +69,10 @@ export const useDataGrid = ( const [invalidSortingColumnns, setInvalidSortingColumnns] = useState([]); const onSort: OnSort = useCallback( - sc => { + (sc) => { // Check if an unsupported column type for sorting was selected. const updatedInvalidSortingColumnns = sc.reduce((arr, current) => { - const columnType = columns.find(dgc => dgc.id === current.id); + const columnType = columns.find((dgc) => dgc.id === current.id); if (columnType?.schema === 'json') { arr.push(current.id); } diff --git a/x-pack/plugins/ml/public/application/components/data_recognizer/data_recognizer.js b/x-pack/plugins/ml/public/application/components/data_recognizer/data_recognizer.js index fd19e6b2f06b6..5790b8bd239e0 100644 --- a/x-pack/plugins/ml/public/application/components/data_recognizer/data_recognizer.js +++ b/x-pack/plugins/ml/public/application/components/data_recognizer/data_recognizer.js @@ -28,8 +28,8 @@ export class DataRecognizer extends Component { componentDidMount() { // once the mount is complete, call the recognize endpoint to see if the index format is known to us, ml.recognizeIndex({ indexPatternTitle: this.indexPattern.title }) - .then(resp => { - const results = resp.map(r => ( + .then((resp) => { + const results = resp.map((r) => ( { + .catch((e) => { console.error('Error attempting to recognize index', e); }); } diff --git a/x-pack/plugins/ml/public/application/components/influencers_list/influencers_list.js b/x-pack/plugins/ml/public/application/components/influencers_list/influencers_list.js index 1044caa83e2ad..06978dc0aa736 100644 --- a/x-pack/plugins/ml/public/application/components/influencers_list/influencers_list.js +++ b/x-pack/plugins/ml/public/application/components/influencers_list/influencers_list.js @@ -103,7 +103,7 @@ Influencer.propTypes = { }; function InfluencersByName({ influencerFieldName, influencerFilter, fieldValues }) { - const influencerValues = fieldValues.map(valueData => ( + const influencerValues = fieldValues.map((valueData) => ( ( + const influencersByName = Object.keys(influencers).map((influencerFieldName) => ( = 0} - onChange={e => { + onChange={(e) => { setItemSelected(item, e.target.checked); }} /> diff --git a/x-pack/plugins/ml/public/application/components/items_grid/items_grid_pagination.js b/x-pack/plugins/ml/public/application/components/items_grid/items_grid_pagination.js index b76cb5d66a35f..8d170e76664b1 100644 --- a/x-pack/plugins/ml/public/application/components/items_grid/items_grid_pagination.js +++ b/x-pack/plugins/ml/public/application/components/items_grid/items_grid_pagination.js @@ -48,11 +48,11 @@ export class ItemsGridPagination extends Component { }); }; - onPageClick = pageNumber => { + onPageClick = (pageNumber) => { this.props.setActivePage(pageNumber); }; - onChangeItemsPerPage = pageSize => { + onChangeItemsPerPage = (pageSize) => { this.closePopover(); this.props.setItemsPerPage(pageSize); }; @@ -78,7 +78,7 @@ export class ItemsGridPagination extends Component { const pageCount = Math.ceil(itemCount / itemsPerPage); - const items = itemsPerPageOptions.map(pageSize => { + const items = itemsPerPageOptions.map((pageSize) => { return ( { + selectedIds.forEach((id) => { selectedIdsMap[id] = true; }); return selectedIdsMap; @@ -100,10 +100,10 @@ export function CustomSelectionTable({ function handleTableChange({ isSelected, itemId }) { const selectedMapIds = Object.getOwnPropertyNames(itemIdToSelectedMap); - const currentItemIds = currentItems.map(item => item.id); + const currentItemIds = currentItems.map((item) => item.id); let currentSelected = selectedMapIds.filter( - id => itemIdToSelectedMap[id] === true && id !== itemId + (id) => itemIdToSelectedMap[id] === true && id !== itemId ); if (itemId !== 'all') { @@ -113,7 +113,7 @@ export function CustomSelectionTable({ } else { if (isSelected === false) { // don't include any current items in the selection update since we're deselecting 'all' - currentSelected = currentSelected.filter(id => currentItemIds.includes(id) === false); + currentSelected = currentSelected.filter((id) => currentItemIds.includes(id) === false); } else { // grab all id's currentSelected = [...currentSelected, ...currentItemIds]; @@ -161,7 +161,7 @@ export function CustomSelectionTable({ } function areAllItemsSelected() { - const indexOfUnselectedItem = currentItems.findIndex(item => !isItemSelected(item.id)); + const indexOfUnselectedItem = currentItems.findIndex((item) => !isItemSelected(item.id)); return indexOfUnselectedItem === -1; } @@ -199,7 +199,7 @@ export function CustomSelectionTable({ function toggleAll() { const allSelected = areAllItemsSelected() || itemIdToSelectedMap.all === true; const newItemIdToSelectedMap = {}; - currentItems.forEach(item => (newItemIdToSelectedMap[item.id] = !allSelected)); + currentItems.forEach((item) => (newItemIdToSelectedMap[item.id] = !allSelected)); setItemIdToSelectedMap(newItemIdToSelectedMap); handleTableChange({ isSelected: !allSelected, itemId: 'all' }); } @@ -244,8 +244,8 @@ export function CustomSelectionTable({ } function renderRows() { - const renderRow = item => { - const cells = columns.map(column => { + const renderRow = (item) => { + const cells = columns.map((column) => { const cell = item[column.id]; let child; @@ -371,7 +371,7 @@ export function CustomSelectionTable({ itemsPerPageOptions={[10, JOBS_PER_PAGE, 50]} pageCount={pager.getTotalPages()} onChangeItemsPerPage={handleChangeItemsPerPage} - onChangePage={pageIndex => handlePageChange(pageIndex)} + onChangePage={(pageIndex) => handlePageChange(pageIndex)} /> )} diff --git a/x-pack/plugins/ml/public/application/components/job_selector/id_badges/id_badges.js b/x-pack/plugins/ml/public/application/components/job_selector/id_badges/id_badges.js index 1810896770c7a..8afe9aa06fb09 100644 --- a/x-pack/plugins/ml/public/application/components/job_selector/id_badges/id_badges.js +++ b/x-pack/plugins/ml/public/application/components/job_selector/id_badges/id_badges.js @@ -38,7 +38,7 @@ export function IdBadges({ limit, maps, onLinkClick, selectedIds, showAllBarBadg if (maps.groupsMap[currentId] === undefined) { const jobGroups = maps.jobsMap[currentId] || []; - if (jobGroups.some(g => currentGroups.includes(g)) === false) { + if (jobGroups.some((g) => currentGroups.includes(g)) === false) { badges.push( diff --git a/x-pack/plugins/ml/public/application/components/job_selector/job_select_service_utils.ts b/x-pack/plugins/ml/public/application/components/job_selector/job_select_service_utils.ts index 3a215f8cfb46d..3f3de405711c5 100644 --- a/x-pack/plugins/ml/public/application/components/job_selector/job_select_service_utils.ts +++ b/x-pack/plugins/ml/public/application/components/job_selector/job_select_service_utils.ts @@ -15,10 +15,10 @@ export function getGroupsFromJobs(jobs: MlJobWithTimeRange[]) { const groups: Dictionary = {}; const groupsMap: Dictionary = {}; - jobs.forEach(job => { + jobs.forEach((job) => { // Organize job by group if (job.groups !== undefined) { - job.groups.forEach(g => { + job.groups.forEach((g) => { if (groups[g] === undefined) { groups[g] = { id: g, @@ -61,7 +61,7 @@ export function getGroupsFromJobs(jobs: MlJobWithTimeRange[]) { } }); - Object.keys(groups).forEach(groupId => { + Object.keys(groups).forEach((groupId) => { const group = groups[groupId]; group.timeRange.widthPx = group.timeRange.toPx - group.timeRange.fromPx; group.timeRange.toMoment = moment(group.timeRange.to); @@ -78,13 +78,13 @@ export function getGroupsFromJobs(jobs: MlJobWithTimeRange[]) { }); }); - return { groups: Object.keys(groups).map(g => groups[g]), groupsMap }; + return { groups: Object.keys(groups).map((g) => groups[g]), groupsMap }; } export function getTimeRangeFromSelection(jobs: MlJobWithTimeRange[], selection: string[]) { if (jobs.length > 0) { const times: number[] = []; - jobs.forEach(job => { + jobs.forEach((job) => { if (selection.includes(job.job_id)) { if (job.timeRange.from !== undefined) { times.push(job.timeRange.from); @@ -110,18 +110,15 @@ export function normalizeTimes( dateFormatTz: string, ganttBarWidth: number ) { - const jobsWithTimeRange = jobs.filter(job => { + const jobsWithTimeRange = jobs.filter((job) => { return job.timeRange.to !== undefined && job.timeRange.from !== undefined; }); - const min = Math.min(...jobsWithTimeRange.map(job => +job.timeRange.from)); - const max = Math.max(...jobsWithTimeRange.map(job => +job.timeRange.to)); - const ganttScale = d3.scale - .linear() - .domain([min, max]) - .range([1, ganttBarWidth]); + const min = Math.min(...jobsWithTimeRange.map((job) => +job.timeRange.from)); + const max = Math.max(...jobsWithTimeRange.map((job) => +job.timeRange.to)); + const ganttScale = d3.scale.linear().domain([min, max]).range([1, ganttBarWidth]); - jobs.forEach(job => { + jobs.forEach((job) => { if (job.timeRange.to !== undefined && job.timeRange.from !== undefined) { job.timeRange.fromPx = ganttScale(job.timeRange.from); job.timeRange.toPx = ganttScale(job.timeRange.to); diff --git a/x-pack/plugins/ml/public/application/components/job_selector/job_selector.tsx b/x-pack/plugins/ml/public/application/components/job_selector/job_selector.tsx index f709c161bef17..6bdf2fdb7caa2 100644 --- a/x-pack/plugins/ml/public/application/components/job_selector/job_selector.tsx +++ b/x-pack/plugins/ml/public/application/components/job_selector/job_selector.tsx @@ -33,12 +33,12 @@ function mergeSelection( const selectedIds: string[] = []; const alreadySelected: string[] = []; - groupObjs.forEach(group => { + groupObjs.forEach((group) => { selectedIds.push(group.groupId); alreadySelected.push(...group.jobIds); }); - jobIds.forEach(jobId => { + jobIds.forEach((jobId) => { // Add jobId if not already included in group selection if (alreadySelected.includes(jobId) === false) { selectedIds.push(jobId); @@ -53,7 +53,7 @@ export function getInitialGroupsMap(selectedGroups: GroupObj[]): GroupsMap { const map: GroupsMap = {}; if (selectedGroups.length) { - selectedGroups.forEach(group => { + selectedGroups.forEach((group) => { map[group.groupId] = group.jobIds; }); } diff --git a/x-pack/plugins/ml/public/application/components/job_selector/job_selector_flyout.tsx b/x-pack/plugins/ml/public/application/components/job_selector/job_selector_flyout.tsx index 66aa05d2aaa97..3fb654f35be4d 100644 --- a/x-pack/plugins/ml/public/application/components/job_selector/job_selector_flyout.tsx +++ b/x-pack/plugins/ml/public/application/components/job_selector/job_selector_flyout.tsx @@ -85,7 +85,7 @@ export const JobSelectorFlyout: FC = ({ const allNewSelection: string[] = []; const groupSelection: Array<{ groupId: string; jobIds: string[] }> = []; - newSelection.forEach(id => { + newSelection.forEach((id) => { if (jobGroupsMaps.groupsMap[id] !== undefined) { // Push all jobs from selected groups into the newSelection list allNewSelection.push(...jobGroupsMaps.groupsMap[id]); @@ -111,7 +111,7 @@ export const JobSelectorFlyout: FC = ({ } function removeId(id: string) { - setNewSelection(newSelection.filter(item => item !== id)); + setNewSelection(newSelection.filter((item) => item !== id)); } function toggleTimerangeSwitch() { diff --git a/x-pack/plugins/ml/public/application/components/job_selector/job_selector_table/job_selector_table.js b/x-pack/plugins/ml/public/application/components/job_selector/job_selector_table/job_selector_table.js index c55e03776c09d..4eeef560dd6d1 100644 --- a/x-pack/plugins/ml/public/application/components/job_selector/job_selector_table/job_selector_table.js +++ b/x-pack/plugins/ml/public/application/components/job_selector/job_selector_table/job_selector_table.js @@ -38,12 +38,12 @@ export function JobSelectorTable({ sortablePropertyItems = [ { name: 'job_id', - getValue: item => item.job_id.toLowerCase(), + getValue: (item) => item.job_id.toLowerCase(), isAscending: true, }, { name: 'groups', - getValue: item => (item.groups && item.groups[0] ? item.groups[0].toLowerCase() : ''), + getValue: (item) => (item.groups && item.groups[0] ? item.groups[0].toLowerCase() : ''), isAscending: true, }, ]; @@ -52,7 +52,7 @@ export function JobSelectorTable({ sortablePropertyItems = [ { name: 'id', - getValue: item => item.id.toLowerCase(), + getValue: (item) => item.id.toLowerCase(), isAscending: true, }, ]; @@ -81,7 +81,7 @@ export function JobSelectorTable({ ]; function getGroupOptions() { - return groupsList.map(g => ({ + return groupsList.map((g) => ({ value: g.id, view: ( @@ -121,7 +121,9 @@ export function JobSelectorTable({ isSortable: true, alignment: LEFT_ALIGNMENT, render: ({ groups = [] }) => - groups.map(group => ), + groups.map((group) => ( + + )), }, { label: 'time range', @@ -154,7 +156,7 @@ export function JobSelectorTable({ filters={filters} filterDefaultFields={!singleSelection ? JOB_FILTER_FIELDS : undefined} items={jobs} - onTableChange={selectionFromTable => onSelection({ selectionFromTable })} + onTableChange={(selectionFromTable) => onSelection({ selectionFromTable })} selectedIds={selectedIds} singleSelection={singleSelection} sortableProperties={sortableProperties} @@ -200,7 +202,7 @@ export function JobSelectorTable({ columns={groupColumns} filterDefaultFields={!singleSelection ? GROUP_FILTER_FIELDS : undefined} items={groupsList} - onTableChange={selectionFromTable => onSelection({ selectionFromTable })} + onTableChange={(selectionFromTable) => onSelection({ selectionFromTable })} selectedIds={selectedIds} sortableProperties={sortableProperties} /> @@ -213,7 +215,7 @@ export function JobSelectorTable({ size="s" tabs={tabs} initialSelectedTab={tabs[0]} - onTabClick={tab => { + onTabClick={(tab) => { setCurrentTab(tab.id); }} /> diff --git a/x-pack/plugins/ml/public/application/components/job_selector/use_job_selection.ts b/x-pack/plugins/ml/public/application/components/job_selector/use_job_selection.ts index d3fad9ae6bc2c..74c238a0895ca 100644 --- a/x-pack/plugins/ml/public/application/components/job_selector/use_job_selection.ts +++ b/x-pack/plugins/ml/public/application/components/job_selector/use_job_selection.ts @@ -19,8 +19,8 @@ import { getTimeRangeFromSelection } from './job_select_service_utils'; // check that the ids read from the url exist by comparing them to the // jobs loaded via mlJobsService. function getInvalidJobIds(jobs: MlJobWithTimeRange[], ids: string[]) { - return ids.filter(id => { - const jobExists = jobs.some(job => job.job_id === id); + return ids.filter((id) => { + const jobExists = jobs.some((job) => job.job_id === id); return jobExists === false && id !== '*'; }); } diff --git a/x-pack/plugins/ml/public/application/components/navigation_menu/top_nav/top_nav.tsx b/x-pack/plugins/ml/public/application/components/navigation_menu/top_nav/top_nav.tsx index edc6aece265f3..abaaf2cc3a185 100644 --- a/x-pack/plugins/ml/public/application/components/navigation_menu/top_nav/top_nav.tsx +++ b/x-pack/plugins/ml/public/application/components/navigation_menu/top_nav/top_nav.tsx @@ -27,7 +27,7 @@ interface RefreshInterval { } function getRecentlyUsedRangesFactory(timeHistory: TimeHistoryContract) { - return function(): Duration[] { + return function (): Duration[] { return ( timeHistory.get()?.map(({ from, to }: TimeRange) => { return { diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/condition_expression.js b/x-pack/plugins/ml/public/application/components/rule_editor/condition_expression.js index e6b1f55775608..ceb03b5f175ac 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/condition_expression.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/condition_expression.js @@ -84,17 +84,17 @@ export class ConditionExpression extends Component { }); }; - changeAppliesTo = event => { + changeAppliesTo = (event) => { const { index, operator, value, updateCondition } = this.props; updateCondition(index, event.target.value, operator, value); }; - changeOperator = event => { + changeOperator = (event) => { const { index, appliesTo, value, updateCondition } = this.props; updateCondition(index, appliesTo, event.target.value, value); }; - changeValue = event => { + changeValue = (event) => { const { index, appliesTo, operator, updateCondition } = this.props; updateCondition(index, appliesTo, operator, +event.target.value); }; diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js b/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js index f259a1f1ffb02..0f3b484402819 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js @@ -91,7 +91,7 @@ class RuleEditorFlyoutUI extends Component { } } - showFlyout = anomaly => { + showFlyout = (anomaly) => { let ruleIndex = -1; const job = mlJobService.getJob(anomaly.jobId); if (job === undefined) { @@ -144,13 +144,13 @@ class RuleEditorFlyoutUI extends Component { // Load the current list of filters. These are used for configuring rule scope. ml.filters .filters() - .then(filters => { - const filterListIds = filters.map(filter => filter.filter_id); + .then((filters) => { + const filterListIds = filters.map((filter) => filter.filter_id); this.setState({ filterListIds, }); }) - .catch(resp => { + .catch((resp) => { console.log('Error loading list of filters:', resp); const { toasts } = this.props.kibana.services.notifications; toasts.addDanger( @@ -169,7 +169,7 @@ class RuleEditorFlyoutUI extends Component { this.setState({ isFlyoutVisible: false }); }; - setEditRuleIndex = ruleIndex => { + setEditRuleIndex = (ruleIndex) => { const detectorIndex = this.state.anomaly.detectorIndex; const detector = this.state.job.analysis_config.detectors[detectorIndex]; const rules = detector.custom_rules; @@ -182,7 +182,7 @@ class RuleEditorFlyoutUI extends Component { const isScopeEnabled = rule.scope !== undefined && Object.keys(rule.scope).length > 0; if (isScopeEnabled === true) { // Add 'enabled:true' to mark them as selected in the UI. - Object.keys(rule.scope).forEach(field => { + Object.keys(rule.scope).forEach((field) => { rule.scope[field].enabled = true; }); } @@ -195,9 +195,9 @@ class RuleEditorFlyoutUI extends Component { }); }; - onSkipResultChange = e => { + onSkipResultChange = (e) => { const checked = e.target.checked; - this.setState(prevState => { + this.setState((prevState) => { const actions = [...prevState.rule.actions]; const idx = actions.indexOf(ACTION.SKIP_RESULT); if (idx === -1 && checked) { @@ -212,9 +212,9 @@ class RuleEditorFlyoutUI extends Component { }); }; - onSkipModelUpdateChange = e => { + onSkipModelUpdateChange = (e) => { const checked = e.target.checked; - this.setState(prevState => { + this.setState((prevState) => { const actions = [...prevState.rule.actions]; const idx = actions.indexOf(ACTION.SKIP_MODEL_UPDATE); if (idx === -1 && checked) { @@ -229,9 +229,9 @@ class RuleEditorFlyoutUI extends Component { }); }; - onConditionsEnabledChange = e => { + onConditionsEnabledChange = (e) => { const isConditionsEnabled = e.target.checked; - this.setState(prevState => { + this.setState((prevState) => { let conditions; if (isConditionsEnabled === false) { // Clear any conditions that have been added. @@ -249,7 +249,7 @@ class RuleEditorFlyoutUI extends Component { }; addCondition = () => { - this.setState(prevState => { + this.setState((prevState) => { const conditions = [...prevState.rule.conditions]; conditions.push(getNewConditionDefaults()); @@ -260,7 +260,7 @@ class RuleEditorFlyoutUI extends Component { }; updateCondition = (index, appliesTo, operator, value) => { - this.setState(prevState => { + this.setState((prevState) => { const conditions = [...prevState.rule.conditions]; if (index < conditions.length) { conditions[index] = { @@ -276,8 +276,8 @@ class RuleEditorFlyoutUI extends Component { }); }; - deleteCondition = index => { - this.setState(prevState => { + deleteCondition = (index) => { + this.setState((prevState) => { const conditions = [...prevState.rule.conditions]; if (index < conditions.length) { conditions.splice(index, 1); @@ -289,9 +289,9 @@ class RuleEditorFlyoutUI extends Component { }); }; - onScopeEnabledChange = e => { + onScopeEnabledChange = (e) => { const isScopeEnabled = e.target.checked; - this.setState(prevState => { + this.setState((prevState) => { const rule = { ...prevState.rule }; if (isScopeEnabled === false) { // Clear scope property. @@ -306,7 +306,7 @@ class RuleEditorFlyoutUI extends Component { }; updateScope = (fieldName, filterId, filterType, enabled) => { - this.setState(prevState => { + this.setState((prevState) => { let scope = { ...prevState.rule.scope }; if (scope === undefined) { scope = {}; @@ -338,7 +338,7 @@ class RuleEditorFlyoutUI extends Component { const detectorIndex = anomaly.detectorIndex; saveJobRule(job, detectorIndex, ruleIndex, editedRule) - .then(resp => { + .then((resp) => { if (resp.success) { toasts.add({ title: i18n.translate( @@ -370,7 +370,7 @@ class RuleEditorFlyoutUI extends Component { ); } }) - .catch(error => { + .catch((error) => { console.error(error); toasts.addDanger( i18n.translate( @@ -384,14 +384,14 @@ class RuleEditorFlyoutUI extends Component { }); }; - deleteRuleAtIndex = index => { + deleteRuleAtIndex = (index) => { const { toasts } = this.props.kibana.services.notifications; const { job, anomaly } = this.state; const jobId = job.job_id; const detectorIndex = anomaly.detectorIndex; deleteJobRule(job, detectorIndex, index) - .then(resp => { + .then((resp) => { if (resp.success) { toasts.addSuccess( i18n.translate( @@ -415,7 +415,7 @@ class RuleEditorFlyoutUI extends Component { ); } }) - .catch(error => { + .catch((error) => { console.error(error); let errorMessage = i18n.translate( 'xpack.ml.ruleEditor.ruleEditorFlyout.errorWithDeletingRuleFromJobDetectorNotificationMessage', @@ -456,7 +456,7 @@ class RuleEditorFlyoutUI extends Component { this.closeFlyout(); } }) - .catch(error => { + .catch((error) => { console.log(`Error adding ${item} to filter ${filterId}:`, error); toasts.addDanger( i18n.translate( diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.test.js b/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.test.js index 3e8a17eeb8617..79080ef0f9bb6 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.test.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.test.js @@ -50,7 +50,7 @@ jest.mock('../../capabilities/check_capabilities', () => ({ })); jest.mock('../../../../../../../src/plugins/kibana_react/public', () => ({ - withKibana: comp => { + withKibana: (comp) => { return comp; }, })); diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/scope_expression.js b/x-pack/plugins/ml/public/application/components/rule_editor/scope_expression.js index d776ebb8c4cd5..a8c7ac0f6f598 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/scope_expression.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/scope_expression.js @@ -29,7 +29,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; const POPOVER_STYLE = { zIndex: '200' }; function getFilterListOptions(filterListIds) { - return filterListIds.map(filterId => ({ value: filterId, text: filterId })); + return filterListIds.map((filterId) => ({ value: filterId, text: filterId })); } export class ScopeExpression extends Component { @@ -53,19 +53,19 @@ export class ScopeExpression extends Component { }); }; - onChangeFilterType = event => { + onChangeFilterType = (event) => { const { fieldName, filterId, enabled, updateScope } = this.props; updateScope(fieldName, filterId, event.target.value, enabled); }; - onChangeFilterId = event => { + onChangeFilterId = (event) => { const { fieldName, filterType, enabled, updateScope } = this.props; updateScope(fieldName, event.target.value, filterType, enabled); }; - onEnableChange = event => { + onEnableChange = (event) => { const { fieldName, filterId, filterType, updateScope } = this.props; updateScope(fieldName, filterId, filterType, event.target.checked); @@ -131,7 +131,7 @@ export class ScopeExpression extends Component { } value={fieldName} isActive={false} - onClick={event => event.preventDefault()} + onClick={(event) => event.preventDefault()} /> diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/scope_section.test.js b/x-pack/plugins/ml/public/application/components/rule_editor/scope_section.test.js index 189fb6a35d3e6..839dcee870983 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/scope_section.test.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/scope_section.test.js @@ -12,7 +12,7 @@ jest.mock('../../services/job_service.js', () => 'mlJobService'); // with 'mock' so it can be used lazily. const mockCheckPermission = jest.fn(() => true); jest.mock('../../capabilities/check_capabilities', () => ({ - checkPermission: privilege => mockCheckPermission(privilege), + checkPermission: (privilege) => mockCheckPermission(privilege), })); import { shallowWithIntl } from 'test_utils/enzyme_helpers'; diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/edit_condition_link.js b/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/edit_condition_link.js index 07ca459949947..612cebff60d02 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/edit_condition_link.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/edit_condition_link.js @@ -52,7 +52,7 @@ export class EditConditionLink extends Component { this.state = { value }; } - onChangeValue = event => { + onChangeValue = (event) => { const enteredValue = event.target.value; this.setState({ value: enteredValue !== '' ? +enteredValue : '', diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.js b/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.js index ec966ec8bcded..c8071d2629eeb 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.js @@ -57,13 +57,13 @@ export class RuleActionPanel extends Component { const filterId = scope[partitionFieldName].filter_id; ml.filters .filters({ filterId }) - .then(filter => { + .then((filter) => { const filterItems = filter.items; if (filterItems.indexOf(partitionFieldValue[0]) === -1) { this.setState({ showAddToFilterListLink: true }); } }) - .catch(resp => { + .catch((resp) => { console.log(`Error loading filter ${filterId}:`, resp); }); } diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/utils.js b/x-pack/plugins/ml/public/application/components/rule_editor/utils.js index f8787100d6b95..a697eed00fd66 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/utils.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/utils.js @@ -60,7 +60,7 @@ export function isValidRule(rule) { } else { const scope = rule.scope; if (scope !== undefined) { - isValid = Object.keys(scope).some(field => scope[field].enabled === true); + isValid = Object.keys(scope).some((field) => scope[field].enabled === true); } } } @@ -76,7 +76,7 @@ export function saveJobRule(job, detectorIndex, ruleIndex, editedRule) { const clonedRule = cloneDeep(editedRule); const scope = clonedRule.scope; if (scope !== undefined) { - Object.keys(scope).forEach(field => { + Object.keys(scope).forEach((field) => { if (scope[field].enabled === false) { delete scope[field]; } else { @@ -148,7 +148,7 @@ export function updateJobRules(job, detectorIndex, rules) { return new Promise((resolve, reject) => { mlJobService .updateJob(jobId, jobData) - .then(resp => { + .then((resp) => { if (resp.success) { // Refresh the job data in the job service before resolving. mlJobService @@ -156,14 +156,14 @@ export function updateJobRules(job, detectorIndex, rules) { .then(() => { resolve({ success: true }); }) - .catch(refreshResp => { + .catch((refreshResp) => { reject(refreshResp); }); } else { reject(resp); } }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -175,10 +175,10 @@ export function addItemToFilter(item, filterId) { return new Promise((resolve, reject) => { ml.filters .updateFilter(filterId, undefined, [item], undefined) - .then(updatedFilter => { + .then((updatedFilter) => { resolve(updatedFilter); }) - .catch(error => { + .catch((error) => { reject(error); }); }); diff --git a/x-pack/plugins/ml/public/application/components/stats_bar/stats_bar.tsx b/x-pack/plugins/ml/public/application/components/stats_bar/stats_bar.tsx index 4ad1139bc9b52..0bd33a8c99f49 100644 --- a/x-pack/plugins/ml/public/application/components/stats_bar/stats_bar.tsx +++ b/x-pack/plugins/ml/public/application/components/stats_bar/stats_bar.tsx @@ -32,7 +32,7 @@ interface StatsBarProps { } export const StatsBar: FC = ({ stats, dataTestSub }) => { - const statsList = Object.keys(stats).map(k => stats[k as StatsKey]); + const statsList = Object.keys(stats).map((k) => stats[k as StatsKey]); return (
{statsList diff --git a/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js b/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js index 6001d7cbf6f61..dde6925631d3e 100644 --- a/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js +++ b/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js @@ -47,7 +47,7 @@ const getDefaultState = () => ({ title: '', }); -const statusToEuiColor = status => { +const statusToEuiColor = (status) => { switch (status) { case VALIDATION_STATUS.INFO: return 'primary'; @@ -60,7 +60,7 @@ const statusToEuiColor = status => { } }; -const statusToEuiIconType = status => { +const statusToEuiIconType = (status) => { switch (status) { case VALIDATION_STATUS.INFO: return 'iInCircle'; @@ -104,7 +104,7 @@ Message.propTypes = { const MessageList = ({ messages, idFilterList }) => { const callouts = messages - .filter(m => idFilterList.includes(m.id) === false) + .filter((m) => idFilterList.includes(m.id) === false) .map((m, i) => ); // there could be no error or success messages due to the @@ -209,7 +209,7 @@ export class ValidateJob extends Component { if (typeof job === 'object') { let shouldShowLoadingIndicator = true; - this.props.mlJobService.validateJob({ duration, fields, job }).then(data => { + this.props.mlJobService.validateJob({ duration, fields, job }).then((data) => { shouldShowLoadingIndicator = false; this.setState({ ...this.state, @@ -224,7 +224,7 @@ export class ValidateJob extends Component { }); if (typeof this.props.setIsValid === 'function') { this.props.setIsValid( - data.messages.some(m => m.status === VALIDATION_STATUS.ERROR) === false + data.messages.some((m) => m.status === VALIDATION_STATUS.ERROR) === false ); } }); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts index 7501fe3d82fc6..7633e07e8f3dc 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts @@ -343,7 +343,7 @@ export const useRefreshAnalyticsList = ( subscriptions.push( distinct$ - .pipe(filter(state => state === REFRESH_ANALYTICS_LIST_STATE.REFRESH)) + .pipe(filter((state) => state === REFRESH_ANALYTICS_LIST_STATE.REFRESH)) .subscribe(() => typeof callback.onRefresh === 'function' && callback.onRefresh()) ); } @@ -351,7 +351,7 @@ export const useRefreshAnalyticsList = ( if (typeof callback.isLoading === 'function') { subscriptions.push( distinct$.subscribe( - state => + (state) => typeof callback.isLoading === 'function' && callback.isLoading(state === REFRESH_ANALYTICS_LIST_STATE.LOADING) ) @@ -359,7 +359,7 @@ export const useRefreshAnalyticsList = ( } return () => { - subscriptions.map(sub => sub.unsubscribe()); + subscriptions.map((sub) => sub.unsubscribe()); }; }, []); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/fields.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/fields.ts index 8423bc1b94a09..8db349b395cfc 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/fields.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/fields.ts @@ -51,7 +51,7 @@ export const ML__ID_COPY = 'ml__id_copy'; export const isKeywordAndTextType = (fieldName: string): boolean => { const { fields } = newJobCapsService; - const fieldType = fields.find(field => field.name === fieldName)?.type; + const fieldType = fields.find((field) => field.name === fieldName)?.type; let isBothTypes = false; // If it's a keyword type - check if it has a corresponding text type @@ -192,8 +192,8 @@ export const getDefaultFieldsFromJobCaps = ( featureInfluenceFields.push( ...fields - .filter(d => !jobConfig.analyzed_fields.excludes.includes(d.id)) - .map(d => ({ + .filter((d) => !jobConfig.analyzed_fields.excludes.includes(d.id)) + .map((d) => ({ id: `${resultsField}.${FEATURE_INFLUENCE}.${d.id}`, name: `${resultsField}.${FEATURE_INFLUENCE}.${d.name}`, type: KBN_FIELD_TYPES.NUMBER, diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts index 87b8c15aeaa78..eb38a23d10eef 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts @@ -34,7 +34,7 @@ export const getIndexData = async ( try { const sort: EsSorting = sortingColumns - .map(column => { + .map((column) => { const { id } = column; column.id = isKeywordAndTextType(id) ? `${id}.keyword` : id; return column; @@ -57,7 +57,7 @@ export const getIndexData = async ( setRowCount(resp.hits.total.value); - const docs = resp.hits.hits.map(d => d._source); + const docs = resp.hits.hits.map((d) => d._source); setTableItems(docs); setStatus(INDEX_STATUS.LOADED); } catch (e) { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_fields.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_fields.ts index 12ae4a586e949..9aacf216dd2a5 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_fields.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_fields.ts @@ -29,13 +29,13 @@ export const getIndexFields = ( const types: FieldTypes = {}; const allFields: string[] = []; - docFields.forEach(field => { + docFields.forEach((field) => { types[field.id] = field.type; allFields.push(field.id); }); return { - defaultSelectedFields: defaultSelected.map(field => field.id), + defaultSelectedFields: defaultSelected.map((field) => field.id), fieldTypes: types, tableFields: allFields, }; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts index 0bc9e78207596..2570dd20416be 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts @@ -34,7 +34,7 @@ export const useResultsViewConfig = (jobId: string) => { // get analytics configuration, index pattern and field caps useEffect(() => { - (async function() { + (async function () { setIsLoadingJobConfig(false); try { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/column_data.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/column_data.tsx index 14493ab024f34..64fdf161b5615 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/column_data.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/column_data.tsx @@ -36,7 +36,7 @@ export function getColumnData(confusionMatrixData: ConfusionMatrix[]) { let showOther = false; - confusionMatrixData.forEach(classData => { + confusionMatrixData.forEach((classData) => { const otherCount = classData.other_predicted_class_doc_count; if (otherCount > 0) { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts index e664a1ddbdbcc..e391b90e6eb96 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts @@ -48,7 +48,7 @@ export const useExplorationResults = ( // reduce default selected rows from 20 to 8 for performance reasons. 8, // by default, hide feature-importance columns and the doc id copy - d => !d.includes(`.${FEATURE_IMPORTANCE}.`) && d !== ML__ID_COPY + (d) => !d.includes(`.${FEATURE_IMPORTANCE}.`) && d !== ML__ID_COPY ); useEffect(() => { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/common.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/common.ts index bfd3dd33995aa..3746fa12bdc1e 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/common.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/common.ts @@ -17,7 +17,7 @@ export const getFeatureCount = (resultsField: string, tableItems: DataGridItem[] return 0; } - return Object.keys(tableItems[0]).filter(key => + return Object.keys(tableItems[0]).filter((key) => key.includes(`${resultsField}.${FEATURE_INFLUENCE}.`) ).length; }; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts index 75b2f6aa867df..ebac6ccb2298e 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts @@ -55,7 +55,7 @@ export const useOutlierData = ( // reduce default selected rows from 20 to 8 for performance reasons. 8, // by default, hide feature-influence columns and the doc id copy - d => !d.includes(`.${FEATURE_INFLUENCE}.`) && d !== ML__ID_COPY + (d) => !d.includes(`.${FEATURE_INFLUENCE}.`) && d !== ML__ID_COPY ); useEffect(() => { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_delete.test.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_delete.test.tsx index 3e5224b76329e..2ef1515726d1b 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_delete.test.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/action_delete.test.tsx @@ -26,7 +26,7 @@ describe('DeleteAction', () => { test('When canDeleteDataFrameAnalytics permission is true, button should not be disabled.', () => { const mock = jest.spyOn(CheckPrivilige, 'checkPermission'); - mock.mockImplementation(p => p === 'canDeleteDataFrameAnalytics'); + mock.mockImplementation((p) => p === 'canDeleteDataFrameAnalytics'); const { getByTestId } = render(); expect(getByTestId('mlAnalyticsJobDeleteButton')).not.toHaveAttribute('disabled'); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/analytics_list.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/analytics_list.tsx index 68e728c019873..4a99c042b108b 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/analytics_list.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/analytics_list.tsx @@ -59,7 +59,7 @@ function getItemIdToExpandedRowMap( dataFrameAnalytics: DataFrameAnalyticsListRow[] ): ItemIdToExpandedRowMap { return itemIds.reduce((m: ItemIdToExpandedRowMap, analyticsId: DataFrameAnalyticsId) => { - const item = dataFrameAnalytics.find(analytics => analytics.config.id === analyticsId); + const item = dataFrameAnalytics.find((analytics) => analytics.config.id === analyticsId); if (item !== undefined) { m[analyticsId] = ; } @@ -176,7 +176,7 @@ export const DataFrameAnalyticsList: FC = ({ return p; }, {}); - clauses.forEach(c => { + clauses.forEach((c) => { // the search term could be negated with a minus, e.g. -bananas const bool = c.match === 'must'; let ts: DataFrameAnalyticsListRow[]; @@ -187,12 +187,12 @@ export const DataFrameAnalyticsList: FC = ({ // if the term has been negated, AND the matches if (bool === true) { ts = analytics.filter( - d => stringMatch(d.id, c.value) === bool // || + (d) => stringMatch(d.id, c.value) === bool // || // stringMatch(d.config.description, c.value) === bool ); } else { ts = analytics.filter( - d => stringMatch(d.id, c.value) === bool // && + (d) => stringMatch(d.id, c.value) === bool // && // stringMatch(d.config.description, c.value) === bool ); } @@ -200,25 +200,25 @@ export const DataFrameAnalyticsList: FC = ({ // filter other clauses, i.e. the mode and status filters if (Array.isArray(c.value)) { if (c.field === 'job_type') { - ts = analytics.filter(d => + ts = analytics.filter((d) => (c.value as string).includes(getAnalysisType(d.config.analysis)) ); } else { // the status value is an array of string(s) e.g. ['failed', 'stopped'] - ts = analytics.filter(d => (c.value as string).includes(d.stats.state)); + ts = analytics.filter((d) => (c.value as string).includes(d.stats.state)); } } else { - ts = analytics.filter(d => d.mode === c.value); + ts = analytics.filter((d) => d.mode === c.value); } } - ts.forEach(t => matches[t.id].count++); + ts.forEach((t) => matches[t.id].count++); }); // loop through the matches and return only analytics which have match all the clauses const filtered = Object.values(matches) - .filter(m => (m && m.count) >= clauses.length) - .map(m => m.analytics); + .filter((m) => (m && m.count) >= clauses.length) + .map((m) => m.analytics); let pageStart = pageIndex * pageSize; if (pageStart >= filtered.length && filtered.length !== 0) { @@ -330,7 +330,7 @@ export const DataFrameAnalyticsList: FC = ({ defaultMessage: 'Type', }), multiSelect: 'or', - options: Object.values(ANALYSIS_CONFIG_TYPE).map(val => ({ + options: Object.values(ANALYSIS_CONFIG_TYPE).map((val) => ({ value: val, name: val, view: getJobTypeBadge(val), @@ -343,7 +343,7 @@ export const DataFrameAnalyticsList: FC = ({ defaultMessage: 'Status', }), multiSelect: 'or', - options: Object.values(DATA_FRAME_TASK_STATE).map(val => ({ + options: Object.values(DATA_FRAME_TASK_STATE).map((val) => ({ value: val, name: val, view: getTaskStateBadge(val), @@ -426,7 +426,7 @@ export const DataFrameAnalyticsList: FC = ({ sorting={sorting} search={search} data-test-subj={isLoading ? 'mlAnalyticsTable loading' : 'mlAnalyticsTable loaded'} - rowProps={item => ({ + rowProps={(item) => ({ 'data-test-subj': `mlAnalyticsTableRow row-${item.id}`, })} /> diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row.tsx index 94dc7ec87cc61..0ee57fe5be141 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row.tsx @@ -186,7 +186,7 @@ export const ExpandedRow: FC = ({ item }) => { ), description: `${currentPhase}/${totalPhases}`, }, - ...item.stats.progress.map(s => { + ...item.stats.progress.map((s) => { return { title: s.phase, description: , diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row_details_pane.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row_details_pane.tsx index 32b2ca3472018..71ca2b6f60492 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row_details_pane.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row_details_pane.tsx @@ -53,8 +53,8 @@ export const ExpandedRowDetailsPane: FC = ({ sectio {sections - .filter(s => s.position === 'left') - .map(s => ( + .filter((s) => s.position === 'left') + .map((s) => (
@@ -63,8 +63,8 @@ export const ExpandedRowDetailsPane: FC = ({ sectio {sections - .filter(s => s.position === 'right') - .map(s => ( + .filter((s) => s.position === 'right') + .map((s) => (
diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx index cef03cc0d0c76..48eb95948bb12 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx @@ -101,7 +101,7 @@ export const CreateAnalyticsAdvancedEditor: FC = ({ ac ]} > { + inputRef={(input) => { if (input) { forceInput.current = input; } @@ -109,7 +109,7 @@ export const CreateAnalyticsAdvancedEditor: FC = ({ ac disabled={isJobCreated} placeholder="analytics job ID" value={jobId} - onChange={e => setFormState({ jobId: e.target.value })} + onChange={(e) => setFormState({ jobId: e.target.value })} aria-label={i18n.translate( 'xpack.ml.dataframe.analytics.create.advancedEditor.jobIdInputAriaLabel', { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_button/create_analytics_button.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_button/create_analytics_button.tsx index 3c8c3c3b3aa55..952bd48468b0a 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_button/create_analytics_button.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_button/create_analytics_button.tsx @@ -10,7 +10,7 @@ import { i18n } from '@kbn/i18n'; import { createPermissionFailureMessage } from '../../../../../capabilities/check_capabilities'; import { CreateAnalyticsFormProps } from '../../hooks/use_create_analytics_form'; -export const CreateAnalyticsButton: FC = props => { +export const CreateAnalyticsButton: FC = (props) => { const { disabled } = props.state; const { openModal } = props.actions; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout_wrapper/create_analytics_flyout_wrapper.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout_wrapper/create_analytics_flyout_wrapper.tsx index 8716f84be3d34..2f3c38b6ffe4e 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout_wrapper/create_analytics_flyout_wrapper.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_flyout_wrapper/create_analytics_flyout_wrapper.tsx @@ -12,7 +12,7 @@ import { CreateAnalyticsAdvancedEditor } from '../create_analytics_advanced_edit import { CreateAnalyticsForm } from '../create_analytics_form'; import { CreateAnalyticsFlyout } from '../create_analytics_flyout'; -export const CreateAnalyticsFlyoutWrapper: FC = props => { +export const CreateAnalyticsFlyoutWrapper: FC = (props) => { const { isAdvancedEditorEnabled, isModalVisible } = props.state; if (isModalVisible === false) { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/create_analytics_form.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/create_analytics_form.tsx index 11052b171845d..64fe736e67b17 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/create_analytics_form.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/create_analytics_form.tsx @@ -465,7 +465,7 @@ export const CreateAnalyticsForm: FC = ({ actions, sta ]} > { + inputRef={(input) => { if (input) { forceInput.current = input; } @@ -475,7 +475,7 @@ export const CreateAnalyticsForm: FC = ({ actions, sta defaultMessage: 'Job ID', })} value={jobId} - onChange={e => setFormState({ jobId: e.target.value })} + onChange={(e) => setFormState({ jobId: e.target.value })} aria-label={i18n.translate( 'xpack.ml.dataframe.analytics.create.jobIdInputAriaLabel', { @@ -579,7 +579,7 @@ export const CreateAnalyticsForm: FC = ({ actions, sta disabled={isJobCreated} placeholder="destination index" value={destinationIndex} - onChange={e => setFormState({ destinationIndex: e.target.value })} + onChange={(e) => setFormState({ destinationIndex: e.target.value })} aria-label={i18n.translate( 'xpack.ml.dataframe.analytics.create.destinationIndexInputAriaLabel', { @@ -667,7 +667,7 @@ export const CreateAnalyticsForm: FC = ({ actions, sta singleSelection={true} options={dependentVariableOptions} selectedOptions={dependentVariable ? [{ label: dependentVariable }] : []} - onChange={selectedOptions => + onChange={(selectedOptions) => setFormState({ dependentVariable: selectedOptions[0].label || '', }) @@ -691,7 +691,7 @@ export const CreateAnalyticsForm: FC = ({ actions, sta showValue value={trainingPercent} // @ts-ignore Property 'value' does not exist on type 'EventTarget' | (EventTarget & HTMLInputElement) - onChange={e => setFormState({ trainingPercent: +e.target.value })} + onChange={(e) => setFormState({ trainingPercent: +e.target.value })} data-test-subj="mlAnalyticsCreateJobFlyoutTrainingPercentSlider" /> @@ -738,7 +738,7 @@ export const CreateAnalyticsForm: FC = ({ actions, sta disabled={false} isInvalid={numTopFeatureImportanceValuesValid === false} min={NUM_TOP_FEATURE_IMPORTANCE_VALUES_MIN} - onChange={e => setFormState({ numTopFeatureImportanceValues: +e.target.value })} + onChange={(e) => setFormState({ numTopFeatureImportanceValues: +e.target.value })} step={1} value={numTopFeatureImportanceValues} /> @@ -790,12 +790,12 @@ export const CreateAnalyticsForm: FC = ({ actions, sta isDisabled={isJobCreated} isLoading={loadingFieldOptions} options={excludesOptions} - selectedOptions={excludes.map(field => ({ + selectedOptions={excludes.map((field) => ({ label: field, }))} onCreateOption={onCreateOption} - onChange={selectedOptions => - setFormState({ excludes: selectedOptions.map(option => option.label) }) + onChange={(selectedOptions) => + setFormState({ excludes: selectedOptions.map((option) => option.label) }) } isClearable={true} data-test-subj="mlAnalyticsCreateJobFlyoutExcludesSelect" @@ -816,7 +816,7 @@ export const CreateAnalyticsForm: FC = ({ actions, sta } disabled={isJobCreated} value={modelMemoryLimit || ''} - onChange={e => setFormState({ modelMemoryLimit: e.target.value })} + onChange={(e) => setFormState({ modelMemoryLimit: e.target.value })} isInvalid={modelMemoryLimitValidationResult !== null} data-test-subj="mlAnalyticsCreateJobFlyoutModelMemoryInput" /> diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_description.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_description.tsx index 58f3129280c09..46301a6f832e7 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_description.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_description.tsx @@ -27,7 +27,7 @@ export const JobDescriptionInput: FC = ({ description, setFormState }) => value={description} placeholder={helpText} rows={2} - onChange={e => { + onChange={(e) => { const value = e.target.value; setFormState({ description: value }); }} diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_type.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_type.tsx index 210f2c2dbedf1..6daa72dd805b1 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_type.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/create_analytics_form/job_type.tsx @@ -57,13 +57,13 @@ export const JobType: FC = ({ type, setFormState }) => { helpText={type !== undefined ? helpText[type] : ''} > ({ + options={Object.values(ANALYSIS_CONFIG_TYPE).map((jobType) => ({ value: jobType, text: jobType.replace(/_/g, ' '), }))} value={type} hasNoInitialSelection={true} - onChange={e => { + onChange={(e) => { const value = e.target.value as AnalyticsJobType; setFormState({ previousJobType: type, diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.ts index 1cab42d8ee12d..a79a8fcf61ed4 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/reducer.ts @@ -144,7 +144,7 @@ export const validateAdvancedEditor = (state: State): State => { sourceIndexNameValid = !sourceIndex.includes(','); } if (Array.isArray(sourceIndex)) { - sourceIndexNameValid = !sourceIndex.some(d => d?.includes(',')); + sourceIndexNameValid = !sourceIndex.some((d) => d?.includes(',')); } } @@ -479,7 +479,7 @@ export function reducer(state: State, action: Action): State { // update state attributes which are derived from other state attributes. if (action.payload.destinationIndex !== undefined) { newFormState.destinationIndexNameExists = state.indexNames.some( - name => newFormState.destinationIndex === name + (name) => newFormState.destinationIndex === name ); newFormState.destinationIndexNameEmpty = newFormState.destinationIndex === ''; newFormState.destinationIndexNameValid = isValidIndexName(newFormState.destinationIndex); @@ -488,7 +488,7 @@ export function reducer(state: State, action: Action): State { } if (action.payload.jobId !== undefined) { - newFormState.jobIdExists = state.jobIds.some(id => newFormState.jobId === id); + newFormState.jobIdExists = state.jobIds.some((id) => newFormState.jobId === id); newFormState.jobIdEmpty = newFormState.jobId === ''; newFormState.jobIdValid = isJobIdValid(newFormState.jobId); newFormState.jobIdInvalidMaxLength = !!maxLengthValidator(JOB_ID_MAX_LENGTH)( @@ -515,7 +515,7 @@ export function reducer(state: State, action: Action): State { case ACTION.SET_INDEX_NAMES: { const newState = { ...state, indexNames: action.indexNames }; newState.form.destinationIndexNameExists = newState.indexNames.some( - name => newState.form.destinationIndex === name + (name) => newState.form.destinationIndex === name ); return newState; } @@ -547,7 +547,7 @@ export function reducer(state: State, action: Action): State { case ACTION.SET_JOB_IDS: { const newState = { ...state, jobIds: action.jobIds }; - newState.form.jobIdExists = newState.jobIds.some(id => newState.form.jobId === id); + newState.form.jobIdExists = newState.jobIds.some((id) => newState.form.jobId === id); return newState; } diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts index 8ca985a537b6e..4ff7deab34f26 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts @@ -220,7 +220,7 @@ export const getJobConfigFromFormState = ( // the into an array of indices to be in the correct format for // the data frame analytics API. index: formState.sourceIndex.includes(',') - ? formState.sourceIndex.split(',').map(d => d.trim()) + ? formState.sourceIndex.split(',').map((d) => d.trim()) : formState.sourceIndex, }, dest: { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts index 2478dbf7cf63d..1ec767d014a2e 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts @@ -214,7 +214,7 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { } try { - setIndexNames((await ml.getIndices()).map(index => index.name)); + setIndexNames((await ml.getIndices()).map((index) => index.name)); } catch (e) { addRequestMessage({ error: getErrorMessage(e), diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts index df58f225e62de..964e8e4062b38 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts @@ -125,7 +125,7 @@ export const getAnalyticsFactory = ( const tableRows = analyticsConfigs.data_frame_analytics.reduce( (reducedtableRows, config) => { const stats = isGetDataFrameAnalyticsStatsResponseOk(analyticsStats) - ? analyticsStats.data_frame_analytics.find(d => config.id === d.id) + ? analyticsStats.data_frame_analytics.find((d) => config.id === d.id) : undefined; // A newly created analytics job might not have corresponding stats yet. diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/about_panel/about_panel.tsx b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/about_panel/about_panel.tsx index 2bddf0de0499d..8aef8d456e75f 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/about_panel/about_panel.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/about_panel/about_panel.tsx @@ -47,7 +47,7 @@ export const AboutPanel: FC = ({ onFilePickerChange }) => { defaultMessage: 'Select or drag and drop a file', } )} - onChange={files => onFilePickerChange(files)} + onChange={(files) => onFilePickerChange(files)} className="file-datavisualizer-file-picker" />
diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/edit_flyout.js b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/edit_flyout.js index 253ec0ba4d028..1f0115a7ee9d2 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/edit_flyout.js +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/edit_flyout.js @@ -36,13 +36,13 @@ export class EditFlyout extends Component { this.props.closeEditFlyout(); }; - setApplyOverrides = applyOverrides => { + setApplyOverrides = (applyOverrides) => { this.applyOverrides = applyOverrides; }; unsetApplyOverrides = () => { this.applyOverrides = () => {}; }; - setOverridesValid = overridesValid => { + setOverridesValid = (overridesValid) => { this.setState({ overridesValid }); }; diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/options/options.js b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/options/options.js index 503f26a9e978f..7728e96d6fc64 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/options/options.js +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/options/options.js @@ -13,7 +13,7 @@ import { } from './option_lists'; function getOptions(list) { - return list.map(o => ({ label: o })); + return list.map((o) => ({ label: o })); } export function getFormatOptions() { diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.js b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.js index c84e456b206cd..bbbc33052f3c7 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.js +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.js @@ -130,7 +130,7 @@ class OverridesUI extends Component { } if (originalTimestampFormat !== undefined) { - const optionExists = TIMESTAMP_OPTIONS.some(option => option === originalTimestampFormat); + const optionExists = TIMESTAMP_OPTIONS.some((option) => option === originalTimestampFormat); if (optionExists === false) { // Incoming format does not exist in dropdown. Display custom input with incoming format as default value. const overrides = { ...this.state.overrides }; @@ -177,7 +177,7 @@ class OverridesUI extends Component { } }; - onCustomTimestampFormatChange = e => { + onCustomTimestampFormatChange = (e) => { this.setState({ customTimestampFormat: e.target.value }); // check whether the value is valid and set that to state. const { isValid, errorMessage } = isTimestampFormatValid(e.target.value); @@ -195,7 +195,7 @@ class OverridesUI extends Component { this.setOverride({ delimiter }); }; - onCustomDelimiterChange = e => { + onCustomDelimiterChange = (e) => { this.setState({ customDelimiter: e.target.value }); }; @@ -204,11 +204,11 @@ class OverridesUI extends Component { this.setOverride({ quote }); }; - onHasHeaderRowChange = e => { + onHasHeaderRowChange = (e) => { this.setOverride({ hasHeaderRow: e.target.checked }); }; - onShouldTrimFieldsChange = e => { + onShouldTrimFieldsChange = (e) => { this.setOverride({ shouldTrimFields: e.target.checked }); }; @@ -223,11 +223,11 @@ class OverridesUI extends Component { this.setOverride({ columnNames }); }; - grokPatternChange = e => { + grokPatternChange = (e) => { this.setOverride({ grokPattern: e.target.value }); }; - onLinesToSampleChange = e => { + onLinesToSampleChange = (e) => { const linesToSample = +e.target.value; this.setOverride({ linesToSample }); @@ -493,7 +493,7 @@ class OverridesUI extends Component { this.onColumnNameChange(e, i)} + onChange={(e) => this.onColumnNameChange(e, i)} /> ))} @@ -514,7 +514,7 @@ function selectedOption(opt) { // also sort alphanumerically function getSortedFields(fields) { return fields - .map(f => ({ label: f })) + .map((f) => ({ label: f })) .sort((a, b) => a.label.localeCompare(b.label, undefined, { numeric: true })); } diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.test.js b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.test.js index 0257e69053d33..1a2bc20a5192a 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.test.js +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/edit_flyout/overrides.test.js @@ -10,7 +10,7 @@ import React from 'react'; import { Overrides } from './overrides'; jest.mock('../../../../../../../../../src/plugins/kibana_react/public', () => ({ - withKibana: comp => { + withKibana: (comp) => { return comp; }, })); diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/fields_stats/fields_stats.js b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/fields_stats/fields_stats.js index 5dfae43f223b1..9e83f72d7a07b 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/fields_stats/fields_stats.js +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/fields_stats/fields_stats.js @@ -31,7 +31,7 @@ export class FieldsStats extends Component { return (
- {this.state.fields.map(f => ( + {this.state.fields.map((f) => ( @@ -53,7 +53,7 @@ function createFields(results) { if (mappings && fieldStats) { const fieldNames = getFieldNames(results); - return fieldNames.map(name => { + return fieldNames.map((name) => { if (fieldStats[name] !== undefined) { const field = { name }; const f = fieldStats[name]; diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_contents/file_contents.tsx b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_contents/file_contents.tsx index 6564b9a1f4d83..ee73b20051427 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_contents/file_contents.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_contents/file_contents.tsx @@ -60,8 +60,5 @@ export const FileContents: FC = ({ data, format, numberOfLines }) => { }; function limitByNumberOfLines(data: string, numberOfLines: number) { - return data - .split('\n') - .slice(0, numberOfLines) - .join('\n'); + return data.split('\n').slice(0, numberOfLines).join('\n'); } diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_datavisualizer_view/file_datavisualizer_view.js b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_datavisualizer_view/file_datavisualizer_view.js index c73ab4b9e11c7..7cb545cd5a776 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_datavisualizer_view/file_datavisualizer_view.js +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/file_datavisualizer_view/file_datavisualizer_view.js @@ -67,7 +67,7 @@ export class FileDataVisualizerView extends Component { this.setState({ hasPermissionToImport }); } - onFilePickerChange = files => { + onFilePickerChange = (files) => { this.overrides = {}; this.setState( @@ -147,8 +147,8 @@ export class FileDataVisualizerView extends Component { // if no overrides were used, store all the settings returned from the endpoint this.originalSettings = serverSettings; } else { - Object.keys(serverOverrides).forEach(o => { - const camelCaseO = o.replace(/_\w/g, m => m[1].toUpperCase()); + Object.keys(serverOverrides).forEach((o) => { + const camelCaseO = o.replace(/_\w/g, (m) => m[1].toUpperCase()); this.overrides[camelCaseO] = serverOverrides[o]; }); @@ -156,7 +156,7 @@ export class FileDataVisualizerView extends Component { // e.g. changing the name of the time field which is also the time field // will cause the timestamp_field setting to change. // if any have changed, update the originalSettings value - Object.keys(serverSettings).forEach(o => { + Object.keys(serverSettings).forEach((o) => { const value = serverSettings[o]; if ( this.overrides[o] === undefined && @@ -225,7 +225,7 @@ export class FileDataVisualizerView extends Component { this.setState({ bottomBarVisible: false }); }; - setOverrides = overrides => { + setOverrides = (overrides) => { console.log('setOverrides', overrides); this.setState( { @@ -239,7 +239,7 @@ export class FileDataVisualizerView extends Component { ); }; - changeMode = mode => { + changeMode = (mode) => { this.setState({ mode }); }; diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/filebeat_config_flyout/filebeat_config_flyout.tsx b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/filebeat_config_flyout/filebeat_config_flyout.tsx index 32b51c8b7d4ee..07f2825687515 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/filebeat_config_flyout/filebeat_config_flyout.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/components/filebeat_config_flyout/filebeat_config_flyout.tsx @@ -56,7 +56,7 @@ export const FilebeatConfigFlyout: FC = ({ useEffect(() => { if (security !== undefined) { - security.authc.getCurrentUser().then(user => { + security.authc.getCurrentUser().then((user) => { setUsername(user.username === undefined ? null : user.username); }); } @@ -86,7 +86,7 @@ export const FilebeatConfigFlyout: FC = ({ - {copy => ( + {(copy) => ( { + onConfigModeChange = (configMode) => { this.setState({ configMode, }); }; - onIndexChange = e => { + onIndexChange = (e) => { const name = e.target.value; const { indexNames, indexPattern, indexPatternNames } = this.state; @@ -341,7 +341,7 @@ export class ImportView extends Component { }); }; - onIndexPatternChange = e => { + onIndexPatternChange = (e) => { const name = e.target.value; const { indexPatternNames, index } = this.state; this.setState({ @@ -350,37 +350,37 @@ export class ImportView extends Component { }); }; - onCreateIndexPatternChange = e => { + onCreateIndexPatternChange = (e) => { this.setState({ createIndexPattern: e.target.checked, }); }; - onIndexSettingsStringChange = text => { + onIndexSettingsStringChange = (text) => { this.setState({ indexSettingsString: text, }); }; - onMappingsStringChange = text => { + onMappingsStringChange = (text) => { this.setState({ mappingsString: text, }); }; - onPipelineStringChange = text => { + onPipelineStringChange = (text) => { this.setState({ pipelineString: text, }); }; - setImportProgress = progress => { + setImportProgress = (progress) => { this.setState({ uploadProgress: progress, }); }; - setReadProgress = progress => { + setReadProgress = (progress) => { this.setState({ readProgress: progress, }); @@ -398,7 +398,7 @@ export class ImportView extends Component { async loadIndexNames() { const indices = await ml.getIndices(); - const indexNames = indices.map(i => i.name); + const indexNames = indices.map((i) => i.name); this.setState({ indexNames }); } @@ -656,7 +656,7 @@ function getDefaultState(state, results) { } function isIndexNameValid(name, indexNames) { - if (indexNames.find(i => i === name)) { + if (indexNames.find((i) => i === name)) { return ( i === name)) { + if (indexPatternNames.find((i) => i === name)) { return ( `_${$1.toLowerCase()}`); + const snakeCaseO = o.replace(/([A-Z])/g, ($1) => `_${$1.toLowerCase()}`); formattedOverrides[snakeCaseO] = value; } } diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/content_types/number_content.tsx b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/content_types/number_content.tsx index e2c156fc66ded..e2fb8ae5547cc 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/content_types/number_content.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/content_types/number_content.tsx @@ -145,7 +145,7 @@ export const NumberContent: FC = ({ config }) => { setDetailsMode(optionId as DETAILS_MODE)} + onChange={(optionId) => setDetailsMode(optionId as DETAILS_MODE)} aria-label={i18n.translate( 'xpack.ml.fieldDataCard.cardNumber.selectMetricDetailsDisplayAriaLabel', { diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/metric_distribution_chart/metric_distribution_chart.tsx b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/metric_distribution_chart/metric_distribution_chart.tsx index cf0e3ec1a9c9b..4189308a3bc99 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/metric_distribution_chart/metric_distribution_chart.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_data_card/metric_distribution_chart/metric_distribution_chart.tsx @@ -59,7 +59,7 @@ export const MetricDistributionChart: FC = ({ width, height, chartData, f const headerFormatter: TooltipValueFormatter = (tooltipData: ChartTooltipValue) => { const xValue = tooltipData.value; const chartPoint: MetricDistributionChartData | undefined = chartData.find( - data => data.x === xValue + (data) => data.x === xValue ); return ( @@ -97,9 +97,9 @@ export const MetricDistributionChart: FC = ({ width, height, chartData, f kibanaFieldFormat(d, fieldFormat)} + tickFormat={(d) => kibanaFieldFormat(d, fieldFormat)} /> - d.toFixed(3)} hide={true} /> + d.toFixed(3)} hide={true} /> data.y); + let barHeights = processedData.map((data) => data.y); barHeights = barHeights.sort((a, b) => a - b); let maxBarHeight = 0; @@ -131,12 +131,12 @@ export function buildChartDataFromStats( 2; } - processedData.forEach(data => { + processedData.forEach((data) => { data.y = Math.min(data.y, maxBarHeight); }); // Convert the data to the format used by the chart. - chartData = processedData.map(data => { + chartData = processedData.map((data) => { const { x0, y, dataMin, dataMax, percent } = data; return { x: x0, y, dataMin, dataMax, percent }; }); diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_types_select/field_types_select.tsx b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_types_select/field_types_select.tsx index 6fd08076e1f46..24081f835a017 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_types_select/field_types_select.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/field_types_select/field_types_select.tsx @@ -31,7 +31,7 @@ export const FieldTypesSelect: FC = ({ }), }, ]; - fieldTypes.forEach(fieldType => { + fieldTypes.forEach((fieldType) => { options.push({ value: fieldType, text: i18n.translate('xpack.ml.datavisualizer.fieldTypesSelect.typeOptionLabel', { @@ -47,7 +47,7 @@ export const FieldTypesSelect: FC = ({ setSelectedFieldType(e.target.value as ML_JOB_FIELD_TYPES | '*')} + onChange={(e) => setSelectedFieldType(e.target.value as ML_JOB_FIELD_TYPES | '*')} aria-label={i18n.translate('xpack.ml.datavisualizer.fieldTypesSelect.selectAriaLabel', { defaultMessage: 'Select field types to display', })} diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/search_panel/search_panel.tsx b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/search_panel/search_panel.tsx index 16004475eb44f..b93ae9e67ef72 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/search_panel/search_panel.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/components/search_panel/search_panel.tsx @@ -43,7 +43,7 @@ interface Props { totalCount: number; } -const searchSizeOptions = [1000, 5000, 10000, 100000, -1].map(v => { +const searchSizeOptions = [1000, 5000, 10000, 100000, -1].map((v) => { return { value: String(v), inputDisplay: @@ -150,7 +150,7 @@ export const SearchPanel: FC = ({ setSamplerShardSize(+value)} + onChange={(value) => setSamplerShardSize(+value)} aria-label={i18n.translate( 'xpack.ml.datavisualizer.searchPanel.sampleSizeAriaLabel', { diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts b/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts index 9ba99ce891538..7d1f456d2334f 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts @@ -38,7 +38,7 @@ export class DataLoader { ): Promise { const aggregatableFields: string[] = []; const nonAggregatableFields: string[] = []; - this._indexPattern.fields.forEach(field => { + this._indexPattern.fields.forEach((field) => { const fieldName = field.displayName !== undefined ? field.displayName : field.name; if (this.isDisplayField(fieldName) === true) { if (field.aggregatable === true) { diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/page.tsx b/x-pack/plugins/ml/public/application/datavisualizer/index_based/page.tsx index 06d89ab782167..d68c0342ac857 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/page.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/page.tsx @@ -131,7 +131,7 @@ export const Page: FC = () => { // Obtain the list of non metric field types which appear in the index pattern. let indexedFieldTypes: ML_JOB_FIELD_TYPES[] = []; const indexPatternFields: IFieldType[] = currentIndexPattern.fields; - indexPatternFields.forEach(field => { + indexPatternFields.forEach((field) => { if (field.scripted !== true) { const dataVisualizerType: ML_JOB_FIELD_TYPES | undefined = kbnTypeToMLJobType(field); if ( @@ -300,7 +300,7 @@ export const Page: FC = () => { } const configsToLoad = metricConfigs.filter( - config => config.existsInDocs === true && config.loading === true + (config) => config.existsInDocs === true && config.loading === true ); if (configsToLoad.length === 0) { return; @@ -308,7 +308,7 @@ export const Page: FC = () => { // Pass the field name, type and cardinality in the request. // Top values will be obtained on a sample if cardinality > 100000. - const existMetricFields: FieldRequestConfig[] = configsToLoad.map(config => { + const existMetricFields: FieldRequestConfig[] = configsToLoad.map((config) => { const props = { fieldName: config.fieldName, type: config.type, cardinality: 0 }; if (config.stats !== undefined && config.stats.cardinality !== undefined) { props.cardinality = config.stats.cardinality; @@ -347,7 +347,7 @@ export const Page: FC = () => { // Add the metric stats to the existing stats in the corresponding config. const configs: FieldVisConfig[] = []; - metricConfigs.forEach(config => { + metricConfigs.forEach((config) => { const configWithStats = { ...config }; if (config.fieldName !== undefined) { configWithStats.stats = { @@ -383,7 +383,7 @@ export const Page: FC = () => { } const configsToLoad = nonMetricConfigs.filter( - config => config.existsInDocs === true && config.loading === true + (config) => config.existsInDocs === true && config.loading === true ); if (configsToLoad.length === 0) { return; @@ -391,7 +391,7 @@ export const Page: FC = () => { // Pass the field name, type and cardinality in the request. // Top values will be obtained on a sample if cardinality > 100000. - const existNonMetricFields: FieldRequestConfig[] = configsToLoad.map(config => { + const existNonMetricFields: FieldRequestConfig[] = configsToLoad.map((config) => { const props = { fieldName: config.fieldName, type: config.type, cardinality: 0 }; if (config.stats !== undefined && config.stats.cardinality !== undefined) { props.cardinality = config.stats.cardinality; @@ -418,7 +418,7 @@ export const Page: FC = () => { // Add the field stats to the existing stats in the corresponding config. const configs: FieldVisConfig[] = []; - nonMetricConfigs.forEach(config => { + nonMetricConfigs.forEach((config) => { const configWithStats = { ...config }; if (config.fieldName !== undefined) { configWithStats.stats = { @@ -442,7 +442,7 @@ export const Page: FC = () => { const configs: FieldVisConfig[] = []; const aggregatableExistsFields: any[] = overallStats.aggregatableExistsFields || []; - let allMetricFields = indexPatternFields.filter(f => { + let allMetricFields = indexPatternFields.filter((f) => { return ( f.type === KBN_FIELD_TYPES.NUMBER && f.displayName !== undefined && @@ -451,14 +451,14 @@ export const Page: FC = () => { }); if (metricFieldQuery !== undefined) { const metricFieldRegexp = new RegExp(`(${metricFieldQuery})`, 'gi'); - allMetricFields = allMetricFields.filter(f => { + allMetricFields = allMetricFields.filter((f) => { const addField = f.displayName !== undefined && !!f.displayName.match(metricFieldRegexp); return addField; }); } - const metricExistsFields = allMetricFields.filter(f => { - return aggregatableExistsFields.find(existsF => { + const metricExistsFields = allMetricFields.filter((f) => { + return aggregatableExistsFields.find((existsF) => { return existsF.fieldName === f.displayName; }); }); @@ -493,8 +493,8 @@ export const Page: FC = () => { const metricFieldsToShow = showAllMetrics === true ? allMetricFields : metricExistsFields; - metricFieldsToShow.forEach(field => { - const fieldData = aggregatableFields.find(f => { + metricFieldsToShow.forEach((field) => { + const fieldData = aggregatableFields.find((f) => { return f.fieldName === field.displayName; }); @@ -517,7 +517,7 @@ export const Page: FC = () => { function createNonMetricCards() { let allNonMetricFields = []; if (nonMetricShowFieldType === '*') { - allNonMetricFields = indexPatternFields.filter(f => { + allNonMetricFields = indexPatternFields.filter((f) => { return ( f.type !== KBN_FIELD_TYPES.NUMBER && f.displayName !== undefined && @@ -531,7 +531,7 @@ export const Page: FC = () => { ) { const aggregatableCheck = nonMetricShowFieldType === ML_JOB_FIELD_TYPES.KEYWORD ? true : false; - allNonMetricFields = indexPatternFields.filter(f => { + allNonMetricFields = indexPatternFields.filter((f) => { return ( f.displayName !== undefined && dataLoader.isDisplayField(f.displayName) === true && @@ -540,7 +540,7 @@ export const Page: FC = () => { ); }); } else { - allNonMetricFields = indexPatternFields.filter(f => { + allNonMetricFields = indexPatternFields.filter((f) => { return ( f.type === nonMetricShowFieldType && f.displayName !== undefined && @@ -554,7 +554,7 @@ export const Page: FC = () => { if (nonMetricFieldQuery !== undefined) { const nonMetricFieldRegexp = new RegExp(`(${nonMetricFieldQuery})`, 'gi'); allNonMetricFields = allNonMetricFields.filter( - f => f.displayName !== undefined && f.displayName.match(nonMetricFieldRegexp) + (f) => f.displayName !== undefined && f.displayName.match(nonMetricFieldRegexp) ); } @@ -565,9 +565,9 @@ export const Page: FC = () => { const aggregatableExistsFields: any[] = overallStats.aggregatableExistsFields || []; const nonAggregatableExistsFields: any[] = overallStats.nonAggregatableExistsFields || []; - allNonMetricFields.forEach(f => { + allNonMetricFields.forEach((f) => { const checkAggregatableField = aggregatableExistsFields.find( - existsField => existsField.fieldName === f.displayName + (existsField) => existsField.fieldName === f.displayName ); if (checkAggregatableField !== undefined) { @@ -575,7 +575,7 @@ export const Page: FC = () => { nonMetricFieldData.push(checkAggregatableField); } else { const checkNonAggregatableField = nonAggregatableExistsFields.find( - existsField => existsField.fieldName === f.displayName + (existsField) => existsField.fieldName === f.displayName ); if (checkNonAggregatableField !== undefined) { @@ -606,8 +606,8 @@ export const Page: FC = () => { const configs: FieldVisConfig[] = []; - nonMetricFieldsToShow.forEach(field => { - const fieldData = nonMetricFieldData.find(f => f.fieldName === field.displayName); + nonMetricFieldsToShow.forEach((field) => { + const fieldData = nonMetricFieldData.find((f) => f.fieldName === field.displayName); const nonMetricConfig = { ...fieldData, diff --git a/x-pack/plugins/ml/public/application/explorer/actions/job_selection.ts b/x-pack/plugins/ml/public/application/explorer/actions/job_selection.ts index 994d67bfdb02c..24926960abd17 100644 --- a/x-pack/plugins/ml/public/application/explorer/actions/job_selection.ts +++ b/x-pack/plugins/ml/public/application/explorer/actions/job_selection.ts @@ -15,18 +15,18 @@ import { createJobs } from '../explorer_utils'; export function jobSelectionActionCreator(selectedJobIds: string[]) { return from(mlFieldFormatService.populateFormats(selectedJobIds)).pipe( - map(resp => { + map((resp) => { if (resp.err) { console.log('Error populating field formats:', resp.err); // eslint-disable-line no-console return null; } - const jobs = createJobs(mlJobService.jobs).map(job => { - job.selected = selectedJobIds.some(id => job.id === id); + const jobs = createJobs(mlJobService.jobs).map((job) => { + job.selected = selectedJobIds.some((id) => job.id === id); return job; }); - const selectedJobs = jobs.filter(job => job.selected); + const selectedJobs = jobs.filter((job) => job.selected); return { type: EXPLORER_ACTION.JOB_SELECTION_CHANGE, diff --git a/x-pack/plugins/ml/public/application/explorer/actions/load_explorer_data.ts b/x-pack/plugins/ml/public/application/explorer/actions/load_explorer_data.ts index 37794a250db34..590a69283a819 100644 --- a/x-pack/plugins/ml/public/application/explorer/actions/load_explorer_data.ts +++ b/x-pack/plugins/ml/public/application/explorer/actions/load_explorer_data.ts @@ -40,7 +40,7 @@ import { ExplorerState } from '../reducers'; // the original function. const memoizeIsEqual = (newArgs: any[], lastArgs: any[]) => isEqual(newArgs, lastArgs); const wrapWithLastRefreshArg = any>(func: T) => { - return function(lastRefresh: number, ...args: Parameters): ReturnType { + return function (lastRefresh: number, ...args: Parameters): ReturnType { return func.apply(null, args); }; }; @@ -265,5 +265,5 @@ const explorerData$ = loadExplorerData$.pipe( export const useExplorerData = (): [Partial | undefined, (d: any) => void] => { const explorerData = useObservable(explorerData$); - return [explorerData, c => loadExplorerData$.next(c)]; + return [explorerData, (c) => loadExplorerData$.next(c)]; }; diff --git a/x-pack/plugins/ml/public/application/explorer/components/explorer_query_bar/explorer_query_bar.tsx b/x-pack/plugins/ml/public/application/explorer/components/explorer_query_bar/explorer_query_bar.tsx index 0263ad08b03cf..1c3c42b58b10e 100644 --- a/x-pack/plugins/ml/public/application/explorer/components/explorer_query_bar/explorer_query_bar.tsx +++ b/x-pack/plugins/ml/public/application/explorer/components/explorer_query_bar/explorer_query_bar.tsx @@ -35,7 +35,7 @@ export function getKqlQueryValues({ // if ast.type == 'function' then layout of ast.arguments: // [{ arguments: [ { type: 'literal', value: 'AAL' } ] },{ arguments: [ { type: 'literal', value: 'AAL' } ] }] if (ast && Array.isArray(ast.arguments)) { - ast.arguments.forEach(arg => { + ast.arguments.forEach((arg) => { if (arg.arguments !== undefined) { arg.arguments.forEach((nestedArg: { type: string; value: string }) => { if (typeof nestedArg.value === 'string') { diff --git a/x-pack/plugins/ml/public/application/explorer/explorer.js b/x-pack/plugins/ml/public/application/explorer/explorer.js index 9c9c82a212472..5cebb6354c0db 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer.js @@ -84,7 +84,7 @@ import { MlTooltipComponent } from '../components/chart_tooltip'; import { hasMatchingPoints } from './has_matching_points'; function mapSwimlaneOptionsToEuiOptions(options) { - return options.map(option => ({ + return options.map((option) => ({ value: option, text: option, })); @@ -190,12 +190,12 @@ export class Explorer extends React.Component { this.anomaliesTablePreviousArgs = null; } - viewByChangeHandler = e => explorerService.setViewBySwimlaneFieldName(e.target.value); + viewByChangeHandler = (e) => explorerService.setViewBySwimlaneFieldName(e.target.value); isSwimlaneSelectActive = false; onSwimlaneEnterHandler = () => this.setSwimlaneSelectActive(true); onSwimlaneLeaveHandler = () => this.setSwimlaneSelectActive(false); - setSwimlaneSelectActive = active => { + setSwimlaneSelectActive = (active) => { if (this.isSwimlaneSelectActive && !active && this.disableDragSelectOnMouseLeave) { this.dragSelect.stop(); this.isSwimlaneSelectActive = active; @@ -210,7 +210,7 @@ export class Explorer extends React.Component { }; // Listener for click events in the swimlane to load corresponding anomaly data. - swimlaneCellClick = selectedCells => { + swimlaneCellClick = (selectedCells) => { // If selectedCells is an empty object we clear any existing selection, // otherwise we save the new selection in AppState and update the Explorer. if (Object.keys(selectedCells).length === 0) { @@ -276,7 +276,7 @@ export class Explorer extends React.Component { } }; - updateLanguage = language => this.setState({ language }); + updateLanguage = (language) => this.setState({ language }); render() { const { showCharts, severity } = this.props; @@ -416,7 +416,7 @@ export class Explorer extends React.Component { > {showOverallSwimlane && ( - {tooltipService => ( + {(tooltipService) => ( - {tooltipService => ( + {(tooltipService) => (  –  ); - const entityFieldBadges = entityFields.map(entity => ( + const entityFieldBadges = entityFields.map((entity) => ( )); diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.js index edb4b988277f9..b5e9daad7d1c1 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_config_builder.js @@ -60,7 +60,7 @@ export function buildConfig(record) { jobId: record.job_id, aggregationInterval: config.interval, chartFunction: functionLabel, - entityFields: config.entityFields.map(f => ({ + entityFields: config.entityFields.map((f) => ({ fieldName: f.fieldName, fieldValue: f.fieldValue, })), diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js index 2b577c978eb13..6c7c3e9040216 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js @@ -92,7 +92,7 @@ export class ExplorerChartDistribution extends React.Component { const CHART_Y_ATTRIBUTE = chartType === CHART_TYPE.EVENT_DISTRIBUTION ? 'entity' : 'value'; - let highlight = config.chartData.find(d => d.anomalyScore !== undefined); + let highlight = config.chartData.find((d) => d.anomalyScore !== undefined); highlight = highlight && highlight.entity; const filteredChartData = init(config); @@ -118,7 +118,7 @@ export class ExplorerChartDistribution extends React.Component { const categoryLimit = 30; const scaleCategories = d3 .nest() - .key(d => d.entity) + .key((d) => d.entity) .entries(chartData) .sort((a, b) => { return b.values.length - a.values.length; @@ -130,22 +130,22 @@ export class ExplorerChartDistribution extends React.Component { } return true; }) - .map(d => d.key); + .map((d) => d.key); - chartData = chartData.filter(d => { + chartData = chartData.filter((d) => { return scaleCategories.includes(d.entity); }); if (chartType === CHART_TYPE.POPULATION_DISTRIBUTION) { const focusData = chartData - .filter(d => { + .filter((d) => { return d.entity === highlight; }) - .map(d => d.value); + .map((d) => d.value); const focusExtent = d3.extent(focusData); // now again filter chartData to include only the data points within the domain - chartData = chartData.filter(d => { + chartData = chartData.filter((d) => { return d.value <= focusExtent[1]; }); @@ -184,7 +184,7 @@ export class ExplorerChartDistribution extends React.Component { .data(tempLabelTextData) .enter() .append('text') - .text(d => { + .text((d) => { if (fieldFormat !== undefined) { return fieldFormat.convert(d, 'text'); } else { @@ -195,7 +195,7 @@ export class ExplorerChartDistribution extends React.Component { } }) // Don't use an arrow function since we need access to `this`. - .each(function() { + .each(function () { maxYAxisLabelWidth = Math.max( this.getBBox().width + yAxis.tickPadding(), maxYAxisLabelWidth @@ -225,9 +225,9 @@ export class ExplorerChartDistribution extends React.Component { lineChartValuesLine = d3.svg .line() - .x(d => lineChartXScale(d.date)) - .y(d => lineChartYScale(d[CHART_Y_ATTRIBUTE])) - .defined(d => d.value !== null); + .x((d) => lineChartXScale(d.date)) + .y((d) => lineChartYScale(d[CHART_Y_ATTRIBUTE])) + .defined((d) => d.value !== null); lineChartGroup = svg .append('g') @@ -280,7 +280,7 @@ export class ExplorerChartDistribution extends React.Component { .innerTickSize(-chartHeight) .outerTickSize(0) .tickPadding(10) - .tickFormat(d => moment(d).format(xAxisTickFormat)); + .tickFormat((d) => moment(d).format(xAxisTickFormat)); // With tooManyBuckets the chart would end up with no x-axis labels // because the ticks are based on the span of the emphasis section, @@ -300,7 +300,7 @@ export class ExplorerChartDistribution extends React.Component { .tickPadding(10); if (fieldFormat !== undefined) { - yAxis.tickFormat(d => fieldFormat.convert(d, 'text')); + yAxis.tickFormat((d) => fieldFormat.convert(d, 'text')); } const axes = lineChartGroup.append('g'); @@ -311,17 +311,14 @@ export class ExplorerChartDistribution extends React.Component { .attr('transform', 'translate(0,' + chartHeight + ')') .call(xAxis); - axes - .append('g') - .attr('class', 'y axis') - .call(yAxis); + axes.append('g').attr('class', 'y axis').call(yAxis); // emphasize the y axis label this rare chart is actually about if (chartType === CHART_TYPE.EVENT_DISTRIBUTION) { axes .select('.y') .selectAll('text') - .each(function(d) { + .each(function (d) { d3.select(this).classed('ml-explorer-chart-axis-emphasis', d === highlight); }); } @@ -345,10 +342,10 @@ export class ExplorerChartDistribution extends React.Component { .enter() .append('circle') .classed('values-dots-circle', true) - .classed('values-dots-circle-blur', d => { + .classed('values-dots-circle-blur', (d) => { return d.entity !== highlight; }) - .attr('r', d => (d.entity === highlight ? radius * 1.5 : radius)); + .attr('r', (d) => (d.entity === highlight ? radius * 1.5 : radius)); dots.attr('cx', rareChartValuesLine.x()).attr('cy', rareChartValuesLine.y()); @@ -382,7 +379,7 @@ export class ExplorerChartDistribution extends React.Component { .append('g') .attr('class', 'chart-markers') .selectAll('.metric-value') - .data(data.filter(d => d.value !== null)); + .data(data.filter((d) => d.value !== null)); // Remove dots that are no longer needed i.e. if number of chart points has decreased. dots.exit().remove(); @@ -392,16 +389,16 @@ export class ExplorerChartDistribution extends React.Component { .append('circle') .attr('r', LINE_CHART_ANOMALY_RADIUS) // Don't use an arrow function since we need access to `this`. - .on('mouseover', function(d) { + .on('mouseover', function (d) { showLineChartTooltip(d, this); }) .on('mouseout', () => tooltipService.hide()); // Update all dots to new positions. dots - .attr('cx', d => lineChartXScale(d.date)) - .attr('cy', d => lineChartYScale(d[CHART_Y_ATTRIBUTE])) - .attr('class', d => { + .attr('cx', (d) => lineChartXScale(d.date)) + .attr('cy', (d) => lineChartYScale(d[CHART_Y_ATTRIBUTE])) + .attr('class', (d) => { let markerClass = 'metric-value'; if (_.has(d, 'anomalyScore') && Number(d.anomalyScore) >= severity) { markerClass += ' anomaly-marker '; @@ -414,7 +411,7 @@ export class ExplorerChartDistribution extends React.Component { const scheduledEventMarkers = lineChartGroup .select('.chart-markers') .selectAll('.scheduled-event-marker') - .data(data.filter(d => d.scheduledEvents !== undefined)); + .data(data.filter((d) => d.scheduledEvents !== undefined)); // Remove markers that are no longer needed i.e. if number of chart points has decreased. scheduledEventMarkers.exit().remove(); @@ -430,8 +427,11 @@ export class ExplorerChartDistribution extends React.Component { // Update all markers to new positions. scheduledEventMarkers - .attr('x', d => lineChartXScale(d.date) - LINE_CHART_ANOMALY_RADIUS) - .attr('y', d => lineChartYScale(d[CHART_Y_ATTRIBUTE]) - SCHEDULED_EVENT_MARKER_HEIGHT / 2); + .attr('x', (d) => lineChartXScale(d.date) - LINE_CHART_ANOMALY_RADIUS) + .attr( + 'y', + (d) => lineChartYScale(d[CHART_Y_ATTRIBUTE]) - SCHEDULED_EVENT_MARKER_HEIGHT / 2 + ); } function showLineChartTooltip(marker, circle) { diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.test.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.test.js index 06fd82204c1e1..53aca826f2dda 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.test.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.test.js @@ -143,15 +143,9 @@ describe('ExplorerChart', () => { expect(+selectedInterval.getAttribute('y')).toBe(2); expect(+selectedInterval.getAttribute('height')).toBe(166); - const xAxisTicks = wrapper - .getDOMNode() - .querySelector('.x') - .querySelectorAll('.tick'); + const xAxisTicks = wrapper.getDOMNode().querySelector('.x').querySelectorAll('.tick'); expect([...xAxisTicks]).toHaveLength(0); - const yAxisTicks = wrapper - .getDOMNode() - .querySelector('.y') - .querySelectorAll('.tick'); + const yAxisTicks = wrapper.getDOMNode().querySelector('.y').querySelectorAll('.tick'); expect([...yAxisTicks]).toHaveLength(5); const emphasizedAxisLabel = wrapper .getDOMNode() @@ -164,10 +158,7 @@ describe('ExplorerChart', () => { expect(paths[1].getAttribute('class')).toBe('domain'); expect(paths[2]).toBe(undefined); - const dots = wrapper - .getDOMNode() - .querySelector('.values-dots') - .querySelectorAll('circle'); + const dots = wrapper.getDOMNode().querySelector('.values-dots').querySelectorAll('circle'); expect([...dots]).toHaveLength(5); expect(dots[0].getAttribute('r')).toBe('1.5'); @@ -176,7 +167,7 @@ describe('ExplorerChart', () => { .querySelector('.chart-markers') .querySelectorAll('circle'); expect([...chartMarkers]).toHaveLength(5); - expect([...chartMarkers].map(d => +d.getAttribute('r'))).toEqual([7, 7, 7, 7, 7]); + expect([...chartMarkers].map((d) => +d.getAttribute('r'))).toEqual([7, 7, 7, 7, 7]); }); it('Anomaly Explorer Chart with single data point', () => { @@ -192,10 +183,7 @@ describe('ExplorerChart', () => { ]; const wrapper = init(chartData); - const yAxisTicks = wrapper - .getDOMNode() - .querySelector('.y') - .querySelectorAll('.tick'); + const yAxisTicks = wrapper.getDOMNode().querySelector('.y').querySelectorAll('.tick'); expect([...yAxisTicks]).toHaveLength(1); }); }); diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_info_tooltip.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_info_tooltip.js index 0ee1eac19f64d..01f4626e222aa 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_info_tooltip.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_info_tooltip.js @@ -77,7 +77,7 @@ export const ExplorerChartInfoTooltip = ({ }, ]; - entityFields.forEach(entityField => { + entityFields.forEach((entityField) => { toolTipData.push({ title: entityField.fieldName, description: entityField.fieldValue, diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js index 531a24493c961..63775c5ca312e 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js @@ -128,7 +128,7 @@ export class ExplorerChartSingleMetric extends React.Component { .data(lineChartYScale.ticks()) .enter() .append('text') - .text(d => { + .text((d) => { if (fieldFormat !== undefined) { return fieldFormat.convert(d, 'text'); } else { @@ -136,7 +136,7 @@ export class ExplorerChartSingleMetric extends React.Component { } }) // Don't use an arrow function since we need access to `this`. - .each(function() { + .each(function () { maxYAxisLabelWidth = Math.max( this.getBBox().width + yAxis.tickPadding(), maxYAxisLabelWidth @@ -158,9 +158,9 @@ export class ExplorerChartSingleMetric extends React.Component { lineChartValuesLine = d3.svg .line() - .x(d => lineChartXScale(d.date)) - .y(d => lineChartYScale(d.value)) - .defined(d => d.value !== null); + .x((d) => lineChartXScale(d.date)) + .y((d) => lineChartYScale(d.value)) + .defined((d) => d.value !== null); lineChartGroup = svg .append('g') @@ -212,7 +212,7 @@ export class ExplorerChartSingleMetric extends React.Component { .innerTickSize(-chartHeight) .outerTickSize(0) .tickPadding(10) - .tickFormat(d => moment(d).format(xAxisTickFormat)); + .tickFormat((d) => moment(d).format(xAxisTickFormat)); // With tooManyBuckets the chart would end up with no x-axis labels // because the ticks are based on the span of the emphasis section, @@ -232,7 +232,7 @@ export class ExplorerChartSingleMetric extends React.Component { .tickPadding(10); if (fieldFormat !== undefined) { - yAxis.tickFormat(d => fieldFormat.convert(d, 'text')); + yAxis.tickFormat((d) => fieldFormat.convert(d, 'text')); } const axes = lineChartGroup.append('g'); @@ -243,10 +243,7 @@ export class ExplorerChartSingleMetric extends React.Component { .attr('transform', 'translate(0,' + chartHeight + ')') .call(xAxis); - axes - .append('g') - .attr('class', 'y axis') - .call(yAxis); + axes.append('g').attr('class', 'y axis').call(yAxis); if (tooManyBuckets === false) { removeLabelOverlap(gAxis, tickValuesStart, interval, vizWidth); @@ -290,7 +287,7 @@ export class ExplorerChartSingleMetric extends React.Component { .selectAll('.metric-value') .data( data.filter( - d => + (d) => (d.value !== null || typeof d.anomalyScore === 'number') && !showMultiBucketAnomalyMarker(d) ) @@ -304,18 +301,19 @@ export class ExplorerChartSingleMetric extends React.Component { .append('circle') .attr('r', LINE_CHART_ANOMALY_RADIUS) // Don't use an arrow function since we need access to `this`. - .on('mouseover', function(d) { + .on('mouseover', function (d) { showLineChartTooltip(d, this); }) .on('mouseout', () => tooltipService.hide()); - const isAnomalyVisible = d => _.has(d, 'anomalyScore') && Number(d.anomalyScore) >= severity; + const isAnomalyVisible = (d) => + _.has(d, 'anomalyScore') && Number(d.anomalyScore) >= severity; // Update all dots to new positions. dots - .attr('cx', d => lineChartXScale(d.date)) - .attr('cy', d => lineChartYScale(d.value)) - .attr('class', d => { + .attr('cx', (d) => lineChartXScale(d.date)) + .attr('cy', (d) => lineChartYScale(d.value)) + .attr('class', (d) => { let markerClass = 'metric-value'; if (isAnomalyVisible(d)) { markerClass += ` anomaly-marker ${getSeverityWithLow(d.anomalyScore).id}`; @@ -327,7 +325,7 @@ export class ExplorerChartSingleMetric extends React.Component { const multiBucketMarkers = lineChartGroup .select('.chart-markers') .selectAll('.multi-bucket') - .data(data.filter(d => isAnomalyVisible(d) && showMultiBucketAnomalyMarker(d) === true)); + .data(data.filter((d) => isAnomalyVisible(d) && showMultiBucketAnomalyMarker(d) === true)); // Remove multi-bucket markers that are no longer needed multiBucketMarkers.exit().remove(); @@ -336,20 +334,17 @@ export class ExplorerChartSingleMetric extends React.Component { multiBucketMarkers .enter() .append('path') + .attr('d', d3.svg.symbol().size(MULTI_BUCKET_SYMBOL_SIZE).type('cross')) .attr( - 'd', - d3.svg - .symbol() - .size(MULTI_BUCKET_SYMBOL_SIZE) - .type('cross') + 'transform', + (d) => `translate(${lineChartXScale(d.date)}, ${lineChartYScale(d.value)})` ) .attr( - 'transform', - d => `translate(${lineChartXScale(d.date)}, ${lineChartYScale(d.value)})` + 'class', + (d) => `anomaly-marker multi-bucket ${getSeverityWithLow(d.anomalyScore).id}` ) - .attr('class', d => `anomaly-marker multi-bucket ${getSeverityWithLow(d.anomalyScore).id}`) // Don't use an arrow function since we need access to `this`. - .on('mouseover', function(d) { + .on('mouseover', function (d) { showLineChartTooltip(d, this); }) .on('mouseout', () => tooltipService.hide()); @@ -358,7 +353,7 @@ export class ExplorerChartSingleMetric extends React.Component { const scheduledEventMarkers = lineChartGroup .select('.chart-markers') .selectAll('.scheduled-event-marker') - .data(data.filter(d => d.scheduledEvents !== undefined)); + .data(data.filter((d) => d.scheduledEvents !== undefined)); // Remove markers that are no longer needed i.e. if number of chart points has decreased. scheduledEventMarkers.exit().remove(); @@ -374,8 +369,8 @@ export class ExplorerChartSingleMetric extends React.Component { // Update all markers to new positions. scheduledEventMarkers - .attr('x', d => lineChartXScale(d.date) - LINE_CHART_ANOMALY_RADIUS) - .attr('y', d => lineChartYScale(d.value) - SCHEDULED_EVENT_SYMBOL_HEIGHT / 2); + .attr('x', (d) => lineChartXScale(d.date) - LINE_CHART_ANOMALY_RADIUS) + .attr('y', (d) => lineChartYScale(d.value) - SCHEDULED_EVENT_SYMBOL_HEIGHT / 2); } function showLineChartTooltip(marker, circle) { diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.test.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.test.js index 54f541ceb7c3d..99f5c3eff6984 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.test.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.test.js @@ -143,15 +143,9 @@ describe('ExplorerChart', () => { expect(+selectedInterval.getAttribute('y')).toBe(2); expect(+selectedInterval.getAttribute('height')).toBe(166); - const xAxisTicks = wrapper - .getDOMNode() - .querySelector('.x') - .querySelectorAll('.tick'); + const xAxisTicks = wrapper.getDOMNode().querySelector('.x').querySelectorAll('.tick'); expect([...xAxisTicks]).toHaveLength(0); - const yAxisTicks = wrapper - .getDOMNode() - .querySelector('.y') - .querySelectorAll('.tick'); + const yAxisTicks = wrapper.getDOMNode().querySelector('.y').querySelectorAll('.tick'); expect([...yAxisTicks]).toHaveLength(10); const paths = wrapper.getDOMNode().querySelectorAll('path'); @@ -162,10 +156,7 @@ describe('ExplorerChart', () => { 'MNaN,159.33024504444444ZMNaN,9.166257955555556LNaN,169.60736875555557' ); - const dots = wrapper - .getDOMNode() - .querySelector('.values-dots') - .querySelectorAll('circle'); + const dots = wrapper.getDOMNode().querySelector('.values-dots').querySelectorAll('circle'); expect([...dots]).toHaveLength(1); expect(dots[0].getAttribute('r')).toBe('1.5'); @@ -174,7 +165,7 @@ describe('ExplorerChart', () => { .querySelector('.chart-markers') .querySelectorAll('circle'); expect([...chartMarkers]).toHaveLength(4); - expect([...chartMarkers].map(d => +d.getAttribute('r'))).toEqual([7, 7, 7, 7]); + expect([...chartMarkers].map((d) => +d.getAttribute('r'))).toEqual([7, 7, 7, 7]); }); it('Anomaly Explorer Chart with single data point', () => { @@ -191,10 +182,7 @@ describe('ExplorerChart', () => { const wrapper = init(chartData); - const yAxisTicks = wrapper - .getDOMNode() - .querySelector('.y') - .querySelectorAll('.tick'); + const yAxisTicks = wrapper.getDOMNode().querySelector('.y').querySelectorAll('.tick'); expect([...yAxisTicks]).toHaveLength(13); }); }); diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container.js index 5b95931d31ab6..9988298c25c51 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container.js @@ -45,7 +45,7 @@ const textViewButton = i18n.translate( // from charts metadata for React's key attribute function getChartId(series) { const { jobId, detectorLabel, entityFields } = series; - const entities = entityFields.map(ef => `${ef.fieldName}/${ef.fieldValue}`).join(','); + const entities = entityFields.map((ef) => `${ef.fieldName}/${ef.fieldValue}`).join(','); const id = `${jobId}_${detectorLabel}_${entities}`; return id; } @@ -58,7 +58,7 @@ function ExplorerChartContainer({ series, severity, tooManyBuckets, wrapLabel }) let DetectorLabel = {detectorLabel}; if (chartType === CHART_TYPE.EVENT_DISTRIBUTION) { - const byField = series.entityFields.find(d => d.fieldType === 'by'); + const byField = series.entityFields.find((d) => d.fieldType === 'by'); if (typeof byField !== 'undefined') { DetectorLabel = ( @@ -121,7 +121,7 @@ function ExplorerChartContainer({ series, severity, tooManyBuckets, wrapLabel }) ) { return ( - {tooltipService => ( + {(tooltipService) => ( - {tooltipService => ( + {(tooltipService) => ( isLabelLengthAboveThreshold(series)); + const wrapLabel = seriesToPlot.some((series) => isLabelLengthAboveThreshold(series)); return ( {seriesToPlot.length > 0 && - seriesToPlot.map(series => ( + seriesToPlot.map((series) => ( { + const filteredRecords = anomalyRecords.filter((record) => { return Number(record.record_score) >= severity; }); const allSeriesRecords = processRecordsForDisplay(filteredRecords); @@ -88,7 +88,7 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, data.tooManyBuckets = tooManyBuckets; // initialize the charts with loading indicators - data.seriesToPlot = seriesConfigs.map(config => ({ + data.seriesToPlot = seriesConfigs.map((config) => ({ ...config, loading: true, chartData: null, @@ -168,15 +168,15 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, return mlResultsService .getModelPlotOutput(jobId, detectorIndex, criteriaFields, range.min, range.max, interval) .toPromise() - .then(resp => { + .then((resp) => { // Return data in format required by the explorer charts. const results = resp.results; - Object.keys(results).forEach(time => { + Object.keys(results).forEach((time) => { obj.results[time] = results[time].actual; }); resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -225,11 +225,11 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, // Define splitField and filterField based on chartType if (chartType === CHART_TYPE.EVENT_DISTRIBUTION) { - splitField = config.entityFields.find(f => f.fieldType === 'by'); - filterField = config.entityFields.find(f => f.fieldType === 'partition'); + splitField = config.entityFields.find((f) => f.fieldType === 'by'); + filterField = config.entityFields.find((f) => f.fieldType === 'partition'); } else if (chartType === CHART_TYPE.POPULATION_DISTRIBUTION) { - splitField = config.entityFields.find(f => f.fieldType === 'over'); - filterField = config.entityFields.find(f => f.fieldType === 'partition'); + splitField = config.entityFields.find((f) => f.fieldType === 'over'); + filterField = config.entityFields.find((f) => f.fieldType === 'partition'); } const datafeedQuery = _.get(config, 'datafeedConfig.query', null); @@ -251,7 +251,7 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, // only after that trigger data processing and page render. // TODO - if query returns no results e.g. source data has been deleted, // display a message saying 'No data between earliest/latest'. - const seriesPromises = seriesConfigs.map(seriesConfig => + const seriesPromises = seriesConfigs.map((seriesConfig) => Promise.all([ getMetricData(seriesConfig, chartRange), getRecordsForCriteria(seriesConfig, chartRange), @@ -280,7 +280,7 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, if (metricData !== undefined) { if (eventDistribution.length > 0 && records.length > 0) { const filterField = records[0].by_field_value || records[0].over_field_value; - chartData = eventDistribution.filter(d => d.entity !== filterField); + chartData = eventDistribution.filter((d) => d.entity !== filterField); _.map(metricData, (value, time) => { // The filtering for rare/event_distribution charts needs to be handled // differently because of how the source data is structured. @@ -310,7 +310,7 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, // Iterate through the anomaly records, adding anomalyScore properties // to the chartData entries for anomalous buckets. const chartDataForPointSearch = getChartDataForPointSearch(chartData, records[0], chartType); - _.each(records, record => { + _.each(records, (record) => { // Look for a chart point with the same time as the record. // If none found, insert a point for anomalies due to a gap in the data. const recordTime = record[ML_TIME_FIELD_NAME]; @@ -365,7 +365,7 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, chartType === CHART_TYPE.EVENT_DISTRIBUTION || chartType === CHART_TYPE.POPULATION_DISTRIBUTION ) { - return chartData.filter(d => { + return chartData.filter((d) => { return d.entity === (record && (record.by_field_value || record.over_field_value)); }); } @@ -374,17 +374,17 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, } function findChartPointForTime(chartData, time) { - return chartData.find(point => point.date === time); + return chartData.find((point) => point.date === time); } Promise.all(seriesPromises) - .then(response => { + .then((response) => { // calculate an overall min/max for all series const processedData = response.map(processChartData); const allDataPoints = _.reduce( processedData, (datapoints, series) => { - _.each(series, d => datapoints.push(d)); + _.each(series, (d) => datapoints.push(d)); return datapoints; }, [] @@ -403,7 +403,7 @@ export const anomalyDataChange = function(anomalyRecords, earliestMs, latestMs, })); explorerService.setCharts({ ...data }); }) - .catch(error => { + .catch((error) => { console.error(error); }); }; @@ -416,7 +416,7 @@ function processRecordsForDisplay(anomalyRecords) { // Aggregate by job, detector, and analysis fields (partition, by, over). const aggregatedData = {}; - _.each(anomalyRecords, record => { + _.each(anomalyRecords, (record) => { // Check if we can plot a chart for this record, depending on whether the source data // is chartable, and if model plot is enabled for the job. const job = mlJobService.getJob(record.job_id); @@ -521,20 +521,20 @@ function processRecordsForDisplay(anomalyRecords) { console.log('explorer charts aggregatedData is:', aggregatedData); let recordsForSeries = []; // Convert to an array of the records with the highest record_score per unique series. - _.each(aggregatedData, detectorsForJob => { - _.each(detectorsForJob, groupsForDetector => { + _.each(aggregatedData, (detectorsForJob) => { + _.each(detectorsForJob, (groupsForDetector) => { if (groupsForDetector.maxScoreRecord !== undefined) { // Detector with no partition / by field. recordsForSeries.push(groupsForDetector.maxScoreRecord); } else { - _.each(groupsForDetector, valuesForGroup => { - _.each(valuesForGroup, dataForGroupValue => { + _.each(groupsForDetector, (valuesForGroup) => { + _.each(valuesForGroup, (dataForGroupValue) => { if (dataForGroupValue.maxScoreRecord !== undefined) { recordsForSeries.push(dataForGroupValue.maxScoreRecord); } else { // Second level of aggregation for partition and by/over. - _.each(dataForGroupValue, splitsForGroup => { - _.each(splitsForGroup, dataForSplitValue => { + _.each(dataForGroupValue, (splitsForGroup) => { + _.each(splitsForGroup, (dataForSplitValue) => { recordsForSeries.push(dataForSplitValue.maxScoreRecord); }); }); @@ -585,7 +585,7 @@ function calculateChartRange( let minMs = recordsToPlot[0][timeFieldName]; let maxMs = recordsToPlot[0][timeFieldName]; - _.each(recordsToPlot, record => { + _.each(recordsToPlot, (record) => { const diffMs = maxMs - minMs; if (diffMs < maxTimeSpan) { const recordTime = record[timeFieldName]; diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.test.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.test.js index 35261257ce625..6a9fd19180a4e 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.test.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_charts_container_service.test.js @@ -108,7 +108,7 @@ describe('explorerChartsContainerService', () => { explorerService.setCharts.mockClear(); }); - test('call anomalyChangeListener with empty series config', done => { + test('call anomalyChangeListener with empty series config', (done) => { anomalyDataChange([], 1486656000000, 1486670399999); setImmediate(() => { @@ -121,7 +121,7 @@ describe('explorerChartsContainerService', () => { }); }); - test('call anomalyChangeListener with actual series config', done => { + test('call anomalyChangeListener with actual series config', (done) => { anomalyDataChange(mockAnomalyChartRecords, 1486656000000, 1486670399999); setImmediate(() => { @@ -132,8 +132,8 @@ describe('explorerChartsContainerService', () => { }); }); - test('filtering should skip values of null', done => { - const mockAnomalyChartRecordsClone = _.cloneDeep(mockAnomalyChartRecords).map(d => { + test('filtering should skip values of null', (done) => { + const mockAnomalyChartRecordsClone = _.cloneDeep(mockAnomalyChartRecords).map((d) => { d.job_id = 'mock-job-id-distribution'; return d; }); @@ -150,13 +150,13 @@ describe('explorerChartsContainerService', () => { // it should remove the datapoint with `null` and keep the one with `0`. const chartData = explorerService.setCharts.mock.calls[1][0].seriesToPlot[0].chartData; expect(chartData).toHaveLength(114); - expect(chartData.filter(d => d.value === 0)).toHaveLength(1); - expect(chartData.filter(d => d.value === null)).toHaveLength(0); + expect(chartData.filter((d) => d.value === 0)).toHaveLength(1); + expect(chartData.filter((d) => d.value === null)).toHaveLength(0); done(); }); }); - test('field value with trailing dot should not throw an error', done => { + test('field value with trailing dot should not throw an error', (done) => { const mockAnomalyChartRecordsClone = _.cloneDeep(mockAnomalyChartRecords); mockAnomalyChartRecordsClone[1].partition_field_value = 'AAL.'; diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx b/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx index e8ea54d28f5a0..18b5de1d51f9c 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx +++ b/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx @@ -118,7 +118,7 @@ export class ExplorerSwimlane extends React.Component { // immediately clear the selection, otherwise trigger // a reload with the updated selected cells. if (selectedData.bucketScore === 0) { - elements.map(e => d3.select(e).classed('ds-selected', false)); + elements.map((e) => d3.select(e).classed('ds-selected', false)); this.selectCell([], selectedData); previousSelectedData = null; } else { @@ -199,7 +199,7 @@ export class ExplorerSwimlane extends React.Component { highlightOverall(times: number[]) { const overallSwimlane = d3.select('.ml-swimlane-overall'); - times.forEach(time => { + times.forEach((time) => { const overallCell = overallSwimlane .selectAll(`div[data-time="${time}"]`) .selectAll('.sl-cell-inner,.sl-cell-inner-dragselect'); @@ -229,7 +229,7 @@ export class ExplorerSwimlane extends React.Component { .classed('sl-cell-inner-selected', true); const rootParent = d3.select(this.rootNode.current!.parentNode!); - rootParent.selectAll('.lane-label').classed('lane-label-masked', function(this: HTMLElement) { + rootParent.selectAll('.lane-label').classed('lane-label-masked', function (this: HTMLElement) { return laneLabels.indexOf(d3.select(this).text()) === -1; }); @@ -379,7 +379,7 @@ export class ExplorerSwimlane extends React.Component { function cellMouseOverFactory(time: number, i: number) { // Don't use an arrow function here because we need access to `this`, // which is where d3 supplies a reference to the corresponding DOM element. - return function(this: HTMLElement, lane: string) { + return function (this: HTMLElement, lane: string) { const bucketScore = getBucketScore(lane, time); if (bucketScore !== 0) { lane = lane === '' ? EMPTY_FIELD_VALUE_LABEL : lane; @@ -393,10 +393,7 @@ export class ExplorerSwimlane extends React.Component { }; const d3Lanes = swimlanes.selectAll('.lane').data(lanes); - const d3LanesEnter = d3Lanes - .enter() - .append('div') - .classed('lane', true); + const d3LanesEnter = d3Lanes.enter().append('div').classed('lane', true); const that = this; @@ -420,10 +417,10 @@ export class ExplorerSwimlane extends React.Component { swimlaneCellClick({}); } }) - .each(function(this: HTMLElement) { + .each(function (this: HTMLElement) { if (swimlaneData.fieldName !== undefined) { d3.select(this) - .on('mouseover', value => { + .on('mouseover', (value) => { that.props.tooltipService.show( [ { skipHeader: true } as ChartTooltipValue, @@ -447,7 +444,7 @@ export class ExplorerSwimlane extends React.Component { }) .attr( 'aria-label', - value => `${mlEscape(swimlaneData.fieldName!)}: ${mlEscape(value)}` + (value) => `${mlEscape(swimlaneData.fieldName!)}: ${mlEscape(value)}` ); } }); @@ -456,7 +453,7 @@ export class ExplorerSwimlane extends React.Component { function getBucketScore(lane: string, time: number): number { let bucketScore = 0; - const point = points.find(p => { + const point = points.find((p) => { return p.value > 0 && p.laneLabel === lane && p.time === time; }); if (typeof point !== 'undefined') { @@ -483,7 +480,7 @@ export class ExplorerSwimlane extends React.Component { // of this iteration to the event. .on('mouseover', cellMouseOverFactory(time, i)) .on('mouseleave', cellMouseleave) - .each(function(this: NodeWithData, laneLabel: string) { + .each(function (this: NodeWithData, laneLabel: string) { this.__clickData__ = { bucketScore: getBucketScore(laneLabel, time), laneLabel, @@ -493,13 +490,13 @@ export class ExplorerSwimlane extends React.Component { }); // calls itself with each() to get access to lane (= d3 data) - cell.append('div').each(function(this: HTMLElement, lane: string) { + cell.append('div').each(function (this: HTMLElement, lane: string) { const el = d3.select(this); let color = 'none'; let bucketScore = 0; - const point = points.find(p => { + const point = points.find((p) => { return p.value > 0 && p.laneLabel === lane && p.time === time; }); @@ -525,25 +522,19 @@ export class ExplorerSwimlane extends React.Component { // height of .time-tick-labels const svgHeight = 25; - const svg = laneTimes - .append('svg') - .attr('width', chartWidth) - .attr('height', svgHeight); + const svg = laneTimes.append('svg').attr('width', chartWidth).attr('height', svgHeight); const xAxis = d3.svg .axis() .scale(xAxisScale) .ticks(numTicksForDateFormat(chartWidth, xAxisTickFormat)) - .tickFormat(tick => moment(tick).format(xAxisTickFormat)); + .tickFormat((tick) => moment(tick).format(xAxisTickFormat)); - const gAxis = svg - .append('g') - .attr('class', 'x axis') - .call(xAxis); + const gAxis = svg.append('g').attr('class', 'x axis').call(xAxis); // remove overlapping labels let overlapCheck = 0; - gAxis.selectAll('g.tick').each(function(this: HTMLElement) { + gAxis.selectAll('g.tick').each(function (this: HTMLElement) { const tick = d3.select(this); const xTransform = d3.transform(tick.attr('transform')).translate[0]; const tickWidth = (tick.select('text').node() as SVGGraphicsElement).getBBox().width; @@ -595,7 +586,7 @@ export class ExplorerSwimlane extends React.Component { const selectedTimes = _.get(selectionState, 'times', []); const selectedTimeExtent = d3.extent(selectedTimes); - selectedLanes.forEach(selectedLane => { + selectedLanes.forEach((selectedLane) => { if ( lanes.indexOf(selectedLane) > -1 && selectedTimeExtent[0] >= startTime && @@ -607,7 +598,7 @@ export class ExplorerSwimlane extends React.Component { `div[data-lane-label="${mlEscape(selectedLane)}"]` ); - laneCells.each(function(this: HTMLElement) { + laneCells.each(function (this: HTMLElement) { const cell = d3.select(this); const cellTime = parseInt(cell.attr('data-time'), 10); if (cellTime >= selectedTimeExtent[0] && cellTime <= selectedTimeExtent[1]) { @@ -621,7 +612,7 @@ export class ExplorerSwimlane extends React.Component { return Math.max(maxBucketScore, +d3.select(cell).attr('data-bucket-score') || 0); }, 0); - const selectedCellTimes = cellsToSelect.map(e => { + const selectedCellTimes = cellsToSelect.map((e) => { return (d3.select(e).node() as NodeWithData).__clickData__.time; }); diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_utils.js b/x-pack/plugins/ml/public/application/explorer/explorer_utils.js index aaf9ff491ce32..f35a000b7f9e1 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_utils.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_utils.js @@ -41,7 +41,7 @@ import { getSwimlaneContainerWidth } from './legacy_utils'; // create new job objects based on standard job config objects // new job objects just contain job id, bucket span in seconds and a selected flag. export function createJobs(jobs) { - return jobs.map(job => { + return jobs.map((job) => { const bucketSpan = parseInterval(job.analysis_config.bucket_span); return { id: job.job_id, selected: false, bucketSpanSeconds: bucketSpan.asSeconds() }; }); @@ -78,7 +78,7 @@ export async function loadFilteredTopInfluencers( // Add the specified influencer(s) to ensure they are used in the filter // even if their influencer score for the selected time range is zero. - influencers.forEach(influencer => { + influencers.forEach((influencer) => { const fieldName = influencer.fieldName; if (recordInfluencersByName[influencer.fieldName] === undefined) { recordInfluencersByName[influencer.fieldName] = []; @@ -87,9 +87,9 @@ export async function loadFilteredTopInfluencers( }); // Add the influencers from the top scoring anomalies. - records.forEach(record => { + records.forEach((record) => { const influencersByName = record.influencers || []; - influencersByName.forEach(influencer => { + influencersByName.forEach((influencer) => { const fieldName = influencer.influencer_field_name; const fieldValues = influencer.influencer_field_values; if (recordInfluencersByName[fieldName] === undefined) { @@ -100,15 +100,15 @@ export async function loadFilteredTopInfluencers( }); const uniqValuesByName = {}; - Object.keys(recordInfluencersByName).forEach(fieldName => { + Object.keys(recordInfluencersByName).forEach((fieldName) => { const fieldValues = recordInfluencersByName[fieldName]; uniqValuesByName[fieldName] = uniq(fieldValues); }); const filterInfluencers = []; - Object.keys(uniqValuesByName).forEach(fieldName => { + Object.keys(uniqValuesByName).forEach((fieldName) => { // Find record influencers with the same field name as the clicked on cell(s). - const matchingFieldName = influencers.find(influencer => { + const matchingFieldName = influencers.find((influencer) => { return influencer.fieldName === fieldName; }); @@ -117,7 +117,7 @@ export async function loadFilteredTopInfluencers( filterInfluencers.push(...influencers); } else { // For other field names, add values from all records. - uniqValuesByName[fieldName].forEach(fieldValue => { + uniqValuesByName[fieldName].forEach((fieldValue) => { filterInfluencers.push({ fieldName, fieldValue }); }); } @@ -135,7 +135,7 @@ export async function loadFilteredTopInfluencers( export function getInfluencers(selectedJobs = []) { const influencers = []; - selectedJobs.forEach(selectedJob => { + selectedJobs.forEach((selectedJob) => { const job = mlJobService.getJob(selectedJob.id); if (job !== undefined && job.analysis_config && job.analysis_config.influencers) { influencers.push(...job.analysis_config.influencers); @@ -212,7 +212,7 @@ export function getSelectionInfluencers(selectedCells, fieldName) { selectedCells.viewByFieldName !== undefined && selectedCells.viewByFieldName !== VIEW_BY_JOB_LABEL ) { - return selectedCells.lanes.map(laneLabel => ({ fieldName, fieldValue: laneLabel })); + return selectedCells.lanes.map((laneLabel) => ({ fieldName, fieldValue: laneLabel })); } return []; @@ -228,7 +228,7 @@ export function getSelectionJobIds(selectedCells, selectedJobs) { return selectedCells.lanes; } - return selectedJobs.map(d => d.id); + return selectedJobs.map((d) => d.id); } export function getSwimlaneBucketInterval(selectedJobs, swimlaneContainerWidth) { @@ -275,15 +275,15 @@ export function loadViewByTopFieldValuesForSelectedTime( swimlaneLimit, noInfluencersConfigured ) { - const selectedJobIds = selectedJobs.map(d => d.id); + const selectedJobIds = selectedJobs.map((d) => d.id); // Find the top field values for the selected time, and then load the 'view by' // swimlane over the full time range for those specific field values. - return new Promise(resolve => { + return new Promise((resolve) => { if (viewBySwimlaneFieldName !== VIEW_BY_JOB_LABEL) { mlResultsService .getTopInfluencers(selectedJobIds, earliestMs, latestMs, swimlaneLimit) - .then(resp => { + .then((resp) => { if (resp.influencers[viewBySwimlaneFieldName] === undefined) { resolve([]); } @@ -291,7 +291,7 @@ export function loadViewByTopFieldValuesForSelectedTime( const topFieldValues = []; const topInfluencers = resp.influencers[viewBySwimlaneFieldName]; if (Array.isArray(topInfluencers)) { - topInfluencers.forEach(influencerData => { + topInfluencers.forEach((influencerData) => { if (influencerData.maxAnomalyScore > 0) { topFieldValues.push(influencerData.influencerFieldValue); } @@ -311,7 +311,7 @@ export function loadViewByTopFieldValuesForSelectedTime( ).asSeconds() + 's', swimlaneLimit ) - .then(resp => { + .then((resp) => { const topFieldValues = Object.keys(resp.results); resolve(topFieldValues); }); @@ -328,19 +328,19 @@ export function getViewBySwimlaneOptions({ selectedCells, selectedJobs, }) { - const selectedJobIds = selectedJobs.map(d => d.id); + const selectedJobIds = selectedJobs.map((d) => d.id); // Unique influencers for the selected job(s). const viewByOptions = chain( mlJobService.jobs.reduce((reducedViewByOptions, job) => { - if (selectedJobIds.some(jobId => jobId === job.job_id)) { + if (selectedJobIds.some((jobId) => jobId === job.job_id)) { return reducedViewByOptions.concat(job.analysis_config.influencers || []); } return reducedViewByOptions; }, []) ) .uniq() - .sortBy(fieldName => fieldName.toLowerCase()) + .sortBy((fieldName) => fieldName.toLowerCase()) .value(); viewByOptions.push(VIEW_BY_JOB_LABEL); @@ -360,12 +360,12 @@ export function getViewBySwimlaneOptions({ } else if (mlJobService.jobs.length > 0 && selectedJobIds.length > 0) { // For a single job, default to the first partition, over, // by or influencer field of the first selected job. - const firstSelectedJob = mlJobService.jobs.find(job => { + const firstSelectedJob = mlJobService.jobs.find((job) => { return job.job_id === selectedJobIds[0]; }); const firstJobInfluencers = firstSelectedJob.analysis_config.influencers || []; - firstSelectedJob.analysis_config.detectors.forEach(detector => { + firstSelectedJob.analysis_config.detectors.forEach((detector) => { if ( detector.partition_field_name !== undefined && firstJobInfluencers.indexOf(detector.partition_field_name) !== -1 @@ -416,7 +416,7 @@ export function getViewBySwimlaneOptions({ Array.isArray(viewBySwimlaneOptions) && Array.isArray(filteredFields) ) { - const filteredOptions = viewBySwimlaneOptions.filter(option => { + const filteredOptions = viewBySwimlaneOptions.filter((option) => { return ( filteredFields.includes(option) || option === VIEW_BY_JOB_LABEL || @@ -538,10 +538,10 @@ export function loadAnnotationsTableData(selectedCells, selectedJobs, interval, const jobIds = selectedCells !== undefined && selectedCells.viewByFieldName === VIEW_BY_JOB_LABEL ? selectedCells.lanes - : selectedJobs.map(d => d.id); + : selectedJobs.map((d) => d.id); const timeRange = getSelectionTimeRange(selectedCells, interval, bounds); - return new Promise(resolve => { + return new Promise((resolve) => { ml.annotations .getAnnotations({ jobIds, @@ -550,13 +550,13 @@ export function loadAnnotationsTableData(selectedCells, selectedJobs, interval, maxAnnotations: ANNOTATIONS_TABLE_DEFAULT_QUERY_SIZE, }) .toPromise() - .then(resp => { + .then((resp) => { if (resp.error !== undefined || resp.annotations === undefined) { return resolve([]); } const annotationsData = []; - jobIds.forEach(jobId => { + jobIds.forEach((jobId) => { const jobAnnotations = resp.annotations[jobId]; if (jobAnnotations !== undefined) { annotationsData.push(...jobAnnotations); @@ -574,7 +574,7 @@ export function loadAnnotationsTableData(selectedCells, selectedJobs, interval, }) ); }) - .catch(resp => { + .catch((resp) => { console.log('Error loading list of annotations for jobs list:', resp); // Silently fail and just return an empty array for annotations to not break the UI. return resolve([]); @@ -613,10 +613,10 @@ export async function loadAnomaliesTableData( influencersFilterQuery ) .toPromise() - .then(resp => { + .then((resp) => { const anomalies = resp.anomalies; const detectorsByJob = mlJobService.detectorsByJob; - anomalies.forEach(anomaly => { + anomalies.forEach((anomaly) => { // Add a detector property to each anomaly. // Default to functionDescription if no description available. // TODO - when job_service is moved server_side, move this to server endpoint. @@ -662,7 +662,7 @@ export async function loadAnomaliesTableData( jobIds, }); }) - .catch(resp => { + .catch((resp) => { console.log('Explorer - error loading data for anomalies table:', resp); reject(); }); @@ -680,7 +680,7 @@ export async function loadDataForCharts( selectedCells, influencersFilterQuery ) { - return new Promise(resolve => { + return new Promise((resolve) => { // Just skip doing the request when this function // is called without the minimum required data. if ( @@ -705,7 +705,7 @@ export async function loadDataForCharts( 500, influencersFilterQuery ) - .then(resp => { + .then((resp) => { // Ignore this response if it's returned by an out of date promise if (newRequestCount < requestCount) { resolve([]); @@ -725,7 +725,7 @@ export async function loadDataForCharts( } export function loadOverallData(selectedJobs, interval, bounds) { - return new Promise(resolve => { + return new Promise((resolve) => { // Loads the overall data components i.e. the overall swimlane and influencers list. if (selectedJobs === null) { resolve({ @@ -738,7 +738,7 @@ export function loadOverallData(selectedJobs, interval, bounds) { // Ensure the search bounds align to the bucketing interval used in the swimlane so // that the first and last buckets are complete. const searchBounds = getBoundsRoundedToInterval(bounds, interval, false); - const selectedJobIds = selectedJobs.map(d => d.id); + const selectedJobIds = selectedJobs.map((d) => d.id); // Load the overall bucket scores by time. // Pass the interval in seconds as the swimlane relies on a fixed number of seconds between buckets @@ -757,7 +757,7 @@ export function loadOverallData(selectedJobs, interval, bounds) { overallBucketsBounds.max.valueOf(), interval.asSeconds() + 's' ) - .then(resp => { + .then((resp) => { const overallSwimlaneData = processOverallResults( resp.results, searchBounds, @@ -782,8 +782,8 @@ export function loadViewBySwimlane( influencersFilterQuery, noInfluencersConfigured ) { - return new Promise(resolve => { - const finish = resp => { + return new Promise((resolve) => { + const finish = (resp) => { if (resp !== undefined) { const viewBySwimlaneData = processViewByResults( resp.results, @@ -819,7 +819,7 @@ export function loadViewBySwimlane( getSwimlaneBucketInterval(selectedJobs, getSwimlaneContainerWidth(noInfluencersConfigured)), false ); - const selectedJobIds = selectedJobs.map(d => d.id); + const selectedJobIds = selectedJobs.map((d) => d.id); // load scores by influencer/jobId value and time. // Pass the interval in seconds as the swimlane relies on a fixed number of seconds between buckets @@ -866,7 +866,7 @@ export async function loadTopInfluencers( noInfluencersConfigured, influencersFilterQuery ) { - return new Promise(resolve => { + return new Promise((resolve) => { if (noInfluencersConfigured !== true) { mlResultsService .getTopInfluencers( @@ -877,7 +877,7 @@ export async function loadTopInfluencers( influencers, influencersFilterQuery ) - .then(resp => { + .then((resp) => { // TODO - sort the influencers keys so that the partition field(s) are first. console.log('Explorer top influencers data set:', resp.influencers); resolve(resp.influencers); diff --git a/x-pack/plugins/ml/public/application/explorer/has_matching_points.ts b/x-pack/plugins/ml/public/application/explorer/has_matching_points.ts index 397615d68f189..1af399d9a70b5 100644 --- a/x-pack/plugins/ml/public/application/explorer/has_matching_points.ts +++ b/x-pack/plugins/ml/public/application/explorer/has_matching_points.ts @@ -17,13 +17,13 @@ export const hasMatchingPoints = ({ swimlaneData, }: HasMatchingPointsParams): boolean => { // If filtered fields includes a wildcard search maskAll only if there are no points matching the pattern - const wildCardField = filteredFields.find(field => /\@kuery-wildcard\@$/.test(field)); + const wildCardField = filteredFields.find((field) => /\@kuery-wildcard\@$/.test(field)); const substring = wildCardField !== undefined ? wildCardField.replace(/\@kuery-wildcard\@$/, '') : null; return ( substring !== null && - swimlaneData.points.some(point => { + swimlaneData.points.some((point) => { return point.laneLabel.includes(substring); }) ); diff --git a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/get_index_pattern.ts b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/get_index_pattern.ts index 9b6c7e4fb99bc..98e630d0028f2 100644 --- a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/get_index_pattern.ts +++ b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/get_index_pattern.ts @@ -13,7 +13,7 @@ import { getInfluencers, ExplorerJob } from '../../explorer_utils'; export function getIndexPattern(selectedJobs: ExplorerJob[]) { return { title: ML_RESULTS_INDEX_PATTERN, - fields: getInfluencers(selectedJobs).map(influencer => ({ + fields: getInfluencers(selectedJobs).map((influencer) => ({ name: influencer, type: 'string', aggregatable: true, diff --git a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/set_influencer_filter_settings.ts b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/set_influencer_filter_settings.ts index 0d84179c572d2..819f6ca1cac92 100644 --- a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/set_influencer_filter_settings.ts +++ b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/set_influencer_filter_settings.ts @@ -23,7 +23,7 @@ export function setInfluencerFilterSettings( const { selectedCells, viewBySwimlaneOptions } = state; let selectedViewByFieldName = state.viewBySwimlaneFieldName; - const filteredViewBySwimlaneOptions = viewBySwimlaneOptions.filter(d => + const filteredViewBySwimlaneOptions = viewBySwimlaneOptions.filter((d) => filteredFields.includes(d) ); diff --git a/x-pack/plugins/ml/public/application/explorer/select_limit/select_limit.tsx b/x-pack/plugins/ml/public/application/explorer/select_limit/select_limit.tsx index 03e3273b80832..7f7a8fc5a70bd 100644 --- a/x-pack/plugins/ml/public/application/explorer/select_limit/select_limit.tsx +++ b/x-pack/plugins/ml/public/application/explorer/select_limit/select_limit.tsx @@ -15,7 +15,7 @@ import { EuiSelect } from '@elastic/eui'; const limitOptions = [5, 10, 25, 50]; -const euiOptions = limitOptions.map(limit => ({ +const euiOptions = limitOptions.map((limit) => ({ value: limit, text: `${limit}`, })); diff --git a/x-pack/plugins/ml/public/application/formatters/format_value.ts b/x-pack/plugins/ml/public/application/formatters/format_value.ts index abafe65615156..1a696d6e01dde 100644 --- a/x-pack/plugins/ml/public/application/formatters/format_value.ts +++ b/x-pack/plugins/ml/public/application/formatters/format_value.ts @@ -39,7 +39,7 @@ export function formatValue( // Currently only multi-value response is for lat_long detectors. // Return with array style formatting, with items formatted as numbers, rather than // the default String format which is set for geo_point and geo_shape fields. - const values = value.map(val => formatSingleValue(val, mlFunction, undefined, record)); + const values = value.map((val) => formatSingleValue(val, mlFunction, undefined, record)); return `[${values}]`; } } else { @@ -73,20 +73,14 @@ function formatSingleValue( record !== undefined && record.timestamp !== undefined ? new Date(record.timestamp) : new Date(); - const utcMoment = moment - .utc(d) - .startOf('week') - .add(value, 's'); + const utcMoment = moment.utc(d).startOf('week').add(value, 's'); return moment(utcMoment.valueOf()).format('ddd HH:mm'); } else if (mlFunction === 'time_of_day') { const d = record !== undefined && record.timestamp !== undefined ? new Date(record.timestamp) : new Date(); - const utcMoment = moment - .utc(d) - .startOf('day') - .add(value, 's'); + const utcMoment = moment.utc(d).startOf('day').add(value, 's'); return moment(utcMoment.valueOf()).format('HH:mm'); } else { if (fieldFormat !== undefined) { diff --git a/x-pack/plugins/ml/public/application/formatters/number_as_ordinal.test.ts b/x-pack/plugins/ml/public/application/formatters/number_as_ordinal.test.ts index 5b378934ed5e8..d5f357106b735 100644 --- a/x-pack/plugins/ml/public/application/formatters/number_as_ordinal.test.ts +++ b/x-pack/plugins/ml/public/application/formatters/number_as_ordinal.test.ts @@ -21,7 +21,7 @@ describe('ML - numberAsOrdinal formatter', () => { { number: 100, asOrdinal: '100th' }, ]; test('returns the expected numeral format', () => { - tests.forEach(test => { + tests.forEach((test) => { expect(numberAsOrdinal(test.number)).toBe(test.asOrdinal); }); }); diff --git a/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/editor.tsx b/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/editor.tsx index c4c32c1f4c5f2..4f6e520298efb 100644 --- a/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/editor.tsx +++ b/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/editor.tsx @@ -114,7 +114,7 @@ export const CustomUrlEditor: FC = ({ }; const onQueryEntitiesChange = (selectedOptions: EuiComboBoxOptionOption[]) => { - const selectedFieldNames = selectedOptions.map(option => option.label); + const selectedFieldNames = selectedOptions.map((option) => option.label); const kibanaSettings = customUrl.kibanaSettings; setEditCustomUrl({ @@ -159,22 +159,22 @@ export const CustomUrlEditor: FC = ({ const { label, type, timeRange, kibanaSettings, otherUrlSettings } = customUrl; - const dashboardOptions = dashboards.map(dashboard => { + const dashboardOptions = dashboards.map((dashboard) => { return { value: dashboard.id, text: dashboard.title }; }); - const indexPatternOptions = indexPatterns.map(indexPattern => { + const indexPatternOptions = indexPatterns.map((indexPattern) => { return { value: indexPattern.id, text: indexPattern.title }; }); - const entityOptions = queryEntityFieldNames.map(fieldName => ({ label: fieldName })); + const entityOptions = queryEntityFieldNames.map((fieldName) => ({ label: fieldName })); let selectedEntityOptions: EuiComboBoxOptionOption[] = []; if (kibanaSettings !== undefined && kibanaSettings.queryFieldNames !== undefined) { const queryFieldNames: string[] = kibanaSettings.queryFieldNames; - selectedEntityOptions = queryFieldNames.map(fieldName => ({ label: fieldName })); + selectedEntityOptions = queryFieldNames.map((fieldName) => ({ label: fieldName })); } - const timeRangeOptions = Object.values(TIME_RANGE_TYPE).map(timeRangeType => ({ + const timeRangeOptions = Object.values(TIME_RANGE_TYPE).map((timeRangeType) => ({ value: timeRangeType, text: timeRangeType, })); diff --git a/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/list.tsx b/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/list.tsx index 1b18afaf2569f..7e228757dfd90 100644 --- a/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/list.tsx +++ b/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/list.tsx @@ -102,10 +102,10 @@ export const CustomUrlList: FC = ({ job, customUrls, setCust const onTestButtonClick = (index: number) => { if (index < customUrls.length) { getTestUrl(job, customUrls[index]) - .then(testUrl => { + .then((testUrl) => { openCustomUrlWindow(testUrl, customUrls[index]); }) - .catch(resp => { + .catch((resp) => { // eslint-disable-next-line no-console console.error('Error obtaining URL for test:', resp); @@ -163,7 +163,7 @@ export const CustomUrlList: FC = ({ job, customUrls, setCust onLabelChange(e, index)} + onChange={(e) => onLabelChange(e, index)} data-test-subj={`mlJobEditCustomUrlLabelInput_${index}`} /> @@ -184,7 +184,7 @@ export const CustomUrlList: FC = ({ job, customUrls, setCust }} fullWidth={true} value={customUrl.url_value} - onChange={e => onUrlValueChange(e, index)} + onChange={(e) => onUrlValueChange(e, index)} onBlur={() => { setExpandedUrlIndex(null); }} @@ -216,7 +216,7 @@ export const CustomUrlList: FC = ({ job, customUrls, setCust value={(customUrl as KibanaUrlConfig).time_range || ''} isInvalid={isInvalidTimeRange} placeholder={TIME_RANGE_TYPE.AUTO} - onChange={e => onTimeRangeChange(e, index)} + onChange={(e) => onTimeRangeChange(e, index)} /> diff --git a/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/utils.js b/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/utils.js index 18873b3b6b6d3..0b33efa3f9ff1 100644 --- a/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/utils.js +++ b/x-pack/plugins/ml/public/application/jobs/components/custom_url_editor/utils.js @@ -47,7 +47,7 @@ export function getNewCustomUrlDefaults(job, dashboards, indexPatterns) { datafeedConfig.indices.length > 0 ) { const datafeedIndex = datafeedConfig.indices[0]; - let defaultIndexPattern = indexPatterns.find(indexPattern => { + let defaultIndexPattern = indexPatterns.find((indexPattern) => { return indexPattern.title === datafeedIndex; }); @@ -87,7 +87,7 @@ export function getQueryEntityFieldNames(job) { detectors.forEach((detector, detectorIndex) => { const partitioningFields = getPartitioningFieldNames(job, detectorIndex); - partitioningFields.forEach(fieldName => { + partitioningFields.forEach((fieldName) => { if (entityFieldNames.indexOf(fieldName) === -1) { entityFieldNames.push(fieldName); } @@ -139,7 +139,7 @@ function buildDashboardUrlFromSettings(settings) { const savedObjectsClient = getSavedObjectsClient(); savedObjectsClient .get('dashboard', dashboardId) - .then(response => { + .then((response) => { // Use the filters from the saved dashboard if there are any. let filters = []; @@ -176,7 +176,7 @@ function buildDashboardUrlFromSettings(settings) { // template to inject the time parameters. useHash: false, }) - .then(urlValue => { + .then((urlValue) => { const urlToAdd = { url_name: settings.label, url_value: decodeURIComponent(`dashboards${url.parse(urlValue).hash}`), @@ -190,7 +190,7 @@ function buildDashboardUrlFromSettings(settings) { resolve(urlToAdd); }); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -300,7 +300,7 @@ export function getTestUrl(job, customUrl) { rest_total_hits_as_int: true, body, }) - .then(resp => { + .then((resp) => { if (resp.hits.total > 0) { const record = resp.hits.hits[0]._source; testUrl = replaceTokensInUrlValue(customUrl, bucketSpanSecs, record, 'timestamp'); @@ -308,7 +308,7 @@ export function getTestUrl(job, customUrl) { } else { // No anomalies yet for this job, so do a preview of the search // configured in the job datafeed to obtain sample docs. - mlJobService.searchPreview(job).then(response => { + mlJobService.searchPreview(job).then((response) => { let testDoc; const docTimeFieldName = job.data_description.time_field; @@ -348,7 +348,7 @@ export function getTestUrl(job, customUrl) { }); } }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_flyout.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_flyout.js index 0d88aa29d70e9..d05278c19b5a5 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_flyout.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_flyout.js @@ -81,9 +81,9 @@ export class CreateWatchFlyoutUI extends Component { }); }; - showFlyout = jobId => { + showFlyout = (jobId) => { loadFullJob(jobId) - .then(job => { + .then((job) => { const bucketSpan = job.analysis_config.bucket_span; mlCreateWatchService.config.includeInfluencers = job.analysis_config.influencers.length > 0; @@ -94,7 +94,7 @@ export class CreateWatchFlyoutUI extends Component { isFlyoutVisible: true, }); }) - .catch(error => { + .catch((error) => { console.error(error); }); }; @@ -103,11 +103,11 @@ export class CreateWatchFlyoutUI extends Component { const { toasts } = this.props.kibana.services.notifications; mlCreateWatchService .createNewWatch(this.state.jobId) - .then(resp => { + .then((resp) => { toasts.addSuccess(getSuccessToast(resp.id, resp.url)); this.closeFlyout(true); }) - .catch(error => { + .catch((error) => { toasts.addDanger( i18n.translate( 'xpack.ml.jobsList.createWatchFlyout.watchNotSavedErrorNotificationMessage', diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_service.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_service.js index 307fa79f5dea2..67de83e90695d 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_service.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_service.js @@ -80,7 +80,7 @@ class CreateWatchService { this.config.threshold = { display, val }; } - createNewWatch = function(jobId) { + createNewWatch = function (jobId) { return new Promise((resolve, reject) => { this.status.watch = this.STATUS.SAVING; if (jobId !== undefined) { @@ -173,7 +173,7 @@ class CreateWatchService { url: this.config.watcherEditURL, }); }) - .catch(resp => { + .catch((resp) => { this.status.watch = this.STATUS.SAVE_FAILED; reject(resp); }); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_view.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_view.js index 0595ce5caf931..97520626783fa 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_view.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/create_watch_view.js @@ -66,7 +66,7 @@ export class CreateWatch extends Component { } // load elasticsearch settings to see if email has been configured - ml.getNotificationSettings().then(resp => { + ml.getNotificationSettings().then((resp) => { if (has(resp, 'defaults.xpack.notification.email')) { this.setState({ emailEnabled: true }); } @@ -82,27 +82,27 @@ export class CreateWatch extends Component { }); } - onThresholdChange = threshold => { + onThresholdChange = (threshold) => { this.setState({ threshold }, () => { this.config.threshold = threshold; }); }; - onIntervalChange = e => { + onIntervalChange = (e) => { const interval = e.target.value; this.setState({ interval }, () => { this.config.interval = interval; }); }; - onIncludeEmailChanged = e => { + onIncludeEmailChanged = (e) => { const includeEmail = e.target.checked; this.setState({ includeEmail }, () => { this.config.includeEmail = includeEmail; }); }; - onEmailChange = e => { + onEmailChange = (e) => { const email = e.target.value; this.setState({ email }, () => { this.config.email = email; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/select_severity.tsx b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/select_severity.tsx index 727830a58bb41..ff930832bde3e 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/select_severity.tsx +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/create_watch_flyout/select_severity.tsx @@ -68,7 +68,7 @@ export const SEVERITY_OPTIONS: TableSeverity[] = [ function optionValueToThreshold(value: number) { // Get corresponding threshold object with required display and val properties from the specified value. - let threshold = SEVERITY_OPTIONS.find(opt => opt.val === value); + let threshold = SEVERITY_OPTIONS.find((opt) => opt.val === value); // Default to warning if supplied value doesn't map to one of the options. if (threshold === undefined) { diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/delete_job_modal/delete_job_modal.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/delete_job_modal/delete_job_modal.js index 3e129a174c9e0..1e3ec6241311b 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/delete_job_modal/delete_job_modal.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/delete_job_modal/delete_job_modal.js @@ -56,7 +56,7 @@ export class DeleteJobModal extends Component { this.setState({ isModalVisible: false }); }; - showModal = jobs => { + showModal = (jobs) => { this.setState({ jobs, isModalVisible: true, @@ -74,7 +74,7 @@ export class DeleteJobModal extends Component { }, DELETING_JOBS_REFRESH_INTERVAL_MS); }; - setEL = el => { + setEL = (el) => { if (el) { this.el = el; } diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js index 9066e41fb8f23..b463322ea55db 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js @@ -108,17 +108,17 @@ export class EditJobFlyoutUI extends Component { ); } - showFlyout = jobLite => { + showFlyout = (jobLite) => { const hasDatafeed = jobLite.hasDatafeed; loadFullJob(jobLite.id) - .then(job => { + .then((job) => { this.extractJob(job, hasDatafeed); this.setState({ job, isFlyoutVisible: true, }); }) - .catch(error => { + .catch((error) => { console.error(error); }); }; @@ -147,7 +147,7 @@ export class EditJobFlyoutUI extends Component { jobGroups: job.groups !== undefined ? job.groups : [], jobModelMemoryLimit: mml, jobDetectors: detectors, - jobDetectorDescriptions: detectors.map(d => d.detector_description), + jobDetectorDescriptions: detectors.map((d) => d.detector_description), jobBucketSpan: bucketSpan, jobCustomUrls: customUrls, datafeedQuery: hasDatafeed ? JSON.stringify(datafeedConfig.query, null, 2) : '', @@ -171,7 +171,7 @@ export class EditJobFlyoutUI extends Component { }); } - setJobDetails = jobDetails => { + setJobDetails = (jobDetails) => { let { jobModelMemoryLimitValidationError, jobGroupsValidationError } = this.state; if (jobDetails.jobModelMemoryLimit !== undefined) { @@ -180,7 +180,7 @@ export class EditJobFlyoutUI extends Component { } if (jobDetails.jobGroups !== undefined) { - if (jobDetails.jobGroups.some(j => this.props.allJobIds.includes(j))) { + if (jobDetails.jobGroups.some((j) => this.props.allJobIds.includes(j))) { jobGroupsValidationError = i18n.translate( 'xpack.ml.jobsList.editJobFlyout.groupsAndJobsHasSameIdErrorMessage', { @@ -204,19 +204,19 @@ export class EditJobFlyoutUI extends Component { }); }; - setDetectorDescriptions = jobDetectorDescriptions => { + setDetectorDescriptions = (jobDetectorDescriptions) => { this.setState({ ...jobDetectorDescriptions, }); }; - setDatafeed = datafeed => { + setDatafeed = (datafeed) => { this.setState({ ...datafeed, }); }; - setCustomUrls = jobCustomUrls => { + setCustomUrls = (jobCustomUrls) => { const isValidJobCustomUrls = isValidCustomUrls(jobCustomUrls); this.setState({ jobCustomUrls, @@ -251,7 +251,7 @@ export class EditJobFlyoutUI extends Component { this.refreshJobs(); this.closeFlyout(true); }) - .catch(error => { + .catch((error) => { console.error(error); toasts.addDanger( i18n.translate('xpack.ml.jobsList.editJobFlyout.changesNotSavedNotificationMessage', { diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js index a49a2af896be2..fcd2c09f72767 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js @@ -32,7 +32,7 @@ export function saveJob(job, newJobData, finish) { .then(() => { resolve(); }) - .catch(error => { + .catch((error) => { reject(error); }); }; @@ -41,14 +41,14 @@ export function saveJob(job, newJobData, finish) { if (Object.keys(jobData).length) { mlJobService .updateJob(job.job_id, jobData) - .then(resp => { + .then((resp) => { if (resp.success) { saveDatafeedWrapper(); } else { reject(resp); } }) - .catch(error => { + .catch((error) => { reject(error); }); } else { @@ -61,7 +61,7 @@ function saveDatafeed(datafeedData, job) { return new Promise((resolve, reject) => { if (Object.keys(datafeedData).length) { const datafeedId = job.datafeed_config.datafeed_id; - mlJobService.updateDatafeed(datafeedId, datafeedData).then(resp => { + mlJobService.updateDatafeed(datafeedId, datafeedData).then((resp) => { if (resp.success) { resolve(); } else { @@ -84,10 +84,10 @@ export function loadSavedDashboards(maxNumber) { fields: ['title'], perPage: maxNumber, }) - .then(resp => { + .then((resp) => { const savedObjects = resp.savedObjects; if (savedObjects !== undefined) { - const dashboards = savedObjects.map(savedObj => { + const dashboards = savedObjects.map((savedObj) => { return { id: savedObj.id, title: savedObj.attributes.title }; }); @@ -98,7 +98,7 @@ export function loadSavedDashboards(maxNumber) { resolve(dashboards); } }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -116,10 +116,10 @@ export function loadIndexPatterns(maxNumber) { fields: ['title'], perPage: maxNumber, }) - .then(resp => { + .then((resp) => { const savedObjects = resp.savedObjects; if (savedObjects !== undefined) { - const indexPatterns = savedObjects.map(savedObj => { + const indexPatterns = savedObjects.map((savedObj) => { return { id: savedObj.id, title: savedObj.attributes.title }; }); @@ -130,7 +130,7 @@ export function loadIndexPatterns(maxNumber) { resolve(indexPatterns); } }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -183,7 +183,7 @@ function extractDetectorDescriptions(job, newJobData) { })); const originalDetectors = job.analysis_config.detectors; - originalDetectors.forEach(d => { + originalDetectors.forEach((d) => { if (descriptions[d.detector_index].description !== d.detector_description) { detectors.push(descriptions[d.detector_index]); } diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/custom_urls.tsx b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/custom_urls.tsx index 6cb9dde056c5c..7af27fc22e34c 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/custom_urls.tsx +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/custom_urls.tsx @@ -84,10 +84,10 @@ class CustomUrlsUI extends Component { componentDidMount() { const { toasts } = this.props.kibana.services.notifications; loadSavedDashboards(MAX_NUMBER_DASHBOARDS) - .then(dashboards => { + .then((dashboards) => { this.setState({ dashboards }); }) - .catch(resp => { + .catch((resp) => { // eslint-disable-next-line no-console console.error('Error loading list of dashboards:', resp); toasts.addDanger( @@ -101,10 +101,10 @@ class CustomUrlsUI extends Component { }); loadIndexPatterns(MAX_NUMBER_INDEX_PATTERNS) - .then(indexPatterns => { + .then((indexPatterns) => { this.setState({ indexPatterns }); }) - .catch(resp => { + .catch((resp) => { // eslint-disable-next-line no-console console.error('Error loading list of dashboards:', resp); toasts.addDanger( @@ -120,7 +120,7 @@ class CustomUrlsUI extends Component { editNewCustomUrl = () => { // Opens the editor for configuring a new custom URL. - this.setState(prevState => { + this.setState((prevState) => { const { dashboards, indexPatterns } = prevState; return { @@ -138,7 +138,7 @@ class CustomUrlsUI extends Component { addNewCustomUrl = () => { buildCustomUrlFromSettings(this.state.editorSettings as CustomUrlSettings) - .then(customUrl => { + .then((customUrl) => { const customUrls = [...this.state.customUrls, customUrl]; this.props.setCustomUrls(customUrls); this.setState({ editorOpen: false }); @@ -163,12 +163,12 @@ class CustomUrlsUI extends Component { const { toasts } = this.props.kibana.services.notifications; const job = this.props.job; buildCustomUrlFromSettings(this.state.editorSettings as CustomUrlSettings) - .then(customUrl => { + .then((customUrl) => { getTestUrl(job, customUrl) - .then(testUrl => { + .then((testUrl) => { openCustomUrlWindow(testUrl, customUrl); }) - .catch(resp => { + .catch((resp) => { // eslint-disable-next-line no-console console.error('Error obtaining URL for test:', resp); toasts.addWarning( @@ -181,7 +181,7 @@ class CustomUrlsUI extends Component { ); }); }) - .catch(resp => { + .catch((resp) => { // eslint-disable-next-line no-console console.error('Error building custom URL from settings:', resp); toasts.addWarning( diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/datafeed.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/datafeed.js index 3d81b767021a0..a038f761d47a0 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/datafeed.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/datafeed.js @@ -61,19 +61,19 @@ export class Datafeed extends Component { }; } - onQueryChange = query => { + onQueryChange = (query) => { this.setDatafeed({ datafeedQuery: query }); }; - onQueryDelayChange = e => { + onQueryDelayChange = (e) => { this.setDatafeed({ datafeedQueryDelay: e.target.value }); }; - onFrequencyChange = e => { + onFrequencyChange = (e) => { this.setDatafeed({ datafeedFrequency: e.target.value }); }; - onScrollSizeChange = e => { + onScrollSizeChange = (e) => { this.setDatafeed({ datafeedScrollSize: +e.target.value }); }; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/detectors.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/detectors.js index 0296004f736a2..e9ba65f14138b 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/detectors.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/detectors.js @@ -16,7 +16,7 @@ export class Detectors extends Component { constructor(props) { super(props); - this.detectors = mlJobService.getJobGroups().map(g => ({ label: g.id })); + this.detectors = mlJobService.getJobGroups().map((g) => ({ label: g.id })); this.state = { detectors: [], @@ -47,7 +47,7 @@ export class Detectors extends Component { {detectorDescriptions.map((d, i) => ( - this.onDescriptionChange(e, i)} /> + this.onDescriptionChange(e, i)} /> ))} diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/job_details.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/job_details.js index 672fd8cefaaba..974afafc08b6b 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/job_details.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/job_details.js @@ -33,18 +33,18 @@ export class JobDetails extends Component { // load groups to populate the select options ml.jobs .groups() - .then(resp => { - const groups = resp.map(g => ({ label: g.id })); + .then((resp) => { + const groups = resp.map((g) => ({ label: g.id })); this.setState({ groups }); }) - .catch(error => { + .catch((error) => { console.error('Could not load groups', error); }); } static getDerivedStateFromProps(props) { const selectedGroups = - props.jobGroups !== undefined ? props.jobGroups.map(g => ({ label: g })) : []; + props.jobGroups !== undefined ? props.jobGroups.map((g) => ({ label: g })) : []; return { description: props.jobDescription, @@ -55,16 +55,16 @@ export class JobDetails extends Component { }; } - onDescriptionChange = e => { + onDescriptionChange = (e) => { this.setJobDetails({ jobDescription: e.target.value }); }; - onMmlChange = e => { + onMmlChange = (e) => { this.setJobDetails({ jobModelMemoryLimit: e.target.value }); }; - onGroupsChange = selectedGroups => { - this.setJobDetails({ jobGroups: selectedGroups.map(g => g.label) }); + onGroupsChange = (selectedGroups) => { + this.setJobDetails({ jobGroups: selectedGroups.map((g) => g.label) }); }; onCreateGroup = (input, flattenedOptions) => { @@ -82,7 +82,7 @@ export class JobDetails extends Component { // Create the option if it doesn't exist. if ( flattenedOptions.findIndex( - option => option.label.trim().toLowerCase() === normalizedSearchValue + (option) => option.label.trim().toLowerCase() === normalizedSearchValue ) === -1 ) { groups.push(newGroup); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_actions/management.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_actions/management.js index bb4bed93f922e..254c546df65bc 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_actions/management.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_actions/management.js @@ -33,9 +33,9 @@ export function actionsMenuContent( defaultMessage: 'Start datafeed', }), icon: 'play', - enabled: item => item.deleting !== true && canStartStopDatafeed, - available: item => isStartable([item]), - onClick: item => { + enabled: (item) => item.deleting !== true && canStartStopDatafeed, + available: (item) => isStartable([item]), + onClick: (item) => { showStartDatafeedModal([item]); closeMenu(); }, @@ -49,9 +49,9 @@ export function actionsMenuContent( defaultMessage: 'Stop datafeed', }), icon: 'stop', - enabled: item => item.deleting !== true && canStartStopDatafeed, - available: item => isStoppable([item]), - onClick: item => { + enabled: (item) => item.deleting !== true && canStartStopDatafeed, + available: (item) => isStoppable([item]), + onClick: (item) => { stopDatafeeds([item], refreshJobs); closeMenu(true); }, @@ -65,9 +65,9 @@ export function actionsMenuContent( defaultMessage: 'Close job', }), icon: 'cross', - enabled: item => item.deleting !== true && canCloseJob, - available: item => isClosable([item]), - onClick: item => { + enabled: (item) => item.deleting !== true && canCloseJob, + available: (item) => isClosable([item]), + onClick: (item) => { closeJobs([item], refreshJobs); closeMenu(true); }, @@ -81,19 +81,19 @@ export function actionsMenuContent( defaultMessage: 'Clone job', }), icon: 'copy', - enabled: item => { + enabled: (item) => { // We only allow cloning of a job if the user has the right permissions and can still access // the indexPattern the job was created for. An indexPattern could either have been deleted // since the the job was created or the current user doesn't have the required permissions to // access the indexPattern. const indexPatternNames = getIndexPatternNames(); - const jobIndicesAvailable = item.datafeedIndices.every(dfiName => { - return indexPatternNames.some(ipName => ipName === dfiName); + const jobIndicesAvailable = item.datafeedIndices.every((dfiName) => { + return indexPatternNames.some((ipName) => ipName === dfiName); }); return item.deleting !== true && canCreateJob && jobIndicesAvailable; }, - onClick: item => { + onClick: (item) => { cloneJob(item.id); closeMenu(true); }, @@ -107,8 +107,8 @@ export function actionsMenuContent( defaultMessage: 'Edit job', }), icon: 'pencil', - enabled: item => item.deleting !== true && canUpdateJob && canUpdateDatafeed, - onClick: item => { + enabled: (item) => item.deleting !== true && canUpdateJob && canUpdateDatafeed, + onClick: (item) => { showEditJobFlyout(item); closeMenu(); }, @@ -124,7 +124,7 @@ export function actionsMenuContent( icon: 'trash', color: 'danger', enabled: () => canDeleteJob, - onClick: item => { + onClick: (item) => { showDeleteJobModal([item]); closeMenu(); }, diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/datafeed_preview_tab.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/datafeed_preview_tab.js index 9406f1b3456cf..ff314c237f5d7 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/datafeed_preview_tab.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/datafeed_preview_tab.js @@ -62,10 +62,10 @@ export class DatafeedPreviewPane extends Component { this.setState({ canPreviewDatafeed }); updateDatafeedPreview(this.props.job, canPreviewDatafeed) - .then(previewJson => { + .then((previewJson) => { this.setState({ previewJson, loading: false }); }) - .catch(error => { + .catch((error) => { console.log('Datafeed preview could not be loaded', error); this.setState({ loading: false }); }); @@ -89,7 +89,7 @@ function updateDatafeedPreview(job, canPreviewDatafeed) { if (canPreviewDatafeed) { mlJobService .getDatafeedPreview(job.datafeed_config.datafeed_id) - .then(resp => { + .then((resp) => { if (Array.isArray(resp)) { resolve(JSON.stringify(resp.slice(0, ML_DATA_PREVIEW_COUNT), null, 2)); } else { @@ -97,7 +97,7 @@ function updateDatafeedPreview(job, canPreviewDatafeed) { console.log('Datafeed preview could not be loaded', resp); } }) - .catch(error => { + .catch((error) => { reject(error); }); } diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/extract_job_details.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/extract_job_details.js index fa36a0626d632..50e5aeeb29dd9 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/extract_job_details.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/extract_job_details.js @@ -34,7 +34,7 @@ export function extractJobDetails(job) { }; if (job.custom_settings && job.custom_settings.custom_urls) { customUrl.items.push( - ...job.custom_settings.custom_urls.map(cu => [cu.url_name, cu.url_value, cu.time_range]) + ...job.custom_settings.custom_urls.map((cu) => [cu.url_name, cu.url_value, cu.time_range]) ); } @@ -59,13 +59,13 @@ export function extractJobDetails(job) { items: [], }; if (job.calendars) { - calendars.items = job.calendars.map(c => [ + calendars.items = job.calendars.map((c) => [ '', {c}, ]); // remove the calendars list from the general section // so not to show it twice. - const i = general.items.findIndex(item => item[0] === 'calendars'); + const i = general.items.findIndex((item) => item[0] === 'calendars'); if (i >= 0) { general.items.splice(i, 1); } @@ -81,7 +81,7 @@ export function extractJobDetails(job) { }; if (job.analysis_config && job.analysis_config.detectors) { detectors.items.push( - ...job.analysis_config.detectors.map(d => { + ...job.analysis_config.detectors.map((d) => { const stringifiedDtr = detectorToString(d); return [ stringifiedDtr, @@ -97,7 +97,7 @@ export function extractJobDetails(job) { defaultMessage: 'Influencers', }), position: 'left', - items: job.analysis_config.influencers.map(i => ['', i]), + items: job.analysis_config.influencers.map((i) => ['', i]), }; const analysisConfig = { @@ -141,7 +141,7 @@ export function extractJobDetails(job) { if (job.datafeed_config && job.datafeed_config.timing_stats) { // remove the timing_stats list from the datafeed section // so not to show it twice. - const i = datafeed.items.findIndex(item => item[0] === 'timing_stats'); + const i = datafeed.items.findIndex((item) => item[0] === 'timing_stats'); if (i >= 0) { datafeed.items.splice(i, 1); } @@ -183,7 +183,7 @@ export function extractJobDetails(job) { items: job.datafeed_config && job.datafeed_config.timing_stats ? filterObjects(job.datafeed_config.timing_stats) - .filter(o => o[0] !== 'total_search_time_ms') // remove total_search_time_ms as average_search_time_per_bucket_ms is better + .filter((o) => o[0] !== 'total_search_time_ms') // remove total_search_time_ms as average_search_time_per_bucket_ms is better .map(formatValues) : [], }; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js index 41dfdb0dcfeed..817715dbf6413 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js @@ -56,13 +56,13 @@ export class ForecastsTable extends Component { dataCounts.earliest_record_timestamp, MAX_FORECASTS ) - .then(resp => { + .then((resp) => { this.setState({ isLoading: false, forecasts: resp.forecasts, }); }) - .catch(resp => { + .catch((resp) => { console.log('Error loading list of forecasts for jobs list:', resp); this.setState({ isLoading: false, @@ -201,7 +201,7 @@ export class ForecastsTable extends Component { defaultMessage: 'Created', }), dataType: 'date', - render: date => formatDate(date, TIME_FORMAT), + render: (date) => formatDate(date, TIME_FORMAT), textOnly: true, sortable: true, scope: 'row', @@ -212,7 +212,7 @@ export class ForecastsTable extends Component { defaultMessage: 'From', }), dataType: 'date', - render: date => formatDate(date, TIME_FORMAT), + render: (date) => formatDate(date, TIME_FORMAT), textOnly: true, sortable: true, }, @@ -222,7 +222,7 @@ export class ForecastsTable extends Component { defaultMessage: 'To', }), dataType: 'date', - render: date => formatDate(date, TIME_FORMAT), + render: (date) => formatDate(date, TIME_FORMAT), textOnly: true, sortable: true, }, @@ -238,7 +238,7 @@ export class ForecastsTable extends Component { name: i18n.translate('xpack.ml.jobsList.jobDetails.forecastsTable.memorySizeLabel', { defaultMessage: 'Memory size', }), - render: bytes => formatNumber(bytes, '0b'), + render: (bytes) => formatNumber(bytes, '0b'), sortable: true, }, { @@ -246,7 +246,7 @@ export class ForecastsTable extends Component { name: i18n.translate('xpack.ml.jobsList.jobDetails.forecastsTable.processingTimeLabel', { defaultMessage: 'Processing time', }), - render: ms => + render: (ms) => i18n.translate('xpack.ml.jobsList.jobDetails.forecastsTable.msTimeUnitLabel', { defaultMessage: '{ms} ms', values: { @@ -260,7 +260,7 @@ export class ForecastsTable extends Component { name: i18n.translate('xpack.ml.jobsList.jobDetails.forecastsTable.expiresLabel', { defaultMessage: 'Expires', }), - render: date => formatDate(date, TIME_FORMAT), + render: (date) => formatDate(date, TIME_FORMAT), textOnly: true, sortable: true, }, @@ -270,7 +270,7 @@ export class ForecastsTable extends Component { defaultMessage: 'Messages', }), sortable: false, - render: messages => { + render: (messages) => { return (
{messages.map((message, index) => { @@ -286,7 +286,7 @@ export class ForecastsTable extends Component { defaultMessage: 'View', }), width: '60px', - render: forecast => { + render: (forecast) => { const viewForecastAriaLabel = i18n.translate( 'xpack.ml.jobsList.jobDetails.forecastsTable.viewAriaLabel', { diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js index 246a476517ace..9194f7537cf3d 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js @@ -84,9 +84,9 @@ export function formatValues([key, value]) { export function filterObjects(obj, allowArrays, allowObjects) { return Object.keys(obj) .filter( - k => allowObjects || typeof obj[k] !== 'object' || (allowArrays && Array.isArray(obj[k])) + (k) => allowObjects || typeof obj[k] !== 'object' || (allowArrays && Array.isArray(obj[k])) ) - .map(k => { + .map((k) => { let item = obj[k]; if (Array.isArray(item)) { item = item.join(', '); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/job_details_pane.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/job_details_pane.js index e7df2c089dca2..606210dd87593 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/job_details_pane.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/job_details_pane.js @@ -79,14 +79,14 @@ export class JobDetailsPane extends Component {
{sections - .filter(s => s.position === 'left') + .filter((s) => s.position === 'left') .map((s, i) => (
))}
{sections - .filter(s => s.position === 'right') + .filter((s) => s.position === 'right') .map((s, i) => (
))} diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_filter_bar/job_filter_bar.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_filter_bar/job_filter_bar.js index a91df3cce01f2..b274a8d572adb 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_filter_bar/job_filter_bar.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_filter_bar/job_filter_bar.js @@ -18,8 +18,8 @@ import { FormattedMessage } from '@kbn/i18n/react'; function loadGroups() { return ml.jobs .groups() - .then(groups => { - return groups.map(g => ({ + .then((groups) => { + return groups.map((g) => ({ value: g.id, view: (
@@ -36,7 +36,7 @@ function loadGroups() { ), })); }) - .catch(error => { + .catch((error) => { console.log(error); return []; }); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/job_description.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/job_description.js index 0cccca722557d..dbaa1ff59a487 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/job_description.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/job_description.js @@ -14,7 +14,7 @@ export function JobDescription({ job }) {
{job.description}   - {job.groups.map(group => ( + {job.groups.map((group) => ( ))}
diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/jobs_list.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/jobs_list.js index 9874ac56577d3..0afaca3ec12e1 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/jobs_list.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/jobs_list.js @@ -61,7 +61,7 @@ export class JobsList extends Component { }); }; - toggleRow = item => { + toggleRow = (item) => { this.props.toggleRow(item.id); }; @@ -76,7 +76,7 @@ export class JobsList extends Component { getPageOfJobs(index, size, sortField, sortDirection) { let list = this.state.jobsSummaryList; - list = sortBy(this.state.jobsSummaryList, item => item[sortField]); + list = sortBy(this.state.jobsSummaryList, (item) => item[sortField]); list = sortDirection === 'asc' ? list : list.reverse(); const listLength = list.length; @@ -101,7 +101,7 @@ export class JobsList extends Component { render() { const { loading, isManagementTable } = this.props; const selectionControls = { - selectable: job => job.deleting !== true, + selectable: (job) => job.deleting !== true, selectableMessage: (selectable, rowItem) => selectable === false ? i18n.translate('xpack.ml.jobsList.cannotSelectRowForJobMessage', { @@ -134,7 +134,7 @@ export class JobsList extends Component {

), - render: item => ( + render: (item) => ( this.toggleRow(item)} isDisabled={item.deleting === true} @@ -166,7 +166,7 @@ export class JobsList extends Component { truncateText: false, width: '20%', scope: 'row', - render: isManagementTable ? id => this.getJobIdLink(id) : undefined, + render: isManagementTable ? (id) => this.getJobIdLink(id) : undefined, }, { field: 'auditMessage', @@ -180,7 +180,7 @@ export class JobsList extends Component {

), - render: item => , + render: (item) => , }, { name: i18n.translate('xpack.ml.jobsList.descriptionLabel', { @@ -202,7 +202,7 @@ export class JobsList extends Component { sortable: true, truncateText: false, dataType: 'number', - render: count => toLocaleString(count), + render: (count) => toLocaleString(count), width: '10%', }, { @@ -239,7 +239,7 @@ export class JobsList extends Component { name: i18n.translate('xpack.ml.jobsList.actionsLabel', { defaultMessage: 'Actions', }), - render: item => , + render: (item) => , }, ]; @@ -344,7 +344,7 @@ export class JobsList extends Component { isExpandable={true} sorting={sorting} hasActions={true} - rowProps={item => ({ + rowProps={(item) => ({ 'data-test-subj': `mlJobListRow row-${item.id}`, })} /> diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js index 6999f4c591eac..276ff5468b1d9 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js @@ -94,7 +94,7 @@ export class JobsListView extends Component { } } - toggleRow = jobId => { + toggleRow = (jobId) => { if (this.state.itemIdToExpandedRowMap[jobId]) { const itemIdToExpandedRowMap = { ...this.state.itemIdToExpandedRowMap }; delete itemIdToExpandedRowMap[jobId]; @@ -125,7 +125,7 @@ export class JobsListView extends Component { this.setState({ itemIdToExpandedRowMap }, () => { loadFullJob(jobId) - .then(job => { + .then((job) => { const fullJobsList = { ...this.state.fullJobsList }; fullJobsList[jobId] = job; this.setState({ fullJobsList }, () => { @@ -147,7 +147,7 @@ export class JobsListView extends Component { this.setState({ itemIdToExpandedRowMap }); }); }) - .catch(error => { + .catch((error) => { console.error(error); }); }); @@ -157,32 +157,32 @@ export class JobsListView extends Component { addUpdateFunction = (id, f) => { this.updateFunctions[id] = f; }; - removeUpdateFunction = id => { + removeUpdateFunction = (id) => { delete this.updateFunctions[id]; }; - setShowEditJobFlyoutFunction = func => { + setShowEditJobFlyoutFunction = (func) => { this.showEditJobFlyout = func; }; unsetShowEditJobFlyoutFunction = () => { this.showEditJobFlyout = () => {}; }; - setShowDeleteJobModalFunction = func => { + setShowDeleteJobModalFunction = (func) => { this.showDeleteJobModal = func; }; unsetShowDeleteJobModalFunction = () => { this.showDeleteJobModal = () => {}; }; - setShowStartDatafeedModalFunction = func => { + setShowStartDatafeedModalFunction = (func) => { this.showStartDatafeedModal = func; }; unsetShowStartDatafeedModalFunction = () => { this.showStartDatafeedModal = () => {}; }; - setShowCreateWatchFlyoutFunction = func => { + setShowCreateWatchFlyoutFunction = (func) => { this.showCreateWatchFlyout = func; }; unsetShowCreateWatchFlyoutFunction = () => { @@ -192,24 +192,24 @@ export class JobsListView extends Component { return this.showCreateWatchFlyout; }; - selectJobChange = selectedJobs => { + selectJobChange = (selectedJobs) => { this.setState({ selectedJobs }); }; refreshSelectedJobs() { - const selectedJobsIds = this.state.selectedJobs.map(j => j.id); - const filteredJobIds = this.state.filteredJobsSummaryList.map(j => j.id); + const selectedJobsIds = this.state.selectedJobs.map((j) => j.id); + const filteredJobIds = this.state.filteredJobsSummaryList.map((j) => j.id); // refresh the jobs stored as selected // only select those which are also in the filtered list const selectedJobs = this.state.jobsSummaryList - .filter(j => selectedJobsIds.find(id => id === j.id)) - .filter(j => filteredJobIds.find(id => id === j.id)); + .filter((j) => selectedJobsIds.find((id) => id === j.id)) + .filter((j) => filteredJobIds.find((id) => id === j.id)); this.setState({ selectedJobs }); } - setFilters = filterClauses => { + setFilters = (filterClauses) => { const filteredJobsSummaryList = filterJobs(this.state.jobsSummaryList, filterClauses); this.setState({ filteredJobsSummaryList, filterClauses }, () => { this.refreshSelectedJobs(); @@ -235,7 +235,7 @@ export class JobsListView extends Component { try { const jobs = await ml.jobs.jobsSummary(expandedJobsIds); const fullJobsList = {}; - const jobsSummaryList = jobs.map(job => { + const jobsSummaryList = jobs.map((job) => { if (job.fullJob !== undefined) { fullJobsList[job.id] = job.fullJob; delete job.fullJob; @@ -251,18 +251,18 @@ export class JobsListView extends Component { } ); - Object.keys(this.updateFunctions).forEach(j => { + Object.keys(this.updateFunctions).forEach((j) => { this.updateFunctions[j].setState({ job: fullJobsList[j] }); }); - jobs.forEach(job => { + jobs.forEach((job) => { if (job.deleting && this.state.itemIdToExpandedRowMap[job.id]) { this.toggleRow(job.id); } }); this.isDoneRefreshing(); - if (jobsSummaryList.some(j => j.deleting === true)) { + if (jobsSummaryList.some((j) => j.deleting === true)) { // if there are some jobs in a deleting state, start polling for // deleting jobs so we can update the jobs list once the // deleting tasks are over @@ -351,7 +351,7 @@ export class JobsListView extends Component { renderJobsListComponents() { const { isRefreshing, loading, jobsSummaryList } = this.state; - const jobIds = jobsSummaryList.map(j => j.id); + const jobIds = jobsSummaryList.map((j) => j.id); return ( diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_stats_bar/jobs_stats_bar.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_stats_bar/jobs_stats_bar.js index 3c791ff658978..63c29e9df328f 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_stats_bar/jobs_stats_bar.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_stats_bar/jobs_stats_bar.js @@ -65,7 +65,7 @@ function createJobStats(jobsSummaryList) { const mlNodes = {}; let failedJobs = 0; - jobsSummaryList.forEach(job => { + jobsSummaryList.forEach((job) => { if (job.jobState === JOB_STATE.OPENED) { jobStats.open.value++; } else if (job.jobState === JOB_STATE.CLOSED) { diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/actions_menu.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/actions_menu.js index 2e530a66cd83d..a011f21fddfef 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/actions_menu.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/actions_menu.js @@ -29,7 +29,7 @@ class MultiJobActionsMenuUI extends Component { } onButtonClick = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isOpen: !prevState.isOpen, })); }; @@ -41,7 +41,7 @@ class MultiJobActionsMenuUI extends Component { }; render() { - const anyJobsDeleting = this.props.jobs.some(j => j.deleting); + const anyJobsDeleting = this.props.jobs.some((j) => j.deleting); const button = ( { + selectGroup = (group) => { this.props.selectGroup(group); }; @@ -91,11 +91,11 @@ export class GroupList extends Component { {groups.map((g, index) => (
this.handleKeyDown(event, g, index)} + onKeyDown={(event) => this.handleKeyDown(event, g, index)} key={g.id} className="group-item" onClick={() => this.selectGroup(g)} - ref={ref => this.setRef(ref, index)} + ref={(ref) => this.setRef(ref, index)} > diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js index e7b6e3a771a85..7792893305326 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js @@ -30,10 +30,10 @@ import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; function createSelectedGroups(jobs, groups) { - const jobIds = jobs.map(j => j.id); + const jobIds = jobs.map((j) => j.id); const groupCounts = {}; - jobs.forEach(j => { - j.groups.forEach(g => { + jobs.forEach((j) => { + j.groups.forEach((g) => { if (groupCounts[g] === undefined) { groupCounts[g] = 0; } @@ -42,7 +42,7 @@ function createSelectedGroups(jobs, groups) { }); const selectedGroups = groups.reduce((p, c) => { - if (c.jobIds.some(j => jobIds.includes(j))) { + if (c.jobIds.some((j) => jobIds.includes(j))) { p[c.id] = { partial: groupCounts[c.id] !== jobIds.length, }; @@ -89,7 +89,7 @@ export class GroupSelector extends Component { } else { ml.jobs .groups() - .then(groups => { + .then((groups) => { const selectedGroups = createSelectedGroups(this.props.jobs, groups); this.setState({ @@ -99,7 +99,7 @@ export class GroupSelector extends Component { groups, }); }) - .catch(error => { + .catch((error) => { console.error(error); }); } @@ -112,7 +112,7 @@ export class GroupSelector extends Component { }); }; - selectGroup = group => { + selectGroup = (group) => { const newSelectedGroups = cloneDeep(this.state.selectedGroups); if (newSelectedGroups[group.id] === undefined) { @@ -134,7 +134,7 @@ export class GroupSelector extends Component { applyChanges = () => { const { selectedGroups } = this.state; const { jobs } = this.props; - const newJobs = jobs.map(j => ({ + const newJobs = jobs.map((j) => ({ id: j.id, oldGroups: j.groups, newGroups: [], @@ -143,7 +143,7 @@ export class GroupSelector extends Component { for (const gId in selectedGroups) { if (selectedGroups.hasOwnProperty(gId)) { const group = selectedGroups[gId]; - newJobs.forEach(j => { + newJobs.forEach((j) => { if (group.partial === false || (group.partial === true && j.oldGroups.includes(gId))) { j.newGroups.push(gId); } @@ -151,10 +151,10 @@ export class GroupSelector extends Component { } } - const tempJobs = newJobs.map(j => ({ job_id: j.id, groups: j.newGroups })); + const tempJobs = newJobs.map((j) => ({ job_id: j.id, groups: j.newGroups })); ml.jobs .updateGroups(tempJobs) - .then(resp => { + .then((resp) => { let success = true; for (const jobId in resp) { // check success of each job update @@ -174,13 +174,13 @@ export class GroupSelector extends Component { console.error(resp); } }) - .catch(error => { + .catch((error) => { mlMessageBarService.notify.error(error); console.error(error); }); }; - addNewGroup = id => { + addNewGroup = (id) => { const newGroup = { id, calendarIds: [], @@ -188,7 +188,7 @@ export class GroupSelector extends Component { }; const groups = this.state.groups; - if (groups.some(g => g.id === newGroup.id) === false) { + if (groups.some((g) => g.id === newGroup.id) === false) { groups.push(newGroup); } diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/new_group_input/new_group_input.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/new_group_input/new_group_input.js index f92f9c2fa4a3d..6a97d32f8cf0c 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/new_group_input/new_group_input.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/new_group_input/new_group_input.js @@ -35,7 +35,7 @@ export class NewGroupInput extends Component { }; } - changeTempNewGroup = e => { + changeTempNewGroup = (e) => { const tempNewGroupName = e.target.value; let groupsValidationError = ''; @@ -59,7 +59,7 @@ export class NewGroupInput extends Component { }); }; - newGroupKeyPress = e => { + newGroupKeyPress = (e) => { if ( e.keyCode === keyCodes.ENTER && this.state.groupsValidationError === '' && diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js index 3ea25fb2f44eb..9ce15fb881bd8 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js @@ -62,15 +62,15 @@ export class StartDatafeedModal extends Component { } } - setStartTime = time => { + setStartTime = (time) => { this.setState({ startTime: time }); }; - setEndTime = time => { + setEndTime = (time) => { this.setState({ endTime: time }); }; - setCreateWatch = e => { + setCreateWatch = (e) => { this.setState({ createWatch: e.target.checked }); }; @@ -78,7 +78,7 @@ export class StartDatafeedModal extends Component { this.setState({ isModalVisible: false }); }; - setTimeRangeValid = timeRangeValid => { + setTimeRangeValid = (timeRangeValid) => { this.setState({ timeRangeValid }); }; @@ -130,7 +130,7 @@ export class StartDatafeedModal extends Component { now, timeRangeValid, } = this.state; - const startableJobs = jobs !== undefined ? jobs.filter(j => j.hasDatafeed) : []; + const startableJobs = jobs !== undefined ? jobs.filter((j) => j.hasDatafeed) : []; // disable start button if the start and end times are the same const startDisabled = timeRangeValid === false || (startTime !== undefined && startTime === endTime); @@ -222,6 +222,6 @@ StartDatafeedModal.propTypes = { }; function getLowestLatestTime(jobs) { - const times = jobs.map(j => j.latestTimestampSortValue); + const times = jobs.map((j) => j.latestTimestampSortValue); return moment(Math.min(...times)); } diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/time_range_selector/time_range_selector.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/time_range_selector/time_range_selector.js index d30ec83acdede..55c87bbc90b10 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/time_range_selector/time_range_selector.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/time_range_selector/time_range_selector.js @@ -28,7 +28,7 @@ export class TimeRangeSelector extends Component { this.now = this.props.now; } - setStartTab = tab => { + setStartTab = (tab) => { this.setState({ startTab: tab }); switch (tab) { case 0: @@ -42,7 +42,7 @@ export class TimeRangeSelector extends Component { } }; - setEndTab = tab => { + setEndTab = (tab) => { this.setState({ endTab: tab }); switch (tab) { case 0: @@ -56,11 +56,11 @@ export class TimeRangeSelector extends Component { } }; - setStartTime = time => { + setStartTime = (time) => { this.props.setStartTime(time); }; - setEndTime = time => { + setEndTime = (time) => { this.props.setEndTime(time); }; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js index 4f77004b91f99..0a3728c7351b5 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js @@ -20,44 +20,44 @@ export function loadFullJob(jobId) { return new Promise((resolve, reject) => { ml.jobs .jobs(jobId) - .then(jobs => { + .then((jobs) => { if (jobs.length) { resolve(jobs[0]); } else { throw new Error(`Could not find job ${jobId}`); } }) - .catch(error => { + .catch((error) => { reject(error); }); }); } export function isStartable(jobs) { - return jobs.some(j => j.datafeedState === DATAFEED_STATE.STOPPED); + return jobs.some((j) => j.datafeedState === DATAFEED_STATE.STOPPED); } export function isStoppable(jobs) { return jobs.some( - j => j.datafeedState === DATAFEED_STATE.STARTED || j.datafeedState === DATAFEED_STATE.STARTING + (j) => j.datafeedState === DATAFEED_STATE.STARTED || j.datafeedState === DATAFEED_STATE.STARTING ); } export function isClosable(jobs) { return jobs.some( - j => j.datafeedState === DATAFEED_STATE.STOPPED && j.jobState !== JOB_STATE.CLOSED + (j) => j.datafeedState === DATAFEED_STATE.STOPPED && j.jobState !== JOB_STATE.CLOSED ); } export function forceStartDatafeeds(jobs, start, end, finish = () => {}) { - const datafeedIds = jobs.filter(j => j.hasDatafeed).map(j => j.datafeedId); + const datafeedIds = jobs.filter((j) => j.hasDatafeed).map((j) => j.datafeedId); mlJobService .forceStartDatafeeds(datafeedIds, start, end) - .then(resp => { + .then((resp) => { showResults(resp, DATAFEED_STATE.STARTED); finish(); }) - .catch(error => { + .catch((error) => { mlMessageBarService.notify.error(error); const toastNotifications = getToastNotifications(); toastNotifications.addDanger( @@ -71,14 +71,14 @@ export function forceStartDatafeeds(jobs, start, end, finish = () => {}) { } export function stopDatafeeds(jobs, finish = () => {}) { - const datafeedIds = jobs.filter(j => j.hasDatafeed).map(j => j.datafeedId); + const datafeedIds = jobs.filter((j) => j.hasDatafeed).map((j) => j.datafeedId); mlJobService .stopDatafeeds(datafeedIds) - .then(resp => { + .then((resp) => { showResults(resp, DATAFEED_STATE.STOPPED); finish(); }) - .catch(error => { + .catch((error) => { mlMessageBarService.notify.error(error); const toastNotifications = getToastNotifications(); toastNotifications.addDanger( @@ -156,7 +156,7 @@ function showResults(resp, action) { ); if (failures.length > 0) { - failures.forEach(f => { + failures.forEach((f) => { mlMessageBarService.notify.error(f.result.error); toastNotifications.addDanger( i18n.translate('xpack.ml.jobsList.actionFailedNotificationMessage', { @@ -228,14 +228,14 @@ export async function cloneJob(jobId) { } export function closeJobs(jobs, finish = () => {}) { - const jobIds = jobs.map(j => j.id); + const jobIds = jobs.map((j) => j.id); mlJobService .closeJobs(jobIds) - .then(resp => { + .then((resp) => { showResults(resp, JOB_STATE.CLOSED); finish(); }) - .catch(error => { + .catch((error) => { mlMessageBarService.notify.error(error); const toastNotifications = getToastNotifications(); toastNotifications.addDanger( @@ -249,14 +249,14 @@ export function closeJobs(jobs, finish = () => {}) { } export function deleteJobs(jobs, finish = () => {}) { - const jobIds = jobs.map(j => j.id); + const jobIds = jobs.map((j) => j.id); mlJobService .deleteJobs(jobIds) - .then(resp => { + .then((resp) => { showResults(resp, JOB_STATE.DELETED); finish(); }) - .catch(error => { + .catch((error) => { mlMessageBarService.notify.error(error); const toastNotifications = getToastNotifications(); toastNotifications.addDanger( @@ -284,7 +284,7 @@ export function filterJobs(jobs, clauses) { return p; }, {}); - clauses.forEach(c => { + clauses.forEach((c) => { // the search term could be negated with a minus, e.g. -bananas const bool = c.match === 'must'; let js = []; @@ -295,14 +295,14 @@ export function filterJobs(jobs, clauses) { // if the term has been negated, AND the matches if (bool === true) { js = jobs.filter( - job => + (job) => stringMatch(job.id, c.value) === bool || stringMatch(job.description, c.value) === bool || stringMatch(job.memory_status, c.value) === bool ); } else { js = jobs.filter( - job => + (job) => stringMatch(job.id, c.value) === bool && stringMatch(job.description, c.value) === bool && stringMatch(job.memory_status, c.value) === bool @@ -312,18 +312,18 @@ export function filterJobs(jobs, clauses) { // filter other clauses, i.e. the toggle group buttons if (Array.isArray(c.value)) { // the groups value is an array of group ids - js = jobs.filter(job => jobProperty(job, c.field).some(g => c.value.indexOf(g) >= 0)); + js = jobs.filter((job) => jobProperty(job, c.field).some((g) => c.value.indexOf(g) >= 0)); } else { - js = jobs.filter(job => jobProperty(job, c.field) === c.value); + js = jobs.filter((job) => jobProperty(job, c.field) === c.value); } } - js.forEach(j => matches[j.id].count++); + js.forEach((j) => matches[j.id].count++); }); // loop through the matches and return only those jobs which have match all the clauses const filteredJobs = []; - each(matches, m => { + each(matches, (m) => { if (m.count >= clauses.length) { filteredJobs.push(m.job); } @@ -369,7 +369,7 @@ function jobProperty(job, prop) { function getUrlVars(url) { const vars = {}; - url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(_, key, value) { + url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (_, key, value) { vars[key] = value; }); return vars; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/jobs.tsx b/x-pack/plugins/ml/public/application/jobs/jobs_list/jobs.tsx index 103db5707eed5..d738c8aa3d615 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/jobs.tsx +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/jobs.tsx @@ -18,7 +18,7 @@ interface JobsPageProps { lastRefresh?: number; } -export const JobsPage: FC = props => { +export const JobsPage: FC = (props) => { return (
diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/components/job_groups_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/common/components/job_groups_input.tsx index 131e313e7c9e5..06317375d8bc6 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/components/job_groups_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/components/job_groups_input.tsx @@ -20,18 +20,18 @@ export interface JobGroupsInputProps { export const JobGroupsInput: FC = memo( ({ existingGroups, selectedGroups, onChange, validation }) => { - const options = existingGroups.map(g => ({ + const options = existingGroups.map((g) => ({ label: g, color: tabColor(g), })); - const selectedOptions = selectedGroups.map(g => ({ + const selectedOptions = selectedGroups.map((g) => ({ label: g, color: tabColor(g), })); function onChangeCallback(optionsIn: EuiComboBoxOptionOption[]) { - onChange(optionsIn.map(g => g.label)); + onChange(optionsIn.map((g) => g.label)); } function onCreateGroup(input: string, flattenedOptions: EuiComboBoxOptionOption[]) { @@ -48,7 +48,7 @@ export const JobGroupsInput: FC = memo( if ( flattenedOptions.findIndex( - option => option.label.trim().toLowerCase() === normalizedSearchValue + (option) => option.label.trim().toLowerCase() === normalizedSearchValue ) === -1 ) { options.push(newGroup); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts index 9fa0eb901c61f..ad7197cc2478f 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts @@ -193,7 +193,7 @@ export class AdvancedJobCreator extends JobCreator { const detectors = getRichDetectors(job, datafeed, this.additionalFields, true); // keep track of the custom rules for each detector - const customRules = this._detectors.map(d => d.custom_rules); + const customRules = this._detectors.map((d) => d.custom_rules); this.removeAllDetectors(); this._richDetectors.length = 0; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts index ca982304bd4f3..89a0c45828737 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts @@ -617,7 +617,7 @@ export class JobCreator { } if (this._job_config.analysis_config.influencers !== undefined) { - this._job_config.analysis_config.influencers.forEach(i => this.addInfluencer(i)); + this._job_config.analysis_config.influencers.forEach((i) => this.addInfluencer(i)); } if ( @@ -630,7 +630,7 @@ export class JobCreator { this._scriptFields = []; if (this._datafeed_config.script_fields !== undefined) { - this._scriptFields = Object.keys(this._datafeed_config.script_fields).map(f => ({ + this._scriptFields = Object.keys(this._datafeed_config.script_fields).map((f) => ({ id: f, name: f, type: ES_FIELD_TYPES.KEYWORD, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/multi_metric_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/multi_metric_job_creator.ts index 10d306c37d114..95141f31cdea6 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/multi_metric_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/multi_metric_job_creator.ts @@ -49,7 +49,7 @@ export class MultiMetricJobCreator extends JobCreator { } public removeSplitField() { - this._detectors.forEach(d => { + this._detectors.forEach((d) => { delete d.partition_field_name; }); } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/population_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/population_job_creator.ts index 276f16c9e76b7..de6cc855e4963 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/population_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/population_job_creator.ts @@ -78,7 +78,7 @@ export class PopulationJobCreator extends JobCreator { // remove over field from all detectors public removeSplitField() { - this._detectors.forEach(d => { + this._detectors.forEach((d) => { delete d.over_field_name; }); } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/general.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/general.ts index 6d061c2df9ad9..92e65e580fc01 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/general.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/general.ts @@ -35,7 +35,7 @@ const getFieldByIdFactory = (additionalFields: Field[]) => (id: string) => { if (id === MLCATEGORY) { field = mlCategory; } else if (additionalFields.length) { - field = additionalFields.find(f => f.id === id) || null; + field = additionalFields.find((f) => f.id === id) || null; } } return field; @@ -52,7 +52,7 @@ export function getRichDetectors( const getFieldById = getFieldByIdFactory(additionalFields); - return detectors.map(d => { + return detectors.map((d) => { let field = null; let byField = null; let overField = null; @@ -86,13 +86,13 @@ export function getRichDetectors( export function createFieldOptions(fields: Field[], additionalFields: Field[]) { return [ ...fields - .filter(f => f.id !== EVENT_RATE_FIELD_ID) - .map(f => ({ + .filter((f) => f.id !== EVENT_RATE_FIELD_ID) + .map((f) => ({ label: f.name, })), ...additionalFields - .filter(f => fields.some(f2 => f2.id === f.id) === false) - .map(f => ({ + .filter((f) => fields.some((f2) => f2.id === f.id) === false) + .map((f) => ({ label: f.id, })), ].sort((a, b) => a.label.localeCompare(b.label)); @@ -150,7 +150,7 @@ function getDetectors(job: Job, datafeed: Datafeed) { } else { // all other detectors. detectors = processFieldlessAggs(detectors); - detectors = detectors.map(d => { + detectors = detectors.map((d) => { switch (d.function) { // if sparse data functions were used, replace them with their non-sparse versions // the sparse data flag has already been determined and set, so this information is not being lost. @@ -182,7 +182,7 @@ function getDetectors(job: Job, datafeed: Datafeed) { // if a fieldless function is used, add EVENT_RATE_FIELD_ID as its field function processFieldlessAggs(detectors: Detector[]) { - return detectors.map(d => { + return detectors.map((d) => { switch (d.function) { case ML_JOB_AGGREGATION.COUNT: case ML_JOB_AGGREGATION.HIGH_COUNT: @@ -287,7 +287,7 @@ export function advancedStartDatafeed(jobCreator: JobCreatorType) { } export function aggFieldPairsCanBeCharted(afs: AggFieldPair[]) { - return afs.some(a => a.agg.dslName === null) === false; + return afs.some((a) => a.agg.dslName === null) === false; } export function getJobCreatorTitle(jobCreator: JobCreatorType) { @@ -324,7 +324,7 @@ export function collectAggs(o: any, aggFields: Field[]) { for (const i in o) { if (o[i] !== null && typeof o[i] === 'object') { if (i === 'aggregations' || i === 'aggs') { - Object.keys(o[i]).forEach(k => { + Object.keys(o[i]).forEach((k) => { if (k !== 'aggregations' && k !== 'aggs') { aggFields.push({ id: k, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts index eb563e8b36107..0011c88d2b524 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts @@ -45,7 +45,7 @@ export const modelMemoryEstimatorProvider = ( get updates$(): Observable { return combineLatest([ jobCreator.wizardInitialized$.pipe( - skipWhile(wizardInitialized => wizardInitialized === false) + skipWhile((wizardInitialized) => wizardInitialized === false) ), modelMemoryCheck$, ]).pipe( @@ -58,10 +58,10 @@ export const modelMemoryEstimatorProvider = ( distinctUntilChanged(isEqual), // don't call the endpoint with invalid payload filter(() => jobValidator.isModelMemoryEstimationPayloadValid), - switchMap(payload => { + switchMap((payload) => { return ml.calculateModelMemoryLimit$(payload).pipe( pluck('modelMemoryLimit'), - catchError(error => { + catchError((error) => { // eslint-disable-next-line no-console console.error('Model memory limit could not be calculated', error.body); error$.next(error.body); @@ -115,7 +115,7 @@ export const useModelMemoryEstimator = ( ); subscription.add( - modelMemoryEstimator.error$.subscribe(error => { + modelMemoryEstimator.error$.subscribe((error) => { notifications.toasts.addWarning({ title: i18n.translate('xpack.ml.newJob.wizard.estimateModelMemoryError', { defaultMessage: 'Model memory limit could not be calculated', diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/job_runner.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/job_runner.ts index 2571fe70f4a83..9afc6e5bfca93 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/job_runner.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/job_runner.ts @@ -81,7 +81,7 @@ export class JobRunner { // link the _subscribers list from the JobCreator // to the progress BehaviorSubject. const subscriptions = - pollProgress === true ? this._subscribers.map(s => this._progress$.subscribe(s)) : []; + pollProgress === true ? this._subscribers.map((s) => this._progress$.subscribe(s)) : []; await this.openJob(); const { started } = await mlJobService.startDatafeed( @@ -118,7 +118,7 @@ export class JobRunner { // than the end date supplied to the datafeed this._progress$.next(100); // unsubscribe everyone - subscriptions.forEach(s => s.unsubscribe()); + subscriptions.forEach((s) => s.unsubscribe()); } }; // wait for the first check to run and then return success. diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/job_validator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/job_validator.ts index a942603d7f9d4..242a643ddd3ce 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/job_validator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/job_validator.ts @@ -103,7 +103,7 @@ export class JobValidator { this._asyncValidators$ = [cardinalityValidator(this._jobCreatorSubject$)]; this._asyncValidatorsResult$ = combineLatest(this._asyncValidators$).pipe( - map(res => { + map((res) => { return res.reduce((acc, curr) => { return { ...acc, @@ -124,7 +124,7 @@ export class JobValidator { ...asyncValidatorsResult, }; }), - tap(latestValidationResult => { + tap((latestValidationResult) => { this.latestValidationResult = latestValidationResult; }) ); @@ -168,7 +168,7 @@ export class JobValidator { private _resetBasicValidations() { this._validationSummary.basic = true; - Object.values(this._basicValidations).forEach(v => { + Object.values(this._basicValidations).forEach((v) => { v.valid = true; delete v.message; }); @@ -214,7 +214,7 @@ export class JobValidator { } private _isOverallBasicValid() { - return Object.values(this._basicValidations).some(v => v.valid === false) === false; + return Object.values(this._basicValidations).some((v) => v.valid === false) === false; } public get validationSummary(): ValidationSummary { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/util.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/util.ts index 2ab58714830e3..d5cc1cf535a78 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/util.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/util.ts @@ -189,16 +189,16 @@ export function checkForExistingJobAndGroupIds( } // check that groups that have been newly added in this job do not already exist as job ids - const newGroups = groupIds.filter(g => !existingJobsAndGroups.groupIds.includes(g)); - if (existingJobsAndGroups.jobIds.some(g => newGroups.includes(g))) { + const newGroups = groupIds.filter((g) => !existingJobsAndGroups.groupIds.includes(g)); + if (existingJobsAndGroups.jobIds.some((g) => newGroups.includes(g))) { messages.push({ id: 'job_group_id_already_exists' }); } return { messages, valid: messages.length === 0, - contains: (id: string) => messages.some(m => id === m.id), - find: (id: string) => messages.find(m => id === m.id), + contains: (id: string) => messages.some((m) => id === m.id), + find: (id: string) => messages.find((m) => id === m.id), }; } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts index ea7ba21699f60..eabf5588579c5 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts @@ -41,10 +41,10 @@ export function cardinalityValidator( ): Observable { return jobCreator$.pipe( // Perform a cardinality check only with enabled model plot. - filter(jobCreator => { + filter((jobCreator) => { return jobCreator?.modelPlot; }), - map(jobCreator => { + map((jobCreator) => { return { jobCreator, analysisConfigString: JSON.stringify(jobCreator.jobConfig.analysis_config), @@ -60,7 +60,7 @@ export function cardinalityValidator( datafeed_config: jobCreator.datafeedConfig, } as CombinedJob); }), - map(validationResults => { + map((validationResults) => { for (const validationResult of validationResults) { if (isCardinalityModelPlotHigh(validationResult)) { return { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts index 5048f44586a38..110b031cd1dc0 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts @@ -236,7 +236,7 @@ export class ResultsLoader { const anomalies: Record = {}; Object.entries(resp.results).forEach(([dtrIdx, results]) => { anomalies[+dtrIdx] = results.map( - r => ({ ...r, severity: getSeverityType(r.value as number) } as Anomaly) + (r) => ({ ...r, severity: getSeverityType(r.value as number) } as Anomaly) ); }); return anomalies; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/charts/common/anomalies.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/charts/common/anomalies.tsx index 1596177daaf03..ab2098ca27135 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/charts/common/anomalies.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/charts/common/anomalies.tsx @@ -48,7 +48,7 @@ function splitAnomalySeverities(anomalies: Anomaly[]) { unknown: [], low: [], }; - anomalies.forEach(a => { + anomalies.forEach((a) => { if (a.value !== 0) { severities[a.severity].push({ dataValue: a.time }); } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/common/model_memory_limit/model_memory_limit_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/common/model_memory_limit/model_memory_limit_input.tsx index 54fb19d868cdc..3909a7a31fb2f 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/common/model_memory_limit/model_memory_limit_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/common/model_memory_limit/model_memory_limit_input.tsx @@ -44,7 +44,7 @@ export const ModelMemoryLimitInput: FC = () => { setModelMemoryLimit(e.target.value)} + onChange={(e) => setModelMemoryLimit(e.target.value)} isInvalid={validation.valid === false} data-test-subj="mlJobWizardInputModelMemoryLimit" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/frequency/frequency_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/frequency/frequency_input.tsx index 6328366626894..7a75a17a870c9 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/frequency/frequency_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/frequency/frequency_input.tsx @@ -50,7 +50,7 @@ export const FrequencyInput: FC = () => { setFrequency(e.target.value)} + onChange={(e) => setFrequency(e.target.value)} isInvalid={validation.valid === false} data-test-subj="mlJobWizardInputFrequency" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/query_delay/query_delay_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/query_delay/query_delay_input.tsx index 0e6dd81fb91a9..22573fb215cea 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/query_delay/query_delay_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/query_delay/query_delay_input.tsx @@ -36,7 +36,7 @@ export const QueryDelayInput: FC = () => { setQueryDelay(e.target.value)} + onChange={(e) => setQueryDelay(e.target.value)} isInvalid={validation.valid === false} data-test-subj="mlJobWizardInputQueryDelay" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/scroll_size/scroll_size_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/scroll_size/scroll_size_input.tsx index ea03d16fcccca..508811731ae3e 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/scroll_size/scroll_size_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/scroll_size/scroll_size_input.tsx @@ -41,7 +41,7 @@ export const ScrollSizeInput: FC = () => { min={0} placeholder={scrollSizeDefault} value={scrollSizeString === '' ? scrollSizeString : +scrollSizeString} - onChange={e => setScrollSize(e.target.value)} + onChange={(e) => setScrollSize(e.target.value)} isInvalid={validation.valid === false} data-test-subj="mlJobWizardInputScrollSize" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/additional_section/components/calendars/calendars_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/additional_section/components/calendars/calendars_selection.tsx index 597fe42543301..60b034b516939 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/additional_section/components/calendars/calendars_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/additional_section/components/calendars/calendars_selection.tsx @@ -37,10 +37,10 @@ export const CalendarsSelection: FC = () => { async function loadCalendars() { setIsLoading(true); const calendars = (await ml.calendars()).filter( - c => c.job_ids.includes(GLOBAL_CALENDAR) === false + (c) => c.job_ids.includes(GLOBAL_CALENDAR) === false ); - setOptions(calendars.map(c => ({ label: c.calendar_id, value: c }))); - setSelectedOptions(selectedCalendars.map(c => ({ label: c.calendar_id, value: c }))); + setOptions(calendars.map((c) => ({ label: c.calendar_id, value: c }))); + setSelectedOptions(selectedCalendars.map((c) => ({ label: c.calendar_id, value: c }))); setIsLoading(false); } @@ -58,9 +58,9 @@ export const CalendarsSelection: FC = () => { options, selectedOptions, isLoading, - onChange: optionsIn => { + onChange: (optionsIn) => { setSelectedOptions(optionsIn); - setSelectedCalendars(optionsIn.map(o => o.value!)); + setSelectedCalendars(optionsIn.map((o) => o.value!)); }, }; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/advanced_section/components/model_plot/model_plot_switch.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/advanced_section/components/model_plot/model_plot_switch.tsx index a034bdcc2900f..b63f3004efdc5 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/advanced_section/components/model_plot/model_plot_switch.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/advanced_section/components/model_plot/model_plot_switch.tsx @@ -29,7 +29,7 @@ export const ModelPlotSwitch: FC = () => { // and a rare detector is being used. const isRareCategoryJob = isCategorizationJobCreator(jobCreator) && - jobCreator.aggregations.some(agg => aggs.includes(agg.id)); + jobCreator.aggregations.some((agg) => aggs.includes(agg.id)); setEnabled(isRareCategoryJob === false); }, [jobCreatorUpdated]); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/groups/groups_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/groups/groups_input.tsx index 841ccfdce0958..a693127e07f48 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/groups/groups_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/groups/groups_input.tsx @@ -35,7 +35,7 @@ export const GroupsInput: FC = () => { })); function onChange(optionsIn: EuiComboBoxOptionOption[]) { - setSelectedGroups(optionsIn.map(g => g.label)); + setSelectedGroups(optionsIn.map((g) => g.label)); } function onCreateGroup(input: string, flattenedOptions: EuiComboBoxOptionOption[]) { @@ -52,13 +52,13 @@ export const GroupsInput: FC = () => { if ( flattenedOptions.findIndex( - option => option.label.trim().toLowerCase() === normalizedSearchValue + (option) => option.label.trim().toLowerCase() === normalizedSearchValue ) === -1 ) { options.push(newGroup); } - setSelectedGroups([...selectedOptions, newGroup].map(g => g.label)); + setSelectedGroups([...selectedOptions, newGroup].map((g) => g.label)); } useEffect(() => { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_description/job_description_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_description/job_description_input.tsx index 1c027b6c81ff9..bfddae0e79ea1 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_description/job_description_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_description/job_description_input.tsx @@ -22,7 +22,7 @@ export const JobDescriptionInput: FC = () => { setJobDescription(e.target.value)} + onChange={(e) => setJobDescription(e.target.value)} data-test-subj="mlJobWizardInputJobDescription" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_id/job_id_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_id/job_id_input.tsx index c77024a4d329f..43468d83844ed 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_id/job_id_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/job_id/job_id_input.tsx @@ -33,7 +33,7 @@ export const JobIdInput: FC = () => { setJobId(e.target.value)} + onChange={(e) => setJobId(e.target.value)} isInvalid={validation.valid === false} data-test-subj="mlJobWizardInputJobId" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx index 9e784a20c4f5f..7d71583977204 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx @@ -91,7 +91,7 @@ export const AdvancedDetectorModal: FC = ({ // list of aggregation combobox options. const aggOptions: EuiComboBoxOptionOption[] = aggs - .filter(agg => filterAggs(agg, usingScriptFields)) + .filter((agg) => filterAggs(agg, usingScriptFields)) .map(createAggOption); // fields available for the selected agg @@ -110,7 +110,7 @@ export const AdvancedDetectorModal: FC = ({ ...createMlcategoryFieldOption(jobCreator.categorizationFieldName), ].sort(comboBoxOptionsSort); - const eventRateField = fields.find(f => f.id === EVENT_RATE_FIELD_ID); + const eventRateField = fields.find((f) => f.id === EVENT_RATE_FIELD_ID); const onOptionChange = (func: (p: EuiComboBoxOptionOption) => any) => ( selectedOptions: EuiComboBoxOptionOption[] @@ -119,15 +119,15 @@ export const AdvancedDetectorModal: FC = ({ }; function getAgg(title: string) { - return aggs.find(a => a.id === title) || null; + return aggs.find((a) => a.id === title) || null; } function getField(title: string) { if (title === mlCategory.id) { return mlCategory; } return ( - fields.find(f => f.id === title) || - jobCreator.additionalFields.find(f => f.id === title) || + fields.find((f) => f.id === title) || + jobCreator.additionalFields.find((f) => f.id === title) || null ); } @@ -301,7 +301,7 @@ export const AdvancedDetectorModal: FC = ({ fullWidth={true} placeholder={descriptionPlaceholder} value={descriptionOption} - onChange={e => setDescriptionOption(e.target.value)} + onChange={(e) => setDescriptionOption(e.target.value)} data-test-subj="mlAdvancedDetectorDescriptionInput" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/agg_select/agg_select.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/agg_select/agg_select.tsx index e4eccb5f01423..7f108da217035 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/agg_select/agg_select.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/agg_select/agg_select.tsx @@ -42,20 +42,20 @@ export const AggSelect: FC = ({ fields, changeHandler, selectedOptions, r // so they can be removed from the dropdown list const removeLabels = removeOptions.map(createLabel); - const options: EuiComboBoxOptionOption[] = fields.map(f => { + const options: EuiComboBoxOptionOption[] = fields.map((f) => { const aggOption: DropDownOption = { label: f.name, options: [] }; if (typeof f.aggs !== 'undefined') { aggOption.options = f.aggs - .filter(a => a.dslName !== null) // don't include aggs which have no ES equivalent + .filter((a) => a.dslName !== null) // don't include aggs which have no ES equivalent .map( - a => + (a) => ({ label: `${a.title}(${f.name})`, agg: a, field: f, } as DropDownLabel) ) - .filter(o => removeLabels.includes(o.label) === false); + .filter((o) => removeLabels.includes(o.label) === false); } return aggOption; }); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span/bucket_span_input.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span/bucket_span_input.tsx index 35c1cfa9ce65d..740a8614ee205 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span/bucket_span_input.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span/bucket_span_input.tsx @@ -23,7 +23,7 @@ export const BucketSpanInput: FC = ({ bucketSpan, setBucketSpan, isInvali defaultMessage: 'Bucket span', })} value={bucketSpan} - onChange={e => setBucketSpan(e.target.value)} + onChange={(e) => setBucketSpan(e.target.value)} isInvalid={isInvalid} data-test-subj="mlJobWizardInputBucketSpan" /> diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/bucket_span_estimator.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/bucket_span_estimator.tsx index 72ebbb0b438a2..2be0f67f3944f 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/bucket_span_estimator.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/bucket_span_estimator.tsx @@ -35,7 +35,7 @@ export const BucketSpanEstimator: FC = ({ setEstimating }) => { function checkIsUsingMlCategory() { return ( isAdvancedJobCreator(jobCreator) && - jobCreator.detectors.some(d => { + jobCreator.detectors.some((d) => { if ( d.partition_field_name === MLCATEGORY || d.over_field_name === MLCATEGORY || diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts index 5064ba9df9bee..0ec3b609b604f 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts @@ -29,12 +29,12 @@ export function useEstimateBucketSpan() { const [status, setStatus] = useState(ESTIMATE_STATUS.NOT_RUNNING); const data: BucketSpanEstimatorData = { - aggTypes: jobCreator.aggregations.map(a => a.dslName), + aggTypes: jobCreator.aggregations.map((a) => a.dslName), duration: { start: jobCreator.start, end: jobCreator.end, }, - fields: jobCreator.fields.map(f => (f.id === EVENT_RATE_FIELD_ID ? null : f.id)), + fields: jobCreator.fields.map((f) => (f.id === EVENT_RATE_FIELD_ID ? null : f.id)), index: mlContext.currentIndexPattern.title, query: mlContext.combinedQuery, splitField: undefined, @@ -47,7 +47,7 @@ export function useEstimateBucketSpan() { ) { data.splitField = jobCreator.splitField.id; } else if (isAdvancedJobCreator(jobCreator)) { - jobCreator.richDetectors.some(d => { + jobCreator.richDetectors.some((d) => { if (d.partitionField !== null) { data.splitField = d.partitionField.id; return true; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/examples_valid_callout.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/examples_valid_callout.tsx index f139a8013725a..0ca8320eec859 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/examples_valid_callout.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/examples_valid_callout.tsx @@ -123,7 +123,7 @@ const AllValidationChecks: FC<{ validationChecks: FieldExampleCheck[] }> = ({ validationChecks, }) => { const list: EuiListGroupItemProps[] = Object.keys(VALIDATION_CHECK_DESCRIPTION).map((k, i) => { - const failedCheck = validationChecks.find(vc => vc.id === i); + const failedCheck = validationChecks.find((vc) => vc.id === i); if ( failedCheck !== undefined && failedCheck?.valid !== CATEGORY_EXAMPLES_VALIDATION_STATUS.VALID diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/top_categories.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/top_categories.tsx index 227c93dc2d86b..07ae18ae2f810 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/top_categories.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/top_categories.tsx @@ -27,7 +27,7 @@ export const TopCategories: FC = () => { async function loadTopCats() { const results = await ml.jobs.topCategories(jobCreator.jobId, NUMBER_OF_CATEGORY_EXAMPLES); setTableRow( - results.categories.map(c => ({ + results.categories.map((c) => ({ count: c.count, example: c.category.examples?.length ? c.category.examples[0] : '', })) diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers.tsx index c55bdeef4dde8..f80827da03a19 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers.tsx @@ -24,7 +24,7 @@ export const Influencers: FC = () => { useEffect(() => { jobCreator.removeAllInfluencers(); - influencers.forEach(i => jobCreator.addInfluencer(i)); + influencers.forEach((i) => jobCreator.addInfluencer(i)); jobCreatorUpdate(); }, [influencers.join()]); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers_select.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers_select.tsx index 25c924ee0b42f..f3e2e22c871e6 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers_select.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/influencers/influencers_select.tsx @@ -27,10 +27,10 @@ export const InfluencersSelect: FC = ({ fields, changeHandler, selectedIn ...createMlcategoryFieldOption(jobCreator.categorizationFieldName), ]; - const selection: EuiComboBoxOptionOption[] = selectedInfluencers.map(i => ({ label: i })); + const selection: EuiComboBoxOptionOption[] = selectedInfluencers.map((i) => ({ label: i })); function onChange(selectedOptions: EuiComboBoxOptionOption[]) { - changeHandler(selectedOptions.map(o => o.label)); + changeHandler(selectedOptions.map((o) => o.label)); } return ( diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx index cbd7c0ab72ffc..684cb5b4e0dda 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/multi_metric_view/metric_selection.tsx @@ -76,7 +76,7 @@ export const MultiMetricDetectors: FC = ({ setIsValid }) => { // watch for changes in detector list length useEffect(() => { jobCreator.removeAllDetectors(); - aggFieldPairList.forEach(pair => { + aggFieldPairList.forEach((pair) => { jobCreator.addDetector(pair.agg, pair.field); }); jobCreatorUpdate(); @@ -108,7 +108,7 @@ export const MultiMetricDetectors: FC = ({ setIsValid }) => { chartLoader .loadFieldExampleValues(splitField) .then(setFieldValues) - .catch(error => { + .catch((error) => { mlMessageBarService.notify.error(error); }); } else { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx index 70a3d1c7d616c..e5f5ba48900d9 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection.tsx @@ -49,7 +49,7 @@ export const PopulationDetectors: FC = ({ setIsValid }) => { const [splitField, setSplitField] = useState(jobCreator.splitField); const [fieldValuesPerDetector, setFieldValuesPerDetector] = useState({}); const [byFieldsUpdated, setByFieldsUpdated] = useReducer<(s: number, action: any) => number>( - s => s + 1, + (s) => s + 1, 0 ); const [pageReady, setPageReady] = useState(false); @@ -203,7 +203,7 @@ export const PopulationDetectors: FC = ({ setIsValid }) => { function allDataReady() { let ready = aggFieldPairList.length > 0; - aggFieldPairList.forEach(af => { + aggFieldPairList.forEach((af) => { if (af.by !== undefined && af.by.field !== null) { // if a by field is set, it's only ready when the value is loaded ready = ready && af.by.value !== null; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx index 4474a2d6b5413..06f7092e8ac06 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/population_view/metric_selection_summary.tsx @@ -125,7 +125,7 @@ export const PopulationDetectorsSummary: FC = () => { function allDataReady() { let ready = aggFieldPairList.length > 0; - aggFieldPairList.forEach(af => { + aggFieldPairList.forEach((af) => { if (af.by !== undefined && af.by.field !== null) { // if a by field is set, it's only ready when the value is loaded ready = ready && af.by.value !== null; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/sparse_data/sparse_data_switch.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/sparse_data/sparse_data_switch.tsx index 2884bce4d89ad..faa505fae22a1 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/sparse_data/sparse_data_switch.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/sparse_data/sparse_data_switch.tsx @@ -24,7 +24,7 @@ export const SparseDataSwitch: FC = () => { useEffect(() => { const aggs = [ES_AGGREGATION.COUNT, ES_AGGREGATION.SUM]; const isCountOrSum = jobCreator.aggregations.some( - agg => agg.dslName !== null && aggs.includes(agg.dslName) + (agg) => agg.dslName !== null && aggs.includes(agg.dslName) ); setEnabled(isCountOrSum); if (isCountOrSum === false && sparseData === true) { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_cards/split_cards.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_cards/split_cards.tsx index 118923aa203e1..184a851a8d078 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_cards/split_cards.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_cards/split_cards.tsx @@ -48,7 +48,7 @@ export const SplitCards: FC = memo( if (animate === true) { setTimeout(() => { - panels.forEach(p => (p.panel.style.marginBottom = `${p.marginBottom}px`)); + panels.forEach((p) => (p.panel.style.marginBottom = `${p.marginBottom}px`)); }, 100); } @@ -68,7 +68,7 @@ export const SplitCards: FC = memo( ...(animate ? { transition: 'margin 0.5s' } : {}), }; return ( -
storePanels(ref, marginBottom)} style={style}> +
storePanels(ref, marginBottom)} style={style}> { const sf = jobCreator.splitField; if (sf !== null) { - setFields(allCategoryFields.filter(f => f.name !== sf.name)); + setFields(allCategoryFields.filter((f) => f.name !== sf.name)); } else { setFields(allCategoryFields); } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_field/split_field_select.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_field/split_field_select.tsx index 816614fb2a772..af9644f4770d3 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_field/split_field_select.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/split_field/split_field_select.tsx @@ -32,7 +32,7 @@ export const SplitFieldSelect: FC = ({ placeholder, }) => { const options: EuiComboBoxOptionOption[] = fields.map( - f => + (f) => ({ label: f.name, field: f, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/new_job/wizard.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/new_job/wizard.tsx index bfb34b977ec97..2e1a187daa736 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/new_job/wizard.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/new_job/wizard.tsx @@ -43,14 +43,14 @@ export const Wizard: FC = ({ firstWizardStep = WIZARD_STEPS.TIME_RANGE, }) => { const [jobCreatorUpdated, setJobCreatorUpdate] = useReducer<(s: number, action: any) => number>( - s => s + 1, + (s) => s + 1, 0 ); const jobCreatorUpdate = () => setJobCreatorUpdate(jobCreatorUpdated); const [jobValidatorUpdated, setJobValidatorUpdate] = useReducer< (s: number, action: any) => number - >(s => s + 1, 0); + >((s) => s + 1, 0); const jobCreatorContext: JobCreatorContextValue = { jobCreatorUpdated, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx index 0dd222a1726ef..433327497fe05 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/edit_job.tsx @@ -51,8 +51,8 @@ export const EditJob: FC = ({ job, jobOverride, existingGroupIds, const handleValidation = () => { const jobGroupsValidationResult = formState.jobGroups - .map(group => groupValidator(group)) - .filter(result => result !== null); + .map((group) => groupValidator(group)) + .filter((result) => result !== null); setValidationResult({ jobGroups: jobGroupsValidationResult, @@ -92,7 +92,7 @@ export const EditJob: FC = ({ job, jobOverride, existingGroupIds, { + onChange={(value) => { setFormState({ jobGroups: value, }); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx index 2a15a42ba04f8..8dab25bf492f4 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_item.tsx @@ -85,7 +85,7 @@ export const JobItem: FC = memo( - {jobGroups.map(group => ( + {jobGroups.map((group) => ( {group} diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_settings_form.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_settings_form.tsx index bae9c592b94c4..63dec536ea487 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_settings_form.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/components/job_settings_form.tsx @@ -195,7 +195,7 @@ export const JobSettingsForm: FC = ({ <> { + setTimeRange={(value) => { setFormState({ timeRange: value, }); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/page.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/page.tsx index 50c35ec426acb..da1bbbc7ae67c 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/page.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/page.tsx @@ -113,7 +113,7 @@ export const Page: FC = ({ moduleId, existingGroupIds }) => { setSaveState(SAVE_STATE.NOT_SAVED); // mix existing groups from the server with the groups used across all jobs in the module. - const moduleGroups = [...response.jobs.map(j => j.config.groups || [])].flat(); + const moduleGroups = [...response.jobs.map((j) => j.config.groups || [])].flat(); setExistingGroups([...new Set([...existingGroups, ...moduleGroups])]); } catch (e) { // eslint-disable-next-line no-console @@ -176,7 +176,7 @@ export const Page: FC = ({ moduleId, existingGroupIds }) => { const { datafeeds: datafeedsResponse, jobs: jobsResponse, kibana: kibanaResponse } = response; setJobs( - jobs.map(job => { + jobs.map((job) => { return { ...job, datafeedResult: datafeedsResponse.find(({ id }) => id.endsWith(job.id)), @@ -297,7 +297,7 @@ export const Page: FC = ({ moduleId, existingGroupIds }) => { {isFormVisible && ( { + onChange={(formValues) => { setJobPrefix(formValues.jobPrefix); }} saveState={saveState} diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/resolvers.ts b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/resolvers.ts index 9c60b84b16bdf..e3b0fd4cefe0c 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/resolvers.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/resolvers.ts @@ -66,8 +66,8 @@ export const checkForSavedObjects = async (objects: KibanaObjects): Promise { - const find = savedObjects.find(savedObject => savedObject.attributes.title === obj.title); + acc[type] = objects[type].map((obj) => { + const find = savedObjects.find((savedObject) => savedObject.attributes.title === obj.title); return { ...obj, exists: !!find, diff --git a/x-pack/plugins/ml/public/application/management/index.ts b/x-pack/plugins/ml/public/application/management/index.ts index f15cdb12afb21..480e2fe488980 100644 --- a/x-pack/plugins/ml/public/application/management/index.ts +++ b/x-pack/plugins/ml/public/application/management/index.ts @@ -28,7 +28,7 @@ export function initManagementSection( core: CoreSetup ) { const licensing = pluginsSetup.licensing.license$.pipe(take(1)); - licensing.subscribe(license => { + licensing.subscribe((license) => { const management = pluginsSetup.management; if ( management !== undefined && diff --git a/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx b/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx index dac39b1a2071d..03b66f5c369c1 100644 --- a/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx +++ b/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx @@ -43,7 +43,7 @@ const createJobLink = '#/jobs/new_job/step/index_or_search'; function getDefaultAnomalyScores(groups: Group[]): MaxScoresByGroup { const anomalyScores: MaxScoresByGroup = {}; - groups.forEach(group => { + groups.forEach((group) => { anomalyScores[group.id] = { maxScore: 0 }; }); @@ -96,7 +96,7 @@ export const AnomalyDetectionPanel: FC = ({ jobCreationDisabled }) => { try { const promises = groupsList - .filter(group => group.jobIds.length > 0) + .filter((group) => group.jobIds.length > 0) .map((group, i) => { scores[group.id].index = i; const latestTimestamp = group.latest_timestamp; @@ -108,7 +108,7 @@ export const AnomalyDetectionPanel: FC = ({ jobCreationDisabled }) => { const results = await Promise.all(promises); const tempGroups = { ...groupsObject }; // Check results for each group's promise index and update state - Object.keys(scores).forEach(groupId => { + Object.keys(scores).forEach((groupId) => { const resultsIndex = scores[groupId] && scores[groupId].index; // maxScore will be null if it was not loaded correctly const { maxScore } = resultsIndex !== undefined && results[resultsIndex]; diff --git a/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/utils.ts b/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/utils.ts index b030a1ef45ab0..5372862219a89 100644 --- a/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/utils.ts +++ b/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/utils.ts @@ -156,7 +156,7 @@ export function getStatsBarData(jobsList: any) { } export function getJobsFromGroup(group: Group, jobs: any) { - return group.jobIds.map(jobId => jobs[jobId]).filter(id => id !== undefined); + return group.jobIds.map((jobId) => jobs[jobId]).filter((id) => id !== undefined); } export function getJobsWithTimerange(jobsList: any) { diff --git a/x-pack/plugins/ml/public/application/routing/router.tsx b/x-pack/plugins/ml/public/application/routing/router.tsx index f4d6fec5e6ee3..281493c4e31b7 100644 --- a/x-pack/plugins/ml/public/application/routing/router.tsx +++ b/x-pack/plugins/ml/public/application/routing/router.tsx @@ -54,7 +54,7 @@ export const MlRouter: FC<{ pageDeps: PageDependencies }> = ({ pageDeps }) => { key={name} path={route.path} exact - render={props => { + render={(props) => { window.setTimeout(() => { setBreadcrumbs(route.breadcrumbs); }); diff --git a/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx b/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx index a41a6c83615d3..fdf29406893ad 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer.tsx @@ -230,7 +230,7 @@ export const TimeSeriesExplorerUrlStateManager: FC { + .then((resp) => { if (autoZoomDuration === undefined) { return; } @@ -248,7 +248,7 @@ export const TimeSeriesExplorerUrlStateManager: FC { + .catch((resp) => { // eslint-disable-next-line no-console console.error( 'Time series explorer - error loading time range of forecast from elasticsearch:', diff --git a/x-pack/plugins/ml/public/application/routing/use_refresh.ts b/x-pack/plugins/ml/public/application/routing/use_refresh.ts index f9f3bb66f14f3..f0b93c876526b 100644 --- a/x-pack/plugins/ml/public/application/routing/use_refresh.ts +++ b/x-pack/plugins/ml/public/application/routing/use_refresh.ts @@ -22,7 +22,7 @@ export interface Refresh { const refresh$: Observable = merge( mlTimefilterRefresh$, mlTimefilterTimeChange$, - annotationsRefresh$.pipe(map(d => ({ lastRefresh: d }))) + annotationsRefresh$.pipe(map((d) => ({ lastRefresh: d }))) ); export const useRefresh = () => { diff --git a/x-pack/plugins/ml/public/application/routing/use_resolver.ts b/x-pack/plugins/ml/public/application/routing/use_resolver.ts index 8e94f8d77fbb2..4967e3a684a6b 100644 --- a/x-pack/plugins/ml/public/application/routing/use_resolver.ts +++ b/x-pack/plugins/ml/public/application/routing/use_resolver.ts @@ -38,7 +38,7 @@ export const useResolver = ( useEffect(() => { (async () => { try { - const res = await Promise.all(funcs.map(r => r())); + const res = await Promise.all(funcs.map((r) => r())); res.forEach((r, i) => (tempResults[funcNames[i]] = r)); setResults(tempResults); } catch (error) { diff --git a/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts b/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts index 26fcc25492612..6381f1f8eae89 100644 --- a/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts +++ b/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts @@ -24,7 +24,7 @@ export class AnomalyDetectorService { .http$<{ count: number; jobs: Job[] }>({ path: `${this.apiBasePath}/${jobId}`, }) - .pipe(map(response => response.jobs[0])); + .pipe(map((response) => response.jobs[0])); } /** @@ -36,7 +36,7 @@ export class AnomalyDetectorService { .http$<{ count: number; jobs: Job[] }>({ path: `${this.apiBasePath}/${jobIds.join(',')}`, }) - .pipe(map(response => response.jobs)); + .pipe(map((response) => response.jobs)); } /** diff --git a/x-pack/plugins/ml/public/application/services/explorer_service.ts b/x-pack/plugins/ml/public/application/services/explorer_service.ts index 8914fd17d1226..efcec8cf2b954 100644 --- a/x-pack/plugins/ml/public/application/services/explorer_service.ts +++ b/x-pack/plugins/ml/public/application/services/explorer_service.ts @@ -96,7 +96,7 @@ export class ExplorerService { // Ensure the search bounds align to the bucketing interval used in the swimlane so // that the first and last buckets are complete. const searchBounds = getBoundsRoundedToInterval(bounds, interval, false); - const selectedJobIds = selectedJobs.map(d => d.id); + const selectedJobIds = selectedJobs.map((d) => d.id); // Load the overall bucket scores by time. // Pass the interval in seconds as the swimlane relies on a fixed number of seconds between buckets @@ -152,7 +152,7 @@ export class ExplorerService { false ); - const selectedJobIds = selectedJobs.map(d => d.id); + const selectedJobIds = selectedJobs.map((d) => d.id); // load scores by influencer/jobId value and time. // Pass the interval in seconds as the swimlane relies on a fixed number of seconds between buckets // which wouldn't be the case if e.g. '1M' was used. diff --git a/x-pack/plugins/ml/public/application/services/field_format_service.ts b/x-pack/plugins/ml/public/application/services/field_format_service.ts index 343dc2ea564ba..1a5d22e7320a5 100644 --- a/x-pack/plugins/ml/public/application/services/field_format_service.ts +++ b/x-pack/plugins/ml/public/application/services/field_format_service.ts @@ -30,7 +30,7 @@ class FieldFormatService { // pattern with a title attribute which matches the index configured in the datafeed. // If a Kibana index pattern has not been created // for this index, then no custom field formatting will occur. - jobIds.forEach(jobId => { + jobIds.forEach((jobId) => { const jobObj = mlJobService.getJob(jobId); const datafeedIndices = jobObj.datafeed_config.indices; const id = getIndexPatternIdFromName(datafeedIndices.length ? datafeedIndices[0] : ''); @@ -39,17 +39,17 @@ class FieldFormatService { } }); - const promises = jobIds.map(jobId => Promise.all([this.getFormatsForJob(jobId)])); + const promises = jobIds.map((jobId) => Promise.all([this.getFormatsForJob(jobId)])); Promise.all(promises) - .then(fmtsByJobByDetector => { + .then((fmtsByJobByDetector) => { fmtsByJobByDetector.forEach((formatsByDetector, i) => { this.formatsByJob[jobIds[i]] = formatsByDetector[0]; }); resolve(this.formatsByJob); }) - .catch(err => { + .catch((err) => { reject({ formats: {}, err }); }); }); @@ -94,10 +94,10 @@ class FieldFormatService { if (indexPatternId !== undefined) { // Load the full index pattern configuration to obtain the formats of each field. getIndexPatternById(indexPatternId) - .then(indexPatternData => { + .then((indexPatternData) => { // Store the FieldFormat for each job by detector_index. const fieldList = indexPatternData.fields; - detectors.forEach(dtr => { + detectors.forEach((dtr) => { const esAgg = mlFunctionToESAggregation(dtr.function); // distinct_count detectors should fall back to the default // formatter as the values are just counts. @@ -111,7 +111,7 @@ class FieldFormatService { resolve(formatsByDetector); }) - .catch(err => { + .catch((err) => { reject(err); }); } else { diff --git a/x-pack/plugins/ml/public/application/services/forecast_service.js b/x-pack/plugins/ml/public/application/services/forecast_service.js index 5c51839b012bd..c3d593c3347df 100644 --- a/x-pack/plugins/ml/public/application/services/forecast_service.js +++ b/x-pack/plugins/ml/public/application/services/forecast_service.js @@ -61,14 +61,14 @@ function getForecastsSummary(job, query, earliestMs, maxResults) { sort: [{ forecast_create_timestamp: { order: 'desc' } }], }, }) - .then(resp => { + .then((resp) => { if (resp.hits.total !== 0) { - obj.forecasts = resp.hits.hits.map(hit => hit._source); + obj.forecasts = resp.hits.hits.map((hit) => hit._source); } resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -129,7 +129,7 @@ function getForecastDateRange(job, forecastId) { }, }, }) - .then(resp => { + .then((resp) => { obj.earliest = _.get(resp, 'aggregations.earliest.value', null); obj.latest = _.get(resp, 'aggregations.latest.value', null); if (obj.earliest === null || obj.latest === null) { @@ -138,7 +138,7 @@ function getForecastDateRange(job, forecastId) { resolve(obj); } }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -223,7 +223,7 @@ function getForecastData( ]; // Add in term queries for each of the specified criteria. - _.each(criteriaFields, criteria => { + _.each(criteriaFields, (criteria) => { filterCriteria.push({ term: { [criteria.fieldName]: criteria.fieldValue, @@ -282,9 +282,9 @@ function getForecastData( }, }) .pipe( - map(resp => { + map((resp) => { const aggregationsByTime = _.get(resp, ['aggregations', 'times', 'buckets'], []); - _.each(aggregationsByTime, dataForTime => { + _.each(aggregationsByTime, (dataForTime) => { const time = dataForTime.key; obj.results[time] = { prediction: _.get(dataForTime, ['prediction', 'value']), @@ -306,10 +306,10 @@ function runForecast(jobId, duration) { jobId, duration, }) - .then(resp => { + .then((resp) => { resolve(resp); }) - .catch(err => { + .catch((err) => { reject(err); }); }); @@ -355,13 +355,13 @@ function getForecastRequestStats(job, forecastId) { }, }, }) - .then(resp => { + .then((resp) => { if (resp.hits.total !== 0) { obj.stats = _.first(resp.hits.hits)._source; } resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); diff --git a/x-pack/plugins/ml/public/application/services/http_service.ts b/x-pack/plugins/ml/public/application/services/http_service.ts index ff60c67b3c9e6..34dc89dd5f89b 100644 --- a/x-pack/plugins/ml/public/application/services/http_service.ts +++ b/x-pack/plugins/ml/public/application/services/http_service.ts @@ -56,7 +56,7 @@ export function http$(options: HttpFetchOptionsWithPath): Observable { * Creates an Observable from Kibana's HttpHandler. */ export function fromHttpHandler(input: string, init?: RequestInit): Observable { - return new Observable(subscriber => { + return new Observable((subscriber) => { const controller = new AbortController(); const signal = controller.signal; @@ -82,12 +82,12 @@ export function fromHttpHandler(input: string, init?: RequestInit): Observabl getHttp() .fetch(input, perSubscriberInit) - .then(response => { + .then((response) => { abortable = false; subscriber.next(response); subscriber.complete(); }) - .catch(err => { + .catch((err) => { abortable = false; if (!unsubscribed) { subscriber.error(err); @@ -139,7 +139,7 @@ export class HttpService { * Creates an Observable from Kibana's HttpHandler. */ private fromHttpHandler(input: string, init?: RequestInit): Observable { - return new Observable(subscriber => { + return new Observable((subscriber) => { const controller = new AbortController(); const signal = controller.signal; @@ -165,12 +165,12 @@ export class HttpService { this.httpStart .fetch(input, perSubscriberInit) - .then(response => { + .then((response) => { abortable = false; subscriber.next(response); subscriber.complete(); }) - .catch(err => { + .catch((err) => { abortable = false; if (!unsubscribed) { subscriber.error(err); diff --git a/x-pack/plugins/ml/public/application/services/job_service.js b/x-pack/plugins/ml/public/application/services/job_service.js index fb75476c48fa3..8d59270b36dae 100644 --- a/x-pack/plugins/ml/public/application/services/job_service.js +++ b/x-pack/plugins/ml/public/application/services/job_service.js @@ -114,12 +114,12 @@ class JobService { datafeedIds = {}; ml.getJobs() - .then(resp => { + .then((resp) => { jobs = resp.jobs; // load jobs stats ml.getJobStats() - .then(statsResp => { + .then((statsResp) => { // merge jobs stats into jobs for (let i = 0; i < jobs.length; i++) { const job = jobs[i]; @@ -143,7 +143,7 @@ class JobService { } } } - this.loadDatafeeds().then(datafeedsResp => { + this.loadDatafeeds().then((datafeedsResp) => { for (let i = 0; i < jobs.length; i++) { for (let j = 0; j < datafeedsResp.datafeeds.length; j++) { if (jobs[i].job_id === datafeedsResp.datafeeds[j].job_id) { @@ -159,11 +159,11 @@ class JobService { resolve({ jobs: this.jobs }); }); }) - .catch(err => { + .catch((err) => { error(err); }); }) - .catch(err => { + .catch((err) => { error(err); }); @@ -182,10 +182,10 @@ class JobService { loadJobsWrapper = () => { return this.loadJobs() - .then(function(resp) { + .then(function (resp) { return resp; }) - .catch(function(error) { + .catch(function (error) { console.log('Error loading jobs in route resolve.', error); // Always resolve to ensure tab still works. Promise.resolve([]); @@ -195,13 +195,13 @@ class JobService { refreshJob(jobId) { return new Promise((resolve, reject) => { ml.getJobs({ jobId }) - .then(resp => { + .then((resp) => { if (resp.jobs && resp.jobs.length) { const newJob = resp.jobs[0]; // load jobs stats ml.getJobStats({ jobId }) - .then(statsResp => { + .then((statsResp) => { // merge jobs stats into jobs for (let j = 0; j < statsResp.jobs.length; j++) { if (newJob.job_id === statsResp.jobs[j].job_id) { @@ -230,7 +230,7 @@ class JobService { const datafeedId = this.getDatafeedId(jobId); - this.loadDatafeeds(datafeedId).then(datafeedsResp => { + this.loadDatafeeds(datafeedId).then((datafeedsResp) => { for (let i = 0; i < jobs.length; i++) { for (let j = 0; j < datafeedsResp.datafeeds.length; j++) { if (jobs[i].job_id === datafeedsResp.datafeeds[j].job_id) { @@ -245,12 +245,12 @@ class JobService { resolve({ jobs: this.jobs }); }); }) - .catch(err => { + .catch((err) => { error(err); }); } }) - .catch(err => { + .catch((err) => { error(err); }); @@ -272,7 +272,7 @@ class JobService { const sId = datafeedId !== undefined ? { datafeed_id: datafeedId } : undefined; ml.getDatafeeds(sId) - .then(resp => { + .then((resp) => { // console.log('loadDatafeeds query response:', resp); // make deep copy of datafeeds @@ -280,7 +280,7 @@ class JobService { // load datafeeds stats ml.getDatafeedStats() - .then(statsResp => { + .then((statsResp) => { // merge datafeeds stats into datafeeds for (let i = 0; i < datafeeds.length; i++) { const datafeed = datafeeds[i]; @@ -292,11 +292,11 @@ class JobService { } resolve({ datafeeds }); }) - .catch(err => { + .catch((err) => { error(err); }); }) - .catch(err => { + .catch((err) => { error(err); }); @@ -318,7 +318,7 @@ class JobService { const datafeedId = this.getDatafeedId(jobId); ml.getDatafeedStats({ datafeedId }) - .then(resp => { + .then((resp) => { // console.log('updateSingleJobCounts controller query response:', resp); const datafeeds = resp.datafeeds; let state = 'UNKNOWN'; @@ -327,7 +327,7 @@ class JobService { } resolve(state); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -342,10 +342,7 @@ class JobService { } // return the promise chain - return ml - .addJob({ jobId: job.job_id, job }) - .then(func) - .catch(func); + return ml.addJob({ jobId: job.job_id, job }).then(func).catch(func); } cloneJob(job) { @@ -374,7 +371,7 @@ class JobService { delete tempJob.analysis_config.use_per_partition_normalization; - _.each(tempJob.analysis_config.detectors, d => { + _.each(tempJob.analysis_config.detectors, (d) => { delete d.detector_index; }); @@ -414,11 +411,11 @@ class JobService { // return the promise chain return ml .updateJob({ jobId, job }) - .then(resp => { + .then((resp) => { console.log('update job', resp); return { success: true }; }) - .catch(err => { + .catch((err) => { msgs.notify.error( i18n.translate('xpack.ml.jobService.couldNotUpdateJobErrorMessage', { defaultMessage: 'Could not update job: {jobId}', @@ -434,10 +431,10 @@ class JobService { // return the promise chain return ml .validateJob(obj) - .then(messages => { + .then((messages) => { return { success: true, messages }; }) - .catch(err => { + .catch((err) => { msgs.notify.error( i18n.translate('xpack.ml.jobService.jobValidationErrorMessage', { defaultMessage: 'Job Validation Error: {errorMessage}', @@ -459,7 +456,7 @@ class JobService { // find a job based on the id getJob(jobId) { - const job = _.find(jobs, j => { + const job = _.find(jobs, (j) => { return j.job_id === jobId; }); @@ -491,7 +488,7 @@ class JobService { timeFieldName: job.data_description.time_field, query, }) - .then(timeRange => { + .then((timeRange) => { const bucketSpan = parseInterval(job.analysis_config.bucket_span); const earliestMs = timeRange.start.epoch; const latestMs = +timeRange.start.epoch + 10 * bucketSpan.asMilliseconds(); @@ -540,7 +537,7 @@ class JobService { // get fields from detectors if (job.analysis_config.detectors) { - _.each(job.analysis_config.detectors, dtr => { + _.each(job.analysis_config.detectors, (dtr) => { if (dtr.by_field_name) { fields[dtr.by_field_name] = {}; } @@ -558,7 +555,7 @@ class JobService { // get fields from influencers if (job.analysis_config.influencers) { - _.each(job.analysis_config.influencers, inf => { + _.each(job.analysis_config.influencers, (inf) => { fields[inf] = {}; }); } @@ -592,14 +589,14 @@ class JobService { }; ml.esSearch(data) - .then(resp => { + .then((resp) => { resolve(resp); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); } @@ -627,11 +624,11 @@ class JobService { updateDatafeed(datafeedId, datafeedConfig) { return ml .updateDatafeed({ datafeedId, datafeedConfig }) - .then(resp => { + .then((resp) => { console.log('update datafeed', resp); return { success: true }; }) - .catch(err => { + .catch((err) => { msgs.notify.error( i18n.translate('xpack.ml.jobService.couldNotUpdateDatafeedErrorMessage', { defaultMessage: 'Could not update datafeed: {datafeedId}', @@ -658,10 +655,10 @@ class JobService { start, end, }) - .then(resp => { + .then((resp) => { resolve(resp); }) - .catch(err => { + .catch((err) => { console.log('jobService error starting datafeed:', err); msgs.notify.error( i18n.translate('xpack.ml.jobService.couldNotStartDatafeedErrorMessage', { @@ -682,10 +679,10 @@ class JobService { ml.stopDatafeed({ datafeedId, }) - .then(resp => { + .then((resp) => { resolve(resp); }) - .catch(err => { + .catch((err) => { console.log('jobService error stopping datafeed:', err); const couldNotStopDatafeedErrorMessage = i18n.translate( 'xpack.ml.jobService.couldNotStopDatafeedErrorMessage', @@ -731,10 +728,10 @@ class JobService { return new Promise((resolve, reject) => { if (detector) { ml.validateDetector({ detector }) - .then(resp => { + .then((resp) => { resolve(resp); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); } else { @@ -759,9 +756,9 @@ class JobService { getJobGroups() { const groups = []; const tempGroups = {}; - this.jobs.forEach(job => { + this.jobs.forEach((job) => { if (Array.isArray(job.groups)) { - job.groups.forEach(group => { + job.groups.forEach((group) => { if (tempGroups[group] === undefined) { tempGroups[group] = [job]; } else { @@ -829,7 +826,7 @@ function processBasicJobInfo(localJobService, jobsList) { // use cloned copy of jobs list so not to alter the original const jobsListCopy = _.cloneDeep(jobsList); - _.each(jobsListCopy, jobObj => { + _.each(jobsListCopy, (jobObj) => { const analysisConfig = jobObj.analysis_config; const bucketSpan = parseInterval(analysisConfig.bucket_span); @@ -850,7 +847,7 @@ function processBasicJobInfo(localJobService, jobsList) { if (_.has(jobObj, 'custom_settings.custom_urls')) { job.customUrls = []; - _.each(jobObj.custom_settings.custom_urls, url => { + _.each(jobObj.custom_settings.custom_urls, (url) => { if (_.has(url, 'url_name') && _.has(url, 'url_value') && isWebUrl(url.url_value)) { // Only make web URLs (i.e. http or https) available in dashboard drilldowns. job.customUrls.push(url); @@ -887,7 +884,7 @@ function createJobStats(jobsList, jobStats) { const mlNodes = {}; let failedJobs = 0; - _.each(jobsList, job => { + _.each(jobsList, (job) => { if (job.state === 'opened') { jobStats.open.value++; } else if (job.state === 'closed') { @@ -925,10 +922,10 @@ function createResultsUrlForJobs(jobsList, resultsPage) { from = jobsList[0].earliestTimestampMs; to = jobsList[0].latestResultsTimestampMs; // Will be max(latest source data, latest bucket results) } else { - const jobsWithData = jobsList.filter(j => j.earliestTimestampMs !== undefined); + const jobsWithData = jobsList.filter((j) => j.earliestTimestampMs !== undefined); if (jobsWithData.length > 0) { - from = Math.min(...jobsWithData.map(j => j.earliestTimestampMs)); - to = Math.max(...jobsWithData.map(j => j.latestResultsTimestampMs)); + from = Math.min(...jobsWithData.map((j) => j.earliestTimestampMs)); + to = Math.max(...jobsWithData.map((j) => j.latestResultsTimestampMs)); } } @@ -937,12 +934,12 @@ function createResultsUrlForJobs(jobsList, resultsPage) { const fromString = moment(from).format(timeFormat); // Defaults to 'now' if 'from' is undefined const toString = moment(to).format(timeFormat); // Defaults to 'now' if 'to' is undefined - const jobIds = jobsList.map(j => j.id); + const jobIds = jobsList.map((j) => j.id); return createResultsUrl(jobIds, fromString, toString, resultsPage); } function createResultsUrl(jobIds, start, end, resultsPage) { - const idString = jobIds.map(j => `'${j}'`).join(','); + const idString = jobIds.map((j) => `'${j}'`).join(','); const from = moment(start).toISOString(); const to = moment(end).toISOString(); let path = ''; diff --git a/x-pack/plugins/ml/public/application/services/mapping_service.js b/x-pack/plugins/ml/public/application/services/mapping_service.js index 36363cfa3d713..52aa5ed7413cb 100644 --- a/x-pack/plugins/ml/public/application/services/mapping_service.js +++ b/x-pack/plugins/ml/public/application/services/mapping_service.js @@ -14,10 +14,10 @@ export function getFieldTypeFromMapping(index, fieldName) { return new Promise((resolve, reject) => { if (index !== '') { ml.getFieldCaps({ index, fields: [fieldName] }) - .then(resp => { + .then((resp) => { let fieldType = ''; - _.each(resp.fields, field => { - _.each(field, type => { + _.each(resp.fields, (field) => { + _.each(field, (type) => { if (fieldType === '') { fieldType = type.type; } @@ -25,7 +25,7 @@ export function getFieldTypeFromMapping(index, fieldName) { }); resolve(fieldType); }) - .catch(error => { + .catch((error) => { reject(error); }); } else { diff --git a/x-pack/plugins/ml/public/application/services/ml_server_info.test.ts b/x-pack/plugins/ml/public/application/services/ml_server_info.test.ts index 2b6fb50538020..bd91995b6efc3 100644 --- a/x-pack/plugins/ml/public/application/services/ml_server_info.test.ts +++ b/x-pack/plugins/ml/public/application/services/ml_server_info.test.ts @@ -27,7 +27,7 @@ describe('ml_server_info initial state', () => { }); describe('ml_server_info', () => { - beforeEach(async done => { + beforeEach(async (done) => { await loadMlServerInfo(); done(); }); @@ -40,7 +40,7 @@ describe('ml_server_info', () => { }); describe('defaults', () => { - it('can get defaults', async done => { + it('can get defaults', async (done) => { const defaults = getNewJobDefaults(); expect(defaults.anomaly_detectors.model_memory_limit).toBe('128mb'); @@ -52,7 +52,7 @@ describe('ml_server_info', () => { }); describe('limits', () => { - it('can get limits', async done => { + it('can get limits', async (done) => { const limits = getNewJobLimits(); expect(limits.max_model_memory_limit).toBe('128mb'); diff --git a/x-pack/plugins/ml/public/application/services/new_job_capabilities._service.test.ts b/x-pack/plugins/ml/public/application/services/new_job_capabilities._service.test.ts index 792d5222bc6cb..81f05065b5139 100644 --- a/x-pack/plugins/ml/public/application/services/new_job_capabilities._service.test.ts +++ b/x-pack/plugins/ml/public/application/services/new_job_capabilities._service.test.ts @@ -26,14 +26,14 @@ const indexPattern = ({ describe('new_job_capabilities_service', () => { describe('cloudwatch newJobCaps()', () => { - it('can construct job caps objects from endpoint json', async done => { + it('can construct job caps objects from endpoint json', async (done) => { await newJobCapsService.initializeFromIndexPattern(indexPattern); const { fields, aggs } = await newJobCapsService.newJobCaps; - const networkOutField = fields.find(f => f.id === 'NetworkOut') || { aggs: [] }; - const regionField = fields.find(f => f.id === 'region') || { aggs: [] }; - const meanAgg = aggs.find(a => a.id === 'mean') || { fields: [] }; - const distinctCountAgg = aggs.find(a => a.id === 'distinct_count') || { fields: [] }; + const networkOutField = fields.find((f) => f.id === 'NetworkOut') || { aggs: [] }; + const regionField = fields.find((f) => f.id === 'region') || { aggs: [] }; + const meanAgg = aggs.find((a) => a.id === 'mean') || { fields: [] }; + const distinctCountAgg = aggs.find((a) => a.id === 'distinct_count') || { fields: [] }; expect(fields).toHaveLength(12); expect(aggs).toHaveLength(35); @@ -46,7 +46,7 @@ describe('new_job_capabilities_service', () => { done(); }); - it('job caps including text fields', async done => { + it('job caps including text fields', async (done) => { await newJobCapsService.initializeFromIndexPattern(indexPattern, true, false); const { fields, aggs } = await newJobCapsService.newJobCaps; @@ -56,7 +56,7 @@ describe('new_job_capabilities_service', () => { done(); }); - it('job caps excluding event rate', async done => { + it('job caps excluding event rate', async (done) => { await newJobCapsService.initializeFromIndexPattern(indexPattern, false, true); const { fields, aggs } = await newJobCapsService.newJobCaps; diff --git a/x-pack/plugins/ml/public/application/services/new_job_capabilities_service.ts b/x-pack/plugins/ml/public/application/services/new_job_capabilities_service.ts index f5f1bd3d4c541..bc65ebe7a5fac 100644 --- a/x-pack/plugins/ml/public/application/services/new_job_capabilities_service.ts +++ b/x-pack/plugins/ml/public/application/services/new_job_capabilities_service.ts @@ -85,7 +85,7 @@ class NewJobCapsService { } public get categoryFields(): Field[] { - return this._fields.filter(f => categoryFieldTypes.includes(f.type)); + return this._fields.filter((f) => categoryFieldTypes.includes(f.type)); } public async initializeFromIndexPattern( @@ -108,9 +108,9 @@ class NewJobCapsService { allFields ); const catFields = fieldsPreferringText.filter( - f => f.type === ES_FIELD_TYPES.KEYWORD || f.type === ES_FIELD_TYPES.TEXT + (f) => f.type === ES_FIELD_TYPES.KEYWORD || f.type === ES_FIELD_TYPES.TEXT ); - const dateFields = fieldsPreferringText.filter(f => f.type === ES_FIELD_TYPES.DATE); + const dateFields = fieldsPreferringText.filter((f) => f.type === ES_FIELD_TYPES.DATE); const fields = this._removeTextFields ? fieldsPreferringKeyword : allFields; // set the main fields list to contain fields which have been filtered to prefer @@ -127,12 +127,12 @@ class NewJobCapsService { } public getFieldById(id: string): Field | null { - const field = this._fields.find(f => f.id === id); + const field = this._fields.find((f) => f.id === id); return field === undefined ? null : field; } public getAggById(id: string): Aggregation | null { - const agg = this._aggs.find(f => f.id === id); + const agg = this._aggs.find((f) => f.id === id); return agg === undefined ? null : agg; } } @@ -190,8 +190,8 @@ function createObjects(resp: any, indexPatternTitle: string) { // the aggIds and fieldIds lists are no longer needed as we've created // lists of real fields and aggs - fields.forEach(f => delete f.aggIds); - aggs.forEach(a => delete a.fieldIds); + fields.forEach((f) => delete f.aggIds); + aggs.forEach((a) => delete a.fieldIds); return { fields, @@ -219,7 +219,7 @@ function addEventRateField(aggs: Aggregation[], fields: Field[]) { aggs: [], }; - aggs.forEach(a => { + aggs.forEach((a) => { if (eventRateField.aggs !== undefined && a.fields === undefined) { // if the agg's field list is undefined, it is a fieldless aggregation and // so can only be used with the event rate field. @@ -232,17 +232,17 @@ function addEventRateField(aggs: Aggregation[], fields: Field[]) { // create two lists, one removing text fields if there are keyword equivalents and vice versa function processTextAndKeywordFields(fields: Field[]) { - const keywordIds = fields.filter(f => f.type === ES_FIELD_TYPES.KEYWORD).map(f => f.id); - const textIds = fields.filter(f => f.type === ES_FIELD_TYPES.TEXT).map(f => f.id); + const keywordIds = fields.filter((f) => f.type === ES_FIELD_TYPES.KEYWORD).map((f) => f.id); + const textIds = fields.filter((f) => f.type === ES_FIELD_TYPES.TEXT).map((f) => f.id); const fieldsPreferringKeyword = fields.filter( - f => + (f) => f.type !== ES_FIELD_TYPES.TEXT || (f.type === ES_FIELD_TYPES.TEXT && keywordIds.includes(`${f.id}.keyword`) === false) ); const fieldsPreferringText = fields.filter( - f => + (f) => f.type !== ES_FIELD_TYPES.KEYWORD || (f.type === ES_FIELD_TYPES.KEYWORD && textIds.includes(f.id.replace(/\.keyword$/, '')) === false) diff --git a/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts b/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts index 8f701a9ebe057..a21d0caaedd33 100644 --- a/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts +++ b/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts @@ -74,7 +74,7 @@ export function getMetricData( ...(query ? [query] : []), ]; - entityFields.forEach(entity => { + entityFields.forEach((entity) => { if (entity.fieldValue.length !== 0) { mustCriteria.push({ term: { @@ -227,7 +227,7 @@ export function getModelPlotOutput( ]; // Add in term queries for each of the specified criteria. - _.each(criteriaFields, criteria => { + _.each(criteriaFields, (criteria) => { mustCriteria.push({ term: { [criteria.fieldName]: criteria.fieldValue, @@ -305,7 +305,7 @@ export function getModelPlotOutput( }, }) .pipe( - map(resp => { + map((resp) => { const aggregationsByTime = _.get(resp, ['aggregations', 'times', 'buckets'], []); _.each(aggregationsByTime, (dataForTime: any) => { const time = dataForTime.key; @@ -385,7 +385,7 @@ export function getRecordsForCriteria( } // Add in term queries for each of the specified criteria. - _.each(criteriaFields, criteria => { + _.each(criteriaFields, (criteria) => { boolCriteria.push({ term: { [criteria.fieldName]: criteria.fieldValue, @@ -420,7 +420,7 @@ export function getRecordsForCriteria( }, }) .pipe( - map(resp => { + map((resp) => { if (resp.hits.total !== 0) { _.each(resp.hits.hits, (hit: any) => { obj.records.push(hit._source); @@ -533,7 +533,7 @@ export function getScheduledEventsByBucket( }, }) .pipe( - map(resp => { + map((resp) => { const dataByJobId = _.get(resp, ['aggregations', 'jobs', 'buckets'], []); _.each(dataByJobId, (dataForJob: any) => { const jobId: string = dataForJob.key; diff --git a/x-pack/plugins/ml/public/application/services/results_service/results_service.js b/x-pack/plugins/ml/public/application/services/results_service/results_service.js index b7aa5edc88638..4fccc4d789370 100644 --- a/x-pack/plugins/ml/public/application/services/results_service/results_service.js +++ b/x-pack/plugins/ml/public/application/services/results_service/results_service.js @@ -116,15 +116,15 @@ export function getScoresByBucket(jobIds, earliestMs, latestMs, interval, maxRes }, }, }) - .then(resp => { + .then((resp) => { const dataByJobId = _.get(resp, ['aggregations', 'jobId', 'buckets'], []); - _.each(dataByJobId, dataForJob => { + _.each(dataByJobId, (dataForJob) => { const jobId = dataForJob.key; const resultsForTime = {}; const dataByTime = _.get(dataForJob, ['byTime', 'buckets'], []); - _.each(dataByTime, dataForTime => { + _.each(dataByTime, (dataForTime) => { const value = _.get(dataForTime, ['anomalyScore', 'value']); if (value !== undefined) { const time = dataForTime.key; @@ -136,7 +136,7 @@ export function getScoresByBucket(jobIds, earliestMs, latestMs, interval, maxRes resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -205,7 +205,7 @@ export function getTopInfluencers( if (influencers.length > 0) { boolCriteria.push({ bool: { - should: influencers.map(influencer => { + should: influencers.map((influencer) => { return { bool: { must: [ @@ -282,18 +282,18 @@ export function getTopInfluencers( }, }, }) - .then(resp => { + .then((resp) => { const fieldNameBuckets = _.get( resp, ['aggregations', 'influencerFieldNames', 'buckets'], [] ); - _.each(fieldNameBuckets, nameBucket => { + _.each(fieldNameBuckets, (nameBucket) => { const fieldName = nameBucket.key; const fieldValues = []; const fieldValueBuckets = _.get(nameBucket, ['influencerFieldValues', 'buckets'], []); - _.each(fieldValueBuckets, valueBucket => { + _.each(fieldValueBuckets, (valueBucket) => { const fieldValueResult = { influencerFieldValue: valueBucket.key, maxAnomalyScore: valueBucket.maxAnomalyScore.value, @@ -307,7 +307,7 @@ export function getTopInfluencers( resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -407,9 +407,9 @@ export function getTopInfluencerValues( }, }, }) - .then(resp => { + .then((resp) => { const buckets = _.get(resp, ['aggregations', 'influencerFieldValues', 'buckets'], []); - _.each(buckets, bucket => { + _.each(buckets, (bucket) => { const result = { influencerFieldValue: bucket.key, maxAnomalyScore: bucket.maxAnomalyScore.value, @@ -420,7 +420,7 @@ export function getTopInfluencerValues( resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -440,9 +440,9 @@ export function getOverallBucketScores(jobIds, topN, earliestMs, latestMs, inter start: earliestMs, end: latestMs, }) - .then(resp => { + .then((resp) => { const dataByTime = _.get(resp, ['overall_buckets'], []); - _.each(dataByTime, dataForTime => { + _.each(dataByTime, (dataForTime) => { const value = _.get(dataForTime, ['overall_score']); if (value !== undefined) { obj.results[dataForTime.timestamp] = value; @@ -451,7 +451,7 @@ export function getOverallBucketScores(jobIds, topN, earliestMs, latestMs, inter resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -594,18 +594,18 @@ export function getInfluencerValueMaxScoreByTime( }, }, }) - .then(resp => { + .then((resp) => { const fieldValueBuckets = _.get( resp, ['aggregations', 'influencerFieldValues', 'buckets'], [] ); - _.each(fieldValueBuckets, valueBucket => { + _.each(fieldValueBuckets, (valueBucket) => { const fieldValue = valueBucket.key; const fieldValues = {}; const timeBuckets = _.get(valueBucket, ['byTime', 'buckets'], []); - _.each(timeBuckets, timeBucket => { + _.each(timeBuckets, (timeBucket) => { const time = timeBucket.key; const score = timeBucket.maxAnomalyScore.value; fieldValues[time] = score; @@ -616,7 +616,7 @@ export function getInfluencerValueMaxScoreByTime( resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -710,15 +710,15 @@ export function getRecordInfluencers(jobIds, threshold, earliestMs, latestMs, ma sort: [{ record_score: { order: 'desc' } }], }, }) - .then(resp => { + .then((resp) => { if (resp.hits.total !== 0) { - _.each(resp.hits.hits, hit => { + _.each(resp.hits.hits, (hit) => { obj.records.push(hit._source); }); } resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -788,7 +788,7 @@ export function getRecordsForInfluencer( if (influencers.length > 0) { boolCriteria.push({ bool: { - should: influencers.map(influencer => { + should: influencers.map((influencer) => { return { nested: { path: 'influencers', @@ -841,15 +841,15 @@ export function getRecordsForInfluencer( sort: [{ record_score: { order: 'desc' } }], }, }) - .then(resp => { + .then((resp) => { if (resp.hits.total !== 0) { - _.each(resp.hits.hits, hit => { + _.each(resp.hits.hits, (hit) => { obj.records.push(hit._source); }); } resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -966,15 +966,15 @@ export function getRecordsForDetector( sort: [{ record_score: { order: 'desc' } }], }, }) - .then(resp => { + .then((resp) => { if (resp.hits.total !== 0) { - _.each(resp.hits.hits, hit => { + _.each(resp.hits.hits, (hit) => { obj.records.push(hit._source); }); } resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -1045,9 +1045,9 @@ export function getEventRateData(index, query, timeFieldName, earliestMs, latest }, }, }) - .then(resp => { + .then((resp) => { const dataByTimeBucket = _.get(resp, ['aggregations', 'eventRate', 'buckets'], []); - _.each(dataByTimeBucket, dataForTime => { + _.each(dataByTimeBucket, (dataForTime) => { const time = dataForTime.key; obj.results[time] = dataForTime.doc_count; }); @@ -1055,7 +1055,7 @@ export function getEventRateData(index, query, timeFieldName, earliestMs, latest resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -1192,7 +1192,7 @@ export function getEventDistributionData( body, rest_total_hits_as_int: true, }) - .then(resp => { + .then((resp) => { // Because of the sampling, results of metricFunctions which use sum or count // can be significantly skewed. Taking into account totalHits we calculate a // a factor to normalize results for these metricFunctions. @@ -1208,7 +1208,7 @@ export function getEventDistributionData( const data = dataByTime.reduce((d, dataForTime) => { const date = +dataForTime.key; const entities = _.get(dataForTime, ['entities', 'buckets'], []); - entities.forEach(entity => { + entities.forEach((entity) => { let value = metricFunction === 'count' ? entity.doc_count : entity.metric.value; if ( @@ -1229,7 +1229,7 @@ export function getEventDistributionData( }, []); resolve(data); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -1260,7 +1260,7 @@ export function getRecordMaxScoreByTime(jobId, criteriaFields, earliestMs, lates { term: { job_id: jobId } }, ]; - _.each(criteriaFields, criteria => { + _.each(criteriaFields, (criteria) => { mustCriteria.push({ term: { [criteria.fieldName]: criteria.fieldValue, @@ -1307,9 +1307,9 @@ export function getRecordMaxScoreByTime(jobId, criteriaFields, earliestMs, lates }, }, }) - .then(resp => { + .then((resp) => { const aggregationsByTime = _.get(resp, ['aggregations', 'times', 'buckets'], []); - _.each(aggregationsByTime, dataForTime => { + _.each(aggregationsByTime, (dataForTime) => { const time = dataForTime.key; obj.results[time] = { score: _.get(dataForTime, ['recordScore', 'value']), @@ -1318,7 +1318,7 @@ export function getRecordMaxScoreByTime(jobId, criteriaFields, earliestMs, lates resolve(obj); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/events_table/events_table.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/events_table/events_table.js index bd3c8779c9d43..dbff27dceff4d 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/events_table/events_table.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/events_table/events_table.js @@ -70,7 +70,7 @@ export const EventsTable = ({ defaultMessage: 'Start', }), sortable: true, - render: timeMs => { + render: (timeMs) => { const time = moment(timeMs); return time.format(TIME_FORMAT); }, @@ -81,7 +81,7 @@ export const EventsTable = ({ defaultMessage: 'End', }), sortable: true, - render: timeMs => { + render: (timeMs) => { const time = moment(timeMs); return time.format(TIME_FORMAT); }, @@ -89,7 +89,7 @@ export const EventsTable = ({ { field: '', name: '', - render: event => ( + render: (event) => ( { + handleImport = async (loadedFile) => { const incomingFile = loadedFile[0]; const errorMessage = i18n.translate( 'xpack.ml.calendarsEdit.importModal.couldNotParseICSFileErrorMessage', @@ -82,14 +82,14 @@ export class ImportModal extends Component { } }; - onEventDelete = eventId => { - this.setState(prevState => ({ - allImportedEvents: prevState.allImportedEvents.filter(event => event.event_id !== eventId), - selectedEvents: prevState.selectedEvents.filter(event => event.event_id !== eventId), + onEventDelete = (eventId) => { + this.setState((prevState) => ({ + allImportedEvents: prevState.allImportedEvents.filter((event) => event.event_id !== eventId), + selectedEvents: prevState.selectedEvents.filter((event) => event.event_id !== eventId), })); }; - onCheckboxToggle = e => { + onCheckboxToggle = (e) => { this.setState({ includePastEvents: e.target.checked, }); @@ -99,7 +99,7 @@ export class ImportModal extends Component { const { allImportedEvents, selectedEvents, includePastEvents } = this.state; const eventsToImport = includePastEvents ? allImportedEvents : selectedEvents; - const events = eventsToImport.map(event => ({ + const events = eventsToImport.map((event) => ({ description: event.description, start_time: event.start_time, end_time: event.end_time, @@ -135,7 +135,7 @@ export class ImportModal extends Component { importedEvents = selectedEvents; } - if (importedEvents.find(e => e.asterisk) !== undefined) { + if (importedEvents.find((e) => e.asterisk) !== undefined) { showRecurringWarning = true; } diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/import_modal/utils.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/import_modal/utils.js index d24577826838e..07bf49ea6d7db 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/import_modal/utils.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/import_modal/utils.js @@ -12,7 +12,7 @@ function createEvents(ical) { const events = ical.events(); const mlEvents = []; - events.forEach(e => { + events.forEach((e) => { if (e.element === 'VEVENT') { const description = e.properties.SUMMARY; const start = e.properties.DTSTART; @@ -38,7 +38,7 @@ function createEvents(ical) { export function filterEvents(events) { const now = moment().valueOf(); - return events.filter(e => e.start_time > now); + return events.filter((e) => e.start_time > now); } export function parseICSFile(data) { diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.js index 67570e2c7c54f..7efc37d4bf8ce 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.js @@ -59,8 +59,8 @@ class NewCalendarUI extends Component { try { const { jobIds, groupIds, calendars } = await getCalendarSettingsData(); - const jobIdOptions = jobIds.map(jobId => ({ label: jobId })); - const groupIdOptions = groupIds.map(groupId => ({ label: groupId })); + const jobIdOptions = jobIds.map((jobId) => ({ label: jobId })); + const groupIdOptions = groupIds.map((groupId) => ({ label: groupId })); const selectedJobOptions = []; const selectedGroupOptions = []; @@ -71,7 +71,7 @@ class NewCalendarUI extends Component { // Editing existing calendar. if (this.props.calendarId !== undefined) { - selectedCalendar = calendars.find(cal => cal.calendar_id === this.props.calendarId); + selectedCalendar = calendars.find((cal) => cal.calendar_id === this.props.calendarId); if (selectedCalendar) { formCalendarId = selectedCalendar.calendar_id; @@ -80,10 +80,10 @@ class NewCalendarUI extends Component { if (selectedCalendar.job_ids.includes(GLOBAL_CALENDAR)) { isGlobalCalendar = true; } else { - selectedCalendar.job_ids.forEach(id => { - if (jobIds.find(jobId => jobId === id)) { + selectedCalendar.job_ids.forEach((id) => { + if (jobIds.find((jobId) => jobId === id)) { selectedJobOptions.push({ label: id }); - } else if (groupIds.find(groupId => groupId === id)) { + } else if (groupIds.find((groupId) => groupId === id)) { selectedGroupOptions.push({ label: id }); } }); @@ -195,12 +195,12 @@ class NewCalendarUI extends Component { const allIds = isGlobalCalendar ? [GLOBAL_CALENDAR] : [ - ...selectedJobOptions.map(option => option.label), - ...selectedGroupOptions.map(option => option.label), + ...selectedJobOptions.map((option) => option.label), + ...selectedGroupOptions.map((option) => option.label), ]; // Reduce events to fields expected by api - const eventsToSave = events.map(event => ({ + const eventsToSave = events.map((event) => ({ description: event.description, start_time: event.start_time, end_time: event.end_time, @@ -217,12 +217,12 @@ class NewCalendarUI extends Component { return calendar; }; - onCreateGroupOption = newGroup => { + onCreateGroupOption = (newGroup) => { const newOption = { label: newGroup, }; // Select the option. - this.setState(prevState => ({ + this.setState((prevState) => ({ selectedGroupOptions: prevState.selectedGroupOptions.concat(newOption), })); }; @@ -233,19 +233,19 @@ class NewCalendarUI extends Component { }); }; - onJobSelection = selectedJobOptions => { + onJobSelection = (selectedJobOptions) => { this.setState({ selectedJobOptions, }); }; - onGroupSelection = selectedGroupOptions => { + onGroupSelection = (selectedGroupOptions) => { this.setState({ selectedGroupOptions, }); }; - onCalendarIdChange = e => { + onCalendarIdChange = (e) => { const isValid = validateCalendarId(e.target.value); this.setState({ @@ -254,14 +254,14 @@ class NewCalendarUI extends Component { }); }; - onDescriptionChange = e => { + onDescriptionChange = (e) => { this.setState({ description: e.target.value, }); }; showImportModal = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ isImportModalVisible: !prevState.isImportModalVisible, })); }; @@ -272,9 +272,9 @@ class NewCalendarUI extends Component { }); }; - onEventDelete = eventId => { - this.setState(prevState => ({ - events: prevState.events.filter(event => event.event_id !== eventId), + onEventDelete = (eventId) => { + this.setState((prevState) => ({ + events: prevState.events.filter((event) => event.event_id !== eventId), })); }; @@ -286,15 +286,15 @@ class NewCalendarUI extends Component { this.setState({ isNewEventModalVisible: true }); }; - addEvent = event => { - this.setState(prevState => ({ + addEvent = (event) => { + this.setState((prevState) => ({ events: [...prevState.events, event], isNewEventModalVisible: false, })); }; - addImportedEvents = events => { - this.setState(prevState => ({ + addImportedEvents = (events) => { + this.setState((prevState) => ({ events: [...prevState.events, ...events], isImportModalVisible: false, })); diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.test.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.test.js index 7f5ade64e7f14..0a6e8916fa657 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.test.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.test.js @@ -38,7 +38,7 @@ jest.mock('../../../services/ml_api_service', () => ({ jest.mock('./utils', () => ({ getCalendarSettingsData: jest.fn().mockImplementation( () => - new Promise(resolve => { + new Promise((resolve) => { resolve({ jobIds: ['test-job-one', 'test-job-2'], groupIds: ['test-group-one', 'test-group-two'], @@ -48,7 +48,7 @@ jest.mock('./utils', () => ({ ), })); jest.mock('../../../../../../../../src/plugins/kibana_react/public', () => ({ - withKibana: comp => { + withKibana: (comp) => { return comp; }, })); diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.js index 814f30a70db54..8380fd36b458c 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.js @@ -42,9 +42,7 @@ export class NewEventModal extends Component { super(props); const startDate = moment().startOf('day'); - const endDate = moment() - .startOf('day') - .add(1, 'days'); + const endDate = moment().startOf('day').add(1, 'days'); this.state = { startDate, @@ -55,7 +53,7 @@ export class NewEventModal extends Component { }; } - onDescriptionChange = e => { + onDescriptionChange = (e) => { this.setState({ description: e.target.value, }); @@ -76,7 +74,7 @@ export class NewEventModal extends Component { this.props.addEvent(event); }; - handleChangeStart = date => { + handleChangeStart = (date) => { let start = null; let end = this.state.endDate; @@ -96,7 +94,7 @@ export class NewEventModal extends Component { }); }; - handleChangeEnd = date => { + handleChangeEnd = (date) => { let start = this.state.startDate; let end = null; @@ -116,7 +114,7 @@ export class NewEventModal extends Component { }); }; - handleTimeStartChange = event => { + handleTimeStartChange = (event) => { const dateString = event.target.value; let isValidDate = false; @@ -136,7 +134,7 @@ export class NewEventModal extends Component { } }; - handleTimeEndChange = event => { + handleTimeEndChange = (event) => { const dateString = event.target.value; let isValidDate = false; diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.test.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.test.js index e91dce6124cef..f8b9c97db09e3 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.test.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_event_modal/new_event_modal.test.js @@ -42,10 +42,7 @@ describe('NewEventModal', () => { // trigger handleChangeStart directly with startMoment instance.handleChangeStart(startMoment); // add 3 days to endMoment as it will be adjusted to be one day after startDate - const expected = endMoment - .startOf('day') - .add(3, 'days') - .format(); + const expected = endMoment.startOf('day').add(3, 'days').format(); expect(wrapper.state('endDate').format()).toBe(expected); }); @@ -66,10 +63,7 @@ describe('NewEventModal', () => { // trigger handleChangeStart directly with endMoment instance.handleChangeStart(endMoment); // subtract 3 days from startDate as it will be adjusted to be one day before endDate - const expected = startMoment - .startOf('day') - .subtract(2, 'days') - .format(); + const expected = startMoment.startOf('day').subtract(2, 'days').format(); expect(wrapper.state('startDate').format()).toBe(expected); }); diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/utils.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/utils.js index efc54c181fdc1..874a1e14cb5aa 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/utils.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/utils.js @@ -12,10 +12,10 @@ function getJobIds() { return new Promise((resolve, reject) => { ml.jobs .jobsSummary() - .then(resp => { - resolve(resp.map(job => job.id)); + .then((resp) => { + resolve(resp.map((job) => job.id)); }) - .catch(err => { + .catch((err) => { const errorMessage = i18n.translate( 'xpack.ml.calendarsEdit.errorWithFetchingJobSummariesErrorMessage', { @@ -33,10 +33,10 @@ function getGroupIds() { return new Promise((resolve, reject) => { ml.jobs .groups() - .then(resp => { - resolve(resp.map(group => group.id)); + .then((resp) => { + resolve(resp.map((group) => group.id)); }) - .catch(err => { + .catch((err) => { const errorMessage = i18n.translate( 'xpack.ml.calendarsEdit.errorWithLoadingGroupsErrorMessage', { @@ -53,10 +53,10 @@ function getGroupIds() { function getCalendars() { return new Promise((resolve, reject) => { ml.calendars() - .then(resp => { + .then((resp) => { resolve(resp); }) - .catch(err => { + .catch((err) => { const errorMessage = i18n.translate( 'xpack.ml.calendarsEdit.errorWithLoadingCalendarsErrorMessage', { @@ -104,7 +104,5 @@ export function validateCalendarId(calendarId) { } export function generateTempId() { - return Math.random() - .toString(36) - .substr(2, 9); + return Math.random().toString(36).substr(2, 9); } diff --git a/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.js b/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.js index c968db0b32d5a..c1c00bb022f20 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.js @@ -75,7 +75,7 @@ export class CalendarsListUI extends Component { this.setState({ isDestroyModalVisible: true }); }; - setSelectedCalendarList = selectedCalendars => { + setSelectedCalendarList = (selectedCalendars) => { this.setState({ selectedForDeletion: selectedCalendars }); }; @@ -137,7 +137,7 @@ export class CalendarsListUI extends Component { defaultMessage="Delete {calendarsCount, plural, one {this calendar} other {these calendars}}? {calendarsList}" values={{ calendarsCount: selectedForDeletion.length, - calendarsList: selectedForDeletion.map(c => c.calendar_id).join(', '), + calendarsList: selectedForDeletion.map((c) => c.calendar_id).join(', '), }} />

diff --git a/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.test.js b/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.test.js index b2fce2c1474cb..619478db54441 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.test.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.test.js @@ -37,11 +37,11 @@ jest.mock('../../../services/ml_api_service', () => ({ jest.mock('react', () => { const r = jest.requireActual('react'); - return { ...r, memo: x => x }; + return { ...r, memo: (x) => x }; }); jest.mock('../../../../../../../../src/plugins/kibana_react/public', () => ({ - withKibana: node => { + withKibana: (node) => { return node; }, })); diff --git a/x-pack/plugins/ml/public/application/settings/calendars/list/header.test.js b/x-pack/plugins/ml/public/application/settings/calendars/list/header.test.js index 47dc373e537ba..857d2e7e6659b 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/list/header.test.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/list/header.test.js @@ -10,7 +10,7 @@ import React from 'react'; import { CalendarsListHeader } from './header'; jest.mock('../../../../../../../../src/plugins/kibana_react/public', () => ({ - withKibana: comp => { + withKibana: (comp) => { return comp; }, })); diff --git a/x-pack/plugins/ml/public/application/settings/calendars/list/table/table.js b/x-pack/plugins/ml/public/application/settings/calendars/list/table/table.js index be41eabd5ae2d..b81cc6fbb4c30 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/list/table/table.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/list/table/table.js @@ -45,7 +45,9 @@ export const CalendarsListTable = ({ sortable: true, truncateText: true, scope: 'row', - render: id => {id}, + render: (id) => ( + {id} + ), }, { field: 'job_ids_string', @@ -54,7 +56,7 @@ export const CalendarsListTable = ({ }), sortable: true, truncateText: true, - render: jobList => { + render: (jobList) => { return jobList === GLOBAL_CALENDAR ? ( + render: (eventsLength) => i18n.translate('xpack.ml.calendarsList.table.eventsCountLabel', { defaultMessage: '{eventsLength, plural, one {# event} other {# events}}', values: { eventsLength }, @@ -82,7 +84,7 @@ export const CalendarsListTable = ({ ]; const tableSelection = { - onSelectionChange: selection => setSelectedCalendarList(selection), + onSelectionChange: (selection) => setSelectedCalendarList(selection), }; const search = { diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/components/add_item_popover/add_item_popover.js b/x-pack/plugins/ml/public/application/settings/filter_lists/components/add_item_popover/add_item_popover.js index 404484b8055f2..816eea39059a8 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/components/add_item_popover/add_item_popover.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/components/add_item_popover/add_item_popover.js @@ -40,7 +40,7 @@ export class AddItemPopover extends Component { }; } - onItemsTextChange = e => { + onItemsTextChange = (e) => { this.setState({ itemsText: e.target.value, }); @@ -62,7 +62,7 @@ export class AddItemPopover extends Component { const items = this.state.itemsText.split('\n'); const addItems = []; // Remove duplicates. - items.forEach(item => { + items.forEach((item) => { if (addItems.indexOf(item) === -1 && item.length > 0) { addItems.push(item); } diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_list_modal.test.js b/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_list_modal.test.js index 0266bc2a55318..bb909ddc3aa78 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_list_modal.test.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_list_modal.test.js @@ -9,7 +9,7 @@ // with 'mock' so it can be used lazily. const mockCheckPermission = jest.fn(() => true); jest.mock('../../../../capabilities/check_capabilities', () => ({ - checkPermission: privilege => mockCheckPermission(privilege), + checkPermission: (privilege) => mockCheckPermission(privilege), })); jest.mock('../../../../services/ml_api_service', () => 'ml'); diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/components/edit_description_popover/edit_description_popover.js b/x-pack/plugins/ml/public/application/settings/filter_lists/components/edit_description_popover/edit_description_popover.js index e1e32afe08dbe..e7846cb546852 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/components/edit_description_popover/edit_description_popover.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/components/edit_description_popover/edit_description_popover.js @@ -33,7 +33,7 @@ export class EditDescriptionPopover extends Component { }; } - onChange = e => { + onChange = (e) => { this.setState({ value: e.target.value, }); diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/components/filter_list_usage_popover/filter_list_usage_popover.js b/x-pack/plugins/ml/public/application/settings/filter_lists/components/filter_list_usage_popover/filter_list_usage_popover.js index b3547b3ee6568..25c86c559e303 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/components/filter_list_usage_popover/filter_list_usage_popover.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/components/filter_list_usage_popover/filter_list_usage_popover.js @@ -39,7 +39,7 @@ export class FilterListUsagePopover extends Component { const linkText = `${entityValues.length} ${entityType}${entityValues.length !== 1 ? 's' : ''}`; - const listItems = entityValues.map(value =>
  • {value}
  • ); + const listItems = entityValues.map((value) =>
  • {value}
  • ); const button = ( diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.js b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.js index adf57632bc84b..6437e819db04f 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.js @@ -49,11 +49,11 @@ function getMatchingFilterItems(searchBarQuery, items) { // Convert the list of Strings into a list of Objects suitable for running through // the search bar query. - const allItems = items.map(item => ({ value: item })); + const allItems = items.map((item) => ({ value: item })); const matchingObjects = EuiSearchBar.Query.execute(searchBarQuery, allItems, { defaultFields: ['value'], }); - return matchingObjects.map(item => item.value); + return matchingObjects.map((item) => item.value); } function getActivePage(activePageState, itemsPerPage, numMatchingItems) { @@ -105,13 +105,13 @@ export class EditFilterListUI extends Component { } } - loadFilterList = filterId => { + loadFilterList = (filterId) => { ml.filters .filters({ filterId }) - .then(filter => { + .then((filter) => { this.setLoadedFilterState(filter); }) - .catch(resp => { + .catch((resp) => { console.log(`Error loading filter ${filterId}:`, resp); const { toasts } = this.props.kibana.services.notifications; toasts.addDanger( @@ -128,9 +128,9 @@ export class EditFilterListUI extends Component { }); }; - setLoadedFilterState = loadedFilter => { + setLoadedFilterState = (loadedFilter) => { // Store the loaded filter so we can diff changes to the items when saving updates. - this.setState(prevState => { + this.setState((prevState) => { const { itemsPerPage, searchQuery } = prevState; const matchingItems = getMatchingFilterItems(searchQuery, loadedFilter.items); @@ -150,23 +150,23 @@ export class EditFilterListUI extends Component { }); }; - updateNewFilterId = newFilterId => { + updateNewFilterId = (newFilterId) => { this.setState({ newFilterId, isNewFilterIdInvalid: !isValidFilterListId(newFilterId), }); }; - updateDescription = description => { + updateDescription = (description) => { this.setState({ description }); }; - addItems = itemsToAdd => { - this.setState(prevState => { + addItems = (itemsToAdd) => { + this.setState((prevState) => { const { itemsPerPage, searchQuery } = prevState; const items = [...prevState.items]; const alreadyInFilter = []; - itemsToAdd.forEach(item => { + itemsToAdd.forEach((item) => { if (items.indexOf(item) === -1) { items.push(item); } else { @@ -206,10 +206,10 @@ export class EditFilterListUI extends Component { }; deleteSelectedItems = () => { - this.setState(prevState => { + this.setState((prevState) => { const { selectedItems, itemsPerPage, searchQuery } = prevState; const items = [...prevState.items]; - selectedItems.forEach(item => { + selectedItems.forEach((item) => { const index = items.indexOf(item); if (index !== -1) { items.splice(index, 1); @@ -230,7 +230,7 @@ export class EditFilterListUI extends Component { }; onSearchChange = ({ query }) => { - this.setState(prevState => { + this.setState((prevState) => { const { items, itemsPerPage } = prevState; const matchingItems = getMatchingFilterItems(query, items); @@ -245,7 +245,7 @@ export class EditFilterListUI extends Component { }; setItemSelected = (item, isSelected) => { - this.setState(prevState => { + this.setState((prevState) => { const selectedItems = [...prevState.selectedItems]; const index = selectedItems.indexOf(item); if (isSelected === true && index === -1) { @@ -260,11 +260,11 @@ export class EditFilterListUI extends Component { }); }; - setActivePage = activePage => { + setActivePage = (activePage) => { this.setState({ activePage }); }; - setItemsPerPage = itemsPerPage => { + setItemsPerPage = (itemsPerPage) => { this.setState({ itemsPerPage, activePage: 0, @@ -277,11 +277,11 @@ export class EditFilterListUI extends Component { const { loadedFilter, newFilterId, description, items } = this.state; const filterId = this.props.filterId !== undefined ? this.props.filterId : newFilterId; saveFilterList(filterId, description, items, loadedFilter) - .then(savedFilter => { + .then((savedFilter) => { this.setLoadedFilterState(savedFilter); returnToFiltersList(); }) - .catch(resp => { + .catch((resp) => { console.log(`Error saving filter ${filterId}:`, resp); const { toasts } = this.props.kibana.services.notifications; toasts.addDanger( diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.test.js b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.test.js index a743a4b22ce92..1223194030e64 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.test.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.test.js @@ -37,7 +37,7 @@ jest.mock('../../../services/ml_api_service', () => ({ })); jest.mock('../../../../../../../../src/plugins/kibana_react/public', () => ({ - withKibana: node => { + withKibana: (node) => { return node; }, })); diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/header.js b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/header.js index f1efa173178f2..f47264221eaec 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/header.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/header.js @@ -88,7 +88,7 @@ export const EditFilterListHeader = ({ name="new_filter_id" value={newFilterId} isInvalid={isNewFilterIdInvalid} - onChange={e => updateNewFilterId(e.target.value)} + onChange={(e) => updateNewFilterId(e.target.value)} /> ); diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/utils.js b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/utils.js index c82be4cbfa71e..b07dfcc48c891 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/utils.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/utils.js @@ -21,19 +21,19 @@ export function saveFilterList(filterId, description, items, loadedFilterList) { if (loadedFilterList === undefined || loadedFilterList.filter_id === undefined) { // Create a new filter. addFilterList(filterId, description, items) - .then(newFilter => { + .then((newFilter) => { resolve(newFilter); }) - .catch(error => { + .catch((error) => { reject(error); }); } else { // Edit to existing filter. updateFilterList(loadedFilterList, description, items) - .then(updatedFilter => { + .then((updatedFilter) => { resolve(updatedFilter); }) - .catch(error => { + .catch((error) => { reject(error); }); } @@ -55,16 +55,16 @@ export function addFilterList(filterId, description, items) { // First check the filterId isn't already in use by loading the current list of filters. ml.filters .filtersStats() - .then(filterLists => { - const savedFilterIds = filterLists.map(filterList => filterList.filter_id); + .then((filterLists) => { + const savedFilterIds = filterLists.map((filterList) => filterList.filter_id); if (savedFilterIds.indexOf(filterId) === -1) { // Save the new filter. ml.filters .addFilter(filterId, description, items) - .then(newFilter => { + .then((newFilter) => { resolve(newFilter); }) - .catch(error => { + .catch((error) => { reject(error); }); } else { @@ -73,7 +73,7 @@ export function addFilterList(filterId, description, items) { reject(new Error(filterWithIdExistsErrorMessage)); } }) - .catch(error => { + .catch((error) => { reject(error); }); }); @@ -83,15 +83,15 @@ export function updateFilterList(loadedFilterList, description, items) { return new Promise((resolve, reject) => { // Get items added and removed from loaded filter. const loadedItems = loadedFilterList.items; - const addItems = items.filter(item => loadedItems.includes(item) === false); - const removeItems = loadedItems.filter(item => items.includes(item) === false); + const addItems = items.filter((item) => loadedItems.includes(item) === false); + const removeItems = loadedItems.filter((item) => items.includes(item) === false); ml.filters .updateFilter(loadedFilterList.filter_id, description, addItems, removeItems) - .then(updatedFilter => { + .then((updatedFilter) => { resolve(updatedFilter); }) - .catch(error => { + .catch((error) => { reject(error); }); }); diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.js b/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.js index 9e40d99f1c898..270d5fa350cae 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.js @@ -42,11 +42,11 @@ export class FilterListsUI extends Component { this.refreshFilterLists(); } - setFilterLists = filterLists => { + setFilterLists = (filterLists) => { // Check selected filter lists still exist. - this.setState(prevState => { - const loadedFilterIds = filterLists.map(filterList => filterList.filter_id); - const selectedFilterLists = prevState.selectedFilterLists.filter(filterList => { + this.setState((prevState) => { + const loadedFilterIds = filterLists.map((filterList) => filterList.filter_id); + const selectedFilterLists = prevState.selectedFilterLists.filter((filterList) => { return loadedFilterIds.indexOf(filterList.filter_id) !== -1; }); @@ -57,7 +57,7 @@ export class FilterListsUI extends Component { }); }; - setSelectedFilterLists = selectedFilterLists => { + setSelectedFilterLists = (selectedFilterLists) => { this.setState({ selectedFilterLists }); }; @@ -65,10 +65,10 @@ export class FilterListsUI extends Component { // Load the list of filters. ml.filters .filtersStats() - .then(filterLists => { + .then((filterLists) => { this.setFilterLists(filterLists); }) - .catch(resp => { + .catch((resp) => { console.log('Error loading list of filters:', resp); const { toasts } = this.props.kibana.services.notifications; toasts.addDanger( diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.test.js b/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.test.js index c1bcee4acdd37..6ddea7a3281d3 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.test.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.test.js @@ -17,7 +17,7 @@ jest.mock('../../../capabilities/check_capabilities', () => ({ })); jest.mock('../../../../../../../../src/plugins/kibana_react/public', () => ({ - withKibana: node => { + withKibana: (node) => { return node; }, })); diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/list/table.js b/x-pack/plugins/ml/public/application/settings/filter_lists/list/table.js index fcbf90ec62d4a..7f94f1f2534fb 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/list/table.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/list/table.js @@ -81,7 +81,9 @@ function getColumns() { name: i18n.translate('xpack.ml.settings.filterLists.table.idColumnName', { defaultMessage: 'ID', }), - render: id => {id}, + render: (id) => ( + {id} + ), sortable: true, scope: 'row', }, @@ -104,7 +106,7 @@ function getColumns() { name: i18n.translate('xpack.ml.settings.filterLists.table.inUseColumnName', { defaultMessage: 'In use', }), - render: usedBy => , + render: (usedBy) => , sortable: true, }, ]; @@ -157,10 +159,10 @@ export function FilterListsTable({ }; const tableSelection = { - selectable: filterList => + selectable: (filterList) => filterList.used_by === undefined || filterList.used_by.jobs.length === 0, selectableMessage: () => undefined, - onSelectionChange: selection => setSelectedFilterLists(selection), + onSelectionChange: (selection) => setSelectedFilterLists(selection), }; return ( diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/context_chart_mask/context_chart_mask.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/context_chart_mask/context_chart_mask.js index 43578e9f5898a..e9657ed601b78 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/context_chart_mask/context_chart_mask.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/context_chart_mask/context_chart_mask.js @@ -39,13 +39,13 @@ export function ContextChartMask(contextGroup, data, drawBounds, swimlaneHeight) this._y = null; } -ContextChartMask.prototype.style = function(prop, val) { +ContextChartMask.prototype.style = function (prop, val) { this.leftGroup.style(prop, val); this.rightGroup.style(prop, val); return this; }; -ContextChartMask.prototype.x = function(f) { +ContextChartMask.prototype.x = function (f) { if (f == null) { return this._x; } @@ -53,7 +53,7 @@ ContextChartMask.prototype.x = function(f) { return this; }; -ContextChartMask.prototype.y = function(f) { +ContextChartMask.prototype.y = function (f) { if (f == null) { return this._y; } @@ -61,7 +61,7 @@ ContextChartMask.prototype.y = function(f) { return this; }; -ContextChartMask.prototype.redraw = function() { +ContextChartMask.prototype.redraw = function () { const yDomain = this._y.domain(); const minY = yDomain[0]; const maxY = yDomain[1]; @@ -71,11 +71,11 @@ ContextChartMask.prototype.redraw = function() { const that = this; - const leftData = this.data.filter(function(d) { + const leftData = this.data.filter(function (d) { return d.date < that.from; }); - const rightData = this.data.filter(function(d) { + const rightData = this.data.filter(function (d) { return d.date > that.to; }); @@ -83,29 +83,29 @@ ContextChartMask.prototype.redraw = function() { if (this.drawBounds === true) { const boundedArea = d3.svg .area() - .x(function(d) { + .x(function (d) { return that._x(d.date) || 1; }) - .y0(function(d) { + .y0(function (d) { return that._y(Math.min(maxY, Math.max(d.lower, minY))); }) - .y1(function(d) { + .y1(function (d) { return that._y(Math.max(minY, Math.min(d.upper, maxY))); }) - .defined(d => d.lower !== null && d.upper !== null); + .defined((d) => d.lower !== null && d.upper !== null); this.leftGroup.select('.left.area.bounds').attr('d', boundedArea(leftData)); this.rightGroup.select('.right.area.bounds').attr('d', boundedArea(rightData)); } const valuesLine = d3.svg .line() - .x(function(d) { + .x(function (d) { return that._x(d.date); }) - .y(function(d) { + .y(function (d) { return that._y(d.value); }) - .defined(d => d.value !== null); + .defined((d) => d.value !== null); this.leftGroup.select('.left.values-line').attr('d', valuesLine(leftData)); drawLineChartDots(leftData, this.leftGroup, valuesLine, 1); @@ -168,7 +168,7 @@ ContextChartMask.prototype.redraw = function() { return this; }; -ContextChartMask.prototype.reveal = function(extent) { +ContextChartMask.prototype.reveal = function (extent) { this.from = extent[0]; this.to = extent[1]; this.redraw(); diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/entity_control/entity_control.tsx b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/entity_control/entity_control.tsx index 7bb0b27472c88..c144525699d81 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/entity_control/entity_control.tsx +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/entity_control/entity_control.tsx @@ -126,7 +126,7 @@ export class EntityControl extends Component { + inputRef={(input) => { if (input) { this.inputRef = input; } diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js index eded8460d2205..87bd2bb4af62c 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js @@ -72,17 +72,17 @@ export class ForecastingModalUI extends Component { addMessage = (message, status, clearFirst = false) => { const msg = { message, status }; - this.setState(prevState => ({ + this.setState((prevState) => ({ messages: clearFirst ? [msg] : [...prevState.messages, msg], })); }; - viewForecast = forecastId => { + viewForecast = (forecastId) => { this.props.setForecastId(forecastId); this.closeModal(); }; - onNewForecastDurationChange = event => { + onNewForecastDurationChange = (event) => { const newForecastDurationErrors = []; let isNewForecastDurationValid = true; const duration = parseInterval(event.target.value); @@ -157,7 +157,7 @@ export class ForecastingModalUI extends Component { }); this.runForecast(true); }) - .catch(resp => { + .catch((resp) => { console.log('Time series forecast modal - could not open job:', resp); this.addMessage( i18n.translate( @@ -200,7 +200,7 @@ export class ForecastingModalUI extends Component { .then(() => { this.setState({ jobClosingState: PROGRESS_STATES.DONE }); }) - .catch(response => { + .catch((response) => { console.log('Time series forecast modal - could not close job:', response); this.addMessage( i18n.translate( @@ -216,7 +216,7 @@ export class ForecastingModalUI extends Component { } }; - runForecast = closeJobAfterRunning => { + runForecast = (closeJobAfterRunning) => { this.setState({ forecastProgress: 0, }); @@ -227,7 +227,7 @@ export class ForecastingModalUI extends Component { mlForecastService .runForecast(this.props.job.job_id, `${durationInSeconds}s`) - .then(resp => { + .then((resp) => { // Endpoint will return { acknowledged:true, id: } before forecast is complete. // So wait for results and then refresh the dashboard to the end of the forecast. if (resp.forecast_id !== undefined) { @@ -236,7 +236,7 @@ export class ForecastingModalUI extends Component { this.runForecastErrorHandler(resp, closeJobAfterRunning); } }) - .catch(resp => this.runForecastErrorHandler(resp, closeJobAfterRunning)); + .catch((resp) => this.runForecastErrorHandler(resp, closeJobAfterRunning)); }; waitForForecastResults = (forecastId, closeJobAfterRunning) => { @@ -248,7 +248,7 @@ export class ForecastingModalUI extends Component { this.forecastChecker = setInterval(() => { mlForecastService .getForecastRequestStats(this.props.job, forecastId) - .then(resp => { + .then((resp) => { // Get the progress (stats value is between 0 and 1). const progress = _.get(resp, ['stats', 'forecast_progress'], previousProgress); const status = _.get(resp, ['stats', 'forecast_status']); @@ -264,7 +264,7 @@ export class ForecastingModalUI extends Component { // Display any messages returned in the request stats. let messages = _.get(resp, ['stats', 'forecast_messages'], []); - messages = messages.map(message => ({ message, status: MESSAGE_LEVEL.WARNING })); + messages = messages.map((message) => ({ message, status: MESSAGE_LEVEL.WARNING })); this.setState({ messages }); if (status === FORECAST_REQUEST_STATE.FINISHED) { @@ -281,7 +281,7 @@ export class ForecastingModalUI extends Component { this.props.setForecastId(forecastId); this.closeAfterRunningForecast(); }) - .catch(response => { + .catch((response) => { // Load the forecast data in the main page, // but leave this dialog open so the error can be viewed. console.log('Time series forecast modal - could not close job:', response); @@ -340,7 +340,7 @@ export class ForecastingModalUI extends Component { } } }) - .catch(resp => { + .catch((resp) => { console.log( 'Time series forecast modal - error loading stats of forecast from elasticsearch:', resp @@ -376,12 +376,12 @@ export class ForecastingModalUI extends Component { }; mlForecastService .getForecastsSummary(job, statusFinishedQuery, bounds.min.valueOf(), FORECASTS_VIEW_MAX) - .then(resp => { + .then((resp) => { this.setState({ previousForecasts: resp.forecasts, }); }) - .catch(resp => { + .catch((resp) => { console.log('Time series forecast modal - error obtaining forecasts summary:', resp); this.addMessage( i18n.translate( @@ -396,7 +396,7 @@ export class ForecastingModalUI extends Component { // Display a warning about running a forecast if there is high number // of partitioning fields. - const entityFieldNames = this.props.entities.map(entity => entity.fieldName); + const entityFieldNames = this.props.entities.map((entity) => entity.fieldName); if (entityFieldNames.length > 0) { ml.getCardinalityOfFields({ index: job.datafeed_config.indices, @@ -406,9 +406,9 @@ export class ForecastingModalUI extends Component { earliestMs: job.data_counts.earliest_record_timestamp, latestMs: job.data_counts.latest_record_timestamp, }) - .then(results => { + .then((results) => { let numPartitions = 1; - Object.values(results).forEach(cardinality => { + Object.values(results).forEach((cardinality) => { numPartitions = numPartitions * cardinality; }); if (numPartitions > WARN_NUM_PARTITIONS) { @@ -426,7 +426,7 @@ export class ForecastingModalUI extends Component { ); } }) - .catch(resp => { + .catch((resp) => { console.log( 'Time series forecast modal - error obtaining cardinality of fields:', resp diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js index 83c153ab39eba..42e9e28f5862d 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js @@ -25,7 +25,7 @@ function getColumns(viewForecast) { defaultMessage: 'Created', }), dataType: 'date', - render: date => formatHumanReadableDateTimeSeconds(date), + render: (date) => formatHumanReadableDateTimeSeconds(date), sortable: true, }, { @@ -34,7 +34,7 @@ function getColumns(viewForecast) { defaultMessage: 'From', }), dataType: 'date', - render: date => formatHumanReadableDateTimeSeconds(date), + render: (date) => formatHumanReadableDateTimeSeconds(date), sortable: true, }, { @@ -43,7 +43,7 @@ function getColumns(viewForecast) { defaultMessage: 'To', }), dataType: 'date', - render: date => formatHumanReadableDateTimeSeconds(date), + render: (date) => formatHumanReadableDateTimeSeconds(date), sortable: true, }, { @@ -51,7 +51,7 @@ function getColumns(viewForecast) { defaultMessage: 'View', }), width: '60px', - render: forecast => { + render: (forecast) => { const viewForecastAriaLabel = i18n.translate( 'xpack.ml.timeSeriesExplorer.forecastsList.viewForecastAriaLabel', { diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js index fca65ea2c1f3b..190bce1639c4a 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js @@ -158,25 +158,25 @@ class TimeseriesChartIntl extends Component { this.focusValuesLine = d3.svg .line() - .x(function(d) { + .x(function (d) { return focusXScale(d.date); }) - .y(function(d) { + .y(function (d) { return focusYScale(d.value); }) - .defined(d => d.value !== null); + .defined((d) => d.value !== null); this.focusBoundedArea = d3.svg .area() - .x(function(d) { + .x(function (d) { return focusXScale(d.date) || 1; }) - .y0(function(d) { + .y0(function (d) { return focusYScale(d.upper); }) - .y1(function(d) { + .y1(function (d) { return focusYScale(d.lower); }) - .defined(d => d.lower !== null && d.upper !== null); + .defined((d) => d.lower !== null && d.upper !== null); this.contextXScale = d3.time.scale().range([0, vizWidth]); this.contextYScale = d3.scale.linear().range([contextChartHeight, contextChartLineTopMargin]); @@ -274,10 +274,7 @@ class TimeseriesChartIntl extends Component { const fieldFormat = this.fieldFormat; - const svg = chartElement - .append('svg') - .attr('width', svgWidth) - .attr('height', svgHeight); + const svg = chartElement.append('svg').attr('width', svgWidth).attr('height', svgHeight); let contextDataMin; let contextDataMax; @@ -290,11 +287,11 @@ class TimeseriesChartIntl extends Component { ? contextChartData : contextChartData.concat(contextForecastData); - contextDataMin = d3.min(combinedData, d => Math.min(d.value, d.lower)); - contextDataMax = d3.max(combinedData, d => Math.max(d.value, d.upper)); + contextDataMin = d3.min(combinedData, (d) => Math.min(d.value, d.lower)); + contextDataMax = d3.max(combinedData, (d) => Math.max(d.value, d.upper)); } else { - contextDataMin = d3.min(contextChartData, d => d.value); - contextDataMax = d3.max(contextChartData, d => d.value); + contextDataMin = d3.min(contextChartData, (d) => d.value); + contextDataMax = d3.max(contextChartData, (d) => d.value); } // Set the size of the left margin according to the width of the largest y axis tick label. @@ -324,14 +321,14 @@ class TimeseriesChartIntl extends Component { .data(focusYScale.ticks()) .enter() .append('text') - .text(d => { + .text((d) => { if (fieldFormat !== undefined) { return fieldFormat.convert(d, 'text'); } else { return focusYScale.tickFormat()(d); } }) - .each(function() { + .each(function () { maxYAxisLabelWidth = Math.max( this.getBBox().width + focusYAxis.tickPadding(), maxYAxisLabelWidth @@ -359,10 +356,7 @@ class TimeseriesChartIntl extends Component { ); // Mask to hide annotations overflow - const annotationsMask = svg - .append('defs') - .append('mask') - .attr('id', ANNOTATION_MASK_ID); + const annotationsMask = svg.append('defs').append('mask').attr('id', ANNOTATION_MASK_ID); annotationsMask .append('rect') @@ -622,7 +616,7 @@ class TimeseriesChartIntl extends Component { (focusForecastData !== undefined && focusForecastData.length > 0) ) { if (this.fieldFormat !== undefined) { - this.focusYAxis.tickFormat(d => this.fieldFormat.convert(d, 'text')); + this.focusYAxis.tickFormat((d) => this.fieldFormat.convert(d, 'text')); } else { // Use default tick formatter. this.focusYAxis.tickFormat(null); @@ -637,7 +631,7 @@ class TimeseriesChartIntl extends Component { combinedData = data.concat(focusForecastData); } - yMin = d3.min(combinedData, d => { + yMin = d3.min(combinedData, (d) => { let metricValue = d.value; if (metricValue === null && d.anomalyScore !== undefined && d.actual !== undefined) { // If an anomaly coincides with a gap in the data, use the anomaly actual value. @@ -653,7 +647,7 @@ class TimeseriesChartIntl extends Component { } return metricValue; }); - yMax = d3.max(combinedData, d => { + yMax = d3.max(combinedData, (d) => { let metricValue = d.value; if (metricValue === null && d.anomalyScore !== undefined && d.actual !== undefined) { // If an anomaly coincides with a gap in the data, use the anomaly actual value. @@ -681,7 +675,7 @@ class TimeseriesChartIntl extends Component { // between annotation labels, chart lines and anomalies. if (focusAnnotationData && focusAnnotationData.length > 0) { const levels = getAnnotationLevels(focusAnnotationData); - const maxLevel = d3.max(Object.keys(levels).map(key => levels[key])); + const maxLevel = d3.max(Object.keys(levels).map((key) => levels[key])); // TODO needs revisiting to be a more robust normalization yMax = yMax * (1 + (maxLevel + 1) / 5); } @@ -698,9 +692,11 @@ class TimeseriesChartIntl extends Component { timeBuckets.setBounds(bounds); const xAxisTickFormat = timeBuckets.getScaledDateFormat(); focusChart.select('.x.axis').call( - this.focusXAxis.ticks(numTicksForDateFormat(this.vizWidth), xAxisTickFormat).tickFormat(d => { - return moment(d).format(xAxisTickFormat); - }) + this.focusXAxis + .ticks(numTicksForDateFormat(this.vizWidth), xAxisTickFormat) + .tickFormat((d) => { + return moment(d).format(xAxisTickFormat); + }) ); focusChart.select('.y.axis').call(this.focusYAxis); @@ -740,7 +736,7 @@ class TimeseriesChartIntl extends Component { .selectAll('.metric-value') .data( data.filter( - d => + (d) => (d.value !== null || typeof d.anomalyScore === 'number') && !showMultiBucketAnomalyMarker(d) ) @@ -753,20 +749,20 @@ class TimeseriesChartIntl extends Component { .enter() .append('circle') .attr('r', LINE_CHART_ANOMALY_RADIUS) - .on('mouseover', function(d) { + .on('mouseover', function (d) { showFocusChartTooltip(d, this); }) .on('mouseout', () => this.props.tooltipService.hide()); // Update all dots to new positions. dots - .attr('cx', d => { + .attr('cx', (d) => { return this.focusXScale(d.date); }) - .attr('cy', d => { + .attr('cy', (d) => { return this.focusYScale(d.value); }) - .attr('class', d => { + .attr('class', (d) => { let markerClass = 'metric-value'; if (_.has(d, 'anomalyScore')) { markerClass += ` anomaly-marker ${getSeverityWithLow(d.anomalyScore).id}`; @@ -778,7 +774,9 @@ class TimeseriesChartIntl extends Component { const multiBucketMarkers = d3 .select('.focus-chart-markers') .selectAll('.multi-bucket') - .data(data.filter(d => d.anomalyScore !== null && showMultiBucketAnomalyMarker(d) === true)); + .data( + data.filter((d) => d.anomalyScore !== null && showMultiBucketAnomalyMarker(d) === true) + ); // Remove multi-bucket markers that are no longer needed. multiBucketMarkers.exit().remove(); @@ -787,14 +785,8 @@ class TimeseriesChartIntl extends Component { multiBucketMarkers .enter() .append('path') - .attr( - 'd', - d3.svg - .symbol() - .size(MULTI_BUCKET_SYMBOL_SIZE) - .type('cross') - ) - .on('mouseover', function(d) { + .attr('d', d3.svg.symbol().size(MULTI_BUCKET_SYMBOL_SIZE).type('cross')) + .on('mouseover', function (d) { showFocusChartTooltip(d, this); }) .on('mouseout', () => this.props.tooltipService.hide()); @@ -803,15 +795,15 @@ class TimeseriesChartIntl extends Component { multiBucketMarkers .attr( 'transform', - d => `translate(${this.focusXScale(d.date)}, ${this.focusYScale(d.value)})` + (d) => `translate(${this.focusXScale(d.date)}, ${this.focusYScale(d.value)})` ) - .attr('class', d => `anomaly-marker multi-bucket ${getSeverityWithLow(d.anomalyScore).id}`); + .attr('class', (d) => `anomaly-marker multi-bucket ${getSeverityWithLow(d.anomalyScore).id}`); // Add rectangular markers for any scheduled events. const scheduledEventMarkers = d3 .select('.focus-chart-markers') .selectAll('.scheduled-event-marker') - .data(data.filter(d => d.scheduledEvents !== undefined)); + .data(data.filter((d) => d.scheduledEvents !== undefined)); // Remove markers that are no longer needed i.e. if number of chart points has decreased. scheduledEventMarkers.exit().remove(); @@ -828,8 +820,8 @@ class TimeseriesChartIntl extends Component { // Update all markers to new positions. scheduledEventMarkers - .attr('x', d => this.focusXScale(d.date) - LINE_CHART_ANOMALY_RADIUS) - .attr('y', d => this.focusYScale(d.value) - 3); + .attr('x', (d) => this.focusXScale(d.date) - LINE_CHART_ANOMALY_RADIUS) + .attr('y', (d) => this.focusYScale(d.value) - 3); // Plot any forecast data in scope. if (focusForecastData !== undefined) { @@ -854,17 +846,17 @@ class TimeseriesChartIntl extends Component { .enter() .append('circle') .attr('r', LINE_CHART_ANOMALY_RADIUS) - .on('mouseover', function(d) { + .on('mouseover', function (d) { showFocusChartTooltip(d, this); }) .on('mouseout', () => this.props.tooltipService.hide()); // Update all dots to new positions. forecastDots - .attr('cx', d => { + .attr('cx', (d) => { return this.focusXScale(d.date); }) - .attr('cy', d => { + .attr('cy', (d) => { return this.focusYScale(d.value); }) .attr('class', 'metric-value') @@ -895,14 +887,14 @@ class TimeseriesChartIntl extends Component { ); const zoomOptions = [{ durationMs: autoZoomDuration, label: 'auto' }]; - _.each(ZOOM_INTERVAL_OPTIONS, option => { + _.each(ZOOM_INTERVAL_OPTIONS, (option) => { if (option.duration.asSeconds() > minSecs && option.duration.asSeconds() < boundsSecs) { zoomOptions.push({ durationMs: option.duration.asMilliseconds(), label: option.label }); } }); xPos += zoomLabel.node().getBBox().width + 4; - _.each(zoomOptions, option => { + _.each(zoomOptions, (option) => { const text = zoomGroup .append('a') .attr('data-ms', option.durationMs) @@ -949,7 +941,7 @@ class TimeseriesChartIntl extends Component { } const chartElement = d3.select(this.rootNode); - chartElement.selectAll('.focus-zoom a').on('click', function() { + chartElement.selectAll('.focus-zoom a').on('click', function () { d3.event.preventDefault(); setZoomInterval(d3.select(this).attr('data-ms')); }); @@ -968,7 +960,7 @@ class TimeseriesChartIntl extends Component { const combinedData = contextForecastData === undefined ? data : data.concat(contextForecastData); const valuesRange = { min: Number.MAX_VALUE, max: Number.MIN_VALUE }; - _.each(combinedData, item => { + _.each(combinedData, (item) => { valuesRange.min = Math.min(item.value, valuesRange.min); valuesRange.max = Math.max(item.value, valuesRange.max); }); @@ -981,7 +973,7 @@ class TimeseriesChartIntl extends Component { (contextForecastData !== undefined && contextForecastData.length > 0) ) { const boundsRange = { min: Number.MAX_VALUE, max: Number.MIN_VALUE }; - _.each(combinedData, item => { + _.each(combinedData, (item) => { boundsRange.min = Math.min(item.lower, boundsRange.min); boundsRange.max = Math.max(item.upper, boundsRange.max); }); @@ -1034,7 +1026,7 @@ class TimeseriesChartIntl extends Component { .outerTickSize(0) .tickPadding(0) .ticks(numTicksForDateFormat(cxtWidth, xAxisTickFormat)) - .tickFormat(d => { + .tickFormat((d) => { return moment(d).format(xAxisTickFormat); }); @@ -1042,16 +1034,16 @@ class TimeseriesChartIntl extends Component { const contextBoundsArea = d3.svg .area() - .x(d => { + .x((d) => { return this.contextXScale(d.date); }) - .y0(d => { + .y0((d) => { return this.contextYScale(Math.min(chartLimits.max, Math.max(d.lower, chartLimits.min))); }) - .y1(d => { + .y1((d) => { return this.contextYScale(Math.max(chartLimits.min, Math.min(d.upper, chartLimits.max))); }) - .defined(d => d.lower !== null && d.upper !== null); + .defined((d) => d.lower !== null && d.upper !== null); if (modelPlotEnabled === true) { cxtGroup @@ -1063,19 +1055,15 @@ class TimeseriesChartIntl extends Component { const contextValuesLine = d3.svg .line() - .x(d => { + .x((d) => { return this.contextXScale(d.date); }) - .y(d => { + .y((d) => { return this.contextYScale(d.value); }) - .defined(d => d.value !== null); + .defined((d) => d.value !== null); - cxtGroup - .append('path') - .datum(data) - .attr('class', 'values-line') - .attr('d', contextValuesLine); + cxtGroup.append('path').datum(data).attr('class', 'values-line').attr('d', contextValuesLine); drawLineChartDots(data, cxtGroup, contextValuesLine, 1); // Create the path elements for the forecast value line and bounds area. @@ -1107,10 +1095,7 @@ class TimeseriesChartIntl extends Component { .y(this.contextYScale); // Draw the x axis on top of the mask so that the labels are visible. - cxtGroup - .append('g') - .attr('class', 'x axis context-chart-axis') - .call(xAxis); + cxtGroup.append('g').attr('class', 'x axis context-chart-axis').call(xAxis); // Move the x axis labels up so that they are inside the contact chart area. cxtGroup.selectAll('.x.context-chart-axis text').attr('dy', cxtChartHeight - 5); @@ -1120,7 +1105,7 @@ class TimeseriesChartIntl extends Component { this.drawContextBrush(cxtGroup); } - drawContextBrush = contextGroup => { + drawContextBrush = (contextGroup) => { const { contextChartSelected } = this.props; const brush = this.brush; @@ -1128,10 +1113,7 @@ class TimeseriesChartIntl extends Component { const mask = this.mask; // Create the brush for zooming in to the focus area of interest. - brush - .x(contextXScale) - .on('brush', brushing) - .on('brushend', brushed); + brush.x(contextXScale).on('brush', brushing).on('brushend', brushed); contextGroup .append('g') @@ -1143,15 +1125,9 @@ class TimeseriesChartIntl extends Component { // move the left and right resize areas over to // be under the handles - contextGroup - .selectAll('.w rect') - .attr('x', -10) - .attr('width', 10); + contextGroup.selectAll('.w rect').attr('x', -10).attr('width', 10); - contextGroup - .selectAll('.e rect') - .attr('x', 0) - .attr('width', 10); + contextGroup.selectAll('.e rect').attr('x', 0).attr('width', 10); const handleBrushExtent = brush.extent(); @@ -1219,7 +1195,7 @@ class TimeseriesChartIntl extends Component { } // Set the color of the swimlane cells according to whether they are inside the selection. - contextGroup.selectAll('.swimlane-cell').style('fill', d => { + contextGroup.selectAll('.swimlane-cell').style('fill', (d) => { const cellMs = d.date.getTime(); if (cellMs < selectionMin || cellMs > selectionMax) { return anomalyGrayScale(d.score); @@ -1248,15 +1224,9 @@ class TimeseriesChartIntl extends Component { // Need to use the min(earliest) and max(earliest) of the context chart // aggregation to align the axes of the chart and swimlane elements. const xAxisDomain = this.calculateContextXAxisDomain(); - const x = d3.time - .scale() - .range([0, swlWidth]) - .domain(xAxisDomain); + const x = d3.time.scale().range([0, swlWidth]).domain(xAxisDomain); - const y = d3.scale - .linear() - .range([swlHeight, 0]) - .domain([0, swlHeight]); + const y = d3.scale.linear().range([swlHeight, 0]).domain([0, swlHeight]); const xAxis = d3.svg .axis() @@ -1281,10 +1251,7 @@ class TimeseriesChartIntl extends Component { .attr('transform', 'translate(0,' + swlHeight + ')') .call(xAxis); - axes - .append('g') - .attr('class', 'y axis') - .call(yAxis); + axes.append('g').attr('class', 'y axis').call(yAxis); const earliest = xAxisDomain[0].getTime(); const latest = xAxisDomain[1].getTime(); @@ -1294,27 +1261,23 @@ class TimeseriesChartIntl extends Component { cellWidth = 1; } - const cells = swlGroup - .append('g') - .attr('class', 'swimlane-cells') - .selectAll('rect') - .data(data); + const cells = swlGroup.append('g').attr('class', 'swimlane-cells').selectAll('rect').data(data); cells .enter() .append('rect') - .attr('x', d => { + .attr('x', (d) => { return x(d.date); }) .attr('y', 0) .attr('rx', 0) .attr('ry', 0) - .attr('class', d => { + .attr('class', (d) => { return d.score > 0 ? 'swimlane-cell' : 'swimlane-cell-hidden'; }) .attr('width', cellWidth) .attr('height', swlHeight) - .style('fill', d => { + .style('fill', (d) => { return anomalyColorScale(d.score); }); }; @@ -1675,28 +1638,24 @@ class TimeseriesChartIntl extends Component { selectedMarker .enter() .append('path') - .attr( - 'd', - d3.svg - .symbol() - .size(MULTI_BUCKET_SYMBOL_SIZE) - .type('cross') - ) - .attr('transform', d => `translate(${focusXScale(d.date)}, ${focusYScale(d.value)})`) + .attr('d', d3.svg.symbol().size(MULTI_BUCKET_SYMBOL_SIZE).type('cross')) + .attr('transform', (d) => `translate(${focusXScale(d.date)}, ${focusYScale(d.value)})`) .attr( 'class', - d => `anomaly-marker multi-bucket ${getSeverityWithLow(d.anomalyScore).id} highlighted` + (d) => + `anomaly-marker multi-bucket ${getSeverityWithLow(d.anomalyScore).id} highlighted` ); } else { selectedMarker .enter() .append('circle') .attr('r', LINE_CHART_ANOMALY_RADIUS) - .attr('cx', d => focusXScale(d.date)) - .attr('cy', d => focusYScale(d.value)) + .attr('cx', (d) => focusXScale(d.date)) + .attr('cy', (d) => focusYScale(d.value)) .attr( 'class', - d => `anomaly-marker metric-value ${getSeverityWithLow(d.anomalyScore).id} highlighted` + (d) => + `anomaly-marker metric-value ${getSeverityWithLow(d.anomalyScore).id} highlighted` ); } @@ -1713,9 +1672,7 @@ class TimeseriesChartIntl extends Component { } unhighlightFocusChartAnomaly() { - d3.select('.focus-chart-markers') - .selectAll('.anomaly-marker.highlighted') - .remove(); + d3.select('.focus-chart-markers').selectAll('.anomaly-marker.highlighted').remove(); this.props.tooltipService.hide(); } @@ -1732,7 +1689,7 @@ class TimeseriesChartIntl extends Component { } } -export const TimeseriesChart = props => { +export const TimeseriesChart = (props) => { const annotationProp = useObservable(annotation$); if (annotationProp === undefined) { return null; diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.js index 784ab102fd8ca..2a0fcd57467bd 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.js @@ -13,7 +13,7 @@ import React from 'react'; import { TimeseriesChart } from './timeseries_chart'; jest.mock('../../../util/time_buckets', () => ({ - TimeBuckets: function() { + TimeBuckets: function () { this.setBounds = jest.fn(); this.setInterval = jest.fn(); this.getScaledDateFormat = jest.fn(); diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_annotations.ts b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_annotations.ts index f23c52fc7119a..0b541d54ee7b3 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_annotations.ts +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_annotations.ts @@ -22,10 +22,7 @@ export const ANNOTATION_MASK_ID = 'mlAnnotationMask'; export function getAnnotationBrush(this: TimeseriesChart) { const focusXScale = this.focusXScale; - const annotateBrush = d3.svg - .brush() - .x(focusXScale) - .on('brushend', brushend.bind(this)); + const annotateBrush = d3.svg.brush().x(focusXScale).on('brushend', brushend.bind(this)); // cast a reference to this so we get the latest state when brushend() gets called function brushend(this: TimeseriesChart) { @@ -114,7 +111,7 @@ export function renderAnnotations( const upperTextMargin = ANNOTATION_UPPER_TEXT_MARGIN; const durations: Dictionary = {}; - focusAnnotationData.forEach(d => { + focusAnnotationData.forEach((d) => { if (d.key !== undefined) { const duration = (d.end_timestamp || 0) - d.timestamp; durations[d.key] = duration; @@ -137,10 +134,7 @@ export function renderAnnotations( .selectAll('g.mlAnnotation') .data(focusAnnotationData || [], (d: Annotation) => d._id || ''); - annotations - .enter() - .append('g') - .classed('mlAnnotation', true); + annotations.enter().append('g').classed('mlAnnotation', true); const rects = annotations.selectAll('.mlAnnotationRect').data((d: Annotation) => [d]); @@ -151,7 +145,7 @@ export function renderAnnotations( .attr('ry', ANNOTATION_RECT_BORDER_RADIUS) .classed('mlAnnotationRect', true) .attr('mask', `url(#${ANNOTATION_MASK_ID})`) - .on('mouseover', function(this: object, d: Annotation) { + .on('mouseover', function (this: object, d: Annotation) { showFocusChartTooltip(d, this); }) .on('mouseout', () => hideFocusChartTooltip()) @@ -189,8 +183,8 @@ export function renderAnnotations( rects.exit().remove(); - const textRects = annotations.selectAll('.mlAnnotationTextRect').data(d => [d]); - const texts = annotations.selectAll('.mlAnnotationText').data(d => [d]); + const textRects = annotations.selectAll('.mlAnnotationTextRect').data((d) => [d]); + const texts = annotations.selectAll('.mlAnnotationText').data((d) => [d]); textRects .enter() @@ -201,10 +195,7 @@ export function renderAnnotations( .attr('rx', ANNOTATION_RECT_BORDER_RADIUS) .attr('ry', ANNOTATION_RECT_BORDER_RADIUS); - texts - .enter() - .append('text') - .classed('mlAnnotationText', true); + texts.enter().append('text').classed('mlAnnotationText', true); function labelXOffset(ts: number) { const earliestMs = focusXScale.domain()[0]; @@ -271,7 +262,7 @@ export function getAnnotationWidth( export function highlightFocusChartAnnotation(annotation: Annotation) { const annotations = d3.selectAll('.mlAnnotation'); - annotations.each(function(d) { + annotations.each(function (d) { // @ts-ignore const element = d3.select(this); @@ -288,7 +279,7 @@ export function highlightFocusChartAnnotation(annotation: Annotation) { export function unhighlightFocusChartAnnotation() { const annotations = d3.selectAll('.mlAnnotation'); - annotations.each(function() { + annotations.each(function () { // @ts-ignore const element = d3.select(this); diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts index 4c57eda65a9da..ce5a7565c519b 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseries_search_service.ts @@ -96,7 +96,7 @@ function getMetricData( interval ) .pipe( - map(resp => { + map((resp) => { _.each(resp.results, (value, time) => { // @ts-ignore obj.results[time] = { @@ -134,7 +134,7 @@ function getChartDetails( } obj.results.functionLabel = functionLabel; - const blankEntityFields = _.filter(entityFields, entity => { + const blankEntityFields = _.filter(entityFields, (entity) => { return entity.fieldValue === null; }); @@ -155,7 +155,7 @@ function getChartDetails( latestMs, }) .then((results: any) => { - _.each(blankEntityFields, field => { + _.each(blankEntityFields, (field) => { // results will not contain keys for non-aggregatable fields, // so store as 0 to indicate over all field values. obj.results.entityData.entities.push({ diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js index 4e04a63640a87..34da6b8ef6af6 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js @@ -95,7 +95,7 @@ function getEntityControlOptions(fieldValues) { fieldValues.sort(); - return fieldValues.map(value => { + return fieldValues.map((value) => { return { label: value === '' ? EMPTY_FIELD_VALUE_LABEL : value, value }; }); } @@ -206,7 +206,7 @@ export class TimeSeriesExplorer extends React.Component { return fieldNamesWithEmptyValues.length === 0; }; - detectorIndexChangeHandler = e => { + detectorIndexChangeHandler = (e) => { const { appStateHandler } = this.props; const id = e.target.value; if (id !== undefined) { @@ -215,13 +215,13 @@ export class TimeSeriesExplorer extends React.Component { }; toggleShowAnnotationsHandler = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ showAnnotations: !prevState.showAnnotations, })); }; toggleShowForecastHandler = () => { - this.setState(prevState => ({ + this.setState((prevState) => ({ showForecast: !prevState.showForecast, })); }; @@ -304,14 +304,14 @@ export class TimeSeriesExplorer extends React.Component { focusAggregationInterval, selectedForecastId, modelPlotEnabled, - entityControls.filter(entity => entity.fieldValue !== null), + entityControls.filter((entity) => entity.fieldValue !== null), searchBounds, selectedJob, TIME_FIELD_NAME ); } - contextChartSelected = selection => { + contextChartSelected = (selection) => { const zoomState = { from: selection.from.toISOString(), to: selection.to.toISOString(), @@ -375,10 +375,10 @@ export class TimeSeriesExplorer extends React.Component { ANOMALIES_TABLE_DEFAULT_QUERY_SIZE ) .pipe( - map(resp => { + map((resp) => { const anomalies = resp.anomalies; const detectorsByJob = mlJobService.detectorsByJob; - anomalies.forEach(anomaly => { + anomalies.forEach((anomaly) => { // Add a detector property to each anomaly. // Default to functionDescription if no description available. // TODO - when job_service is moved server_side, move this to server endpoint. @@ -450,7 +450,7 @@ export class TimeSeriesExplorer extends React.Component { .toPromise(); const entityValues = {}; - entities.forEach(entity => { + entities.forEach((entity) => { let fieldValues; if (partitionField?.name === entity.fieldName) { @@ -468,7 +468,7 @@ export class TimeSeriesExplorer extends React.Component { this.setState({ entitiesLoading: false, entityValues }); }; - setForecastId = forecastId => { + setForecastId = (forecastId) => { this.props.appStateHandler(APP_STATE_ACTION.SET_FORECAST_ID, forecastId); }; @@ -528,7 +528,7 @@ export class TimeSeriesExplorer extends React.Component { // finish() function, called after each data set has been loaded and processed. // The last one to call it will trigger the page render. - const finish = counterVar => { + const finish = (counterVar) => { awaitingCount--; if (awaitingCount === 0 && counterVar === loadCounter) { stateUpdate.hasResults = @@ -575,7 +575,7 @@ export class TimeSeriesExplorer extends React.Component { } }; - const nonBlankEntities = entityControls.filter(entity => { + const nonBlankEntities = entityControls.filter((entity) => { return entity.fieldValue !== null; }); @@ -626,12 +626,12 @@ export class TimeSeriesExplorer extends React.Component { stateUpdate.contextAggregationInterval.expression ) .toPromise() - .then(resp => { + .then((resp) => { const fullRangeChartData = processMetricPlotResults(resp.results, modelPlotEnabled); stateUpdate.contextChartData = fullRangeChartData; finish(counter); }) - .catch(resp => { + .catch((resp) => { console.log( 'Time series explorer - error getting metric data from elasticsearch:', resp @@ -648,12 +648,12 @@ export class TimeSeriesExplorer extends React.Component { searchBounds.max.valueOf(), stateUpdate.contextAggregationInterval.expression ) - .then(resp => { + .then((resp) => { const fullRangeRecordScoreData = processRecordScoreResults(resp.results); stateUpdate.swimlaneData = fullRangeRecordScoreData; finish(counter); }) - .catch(resp => { + .catch((resp) => { console.log( 'Time series explorer - error getting bucket anomaly scores from elasticsearch:', resp @@ -669,11 +669,11 @@ export class TimeSeriesExplorer extends React.Component { searchBounds.min.valueOf(), searchBounds.max.valueOf() ) - .then(resp => { + .then((resp) => { stateUpdate.chartDetails = resp.results; finish(counter); }) - .catch(resp => { + .catch((resp) => { console.log( 'Time series explorer - error getting entity counts from elasticsearch:', resp @@ -701,11 +701,11 @@ export class TimeSeriesExplorer extends React.Component { aggType ) .toPromise() - .then(resp => { + .then((resp) => { stateUpdate.contextForecastData = processForecastResults(resp.results); finish(counter); }) - .catch(resp => { + .catch((resp) => { console.log( `Time series explorer - error loading data for forecast ID ${selectedForecastId}`, resp @@ -775,7 +775,7 @@ export class TimeSeriesExplorer extends React.Component { */ getCriteriaFields(detectorIndex, entities) { // Only filter on the entity if the field has a value. - const nonBlankEntities = entities.filter(entity => entity.fieldValue !== null); + const nonBlankEntities = entities.filter((entity) => entity.fieldValue !== null); return [ { fieldName: 'detector_index', @@ -822,7 +822,7 @@ export class TimeSeriesExplorer extends React.Component { } // Populate the map of jobs / detectors / field formatters for the selected IDs and refresh. - mlFieldFormatService.populateFormats([jobId]).catch(err => { + mlFieldFormatService.populateFormats([jobId]).catch((err) => { console.log('Error populating field formats:', err); }); } @@ -839,14 +839,14 @@ export class TimeSeriesExplorer extends React.Component { this.subscriptions.add( this.contextChart$ .pipe( - tap(selection => { + tap((selection) => { this.setState({ zoomFrom: selection.from, zoomTo: selection.to, }); }), debounceTime(500), - tap(selection => { + tap((selection) => { const { contextChartData, contextForecastData, @@ -875,7 +875,7 @@ export class TimeSeriesExplorer extends React.Component { }); } }), - switchMap(selection => { + switchMap((selection) => { const { selectedJobId } = this.props; const jobs = createTimeSeriesJobData(mlJobService.jobs); const selectedJob = mlJobService.getJob(selectedJobId); @@ -987,7 +987,7 @@ export class TimeSeriesExplorer extends React.Component { const tableControlsListener = () => { const { zoomFrom, zoomTo } = this.state; if (zoomFrom !== undefined && zoomTo !== undefined) { - this.loadAnomaliesTableData(zoomFrom.getTime(), zoomTo.getTime()).subscribe(res => + this.loadAnomaliesTableData(zoomFrom.getTime(), zoomTo.getTime()).subscribe((res) => this.setState(res) ); } @@ -1076,7 +1076,7 @@ export class TimeSeriesExplorer extends React.Component { const fieldNamesWithEmptyValues = this.getFieldNamesWithEmptyValues(); const arePartitioningFieldsProvided = this.arePartitioningFieldsProvided(); - const detectorSelectOptions = getViewableDetectors(selectedJob).map(d => ({ + const detectorSelectOptions = getViewableDetectors(selectedJob).map((d) => ({ value: d.index, text: d.detector_description, })); @@ -1148,7 +1148,7 @@ export class TimeSeriesExplorer extends React.Component { /> - {entityControls.map(entity => { + {entityControls.map((entity) => { const entityKey = `${entity.fieldName}`; const forceSelection = !hasEmptyFieldValues && entity.fieldValue === null; hasEmptyFieldValues = !hasEmptyFieldValues && forceSelection; @@ -1219,7 +1219,7 @@ export class TimeSeriesExplorer extends React.Component { {chartDetails.entityData.entities.length > 0 && '('} {chartDetails.entityData.entities - .map(entity => { + .map((entity) => { return `${entity.fieldName}: ${entity.fieldValue}`; }) .join(', ')} @@ -1300,7 +1300,7 @@ export class TimeSeriesExplorer extends React.Component {
    - {tooltipService => ( + {(tooltipService) => ( { + return singleTimeSeriesJobs.map((job) => { const bucketSpan = parseInterval(job.analysis_config.bucket_span); return { id: job.job_id, @@ -110,7 +110,7 @@ export function processDataForFocusAnomalies( if (chartData !== undefined && chartData.length > 0) { lastChartDataPointTime = chartData[chartData.length - 1].date.getTime(); } - anomalyRecords.forEach(record => { + anomalyRecords.forEach((record) => { const recordTime = record[TIME_FIELD_NAME]; const chartPoint = findChartPointForAnomalyTime(chartData, recordTime, aggregationInterval); if (chartPoint === undefined) { @@ -123,7 +123,7 @@ export function processDataForFocusAnomalies( timesToAddPointsFor.sort((a, b) => a - b); - timesToAddPointsFor.forEach(time => { + timesToAddPointsFor.forEach((time) => { const pointToAdd = { date: new Date(time), value: null, @@ -138,7 +138,7 @@ export function processDataForFocusAnomalies( // Iterate through the anomaly records adding the // various properties required for display. - anomalyRecords.forEach(record => { + anomalyRecords.forEach((record) => { // Look for a chart point with the same time as the record. // If none found, find closest time in chartData set. const recordTime = record[TIME_FIELD_NAME]; diff --git a/x-pack/plugins/ml/public/application/util/calc_auto_interval.js b/x-pack/plugins/ml/public/application/util/calc_auto_interval.js index 29064db6689d0..c0a001b968970 100644 --- a/x-pack/plugins/ml/public/application/util/calc_auto_interval.js +++ b/x-pack/plugins/ml/public/application/util/calc_auto_interval.js @@ -81,7 +81,7 @@ export function timeBucketsCalcAutoIntervalProvider() { return moment.duration(ms, 'ms'); } - return function(buckets, duration) { + return function (buckets, duration) { const interval = pick(buckets, duration); if (interval) { return moment.duration(interval._data); @@ -111,7 +111,7 @@ export function timeBucketsCalcAutoIntervalProvider() { true ), - lessThan: find(revRoundingRules, function(upperBound, lowerBound, target) { + lessThan: find(revRoundingRules, function (upperBound, lowerBound, target) { // upperBound - first duration in rule // lowerBound - second duration in rule // target - target interval in milliseconds. Must not return intervals less than this duration. diff --git a/x-pack/plugins/ml/public/application/util/chart_utils.js b/x-pack/plugins/ml/public/application/util/chart_utils.js index 5a062320ca6c5..2caf964cb9774 100644 --- a/x-pack/plugins/ml/public/application/util/chart_utils.js +++ b/x-pack/plugins/ml/public/application/util/chart_utils.js @@ -21,7 +21,7 @@ export const SCHEDULED_EVENT_SYMBOL_HEIGHT = 5; const MAX_LABEL_WIDTH = 100; export function chartLimits(data = []) { - const domain = d3.extent(data, d => { + const domain = d3.extent(data, (d) => { let metricValue = d.value; if (metricValue === null && d.anomalyScore !== undefined && d.actual !== undefined) { // If an anomaly coincides with a gap in the data, use the anomaly actual value. @@ -32,7 +32,7 @@ export function chartLimits(data = []) { const limits = { max: domain[1], min: domain[0] }; if (limits.max === limits.min) { - limits.max = d3.max(data, d => { + limits.max = d3.max(data, (d) => { if (d.typical) { return Math.max(d.value, d.typical); } else { @@ -42,7 +42,7 @@ export function chartLimits(data = []) { return d.value; } }); - limits.min = d3.min(data, d => { + limits.min = d3.min(data, (d) => { if (d.typical) { return Math.min(d.value, d.typical); } else { @@ -96,10 +96,7 @@ export function drawLineChartDots(data, lineChartGroup, lineChartValuesLine, rad // use d3's enter/update/exit pattern to render the dots const dots = dotGroup.selectAll('circle').data(dotsData); - dots - .enter() - .append('circle') - .attr('r', radius); + dots.enter().append('circle').attr('r', radius); dots.attr('cx', lineChartValuesLine.x()).attr('cy', lineChartValuesLine.y()); @@ -118,7 +115,7 @@ export function filterAxisLabels(selection, chartWidth) { .selectAll('.tick text') // don't refactor this to an arrow function because // we depend on using `this` here. - .text(function() { + .text(function () { const parent = d3.select(this.parentNode); const labelWidth = parent.node().getBBox().width; const labelXPos = d3.transform(parent.attr('transform')).translate[0]; @@ -142,13 +139,13 @@ export function getChartType(config) { if ( EVENT_DISTRIBUTION_ENABLED && config.functionDescription === 'rare' && - config.entityFields.some(f => f.fieldType === 'over') === false + config.entityFields.some((f) => f.fieldType === 'over') === false ) { chartType = CHART_TYPE.EVENT_DISTRIBUTION; } else if ( POPULATION_DISTRIBUTION_ENABLED && config.functionDescription !== 'rare' && - config.entityFields.some(f => f.fieldType === 'over') && + config.entityFields.some((f) => f.fieldType === 'over') && config.metricFunction !== null // Event distribution chart relies on the ML function mapping to an ES aggregation ) { chartType = CHART_TYPE.POPULATION_DISTRIBUTION; @@ -161,12 +158,12 @@ export function getChartType(config) { // Check that the config does not use script fields defined in the datafeed config. if (config.datafeedConfig !== undefined && config.datafeedConfig.script_fields !== undefined) { const scriptFields = Object.keys(config.datafeedConfig.script_fields); - const checkFields = config.entityFields.map(entity => entity.fieldName); + const checkFields = config.entityFields.map((entity) => entity.fieldName); if (config.metricFieldName) { checkFields.push(config.metricFieldName); } const usesScriptFields = - checkFields.find(fieldName => scriptFields.includes(fieldName)) !== undefined; + checkFields.find((fieldName) => scriptFields.includes(fieldName)) !== undefined; if (usesScriptFields === true) { // Only single metric chart type supports query of model plot data. chartType = CHART_TYPE.SINGLE_METRIC; @@ -193,7 +190,7 @@ export function getExploreSeriesLink(series) { // Initially pass them in the mlTimeSeriesExplorer part of the AppState. // TODO - do we want to pass the entities via the filter? const entityCondition = {}; - series.entityFields.forEach(entity => { + series.entityFields.forEach((entity) => { entityCondition[entity.fieldName] = entity.fieldValue; }); @@ -310,7 +307,8 @@ const LABEL_WRAP_THRESHOLD = 60; // and entity fields) is above LABEL_WRAP_THRESHOLD. export function isLabelLengthAboveThreshold({ detectorLabel, entityFields }) { const labelLength = - detectorLabel.length + entityFields.map(d => `${d.fieldName} ${d.fieldValue}`).join(' ').length; + detectorLabel.length + + entityFields.map((d) => `${d.fieldName} ${d.fieldValue}`).join(' ').length; return labelLength > LABEL_WRAP_THRESHOLD; } @@ -335,13 +333,10 @@ export function getXTransform(t) { export function removeLabelOverlap(axis, startTimeMs, tickInterval, width) { // Put emphasis on all tick lines, will again de-emphasize the // ones where we remove the label in the next steps. - axis - .selectAll('g.tick') - .select('line') - .classed('ml-tick-emphasis', true); + axis.selectAll('g.tick').select('line').classed('ml-tick-emphasis', true); function getNeighborTickFactory(operator) { - return function(ts) { + return function (ts) { switch (operator) { case TICK_DIRECTION.PREVIOUS: return ts - tickInterval; @@ -353,8 +348,8 @@ export function removeLabelOverlap(axis, startTimeMs, tickInterval, width) { function getTickDataFactory(operator) { const getNeighborTick = getNeighborTickFactory(operator); - const fn = function(ts) { - const filteredTicks = axis.selectAll('.tick').filter(d => d === ts); + const fn = function (ts) { + const filteredTicks = axis.selectAll('.tick').filter((d) => d === ts); if (filteredTicks.length === 0 || filteredTicks[0].length === 0) { return false; diff --git a/x-pack/plugins/ml/public/application/util/chart_utils.test.js b/x-pack/plugins/ml/public/application/util/chart_utils.test.js index 57aea3c0ab5aa..b7cf11c088a1e 100644 --- a/x-pack/plugins/ml/public/application/util/chart_utils.test.js +++ b/x-pack/plugins/ml/public/application/util/chart_utils.test.js @@ -10,7 +10,7 @@ jest.mock('./dependency_cache', () => { const dateMath = require('@elastic/datemath'); let _time = undefined; const timefilter = { - setTime: time => { + setTime: (time) => { _time = time; }, getActiveBounds: () => { @@ -436,15 +436,12 @@ describe('ML - chart utils', () => { .innerTickSize(-chartHeight) .outerTickSize(0) .tickPadding(10) - .tickFormat(d => moment(d).format(xAxisTickFormat)); + .tickFormat((d) => moment(d).format(xAxisTickFormat)); const tickValues = getTickValues(startTimeMs, interval, plotEarliest, plotLatest); xAxis.tickValues(tickValues); - const svg = chartElement - .append('svg') - .attr('width', svgWidth) - .attr('height', svgHeight); + const svg = chartElement.append('svg').attr('width', svgWidth).attr('height', svgHeight); const axes = svg.append('g'); diff --git a/x-pack/plugins/ml/public/application/util/custom_url_utils.ts b/x-pack/plugins/ml/public/application/util/custom_url_utils.ts index 47f7b6f4d4fd2..20bb1c7f60597 100644 --- a/x-pack/plugins/ml/public/application/util/custom_url_utils.ts +++ b/x-pack/plugins/ml/public/application/util/custom_url_utils.ts @@ -170,7 +170,7 @@ function buildKibanaUrl(urlConfig: UrlConfig, record: CustomUrlAnomalyRecordDoc) // Split query string by AND operator. .split(/\sand\s/i) // Get property name from `influencerField:$influencerField$` string. - .map(v => v.split(':')[0]); + .map((v) => v.split(':')[0]); const queryParts: string[] = []; const joinOperator = ' AND '; @@ -226,7 +226,7 @@ export function isValidLabel(label: string, savedCustomUrls: any[]) { let isValid = label !== undefined && label.trim().length > 0; if (isValid === true && savedCustomUrls !== undefined) { // Check the label is unique. - const existingLabels = savedCustomUrls.map(customUrl => customUrl.url_name); + const existingLabels = savedCustomUrls.map((customUrl) => customUrl.url_name); isValid = !existingLabels.includes(label); } return isValid; diff --git a/x-pack/plugins/ml/public/application/util/dependency_cache.ts b/x-pack/plugins/ml/public/application/util/dependency_cache.ts index 356da38d5ad08..2586dfe45345e 100644 --- a/x-pack/plugins/ml/public/application/util/dependency_cache.ts +++ b/x-pack/plugins/ml/public/application/util/dependency_cache.ts @@ -204,7 +204,7 @@ export function getGetUrlGenerator() { export function clearCache() { console.log('clearing dependency cache'); // eslint-disable-line no-console - Object.keys(cache).forEach(k => { + Object.keys(cache).forEach((k) => { cache[k as keyof DependencyCache] = null; }); } diff --git a/x-pack/plugins/ml/public/application/util/field_types_utils.test.ts b/x-pack/plugins/ml/public/application/util/field_types_utils.test.ts index 6052cd0dfaa21..4275142d63d56 100644 --- a/x-pack/plugins/ml/public/application/util/field_types_utils.test.ts +++ b/x-pack/plugins/ml/public/application/util/field_types_utils.test.ts @@ -68,7 +68,7 @@ describe('ML - field type utils', () => { const mlKeys = Object.keys(ML_JOB_FIELD_TYPES); const receivedMlLabels: Record = {}; const testStorage = mlJobTypeAriaLabels; - mlKeys.forEach(constant => { + mlKeys.forEach((constant) => { receivedMlLabels[constant] = getMLJobTypeAriaLabel( ML_JOB_FIELD_TYPES[constant as keyof typeof ML_JOB_FIELD_TYPES] ); diff --git a/x-pack/plugins/ml/public/application/util/field_types_utils.ts b/x-pack/plugins/ml/public/application/util/field_types_utils.ts index d6e0a885269e8..8cf2661d7b74d 100644 --- a/x-pack/plugins/ml/public/application/util/field_types_utils.ts +++ b/x-pack/plugins/ml/public/application/util/field_types_utils.ts @@ -73,7 +73,7 @@ export const mlJobTypeAriaLabels = { export const getMLJobTypeAriaLabel = (type: string) => { const requestedFieldType = Object.keys(ML_JOB_FIELD_TYPES).find( - k => ML_JOB_FIELD_TYPES[k as keyof typeof ML_JOB_FIELD_TYPES] === type + (k) => ML_JOB_FIELD_TYPES[k as keyof typeof ML_JOB_FIELD_TYPES] === type ); if (requestedFieldType === undefined) { return null; diff --git a/x-pack/plugins/ml/public/application/util/index_utils.ts b/x-pack/plugins/ml/public/application/util/index_utils.ts index b8cf2e6fa8e96..192552b25d15a 100644 --- a/x-pack/plugins/ml/public/application/util/index_utils.ts +++ b/x-pack/plugins/ml/public/application/util/index_utils.ts @@ -28,7 +28,7 @@ export function loadIndexPatterns(indexPatterns: IndexPatternsContract) { fields: ['id', 'title', 'type', 'fields'], perPage: 10000, }) - .then(response => { + .then((response) => { indexPatternCache = response.savedObjects; return indexPatternCache; }); @@ -41,7 +41,7 @@ export function loadSavedSearches() { type: 'search', perPage: 10000, }) - .then(response => { + .then((response) => { savedSearchesCache = response.savedObjects; return savedSearchesCache; }); @@ -62,7 +62,7 @@ export function getIndexPatternsContract() { } export function getIndexPatternNames() { - return indexPatternCache.map(i => i.attributes && i.attributes.title); + return indexPatternCache.map((i) => i.attributes && i.attributes.title); } export function getIndexPatternIdFromName(name: string) { @@ -88,7 +88,7 @@ export async function getIndexPatternAndSavedSearch(savedSearchId: string) { if (ss === null) { return resp; } - const indexPatternId = ss.references.find(r => r.type === 'index-pattern')?.id; + const indexPatternId = ss.references.find((r) => r.type === 'index-pattern')?.id; resp.indexPattern = await getIndexPatternById(indexPatternId!); resp.savedSearch = ss; return resp; @@ -111,7 +111,7 @@ export function getIndexPatternById(id: string): Promise { } export function getSavedSearchById(id: string): SavedSearchSavedObject | undefined { - return savedSearchesCache.find(s => s.id === id); + return savedSearchesCache.find((s) => s.id === id); } /** diff --git a/x-pack/plugins/ml/public/application/util/string_utils.js b/x-pack/plugins/ml/public/application/util/string_utils.js index 66835984df5e5..450c166f90300 100644 --- a/x-pack/plugins/ml/public/application/util/string_utils.js +++ b/x-pack/plugins/ml/public/application/util/string_utils.js @@ -83,7 +83,7 @@ function quoteField(field) { // re-order an object based on the value of the keys export function sortByKey(list, reverse, comparator) { - let keys = _.sortBy(_.keys(list), key => { + let keys = _.sortBy(_.keys(list), (key) => { return comparator ? comparator(list[key], key) : key; }); @@ -93,7 +93,7 @@ export function sortByKey(list, reverse, comparator) { return _.object( keys, - _.map(keys, key => { + _.map(keys, (key) => { return list[key]; }) ); @@ -121,7 +121,7 @@ export function mlEscape(str) { "'": ''', '/': '/', }; - return String(str).replace(/[&<>"'\/]/g, s => entityMap[s]); + return String(str).replace(/[&<>"'\/]/g, (s) => entityMap[s]); } // Escapes reserved characters for use in Elasticsearch query terms. diff --git a/x-pack/plugins/ml/public/application/util/string_utils.test.ts b/x-pack/plugins/ml/public/application/util/string_utils.test.ts index d940fce2ee1d5..25f1cbd3abac3 100644 --- a/x-pack/plugins/ml/public/application/util/string_utils.test.ts +++ b/x-pack/plugins/ml/public/application/util/string_utils.test.ts @@ -102,7 +102,7 @@ describe('ML - string utils', () => { elephant: 'trunk', }; - const valueComparator = function(value: string) { + const valueComparator = function (value: string) { return value; }; diff --git a/x-pack/plugins/ml/public/application/util/time_buckets.js b/x-pack/plugins/ml/public/application/util/time_buckets.js index ccc51982678b7..2b23eca1ab5c0 100644 --- a/x-pack/plugins/ml/public/application/util/time_buckets.js +++ b/x-pack/plugins/ml/public/application/util/time_buckets.js @@ -46,7 +46,7 @@ export function TimeBuckets(timeBucketsConfig) { * * @returns {undefined} */ -TimeBuckets.prototype.setBarTarget = function(bt) { +TimeBuckets.prototype.setBarTarget = function (bt) { this.barTarget = bt; }; @@ -57,7 +57,7 @@ TimeBuckets.prototype.setBarTarget = function(bt) { * * @returns {undefined} */ -TimeBuckets.prototype.setMaxBars = function(mb) { +TimeBuckets.prototype.setMaxBars = function (mb) { this.maxBars = mb; }; @@ -72,7 +72,7 @@ TimeBuckets.prototype.setMaxBars = function(mb) { * * @returns {undefined} */ -TimeBuckets.prototype.setBounds = function(input) { +TimeBuckets.prototype.setBounds = function (input) { if (!input) return this.clearBounds(); let bounds; @@ -83,9 +83,7 @@ TimeBuckets.prototype.setBounds = function(input) { bounds = Array.isArray(input) ? input : []; } - const moments = _(bounds) - .map(_.ary(moment, 1)) - .sortBy(Number); + const moments = _(bounds).map(_.ary(moment, 1)).sortBy(Number); const valid = moments.size() === 2 && moments.every(isValidMoment); if (!valid) { @@ -105,7 +103,7 @@ TimeBuckets.prototype.setBounds = function(input) { * * @return {undefined} */ -TimeBuckets.prototype.clearBounds = function() { +TimeBuckets.prototype.clearBounds = function () { this._lb = this._ub = null; }; @@ -114,7 +112,7 @@ TimeBuckets.prototype.clearBounds = function() { * * @return {Boolean} */ -TimeBuckets.prototype.hasBounds = function() { +TimeBuckets.prototype.hasBounds = function () { return isValidMoment(this._ub) && isValidMoment(this._lb); }; @@ -130,7 +128,7 @@ TimeBuckets.prototype.hasBounds = function() { * min and max. Each property will be a moment() * object */ -TimeBuckets.prototype.getBounds = function() { +TimeBuckets.prototype.getBounds = function () { if (!this.hasBounds()) return; return { min: this._lb, @@ -145,7 +143,7 @@ TimeBuckets.prototype.getBounds = function() { * * @return {moment.duration|undefined} */ -TimeBuckets.prototype.getDuration = function() { +TimeBuckets.prototype.getDuration = function () { if (!this.hasBounds()) return; return moment.duration(this._ub - this._lb, 'ms'); }; @@ -161,7 +159,7 @@ TimeBuckets.prototype.getDuration = function() { * * @param {string|moment.duration} input - see desc */ -TimeBuckets.prototype.setInterval = function(input) { +TimeBuckets.prototype.setInterval = function (input) { // Preserve the original units because they're lost when the interval is converted to a // moment duration object. this.originalInterval = input; @@ -223,7 +221,7 @@ TimeBuckets.prototype.setInterval = function(input) { * * @return {[type]} [description] */ -TimeBuckets.prototype.getInterval = function() { +TimeBuckets.prototype.getInterval = function () { const self = this; const duration = self.getDuration(); return decorateInterval(maybeScaleInterval(readInterval()), duration); @@ -268,7 +266,7 @@ TimeBuckets.prototype.getInterval = function() { * * @return {moment.duration|undefined} */ -TimeBuckets.prototype.getIntervalToNearestMultiple = function(divisorSecs) { +TimeBuckets.prototype.getIntervalToNearestMultiple = function (divisorSecs) { const interval = this.getInterval(); const intervalSecs = interval.asSeconds(); @@ -306,7 +304,7 @@ TimeBuckets.prototype.getIntervalToNearestMultiple = function(divisorSecs) { * * @return {string} */ -TimeBuckets.prototype.getScaledDateFormat = function() { +TimeBuckets.prototype.getScaledDateFormat = function () { const interval = this.getInterval(); const rules = this._timeBucketsConfig['dateFormat:scaled']; @@ -320,7 +318,7 @@ TimeBuckets.prototype.getScaledDateFormat = function() { return this._timeBucketsConfig.dateFormat; }; -TimeBuckets.prototype.getScaledDateFormatter = function() { +TimeBuckets.prototype.getScaledDateFormatter = function () { const fieldFormats = getFieldFormats(); const DateFieldFormat = fieldFormats.getType(FIELD_FORMAT_IDS.DATE); return new DateFieldFormat( diff --git a/x-pack/plugins/ml/public/application/util/url_state.ts b/x-pack/plugins/ml/public/application/util/url_state.ts index b0699116895d4..beff5340ce7e4 100644 --- a/x-pack/plugins/ml/public/application/util/url_state.ts +++ b/x-pack/plugins/ml/public/application/util/url_state.ts @@ -35,7 +35,7 @@ export function getUrlState(search: string): Dictionary { const parsedQueryString = parse(search, { sort: false }); try { - Object.keys(parsedQueryString).forEach(a => { + Object.keys(parsedQueryString).forEach((a) => { if (isRisonSerializationRequired(a)) { urlState[a] = decode(parsedQueryString[a] as string); } else { @@ -77,7 +77,7 @@ export const useUrlState = (accessor: string): UrlState => { urlState[accessor][attribute] = value; } else { const attributes = attribute; - Object.keys(attributes).forEach(a => { + Object.keys(attributes).forEach((a) => { urlState[accessor][a] = attributes[a]; }); } @@ -85,7 +85,7 @@ export const useUrlState = (accessor: string): UrlState => { try { const oldLocationSearch = stringify(parsedQueryString, { sort: false, encode: false }); - Object.keys(urlState).forEach(a => { + Object.keys(urlState).forEach((a) => { if (isRisonSerializationRequired(a)) { parsedQueryString[a] = encode(urlState[a]); } else { diff --git a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_embeddable.tsx b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_embeddable.tsx index 1f26bce165e9f..b53b08e5f6146 100644 --- a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_embeddable.tsx +++ b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_embeddable.tsx @@ -96,7 +96,7 @@ export class AnomalySwimlaneEmbeddable extends Embeddable< embeddableInput={this.getInput$()} services={this.services} refresh={this.reload$.asObservable()} - onOutputChange={output => this.updateOutput(output)} + onOutputChange={(output) => this.updateOutput(output)} />, node ); diff --git a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_initializer.tsx b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_initializer.tsx index ab25137f2b7d6..00d47c0d897c7 100644 --- a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_initializer.tsx +++ b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_initializer.tsx @@ -38,7 +38,7 @@ export interface AnomalySwimlaneInitializerProps { onCancel: () => void; } -const limitOptions = [5, 10, 25, 50].map(limit => ({ +const limitOptions = [5, 10, 25, 50].map((limit) => ({ value: limit, text: `${limit}`, })); @@ -72,7 +72,7 @@ export const AnomalySwimlaneInitializer: FC = ( }, ]; - const viewBySwimlaneOptions = ['', ...influencers].map(influencer => { + const viewBySwimlaneOptions = ['', ...influencers].map((influencer) => { return { value: influencer, text: influencer, @@ -112,7 +112,7 @@ export const AnomalySwimlaneInitializer: FC = ( id="panelTitle" name="panelTitle" value={panelTitle} - onChange={e => setPanelTitle(e.target.value)} + onChange={(e) => setPanelTitle(e.target.value)} isInvalid={!isPanelTitleValid} /> @@ -135,7 +135,7 @@ export const AnomalySwimlaneInitializer: FC = ( })} options={swimlaneTypeOptions} idSelected={swimlaneType} - onChange={id => setSwimlaneType(id as SWIMLANE_TYPE)} + onChange={(id) => setSwimlaneType(id as SWIMLANE_TYPE)} /> @@ -151,7 +151,7 @@ export const AnomalySwimlaneInitializer: FC = ( name="selectViewBy" options={viewBySwimlaneOptions} value={viewBySwimlaneFieldName} - onChange={e => setViewBySwimlaneFieldName(e.target.value)} + onChange={(e) => setViewBySwimlaneFieldName(e.target.value)} /> = ( name="limit" options={limitOptions} value={limit} - onChange={e => setLimit(Number(e.target.value))} + onChange={(e) => setLimit(Number(e.target.value))} /> diff --git a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/explorer_swimlane_container.tsx b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/explorer_swimlane_container.tsx index 89c237b205287..e5d8584683c55 100644 --- a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/explorer_swimlane_container.tsx +++ b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/explorer_swimlane_container.tsx @@ -79,11 +79,11 @@ export const ExplorerSwimlaneContainer: FC = ({ return ( - {resizeRef => ( + {(resizeRef) => (
    { + ref={(el) => { resizeRef(el); }} > @@ -93,7 +93,7 @@ export const ExplorerSwimlaneContainer: FC = ({ {chartWidth > 0 && swimlaneData && swimlaneType ? ( - {tooltipService => ( + {(tooltipService) => ( anomalyDetectorService.getJobs$(jobsIds)) + switchMap((jobsIds) => anomalyDetectorService.getJobs$(jobsIds)) ); } @@ -74,7 +74,7 @@ export function useSwimlaneInputResolver( getJobsObservable(embeddableInput, anomalyDetectorService), embeddableInput, chartWidth$.pipe( - skipWhile(v => !v), + skipWhile((v) => !v), distinctUntilChanged((prev, curr) => { // emit only if the width has been changed significantly return Math.abs(curr - prev) < RESIZE_IGNORED_DIFF_PX; @@ -100,7 +100,7 @@ export function useSwimlaneInputResolver( setSwimlaneType(swimlaneTypeInput); } - const explorerJobs: ExplorerJob[] = jobs.map(job => { + const explorerJobs: ExplorerJob[] = jobs.map((job) => { const bucketSpan = parseInterval(job.analysis_config.bucket_span); return { id: job.job_id, @@ -119,7 +119,7 @@ export function useSwimlaneInputResolver( } return from(explorerService.loadOverallData(explorerJobs, swimlaneContainerWidth)).pipe( - switchMap(overallSwimlaneData => { + switchMap((overallSwimlaneData) => { const { earliest, latest } = overallSwimlaneData; if (overallSwimlaneData && swimlaneTypeInput === SWIMLANE_TYPE.VIEW_BY) { @@ -134,7 +134,7 @@ export function useSwimlaneInputResolver( appliedFilters ) ).pipe( - map(viewBySwimlaneData => { + map((viewBySwimlaneData) => { return { ...viewBySwimlaneData!, earliest, @@ -147,12 +147,12 @@ export function useSwimlaneInputResolver( }) ); }), - catchError(e => { + catchError((e) => { setError(e.body); return of(undefined); }) ) - .subscribe(data => { + .subscribe((data) => { if (data !== undefined) { setError(null); setSwimlaneData(data); diff --git a/x-pack/plugins/ml/server/client/elasticsearch_ml.test.ts b/x-pack/plugins/ml/server/client/elasticsearch_ml.test.ts index 543cf4ddad982..5ad0db3c58ce4 100644 --- a/x-pack/plugins/ml/server/client/elasticsearch_ml.test.ts +++ b/x-pack/plugins/ml/server/client/elasticsearch_ml.test.ts @@ -31,7 +31,7 @@ describe('ML - Endpoints', () => { factory(obj: ClientAction) { // add each endpoint URL to a list if (obj.urls) { - obj.urls.forEach(url => { + obj.urls.forEach((url) => { urls.push(url.fmt); }); } @@ -52,7 +52,7 @@ describe('ML - Endpoints', () => { describe('paths', () => { it(`should start with ${PATH_START}`, () => { - urls.forEach(url => { + urls.forEach((url) => { expect(url[0]).toEqual(PATH_START); }); }); diff --git a/x-pack/plugins/ml/server/lib/capabilities/__mocks__/ml_capabilities.ts b/x-pack/plugins/ml/server/lib/capabilities/__mocks__/ml_capabilities.ts index 8e350b8382276..a5c04092fab77 100644 --- a/x-pack/plugins/ml/server/lib/capabilities/__mocks__/ml_capabilities.ts +++ b/x-pack/plugins/ml/server/lib/capabilities/__mocks__/ml_capabilities.ts @@ -13,7 +13,7 @@ import { export function getAdminCapabilities() { const caps: any = {}; - Object.keys(adminMlCapabilities).forEach(k => { + Object.keys(adminMlCapabilities).forEach((k) => { caps[k] = true; }); return { ...getUserCapabilities(), ...caps } as MlCapabilities; @@ -21,7 +21,7 @@ export function getAdminCapabilities() { export function getUserCapabilities() { const caps: any = {}; - Object.keys(userMlCapabilities).forEach(k => { + Object.keys(userMlCapabilities).forEach((k) => { caps[k] = true; }); diff --git a/x-pack/plugins/ml/server/lib/capabilities/capabilities_switcher.ts b/x-pack/plugins/ml/server/lib/capabilities/capabilities_switcher.ts index aef22debf3642..5b8cbc4bdbbe8 100644 --- a/x-pack/plugins/ml/server/lib/capabilities/capabilities_switcher.ts +++ b/x-pack/plugins/ml/server/lib/capabilities/capabilities_switcher.ts @@ -40,13 +40,13 @@ function getSwitcher(license$: Observable, logger: Logger): Capabiliti const originalCapabilities = cloneDeep(mlCaps); // not full licence, switch off all capabilities - Object.keys(mlCaps).forEach(k => { + Object.keys(mlCaps).forEach((k) => { mlCaps[k as keyof MlCapabilities] = false; }); // for a basic license, reapply the original capabilities for the basic license features if (isMinimumLicense(license)) { - basicLicenseMlCapabilities.forEach(c => (mlCaps[c] = originalCapabilities[c])); + basicLicenseMlCapabilities.forEach((c) => (mlCaps[c] = originalCapabilities[c])); } return capabilities; diff --git a/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.test.ts b/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.test.ts index 746c9da47d0ad..3354523b1718c 100644 --- a/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.test.ts +++ b/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.test.ts @@ -27,7 +27,7 @@ const callWithRequestUpgrade = async () => ({ upgrade_mode: true }); describe('check_capabilities', () => { describe('getCapabilities() - right number of capabilities', () => { - test('kibana capabilities count', async done => { + test('kibana capabilities count', async (done) => { const { getCapabilities } = capabilitiesProvider( callWithRequestNonUpgrade, getAdminCapabilities(), @@ -42,7 +42,7 @@ describe('check_capabilities', () => { }); describe('getCapabilities() with security', () => { - test('ml_user capabilities only', async done => { + test('ml_user capabilities only', async (done) => { const { getCapabilities } = capabilitiesProvider( callWithRequestNonUpgrade, getUserCapabilities(), @@ -91,7 +91,7 @@ describe('check_capabilities', () => { done(); }); - test('full capabilities', async done => { + test('full capabilities', async (done) => { const { getCapabilities } = capabilitiesProvider( callWithRequestNonUpgrade, getAdminCapabilities(), @@ -140,7 +140,7 @@ describe('check_capabilities', () => { done(); }); - test('upgrade in progress with full capabilities', async done => { + test('upgrade in progress with full capabilities', async (done) => { const { getCapabilities } = capabilitiesProvider( callWithRequestUpgrade, getAdminCapabilities(), @@ -189,7 +189,7 @@ describe('check_capabilities', () => { done(); }); - test('upgrade in progress with partial capabilities', async done => { + test('upgrade in progress with partial capabilities', async (done) => { const { getCapabilities } = capabilitiesProvider( callWithRequestUpgrade, getUserCapabilities(), @@ -238,7 +238,7 @@ describe('check_capabilities', () => { done(); }); - test('full capabilities, ml disabled in space', async done => { + test('full capabilities, ml disabled in space', async (done) => { const { getCapabilities } = capabilitiesProvider( callWithRequestNonUpgrade, getDefaultCapabilities(), @@ -288,7 +288,7 @@ describe('check_capabilities', () => { }); }); - test('full capabilities, basic license, ml disabled in space', async done => { + test('full capabilities, basic license, ml disabled in space', async (done) => { const { getCapabilities } = capabilitiesProvider( callWithRequestNonUpgrade, getDefaultCapabilities(), diff --git a/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.ts b/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.ts index d955cf981faca..ce775a425fa73 100644 --- a/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.ts +++ b/x-pack/plugins/ml/server/lib/capabilities/check_capabilities.ts @@ -41,7 +41,7 @@ export function capabilitiesProvider( } function disableAdminPrivileges(capabilities: MlCapabilities) { - Object.keys(adminMlCapabilities).forEach(k => { + Object.keys(adminMlCapabilities).forEach((k) => { capabilities[k as keyof MlCapabilities] = false; }); capabilities.canCreateAnnotation = false; diff --git a/x-pack/plugins/ml/server/models/annotation_service/annotation.test.ts b/x-pack/plugins/ml/server/models/annotation_service/annotation.test.ts index 8d70b11bce152..0d88fd0cd1bb0 100644 --- a/x-pack/plugins/ml/server/models/annotation_service/annotation.test.ts +++ b/x-pack/plugins/ml/server/models/annotation_service/annotation.test.ts @@ -35,7 +35,7 @@ describe('annotation_service', () => { }); describe('deleteAnnotation()', () => { - it('should delete annotation', async done => { + it('should delete annotation', async (done) => { const { deleteAnnotation } = annotationServiceProvider(callWithRequestSpy); const mockFunct = callWithRequestSpy; @@ -56,7 +56,7 @@ describe('annotation_service', () => { }); describe('getAnnotation()', () => { - it('should get annotations for specific job', async done => { + it('should get annotations for specific job', async (done) => { const { getAnnotations } = annotationServiceProvider(callWithRequestSpy); const mockFunct = callWithRequestSpy; @@ -104,7 +104,7 @@ describe('annotation_service', () => { }); describe('indexAnnotation()', () => { - it('should index annotation', async done => { + it('should index annotation', async (done) => { const { indexAnnotation } = annotationServiceProvider(callWithRequestSpy); const mockFunct = callWithRequestSpy; @@ -132,7 +132,7 @@ describe('annotation_service', () => { done(); }); - it('should remove ._id and .key before updating annotation', async done => { + it('should remove ._id and .key before updating annotation', async (done) => { const { indexAnnotation } = annotationServiceProvider(callWithRequestSpy); const mockFunct = callWithRequestSpy; @@ -164,7 +164,7 @@ describe('annotation_service', () => { done(); }); - it('should update annotation text and the username for modified_username', async done => { + it('should update annotation text and the username for modified_username', async (done) => { const { getAnnotations, indexAnnotation } = annotationServiceProvider(callWithRequestSpy); const mockFunct = callWithRequestSpy; diff --git a/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js b/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js index d2e4311bf6f22..2e03a9532c831 100644 --- a/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js +++ b/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.js @@ -128,7 +128,7 @@ export function estimateBucketSpanFactory( this.polledDataChecker .run() - .then(result => { + .then((result) => { // if the data is polled, set a minimum threshold // of bucket span if (result.isPolled) { @@ -154,10 +154,10 @@ export function estimateBucketSpanFactory( } }; - _.each(this.checkers, check => { + _.each(this.checkers, (check) => { check.check .run() - .then(interval => { + .then((interval) => { check.result = interval; runComplete(); }) @@ -170,7 +170,7 @@ export function estimateBucketSpanFactory( }); }); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); @@ -188,8 +188,8 @@ export function estimateBucketSpanFactory( const pos = i * numberOfSplitFields; let resultsSubset = allResults.slice(pos, pos + numberOfSplitFields); // remove results of tests which have failed - resultsSubset = _.remove(resultsSubset, res => res !== null); - resultsSubset = _.sortBy(resultsSubset, r => r.ms); + resultsSubset = _.remove(resultsSubset, (res) => res !== null); + resultsSubset = _.sortBy(resultsSubset, (r) => r.ms); const tempMedian = this.findMedian(resultsSubset); if (tempMedian !== null) { @@ -197,7 +197,7 @@ export function estimateBucketSpanFactory( } } - reducedResults = _.sortBy(reducedResults, r => r.ms); + reducedResults = _.sortBy(reducedResults, (r) => r.ms); return this.findMedian(reducedResults); } @@ -243,7 +243,7 @@ export function estimateBucketSpanFactory( } } - const getFieldCardinality = function(index, field) { + const getFieldCardinality = function (index, field) { return new Promise((resolve, reject) => { callAsCurrentUser('search', { index, @@ -258,24 +258,24 @@ export function estimateBucketSpanFactory( }, }, }) - .then(resp => { + .then((resp) => { const value = _.get(resp, ['aggregations', 'field_count', 'value'], 0); resolve(value); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); }; - const getRandomFieldValues = function(index, field, query) { + const getRandomFieldValues = function (index, field, query) { let fieldValues = []; return new Promise((resolve, reject) => { const NUM_PARTITIONS = 10; // use a partitioned search to load 10 random fields // load ten fields, to test that there are at least 10. getFieldCardinality(index, field) - .then(value => { + .then((value) => { const numPartitions = Math.floor(value / NUM_PARTITIONS) || 1; callAsCurrentUser('search', { index, @@ -295,24 +295,24 @@ export function estimateBucketSpanFactory( }, }, }) - .then(partitionResp => { + .then((partitionResp) => { if (_.has(partitionResp, 'aggregations.fields_bucket_counts.buckets')) { const buckets = partitionResp.aggregations.fields_bucket_counts.buckets; - fieldValues = _.map(buckets, b => b.key); + fieldValues = _.map(buckets, (b) => b.key); } resolve(fieldValues); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); }; - return function(formConfig) { + return function (formConfig) { if (typeof formConfig !== 'object' || formConfig === null) { throw new Error('Invalid formConfig: formConfig needs to be an object.'); } @@ -342,7 +342,7 @@ export function estimateBucketSpanFactory( includeDefaults: true, filterPath: '*.*max_buckets', }) - .then(settings => { + .then((settings) => { if (typeof settings !== 'object') { reject('Unable to retrieve cluster settings'); } @@ -368,10 +368,10 @@ export function estimateBucketSpanFactory( bucketSpanEstimator .run() - .then(resp => { + .then((resp) => { resolve(resp); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }; @@ -380,10 +380,10 @@ export function estimateBucketSpanFactory( // bucket span tests. if (formConfig.splitField !== undefined) { getRandomFieldValues(formConfig.index, formConfig.splitField, formConfig.query) - .then(splitFieldValues => { + .then((splitFieldValues) => { runEstimator(splitFieldValues); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); } else { @@ -391,7 +391,7 @@ export function estimateBucketSpanFactory( runEstimator(); } }) - .catch(resp => { + .catch((resp) => { reject(resp); }); } @@ -413,7 +413,7 @@ export function estimateBucketSpanFactory( ], }; callAsCurrentUser('ml.privilegeCheck', { body }) - .then(resp => { + .then((resp) => { if ( resp.cluster['cluster:monitor/xpack/ml/job/get'] && resp.cluster['cluster:monitor/xpack/ml/job/stats/get'] && diff --git a/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.test.ts b/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.test.ts index f5daadfe86be0..8e8301db2a3a3 100644 --- a/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.test.ts +++ b/x-pack/plugins/ml/server/models/bucket_span_estimator/bucket_span_estimator.test.ts @@ -18,7 +18,7 @@ import { estimateBucketSpanFactory, BucketSpanEstimatorData } from './bucket_spa // permissions. const permissions = [false, true]; const callWithRequest: APICaller = (method: string) => { - return new Promise(resolve => { + return new Promise((resolve) => { if (method === 'ml.privilegeCheck') { resolve({ cluster: { @@ -35,7 +35,7 @@ const callWithRequest: APICaller = (method: string) => { }; const callWithInternalUser: APICaller = () => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve({}); }) as Promise; }; @@ -58,20 +58,20 @@ const formConfig: BucketSpanEstimatorData = { describe('ML - BucketSpanEstimator', () => { it('call factory', () => { - expect(function() { + expect(function () { estimateBucketSpanFactory(callWithRequest, callWithInternalUser, false); }).not.toThrow('Not initialized.'); }); - it('call factory and estimator with security disabled', done => { - expect(function() { + it('call factory and estimator with security disabled', (done) => { + expect(function () { const estimateBucketSpan = estimateBucketSpanFactory( callWithRequest, callWithInternalUser, true ); - estimateBucketSpan(formConfig).catch(catchData => { + estimateBucketSpan(formConfig).catch((catchData) => { expect(catchData).toBe('Unable to retrieve cluster setting search.max_buckets'); done(); @@ -79,14 +79,14 @@ describe('ML - BucketSpanEstimator', () => { }).not.toThrow('Not initialized.'); }); - it('call factory and estimator with security enabled.', done => { - expect(function() { + it('call factory and estimator with security enabled.', (done) => { + expect(function () { const estimateBucketSpan = estimateBucketSpanFactory( callWithRequest, callWithInternalUser, false ); - estimateBucketSpan(formConfig).catch(catchData => { + estimateBucketSpan(formConfig).catch((catchData) => { expect(catchData).toBe('Unable to retrieve cluster setting search.max_buckets'); done(); diff --git a/x-pack/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js b/x-pack/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js index 674875f8d5d16..de9fd06c34e6a 100644 --- a/x-pack/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js +++ b/x-pack/plugins/ml/server/models/bucket_span_estimator/polled_data_checker.js @@ -28,7 +28,7 @@ export function polledDataCheckerFactory(callAsCurrentUser) { return new Promise((resolve, reject) => { const interval = { name: '1m', ms: 60000 }; this.performSearch(interval.ms) - .then(resp => { + .then((resp) => { const fullBuckets = _.get(resp, 'aggregations.non_empty_buckets.buckets', []); const result = this.isPolledData(fullBuckets, interval); if (result.pass) { @@ -42,7 +42,7 @@ export function polledDataCheckerFactory(callAsCurrentUser) { minimumBucketSpan: this.minimumBucketSpan, }); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); diff --git a/x-pack/plugins/ml/server/models/bucket_span_estimator/single_series_checker.js b/x-pack/plugins/ml/server/models/bucket_span_estimator/single_series_checker.js index 71e692d089b49..6ae485fe11307 100644 --- a/x-pack/plugins/ml/server/models/bucket_span_estimator/single_series_checker.js +++ b/x-pack/plugins/ml/server/models/bucket_span_estimator/single_series_checker.js @@ -39,11 +39,11 @@ export function singleSeriesCheckerFactory(callAsCurrentUser) { const start = () => { // run all tests, returns a suggested interval this.runTests() - .then(interval => { + .then((interval) => { this.interval = interval; resolve(this.interval); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }; @@ -56,7 +56,7 @@ export function singleSeriesCheckerFactory(callAsCurrentUser) { .then(() => { start(); }) - .catch(resp => { + .catch((resp) => { mlLog.warn('SingleSeriesChecker: Could not load metric reference data'); reject(resp); }); @@ -105,10 +105,10 @@ export function singleSeriesCheckerFactory(callAsCurrentUser) { // recursive function called with the index of the INTERVALS array // each time one of the checks fails, the index is increased and // the tests are repeated. - const runTest = i => { + const runTest = (i) => { const interval = intervals[i]; this.performSearch(interval.ms) - .then(resp => { + .then((resp) => { const buckets = resp.aggregations.non_empty_buckets.buckets; const fullBuckets = this.getFullBuckets(buckets); if (fullBuckets.length) { @@ -149,7 +149,7 @@ export function singleSeriesCheckerFactory(callAsCurrentUser) { reject('runTest stopped because fullBuckets is empty'); } }) - .catch(resp => { + .catch((resp) => { // do something better with this reject(resp); }); @@ -265,7 +265,7 @@ export function singleSeriesCheckerFactory(callAsCurrentUser) { } this.performSearch(intervalMs) // 1h - .then(resp => { + .then((resp) => { const buckets = resp.aggregations.non_empty_buckets.buckets; const fullBuckets = this.getFullBuckets(buckets); if (fullBuckets.length) { @@ -275,7 +275,7 @@ export function singleSeriesCheckerFactory(callAsCurrentUser) { resolve(); }) - .catch(resp => { + .catch((resp) => { reject(resp); }); }); diff --git a/x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts b/x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts index 1cc2a07ddbc88..9533fbc89c76c 100644 --- a/x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts +++ b/x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts @@ -77,8 +77,8 @@ const cardinalityCheckProvider = (callAsCurrentUser: APICaller) => { } ) => { [byFieldName, partitionFieldName, overFieldName] - .filter(field => field !== undefined && field !== '' && !excludedKeywords.has(field)) - .forEach(key => { + .filter((field) => field !== undefined && field !== '' && !excludedKeywords.has(field)) + .forEach((key) => { acc.add(key as string); }); return acc; @@ -87,7 +87,7 @@ const cardinalityCheckProvider = (callAsCurrentUser: APICaller) => { ); const maxBucketFieldCardinalities: string[] = influencers.filter( - influencerField => + (influencerField) => !!influencerField && !excludedKeywords.has(influencerField) && !overallCardinalityFields.has(influencerField) diff --git a/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts b/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts index 581770e59043f..acb1bed6a37c0 100644 --- a/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts +++ b/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts @@ -47,11 +47,11 @@ export class CalendarManager { const events: CalendarEvent[] = await this._eventManager.getAllEvents(); const calendars: Calendar[] = calendarsResp.calendars; - calendars.forEach(cal => (cal.events = [])); + calendars.forEach((cal) => (cal.events = [])); // loop events and combine with related calendars - events.forEach(event => { - const calendar = calendars.find(cal => cal.calendar_id === event.calendar_id); + events.forEach((event) => { + const calendar = calendars.find((cal) => cal.calendar_id === event.calendar_id); if (calendar) { calendar.events.push(event); } @@ -66,7 +66,7 @@ export class CalendarManager { */ async getCalendarsByIds(calendarIds: string) { const calendars: Calendar[] = await this.getAllCalendars(); - return calendars.filter(calendar => calendarIds.includes(calendar.calendar_id)); + return calendars.filter((calendar) => calendarIds.includes(calendar.calendar_id)); } async newCalendar(calendar: FormCalendar) { @@ -96,12 +96,12 @@ export class CalendarManager { // workout the differences between the original events list and the new one // if an event has no event_id, it must be new const eventsToAdd = calendar.events.filter( - event => origCalendar.events.find(e => this._eventManager.isEqual(e, event)) === undefined + (event) => origCalendar.events.find((e) => this._eventManager.isEqual(e, event)) === undefined ); // if an event in the original calendar cannot be found, it must have been deleted const eventsToRemove: CalendarEvent[] = origCalendar.events.filter( - event => calendar.events.find(e => this._eventManager.isEqual(e, event)) === undefined + (event) => calendar.events.find((e) => this._eventManager.isEqual(e, event)) === undefined ); // note, both of the loops below could be removed if the add and delete endpoints @@ -130,7 +130,7 @@ export class CalendarManager { // remove all removed events await Promise.all( - eventsToRemove.map(async event => { + eventsToRemove.map(async (event) => { await this._eventManager.deleteEvent(calendarId, event.event_id); }) ); diff --git a/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts b/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts index 92ab7739dbcfb..82a272b068bb3 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts +++ b/x-pack/plugins/ml/server/models/data_recognizer/data_recognizer.ts @@ -125,7 +125,7 @@ export class DataRecognizer { if (err) { reject(err); } - fileNames.forEach(fileName => { + fileNames.forEach((fileName) => { const path = `${dirName}/${fileName}`; if (fs.lstatSync(path).isDirectory()) { dirs.push(fileName); @@ -152,7 +152,7 @@ export class DataRecognizer { const configs: Config[] = []; const dirs = await this.listDirs(this.modulesDir); await Promise.all( - dirs.map(async dir => { + dirs.map(async (dir) => { let file: string | undefined; try { file = await this.readFile(`${this.modulesDir}/${dir}/manifest.json`); @@ -179,7 +179,7 @@ export class DataRecognizer { // get the manifest.json file for a specified id, e.g. "nginx" async getManifestFile(id: string) { const manifestFiles = await this.loadManifestFiles(); - return manifestFiles.find(i => i.json.id === id); + return manifestFiles.find((i) => i.json.id === id); } // called externally by an endpoint @@ -188,7 +188,7 @@ export class DataRecognizer { const results: RecognizeResult[] = []; await Promise.all( - manifestFiles.map(async i => { + manifestFiles.map(async (i) => { const moduleConfig = i.json; let match = false; try { @@ -278,7 +278,7 @@ export class DataRecognizer { const kibana: KibanaObjects = {}; // load all of the job configs await Promise.all( - manifestJSON.jobs.map(async job => { + manifestJSON.jobs.map(async (job) => { try { const jobConfig = await this.readFile( `${this.modulesDir}/${dirName}/${ML_DIR}/${job.file}` @@ -298,7 +298,7 @@ export class DataRecognizer { // load all of the datafeed configs await Promise.all( - manifestJSON.datafeeds.map(async datafeed => { + manifestJSON.datafeeds.map(async (datafeed) => { try { const datafeedConfig = await this.readFile( `${this.modulesDir}/${dirName}/${ML_DIR}/${datafeed.file}` @@ -323,10 +323,10 @@ export class DataRecognizer { if (manifestJSON.kibana !== undefined) { const kKeys = Object.keys(manifestJSON.kibana) as Array; await Promise.all( - kKeys.map(async key => { + kKeys.map(async (key) => { kibana[key] = []; await Promise.all( - manifestJSON!.kibana[key].map(async obj => { + manifestJSON!.kibana[key].map(async (obj) => { try { const kConfig = await this.readFile( `${this.modulesDir}/${dirName}/${KIBANA_DIR}/${key}/${obj.file}` @@ -416,9 +416,9 @@ export class DataRecognizer { savedObjects: [] as KibanaObjectResponse[], }; - this.jobsForModelMemoryEstimation = moduleConfig.jobs.map(job => ({ + this.jobsForModelMemoryEstimation = moduleConfig.jobs.map((job) => ({ job, - query: moduleConfig.datafeeds.find(d => d.config.job_id === job.id)?.config.query ?? null, + query: moduleConfig.datafeeds.find((d) => d.config.job_id === job.id)?.config.query ?? null, })); this.applyJobConfigOverrides(moduleConfig, jobOverrides, jobPrefix); @@ -431,12 +431,12 @@ export class DataRecognizer { if (moduleConfig.jobs && moduleConfig.jobs.length) { if (Array.isArray(groups)) { // update groups list for each job - moduleConfig.jobs.forEach(job => (job.config.groups = groups)); + moduleConfig.jobs.forEach((job) => (job.config.groups = groups)); } // Set the results_index_name property for each job if useDedicatedIndex is true if (useDedicatedIndex === true) { - moduleConfig.jobs.forEach(job => (job.config.results_index_name = job.id)); + moduleConfig.jobs.forEach((job) => (job.config.results_index_name = job.id)); } saveResults.jobs = await this.saveJobs(moduleConfig.jobs); } @@ -444,20 +444,20 @@ export class DataRecognizer { // create the datafeeds if (moduleConfig.datafeeds && moduleConfig.datafeeds.length) { if (typeof query === 'object' && query !== null) { - moduleConfig.datafeeds.forEach(df => { + moduleConfig.datafeeds.forEach((df) => { df.config.query = query; }); } saveResults.datafeeds = await this.saveDatafeeds(moduleConfig.datafeeds); if (startDatafeed) { - const savedDatafeeds = moduleConfig.datafeeds.filter(df => { - const datafeedResult = saveResults.datafeeds.find(d => d.id === df.id); + const savedDatafeeds = moduleConfig.datafeeds.filter((df) => { + const datafeedResult = saveResults.datafeeds.find((d) => d.id === df.id); return datafeedResult !== undefined && datafeedResult.success === true; }); const startResults = await this.startDatafeeds(savedDatafeeds, start, end); - saveResults.datafeeds.forEach(df => { + saveResults.datafeeds.forEach((df) => { const startedDatafeed = startResults[df.id]; if (startedDatafeed !== undefined) { df.started = startedDatafeed.started; @@ -494,7 +494,7 @@ export class DataRecognizer { if (module && module.jobs) { // Add a wildcard at the front of each of the job IDs in the module, // as a prefix may have been supplied when creating the jobs in the module. - const jobIds = module.jobs.map(job => `*${job.id}`); + const jobIds = module.jobs.map((job) => `*${job.id}`); const { jobsExist } = jobServiceProvider(this.callAsCurrentUser); const jobInfo = await jobsExist(jobIds); @@ -507,11 +507,11 @@ export class DataRecognizer { const jobStats: MlJobStats = await this.callAsCurrentUser('ml.jobStats', { jobId: jobIds }); const jobStatsJobs: JobStat[] = []; if (jobStats.jobs && jobStats.jobs.length > 0) { - const foundJobIds = jobStats.jobs.map(job => job.job_id); + const foundJobIds = jobStats.jobs.map((job) => job.job_id); const { getLatestBucketTimestampByJob } = resultsServiceProvider(this.callAsCurrentUser); const latestBucketTimestampsByJob = await getLatestBucketTimestampByJob(foundJobIds); - jobStats.jobs.forEach(job => { + jobStats.jobs.forEach((job) => { const jobStat = { id: job.job_id, } as JobStat; @@ -548,7 +548,7 @@ export class DataRecognizer { if (indexPatterns === undefined || indexPatterns.saved_objects === undefined) { return; } - const ip = indexPatterns.saved_objects.find(i => i.attributes.title === name); + const ip = indexPatterns.saved_objects.find((i) => i.attributes.title === name); return ip !== undefined ? ip.id : undefined; } catch (error) { mlLog.warn(`Error loading index patterns, ${error}`); @@ -563,10 +563,10 @@ export class DataRecognizer { // first check if the saved objects already exist. const savedObjectExistResults = await this.checkIfSavedObjectsExist(moduleConfig.kibana); // loop through the kibanaSaveResults and update - Object.keys(moduleConfig.kibana).forEach(type => { + Object.keys(moduleConfig.kibana).forEach((type) => { // type e.g. dashboard, search ,visualization - moduleConfig.kibana[type]!.forEach(configItem => { - const existsResult = savedObjectExistResults.find(o => o.id === configItem.id); + moduleConfig.kibana[type]!.forEach((configItem) => { + const existsResult = savedObjectExistResults.find((o) => o.id === configItem.id); if (existsResult !== undefined) { configItem.exists = existsResult.exists; if (existsResult.exists === false) { @@ -590,9 +590,9 @@ export class DataRecognizer { objectExistResults: ObjectExistResult[] ) { (Object.keys(kibanaSaveResults) as Array).forEach( - type => { - kibanaSaveResults[type].forEach(resultItem => { - const i = objectExistResults.find(o => o.id === resultItem.id && o.type === type); + (type) => { + kibanaSaveResults[type].forEach((resultItem) => { + const i = objectExistResults.find((o) => o.id === resultItem.id && o.type === type); resultItem.exists = i !== undefined; }); } @@ -606,11 +606,11 @@ export class DataRecognizer { async checkIfSavedObjectsExist(kibanaObjects: KibanaObjects): Promise { const types = Object.keys(kibanaObjects); const results: ObjectExistResponse[][] = await Promise.all( - types.map(async type => { + types.map(async (type) => { const existingObjects = await this.loadExistingSavedObjects(type); - return kibanaObjects[type]!.map(obj => { + return kibanaObjects[type]!.map((obj) => { const existingObject = existingObjects.saved_objects.find( - o => o.attributes && o.attributes.title === obj.title + (o) => o.attributes && o.attributes.title === obj.title ); return { id: obj.id, @@ -634,13 +634,16 @@ export class DataRecognizer { async saveKibanaObjects(objectExistResults: ObjectExistResponse[]) { let results = { saved_objects: [] as any[] }; const filteredSavedObjects = objectExistResults - .filter(o => o.exists === false) - .map(o => o.savedObject); + .filter((o) => o.exists === false) + .map((o) => o.savedObject); if (filteredSavedObjects.length) { results = await this.savedObjectsClient.bulkCreate( // Add an empty migrationVersion attribute to each saved object to ensure // it is automatically migrated to the 7.0+ format with a references attribute. - filteredSavedObjects.map(doc => ({ ...doc, migrationVersion: doc.migrationVersion || {} })) + filteredSavedObjects.map((doc) => ({ + ...doc, + migrationVersion: doc.migrationVersion || {}, + })) ); } return results.saved_objects; @@ -651,7 +654,7 @@ export class DataRecognizer { // as success: false async saveJobs(jobs: ModuleJob[]): Promise { return await Promise.all( - jobs.map(async job => { + jobs.map(async (job) => { const jobId = job.id; try { job.id = jobId; @@ -674,7 +677,7 @@ export class DataRecognizer { // as success: false async saveDatafeeds(datafeeds: ModuleDataFeed[]) { return await Promise.all( - datafeeds.map(async datafeed => { + datafeeds.map(async (datafeed) => { try { await this.saveDatafeed(datafeed); return { id: datafeed.id, success: true, started: false }; @@ -748,8 +751,8 @@ export class DataRecognizer { // which is returned from the endpoint async updateResults(results: DataRecognizerConfigResponse, saveResults: SaveResults) { // update job results - results.jobs.forEach(j => { - saveResults.jobs.forEach(j2 => { + results.jobs.forEach((j) => { + saveResults.jobs.forEach((j2) => { if (j.id === j2.id) { j.success = j2.success; if (j2.error !== undefined) { @@ -760,8 +763,8 @@ export class DataRecognizer { }); // update datafeed results - results.datafeeds.forEach(d => { - saveResults.datafeeds.forEach(d2 => { + results.datafeeds.forEach((d) => { + saveResults.datafeeds.forEach((d2) => { if (d.id === d2.id) { d.success = d2.success; d.started = d2.started; @@ -774,9 +777,9 @@ export class DataRecognizer { // update savedObjects results (Object.keys(results.kibana) as Array).forEach( - category => { - results.kibana[category].forEach(item => { - const result = saveResults.savedObjects.find(o => o.id === item.id); + (category) => { + results.kibana[category].forEach((item) => { + const result = saveResults.savedObjects.find((o) => o.id === item.id); if (result !== undefined) { item.exists = result.exists; @@ -808,7 +811,7 @@ export class DataRecognizer { index: string | number ): void { resultItems[index] = []; - configItems.forEach(j => { + configItems.forEach((j) => { resultItems[index].push({ id: j.id, success: false, @@ -816,12 +819,12 @@ export class DataRecognizer { }); } - (Object.keys(reducedConfig) as Array).forEach(i => { + (Object.keys(reducedConfig) as Array).forEach((i) => { if (Array.isArray(reducedConfig[i])) { createResultsItems(reducedConfig[i] as any[], results, i); } else { results[i] = {} as any; - Object.keys(reducedConfig[i]).forEach(k => { + Object.keys(reducedConfig[i]).forEach((k) => { createResultsItems((reducedConfig[i] as Module['kibana'])[k] as any[], results[i], k); }); } @@ -837,13 +840,13 @@ export class DataRecognizer { // add each one to the datafeed const indexPatternNames = splitIndexPatternNames(this.indexPatternName); - moduleConfig.datafeeds.forEach(df => { + moduleConfig.datafeeds.forEach((df) => { const newIndices: string[] = []; // the datafeed can contain indexes and indices const currentIndices = df.config.indexes !== undefined ? df.config.indexes : df.config.indices; - currentIndices.forEach(index => { + currentIndices.forEach((index) => { if (index === INDEX_PATTERN_NAME) { // the datafeed index is INDEX_PATTERN_NAME, so replace it with index pattern(s) // supplied by the user or the default one from the manifest @@ -864,11 +867,11 @@ export class DataRecognizer { // marker for the id of the specified index pattern updateJobUrlIndexPatterns(moduleConfig: Module) { if (Array.isArray(moduleConfig.jobs)) { - moduleConfig.jobs.forEach(job => { + moduleConfig.jobs.forEach((job) => { // if the job has custom_urls if (job.config.custom_settings && job.config.custom_settings.custom_urls) { // loop through each url, replacing the INDEX_PATTERN_ID marker - job.config.custom_settings.custom_urls.forEach(cUrl => { + job.config.custom_settings.custom_urls.forEach((cUrl) => { const url = cUrl.url_value; if (url.match(INDEX_PATTERN_ID)) { const newUrl = url.replace( @@ -906,8 +909,8 @@ export class DataRecognizer { // INDEX_PATTERN_NAME markers for the id or name of the specified index pattern updateSavedObjectIndexPatterns(moduleConfig: Module) { if (moduleConfig.kibana) { - Object.keys(moduleConfig.kibana).forEach(category => { - moduleConfig.kibana[category]!.forEach(item => { + Object.keys(moduleConfig.kibana).forEach((category) => { + moduleConfig.kibana[category]!.forEach((item) => { let jsonString = item.config.kibanaSavedObjectMeta!.searchSourceJSON; if (jsonString.match(INDEX_PATTERN_ID)) { jsonString = jsonString.replace( @@ -1094,7 +1097,7 @@ export class DataRecognizer { const generalOverrides: GeneralJobsOverride[] = []; const jobSpecificOverrides: JobSpecificOverride[] = []; - overrides.forEach(override => { + overrides.forEach((override) => { if (isGeneralJobOverride(override)) { generalOverrides.push(override); } else { @@ -1102,17 +1105,18 @@ export class DataRecognizer { } }); - if (generalOverrides.some(override => !!override.analysis_limits?.model_memory_limit)) { + if (generalOverrides.some((override) => !!override.analysis_limits?.model_memory_limit)) { this.jobsForModelMemoryEstimation = []; } else { this.jobsForModelMemoryEstimation = moduleConfig.jobs - .filter(job => { - const override = jobSpecificOverrides.find(o => `${jobPrefix}${o.job_id}` === job.id); + .filter((job) => { + const override = jobSpecificOverrides.find((o) => `${jobPrefix}${o.job_id}` === job.id); return override?.analysis_limits?.model_memory_limit === undefined; }) - .map(job => ({ + .map((job) => ({ job, - query: moduleConfig.datafeeds.find(d => d.config.job_id === job.id)?.config.query || null, + query: + moduleConfig.datafeeds.find((d) => d.config.job_id === job.id)?.config.query || null, })); } @@ -1121,7 +1125,7 @@ export class DataRecognizer { return; } - Object.keys(source).forEach(key => { + Object.keys(source).forEach((key) => { const sourceValue = source[key]; const updateValue = update[key]; @@ -1142,17 +1146,17 @@ export class DataRecognizer { }); } - generalOverrides.forEach(generalOverride => { - jobs.forEach(job => { + generalOverrides.forEach((generalOverride) => { + jobs.forEach((job) => { merge(job.config, generalOverride); processArrayValues(job.config, generalOverride); }); }); - jobSpecificOverrides.forEach(jobSpecificOverride => { + jobSpecificOverrides.forEach((jobSpecificOverride) => { // for each override, find the relevant job. // note, the job id already has the prefix prepended to it - const job = jobs.find(j => j.id === `${jobPrefix}${jobSpecificOverride.job_id}`); + const job = jobs.find((j) => j.id === `${jobPrefix}${jobSpecificOverride.job_id}`); if (job !== undefined) { // delete the job_id in the override as this shouldn't be overridden delete jobSpecificOverride.job_id; @@ -1183,7 +1187,7 @@ export class DataRecognizer { // the overrides which don't contain a datafeed id or a job id will be applied to all jobs in the module const generalOverrides: GeneralDatafeedsOverride[] = []; const datafeedSpecificOverrides: DatafeedOverride[] = []; - overrides.forEach(o => { + overrides.forEach((o) => { if (o.datafeed_id === undefined && o.job_id === undefined) { generalOverrides.push(o); } else { @@ -1191,20 +1195,20 @@ export class DataRecognizer { } }); - generalOverrides.forEach(o => { + generalOverrides.forEach((o) => { datafeeds.forEach(({ config }) => { merge(config, o); }); }); // collect all the overrides which contain either a job id or a datafeed id - datafeedSpecificOverrides.forEach(o => { + datafeedSpecificOverrides.forEach((o) => { // either a job id or datafeed id has been specified, so create a new id // containing either one plus the prefix const tempId: string = String(o.datafeed_id !== undefined ? o.datafeed_id : o.job_id); const dId = prefixDatafeedId(tempId, jobPrefix); - const datafeed = datafeeds.find(d => d.id === dId); + const datafeed = datafeeds.find((d) => d.id === dId); if (datafeed !== undefined) { delete o.job_id; delete o.datafeed_id; diff --git a/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts b/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts index 8ccd359137b67..43581ad75fb17 100644 --- a/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts +++ b/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts @@ -142,7 +142,7 @@ export class DataVisualizer { // To avoid checking for the existence of too many aggregatable fields in one request, // split the check into multiple batches (max 200 fields per request). const batches: string[][] = [[]]; - _.each(aggregatableFields, field => { + _.each(aggregatableFields, (field) => { let lastArray: string[] = _.last(batches); if (lastArray.length === AGGREGATABLE_EXISTS_REQUEST_BATCH_SIZE) { lastArray = []; @@ -152,7 +152,7 @@ export class DataVisualizer { }); await Promise.all( - batches.map(async fields => { + batches.map(async (fields) => { const batchStats = await this.checkAggregatableFieldsExist( indexPatternTitle, query, @@ -173,7 +173,7 @@ export class DataVisualizer { ); await Promise.all( - nonAggregatableFields.map(async field => { + nonAggregatableFields.map(async (field) => { const existsInDocs = await this.checkNonAggregatableFieldExists( indexPatternTitle, query, @@ -217,7 +217,7 @@ export class DataVisualizer { // Batch up fields by type, getting stats for multiple fields at a time. const batches: Field[][] = []; const batchedFields: { [key: string]: Field[][] } = {}; - _.each(fields, field => { + _.each(fields, (field) => { if (field.fieldName === undefined) { // undefined fieldName is used for a document count request. // getDocumentCountStats requires timeField - don't add to batched requests if not defined @@ -238,13 +238,13 @@ export class DataVisualizer { } }); - _.each(batchedFields, lists => { + _.each(batchedFields, (lists) => { batches.push(...lists); }); let results: BatchStats[] = []; await Promise.all( - batches.map(async batch => { + batches.map(async (batch) => { let batchStats: BatchStats[] = []; const first = batch[0]; switch (first.type) { @@ -313,7 +313,7 @@ export class DataVisualizer { // Use an exists filter on the the field name to get // examples of the field, so cannot batch up. await Promise.all( - batch.map(async field => { + batch.map(async (field) => { const stats = await this.getFieldExamples( indexPatternTitle, query, @@ -492,7 +492,7 @@ export class DataVisualizer { ['aggregations', 'eventRate', 'buckets'], [] ); - _.each(dataByTimeBucket, dataForTime => { + _.each(dataByTimeBucket, (dataForTime) => { const time = dataForTime.key; buckets[time] = dataForTime.doc_count; }); @@ -867,7 +867,7 @@ export class DataVisualizer { [...aggsPath, `${safeFieldName}_values`, 'buckets'], [] ); - _.each(valueBuckets, bucket => { + _.each(valueBuckets, (bucket) => { stats[`${bucket.key_as_string}Count`] = bucket.doc_count; }); diff --git a/x-pack/plugins/ml/server/models/fields_service/fields_service.ts b/x-pack/plugins/ml/server/models/fields_service/fields_service.ts index 6558d0d48ded9..d9d765028b123 100644 --- a/x-pack/plugins/ml/server/models/fields_service/fields_service.ts +++ b/x-pack/plugins/ml/server/models/fields_service/fields_service.ts @@ -42,7 +42,7 @@ export function fieldsServiceProvider(callAsCurrentUser: APICaller) { fields: fieldNames, }); const aggregatableFields: string[] = []; - fieldNames.forEach(fieldName => { + fieldNames.forEach((fieldName) => { const fieldInfo = fieldCapsResp.fields[fieldName]; const typeKeys = fieldInfo !== undefined ? Object.keys(fieldInfo) : []; if (typeKeys.length > 0) { @@ -88,7 +88,7 @@ export function fieldsServiceProvider(callAsCurrentUser: APICaller) { ) ?? {}; // No need to perform aggregation over the cached fields - const fieldsToAgg = aggregatableFields.filter(field => !cachedValues.hasOwnProperty(field)); + const fieldsToAgg = aggregatableFields.filter((field) => !cachedValues.hasOwnProperty(field)); if (fieldsToAgg.length === 0) { return cachedValues; @@ -276,7 +276,7 @@ export function fieldsServiceProvider(callAsCurrentUser: APICaller) { ) ?? {}; // No need to perform aggregation over the cached fields - const fieldsToAgg = aggregatableFields.filter(field => !cachedValues.hasOwnProperty(field)); + const fieldsToAgg = aggregatableFields.filter((field) => !cachedValues.hasOwnProperty(field)); if (fieldsToAgg.length === 0) { return cachedValues; diff --git a/x-pack/plugins/ml/server/models/file_data_visualizer/import_data.ts b/x-pack/plugins/ml/server/models/file_data_visualizer/import_data.ts index 9d7009955124f..afe699cc7fecf 100644 --- a/x-pack/plugins/ml/server/models/file_data_visualizer/import_data.ts +++ b/x-pack/plugins/ml/server/models/file_data_visualizer/import_data.ts @@ -175,7 +175,5 @@ export function importDataProvider(callAsCurrentUser: APICaller) { } function generateId() { - return Math.random() - .toString(36) - .substr(2, 9); + return Math.random().toString(36).substr(2, 9); } diff --git a/x-pack/plugins/ml/server/models/filter/filter_manager.ts b/x-pack/plugins/ml/server/models/filter/filter_manager.ts index 42440057a2d1a..11208b4d941f3 100644 --- a/x-pack/plugins/ml/server/models/filter/filter_manager.ts +++ b/x-pack/plugins/ml/server/models/filter/filter_manager.ts @@ -174,16 +174,16 @@ export class FilterManager { buildFiltersInUse(jobsList: PartialJob[]) { // Build a map of filter_ids against jobs and detectors using that filter. const filtersInUse: FiltersInUse = {}; - jobsList.forEach(job => { + jobsList.forEach((job) => { const detectors = job.analysis_config.detectors; - detectors.forEach(detector => { + detectors.forEach((detector) => { if (detector.custom_rules) { const rules = detector.custom_rules; - rules.forEach(rule => { + rules.forEach((rule) => { if (rule.scope) { const ruleScope: DetectorRuleScope = rule.scope; const scopeFields = Object.keys(ruleScope); - scopeFields.forEach(scopeField => { + scopeFields.forEach((scopeField) => { const filter = ruleScope[scopeField]; const filterId = filter.filter_id; if (filtersInUse[filterId] === undefined) { diff --git a/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.js b/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.js index 2cdfc0ef4f4c5..6b782f8652363 100644 --- a/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.js +++ b/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.js @@ -113,7 +113,7 @@ export function jobAuditMessagesProvider(callAsCurrentUser) { let messages = []; if (resp.hits.total !== 0) { - messages = resp.hits.hits.map(hit => hit._source); + messages = resp.hits.hits.map((hit) => hit._source); } return messages; } catch (e) { @@ -210,14 +210,14 @@ export function jobAuditMessagesProvider(callAsCurrentUser) { messagesPerJob = resp.aggregations.levelsPerJob.buckets; } - messagesPerJob.forEach(job => { + messagesPerJob.forEach((job) => { // ignore system messages (id==='') if (job.key !== '' && job.levels && job.levels.buckets && job.levels.buckets.length) { let highestLevel = 0; let highestLevelText = ''; let msgTime = 0; - job.levels.buckets.forEach(level => { + job.levels.buckets.forEach((level) => { const label = level.key; // note the highest message level if (LEVEL[label] > highestLevel) { @@ -227,7 +227,7 @@ export function jobAuditMessagesProvider(callAsCurrentUser) { level.latestMessage.buckets && level.latestMessage.buckets.length ) { - level.latestMessage.buckets.forEach(msg => { + level.latestMessage.buckets.forEach((msg) => { // there should only be one result here. highestLevelText = msg.key; diff --git a/x-pack/plugins/ml/server/models/job_service/groups.ts b/x-pack/plugins/ml/server/models/job_service/groups.ts index e44609bc66711..56757e4cc3ff7 100644 --- a/x-pack/plugins/ml/server/models/job_service/groups.ts +++ b/x-pack/plugins/ml/server/models/job_service/groups.ts @@ -35,10 +35,10 @@ export function groupsProvider(callAsCurrentUser: APICaller) { ]); if (jobs) { - jobs.forEach(job => { + jobs.forEach((job) => { jobIds[job.job_id] = null; if (job.groups !== undefined) { - job.groups.forEach(g => { + job.groups.forEach((g) => { if (groups[g] === undefined) { groups[g] = { id: g, @@ -53,8 +53,8 @@ export function groupsProvider(callAsCurrentUser: APICaller) { }); } if (calendars) { - calendars.forEach(cal => { - cal.job_ids.forEach(jId => { + calendars.forEach((cal) => { + cal.job_ids.forEach((jId) => { // don't include _all in the calendar groups list if (jId !== GLOBAL_CALENDAR && jobIds[jId] === undefined) { if (groups[jId] === undefined) { @@ -71,7 +71,7 @@ export function groupsProvider(callAsCurrentUser: APICaller) { }); } - return Object.keys(groups).map(g => groups[g]); + return Object.keys(groups).map((g) => groups[g]); } async function updateGroups(jobs: Job[]) { diff --git a/x-pack/plugins/ml/server/models/job_service/jobs.ts b/x-pack/plugins/ml/server/models/job_service/jobs.ts index 225cd43e411a4..5503169f2d371 100644 --- a/x-pack/plugins/ml/server/models/job_service/jobs.ts +++ b/x-pack/plugins/ml/server/models/job_service/jobs.ts @@ -130,7 +130,7 @@ export function jobsProvider(callAsCurrentUser: APICaller) { async function jobsSummary(jobIds: string[] = []) { const fullJobsList: CombinedJobWithStats[] = await createFullJobsList(); - const fullJobsIds = fullJobsList.map(job => job.job_id); + const fullJobsIds = fullJobsList.map((job) => job.job_id); const auditMessages: AuditMessage[] = await getAuditMessagesSummary(fullJobsIds); const auditMessagesByJob = auditMessages.reduce((acc, cur) => { acc[cur.job_id] = cur; @@ -141,7 +141,7 @@ export function jobsProvider(callAsCurrentUser: APICaller) { defaultMessage: 'deleting', }); - const jobs = fullJobsList.map(job => { + const jobs = fullJobsList.map((job) => { const hasDatafeed = typeof job.datafeed_config === 'object' && Object.keys(job.datafeed_config).length > 0; const dataCounts = job.data_counts; @@ -169,7 +169,7 @@ export function jobsProvider(callAsCurrentUser: APICaller) { nodeName: job.node ? job.node.name : undefined, deleting: job.deleting || undefined, }; - if (jobIds.find(j => j === tempJob.id)) { + if (jobIds.find((j) => j === tempJob.id)) { tempJob.fullJob = job; } const auditMessage = auditMessagesByJob[tempJob.id]; @@ -193,7 +193,7 @@ export function jobsProvider(callAsCurrentUser: APICaller) { const fullJobsList = await createFullJobsList(); const jobsMap: { [id: string]: string[] } = {}; - const jobs = fullJobsList.map(job => { + const jobs = fullJobsList.map((job) => { jobsMap[job.job_id] = job.groups || []; const hasDatafeed = typeof job.datafeed_config === 'object' && Object.keys(job.datafeed_config).length > 0; @@ -267,10 +267,10 @@ export function jobsProvider(callAsCurrentUser: APICaller) { >(requests); if (datafeedResults && datafeedResults.datafeeds) { - datafeedResults.datafeeds.forEach(datafeed => { + datafeedResults.datafeeds.forEach((datafeed) => { if (datafeedStatsResults && datafeedStatsResults.datafeeds) { const datafeedStats = datafeedStatsResults.datafeeds.find( - ds => ds.datafeed_id === datafeed.datafeed_id + (ds) => ds.datafeed_id === datafeed.datafeed_id ); if (datafeedStats) { datafeeds[datafeed.job_id] = { ...datafeed, ...datafeedStats }; @@ -283,11 +283,11 @@ export function jobsProvider(callAsCurrentUser: APICaller) { // used for assigning calendars to jobs when a calendar has // only been attached to a group if (jobResults && jobResults.jobs) { - jobResults.jobs.forEach(job => { + jobResults.jobs.forEach((job) => { calendarsByJobId[job.job_id] = []; if (job.groups !== undefined) { - job.groups.forEach(gId => { + job.groups.forEach((gId) => { if (groups[gId] === undefined) { groups[gId] = []; } @@ -299,12 +299,12 @@ export function jobsProvider(callAsCurrentUser: APICaller) { // assign calendars to jobs if (calendarResults) { - calendarResults.forEach(cal => { - cal.job_ids.forEach(id => { + calendarResults.forEach((cal) => { + cal.job_ids.forEach((id) => { if (id === GLOBAL_CALENDAR) { globalCalendars.push(cal.calendar_id); } else if (groups[id]) { - groups[id].forEach(jId => { + groups[id].forEach((jId) => { if (calendarsByJobId[jId] !== undefined) { calendarsByJobId[jId].push(cal.calendar_id); } @@ -327,7 +327,7 @@ export function jobsProvider(callAsCurrentUser: APICaller) { // create jobs objects containing job stats, datafeeds, datafeed stats and calendars if (jobResults && jobResults.jobs) { - jobResults.jobs.forEach(job => { + jobResults.jobs.forEach((job) => { let tempJob = job as CombinedJobWithStats; const calendars: string[] = [ @@ -339,7 +339,7 @@ export function jobsProvider(callAsCurrentUser: APICaller) { } if (jobStatsResults && jobStatsResults.jobs) { - const jobStats = jobStatsResults.jobs.find(js => js.job_id === tempJob.job_id); + const jobStats = jobStatsResults.jobs.find((js) => js.job_id === tempJob.job_id); if (jobStats !== undefined) { tempJob = { ...tempJob, ...jobStats }; if (jobStats.node) { @@ -375,9 +375,9 @@ export function jobsProvider(callAsCurrentUser: APICaller) { const jobIds = []; try { const tasksList = await callAsCurrentUser('tasks.list', { actions, detailed }); - Object.keys(tasksList.nodes).forEach(nodeId => { + Object.keys(tasksList.nodes).forEach((nodeId) => { const tasks = tasksList.nodes[nodeId].tasks; - Object.keys(tasks).forEach(taskId => { + Object.keys(tasks).forEach((taskId) => { jobIds.push(tasks[taskId].description.replace(/^delete-job-/, '')); }); }); @@ -385,7 +385,7 @@ export function jobsProvider(callAsCurrentUser: APICaller) { // if the user doesn't have permission to load the task list, // use the jobs list to get the ids of deleting jobs const { jobs } = await callAsCurrentUser('ml.jobs'); - jobIds.push(...jobs.filter(j => j.deleting === true).map(j => j.job_id)); + jobIds.push(...jobs.filter((j) => j.deleting === true).map((j) => j.job_id)); } return { jobIds }; } @@ -401,17 +401,17 @@ export function jobsProvider(callAsCurrentUser: APICaller) { const results: { [id: string]: boolean } = {}; if (jobsInfo.count > 0) { - const allJobIds = jobsInfo.jobs.map(job => job.job_id); + const allJobIds = jobsInfo.jobs.map((job) => job.job_id); // Check if each of the supplied IDs match existing jobs. - jobIds.forEach(jobId => { + jobIds.forEach((jobId) => { // Create a Regex for each supplied ID as wildcard * is allowed. const regexp = new RegExp(`^${jobId.replace(/\*+/g, '.*')}$`); - const exists = allJobIds.some(existsJobId => regexp.test(existsJobId)); + const exists = allJobIds.some((existsJobId) => regexp.test(existsJobId)); results[jobId] = exists; }); } else { - jobIds.forEach(jobId => { + jobIds.forEach((jobId) => { results[jobId] = false; }); } @@ -422,9 +422,9 @@ export function jobsProvider(callAsCurrentUser: APICaller) { async function getAllJobAndGroupIds() { const { getAllGroups } = groupsProvider(callAsCurrentUser); const jobs = await callAsCurrentUser('ml.jobs'); - const jobIds = jobs.jobs.map(job => job.job_id); + const jobIds = jobs.jobs.map((job) => job.job_id); const groups = await getAllGroups(); - const groupIds = groups.map(group => group.id); + const groupIds = groups.map((group) => group.id); return { jobIds, diff --git a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/examples.ts b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/examples.ts index b209dc5681563..bf0d79b3ec072 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/examples.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/examples.ts @@ -92,7 +92,7 @@ export function categorizationExamplesProvider( return { examples: examplesWithTokens }; } catch (error) { validationResults.createTooManyTokensResult(error, halfChunkSize); - return { examples: halfExamples.map(e => ({ text: e, tokens: [] })) }; + return { examples: halfExamples.map((e) => ({ text: e, tokens: [] })) }; } } } @@ -119,10 +119,10 @@ export function categorizationExamplesProvider( }, }); - const lengths = examples.map(e => e.length); - const sumLengths = lengths.map((s => (a: number) => (s += a))(0)); + const lengths = examples.map((e) => e.length); + const sumLengths = lengths.map(((s) => (a: number) => (s += a))(0)); - const tokensPerExample: Token[][] = examples.map(e => []); + const tokensPerExample: Token[][] = examples.map((e) => []); tokens.forEach((t, i) => { for (let g = 0; g < sumLengths.length; g++) { @@ -193,7 +193,7 @@ export function categorizationExamplesProvider( // sort back into original order and remove origIndex property const processedExamples = filteredExamples .sort((a, b) => a.origIndex - b.origIndex) - .map(e => ({ text: e.text, tokens: e.tokens })); + .map((e) => ({ text: e.text, tokens: e.tokens })); return { overallValidStatus: validationResults.overallResult, diff --git a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts index 3361cc454e2b7..13c5f107972eb 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts @@ -125,7 +125,7 @@ export function topCategoriesProvider(callWithRequest: callWithRequestType) { const catCounts = await getTopCategoryCounts(jobId, numberOfCategories); const categories = await getCategories( jobId, - catCounts.map(c => c.id), + catCounts.map((c) => c.id), catCounts.length || numberOfCategories ); @@ -149,7 +149,7 @@ export function topCategoriesProvider(callWithRequest: callWithRequestType) { } else { return { total, - categories: categories.map(category => { + categories: categories.map((category) => { return { category, }; diff --git a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/validation_results.ts b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/validation_results.ts index e3b37fffa9c77..4b90283a3a966 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/validation_results.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/validation_results.ts @@ -28,17 +28,19 @@ export class ValidationResults { } public get overallResult() { - if (this._results.some(c => c.valid === CATEGORY_EXAMPLES_VALIDATION_STATUS.INVALID)) { + if (this._results.some((c) => c.valid === CATEGORY_EXAMPLES_VALIDATION_STATUS.INVALID)) { return CATEGORY_EXAMPLES_VALIDATION_STATUS.INVALID; } - if (this._results.some(c => c.valid === CATEGORY_EXAMPLES_VALIDATION_STATUS.PARTIALLY_VALID)) { + if ( + this._results.some((c) => c.valid === CATEGORY_EXAMPLES_VALIDATION_STATUS.PARTIALLY_VALID) + ) { return CATEGORY_EXAMPLES_VALIDATION_STATUS.PARTIALLY_VALID; } return CATEGORY_EXAMPLES_VALIDATION_STATUS.VALID; } private _resultExists(id: VALIDATION_RESULT) { - return this._results.some(r => r.id === id); + return this._results.some((r) => r.id === id); } public createTokenCountResult(examples: CategoryFieldExample[], sampleSize: number) { @@ -53,7 +55,7 @@ export class ValidationResults { return; } - const validExamplesSize = examples.filter(e => e.tokens.length >= VALID_TOKEN_COUNT).length; + const validExamplesSize = examples.filter((e) => e.tokens.length >= VALID_TOKEN_COUNT).length; const percentValid = sampleSize === 0 ? 0 : validExamplesSize / sampleSize; let valid = CATEGORY_EXAMPLES_VALIDATION_STATUS.VALID; @@ -119,7 +121,7 @@ export class ValidationResults { } public createNullValueResult(examples: Array) { - const nullCount = examples.filter(e => e === null).length; + const nullCount = examples.filter((e) => e === null).length; if (nullCount / examples.length >= NULL_COUNT_PERCENT_LIMIT) { this._results.push({ diff --git a/x-pack/plugins/ml/server/models/job_service/new_job/line_chart.ts b/x-pack/plugins/ml/server/models/job_service/new_job/line_chart.ts index a198fac4e3fef..4872f0f5e0ea4 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job/line_chart.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/line_chart.ts @@ -50,7 +50,7 @@ export function newJobLineChartProvider(callWithRequest: callWithRequestType) { const results = await callWithRequest('search', json); return processSearchResults( results, - aggFieldNamePairs.map(af => af.field) + aggFieldNamePairs.map((af) => af.field) ); } diff --git a/x-pack/plugins/ml/server/models/job_service/new_job/population_chart.ts b/x-pack/plugins/ml/server/models/job_service/new_job/population_chart.ts index ee35f13c44ee6..26609bdcc8f7d 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job/population_chart.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job/population_chart.ts @@ -55,7 +55,7 @@ export function newJobPopulationChartProvider(callWithRequest: callWithRequestTy const results = await callWithRequest('search', json); return processSearchResults( results, - aggFieldNamePairs.map(af => af.field) + aggFieldNamePairs.map((af) => af.field) ); } catch (error) { return { error }; diff --git a/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts index 405f645ca0e1d..a5ed4a18bf51c 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts @@ -149,27 +149,27 @@ async function combineFieldsAndAggs( const isRollup = Object.keys(rollupFields).length > 0; const mix = mixFactory(isRollup, rollupFields); - aggs.forEach(a => { + aggs.forEach((a) => { if (a.type === METRIC_AGG_TYPE && a.fields !== undefined) { switch (a.id) { case ML_JOB_AGGREGATION.LAT_LONG: - geoFields.forEach(f => mix(f, a)); + geoFields.forEach((f) => mix(f, a)); break; case ML_JOB_AGGREGATION.INFO_CONTENT: case ML_JOB_AGGREGATION.HIGH_INFO_CONTENT: case ML_JOB_AGGREGATION.LOW_INFO_CONTENT: - textFields.forEach(f => mix(f, a)); + textFields.forEach((f) => mix(f, a)); case ML_JOB_AGGREGATION.DISTINCT_COUNT: case ML_JOB_AGGREGATION.HIGH_DISTINCT_COUNT: case ML_JOB_AGGREGATION.LOW_DISTINCT_COUNT: // distinct count (i.e. cardinality) takes keywords, ips // as well as numerical fields - keywordFields.forEach(f => mix(f, a)); - ipFields.forEach(f => mix(f, a)); + keywordFields.forEach((f) => mix(f, a)); + ipFields.forEach((f) => mix(f, a)); // note, no break to fall through to add numerical fields. default: // all other aggs take numerical fields - numericalFields.forEach(f => { + numericalFields.forEach((f) => { mix(f, a); }); break; @@ -186,7 +186,7 @@ async function combineFieldsAndAggs( // remove fields that have no aggs associated to them, unless they are date fields function filterFields(fields: Field[]): Field[] { return fields.filter( - f => f.aggs && (f.aggs.length > 0 || (f.aggs.length === 0 && f.type === ES_FIELD_TYPES.DATE)) + (f) => f.aggs && (f.aggs.length > 0 || (f.aggs.length === 0 && f.type === ES_FIELD_TYPES.DATE)) ); } @@ -196,7 +196,7 @@ function mixFactory(isRollup: boolean, rollupFields: RollupFields) { return function mix(field: Field, agg: Aggregation): void { if ( isRollup === false || - (rollupFields[field.id] && rollupFields[field.id].find(f => f.agg === agg.dslName)) + (rollupFields[field.id] && rollupFields[field.id].find((f) => f.agg === agg.dslName)) ) { if (field.aggs !== undefined) { field.aggs.push(agg); @@ -210,14 +210,14 @@ function mixFactory(isRollup: boolean, rollupFields: RollupFields) { function combineAllRollupFields(rollupConfigs: RollupJob[]): RollupFields { const rollupFields: RollupFields = {}; - rollupConfigs.forEach(conf => { - Object.keys(conf.fields).forEach(fieldName => { + rollupConfigs.forEach((conf) => { + Object.keys(conf.fields).forEach((fieldName) => { if (rollupFields[fieldName] === undefined) { rollupFields[fieldName] = conf.fields[fieldName]; } else { const aggs = conf.fields[fieldName]; - aggs.forEach(agg => { - if (rollupFields[fieldName].find(f => f.agg === agg.agg) === null) { + aggs.forEach((agg) => { + if (rollupFields[fieldName].find((f) => f.agg === agg.agg) === null) { rollupFields[fieldName].push(agg); } }); @@ -228,20 +228,20 @@ function combineAllRollupFields(rollupConfigs: RollupJob[]): RollupFields { } function getKeywordFields(fields: Field[]): Field[] { - return fields.filter(f => f.type === ES_FIELD_TYPES.KEYWORD); + return fields.filter((f) => f.type === ES_FIELD_TYPES.KEYWORD); } function getTextFields(fields: Field[]): Field[] { - return fields.filter(f => f.type === ES_FIELD_TYPES.TEXT); + return fields.filter((f) => f.type === ES_FIELD_TYPES.TEXT); } function getIpFields(fields: Field[]): Field[] { - return fields.filter(f => f.type === ES_FIELD_TYPES.IP); + return fields.filter((f) => f.type === ES_FIELD_TYPES.IP); } function getNumericalFields(fields: Field[]): Field[] { return fields.filter( - f => + (f) => f.type === ES_FIELD_TYPES.LONG || f.type === ES_FIELD_TYPES.INTEGER || f.type === ES_FIELD_TYPES.SHORT || @@ -255,6 +255,6 @@ function getNumericalFields(fields: Field[]): Field[] { function getGeoFields(fields: Field[]): Field[] { return fields.filter( - f => f.type === ES_FIELD_TYPES.GEO_POINT || f.type === ES_FIELD_TYPES.GEO_SHAPE + (f) => f.type === ES_FIELD_TYPES.GEO_POINT || f.type === ES_FIELD_TYPES.GEO_SHAPE ); } diff --git a/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.test.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.test.ts index f1af7614b4232..02fef16a384d0 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.test.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.test.ts @@ -45,7 +45,7 @@ describe('job_service - job_caps', () => { }); describe('farequote newJobCaps()', () => { - it('can get job caps for index pattern', async done => { + it('can get job caps for index pattern', async (done) => { const indexPattern = 'farequote-*'; const isRollup = false; const { newJobCaps } = newJobCapsProvider(callWithRequestNonRollupMock); @@ -54,7 +54,7 @@ describe('job_service - job_caps', () => { done(); }); - it('can get rollup job caps for non rollup index pattern', async done => { + it('can get rollup job caps for non rollup index pattern', async (done) => { const indexPattern = 'farequote-*'; const isRollup = true; const { newJobCaps } = newJobCapsProvider(callWithRequestNonRollupMock); @@ -65,7 +65,7 @@ describe('job_service - job_caps', () => { }); describe('cloudwatch newJobCaps()', () => { - it('can get rollup job caps for rollup index pattern', async done => { + it('can get rollup job caps for rollup index pattern', async (done) => { const indexPattern = 'cloud_roll_index'; const isRollup = true; const { newJobCaps } = newJobCapsProvider(callWithRequestRollupMock); @@ -74,7 +74,7 @@ describe('job_service - job_caps', () => { done(); }); - it('can get non rollup job caps for rollup index pattern', async done => { + it('can get non rollup job caps for rollup index pattern', async (done) => { const indexPattern = 'cloud_roll_index'; const isRollup = false; const { newJobCaps } = newJobCapsProvider(callWithRequestRollupMock); diff --git a/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.ts index 3a9d979ccb22c..a0ab4b5cf4e3e 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/new_job_caps.ts @@ -43,15 +43,15 @@ export function newJobCapsProvider(callWithRequest: any) { // map of ids to allow it to be stringified for transportation // over the network. function convertForStringify(aggs: Aggregation[], fields: Field[]): void { - fields.forEach(f => { - f.aggIds = f.aggs ? f.aggs.map(a => a.id) : []; + fields.forEach((f) => { + f.aggIds = f.aggs ? f.aggs.map((a) => a.id) : []; delete f.aggs; }); - aggs.forEach(a => { + aggs.forEach((a) => { if (a.fields !== undefined) { // if the aggregation supports fields, i.e. it's fields list isn't undefined, // create a list of field ids - a.fieldIds = a.fields.map(f => f.id); + a.fieldIds = a.fields.map((f) => f.id); } delete a.fields; }); diff --git a/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts index 2845006dae05f..f7d846839503d 100644 --- a/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts +++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts @@ -67,7 +67,7 @@ async function loadRollupIndexPattern( }); const obj = resp.saved_objects.find( - r => + (r) => r.attributes && r.attributes.type === 'rollup' && r.attributes.title === indexPattern && diff --git a/x-pack/plugins/ml/server/models/job_validation/job_validation.test.ts b/x-pack/plugins/ml/server/models/job_validation/job_validation.test.ts index 3a86693e91828..f9999a06f38ed 100644 --- a/x-pack/plugins/ml/server/models/job_validation/job_validation.test.ts +++ b/x-pack/plugins/ml/server/models/job_validation/job_validation.test.ts @@ -11,7 +11,7 @@ import { JobValidationMessage } from '../../../common/constants/messages'; // mock callWithRequest const callWithRequest: APICaller = (method: string) => { - return new Promise(resolve => { + return new Promise((resolve) => { if (method === 'fieldCaps') { resolve({ fields: [] }); return; @@ -36,8 +36,8 @@ describe('ML - validateJob', () => { job: { analysis_config: { detectors: [] } }, } as unknown) as ValidateJobPayload; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([ 'job_id_empty', @@ -49,7 +49,7 @@ describe('ML - validateJob', () => { }); const jobIdTests = (testIds: string[], messageId: string) => { - const promises = testIds.map(id => { + const promises = testIds.map((id) => { const payload = ({ job: { analysis_config: { detectors: [] }, @@ -61,11 +61,11 @@ describe('ML - validateJob', () => { }); }); - return Promise.all(promises).then(testResults => { - testResults.forEach(messages => { + return Promise.all(promises).then((testResults) => { + testResults.forEach((messages) => { expect(Array.isArray(messages)).toBe(true); if (Array.isArray(messages)) { - const ids = messages.map(m => m.id); + const ids = messages.map((m) => m.id); expect(ids.includes(messageId)).toBe(true); } }); @@ -77,8 +77,8 @@ describe('ML - validateJob', () => { job: { analysis_config: { detectors: [] }, groups: testIds }, } as unknown) as ValidateJobPayload; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids.includes(messageId)).toBe(true); }); }; @@ -113,7 +113,7 @@ describe('ML - validateJob', () => { }); const bucketSpanFormatTests = (testFormats: string[], messageId: string) => { - const promises = testFormats.map(format => { + const promises = testFormats.map((format) => { const payload = ({ job: { analysis_config: { bucket_span: format, detectors: [] } }, } as unknown) as ValidateJobPayload; @@ -122,11 +122,11 @@ describe('ML - validateJob', () => { }); }); - return Promise.all(promises).then(testResults => { - testResults.forEach(messages => { + return Promise.all(promises).then((testResults) => { + testResults.forEach((messages) => { expect(Array.isArray(messages)).toBe(true); if (Array.isArray(messages)) { - const ids = messages.map(m => m.id); + const ids = messages.map((m) => m.id); expect(ids.includes(messageId)).toBe(true); } }); @@ -156,8 +156,8 @@ describe('ML - validateJob', () => { function: undefined, }); - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids.includes('detectors_function_empty')).toBe(true); }); }); @@ -170,8 +170,8 @@ describe('ML - validateJob', () => { function: 'count', }); - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids.includes('detectors_function_not_empty')).toBe(true); }); }); @@ -182,8 +182,8 @@ describe('ML - validateJob', () => { fields: {}, } as unknown) as ValidateJobPayload; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids.includes('index_fields_invalid')).toBe(true); }); }); @@ -194,8 +194,8 @@ describe('ML - validateJob', () => { fields: { testField: {} }, } as unknown) as ValidateJobPayload; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids.includes('index_fields_valid')).toBe(true); }); }); @@ -218,7 +218,7 @@ describe('ML - validateJob', () => { fields: { testField: {} }, }); - it('throws an error because job.analysis_config.influencers is not an Array', done => { + it('throws an error because job.analysis_config.influencers is not an Array', (done) => { const payload = getBasicPayload() as any; delete payload.job.analysis_config.influencers; @@ -234,8 +234,8 @@ describe('ML - validateJob', () => { it('detect duplicate detectors', () => { const payload = getBasicPayload() as any; payload.job.analysis_config.detectors.push({ function: 'count' }); - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([ 'job_id_valid', 'detectors_function_not_empty', @@ -257,8 +257,8 @@ describe('ML - validateJob', () => { { function: 'count', by_field_name: 'airline' }, { function: 'count', partition_field_name: 'airline' }, ]; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([ 'job_id_valid', 'detectors_function_not_empty', @@ -272,8 +272,8 @@ describe('ML - validateJob', () => { // Failing https://github.com/elastic/kibana/issues/65865 it('basic validation passes, extended checks return some messages', () => { const payload = getBasicPayload(); - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([ 'job_id_valid', 'detectors_function_not_empty', @@ -305,8 +305,8 @@ describe('ML - validateJob', () => { fields: { testField: {} }, }; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([ 'job_id_valid', 'detectors_function_not_empty', @@ -338,8 +338,8 @@ describe('ML - validateJob', () => { fields: { testField: {} }, }; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([ 'job_id_valid', 'detectors_function_not_empty', @@ -381,8 +381,8 @@ describe('ML - validateJob', () => { fields: { testField: {} }, }; - return validateJob(callWithRequest, payload).then(messages => { - const ids = messages.map(m => m.id); + return validateJob(callWithRequest, payload).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([ 'job_id_valid', 'detectors_function_not_empty', @@ -400,18 +400,18 @@ describe('ML - validateJob', () => { const docsTestPayload = getBasicPayload() as any; docsTestPayload.job.analysis_config.detectors = [{ function: 'count', by_field_name: 'airline' }]; it('creates a docs url pointing to the current docs version', () => { - return validateJob(callWithRequest, docsTestPayload).then(messages => { + return validateJob(callWithRequest, docsTestPayload).then((messages) => { const message = messages[ - messages.findIndex(m => m.id === 'field_not_aggregatable') + messages.findIndex((m) => m.id === 'field_not_aggregatable') ] as JobValidationMessage; expect(message.url!.search('/current/')).not.toBe(-1); }); }); it('creates a docs url pointing to the master docs version', () => { - return validateJob(callWithRequest, docsTestPayload, 'master').then(messages => { + return validateJob(callWithRequest, docsTestPayload, 'master').then((messages) => { const message = messages[ - messages.findIndex(m => m.id === 'field_not_aggregatable') + messages.findIndex((m) => m.id === 'field_not_aggregatable') ] as JobValidationMessage; expect(message.url!.search('/master/')).not.toBe(-1); }); diff --git a/x-pack/plugins/ml/server/models/job_validation/job_validation.ts b/x-pack/plugins/ml/server/models/job_validation/job_validation.ts index f852de785c70a..9d7154bbbb304 100644 --- a/x-pack/plugins/ml/server/models/job_validation/job_validation.ts +++ b/x-pack/plugins/ml/server/models/job_validation/job_validation.ts @@ -58,7 +58,7 @@ export async function validateJob( if (basicValidation.valid === true) { // remove basic success messages from tests // where we run additional extended tests. - const filteredBasicValidationMessages = basicValidation.messages.filter(m => { + const filteredBasicValidationMessages = basicValidation.messages.filter((m) => { return m.id !== 'bucket_span_valid'; }); @@ -83,7 +83,7 @@ export async function validateJob( // so we can decide later whether certain additional tests should be run const cardinalityMessages = await validateCardinality(callWithRequest, job); validationMessages.push(...cardinalityMessages); - const cardinalityError = cardinalityMessages.some(m => { + const cardinalityError = cardinalityMessages.some((m) => { return messages[m.id as MessageId].status === VALIDATION_STATUS.ERROR; }); @@ -111,7 +111,7 @@ export async function validateJob( validationMessages.push({ id: 'skipped_extended_tests' }); } - return uniqWithIsEqual(validationMessages).map(message => { + return uniqWithIsEqual(validationMessages).map((message) => { const messageId = message.id as MessageId; const messageDef = messages[messageId] as JobValidationMessageDef; if (typeof messageDef !== 'undefined') { diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.js b/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.js index 883f1aed1209e..46d05d3cf7637 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.js +++ b/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.js @@ -13,7 +13,7 @@ import { validateJobObject } from './validate_job_object'; const BUCKET_SPAN_HIGH_THRESHOLD = 1; -const wrapQuery = query => ({ +const wrapQuery = (query) => ({ bool: { must: [query], must_not: [], @@ -28,7 +28,7 @@ const wrapQuery = query => ({ // 3 * (30 - 10) + 30 - 30 + 60 - 30 = 90, // 3 * (60 - 10) + 60 - 30 + 60 - 60 = 180] // 70 is the lowest so 10m would be picked -const pickBucketSpan = bucketSpans => { +const pickBucketSpan = (bucketSpans) => { if (bucketSpans.length === 1) { return bucketSpans[0]; } @@ -39,10 +39,10 @@ const pickBucketSpan = bucketSpans => { }, 0); }; - const spansMs = bucketSpans.map(span => span.ms); - const sumDistances = spansMs.map(ms => getSumDistance(spansMs, ms)); + const spansMs = bucketSpans.map((span) => span.ms); + const sumDistances = spansMs.map((ms) => getSumDistance(spansMs, ms)); const minSumDistance = Math.min(...sumDistances); - const i = sumDistances.findIndex(d => d === minSumDistance); + const i = sumDistances.findIndex((d) => d === minSumDistance); return bucketSpans[i]; }; @@ -105,7 +105,7 @@ export async function validateBucketSpan( const estimatorConfigs = []; - job.analysis_config.detectors.forEach(detector => { + job.analysis_config.detectors.forEach((detector) => { const data = getRequestData(); const aggType = mlFunctionToESAggregation(detector.function); const fieldName = typeof detector.field_name === 'undefined' ? null : detector.field_name; @@ -119,8 +119,8 @@ export async function validateBucketSpan( // do the actual bucket span estimation try { - const estimations = estimatorConfigs.map(data => { - return new Promise(resolve => { + const estimations = estimatorConfigs.map((data) => { + return new Promise((resolve) => { estimateBucketSpanFactory( callWithRequest, callAsInternalUser, @@ -131,7 +131,7 @@ export async function validateBucketSpan( // but isn't able to come up with a bucket span estimation. // this doesn't trigger a HTTP error but an object with an error message. // triggering a HTTP error would be too severe for this case. - .catch(resp => { + .catch((resp) => { resolve({ error: true, message: resp, @@ -142,7 +142,7 @@ export async function validateBucketSpan( // run the estimations, filter valid results, then pick a bucket span. const results = await Promise.all(estimations); - const bucketSpans = results.filter(result => result.name && result.ms); + const bucketSpans = results.filter((result) => result.name && result.ms); if (bucketSpans.length > 0) { const bucketSpan = pickBucketSpan(bucketSpans); diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.test.ts b/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.test.ts index 84f865879d67f..8d77fd5a1fd0e 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.test.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_bucket_span.test.ts @@ -23,28 +23,28 @@ import mockItSearchResponse from './__mocks__/mock_it_search_response.json'; // mock callWithRequestFactory const callWithRequestFactory = (mockSearchResponse: any) => { return () => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve(mockSearchResponse); }); }; }; describe('ML - validateBucketSpan', () => { - it('called without arguments', done => { + it('called without arguments', (done) => { validateBucketSpan(callWithRequestFactory(mockFareQuoteSearchResponse)).then( () => done(new Error('Promise should not resolve for this test without job argument.')), () => done() ); }); - it('called with non-valid job argument #1, missing datafeed_config', done => { + it('called with non-valid job argument #1, missing datafeed_config', (done) => { validateBucketSpan(callWithRequestFactory(mockFareQuoteSearchResponse), {}).then( () => done(new Error('Promise should not resolve for this test without valid job argument.')), () => done() ); }); - it('called with non-valid job argument #2, missing datafeed_config.indices', done => { + it('called with non-valid job argument #2, missing datafeed_config.indices', (done) => { validateBucketSpan(callWithRequestFactory(mockFareQuoteSearchResponse), { datafeed_config: {}, }).then( @@ -53,7 +53,7 @@ describe('ML - validateBucketSpan', () => { ); }); - it('called with non-valid job argument #3, missing data_description', done => { + it('called with non-valid job argument #3, missing data_description', (done) => { const job = { datafeed_config: { indices: [] } }; validateBucketSpan(callWithRequestFactory(mockFareQuoteSearchResponse), job).then( () => done(new Error('Promise should not resolve for this test without valid job argument.')), @@ -61,7 +61,7 @@ describe('ML - validateBucketSpan', () => { ); }); - it('called with non-valid job argument #4, missing data_description.time_field', done => { + it('called with non-valid job argument #4, missing data_description.time_field', (done) => { const job = { datafeed_config: { indices: [] }, data_description: {} }; validateBucketSpan(callWithRequestFactory(mockFareQuoteSearchResponse), job).then( () => done(new Error('Promise should not resolve for this test without valid job argument.')), @@ -69,7 +69,7 @@ describe('ML - validateBucketSpan', () => { ); }); - it('called with non-valid job argument #5, missing analysis_config.influencers', done => { + it('called with non-valid job argument #5, missing analysis_config.influencers', (done) => { const job = { datafeed_config: { indices: [] }, data_description: { time_field: '@timestamp' }, @@ -89,7 +89,7 @@ describe('ML - validateBucketSpan', () => { return validateBucketSpan(callWithRequestFactory(mockFareQuoteSearchResponse), job).then( (messages: JobValidationMessage[]) => { - const ids = messages.map(m => m.id); + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([]); } ); @@ -114,7 +114,7 @@ describe('ML - validateBucketSpan', () => { job, duration ).then((messages: JobValidationMessage[]) => { - const ids = messages.map(m => m.id); + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['success_bucket_span']); }); }); @@ -128,7 +128,7 @@ describe('ML - validateBucketSpan', () => { job, duration ).then((messages: JobValidationMessage[]) => { - const ids = messages.map(m => m.id); + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['bucket_span_high']); }); }); @@ -149,20 +149,20 @@ describe('ML - validateBucketSpan', () => { return validateBucketSpan(callWithRequestFactory(mockSearchResponse), job, {}).then( (messages: JobValidationMessage[]) => { - const ids = messages.map(m => m.id); + const ids = messages.map((m) => m.id); test(ids); } ); }; it('farequote count detector, bucket span estimation matches 15m', () => { - return testBucketSpan('15m', mockFareQuoteSearchResponse, ids => { + return testBucketSpan('15m', mockFareQuoteSearchResponse, (ids) => { expect(ids).toStrictEqual(['success_bucket_span']); }); }); it('farequote count detector, bucket span estimation does not match 1m', () => { - return testBucketSpan('1m', mockFareQuoteSearchResponse, ids => { + return testBucketSpan('1m', mockFareQuoteSearchResponse, (ids) => { expect(ids).toStrictEqual(['bucket_span_estimation_mismatch']); }); }); @@ -172,7 +172,7 @@ describe('ML - validateBucketSpan', () => { // not many non-empty buckets. future work on bucket estimation and sparsity validation // should result in a lower bucket span estimation. it('it_ops_app_logs count detector, bucket span estimation matches 6h', () => { - return testBucketSpan('6h', mockItSearchResponse, ids => { + return testBucketSpan('6h', mockItSearchResponse, (ids) => { expect(ids).toStrictEqual(['success_bucket_span']); }); }); diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.test.ts b/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.test.ts index e5111629f1182..13e5495aac4c4 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.test.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.test.ts @@ -35,21 +35,21 @@ const callWithRequestFactory = (responses: Record, fail = false): A }; describe('ML - validateCardinality', () => { - it('called without arguments', done => { + it('called without arguments', (done) => { validateCardinality(callWithRequestFactory(mockResponses)).then( () => done(new Error('Promise should not resolve for this test without job argument.')), () => done() ); }); - it('called with non-valid job argument #1, missing analysis_config', done => { + it('called with non-valid job argument #1, missing analysis_config', (done) => { validateCardinality(callWithRequestFactory(mockResponses), {} as CombinedJob).then( () => done(new Error('Promise should not resolve for this test without valid job argument.')), () => done() ); }); - it('called with non-valid job argument #2, missing datafeed_config', done => { + it('called with non-valid job argument #2, missing datafeed_config', (done) => { validateCardinality(callWithRequestFactory(mockResponses), { analysis_config: {}, } as CombinedJob).then( @@ -58,7 +58,7 @@ describe('ML - validateCardinality', () => { ); }); - it('called with non-valid job argument #3, missing datafeed_config.indices', done => { + it('called with non-valid job argument #3, missing datafeed_config.indices', (done) => { const job = { analysis_config: {}, datafeed_config: {} } as CombinedJob; validateCardinality(callWithRequestFactory(mockResponses), job).then( () => done(new Error('Promise should not resolve for this test without valid job argument.')), @@ -66,7 +66,7 @@ describe('ML - validateCardinality', () => { ); }); - it('called with non-valid job argument #4, missing data_description', done => { + it('called with non-valid job argument #4, missing data_description', (done) => { const job = ({ analysis_config: {}, datafeed_config: { indices: [] }, @@ -77,7 +77,7 @@ describe('ML - validateCardinality', () => { ); }); - it('called with non-valid job argument #5, missing data_description.time_field', done => { + it('called with non-valid job argument #5, missing data_description.time_field', (done) => { const job = ({ analysis_config: {}, data_description: {}, @@ -89,7 +89,7 @@ describe('ML - validateCardinality', () => { ); }); - it('called with non-valid job argument #6, missing analysis_config.influencers', done => { + it('called with non-valid job argument #6, missing analysis_config.influencers', (done) => { const job = ({ analysis_config: {}, datafeed_config: { indices: [] }, @@ -110,8 +110,8 @@ describe('ML - validateCardinality', () => { }, } as unknown) as CombinedJob; - return validateCardinality(callWithRequestFactory(mockResponses), job).then(messages => { - const ids = messages.map(m => m.id); + return validateCardinality(callWithRequestFactory(mockResponses), job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([]); }); }); @@ -143,8 +143,8 @@ describe('ML - validateCardinality', () => { return validateCardinality( callWithRequestFactory(mockCardinality), (job as unknown) as CombinedJob - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); test(ids); }); }; @@ -155,8 +155,8 @@ describe('ML - validateCardinality', () => { return validateCardinality( callWithRequestFactory(mockResponses), (job as unknown) as CombinedJob - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['field_not_aggregatable']); }); }); @@ -166,8 +166,8 @@ describe('ML - validateCardinality', () => { return validateCardinality( callWithRequestFactory(mockResponses), (job as unknown) as CombinedJob - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['success_cardinality']); }); }); @@ -175,8 +175,8 @@ describe('ML - validateCardinality', () => { it('field not aggregatable', () => { const job = getJobConfig('partition_field_name'); return validateCardinality(callWithRequestFactory({}), (job as unknown) as CombinedJob).then( - messages => { - const ids = messages.map(m => m.id); + (messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['field_not_aggregatable']); } ); @@ -191,50 +191,50 @@ describe('ML - validateCardinality', () => { return validateCardinality( callWithRequestFactory({}, true), (job as unknown) as CombinedJob - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['fields_not_aggregatable']); }); }); it('valid partition field cardinality', () => { - return testCardinality('partition_field_name', 50, ids => { + return testCardinality('partition_field_name', 50, (ids) => { expect(ids).toStrictEqual(['success_cardinality']); }); }); it('too high partition field cardinality', () => { - return testCardinality('partition_field_name', 1001, ids => { + return testCardinality('partition_field_name', 1001, (ids) => { expect(ids).toStrictEqual(['cardinality_partition_field']); }); }); it('valid by field cardinality', () => { - return testCardinality('by_field_name', 50, ids => { + return testCardinality('by_field_name', 50, (ids) => { expect(ids).toStrictEqual(['success_cardinality']); }); }); it('too high by field cardinality', () => { - return testCardinality('by_field_name', 1001, ids => { + return testCardinality('by_field_name', 1001, (ids) => { expect(ids).toStrictEqual(['cardinality_by_field']); }); }); it('valid over field cardinality', () => { - return testCardinality('over_field_name', 50, ids => { + return testCardinality('over_field_name', 50, (ids) => { expect(ids).toStrictEqual(['success_cardinality']); }); }); it('too low over field cardinality', () => { - return testCardinality('over_field_name', 9, ids => { + return testCardinality('over_field_name', 9, (ids) => { expect(ids).toStrictEqual(['cardinality_over_field_low']); }); }); it('too high over field cardinality', () => { - return testCardinality('over_field_name', 1000001, ids => { + return testCardinality('over_field_name', 1000001, (ids) => { expect(ids).toStrictEqual(['cardinality_over_field_high']); }); }); @@ -245,8 +245,8 @@ describe('ML - validateCardinality', () => { job.model_plot_config = { enabled: false }; const mockCardinality = _.cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; - return validateCardinality(callWithRequestFactory(mockCardinality), job).then(messages => { - const ids = messages.map(m => m.id); + return validateCardinality(callWithRequestFactory(mockCardinality), job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['success_cardinality']); }); }); @@ -256,8 +256,8 @@ describe('ML - validateCardinality', () => { job.model_plot_config = { enabled: true }; const mockCardinality = _.cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; - return validateCardinality(callWithRequestFactory(mockCardinality), job).then(messages => { - const ids = messages.map(m => m.id); + return validateCardinality(callWithRequestFactory(mockCardinality), job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['cardinality_model_plot_high']); }); }); @@ -267,8 +267,8 @@ describe('ML - validateCardinality', () => { job.model_plot_config = { enabled: false }; const mockCardinality = _.cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; - return validateCardinality(callWithRequestFactory(mockCardinality), job).then(messages => { - const ids = messages.map(m => m.id); + return validateCardinality(callWithRequestFactory(mockCardinality), job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['cardinality_by_field']); }); }); @@ -278,8 +278,8 @@ describe('ML - validateCardinality', () => { job.model_plot_config = { enabled: true }; const mockCardinality = _.cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; - return validateCardinality(callWithRequestFactory(mockCardinality), job).then(messages => { - const ids = messages.map(m => m.id); + return validateCardinality(callWithRequestFactory(mockCardinality), job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['cardinality_model_plot_high', 'cardinality_by_field']); }); }); @@ -289,8 +289,8 @@ describe('ML - validateCardinality', () => { job.model_plot_config = { enabled: true, terms: 'AAL,AAB' }; const mockCardinality = _.cloneDeep(mockResponses); mockCardinality.search.aggregations.airline_cardinality.value = cardinality; - return validateCardinality(callWithRequestFactory(mockCardinality), job).then(messages => { - const ids = messages.map(m => m.id); + return validateCardinality(callWithRequestFactory(mockCardinality), job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['cardinality_by_field']); }); }); diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.ts b/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.ts index 2ad483fb07ca7..62f272f26bb3f 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_cardinality.ts @@ -62,13 +62,15 @@ const validateFactory = (callWithRequest: APICaller, job: CombinedJob): Validato >; const detectors = job.analysis_config.detectors; - const relevantDetectors = detectors.filter(detector => { + const relevantDetectors = detectors.filter((detector) => { return typeof detector[fieldName] !== 'undefined'; }); if (relevantDetectors.length > 0) { try { - const uniqueFieldNames = [...new Set(relevantDetectors.map(f => f[fieldName]))] as string[]; + const uniqueFieldNames = [ + ...new Set(relevantDetectors.map((f) => f[fieldName])), + ] as string[]; // use fieldCaps endpoint to get data about whether fields are aggregatable const fieldCaps = await callWithRequest('fieldCaps', { @@ -79,7 +81,7 @@ const validateFactory = (callWithRequest: APICaller, job: CombinedJob): Validato let aggregatableFieldNames: string[] = []; // parse fieldCaps to return an array of just the fields which are aggregatable if (typeof fieldCaps === 'object' && typeof fieldCaps.fields === 'object') { - aggregatableFieldNames = uniqueFieldNames.filter(field => { + aggregatableFieldNames = uniqueFieldNames.filter((field) => { if (typeof fieldCaps.fields[field] !== 'undefined') { const fieldType = Object.keys(fieldCaps.fields[field])[0]; return fieldCaps.fields[field][fieldType].aggregatable; @@ -96,9 +98,9 @@ const validateFactory = (callWithRequest: APICaller, job: CombinedJob): Validato job.data_description.time_field ); - uniqueFieldNames.forEach(uniqueFieldName => { + uniqueFieldNames.forEach((uniqueFieldName) => { const field = stats.aggregatableExistsFields.find( - fieldData => fieldData.fieldName === uniqueFieldName + (fieldData) => fieldData.fieldName === uniqueFieldName ); if (field !== undefined && typeof field === 'object' && field.stats) { modelPlotCardinality += @@ -160,7 +162,7 @@ export async function validateCardinality( // find out if there are any relevant detector field names // where cardinality checks could be run against. - const numDetectorsWithFieldNames = job.analysis_config.detectors.filter(d => { + const numDetectorsWithFieldNames = job.analysis_config.detectors.filter((d) => { return d.by_field_name || d.over_field_name || d.partition_field_name; }); if (numDetectorsWithFieldNames.length === 0) { @@ -175,23 +177,23 @@ export async function validateCardinality( // check over fields (population analysis) const validateOverFieldsLow = validate({ type: 'over', - isInvalid: cardinality => cardinality < OVER_FIELD_CARDINALITY_THRESHOLD_LOW, + isInvalid: (cardinality) => cardinality < OVER_FIELD_CARDINALITY_THRESHOLD_LOW, messageId: 'cardinality_over_field_low', }); const validateOverFieldsHigh = validate({ type: 'over', - isInvalid: cardinality => cardinality > OVER_FIELD_CARDINALITY_THRESHOLD_HIGH, + isInvalid: (cardinality) => cardinality > OVER_FIELD_CARDINALITY_THRESHOLD_HIGH, messageId: 'cardinality_over_field_high', }); // check partition/by fields (multi-metric analysis) const validatePartitionFields = validate({ type: 'partition', - isInvalid: cardinality => cardinality > PARTITION_FIELD_CARDINALITY_THRESHOLD, + isInvalid: (cardinality) => cardinality > PARTITION_FIELD_CARDINALITY_THRESHOLD, }); const validateByFields = validate({ type: 'by', - isInvalid: cardinality => cardinality > BY_FIELD_CARDINALITY_THRESHOLD, + isInvalid: (cardinality) => cardinality > BY_FIELD_CARDINALITY_THRESHOLD, }); // we already called the validation functions above, @@ -217,7 +219,7 @@ export async function validateCardinality( } // add all messages returned from the individual cardinality checks - validations.forEach(v => messages.push(...v.messages)); + validations.forEach((v) => messages.push(...v.messages)); if (messages.length === 0) { messages.push({ id: 'success_cardinality' }); diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_influencers.test.ts b/x-pack/plugins/ml/server/models/job_validation/validate_influencers.test.ts index df3310ad9f5e8..89c265d0b6f60 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_influencers.test.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_influencers.test.ts @@ -11,7 +11,7 @@ import { CombinedJob } from '../../../common/types/anomaly_detection_jobs'; import { validateInfluencers } from './validate_influencers'; describe('ML - validateInfluencers', () => { - it('called without arguments throws an error', done => { + it('called without arguments throws an error', (done) => { validateInfluencers( (undefined as unknown) as APICaller, (undefined as unknown) as CombinedJob @@ -21,14 +21,14 @@ describe('ML - validateInfluencers', () => { ); }); - it('called with non-valid job argument #1, missing analysis_config', done => { + it('called with non-valid job argument #1, missing analysis_config', (done) => { validateInfluencers((undefined as unknown) as APICaller, ({} as unknown) as CombinedJob).then( () => done(new Error('Promise should not resolve for this test without valid job argument.')), () => done() ); }); - it('called with non-valid job argument #2, missing analysis_config.influencers', done => { + it('called with non-valid job argument #2, missing analysis_config.influencers', (done) => { const job = { analysis_config: {}, datafeed_config: { indices: [] }, @@ -40,7 +40,7 @@ describe('ML - validateInfluencers', () => { ); }); - it('called with non-valid job argument #3, missing analysis_config.detectors', done => { + it('called with non-valid job argument #3, missing analysis_config.detectors', (done) => { const job = { analysis_config: { influencers: [] }, datafeed_config: { indices: [] }, @@ -66,8 +66,8 @@ describe('ML - validateInfluencers', () => { it('success_influencer', () => { const job = getJobConfig(['airline']); - return validateInfluencers((undefined as unknown) as APICaller, job).then(messages => { - const ids = messages.map(m => m.id); + return validateInfluencers((undefined as unknown) as APICaller, job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['success_influencers']); }); }); @@ -84,24 +84,24 @@ describe('ML - validateInfluencers', () => { ] ); - return validateInfluencers((undefined as unknown) as APICaller, job).then(messages => { - const ids = messages.map(m => m.id); + return validateInfluencers((undefined as unknown) as APICaller, job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual([]); }); }); it('influencer_low', () => { const job = getJobConfig(); - return validateInfluencers((undefined as unknown) as APICaller, job).then(messages => { - const ids = messages.map(m => m.id); + return validateInfluencers((undefined as unknown) as APICaller, job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['influencer_low']); }); }); it('influencer_high', () => { const job = getJobConfig(['i1', 'i2', 'i3', 'i4']); - return validateInfluencers((undefined as unknown) as APICaller, job).then(messages => { - const ids = messages.map(m => m.id); + return validateInfluencers((undefined as unknown) as APICaller, job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['influencer_high']); }); }); @@ -118,8 +118,8 @@ describe('ML - validateInfluencers', () => { }, ] ); - return validateInfluencers((undefined as unknown) as APICaller, job).then(messages => { - const ids = messages.map(m => m.id); + return validateInfluencers((undefined as unknown) as APICaller, job).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['influencer_low_suggestion']); }); }); @@ -148,7 +148,7 @@ describe('ML - validateInfluencers', () => { }, ] ); - return validateInfluencers((undefined as unknown) as APICaller, job).then(messages => { + return validateInfluencers((undefined as unknown) as APICaller, job).then((messages) => { expect(messages).toStrictEqual([ { id: 'influencer_low_suggestions', diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_influencers.ts b/x-pack/plugins/ml/server/models/job_validation/validate_influencers.ts index e54ffc4586a8e..531d4dfdba0c5 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_influencers.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_influencers.ts @@ -21,7 +21,7 @@ export async function validateInfluencers(callWithRequest: APICaller, job: Combi const influencers = job.analysis_config.influencers; const detectorFieldNames: string[] = []; - job.analysis_config.detectors.forEach(d => { + job.analysis_config.detectors.forEach((d) => { if (d.by_field_name) { detectorFieldNames.push(d.by_field_name); } @@ -56,7 +56,7 @@ export async function validateInfluencers(callWithRequest: APICaller, job: Combi if (detectorFieldNames.length > 1) { id = 'influencer_low_suggestions'; const uniqueInfluencers = [...new Set(detectorFieldNames)]; - influencerSuggestion = `[${uniqueInfluencers.map(i => `"${i}"`).join(',')}]`; + influencerSuggestion = `[${uniqueInfluencers.map((i) => `"${i}"`).join(',')}]`; } messages.push({ id, influencerSuggestion }); diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_model_memory_limit.test.ts b/x-pack/plugins/ml/server/models/job_validation/validate_model_memory_limit.test.ts index bf88716181bb3..581153036fed7 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_model_memory_limit.test.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_model_memory_limit.test.ts @@ -129,8 +129,8 @@ describe('ML - validateModelMemoryLimit', () => { const job = getJobConfig(); const duration = undefined; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual([]); }); }); @@ -141,8 +141,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '31mb'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_greater_than_max_mml']); }); }); @@ -158,8 +158,8 @@ describe('ML - validateModelMemoryLimit', () => { getMockCallWithRequest({ 'ml.estimateModelMemory': { model_memory_estimate: '66mb' } }), job, duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['estimated_mml_greater_than_max_mml']); }); }); @@ -175,8 +175,8 @@ describe('ML - validateModelMemoryLimit', () => { getMockCallWithRequest({ 'ml.estimateModelMemory': { model_memory_estimate: '24mb' } }), job, duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['success_mml']); }); }); @@ -192,8 +192,8 @@ describe('ML - validateModelMemoryLimit', () => { getMockCallWithRequest({ 'ml.estimateModelMemory': { model_memory_estimate: '22mb' } }), job, duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['half_estimated_mml_greater_than_mml']); }); }); @@ -206,8 +206,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '10mb'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['half_estimated_mml_greater_than_mml']); }); }); @@ -218,8 +218,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '31mb'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual([]); }); }); @@ -230,8 +230,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '41mb'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_greater_than_effective_max_mml']); }); }); @@ -247,8 +247,8 @@ describe('ML - validateModelMemoryLimit', () => { getMockCallWithRequest({ 'ml.estimateModelMemory': { model_memory_estimate: '19mb' } }), job, duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['success_mml']); }); }); @@ -260,8 +260,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '0mb'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_value_invalid']); }); }); @@ -273,8 +273,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '10mbananas'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_value_invalid']); }); }); @@ -286,8 +286,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '10'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_value_invalid']); }); }); @@ -299,8 +299,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = 'mb'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_value_invalid']); }); }); @@ -312,8 +312,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = 'asdf'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_value_invalid']); }); }); @@ -325,8 +325,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '1023KB'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['mml_value_invalid']); }); }); @@ -338,8 +338,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '1024KB'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['half_estimated_mml_greater_than_mml']); }); }); @@ -351,8 +351,8 @@ describe('ML - validateModelMemoryLimit', () => { // @ts-ignore job.analysis_limits.model_memory_limit = '6MB'; - return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then(messages => { - const ids = messages.map(m => m.id); + return validateModelMemoryLimit(getMockCallWithRequest(), job, duration).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['half_estimated_mml_greater_than_mml']); }); }); @@ -368,8 +368,8 @@ describe('ML - validateModelMemoryLimit', () => { getMockCallWithRequest({ 'ml.estimateModelMemory': { model_memory_estimate: '20mb' } }), job, duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toEqual(['success_mml']); }); }); diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_time_range.test.ts b/x-pack/plugins/ml/server/models/job_validation/validate_time_range.test.ts index 2c3b2dd4dc6ae..3ba8701b4bbd2 100644 --- a/x-pack/plugins/ml/server/models/job_validation/validate_time_range.test.ts +++ b/x-pack/plugins/ml/server/models/job_validation/validate_time_range.test.ts @@ -23,7 +23,7 @@ const mockSearchResponse = { const callWithRequestFactory = (resp: any): APICaller => { return (path: string) => { - return new Promise(resolve => { + return new Promise((resolve) => { resolve(resp[path]); }) as Promise; }; @@ -44,7 +44,7 @@ function getMinimalValidJob() { } describe('ML - isValidTimeField', () => { - it('called without job config argument triggers Promise rejection', done => { + it('called without job config argument triggers Promise rejection', (done) => { isValidTimeField( callWithRequestFactory(mockSearchResponse), (undefined as unknown) as CombinedJob @@ -54,9 +54,9 @@ describe('ML - isValidTimeField', () => { ); }); - it('time_field `@timestamp`', done => { + it('time_field `@timestamp`', (done) => { isValidTimeField(callWithRequestFactory(mockSearchResponse), getMinimalValidJob()).then( - valid => { + (valid) => { expect(valid).toBe(true); done(); }, @@ -64,7 +64,7 @@ describe('ML - isValidTimeField', () => { ); }); - it('time_field `metadata.timestamp`', done => { + it('time_field `metadata.timestamp`', (done) => { const mockJobConfigNestedDate = getMinimalValidJob(); mockJobConfigNestedDate.data_description.time_field = 'metadata.timestamp'; @@ -77,7 +77,7 @@ describe('ML - isValidTimeField', () => { callWithRequestFactory(mockSearchResponseNestedDate), mockJobConfigNestedDate ).then( - valid => { + (valid) => { expect(valid).toBe(true); done(); }, @@ -87,7 +87,7 @@ describe('ML - isValidTimeField', () => { }); describe('ML - validateTimeRange', () => { - it('called without arguments', done => { + it('called without arguments', (done) => { validateTimeRange( callWithRequestFactory(mockSearchResponse), (undefined as unknown) as CombinedJob @@ -97,7 +97,7 @@ describe('ML - validateTimeRange', () => { ); }); - it('called with non-valid job argument #2, missing datafeed_config', done => { + it('called with non-valid job argument #2, missing datafeed_config', (done) => { validateTimeRange(callWithRequestFactory(mockSearchResponse), ({ analysis_config: {}, } as unknown) as CombinedJob).then( @@ -106,7 +106,7 @@ describe('ML - validateTimeRange', () => { ); }); - it('called with non-valid job argument #3, missing datafeed_config.indices', done => { + it('called with non-valid job argument #3, missing datafeed_config.indices', (done) => { const job = { analysis_config: {}, datafeed_config: {} }; validateTimeRange( callWithRequestFactory(mockSearchResponse), @@ -117,7 +117,7 @@ describe('ML - validateTimeRange', () => { ); }); - it('called with non-valid job argument #4, missing data_description', done => { + it('called with non-valid job argument #4, missing data_description', (done) => { const job = { analysis_config: {}, datafeed_config: { indices: [] } }; validateTimeRange( callWithRequestFactory(mockSearchResponse), @@ -128,7 +128,7 @@ describe('ML - validateTimeRange', () => { ); }); - it('called with non-valid job argument #5, missing data_description.time_field', done => { + it('called with non-valid job argument #5, missing data_description.time_field', (done) => { const job = { analysis_config: {}, data_description: {}, datafeed_config: { indices: [] } }; validateTimeRange( callWithRequestFactory(mockSearchResponse), @@ -147,8 +147,8 @@ describe('ML - validateTimeRange', () => { callWithRequestFactory(mockSearchResponseInvalid), getMinimalValidJob(), duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['time_field_invalid']); }); }); @@ -161,8 +161,8 @@ describe('ML - validateTimeRange', () => { callWithRequestFactory(mockSearchResponse), jobShortTimeRange, duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['time_range_short']); }); }); @@ -173,8 +173,8 @@ describe('ML - validateTimeRange', () => { callWithRequestFactory(mockSearchResponse), getMinimalValidJob(), duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['time_range_short']); }); }); @@ -185,8 +185,8 @@ describe('ML - validateTimeRange', () => { callWithRequestFactory(mockSearchResponse), getMinimalValidJob(), duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['time_range_short']); }); }); @@ -197,8 +197,8 @@ describe('ML - validateTimeRange', () => { callWithRequestFactory(mockSearchResponse), getMinimalValidJob(), duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['success_time_range']); }); }); @@ -209,8 +209,8 @@ describe('ML - validateTimeRange', () => { callWithRequestFactory(mockSearchResponse), getMinimalValidJob(), duration - ).then(messages => { - const ids = messages.map(m => m.id); + ).then((messages) => { + const ids = messages.map((m) => m.id); expect(ids).toStrictEqual(['time_range_before_epoch']); }); }); diff --git a/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.js b/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.js index 4934a0ba07081..e664a1403d7d6 100644 --- a/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.js +++ b/x-pack/plugins/ml/server/models/results_service/build_anomaly_table_items.js @@ -25,7 +25,7 @@ export function buildAnomalyTableItems(anomalyRecords, aggregationInterval, date displayRecords = aggregateAnomalies(anomalyRecords, aggregationInterval, dateFormatTz); } else { // Show all anomaly records. - displayRecords = anomalyRecords.map(record => { + displayRecords = anomalyRecords.map((record) => { return { time: record.timestamp, source: record, @@ -56,9 +56,9 @@ export function buildAnomalyTableItems(anomalyRecords, aggregationInterval, date if (source.influencers !== undefined) { const influencers = []; const sourceInfluencers = _.sortBy(source.influencers, 'influencer_field_name'); - sourceInfluencers.forEach(influencer => { + sourceInfluencers.forEach((influencer) => { const influencerFieldName = influencer.influencer_field_name; - influencer.influencer_field_values.forEach(influencerFieldValue => { + influencer.influencer_field_values.forEach((influencerFieldValue) => { influencers.push({ [influencerFieldName]: influencerFieldValue, }); @@ -125,17 +125,12 @@ function aggregateAnomalies(anomalyRecords, interval, dateFormatTz) { } const aggregatedData = {}; - anomalyRecords.forEach(record => { + anomalyRecords.forEach((record) => { // Use moment.js to get start of interval. const roundedTime = dateFormatTz !== undefined - ? moment(record.timestamp) - .tz(dateFormatTz) - .startOf(interval) - .valueOf() - : moment(record.timestamp) - .startOf(interval) - .valueOf(); + ? moment(record.timestamp).tz(dateFormatTz).startOf(interval).valueOf() + : moment(record.timestamp).startOf(interval).valueOf(); if (aggregatedData[roundedTime] === undefined) { aggregatedData[roundedTime] = {}; } @@ -178,9 +173,9 @@ function aggregateAnomalies(anomalyRecords, interval, dateFormatTz) { // the highest score per bucketed time / jobId / detectorIndex. const summaryRecords = []; _.each(aggregatedData, (times, roundedTime) => { - _.each(times, jobIds => { - _.each(jobIds, entityDetectors => { - _.each(entityDetectors, record => { + _.each(times, (jobIds) => { + _.each(jobIds, (entityDetectors) => { + _.each(entityDetectors, (record) => { summaryRecords.push({ time: +roundedTime, source: record, diff --git a/x-pack/plugins/ml/server/models/results_service/results_service.ts b/x-pack/plugins/ml/server/models/results_service/results_service.ts index 1df53d9cee79c..a985ef7b8f3f5 100644 --- a/x-pack/plugins/ml/server/models/results_service/results_service.ts +++ b/x-pack/plugins/ml/server/models/results_service/results_service.ts @@ -89,7 +89,7 @@ export function resultsServiceProvider(callAsCurrentUser: APICaller) { } // Add in term queries for each of the specified criteria. - criteriaFields.forEach(criteria => { + criteriaFields.forEach((criteria) => { boolCriteria.push({ term: { [criteria.fieldName]: criteria.fieldValue, @@ -105,7 +105,7 @@ export function resultsServiceProvider(callAsCurrentUser: APICaller) { if (influencers.length > 0) { boolCriteria.push({ bool: { - should: influencers.map(influencer => { + should: influencers.map((influencer) => { return { nested: { path: 'influencers', @@ -169,7 +169,7 @@ export function resultsServiceProvider(callAsCurrentUser: APICaller) { }; if (resp.hits.total !== 0) { let records: AnomalyRecordDoc[] = []; - resp.hits.hits.forEach(hit => { + resp.hits.hits.forEach((hit) => { records.push(hit._source); }); @@ -195,7 +195,7 @@ export function resultsServiceProvider(callAsCurrentUser: APICaller) { tableData.examplesByJobId = {}; const categoryIdsByJobId: { [key: string]: any } = {}; - categoryAnomalies.forEach(anomaly => { + categoryAnomalies.forEach((anomaly) => { if (!_.has(categoryIdsByJobId, anomaly.jobId)) { categoryIdsByJobId[anomaly.jobId] = []; } @@ -206,7 +206,7 @@ export function resultsServiceProvider(callAsCurrentUser: APICaller) { const categoryJobIds = Object.keys(categoryIdsByJobId); await Promise.all( - categoryJobIds.map(async jobId => { + categoryJobIds.map(async (jobId) => { const examplesByCategoryId = await getCategoryExamples( jobId, categoryIdsByJobId[jobId], @@ -358,7 +358,7 @@ export function resultsServiceProvider(callAsCurrentUser: APICaller) { [] ); const timestampByJobId: { [key: string]: number | undefined } = {}; - bucketsByJobId.forEach(bucket => { + bucketsByJobId.forEach((bucket) => { timestampByJobId[bucket.key] = bucket.maxTimestamp.value; }); diff --git a/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_extractor.ts b/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_extractor.ts index 01adcb462689e..7116d1c23b515 100644 --- a/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_extractor.ts +++ b/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_extractor.ts @@ -67,7 +67,7 @@ export function extractDocumentation( return collection; } - members.forEach(member => { + members.forEach((member) => { collection.push(serializeProperty(member)); }); @@ -138,7 +138,7 @@ export function extractDocumentation( ? `${symbol.getName()}[]` : symbol.getName(); - members.forEach(member => { + members.forEach((member) => { nestedEntries.push(serializeProperty(member)); }); } diff --git a/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_worker.ts b/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_worker.ts index 0eaf3143eaac0..8b9b35f7a0d3c 100644 --- a/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_worker.ts +++ b/x-pack/plugins/ml/server/routes/apidoc_scripts/schema_worker.ts @@ -13,11 +13,11 @@ export function postProcess(parsedFiles: any[]): void { const schemasDirPath = `${__dirname}${path.sep}..${path.sep}..${path.sep}schemas${path.sep}`; const schemaFiles = fs .readdirSync(schemasDirPath) - .map(filename => path.resolve(schemasDirPath + filename)); + .map((filename) => path.resolve(schemasDirPath + filename)); const schemaDocs = extractDocumentation(schemaFiles); - parsedFiles.forEach(parsedFile => { + parsedFiles.forEach((parsedFile) => { parsedFile.forEach((block: Block) => { const { local: { schemas }, diff --git a/x-pack/plugins/ml/server/routes/apidoc_scripts/version_filter.ts b/x-pack/plugins/ml/server/routes/apidoc_scripts/version_filter.ts index 8cbe38d667b2c..754368e318f38 100644 --- a/x-pack/plugins/ml/server/routes/apidoc_scripts/version_filter.ts +++ b/x-pack/plugins/ml/server/routes/apidoc_scripts/version_filter.ts @@ -13,7 +13,7 @@ const API_VERSION = '7.8.0'; * Updates api version of the endpoints. */ export function postFilter(parsedFiles: any[]) { - parsedFiles.forEach(parsedFile => { + parsedFiles.forEach((parsedFile) => { parsedFile.forEach((block: Block) => { block.local.version = API_VERSION; }); diff --git a/x-pack/plugins/ml/server/routes/system.ts b/x-pack/plugins/ml/server/routes/system.ts index 7ae7dd8eef065..99c7805a62e76 100644 --- a/x-pack/plugins/ml/server/routes/system.ts +++ b/x-pack/plugins/ml/server/routes/system.ts @@ -29,7 +29,7 @@ export function systemRoutes( let count = 0; if (typeof resp.nodes === 'object') { - Object.keys(resp.nodes).forEach(k => { + Object.keys(resp.nodes).forEach((k) => { if (resp.nodes[k].attributes !== undefined) { const maxOpenJobs = resp.nodes[k].attributes['ml.max_open_jobs']; if (maxOpenJobs !== null && maxOpenJobs > 0) { diff --git a/x-pack/plugins/monitoring/common/__tests__/format_timestamp_to_duration.js b/x-pack/plugins/monitoring/common/__tests__/format_timestamp_to_duration.js index 470d596bd2bdc..aec30f0628f31 100644 --- a/x-pack/plugins/monitoring/common/__tests__/format_timestamp_to_duration.js +++ b/x-pack/plugins/monitoring/common/__tests__/format_timestamp_to_duration.js @@ -24,16 +24,12 @@ describe('formatTimestampToDuration', () => { formatTimestampToDuration(fiftyNineSeconds, CALCULATE_DURATION_SINCE, getTestTime()) ).to.be('59 seconds'); - const fiveMins = getTestTime() - .subtract(5, 'minutes') - .subtract(30, 'seconds'); + const fiveMins = getTestTime().subtract(5, 'minutes').subtract(30, 'seconds'); expect(formatTimestampToDuration(fiveMins, CALCULATE_DURATION_SINCE, getTestTime())).to.be( '6 mins' ); - const sixHours = getTestTime() - .subtract(6, 'hours') - .subtract(30, 'minutes'); + const sixHours = getTestTime().subtract(6, 'hours').subtract(30, 'minutes'); expect(formatTimestampToDuration(sixHours, CALCULATE_DURATION_SINCE, getTestTime())).to.be( '6 hrs 30 mins' ); @@ -85,17 +81,12 @@ describe('formatTimestampToDuration', () => { '10 mins' ); - const sixHours = getTestTime() - .add(6, 'hours') - .add(30, 'minutes'); + const sixHours = getTestTime().add(6, 'hours').add(30, 'minutes'); expect(formatTimestampToDuration(sixHours, CALCULATE_DURATION_UNTIL, getTestTime())).to.be( '6 hrs 30 mins' ); - const sevenDays = getTestTime() - .add(7, 'days') - .add(6, 'hours') - .add(18, 'minutes'); + const sevenDays = getTestTime().add(7, 'days').add(6, 'hours').add(18, 'minutes'); expect(formatTimestampToDuration(sevenDays, CALCULATE_DURATION_UNTIL, getTestTime())).to.be( '7 days 6 hrs 18 mins' ); diff --git a/x-pack/plugins/monitoring/common/cancel_promise.ts b/x-pack/plugins/monitoring/common/cancel_promise.ts index f100edda50796..e8d9282945947 100644 --- a/x-pack/plugins/monitoring/common/cancel_promise.ts +++ b/x-pack/plugins/monitoring/common/cancel_promise.ts @@ -53,13 +53,13 @@ export class PromiseWithCancel { return new Promise((resolve, reject) => { this._status = Status.Awaiting; return this._promise - .then(response => { + .then((response) => { if (this._status !== Status.Canceled) { this._status = Status.Resolved; return resolve(response); } }) - .catch(error => { + .catch((error) => { if (this._status !== Status.Canceled) { this._status = Status.Failed; return reject(error); diff --git a/x-pack/plugins/monitoring/public/angular/app_modules.ts b/x-pack/plugins/monitoring/public/angular/app_modules.ts index 3fa79cedf4ce7..96b122801085f 100644 --- a/x-pack/plugins/monitoring/public/angular/app_modules.ts +++ b/x-pack/plugins/monitoring/public/angular/app_modules.ts @@ -102,7 +102,7 @@ function createMonitoringAppConfigConstants(keys: MonitoringPluginDependencies[' function createLocalStateModule(query: any) { angular .module('monitoring/State', ['monitoring/Private']) - .service('globalState', function( + .service('globalState', function ( Private: IPrivate, $rootScope: ng.IRootScopeService, $location: ng.ILocationService @@ -129,7 +129,7 @@ function createLocalStateModule(query: any) { function createLocalKbnUrlModule() { angular .module('monitoring/KbnUrl', ['monitoring/Private', 'ngRoute']) - .service('kbnUrl', function(Private: IPrivate) { + .service('kbnUrl', function (Private: IPrivate) { return Private(KbnUrlProvider); }); } @@ -137,22 +137,22 @@ function createLocalKbnUrlModule() { function createMonitoringAppServices() { angular .module('monitoring/services', ['monitoring/Private']) - .service('breadcrumbs', function(Private: IPrivate) { + .service('breadcrumbs', function (Private: IPrivate) { return Private(breadcrumbsProvider); }) - .service('monitoringClusters', function(Private: IPrivate) { + .service('monitoringClusters', function (Private: IPrivate) { return Private(monitoringClustersProvider); }) - .service('$executor', function(Private: IPrivate) { + .service('$executor', function (Private: IPrivate) { return Private(executorProvider); }) - .service('features', function(Private: IPrivate) { + .service('features', function (Private: IPrivate) { return Private(featuresProvider); }) - .service('license', function(Private: IPrivate) { + .service('license', function (Private: IPrivate) { return Private(licenseProvider); }) - .service('title', function(Private: IPrivate) { + .service('title', function (Private: IPrivate) { return Private(titleProvider); }); } @@ -169,24 +169,24 @@ function createMonitoringAppDirectives() { function createMonitoringAppFilters() { angular .module('monitoring/filters', []) - .filter('capitalize', function() { - return function(input: string) { + .filter('capitalize', function () { + return function (input: string) { return capitalize(input?.toLowerCase()); }; }) - .filter('formatNumber', function() { + .filter('formatNumber', function () { return formatNumber; }) - .filter('formatMetric', function() { + .filter('formatMetric', function () { return formatMetric; }) - .filter('extractIp', function() { + .filter('extractIp', function () { return extractIp; }); } function createLocalConfigModule(core: MonitoringPluginDependencies['core']) { - angular.module('monitoring/Config', []).provider('config', function() { + angular.module('monitoring/Config', []).provider('config', function () { return { $get: () => ({ get: (key: string) => core.uiSettings?.get(key), @@ -198,13 +198,13 @@ function createLocalConfigModule(core: MonitoringPluginDependencies['core']) { function createLocalStorage() { angular .module('monitoring/Storage', []) - .service('localStorage', function($window: IWindowService) { + .service('localStorage', function ($window: IWindowService) { return new Storage($window.localStorage); }) - .service('sessionStorage', function($window: IWindowService) { + .service('sessionStorage', function ($window: IWindowService) { return new Storage($window.sessionStorage); }) - .service('sessionTimeout', function() { + .service('sessionTimeout', function () { return {}; }); } @@ -230,12 +230,12 @@ function createLocalI18nModule() { function createHrefModule(core: AppMountContext['core']) { const name: string = 'kbnHref'; - angular.module('monitoring/href', []).directive(name, function() { + angular.module('monitoring/href', []).directive(name, function () { return { restrict: 'A', link: { pre: (_$scope, _$el, $attr) => { - $attr.$observe(name, val => { + $attr.$observe(name, (val) => { if (val) { const url = getSafeForExternalLink(val as string); $attr.$set('href', core.http.basePath.prepend(url)); diff --git a/x-pack/plugins/monitoring/public/angular/helpers/routes.ts b/x-pack/plugins/monitoring/public/angular/helpers/routes.ts index b9307e8594a7a..22b6fd8a4e912 100644 --- a/x-pack/plugins/monitoring/public/angular/helpers/routes.ts +++ b/x-pack/plugins/monitoring/public/angular/helpers/routes.ts @@ -26,7 +26,7 @@ class Routes { }; public addToProvider = ($routeProvider: any) => { - this.routes.forEach(args => { + this.routes.forEach((args) => { $routeProvider.when.apply(this, args); }); diff --git a/x-pack/plugins/monitoring/public/angular/providers/private.js b/x-pack/plugins/monitoring/public/angular/providers/private.js index e456f2617f7b8..3a667037b2919 100644 --- a/x-pack/plugins/monitoring/public/angular/providers/private.js +++ b/x-pack/plugins/monitoring/public/angular/providers/private.js @@ -86,13 +86,7 @@ import _ from 'lodash'; const nextId = _.partial(_.uniqueId, 'privateProvider#'); function name(fn) { - return ( - fn.name || - fn - .toString() - .split('\n') - .shift() - ); + return fn.name || fn.toString().split('\n').shift(); } export function PrivateProvider() { @@ -112,12 +106,12 @@ export function PrivateProvider() { else return (fn.$$id = nextId()); } - provider.stub = function(fn, instance) { + provider.stub = function (fn, instance) { cache[identify(fn)] = instance; return instance; }; - provider.swap = function(fn, prov) { + provider.swap = function (fn, prov) { const id = identify(fn); swaps[id] = prov; }; @@ -127,7 +121,7 @@ export function PrivateProvider() { function PrivateFactory($injector) { // prevent circular deps by tracking where we came from const privPath = []; - const pathToString = function() { + const pathToString = function () { return privPath.map(name).join(' -> '); }; diff --git a/x-pack/plugins/monitoring/public/angular/providers/url.js b/x-pack/plugins/monitoring/public/angular/providers/url.js index 57b63708b546e..0c984a71c9f2c 100644 --- a/x-pack/plugins/monitoring/public/angular/providers/url.js +++ b/x-pack/plugins/monitoring/public/angular/providers/url.js @@ -34,7 +34,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {Object} [paramObj] - optional set of parameters for the url template * @return {undefined} */ - self.change = function(url, paramObj, appState) { + self.change = function (url, paramObj, appState) { self._changeLocation('url', url, paramObj, false, appState); }; @@ -46,7 +46,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {Object} [paramObj] - optional set of parameters for the path template * @return {undefined} */ - self.changePath = function(path, paramObj) { + self.changePath = function (path, paramObj) { self._changeLocation('path', path, paramObj); }; @@ -57,7 +57,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {Object} [paramObj] - optional set of parameters for the url template * @return {undefined} */ - self.redirect = function(url, paramObj, appState) { + self.redirect = function (url, paramObj, appState) { self._changeLocation('url', url, paramObj, true, appState); }; @@ -69,7 +69,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {Object} [paramObj] - optional set of parameters for the path template * @return {undefined} */ - self.redirectPath = function(path, paramObj) { + self.redirectPath = function (path, paramObj) { self._changeLocation('path', path, paramObj, true); }; @@ -82,10 +82,10 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @return {String} - the evaluated result * @throws {Error} If any of the expressions can't be parsed. */ - self.eval = function(template, paramObj) { + self.eval = function (template, paramObj) { paramObj = paramObj || {}; - return template.replace(/\{\{([^\}]+)\}\}/g, function(match, expr) { + return template.replace(/\{\{([^\}]+)\}\}/g, function (match, expr) { // remove filters const key = expr.split('|')[0].trim(); @@ -109,7 +109,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {string} route - the route name * @return {string} - the computed href */ - self.getRouteHref = function(obj, route) { + self.getRouteHref = function (obj, route) { return '#' + self.getRouteUrl(obj, route); }; @@ -120,7 +120,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {string} route - the route name * @return {string} - the computed url */ - self.getRouteUrl = function(obj, route) { + self.getRouteUrl = function (obj, route) { const template = obj && obj.routes && obj.routes[route]; if (template) return self.eval(template, obj); }; @@ -133,7 +133,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {string} route - the route name * @return {undefined} */ - self.redirectToRoute = function(obj, route) { + self.redirectToRoute = function (obj, route) { self.redirect(self.getRouteUrl(obj, route)); }; @@ -145,7 +145,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * @param {string} route - the route name * @return {undefined} */ - self.changeToRoute = function(obj, route) { + self.changeToRoute = function (obj, route) { self.change(self.getRouteUrl(obj, route)); }; @@ -154,7 +154,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { * history. * @param param */ - self.removeParam = function(param) { + self.removeParam = function (param) { $location.search(param, null).replace(); }; @@ -163,7 +163,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { ///// let reloading; - self._changeLocation = function(type, url, paramObj, replace, appState) { + self._changeLocation = function (type, url, paramObj, replace, appState) { const prev = { path: $location.path(), search: $location.search(), @@ -186,7 +186,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { const $route = $injector.get('$route'); if (self._shouldForceReload(next, prev, $route)) { - reloading = $rootScope.$on('$locationChangeSuccess', function() { + reloading = $rootScope.$on('$locationChangeSuccess', function () { // call the "unlisten" function returned by $on reloading(); reloading = false; @@ -198,7 +198,7 @@ export function KbnUrlProvider($injector, $location, $rootScope, $parse) { }; // determine if the router will automatically reload the route - self._shouldForceReload = function(next, prev, $route) { + self._shouldForceReload = function (next, prev, $route) { if (reloading) return false; const route = $route.current && $route.current.$$route; diff --git a/x-pack/plugins/monitoring/public/components/alerts/alerts.js b/x-pack/plugins/monitoring/public/components/alerts/alerts.js index a86fdb1041a5c..0ac67228db359 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/alerts.js +++ b/x-pack/plugins/monitoring/public/components/alerts/alerts.js @@ -36,7 +36,7 @@ const getColumns = (kbnUrl, scope, timezone) => [ }), field: 'status', sortable: true, - render: severity => { + render: (severity) => { const severityIconDefaults = { title: i18n.translate('xpack.monitoring.alerts.severityTitle.unknown', { defaultMessage: 'Unknown', @@ -67,7 +67,7 @@ const getColumns = (kbnUrl, scope, timezone) => [ }), field: 'resolved_timestamp', sortable: true, - render: resolvedTimestamp => { + render: (resolvedTimestamp) => { const notResolvedLabel = i18n.translate('xpack.monitoring.alerts.notResolvedDescription', { defaultMessage: 'Not Resolved', }); @@ -109,7 +109,7 @@ const getColumns = (kbnUrl, scope, timezone) => [ suffix={alert.suffix} message={message} metadata={alert.metadata} - changeUrl={target => { + changeUrl={(target) => { scope.$evalAsync(() => { kbnUrl.changePath(target); }); @@ -124,7 +124,7 @@ const getColumns = (kbnUrl, scope, timezone) => [ }), field: 'category', sortable: true, - render: link => + render: (link) => linkToCategories[link] ? linkToCategories[link] : i18n.translate('xpack.monitoring.alerts.categoryColumn.generalLabel', { @@ -137,7 +137,7 @@ const getColumns = (kbnUrl, scope, timezone) => [ }), field: 'update_timestamp', sortable: true, - render: timestamp => formatDateTimeLocal(timestamp, timezone), + render: (timestamp) => formatDateTimeLocal(timestamp, timezone), }, { name: i18n.translate('xpack.monitoring.alerts.triggeredColumnTitle', { @@ -145,7 +145,7 @@ const getColumns = (kbnUrl, scope, timezone) => [ }), field: 'timestamp', sortable: true, - render: timestamp => + render: (timestamp) => i18n.translate('xpack.monitoring.alerts.triggeredColumnValue', { defaultMessage: '{timestamp} ago', values: { @@ -156,7 +156,7 @@ const getColumns = (kbnUrl, scope, timezone) => [ ]; export const Alerts = ({ alerts, angular, sorting, pagination, onTableChange }) => { - const alertsFlattened = alerts.map(alert => ({ + const alertsFlattened = alerts.map((alert) => ({ ...alert, status: get(alert, 'metadata.severity', get(alert, 'severity', 0)), category: get(alert, 'metadata.link', get(alert, 'type', null)), diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.test.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.test.tsx index 2c2d7c6464e1b..7caef8c230bf4 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.test.tsx +++ b/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.test.tsx @@ -30,13 +30,7 @@ describe('Configuration', () => { }); function getStep(component: ShallowWrapper, index: number) { - return component - .find('EuiSteps') - .shallow() - .find('EuiStep') - .at(index) - .children() - .shallow(); + return component.find('EuiSteps').shallow().find('EuiStep').at(index).children().shallow(); } describe('shallow view', () => { @@ -82,12 +76,7 @@ describe('Configuration', () => { it('reflect in Step1', async () => { const steps = component.find('EuiSteps').dive(); - expect( - steps - .find('EuiStep') - .at(0) - .prop('title') - ).toBe('Select email action'); + expect(steps.find('EuiStep').at(0).prop('title')).toBe('Select email action'); expect(steps.find('Step1').prop('selectedEmailActionId')).toBe(actionId); }); diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.tsx index 61f86b0f9b609..f248e20493a24 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.tsx +++ b/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.tsx @@ -61,7 +61,7 @@ export const AlertsConfiguration: React.FC = ( async function fetchEmailActions() { const kibanaActions = await Legacy.shims.kfetch({ method: 'GET', - pathname: `/api/action/_getAll`, + pathname: `/api/actions`, }); const actions = kibanaActions.data.filter( diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.test.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.test.tsx index 5734d379dfb0c..1be66ce4ccfef 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.test.tsx +++ b/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.test.tsx @@ -135,7 +135,7 @@ describe('Step1', () => { expect(kfetch).toHaveBeenCalledWith({ method: 'POST', - pathname: `/api/action`, + pathname: `/api/actions/action`, body: JSON.stringify({ name: 'Email action for Stack Monitoring alerts', actionTypeId: ALERT_ACTION_TYPE_EMAIL, @@ -193,7 +193,7 @@ describe('Step1', () => { expect(kfetch).toHaveBeenCalledWith({ method: 'PUT', - pathname: `/api/action/${emailActions[0].id}`, + pathname: `/api/actions/action/${emailActions[0].id}`, body: JSON.stringify({ name: emailActions[0].name, config: omit(data, ['user', 'password']), @@ -209,8 +209,8 @@ describe('Step1', () => { jest.doMock('../../../legacy_shims', () => ({ Legacy: { shims: { - kfetch: jest.fn().mockImplementation(arg => { - if (arg.pathname === '/api/action/1/_execute') { + kfetch: jest.fn().mockImplementation((arg) => { + if (arg.pathname === '/api/actions/action/1/_execute') { return { status: 'ok' }; } return {}; @@ -223,29 +223,11 @@ describe('Step1', () => { const component = shallow(); - expect( - component - .find('EuiButton') - .at(1) - .prop('isLoading') - ).toBe(false); - component - .find('EuiButton') - .at(1) - .simulate('click'); - expect( - component - .find('EuiButton') - .at(1) - .prop('isLoading') - ).toBe(true); + expect(component.find('EuiButton').at(1).prop('isLoading')).toBe(false); + component.find('EuiButton').at(1).simulate('click'); + expect(component.find('EuiButton').at(1).prop('isLoading')).toBe(true); await component.update(); - expect( - component - .find('EuiButton') - .at(1) - .prop('isLoading') - ).toBe(false); + expect(component.find('EuiButton').at(1).prop('isLoading')).toBe(false); }); it('should show a successful test', async () => { @@ -254,7 +236,7 @@ describe('Step1', () => { Legacy: { shims: { kfetch: (arg: any) => { - if (arg.pathname === '/api/action/1/_execute') { + if (arg.pathname === '/api/actions/action/1/_execute') { return { status: 'ok' }; } return {}; @@ -267,10 +249,7 @@ describe('Step1', () => { const component = shallow(); - component - .find('EuiButton') - .at(1) - .simulate('click'); + component.find('EuiButton').at(1).simulate('click'); await component.update(); expect(component).toMatchSnapshot(); }); @@ -281,7 +260,7 @@ describe('Step1', () => { Legacy: { shims: { kfetch: (arg: any) => { - if (arg.pathname === '/api/action/1/_execute') { + if (arg.pathname === '/api/actions/action/1/_execute') { return { message: 'Very detailed error message' }; } return {}; @@ -294,10 +273,7 @@ describe('Step1', () => { const component = shallow(); - component - .find('EuiButton') - .at(1) - .simulate('click'); + component.find('EuiButton').at(1).simulate('click'); await component.update(); expect(component).toMatchSnapshot(); }); @@ -307,12 +283,7 @@ describe('Step1', () => { emailAddress: '', }; const component = shallow(); - expect( - component - .find('EuiButton') - .at(1) - .prop('isDisabled') - ).toBe(true); + expect(component.find('EuiButton').at(1).prop('isDisabled')).toBe(true); }); it('should should a tooltip if there is no email address', () => { @@ -344,25 +315,17 @@ describe('Step1', () => { }; const component = shallow(); - await component - .find('EuiButton') - .at(2) - .simulate('click'); + await component.find('EuiButton').at(2).simulate('click'); await component.update(); expect(kfetch).toHaveBeenCalledWith({ method: 'DELETE', - pathname: `/api/action/${emailActions[0].id}`, + pathname: `/api/actions/action/${emailActions[0].id}`, }); expect(customProps.setSelectedEmailActionId).toHaveBeenCalledWith(''); expect(customProps.onActionDone).toHaveBeenCalled(); - expect( - component - .find('EuiButton') - .at(2) - .prop('isLoading') - ).toBe(false); + expect(component.find('EuiButton').at(2).prop('isLoading')).toBe(false); }); }); }); diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.tsx index 7953010005885..b3e6c079378ef 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.tsx +++ b/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.tsx @@ -44,7 +44,7 @@ export const Step1: React.FC = (props: GetStep1Props) => { if (props.editAction) { await Legacy.shims.kfetch({ method: 'PUT', - pathname: `${BASE_ACTION_API_PATH}/${props.editAction.id}`, + pathname: `${BASE_ACTION_API_PATH}/action/${props.editAction.id}`, body: JSON.stringify({ name: props.editAction.name, config: omit(data, ['user', 'password']), @@ -55,7 +55,7 @@ export const Step1: React.FC = (props: GetStep1Props) => { } else { await Legacy.shims.kfetch({ method: 'POST', - pathname: BASE_ACTION_API_PATH, + pathname: `${BASE_ACTION_API_PATH}/action`, body: JSON.stringify({ name: i18n.translate('xpack.monitoring.alerts.configuration.emailAction.name', { defaultMessage: 'Email action for Stack Monitoring alerts', @@ -75,7 +75,7 @@ export const Step1: React.FC = (props: GetStep1Props) => { await Legacy.shims.kfetch({ method: 'DELETE', - pathname: `${BASE_ACTION_API_PATH}/${id}`, + pathname: `${BASE_ACTION_API_PATH}/action/${id}`, }); if (props.editAction && props.editAction.id === id) { @@ -101,7 +101,7 @@ export const Step1: React.FC = (props: GetStep1Props) => { const result = await Legacy.shims.kfetch({ method: 'POST', - pathname: `${BASE_ACTION_API_PATH}/${props.selectedEmailActionId}/_execute`, + pathname: `${BASE_ACTION_API_PATH}/action/${props.selectedEmailActionId}/_execute`, body: JSON.stringify({ params }), }); if (result.status === 'ok') { @@ -178,7 +178,7 @@ export const Step1: React.FC = (props: GetStep1Props) => { ); const options = [ - ...props.emailActions.map(action => { + ...props.emailActions.map((action) => { const actionLabel = i18n.translate( 'xpack.monitoring.alerts.configuration.selectAction.inputDisplay', { @@ -207,7 +207,7 @@ export const Step1: React.FC = (props: GetStep1Props) => { props.setSelectedEmailActionId(id)} + onChange={(id) => props.setSelectedEmailActionId(id)} hasDividers /> ); @@ -238,7 +238,7 @@ export const Step1: React.FC = (props: GetStep1Props) => { let manageConfiguration = null; const selectedEmailAction = props.emailActions.find( - action => action.id === props.selectedEmailActionId + (action) => action.id === props.selectedEmailActionId ); if ( @@ -288,7 +288,7 @@ export const Step1: React.FC = (props: GetStep1Props) => { iconType="pencil" onClick={() => { const editAction = - props.emailActions.find(action => action.id === props.selectedEmailActionId) || + props.emailActions.find((action) => action.id === props.selectedEmailActionId) || null; props.setEditAction(editAction); }} diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/step2.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/step2.tsx index 974dd8513d231..2c215e310af69 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/step2.tsx +++ b/x-pack/plugins/monitoring/public/components/alerts/configuration/step2.tsx @@ -30,7 +30,7 @@ export const Step2: React.FC = (props: GetStep2Props) => { props.setEmailAddress(e.target.value)} + onChange={(e) => props.setEmailAddress(e.target.value)} /> diff --git a/x-pack/plugins/monitoring/public/components/alerts/manage_email_action.tsx b/x-pack/plugins/monitoring/public/components/alerts/manage_email_action.tsx index 3ef9654076340..87588a435078d 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/manage_email_action.tsx +++ b/x-pack/plugins/monitoring/public/components/alerts/manage_email_action.tsx @@ -108,7 +108,7 @@ export const ManageEmailAction: React.FC = ( } } - const serviceOptions = ALERT_EMAIL_SERVICES.map(service => ({ + const serviceOptions = ALERT_EMAIL_SERVICES.map((service) => ({ value: service, inputDisplay: {service}, dropdownDisplay: {service}, @@ -139,7 +139,7 @@ export const ManageEmailAction: React.FC = ( setNewService(e.target.value)} + onChange={(e) => setNewService(e.target.value)} isInvalid={showErrors} /> @@ -166,7 +166,7 @@ export const ManageEmailAction: React.FC = ( { + onChange={(id) => { if (id === NEW_SERVICE_ID) { setCreateNewService(true); setData({ ...data, service: NEW_SERVICE_ID }); @@ -194,7 +194,7 @@ export const ManageEmailAction: React.FC = ( > setData({ ...data, host: e.target.value })} + onChange={(e) => setData({ ...data, host: e.target.value })} isInvalid={showErrors && !!errors.host} /> @@ -211,7 +211,7 @@ export const ManageEmailAction: React.FC = ( > setData({ ...data, port: parseInt(e.target.value, 10) })} + onChange={(e) => setData({ ...data, port: parseInt(e.target.value, 10) })} isInvalid={showErrors && !!errors.port} /> @@ -227,7 +227,7 @@ export const ManageEmailAction: React.FC = ( setData({ ...data, secure: e.target.checked })} + onChange={(e) => setData({ ...data, secure: e.target.checked })} /> @@ -243,7 +243,7 @@ export const ManageEmailAction: React.FC = ( > setData({ ...data, from: e.target.value })} + onChange={(e) => setData({ ...data, from: e.target.value })} isInvalid={showErrors && !!errors.from} /> @@ -260,7 +260,7 @@ export const ManageEmailAction: React.FC = ( > setData({ ...data, user: e.target.value })} + onChange={(e) => setData({ ...data, user: e.target.value })} isInvalid={showErrors && !!errors.user} /> @@ -277,7 +277,7 @@ export const ManageEmailAction: React.FC = ( > setData({ ...data, password: e.target.value })} + onChange={(e) => setData({ ...data, password: e.target.value })} isInvalid={showErrors && !!errors.password} /> diff --git a/x-pack/plugins/monitoring/public/components/alerts/status.test.tsx b/x-pack/plugins/monitoring/public/components/alerts/status.test.tsx index a0031f50951bd..1c35328d2f881 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/status.test.tsx +++ b/x-pack/plugins/monitoring/public/components/alerts/status.test.tsx @@ -71,7 +71,7 @@ describe('Status', () => { it('should render a success message if all alerts have been migrated and in setup mode', async () => { (Legacy.shims.kfetch as jest.Mock).mockReturnValue({ - data: ALERT_TYPES.map(type => ({ alertTypeId: type })), + data: ALERT_TYPES.map((type) => ({ alertTypeId: type })), }); (getSetupModeState as jest.Mock).mockReturnValue({ diff --git a/x-pack/plugins/monitoring/public/components/apm/instances/instances.js b/x-pack/plugins/monitoring/public/components/apm/instances/instances.js index a48fbc51341f1..9d0d2c5aefa56 100644 --- a/x-pack/plugins/monitoring/public/components/apm/instances/instances.js +++ b/x-pack/plugins/monitoring/public/components/apm/instances/instances.js @@ -79,28 +79,28 @@ function getColumns(setupMode) { defaultMessage: 'Total Events Rate', }), field: 'total_events_rate', - render: value => formatMetric(value, '', '/s'), + render: (value) => formatMetric(value, '', '/s'), }, { name: i18n.translate('xpack.monitoring.apm.instances.bytesSentRateTitle', { defaultMessage: 'Bytes Sent Rate', }), field: 'bytes_sent_rate', - render: value => formatMetric(value, 'byte', '/s'), + render: (value) => formatMetric(value, 'byte', '/s'), }, { name: i18n.translate('xpack.monitoring.apm.instances.outputErrorsTitle', { defaultMessage: 'Output Errors', }), field: 'errors', - render: value => formatMetric(value, '0'), + render: (value) => formatMetric(value, '0'), }, { name: i18n.translate('xpack.monitoring.apm.instances.lastEventTitle', { defaultMessage: 'Last Event', }), field: 'time_of_last_event', - render: value => + render: (value) => i18n.translate('xpack.monitoring.apm.instances.lastEventValue', { defaultMessage: '{timeOfLastEvent} ago', values: { @@ -113,7 +113,7 @@ function getColumns(setupMode) { defaultMessage: 'Allocated Memory', }), field: 'memory', - render: value => formatMetric(value, 'byte'), + render: (value) => formatMetric(value, 'byte'), }, { name: i18n.translate('xpack.monitoring.apm.instances.versionTitle', { @@ -138,7 +138,7 @@ export function ApmServerInstances({ apms, setupMode }) { ); } - const versions = uniq(data.apms.map(item => item.version)).map(version => { + const versions = uniq(data.apms.map((item) => item.version)).map((version) => { return { value: version }; }); diff --git a/x-pack/plugins/monitoring/public/components/beats/listing/listing.js b/x-pack/plugins/monitoring/public/components/beats/listing/listing.js index 5863f6e5161ad..81ae6796d7294 100644 --- a/x-pack/plugins/monitoring/public/components/beats/listing/listing.js +++ b/x-pack/plugins/monitoring/public/components/beats/listing/listing.js @@ -86,28 +86,28 @@ export class Listing extends PureComponent { defaultMessage: 'Total Events Rate', }), field: 'total_events_rate', - render: value => formatMetric(value, '', '/s'), + render: (value) => formatMetric(value, '', '/s'), }, { name: i18n.translate('xpack.monitoring.beats.instances.bytesSentRateTitle', { defaultMessage: 'Bytes Sent Rate', }), field: 'bytes_sent_rate', - render: value => formatMetric(value, 'byte', '/s'), + render: (value) => formatMetric(value, 'byte', '/s'), }, { name: i18n.translate('xpack.monitoring.beats.instances.outputErrorsTitle', { defaultMessage: 'Output Errors', }), field: 'errors', - render: value => formatMetric(value, '0'), + render: (value) => formatMetric(value, '0'), }, { name: i18n.translate('xpack.monitoring.beats.instances.allocatedMemoryTitle', { defaultMessage: 'Allocated Memory', }), field: 'memory', - render: value => formatMetric(value, 'byte'), + render: (value) => formatMetric(value, 'byte'), }, { name: i18n.translate('xpack.monitoring.beats.instances.versionTitle', { @@ -132,11 +132,11 @@ export class Listing extends PureComponent { ); } - const types = uniq(data.map(item => item.type)).map(type => { + const types = uniq(data.map((item) => item.type)).map((type) => { return { value: type }; }); - const versions = uniq(data.map(item => item.version)).map(version => { + const versions = uniq(data.map((item) => item.version)).map((version) => { return { value: version }; }); diff --git a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_color.js b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_color.js index c1f0d3e8bbb23..7b70f1d1fb224 100644 --- a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_color.js +++ b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_color.js @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { getColor } from '../get_color'; -describe('getColors', function() { +describe('getColors', function () { it('elasticsearch colors', () => { expect(getColor('elasticsearch', 0)).to.be('#3ebeb0'); expect(getColor('elasticsearch', 1)).to.be('#3b73ac'); diff --git a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_last_value.js b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_last_value.js index bc469b7149e2c..c089b47408e81 100644 --- a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_last_value.js +++ b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_last_value.js @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { getLastValue } from '../get_last_value'; -describe('monitoringChartGetLastValue', function() { +describe('monitoringChartGetLastValue', function () { it('getLastValue for single number', () => { expect(getLastValue(3)).to.be(3); }); diff --git a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_title.js b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_title.js index 66100ee573aca..a7f4b48a5862a 100644 --- a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_title.js +++ b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_title.js @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import { getTitle } from '../get_title'; -describe('getTitle', function() { +describe('getTitle', function () { it('with metric.title', () => { const series = [ { metric: { title: 'Foo', label: 'Bar X' } }, diff --git a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_values_for_legend.js b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_values_for_legend.js index 59386996678dc..e5c933426efcd 100644 --- a/x-pack/plugins/monitoring/public/components/chart/__tests__/get_values_for_legend.js +++ b/x-pack/plugins/monitoring/public/components/chart/__tests__/get_values_for_legend.js @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import sinon from 'sinon'; import { findIndexByX, getValuesByX, getValuesForSeriesIndex } from '../get_values_for_legend'; -describe('monitoringChartHelpers', function() { +describe('monitoringChartHelpers', function () { it('getValuesForSeriesIndex sets does not impact callback without series', () => { const callback = sinon.stub(); diff --git a/x-pack/plugins/monitoring/public/components/chart/chart_target.js b/x-pack/plugins/monitoring/public/components/chart/chart_target.js index e6a6cc4b77755..31199c5b092f6 100644 --- a/x-pack/plugins/monitoring/public/components/chart/chart_target.js +++ b/x-pack/plugins/monitoring/public/components/chart/chart_target.js @@ -42,8 +42,8 @@ export class ChartTarget extends React.Component { filterByShow(seriesToShow) { if (seriesToShow) { - return metric => { - return seriesToShow.some(id => id.toLowerCase() === metric.id.toLowerCase()); + return (metric) => { + return seriesToShow.some((id) => id.toLowerCase() === metric.id.toLowerCase()); }; } return () => true; @@ -73,9 +73,7 @@ export class ChartTarget extends React.Component { } filterData(data, seriesToShow) { - return _(data) - .filter(this.filterByShow(seriesToShow)) - .value(); + return _(data).filter(this.filterByShow(seriesToShow)).value(); } async getOptions() { diff --git a/x-pack/plugins/monitoring/public/components/chart/get_title.js b/x-pack/plugins/monitoring/public/components/chart/get_title.js index 4450352add45f..bb40551fe8428 100644 --- a/x-pack/plugins/monitoring/public/components/chart/get_title.js +++ b/x-pack/plugins/monitoring/public/components/chart/get_title.js @@ -12,7 +12,7 @@ import { chain } from 'lodash'; */ export function getTitle(series = []) { return chain( - series.map(s => { + series.map((s) => { return s.metric.title || s.metric.label; }) ) diff --git a/x-pack/plugins/monitoring/public/components/chart/get_units.js b/x-pack/plugins/monitoring/public/components/chart/get_units.js index e8348059a6d4d..fd377cced122c 100644 --- a/x-pack/plugins/monitoring/public/components/chart/get_units.js +++ b/x-pack/plugins/monitoring/public/components/chart/get_units.js @@ -13,7 +13,7 @@ export function getUnits(series) { // For Bytes, find the largest unit from any data set's _last_ item if (units === 'B') { let maxLastBytes = 0; - forEach(series, s => { + forEach(series, (s) => { const lastDataPoint = last(s.data) || [null, 0]; maxLastBytes = Math.max(maxLastBytes, lastDataPoint[1]); // lastDataPoint[1] is the "y" value }); diff --git a/x-pack/plugins/monitoring/public/components/chart/horizontal_legend.js b/x-pack/plugins/monitoring/public/components/chart/horizontal_legend.js index ab322324ac200..738775ed8d4d9 100644 --- a/x-pack/plugins/monitoring/public/components/chart/horizontal_legend.js +++ b/x-pack/plugins/monitoring/public/components/chart/horizontal_legend.js @@ -71,7 +71,7 @@ export class HorizontalLegend extends React.Component { @@ -113,7 +113,7 @@ describe('DeleteProvider', () => { const wrapper = mountWithIntl( - {onDelete => ( + {(onDelete) => ( @@ -189,7 +189,7 @@ describe('DeleteProvider', () => { const wrapper = mountWithIntl( - {onDelete => ( + {(onDelete) => ( @@ -253,7 +253,7 @@ describe('DeleteProvider', () => { const wrapper = mountWithIntl( - {onDelete => ( + {(onDelete) => ( diff --git a/x-pack/plugins/security/public/management/role_mappings/components/delete_provider/delete_provider.tsx b/x-pack/plugins/security/public/management/role_mappings/components/delete_provider/delete_provider.tsx index 860fe22cb8032..7abf34700ad7a 100644 --- a/x-pack/plugins/security/public/management/role_mappings/components/delete_provider/delete_provider.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/components/delete_provider/delete_provider.tsx @@ -58,7 +58,7 @@ export const DeleteProvider: React.FunctionComponent = ({ setIsDeleteInProgress(true); try { - result = await roleMappingsAPI.deleteRoleMappings(roleMappings.map(rm => rm.name)); + result = await roleMappingsAPI.deleteRoleMappings(roleMappings.map((rm) => rm.name)); } catch (e) { notifications.toasts.addError(e, { title: i18n.translate( @@ -76,8 +76,8 @@ export const DeleteProvider: React.FunctionComponent = ({ closeModal(); - const successfulDeletes = result.filter(res => res.success); - const erroredDeletes = result.filter(res => !res.success); + const successfulDeletes = result.filter((res) => res.success); + const erroredDeletes = result.filter((res) => !res.success); // Surface success notifications if (successfulDeletes.length > 0) { diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.test.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.test.tsx index 149c1271123d2..eea6bbef94306 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.test.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.test.tsx @@ -64,10 +64,7 @@ describe('EditRoleMappingPage', () => { target: { value: 'my-role-mapping' }, }); - wrapper - .find(RoleComboBox) - .props() - .onChange(['foo_role']); + wrapper.find(RoleComboBox).props().onChange(['foo_role']); findTestSubject(wrapper, 'roleMappingsAddRuleButton').simulate('click'); @@ -127,10 +124,7 @@ describe('EditRoleMappingPage', () => { findTestSubject(wrapper, 'switchToRolesButton').simulate('click'); - wrapper - .find(RoleComboBox) - .props() - .onChange(['foo_role']); + wrapper.find(RoleComboBox).props().onChange(['foo_role']); findTestSubject(wrapper, 'roleMappingsAddRuleButton').simulate('click'); wrapper.find('button[id="addRuleOption"]').simulate('click'); diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.tsx index 142b53cbb50f2..3b16bd8dc44ac 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.tsx @@ -106,7 +106,7 @@ export class EditRoleMappingPage extends Component { this.setState({ roleMapping })} + onChange={(roleMapping) => this.setState({ roleMapping })} mode={this.editingExistingRoleMapping() ? 'edit' : 'create'} validateForm={this.state.validateForm} canUseInlineScripts={this.state.canUseInlineScripts} @@ -119,7 +119,7 @@ export class EditRoleMappingPage extends Component { rawRules={this.state.roleMapping!.rules} validateForm={this.state.validateForm} onValidityChange={this.onRuleValidityChange} - onChange={rules => + onChange={(rules) => this.setState({ roleMapping: { ...this.state.roleMapping!, @@ -218,7 +218,7 @@ export class EditRoleMappingPage extends Component { roleMappingsAPI={this.props.roleMappingsAPI} notifications={this.props.notifications} > - {deleteRoleMappingsPrompt => { + {(deleteRoleMappingsPrompt) => { return ( @@ -279,7 +279,7 @@ export class EditRoleMappingPage extends Component { }); this.backToRoleMappingsList(); }) - .catch(e => { + .catch((e) => { this.props.notifications.toasts.addError(e, { title: i18n.translate('xpack.security.management.editRoleMapping.saveError', { defaultMessage: `Error saving role mapping`, diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/mapping_info_panel/mapping_info_panel.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/mapping_info_panel/mapping_info_panel.tsx index b376a3943ff48..3df9987141fb2 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/mapping_info_panel/mapping_info_panel.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/mapping_info_panel/mapping_info_panel.tsx @@ -172,7 +172,7 @@ export class MappingInfoPanel extends Component { mode={this.state.rolesMode} canUseInlineScripts={this.props.canUseInlineScripts} canUseStoredScripts={this.props.canUseStoredScripts} - onChange={roleMapping => this.props.onChange(roleMapping)} + onChange={(roleMapping) => this.props.onChange(roleMapping)} /> @@ -240,7 +240,7 @@ export class MappingInfoPanel extends Component { mode={this.state.rolesMode} canUseInlineScripts={this.props.canUseInlineScripts} canUseStoredScripts={this.props.canUseStoredScripts} - onChange={roleMapping => this.props.onChange(roleMapping)} + onChange={(roleMapping) => this.props.onChange(roleMapping)} /> @@ -286,7 +286,7 @@ export class MappingInfoPanel extends Component { showLabel={false} data-test-subj="roleMappingsEnabledSwitch" checked={this.props.roleMapping.enabled} - onChange={e => { + onChange={(e) => { this.props.onChange({ ...this.props.roleMapping, enabled: e.target.checked, diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_selector.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_selector.tsx index 8e1597cf3d598..b0f558ee71be8 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_selector.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_selector.tsx @@ -59,7 +59,7 @@ export class RoleSelector extends React.Component { isLoading={this.state.roles.length === 0} availableRoles={this.state.roles} selectedRoleNames={roles} - onChange={selectedRoles => { + onChange={(selectedRoles) => { this.props.onChange({ ...this.props.roleMapping, roles: selectedRoles, @@ -80,7 +80,7 @@ export class RoleSelector extends React.Component { canUseStoredScripts={this.props.canUseStoredScripts} canUseInlineScripts={this.props.canUseInlineScripts} roleTemplate={rt} - onChange={updatedTemplate => { + onChange={(updatedTemplate) => { const templates = [...(this.props.roleMapping.role_templates || [])]; templates.splice(index, 1, updatedTemplate); this.props.onChange({ @@ -103,7 +103,7 @@ export class RoleSelector extends React.Component { { + onClick={(type) => { switch (type) { case 'inline': { const templates = this.props.roleMapping.role_templates || []; @@ -147,8 +147,8 @@ export class RoleSelector extends React.Component { private hasDeprecatedRolesAssigned = () => { return ( - this.props.roleMapping.roles?.some(r => - this.state.roles.some(role => role.name === r && isRoleDeprecated(role)) + this.props.roleMapping.roles?.some((r) => + this.state.roles.some((role) => role.name === r && isRoleDeprecated(role)) ) ?? false ); }; diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_editor.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_editor.tsx index d79651d7b9cd6..0191f7194e8e5 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_editor.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_editor.tsx @@ -81,7 +81,7 @@ export const RoleTemplateEditor = ({ checked={roleTemplate.format === 'json'} label={returnsJsonLabel} showLabel={false} - onChange={e => { + onChange={(e) => { onChange({ ...roleTemplate, format: e.target.checked ? 'json' : 'string', @@ -164,7 +164,7 @@ export const RoleTemplateEditor = ({ { + onChange={(e) => { onChange({ ...roleTemplate, template: { @@ -213,7 +213,7 @@ export const RoleTemplateEditor = ({ { + onChange={(e) => { onChange({ ...roleTemplate, template: { diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_type_select.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_type_select.tsx index aa65c5c9bcae7..9bbf4b7ff405a 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_type_select.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/role_selector/role_template_type_select.tsx @@ -53,7 +53,7 @@ export const RoleTemplateTypeSelect = (props: Props) => { singleSelection={{ asPlainText: true }} selectedOptions={selectedOptions} data-test-subj="roleMappingsFormTemplateType" - onChange={selected => { + onChange={(selected) => { const [{ id }] = selected; if (id === 'inline') { props.onChange({ diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/field_rule_editor.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/field_rule_editor.tsx index 6022c836c6904..125e751f9a91b 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/field_rule_editor.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/field_rule_editor.tsx @@ -41,7 +41,7 @@ const userFields = [ }, ]; -const fieldOptions = userFields.map(f => ({ label: f.name })); +const fieldOptions = userFields.map((f) => ({ label: f.name })); type ComparisonOption = 'text' | 'number' | 'null' | 'boolean'; const comparisonOptions: Record< @@ -196,7 +196,7 @@ export class FieldRuleEditor extends Component { ]} data-test-subj={`fieldRuleEditorValueType-${valueIndex}`} value={inputType} - onChange={e => + onChange={(e) => this.onComparisonTypeChange(valueIndex, e.target.value as ComparisonOption) } /> diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.test.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.test.tsx index 5946aac4306b1..48eb1380bd08f 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.test.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.test.tsx @@ -48,7 +48,7 @@ describe('RuleGroupEditor', () => { await nextTick(); wrapper.update(); - const anyRuleOption = wrapper.find(EuiContextMenuItem).filterWhere(menuItem => { + const anyRuleOption = wrapper.find(EuiContextMenuItem).filterWhere((menuItem) => { return menuItem.text() === anyRule.getDisplayTitle(); }); @@ -76,13 +76,11 @@ describe('RuleGroupEditor', () => { const anyRule = new AnyRule(); - findTestSubject(wrapper, 'ruleGroupTitle') - .first() - .simulate('click'); + findTestSubject(wrapper, 'ruleGroupTitle').first().simulate('click'); await nextTick(); wrapper.update(); - const anyRuleOption = wrapper.find(EuiContextMenuItem).filterWhere(menuItem => { + const anyRuleOption = wrapper.find(EuiContextMenuItem).filterWhere((menuItem) => { return menuItem.text() === anyRule.getDisplayTitle(); }); @@ -116,13 +114,11 @@ describe('RuleGroupEditor', () => { const anyRule = new AnyRule(); - findTestSubject(wrapper, 'ruleGroupTitle') - .first() - .simulate('click'); + findTestSubject(wrapper, 'ruleGroupTitle').first().simulate('click'); await nextTick(); wrapper.update(); - const anyRuleOption = wrapper.find(EuiContextMenuItem).filterWhere(menuItem => { + const anyRuleOption = wrapper.find(EuiContextMenuItem).filterWhere((menuItem) => { return menuItem.text() === anyRule.getDisplayTitle(); }); diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.tsx index b10a6dd8d183f..2e6cfa5f1cde6 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_editor.tsx @@ -90,7 +90,7 @@ export class RuleGroupEditor extends Component { parentRule={this.props.rule} allowAdd={this.props.allowAdd} ruleDepth={this.props.ruleDepth + 1} - onChange={updatedSubRule => { + onChange={(updatedSubRule) => { const updatedRule = this.props.rule.clone() as RuleGroup; updatedRule.replaceRule(subRuleIndex, updatedSubRule); this.props.onChange(updatedRule); @@ -112,7 +112,7 @@ export class RuleGroupEditor extends Component { { + onChange={(updatedSubRule) => { const updatedRule = this.props.rule.clone() as RuleGroup; updatedRule.replaceRule(subRuleIndex, updatedSubRule); this.props.onChange(updatedRule); diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_title.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_title.tsx index 6bef9c09eeef3..6f9853041ffbe 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_title.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/rule_group_title.tsx @@ -42,7 +42,7 @@ export const RuleGroupTitle = (props: Props) => { const areSubRulesValid = newRule.canContainRules(currentSubRules); if (areSubRulesValid) { const clone = newRule.clone() as RuleGroup; - currentSubRules.forEach(subRule => clone.addRule(subRule)); + currentSubRules.forEach((subRule) => clone.addRule(subRule)); props.onChange(clone); setIsMenuOpen(false); diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/visual_rule_editor.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/visual_rule_editor.tsx index 2e3db275788ee..cb50d30b02a1e 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/visual_rule_editor.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/rule_editor_panel/visual_rule_editor.tsx @@ -127,7 +127,7 @@ export class VisualRuleEditor extends Component { rule={rule as RuleGroup} ruleDepth={0} allowAdd={this.canUseVisualEditor()} - onChange={value => onChange(value)} + onChange={(value) => onChange(value)} onDelete={this.onRuleDelete} /> ); @@ -135,7 +135,7 @@ export class VisualRuleEditor extends Component { return ( onChange(value)} + onChange={(value) => onChange(value)} onDelete={this.onRuleDelete} /> ); diff --git a/x-pack/plugins/security/public/management/role_mappings/model/all_rule.test.ts b/x-pack/plugins/security/public/management/role_mappings/model/all_rule.test.ts index ddf3b4499f73b..d046945747a57 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/all_rule.test.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/all_rule.test.ts @@ -28,7 +28,7 @@ describe('All rule', () => { const rule = new AllRule() as RuleGroup; expect(rule.canContainRules(subRules)).toEqual(true); - subRules.forEach(sr => rule.addRule(sr)); + subRules.forEach((sr) => rule.addRule(sr)); expect(rule.getRules()).toEqual([...subRules]); }); diff --git a/x-pack/plugins/security/public/management/role_mappings/model/all_rule.ts b/x-pack/plugins/security/public/management/role_mappings/model/all_rule.ts index ecea27a7fb87f..f948d4c15e611 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/all_rule.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/all_rule.ts @@ -50,13 +50,13 @@ export class AllRule extends RuleGroup { /** {@see RuleGroup.clone} */ public clone() { - return new AllRule(this.rules.map(r => r.clone())); + return new AllRule(this.rules.map((r) => r.clone())); } /** {@see RuleGroup.toRaw} */ public toRaw() { return { - all: [...this.rules.map(rule => rule.toRaw())], + all: [...this.rules.map((rule) => rule.toRaw())], }; } } diff --git a/x-pack/plugins/security/public/management/role_mappings/model/any_rule.test.ts b/x-pack/plugins/security/public/management/role_mappings/model/any_rule.test.ts index 767aa075755af..d56469c4c9622 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/any_rule.test.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/any_rule.test.ts @@ -22,7 +22,7 @@ describe('Any rule', () => { const rule = new AnyRule() as RuleGroup; expect(rule.canContainRules(subRules)).toEqual(true); - subRules.forEach(sr => rule.addRule(sr)); + subRules.forEach((sr) => rule.addRule(sr)); expect(rule.getRules()).toEqual([...subRules]); }); diff --git a/x-pack/plugins/security/public/management/role_mappings/model/any_rule.ts b/x-pack/plugins/security/public/management/role_mappings/model/any_rule.ts index 6a4f2eaf1b362..5f3f190dd0f37 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/any_rule.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/any_rule.ts @@ -49,19 +49,19 @@ export class AnyRule extends RuleGroup { public canContainRules(rules: Rule[]) { const forbiddenRules = [ExceptAllRule, ExceptAnyRule]; return rules.every( - candidate => !forbiddenRules.some(forbidden => candidate instanceof forbidden) + (candidate) => !forbiddenRules.some((forbidden) => candidate instanceof forbidden) ); } /** {@see RuleGroup.clone} */ public clone() { - return new AnyRule(this.rules.map(r => r.clone())); + return new AnyRule(this.rules.map((r) => r.clone())); } /** {@see RuleGroup.toRaw} */ public toRaw() { return { - any: [...this.rules.map(rule => rule.toRaw())], + any: [...this.rules.map((rule) => rule.toRaw())], }; } } diff --git a/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.test.ts b/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.test.ts index 7a00e5b19638f..73a5451534ec0 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.test.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.test.ts @@ -28,7 +28,7 @@ describe('Except All rule', () => { const rule = new ExceptAllRule() as RuleGroup; expect(rule.canContainRules(subRules)).toEqual(true); - subRules.forEach(sr => rule.addRule(sr)); + subRules.forEach((sr) => rule.addRule(sr)); expect(rule.getRules()).toEqual([...subRules]); }); diff --git a/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.ts b/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.ts index a67c2622a2533..af75f08539c1c 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/except_all_rule.ts @@ -50,13 +50,13 @@ export class ExceptAllRule extends RuleGroup { /** {@see RuleGroup.clone} */ public clone() { - return new ExceptAllRule(this.rules.map(r => r.clone())); + return new ExceptAllRule(this.rules.map((r) => r.clone())); } /** {@see RuleGroup.toRaw} */ public toRaw() { const rawRule = { - all: [...this.rules.map(rule => rule.toRaw())], + all: [...this.rules.map((rule) => rule.toRaw())], }; return { diff --git a/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.test.ts b/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.test.ts index e4e182ce88d8d..902c706d75aec 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.test.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.test.ts @@ -22,7 +22,7 @@ describe('Except Any rule', () => { const rule = new ExceptAnyRule() as RuleGroup; expect(rule.canContainRules(subRules)).toEqual(true); - subRules.forEach(sr => rule.addRule(sr)); + subRules.forEach((sr) => rule.addRule(sr)); expect(rule.getRules()).toEqual([...subRules]); }); diff --git a/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.ts b/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.ts index 12ec3fe85b80d..e7bc6a7b0ae4e 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/except_any_rule.ts @@ -48,19 +48,19 @@ export class ExceptAnyRule extends RuleGroup { public canContainRules(rules: Rule[]) { const forbiddenRules = [ExceptAllRule, ExceptAnyRule]; return rules.every( - candidate => !forbiddenRules.some(forbidden => candidate instanceof forbidden) + (candidate) => !forbiddenRules.some((forbidden) => candidate instanceof forbidden) ); } /** {@see RuleGroup.clone} */ public clone() { - return new ExceptAnyRule(this.rules.map(r => r.clone())); + return new ExceptAnyRule(this.rules.map((r) => r.clone())); } /** {@see RuleGroup.toRaw} */ public toRaw() { const rawRule = { - any: [...this.rules.map(rule => rule.toRaw())], + any: [...this.rules.map((rule) => rule.toRaw())], }; return { diff --git a/x-pack/plugins/security/public/management/role_mappings/model/field_rule.test.ts b/x-pack/plugins/security/public/management/role_mappings/model/field_rule.test.ts index 3447e81707002..b7bb2a4170ff1 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/field_rule.test.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/field_rule.test.ts @@ -7,7 +7,7 @@ import { FieldRule } from '.'; describe('FieldRule', () => { - ['*', 1, null, true, false].forEach(value => { + ['*', 1, null, true, false].forEach((value) => { it(`can convert itself to raw form with a single value of ${value}`, () => { const rule = new FieldRule('username', value); expect(rule.toRaw()).toEqual({ diff --git a/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.test.ts b/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.test.ts index ad486a8b314c4..fea110e6beca4 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.test.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.test.ts @@ -252,7 +252,7 @@ describe('generateRulesFromRaw', () => { expect((rules as FieldRule).value).toEqual([0, '*', null, 'foo', true, false]); }); - [{}, () => null, undefined, [{}, undefined, [], () => null]].forEach(invalidValue => { + [{}, () => null, undefined, [{}, undefined, [], () => null]].forEach((invalidValue) => { it(`does not support a value of ${invalidValue}`, () => { expect(() => { generateRulesFromRaw({ diff --git a/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.ts b/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.ts index a384e61e521ab..44c6ace3bfeac 100644 --- a/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.ts +++ b/x-pack/plugins/security/public/management/role_mappings/model/rule_builder.ts @@ -92,7 +92,7 @@ function createRuleForType( const [field, value] = entries[0] as [string, FieldRuleValue]; const values = Array.isArray(value) ? value : [value]; - values.forEach(fieldValue => { + values.forEach((fieldValue) => { const valueType = typeof fieldValue; if (fieldValue !== null && !['string', 'number', 'boolean'].includes(valueType)) { throw new RuleBuilderError( diff --git a/x-pack/plugins/security/public/management/role_mappings/role_mappings_api_client.ts b/x-pack/plugins/security/public/management/role_mappings/role_mappings_api_client.ts index 0a88ed1da9ac3..8e8bae42d4ad8 100644 --- a/x-pack/plugins/security/public/management/role_mappings/role_mappings_api_client.ts +++ b/x-pack/plugins/security/public/management/role_mappings/role_mappings_api_client.ts @@ -47,11 +47,11 @@ export class RoleMappingsAPIClient { public async deleteRoleMappings(names: string[]): Promise { return Promise.all( - names.map(name => + names.map((name) => this.http .delete(`/internal/security/role_mapping/${encodeURIComponent(name)}`) .then(() => ({ success: true, name })) - .catch(error => ({ success: false, name, error })) + .catch((error) => ({ success: false, name, error })) ) ); } diff --git a/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.tsx b/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.tsx index 5802c3444e85f..d0bc96b4fcedf 100644 --- a/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.tsx @@ -192,9 +192,7 @@ export class RoleMappingsGridPage extends Component { id="xpack.security.management.roleMappings.roleMappingTableLoadingMessage" defaultMessage="Loading role mappings…" /> - ) : ( - undefined - ); + ) : undefined; const sorting = { sort: { @@ -222,7 +220,7 @@ export class RoleMappingsGridPage extends Component { roleMappingsAPI={this.props.roleMappingsAPI} notifications={this.props.notifications} > - {deleteRoleMappingsPrompt => { + {(deleteRoleMappingsPrompt) => { return ( deleteRoleMappingsPrompt(selectedItems, this.onRoleMappingsDeleted)} @@ -240,9 +238,7 @@ export class RoleMappingsGridPage extends Component { ); }} - ) : ( - undefined - ), + ) : undefined, toolsRight: ( { } const roleLinks = assignedRoleNames.map((rolename, index) => { const role: Role | string = - this.state.roles?.find(r => r.name === rolename) ?? rolename; + this.state.roles?.find((r) => r.name === rolename) ?? rolename; return ; }); @@ -386,7 +382,7 @@ export class RoleMappingsGridPage extends Component { roleMappingsAPI={this.props.roleMappingsAPI} notifications={this.props.notifications} > - {deleteRoleMappingPrompt => { + {(deleteRoleMappingPrompt) => { return ( (null); useEffect(() => { userAPIClient.getUsers().then( - users => setUserNames(users.map(user => user.username)), - err => fatalErrors.add(err) + (users) => setUserNames(users.map((user) => user.username)), + (err) => fatalErrors.add(err) ); }, [fatalErrors, userAPIClient]); @@ -143,7 +143,7 @@ function usePrivileges( ]).then( ([kibanaPrivileges, builtInESPrivileges]) => setPrivileges([kibanaPrivileges, builtInESPrivileges]), - err => fatalErrors.add(err) + (err) => fatalErrors.add(err) ); }, [privilegesAPIClient, fatalErrors]); @@ -170,7 +170,7 @@ function useRole( } as Role); rolePromise - .then(fetchedRole => { + .then((fetchedRole) => { if (action === 'clone' && checkIfRoleReserved(fetchedRole)) { backToRoleList(); return; @@ -225,8 +225,8 @@ function useSpaces(http: HttpStart, fatalErrors: FatalErrorsSetup, spacesEnabled const [spaces, setSpaces] = useState(null); useEffect(() => { (spacesEnabled ? http.get('/api/spaces/space') : Promise.resolve([])).then( - fetchedSpaces => setSpaces(fetchedSpaces), - err => fatalErrors.add(err) + (fetchedSpaces) => setSpaces(fetchedSpaces), + (err) => fatalErrors.add(err) ); }, [http, fatalErrors, spacesEnabled]); @@ -255,7 +255,7 @@ function useFeatures( fatalErrors.add(err); }) - .then(retrievedFeatures => { + .then((retrievedFeatures) => { setFeatures(retrievedFeatures); }); }, [fatalErrors, getFeatures]); @@ -380,9 +380,7 @@ export const EditRolePage: FunctionComponent = ({ id="xpack.security.management.editRole.roleNameFormRowHelpText" defaultMessage="A role's name cannot be changed once it has been created." /> - ) : ( - undefined - ) + ) : undefined } {...validator.validateRoleName(role)} > diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/cluster_privileges.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/cluster_privileges.tsx index 54be04ade370e..0041e63da1fba 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/cluster_privileges.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/cluster_privileges.tsx @@ -24,11 +24,11 @@ export class ClusterPrivileges extends Component { public buildComboBox = (items: string[]) => { const role = this.props.role; - const options = items.map(i => ({ + const options = items.map((i) => ({ label: i, })); - const selectedOptions = (role.elasticsearch.cluster || []).map(k => ({ label: k })); + const selectedOptions = (role.elasticsearch.cluster || []).map((k) => ({ label: k })); return ( diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/elasticsearch_privileges.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/elasticsearch_privileges.tsx index 96249ccf3ff87..46e0183b2f38c 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/elasticsearch_privileges.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/elasticsearch_privileges.tsx @@ -133,12 +133,12 @@ export class ElasticsearchPrivileges extends Component { ) : undefined } - options={this.props.runAsUsers.map(username => ({ + options={this.props.runAsUsers.map((username) => ({ id: username, label: username, isGroupLabelOption: false, }))} - selectedOptions={this.props.role.elasticsearch.run_as.map(u => ({ label: u }))} + selectedOptions={this.props.role.elasticsearch.run_as.map((u) => ({ label: u }))} onCreateOption={this.onCreateRunAsOption} onChange={this.onRunAsUserChange} isDisabled={!editable} diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privilege_form.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privilege_form.tsx index 32e8a558ecbc6..ed5ade0d23bf3 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privilege_form.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privilege_form.tsx @@ -198,9 +198,7 @@ export class IndexPrivilegeForm extends Component { id="xpack.security.management.editRoles.indexPrivilegeForm.grantedFieldsFormRowHelpText" defaultMessage="If no fields are granted, then users assigned to this role will not be able to see any data for this index." /> - ) : ( - undefined - ) + ) : undefined } > diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privileges.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privileges.tsx index 1157640ca57a7..e4a2bbd260deb 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privileges.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/es/index_privileges.tsx @@ -147,14 +147,14 @@ export class IndexPrivileges extends Component { return; } - const patterns = privileges.map(index => index.names.join(',')); + const patterns = privileges.map((index) => index.names.join(',')); const cachedPatterns = Object.keys(this.state.availableFields); const patternsToFetch = _.difference(patterns, cachedPatterns); const fetchRequests = patternsToFetch.map(this.loadFieldsForPattern); - Promise.all(fetchRequests).then(response => { + Promise.all(fetchRequests).then((response) => { this.setState({ availableFields: { ...this.state.availableFields, diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/__fixtures__/index.ts b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/__fixtures__/index.ts index 440ed78f944ba..9df50b198bde0 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/__fixtures__/index.ts +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/__fixtures__/index.ts @@ -19,7 +19,7 @@ import { SubFeatureForm } from '../sub_feature_form'; export function getDisplayedFeaturePrivileges(wrapper: ReactWrapper) { const allExpanderButtons = findTestSubject(wrapper, 'expandFeaturePrivilegeRow'); - allExpanderButtons.forEach(button => button.simulate('click')); + allExpanderButtons.forEach((button) => button.simulate('click')); // each expanded row renders its own `EuiTableRow`, so there are 2 rows // for each feature: one for the primary feature privilege, and one for the sub privilege form diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/change_all_privileges.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/change_all_privileges.tsx index 5d7b13acf79da..10aa59083dff6 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/change_all_privileges.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/change_all_privileges.tsx @@ -41,7 +41,7 @@ export class ChangeAllPrivilegesControl extends Component { ); - const items = this.props.privileges.map(privilege => { + const items = this.props.privileges.map((privilege) => { return ( { }; describe('FeatureTable', () => { - [true, false].forEach(canCustomizeSubFeaturePrivileges => { + [true, false].forEach((canCustomizeSubFeaturePrivileges) => { describe(`with sub feature privileges ${ canCustomizeSubFeaturePrivileges ? 'allowed' : 'disallowed' }`, () => { @@ -312,7 +312,7 @@ describe('FeatureTable', () => { canCustomizeSubFeaturePrivileges: true, }); - kibanaFeatures.forEach(feature => { + kibanaFeatures.forEach((feature) => { const rowExpander = findTestSubject(wrapper, `expandFeaturePrivilegeRow-${feature.id}`); if (!feature.subFeatures || feature.subFeatures.length === 0) { expect(rowExpander).toHaveLength(0); @@ -345,9 +345,7 @@ describe('FeatureTable', () => { expect(wrapper.find(FeatureTableExpandedRow)).toHaveLength(0); - findTestSubject(wrapper, 'expandFeaturePrivilegeRow') - .first() - .simulate('click'); + findTestSubject(wrapper, 'expandFeaturePrivilegeRow').first().simulate('click'); expect(wrapper.find(FeatureTableExpandedRow)).toHaveLength(1); }); diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table.tsx index 4610da95e9649..0776f2af2ddd7 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table.tsx @@ -78,7 +78,7 @@ export class FeatureTable extends Component { return 0; }) - .map(feature => { + .map((feature) => { return { featureId: feature.id, feature, @@ -98,7 +98,7 @@ export class FeatureTable extends Component { ...acc, [featureId]: ( f.id === featureId)!} + feature={featurePrivileges.find((f) => f.id === featureId)!} privilegeIndex={this.props.privilegeIndex} onChange={this.props.onChange} privilegeCalculator={this.props.privilegeCalculator} @@ -208,7 +208,7 @@ export class FeatureTable extends Component { this.props.privilegeIndex ); - const options = primaryFeaturePrivileges.map(privilege => { + const options = primaryFeaturePrivileges.map((privilege) => { return { id: `${feature.id}_${privilege.id}`, label: privilege.name, @@ -268,7 +268,7 @@ export class FeatureTable extends Component { private toggleExpandedFeature = (featureId: string) => { if (this.state.expandedFeatures.includes(featureId)) { this.setState({ - expandedFeatures: this.state.expandedFeatures.filter(ef => ef !== featureId), + expandedFeatures: this.state.expandedFeatures.filter((ef) => ef !== featureId), }); } else { this.setState({ diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table_expanded_row.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table_expanded_row.tsx index fb302c2269485..ca73c4d183f23 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table_expanded_row.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/feature_table_expanded_row.tsx @@ -31,13 +31,13 @@ export const FeatureTableExpandedRow = ({ const [isCustomizing, setIsCustomizing] = useState(() => { return feature .getMinimalFeaturePrivileges() - .some(p => selectedFeaturePrivileges.includes(p.id)); + .some((p) => selectedFeaturePrivileges.includes(p.id)); }); useEffect(() => { const hasMinimalFeaturePrivilegeSelected = feature .getMinimalFeaturePrivileges() - .some(p => selectedFeaturePrivileges.includes(p.id)); + .some((p) => selectedFeaturePrivileges.includes(p.id)); if (!hasMinimalFeaturePrivilegeSelected && isCustomizing) { setIsCustomizing(false); @@ -75,7 +75,7 @@ export const FeatureTableExpandedRow = ({ } /> - {feature.getSubFeatures().map(subFeature => { + {feature.getSubFeatures().map((subFeature) => { return ( onChange(feature.id, updatedPrivileges)} + onChange={(updatedPrivileges) => onChange(feature.id, updatedPrivileges)} selectedFeaturePrivileges={selectedFeaturePrivileges} disabled={disabled || !isCustomizing} /> diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.test.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.test.tsx index ba7eff601f4c1..ced90e24b9c72 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.test.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.test.tsx @@ -27,7 +27,7 @@ const createRole = (kibana: Role['kibana'] = []): Role => { }; const featureId = 'with_sub_features'; -const subFeature = kibanaFeatures.find(kf => kf.id === featureId)!.subFeatures[0]; +const subFeature = kibanaFeatures.find((kf) => kf.id === featureId)!.subFeatures[0]; const securedSubFeature = new SecuredSubFeature(subFeature.toRaw()); describe('SubFeatureForm', () => { @@ -57,8 +57,8 @@ describe('SubFeatureForm', () => { const checkboxes = wrapper.find(EuiCheckbox); const buttonGroups = wrapper.find(EuiButtonGroup); - expect(checkboxes.everyWhere(checkbox => checkbox.props().disabled === true)).toBe(true); - expect(buttonGroups.everyWhere(checkbox => checkbox.props().isDisabled === true)).toBe(true); + expect(checkboxes.everyWhere((checkbox) => checkbox.props().disabled === true)).toBe(true); + expect(buttonGroups.everyWhere((checkbox) => checkbox.props().isDisabled === true)).toBe(true); }); it('fires onChange when an independent privilege is selected', () => { diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.tsx index d4b6721ddad05..5432a50c1f0df 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table/sub_feature_form.tsx @@ -64,12 +64,14 @@ export const SubFeatureForm = (props: Props) => { id={`${props.featureId}_${privilege.id}`} label={privilege.name} data-test-subj="independentSubFeaturePrivilegeControl" - onChange={e => { + onChange={(e) => { const { checked } = e.target; if (checked) { props.onChange([...props.selectedFeaturePrivileges, privilege.id]); } else { - props.onChange(props.selectedFeaturePrivileges.filter(sp => sp !== privilege.id)); + props.onChange( + props.selectedFeaturePrivileges.filter((sp) => sp !== privilege.id) + ); } }} checked={isGranted} @@ -116,10 +118,10 @@ export const SubFeatureForm = (props: Props) => { options={options} idSelected={firstSelectedPrivilege?.id ?? NO_PRIVILEGE_VALUE} isDisabled={props.disabled} - onChange={selectedPrivilegeId => { + onChange={(selectedPrivilegeId) => { // Deselect all privileges which belong to this mutually-exclusive group const privilegesWithoutGroupEntries = props.selectedFeaturePrivileges.filter( - sp => !privilegeGroup.privileges.some(privilege => privilege.id === sp) + (sp) => !privilegeGroup.privileges.some((privilege) => privilege.id === sp) ); // fire on-change with the newly selected privilege if (selectedPrivilegeId === NO_PRIVILEGE_VALUE) { diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table_cell/feature_table_cell.test.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table_cell/feature_table_cell.test.tsx index 316818e4deed3..155e41baeba1e 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table_cell/feature_table_cell.test.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/feature_table_cell/feature_table_cell.test.tsx @@ -41,12 +41,7 @@ describe('FeatureTableCell', () => { ); expect(wrapper.text()).toMatchInlineSnapshot(`"Test Feature "`); - expect( - wrapper - .find(EuiIcon) - .first() - .props() - ).toMatchObject({ + expect(wrapper.find(EuiIcon).first().props()).toMatchObject({ type: feature.icon, }); expect(wrapper.find(EuiIconTip).props().content).toMatchInlineSnapshot(` diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.test.ts b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.test.ts index edf2af918fd04..53bebf6f5bb93 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.test.ts +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.test.ts @@ -515,10 +515,10 @@ describe('PrivilegeFormCalculator', () => { ]); const feature = kibanaPrivileges.getSecuredFeature('with_sub_features'); - const coolSubFeature = feature.getSubFeatures().find(sf => sf.name === 'Cool Sub Feature')!; + const coolSubFeature = feature.getSubFeatures().find((sf) => sf.name === 'Cool Sub Feature')!; const subFeatureGroup = coolSubFeature .getPrivilegeGroups() - .find(pg => pg.groupType === 'mutually_exclusive')!; + .find((pg) => pg.groupType === 'mutually_exclusive')!; const calculator = new PrivilegeFormCalculator(kibanaPrivileges, role); expect( @@ -543,10 +543,10 @@ describe('PrivilegeFormCalculator', () => { ]); const feature = kibanaPrivileges.getSecuredFeature('with_sub_features'); - const coolSubFeature = feature.getSubFeatures().find(sf => sf.name === 'Cool Sub Feature')!; + const coolSubFeature = feature.getSubFeatures().find((sf) => sf.name === 'Cool Sub Feature')!; const subFeatureGroup = coolSubFeature .getPrivilegeGroups() - .find(pg => pg.groupType === 'mutually_exclusive')!; + .find((pg) => pg.groupType === 'mutually_exclusive')!; const calculator = new PrivilegeFormCalculator(kibanaPrivileges, role); expect( @@ -573,10 +573,10 @@ describe('PrivilegeFormCalculator', () => { ]); const feature = kibanaPrivileges.getSecuredFeature('with_sub_features'); - const coolSubFeature = feature.getSubFeatures().find(sf => sf.name === 'Cool Sub Feature')!; + const coolSubFeature = feature.getSubFeatures().find((sf) => sf.name === 'Cool Sub Feature')!; const subFeatureGroup = coolSubFeature .getPrivilegeGroups() - .find(pg => pg.groupType === 'mutually_exclusive')!; + .find((pg) => pg.groupType === 'mutually_exclusive')!; const calculator = new PrivilegeFormCalculator(kibanaPrivileges, role); expect( diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.ts b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.ts index 8cff37f4bd4b0..87aabcb6fbf63 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.ts +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_form_calculator/privilege_form_calculator.ts @@ -27,7 +27,7 @@ export class PrivilegeFormCalculator { const entry = this.role.kibana[privilegeIndex]; const basePrivileges = this.kibanaPrivileges.getBasePrivileges(entry); - return basePrivileges.find(bp => entry.base.includes(bp.id)); + return basePrivileges.find((bp) => entry.base.includes(bp.id)); } /** @@ -67,7 +67,7 @@ export class PrivilegeFormCalculator { this.role.kibana[privilegeIndex], ]); - return feature.getSubFeaturePrivileges().some(sfp => { + return feature.getSubFeaturePrivileges().some((sfp) => { const isGranted = formPrivileges.grantsPrivilege(sfp); const isGrantedByDisplayedPrimary = displayedPrimary?.grantsPrivilege(sfp) ?? isGranted; @@ -90,7 +90,7 @@ export class PrivilegeFormCalculator { return feature .getPrimaryFeaturePrivileges({ includeMinimalFeaturePrivileges: true }) - .find(fp => { + .find((fp) => { return selectedFeaturePrivileges.includes(fp.id) || basePrivilege?.grantsPrivilege(fp); }); } @@ -112,7 +112,7 @@ export class PrivilegeFormCalculator { const feature = this.kibanaPrivileges.getSecuredFeature(featureId); const subFeaturePrivilege = feature .getSubFeaturePrivileges() - .find(ap => ap.id === privilegeId)!; + .find((ap) => ap.id === privilegeId)!; const assignedPrivileges = this.kibanaPrivileges.createCollectionFromRoleKibanaPrivileges([ kibanaPrivilege, @@ -138,7 +138,7 @@ export class PrivilegeFormCalculator { kibanaPrivilege, ]); - return subFeatureGroup.privileges.find(p => { + return subFeatureGroup.privileges.find((p) => { return assignedPrivileges.grantsPrivilege(p); }); } @@ -155,7 +155,7 @@ export class PrivilegeFormCalculator { return feature .getPrimaryFeaturePrivileges({ includeMinimalFeaturePrivileges: true }) - .some(apfp => selectedFeaturePrivileges.includes(apfp.id)); + .some((apfp) => selectedFeaturePrivileges.includes(apfp.id)); } /** @@ -184,8 +184,8 @@ export class PrivilegeFormCalculator { const startingPrivileges = feature .getSubFeaturePrivileges() - .filter(ap => primary.grantsPrivilege(ap)) - .map(p => p.id); + .filter((ap) => primary.grantsPrivilege(ap)) + .map((p) => p.id); nextPrivileges.push(primary.getMinimalPrivilegeId(), ...startingPrivileges); } else { @@ -216,14 +216,14 @@ export class PrivilegeFormCalculator { const hasAssignedBasePrivileges = this.kibanaPrivileges .getBasePrivileges(entry) - .some(base => entry.base.includes(base.id)); + .some((base) => entry.base.includes(base.id)); const featuresWithDirectlyAssignedPrivileges = this.kibanaPrivileges .getSecuredFeatures() - .filter(feature => + .filter((feature) => feature .getAllPrivileges() - .some(privilege => entry.feature[feature.id]?.includes(privilege.id)) + .some((privilege) => entry.feature[feature.id]?.includes(privilege.id)) ); const hasSupersededBasePrivileges = @@ -231,15 +231,15 @@ export class PrivilegeFormCalculator { this.kibanaPrivileges .getBasePrivileges(entry) .some( - privilege => + (privilege) => globalPrivileges.grantsPrivilege(privilege) && !formPrivileges.grantsPrivilege(privilege) ); - const hasSupersededFeaturePrivileges = featuresWithDirectlyAssignedPrivileges.some(feature => + const hasSupersededFeaturePrivileges = featuresWithDirectlyAssignedPrivileges.some((feature) => feature .getAllPrivileges() - .some(fp => globalPrivileges.grantsPrivilege(fp) && !formPrivileges.grantsPrivilege(fp)) + .some((fp) => globalPrivileges.grantsPrivilege(fp) && !formPrivileges.grantsPrivilege(fp)) ); return hasSupersededBasePrivileges || hasSupersededFeaturePrivileges; @@ -270,12 +270,12 @@ export class PrivilegeFormCalculator { const selectedFeaturePrivileges = this.getSelectedFeaturePrivileges(featureId, privilegeIndex); - return feature.getPrimaryFeaturePrivileges().find(fp => { + return feature.getPrimaryFeaturePrivileges().find((fp) => { const correspondingMinimalPrivilegeId = fp.getMinimalPrivilegeId(); const correspendingMinimalPrivilege = feature .getMinimalFeaturePrivileges() - .find(mp => mp.id === correspondingMinimalPrivilegeId)!; + .find((mp) => mp.id === correspondingMinimalPrivilegeId)!; // There are two cases where the minimal privileges aren't available: // 1. The feature has no registered sub-features @@ -298,6 +298,6 @@ export class PrivilegeFormCalculator { } private locateGlobalPrivilege(role: Role) { - return role.kibana.find(entry => isGlobalPrivilegeDefinition(entry)); + return role.kibana.find((entry) => isGlobalPrivilegeDefinition(entry)); } } diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/__fixtures__/index.ts b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/__fixtures__/index.ts index 63b38b6967575..b920e7b696375 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/__fixtures__/index.ts +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/__fixtures__/index.ts @@ -32,7 +32,7 @@ export function getDisplayedFeaturePrivileges( role: Role ): DisplayedFeaturePrivileges { const allExpanderButtons = findTestSubject(wrapper, 'expandPrivilegeSummaryRow'); - allExpanderButtons.forEach(button => button.simulate('click')); + allExpanderButtons.forEach((button) => button.simulate('click')); // each expanded row renders its own `EuiTableRow`, so there are 2 rows // for each feature: one for the primary feature privilege, and one for the sub privilege form @@ -81,7 +81,7 @@ function getDisplayedSubFeaturePrivileges( displayedFeatures[feature.id] = displayedFeatures[feature.id] ?? {}; - subFeatureEntries.forEach(subFeatureEntry => { + subFeatureEntries.forEach((subFeatureEntry) => { const subFeatureName = findTestSubject(subFeatureEntry, 'subFeatureName').text(); const entryElements = findTestSubject(subFeatureEntry as ReactWrapper, 'entry', '|='); diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_calculator.ts b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_calculator.ts index 27ed8c443045a..5ad0f6752b1cd 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_calculator.ts +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_calculator.ts @@ -32,7 +32,7 @@ export class PrivilegeSummaryCalculator { const effectiveSubPrivileges = feature .getSubFeaturePrivileges() - .filter(ap => assignedPrivileges.grantsPrivilege(ap)); + .filter((ap) => assignedPrivileges.grantsPrivilege(ap)); const hasCustomizedSubFeaturePrivileges = this.hasCustomizedSubFeaturePrivileges( feature, @@ -45,7 +45,7 @@ export class PrivilegeSummaryCalculator { [feature.id]: { primary: displayedPrimaryFeaturePrivilege, hasCustomizedSubFeaturePrivileges, - subFeature: effectiveSubPrivileges.map(p => p.id), + subFeature: effectiveSubPrivileges.map((p) => p.id), }, }; }, {} as EffectiveFeaturePrivileges); @@ -58,7 +58,7 @@ export class PrivilegeSummaryCalculator { ) { const formPrivileges = this.collectAssignedPrivileges(entry); - return feature.getSubFeaturePrivileges().some(sfp => { + return feature.getSubFeaturePrivileges().some((sfp) => { const isGranted = formPrivileges.grantsPrivilege(sfp); const isGrantedByDisplayedPrimary = displayedPrimaryFeaturePrivilege?.grantsPrivilege(sfp) ?? isGranted; @@ -77,11 +77,11 @@ export class PrivilegeSummaryCalculator { const hasMinimalPrivileges = feature.subFeatures.length > 0; - const effectivePrivilege = primaryFeaturePrivileges.find(pfp => { + const effectivePrivilege = primaryFeaturePrivileges.find((pfp) => { const isPrimaryGranted = assignedPrivileges.grantsPrivilege(pfp); if (!isPrimaryGranted && hasMinimalPrivileges) { const correspondingMinimal = minimalPrimaryFeaturePrivileges.find( - mpfp => mpfp.id === pfp.getMinimalPrivilegeId() + (mpfp) => mpfp.id === pfp.getMinimalPrivilegeId() )!; return assignedPrivileges.grantsPrivilege(correspondingMinimal); @@ -104,6 +104,6 @@ export class PrivilegeSummaryCalculator { } private locateGlobalPrivilege(role: Role) { - return role.kibana.find(entry => isGlobalPrivilegeDefinition(entry)); + return role.kibana.find((entry) => isGlobalPrivilegeDefinition(entry)); } } diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_expanded_row.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_expanded_row.tsx index 3283f7a58a27c..d7483e840ec7e 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_expanded_row.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_expanded_row.tsx @@ -18,7 +18,7 @@ interface Props { export const PrivilegeSummaryExpandedRow = (props: Props) => { return ( - {props.feature.getSubFeatures().map(subFeature => { + {props.feature.getSubFeatures().map((subFeature) => { return ( @@ -107,7 +107,7 @@ export const PrivilegeSummaryExpandedRow = (props: Props) => { privilegeGroup: SubFeaturePrivilegeGroup, index: number ) { - const firstSelectedPrivilege = privilegeGroup.privileges.find(p => + const firstSelectedPrivilege = privilegeGroup.privileges.find((p) => effectiveSubFeaturePrivileges.includes(p.id) )?.name; diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.test.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.test.tsx index 0498f099b536b..502868a509f91 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.test.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.test.tsx @@ -83,7 +83,7 @@ const expectNoPrivileges = (displayedPrivileges: any, expectSubFeatures: boolean }; describe('PrivilegeSummaryTable', () => { - [true, false].forEach(allowSubFeaturePrivileges => { + [true, false].forEach((allowSubFeaturePrivileges) => { describe(`when sub feature privileges are ${ allowSubFeaturePrivileges ? 'allowed' : 'disallowed' }`, () => { diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.tsx index e04ca36b6d193..4b5169de3dfc3 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/privilege_summary_table.tsx @@ -43,7 +43,7 @@ export const PrivilegeSummaryTable = (props: Props) => { const toggleExpandedFeature = (featureId: string) => { if (expandedFeatures.includes(featureId)) { - setExpandedFeatures(expandedFeatures.filter(ef => ef !== featureId)); + setExpandedFeatures(expandedFeatures.filter((ef) => ef !== featureId)); } else { setExpandedFeatures([...expandedFeatures, featureId]); } @@ -88,7 +88,7 @@ export const PrivilegeSummaryTable = (props: Props) => { } return 0; }); - const privilegeColumns = rawKibanaPrivileges.map(entry => { + const privilegeColumns = rawKibanaPrivileges.map((entry) => { const key = getColumnKey(entry); return { name: , @@ -140,7 +140,7 @@ export const PrivilegeSummaryTable = (props: Props) => { }; }, {} as Record); - const items = props.kibanaPrivileges.getSecuredFeatures().map(feature => { + const items = props.kibanaPrivileges.getSecuredFeatures().map((feature) => { return { feature, featureId: feature.id, @@ -153,7 +153,7 @@ export const PrivilegeSummaryTable = (props: Props) => { columns={columns} items={items} itemId="featureId" - rowProps={record => { + rowProps={(record) => { return { 'data-test-subj': `summaryTableRow-${record.featureId}`, }; @@ -164,7 +164,7 @@ export const PrivilegeSummaryTable = (props: Props) => { [featureId]: ( p[featureId])} + effectiveFeaturePrivileges={Object.values(privileges).map((p) => p[featureId])} /> ), }; diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/space_column_header.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/space_column_header.tsx index 8ed9bb449b595..24ac0022b12af 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/space_column_header.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/privilege_summary/space_column_header.tsx @@ -20,9 +20,9 @@ const SPACES_DISPLAY_COUNT = 4; export const SpaceColumnHeader = (props: Props) => { const isGlobal = isGlobalPrivilegeDefinition(props.entry); - const entrySpaces = props.entry.spaces.map(spaceId => { + const entrySpaces = props.entry.spaces.map((spaceId) => { return ( - props.spaces.find(s => s.id === spaceId) ?? { + props.spaces.find((s) => s.id === spaceId) ?? { id: spaceId, name: spaceId, disabledFeatures: [], @@ -31,7 +31,7 @@ export const SpaceColumnHeader = (props: Props) => { }); return (
    - {entrySpaces.slice(0, SPACES_DISPLAY_COUNT).map(space => { + {entrySpaces.slice(0, SPACES_DISPLAY_COUNT).map((space) => { return ( {' '} @@ -43,7 +43,7 @@ export const SpaceColumnHeader = (props: Props) => { />
    s.id !== '*')} + spaces={props.spaces.filter((s) => s.id !== '*')} buttonText={i18n.translate( 'xpack.security.management.editRole.spacePrivilegeMatrix.showAllSpacesLink', { diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/privilege_selector.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/privilege_selector.tsx index bda0227372c09..493ae290cac5e 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/privilege_selector.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/privilege_selector.tsx @@ -31,7 +31,7 @@ export class PrivilegeSelector extends Component { } options.push( - ...availablePrivileges.map(p => ({ + ...availablePrivileges.map((p) => ({ value: p, text: p, })) diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.tsx index d68d43e8089c7..34b4db89623bb 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.tsx @@ -83,7 +83,7 @@ export class SimplePrivilegeSection extends Component { {reservedPrivileges.length > 0 ? ( ({ label: rp }))} + selectedOptions={reservedPrivileges.map((rp) => ({ label: rp }))} isDisabled /> ) : ( @@ -215,7 +215,7 @@ export class SimplePrivilegeSection extends Component { } onChange={this.onFeaturePrivilegeChange} onChangeAll={this.onChangeAllFeaturePrivileges} - privilegeIndex={this.props.role.kibana.findIndex(k => + privilegeIndex={this.props.role.kibana.findIndex((k) => isGlobalPrivilegeDefinition(k) )} canCustomizeSubFeaturePrivileges={this.props.canCustomizeSubFeaturePrivileges} @@ -248,7 +248,7 @@ export class SimplePrivilegeSection extends Component { if (privilege === NO_PRIVILEGE_VALUE) { // Remove global entry if no privilege value - role.kibana = role.kibana.filter(entry => !isGlobalPrivilegeDefinition(entry)); + role.kibana = role.kibana.filter((entry) => !isGlobalPrivilegeDefinition(entry)); } else if (privilege === CUSTOM_PRIVILEGE_VALUE) { // Remove base privilege if customizing feature privileges form.base = []; @@ -280,7 +280,7 @@ export class SimplePrivilegeSection extends Component { const form = this.locateGlobalPrivilege(role) || this.createGlobalPrivilegeEntry(role); if (privileges.length > 0) { - this.props.kibanaPrivileges.getSecuredFeatures().forEach(feature => { + this.props.kibanaPrivileges.getSecuredFeatures().forEach((feature) => { form.feature[feature.id] = [...privileges]; }); } else { @@ -292,7 +292,7 @@ export class SimplePrivilegeSection extends Component { private maybeRenderSpacePrivilegeWarning = () => { const kibanaPrivileges = this.props.role.kibana; const hasSpacePrivileges = kibanaPrivileges.some( - privilege => !isGlobalPrivilegeDefinition(privilege) + (privilege) => !isGlobalPrivilegeDefinition(privilege) ); if (hasSpacePrivileges) { @@ -306,12 +306,12 @@ export class SimplePrivilegeSection extends Component { }; private locateGlobalPrivilegeIndex = (role: Role) => { - return role.kibana.findIndex(privileges => isGlobalPrivilegeDefinition(privileges)); + return role.kibana.findIndex((privileges) => isGlobalPrivilegeDefinition(privileges)); }; private locateGlobalPrivilege = (role: Role) => { const spacePrivileges = role.kibana; - return spacePrivileges.find(privileges => isGlobalPrivilegeDefinition(privileges)); + return spacePrivileges.find((privileges) => isGlobalPrivilegeDefinition(privileges)); }; private createGlobalPrivilegeEntry(role: Role): RoleKibanaPrivilege { diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_display.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_display.tsx index 93f1d9bba460d..7b5d8d8c1ed27 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_display.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_display.tsx @@ -40,7 +40,7 @@ function getDisplayValue(privilege: string | string[] | undefined) { if (isPrivilegeMissing) { displayValue = ; } else { - displayValue = privileges.map(p => _.capitalize(p)).join(', '); + displayValue = privileges.map((p) => _.capitalize(p)).join(', '); } return displayValue; diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.test.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.test.tsx index 968730181fe10..32eed6c878016 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.test.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.test.tsx @@ -218,10 +218,7 @@ describe('PrivilegeSpaceForm', () => { /> ); - wrapper - .find(SpaceSelector) - .props() - .onChange(['*']); + wrapper.find(SpaceSelector).props().onChange(['*']); wrapper.update(); diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.tsx index 4e9e02bb531f1..c457401196ba1 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_form.tsx @@ -452,8 +452,8 @@ export class PrivilegeSpaceForm extends Component { // remove any spaces that no longer exist if (!this.isDefiningGlobalPrivilege()) { - form.spaces = form.spaces.filter(spaceId => - this.props.spaces.find(space => space.id === spaceId) + form.spaces = form.spaces.filter((spaceId) => + this.props.spaces.find((space) => space.id === spaceId) ); } @@ -532,10 +532,10 @@ export class PrivilegeSpaceForm extends Component { if (privileges.length === 0) { entry.feature = {}; } else { - this.props.kibanaPrivileges.getSecuredFeatures().forEach(feature => { + this.props.kibanaPrivileges.getSecuredFeatures().forEach((feature) => { const nextFeaturePrivilege = feature .getPrimaryFeaturePrivileges() - .find(pfp => privileges.includes(pfp.id)); + .find((pfp) => privileges.includes(pfp.id)); if (nextFeaturePrivilege) { entry.feature[feature.id] = [nextFeaturePrivilege.id]; } diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.test.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.test.tsx index b1c7cb4b631e6..5530d9964f8cd 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.test.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.test.tsx @@ -176,7 +176,7 @@ const getTableFromComponent = ( return [ ...acc, { - spaces: spacesBadge.map(badge => badge.text().trim()), + spaces: spacesBadge.map((badge) => badge.text().trim()), privileges: { summary: privilegesDisplay.text().trim(), overridden: diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.tsx index 30a275876fdc7..585c07c2e834f 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/privilege_space_table.tsx @@ -78,8 +78,8 @@ export class PrivilegeSpaceTable extends Component { const rows: TableRow[] = spacePrivileges.map((spacePrivs, privilegeIndex) => { const spaces = spacePrivs.spaces.map( - spaceId => - displaySpaces.find(space => space.id === spaceId) || { + (spaceId) => + displaySpaces.find((space) => space.id === spaceId) || { id: spaceId, name: spaceId, disabledFeatures: [], @@ -122,7 +122,7 @@ export class PrivilegeSpaceTable extends Component { if (record.isGlobal) { button = ( s.id !== '*')} + spaces={this.props.displaySpaces.filter((s) => s.id !== '*')} buttonText={i18n.translate( 'xpack.security.management.editRole.spacePrivilegeTable.showAllSpacesLink', { @@ -238,7 +238,7 @@ export class PrivilegeSpaceTable extends Component { 'xpack.security.management.editRole.spacePrivilegeTable.editPrivilegesLabel', { defaultMessage: `Edit privileges for the following spaces: {spaceNames}.`, - values: { spaceNames: record.spaces.map(s => s.name).join(', ') }, + values: { spaceNames: record.spaces.map((s) => s.name).join(', ') }, } )} color={'primary'} @@ -256,7 +256,7 @@ export class PrivilegeSpaceTable extends Component { 'xpack.security.management.editRole.spacePrivilegeTable.deletePrivilegesLabel', { defaultMessage: `Delete privileges for the following spaces: {spaceNames}.`, - values: { spaceNames: record.spaces.map(s => s.name).join(', ') }, + values: { spaceNames: record.spaces.map((s) => s.name).join(', ') }, } )} color={'danger'} @@ -296,7 +296,7 @@ export class PrivilegeSpaceTable extends Component { private toggleExpandSpacesGroup = (privilegeIndex: number) => { if (this.state.expandedSpacesGroups.includes(privilegeIndex)) { this.setState({ - expandedSpacesGroups: this.state.expandedSpacesGroups.filter(i => i !== privilegeIndex), + expandedSpacesGroups: this.state.expandedSpacesGroups.filter((i) => i !== privilegeIndex), }); } else { this.setState({ @@ -312,7 +312,9 @@ export class PrivilegeSpaceTable extends Component { this.props.onChange(roleCopy); this.setState({ - expandedSpacesGroups: this.state.expandedSpacesGroups.filter(i => i !== item.privilegeIndex), + expandedSpacesGroups: this.state.expandedSpacesGroups.filter( + (i) => i !== item.privilegeIndex + ), }); }; } diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_aware_privilege_section.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_aware_privilege_section.tsx index 86b09e5332792..734f7b1826723 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_aware_privilege_section.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_aware_privilege_section.tsx @@ -243,7 +243,7 @@ export class SpaceAwarePrivilegeSection extends Component { ); return this.getDisplaySpaces().filter( - displaySpace => !spacesToExclude.includes(displaySpace.id) + (displaySpace) => !spacesToExclude.includes(displaySpace.id) ); }; diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_selector.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_selector.tsx index 70790f785ad58..4344cd4b0784e 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_selector.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/space_aware_privilege_section/space_selector.tsx @@ -26,7 +26,7 @@ const spaceToOption = (space?: Space, currentSelection?: 'global' | 'spaces') => }; const spaceIdToOption = (spaces: Space[]) => (s: string) => - spaceToOption(spaces.find(space => space.id === s)); + spaceToOption(spaces.find((space) => space.id === s)); interface Props { spaces: Space[]; @@ -65,11 +65,11 @@ export class SpaceSelector extends Component { } private onChange = (selectedSpaces: EuiComboBoxOptionOption[]) => { - this.props.onChange(selectedSpaces.map(s => (s.id as string).split('spaceOption_')[1])); + this.props.onChange(selectedSpaces.map((s) => (s.id as string).split('spaceOption_')[1])); }; private getOptions = () => { - const options = this.props.spaces.map(space => + const options = this.props.spaces.map((space) => spaceToOption( space, this.props.selectedSpaceIds.includes('*') diff --git a/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.test.tsx b/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.test.tsx index 20882864645d3..9c68a097a890e 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.test.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.test.tsx @@ -62,7 +62,7 @@ describe('SpacesPopoverList', () => { }); it('renders a search box when there are 8 or more spaces', () => { - const lotsOfSpaces = [1, 2, 3, 4, 5, 6, 7, 8].map(num => ({ + const lotsOfSpaces = [1, 2, 3, 4, 5, 6, 7, 8].map((num) => ({ id: `space-${num}`, name: `Space ${num}`, disabledFeatures: [], @@ -100,10 +100,7 @@ describe('SpacesPopoverList', () => { expect(wrapper.find(EuiPopover).props().isOpen).toEqual(true); - wrapper - .find(EuiPopover) - .props() - .closePopover(); + wrapper.find(EuiPopover).props().closePopover(); wrapper.update(); diff --git a/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.tsx b/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.tsx index 63ee311f3155e..9c1a94d3d06f3 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/spaces_popover_list/spaces_popover_list.tsx @@ -104,7 +104,7 @@ export class SpacesPopoverList extends Component { let filteredSpaces = spaces; if (searchTerm) { - filteredSpaces = spaces.filter(space => { + filteredSpaces = spaces.filter((space) => { const { name, description = '' } = space; return ( name.toLowerCase().indexOf(searchTerm) >= 0 || diff --git a/x-pack/plugins/security/public/management/roles/edit_role/validate_role.test.ts b/x-pack/plugins/security/public/management/roles/edit_role/validate_role.test.ts index e9be52557bd7d..868674aec6f86 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/validate_role.test.ts +++ b/x-pack/plugins/security/public/management/roles/edit_role/validate_role.test.ts @@ -62,7 +62,7 @@ describe('validateRoleName', () => { }); const charList = `!#%^&*()+=[]{}\|';:"/,<>?`.split(''); - charList.forEach(element => { + charList.forEach((element) => { test(`it cannot support the "${element}" character`, () => { const role = { name: `role-${element}`, diff --git a/x-pack/plugins/security/public/management/roles/edit_role/validate_role.ts b/x-pack/plugins/security/public/management/roles/edit_role/validate_role.ts index 02d3061b82b96..89b16b1467776 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/validate_role.ts +++ b/x-pack/plugins/security/public/management/roles/edit_role/validate_role.ts @@ -85,7 +85,7 @@ export class RoleValidator { const areIndicesValid = role.elasticsearch.indices - .map(indexPriv => this.validateIndexPrivilege(indexPriv)) + .map((indexPriv) => this.validateIndexPrivilege(indexPriv)) .find((result: RoleValidationResult) => result.isInvalid) == null; if (areIndicesValid) { @@ -171,7 +171,7 @@ export class RoleValidator { const privileges = role.kibana || []; - const arePrivilegesValid = privileges.every(assignedPrivilege => { + const arePrivilegesValid = privileges.every((assignedPrivilege) => { return assignedPrivilege.base.length > 0 || Object.keys(assignedPrivilege.feature).length > 0; }); diff --git a/x-pack/plugins/security/public/management/roles/model/kibana_privilege.ts b/x-pack/plugins/security/public/management/roles/model/kibana_privilege.ts index 7c21a4b5c0ee6..f5c85d3d92be2 100644 --- a/x-pack/plugins/security/public/management/roles/model/kibana_privilege.ts +++ b/x-pack/plugins/security/public/management/roles/model/kibana_privilege.ts @@ -18,7 +18,7 @@ export class KibanaPrivilege { } private checkActions(knownActions: string[], candidateActions: string[]) { - const missing = candidateActions.filter(action => !knownActions.includes(action)); + const missing = candidateActions.filter((action) => !knownActions.includes(action)); const hasAllRequested = knownActions.length > 0 && candidateActions.length > 0 && missing.length === 0; diff --git a/x-pack/plugins/security/public/management/roles/model/kibana_privileges.ts b/x-pack/plugins/security/public/management/roles/model/kibana_privileges.ts index d8d75e90847e3..a1617f71a0df8 100644 --- a/x-pack/plugins/security/public/management/roles/model/kibana_privileges.ts +++ b/x-pack/plugins/security/public/management/roles/model/kibana_privileges.ts @@ -19,7 +19,7 @@ function toBasePrivilege(entry: [string, string[]]): [string, KibanaPrivilege] { function recordsToBasePrivilegeMap( record: Record ): ReadonlyMap { - return new Map(Object.entries(record).map(entry => toBasePrivilege(entry))); + return new Map(Object.entries(record).map((entry) => toBasePrivilege(entry))); } export class KibanaPrivileges { @@ -33,7 +33,7 @@ export class KibanaPrivileges { this.global = recordsToBasePrivilegeMap(rawKibanaPrivileges.global); this.spaces = recordsToBasePrivilegeMap(rawKibanaPrivileges.space); this.feature = new Map( - features.map(feature => { + features.map((feature) => { const rawPrivs = rawKibanaPrivileges.features[feature.id]; return [feature.id, new SecuredFeature(feature.toRaw(), rawPrivs)]; }) @@ -60,7 +60,7 @@ export class KibanaPrivileges { assignedPrivileges.includes(privilege.id); const privileges: KibanaPrivilege[] = roleKibanaPrivileges - .map(entry => { + .map((entry) => { const assignedBasePrivileges = this.getBasePrivileges(entry).filter( filterAssigned(entry.base) ); diff --git a/x-pack/plugins/security/public/management/roles/model/privilege_collection.ts b/x-pack/plugins/security/public/management/roles/model/privilege_collection.ts index cbbd22857666e..d023f18d39279 100644 --- a/x-pack/plugins/security/public/management/roles/model/privilege_collection.ts +++ b/x-pack/plugins/security/public/management/roles/model/privilege_collection.ts @@ -20,7 +20,7 @@ export class PrivilegeCollection { } private checkActions(knownActions: ReadonlySet, candidateActions: string[]) { - const missing = candidateActions.filter(action => !knownActions.has(action)); + const missing = candidateActions.filter((action) => !knownActions.has(action)); const hasAllRequested = knownActions.size > 0 && candidateActions.length > 0 && missing.length === 0; diff --git a/x-pack/plugins/security/public/management/roles/model/secured_feature.ts b/x-pack/plugins/security/public/management/roles/model/secured_feature.ts index 7fc466a70b984..284a85583c33c 100644 --- a/x-pack/plugins/security/public/management/roles/model/secured_feature.ts +++ b/x-pack/plugins/security/public/management/roles/model/secured_feature.ts @@ -34,7 +34,7 @@ export class SecuredFeature extends Feature { } this.securedSubFeatures = - this.config.subFeatures?.map(sf => new SecuredSubFeature(sf, actionMapping)) ?? []; + this.config.subFeatures?.map((sf) => new SecuredSubFeature(sf, actionMapping)) ?? []; this.subFeaturePrivileges = this.securedSubFeatures.reduce((acc, subFeature) => { return [...acc, ...subFeature.privilegeIterator()]; diff --git a/x-pack/plugins/security/public/management/roles/model/secured_sub_feature.ts b/x-pack/plugins/security/public/management/roles/model/secured_sub_feature.ts index 3d69e5e709bb0..f7bdd9ba520ad 100644 --- a/x-pack/plugins/security/public/management/roles/model/secured_sub_feature.ts +++ b/x-pack/plugins/security/public/management/roles/model/secured_sub_feature.ts @@ -24,7 +24,7 @@ export class SecuredSubFeature extends SubFeature { } public getPrivilegeGroups() { - return this.privilegeGroups.map(pg => new SubFeaturePrivilegeGroup(pg, this.actionMapping)); + return this.privilegeGroups.map((pg) => new SubFeaturePrivilegeGroup(pg, this.actionMapping)); } public *privilegeIterator({ @@ -34,8 +34,8 @@ export class SecuredSubFeature extends SubFeature { } = {}): IterableIterator { for (const group of this.privilegeGroups) { yield* group.privileges - .map(gp => new SubFeaturePrivilege(gp, this.actionMapping[gp.id])) - .filter(privilege => predicate(privilege, this)); + .map((gp) => new SubFeaturePrivilege(gp, this.actionMapping[gp.id])) + .filter((privilege) => predicate(privilege, this)); } } } diff --git a/x-pack/plugins/security/public/management/roles/model/sub_feature_privilege_group.ts b/x-pack/plugins/security/public/management/roles/model/sub_feature_privilege_group.ts index b437649236e27..17d899874d8ff 100644 --- a/x-pack/plugins/security/public/management/roles/model/sub_feature_privilege_group.ts +++ b/x-pack/plugins/security/public/management/roles/model/sub_feature_privilege_group.ts @@ -19,7 +19,7 @@ export class SubFeaturePrivilegeGroup { public get privileges() { return this.config.privileges.map( - p => new SubFeaturePrivilege(p, this.actionMapping[p.id] || []) + (p) => new SubFeaturePrivilege(p, this.actionMapping[p.id] || []) ); } } diff --git a/x-pack/plugins/security/public/management/roles/roles_api_client.ts b/x-pack/plugins/security/public/management/roles/roles_api_client.ts index d7e98e03a965b..50c490d2924ba 100644 --- a/x-pack/plugins/security/public/management/roles/roles_api_client.ts +++ b/x-pack/plugins/security/public/management/roles/roles_api_client.ts @@ -34,18 +34,18 @@ export class RolesAPIClient { const isPlaceholderPrivilege = (indexPrivilege: RoleIndexPrivilege) => indexPrivilege.names.length === 0; role.elasticsearch.indices = role.elasticsearch.indices.filter( - indexPrivilege => !isPlaceholderPrivilege(indexPrivilege) + (indexPrivilege) => !isPlaceholderPrivilege(indexPrivilege) ); // Remove any placeholder query entries - role.elasticsearch.indices.forEach(index => index.query || delete index.query); + role.elasticsearch.indices.forEach((index) => index.query || delete index.query); // If spaces are disabled, then do not persist any space privileges if (!spacesEnabled) { role.kibana = role.kibana.filter(isGlobalPrivilegeDefinition); } - role.kibana.forEach(kibanaPrivilege => { + role.kibana.forEach((kibanaPrivilege) => { // If a base privilege is defined, then do not persist feature privileges if (kibanaPrivilege.base.length > 0) { kibanaPrivilege.feature = {}; diff --git a/x-pack/plugins/security/public/management/roles/roles_grid/confirm_delete/confirm_delete.tsx b/x-pack/plugins/security/public/management/roles/roles_grid/confirm_delete/confirm_delete.tsx index 37eed3357241d..d1b266d2a68fe 100644 --- a/x-pack/plugins/security/public/management/roles/roles_grid/confirm_delete/confirm_delete.tsx +++ b/x-pack/plugins/security/public/management/roles/roles_grid/confirm_delete/confirm_delete.tsx @@ -71,7 +71,7 @@ export class ConfirmDelete extends Component { />

      - {rolesToDelete.map(roleName => ( + {rolesToDelete.map((roleName) => (
    • {roleName}
    • ))}
    @@ -129,7 +129,7 @@ export class ConfirmDelete extends Component { private deleteRoles = async () => { const { rolesToDelete, callback, rolesAPIClient, notifications } = this.props; const errors: string[] = []; - const deleteOperations = rolesToDelete.map(roleName => { + const deleteOperations = rolesToDelete.map((roleName) => { const deleteRoleTask = async () => { try { await rolesAPIClient.deleteRole(roleName); diff --git a/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.test.tsx b/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.test.tsx index 410d5bc9f7643..e0a7d96d1cf72 100644 --- a/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.test.tsx +++ b/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.test.tsx @@ -73,7 +73,7 @@ describe('', () => { ); const initialIconCount = wrapper.find(EuiIcon).length; - await waitForRender(wrapper, updatedWrapper => { + await waitForRender(wrapper, (updatedWrapper) => { return updatedWrapper.find(EuiIcon).length > initialIconCount; }); @@ -90,7 +90,7 @@ describe('', () => { ); const initialIconCount = wrapper.find(EuiIcon).length; - await waitForRender(wrapper, updatedWrapper => { + await waitForRender(wrapper, (updatedWrapper) => { return updatedWrapper.find(EuiIcon).length > initialIconCount; }); @@ -107,7 +107,7 @@ describe('', () => { notifications={coreMock.createStart().notifications} /> ); - await waitForRender(wrapper, updatedWrapper => { + await waitForRender(wrapper, (updatedWrapper) => { return updatedWrapper.find(PermissionDenied).length > 0; }); expect(wrapper.find(PermissionDenied)).toMatchSnapshot(); @@ -122,7 +122,7 @@ describe('', () => { ); const initialIconCount = wrapper.find(EuiIcon).length; - await waitForRender(wrapper, updatedWrapper => { + await waitForRender(wrapper, (updatedWrapper) => { return updatedWrapper.find(EuiIcon).length > initialIconCount; }); @@ -151,7 +151,7 @@ describe('', () => { ); const initialIconCount = wrapper.find(EuiIcon).length; - await waitForRender(wrapper, updatedWrapper => { + await waitForRender(wrapper, (updatedWrapper) => { return updatedWrapper.find(EuiIcon).length > initialIconCount; }); diff --git a/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.tsx b/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.tsx index 04a74a1a9b99a..4f0d7ca8621a3 100644 --- a/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.tsx +++ b/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.tsx @@ -118,7 +118,7 @@ export class RolesGridPage extends Component { {this.state.showDeleteConfirmation ? ( role.name)} + rolesToDelete={this.state.selection.map((role) => role.name)} callback={this.handleDelete} notifications={this.props.notifications} rolesAPIClient={this.props.rolesAPIClient} @@ -259,7 +259,7 @@ export class RolesGridPage extends Component { }; private getVisibleRoles = (roles: Role[], filter: string, includeReservedRoles: boolean) => { - return roles.filter(role => { + return roles.filter((role) => { const normalized = `${role.name}`.toLowerCase(); const normalizedQuery = filter.toLowerCase(); return ( diff --git a/x-pack/plugins/security/public/management/users/components/change_password_form/change_password_form.tsx b/x-pack/plugins/security/public/management/users/components/change_password_form/change_password_form.tsx index 047cad7bead81..7a97794303558 100644 --- a/x-pack/plugins/security/public/management/users/components/change_password_form/change_password_form.tsx +++ b/x-pack/plugins/security/public/management/users/components/change_password_form/change_password_form.tsx @@ -267,7 +267,7 @@ export class ChangePasswordForm extends Component { this.validateConfirmPassword(true), ]; - const firstFailure = validation.find(result => result.isInvalid); + const firstFailure = validation.find((result) => result.isInvalid); if (firstFailure) { return firstFailure; } diff --git a/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.test.tsx b/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.test.tsx index 9c5a8b0b75ead..e39a4acdaaff9 100644 --- a/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.test.tsx +++ b/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.test.tsx @@ -80,7 +80,7 @@ describe('ConfirmDeleteUsers', () => { const onCancel = jest.fn(); const apiClientMock = userAPIClientMock.create(); - apiClientMock.deleteUser.mockImplementation(user => { + apiClientMock.deleteUser.mockImplementation((user) => { if (user === 'foo') { return Promise.reject('something terrible happened'); } diff --git a/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.tsx b/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.tsx index 53acbf42273e8..a6fbc6be945c9 100644 --- a/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.tsx +++ b/x-pack/plugins/security/public/management/users/components/confirm_delete_users/confirm_delete_users.tsx @@ -58,7 +58,7 @@ export class ConfirmDeleteUsers extends Component { />

      - {usersToDelete.map(username => ( + {usersToDelete.map((username) => (
    • {username}
    • ))}
    @@ -79,7 +79,7 @@ export class ConfirmDeleteUsers extends Component { private deleteUsers = () => { const { usersToDelete, callback, userAPIClient, notifications } = this.props; const errors: string[] = []; - usersToDelete.forEach(async username => { + usersToDelete.forEach(async (username) => { try { await userAPIClient.deleteUser(username); notifications.toasts.addSuccess( diff --git a/x-pack/plugins/security/public/management/users/edit_user/edit_user_page.tsx b/x-pack/plugins/security/public/management/users/edit_user/edit_user_page.tsx index 7172ff178eb6b..49da4c66a7630 100644 --- a/x-pack/plugins/security/public/management/users/edit_user/edit_user_page.tsx +++ b/x-pack/plugins/security/public/management/users/edit_user/edit_user_page.tsx @@ -382,8 +382,8 @@ export class EditUserPage extends Component { return null; } - const hasAnyDeprecatedRolesAssigned = selectedRoles.some(selected => { - const role = roles.find(r => r.name === selected); + const hasAnyDeprecatedRolesAssigned = selectedRoles.some((selected) => { + const role = roles.find((r) => r.name === selected); return role && isRoleDeprecated(role); }); @@ -394,9 +394,7 @@ export class EditUserPage extends Component { defaultMessage="This user is assigned a deprecated role. Please migrate to a supported role." />
    - ) : ( - undefined - ); + ) : undefined; return (
    diff --git a/x-pack/plugins/security/public/management/users/users_grid/users_grid_page.tsx b/x-pack/plugins/security/public/management/users/users_grid/users_grid_page.tsx index f8882129772f7..5fd2b4ec85589 100644 --- a/x-pack/plugins/security/public/management/users/users_grid/users_grid_page.tsx +++ b/x-pack/plugins/security/public/management/users/users_grid/users_grid_page.tsx @@ -143,7 +143,7 @@ export class UsersGridPage extends Component { width: '30%', render: (rolenames: string[]) => { const roleLinks = rolenames.map((rolename, index) => { - const roleDefinition = roles?.find(role => role.name === rolename) ?? rolename; + const roleDefinition = roles?.find((role) => role.name === rolename) ?? rolename; return ; }); return
    {roleLinks}
    ; @@ -231,7 +231,7 @@ export class UsersGridPage extends Component { {showDeleteConfirmation ? ( user.username)} + usersToDelete={selection.map((user) => user.username)} callback={this.handleDelete} userAPIClient={this.props.userAPIClient} notifications={this.props.notifications} diff --git a/x-pack/plugins/security/public/nav_control/nav_control_component.tsx b/x-pack/plugins/security/public/nav_control/nav_control_component.tsx index eaa1d8dee0a11..3ddabb0dc55f8 100644 --- a/x-pack/plugins/security/public/nav_control/nav_control_component.tsx +++ b/x-pack/plugins/security/public/nav_control/nav_control_component.tsx @@ -41,7 +41,7 @@ export class SecurityNavControl extends Component { authenticatedUser: null, }; - props.user.then(authenticatedUser => { + props.user.then((authenticatedUser) => { this.setState({ authenticatedUser, }); diff --git a/x-pack/plugins/security/public/nav_control/nav_control_service.test.ts b/x-pack/plugins/security/public/nav_control/nav_control_service.test.ts index 66731cf19006d..acf62f3376b8b 100644 --- a/x-pack/plugins/security/public/nav_control/nav_control_service.test.ts +++ b/x-pack/plugins/security/public/nav_control/nav_control_service.test.ts @@ -15,7 +15,7 @@ import { mockAuthenticatedUser } from '../../common/model/authenticated_user.moc const validLicense = { isAvailable: true, - getFeature: feature => { + getFeature: (feature) => { expect(feature).toEqual('security'); return { diff --git a/x-pack/plugins/security/public/session/session_expired.test.ts b/x-pack/plugins/security/public/session/session_expired.test.ts index f5ad9cb464e3e..1ec2f772050f9 100644 --- a/x-pack/plugins/security/public/session/session_expired.test.ts +++ b/x-pack/plugins/security/public/session/session_expired.test.ts @@ -26,8 +26,8 @@ describe('#logout', () => { beforeEach(() => { window.history.pushState({}, '', CURRENT_URL); mockGetItem.mockReset(); - newUrlPromise = new Promise(resolve => { - jest.spyOn(window.location, 'assign').mockImplementation(url => { + newUrlPromise = new Promise((resolve) => { + jest.spyOn(window.location, 'assign').mockImplementation((url) => { resolve(url); }); }); diff --git a/x-pack/plugins/security/public/session/session_timeout_http_interceptor.test.ts b/x-pack/plugins/security/public/session/session_timeout_http_interceptor.test.ts index 427bdb04f9c61..40cbd00858b5f 100644 --- a/x-pack/plugins/security/public/session/session_timeout_http_interceptor.test.ts +++ b/x-pack/plugins/security/public/session/session_timeout_http_interceptor.test.ts @@ -13,7 +13,7 @@ import { createSessionTimeoutMock } from './session_timeout.mock'; const mockCurrentUrl = (url: string) => window.history.pushState({}, '', url); const setupHttp = (basePath: string) => { - const { http } = setup(injectedMetadata => { + const { http } = setup((injectedMetadata) => { injectedMetadata.getBasePath.mockReturnValue(basePath); }); return http; diff --git a/x-pack/plugins/security/public/session/unauthorized_response_http_interceptor.test.ts b/x-pack/plugins/security/public/session/unauthorized_response_http_interceptor.test.ts index fba2a2ec98146..78c82cbc3a9a6 100644 --- a/x-pack/plugins/security/public/session/unauthorized_response_http_interceptor.test.ts +++ b/x-pack/plugins/security/public/session/unauthorized_response_http_interceptor.test.ts @@ -12,7 +12,7 @@ import { UnauthorizedResponseHttpInterceptor } from './unauthorized_response_htt jest.mock('./session_expired'); const drainPromiseQueue = () => { - return new Promise(resolve => { + return new Promise((resolve) => { setImmediate(resolve); }); }; @@ -20,7 +20,7 @@ const drainPromiseQueue = () => { const mockCurrentUrl = (url: string) => window.history.pushState({}, '', url); const setupHttp = (basePath: string) => { - const { http } = setup(injectedMetadata => { + const { http } = setup((injectedMetadata) => { injectedMetadata.getBasePath.mockReturnValue(basePath); }); return http; @@ -34,7 +34,7 @@ afterEach(() => { it(`logs out 401 responses`, async () => { const http = setupHttp('/foo'); const sessionExpired = new SessionExpired(`${http.basePath}/logout`, tenant); - const logoutPromise = new Promise(resolve => { + const logoutPromise = new Promise((resolve) => { jest.spyOn(sessionExpired, 'logout').mockImplementation(() => resolve()); }); const interceptor = new UnauthorizedResponseHttpInterceptor(sessionExpired, http.anonymousPaths); diff --git a/x-pack/plugins/security/server/authentication/authenticator.ts b/x-pack/plugins/security/server/authentication/authenticator.ts index 58dea2b23e546..98342a8494e38 100644 --- a/x-pack/plugins/security/server/authentication/authenticator.ts +++ b/x-pack/plugins/security/server/authentication/authenticator.ts @@ -475,7 +475,7 @@ export class Authenticator { * @param providerType Type of the provider (`basic`, `saml`, `pki` etc.). */ isProviderTypeEnabled(providerType: string) { - return [...this.providers.values()].some(provider => provider.type === providerType); + return [...this.providers.values()].some((provider) => provider.type === providerType); } /** @@ -511,7 +511,7 @@ export class Authenticator { */ private setupHTTPAuthenticationProvider(options: AuthenticationProviderOptions) { const supportedSchemes = new Set( - this.options.config.authc.http.schemes.map(scheme => scheme.toLowerCase()) + this.options.config.authc.http.schemes.map((scheme) => scheme.toLowerCase()) ); // If `autoSchemesEnabled` is set we should allow schemes that other providers use to diff --git a/x-pack/plugins/security/server/authentication/providers/http.ts b/x-pack/plugins/security/server/authentication/providers/http.ts index 6b75ae2d48156..3e33a52cbbc6b 100644 --- a/x-pack/plugins/security/server/authentication/providers/http.ts +++ b/x-pack/plugins/security/server/authentication/providers/http.ts @@ -39,7 +39,7 @@ export class HTTPAuthenticationProvider extends BaseAuthenticationProvider { throw new Error('Supported schemes should be specified'); } this.supportedSchemes = new Set( - [...httpOptions.supportedSchemes].map(scheme => scheme.toLowerCase()) + [...httpOptions.supportedSchemes].map((scheme) => scheme.toLowerCase()) ); } diff --git a/x-pack/plugins/security/server/authentication/providers/kerberos.test.ts b/x-pack/plugins/security/server/authentication/providers/kerberos.test.ts index 6eb47cfa83e32..ca80761ee140c 100644 --- a/x-pack/plugins/security/server/authentication/providers/kerberos.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/kerberos.test.ts @@ -280,11 +280,11 @@ describe('KerberosAuthenticationProvider', () => { } describe('`login` method', () => { - defineCommonLoginAndAuthenticateTests(request => provider.login(request)); + defineCommonLoginAndAuthenticateTests((request) => provider.login(request)); }); describe('`authenticate` method', () => { - defineCommonLoginAndAuthenticateTests(request => provider.authenticate(request, null)); + defineCommonLoginAndAuthenticateTests((request) => provider.authenticate(request, null)); it('does not handle authentication via `authorization` header with non-negotiate scheme.', async () => { const request = httpServerMock.createKibanaRequest({ @@ -376,7 +376,7 @@ describe('KerberosAuthenticationProvider', () => { const request = httpServerMock.createKibanaRequest(); const tokenPair = { accessToken: 'foo', refreshToken: 'bar' }; - mockOptions.client.asScoped.mockImplementation(scopeableRequest => { + mockOptions.client.asScoped.mockImplementation((scopeableRequest) => { if (scopeableRequest?.headers.authorization === `Bearer ${tokenPair.accessToken}`) { const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( diff --git a/x-pack/plugins/security/server/authentication/providers/kerberos.ts b/x-pack/plugins/security/server/authentication/providers/kerberos.ts index c4bbe554a3da1..2540c21210bd5 100644 --- a/x-pack/plugins/security/server/authentication/providers/kerberos.ts +++ b/x-pack/plugins/security/server/authentication/providers/kerberos.ts @@ -339,7 +339,7 @@ export class KerberosAuthenticationProvider extends BaseAuthenticationProvider { private getNegotiateChallenge(error: ElasticsearchError) { const challenges = ([] as string[]).concat(error.output.headers[WWWAuthenticateHeaderName]); - const negotiateChallenge = challenges.find(challenge => + const negotiateChallenge = challenges.find((challenge) => challenge.toLowerCase().startsWith('negotiate') ); if (negotiateChallenge) { diff --git a/x-pack/plugins/security/server/authentication/providers/oidc.test.ts b/x-pack/plugins/security/server/authentication/providers/oidc.test.ts index 14fe42aac7599..2d42d90ab60b8 100644 --- a/x-pack/plugins/security/server/authentication/providers/oidc.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/oidc.test.ts @@ -464,7 +464,7 @@ describe('OIDCAuthenticationProvider', () => { const request = httpServerMock.createKibanaRequest(); const tokenPair = { accessToken: 'expired-token', refreshToken: 'valid-refresh-token' }; - mockOptions.client.asScoped.mockImplementation(scopeableRequest => { + mockOptions.client.asScoped.mockImplementation((scopeableRequest) => { if (scopeableRequest?.headers.authorization === `Bearer ${tokenPair.accessToken}`) { const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( diff --git a/x-pack/plugins/security/server/authentication/providers/pki.test.ts b/x-pack/plugins/security/server/authentication/providers/pki.test.ts index 638bb5732f3c0..28db64edd9e32 100644 --- a/x-pack/plugins/security/server/authentication/providers/pki.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/pki.test.ts @@ -241,11 +241,11 @@ describe('PKIAuthenticationProvider', () => { } describe('`login` method', () => { - defineCommonLoginAndAuthenticateTests(request => provider.login(request)); + defineCommonLoginAndAuthenticateTests((request) => provider.login(request)); }); describe('`authenticate` method', () => { - defineCommonLoginAndAuthenticateTests(request => provider.authenticate(request, null)); + defineCommonLoginAndAuthenticateTests((request) => provider.authenticate(request, null)); it('does not handle authentication via `authorization` header.', async () => { const request = httpServerMock.createKibanaRequest({ diff --git a/x-pack/plugins/security/server/authentication/providers/saml.test.ts b/x-pack/plugins/security/server/authentication/providers/saml.test.ts index ec50ac090f1e7..461ad3e38eca5 100644 --- a/x-pack/plugins/security/server/authentication/providers/saml.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/saml.test.ts @@ -835,7 +835,7 @@ describe('SAMLAuthenticationProvider', () => { realm: 'test-realm', }; - mockOptions.client.asScoped.mockImplementation(scopeableRequest => { + mockOptions.client.asScoped.mockImplementation((scopeableRequest) => { if (scopeableRequest?.headers.authorization === `Bearer ${state.accessToken}`) { const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( diff --git a/x-pack/plugins/security/server/authentication/providers/saml.ts b/x-pack/plugins/security/server/authentication/providers/saml.ts index 5c5ec49890901..3161144023c1f 100644 --- a/x-pack/plugins/security/server/authentication/providers/saml.ts +++ b/x-pack/plugins/security/server/authentication/providers/saml.ts @@ -177,8 +177,9 @@ export class SAMLAuthenticationProvider extends BaseAuthenticationProvider { this.logger.debug('Login has been successfully performed.'); } else { this.logger.debug( - `Failed to perform a login: ${authenticationResult.error && - authenticationResult.error.message}` + `Failed to perform a login: ${ + authenticationResult.error && authenticationResult.error.message + }` ); } diff --git a/x-pack/plugins/security/server/authentication/providers/token.test.ts b/x-pack/plugins/security/server/authentication/providers/token.test.ts index 7472adb30307c..92cea424e575d 100644 --- a/x-pack/plugins/security/server/authentication/providers/token.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/token.test.ts @@ -211,7 +211,7 @@ describe('TokenAuthenticationProvider', () => { const request = httpServerMock.createKibanaRequest(); const tokenPair = { accessToken: 'foo', refreshToken: 'bar' }; - mockOptions.client.asScoped.mockImplementation(scopeableRequest => { + mockOptions.client.asScoped.mockImplementation((scopeableRequest) => { if (scopeableRequest?.headers.authorization === `Bearer ${tokenPair.accessToken}`) { const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( @@ -386,7 +386,7 @@ describe('TokenAuthenticationProvider', () => { const tokenPair = { accessToken: 'foo', refreshToken: 'bar' }; const authenticationError = new errors.AuthenticationException('Some error'); - mockOptions.client.asScoped.mockImplementation(scopeableRequest => { + mockOptions.client.asScoped.mockImplementation((scopeableRequest) => { if (scopeableRequest?.headers.authorization === `Bearer ${tokenPair.accessToken}`) { const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( diff --git a/x-pack/plugins/security/server/authorization/actions/ui.ts b/x-pack/plugins/security/server/authorization/actions/ui.ts index 3dae9a47b3827..fa5bea867e9cc 100644 --- a/x-pack/plugins/security/server/authorization/actions/ui.ts +++ b/x-pack/plugins/security/server/authorization/actions/ui.ts @@ -26,7 +26,7 @@ export class UIActions { if ( uiCapabilityParts.length === 0 || uiCapabilityParts.findIndex( - part => !part || !isString(part) || !uiCapabilitiesRegex.test(part) + (part) => !part || !isString(part) || !uiCapabilitiesRegex.test(part) ) >= 0 ) { throw new Error( diff --git a/x-pack/plugins/security/server/authorization/api_authorization.test.ts b/x-pack/plugins/security/server/authorization/api_authorization.test.ts index 409f998cfe8d2..183a36274142c 100644 --- a/x-pack/plugins/security/server/authorization/api_authorization.test.ts +++ b/x-pack/plugins/security/server/authorization/api_authorization.test.ts @@ -82,7 +82,7 @@ describe('initAPIAuthorization', () => { const mockCheckPrivileges = jest.fn().mockReturnValue({ hasAllRequested: true }); mockAuthz.mode.useRbacForRequest.mockReturnValue(true); - mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation(request => { + mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation((request) => { // hapi conceals the actual "request" from us, so we make sure that the headers are passed to // "checkPrivilegesDynamicallyWithRequest" because this is what we're really concerned with expect(request.headers).toMatchObject(headers); @@ -117,7 +117,7 @@ describe('initAPIAuthorization', () => { const mockCheckPrivileges = jest.fn().mockReturnValue({ hasAllRequested: false }); mockAuthz.mode.useRbacForRequest.mockReturnValue(true); - mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation(request => { + mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation((request) => { // hapi conceals the actual "request" from us, so we make sure that the headers are passed to // "checkPrivilegesDynamicallyWithRequest" because this is what we're really concerned with expect(request.headers).toMatchObject(headers); diff --git a/x-pack/plugins/security/server/authorization/api_authorization.ts b/x-pack/plugins/security/server/authorization/api_authorization.ts index 88b3f2c6f7155..3e3ea34618da9 100644 --- a/x-pack/plugins/security/server/authorization/api_authorization.ts +++ b/x-pack/plugins/security/server/authorization/api_authorization.ts @@ -20,14 +20,14 @@ export function initAPIAuthorization( const tags = request.route.options.tags; const tagPrefix = 'access:'; - const actionTags = tags.filter(tag => tag.startsWith(tagPrefix)); + const actionTags = tags.filter((tag) => tag.startsWith(tagPrefix)); // if there are no tags starting with "access:", just continue if (actionTags.length === 0) { return toolkit.next(); } - const apiActions = actionTags.map(tag => actions.api.get(tag.substring(tagPrefix.length))); + const apiActions = actionTags.map((tag) => actions.api.get(tag.substring(tagPrefix.length))); const checkPrivileges = checkPrivilegesDynamicallyWithRequest(request); const checkPrivilegesResponse = await checkPrivileges(apiActions); diff --git a/x-pack/plugins/security/server/authorization/app_authorization.test.ts b/x-pack/plugins/security/server/authorization/app_authorization.test.ts index 6d23333022302..1dc56161d6363 100644 --- a/x-pack/plugins/security/server/authorization/app_authorization.test.ts +++ b/x-pack/plugins/security/server/authorization/app_authorization.test.ts @@ -117,7 +117,7 @@ describe('initAppAuthorization', () => { const mockCheckPrivileges = jest.fn().mockReturnValue({ hasAllRequested: true }); mockAuthz.mode.useRbacForRequest.mockReturnValue(true); - mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation(request => { + mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation((request) => { // hapi conceals the actual "request" from us, so we make sure that the headers are passed to // "checkPrivilegesDynamicallyWithRequest" because this is what we're really concerned with expect(request.headers).toMatchObject(headers); @@ -157,7 +157,7 @@ describe('initAppAuthorization', () => { const mockCheckPrivileges = jest.fn().mockReturnValue({ hasAllRequested: false }); mockAuthz.mode.useRbacForRequest.mockReturnValue(true); - mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation(request => { + mockAuthz.checkPrivilegesDynamicallyWithRequest.mockImplementation((request) => { // hapi conceals the actual "request" from us, so we make sure that the headers are passed to // "checkPrivilegesDynamicallyWithRequest" because this is what we're really concerned with expect(request.headers).toMatchObject(headers); diff --git a/x-pack/plugins/security/server/authorization/app_authorization.ts b/x-pack/plugins/security/server/authorization/app_authorization.ts index 8516e8228ab5a..aead8cb07897c 100644 --- a/x-pack/plugins/security/server/authorization/app_authorization.ts +++ b/x-pack/plugins/security/server/authorization/app_authorization.ts @@ -20,7 +20,7 @@ class ProtectedApplications { this.applications = new Set( this.featuresService .getFeatures() - .map(feature => feature.app) + .map((feature) => feature.app) .flat() ); } diff --git a/x-pack/plugins/security/server/authorization/check_privileges.test.ts b/x-pack/plugins/security/server/authorization/check_privileges.test.ts index a64c5d509ca11..65a3d1bf1650b 100644 --- a/x-pack/plugins/security/server/authorization/check_privileges.test.ts +++ b/x-pack/plugins/security/server/authorization/check_privileges.test.ts @@ -333,7 +333,7 @@ describe('#atSpaces', () => { applications: [ { application, - resources: options.spaceIds.map(spaceId => `space:${spaceId}`), + resources: options.spaceIds.map((spaceId) => `space:${spaceId}`), privileges: uniq([ mockActions.version, mockActions.login, diff --git a/x-pack/plugins/security/server/authorization/check_privileges.ts b/x-pack/plugins/security/server/authorization/check_privileges.ts index 177a49d6defe9..44e9438bd07f5 100644 --- a/x-pack/plugins/security/server/authorization/check_privileges.ts +++ b/x-pack/plugins/security/server/authorization/check_privileges.ts @@ -52,7 +52,7 @@ export function checkPrivilegesWithRequestFactory( applicationPrivilegesResponse: HasPrivilegesResponseApplication ) => { return Object.values(applicationPrivilegesResponse).some( - resource => !resource[actions.version] && resource[actions.login] + (resource) => !resource[actions.version] && resource[actions.login] ); }; @@ -121,7 +121,7 @@ export function checkPrivilegesWithRequestFactory( return await checkPrivilegesAtResources([spaceResource], privilegeOrPrivileges); }, async atSpaces(spaceIds: string[], privilegeOrPrivileges: string | string[]) { - const spaceResources = spaceIds.map(spaceId => + const spaceResources = spaceIds.map((spaceId) => ResourceSerializer.serializeSpaceResource(spaceId) ); return await checkPrivilegesAtResources(spaceResources, privilegeOrPrivileges); diff --git a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts index 43b3824500579..4ab00b511b48b 100644 --- a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts +++ b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts @@ -78,7 +78,7 @@ describe('#checkSavedObjectsPrivileges', () => { expect(mockCheckPrivilegesWithRequest).toHaveBeenCalledTimes(1); expect(mockCheckPrivilegesWithRequest).toHaveBeenCalledWith(request); expect(mockCheckPrivileges.atSpaces).toHaveBeenCalledTimes(1); - const spaceIds = mockSpacesService!.namespaceToSpaceId.mock.results.map(x => x.value); + const spaceIds = mockSpacesService!.namespaceToSpaceId.mock.results.map((x) => x.value); expect(mockCheckPrivileges.atSpaces).toHaveBeenCalledWith(spaceIds, actions); }); }); diff --git a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts index 43140143a1773..d9b070c72f946 100644 --- a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts +++ b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts @@ -37,7 +37,7 @@ export const checkSavedObjectsPrivilegesWithRequestFactory = ( } else if (!namespaceOrNamespaces.length) { throw new Error(`Can't check saved object privileges for 0 namespaces`); } - const spaceIds = namespaceOrNamespaces.map(x => spacesService.namespaceToSpaceId(x)); + const spaceIds = namespaceOrNamespaces.map((x) => spacesService.namespaceToSpaceId(x)); return await checkPrivilegesWithRequest(request).atSpaces(spaceIds, actions); } else if (spacesService) { const spaceId = spacesService.namespaceToSpaceId(namespaceOrNamespaces); diff --git a/x-pack/plugins/security/server/authorization/disable_ui_capabilities.test.ts b/x-pack/plugins/security/server/authorization/disable_ui_capabilities.test.ts index ea97a1b3b590c..082484d5fa6b4 100644 --- a/x-pack/plugins/security/server/authorization/disable_ui_capabilities.test.ts +++ b/x-pack/plugins/security/server/authorization/disable_ui_capabilities.test.ts @@ -20,15 +20,15 @@ const mockRequest = httpServerMock.createKibanaRequest(); const createMockAuthz = (options: MockAuthzOptions) => { const mock = authorizationMock.create({ version: '1.0.0-zeta1' }); - mock.checkPrivilegesDynamicallyWithRequest.mockImplementation(request => { + mock.checkPrivilegesDynamicallyWithRequest.mockImplementation((request) => { expect(request).toBe(mockRequest); - return jest.fn().mockImplementation(checkActions => { + return jest.fn().mockImplementation((checkActions) => { if ('rejectCheckPrivileges' in options) { throw options.rejectCheckPrivileges; } - const expected = options.resolveCheckPrivileges.privileges.map(x => x.privilege); + const expected = options.resolveCheckPrivileges.privileges.map((x) => x.privilege); expect(checkActions).toEqual(expected); return options.resolveCheckPrivileges; }); diff --git a/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts b/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts index f0f1a42ad0bd5..72937c15756ac 100644 --- a/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts +++ b/x-pack/plugins/security/server/authorization/disable_ui_capabilities.ts @@ -19,8 +19,8 @@ export function disableUICapabilitiesFactory( authz: Authorization ) { const featureNavLinkIds = features - .map(feature => feature.navLinkId) - .filter(navLinkId => navLinkId != null); + .map((feature) => feature.navLinkId) + .filter((navLinkId) => navLinkId != null); const shouldDisableFeatureUICapability = ( featureId: keyof UICapabilities, @@ -60,7 +60,9 @@ export function disableUICapabilitiesFactory( return [authz.actions.ui.get(featureId, uiCapability)]; } if (isObject(value)) { - return Object.keys(value).map(item => authz.actions.ui.get(featureId, uiCapability, item)); + return Object.keys(value).map((item) => + authz.actions.ui.get(featureId, uiCapability, item) + ); } throw new Error(`Expected value type of boolean or object, but found ${value}`); } @@ -106,7 +108,7 @@ export function disableUICapabilitiesFactory( const action = authz.actions.ui.get(featureId, ...uiCapabilityParts); return checkPrivilegesResponse.privileges.some( - x => x.privilege === action && x.authorized === true + (x) => x.privilege === action && x.authorized === true ); }; diff --git a/x-pack/plugins/security/server/authorization/privilege_serializer.test.ts b/x-pack/plugins/security/server/authorization/privilege_serializer.test.ts index ecfe0d34fdbcb..b35bfe9b0a271 100644 --- a/x-pack/plugins/security/server/authorization/privilege_serializer.test.ts +++ b/x-pack/plugins/security/server/authorization/privilege_serializer.test.ts @@ -7,14 +7,14 @@ import { PrivilegeSerializer } from './privilege_serializer'; describe(`#isSerializedGlobalBasePrivilege`, () => { - ['all', 'read'].forEach(validValue => { + ['all', 'read'].forEach((validValue) => { test(`returns true for '${validValue}'`, () => { expect(PrivilegeSerializer.isSerializedGlobalBasePrivilege(validValue)).toBe(true); }); }); ['space_all', 'space_read', 'foo', 'bar', 'feature_foo', 'feature_foo.privilege1'].forEach( - invalidValue => { + (invalidValue) => { test(`returns false for '${invalidValue}'`, () => { expect(PrivilegeSerializer.isSerializedGlobalBasePrivilege(invalidValue)).toBe(false); }); @@ -23,13 +23,13 @@ describe(`#isSerializedGlobalBasePrivilege`, () => { }); describe(`#isSerializedSpaceBasePrivilege`, () => { - ['space_all', 'space_read'].forEach(validValue => { + ['space_all', 'space_read'].forEach((validValue) => { test(`returns true for '${validValue}'`, () => { expect(PrivilegeSerializer.isSerializedSpaceBasePrivilege(validValue)).toBe(true); }); }); - ['all', 'read', 'foo', 'bar', 'feature_foo', 'feature_foo.privilege1'].forEach(invalid => { + ['all', 'read', 'foo', 'bar', 'feature_foo', 'feature_foo.privilege1'].forEach((invalid) => { test(`returns false for '${invalid}'`, () => { expect(PrivilegeSerializer.isSerializedSpaceBasePrivilege(invalid)).toBe(false); }); @@ -37,7 +37,7 @@ describe(`#isSerializedSpaceBasePrivilege`, () => { }); describe(`#isSerializedReservedPrivilege`, () => { - ['reserved_foo', 'reserved_bar'].forEach(validValue => { + ['reserved_foo', 'reserved_bar'].forEach((validValue) => { test(`returns true for '${validValue}'`, () => { expect(PrivilegeSerializer.isSerializedReservedPrivilege(validValue)).toBe(true); }); @@ -52,7 +52,7 @@ describe(`#isSerializedReservedPrivilege`, () => { 'bar', 'feature_foo', 'feature_foo.privilege1', - ].forEach(invalidValue => { + ].forEach((invalidValue) => { test(`returns false for '${invalidValue}'`, () => { expect(PrivilegeSerializer.isSerializedReservedPrivilege(invalidValue)).toBe(false); }); @@ -60,14 +60,14 @@ describe(`#isSerializedReservedPrivilege`, () => { }); describe(`#isSerializedFeaturePrivilege`, () => { - ['feature_foo.privilege1', 'feature_bar.privilege2'].forEach(validValue => { + ['feature_foo.privilege1', 'feature_bar.privilege2'].forEach((validValue) => { test(`returns true for '${validValue}'`, () => { expect(PrivilegeSerializer.isSerializedFeaturePrivilege(validValue)).toBe(true); }); }); ['all', 'read', 'space_all', 'space_read', 'reserved_foo', 'reserved_bar'].forEach( - invalidValue => { + (invalidValue) => { test(`returns false for '${invalidValue}'`, () => { expect(PrivilegeSerializer.isSerializedFeaturePrivilege(invalidValue)).toBe(false); }); @@ -154,7 +154,7 @@ describe('#deserializeFeaturePrivilege', () => { 'feature_foo_privilege-1', // no '.' 'feature_foo.', // has a '.' but nothing after it 'feature_.privilege-1', // nothing before the '.' - ].forEach(privilege => { + ].forEach((privilege) => { test(`throws error when deserializing ${privilege}`, () => { expect(() => PrivilegeSerializer.deserializeFeaturePrivilege(privilege) diff --git a/x-pack/plugins/security/server/authorization/privilege_serializer.ts b/x-pack/plugins/security/server/authorization/privilege_serializer.ts index 2bbebaa1cc951..bc5bf81c2d429 100644 --- a/x-pack/plugins/security/server/authorization/privilege_serializer.ts +++ b/x-pack/plugins/security/server/authorization/privilege_serializer.ts @@ -10,7 +10,7 @@ const reservedPrefix = 'reserved_'; const basePrivilegeNames = ['all', 'read']; const globalBasePrivileges = [...basePrivilegeNames]; const spaceBasePrivileges = basePrivilegeNames.map( - privilegeName => `${spacePrefix}${privilegeName}` + (privilegeName) => `${spacePrefix}${privilegeName}` ); const deserializeFeaturePrivilegeRegexp = new RegExp( `^${featurePrefix}([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_-]+)$` diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/api.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/api.ts index b13132f6efbe5..6b7d94bb0127e 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/api.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/api.ts @@ -10,7 +10,7 @@ import { BaseFeaturePrivilegeBuilder } from './feature_privilege_builder'; export class FeaturePrivilegeApiBuilder extends BaseFeaturePrivilegeBuilder { public getActions(privilegeDefinition: FeatureKibanaPrivileges, feature: Feature): string[] { if (privilegeDefinition.api) { - return privilegeDefinition.api.map(operation => this.actions.api.get(operation)); + return privilegeDefinition.api.map((operation) => this.actions.api.get(operation)); } return []; diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/app.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/app.ts index 514d6734b47ba..213aa83f2d26e 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/app.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/app.ts @@ -15,6 +15,6 @@ export class FeaturePrivilegeAppBuilder extends BaseFeaturePrivilegeBuilder { return []; } - return appIds.map(appId => this.actions.app.get(appId)); + return appIds.map((appId) => this.actions.app.get(appId)); } } diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/catalogue.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/catalogue.ts index fc15aff32b975..f1ea7091b9481 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/catalogue.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/catalogue.ts @@ -15,7 +15,7 @@ export class FeaturePrivilegeCatalogueBuilder extends BaseFeaturePrivilegeBuilde return []; } - return catalogueEntries.map(catalogueEntryId => + return catalogueEntries.map((catalogueEntryId) => this.actions.ui.get('catalogue', catalogueEntryId) ); } diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts index c293319070419..3d6dfbdac0251 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/index.ts @@ -30,7 +30,7 @@ export const featurePrivilegeBuilderFactory = (actions: Actions): FeaturePrivile return { getActions(privilege: FeatureKibanaPrivileges, feature: Feature) { - return flatten(builders.map(builder => builder.getActions(privilege, feature))); + return flatten(builders.map((builder) => builder.getActions(privilege, feature))); }, }; }; diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/management.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/management.ts index 7a2bb87d72b45..be784949dc2fa 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/management.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/management.ts @@ -16,7 +16,7 @@ export class FeaturePrivilegeManagementBuilder extends BaseFeaturePrivilegeBuild } return Object.entries(managementSections).reduce((acc, [sectionId, items]) => { - return [...acc, ...items.map(item => this.actions.ui.get('management', sectionId, item))]; + return [...acc, ...items.map((item) => this.actions.ui.get('management', sectionId, item))]; }, [] as string[]); } } diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/saved_object.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/saved_object.ts index 9baa8dadc2923..2c325fc8c6cb7 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/saved_object.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/saved_object.ts @@ -16,13 +16,13 @@ export class FeaturePrivilegeSavedObjectBuilder extends BaseFeaturePrivilegeBuil public getActions(privilegeDefinition: FeatureKibanaPrivileges, feature: Feature): string[] { return uniq([ ...flatten( - privilegeDefinition.savedObject.all.map(type => [ - ...allOperations.map(operation => this.actions.savedObject.get(type, operation)), + privilegeDefinition.savedObject.all.map((type) => [ + ...allOperations.map((operation) => this.actions.savedObject.get(type, operation)), ]) ), ...flatten( - privilegeDefinition.savedObject.read.map(type => [ - ...readOperations.map(operation => this.actions.savedObject.get(type, operation)), + privilegeDefinition.savedObject.read.map((type) => [ + ...readOperations.map((operation) => this.actions.savedObject.get(type, operation)), ]) ), ]); diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/ui.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/ui.ts index 28a22285c2b8f..31bc351206e54 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/ui.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_builder/ui.ts @@ -9,6 +9,6 @@ import { BaseFeaturePrivilegeBuilder } from './feature_privilege_builder'; export class FeaturePrivilegeUIBuilder extends BaseFeaturePrivilegeBuilder { public getActions(privilegeDefinition: FeatureKibanaPrivileges, feature: Feature): string[] { - return privilegeDefinition.ui.map(ui => this.actions.ui.get(feature.id, ui)); + return privilegeDefinition.ui.map((ui) => this.actions.ui.get(feature.id, ui)); } } diff --git a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.test.ts b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.test.ts index 7d92eacfe6b35..485783253d29d 100644 --- a/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.test.ts +++ b/x-pack/plugins/security/server/authorization/privileges/feature_privilege_iterator/feature_privilege_iterator.test.ts @@ -140,7 +140,7 @@ describe('featurePrivilegeIterator', () => { const actualPrivileges = Array.from( featurePrivilegeIterator(feature, { augmentWithSubFeaturePrivileges: true, - predicate: privilegeId => privilegeId === 'all', + predicate: (privilegeId) => privilegeId === 'all', }) ); diff --git a/x-pack/plugins/security/server/authorization/privileges/privileges.ts b/x-pack/plugins/security/server/authorization/privileges/privileges.ts index 9a8935f80a174..f3b2881e79ece 100644 --- a/x-pack/plugins/security/server/authorization/privileges/privileges.ts +++ b/x-pack/plugins/security/server/authorization/privileges/privileges.ts @@ -31,12 +31,14 @@ export function privilegesFactory( get() { const features = featuresService.getFeatures(); const { allowSubFeaturePrivileges } = licenseService.getFeatures(); - const basePrivilegeFeatures = features.filter(feature => !feature.excludeFromBasePrivileges); + const basePrivilegeFeatures = features.filter( + (feature) => !feature.excludeFromBasePrivileges + ); let allActions: string[] = []; let readActions: string[] = []; - basePrivilegeFeatures.forEach(feature => { + basePrivilegeFeatures.forEach((feature) => { for (const { privilegeId, privilege } of featurePrivilegeIterator(feature, { augmentWithSubFeaturePrivileges: true, predicate: (pId, featurePrivilege) => !featurePrivilege.excludeFromBasePrivileges, @@ -110,7 +112,7 @@ export function privilegesFactory( }, reserved: features.reduce((acc: Record, feature: Feature) => { if (feature.reserved) { - feature.reserved.privileges.forEach(reservedPrivilege => { + feature.reserved.privileges.forEach((reservedPrivilege) => { acc[reservedPrivilege.id] = [ actions.version, ...uniq(featurePrivilegeBuilder.getActions(reservedPrivilege.privilege, feature)), diff --git a/x-pack/plugins/security/server/authorization/register_privileges_with_cluster.test.ts b/x-pack/plugins/security/server/authorization/register_privileges_with_cluster.test.ts index dc406c17925dd..fff4345c72409 100644 --- a/x-pack/plugins/security/server/authorization/register_privileges_with_cluster.test.ts +++ b/x-pack/plugins/security/server/authorization/register_privileges_with_cluster.test.ts @@ -101,7 +101,7 @@ const registerPrivilegesWithClusterTest = ( test(description, async () => { const mockClusterClient = elasticsearchServiceMock.createClusterClient(); - mockClusterClient.callAsInternalUser.mockImplementation(async api => { + mockClusterClient.callAsInternalUser.mockImplementation(async (api) => { switch (api) { case 'shield.getPrivilege': { if (throwErrorWhenGettingPrivileges) { diff --git a/x-pack/plugins/security/server/authorization/validate_feature_privileges.ts b/x-pack/plugins/security/server/authorization/validate_feature_privileges.ts index 510feb1151a9b..79e5348b4ac64 100644 --- a/x-pack/plugins/security/server/authorization/validate_feature_privileges.ts +++ b/x-pack/plugins/security/server/authorization/validate_feature_privileges.ts @@ -9,15 +9,15 @@ import { Feature } from '../../../features/server'; export function validateFeaturePrivileges(features: Feature[]) { for (const feature of features) { const seenPrivilegeIds = new Set(); - Object.keys(feature.privileges ?? {}).forEach(privilegeId => { + Object.keys(feature.privileges ?? {}).forEach((privilegeId) => { seenPrivilegeIds.add(privilegeId); seenPrivilegeIds.add(`minimal_${privilegeId}`); }); const subFeatureEntries = feature.subFeatures ?? []; - subFeatureEntries.forEach(subFeature => { - subFeature.privilegeGroups.forEach(subFeaturePrivilegeGroup => { - subFeaturePrivilegeGroup.privileges.forEach(subFeaturePrivilege => { + subFeatureEntries.forEach((subFeature) => { + subFeature.privilegeGroups.forEach((subFeaturePrivilegeGroup) => { + subFeaturePrivilegeGroup.privileges.forEach((subFeaturePrivilege) => { if (seenPrivilegeIds.has(subFeaturePrivilege.id)) { throw new Error( `Feature '${feature.id}' already has a privilege with ID '${subFeaturePrivilege.id}'. Sub feature '${subFeature.name}' cannot also specify this.` diff --git a/x-pack/plugins/security/server/config.ts b/x-pack/plugins/security/server/config.ts index 695653a2ac1db..4026666d042bd 100644 --- a/x-pack/plugins/security/server/config.ts +++ b/x-pack/plugins/security/server/config.ts @@ -15,7 +15,7 @@ const providerOptionsSchema = (providerType: string, optionsSchema: Type) = schema.conditional( schema.siblingRef('providers'), schema.arrayOf(schema.string(), { - validate: providers => (!providers.includes(providerType) ? 'error' : undefined), + validate: (providers) => (!providers.includes(providerType) ? 'error' : undefined), }), optionsSchema, schema.never() @@ -45,7 +45,7 @@ function getUniqueProviderSchema( return schema.maybe( schema.recordOf(schema.string(), schema.object(getCommonProviderSchemaProperties(overrides)), { validate(config) { - if (Object.values(config).filter(provider => provider.enabled).length > 1) { + if (Object.values(config).filter((provider) => provider.enabled).length > 1) { return `Only one "${providerType}" provider can be configured.`; } }, @@ -65,7 +65,7 @@ const providersConfigSchema = schema.object( icon: schema.string({ defaultValue: 'logoElasticsearch' }), showInSelector: schema.boolean({ defaultValue: true, - validate: value => { + validate: (value) => { if (!value) { return '`basic` provider only supports `true` in `showInSelector`.'; } @@ -81,7 +81,7 @@ const providersConfigSchema = schema.object( icon: schema.string({ defaultValue: 'logoElasticsearch' }), showInSelector: schema.boolean({ defaultValue: true, - validate: value => { + validate: (value) => { if (!value) { return '`token` provider only supports `true` in `showInSelector`.'; } diff --git a/x-pack/plugins/security/server/index.ts b/x-pack/plugins/security/server/index.ts index 0011737d85734..0de86c72002c9 100644 --- a/x-pack/plugins/security/server/index.ts +++ b/x-pack/plugins/security/server/index.ts @@ -53,7 +53,7 @@ export const config: PluginConfigDescriptor> = { } return Object.values(providers?.[providerType] || {}).some( - provider => (provider as { enabled: boolean | undefined })?.enabled !== false + (provider) => (provider as { enabled: boolean | undefined })?.enabled !== false ); }; diff --git a/x-pack/plugins/security/server/plugin.ts b/x-pack/plugins/security/server/plugin.ts index 77a2d716e6d87..89cffde92d564 100644 --- a/x-pack/plugins/security/server/plugin.ts +++ b/x-pack/plugins/security/server/plugin.ts @@ -115,7 +115,7 @@ export class Plugin { public async setup(core: CoreSetup, { features, licensing }: PluginSetupDependencies) { const [config, legacyConfig] = await combineLatest([ this.initializerContext.config.create>().pipe( - map(rawConfig => + map((rawConfig) => createConfig(rawConfig, this.initializerContext.logger.get('config'), { isTLSEnabled: core.http.isTlsEnabled, }) @@ -196,7 +196,7 @@ export class Plugin { license, - registerSpacesService: service => { + registerSpacesService: (service) => { if (this.wasSpacesServiceAccessed()) { throw new Error('Spaces service has been accessed before registration.'); } diff --git a/x-pack/plugins/security/server/routes/api_keys/invalidate.ts b/x-pack/plugins/security/server/routes/api_keys/invalidate.ts index cb86c1024ae9a..dd472c0b60cbc 100644 --- a/x-pack/plugins/security/server/routes/api_keys/invalidate.ts +++ b/x-pack/plugins/security/server/routes/api_keys/invalidate.ts @@ -33,7 +33,7 @@ export function defineInvalidateApiKeysRoutes({ router, clusterClient }: RouteDe // Invalidate all API keys in parallel. const invalidationResult = ( await Promise.all( - request.body.apiKeys.map(async key => { + request.body.apiKeys.map(async (key) => { try { const body: { id: string; owner?: boolean } = { id: key.id }; if (!request.body.isAdmin) { diff --git a/x-pack/plugins/security/server/routes/authentication/basic.test.ts b/x-pack/plugins/security/server/routes/authentication/basic.test.ts index 5eed8e166c957..944bc567de586 100644 --- a/x-pack/plugins/security/server/routes/authentication/basic.test.ts +++ b/x-pack/plugins/security/server/routes/authentication/basic.test.ts @@ -28,7 +28,7 @@ describe('Basic authentication routes', () => { router = routeParamsMock.router; authc = routeParamsMock.authc; - authc.isProviderTypeEnabled.mockImplementation(provider => provider === 'basic'); + authc.isProviderTypeEnabled.mockImplementation((provider) => provider === 'basic'); mockContext = ({ licensing: { @@ -156,7 +156,7 @@ describe('Basic authentication routes', () => { it('prefers `token` authentication provider if it is enabled', async () => { authc.login.mockResolvedValue(AuthenticationResult.succeeded(mockAuthenticatedUser())); authc.isProviderTypeEnabled.mockImplementation( - provider => provider === 'token' || provider === 'basic' + (provider) => provider === 'token' || provider === 'basic' ); const response = await routeHandler(mockContext, mockRequest, kibanaResponseFactory); diff --git a/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts b/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts index c9e963f0b8fc7..08cd3ba487b0b 100644 --- a/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts +++ b/x-pack/plugins/security/server/routes/authorization/privileges/get_builtin.ts @@ -16,8 +16,8 @@ export function defineGetBuiltinPrivilegesRoutes({ router, clusterClient }: Rout .callAsCurrentUser('shield.getBuiltinPrivileges'); // Exclude the `none` privilege, as it doesn't make sense as an option within the Kibana UI - privileges.cluster = privileges.cluster.filter(privilege => privilege !== 'none'); - privileges.index = privileges.index.filter(privilege => privilege !== 'none'); + privileges.cluster = privileges.cluster.filter((privilege) => privilege !== 'none'); + privileges.index = privileges.index.filter((privilege) => privilege !== 'none'); return response.ok({ body: privileges }); } diff --git a/x-pack/plugins/security/server/routes/authorization/roles/model/elasticsearch_role.ts b/x-pack/plugins/security/server/routes/authorization/roles/model/elasticsearch_role.ts index 609b7d2f35c4b..0fd087231b770 100644 --- a/x-pack/plugins/security/server/routes/authorization/roles/model/elasticsearch_role.ts +++ b/x-pack/plugins/security/server/routes/authorization/roles/model/elasticsearch_role.ts @@ -56,13 +56,13 @@ function transformRoleApplicationsToKibanaPrivileges( application: string ) { const roleKibanaApplications = roleApplications.filter( - roleApplication => + (roleApplication) => roleApplication.application === application || roleApplication.application === RESERVED_PRIVILEGES_APPLICATION_WILDCARD ); // if any application entry contains an empty resource, we throw an error - if (roleKibanaApplications.some(entry => entry.resources.length === 0)) { + if (roleKibanaApplications.some((entry) => entry.resources.length === 0)) { throw new Error(`ES returned an application entry without resources, can't process this`); } @@ -70,9 +70,9 @@ function transformRoleApplicationsToKibanaPrivileges( // and there are privileges which aren't reserved, we won't transform these if ( roleKibanaApplications.some( - entry => + (entry) => entry.application === RESERVED_PRIVILEGES_APPLICATION_WILDCARD && - !entry.privileges.every(privilege => + !entry.privileges.every((privilege) => PrivilegeSerializer.isSerializedReservedPrivilege(privilege) ) ) @@ -85,9 +85,9 @@ function transformRoleApplicationsToKibanaPrivileges( // if space privilege assigned globally, we can't transform these if ( roleKibanaApplications.some( - entry => + (entry) => entry.resources.includes(GLOBAL_RESOURCE) && - entry.privileges.some(privilege => + entry.privileges.some((privilege) => PrivilegeSerializer.isSerializedSpaceBasePrivilege(privilege) ) ) @@ -100,10 +100,10 @@ function transformRoleApplicationsToKibanaPrivileges( // if global base or reserved privilege assigned at a space, we can't transform these if ( roleKibanaApplications.some( - entry => + (entry) => !entry.resources.includes(GLOBAL_RESOURCE) && entry.privileges.some( - privilege => + (privilege) => PrivilegeSerializer.isSerializedGlobalBasePrivilege(privilege) || PrivilegeSerializer.isSerializedReservedPrivilege(privilege) ) @@ -117,12 +117,12 @@ function transformRoleApplicationsToKibanaPrivileges( // if reserved privilege assigned with feature or base privileges, we won't transform these if ( roleKibanaApplications.some( - entry => - entry.privileges.some(privilege => + (entry) => + entry.privileges.some((privilege) => PrivilegeSerializer.isSerializedReservedPrivilege(privilege) ) && entry.privileges.some( - privilege => !PrivilegeSerializer.isSerializedReservedPrivilege(privilege) + (privilege) => !PrivilegeSerializer.isSerializedReservedPrivilege(privilege) ) ) ) { @@ -134,14 +134,14 @@ function transformRoleApplicationsToKibanaPrivileges( // if base privilege assigned with feature privileges, we won't transform these if ( roleKibanaApplications.some( - entry => - entry.privileges.some(privilege => + (entry) => + entry.privileges.some((privilege) => PrivilegeSerializer.isSerializedFeaturePrivilege(privilege) ) && - (entry.privileges.some(privilege => + (entry.privileges.some((privilege) => PrivilegeSerializer.isSerializedGlobalBasePrivilege(privilege) ) || - entry.privileges.some(privilege => + entry.privileges.some((privilege) => PrivilegeSerializer.isSerializedSpaceBasePrivilege(privilege) )) ) @@ -154,7 +154,7 @@ function transformRoleApplicationsToKibanaPrivileges( // if any application entry contains the '*' resource in addition to another resource, we can't transform these if ( roleKibanaApplications.some( - entry => entry.resources.includes(GLOBAL_RESOURCE) && entry.resources.length > 1 + (entry) => entry.resources.includes(GLOBAL_RESOURCE) && entry.resources.length > 1 ) ) { return { @@ -162,11 +162,11 @@ function transformRoleApplicationsToKibanaPrivileges( }; } - const allResources = roleKibanaApplications.map(entry => entry.resources).flat(); + const allResources = roleKibanaApplications.map((entry) => entry.resources).flat(); // if we have improperly formatted resource entries, we can't transform these if ( allResources.some( - resource => + (resource) => resource !== GLOBAL_RESOURCE && !ResourceSerializer.isSerializedSpaceResource(resource) ) ) { @@ -187,25 +187,25 @@ function transformRoleApplicationsToKibanaPrivileges( value: roleKibanaApplications.map(({ resources, privileges }) => { // if we're dealing with a global entry, which we've ensured above is only possible if it's the only item in the array if (resources.length === 1 && resources[0] === GLOBAL_RESOURCE) { - const reservedPrivileges = privileges.filter(privilege => + const reservedPrivileges = privileges.filter((privilege) => PrivilegeSerializer.isSerializedReservedPrivilege(privilege) ); - const basePrivileges = privileges.filter(privilege => + const basePrivileges = privileges.filter((privilege) => PrivilegeSerializer.isSerializedGlobalBasePrivilege(privilege) ); - const featurePrivileges = privileges.filter(privilege => + const featurePrivileges = privileges.filter((privilege) => PrivilegeSerializer.isSerializedFeaturePrivilege(privilege) ); return { ...(reservedPrivileges.length ? { - _reserved: reservedPrivileges.map(privilege => + _reserved: reservedPrivileges.map((privilege) => PrivilegeSerializer.deserializeReservedPrivilege(privilege) ), } : {}), - base: basePrivileges.map(privilege => + base: basePrivileges.map((privilege) => PrivilegeSerializer.serializeGlobalBasePrivilege(privilege) ), feature: featurePrivileges.reduce((acc, privilege) => { @@ -222,14 +222,14 @@ function transformRoleApplicationsToKibanaPrivileges( }; } - const basePrivileges = privileges.filter(privilege => + const basePrivileges = privileges.filter((privilege) => PrivilegeSerializer.isSerializedSpaceBasePrivilege(privilege) ); - const featurePrivileges = privileges.filter(privilege => + const featurePrivileges = privileges.filter((privilege) => PrivilegeSerializer.isSerializedFeaturePrivilege(privilege) ); return { - base: basePrivileges.map(privilege => + base: basePrivileges.map((privilege) => PrivilegeSerializer.deserializeSpaceBasePrivilege(privilege) ), feature: featurePrivileges.reduce((acc, privilege) => { @@ -242,7 +242,7 @@ function transformRoleApplicationsToKibanaPrivileges( ]), }; }, {} as RoleKibanaPrivilege['feature']), - spaces: resources.map(resource => ResourceSerializer.deserializeSpaceResource(resource)), + spaces: resources.map((resource) => ResourceSerializer.deserializeSpaceResource(resource)), }; }), }; @@ -255,11 +255,11 @@ const extractUnrecognizedApplicationNames = ( return getUniqueList( roleApplications .filter( - roleApplication => + (roleApplication) => roleApplication.application !== application && roleApplication.application !== RESERVED_PRIVILEGES_APPLICATION_WILDCARD ) - .map(roleApplication => roleApplication.application) + .map((roleApplication) => roleApplication.application) ); }; diff --git a/x-pack/plugins/security/server/routes/authorization/roles/model/put_payload.ts b/x-pack/plugins/security/server/routes/authorization/roles/model/put_payload.ts index a5f6b2fd9fcc1..e0af14f90d01c 100644 --- a/x-pack/plugins/security/server/routes/authorization/roles/model/put_payload.ts +++ b/x-pack/plugins/security/server/routes/authorization/roles/model/put_payload.ts @@ -142,7 +142,7 @@ export function getPutPayloadSchema( schema.string({ validate(value) { const globalPrivileges = getBasePrivilegeNames().global; - if (!globalPrivileges.some(privilege => privilege === value)) { + if (!globalPrivileges.some((privilege) => privilege === value)) { return `unknown global privilege "${value}", must be one of [${globalPrivileges}]`; } }, @@ -152,7 +152,7 @@ export function getPutPayloadSchema( schema.string({ validate(value) { const spacePrivileges = getBasePrivilegeNames().space; - if (!spacePrivileges.some(privilege => privilege === value)) { + if (!spacePrivileges.some((privilege) => privilege === value)) { return `unknown space privilege "${value}", must be one of [${spacePrivileges}]`; } }, @@ -235,7 +235,7 @@ export const transformPutPayloadToElasticsearchRole = ( kibana = [], } = rolePayload; const otherApplications = allExistingApplications.filter( - roleApplication => roleApplication.application !== application + (roleApplication) => roleApplication.application !== application ); return { @@ -259,12 +259,12 @@ const transformPrivilegesToElasticsearchPrivileges = ( return { privileges: [ ...(base - ? base.map(privilege => PrivilegeSerializer.serializeGlobalBasePrivilege(privilege)) + ? base.map((privilege) => PrivilegeSerializer.serializeGlobalBasePrivilege(privilege)) : []), ...(feature ? Object.entries(feature) .map(([featureName, featurePrivileges]) => - featurePrivileges.map(privilege => + featurePrivileges.map((privilege) => PrivilegeSerializer.serializeFeaturePrivilege(featureName, privilege) ) ) @@ -279,12 +279,12 @@ const transformPrivilegesToElasticsearchPrivileges = ( return { privileges: [ ...(base - ? base.map(privilege => PrivilegeSerializer.serializeSpaceBasePrivilege(privilege)) + ? base.map((privilege) => PrivilegeSerializer.serializeSpaceBasePrivilege(privilege)) : []), ...(feature ? Object.entries(feature) .map(([featureName, featurePrivileges]) => - featurePrivileges.map(privilege => + featurePrivileges.map((privilege) => PrivilegeSerializer.serializeFeaturePrivilege(featureName, privilege) ) ) @@ -292,7 +292,7 @@ const transformPrivilegesToElasticsearchPrivileges = ( : []), ], application, - resources: (spaces as string[]).map(resource => + resources: (spaces as string[]).map((resource) => ResourceSerializer.serializeSpaceResource(resource) ), }; diff --git a/x-pack/plugins/security/server/routes/indices/get_fields.ts b/x-pack/plugins/security/server/routes/indices/get_fields.ts index 64c3d4f7471ef..356b78aa33879 100644 --- a/x-pack/plugins/security/server/routes/indices/get_fields.ts +++ b/x-pack/plugins/security/server/routes/indices/get_fields.ts @@ -34,7 +34,7 @@ export function defineGetFieldsRoutes({ router, clusterClient }: RouteDefinition body: Array.from( new Set( Object.values(indexMappings) - .map(indexMapping => Object.keys(indexMapping.mappings)) + .map((indexMapping) => Object.keys(indexMapping.mappings)) .flat() ) ), diff --git a/x-pack/plugins/security/server/routes/role_mapping/feature_check.ts b/x-pack/plugins/security/server/routes/role_mapping/feature_check.ts index 2be4f4cd89177..b056d9e358737 100644 --- a/x-pack/plugins/security/server/routes/role_mapping/feature_check.ts +++ b/x-pack/plugins/security/server/routes/role_mapping/feature_check.ts @@ -80,7 +80,7 @@ async function getEnabledRoleMappingsFeatures(clusterClient: IClusterClient, log .callAsInternalUser('nodes.info', { filterPath: 'nodes.*.settings.script', }) - .catch(error => { + .catch((error) => { // fall back to assuming that node settings are unset/at their default values. // this will allow the role mappings UI to permit both role template script types, // even if ES will disallow it at mapping evaluation time. @@ -95,7 +95,7 @@ async function getEnabledRoleMappingsFeatures(clusterClient: IClusterClient, log method: 'GET', path: '/_xpack/usage', }) - .catch(error => { + .catch((error) => { // fall back to no external realms configured. // this will cause a warning in the UI about no compatible realms being enabled, but will otherwise allow // the mappings screen to function correctly. @@ -115,12 +115,12 @@ async function getEnabledRoleMappingsFeatures(clusterClient: IClusterClient, log let canUseStoredScripts = true; let canUseInlineScripts = true; if (usesCustomScriptSettings(nodeScriptSettings)) { - canUseStoredScripts = Object.values(nodeScriptSettings.nodes).some(node => { + canUseStoredScripts = Object.values(nodeScriptSettings.nodes).some((node) => { const allowedTypes = node.settings.script.allowed_types; return !allowedTypes || allowedTypes.includes('stored'); }); - canUseInlineScripts = Object.values(nodeScriptSettings.nodes).some(node => { + canUseInlineScripts = Object.values(nodeScriptSettings.nodes).some((node) => { const allowedTypes = node.settings.script.allowed_types; return !allowedTypes || allowedTypes.includes('inline'); }); diff --git a/x-pack/plugins/security/server/routes/role_mapping/get.ts b/x-pack/plugins/security/server/routes/role_mapping/get.ts index def6fabc0e322..63598584b5d1b 100644 --- a/x-pack/plugins/security/server/routes/role_mapping/get.ts +++ b/x-pack/plugins/security/server/routes/role_mapping/get.ts @@ -39,7 +39,7 @@ export function defineRoleMappingGetRoutes(params: RouteDefinitionParams) { return { name, ...mapping, - role_templates: (mapping.role_templates || []).map(entry => { + role_templates: (mapping.role_templates || []).map((entry) => { return { ...entry, template: tryParseRoleTemplate(entry.template as string), diff --git a/x-pack/plugins/security/server/routes/views/index.test.ts b/x-pack/plugins/security/server/routes/views/index.test.ts index 7cddef9bf2b98..0c0117dec5390 100644 --- a/x-pack/plugins/security/server/routes/views/index.test.ts +++ b/x-pack/plugins/security/server/routes/views/index.test.ts @@ -12,7 +12,7 @@ describe('View routes', () => { it('does not register Login routes if both `basic` and `token` providers are disabled', () => { const routeParamsMock = routeDefinitionParamsMock.create(); routeParamsMock.authc.isProviderTypeEnabled.mockImplementation( - provider => provider !== 'basic' && provider !== 'token' + (provider) => provider !== 'basic' && provider !== 'token' ); defineViewRoutes(routeParamsMock); @@ -37,7 +37,7 @@ describe('View routes', () => { it('registers Login routes if `basic` provider is enabled', () => { const routeParamsMock = routeDefinitionParamsMock.create(); routeParamsMock.authc.isProviderTypeEnabled.mockImplementation( - provider => provider !== 'token' + (provider) => provider !== 'token' ); defineViewRoutes(routeParamsMock); @@ -64,7 +64,7 @@ describe('View routes', () => { it('registers Login routes if `token` provider is enabled', () => { const routeParamsMock = routeDefinitionParamsMock.create(); routeParamsMock.authc.isProviderTypeEnabled.mockImplementation( - provider => provider !== 'basic' + (provider) => provider !== 'basic' ); defineViewRoutes(routeParamsMock); diff --git a/x-pack/plugins/security/server/saved_objects/index.ts b/x-pack/plugins/security/server/saved_objects/index.ts index 40c17e5429aa8..29fbe3af21b95 100644 --- a/x-pack/plugins/security/server/saved_objects/index.ts +++ b/x-pack/plugins/security/server/saved_objects/index.ts @@ -31,14 +31,16 @@ export function setupSavedObjects({ const getKibanaRequest = (request: KibanaRequest | LegacyRequest) => request instanceof KibanaRequest ? request : KibanaRequest.from(request); - savedObjects.setClientFactoryProvider(repositoryFactory => ({ request, includedHiddenTypes }) => { - const kibanaRequest = getKibanaRequest(request); - return new SavedObjectsClient( - authz.mode.useRbacForRequest(kibanaRequest) - ? repositoryFactory.createInternalRepository(includedHiddenTypes) - : repositoryFactory.createScopedRepository(kibanaRequest, includedHiddenTypes) - ); - }); + savedObjects.setClientFactoryProvider( + (repositoryFactory) => ({ request, includedHiddenTypes }) => { + const kibanaRequest = getKibanaRequest(request); + return new SavedObjectsClient( + authz.mode.useRbacForRequest(kibanaRequest) + ? repositoryFactory.createInternalRepository(includedHiddenTypes) + : repositoryFactory.createScopedRepository(kibanaRequest, includedHiddenTypes) + ); + } + ); savedObjects.addClientWrapper(Number.MAX_SAFE_INTEGER - 1, 'security', ({ client, request }) => { const kibanaRequest = getKibanaRequest(request); diff --git a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts index 3c4034e07f995..c646cd95228f0 100644 --- a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts +++ b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts @@ -76,7 +76,7 @@ const expectForbiddenError = async (fn: Function, args: Record) => const spaceId = args.options?.namespace || 'default'; const ACTION = getCalls[0][1]; - const types = getCalls.map(x => x[0]); + const types = getCalls.map((x) => x[0]); const missing = [{ spaceId, privilege: actions[0] }]; // if there was more than one type, only the first type was unauthorized const spaceIds = [spaceId]; @@ -99,7 +99,7 @@ const expectSuccess = async (fn: Function, args: Record) => { SavedObjectActions['get'] >).mock.calls; const ACTION = getCalls[0][1]; - const types = getCalls.map(x => x[0]); + const types = getCalls.map((x) => x[0]); const spaceIds = [args.options?.namespace || 'default']; expect(clientOpts.auditLogger.savedObjectsAuthorizationFailure).not.toHaveBeenCalled(); @@ -123,7 +123,7 @@ const expectPrivilegeCheck = async (fn: Function, args: Record) => const getResults = (clientOpts.actions.savedObject.get as jest.MockedFunction< SavedObjectActions['get'] >).mock.results; - const actions = getResults.map(x => x.value); + const actions = getResults.map((x) => x.value); expect(clientOpts.checkSavedObjectsPrivilegesAsCurrentUser).toHaveBeenCalledTimes(1); expect(clientOpts.checkSavedObjectsPrivilegesAsCurrentUser).toHaveBeenCalledWith( @@ -206,8 +206,8 @@ function getMockCheckPrivilegesSuccess(actions: string | string[], namespaces?: hasAllRequested: true, username: USERNAME, privileges: _namespaces - .map(resource => - _actions.map(action => ({ + .map((resource) => + _actions.map((action) => ({ resource, privilege: action, authorized: true, diff --git a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts index 29503d475be73..969344afae5e3 100644 --- a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts +++ b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts @@ -207,14 +207,14 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra ) { const types = Array.isArray(typeOrTypes) ? typeOrTypes : [typeOrTypes]; const actionsToTypesMap = new Map( - types.map(type => [this.actions.savedObject.get(type, action), type]) + types.map((type) => [this.actions.savedObject.get(type, action), type]) ); const actions = Array.from(actionsToTypesMap.keys()); const result = await this.checkPrivileges(actions, namespaceOrNamespaces); const { hasAllRequested, username, privileges } = result; const spaceIds = uniq( - privileges.map(({ resource }) => resource).filter(x => x !== undefined) + privileges.map(({ resource }) => resource).filter((x) => x !== undefined) ).sort() as string[]; const isAuthorized = @@ -253,7 +253,7 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra } private getUniqueObjectTypes(objects: Array<{ type: string }>) { - return uniq(objects.map(o => o.type)); + return uniq(objects.map((o) => o.type)); } private async getNamespacesPrivilegeMap(namespaces: string[]) { @@ -287,7 +287,7 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra } return 0; }; - return spaceIds.map(spaceId => (privilegeMap[spaceId] ? spaceId : '?')).sort(comparator); + return spaceIds.map((spaceId) => (privilegeMap[spaceId] ? spaceId : '?')).sort(comparator); } private async redactSavedObjectNamespaces( @@ -312,7 +312,7 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra return response; } const { saved_objects: savedObjects } = response; - const namespaces = uniq(savedObjects.flatMap(savedObject => savedObject.namespaces || [])); + const namespaces = uniq(savedObjects.flatMap((savedObject) => savedObject.namespaces || [])); if (namespaces.length === 0) { return response; } @@ -321,7 +321,7 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra return { ...response, - saved_objects: savedObjects.map(savedObject => ({ + saved_objects: savedObjects.map((savedObject) => ({ ...savedObject, namespaces: savedObject.namespaces && diff --git a/x-pack/plugins/siem/common/endpoint/generate_data.test.ts b/x-pack/plugins/siem/common/endpoint/generate_data.test.ts index f99fa5c871d89..3dcf20c41f269 100644 --- a/x-pack/plugins/siem/common/endpoint/generate_data.test.ts +++ b/x-pack/plugins/siem/common/endpoint/generate_data.test.ts @@ -142,7 +142,7 @@ describe('data generator', () => { function buildResolverTree(events: Event[]): Node { // First pass we gather up all the events by entity_id const tree: Record = {}; - events.forEach(event => { + events.forEach((event) => { if (event.process.entity_id in tree) { tree[event.process.entity_id].events.push(event); } else { @@ -169,7 +169,7 @@ describe('data generator', () => { let visitedEvents = 0; for (let i = 0; i < generations + 1; i++) { let nextNodes: Node[] = []; - nodes.forEach(node => { + nodes.forEach((node) => { nextNodes = nextNodes.concat(node.children); visitedEvents += node.events.length; }); diff --git a/x-pack/plugins/siem/common/endpoint/generate_data.ts b/x-pack/plugins/siem/common/endpoint/generate_data.ts index 9e3b5a22f1607..f520e2bf91041 100644 --- a/x-pack/plugins/siem/common/endpoint/generate_data.ts +++ b/x-pack/plugins/siem/common/endpoint/generate_data.ts @@ -752,15 +752,15 @@ export class EndpointDocGenerator { } private randomMac(): string { - return [...this.randomNGenerator(255, 6)].map(x => x.toString(16)).join('-'); + return [...this.randomNGenerator(255, 6)].map((x) => x.toString(16)).join('-'); } private randomIP(): string { - return [10, ...this.randomNGenerator(255, 3)].map(x => x.toString()).join('.'); + return [10, ...this.randomNGenerator(255, 3)].map((x) => x.toString()).join('.'); } private randomVersion(): string { - return [6, ...this.randomNGenerator(10, 2)].map(x => x.toString()).join('.'); + return [6, ...this.randomNGenerator(10, 2)].map((x) => x.toString()).join('.'); } private randomChoice(choices: T[]): T { @@ -768,7 +768,7 @@ export class EndpointDocGenerator { } private randomString(length: number): string { - return [...this.randomNGenerator(36, length)].map(x => x.toString(36)).join(''); + return [...this.randomNGenerator(36, length)].map((x) => x.toString(36)).join(''); } private randomHostname(): string { diff --git a/x-pack/plugins/siem/common/exact_check.ts b/x-pack/plugins/siem/common/exact_check.ts index 9484765f9973d..30c5b585a3480 100644 --- a/x-pack/plugins/siem/common/exact_check.ts +++ b/x-pack/plugins/siem/common/exact_check.ts @@ -58,8 +58,8 @@ export const findDifferencesRecursive = (original: T, decodedValue: T): strin return []; } else { const decodedKeys = Object.keys(decodedValue); - const differences = Object.keys(original).flatMap(originalKey => { - const foundKey = decodedKeys.some(key => key === originalKey); + const differences = Object.keys(original).flatMap((originalKey) => { + const foundKey = decodedKeys.some((key) => key === originalKey); const topLevelKey = foundKey ? [] : [originalKey]; // I use lodash to cheat and get an any (not going to lie ;-)) const valueObjectOrArrayOriginal = get(originalKey, original); diff --git a/x-pack/plugins/siem/common/format_errors.ts b/x-pack/plugins/siem/common/format_errors.ts index a9c222050ee38..d712979f9eff3 100644 --- a/x-pack/plugins/siem/common/format_errors.ts +++ b/x-pack/plugins/siem/common/format_errors.ts @@ -7,15 +7,15 @@ import * as t from 'io-ts'; export const formatErrors = (errors: t.Errors): string[] => { - return errors.map(error => { + return errors.map((error) => { if (error.message != null) { return error.message; } else { const mappedContext = error.context .filter( - entry => entry.key != null && !Number.isInteger(+entry.key) && entry.key.trim() !== '' + (entry) => entry.key != null && !Number.isInteger(+entry.key) && entry.key.trim() !== '' ) - .map(entry => entry.key) + .map((entry) => entry.key) .join(','); return `Invalid value "${error.value}" supplied to "${mappedContext}"`; } diff --git a/x-pack/plugins/siem/common/test_utils.ts b/x-pack/plugins/siem/common/test_utils.ts index 29b0119dcbeb7..b96639ad7b034 100644 --- a/x-pack/plugins/siem/common/test_utils.ts +++ b/x-pack/plugins/siem/common/test_utils.ts @@ -36,7 +36,7 @@ export const getPaths = (validation: t.Validation): string[] => { return pipe( validation, fold( - errors => formatErrors(errors), + (errors) => formatErrors(errors), () => ['no errors'] ) ); diff --git a/x-pack/plugins/siem/cypress/integration/cases.spec.ts b/x-pack/plugins/siem/cypress/integration/cases.spec.ts index 8f35a3209c69d..bb2dffe8ddd7d 100644 --- a/x-pack/plugins/siem/cypress/integration/cases.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/cases.spec.ts @@ -84,22 +84,14 @@ describe('Cases', () => { const expectedTags = case1.tags.join(''); cy.get(CASE_DETAILS_PAGE_TITLE).should('have.text', case1.name); cy.get(CASE_DETAILS_STATUS).should('have.text', 'open'); - cy.get(CASE_DETAILS_USER_ACTION) - .eq(USER) - .should('have.text', case1.reporter); - cy.get(CASE_DETAILS_USER_ACTION) - .eq(ACTION) - .should('have.text', 'added description'); + cy.get(CASE_DETAILS_USER_ACTION).eq(USER).should('have.text', case1.reporter); + cy.get(CASE_DETAILS_USER_ACTION).eq(ACTION).should('have.text', 'added description'); cy.get(CASE_DETAILS_DESCRIPTION).should( 'have.text', `${case1.description} ${case1.timeline.title}` ); - cy.get(CASE_DETAILS_USERNAMES) - .eq(REPORTER) - .should('have.text', case1.reporter); - cy.get(CASE_DETAILS_USERNAMES) - .eq(PARTICIPANTS) - .should('have.text', case1.reporter); + cy.get(CASE_DETAILS_USERNAMES).eq(REPORTER).should('have.text', case1.reporter); + cy.get(CASE_DETAILS_USERNAMES).eq(PARTICIPANTS).should('have.text', case1.reporter); cy.get(CASE_DETAILS_TAGS).should('have.text', expectedTags); cy.get(CASE_DETAILS_PUSH_TO_EXTERNAL_SERVICE_BTN).should('have.attr', 'disabled'); diff --git a/x-pack/plugins/siem/cypress/integration/cases_connectors.spec.ts b/x-pack/plugins/siem/cypress/integration/cases_connectors.spec.ts index 9be9067a38ee8..ae4bb82ebfee6 100644 --- a/x-pack/plugins/siem/cypress/integration/cases_connectors.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/cases_connectors.spec.ts @@ -21,7 +21,7 @@ import { CASES } from '../urls/navigation'; describe.skip('Cases connectors', () => { before(() => { cy.server(); - cy.route('POST', '**/api/action').as('createConnector'); + cy.route('POST', '**/api/actions/action').as('createConnector'); cy.route('POST', '**/api/cases/configure').as('saveConnector'); }); @@ -31,16 +31,12 @@ describe.skip('Cases connectors', () => { openAddNewConnectorOption(); addServiceNowConnector(serviceNowConnector); - cy.wait('@createConnector') - .its('status') - .should('eql', 200); + cy.wait('@createConnector').its('status').should('eql', 200); cy.get(TOASTER).should('have.text', "Created 'New connector'"); selectLastConnectorCreated(); - cy.wait('@saveConnector', { timeout: 10000 }) - .its('status') - .should('eql', 200); + cy.wait('@saveConnector', { timeout: 10000 }).its('status').should('eql', 200); cy.get(TOASTER).should('have.text', 'Saved external connection settings'); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/detections.spec.ts b/x-pack/plugins/siem/cypress/integration/detections.spec.ts index f38cb2285b480..91727595708f6 100644 --- a/x-pack/plugins/siem/cypress/integration/detections.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/detections.spec.ts @@ -41,7 +41,7 @@ describe('Detections', () => { cy.get(NUMBER_OF_SIGNALS) .invoke('text') - .then(numberOfSignals => { + .then((numberOfSignals) => { cy.get(SHOWING_SIGNALS).should('have.text', `Showing ${numberOfSignals} signals`); const numberOfSignalsToBeClosed = 3; @@ -127,7 +127,7 @@ describe('Detections', () => { cy.get(NUMBER_OF_SIGNALS) .invoke('text') - .then(numberOfSignals => { + .then((numberOfSignals) => { const numberOfSignalsToBeClosed = 1; const numberOfSignalsToBeSelected = 3; @@ -141,9 +141,7 @@ describe('Detections', () => { waitForSignals(); const expectedNumberOfSignals = +numberOfSignals - numberOfSignalsToBeClosed; - cy.get(NUMBER_OF_SIGNALS) - .invoke('text') - .should('eq', expectedNumberOfSignals.toString()); + cy.get(NUMBER_OF_SIGNALS).invoke('text').should('eq', expectedNumberOfSignals.toString()); cy.get(SHOWING_SIGNALS) .invoke('text') .should('eql', `Showing ${expectedNumberOfSignals.toString()} signals`); @@ -174,7 +172,7 @@ describe('Detections', () => { cy.get(NUMBER_OF_SIGNALS) .invoke('text') - .then(numberOfSignals => { + .then((numberOfSignals) => { const numberOfSignalsToBeOpened = 1; const numberOfSignalsToBeSelected = 3; @@ -189,9 +187,7 @@ describe('Detections', () => { waitForSignals(); const expectedNumberOfSignals = +numberOfSignals - numberOfSignalsToBeOpened; - cy.get(NUMBER_OF_SIGNALS) - .invoke('text') - .should('eq', expectedNumberOfSignals.toString()); + cy.get(NUMBER_OF_SIGNALS).invoke('text').should('eq', expectedNumberOfSignals.toString()); cy.get(SHOWING_SIGNALS) .invoke('text') .should('eql', `Showing ${expectedNumberOfSignals.toString()} signals`); diff --git a/x-pack/plugins/siem/cypress/integration/detections_timeline.spec.ts b/x-pack/plugins/siem/cypress/integration/detections_timeline.spec.ts index 2cac6e0f603b9..6ea34f5203adc 100644 --- a/x-pack/plugins/siem/cypress/integration/detections_timeline.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/detections_timeline.spec.ts @@ -33,11 +33,9 @@ describe('Detections timeline', () => { cy.get(SIGNAL_ID) .first() .invoke('text') - .then(eventId => { + .then((eventId) => { investigateFirstSignalInTimeline(); - cy.get(PROVIDER_BADGE) - .invoke('text') - .should('eql', `_id: "${eventId}"`); + cy.get(PROVIDER_BADGE).invoke('text').should('eql', `_id: "${eventId}"`); }); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/events_viewer.spec.ts b/x-pack/plugins/siem/cypress/integration/events_viewer.spec.ts index aa463b01fd190..26ebaeb844825 100644 --- a/x-pack/plugins/siem/cypress/integration/events_viewer.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/events_viewer.spec.ts @@ -61,13 +61,11 @@ describe('Events Viewer', () => { }); it('displays the `default ECS` category (by default)', () => { - cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_TITLE) - .invoke('text') - .should('eq', 'default ECS'); + cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_TITLE).invoke('text').should('eq', 'default ECS'); }); it('displays a checked checkbox for all of the default events viewer columns that are also in the default ECS category', () => { - defaultHeadersInDefaultEcsCategory.forEach(header => + defaultHeadersInDefaultEcsCategory.forEach((header) => cy.get(FIELDS_BROWSER_CHECKBOX(header.id)).should('be.checked') ); }); @@ -137,25 +135,19 @@ describe('Events Viewer', () => { const filterInput = 'aa7ca589f1b8220002f2fc61c64cfbf1'; // this will never match real data cy.get(HEADER_SUBTITLE) .invoke('text') - .then(initialNumberOfEvents => { + .then((initialNumberOfEvents) => { kqlSearch(`${filterInput}{enter}`); - cy.get(HEADER_SUBTITLE) - .invoke('text') - .should('not.equal', initialNumberOfEvents); + cy.get(HEADER_SUBTITLE).invoke('text').should('not.equal', initialNumberOfEvents); }); }); it('loads more events when the load more button is clicked', () => { const defaultNumberOfLoadedEvents = '25'; - cy.get(LOCAL_EVENTS_COUNT) - .invoke('text') - .should('equal', defaultNumberOfLoadedEvents); + cy.get(LOCAL_EVENTS_COUNT).invoke('text').should('equal', defaultNumberOfLoadedEvents); cy.get(LOAD_MORE).click({ force: true }); - cy.get(LOCAL_EVENTS_COUNT) - .invoke('text') - .should('not.equal', defaultNumberOfLoadedEvents); + cy.get(LOCAL_EVENTS_COUNT).invoke('text').should('not.equal', defaultNumberOfLoadedEvents); }); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/fields_browser.spec.ts b/x-pack/plugins/siem/cypress/integration/fields_browser.spec.ts index 8dddd97f2d830..b058c9fb51fd1 100644 --- a/x-pack/plugins/siem/cypress/integration/fields_browser.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/fields_browser.spec.ts @@ -58,9 +58,7 @@ describe('Fields Browser', () => { }); it('displays the `default ECS` category (by default)', () => { - cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_TITLE) - .invoke('text') - .should('eq', 'default ECS'); + cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_TITLE).invoke('text').should('eq', 'default ECS'); }); it('the `defaultECS` (selected) category count matches the default timeline header count', () => { @@ -70,7 +68,7 @@ describe('Fields Browser', () => { }); it('displays a checked checkbox for all of the default timeline columns', () => { - defaultHeaders.forEach(header => + defaultHeaders.forEach((header) => cy.get(`[data-test-subj="field-${header.id}-checkbox"]`).should('be.checked') ); }); @@ -80,9 +78,7 @@ describe('Fields Browser', () => { filterFieldsBrowser(filterInput); - cy.get(FIELDS_BROWSER_CATEGORIES_COUNT) - .invoke('text') - .should('eq', '2 categories'); + cy.get(FIELDS_BROWSER_CATEGORIES_COUNT).invoke('text').should('eq', '2 categories'); }); it('displays a search results label with the expected count of fields matching the filter input', () => { @@ -92,10 +88,10 @@ describe('Fields Browser', () => { cy.get(FIELDS_BROWSER_HOST_CATEGORIES_COUNT) .invoke('text') - .then(hostCategoriesCount => { + .then((hostCategoriesCount) => { cy.get(FIELDS_BROWSER_SYSTEM_CATEGORIES_COUNT) .invoke('text') - .then(systemCategoriesCount => { + .then((systemCategoriesCount) => { cy.get(FIELDS_BROWSER_FIELDS_COUNT) .invoke('text') .should('eq', `${+hostCategoriesCount + +systemCategoriesCount} fields`); @@ -108,9 +104,7 @@ describe('Fields Browser', () => { filterFieldsBrowser(filterInput); - cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_COUNT) - .invoke('text') - .should('eq', '4'); + cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_COUNT).invoke('text').should('eq', '4'); }); }); @@ -140,9 +134,7 @@ describe('Fields Browser', () => { const category = 'host'; filterFieldsBrowser(category); - cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_TITLE) - .invoke('text') - .should('eq', category); + cy.get(FIELDS_BROWSER_SELECTED_CATEGORY_TITLE).invoke('text').should('eq', category); }); it('adds a field to the timeline when the user clicks the checkbox', () => { diff --git a/x-pack/plugins/siem/cypress/integration/inspect.spec.ts b/x-pack/plugins/siem/cypress/integration/inspect.spec.ts index b6b4e7a72b8f6..d770eb6c761cf 100644 --- a/x-pack/plugins/siem/cypress/integration/inspect.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/inspect.spec.ts @@ -30,7 +30,7 @@ describe('Inspect', () => { closesModal(); }); - INSPECT_HOSTS_BUTTONS_IN_SIEM.forEach(table => + INSPECT_HOSTS_BUTTONS_IN_SIEM.forEach((table) => it(`inspects the ${table.title}`, () => { openStatsAndTables(table); cy.get(INSPECT_MODAL).should('be.visible'); @@ -46,7 +46,7 @@ describe('Inspect', () => { closesModal(); }); - INSPECT_NETWORK_BUTTONS_IN_SIEM.forEach(table => + INSPECT_NETWORK_BUTTONS_IN_SIEM.forEach((table) => it(`inspects the ${table.title}`, () => { openStatsAndTables(table); cy.get(INSPECT_MODAL).should('be.visible'); diff --git a/x-pack/plugins/siem/cypress/integration/overview.spec.ts b/x-pack/plugins/siem/cypress/integration/overview.spec.ts index cadb4beca0f9e..55bcbfafaa092 100644 --- a/x-pack/plugins/siem/cypress/integration/overview.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/overview.spec.ts @@ -20,20 +20,16 @@ describe('Overview Page', () => { it('Host stats render with correct values', () => { expandHostStats(); - HOST_STATS.forEach(stat => { - cy.get(stat.domId) - .invoke('text') - .should('eq', stat.value); + HOST_STATS.forEach((stat) => { + cy.get(stat.domId).invoke('text').should('eq', stat.value); }); }); it('Network stats render with correct values', () => { expandNetworkStats(); - NETWORK_STATS.forEach(stat => { - cy.get(stat.domId) - .invoke('text') - .should('eq', stat.value); + NETWORK_STATS.forEach((stat) => { + cy.get(stat.domId).invoke('text').should('eq', stat.value); }); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/pagination.spec.ts b/x-pack/plugins/siem/cypress/integration/pagination.spec.ts index 482c97fe29c3b..e430520fe1dc4 100644 --- a/x-pack/plugins/siem/cypress/integration/pagination.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/pagination.spec.ts @@ -32,13 +32,13 @@ describe('Pagination', () => { cy.get(PROCESS_NAME_FIELD) .first() .invoke('text') - .then(processNameFirstPage => { + .then((processNameFirstPage) => { goToThirdPage(); waitForUncommonProcessesToBeLoaded(); cy.get(PROCESS_NAME_FIELD) .first() .invoke('text') - .should(processNameSecondPage => { + .should((processNameSecondPage) => { expect(processNameFirstPage).not.to.eq(processNameSecondPage); }); }); @@ -54,7 +54,7 @@ describe('Pagination', () => { cy.get(PROCESS_NAME_FIELD) .first() .invoke('text') - .then(expectedThirdPageResult => { + .then((expectedThirdPageResult) => { openAuthentications(); waitForAuthenticationsToBeLoaded(); cy.get(FIRST_PAGE_SELECTOR).should('have.class', 'euiPaginationButton-isActive'); @@ -64,7 +64,7 @@ describe('Pagination', () => { cy.get(PROCESS_NAME_FIELD) .first() .invoke('text') - .should(actualThirdPageResult => { + .should((actualThirdPageResult) => { expect(expectedThirdPageResult).to.eq(actualThirdPageResult); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/signal_detection_rules.spec.ts b/x-pack/plugins/siem/cypress/integration/signal_detection_rules.spec.ts index ce6a49b675ef1..d07850e23f05e 100644 --- a/x-pack/plugins/siem/cypress/integration/signal_detection_rules.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/signal_detection_rules.spec.ts @@ -46,13 +46,13 @@ describe('Signal detection rules', () => { cy.get(RULE_NAME) .eq(FIFTH_RULE) .invoke('text') - .then(fifthRuleName => { + .then((fifthRuleName) => { activateRule(FIFTH_RULE); waitForRuleToBeActivated(); cy.get(RULE_NAME) .eq(SEVENTH_RULE) .invoke('text') - .then(seventhRuleName => { + .then((seventhRuleName) => { activateRule(SEVENTH_RULE); waitForRuleToBeActivated(); sortByActivatedRules(); @@ -60,23 +60,19 @@ describe('Signal detection rules', () => { cy.get(RULE_NAME) .eq(FIRST_RULE) .invoke('text') - .then(firstRuleName => { + .then((firstRuleName) => { cy.get(RULE_NAME) .eq(SECOND_RULE) .invoke('text') - .then(secondRuleName => { + .then((secondRuleName) => { const expectedRulesNames = `${firstRuleName} ${secondRuleName}`; cy.wrap(expectedRulesNames).should('include', fifthRuleName); cy.wrap(expectedRulesNames).should('include', seventhRuleName); }); }); - cy.get(RULE_SWITCH) - .eq(FIRST_RULE) - .should('have.attr', 'role', 'switch'); - cy.get(RULE_SWITCH) - .eq(SECOND_RULE) - .should('have.attr', 'role', 'switch'); + cy.get(RULE_SWITCH).eq(FIRST_RULE).should('have.attr', 'role', 'switch'); + cy.get(RULE_SWITCH).eq(SECOND_RULE).should('have.attr', 'role', 'switch'); }); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_custom.spec.ts b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_custom.spec.ts index 24325676f0cca..4b5e12124dd40 100644 --- a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_custom.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_custom.spec.ts @@ -84,52 +84,44 @@ describe('Signal detection rules, custom', () => { fillAboutRuleAndContinue(newRule); createAndActivateRule(); - cy.get(CUSTOM_RULES_BTN) - .invoke('text') - .should('eql', 'Custom rules (1)'); + cy.get(CUSTOM_RULES_BTN).invoke('text').should('eql', 'Custom rules (1)'); changeToThreeHundredRowsPerPage(); waitForRulesToBeLoaded(); const expectedNumberOfRules = totalNumberOfPrebuiltRulesInEsArchive + 1; - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRules); }); filterByCustomRules(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', 1); }); - cy.get(RULE_NAME) - .invoke('text') - .should('eql', newRule.name); - cy.get(RISK_SCORE) - .invoke('text') - .should('eql', newRule.riskScore); - cy.get(SEVERITY) - .invoke('text') - .should('eql', newRule.severity); + cy.get(RULE_NAME).invoke('text').should('eql', newRule.name); + cy.get(RISK_SCORE).invoke('text').should('eql', newRule.riskScore); + cy.get(SEVERITY).invoke('text').should('eql', newRule.severity); cy.get('[data-test-subj="rule-switch"]').should('have.attr', 'aria-checked', 'true'); goToRuleDetails(); let expectedUrls = ''; - newRule.referenceUrls.forEach(url => { + newRule.referenceUrls.forEach((url) => { expectedUrls = expectedUrls + url; }); let expectedFalsePositives = ''; - newRule.falsePositivesExamples.forEach(falsePositive => { + newRule.falsePositivesExamples.forEach((falsePositive) => { expectedFalsePositives = expectedFalsePositives + falsePositive; }); let expectedTags = ''; - newRule.tags.forEach(tag => { + newRule.tags.forEach((tag) => { expectedTags = expectedTags + tag; }); let expectedMitre = ''; - newRule.mitre.forEach(mitre => { + newRule.mitre.forEach((mitre) => { expectedMitre = expectedMitre + mitre.tactic; - mitre.techniques.forEach(technique => { + mitre.techniques.forEach((technique) => { expectedMitre = expectedMitre + technique; }); }); @@ -142,69 +134,35 @@ describe('Signal detection rules, custom', () => { 'winlogbeat-*', ]; - cy.get(RULE_NAME_HEADER) - .invoke('text') - .should('eql', `${newRule.name} Beta`); + cy.get(RULE_NAME_HEADER).invoke('text').should('eql', `${newRule.name} Beta`); - cy.get(ABOUT_RULE_DESCRIPTION) - .invoke('text') - .should('eql', newRule.description); - cy.get(ABOUT_STEP) - .eq(ABOUT_SEVERITY) - .invoke('text') - .should('eql', newRule.severity); - cy.get(ABOUT_STEP) - .eq(ABOUT_RISK) - .invoke('text') - .should('eql', newRule.riskScore); - cy.get(ABOUT_STEP) - .eq(ABOUT_URLS) - .invoke('text') - .should('eql', expectedUrls); + cy.get(ABOUT_RULE_DESCRIPTION).invoke('text').should('eql', newRule.description); + cy.get(ABOUT_STEP).eq(ABOUT_SEVERITY).invoke('text').should('eql', newRule.severity); + cy.get(ABOUT_STEP).eq(ABOUT_RISK).invoke('text').should('eql', newRule.riskScore); + cy.get(ABOUT_STEP).eq(ABOUT_URLS).invoke('text').should('eql', expectedUrls); cy.get(ABOUT_STEP) .eq(ABOUT_FALSE_POSITIVES) .invoke('text') .should('eql', expectedFalsePositives); - cy.get(ABOUT_STEP) - .eq(ABOUT_MITRE) - .invoke('text') - .should('eql', expectedMitre); - cy.get(ABOUT_STEP) - .eq(ABOUT_TAGS) - .invoke('text') - .should('eql', expectedTags); + cy.get(ABOUT_STEP).eq(ABOUT_MITRE).invoke('text').should('eql', expectedMitre); + cy.get(ABOUT_STEP).eq(ABOUT_TAGS).invoke('text').should('eql', expectedTags); - cy.get(RULE_ABOUT_DETAILS_HEADER_TOGGLE) - .eq(INVESTIGATION_NOTES_TOGGLE) - .click({ force: true }); - cy.get(ABOUT_INVESTIGATION_NOTES) - .invoke('text') - .should('eql', INVESTIGATION_NOTES_MARKDOWN); + cy.get(RULE_ABOUT_DETAILS_HEADER_TOGGLE).eq(INVESTIGATION_NOTES_TOGGLE).click({ force: true }); + cy.get(ABOUT_INVESTIGATION_NOTES).invoke('text').should('eql', INVESTIGATION_NOTES_MARKDOWN); - cy.get(DEFINITION_INDEX_PATTERNS).then(patterns => { + cy.get(DEFINITION_INDEX_PATTERNS).then((patterns) => { cy.wrap(patterns).each((pattern, index) => { - cy.wrap(pattern) - .invoke('text') - .should('eql', expectedIndexPatterns[index]); + cy.wrap(pattern).invoke('text').should('eql', expectedIndexPatterns[index]); }); }); cy.get(DEFINITION_STEP) .eq(DEFINITION_CUSTOM_QUERY) .invoke('text') .should('eql', `${newRule.customQuery} `); - cy.get(DEFINITION_STEP) - .eq(DEFINITION_TIMELINE) - .invoke('text') - .should('eql', 'Default blank timeline'); + cy.get(DEFINITION_STEP).eq(DEFINITION_TIMELINE).invoke('text').should('eql', 'None'); - cy.get(SCHEDULE_STEP) - .eq(SCHEDULE_RUNS) - .invoke('text') - .should('eql', '5m'); - cy.get(SCHEDULE_STEP) - .eq(SCHEDULE_LOOPBACK) - .invoke('text') - .should('eql', '1m'); + cy.get(SCHEDULE_STEP).eq(SCHEDULE_RUNS).invoke('text').should('eql', '5m'); + cy.get(SCHEDULE_STEP).eq(SCHEDULE_LOOPBACK).invoke('text').should('eql', '1m'); }); }); @@ -224,7 +182,7 @@ describe('Deletes custom rules', () => { it('Deletes one rule', () => { cy.get(RULES_TABLE) .find(RULES_ROW) - .then(rules => { + .then((rules) => { const initialNumberOfRules = rules.length; const expectedNumberOfRulesAfterDeletion = initialNumberOfRules - 1; @@ -235,7 +193,7 @@ describe('Deletes custom rules', () => { deleteFirstRule(); waitForRulesToBeLoaded(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRulesAfterDeletion); }); cy.get(SHOWING_RULES_TEXT) @@ -250,7 +208,7 @@ describe('Deletes custom rules', () => { it('Deletes more than one rule', () => { cy.get(RULES_TABLE) .find(RULES_ROW) - .then(rules => { + .then((rules) => { const initialNumberOfRules = rules.length; const numberOfRulesToBeDeleted = 3; const expectedNumberOfRulesAfterDeletion = initialNumberOfRules - numberOfRulesToBeDeleted; @@ -259,7 +217,7 @@ describe('Deletes custom rules', () => { deleteSelectedRules(); waitForRulesToBeLoaded(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRulesAfterDeletion); }); cy.get(SHOWING_RULES_TEXT) diff --git a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_export.spec.ts b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_export.spec.ts index f0e8b4556f704..aa1a111102160 100644 --- a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_export.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_export.spec.ts @@ -37,8 +37,8 @@ describe('Export rules', () => { waitForSignalsIndexToBeCreated(); goToManageSignalDetectionRules(); exportFirstRule(); - cy.wait('@export').then(xhr => { - cy.readFile(EXPECTED_EXPORTED_RULE_FILE_PATH).then($expectedExportedJson => { + cy.wait('@export').then((xhr) => { + cy.readFile(EXPECTED_EXPORTED_RULE_FILE_PATH).then(($expectedExportedJson) => { cy.wrap(xhr.responseBody).should('eql', $expectedExportedJson); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_ml.spec.ts b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_ml.spec.ts index ad56c905aa4fc..cb04d8117a923 100644 --- a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_ml.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_ml.spec.ts @@ -81,92 +81,65 @@ describe('Signal detection rules, machine learning', () => { fillAboutRuleAndContinue(machineLearningRule); createAndActivateRule(); - cy.get(CUSTOM_RULES_BTN) - .invoke('text') - .should('eql', 'Custom rules (1)'); + cy.get(CUSTOM_RULES_BTN).invoke('text').should('eql', 'Custom rules (1)'); changeToThreeHundredRowsPerPage(); waitForRulesToBeLoaded(); const expectedNumberOfRules = totalNumberOfPrebuiltRulesInEsArchive + 1; - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRules); }); filterByCustomRules(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', 1); }); - cy.get(RULE_NAME) - .invoke('text') - .should('eql', machineLearningRule.name); - cy.get(RISK_SCORE) - .invoke('text') - .should('eql', machineLearningRule.riskScore); - cy.get(SEVERITY) - .invoke('text') - .should('eql', machineLearningRule.severity); + cy.get(RULE_NAME).invoke('text').should('eql', machineLearningRule.name); + cy.get(RISK_SCORE).invoke('text').should('eql', machineLearningRule.riskScore); + cy.get(SEVERITY).invoke('text').should('eql', machineLearningRule.severity); cy.get(RULE_SWITCH).should('have.attr', 'aria-checked', 'true'); goToRuleDetails(); let expectedUrls = ''; - machineLearningRule.referenceUrls.forEach(url => { + machineLearningRule.referenceUrls.forEach((url) => { expectedUrls = expectedUrls + url; }); let expectedFalsePositives = ''; - machineLearningRule.falsePositivesExamples.forEach(falsePositive => { + machineLearningRule.falsePositivesExamples.forEach((falsePositive) => { expectedFalsePositives = expectedFalsePositives + falsePositive; }); let expectedTags = ''; - machineLearningRule.tags.forEach(tag => { + machineLearningRule.tags.forEach((tag) => { expectedTags = expectedTags + tag; }); let expectedMitre = ''; - machineLearningRule.mitre.forEach(mitre => { + machineLearningRule.mitre.forEach((mitre) => { expectedMitre = expectedMitre + mitre.tactic; - mitre.techniques.forEach(technique => { + mitre.techniques.forEach((technique) => { expectedMitre = expectedMitre + technique; }); }); - cy.get(RULE_NAME_HEADER) - .invoke('text') - .should('eql', `${machineLearningRule.name} Beta`); + cy.get(RULE_NAME_HEADER).invoke('text').should('eql', `${machineLearningRule.name} Beta`); - cy.get(ABOUT_RULE_DESCRIPTION) - .invoke('text') - .should('eql', machineLearningRule.description); + cy.get(ABOUT_RULE_DESCRIPTION).invoke('text').should('eql', machineLearningRule.description); cy.get(ABOUT_STEP) .eq(ABOUT_SEVERITY) .invoke('text') .should('eql', machineLearningRule.severity); - cy.get(ABOUT_STEP) - .eq(ABOUT_RISK) - .invoke('text') - .should('eql', machineLearningRule.riskScore); - cy.get(ABOUT_STEP) - .eq(ABOUT_URLS) - .invoke('text') - .should('eql', expectedUrls); + cy.get(ABOUT_STEP).eq(ABOUT_RISK).invoke('text').should('eql', machineLearningRule.riskScore); + cy.get(ABOUT_STEP).eq(ABOUT_URLS).invoke('text').should('eql', expectedUrls); cy.get(ABOUT_STEP) .eq(ABOUT_FALSE_POSITIVES) .invoke('text') .should('eql', expectedFalsePositives); - cy.get(ABOUT_STEP) - .eq(ABOUT_MITRE) - .invoke('text') - .should('eql', expectedMitre); - cy.get(ABOUT_STEP) - .eq(ABOUT_TAGS) - .invoke('text') - .should('eql', expectedTags); + cy.get(ABOUT_STEP).eq(ABOUT_MITRE).invoke('text').should('eql', expectedMitre); + cy.get(ABOUT_STEP).eq(ABOUT_TAGS).invoke('text').should('eql', expectedTags); - cy.get(DEFINITION_STEP) - .eq(RULE_TYPE) - .invoke('text') - .should('eql', 'Machine Learning'); + cy.get(DEFINITION_STEP).eq(RULE_TYPE).invoke('text').should('eql', 'Machine Learning'); cy.get(DEFINITION_STEP) .eq(ANOMALY_SCORE) .invoke('text') @@ -180,18 +153,9 @@ describe('Signal detection rules, machine learning', () => { .invoke('text') .should('eql', machineLearningRule.machineLearningJob); - cy.get(DEFINITION_STEP) - .eq(DEFINITION_TIMELINE) - .invoke('text') - .should('eql', 'Default blank timeline'); + cy.get(DEFINITION_STEP).eq(DEFINITION_TIMELINE).invoke('text').should('eql', 'None'); - cy.get(SCHEDULE_STEP) - .eq(SCHEDULE_RUNS) - .invoke('text') - .should('eql', '5m'); - cy.get(SCHEDULE_STEP) - .eq(SCHEDULE_LOOPBACK) - .invoke('text') - .should('eql', '1m'); + cy.get(SCHEDULE_STEP).eq(SCHEDULE_RUNS).invoke('text').should('eql', '5m'); + cy.get(SCHEDULE_STEP).eq(SCHEDULE_LOOPBACK).invoke('text').should('eql', '1m'); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_prebuilt.spec.ts b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_prebuilt.spec.ts index 866302e81e1a0..005e24dad2a16 100644 --- a/x-pack/plugins/siem/cypress/integration/signal_detection_rules_prebuilt.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/signal_detection_rules_prebuilt.spec.ts @@ -56,14 +56,12 @@ describe('Signal detection rules, prebuilt rules', () => { loadPrebuiltDetectionRules(); waitForPrebuiltDetectionRulesToBeLoaded(); - cy.get(ELASTIC_RULES_BTN) - .invoke('text') - .should('eql', expectedElasticRulesBtnText); + cy.get(ELASTIC_RULES_BTN).invoke('text').should('eql', expectedElasticRulesBtnText); changeToThreeHundredRowsPerPage(); waitForRulesToBeLoaded(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRules); }); }); @@ -83,14 +81,12 @@ describe('Deleting prebuilt rules', () => { loadPrebuiltDetectionRules(); waitForPrebuiltDetectionRulesToBeLoaded(); - cy.get(ELASTIC_RULES_BTN) - .invoke('text') - .should('eql', expectedElasticRulesBtnText); + cy.get(ELASTIC_RULES_BTN).invoke('text').should('eql', expectedElasticRulesBtnText); changeToThreeHundredRowsPerPage(); waitForRulesToBeLoaded(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRules); }); }); @@ -103,7 +99,7 @@ describe('Deleting prebuilt rules', () => { const numberOfRulesToBeSelected = 2; selectNumberOfRules(numberOfRulesToBeSelected); - cy.get(COLLAPSED_ACTION_BTN).each(collapsedItemActionBtn => { + cy.get(COLLAPSED_ACTION_BTN).each((collapsedItemActionBtn) => { cy.wrap(collapsedItemActionBtn).should('have.attr', 'disabled'); }); }); @@ -120,7 +116,7 @@ describe('Deleting prebuilt rules', () => { cy.get(ELASTIC_RULES_BTN) .invoke('text') .should('eql', `Elastic rules (${expectedNumberOfRulesAfterDeletion})`); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRulesAfterDeletion); }); cy.get(RELOAD_PREBUILT_RULES_BTN).should('exist'); @@ -136,7 +132,7 @@ describe('Deleting prebuilt rules', () => { changeToThreeHundredRowsPerPage(); waitForRulesToBeLoaded(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRulesAfterRecovering); }); cy.get(ELASTIC_RULES_BTN) @@ -162,7 +158,7 @@ describe('Deleting prebuilt rules', () => { cy.get(ELASTIC_RULES_BTN) .invoke('text') .should('eql', `Elastic rules (${expectedNumberOfRulesAfterDeletion})`); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRulesAfterDeletion); }); @@ -174,7 +170,7 @@ describe('Deleting prebuilt rules', () => { changeToThreeHundredRowsPerPage(); waitForRulesToBeLoaded(); - cy.get(RULES_TABLE).then($table => { + cy.get(RULES_TABLE).then(($table) => { cy.wrap($table.find(RULES_ROW).length).should('eql', expectedNumberOfRulesAfterRecovering); }); cy.get(ELASTIC_RULES_BTN) diff --git a/x-pack/plugins/siem/cypress/integration/timeline_data_providers.spec.ts b/x-pack/plugins/siem/cypress/integration/timeline_data_providers.spec.ts index 08eb3df57c7a0..243886752706d 100644 --- a/x-pack/plugins/siem/cypress/integration/timeline_data_providers.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/timeline_data_providers.spec.ts @@ -44,11 +44,11 @@ describe('timeline data providers', () => { cy.get(TIMELINE_DROPPED_DATA_PROVIDERS) .first() .invoke('text') - .then(dataProviderText => { + .then((dataProviderText) => { cy.get(HOSTS_NAMES_DRAGGABLE) .first() .invoke('text') - .should(hostname => { + .should((hostname) => { expect(dataProviderText).to.eq(`host.name: "${hostname}"AND`); }); }); diff --git a/x-pack/plugins/siem/cypress/integration/timeline_search_or_filter.spec.ts b/x-pack/plugins/siem/cypress/integration/timeline_search_or_filter.spec.ts index f738ff792049a..0668b91ca4fc1 100644 --- a/x-pack/plugins/siem/cypress/integration/timeline_search_or_filter.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/timeline_search_or_filter.spec.ts @@ -24,7 +24,7 @@ describe('timeline search or filter KQL bar', () => { cy.get(SERVER_SIDE_EVENT_COUNT) .invoke('text') - .then(strCount => { + .then((strCount) => { const intCount = +strCount; cy.wrap(intCount).should('be.above', 0); }); diff --git a/x-pack/plugins/siem/cypress/integration/url_state.spec.ts b/x-pack/plugins/siem/cypress/integration/url_state.spec.ts index cd60745b19040..5625e1812f696 100644 --- a/x-pack/plugins/siem/cypress/integration/url_state.spec.ts +++ b/x-pack/plugins/siem/cypress/integration/url_state.spec.ts @@ -197,10 +197,7 @@ describe('url state', () => { 'href', "#/link-to/network?query=(language:kuery,query:'host.name:%20%22siem-kibana%22%20')&timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1577914409186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1577914409186)))" ); - cy.get(HOSTS_NAMES) - .first() - .invoke('text') - .should('eq', 'siem-kibana'); + cy.get(HOSTS_NAMES).first().invoke('text').should('eq', 'siem-kibana'); openFirstHostDetails(); clearSearchBar(); @@ -241,7 +238,7 @@ describe('url state', () => { cy.get(SERVER_SIDE_EVENT_COUNT) .invoke('text') - .then(strCount => { + .then((strCount) => { const intCount = +strCount; cy.wrap(intCount).should('be.above', 0); }); @@ -252,7 +249,7 @@ describe('url state', () => { cy.wait(5000); cy.url({ timeout: 30000 }).should('match', /\w*-\w*-\w*-\w*-\w*/); - cy.url().then(url => { + cy.url().then((url) => { const matched = url.match(/\w*-\w*-\w*-\w*-\w*/); const newTimelineId = matched && matched.length > 0 ? matched[0] : 'null'; expect(matched).to.have.lengthOf(1); @@ -260,9 +257,7 @@ describe('url state', () => { cy.visit('/app/kibana'); cy.visit(`/app/siem#/overview?timeline\=(id:'${newTimelineId}',isOpen:!t)`); cy.contains('a', 'SIEM'); - cy.get(DATE_PICKER_APPLY_BUTTON_TIMELINE) - .invoke('text') - .should('not.equal', 'Updating'); + cy.get(DATE_PICKER_APPLY_BUTTON_TIMELINE).invoke('text').should('not.equal', 'Updating'); cy.get(TIMELINE_TITLE).should('have.attr', 'value', timelineName); }); }); diff --git a/x-pack/plugins/siem/cypress/plugins/index.js b/x-pack/plugins/siem/cypress/plugins/index.js index 01d31b85de463..35e2669f1611a 100644 --- a/x-pack/plugins/siem/cypress/plugins/index.js +++ b/x-pack/plugins/siem/cypress/plugins/index.js @@ -20,7 +20,7 @@ // eslint-disable-next-line import/no-extraneous-dependencies const wp = require('@cypress/webpack-preprocessor'); -module.exports = on => { +module.exports = (on) => { const options = { webpackOptions: { resolve: { diff --git a/x-pack/plugins/siem/cypress/support/commands.js b/x-pack/plugins/siem/cypress/support/commands.js index e697dbce0f249..4bc62da22aca7 100644 --- a/x-pack/plugins/siem/cypress/support/commands.js +++ b/x-pack/plugins/siem/cypress/support/commands.js @@ -30,8 +30,8 @@ // -- This is will overwrite an existing command -- // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... }) -Cypress.Commands.add('stubSIEMapi', function(dataFileName) { - cy.on('window:before:load', win => { +Cypress.Commands.add('stubSIEMapi', function (dataFileName) { + cy.on('window:before:load', (win) => { // @ts-ignore no null, this is a temp hack see issue above win.fetch = null; }); diff --git a/x-pack/plugins/siem/cypress/support/index.js b/x-pack/plugins/siem/cypress/support/index.js index 672acfd41a264..42abecd4b0bad 100644 --- a/x-pack/plugins/siem/cypress/support/index.js +++ b/x-pack/plugins/siem/cypress/support/index.js @@ -26,13 +26,13 @@ Cypress.Cookies.defaults({ whitelist: 'sid', }); -Cypress.on('uncaught:exception', err => { +Cypress.on('uncaught:exception', (err) => { if (err.message.includes('ResizeObserver loop limit exceeded')) { return false; } }); -Cypress.on('window:before:load', win => { +Cypress.on('window:before:load', (win) => { win.fetch = null; win.Blob = null; }); diff --git a/x-pack/plugins/siem/cypress/tasks/configure_cases.ts b/x-pack/plugins/siem/cypress/tasks/configure_cases.ts index 6ba9e875c7cb0..8ff8fbf4b0cb7 100644 --- a/x-pack/plugins/siem/cypress/tasks/configure_cases.ts +++ b/x-pack/plugins/siem/cypress/tasks/configure_cases.ts @@ -29,7 +29,7 @@ export const addServiceNowConnector = (connector: Connector) => { }; export const openAddNewConnectorOption = () => { - cy.get(MAIN_PAGE).then($page => { + cy.get(MAIN_PAGE).then(($page) => { if ($page.find(SERVICE_NOW_CONNECTOR_CARD).length !== 1) { cy.wait(1000); cy.get(CONNECTORS_DROPDOWN).click({ force: true }); @@ -42,7 +42,7 @@ export const selectLastConnectorCreated = () => { cy.get(CONNECTORS_DROPDOWN).click({ force: true }); cy.get('@createConnector') .its('response') - .then(response => { + .then((response) => { cy.get(CONNECTOR(response.body.id)).click(); }); }; diff --git a/x-pack/plugins/siem/cypress/tasks/create_new_case.ts b/x-pack/plugins/siem/cypress/tasks/create_new_case.ts index 491fdd84e9b38..2dac1065e23eb 100644 --- a/x-pack/plugins/siem/cypress/tasks/create_new_case.ts +++ b/x-pack/plugins/siem/cypress/tasks/create_new_case.ts @@ -24,7 +24,7 @@ export const backToCases = () => { export const createNewCase = (newCase: TestCase) => { cy.get(TITLE_INPUT).type(newCase.name, { force: true }); - newCase.tags.forEach(tag => { + newCase.tags.forEach((tag) => { cy.get(TAGS_INPUT).type(`${tag}{enter}`, { force: true }); }); cy.get(DESCRIPTION_INPUT).type(`${newCase.description} `, { force: true }); @@ -33,9 +33,7 @@ export const createNewCase = (newCase: TestCase) => { cy.get(TIMELINE_SEARCHBOX).type(`${newCase.timeline.title}{enter}`); cy.get(TIMELINE).should('be.visible'); cy.wait(300); - cy.get(TIMELINE) - .eq(1) - .click({ force: true }); + cy.get(TIMELINE).eq(1).click({ force: true }); cy.get(SUBMIT_BTN).click({ force: true }); cy.get(LOADING_SPINNER).should('exist'); diff --git a/x-pack/plugins/siem/cypress/tasks/create_new_rule.ts b/x-pack/plugins/siem/cypress/tasks/create_new_rule.ts index a20ad372a689c..6324b42f3783a 100644 --- a/x-pack/plugins/siem/cypress/tasks/create_new_rule.ts +++ b/x-pack/plugins/siem/cypress/tasks/create_new_rule.ts @@ -44,40 +44,30 @@ export const fillAboutRuleAndContinue = (rule: CustomRule | MachineLearningRule) cy.get(SEVERITY_DROPDOWN).click({ force: true }); cy.get(`#${rule.severity.toLowerCase()}`).click(); - cy.get(RISK_INPUT) - .clear({ force: true }) - .type(`${rule.riskScore}`, { force: true }); + cy.get(RISK_INPUT).clear({ force: true }).type(`${rule.riskScore}`, { force: true }); - rule.tags.forEach(tag => { + rule.tags.forEach((tag) => { cy.get(TAGS_INPUT).type(`${tag}{enter}`, { force: true }); }); cy.get(ADVANCED_SETTINGS_BTN).click({ force: true }); rule.referenceUrls.forEach((url, index) => { - cy.get(REFERENCE_URLS_INPUT) - .eq(index) - .type(url, { force: true }); + cy.get(REFERENCE_URLS_INPUT).eq(index).type(url, { force: true }); cy.get(ADD_REFERENCE_URL_BTN).click({ force: true }); }); rule.falsePositivesExamples.forEach((falsePositive, index) => { - cy.get(FALSE_POSITIVES_INPUT) - .eq(index) - .type(falsePositive, { force: true }); + cy.get(FALSE_POSITIVES_INPUT).eq(index).type(falsePositive, { force: true }); cy.get(ADD_FALSE_POSITIVE_BTN).click({ force: true }); }); rule.mitre.forEach((mitre, index) => { - cy.get(MITRE_TACTIC_DROPDOWN) - .eq(index) - .click({ force: true }); + cy.get(MITRE_TACTIC_DROPDOWN).eq(index).click({ force: true }); cy.contains(MITRE_TACTIC, mitre.tactic).click(); - mitre.techniques.forEach(technique => { - cy.get(MITRE_TECHNIQUES_INPUT) - .eq(index) - .type(`${technique}{enter}`, { force: true }); + mitre.techniques.forEach((technique) => { + cy.get(MITRE_TECHNIQUES_INPUT).eq(index).type(`${technique}{enter}`, { force: true }); }); cy.get(MITRE_BTN).click({ force: true }); @@ -85,17 +75,13 @@ export const fillAboutRuleAndContinue = (rule: CustomRule | MachineLearningRule) cy.get(INVESTIGATION_NOTES_TEXTAREA).type(rule.note, { force: true }); - cy.get(ABOUT_CONTINUE_BTN) - .should('exist') - .click({ force: true }); + cy.get(ABOUT_CONTINUE_BTN).should('exist').click({ force: true }); }; export const fillDefineCustomRuleAndContinue = (rule: CustomRule) => { cy.get(CUSTOM_QUERY_INPUT).type(rule.customQuery); cy.get(CUSTOM_QUERY_INPUT).should('have.attr', 'value', rule.customQuery); - cy.get(DEFINE_CONTINUE_BUTTON) - .should('exist') - .click({ force: true }); + cy.get(DEFINE_CONTINUE_BUTTON).should('exist').click({ force: true }); cy.get(CUSTOM_QUERY_INPUT).should('not.exist'); }; @@ -106,9 +92,7 @@ export const fillDefineMachineLearningRuleAndContinue = (rule: MachineLearningRu cy.get(ANOMALY_THRESHOLD_INPUT).type(`{selectall}${machineLearningRule.anomalyScoreThreshold}`, { force: true, }); - cy.get(DEFINE_CONTINUE_BUTTON) - .should('exist') - .click({ force: true }); + cy.get(DEFINE_CONTINUE_BUTTON).should('exist').click({ force: true }); cy.get(MACHINE_LEARNING_DROPDOWN).should('not.exist'); }; diff --git a/x-pack/plugins/siem/cypress/tasks/date_picker.ts b/x-pack/plugins/siem/cypress/tasks/date_picker.ts index 0d778b737380b..809498d25c5d8 100644 --- a/x-pack/plugins/siem/cypress/tasks/date_picker.ts +++ b/x-pack/plugins/siem/cypress/tasks/date_picker.ts @@ -18,36 +18,26 @@ import { export const setEndDate = (date: string) => { cy.get(DATE_PICKER_END_DATE_POPOVER_BUTTON).click({ force: true }); - cy.get(DATE_PICKER_ABSOLUTE_TAB) - .first() - .click({ force: true }); + cy.get(DATE_PICKER_ABSOLUTE_TAB).first().click({ force: true }); - cy.get(DATE_PICKER_ABSOLUTE_INPUT) - .clear() - .type(date); + cy.get(DATE_PICKER_ABSOLUTE_INPUT).clear().type(date); }; export const setStartDate = (date: string) => { cy.get(DATE_PICKER_START_DATE_POPOVER_BUTTON).click({ force: true }); - cy.get(DATE_PICKER_ABSOLUTE_TAB) - .first() - .click({ force: true }); + cy.get(DATE_PICKER_ABSOLUTE_TAB).first().click({ force: true }); - cy.get(DATE_PICKER_ABSOLUTE_INPUT) - .clear() - .type(date); + cy.get(DATE_PICKER_ABSOLUTE_INPUT).clear().type(date); }; export const setTimelineEndDate = (date: string) => { cy.get(DATE_PICKER_END_DATE_POPOVER_BUTTON_TIMELINE).click({ force: true }); - cy.get(DATE_PICKER_ABSOLUTE_TAB) - .first() - .click({ force: true }); + cy.get(DATE_PICKER_ABSOLUTE_TAB).first().click({ force: true }); cy.get(DATE_PICKER_ABSOLUTE_INPUT).click({ force: true }); - cy.get(DATE_PICKER_ABSOLUTE_INPUT).then($el => { + cy.get(DATE_PICKER_ABSOLUTE_INPUT).then(($el) => { // @ts-ignore if (Cypress.dom.isAttached($el)) { cy.wrap($el).click({ force: true }); @@ -61,12 +51,10 @@ export const setTimelineStartDate = (date: string) => { force: true, }); - cy.get(DATE_PICKER_ABSOLUTE_TAB) - .first() - .click({ force: true }); + cy.get(DATE_PICKER_ABSOLUTE_TAB).first().click({ force: true }); cy.get(DATE_PICKER_ABSOLUTE_INPUT).click({ force: true }); - cy.get(DATE_PICKER_ABSOLUTE_INPUT).then($el => { + cy.get(DATE_PICKER_ABSOLUTE_INPUT).then(($el) => { // @ts-ignore if (Cypress.dom.isAttached($el)) { cy.wrap($el).click({ force: true }); diff --git a/x-pack/plugins/siem/cypress/tasks/detections.ts b/x-pack/plugins/siem/cypress/tasks/detections.ts index c30a178eab489..9461dd5ff99cf 100644 --- a/x-pack/plugins/siem/cypress/tasks/detections.ts +++ b/x-pack/plugins/siem/cypress/tasks/detections.ts @@ -19,9 +19,7 @@ import { import { REFRESH_BUTTON } from '../screens/siem_header'; export const closeFirstSignal = () => { - cy.get(OPEN_CLOSE_SIGNAL_BTN) - .first() - .click({ force: true }); + cy.get(OPEN_CLOSE_SIGNAL_BTN).first().click({ force: true }); }; export const closeSignals = () => { @@ -29,9 +27,7 @@ export const closeSignals = () => { }; export const expandFirstSignal = () => { - cy.get(EXPAND_SIGNAL_BTN) - .first() - .click({ force: true }); + cy.get(EXPAND_SIGNAL_BTN).first().click({ force: true }); }; export const goToClosedSignals = () => { @@ -39,9 +35,7 @@ export const goToClosedSignals = () => { }; export const goToManageSignalDetectionRules = () => { - cy.get(MANAGE_SIGNAL_DETECTION_RULES_BTN) - .should('exist') - .click({ force: true }); + cy.get(MANAGE_SIGNAL_DETECTION_RULES_BTN).should('exist').click({ force: true }); }; export const goToOpenedSignals = () => { @@ -49,9 +43,7 @@ export const goToOpenedSignals = () => { }; export const openFirstSignal = () => { - cy.get(OPEN_CLOSE_SIGNAL_BTN) - .first() - .click({ force: true }); + cy.get(OPEN_CLOSE_SIGNAL_BTN).first().click({ force: true }); }; export const openSignals = () => { @@ -60,27 +52,21 @@ export const openSignals = () => { export const selectNumberOfSignals = (numberOfSignals: number) => { for (let i = 0; i < numberOfSignals; i++) { - cy.get(SIGNAL_CHECKBOX) - .eq(i) - .click({ force: true }); + cy.get(SIGNAL_CHECKBOX).eq(i).click({ force: true }); } }; export const investigateFirstSignalInTimeline = () => { - cy.get(SEND_SIGNAL_TO_TIMELINE_BTN) - .first() - .click({ force: true }); + cy.get(SEND_SIGNAL_TO_TIMELINE_BTN).first().click({ force: true }); }; export const waitForSignals = () => { - cy.get(REFRESH_BUTTON) - .invoke('text') - .should('not.equal', 'Updating'); + cy.get(REFRESH_BUTTON).invoke('text').should('not.equal', 'Updating'); }; export const waitForSignalsIndexToBeCreated = () => { cy.request({ url: '/api/detection_engine/index', retryOnStatusCodeFailure: true }).then( - response => { + (response) => { if (response.status !== 200) { cy.wait(7500); } diff --git a/x-pack/plugins/siem/cypress/tasks/fields_browser.ts b/x-pack/plugins/siem/cypress/tasks/fields_browser.ts index e1d2f24da424c..eb709d2dd5778 100644 --- a/x-pack/plugins/siem/cypress/tasks/fields_browser.ts +++ b/x-pack/plugins/siem/cypress/tasks/fields_browser.ts @@ -30,9 +30,9 @@ export const addsHostGeoContinentNameToTimeline = () => { export const addsHostGeoCountryNameToTimelineDraggingIt = () => { cy.get(FIELDS_BROWSER_DRAGGABLE_HOST_GEO_COUNTRY_NAME_HEADER).should('exist'); - cy.get(FIELDS_BROWSER_DRAGGABLE_HOST_GEO_COUNTRY_NAME_HEADER).then(field => drag(field)); + cy.get(FIELDS_BROWSER_DRAGGABLE_HOST_GEO_COUNTRY_NAME_HEADER).then((field) => drag(field)); - cy.get(FIELDS_BROWSER_HEADER_DROP_AREA).then(headersDropArea => drop(headersDropArea)); + cy.get(FIELDS_BROWSER_HEADER_DROP_AREA).then((headersDropArea) => drop(headersDropArea)); }; export const clearFieldsBrowser = () => { diff --git a/x-pack/plugins/siem/cypress/tasks/hosts/all_hosts.ts b/x-pack/plugins/siem/cypress/tasks/hosts/all_hosts.ts index 312df96df1ddf..f9f902c3de8c7 100644 --- a/x-pack/plugins/siem/cypress/tasks/hosts/all_hosts.ts +++ b/x-pack/plugins/siem/cypress/tasks/hosts/all_hosts.ts @@ -12,16 +12,16 @@ import { drag, dragWithoutDrop, drop } from '../../tasks/common'; export const dragAndDropFirstHostToTimeline = () => { cy.get(HOSTS_NAMES_DRAGGABLE) .first() - .then(firstHost => drag(firstHost)); - cy.get(TIMELINE_DATA_PROVIDERS).then(dataProvidersDropArea => drop(dataProvidersDropArea)); + .then((firstHost) => drag(firstHost)); + cy.get(TIMELINE_DATA_PROVIDERS).then((dataProvidersDropArea) => drop(dataProvidersDropArea)); }; export const dragFirstHostToEmptyTimelineDataProviders = () => { cy.get(HOSTS_NAMES_DRAGGABLE) .first() - .then(host => drag(host)); + .then((host) => drag(host)); - cy.get(TIMELINE_DATA_PROVIDERS_EMPTY).then(dataProvidersDropArea => + cy.get(TIMELINE_DATA_PROVIDERS_EMPTY).then((dataProvidersDropArea) => dragWithoutDrop(dataProvidersDropArea) ); }; @@ -29,12 +29,10 @@ export const dragFirstHostToEmptyTimelineDataProviders = () => { export const dragFirstHostToTimeline = () => { cy.get(HOSTS_NAMES_DRAGGABLE) .first() - .then(host => drag(host)); + .then((host) => drag(host)); }; export const openFirstHostDetails = () => { - cy.get(HOSTS_NAMES) - .first() - .click({ force: true }); + cy.get(HOSTS_NAMES).first().click({ force: true }); }; export const waitForAllHostsToBeLoaded = () => { diff --git a/x-pack/plugins/siem/cypress/tasks/hosts/authentications.ts b/x-pack/plugins/siem/cypress/tasks/hosts/authentications.ts index ce3767a340376..7ba7f227964ab 100644 --- a/x-pack/plugins/siem/cypress/tasks/hosts/authentications.ts +++ b/x-pack/plugins/siem/cypress/tasks/hosts/authentications.ts @@ -9,7 +9,5 @@ import { REFRESH_BUTTON } from '../../screens/siem_header'; export const waitForAuthenticationsToBeLoaded = () => { cy.get(AUTHENTICATIONS_TABLE).should('exist'); - cy.get(REFRESH_BUTTON) - .invoke('text') - .should('not.equal', 'Updating'); + cy.get(REFRESH_BUTTON).invoke('text').should('not.equal', 'Updating'); }; diff --git a/x-pack/plugins/siem/cypress/tasks/hosts/events.ts b/x-pack/plugins/siem/cypress/tasks/hosts/events.ts index de0c99bd31dff..dff58b4b0e9ea 100644 --- a/x-pack/plugins/siem/cypress/tasks/hosts/events.ts +++ b/x-pack/plugins/siem/cypress/tasks/hosts/events.ts @@ -39,9 +39,7 @@ export const loadMoreEvents = () => { export const openEventsViewerFieldsBrowser = () => { cy.get(EVENTS_VIEWER_FIELDS_BUTTON).click({ force: true }); - cy.get(SERVER_SIDE_EVENT_COUNT) - .invoke('text') - .should('not.equal', '0'); + cy.get(SERVER_SIDE_EVENT_COUNT).invoke('text').should('not.equal', '0'); cy.get(FIELDS_BROWSER_CONTAINER).should('exist'); }; @@ -58,8 +56,5 @@ export const resetFields = () => { }; export const waitsForEventsToBeLoaded = () => { - cy.get(SERVER_SIDE_EVENT_COUNT) - .should('exist') - .invoke('text') - .should('not.equal', '0'); + cy.get(SERVER_SIDE_EVENT_COUNT).should('exist').invoke('text').should('not.equal', '0'); }; diff --git a/x-pack/plugins/siem/cypress/tasks/hosts/uncommon_processes.ts b/x-pack/plugins/siem/cypress/tasks/hosts/uncommon_processes.ts index a28a7df07c3f8..c86b169d60a13 100644 --- a/x-pack/plugins/siem/cypress/tasks/hosts/uncommon_processes.ts +++ b/x-pack/plugins/siem/cypress/tasks/hosts/uncommon_processes.ts @@ -9,7 +9,5 @@ import { REFRESH_BUTTON } from '../../screens/siem_header'; export const waitForUncommonProcessesToBeLoaded = () => { cy.get(UNCOMMON_PROCESSES_TABLE).should('exist'); - cy.get(REFRESH_BUTTON) - .invoke('text') - .should('not.equal', 'Updating'); + cy.get(REFRESH_BUTTON).invoke('text').should('not.equal', 'Updating'); }; diff --git a/x-pack/plugins/siem/cypress/tasks/login.ts b/x-pack/plugins/siem/cypress/tasks/login.ts index 1bbf41d05db00..13580037b3d7c 100644 --- a/x-pack/plugins/siem/cypress/tasks/login.ts +++ b/x-pack/plugins/siem/cypress/tasks/login.ts @@ -98,7 +98,7 @@ const loginViaConfig = () => { ); // read the login details from `kibana.dev.yaml` - cy.readFile(KIBANA_DEV_YML_PATH).then(kibanaDevYml => { + cy.readFile(KIBANA_DEV_YML_PATH).then((kibanaDevYml) => { const config = yaml.safeLoad(kibanaDevYml); // programmatically authenticate without interacting with the Kibana login page diff --git a/x-pack/plugins/siem/cypress/tasks/overview.ts b/x-pack/plugins/siem/cypress/tasks/overview.ts index 0ca4059a90097..38c3c00fbc365 100644 --- a/x-pack/plugins/siem/cypress/tasks/overview.ts +++ b/x-pack/plugins/siem/cypress/tasks/overview.ts @@ -7,9 +7,7 @@ import { OVERVIEW_HOST_STATS, OVERVIEW_NETWORK_STATS } from '../screens/overview'; export const expand = (statType: string) => { - cy.get(statType) - .find('button') - .invoke('click'); + cy.get(statType).find('button').invoke('click'); }; export const expandHostStats = () => { diff --git a/x-pack/plugins/siem/cypress/tasks/siem_header.ts b/x-pack/plugins/siem/cypress/tasks/siem_header.ts index 4c43948445c58..2cc9199a42bbb 100644 --- a/x-pack/plugins/siem/cypress/tasks/siem_header.ts +++ b/x-pack/plugins/siem/cypress/tasks/siem_header.ts @@ -7,9 +7,7 @@ import { KQL_INPUT, REFRESH_BUTTON } from '../screens/siem_header'; export const clearSearchBar = () => { - cy.get(KQL_INPUT) - .clear() - .type('{enter}'); + cy.get(KQL_INPUT).clear().type('{enter}'); }; export const kqlSearch = (search: string) => { @@ -21,8 +19,5 @@ export const navigateFromHeaderTo = (page: string) => { }; export const refreshPage = () => { - cy.get(REFRESH_BUTTON) - .click({ force: true }) - .invoke('text') - .should('not.equal', 'Updating'); + cy.get(REFRESH_BUTTON).click({ force: true }).invoke('text').should('not.equal', 'Updating'); }; diff --git a/x-pack/plugins/siem/cypress/tasks/siem_main.ts b/x-pack/plugins/siem/cypress/tasks/siem_main.ts index 2bdc62ecbdc03..eece7edcb2b44 100644 --- a/x-pack/plugins/siem/cypress/tasks/siem_main.ts +++ b/x-pack/plugins/siem/cypress/tasks/siem_main.ts @@ -11,7 +11,7 @@ export const openTimeline = () => { }; export const openTimelineIfClosed = () => { - cy.get(MAIN_PAGE).then($page => { + cy.get(MAIN_PAGE).then(($page) => { if ($page.find(TIMELINE_TOGGLE_BUTTON).length === 1) { openTimeline(); } diff --git a/x-pack/plugins/siem/cypress/tasks/signal_detection_rules.ts b/x-pack/plugins/siem/cypress/tasks/signal_detection_rules.ts index 5a4d71de9e851..6b2c4644a95d1 100644 --- a/x-pack/plugins/siem/cypress/tasks/signal_detection_rules.ts +++ b/x-pack/plugins/siem/cypress/tasks/signal_detection_rules.ts @@ -27,9 +27,7 @@ import { } from '../screens/signal_detection_rules'; export const activateRule = (rulePosition: number) => { - cy.get(RULE_SWITCH) - .eq(rulePosition) - .click({ force: true }); + cy.get(RULE_SWITCH).eq(rulePosition).click({ force: true }); }; export const changeToThreeHundredRowsPerPage = () => { @@ -38,9 +36,7 @@ export const changeToThreeHundredRowsPerPage = () => { }; export const deleteFirstRule = () => { - cy.get(COLLAPSED_ACTION_BTN) - .first() - .click({ force: true }); + cy.get(COLLAPSED_ACTION_BTN).first().click({ force: true }); cy.get(DELETE_RULE_ACTION_BTN).click(); }; @@ -50,9 +46,7 @@ export const deleteSelectedRules = () => { }; export const exportFirstRule = () => { - cy.get(COLLAPSED_ACTION_BTN) - .first() - .click({ force: true }); + cy.get(COLLAPSED_ACTION_BTN).first().click({ force: true }); cy.get(EXPORT_ACTION_BTN).click(); cy.get(EXPORT_ACTION_BTN).should('not.exist'); }; @@ -72,9 +66,7 @@ export const goToRuleDetails = () => { }; export const loadPrebuiltDetectionRules = () => { - cy.get(LOAD_PREBUILT_RULES_BTN) - .should('exist') - .click({ force: true }); + cy.get(LOAD_PREBUILT_RULES_BTN).should('exist').click({ force: true }); }; export const reloadDeletedRules = () => { @@ -83,9 +75,7 @@ export const reloadDeletedRules = () => { export const selectNumberOfRules = (numberOfRules: number) => { for (let i = 0; i < numberOfRules; i++) { - cy.get(RULE_CHECKBOX) - .eq(i) - .click({ force: true }); + cy.get(RULE_CHECKBOX).eq(i).click({ force: true }); } }; diff --git a/x-pack/plugins/siem/cypress/tasks/timeline.ts b/x-pack/plugins/siem/cypress/tasks/timeline.ts index 7873a76bf99f1..38da611428b2e 100644 --- a/x-pack/plugins/siem/cypress/tasks/timeline.ts +++ b/x-pack/plugins/siem/cypress/tasks/timeline.ts @@ -29,10 +29,7 @@ export const hostExistsQuery = 'host.name: *'; export const addDescriptionToTimeline = (description: string) => { cy.get(TIMELINE_DESCRIPTION).type(`${description}{enter}`); - cy.get(DATE_PICKER_APPLY_BUTTON_TIMELINE) - .click() - .invoke('text') - .should('not.equal', 'Updating'); + cy.get(DATE_PICKER_APPLY_BUTTON_TIMELINE).click().invoke('text').should('not.equal', 'Updating'); }; export const addNameToTimeline = (name: string) => { @@ -63,9 +60,7 @@ export const executeTimelineKQL = (query: string) => { }; export const expandFirstTimelineEventDetails = () => { - cy.get(TOGGLE_TIMELINE_EXPAND_EVENT) - .first() - .click({ force: true }); + cy.get(TOGGLE_TIMELINE_EXPAND_EVENT).first().click({ force: true }); }; export const openTimelineFieldsBrowser = () => { @@ -85,7 +80,7 @@ export const populateTimeline = () => { executeTimelineKQL(hostExistsQuery); cy.get(SERVER_SIDE_EVENT_COUNT) .invoke('text') - .then(strCount => { + .then((strCount) => { const intCount = +strCount; cy.wrap(intCount).should('be.above', 0); }); @@ -100,9 +95,9 @@ export const uncheckTimestampToggleField = () => { export const dragAndDropIdToggleFieldToTimeline = () => { cy.get(ID_HEADER_FIELD).should('not.exist'); - cy.get(ID_FIELD).then(field => drag(field)); + cy.get(ID_FIELD).then((field) => drag(field)); - cy.get(`[data-test-subj="timeline"] [data-test-subj="headers-group"]`).then(headersDropArea => + cy.get(`[data-test-subj="timeline"] [data-test-subj="headers-group"]`).then((headersDropArea) => drop(headersDropArea) ); }; diff --git a/x-pack/plugins/siem/public/alerts/components/detection_engine_header_page/index.tsx b/x-pack/plugins/siem/public/alerts/components/detection_engine_header_page/index.tsx index 42a5afb600fba..a3e76557a6ff5 100644 --- a/x-pack/plugins/siem/public/alerts/components/detection_engine_header_page/index.tsx +++ b/x-pack/plugins/siem/public/alerts/components/detection_engine_header_page/index.tsx @@ -9,7 +9,7 @@ import React from 'react'; import { HeaderPage, HeaderPageProps } from '../../../common/components/header_page'; import * as i18n from './translations'; -const DetectionEngineHeaderPageComponent: React.FC = props => ( +const DetectionEngineHeaderPageComponent: React.FC = (props) => ( ); diff --git a/x-pack/plugins/siem/public/alerts/components/rules/add_item_form/index.tsx b/x-pack/plugins/siem/public/alerts/components/rules/add_item_form/index.tsx index d6c18078f8acd..c8eb6f69c95ba 100644 --- a/x-pack/plugins/siem/public/alerts/components/rules/add_item_form/index.tsx +++ b/x-pack/plugins/siem/public/alerts/components/rules/add_item_form/index.tsx @@ -158,7 +158,7 @@ export const AddItem = ({ setShowValidation(true)} - onChange={e => updateItem(e, index)} + onChange={(e) => updateItem(e, index)} fullWidth {...euiFieldProps} /> diff --git a/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.test.tsx b/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.test.tsx index 70de3d2a72dcc..e39ee38d71da7 100644 --- a/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.test.tsx +++ b/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.test.tsx @@ -314,16 +314,10 @@ describe('helpers', () => { expect(result[0].title).toEqual('Test label'); expect(wrapper.find('[data-test-subj="stringArrayDescriptionBadgeItem"]')).toHaveLength(2); expect( - wrapper - .find('[data-test-subj="stringArrayDescriptionBadgeItem"]') - .first() - .text() + wrapper.find('[data-test-subj="stringArrayDescriptionBadgeItem"]').first().text() ).toEqual('tag1'); expect( - wrapper - .find('[data-test-subj="stringArrayDescriptionBadgeItem"]') - .at(1) - .text() + wrapper.find('[data-test-subj="stringArrayDescriptionBadgeItem"]').at(1).text() ).toEqual('tag2'); }); }); @@ -353,16 +347,10 @@ describe('helpers', () => { expect(result[0].title).toEqual('Test label'); expect(wrapper.find('[data-test-subj="urlsDescriptionReferenceLinkItem"]')).toHaveLength(2); expect( - wrapper - .find('[data-test-subj="urlsDescriptionReferenceLinkItem"]') - .first() - .text() + wrapper.find('[data-test-subj="urlsDescriptionReferenceLinkItem"]').first().text() ).toEqual('www.test.com'); expect( - wrapper - .find('[data-test-subj="urlsDescriptionReferenceLinkItem"]') - .at(1) - .text() + wrapper.find('[data-test-subj="urlsDescriptionReferenceLinkItem"]').at(1).text() ).toEqual('www.test2.com'); }); }); diff --git a/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.tsx b/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.tsx index ad3ed538c875b..091065eedfc22 100644 --- a/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.tsx +++ b/x-pack/plugins/siem/public/alerts/components/rules/description_step/helpers.tsx @@ -121,7 +121,7 @@ export const buildThreatDescription = ({ label, threat }: BuildThreatDescription description: ( {threat.map((singleThreat, index) => { - const tactic = tacticsOptions.find(t => t.id === singleThreat.tactic.id); + const tactic = tacticsOptions.find((t) => t.id === singleThreat.tactic.id); return ( - {singleThreat.technique.map(technique => { - const myTechnique = techniquesOptions.find(t => t.id === technique.id); + {singleThreat.technique.map((technique) => { + const myTechnique = techniquesOptions.find((t) => t.id === technique.id); return (