-
-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathhelpers.ts
297 lines (280 loc) · 8.4 KB
/
helpers.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/* eslint no-nested-ternary: off */
import browserslist from "browserslist";
import {
AstMetadataApiWithTargetsResolver,
ESLintNode,
SourceCode,
BrowserListConfig,
Target,
HandleFailingRule,
Context,
BrowsersListOpts,
} from "./types";
import { TargetNameMappings } from "./constants";
/*
3) Figures out which browsers user is targeting
- Uses browserslist config and/or targets defined eslint config to discover this
- For every API ecnountered during traversal, gets compat record for that
- Protochain (e.g. 'document.querySelector')
- All of the rules have compatibility info attached to them
- Each API is given to versioning.ts with compatibility info
*/
function isInsideIfStatement(
node: ESLintNode,
sourceCode: SourceCode,
context: Context
) {
const ancestors =
"getAncestors" in sourceCode
? // @ts-expect-error Fits
sourceCode?.getAncestors?.(node)
: context.getAncestors();
return ancestors?.some((ancestor) => {
return ancestor.type === "IfStatement";
});
}
function checkNotInsideIfStatementAndReport(
context: Context,
handleFailingRule: HandleFailingRule,
failingRule: AstMetadataApiWithTargetsResolver,
sourceCode: SourceCode,
node: ESLintNode
) {
if (!isInsideIfStatement(node, sourceCode, context)) {
handleFailingRule(failingRule, node);
}
}
export function lintCallExpression(
context: Context,
handleFailingRule: HandleFailingRule,
rules: AstMetadataApiWithTargetsResolver[],
sourceCode: SourceCode,
node: ESLintNode
) {
if (!node.callee) return;
const calleeName = node.callee.name;
const failingRule = rules.find((rule) => rule.object === calleeName);
if (failingRule)
checkNotInsideIfStatementAndReport(
context,
handleFailingRule,
failingRule,
sourceCode,
node
);
}
export function lintNewExpression(
context: Context,
handleFailingRule: HandleFailingRule,
rules: Array<AstMetadataApiWithTargetsResolver>,
sourceCode: SourceCode,
node: ESLintNode
) {
if (!node.callee) return;
const calleeName = node.callee.name;
const failingRule = rules.find((rule) => rule.object === calleeName);
if (failingRule)
checkNotInsideIfStatementAndReport(
context,
handleFailingRule,
failingRule,
sourceCode,
node
);
}
export function lintExpressionStatement(
context: Context,
handleFailingRule: HandleFailingRule,
rules: AstMetadataApiWithTargetsResolver[],
sourceCode: SourceCode,
node: ESLintNode
) {
if (!node?.expression?.name) return;
const failingRule = rules.find(
(rule) => rule.object === node?.expression?.name
);
if (failingRule)
checkNotInsideIfStatementAndReport(
context,
handleFailingRule,
failingRule,
sourceCode,
node
);
}
function isStringLiteral(node: ESLintNode): boolean {
return node.type === "Literal" && typeof node.value === "string";
}
function protoChainFromMemberExpression(node: ESLintNode): string[] {
if (!node.object) return [node.name];
const protoChain = (() => {
if (
node.object.type === "NewExpression" ||
node.object.type === "CallExpression"
) {
return protoChainFromMemberExpression(node.object.callee!);
} else if (node.object.type === "ArrayExpression") {
return ["Array"];
} else if (isStringLiteral(node.object)) {
return ["String"];
} else {
return protoChainFromMemberExpression(node.object);
}
})();
return [...protoChain, node.property!.name];
}
export function lintMemberExpression(
context: Context,
handleFailingRule: HandleFailingRule,
rules: Array<AstMetadataApiWithTargetsResolver>,
sourceCode: SourceCode,
node: ESLintNode
) {
if (!node.object || !node.property) return;
if (
!node.object.name ||
node.object.name === "window" ||
node.object.name === "globalThis"
) {
const rawProtoChain = protoChainFromMemberExpression(node);
const [firstObj] = rawProtoChain;
const protoChain =
firstObj === "window" || firstObj === "globalThis"
? rawProtoChain.slice(1)
: rawProtoChain;
const protoChainId = protoChain.join(".");
const failingRule = rules.find(
(rule) => rule.protoChainId === protoChainId
);
if (failingRule) {
checkNotInsideIfStatementAndReport(
context,
handleFailingRule,
failingRule,
sourceCode,
node
);
}
} else {
const objectName = node.object.name;
const propertyName = node.property.name;
const failingRule = rules.find(
(rule) =>
rule.object === objectName &&
(rule.property == null || rule.property === propertyName)
);
if (failingRule)
checkNotInsideIfStatementAndReport(
context,
handleFailingRule,
failingRule,
sourceCode,
node
);
}
}
export function reverseTargetMappings<K extends string, V extends string>(
targetMappings: Record<K, V>
): Record<V, K> {
const reversedEntries = Object.entries(targetMappings).map((entry) =>
entry.reverse()
);
return Object.fromEntries(reversedEntries);
}
/**
* Determine the targets based on the browserslist config object
* Get the targets from the eslint config and merge them with targets in browserslist config
* Eslint target config will be deprecated in 4.0.0
*
* @param configPath - The file or a directory path to look for the browserslist config file
*/
export function determineTargetsFromConfig(
configPath: string,
config?: BrowserListConfig,
browserslistOptsFromConfig?: BrowsersListOpts
): Array<string> {
const browserslistOpts = { path: configPath, ...browserslistOptsFromConfig };
const eslintTargets = (() => {
// Get targets from eslint settings
if (Array.isArray(config) || typeof config === "string") {
return browserslist(config, browserslistOpts);
}
if (config && typeof config === "object") {
return browserslist(
[...(config.production || []), ...(config.development || [])],
browserslistOpts
);
}
return [];
})();
if (browserslist.findConfig(configPath)) {
// If targets are defined in ESLint and browerslist configs, merge the targets together
if (eslintTargets.length) {
const browserslistTargets = browserslist(undefined, browserslistOpts);
return Array.from(new Set(eslintTargets.concat(browserslistTargets)));
}
} else if (eslintTargets.length) {
return eslintTargets;
}
// Get targets fron browserslist configs
return browserslist(undefined, browserslistOpts);
}
/**
* Parses the versions that are given by browserslist. They're
*
* ```ts
* parseBrowsersListVersion(['chrome 50'])
*
* {
* target: 'chrome',
* parsedVersion: 50,
* version: '50'
* }
* ```
* @param targetslist - List of targest from browserslist api
* @returns - The lowest version version of each target
*/
export function parseBrowsersListVersion(
targetslist: Array<string>
): Array<Target> {
return (
// Sort the targets by target name and then version number in ascending order
targetslist
.map((e: string): Target => {
const [target, version] = e.split(" ") as [
keyof TargetNameMappings,
number | string,
];
const parsedVersion: number = (() => {
if (typeof version === "number") return version;
if (version === "all") return 0;
return version.includes("-")
? parseFloat(version.split("-")[0])
: parseFloat(version);
})();
return {
target,
version,
parsedVersion,
};
}) // Sort the targets by target name and then version number in descending order
// ex. [a@3, b@3, a@1] => [a@3, a@1, b@3]
.sort((a: Target, b: Target): number => {
if (b.target === a.target) {
// If any version === 'all', return 0. The only version of op_mini is 'all'
// Otherwise, compare the versions
return typeof b.parsedVersion === "string" ||
typeof a.parsedVersion === "string"
? 0
: b.parsedVersion - a.parsedVersion;
}
return b.target > a.target ? 1 : -1;
}) // First last target always has the latest version
.filter(
(e: Target, i: number, items: Array<Target>): boolean =>
// Check if the current target is the last of its kind.
// If it is, then it's the most recent version.
i + 1 === items.length || e.target !== items[i + 1].target
)
);
}