no-restricted-exports.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * @fileoverview Rule to disallow specified names in exports
  3. * @author Milos Djermanovic
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. type: "suggestion",
  12. docs: {
  13. description: "disallow specified names in exports",
  14. category: "ECMAScript 6",
  15. recommended: false,
  16. url: "https://eslint.org/docs/rules/no-restricted-exports"
  17. },
  18. schema: [{
  19. type: "object",
  20. properties: {
  21. restrictedNamedExports: {
  22. type: "array",
  23. items: {
  24. type: "string"
  25. },
  26. uniqueItems: true
  27. }
  28. },
  29. additionalProperties: false
  30. }],
  31. messages: {
  32. restrictedNamed: "'{{name}}' is restricted from being used as an exported name."
  33. }
  34. },
  35. create(context) {
  36. const restrictedNames = new Set(context.options[0] && context.options[0].restrictedNamedExports);
  37. /**
  38. * Checks and reports given exported identifier.
  39. * @param {ASTNode} node exported `Identifier` node to check.
  40. * @returns {void}
  41. */
  42. function checkExportedName(node) {
  43. const name = node.name;
  44. if (restrictedNames.has(name)) {
  45. context.report({
  46. node,
  47. messageId: "restrictedNamed",
  48. data: { name }
  49. });
  50. }
  51. }
  52. return {
  53. ExportAllDeclaration(node) {
  54. if (node.exported) {
  55. checkExportedName(node.exported);
  56. }
  57. },
  58. ExportNamedDeclaration(node) {
  59. const declaration = node.declaration;
  60. if (declaration) {
  61. if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") {
  62. checkExportedName(declaration.id);
  63. } else if (declaration.type === "VariableDeclaration") {
  64. context.getDeclaredVariables(declaration)
  65. .map(v => v.defs.find(d => d.parent === declaration))
  66. .map(d => d.name) // Identifier nodes
  67. .forEach(checkExportedName);
  68. }
  69. } else {
  70. node.specifiers
  71. .map(s => s.exported)
  72. .forEach(checkExportedName);
  73. }
  74. }
  75. };
  76. }
  77. };