main
js 86 lines 2.01 KB
Raw
1 /**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @emails react-core
8 */
9
10 'use strict';
11
12 module.exports = {
13 meta: {
14 fixable: 'code',
15 schema: [],
16 },
17 create: function (context) {
18 function isInDEVBlock(node) {
19 let done = false;
20 while (!done) {
21 let parent = node.parent;
22 if (!parent) {
23 return false;
24 }
25 if (
26 parent.type === 'IfStatement' &&
27 node === parent.consequent &&
28 parent.test.type === 'Identifier' &&
29 // This is intentionally strict so we can
30 // see blocks of DEV-only code at once.
31 parent.test.name === '__DEV__'
32 ) {
33 return true;
34 }
35 node = parent;
36 }
37 }
38
39 function reportWrapInDEV(node) {
40 context.report({
41 node: node,
42 message: `Wrap console.{{identifier}}() in an "if (__DEV__) {}" check`,
43 data: {
44 identifier: node.property.name,
45 },
46 fix: function (fixer) {
47 return [
48 fixer.insertTextBefore(node.parent, `if (__DEV__) {`),
49 fixer.insertTextAfter(node.parent, '}'),
50 ];
51 },
52 });
53 }
54
55 function reportUnexpectedConsole(node) {
56 context.report({
57 node: node,
58 message: `Unexpected use of console`,
59 });
60 }
61
62 return {
63 MemberExpression: function (node) {
64 if (
65 node.object.type === 'Identifier' &&
66 node.object.name === 'console' &&
67 node.property.type === 'Identifier'
68 ) {
69 switch (node.property.name) {
70 case 'error':
71 case 'warn': {
72 if (!isInDEVBlock(node)) {
73 reportWrapInDEV(node);
74 }
75 break;
76 }
77 default: {
78 reportUnexpectedConsole(node);
79 break;
80 }
81 }
82 }
83 },
84 };
85 },
86 };