-
-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathhelpers.ts
More file actions
441 lines (414 loc) · 13 KB
/
helpers.ts
File metadata and controls
441 lines (414 loc) · 13 KB
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/* eslint no-nested-ternary: off */
import browserslist from "browserslist";
import globals from "globals";
import { AstNodeTypes, TargetNameMappings } from "./constants";
import {
AstMetadataApiWithTargetsResolver,
BrowserListConfig,
BrowsersListOpts,
Context,
ESLintNode,
HandleFailingRule,
SourceCode,
Target,
} from "./types";
/*
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
) {
// Handle both ESLint 8 and 9 - getAncestors moved from context to sourceCode
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let ancestors: any;
if ("getAncestors" in sourceCode) {
// @ts-expect-error - ESLint 9+ uses sourceCode.getAncestors
ancestors = sourceCode?.getAncestors?.(node);
} else {
// ESLint 8 uses context.getAncestors - cast to any for compatibility
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ancestors = (context as any).getAncestors?.();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return ancestors?.some((ancestor: any) => {
return ancestor.type === "IfStatement";
});
}
/**
* Check if a node (IfStatement consequent) contains a return or throw statement,
* indicating an early exit guard.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function containsEarlyExit(node: any): boolean {
if (!node) return false;
if (node.type === "ReturnStatement" || node.type === "ThrowStatement")
return true;
if (node.type === "BlockStatement" && Array.isArray(node.body)) {
return node.body.some(containsEarlyExit);
}
return false;
}
/**
* Recursively check if an expression references the API identified by the rule
* (by object name, property name, or a string literal matching either).
*/
function expressionReferencesApi(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
node: any,
rule: AstMetadataApiWithTargetsResolver
): boolean {
if (!node) return false;
if (node.type === "Identifier") {
return node.name === rule.object || node.name === rule.property;
}
if (node.type === "Literal" && typeof node.value === "string") {
return node.value === rule.object || node.value === rule.property;
}
if (node.type === "UnaryExpression") {
return expressionReferencesApi(node.argument, rule);
}
if (node.type === "BinaryExpression" || node.type === "LogicalExpression") {
return (
expressionReferencesApi(node.left, rule) ||
expressionReferencesApi(node.right, rule)
);
}
if (node.type === "MemberExpression") {
return (
expressionReferencesApi(node.object, rule) ||
expressionReferencesApi(node.property, rule)
);
}
if (node.type === "CallExpression") {
return expressionReferencesApi(node.callee, rule);
}
return false;
}
/**
* Detect the early-return guard pattern:
*
* if (!('foo' in window)) { return; }
* window.foo.bar(); // <-- this node is guarded
*
* Walks up from the node to the nearest block body, then checks preceding
* sibling statements for an if-with-early-exit whose test references the
* same API as the failing rule.
*/
function isGuardedByEarlyReturn(
node: ESLintNode,
failingRule: AstMetadataApiWithTargetsResolver
): boolean {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let current: any = node;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let parent: any = node.parent;
while (parent) {
if (
(parent.type === "BlockStatement" || parent.type === "Program") &&
Array.isArray(parent.body)
) {
const stmtIndex = parent.body.indexOf(current);
if (stmtIndex > 0) {
for (let i = 0; i < stmtIndex; i++) {
const stmt = parent.body[i];
if (
stmt.type === "IfStatement" &&
containsEarlyExit(stmt.consequent) &&
expressionReferencesApi(stmt.test, failingRule)
) {
return true;
}
}
}
break;
}
current = parent;
parent = parent.parent;
}
return false;
}
function checkNotInsideIfStatementAndReport(
context: Context,
handleFailingRule: HandleFailingRule,
failingRule: AstMetadataApiWithTargetsResolver,
sourceCode: SourceCode,
node: ESLintNode
) {
if (
context.settings?.ignoreConditionalChecks === true ||
(!isInsideIfStatement(node, sourceCode, context) &&
!isGuardedByEarlyReturn(node, failingRule))
) {
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 checkRegexpLiteral(node: ESLintNode): boolean {
return (
node.type === AstNodeTypes.Literal &&
(!!node.regex || node.parent?.callee?.name === "RegExp")
);
}
export function lintLiteral(
context: Context,
handleFailingRule: HandleFailingRule,
rules: AstMetadataApiWithTargetsResolver[],
sourceCode: SourceCode,
node: ESLintNode
) {
const isRegexpLiteral = checkRegexpLiteral(node);
const failingRule = rules.find((rule) =>
rule.syntaxes?.some(
(syntax) => (isRegexpLiteral ? node.raw.includes(syntax) : false) // non-regexp literals are not supported yet
)
);
if (failingRule) handleFailingRule(failingRule, node);
}
function isStringLiteral(node: ESLintNode): boolean {
return node.type === AstNodeTypes.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];
}
const browserGlobals = new Set(Object.keys(globals.browser));
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 isBrowserGlobal = browserGlobals.has(objectName);
const objectNameLower = objectName.toLowerCase();
const failingRule = rules.find((rule) => {
// Match case-insensitively IF the objectName was case-sentively found in browserGlobals
const objectNameMatches = isBrowserGlobal
? rule.object.toLowerCase() === objectNameLower
: rule.object === objectName;
return (
objectNameMatches &&
(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
)
);
}