no-new-func.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * @fileoverview Rule to flag when using new Function
  3. * @author Ilya Volodin
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. type: "suggestion",
  12. docs: {
  13. description: "disallow `new` operators with the `Function` object",
  14. category: "Best Practices",
  15. recommended: false,
  16. url: "https://eslint.org/docs/rules/no-new-func"
  17. },
  18. schema: [],
  19. messages: {
  20. noFunctionConstructor: "The Function constructor is eval."
  21. }
  22. },
  23. create(context) {
  24. return {
  25. "Program:exit"() {
  26. const globalScope = context.getScope();
  27. const variable = globalScope.set.get("Function");
  28. if (variable && variable.defs.length === 0) {
  29. variable.references.forEach(ref => {
  30. const node = ref.identifier;
  31. const { parent } = node;
  32. if (
  33. parent &&
  34. (parent.type === "NewExpression" || parent.type === "CallExpression") &&
  35. node === parent.callee
  36. ) {
  37. context.report({
  38. node: parent,
  39. messageId: "noFunctionConstructor"
  40. });
  41. }
  42. });
  43. }
  44. }
  45. };
  46. }
  47. };