Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ts] enable "resolveJsonModule" and disable existing failures #78855

Merged
merged 2 commits into from
Sep 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
// Resolve modules in the same way as Node.js. Aka make `require` works the
// same in TypeScript as it does in Node.js.
"moduleResolution": "node",
// "resolveJsonModule" allows for importing, extracting types from and generating .json files.
"resolveJsonModule": true,
// Disallow inconsistently-cased references to the same file.
"forceConsistentCasingInFileNames": true,
// Forbid unused local variables as the rule was deprecated by ts-lint
Expand Down
9 changes: 0 additions & 9 deletions typings/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,6 @@ declare module '*.svg' {
export default content;
}

// allow JSON files to be imported directly without lint errors
// see: https://github.com/palantir/tslint/issues/1264#issuecomment-228433367
// and: https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#arbitrary-expressions-are-forbidden-in-export-assignments-in-ambient-contexts
declare module '*.json' {
const json: any;
// eslint-disable-next-line import/no-default-export
export default json;
}

type MethodKeysOf<T> = {
[K in keyof T]: T[K] extends (...args: any[]) => any ? K : never;
}[keyof T];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ describe('ErrorGroupOverview -> List', () => {
<MemoryRouter>
<MockApmPluginContextWrapper>
<MockUrlParamsContextProvider>
{/* @ts-expect-error invalid json props */}
<ErrorGroupList items={props.items} serviceName="opbeans-python" />
</MockUrlParamsContextProvider>
</MockApmPluginContextWrapper>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import mockTransaction from './mockTransaction.json';

describe('DiscoverTransactionLink component', () => {
it('should render with data', () => {
// @ts-expect-error invalid json mock
const transaction: Transaction = mockTransaction;

expect(
Expand All @@ -25,6 +26,7 @@ describe('DiscoverTransactionLink component', () => {

describe('getDiscoverQuery', () => {
it('should return the correct query params object', () => {
// @ts-expect-error invalid json mock
const transaction: Transaction = mockTransaction;
const result = getDiscoverQuery(transaction);
expect(result).toMatchSnapshot();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ import expectedGroupedData from './mock_responses/group_resource_nodes_grouped.j

describe('groupResourceNodes', () => {
it('should group external nodes', () => {
// @ts-expect-error invalid json mock
const responseWithGroups = groupResourceNodes(preGroupedData);
expect(responseWithGroups.elements).toHaveLength(
expectedGroupedData.elements.length
);
for (const element of responseWithGroups.elements) {
const expectedElement = expectedGroupedData.elements.find(
({ data: { id } }: { data: { id: string } }) => id === element.data.id
);
)!;
expect(element).toMatchObject(expectedElement);
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ describe('getServiceAnnotations', () => {
searchAggregatedTransactions: false,
}),
{
// @ts-expect-error invalid json mock
mockResponse: () => noVersions,
}
);
Expand All @@ -50,6 +51,7 @@ describe('getServiceAnnotations', () => {
searchAggregatedTransactions: false,
}),
{
// @ts-expect-error invalid json mock
mockResponse: () => oneVersion,
}
);
Expand All @@ -74,6 +76,7 @@ describe('getServiceAnnotations', () => {
searchAggregatedTransactions: false,
}),
{
// @ts-expect-error invalid json mock
mockResponse: () => responses.shift(),
}
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export function demodata(): ExpressionFunctionDefinition<
{ id: 'project', name: 'project', meta: { type: 'string' } },
{ id: 'percent_uptime', name: 'percent_uptime', meta: { type: 'number' } },
],
// @ts-expect-error invalid json mock
rows: sortBy(demoRows, 'time'),
};
} else if (args.type === DemoRows.SHIRTS) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
* you may not use this file except in compliance with the Elastic License.
*/

/*
One test relies on react-dom at a version of 16.9... it can be enabled
once renovate completes the upgrade. Relevant code has been commented out
in the meantime.
/*
One test relies on react-dom at a version of 16.9... it can be enabled
once renovate completes the upgrade. Relevant code has been commented out
in the meantime.
*/

import { mount, ReactWrapper } from 'enzyme';
Expand Down
9 changes: 8 additions & 1 deletion x-pack/plugins/canvas/shareable_runtime/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,11 @@ import test from './workpads/test.json';
export * from './utils';

export type WorkpadNames = keyof typeof sharedWorkpads;
export const sharedWorkpads = { hello, austin, test };
export const sharedWorkpads = {
// TODO: the automatic types for these JSON files are insufficient, and "austin" is so massive
// that Typescript refuses to type it. These should be converted to TypeScript and typed to fit
// the requirements. "austin" should also be reduced to the necessary data
hello: hello as any,
austin: austin as any,
test: test as any,
};
1 change: 1 addition & 0 deletions x-pack/plugins/infra/public/utils/apollo_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const createApolloClient = (fetch: HttpHandler) => {
const cache = new InMemoryCache({
addTypename: false,
fragmentMatcher: new IntrospectionFragmentMatcher({
// @ts-expect-error apollo-cache-inmemory types don't match actual introspection data
introspectionQueryResultData,
}),
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ describe('AnnotationDescriptionList', () => {
});

test('Initialization with annotation.', () => {
// @ts-expect-error mock data is too loosely typed
const wrapper = shallowWithIntl(<AnnotationDescriptionList annotation={mockAnnotations[0]} />);
expect(wrapper).toMatchSnapshot();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ describe('DeleteAction', () => {

it('should display a tooltip when isDisabled prop is true.', () => {
const { container } = render(
// @ts-expect-error mock data is incorrectly typed
<DeleteActionName isDisabled={true} item={mockAnalyticsListItem} />
);

Expand All @@ -59,6 +60,7 @@ describe('DeleteAction', () => {

it('should not display a tooltip when isDisabled prop is false.', () => {
const { container } = render(
// @ts-expect-error mock data is incorrectly typed
<DeleteActionName isDisabled={false} item={mockAnalyticsListItem} />
);

Expand All @@ -78,8 +80,12 @@ describe('DeleteAction', () => {
{deleteAction.isModalVisible && <DeleteActionModal {...deleteAction} />}
<button
data-test-subj="mlAnalyticsJobDeleteButton"
onClick={() => deleteAction.openModal(mockAnalyticsListItem)}
onClick={() => {
// @ts-expect-error mock data is incorrectly typed
deleteAction.openModal(mockAnalyticsListItem);
}}
>
{/* @ts-expect-error mock data is incorrectly typed */}
<DeleteActionName isDisabled={false} item={mockAnalyticsListItem} />
</button>
</>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { getAnnotationLevels } from './timeseries_chart_annotations';

describe('Timeseries Chart Annotations: getAnnotationLevels()', () => {
test('getAnnotationLevels()', () => {
// @ts-expect-error mock data is too loosely typed
const levels = getAnnotationLevels(mockAnnotationsOverlap);
expect(levels).toEqual({ A: 0, B: 1, C: 2, D: 2 });
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ describe('ML - validateTimeRange', () => {

it('invalid time field', () => {
const mockSearchResponseInvalid = cloneDeep(mockSearchResponse);
// @ts-expect-error creating intentionally invalid data
mockSearchResponseInvalid.fieldCaps = undefined;
const duration = { start: 0, end: 1 };
return validateTimeRange(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ describe('getLinks helper', () => {
const mockCache = new InMemoryCache({
dataIdFromObject: () => null,
fragmentMatcher: new IntrospectionFragmentMatcher({
// @ts-expect-error apollo-cache-inmemory types don't match actual introspection data
introspectionQueryResultData,
}),
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export function composeLibs(core: CoreStart): AppFrontendLibs {
const cache = new InMemoryCache({
dataIdFromObject: () => null,
fragmentMatcher: new IntrospectionFragmentMatcher({
// @ts-expect-error apollo-cache-inmemory types don't match actual introspection data
introspectionQueryResultData,
}),
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@
import { uniq } from 'lodash/fp';
import { db } from 'suricata-sid-db';

const has = <T>(obj: T, key: string | number | symbol): key is keyof T =>
Object.prototype.hasOwnProperty.call(obj, key);

export const getLinksFromSignature = (id: number): string[] => {
const refs = db[id];
const refs = has(db, id) ? db[id] : null;
if (refs != null) {
return uniq(refs);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import signalsMapping from './signals_mapping.json';
import ecsMapping from './ecs_mapping.json';

export const getSignalsTemplate = (index: string) => {
ecsMapping.mappings.properties.signal = signalsMapping.mappings.properties.signal;
const template = {
settings: {
index: {
Expand All @@ -24,7 +23,13 @@ export const getSignalsTemplate = (index: string) => {
},
},
index_patterns: [`${index}-*`],
mappings: ecsMapping.mappings,
mappings: {
...ecsMapping.mappings,
properties: {
...ecsMapping.mappings.properties,
signal: signalsMapping.mappings.properties.signal,
},
},
version: 1,
};
return template;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,14 @@ describe('get_existing_prepackaged_rules', () => {
});

test('should throw an exception if a pre-packaged rule is not valid', () => {
// @ts-expect-error intentionally invalid argument
expect(() => getPrepackagedRules([{ not_valid_made_up_key: true }])).toThrow(
'name: "(rule name unknown)", rule_id: "(rule rule_id unknown)" within the folder rules/prepackaged_rules is not a valid detection engine rule. Expect the system to not work with pre-packaged rules until this rule is fixed or the file is removed. Error is: Invalid value "undefined" supplied to "description",Invalid value "undefined" supplied to "risk_score",Invalid value "undefined" supplied to "name",Invalid value "undefined" supplied to "severity",Invalid value "undefined" supplied to "type",Invalid value "undefined" supplied to "rule_id",Invalid value "undefined" supplied to "version", Full rule contents are:\n{\n "not_valid_made_up_key": true\n}'
);
});

test('should throw an exception with a message having rule_id and name in it', () => {
// @ts-expect-error intentionally invalid argument
expect(() => getPrepackagedRules([{ name: 'rule name', rule_id: 'id-123' }])).toThrow(
'name: "rule name", rule_id: "id-123" within the folder rules/prepackaged_rules is not a valid detection engine rule. Expect the system to not work with pre-packaged rules until this rule is fixed or the file is removed. Error is: Invalid value "undefined" supplied to "description",Invalid value "undefined" supplied to "risk_score",Invalid value "undefined" supplied to "severity",Invalid value "undefined" supplied to "type",Invalid value "undefined" supplied to "version", Full rule contents are:\n{\n "name": "rule name",\n "rule_id": "id-123"\n}'
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import {
AddPrepackagedRulesSchemaDecoded,
} from '../../../../common/detection_engine/schemas/request/add_prepackaged_rules_schema';
import { BadRequestError } from '../errors/bad_request_error';

// TODO: convert rules files to TS and add explicit type definitions
import { rawRules } from './prepackaged_rules';

/**
Expand Down Expand Up @@ -49,5 +51,7 @@ export const validateAllPrepackagedRules = (
});
};

export const getPrepackagedRules = (rules = rawRules): AddPrepackagedRulesSchemaDecoded[] =>
validateAllPrepackagedRules(rules);
export const getPrepackagedRules = (
// @ts-expect-error mock data is too loosely typed
rules: AddPrepackagedRulesSchema[] = rawRules
): AddPrepackagedRulesSchemaDecoded[] => validateAllPrepackagedRules(rules);
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ import { getTransformProgress, isCompletedBatchTransform } from './transform_sta

const getRow = (statsId: string) => {
return {
// @ts-expect-error mock data does not actually match TransformListRow type
...(mockTransformListRow as TransformListRow),
stats: {
...mockTransformStats.transforms.find(
(stats: TransformListRow['stats']) => stats.id === statsId
),
...(mockTransformStats.transforms as Array<TransformListRow['stats']>).find(
(stats) => stats.id === statsId
)!,
},
};
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ jest.mock('../../../../../app/app_dependencies');

describe('Transform: Transform List Actions <StartAction />', () => {
test('Minimal initialization', () => {
// @ts-expect-error mock data is too loosely typed
const item: TransformListRow = transformListRow;
const props: StartActionNameProps = {
forceDisable: false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ jest.mock('../../../../../app/app_dependencies');

describe('Transform: Transform List Actions <StopAction />', () => {
test('Minimal initialization', () => {
// @ts-expect-error mock data is too loosely typed
const item: TransformListRow = transformListRow;
const props: StopActionNameProps = {
forceDisable: false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@ describe('Transform: isCompletedBatchTransform()', () => {
// check the transform config/state against the conditions
// that will be used by isCompletedBatchTransform()
// followed by a call to isCompletedBatchTransform() itself
// @ts-expect-error mock data is too loosely typed
const row = mockTransformListRow as TransformListRow;
expect(row.stats.checkpointing.last.checkpoint === 1).toBe(true);
expect(row.config.sync === undefined).toBe(true);
expect(row.stats.state === TRANSFORM_STATE.STOPPED).toBe(true);
expect(isCompletedBatchTransform(mockTransformListRow)).toBe(true);
expect(isCompletedBatchTransform(row)).toBe(true);

// adapt the mock config to resemble a non-completed transform.
row.stats.checkpointing.last.checkpoint = 0;
expect(isCompletedBatchTransform(mockTransformListRow)).toBe(false);
expect(isCompletedBatchTransform(row)).toBe(false);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ describe('Transform: Transform List <ExpandedRow />', () => {

test('Minimal initialization', async () => {
const mlShared = await getMlSharedImports();
// @ts-expect-error mock data is too loosely typed
const item: TransformListRow = transformListRow;

const { getByText, getByTestId } = render(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const defaultProps = {
*/
describe('CheckupTab', () => {
test('render with deprecations', () => {
// @ts-expect-error mock data is too loosely typed
expect(shallow(<CheckupTab {...defaultProps} />)).toMatchSnapshot();
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ describe('getUpgradeAssistantStatus', () => {
});

beforeEach(() => {
// @ts-expect-error mock data is too loosely typed
deprecationsResponse = _.cloneDeep(fakeDeprecations);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export function InfraOpsGraphQLClientFactoryProvider({ getService }: FtrProvider
return new ApolloClient({
cache: new InMemoryCache({
fragmentMatcher: new IntrospectionFragmentMatcher({
// @ts-expect-error apollo-cache-inmemory types don't match actual introspection data
introspectionQueryResultData,
}),
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export function SecuritySolutionGraphQLClientFactoryProvider({ getService }: Ftr
return new ApolloClient({
cache: new InMemoryCache({
fragmentMatcher: new IntrospectionFragmentMatcher({
// @ts-expect-error apollo-cache-inmemory types don't match actual introspection data
introspectionQueryResultData,
}),
}),
Expand Down
1 change: 0 additions & 1 deletion x-pack/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
"plugins/apm/scripts/**/*"
],
"compilerOptions": {
"outDir": ".",
"paths": {
"kibana/public": ["src/core/public"],
"kibana/server": ["src/core/server"],
Expand Down
9 changes: 0 additions & 9 deletions x-pack/typings/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,6 @@ type Writable<T> = {
-readonly [K in keyof T]: T[K];
};

// allow JSON files to be imported directly without lint errors
// see: https://github.com/palantir/tslint/issues/1264#issuecomment-228433367
// and: https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#arbitrary-expressions-are-forbidden-in-export-assignments-in-ambient-contexts
declare module '*.json' {
const json: any;
// eslint-disable-next-line import/no-default-export
export default json;
}

// Storybook references this module. It's @ts-ignored in the codebase but when
// built into its dist it strips that out. Add it here to avoid a type checking
// error.
Expand Down