no-mixed-requires.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. /**
  2. * @fileoverview Rule to enforce grouped require statements for Node.JS
  3. * @author Raphael Pigulla
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. type: "suggestion",
  12. docs: {
  13. description: "disallow `require` calls to be mixed with regular variable declarations",
  14. category: "Node.js and CommonJS",
  15. recommended: false,
  16. url: "https://eslint.org/docs/rules/no-mixed-requires"
  17. },
  18. schema: [
  19. {
  20. oneOf: [
  21. {
  22. type: "boolean"
  23. },
  24. {
  25. type: "object",
  26. properties: {
  27. grouping: {
  28. type: "boolean"
  29. },
  30. allowCall: {
  31. type: "boolean"
  32. }
  33. },
  34. additionalProperties: false
  35. }
  36. ]
  37. }
  38. ]
  39. },
  40. create(context) {
  41. const options = context.options[0];
  42. let grouping = false,
  43. allowCall = false;
  44. if (typeof options === "object") {
  45. grouping = options.grouping;
  46. allowCall = options.allowCall;
  47. } else {
  48. grouping = !!options;
  49. }
  50. /**
  51. * Returns the list of built-in modules.
  52. * @returns {string[]} An array of built-in Node.js modules.
  53. */
  54. function getBuiltinModules() {
  55. /*
  56. * This list is generated using:
  57. * `require("repl")._builtinLibs.concat('repl').sort()`
  58. * This particular list is as per nodejs v0.12.2 and iojs v0.7.1
  59. */
  60. return [
  61. "assert", "buffer", "child_process", "cluster", "crypto",
  62. "dgram", "dns", "domain", "events", "fs", "http", "https",
  63. "net", "os", "path", "punycode", "querystring", "readline",
  64. "repl", "smalloc", "stream", "string_decoder", "tls", "tty",
  65. "url", "util", "v8", "vm", "zlib"
  66. ];
  67. }
  68. const BUILTIN_MODULES = getBuiltinModules();
  69. const DECL_REQUIRE = "require",
  70. DECL_UNINITIALIZED = "uninitialized",
  71. DECL_OTHER = "other";
  72. const REQ_CORE = "core",
  73. REQ_FILE = "file",
  74. REQ_MODULE = "module",
  75. REQ_COMPUTED = "computed";
  76. /**
  77. * Determines the type of a declaration statement.
  78. * @param {ASTNode} initExpression The init node of the VariableDeclarator.
  79. * @returns {string} The type of declaration represented by the expression.
  80. */
  81. function getDeclarationType(initExpression) {
  82. if (!initExpression) {
  83. // "var x;"
  84. return DECL_UNINITIALIZED;
  85. }
  86. if (initExpression.type === "CallExpression" &&
  87. initExpression.callee.type === "Identifier" &&
  88. initExpression.callee.name === "require"
  89. ) {
  90. // "var x = require('util');"
  91. return DECL_REQUIRE;
  92. }
  93. if (allowCall &&
  94. initExpression.type === "CallExpression" &&
  95. initExpression.callee.type === "CallExpression"
  96. ) {
  97. // "var x = require('diagnose')('sub-module');"
  98. return getDeclarationType(initExpression.callee);
  99. }
  100. if (initExpression.type === "MemberExpression") {
  101. // "var x = require('glob').Glob;"
  102. return getDeclarationType(initExpression.object);
  103. }
  104. // "var x = 42;"
  105. return DECL_OTHER;
  106. }
  107. /**
  108. * Determines the type of module that is loaded via require.
  109. * @param {ASTNode} initExpression The init node of the VariableDeclarator.
  110. * @returns {string} The module type.
  111. */
  112. function inferModuleType(initExpression) {
  113. if (initExpression.type === "MemberExpression") {
  114. // "var x = require('glob').Glob;"
  115. return inferModuleType(initExpression.object);
  116. }
  117. if (initExpression.arguments.length === 0) {
  118. // "var x = require();"
  119. return REQ_COMPUTED;
  120. }
  121. const arg = initExpression.arguments[0];
  122. if (arg.type !== "Literal" || typeof arg.value !== "string") {
  123. // "var x = require(42);"
  124. return REQ_COMPUTED;
  125. }
  126. if (BUILTIN_MODULES.indexOf(arg.value) !== -1) {
  127. // "var fs = require('fs');"
  128. return REQ_CORE;
  129. }
  130. if (/^\.{0,2}\//u.test(arg.value)) {
  131. // "var utils = require('./utils');"
  132. return REQ_FILE;
  133. }
  134. // "var async = require('async');"
  135. return REQ_MODULE;
  136. }
  137. /**
  138. * Check if the list of variable declarations is mixed, i.e. whether it
  139. * contains both require and other declarations.
  140. * @param {ASTNode} declarations The list of VariableDeclarators.
  141. * @returns {boolean} True if the declarations are mixed, false if not.
  142. */
  143. function isMixed(declarations) {
  144. const contains = {};
  145. declarations.forEach(declaration => {
  146. const type = getDeclarationType(declaration.init);
  147. contains[type] = true;
  148. });
  149. return !!(
  150. contains[DECL_REQUIRE] &&
  151. (contains[DECL_UNINITIALIZED] || contains[DECL_OTHER])
  152. );
  153. }
  154. /**
  155. * Check if all require declarations in the given list are of the same
  156. * type.
  157. * @param {ASTNode} declarations The list of VariableDeclarators.
  158. * @returns {boolean} True if the declarations are grouped, false if not.
  159. */
  160. function isGrouped(declarations) {
  161. const found = {};
  162. declarations.forEach(declaration => {
  163. if (getDeclarationType(declaration.init) === DECL_REQUIRE) {
  164. found[inferModuleType(declaration.init)] = true;
  165. }
  166. });
  167. return Object.keys(found).length <= 1;
  168. }
  169. return {
  170. VariableDeclaration(node) {
  171. if (isMixed(node.declarations)) {
  172. context.report({ node, message: "Do not mix 'require' and other declarations." });
  173. } else if (grouping && !isGrouped(node.declarations)) {
  174. context.report({ node, message: "Do not mix core, module, file and computed requires." });
  175. }
  176. }
  177. };
  178. }
  179. };