123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138 |
-
-
- "use strict";
-
-
-
-
-
- const astUtils = require("../util/ast-utils");
-
-
-
-
-
- module.exports = {
- meta: {
- type: "suggestion",
-
- docs: {
- description: "disallow the use of `console`",
- category: "Possible Errors",
- recommended: true,
- url: "https://eslint.org/docs/rules/no-console"
- },
-
- schema: [
- {
- type: "object",
- properties: {
- allow: {
- type: "array",
- items: {
- type: "string"
- },
- minItems: 1,
- uniqueItems: true
- }
- },
- additionalProperties: false
- }
- ],
-
- messages: {
- unexpected: "Unexpected console statement."
- }
- },
-
- create(context) {
- const options = context.options[0] || {};
- const allowed = options.allow || [];
-
-
-
- function isConsole(reference) {
- const id = reference.identifier;
-
- return id && id.name === "console";
- }
-
-
-
- function isAllowed(node) {
- const propertyName = astUtils.getStaticPropertyName(node);
-
- return propertyName && allowed.indexOf(propertyName) !== -1;
- }
-
-
-
- function isMemberAccessExceptAllowed(reference) {
- const node = reference.identifier;
- const parent = node.parent;
-
- return (
- parent.type === "MemberExpression" &&
- parent.object === node &&
- !isAllowed(parent)
- );
- }
-
-
-
- function report(reference) {
- const node = reference.identifier.parent;
-
- context.report({
- node,
- loc: node.loc,
- messageId: "unexpected"
- });
- }
-
- return {
- "Program:exit"() {
- const scope = context.getScope();
- const consoleVar = astUtils.getVariableByName(scope, "console");
- const shadowed = consoleVar && consoleVar.defs.length > 0;
-
-
-
- const references = consoleVar
- ? consoleVar.references
- : scope.through.filter(isConsole);
-
- if (!shadowed) {
- references
- .filter(isMemberAccessExceptAllowed)
- .forEach(report);
- }
- }
- };
- }
- };
|