/
runCodeForEnvVar.macro.ts
42 lines (38 loc) · 1.21 KB
/
runCodeForEnvVar.macro.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { MacroParams, createMacro, MacroError } from "babel-plugin-macros";
import * as t from "@babel/types";
function macro({ references }: MacroParams) {
const { default: runCodeForEnvVar } = references;
runCodeForEnvVar.forEach((path) => {
const call = path.parent;
if (t.isCallExpression(call)) {
const [firstArg, secondArg] = call.arguments;
if (!t.isStringLiteral(firstArg)) {
throw new MacroError(
"1st argument of runCodeForEnvVar() must be a string literal"
);
}
if (
!(
t.isArrowFunctionExpression(secondArg) ||
t.isFunctionExpression(secondArg)
)
) {
throw new MacroError(
"2nd argument of runCodeForEnvVar() must be a function expression."
);
}
// now check if the env var matches
const isValid = process.env[firstArg.value] === "true";
if (isValid) {
path.parentPath?.replaceWith(t.callExpression(secondArg, []));
} else {
path.parentPath?.remove();
}
} else {
throw new MacroError(
"runCodeForEnvVar should be called as runCodeForEnvVar(envVarName, function)"
);
}
});
}
export default createMacro(macro);