1 | "use strict";
|
2 |
|
3 | module.exports = function (_ref) {
|
4 | var t = _ref.types;
|
5 | return {
|
6 | name: "transform-remove-console",
|
7 | visitor: {
|
8 | CallExpression(path, state) {
|
9 | var callee = path.get("callee");
|
10 | if (!callee.isMemberExpression()) return;
|
11 |
|
12 | if (isIncludedConsole(callee, state.opts.exclude)) {
|
13 |
|
14 | if (path.parentPath.isExpressionStatement()) {
|
15 | path.remove();
|
16 | } else {
|
17 | path.replaceWith(createVoid0());
|
18 | }
|
19 | } else if (isIncludedConsoleBind(callee, state.opts.exclude)) {
|
20 |
|
21 | path.replaceWith(createNoop());
|
22 | }
|
23 | },
|
24 |
|
25 | MemberExpression: {
|
26 | exit(path, state) {
|
27 | if (isIncludedConsole(path, state.opts.exclude) && !path.parentPath.isMemberExpression()) {
|
28 | if (path.parentPath.isAssignmentExpression() && path.parentKey === "left") {
|
29 | path.parentPath.get("right").replaceWith(createNoop());
|
30 | } else {
|
31 | path.replaceWith(createNoop());
|
32 | }
|
33 | }
|
34 | }
|
35 |
|
36 | }
|
37 | }
|
38 | };
|
39 |
|
40 | function isGlobalConsoleId(id) {
|
41 | var name = "console";
|
42 | return id.isIdentifier({
|
43 | name
|
44 | }) && !id.scope.getBinding(name) && id.scope.hasGlobal(name);
|
45 | }
|
46 |
|
47 | function isExcluded(property, excludeArray) {
|
48 | return excludeArray && excludeArray.some(function (name) {
|
49 | return property.isIdentifier({
|
50 | name
|
51 | });
|
52 | });
|
53 | }
|
54 |
|
55 | function isIncludedConsole(memberExpr, excludeArray) {
|
56 | var object = memberExpr.get("object");
|
57 | var property = memberExpr.get("property");
|
58 | if (isExcluded(property, excludeArray)) return false;
|
59 | if (isGlobalConsoleId(object)) return true;
|
60 | return isGlobalConsoleId(object.get("object")) && (property.isIdentifier({
|
61 | name: "call"
|
62 | }) || property.isIdentifier({
|
63 | name: "apply"
|
64 | }));
|
65 | }
|
66 |
|
67 | function isIncludedConsoleBind(memberExpr, excludeArray) {
|
68 | var object = memberExpr.get("object");
|
69 | if (!object.isMemberExpression()) return false;
|
70 | if (isExcluded(object.get("property"), excludeArray)) return false;
|
71 | return isGlobalConsoleId(object.get("object")) && memberExpr.get("property").isIdentifier({
|
72 | name: "bind"
|
73 | });
|
74 | }
|
75 |
|
76 | function createNoop() {
|
77 | return t.functionExpression(null, [], t.blockStatement([]));
|
78 | }
|
79 |
|
80 | function createVoid0() {
|
81 | return t.unaryExpression("void", t.numericLiteral(0));
|
82 | }
|
83 | }; |
\ | No newline at end of file |