1 | /**
|
2 | * @fileoverview Rule to flag references to undeclared variables.
|
3 | * @author Mark Macdonald
|
4 | */
|
5 | ;
|
6 |
|
7 | //------------------------------------------------------------------------------
|
8 | // Helpers
|
9 | //------------------------------------------------------------------------------
|
10 |
|
11 | /**
|
12 | * Checks if the given node is the argument of a typeof operator.
|
13 | * @param {ASTNode} node The AST node being checked.
|
14 | * @returns {boolean} Whether or not the node is the argument of a typeof operator.
|
15 | */
|
16 | function hasTypeOfOperator(node) {
|
17 | const parent = node.parent;
|
18 |
|
19 | return parent.type === "UnaryExpression" && parent.operator === "typeof";
|
20 | }
|
21 |
|
22 | //------------------------------------------------------------------------------
|
23 | // Rule Definition
|
24 | //------------------------------------------------------------------------------
|
25 |
|
26 | module.exports = {
|
27 | meta: {
|
28 | docs: {
|
29 | description: "disallow the use of undeclared variables unless mentioned in `/*global */` comments",
|
30 | category: "Variables",
|
31 | recommended: true,
|
32 | url: "https://eslint.org/docs/rules/no-undef"
|
33 | },
|
34 |
|
35 | schema: [
|
36 | {
|
37 | type: "object",
|
38 | properties: {
|
39 | typeof: {
|
40 | type: "boolean"
|
41 | }
|
42 | },
|
43 | additionalProperties: false
|
44 | }
|
45 | ]
|
46 | },
|
47 |
|
48 | create(context) {
|
49 | const options = context.options[0];
|
50 | const considerTypeOf = options && options.typeof === true || false;
|
51 |
|
52 | return {
|
53 | "Program:exit"(/* node */) {
|
54 | const globalScope = context.getScope();
|
55 |
|
56 | globalScope.through.forEach(ref => {
|
57 | const identifier = ref.identifier;
|
58 |
|
59 | if (!considerTypeOf && hasTypeOfOperator(identifier)) {
|
60 | return;
|
61 | }
|
62 |
|
63 | context.report({
|
64 | node: identifier,
|
65 | message: "'{{name}}' is not defined.",
|
66 | data: identifier
|
67 | });
|
68 | });
|
69 | }
|
70 | };
|
71 | }
|
72 | };
|