Skip to content

Commit 20a7dcc

Browse files
authored
fix(scope-manager): fallback to lib 'esnext' or 'es5' when ecma version is unsupported (#2474)
1 parent bfe255f commit 20a7dcc

File tree

2 files changed

+49
-5
lines changed

2 files changed

+49
-5
lines changed

Diff for: packages/scope-manager/src/analyze.ts

+4-5
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { TSESTree, EcmaVersion, Lib } from '@typescript-eslint/types';
22
import { visitorKeys } from '@typescript-eslint/visitor-keys';
33
import { Referencer, ReferencerOptions } from './referencer';
44
import { ScopeManager } from './ScopeManager';
5+
import { lib as TSLibraries } from './lib';
56

67
////////////////////////////////////////////////////
78
// MAKE SURE THIS IS KEPT IN SYNC WITH THE README //
@@ -61,12 +62,10 @@ function mapEcmaVersion(version: EcmaVersion | undefined): Lib {
6162
return 'es5';
6263
}
6364

64-
if (version > 2000) {
65-
return `es${version}` as Lib;
66-
}
65+
const year = version > 2000 ? version : 2015 + (version - 6);
66+
const lib = `es${year}`;
6767

68-
const year = 2015 + (version - 6);
69-
return `es${year}` as Lib;
68+
return lib in TSLibraries ? (lib as Lib) : year > 2020 ? 'esnext' : 'es5';
7069
}
7170

7271
/**
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { analyze } from '../../src/analyze';
2+
import { Referencer } from '../../src/referencer';
3+
import { TSESTree, EcmaVersion, Lib } from '@typescript-eslint/types';
4+
5+
jest.mock('../../src/referencer');
6+
jest.mock('../../src/ScopeManager');
7+
8+
describe('ecma version mapping', () => {
9+
it("should map to 'esnext' when unsuported and new", () => {
10+
expectMapping(2042, 'esnext');
11+
expectMapping(42, 'esnext');
12+
});
13+
14+
it("should map to 'es5' when unsuported and old", () => {
15+
expectMapping(2002, 'es5');
16+
expectMapping(2, 'es5');
17+
});
18+
19+
it("should map to 'es{year}' when supported and >= 6", () => {
20+
expectMapping(2015, 'es2015');
21+
expectMapping(6, 'es2015');
22+
expectMapping(2020, 'es2020');
23+
expectMapping(11, 'es2020');
24+
});
25+
26+
it("should map to 'es5' when 5 or 3", () => {
27+
expectMapping(5, 'es5');
28+
expectMapping(3, 'es5');
29+
});
30+
31+
it("should map to 'es2018' when undefined", () => {
32+
expectMapping(undefined, 'es2018');
33+
});
34+
});
35+
36+
const fakeNode = ({} as unknown) as TSESTree.Node;
37+
38+
function expectMapping(ecmaVersion: number | undefined, lib: Lib): void {
39+
(Referencer as jest.Mock).mockClear();
40+
analyze(fakeNode, { ecmaVersion: ecmaVersion as EcmaVersion });
41+
expect(Referencer).toHaveBeenCalledWith(
42+
expect.objectContaining({ lib: [lib] }),
43+
expect.any(Object),
44+
);
45+
}

0 commit comments

Comments
 (0)