no-empty-file.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. const {isEmptyNode} = require('./ast/index.js');
  3. const MESSAGE_ID = 'no-empty-file';
  4. const messages = {
  5. [MESSAGE_ID]: 'Empty files are not allowed.',
  6. };
  7. const isDirective = node => node.type === 'ExpressionStatement' && 'directive' in node;
  8. const isEmpty = node => isEmptyNode(node, isDirective);
  9. const isTripleSlashDirective = node =>
  10. node.type === 'Line' && node.value.startsWith('/');
  11. const hasTripeSlashDirectives = comments =>
  12. comments.some(currentNode => isTripleSlashDirective(currentNode));
  13. /** @param {import('eslint').Rule.RuleContext} context */
  14. const create = context => {
  15. const filename = context.getPhysicalFilename().toLowerCase();
  16. if (!/\.(?:js|mjs|cjs|ts|mts|cts)$/.test(filename)) {
  17. return;
  18. }
  19. return {
  20. Program(node) {
  21. if (node.body.some(node => !isEmpty(node))) {
  22. return;
  23. }
  24. const sourceCode = context.getSourceCode();
  25. const comments = sourceCode.getAllComments();
  26. if (hasTripeSlashDirectives(comments)) {
  27. return;
  28. }
  29. return {
  30. node,
  31. messageId: MESSAGE_ID,
  32. };
  33. },
  34. };
  35. };
  36. /** @type {import('eslint').Rule.RuleModule} */
  37. module.exports = {
  38. create,
  39. meta: {
  40. type: 'suggestion',
  41. docs: {
  42. description: 'Disallow empty files.',
  43. },
  44. messages,
  45. },
  46. };