Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame^] | 1 | /** |
| 2 | * @fileoverview Rule for disallowing require() outside of the top-level module context |
| 3 | * @author Jamund Ferguson |
| 4 | */ |
| 5 | |
| 6 | "use strict"; |
| 7 | |
| 8 | const ACCEPTABLE_PARENTS = [ |
| 9 | "AssignmentExpression", |
| 10 | "VariableDeclarator", |
| 11 | "MemberExpression", |
| 12 | "ExpressionStatement", |
| 13 | "CallExpression", |
| 14 | "ConditionalExpression", |
| 15 | "Program", |
| 16 | "VariableDeclaration" |
| 17 | ]; |
| 18 | |
| 19 | /** |
| 20 | * Finds the eslint-scope reference in the given scope. |
| 21 | * @param {Object} scope The scope to search. |
| 22 | * @param {ASTNode} node The identifier node. |
| 23 | * @returns {Reference|null} Returns the found reference or null if none were found. |
| 24 | */ |
| 25 | function findReference(scope, node) { |
| 26 | const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] && |
| 27 | reference.identifier.range[1] === node.range[1]); |
| 28 | |
| 29 | /* istanbul ignore else: correctly returns null */ |
| 30 | if (references.length === 1) { |
| 31 | return references[0]; |
| 32 | } |
| 33 | return null; |
| 34 | |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * Checks if the given identifier node is shadowed in the given scope. |
| 39 | * @param {Object} scope The current scope. |
| 40 | * @param {ASTNode} node The identifier node to check. |
| 41 | * @returns {boolean} Whether or not the name is shadowed. |
| 42 | */ |
| 43 | function isShadowed(scope, node) { |
| 44 | const reference = findReference(scope, node); |
| 45 | |
| 46 | return reference && reference.resolved && reference.resolved.defs.length > 0; |
| 47 | } |
| 48 | |
| 49 | module.exports = { |
| 50 | meta: { |
| 51 | type: "suggestion", |
| 52 | |
| 53 | docs: { |
| 54 | description: "require `require()` calls to be placed at top-level module scope", |
| 55 | category: "Node.js and CommonJS", |
| 56 | recommended: false, |
| 57 | url: "https://eslint.org/docs/rules/global-require" |
| 58 | }, |
| 59 | |
| 60 | schema: [], |
| 61 | messages: { |
| 62 | unexpected: "Unexpected require()." |
| 63 | } |
| 64 | }, |
| 65 | |
| 66 | create(context) { |
| 67 | return { |
| 68 | CallExpression(node) { |
| 69 | const currentScope = context.getScope(); |
| 70 | |
| 71 | if (node.callee.name === "require" && !isShadowed(currentScope, node.callee)) { |
| 72 | const isGoodRequire = context.getAncestors().every(parent => ACCEPTABLE_PARENTS.indexOf(parent.type) > -1); |
| 73 | |
| 74 | if (!isGoodRequire) { |
| 75 | context.report({ node, messageId: "unexpected" }); |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | }; |
| 80 | } |
| 81 | }; |