-
-
Notifications
You must be signed in to change notification settings - Fork 106
/
compat.ts
253 lines (234 loc) · 7.8 KB
/
compat.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/*
* Step 2) Logic that handles AST traversal
* Does not handle looking up the API
* Handles checking what kinds of eslint nodes should be linted
* Tells eslint to lint certain nodes (lintCallExpression, lintMemberExpression, lintNewExpression)
* Gets protochain for the ESLint nodes the plugin is interested in
*/
import fs from "fs";
import findUp from "find-up";
import memoize from "lodash.memoize";
import { Rule } from "eslint";
import {
lintCallExpression,
lintMemberExpression,
lintNewExpression,
lintExpressionStatement,
parseBrowsersListVersion,
determineTargetsFromConfig,
} from "../helpers"; // will be deprecated and introduced to this file
import {
ESLintNode,
AstMetadataApiWithTargetsResolver,
BrowserListConfig,
HandleFailingRule,
Context,
} from "../types";
import { nodes } from "../providers";
type ESLint = {
[astNodeTypeName: string]: (node: ESLintNode) => void;
};
function getName(node: ESLintNode): string {
switch (node.type) {
case "NewExpression": {
return node.callee!.name;
}
case "MemberExpression": {
return node.object!.name;
}
case "ExpressionStatement": {
return node.expression!.name;
}
case "CallExpression": {
return node.callee!.name;
}
default:
throw new Error("not found");
}
}
function generateErrorName(rule: AstMetadataApiWithTargetsResolver): string {
if (rule.name) return rule.name;
if (rule.property) return `${rule.object}.${rule.property}()`;
return rule.object;
}
const getPolyfillSet = memoize(
(polyfillArrayJSON: string): Set<String> =>
new Set(JSON.parse(polyfillArrayJSON))
);
function isPolyfilled(
context: Context,
rule: AstMetadataApiWithTargetsResolver
): boolean {
if (!context.settings?.polyfills) return false;
const polyfills = getPolyfillSet(JSON.stringify(context.settings.polyfills));
return (
// v2 allowed users to select polyfills based off their caniuseId. This is
polyfills.has(rule.id) || // no longer supported. Keeping this here to avoid breaking changes.
polyfills.has(rule.protoChainId) || // Check if polyfill is provided (ex. `Promise.all`)
polyfills.has(rule.protoChain[0]) // Check if entire API is polyfilled (ex. `Promise`)
);
}
const babelConfigs = [
"babel.config.json",
"babel.config.js",
"babel.config.cjs",
".babelrc",
".babelrc.json",
".babelrc.js",
".babelrc.cjs",
];
/**
* Determine if a user has a babel config, which we use to infer if the linted code is polyfilled.
*/
function isUsingTranspiler(context: Context): boolean {
const dir = context.getFilename();
const configPath = findUp.sync(babelConfigs, {
cwd: dir,
});
if (configPath) return true;
const pkgPath = findUp.sync("package.json", {
cwd: dir,
});
// Check if babel property exists
if (pkgPath) {
const pkg = JSON.parse(fs.readFileSync(pkgPath).toString());
return !!pkg.babel;
}
return false;
}
type RulesFilteredByTargets = {
CallExpression: AstMetadataApiWithTargetsResolver[];
NewExpression: AstMetadataApiWithTargetsResolver[];
MemberExpression: AstMetadataApiWithTargetsResolver[];
ExpressionStatement: AstMetadataApiWithTargetsResolver[];
};
/**
* A small optimization that only lints APIs that are not supported by targeted browsers.
* For example, if the user is targeting chrome 50, which supports the fetch API, it is
* wasteful to lint calls to fetch.
*/
const getRulesForTargets = memoize(
(targetsJSON: string, lintAllEsApis: boolean): RulesFilteredByTargets => {
const result = {
CallExpression: [] as AstMetadataApiWithTargetsResolver[],
NewExpression: [] as AstMetadataApiWithTargetsResolver[],
MemberExpression: [] as AstMetadataApiWithTargetsResolver[],
ExpressionStatement: [] as AstMetadataApiWithTargetsResolver[],
};
const targets = JSON.parse(targetsJSON);
nodes
.filter((node) => (lintAllEsApis ? true : node.kind !== "es"))
.forEach((node) => {
if (!node.getUnsupportedTargets(node, targets).length) return;
result[node.astNodeType].push(node);
});
return result;
}
);
export default {
meta: {
docs: {
description: "Ensure cross-browser API compatibility",
category: "Compatibility",
url: "https://github.com/amilajack/eslint-plugin-compat/blob/master/docs/rules/compat.md",
recommended: true,
},
type: "problem",
schema: [{ type: "string" }],
},
create(context: Context): ESLint {
// Determine lowest targets from browserslist config, which reads user's
// package.json config section. Use config from eslintrc for testing purposes
const browserslistConfig: BrowserListConfig =
context.settings?.browsers ||
context.settings?.targets ||
context.options[0];
const lintAllEsApis: boolean =
context.settings?.lintAllEsApis === true ||
// Attempt to infer polyfilling of ES APIs from babel config
(!context.settings?.polyfills?.includes("es:all") &&
!isUsingTranspiler(context));
const browserslistTargets = parseBrowsersListVersion(
determineTargetsFromConfig(context.getFilename(), browserslistConfig)
);
// Stringify to support memoization; browserslistConfig is always an array of new objects.
const targetedRules = getRulesForTargets(
JSON.stringify(browserslistTargets),
lintAllEsApis
);
type Error = {
message: string;
node: ESLintNode;
};
const errors: Error[] = [];
const handleFailingRule: HandleFailingRule = (
node: AstMetadataApiWithTargetsResolver,
eslintNode: ESLintNode
) => {
if (isPolyfilled(context, node)) return;
errors.push({
node: eslintNode,
message: [
generateErrorName(node),
"is not supported in",
node.getUnsupportedTargets(node, browserslistTargets).join(", "),
].join(" "),
});
};
const identifiers = new Set();
return {
CallExpression: lintCallExpression.bind(
null,
context,
handleFailingRule,
targetedRules.CallExpression
),
NewExpression: lintNewExpression.bind(
null,
context,
handleFailingRule,
targetedRules.NewExpression
),
ExpressionStatement: lintExpressionStatement.bind(
null,
context,
handleFailingRule,
[...targetedRules.MemberExpression, ...targetedRules.CallExpression]
),
MemberExpression: lintMemberExpression.bind(
null,
context,
handleFailingRule,
[
...targetedRules.MemberExpression,
...targetedRules.CallExpression,
...targetedRules.NewExpression,
]
),
// Keep track of all the defined variables. Do not report errors for nodes that are not defined
Identifier(node: ESLintNode) {
if (node.parent) {
const { type } = node.parent;
if (
type === "Property" || // ex. const { Set } = require('immutable');
type === "FunctionDeclaration" || // ex. function Set() {}
type === "VariableDeclarator" || // ex. const Set = () => {}
type === "ClassDeclaration" || // ex. class Set {}
type === "ImportDefaultSpecifier" || // ex. import Set from 'set';
type === "ImportSpecifier" || // ex. import {Set} from 'set';
type === "ImportDeclaration" // ex. import {Set} from 'set';
) {
identifiers.add(node.name);
}
}
},
"Program:exit": () => {
// Get a map of all the variables defined in the root scope (not the global scope)
// const variablesMap = context.getScope().childScopes.map(e => e.set)[0];
errors
.filter((error) => !identifiers.has(getName(error.node)))
.forEach((node) => context.report(node as Rule.ReportDescriptor));
},
};
},
};