UNPKG

1.27 kBJavaScriptView Raw
1"use strict";
2
3module.exports = removeUseStrict;
4const newIssueUrl = "https://github.com/babel/minify/issues/new";
5const useStrict = "use strict";
6/**
7 * Remove redundant use strict
8 * If the parent has a "use strict" directive, it is not required in
9 * the children
10 *
11 * @param {NodePath} block BlockStatement
12 */
13
14function removeUseStrict(block) {
15 if (!block.isBlockStatement()) {
16 throw new Error(`Received ${block.type}. Expected BlockStatement. ` + `Please report at ${newIssueUrl}`);
17 }
18
19 const useStricts = getUseStrictDirectives(block); // early exit
20
21 if (useStricts.length < 1) return; // only keep the first use strict
22
23 if (useStricts.length > 1) {
24 for (let i = 1; i < useStricts.length; i++) {
25 useStricts[i].remove();
26 }
27 } // check if parent has an use strict
28
29
30 if (hasStrictParent(block)) {
31 useStricts[0].remove();
32 }
33}
34
35function hasStrictParent(path) {
36 return path.findParent(parent => parent.isBlockStatement() && isStrict(parent));
37}
38
39function isStrict(block) {
40 return getUseStrictDirectives(block).length > 0;
41}
42
43function getUseStrictDirectives(block) {
44 var dir = block.get("directives");
45 return Array.isArray(dir) ? dir.filter(function (directive) {
46 return directive.node.value.value === useStrict;
47 }) : [];
48}
\No newline at end of file