apply prettier styles

This commit is contained in:
restrry 2020-05-22 09:08:58 +02:00
parent 64ad4f3f92
commit bf04235dae
7130 changed files with 31393 additions and 37163 deletions

View file

@ -50,7 +50,7 @@ const ELASTIC_LICENSE_HEADER = `
`; `;
const allMochaRulesOff = {}; const allMochaRulesOff = {};
Object.keys(require('eslint-plugin-mocha').rules).forEach(k => { Object.keys(require('eslint-plugin-mocha').rules).forEach((k) => {
allMochaRulesOff['mocha/' + k] = 'off'; allMochaRulesOff['mocha/' + k] = 'off';
}); });

View file

@ -71,7 +71,7 @@ export const AlwaysFiringExpression: React.FunctionComponent<AlwaysFiringParamsP
<EuiFieldNumber <EuiFieldNumber
name="instances" name="instances"
value={instances} value={instances}
onChange={event => { onChange={(event) => {
setAlertParams('instances', event.target.valueAsNumber); setAlertParams('instances', event.target.valueAsNumber);
}} }}
/> />

View file

@ -51,7 +51,7 @@ interface PeopleinSpaceParamsProps {
} }
function isValueInEnum(enumeratin: Record<string, any>, value: any): boolean { function isValueInEnum(enumeratin: Record<string, any>, value: any): boolean {
return !!Object.values(enumeratin).find(enumVal => enumVal === value); return !!Object.values(enumeratin).find((enumVal) => enumVal === value);
} }
export function getAlertType(): AlertTypeModel { export function getAlertType(): AlertTypeModel {
@ -139,7 +139,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent<PeopleinSpaceParam
const errorsCallout = flatten( const errorsCallout = flatten(
Object.entries(errors).map(([field, errs]: [string, string[]]) => Object.entries(errors).map(([field, errs]: [string, string[]]) =>
errs.map(e => ( errs.map((e) => (
<p> <p>
<EuiTextColor color="accent">{field}:</EuiTextColor>`: ${errs}` <EuiTextColor color="accent">{field}:</EuiTextColor>`: ${errs}`
</p> </p>
@ -189,7 +189,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent<PeopleinSpaceParam
<EuiSelect <EuiSelect
compressed compressed
value={craftTrigger.craft} value={craftTrigger.craft}
onChange={event => { onChange={(event) => {
setAlertParams('craft', event.target.value); setAlertParams('craft', event.target.value);
setCraftTrigger({ setCraftTrigger({
craft: event.target.value, craft: event.target.value,
@ -238,7 +238,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent<PeopleinSpaceParam
<EuiSelect <EuiSelect
compressed compressed
value={outerSpaceCapacityTrigger.op} value={outerSpaceCapacityTrigger.op}
onChange={event => { onChange={(event) => {
setAlertParams('op', event.target.value); setAlertParams('op', event.target.value);
setOuterSpaceCapacity({ setOuterSpaceCapacity({
...outerSpaceCapacityTrigger, ...outerSpaceCapacityTrigger,
@ -258,7 +258,7 @@ export const PeopleinSpaceExpression: React.FunctionComponent<PeopleinSpaceParam
<EuiFieldNumber <EuiFieldNumber
compressed compressed
value={outerSpaceCapacityTrigger.outerSpaceCapacity} value={outerSpaceCapacityTrigger.outerSpaceCapacity}
onChange={event => { onChange={(event) => {
setAlertParams('outerSpaceCapacity', event.target.valueAsNumber); setAlertParams('outerSpaceCapacity', event.target.valueAsNumber);
setOuterSpaceCapacity({ setOuterSpaceCapacity({
...outerSpaceCapacityTrigger, ...outerSpaceCapacityTrigger,

View file

@ -68,10 +68,7 @@ export const alertType: AlertType = {
if (getOperator(op)(peopleInCraft.length, outerSpaceCapacity)) { if (getOperator(op)(peopleInCraft.length, outerSpaceCapacity)) {
peopleInCraft.forEach(({ craft, name }) => { peopleInCraft.forEach(({ craft, name }) => {
services services.alertInstanceFactory(name).replaceState({ craft }).scheduleActions('default');
.alertInstanceFactory(name)
.replaceState({ craft })
.scheduleActions('default');
}); });
} }

View file

@ -82,7 +82,7 @@ export const CountUntil: React.FC<Props> = ({ fetchStreaming }) => {
<EuiFieldNumber <EuiFieldNumber
placeholder="Some integer" placeholder="Some integer"
value={data} value={data}
onChange={e => setData(Number(e.target.value))} onChange={(e) => setData(Number(e.target.value))}
/> />
</EuiFormRow> </EuiFormRow>
<EuiButton type="submit" fill onClick={handleSubmit}> <EuiButton type="submit" fill onClick={handleSubmit}>

View file

@ -49,18 +49,18 @@ export const DoubleIntegers: React.FC<Props> = ({ double }) => {
setShowingResults(true); setShowingResults(true);
const nums = numbers const nums = numbers
.split('\n') .split('\n')
.map(num => num.trim()) .map((num) => num.trim())
.filter(Boolean) .filter(Boolean)
.map(Number); .map(Number);
counter.set(nums.length); counter.set(nums.length);
nums.forEach(num => { nums.forEach((num) => {
double({ num }).then( double({ num }).then(
result => { (result) => {
if (!isMounted()) return; if (!isMounted()) return;
counter.dec(); counter.dec();
pushResult({ num, result }); pushResult({ num, result });
}, },
error => { (error) => {
if (!isMounted()) return; if (!isMounted()) return;
counter.dec(); counter.dec();
pushResult({ num, error }); pushResult({ num, error });
@ -94,7 +94,7 @@ export const DoubleIntegers: React.FC<Props> = ({ double }) => {
fullWidth fullWidth
placeholder="Enter numbers in milliseconds separated by new line" placeholder="Enter numbers in milliseconds separated by new line"
value={numbers} value={numbers}
onChange={e => setNumbers(e.target.value)} onChange={(e) => setNumbers(e.target.value)}
/> />
</EuiFormRow> </EuiFormRow>
<EuiButton type="submit" fill onClick={handleSubmit}> <EuiButton type="submit" fill onClick={handleSubmit}>

View file

@ -30,7 +30,7 @@ export const App: React.FC = () => {
const routeElements: React.ReactElement[] = []; const routeElements: React.ReactElement[] = [];
for (const { items } of routes) { for (const { items } of routes) {
for (const { id, component } of items) { for (const { id, component } of items) {
routeElements.push(<Route key={id} path={`/${id}`} render={props => component} />); routeElements.push(<Route key={id} path={`/${id}`} render={(props) => component} />);
} }
} }

View file

@ -39,7 +39,7 @@ export const Sidebar: React.FC<SidebarProps> = () => {
id, id,
name: title, name: title,
isSelected: true, isSelected: true,
items: items.map(route => ({ items: items.map((route) => ({
id: route.id, id: route.id,
name: route.title, name: route.title,
onClick: () => history.push(`/${route.id}`), onClick: () => history.push(`/${route.id}`),

View file

@ -54,7 +54,7 @@ export class BfetchExplorerPlugin implements Plugin {
// Validate inputs. // Validate inputs.
if (num < 0) throw new Error('Invalid number'); if (num < 0) throw new Error('Invalid number');
// Wait number of specified milliseconds. // 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. // Double the number and send it back.
return { num: 2 * num }; return { num: 2 * num };
}, },

View file

@ -40,7 +40,7 @@ const totalMap = new Map<string, number>();
export const asyncDemoSearchStrategyProvider: TSearchStrategyProvider<typeof ASYNC_DEMO_SEARCH_STRATEGY> = () => { export const asyncDemoSearchStrategyProvider: TSearchStrategyProvider<typeof ASYNC_DEMO_SEARCH_STRATEGY> = () => {
return { return {
search: async request => { search: async (request) => {
const id = request.id ?? generateId(); const id = request.id ?? generateId();
const loaded = (loadedMap.get(id) ?? 0) + 1; const loaded = (loadedMap.get(id) ?? 0) + 1;
@ -52,7 +52,7 @@ export const asyncDemoSearchStrategyProvider: TSearchStrategyProvider<typeof ASY
const fibonacciSequence = getFibonacciSequence(loaded); const fibonacciSequence = getFibonacciSequence(loaded);
return { id, total, loaded, fibonacciSequence }; return { id, total, loaded, fibonacciSequence };
}, },
cancel: async id => { cancel: async (id) => {
loadedMap.delete(id); loadedMap.delete(id);
totalMap.delete(id); totalMap.delete(id);
}, },

View file

@ -22,7 +22,7 @@ import { DEMO_SEARCH_STRATEGY } from '../common';
export const demoSearchStrategyProvider: TSearchStrategyProvider<typeof DEMO_SEARCH_STRATEGY> = () => { export const demoSearchStrategyProvider: TSearchStrategyProvider<typeof DEMO_SEARCH_STRATEGY> = () => {
return { return {
search: request => { search: (request) => {
return Promise.resolve({ return Promise.resolve({
greeting: greeting:
request.mood === 'happy' request.mood === 'happy'

View file

@ -40,7 +40,7 @@ function renderList(
embeddableServices: EmbeddableStart embeddableServices: EmbeddableStart
) { ) {
let number = 0; let number = 0;
const list = Object.values(panels).map(panel => { const list = Object.values(panels).map((panel) => {
const child = embeddable.getChild(panel.explicitInput.id); const child = embeddable.getChild(panel.explicitInput.id);
number++; number++;
return ( return (

View file

@ -55,7 +55,7 @@ function wrapSearchTerms(task: string, search?: string) {
} }
function renderTasks(tasks: MultiTaskTodoInput['tasks'], search?: string) { function renderTasks(tasks: MultiTaskTodoInput['tasks'], search?: string) {
return tasks.map(task => ( return tasks.map((task) => (
<EuiListGroupItem <EuiListGroupItem
key={task} key={task}
data-test-subj="multiTaskTodoTask" data-test-subj="multiTaskTodoTask"

View file

@ -48,7 +48,7 @@ function getHasMatch(tasks: string[], title?: string, search?: string) {
if (title && title.match(search)) return true; if (title && title.match(search)) return true;
const match = tasks.find(task => task.match(search)); const match = tasks.find((task) => task.match(search));
if (match) return true; if (match) return true;
return false; return false;

View file

@ -65,12 +65,12 @@ export class SearchableListContainerComponentInner extends Component<Props, Stat
const checked: { [id: string]: boolean } = {}; const checked: { [id: string]: boolean } = {};
const hasMatch: { [id: string]: boolean } = {}; const hasMatch: { [id: string]: boolean } = {};
props.embeddable.getChildIds().forEach(id => { props.embeddable.getChildIds().forEach((id) => {
checked[id] = false; checked[id] = false;
const output = props.embeddable.getChild(id).getOutput(); const output = props.embeddable.getChild(id).getOutput();
hasMatch[id] = hasHasMatchOutput(output) && output.hasMatch; hasMatch[id] = hasHasMatchOutput(output) && output.hasMatch;
}); });
props.embeddable.getChildIds().forEach(id => (checked[id] = false)); props.embeddable.getChildIds().forEach((id) => (checked[id] = false));
this.state = { this.state = {
checked, checked,
hasMatch, hasMatch,
@ -78,13 +78,13 @@ export class SearchableListContainerComponentInner extends Component<Props, Stat
} }
componentDidMount() { componentDidMount() {
this.props.embeddable.getChildIds().forEach(id => { this.props.embeddable.getChildIds().forEach((id) => {
this.subscriptions[id] = this.props.embeddable this.subscriptions[id] = this.props.embeddable
.getChild(id) .getChild(id)
.getOutput$() .getOutput$()
.subscribe(output => { .subscribe((output) => {
if (hasHasMatchOutput(output)) { if (hasHasMatchOutput(output)) {
this.setState(prevState => ({ this.setState((prevState) => ({
hasMatch: { hasMatch: {
...prevState.hasMatch, ...prevState.hasMatch,
[id]: output.hasMatch, [id]: output.hasMatch,
@ -96,7 +96,7 @@ export class SearchableListContainerComponentInner extends Component<Props, Stat
} }
componentWillUnmount() { componentWillUnmount() {
Object.values(this.subscriptions).forEach(sub => sub.unsubscribe()); Object.values(this.subscriptions).forEach((sub) => sub.unsubscribe());
} }
private updateSearch = (search: string) => { private updateSearch = (search: string) => {
@ -104,7 +104,7 @@ export class SearchableListContainerComponentInner extends Component<Props, Stat
}; };
private deleteChecked = () => { private deleteChecked = () => {
Object.values(this.props.input.panels).map(panel => { Object.values(this.props.input.panels).map((panel) => {
if (this.state.checked[panel.explicitInput.id]) { if (this.state.checked[panel.explicitInput.id]) {
this.props.embeddable.removeEmbeddable(panel.explicitInput.id); this.props.embeddable.removeEmbeddable(panel.explicitInput.id);
this.subscriptions[panel.explicitInput.id].unsubscribe(); this.subscriptions[panel.explicitInput.id].unsubscribe();
@ -115,7 +115,7 @@ export class SearchableListContainerComponentInner extends Component<Props, Stat
private checkMatching = () => { private checkMatching = () => {
const { input, embeddable } = this.props; const { input, embeddable } = this.props;
const checked: { [key: string]: boolean } = {}; 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 child = embeddable.getChild(panel.explicitInput.id);
const output = child.getOutput(); const output = child.getOutput();
if (hasHasMatchOutput(output) && output.hasMatch) { if (hasHasMatchOutput(output) && output.hasMatch) {
@ -126,7 +126,7 @@ export class SearchableListContainerComponentInner extends Component<Props, Stat
}; };
private toggleCheck = (isChecked: boolean, id: string) => { private toggleCheck = (isChecked: boolean, id: string) => {
this.setState(prevState => ({ checked: { ...prevState.checked, [id]: isChecked } })); this.setState((prevState) => ({ checked: { ...prevState.checked, [id]: isChecked } }));
}; };
public renderControls() { public renderControls() {
@ -156,7 +156,7 @@ export class SearchableListContainerComponentInner extends Component<Props, Stat
<EuiFieldText <EuiFieldText
data-test-subj="filterTodos" data-test-subj="filterTodos"
value={this.props.input.search || ''} value={this.props.input.search || ''}
onChange={ev => this.updateSearch(ev.target.value)} onChange={(ev) => this.updateSearch(ev.target.value)}
/> />
</EuiFormRow> </EuiFormRow>
</EuiFlexItem> </EuiFlexItem>
@ -183,7 +183,7 @@ export class SearchableListContainerComponentInner extends Component<Props, Stat
private renderList() { private renderList() {
const { embeddableServices, input, embeddable } = this.props; const { embeddableServices, input, embeddable } = this.props;
let id = 0; let id = 0;
const list = Object.values(input.panels).map(panel => { const list = Object.values(input.panels).map((panel) => {
const childEmbeddable = embeddable.getChild(panel.explicitInput.id); const childEmbeddable = embeddable.getChild(panel.explicitInput.id);
id++; id++;
return childEmbeddable ? ( return childEmbeddable ? (
@ -195,7 +195,7 @@ export class SearchableListContainerComponentInner extends Component<Props, Stat
disabled={!childEmbeddable} disabled={!childEmbeddable}
id={childEmbeddable ? childEmbeddable.id : ''} id={childEmbeddable ? childEmbeddable.id : ''}
checked={this.state.checked[childEmbeddable.id]} checked={this.state.checked[childEmbeddable.id]}
onChange={e => this.toggleCheck(e.target.checked, childEmbeddable.id)} onChange={(e) => this.toggleCheck(e.target.checked, childEmbeddable.id)}
/> />
</EuiFlexItem> </EuiFlexItem>
<EuiFlexItem> <EuiFlexItem>

View file

@ -34,7 +34,7 @@ function TaskInput({ onSave }: { onSave: (task: string) => void }) {
data-test-subj="taskInputField" data-test-subj="taskInputField"
value={task} value={task}
placeholder="Enter task here" placeholder="Enter task here"
onChange={e => setTask(e.target.value)} onChange={(e) => setTask(e.target.value)}
/> />
<EuiButton data-test-subj="createTodoEmbeddable" onClick={() => onSave(task)}> <EuiButton data-test-subj="createTodoEmbeddable" onClick={() => onSave(task)}>
Save Save
@ -69,7 +69,7 @@ export class TodoEmbeddableFactory
*/ */
public getExplicitInput = async () => { public getExplicitInput = async () => {
const { openModal } = await this.getStartServices(); const { openModal } = await this.getStartServices();
return new Promise<{ task: string }>(resolve => { return new Promise<{ task: string }>((resolve) => {
const onSave = (task: string) => resolve({ task }); const onSave = (task: string) => resolve({ task });
const overlay = openModal( const overlay = openModal(
toMountPoint( toMountPoint(

View file

@ -51,7 +51,7 @@ type NavProps = RouteComponentProps & {
}; };
const Nav = withRouter(({ history, navigateToApp, pages }: NavProps) => { const Nav = withRouter(({ history, navigateToApp, pages }: NavProps) => {
const navItems = pages.map(page => ({ const navItems = pages.map((page) => ({
id: page.id, id: page.id,
name: page.title, name: page.title,
onClick: () => history.push(`/${page.id}`), onClick: () => history.push(`/${page.id}`),
@ -122,7 +122,7 @@ const EmbeddableExplorerApp = ({
]; ];
const routes = pages.map((page, i) => ( const routes = pages.map((page, i) => (
<Route key={i} path={`/${page.id}`} render={props => page.component} /> <Route key={i} path={`/${page.id}`} render={(props) => page.component} />
)); ));
return ( return (

View file

@ -84,7 +84,7 @@ export function EmbeddablePanelExample({ embeddableServices }: Props) {
const factory = embeddableServices.getEmbeddableFactory(SEARCHABLE_LIST_CONTAINER); const factory = embeddableServices.getEmbeddableFactory(SEARCHABLE_LIST_CONTAINER);
const promise = factory?.create(searchableInput); const promise = factory?.create(searchableInput);
if (promise) { if (promise) {
promise.then(e => { promise.then((e) => {
if (ref.current) { if (ref.current) {
setEmbeddable(e); setEmbeddable(e);
} }

View file

@ -82,7 +82,7 @@ export class TodoEmbeddableExample extends React.Component<Props, State> {
icon: 'broom', icon: 'broom',
title: 'Trash', title: 'Trash',
}) })
.then(embeddable => { .then((embeddable) => {
this.embeddable = embeddable; this.embeddable = embeddable;
this.setState({ loading: false }); this.setState({ loading: false });
}); });
@ -135,7 +135,7 @@ export class TodoEmbeddableExample extends React.Component<Props, State> {
<EuiFormRow label="Title"> <EuiFormRow label="Title">
<EuiFieldText <EuiFieldText
data-test-subj="titleTodo" data-test-subj="titleTodo"
onChange={ev => this.setState({ title: ev.target.value })} onChange={(ev) => this.setState({ title: ev.target.value })}
/> />
</EuiFormRow> </EuiFormRow>
</EuiFlexItem> </EuiFlexItem>
@ -143,7 +143,7 @@ export class TodoEmbeddableExample extends React.Component<Props, State> {
<EuiFormRow label="Icon"> <EuiFormRow label="Icon">
<EuiFieldText <EuiFieldText
data-test-subj="iconTodo" data-test-subj="iconTodo"
onChange={ev => this.setState({ icon: ev.target.value })} onChange={(ev) => this.setState({ icon: ev.target.value })}
/> />
</EuiFormRow> </EuiFormRow>
</EuiFlexItem> </EuiFlexItem>
@ -153,7 +153,7 @@ export class TodoEmbeddableExample extends React.Component<Props, State> {
fullWidth fullWidth
resize="horizontal" resize="horizontal"
data-test-subj="taskTodo" data-test-subj="taskTodo"
onChange={ev => this.setState({ task: ev.target.value })} onChange={(ev) => this.setState({ task: ev.target.value })}
/> />
</EuiFormRow> </EuiFormRow>
</EuiFlexItem> </EuiFlexItem>

View file

@ -51,7 +51,7 @@ type NavProps = RouteComponentProps & {
}; };
const Nav = withRouter(({ history, navigateToApp, pages }: NavProps) => { const Nav = withRouter(({ history, navigateToApp, pages }: NavProps) => {
const navItems = pages.map(page => ({ const navItems = pages.map((page) => ({
id: page.id, id: page.id,
name: page.title, name: page.title,
onClick: () => history.push(`/${page.id}`), onClick: () => history.push(`/${page.id}`),
@ -103,7 +103,7 @@ const SearchApp = ({ basename, data, application }: SearchBarComponentParams) =>
]; ];
const routes = pages.map((page, i) => ( const routes = pages.map((page, i) => (
<Route key={i} path={`/${page.id}`} render={props => buildPage(page)} /> <Route key={i} path={`/${page.id}`} render={(props) => buildPage(page)} />
)); ));
return ( return (

View file

@ -73,7 +73,7 @@ export class AsyncDemoStrategy extends React.Component<Props, State> {
<EuiFormRow label="How many Fibonacci numbers to generate?"> <EuiFormRow label="How many Fibonacci numbers to generate?">
<EuiFieldNumber <EuiFieldNumber
value={this.state.fibonacciNumbers} value={this.state.fibonacciNumbers}
onChange={e => this.setState({ fibonacciNumbers: parseFloat(e.target.value) })} onChange={(e) => this.setState({ fibonacciNumbers: parseFloat(e.target.value) })}
/> />
</EuiFormRow> </EuiFormRow>
</EuiFlexItem> </EuiFlexItem>

View file

@ -81,7 +81,7 @@ export class DemoStrategy extends React.Component<Props, State> {
<EuiFormRow label="What is your name?"> <EuiFormRow label="What is your name?">
<EuiFieldText <EuiFieldText
value={this.state.name} value={this.state.name}
onChange={e => this.setState({ name: e.target.value })} onChange={(e) => this.setState({ name: e.target.value })}
/> />
</EuiFormRow> </EuiFormRow>
</EuiFlexItem> </EuiFlexItem>
@ -90,7 +90,7 @@ export class DemoStrategy extends React.Component<Props, State> {
<EuiFormRow label="How are you feeling today?"> <EuiFormRow label="How are you feeling today?">
<EuiFieldText <EuiFieldText
value={this.state.mood} value={this.state.mood}
onChange={e => this.setState({ mood: e.target.value })} onChange={(e) => this.setState({ mood: e.target.value })}
/> />
</EuiFormRow> </EuiFormRow>
</EuiFlexItem> </EuiFlexItem>

View file

@ -61,10 +61,10 @@ export class DoSearch extends React.Component<Props, State> {
this.abortController = new AbortController(); this.abortController = new AbortController();
this.props.search(this.abortController.signal).subscribe( this.props.search(this.abortController.signal).subscribe(
response => { (response) => {
this.setState({ response, error: undefined }); this.setState({ response, error: undefined });
}, },
error => { (error) => {
this.setState({ error, searching: false, response: undefined }); this.setState({ error, searching: false, response: undefined });
}, },
() => { () => {

View file

@ -92,7 +92,7 @@ export class EsSearchTest extends React.Component<Props, State> {
<EuiFormRow label="Index pattern"> <EuiFormRow label="Index pattern">
<EuiFieldText <EuiFieldText
value={this.state.index} value={this.state.index}
onChange={e => this.setState({ index: e.target.value, changes: true })} onChange={(e) => this.setState({ index: e.target.value, changes: true })}
/> />
</EuiFormRow> </EuiFormRow>
</EuiFlexItem> </EuiFlexItem>
@ -101,7 +101,7 @@ export class EsSearchTest extends React.Component<Props, State> {
<EuiFormRow label="Query string query"> <EuiFormRow label="Query string query">
<EuiFieldText <EuiFieldText
value={this.state.query} value={this.state.query}
onChange={e => this.setState({ query: e.target.value, changes: true })} onChange={(e) => this.setState({ query: e.target.value, changes: true })}
/> />
</EuiFormRow> </EuiFormRow>
</EuiFlexItem> </EuiFlexItem>

View file

@ -59,7 +59,7 @@ export class GuideSection extends React.Component<Props, State> {
} }
if (props.codeSections) { if (props.codeSections) {
props.codeSections.forEach(section => { props.codeSections.forEach((section) => {
this.tabs.push({ this.tabs.push({
name: section.title, name: section.title,
displayName: section.title, displayName: section.title,
@ -79,7 +79,7 @@ export class GuideSection extends React.Component<Props, State> {
}; };
renderTabs() { renderTabs() {
return this.tabs.map(tab => ( return this.tabs.map((tab) => (
<EuiTab <EuiTab
onClick={() => this.onSelectedTabChanged(tab.name)} onClick={() => this.onSelectedTabChanged(tab.name)}
isSelected={tab.name === this.state.selectedTab} isSelected={tab.name === this.state.selectedTab}
@ -98,7 +98,7 @@ export class GuideSection extends React.Component<Props, State> {
if (!this.props.codeSections) { if (!this.props.codeSections) {
return undefined; 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) { if (!section) {
throw new Error('No section named ' + this.state.selectedTab); throw new Error('No section named ' + this.state.selectedTab);

View file

@ -61,7 +61,7 @@ const defaultGlobalState: GlobalState = { text: '' };
const globalStateContainer = createStateContainer<GlobalState, GlobalStateAction>( const globalStateContainer = createStateContainer<GlobalState, GlobalStateAction>(
defaultGlobalState, defaultGlobalState,
{ {
setText: state => text => ({ ...state, text }), setText: (state) => (text) => ({ ...state, text }),
} }
); );
@ -81,7 +81,7 @@ const TodoApp: React.FC<TodoAppProps> = ({ filter }) => {
const { text } = GlobalStateHelpers.useState(); const { text } = GlobalStateHelpers.useState();
const { edit: editTodo, delete: deleteTodo, add: addTodo } = useTransitions(); const { edit: editTodo, delete: deleteTodo, add: addTodo } = useTransitions();
const todos = useState().todos; const todos = useState().todos;
const filteredTodos = todos.filter(todo => { const filteredTodos = todos.filter((todo) => {
if (!filter) return true; if (!filter) return true;
if (filter === 'completed') return todo.completed; if (filter === 'completed') return todo.completed;
if (filter === 'not-completed') return !todo.completed; if (filter === 'not-completed') return !todo.completed;
@ -111,13 +111,13 @@ const TodoApp: React.FC<TodoAppProps> = ({ filter }) => {
</Link> </Link>
</div> </div>
<ul> <ul>
{filteredTodos.map(todo => ( {filteredTodos.map((todo) => (
<li key={todo.id} style={{ display: 'flex', alignItems: 'center', margin: '16px 0px' }}> <li key={todo.id} style={{ display: 'flex', alignItems: 'center', margin: '16px 0px' }}>
<EuiCheckbox <EuiCheckbox
id={todo.id + ''} id={todo.id + ''}
key={todo.id} key={todo.id}
checked={todo.completed} checked={todo.completed}
onChange={e => { onChange={(e) => {
editTodo({ editTodo({
...todo, ...todo,
completed: e.target.checked, completed: e.target.checked,
@ -139,7 +139,7 @@ const TodoApp: React.FC<TodoAppProps> = ({ filter }) => {
))} ))}
</ul> </ul>
<form <form
onSubmit={e => { onSubmit={(e) => {
const inputRef = (e.target as HTMLFormElement).elements.namedItem( const inputRef = (e.target as HTMLFormElement).elements.namedItem(
'newTodo' 'newTodo'
) as HTMLInputElement; ) as HTMLInputElement;
@ -147,7 +147,7 @@ const TodoApp: React.FC<TodoAppProps> = ({ filter }) => {
addTodo({ addTodo({
text: inputRef.value, text: inputRef.value,
completed: false, 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 = ''; inputRef.value = '';
e.preventDefault(); e.preventDefault();
@ -157,7 +157,7 @@ const TodoApp: React.FC<TodoAppProps> = ({ filter }) => {
</form> </form>
<div style={{ margin: '16px 0px' }}> <div style={{ margin: '16px 0px' }}>
<label htmlFor="globalInput">Global state piece: </label> <label htmlFor="globalInput">Global state piece: </label>
<input name="globalInput" value={text} onChange={e => setText(e.target.value)} /> <input name="globalInput" value={text} onChange={(e) => setText(e.target.value)} />
</div> </div>
</> </>
); );
@ -173,7 +173,7 @@ export const TodoAppPage: React.FC<{
appTitle: string; appTitle: string;
appBasePath: string; appBasePath: string;
isInitialRoute: () => boolean; isInitialRoute: () => boolean;
}> = props => { }> = (props) => {
const initialAppUrl = React.useRef(window.location.href); const initialAppUrl = React.useRef(window.location.href);
const [useHashedUrl, setUseHashedUrl] = React.useState(false); 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 * Replicates what src/legacy/ui/public/chrome/api/nav.ts did
* Persists the url in sessionStorage and tries to restore it on "componentDidMount" * 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: // shouldRestoreUrl:
// App decides if it should restore url or not // App decides if it should restore url or not
// In this specific case, restore only if navigated to initial route // In this specific case, restore only if navigated to initial route

View file

@ -135,7 +135,7 @@ const App = ({
<EuiFieldText <EuiFieldText
placeholder="Additional application state: My name is..." placeholder="Additional application state: My name is..."
value={appState.name} value={appState.name}
onChange={e => appStateContainer.set({ ...appState, name: e.target.value })} onChange={(e) => appStateContainer.set({ ...appState, name: e.target.value })}
aria-label="My name" aria-label="My name"
/> />
</EuiPageContent> </EuiPageContent>
@ -217,7 +217,7 @@ function useAppStateSyncing<AppState extends QueryState>(
stateContainer: { stateContainer: {
...appStateContainer, ...appStateContainer,
// stateSync utils requires explicit handling of default state ("null") // stateSync utils requires explicit handling of default state ("null")
set: state => state && appStateContainer.set(state), set: (state) => state && appStateContainer.set(state),
}, },
}); });

View file

@ -47,14 +47,14 @@ export interface PhoneContext {
export const makePhoneCallAction = createAction<typeof ACTION_CALL_PHONE_NUMBER>({ export const makePhoneCallAction = createAction<typeof ACTION_CALL_PHONE_NUMBER>({
type: ACTION_CALL_PHONE_NUMBER, type: ACTION_CALL_PHONE_NUMBER,
getDisplayName: () => '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<typeof ACTION_TRAVEL_GUIDE>({ export const lookUpWeatherAction = createAction<typeof ACTION_TRAVEL_GUIDE>({
type: ACTION_TRAVEL_GUIDE, type: ACTION_TRAVEL_GUIDE,
getIconType: () => 'popout', getIconType: () => 'popout',
getDisplayName: () => 'View travel guide', getDisplayName: () => 'View travel guide',
execute: async context => { execute: async (context) => {
window.open(`https://www.worldtravelguide.net/?s=${context.country}`, '_blank'); window.open(`https://www.worldtravelguide.net/?s=${context.country}`, '_blank');
}, },
}); });
@ -67,7 +67,7 @@ export const viewInMapsAction = createAction<typeof ACTION_VIEW_IN_MAPS>({
type: ACTION_VIEW_IN_MAPS, type: ACTION_VIEW_IN_MAPS,
getIconType: () => 'popout', getIconType: () => 'popout',
getDisplayName: () => 'View in maps', getDisplayName: () => 'View in maps',
execute: async context => { execute: async (context) => {
window.open(`https://www.google.com/maps/place/${context.country}`, '_blank'); window.open(`https://www.google.com/maps/place/${context.country}`, '_blank');
}, },
}); });
@ -90,7 +90,7 @@ function EditUserModal({
const [name, setName] = useState(user.name); const [name, setName] = useState(user.name);
return ( return (
<EuiModalBody> <EuiModalBody>
<EuiFieldText prepend="Name" value={name} onChange={e => setName(e.target.value)} /> <EuiFieldText prepend="Name" value={name} onChange={(e) => setName(e.target.value)} />
<EuiButton <EuiButton
onClick={() => { onClick={() => {
update({ ...user, name }); update({ ...user, name });

View file

@ -72,7 +72,7 @@ const ActionsExplorer = ({ uiActionsApi, openModal }: Props) => {
from. Using the UI Action and Trigger API makes your plugin extensible by other 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! plugins. Any actions attached to the `HELLO_WORLD_TRIGGER_ID` will show up here!
</p> </p>
<EuiFieldText prepend="Name" value={name} onChange={e => setName(e.target.value)} /> <EuiFieldText prepend="Name" value={name} onChange={(e) => setName(e.target.value)} />
<EuiButton <EuiButton
data-test-subj="addDynamicAction" data-test-subj="addDynamicAction"
onClick={() => { onClick={() => {

View file

@ -105,7 +105,7 @@ export function TriggerContextExample({ uiActionsApi }: Props) {
]; ];
const updateUser = (newUser: User, oldName: string) => { 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]; const newRows = [...rows];
newRows.splice(index, 1, createRowData(newUser, uiActionsApi, updateUser)); newRows.splice(index, 1, createRowData(newUser, uiActionsApi, updateUser));
setRows(newRows); setRows(newRows);

View file

@ -67,7 +67,7 @@ export const Routes: React.FC<{}> = () => {
export const LinksExample: React.FC<{ export const LinksExample: React.FC<{
appBasePath: string; appBasePath: string;
}> = props => { }> = (props) => {
const history = React.useMemo( const history = React.useMemo(
() => () =>
createBrowserHistory({ createBrowserHistory({

View file

@ -38,7 +38,7 @@ export const createHelloPageLinkGenerator = (
getStartServices: () => Promise<{ appBasePath: string }> getStartServices: () => Promise<{ appBasePath: string }>
): UrlGeneratorsDefinition<typeof HELLO_URL_GENERATOR> => ({ ): UrlGeneratorsDefinition<typeof HELLO_URL_GENERATOR> => ({
id: HELLO_URL_GENERATOR, id: HELLO_URL_GENERATOR,
createUrl: async state => { createUrl: async (state) => {
const startServices = await getStartServices(); const startServices = await getStartServices();
const appBasePath = startServices.appBasePath; const appBasePath = startServices.appBasePath;
const parsedUrl = url.parse(window.location.href); const parsedUrl = url.parse(window.location.href);
@ -72,7 +72,7 @@ export type LegacyHelloLinkGeneratorState = UrlGeneratorState<
export const helloPageLinkGeneratorV1: UrlGeneratorsDefinition<typeof HELLO_URL_GENERATOR_V1> = { export const helloPageLinkGeneratorV1: UrlGeneratorsDefinition<typeof HELLO_URL_GENERATOR_V1> = {
id: HELLO_URL_GENERATOR_V1, id: HELLO_URL_GENERATOR_V1,
isDeprecated: true, isDeprecated: true,
migrate: async state => { migrate: async (state) => {
return { id: HELLO_URL_GENERATOR, state: { firstName: state.name, lastName: '' } }; return { id: HELLO_URL_GENERATOR, state: { firstName: state.name, lastName: '' } };
}, },
}; };

View file

@ -81,7 +81,7 @@ const ActionsExplorer = ({ getLinkGenerator }: Props) => {
const updateLinks = async () => { const updateLinks = async () => {
const updatedLinks = await Promise.all( const updatedLinks = await Promise.all(
persistedLinks.map(async savedLink => { persistedLinks.map(async (savedLink) => {
const generator = getLinkGenerator(savedLink.id); const generator = getLinkGenerator(savedLink.id);
const link = await generator.createUrl(savedLink.state); const link = await generator.createUrl(savedLink.state);
return { return {
@ -109,11 +109,11 @@ const ActionsExplorer = ({ getLinkGenerator }: Props) => {
</EuiText> </EuiText>
<EuiFieldText <EuiFieldText
prepend="First name" prepend="First name"
onChange={e => { onChange={(e) => {
setFirstName(e.target.value); setFirstName(e.target.value);
}} }}
/> />
<EuiFieldText prepend="Last name" onChange={e => setLastName(e.target.value)} /> <EuiFieldText prepend="Last name" onChange={(e) => setLastName(e.target.value)} />
<EuiButton <EuiButton
onClick={() => onClick={() =>
setPersistedLinks([ setPersistedLinks([
@ -142,7 +142,7 @@ const ActionsExplorer = ({ getLinkGenerator }: Props) => {
{buildingLinks ? ( {buildingLinks ? (
<div>loading...</div> <div>loading...</div>
) : ( ) : (
migratedLinks.map(link => ( migratedLinks.map((link) => (
<React.Fragment> <React.Fragment>
<EuiLink <EuiLink
color={link.isDeprecated ? 'danger' : 'primary'} color={link.isDeprecated ? 'danger' : 'primary'}

View file

@ -138,8 +138,8 @@ describe('dateMath', function() {
clock.restore(); clock.restore();
}); });
[5, 12, 247].forEach(len => { [5, 12, 247].forEach((len) => {
spans.forEach(span => { spans.forEach((span) => {
const nowEx = `now-${len}${span}`; const nowEx = `now-${len}${span}`;
const thenEx = `${anchor}||-${len}${span}`; const thenEx = `${anchor}||-${len}${span}`;
@ -175,8 +175,8 @@ describe('dateMath', function() {
clock.restore(); clock.restore();
}); });
[5, 12, 247].forEach(len => { [5, 12, 247].forEach((len) => {
spans.forEach(span => { spans.forEach((span) => {
const nowEx = `now+${len}${span}`; const nowEx = `now+${len}${span}`;
const thenEx = `${anchor}||+${len}${span}`; const thenEx = `${anchor}||+${len}${span}`;
@ -213,7 +213,7 @@ describe('dateMath', function() {
clock.restore(); clock.restore();
}); });
spans.forEach(span => { spans.forEach((span) => {
it(`should round now to the beginning of the ${span}`, function () { it(`should round now to the beginning of the ${span}`, function () {
expect(dateMath.parse('now/' + span).format(format)).to.eql( expect(dateMath.parse('now/' + span).format(format)).to.eql(
now.startOf(span).format(format) now.startOf(span).format(format)
@ -261,32 +261,17 @@ describe('dateMath', function() {
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); const val = dateMath.parse('now-17s/s').format(format);
expect(val).to.eql( expect(val).to.eql(now.startOf('s').subtract(17, 's').format(format));
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); const val = dateMath.parse('now+555ms/ms').format(format);
expect(val).to.eql( expect(val).to.eql(now.add(555, 'ms').startOf('ms').format(format));
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); const val = dateMath.parse('now-555ms/s').format(format);
expect(val).to.eql( expect(val).to.eql(now.subtract(555, 'ms').startOf('s').format(format));
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 () {

View file

@ -34,9 +34,9 @@ const units = Object.keys(unitsMap).sort((a, b) => unitsMap[b].weight - unitsMap
const unitsDesc = [...units]; const unitsDesc = [...units];
const unitsAsc = [...units].reverse(); 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. * This is a simplified version of elasticsearch's date parser.

View file

@ -31,7 +31,7 @@ const padRight = (width, str) =>
run( run(
async ({ log, flags }) => { async ({ log, flags }) => {
await withProcRunner(log, async proc => { await withProcRunner(log, async (proc) => {
log.info('Deleting old output'); log.info('Deleting old output');
await del(BUILD_DIR); await del(BUILD_DIR);
@ -43,7 +43,7 @@ run(
log.info(`Starting babel and typescript${flags.watch ? ' in watch mode' : ''}`); log.info(`Starting babel and typescript${flags.watch ? ' in watch mode' : ''}`);
await Promise.all([ await Promise.all([
...['web', 'node'].map(subTask => ...['web', 'node'].map((subTask) =>
proc.run(padRight(10, `babel:${subTask}`), { proc.run(padRight(10, `babel:${subTask}`), {
cmd: 'babel', cmd: 'babel',
args: [ args: [

View file

@ -86,7 +86,7 @@ export class ReportManager {
}; };
} }
assignReports(newMetrics: Metric | Metric[]) { 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 }; return { report: this.report };
} }
static createMetricKey(metric: Metric): string { static createMetricKey(metric: Metric): string {

View file

@ -115,7 +115,7 @@ export class Reporter {
eventNames: string | string[], eventNames: string | string[],
count?: number count?: number
) => { ) => {
const metrics = wrapArray(eventNames).map(eventName => { const metrics = wrapArray(eventNames).map((eventName) => {
this.log(`${type} Metric -> (${appName}:${eventName}):`); this.log(`${type} Metric -> (${appName}:${eventName}):`);
const report = createUiStatsMetric({ type, appName, eventName, count }); const report = createUiStatsMetric({ type, appName, eventName, count });
this.log(report); this.log(report);

View file

@ -79,7 +79,7 @@ export async function parseEntries(cwd, entries, strategy, results, wasParsed =
const sanitizedCwd = cwd || process.cwd(); const sanitizedCwd = cwd || process.cwd();
// Test each entry against canRequire function // Test each entry against canRequire function
const entriesQueue = entries.map(entry => canRequire(entry)); const entriesQueue = entries.map((entry) => canRequire(entry));
while (entriesQueue.length) { while (entriesQueue.length) {
// Get the first element in the queue as // Get the first element in the queue as

View file

@ -59,7 +59,7 @@ export async function dependenciesParseStrategy(
// Get dependencies from a single file and filter // Get dependencies from a single file and filter
// out node native modules from the result // out node native modules from the result
const dependencies = (await parseSingleFile(mainEntry, dependenciesVisitorsGenerator)).filter( 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 // Return the list of all the new entries found into

View file

@ -84,7 +84,7 @@ describe('Code Parser Strategies', () => {
cb(null, `require('./relative_dep')`); cb(null, `require('./relative_dep')`);
}); });
canRequire.mockImplementation(entry => { canRequire.mockImplementation((entry) => {
if (entry === `${mockCwd}dep1/relative_dep`) { if (entry === `${mockCwd}dep1/relative_dep`) {
return `${entry}/index.js`; return `${entry}/index.js`;
} }

View file

@ -21,7 +21,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) {
// raw values on require + require.resolve // raw values on require + require.resolve
CallExpression: ({ node }) => { CallExpression: ({ node }) => {
// AST check for require expressions // AST check for require expressions
const isRequire = node => { const isRequire = (node) => {
return matches({ return matches({
callee: { callee: {
type: 'Identifier', type: 'Identifier',
@ -31,7 +31,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) {
}; };
// AST check for require.resolve expressions // AST check for require.resolve expressions
const isRequireResolve = node => { const isRequireResolve = (node) => {
return matches({ return matches({
callee: { callee: {
type: 'MemberExpression', type: 'MemberExpression',
@ -66,7 +66,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) {
// raw values on import // raw values on import
ImportDeclaration: ({ node }) => { ImportDeclaration: ({ node }) => {
// AST check for supported import expressions // AST check for supported import expressions
const isImport = node => { const isImport = (node) => {
return matches({ return matches({
type: 'ImportDeclaration', type: 'ImportDeclaration',
source: { source: {
@ -85,7 +85,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) {
// raw values on export from // raw values on export from
ExportNamedDeclaration: ({ node }) => { ExportNamedDeclaration: ({ node }) => {
// AST check for supported export from expressions // AST check for supported export from expressions
const isExportFrom = node => { const isExportFrom = (node) => {
return matches({ return matches({
type: 'ExportNamedDeclaration', type: 'ExportNamedDeclaration',
source: { source: {
@ -104,7 +104,7 @@ export function dependenciesVisitorsGenerator(dependenciesAcc) {
// raw values on export * from // raw values on export * from
ExportAllDeclaration: ({ node }) => { ExportAllDeclaration: ({ node }) => {
// AST check for supported export * from expressions // AST check for supported export * from expressions
const isExportAllFrom = node => { const isExportAllFrom = (node) => {
return matches({ return matches({
type: 'ExportAllDeclaration', type: 'ExportAllDeclaration',
source: { source: {

View file

@ -21,7 +21,7 @@ import * as parser from '@babel/parser';
import traverse from '@babel/traverse'; import traverse from '@babel/traverse';
import { dependenciesVisitorsGenerator } from './visitors'; import { dependenciesVisitorsGenerator } from './visitors';
const visitorsApplier = code => { const visitorsApplier = (code) => {
const result = []; const result = [];
traverse( traverse(
parser.parse(code, { parser.parse(code, {

View file

@ -26,8 +26,8 @@ import { SchemaError } from '.';
export const cleanStack = (stack: string) => export const cleanStack = (stack: string) =>
stack stack
.split('\n') .split('\n')
.filter(line => !line.includes('node_modules/') && !line.includes('internal/')) .filter((line) => !line.includes('node_modules/') && !line.includes('internal/'))
.map(line => { .map((line) => {
const parts = /.*\((.*)\).?/.exec(line) || []; const parts = /.*\((.*)\).?/.exec(line) || [];
if (parts.length === 0) { if (parts.length === 0) {

View file

@ -26,12 +26,12 @@ export class ValidationError extends SchemaError {
let message = error.message; let message = error.message;
if (error instanceof SchemaTypesError) { if (error instanceof SchemaTypesError) {
const indentLevel = level || 0; const indentLevel = level || 0;
const childErrorMessages = error.errors.map(childError => const childErrorMessages = error.errors.map((childError) =>
ValidationError.extractMessage(childError, namespace, indentLevel + 1) ValidationError.extractMessage(childError, namespace, indentLevel + 1)
); );
message = `${message}\n${childErrorMessages message = `${message}\n${childErrorMessages
.map(childErrorMessage => `${' '.repeat(indentLevel)}- ${childErrorMessage}`) .map((childErrorMessage) => `${' '.repeat(indentLevel)}- ${childErrorMessage}`)
.join('\n')}`; .join('\n')}`;
} }

View file

@ -42,9 +42,7 @@ function isMap<K, V>(o: any): o is Map<K, V> {
const anyCustomRule: Rules = { const anyCustomRule: Rules = {
name: 'custom', name: 'custom',
params: { params: {
validator: Joi.func() validator: Joi.func().maxArity(1).required(),
.maxArity(1)
.required(),
}, },
validate(params, value, state, options) { validate(params, value, state, options) {
let validationResultMessage; let validationResultMessage;

View file

@ -28,10 +28,7 @@ export type ArrayOptions<T> = TypeOptions<T[]> & {
export class ArrayType<T> extends Type<T[]> { export class ArrayType<T> extends Type<T[]> {
constructor(type: Type<T>, options: ArrayOptions<T> = {}) { constructor(type: Type<T>, options: ArrayOptions<T> = {}) {
let schema = internals let schema = internals.array().items(type.getSchema().optional()).sparse(false);
.array()
.items(type.getSchema().optional())
.sparse(false);
if (options.minSize !== undefined) { if (options.minSize !== undefined) {
schema = schema.min(options.minSize); schema = schema.min(options.minSize);

View file

@ -36,14 +36,14 @@ export class StringType extends Type<string> {
let schema = let schema =
options.hostname === true options.hostname === true
? internals.string().hostname() ? internals.string().hostname()
: internals.any().custom(value => { : internals.any().custom((value) => {
if (typeof value !== 'string') { if (typeof value !== 'string') {
return `expected value of type [string] but got [${typeDetect(value)}]`; return `expected value of type [string] but got [${typeDetect(value)}]`;
} }
}); });
if (options.minLength !== undefined) { if (options.minLength !== undefined) {
schema = schema.custom(value => { schema = schema.custom((value) => {
if (value.length < options.minLength!) { if (value.length < options.minLength!) {
return `value has length [${value.length}] but it must have a minimum length of [${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<string> {
} }
if (options.maxLength !== undefined) { if (options.maxLength !== undefined) {
schema = schema.custom(value => { schema = schema.custom((value) => {
if (value.length > options.maxLength!) { if (value.length > options.maxLength!) {
return `value has length [${value.length}] but it must have a maximum length of [${options.maxLength}].`; return `value has length [${value.length}] but it must have a maximum length of [${options.maxLength}].`;
} }

View file

@ -24,7 +24,7 @@ import { Type, TypeOptions } from './type';
export class UnionType<RTS extends Array<Type<any>>, T> extends Type<T> { export class UnionType<RTS extends Array<Type<any>>, T> extends Type<T> {
constructor(types: RTS, options?: TypeOptions<T>) { constructor(types: RTS, options?: TypeOptions<T>) {
const schema = internals.alternatives(types.map(type => type.getSchema())); const schema = internals.alternatives(types.map((type) => type.getSchema()));
super(schema, options); super(schema, options);
} }

View file

@ -145,7 +145,7 @@ export class CiStatsReporter {
`failed to reach kibana-ci-stats service [reason=${reason}], retrying in ${attempt} seconds` `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));
} }
} }
} }

View file

@ -66,7 +66,7 @@ export interface ReqOptions {
} }
const delay = (ms: number) => const delay = (ms: number) =>
new Promise(resolve => { new Promise((resolve) => {
setTimeout(resolve, ms); setTimeout(resolve, ms);
}); });

View file

@ -33,7 +33,7 @@ export function observeReadable(readable: Readable): Rx.Observable<never> {
Rx.fromEvent(readable, 'error').pipe( Rx.fromEvent(readable, 'error').pipe(
first(), first(),
mergeMap(err => Rx.throwError(err)) mergeMap((err) => Rx.throwError(err))
) )
); );
} }

View file

@ -118,7 +118,7 @@ export function startProc(name: string, options: ProcOptions, log: ToolingLog) {
// observe first error event // observe first error event
Rx.fromEvent(childProcess, 'error').pipe( Rx.fromEvent(childProcess, 'error').pipe(
take(1), take(1),
mergeMap(err => Rx.throwError(err)) mergeMap((err) => Rx.throwError(err))
) )
).pipe(share()); ).pipe(share());
@ -126,7 +126,7 @@ export function startProc(name: string, options: ProcOptions, log: ToolingLog) {
observeLines(childProcess.stdout), observeLines(childProcess.stdout),
observeLines(childProcess.stderr) observeLines(childProcess.stderr)
).pipe( ).pipe(
tap(line => log.write(` ${chalk.gray('proc')} [${chalk.gray(name)}] ${line}`)), tap((line) => log.write(` ${chalk.gray('proc')} [${chalk.gray(name)}] ${line}`)),
share() share()
); );

View file

@ -50,7 +50,7 @@ export class ProcRunner {
constructor(private log: ToolingLog) { constructor(private log: ToolingLog) {
this.signalUnsubscribe = exitHook(() => { this.signalUnsubscribe = exitHook(() => {
this.teardown().catch(error => { this.teardown().catch((error) => {
log.error(`ProcRunner teardown error: ${error.stack}`); log.error(`ProcRunner teardown error: ${error.stack}`);
}); });
}); });
@ -105,9 +105,9 @@ export class ProcRunner {
// wait for process to log matching line // wait for process to log matching line
await Rx.race( await Rx.race(
proc.lines$.pipe( proc.lines$.pipe(
filter(line => wait.test(line)), filter((line) => wait.test(line)),
first(), first(),
catchError(err => { catchError((err) => {
if (err.name !== 'EmptyError') { if (err.name !== 'EmptyError') {
throw createCliError(`[${name}] exited without matching pattern: ${wait}`); throw createCliError(`[${name}] exited without matching pattern: ${wait}`);
} else { } else {
@ -159,7 +159,7 @@ export class ProcRunner {
* @return {Promise<undefined>} * @return {Promise<undefined>}
*/ */
async waitForAllToStop() { 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( this.log.warning(
'%d processes left running, stop them with procs.stop(name):', '%d processes left running, stop them with procs.stop(name):',
this.procs.length, this.procs.length,
this.procs.map(proc => proc.name) this.procs.map((proc) => proc.name)
); );
} }
await Promise.all( await Promise.all(
this.procs.map(async proc => { this.procs.map(async (proc) => {
await proc.stop(signal === 'exit' ? 'SIGKILL' : signal); await proc.stop(signal === 'exit' ? 'SIGKILL' : signal);
}) })
); );
} }
private getProc(name: string) { private getProc(name: string) {
return this.procs.find(proc => { return this.procs.find((proc) => {
return proc.name === name; return proc.name === name;
}); });
} }
@ -209,14 +209,14 @@ export class ProcRunner {
// tie into proc outcome$, remove from _procs on compete // tie into proc outcome$, remove from _procs on compete
proc.outcome$.subscribe({ proc.outcome$.subscribe({
next: code => { next: (code) => {
const duration = moment.duration(Date.now() - startMs); const duration = moment.duration(Date.now() - startMs);
this.log.info('[%s] exited with %s after %s', name, code, duration.humanize()); this.log.info('[%s] exited with %s after %s', name, code, duration.humanize());
}, },
complete: () => { complete: () => {
remove(); remove();
}, },
error: error => { error: (error) => {
if (this.closing) { if (this.closing) {
this.log.error(error); this.log.error(error);
} }

View file

@ -22,14 +22,14 @@ import { withProcRunner } from './with_proc_runner';
import { ProcRunner } from './proc_runner'; import { ProcRunner } from './proc_runner';
it('passes proc runner to a function', async () => { it('passes proc runner to a function', async () => {
await withProcRunner(new ToolingLog(), async proc => { await withProcRunner(new ToolingLog(), async (proc) => {
expect(proc).toBeInstanceOf(ProcRunner); expect(proc).toBeInstanceOf(ProcRunner);
}); });
}); });
it('calls procRunner.teardown() if function returns synchronously', async () => { it('calls procRunner.teardown() if function returns synchronously', async () => {
let teardownSpy; let teardownSpy;
await withProcRunner(new ToolingLog(), async proc => { await withProcRunner(new ToolingLog(), async (proc) => {
teardownSpy = jest.spyOn(proc, 'teardown'); teardownSpy = jest.spyOn(proc, 'teardown');
}); });
@ -41,7 +41,7 @@ it('calls procRunner.teardown() if function throw synchronous error, and rejects
let teardownSpy; let teardownSpy;
await expect( await expect(
withProcRunner(new ToolingLog(), async proc => { withProcRunner(new ToolingLog(), async (proc) => {
teardownSpy = jest.spyOn(proc, 'teardown'); teardownSpy = jest.spyOn(proc, 'teardown');
throw error; 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 () => { it('waits for promise to resolve before tearing down proc', async () => {
let teardownSpy; let teardownSpy;
await withProcRunner(new ToolingLog(), async proc => { await withProcRunner(new ToolingLog(), async (proc) => {
await new Promise(resolve => setTimeout(resolve, 500)); await new Promise((resolve) => setTimeout(resolve, 500));
teardownSpy = jest.spyOn(proc, 'teardown'); 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; let teardownSpy;
await expect( await expect(
withProcRunner(new ToolingLog(), async proc => { withProcRunner(new ToolingLog(), async (proc) => {
await new Promise(resolve => setTimeout(resolve, 500)); await new Promise((resolve) => setTimeout(resolve, 500));
teardownSpy = jest.spyOn(proc, 'teardown'); teardownSpy = jest.spyOn(proc, 'teardown');
throw error; throw error;
}) })

View file

@ -61,7 +61,7 @@ export function combineErrors(errors: Array<Error | FailError>) {
.filter(isFailError) .filter(isFailError)
.reduce((acc, error) => Math.max(acc, error.exitCode), 1); .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) => { const message = errors.reduce((acc, error) => {
if (isFailError(error)) { if (isFailError(error)) {

View file

@ -62,7 +62,7 @@ export async function run(fn: RunFn, options: Options = {}) {
writeTo: process.stdout, writeTo: process.stdout,
}); });
process.on('unhandledRejection', error => { process.on('unhandledRejection', (error) => {
log.error('UNHANDLED PROMISE REJECTION'); log.error('UNHANDLED PROMISE REJECTION');
log.error( log.error(
error instanceof Error error instanceof Error
@ -110,7 +110,7 @@ export async function run(fn: RunFn, options: Options = {}) {
} }
try { try {
await withProcRunner(log, async procRunner => { await withProcRunner(log, async (procRunner) => {
await fn({ await fn({
log, log,
flags, flags,

View file

@ -80,7 +80,8 @@ describe('#indent()', () => {
}); });
}); });
(['verbose', 'debug', 'info', 'success', 'warning', 'error', 'write'] as const).forEach(method => { (['verbose', 'debug', 'info', 'success', 'warning', 'error', 'write'] as const).forEach(
(method) => {
describe(`#${method}()`, () => { describe(`#${method}()`, () => {
it(`sends a msg of type "${method}" to each writer with indent and arguments`, () => { it(`sends a msg of type "${method}" to each writer with indent and arguments`, () => {
const log = new ToolingLog(); const log = new ToolingLog();
@ -102,7 +103,8 @@ describe('#indent()', () => {
expect(writeA.mock.calls).toEqual(writeB.mock.calls); expect(writeA.mock.calls).toEqual(writeB.mock.calls);
}); });
}); });
}); }
);
describe('#getWritten$()', () => { describe('#getWritten$()', () => {
async function testWrittenMsgs(writers: Writer[]) { async function testWrittenMsgs(writers: Writer[]) {
@ -110,10 +112,7 @@ describe('#getWritten$()', () => {
log.setWriters(writers); log.setWriters(writers);
const done$ = new Rx.Subject(); const done$ = new Rx.Subject();
const promise = log const promise = log.getWritten$().pipe(takeUntil(done$), toArray()).toPromise();
.getWritten$()
.pipe(takeUntil(done$), toArray())
.toPromise();
log.debug('foo'); log.debug('foo');
log.info('bar'); log.info('bar');

View file

@ -26,7 +26,7 @@ export class ToolingLogCollectingWriter extends ToolingLogTextWriter {
super({ super({
level: 'verbose', level: 'verbose',
writeTo: { writeTo: {
write: msg => { write: (msg) => {
// trim trailing new line // trim trailing new line
this.messages.push(msg.slice(0, -1)); this.messages.push(msg.slice(0, -1));
}, },

View file

@ -60,7 +60,7 @@ async function retry(log, fn) {
} }
log.warning('...failure, retrying in 5 seconds:', error.message); 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'); log.info('...retrying');
return await doAttempt(attempt + 1); return await doAttempt(attempt + 1);
} }
@ -120,7 +120,7 @@ async function getArtifactSpecForSnapshot(urlVersion, license, log) {
const arch = process.arch === 'arm64' ? 'aarch64' : 'x86_64'; const arch = process.arch === 'arm64' ? 'aarch64' : 'x86_64';
const archive = manifest.archives.find( const archive = manifest.archives.find(
archive => (archive) =>
archive.version === desiredVersion && archive.version === desiredVersion &&
archive.platform === platform && archive.platform === platform &&
archive.license === desiredLicense && archive.license === desiredLicense &&

View file

@ -52,14 +52,14 @@ const createArchive = (params = {}) => {
}; };
}; };
const mockFetch = mock => const mockFetch = (mock) =>
fetch.mockReturnValue(Promise.resolve(new Response(JSON.stringify(mock)))); fetch.mockReturnValue(Promise.resolve(new Response(JSON.stringify(mock))));
const previousEnvVars = {}; const previousEnvVars = {};
const ENV_VARS_TO_RESET = ['ES_SNAPSHOT_MANIFEST', 'KBN_ES_SNAPSHOT_USE_UNVERIFIED']; const ENV_VARS_TO_RESET = ['ES_SNAPSHOT_MANIFEST', 'KBN_ES_SNAPSHOT_USE_UNVERIFIED'];
beforeAll(() => { beforeAll(() => {
ENV_VARS_TO_RESET.forEach(key => { ENV_VARS_TO_RESET.forEach((key) => {
if (key in process.env) { if (key in process.env) {
previousEnvVars[key] = process.env[key]; previousEnvVars[key] = process.env[key];
delete process.env[key]; delete process.env[key];
@ -68,7 +68,7 @@ beforeAll(() => {
}); });
afterAll(() => { afterAll(() => {
Object.keys(previousEnvVars).forEach(key => { Object.keys(previousEnvVars).forEach((key) => {
process.env[key] = previousEnvVars[key]; process.env[key] = previousEnvVars[key];
}); });
}); });

View file

@ -26,7 +26,7 @@ const { log } = require('./utils');
function help() { function help() {
const availableCommands = Object.keys(commands).map( const availableCommands = Object.keys(commands).map(
name => `${name} - ${commands[name].description}` (name) => `${name} - ${commands[name].description}`
); );
console.log(dedent` console.log(dedent`

View file

@ -40,8 +40,8 @@ const readFile = util.promisify(fs.readFile);
// listen to data on stream until map returns anything but undefined // listen to data on stream until map returns anything but undefined
const first = (stream, map) => const first = (stream, map) =>
new Promise(resolve => { new Promise((resolve) => {
const onData = data => { const onData = (data) => {
const result = map(data); const result = map(data);
if (result !== undefined) { if (result !== undefined) {
resolve(result); resolve(result);
@ -180,7 +180,7 @@ exports.Cluster = class Cluster {
await Promise.race([ await Promise.race([
// wait for native realm to be setup and es to be started // wait for native realm to be setup and es to be started
Promise.all([ Promise.all([
first(this._process.stdout, data => { first(this._process.stdout, (data) => {
if (/started/.test(data)) { if (/started/.test(data)) {
return true; return true;
} }
@ -207,7 +207,7 @@ exports.Cluster = class Cluster {
this._exec(installPath, options); this._exec(installPath, options);
// log native realm setup errors so they aren't uncaught // log native realm setup errors so they aren't uncaught
this._nativeRealmSetup.catch(error => { this._nativeRealmSetup.catch((error) => {
this._log.error(error); this._log.error(error);
this.stop(); this.stop();
}); });
@ -287,7 +287,7 @@ exports.Cluster = class Cluster {
}); });
// parse log output to find http port // 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]+)/); const match = data.toString('utf8').match(/HttpServer.+publish_address {[0-9.]+:([0-9]+)/);
if (match) { if (match) {
@ -296,7 +296,7 @@ exports.Cluster = class Cluster {
}); });
// once the http port is available setup the native realm // 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 caCert = await this._caCertPromise;
const nativeRealm = new NativeRealm({ const nativeRealm = new NativeRealm({
port, port,
@ -309,19 +309,19 @@ exports.Cluster = class Cluster {
}); });
// parse and forward es stdout to the log // 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()); const lines = parseEsLog(data.toString());
lines.forEach(line => { lines.forEach((line) => {
this._log.info(line.formattedMessage); this._log.info(line.formattedMessage);
}); });
}); });
// forward es stderr to the log // 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 // observe the exit code of the process and reflect in _outcome promies
const exitCode = new Promise(resolve => this._process.once('exit', resolve)); const exitCode = new Promise((resolve) => this._process.once('exit', resolve));
this._outcome = exitCode.then(code => { this._outcome = exitCode.then((code) => {
if (this._stopCalled) { if (this._stopCalled) {
return; return;
} }

View file

@ -99,15 +99,11 @@ async function sourceInfo(cwd, license, log = defaultLog) {
etag.update(sha); etag.update(sha);
// for changed files, use last modified times in hash calculation // 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()); etag.update(fs.statSync(path.join(cwd, file.path)).mtime.toString());
}); });
const cwdHash = crypto const cwdHash = crypto.createHash('md5').update(cwd).digest('hex').substr(0, 8);
.createHash('md5')
.update(cwd)
.digest('hex')
.substr(0, 8);
const basename = `${branch}-${task}-${cwdHash}`; const basename = `${branch}-${task}-${cwdHash}`;
const filename = `${basename}.${ext}`; const filename = `${basename}.${ext}`;

View file

@ -37,7 +37,7 @@ jest.mock('../utils/extract_config_files', () => ({
const log = new ToolingLog(); const log = new ToolingLog();
function sleep(ms) { function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms)); return new Promise((resolve) => setTimeout(resolve, ms));
} }
async function ensureNoResolve(promise) { async function ensureNoResolve(promise) {
@ -77,7 +77,7 @@ function mockEsBin({ exitCode, start }) {
beforeEach(() => { beforeEach(() => {
jest.resetAllMocks(); jest.resetAllMocks();
extractConfigFiles.mockImplementation(config => config); extractConfigFiles.mockImplementation((config) => config);
}); });
describe('#installSource()', () => { describe('#installSource()', () => {
@ -85,7 +85,7 @@ describe('#installSource()', () => {
let resolveInstallSource; let resolveInstallSource;
installSource.mockImplementationOnce( installSource.mockImplementationOnce(
() => () =>
new Promise(resolve => { new Promise((resolve) => {
resolveInstallSource = () => { resolveInstallSource = () => {
resolve({ installPath: 'foo' }); resolve({ installPath: 'foo' });
}; };
@ -124,7 +124,7 @@ describe('#installSnapshot()', () => {
let resolveInstallSnapshot; let resolveInstallSnapshot;
installSnapshot.mockImplementationOnce( installSnapshot.mockImplementationOnce(
() => () =>
new Promise(resolve => { new Promise((resolve) => {
resolveInstallSnapshot = () => { resolveInstallSnapshot = () => {
resolve({ installPath: 'foo' }); resolve({ installPath: 'foo' });
}; };
@ -163,7 +163,7 @@ describe('#installArchive(path)', () => {
let resolveInstallArchive; let resolveInstallArchive;
installArchive.mockImplementationOnce( installArchive.mockImplementationOnce(
() => () =>
new Promise(resolve => { new Promise((resolve) => {
resolveInstallArchive = () => { resolveInstallArchive = () => {
resolve({ installPath: 'foo' }); resolve({ installPath: 'foo' });
}; };

View file

@ -25,7 +25,7 @@ const SECURE_SETTINGS_LIST = [
]; ];
function isSecureSetting(settingName: string) { function isSecureSetting(settingName: string) {
return SECURE_SETTINGS_LIST.some(secureSettingNameRegex => return SECURE_SETTINGS_LIST.some((secureSettingNameRegex) =>
secureSettingNameRegex.test(settingName) secureSettingNameRegex.test(settingName)
); );
} }

View file

@ -25,7 +25,7 @@ const { createCliError } = require('../errors');
const { findMostRecentlyChanged } = require('../utils'); const { findMostRecentlyChanged } = require('../utils');
const { GRADLE_BIN } = require('../paths'); 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 * 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 stdout = readline.createInterface({ input: build.stdout });
const stderr = readline.createInterface({ input: build.stderr }); const stderr = readline.createInterface({ input: build.stderr });
stdout.on('line', line => log.debug(line)); stdout.on('line', (line) => log.debug(line));
stderr.on('line', line => log.error(line)); stderr.on('line', (line) => log.error(line));
const [exitCode] = await Promise.all([ const [exitCode] = await Promise.all([
Promise.race([ Promise.race([
onceEvent(build, 'exit'), onceEvent(build, 'exit'),
onceEvent(build, 'error').then(error => { onceEvent(build, 'error').then((error) => {
throw createCliError(`Error spawning gradle: ${error.message}`); throw createCliError(`Error spawning gradle: ${error.message}`);
}), }),
]), ]),

View file

@ -50,15 +50,12 @@ function decompressZip(input, output) {
resolve(); resolve();
}); });
zipfile.on('error', err => { zipfile.on('error', (err) => {
reject(err); reject(err);
}); });
zipfile.on('entry', entry => { zipfile.on('entry', (entry) => {
const zipPath = entry.fileName const zipPath = entry.fileName.split(/\/|\\/).slice(1).join(path.sep);
.split(/\/|\\/)
.slice(1)
.join(path.sep);
const fileName = path.resolve(output, zipPath); const fileName = path.resolve(output, zipPath);
if (/\/$/.test(entry.fileName)) { if (/\/$/.test(entry.fileName)) {

View file

@ -32,7 +32,7 @@ exports.extractConfigFiles = function extractConfigFiles(config, dest, options =
const originalConfig = typeof config === 'string' ? [config] : config; const originalConfig = typeof config === 'string' ? [config] : config;
const localConfig = []; const localConfig = [];
originalConfig.forEach(prop => { originalConfig.forEach((prop) => {
const [key, value] = prop.split('='); const [key, value] = prop.split('=');
if (isFile(value)) { if (isFile(value)) {

View file

@ -32,7 +32,7 @@ exports.findMostRecentlyChanged = function findMostRecentlyChanged(pattern) {
throw new TypeError(`Pattern must be absolute, got ${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 return glob
.sync(pattern) .sync(pattern)

View file

@ -18,7 +18,7 @@
*/ */
jest.mock('fs', () => ({ jest.mock('fs', () => ({
statSync: jest.fn().mockImplementation(path => { statSync: jest.fn().mockImplementation((path) => {
if (path.includes('oldest')) { if (path.includes('oldest')) {
return { return {
ctime: new Date(2018, 2, 1), ctime: new Date(2018, 2, 1),

View file

@ -77,7 +77,7 @@ exports.NativeRealm = class NativeRealm {
const reservedUsers = await this.getReservedUsers(); const reservedUsers = await this.getReservedUsers();
await Promise.all( await Promise.all(
reservedUsers.map(async user => { reservedUsers.map(async (user) => {
await this.setPassword(user, options[`password.${user}`]); await this.setPassword(user, options[`password.${user}`]);
}) })
); );
@ -87,7 +87,7 @@ exports.NativeRealm = class NativeRealm {
return await this._autoRetry(async () => { return await this._autoRetry(async () => {
const resp = await this._client.security.getUser(); const resp = await this._client.security.getUser();
const usernames = Object.keys(resp.body).filter( const usernames = Object.keys(resp.body).filter(
user => resp.body[user].metadata._reserved === true (user) => resp.body[user].metadata._reserved === true
); );
if (!usernames?.length) { if (!usernames?.length) {
@ -125,7 +125,7 @@ exports.NativeRealm = class NativeRealm {
const sec = 1.5 * attempt; const sec = 1.5 * attempt;
this._log.warning(`assuming ES isn't initialized completely, trying again in ${sec} seconds`); 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); return await this._autoRetry(fn, attempt + 1);
} }
} }

View file

@ -22,7 +22,7 @@ const { dirname, resolve } = require('path');
const glob = require('glob-all'); const glob = require('glob-all');
exports.getPlugins = function (config, kibanaPath, projectRoot) { exports.getPlugins = function (config, kibanaPath, projectRoot) {
const resolveToRoot = path => resolve(projectRoot, path); const resolveToRoot = (path) => resolve(projectRoot, path);
const pluginDirs = [ const pluginDirs = [
...(config.pluginDirs || []).map(resolveToRoot), ...(config.pluginDirs || []).map(resolveToRoot),
@ -39,11 +39,11 @@ exports.getPlugins = function(config, kibanaPath, projectRoot) {
]; ];
const globPatterns = [ const globPatterns = [
...pluginDirs.map(dir => resolve(dir, '*/package.json')), ...pluginDirs.map((dir) => resolve(dir, '*/package.json')),
...pluginPaths.map(path => resolve(path, '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]); const directory = resolveToRoot(config.pluginMap[name]);
return { return {
name, name,
@ -53,7 +53,7 @@ exports.getPlugins = function(config, kibanaPath, projectRoot) {
}); });
return pluginsFromMap.concat( return pluginsFromMap.concat(
glob.sync(globPatterns).map(pkgJsonPath => { glob.sync(globPatterns).map((pkgJsonPath) => {
const path = dirname(pkgJsonPath); const path = dirname(pkgJsonPath);
const pkg = require(pkgJsonPath); // eslint-disable-line import/no-dynamic-require const pkg = require(pkgJsonPath); // eslint-disable-line import/no-dynamic-require
return { return {

View file

@ -39,7 +39,7 @@ exports.getWebpackConfig = function(kibanaPath, projectRoot, config) {
test_utils: fromKibana('src/test_utils/public'), 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; alias[`plugins/${plugin.name}`] = plugin.publicDirectory;
}); });

View file

@ -32,8 +32,8 @@ function readShimNames(shimDirectory) {
} }
return readdirSync(shimDirectory) return readdirSync(shimDirectory)
.filter(name => !name.startsWith('.') && !name.startsWith('_')) .filter((name) => !name.startsWith('.') && !name.startsWith('_'))
.map(name => (name.endsWith('.js') ? name.slice(0, -3) : name)); .map((name) => (name.endsWith('.js') ? name.slice(0, -3) : name));
} }
function findRelativeWebpackShims(directory) { function findRelativeWebpackShims(directory) {
@ -55,5 +55,5 @@ function findRelativeWebpackShims(directory) {
exports.isProbablyWebpackShim = function (source, file) { exports.isProbablyWebpackShim = function (source, file) {
const shims = findRelativeWebpackShims(dirname(file)); const shims = findRelativeWebpackShims(dirname(file));
return shims.some(shim => source === shim || source.startsWith(shim + '/')); return shims.some((shim) => source === shim || source.startsWith(shim + '/'));
}; };

View file

@ -39,7 +39,7 @@ module.exports = {
}, },
], ],
}, },
create: context => { create: (context) => {
return { return {
Program(program) { Program(program) {
const licenses = init(context, program, () => { const licenses = init(context, program, () => {
@ -70,8 +70,8 @@ module.exports = {
sourceCode sourceCode
.getAllComments() .getAllComments()
.filter(node => licenses.includes(normalizeWhitespace(node.value))) .filter((node) => licenses.includes(normalizeWhitespace(node.value)))
.forEach(node => { .forEach((node) => {
context.report({ context.report({
node, node,
message: 'This license header is not allowed in this file.', message: 'This license header is not allowed in this file.',

View file

@ -22,7 +22,7 @@ const KIBANA_ROOT = path.resolve(__dirname, '../../..');
function checkModuleNameNode(context, mappings, node) { function checkModuleNameNode(context, mappings, node) {
const mapping = mappings.find( 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) { if (!mapping) {
@ -105,7 +105,7 @@ module.exports = {
}, },
], ],
}, },
create: context => { create: (context) => {
const mappings = context.options[0]; const mappings = context.options[0];
return { return {

View file

@ -40,7 +40,7 @@ module.exports = {
}, },
], ],
}, },
create: context => { create: (context) => {
return { return {
Program(program) { Program(program) {
const license = init(context, program, function () { const license = init(context, program, function () {
@ -69,7 +69,7 @@ module.exports = {
const sourceCode = context.getSourceCode(); const sourceCode = context.getSourceCode();
const comment = sourceCode const comment = sourceCode
.getAllComments() .getAllComments()
.find(node => normalizeWhitespace(node.value) === license.nodeValue); .find((node) => normalizeWhitespace(node.value) === license.nodeValue);
// no licence comment // no licence comment
if (!comment) { if (!comment) {

View file

@ -31,7 +31,7 @@ const padRight = (width, str) =>
run( run(
async ({ log, flags }) => { async ({ log, flags }) => {
await withProcRunner(log, async proc => { await withProcRunner(log, async (proc) => {
log.info('Deleting old output'); log.info('Deleting old output');
await del(BUILD_DIR); await del(BUILD_DIR);
@ -43,7 +43,7 @@ run(
log.info(`Starting babel and typescript${flags.watch ? ' in watch mode' : ''}`); log.info(`Starting babel and typescript${flags.watch ? ' in watch mode' : ''}`);
await Promise.all([ await Promise.all([
...['web', 'node'].map(subTask => ...['web', 'node'].map((subTask) =>
proc.run(padRight(10, `babel:${subTask}`), { proc.run(padRight(10, `babel:${subTask}`), {
cmd: 'babel', cmd: 'babel',
args: [ args: [

View file

@ -28,17 +28,14 @@ import * as i18n from '../core/i18n';
import { i18nFilter as angularI18nFilter } from './filter'; import { i18nFilter as angularI18nFilter } from './filter';
import { I18nProvider, I18nServiceType } from './provider'; import { I18nProvider, I18nServiceType } from './provider';
angular angular.module('app', []).provider('i18n', I18nProvider).filter('i18n', angularI18nFilter);
.module('app', [])
.provider('i18n', I18nProvider)
.filter('i18n', angularI18nFilter);
describe('i18nFilter', () => { describe('i18nFilter', () => {
let filter: I18nServiceType; let filter: I18nServiceType;
beforeEach(angular.mock.module('app')); beforeEach(angular.mock.module('app'));
beforeEach( beforeEach(
angular.mock.inject(i18nFilter => { angular.mock.inject((i18nFilter) => {
filter = i18nFilter; filter = i18nFilter;
}) })
); );

View file

@ -127,7 +127,7 @@ export function getRegisteredLocales() {
*/ */
export async function getTranslationsByLocale(locale: string): Promise<Translation> { export async function getTranslationsByLocale(locale: string): Promise<Translation> {
const files = translationsRegistry[locale] || []; const files = translationsRegistry[locale] || [];
const notLoadedFiles = files.filter(file => !loadedFiles[file]); const notLoadedFiles = files.filter((file) => !loadedFiles[file]);
if (notLoadedFiles.length) { if (notLoadedFiles.length) {
await loadAndCacheFiles(notLoadedFiles); await loadAndCacheFiles(notLoadedFiles);

View file

@ -37,7 +37,7 @@ function translateFormattedMessageUsingPseudoLocale(message: string) {
if (formattedMessageDelimiter !== null) { if (formattedMessageDelimiter !== null) {
return message return message
.split(formattedMessageDelimiter[0]) .split(formattedMessageDelimiter[0])
.map(part => (part.startsWith('ELEMENT-') ? part : translateUsingPseudoLocale(part))) .map((part) => (part.startsWith('ELEMENT-') ? part : translateUsingPseudoLocale(part)))
.join(formattedMessageDelimiter[0]); .join(formattedMessageDelimiter[0]);
} }

View file

@ -30,7 +30,7 @@ export function Arg(config) {
this.multi = config.multi == null ? false : config.multi; this.multi = config.multi == null ? false : config.multi;
this.resolve = config.resolve == null ? true : config.resolve; this.resolve = config.resolve == null ? true : config.resolve;
this.options = config.options || []; this.options = config.options || [];
this.accepts = type => { this.accepts = (type) => {
if (!this.types.length) return true; if (!this.types.length) return true;
return includes(config.types, type); return includes(config.types, type);
}; };

View file

@ -55,7 +55,7 @@ function getExpressionArgs(block, level = 0) {
const argKeys = Object.keys(args); const argKeys = Object.keys(args);
const MAX_LINE_LENGTH = 80; // length before wrapping arguments const MAX_LINE_LENGTH = 80; // length before wrapping arguments
return argKeys.map(argKey => return argKeys.map((argKey) =>
args[argKey].reduce((acc, arg) => { args[argKey].reduce((acc, arg) => {
const argString = getArgumentString(arg, argKey, level); const argString = getArgumentString(arg, argKey, level);
const lineLength = acc.split('\n').pop().length; const lineLength = acc.split('\n').pop().length;
@ -86,7 +86,7 @@ function getExpression(chain, level = 0) {
const separator = level > 0 ? ' | ' : '\n| '; const separator = level > 0 ? ' | ' : '\n| ';
return chain return chain
.map(chainObj => { .map((chainObj) => {
const type = getType(chainObj); const type = getType(chainObj);
if (type === 'function') { if (type === 'function') {

View file

@ -39,7 +39,7 @@ export function Fn(config) {
this.context = config.context || {}; 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 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 return includes(this.context.types, type); // Otherwise, check it
}; };

View file

@ -26,7 +26,7 @@ export function getByAlias(specs, name) {
const lowerCaseName = name.toLowerCase(); const lowerCaseName = name.toLowerCase();
return Object.values(specs).find(({ name, aliases }) => { return Object.values(specs).find(({ name, aliases }) => {
if (name.toLowerCase() === lowerCaseName) return true; if (name.toLowerCase() === lowerCaseName) return true;
return (aliases || []).some(alias => { return (aliases || []).some((alias) => {
return alias.toLowerCase() === lowerCaseName; return alias.toLowerCase() === lowerCaseName;
}); });
}); });

View file

@ -48,7 +48,7 @@ export class Registry {
} }
toArray() { toArray() {
return Object.keys(this._indexed).map(key => this.get(key)); return Object.keys(this._indexed).map((key) => this.get(key));
} }
get(name) { get(name) {

View file

@ -24,7 +24,7 @@
* @param {*} newRegistries - The new set of registries * @param {*} newRegistries - The new set of registries
*/ */
export function addRegistries(registries, newRegistries) { export function addRegistries(registries, newRegistries) {
Object.keys(newRegistries).forEach(registryName => { Object.keys(newRegistries).forEach((registryName) => {
if (registries[registryName]) { if (registries[registryName]) {
throw new Error(`There is already a registry named "${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: [] }) * @param {*} specs - The specs to be regsitered (e.g. { types: [], browserFunctions: [] })
*/ */
export function register(registries, specs) { export function register(registries, specs) {
Object.keys(specs).forEach(registryName => { Object.keys(specs).forEach((registryName) => {
if (!registries[registryName]) { if (!registries[registryName]) {
throw new Error(`There is no registry named "${registryName}".`); throw new Error(`There is no registry named "${registryName}".`);
} }
@ -49,7 +49,7 @@ export function register(registries, specs) {
if (!registries[registryName].register) { if (!registries[registryName].register) {
throw new Error(`Registry "${registryName}" must have a register function.`); 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; return registries;

View file

@ -56,7 +56,7 @@ if (flags.help) {
process.exit(); process.exit();
} }
withProcRunner(log, async proc => { withProcRunner(log, async (proc) => {
log.info('Deleting old output'); log.info('Deleting old output');
await del(BUILD_DIR); await del(BUILD_DIR);
@ -87,7 +87,7 @@ withProcRunner(log, async proc => {
]); ]);
log.success('Complete'); log.success('Complete');
}).catch(error => { }).catch((error) => {
log.error(error); log.error(error);
process.exit(1); process.exit(1);
}); });

View file

@ -77,8 +77,8 @@ run(
const extraPluginScanDirs = ([] as string[]) const extraPluginScanDirs = ([] as string[])
.concat((flags['scan-dir'] as string | string[]) || []) .concat((flags['scan-dir'] as string | string[]) || [])
.map(p => Path.resolve(p)); .map((p) => Path.resolve(p));
if (!extraPluginScanDirs.every(s => typeof s === 'string')) { if (!extraPluginScanDirs.every((s) => typeof s === 'string')) {
throw createFlagError('expected --scan-dir to be a string'); throw createFlagError('expected --scan-dir to be a string');
} }

View file

@ -53,11 +53,7 @@ describe('ascending/descending', () => {
].sort(() => 0.5 - Math.random()); ].sort(() => 0.5 - Math.random());
it('sorts items using getters', () => { it('sorts items using getters', () => {
expect( expect(Array.from(values).sort(ascending(a, b, c)).map(print)).toMatchInlineSnapshot(`
Array.from(values)
.sort(ascending(a, b, c))
.map(print)
).toMatchInlineSnapshot(`
Array [ Array [
"1/2/3", "1/2/3",
"3/2/1", "3/2/1",
@ -81,11 +77,7 @@ describe('ascending/descending', () => {
] ]
`); `);
expect( expect(Array.from(values).sort(descending(a, b, c)).map(print)).toMatchInlineSnapshot(`
Array.from(values)
.sort(descending(a, b, c))
.map(print)
).toMatchInlineSnapshot(`
Array [ Array [
"9/9/9", "9/9/9",
"8/foo/8", "8/foo/8",

View file

@ -80,7 +80,7 @@ export class Bundle {
return { return {
spec: this.toSpec(), spec: this.toSpec(),
mtimes: entriesToObject( 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]))
), ),
}; };
} }

View file

@ -130,7 +130,7 @@ export const checks: DisallowedSyntaxCheck[] = [
{ {
name: '[es2018] object spread properties', name: '[es2018] object spread properties',
nodeType: 'ObjectExpression', 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 // https://github.com/estree/estree/blob/master/es2018.md#template-literals
{ {
@ -142,7 +142,7 @@ export const checks: DisallowedSyntaxCheck[] = [
{ {
name: '[es2018] rest properties', name: '[es2018] rest properties',
nodeType: 'ObjectPattern', nodeType: 'ObjectPattern',
test: (n: estree.ObjectPattern) => n.properties.some(p => p.type === 'RestElement'), test: (n: estree.ObjectPattern) => n.properties.some((p) => p.type === 'RestElement'),
}, },
/** /**

View file

@ -26,8 +26,8 @@ import { parseFilePath } from '../parse_path';
export class DisallowedSyntaxPlugin { export class DisallowedSyntaxPlugin {
apply(compiler: webpack.Compiler) { apply(compiler: webpack.Compiler) {
compiler.hooks.normalModuleFactory.tap(DisallowedSyntaxPlugin.name, factory => { compiler.hooks.normalModuleFactory.tap(DisallowedSyntaxPlugin.name, (factory) => {
factory.hooks.parser.for('javascript/auto').tap(DisallowedSyntaxPlugin.name, parser => { factory.hooks.parser.for('javascript/auto').tap(DisallowedSyntaxPlugin.name, (parser) => {
parser.hooks.program.tap(DisallowedSyntaxPlugin.name, (program: acorn.Node) => { parser.hooks.program.tap(DisallowedSyntaxPlugin.name, (program: acorn.Node) => {
const module = parser.state?.current; const module = parser.state?.current;
if (!module || !module.resource) { if (!module || !module.resource) {
@ -43,7 +43,7 @@ export class DisallowedSyntaxPlugin {
const failedChecks = new Set<DisallowedSyntaxCheck>(); const failedChecks = new Set<DisallowedSyntaxCheck>();
AcornWalk.full(program, node => { AcornWalk.full(program, (node) => {
const checks = checksByNodeType.get(node.type as any); const checks = checksByNodeType.get(node.type as any);
if (!checks) { if (!checks) {
return; 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 an error to trigger a parse failure, causing this module to be reported as invalid
throw new Error( throw new Error(
`disallowed syntax found in file ${resource}:\n - ${Array.from(failedChecks) `disallowed syntax found in file ${resource}:\n - ${Array.from(failedChecks)
.map(c => c.name) .map((c) => c.name)
.join('\n - ')}` .join('\n - ')}`
); );
}); });

View file

@ -233,6 +233,6 @@ it('stops an infinite stream when unsubscribed', async () => {
// ensure summarizer still only called 10 times after a timeout // ensure summarizer still only called 10 times after a timeout
expect(summarize).toHaveBeenCalledTimes(10); expect(summarize).toHaveBeenCalledTimes(10);
await new Promise(resolve => setTimeout(resolve, 1000)); await new Promise((resolve) => setTimeout(resolve, 1000));
expect(summarize).toHaveBeenCalledTimes(10); expect(summarize).toHaveBeenCalledTimes(10);
}); });

View file

@ -40,7 +40,7 @@ export const summarizeEventStream = <Event, State>(
initialState: State, initialState: State,
summarize: Summarizer<Event, State> summarize: Summarizer<Event, State>
) => { ) => {
return new Rx.Observable<Update<Event, State>>(subscriber => { return new Rx.Observable<Update<Event, State>>((subscriber) => {
const eventBuffer: Event[] = []; const eventBuffer: Event[] = [];
let processingEventBuffer = false; let processingEventBuffer = false;
@ -93,7 +93,7 @@ export const summarizeEventStream = <Event, State>(
subscriber.add( subscriber.add(
event$.subscribe( event$.subscribe(
injectEvent, injectEvent,
error => { (error) => {
subscriber.error(error); subscriber.error(error);
}, },
() => { () => {

View file

@ -32,13 +32,13 @@ const FILES = [
]; ];
describe('parseFilePath()', () => { describe('parseFilePath()', () => {
it.each([...FILES, ...AMBIGUOUS])('parses %s', path => { it.each([...FILES, ...AMBIGUOUS])('parses %s', (path) => {
expect(parseFilePath(path)).toMatchSnapshot(); expect(parseFilePath(path)).toMatchSnapshot();
}); });
}); });
describe('parseDirPath()', () => { describe('parseDirPath()', () => {
it.each([...DIRS, ...AMBIGUOUS])('parses %s', path => { it.each([...DIRS, ...AMBIGUOUS])('parses %s', (path) => {
expect(parseDirPath(path)).toMatchSnapshot(); expect(parseDirPath(path)).toMatchSnapshot();
}); });
}); });

View file

@ -29,9 +29,9 @@ describe('pipeClosure()', () => {
let counter = 0; let counter = 0;
const foo$ = Rx.of(1, 2, 3).pipe( const foo$ = Rx.of(1, 2, 3).pipe(
pipeClosure(source$ => { pipeClosure((source$) => {
const multiplier = ++counter; const multiplier = ++counter;
return source$.pipe(map(i => i * multiplier)); return source$.pipe(map((i) => i * multiplier));
}), }),
toArray() toArray()
); );
@ -71,7 +71,7 @@ describe('maybe()', () => {
describe('maybeMap()', () => { describe('maybeMap()', () => {
it('calls map fn and filters out undefined values returned', async () => { it('calls map fn and filters out undefined values returned', async () => {
const foo$ = Rx.of(1, 2, 3, 4, 5).pipe( const foo$ = Rx.of(1, 2, 3, 4, 5).pipe(
maybeMap(i => (i % 2 ? i : undefined)), maybeMap((i) => (i % 2 ? i : undefined)),
toArray() toArray()
); );
@ -94,7 +94,7 @@ describe('debounceTimeBuffer()', () => {
foo$ foo$
.pipe( .pipe(
debounceTimeBuffer(100), debounceTimeBuffer(100),
map(items => items.reduce((sum, n) => sum + n)) map((items) => items.reduce((sum, n) => sum + n))
) )
.subscribe(dest); .subscribe(dest);
@ -128,7 +128,7 @@ describe('debounceTimeBuffer()', () => {
foo$ foo$
.pipe( .pipe(
debounceTimeBuffer(100), debounceTimeBuffer(100),
map(items => items.reduce((sum, n) => sum + n)) map((items) => items.reduce((sum, n) => sum + n))
) )
.subscribe(dest); .subscribe(dest);

View file

@ -39,7 +39,7 @@ export const pipeClosure = <T1, T2>(fn: Operator<T1, T2>): Operator<T1, T2> => {
* supporting TypeScript * supporting TypeScript
*/ */
export const maybe = <T1>(): Operator<T1 | undefined, T1> => { export const maybe = <T1>(): Operator<T1 | undefined, T1> => {
return mergeMap(item => (item === undefined ? Rx.EMPTY : [item])); return mergeMap((item) => (item === undefined ? Rx.EMPTY : [item]));
}; };
/** /**
@ -64,7 +64,7 @@ export const debounceTimeBuffer = <T>(ms: number) =>
pipeClosure((source$: Rx.Observable<T>) => { pipeClosure((source$: Rx.Observable<T>) => {
const buffer: T[] = []; const buffer: T[] = [];
return source$.pipe( return source$.pipe(
tap(item => buffer.push(item)), tap((item) => buffer.push(item)),
debounceTime(ms), debounceTime(ms),
map(() => { map(() => {
const items = Array.from(buffer); const items = Array.from(buffer);

View file

@ -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); assert('produce at least one initializing event', initializingStates.length >= 1);
const bundleCacheStates = msgs.filter( const bundleCacheStates = msgs.filter(
msg => (msg) =>
(msg.event?.type === 'bundle cached' || msg.event?.type === 'bundle not cached') && (msg.event?.type === 'bundle cached' || msg.event?.type === 'bundle not cached') &&
msg.state.phase === 'initializing' msg.state.phase === 'initializing'
); );
assert('produce two bundle cache events while initializing', bundleCacheStates.length === 2); 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); 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); 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( assert(
'produce two or three "running" states', 'produce two or three "running" states',
runningStates.length === 2 || runningStates.length === 3 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); 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( assert(
'produce one or two "compiler success" states', 'produce one or two "compiler success" states',
successStates.length === 1 || successStates.length === 2 successStates.length === 1 || successStates.length === 2
); );
const otherStates = msgs.filter( const otherStates = msgs.filter(
msg => (msg) =>
msg.state.phase !== 'initializing' && msg.state.phase !== 'initializing' &&
msg.state.phase !== 'success' && msg.state.phase !== 'success' &&
msg.state.phase !== 'running' && 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); 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(); expect(foo).toBeTruthy();
foo.cache.refresh(); foo.cache.refresh();
expect(foo.cache.getModuleCount()).toBe(4); 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(); expect(bar).toBeTruthy();
bar.cache.refresh(); bar.cache.refresh();
expect(bar.cache.getModuleCount()).toBe( expect(bar.cache.getModuleCount()).toBe(
@ -173,7 +173,7 @@ it('uses cache on second run and exist cleanly', async () => {
const msgs = await runOptimizer(config) const msgs = await runOptimizer(config)
.pipe( .pipe(
tap(state => { tap((state) => {
if (state.event?.type === 'worker stdio') { if (state.event?.type === 'worker stdio') {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.log('worker', state.event.stream, state.event.chunk.toString('utf8')); 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(); .toPromise();
expect(msgs.map(m => m.state.phase)).toMatchInlineSnapshot(` expect(msgs.map((m) => m.state.phase)).toMatchInlineSnapshot(`
Array [ Array [
"initializing", "initializing",
"initializing", "initializing",
@ -202,9 +202,7 @@ it('prepares assets for distribution', async () => {
dist: true, dist: true,
}); });
await runOptimizer(config) await runOptimizer(config).pipe(logOptimizerState(log, config), toArray()).toPromise();
.pipe(logOptimizerState(log, config), toArray())
.toPromise();
expectFileMatchesSnapshotWithCompression('plugins/foo/target/public/foo.plugin.js', 'foo bundle'); expectFileMatchesSnapshotWithCompression('plugins/foo/target/public/foo.plugin.js', 'foo bundle');
expectFileMatchesSnapshotWithCompression( expectFileMatchesSnapshotWithCompression(

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