import-style.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. 'use strict';
  2. const {defaultsDeep} = require('lodash');
  3. const {getStringIfConstant} = require('@eslint-community/eslint-utils');
  4. const {callExpressionSelector} = require('./selectors/index.js');
  5. const MESSAGE_ID = 'importStyle';
  6. const messages = {
  7. [MESSAGE_ID]: 'Use {{allowedStyles}} import for module `{{moduleName}}`.',
  8. };
  9. const getActualImportDeclarationStyles = importDeclaration => {
  10. const {specifiers} = importDeclaration;
  11. if (specifiers.length === 0) {
  12. return ['unassigned'];
  13. }
  14. const styles = new Set();
  15. for (const specifier of specifiers) {
  16. if (specifier.type === 'ImportDefaultSpecifier') {
  17. styles.add('default');
  18. continue;
  19. }
  20. if (specifier.type === 'ImportNamespaceSpecifier') {
  21. styles.add('namespace');
  22. continue;
  23. }
  24. if (specifier.type === 'ImportSpecifier') {
  25. if (specifier.imported.type === 'Identifier' && specifier.imported.name === 'default') {
  26. styles.add('default');
  27. continue;
  28. }
  29. styles.add('named');
  30. continue;
  31. }
  32. }
  33. return [...styles];
  34. };
  35. const getActualExportDeclarationStyles = exportDeclaration => {
  36. const {specifiers} = exportDeclaration;
  37. if (specifiers.length === 0) {
  38. return ['unassigned'];
  39. }
  40. const styles = new Set();
  41. for (const specifier of specifiers) {
  42. if (specifier.type === 'ExportSpecifier') {
  43. if (specifier.exported.type === 'Identifier' && specifier.exported.name === 'default') {
  44. styles.add('default');
  45. continue;
  46. }
  47. styles.add('named');
  48. continue;
  49. }
  50. }
  51. return [...styles];
  52. };
  53. const getActualAssignmentTargetImportStyles = assignmentTarget => {
  54. if (assignmentTarget.type === 'Identifier' || assignmentTarget.type === 'ArrayPattern') {
  55. return ['namespace'];
  56. }
  57. if (assignmentTarget.type === 'ObjectPattern') {
  58. if (assignmentTarget.properties.length === 0) {
  59. return ['unassigned'];
  60. }
  61. const styles = new Set();
  62. for (const property of assignmentTarget.properties) {
  63. if (property.type === 'RestElement') {
  64. styles.add('named');
  65. continue;
  66. }
  67. if (property.key.type === 'Identifier') {
  68. if (property.key.name === 'default') {
  69. styles.add('default');
  70. } else {
  71. styles.add('named');
  72. }
  73. }
  74. }
  75. return [...styles];
  76. }
  77. // Next line is not test-coverable until unforceable changes to the language
  78. // like an addition of new AST node types usable in `const __HERE__ = foo;`.
  79. // An exotic custom parser or a bug in one could cover it too.
  80. /* c8 ignore next */
  81. return [];
  82. };
  83. const joinOr = words => words
  84. .map((word, index) => {
  85. if (index === words.length - 1) {
  86. return word;
  87. }
  88. if (index === words.length - 2) {
  89. return word + ' or';
  90. }
  91. return word + ',';
  92. })
  93. .join(' ');
  94. // Keep this alphabetically sorted for easier maintenance
  95. const defaultStyles = {
  96. chalk: {
  97. default: true,
  98. },
  99. path: {
  100. default: true,
  101. },
  102. util: {
  103. named: true,
  104. },
  105. };
  106. const assignedDynamicImportSelector = [
  107. 'VariableDeclarator',
  108. '[init.type="AwaitExpression"]',
  109. '[init.argument.type="ImportExpression"]',
  110. ].join('');
  111. const assignedRequireSelector = [
  112. 'VariableDeclarator',
  113. '[init.type="CallExpression"]',
  114. '[init.callee.type="Identifier"]',
  115. '[init.callee.name="require"]',
  116. ].join('');
  117. /** @param {import('eslint').Rule.RuleContext} context */
  118. const create = context => {
  119. let [
  120. {
  121. styles = {},
  122. extendDefaultStyles = true,
  123. checkImport = true,
  124. checkDynamicImport = true,
  125. checkExportFrom = false,
  126. checkRequire = true,
  127. } = {},
  128. ] = context.options;
  129. styles = extendDefaultStyles
  130. ? defaultsDeep({}, styles, defaultStyles)
  131. : styles;
  132. styles = new Map(
  133. Object.entries(styles).map(
  134. ([moduleName, styles]) =>
  135. [moduleName, new Set(Object.entries(styles).filter(([, isAllowed]) => isAllowed).map(([style]) => style))],
  136. ),
  137. );
  138. const report = (node, moduleName, actualImportStyles, allowedImportStyles, isRequire = false) => {
  139. if (!allowedImportStyles || allowedImportStyles.size === 0) {
  140. return;
  141. }
  142. let effectiveAllowedImportStyles = allowedImportStyles;
  143. // For `require`, `'default'` style allows both `x = require('x')` (`'namespace'` style) and
  144. // `{default: x} = require('x')` (`'default'` style) since we don't know in advance
  145. // whether `'x'` is a compiled ES6 module (with `default` key) or a CommonJS module and `require`
  146. // does not provide any automatic interop for this, so the user may have to use either of these.
  147. if (isRequire && allowedImportStyles.has('default') && !allowedImportStyles.has('namespace')) {
  148. effectiveAllowedImportStyles = new Set(allowedImportStyles);
  149. effectiveAllowedImportStyles.add('namespace');
  150. }
  151. if (actualImportStyles.every(style => effectiveAllowedImportStyles.has(style))) {
  152. return;
  153. }
  154. const data = {
  155. allowedStyles: joinOr([...allowedImportStyles.keys()]),
  156. moduleName,
  157. };
  158. context.report({
  159. node,
  160. messageId: MESSAGE_ID,
  161. data,
  162. });
  163. };
  164. let visitor = {};
  165. if (checkImport) {
  166. visitor = {
  167. ...visitor,
  168. ImportDeclaration(node) {
  169. const moduleName = getStringIfConstant(node.source, context.getScope());
  170. const allowedImportStyles = styles.get(moduleName);
  171. const actualImportStyles = getActualImportDeclarationStyles(node);
  172. report(node, moduleName, actualImportStyles, allowedImportStyles);
  173. },
  174. };
  175. }
  176. if (checkDynamicImport) {
  177. visitor = {
  178. ...visitor,
  179. 'ExpressionStatement > ImportExpression'(node) {
  180. const moduleName = getStringIfConstant(node.source, context.getScope());
  181. const allowedImportStyles = styles.get(moduleName);
  182. const actualImportStyles = ['unassigned'];
  183. report(node, moduleName, actualImportStyles, allowedImportStyles);
  184. },
  185. [assignedDynamicImportSelector](node) {
  186. const assignmentTargetNode = node.id;
  187. const moduleNameNode = node.init.argument.source;
  188. const moduleName = getStringIfConstant(moduleNameNode, context.getScope());
  189. if (!moduleName) {
  190. return;
  191. }
  192. const allowedImportStyles = styles.get(moduleName);
  193. const actualImportStyles = getActualAssignmentTargetImportStyles(assignmentTargetNode);
  194. report(node, moduleName, actualImportStyles, allowedImportStyles);
  195. },
  196. };
  197. }
  198. if (checkExportFrom) {
  199. visitor = {
  200. ...visitor,
  201. ExportAllDeclaration(node) {
  202. const moduleName = getStringIfConstant(node.source, context.getScope());
  203. const allowedImportStyles = styles.get(moduleName);
  204. const actualImportStyles = ['namespace'];
  205. report(node, moduleName, actualImportStyles, allowedImportStyles);
  206. },
  207. ExportNamedDeclaration(node) {
  208. const moduleName = getStringIfConstant(node.source, context.getScope());
  209. const allowedImportStyles = styles.get(moduleName);
  210. const actualImportStyles = getActualExportDeclarationStyles(node);
  211. report(node, moduleName, actualImportStyles, allowedImportStyles);
  212. },
  213. };
  214. }
  215. if (checkRequire) {
  216. visitor = {
  217. ...visitor,
  218. [`ExpressionStatement > ${callExpressionSelector({name: 'require', argumentsLength: 1})}.expression`](node) {
  219. const moduleName = getStringIfConstant(node.arguments[0], context.getScope());
  220. const allowedImportStyles = styles.get(moduleName);
  221. const actualImportStyles = ['unassigned'];
  222. report(node, moduleName, actualImportStyles, allowedImportStyles, true);
  223. },
  224. [assignedRequireSelector](node) {
  225. const assignmentTargetNode = node.id;
  226. const moduleNameNode = node.init.arguments[0];
  227. const moduleName = getStringIfConstant(moduleNameNode, context.getScope());
  228. if (!moduleName) {
  229. return;
  230. }
  231. const allowedImportStyles = styles.get(moduleName);
  232. const actualImportStyles = getActualAssignmentTargetImportStyles(assignmentTargetNode);
  233. report(node, moduleName, actualImportStyles, allowedImportStyles, true);
  234. },
  235. };
  236. }
  237. return visitor;
  238. };
  239. const schema = {
  240. type: 'array',
  241. additionalItems: false,
  242. items: [
  243. {
  244. type: 'object',
  245. additionalProperties: false,
  246. properties: {
  247. checkImport: {
  248. type: 'boolean',
  249. },
  250. checkDynamicImport: {
  251. type: 'boolean',
  252. },
  253. checkExportFrom: {
  254. type: 'boolean',
  255. },
  256. checkRequire: {
  257. type: 'boolean',
  258. },
  259. extendDefaultStyles: {
  260. type: 'boolean',
  261. },
  262. styles: {
  263. $ref: '#/definitions/moduleStyles',
  264. },
  265. },
  266. },
  267. ],
  268. definitions: {
  269. moduleStyles: {
  270. type: 'object',
  271. additionalProperties: {
  272. $ref: '#/definitions/styles',
  273. },
  274. },
  275. styles: {
  276. anyOf: [
  277. {
  278. enum: [
  279. false,
  280. ],
  281. },
  282. {
  283. $ref: '#/definitions/booleanObject',
  284. },
  285. ],
  286. },
  287. booleanObject: {
  288. type: 'object',
  289. additionalProperties: {
  290. type: 'boolean',
  291. },
  292. },
  293. },
  294. };
  295. /** @type {import('eslint').Rule.RuleModule} */
  296. module.exports = {
  297. create,
  298. meta: {
  299. type: 'problem',
  300. docs: {
  301. description: 'Enforce specific import styles per module.',
  302. },
  303. schema,
  304. messages,
  305. },
  306. };