]>
git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/global-require.js
2 * @fileoverview Rule for disallowing require() outside of the top-level module context
3 * @author Jamund Ferguson
8 const ACCEPTABLE_PARENTS
= [
9 "AssignmentExpression",
12 "ExpressionStatement",
14 "ConditionalExpression",
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.
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]);
29 /* istanbul ignore else: correctly returns null */
30 if (references
.length
=== 1) {
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.
43 function isShadowed(scope
, node
) {
44 const reference
= findReference(scope
, node
);
46 return reference
&& reference
.resolved
&& reference
.resolved
.defs
.length
> 0;
54 description
: "require `require()` calls to be placed at top-level module scope",
55 category
: "Node.js and CommonJS",
57 url
: "https://eslint.org/docs/rules/global-require"
62 unexpected
: "Unexpected require()."
68 CallExpression(node
) {
69 const currentScope
= context
.getScope();
71 if (node
.callee
.name
=== "require" && !isShadowed(currentScope
, node
.callee
)) {
72 const isGoodRequire
= context
.getAncestors().every(parent
=> ACCEPTABLE_PARENTS
.indexOf(parent
.type
) > -1);
75 context
.report({ node
, messageId
: "unexpected" });