fix(vite): improve commonjs handling (#3336)
Fixes https://github.com/denoland/fresh/issues/3323
This commit is contained in:
@@ -7,6 +7,7 @@ import { inlineEnvVarsPlugin } from "./patches/inline_env_vars.ts";
|
||||
import { removePolyfills } from "./patches/remove_polyfills.ts";
|
||||
import { JS_REG, JSX_REG } from "../utils.ts";
|
||||
import { denoGlobal } from "./patches/deno_global.ts";
|
||||
import { codeEvalPlugin } from "./patches/code_eval.ts";
|
||||
|
||||
export function patches(): Plugin {
|
||||
let isDev = false;
|
||||
@@ -33,13 +34,14 @@ export function patches(): Plugin {
|
||||
}]);
|
||||
}
|
||||
|
||||
const env = isDev ? "development" : "production";
|
||||
|
||||
const plugins: babel.PluginItem[] = [
|
||||
codeEvalPlugin(options?.ssr ? "ssr" : "client", env),
|
||||
cjsPlugin,
|
||||
removePolyfills,
|
||||
jsxComments,
|
||||
inlineEnvVarsPlugin(
|
||||
isDev ? "development" : "production",
|
||||
),
|
||||
inlineEnvVarsPlugin(env, Deno.env.toObject()),
|
||||
];
|
||||
|
||||
if (!options?.ssr) {
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
import type { PluginObj, PluginPass, types } from "@babel/core";
|
||||
|
||||
const APPLY_PG_QUIRKS = "applyPgQuirks";
|
||||
|
||||
export function codeEvalPlugin(
|
||||
env: "ssr" | "client",
|
||||
mode: string,
|
||||
) {
|
||||
return (
|
||||
{ types: t }: { types: typeof types },
|
||||
): PluginObj => {
|
||||
return {
|
||||
name: "fresh-remove-polyfills",
|
||||
visitor: {
|
||||
IfStatement: {
|
||||
enter(path, state) {
|
||||
const res = evaluateExpr(t, env, mode, path.node.test, state);
|
||||
// Could not evaluate
|
||||
if (res === null) return;
|
||||
if (res) {
|
||||
if (t.isBlockStatement(path.node.consequent)) {
|
||||
path.replaceWithMultiple(path.node.consequent.body);
|
||||
} else {
|
||||
path.replaceWith(path.node.consequent);
|
||||
}
|
||||
} else if (path.node.alternate) {
|
||||
if (t.isBlockStatement(path.node.alternate)) {
|
||||
path.replaceWithMultiple(path.node.alternate.body);
|
||||
} else {
|
||||
path.replaceWith(path.node.alternate);
|
||||
}
|
||||
} else {
|
||||
path.remove();
|
||||
}
|
||||
},
|
||||
},
|
||||
CallExpression: {
|
||||
enter(path) {
|
||||
if (
|
||||
t.isMemberExpression(path.node.callee) &&
|
||||
t.isIdentifier(path.node.callee.object) &&
|
||||
t.isIdentifier(path.node.callee.property) &&
|
||||
path.node.callee.object.name === "Object" &&
|
||||
path.node.callee.property.name === "defineProperty" &&
|
||||
path.node.arguments.length >= 2
|
||||
) {
|
||||
const args = path.node.arguments;
|
||||
|
||||
if (
|
||||
t.isIdentifier(args[0]) && args[0].name === "exports" ||
|
||||
t.isMemberExpression(args[0]) &&
|
||||
t.isIdentifier(args[0].object) &&
|
||||
t.isIdentifier(args[0].property) &&
|
||||
args[0].object.name === "module" &&
|
||||
args[0].property.name === "exports" &&
|
||||
t.isStringLiteral(args[1]) && args[1].value === "native"
|
||||
) {
|
||||
path.remove();
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
function evaluateExpr(
|
||||
t: typeof types,
|
||||
env: "client" | "ssr",
|
||||
mode: string,
|
||||
node: types.Node,
|
||||
state: PluginPass,
|
||||
): boolean | null {
|
||||
if (t.isLogicalExpression(node)) {
|
||||
const left = evaluateExpr(t, env, mode, node.left, state);
|
||||
if (left === null) return null;
|
||||
if (left && node.operator === "||") return true;
|
||||
|
||||
const right = evaluateExpr(t, env, mode, node.right, state);
|
||||
if (right === null) return null;
|
||||
|
||||
switch (node.operator) {
|
||||
case "||":
|
||||
return left || right;
|
||||
case "&&":
|
||||
return left && right;
|
||||
case "??":
|
||||
return left ?? right;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
} else if (t.isBinaryExpression(node)) {
|
||||
// Check: typeof process == "undefined"
|
||||
// Check: typeof process === "undefined"
|
||||
// Check: typeof process != "undefined"
|
||||
// Check: typeof process !== "undefined"
|
||||
if (
|
||||
t.isUnaryExpression(node.left) && node.left.operator === "typeof" &&
|
||||
t.isIdentifier(node.left.argument) &&
|
||||
node.left.argument.name === "process" && t.isStringLiteral(node.right) &&
|
||||
node.right.value === "undefined"
|
||||
) {
|
||||
if (node.operator === "==" || node.operator === "===") {
|
||||
return env !== "ssr";
|
||||
} else if (node.operator === "!=" || node.operator === "!==") {
|
||||
return env === "ssr";
|
||||
}
|
||||
} else if (
|
||||
// Workaround for npm:pg
|
||||
// Check: typeof process.env.NODE_PG_FORCE_NATIVE !== "undefined"
|
||||
t.isUnaryExpression(node.left) &&
|
||||
t.isMemberExpression(node.left.argument) &&
|
||||
t.isMemberExpression(node.left.argument.object) &&
|
||||
t.isIdentifier(node.left.argument.object.object) &&
|
||||
node.left.argument.object.object.name === "process" &&
|
||||
t.isIdentifier(node.left.argument.object.property) &&
|
||||
node.left.argument.object.property.name === "env" &&
|
||||
t.isIdentifier(node.left.argument.property) &&
|
||||
node.left.argument.property.name === "NODE_PG_FORCE_NATIVE" &&
|
||||
t.isStringLiteral(node.right)
|
||||
) {
|
||||
state.set(APPLY_PG_QUIRKS, true);
|
||||
const left = typeof Deno.env.get("NODE_PG_FORCE_NATIVE");
|
||||
const right = node.right.value;
|
||||
|
||||
const result = applyBinExpr(left, right, node);
|
||||
if (result !== null) return result;
|
||||
} else if (
|
||||
// Check: process.env.NODE_ENV == "production"
|
||||
// Check: process.env.NODE_ENV === "production"
|
||||
// Check: process.env.NODE_ENV != "production"
|
||||
// Check: process.env.NODE_ENV !== "production"
|
||||
// Check: process.env.NODE_ENV == "development"
|
||||
// Check: process.env.NODE_ENV === "development"
|
||||
// Check: process.env.NODE_ENV != "development"
|
||||
// Check: process.env.NODE_ENV !== "development"
|
||||
t.isMemberExpression(node.left) &&
|
||||
t.isMemberExpression(node.left.object) &&
|
||||
t.isIdentifier(node.left.object.object) &&
|
||||
node.left.object.object.name === "process" &&
|
||||
t.isIdentifier(node.left.object.property) &&
|
||||
node.left.object.property.name === "env" &&
|
||||
t.isIdentifier(node.left.property) &&
|
||||
node.left.property.name === "NODE_ENV" &&
|
||||
t.isStringLiteral(node.right)
|
||||
) {
|
||||
const value = node.right.value;
|
||||
|
||||
const result = applyBinExpr(mode, value, node);
|
||||
if (result !== null) return result;
|
||||
} else if (
|
||||
// Check: process.foo === "bar"
|
||||
env === "ssr" && t.isMemberExpression(node.left) &&
|
||||
t.isIdentifier(node.left.object) && node.left.object.name === "process" &&
|
||||
t.isIdentifier(node.left.property) &&
|
||||
!PROCESS_PROPERTIES.has(node.left.property.name)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return null;
|
||||
} else if (
|
||||
t.isMemberExpression(node) && t.isIdentifier(node.object) &&
|
||||
node.object.name === "process" && t.isIdentifier(node.property)
|
||||
) {
|
||||
return PROCESS_PROPERTIES.has(node.property.name);
|
||||
} else if (t.isIdentifier(node) && node.name === "useLegacyCrypto") {
|
||||
return false;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function applyBinExpr(
|
||||
left: unknown,
|
||||
right: unknown,
|
||||
node: types.BinaryExpression,
|
||||
): boolean | null {
|
||||
switch (node.operator) {
|
||||
case "==":
|
||||
return left == right;
|
||||
case "===":
|
||||
return left === right;
|
||||
case "!=":
|
||||
return left != right;
|
||||
case "!==":
|
||||
return left !== right;
|
||||
case "+":
|
||||
case "-":
|
||||
case "/":
|
||||
case "%":
|
||||
case "*":
|
||||
case "**":
|
||||
case "&":
|
||||
case "|":
|
||||
case ">>":
|
||||
case ">>>":
|
||||
case "<<":
|
||||
case "^":
|
||||
case "in":
|
||||
case "instanceof":
|
||||
case ">":
|
||||
case "<":
|
||||
case ">=":
|
||||
case "<=":
|
||||
case "|>":
|
||||
break;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const PROCESS_PROPERTIES = new Set([
|
||||
"abort",
|
||||
"allowedNodeEnvironmentFlags",
|
||||
"arch",
|
||||
"argv",
|
||||
"argv0",
|
||||
"availableMemory",
|
||||
"channel",
|
||||
"chdir",
|
||||
"config",
|
||||
"connected",
|
||||
"constrainedMemory",
|
||||
"cpuUsage",
|
||||
"cwd",
|
||||
"debugPort",
|
||||
"disconnect",
|
||||
"dlopen",
|
||||
"emitWarning",
|
||||
"env",
|
||||
"execArgv",
|
||||
"execPath",
|
||||
"execve",
|
||||
"exit",
|
||||
"exitCode",
|
||||
"features",
|
||||
"finalization",
|
||||
"getActiveResourcesInfo",
|
||||
"getBuiltinModule",
|
||||
"getegid",
|
||||
"geteuid",
|
||||
"getgid",
|
||||
"getgroups",
|
||||
"getuid",
|
||||
"hasUncaughtExceptionCaptureCallback",
|
||||
"hrtime",
|
||||
"initgroups",
|
||||
"kill",
|
||||
"loadEnvFile",
|
||||
"mainModule",
|
||||
"memoryUsage",
|
||||
"nextTick",
|
||||
"noDeprecation",
|
||||
"permission",
|
||||
"pid",
|
||||
"platform",
|
||||
"ppid",
|
||||
"ref",
|
||||
"release",
|
||||
"report",
|
||||
"resourceUsage",
|
||||
"send",
|
||||
"setegid",
|
||||
"seteuid",
|
||||
"setgid",
|
||||
"setgroups",
|
||||
"setuid",
|
||||
"setSourceMapsEnabled",
|
||||
"setUncaughtExceptionCaptureCallback",
|
||||
"sourceMapsEnabled",
|
||||
"stderr",
|
||||
"stdin",
|
||||
"stdout",
|
||||
"throwDeprecation",
|
||||
"threadCpuUsage",
|
||||
"title",
|
||||
"traceDeprecation",
|
||||
"umask",
|
||||
"unref",
|
||||
"uptime",
|
||||
"version",
|
||||
"versions",
|
||||
]);
|
||||
@@ -0,0 +1,138 @@
|
||||
import { expect } from "@std/expect/expect";
|
||||
import * as babel from "@babel/core";
|
||||
import { codeEvalPlugin } from "./code_eval.ts";
|
||||
|
||||
function runTest(
|
||||
options: {
|
||||
input: string;
|
||||
expected: string;
|
||||
env: "client" | "ssr";
|
||||
mode: "development" | "production";
|
||||
},
|
||||
) {
|
||||
const res = babel.transformSync(options.input, {
|
||||
filename: "foo.js",
|
||||
babelrc: false,
|
||||
plugins: [codeEvalPlugin(options.env, options.mode)],
|
||||
});
|
||||
|
||||
const output = res?.code ?? "";
|
||||
expect(output).toEqual(options.expected);
|
||||
}
|
||||
|
||||
Deno.test("code eval - resolve runtime conditional detection", () => {
|
||||
runTest({
|
||||
env: "client",
|
||||
mode: "development",
|
||||
input:
|
||||
`if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
|
||||
module.exports = require('./browser.js');
|
||||
} else {
|
||||
module.exports = require('./node.js');
|
||||
}`,
|
||||
expected: `module.exports = require('./browser.js');`,
|
||||
});
|
||||
|
||||
runTest({
|
||||
env: "client",
|
||||
mode: "development",
|
||||
input: `if (typeof process !== 'undefined') {
|
||||
module.exports = require('./node.js');
|
||||
} else {
|
||||
module.exports = require('./browser.js');
|
||||
}`,
|
||||
expected: `module.exports = require('./browser.js');`,
|
||||
});
|
||||
|
||||
runTest({
|
||||
env: "ssr",
|
||||
mode: "development",
|
||||
input: `if (typeof process === 'undefined') {
|
||||
module.exports = require('./browser.js');
|
||||
} else {
|
||||
module.exports = require('./node.js');
|
||||
}`,
|
||||
expected: `module.exports = require('./node.js');`,
|
||||
});
|
||||
|
||||
runTest({
|
||||
env: "ssr",
|
||||
mode: "development",
|
||||
input: `if (typeof process !== 'undefined') {
|
||||
module.exports = require('./node.js');
|
||||
} else {
|
||||
module.exports = require('./browser.js');
|
||||
}`,
|
||||
expected: `module.exports = require('./node.js');`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("code eval - resolve process.env.NODE_ENV", () => {
|
||||
runTest({
|
||||
env: "client",
|
||||
mode: "development",
|
||||
input: `if (process.env.NODE_ENV === 'production') {
|
||||
module.exports = require('./cjs/react.production.js');
|
||||
} else {
|
||||
module.exports = require('./cjs/react.development.js');
|
||||
}`,
|
||||
expected: `module.exports = require('./cjs/react.development.js');`,
|
||||
});
|
||||
|
||||
runTest({
|
||||
env: "client",
|
||||
mode: "production",
|
||||
input: `if (process.env.NODE_ENV === 'production') {
|
||||
module.exports = require('./cjs/react.production.js');
|
||||
} else {
|
||||
module.exports = require('./cjs/react.development.js');
|
||||
}`,
|
||||
expected: `module.exports = require('./cjs/react.production.js');`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("code eval - npm:debug", () => {
|
||||
runTest({
|
||||
env: "ssr",
|
||||
mode: "development",
|
||||
input:
|
||||
`if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
|
||||
module.exports = require('./browser.js');
|
||||
} else {
|
||||
module.exports = require('./node.js');
|
||||
}`,
|
||||
expected: `module.exports = require('./node.js');`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("code eval - npm:pg", () => {
|
||||
runTest({
|
||||
env: "ssr",
|
||||
mode: "development",
|
||||
input: `if (typeof process.env.NODE_PG_FORCE_NATIVE !== "undefined") {
|
||||
module.exports = require('./native.js');
|
||||
} else {
|
||||
module.exports = require('./normal.js');
|
||||
}`,
|
||||
expected: `module.exports = require('./normal.js');`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("code eval - npm:pg #2", () => {
|
||||
runTest({
|
||||
env: "ssr",
|
||||
mode: "development",
|
||||
input:
|
||||
`const useLegacyCrypto = parseInt(process.versions && process.versions.node && process.versions.node.split('.')[0]) < 15
|
||||
if (useLegacyCrypto) {
|
||||
// We are on an old version of Node.js that requires legacy crypto utilities.
|
||||
module.exports = require('./utils-legacy')
|
||||
} else {
|
||||
module.exports = require('./utils-webcrypto')
|
||||
}
|
||||
`,
|
||||
expected:
|
||||
`const useLegacyCrypto = parseInt(process.versions && process.versions.node && process.versions.node.split('.')[0]) < 15;
|
||||
module.exports = require('./utils-webcrypto');`,
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { PluginObj, types } from "@babel/core";
|
||||
import type { NodePath, PluginObj, types } from "@babel/core";
|
||||
|
||||
export function cjsPlugin(
|
||||
{ types: t }: { types: typeof types },
|
||||
@@ -9,6 +9,7 @@ export function cjsPlugin(
|
||||
const EXPORTED = "exported";
|
||||
const EXPORTED_NAMESPACES = "exported_namespaces";
|
||||
const ALIASED = "aliased";
|
||||
const NEEDS_REQUIRE_IMPORT = "needsRequireImport";
|
||||
|
||||
return {
|
||||
name: "fresh-cjs-esm",
|
||||
@@ -37,6 +38,40 @@ export function cjsPlugin(
|
||||
|
||||
const exported = state.get(EXPORTED);
|
||||
const exportedNs = state.get(EXPORTED_NAMESPACES);
|
||||
const needsRequireImport = state.get(NEEDS_REQUIRE_IMPORT);
|
||||
|
||||
if (needsRequireImport) {
|
||||
// Inject:
|
||||
// ```ts
|
||||
// import { createRequire } from "node:module";
|
||||
// const require = createRequire(import.meta.url);
|
||||
// ```
|
||||
const id = t.identifier("createRequire");
|
||||
path.unshiftContainer(
|
||||
"body",
|
||||
t.variableDeclaration("const", [
|
||||
t.variableDeclarator(
|
||||
t.identifier("require"),
|
||||
t.callExpression(t.identifier("createRequire"), [
|
||||
t.memberExpression(
|
||||
t.metaProperty(
|
||||
t.identifier("import"),
|
||||
t.identifier("meta"),
|
||||
),
|
||||
t.identifier("url"),
|
||||
),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
);
|
||||
path.unshiftContainer(
|
||||
"body",
|
||||
t.importDeclaration(
|
||||
[t.importSpecifier(id, id)],
|
||||
t.stringLiteral("node:module"),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const mappedNs: string[] = [];
|
||||
|
||||
@@ -224,30 +259,53 @@ export function cjsPlugin(
|
||||
const mods = state.get(REQUIRE_CALLS) ?? [];
|
||||
state.set(REQUIRE_CALLS, mods);
|
||||
|
||||
mods.push({
|
||||
id,
|
||||
specifier: t.cloneNode(path.node.arguments[0], true),
|
||||
});
|
||||
if (t.isStringLiteral(path.node.arguments[0])) {
|
||||
// Check if we can hoist it or if we need to keep it.
|
||||
let canImport = true;
|
||||
let parent: NodePath | null = path.parentPath;
|
||||
while (parent !== null) {
|
||||
if (
|
||||
t.isTryStatement(parent.node) || t.isIfStatement(parent.node) ||
|
||||
t.isConditionalExpression(parent.node)
|
||||
) {
|
||||
canImport = false;
|
||||
break;
|
||||
}
|
||||
parent = parent.parentPath;
|
||||
}
|
||||
|
||||
if (
|
||||
path.parentPath?.isVariableDeclarator() &&
|
||||
path.parentPath?.get("id").isIdentifier() ||
|
||||
path.parentPath?.isCallExpression()
|
||||
) {
|
||||
path.replaceWith(
|
||||
t.logicalExpression(
|
||||
"??",
|
||||
t.memberExpression(
|
||||
if (!canImport) {
|
||||
state.set(NEEDS_REQUIRE_IMPORT, true);
|
||||
return;
|
||||
}
|
||||
|
||||
mods.push({
|
||||
id,
|
||||
specifier: t.cloneNode(path.node.arguments[0], true),
|
||||
});
|
||||
|
||||
if (
|
||||
path.parentPath?.isVariableDeclarator() &&
|
||||
path.parentPath?.get("id").isIdentifier() ||
|
||||
path.parentPath?.isCallExpression()
|
||||
) {
|
||||
path.replaceWith(
|
||||
t.logicalExpression(
|
||||
"??",
|
||||
t.memberExpression(
|
||||
t.cloneNode(id, true),
|
||||
t.identifier("default"),
|
||||
),
|
||||
t.cloneNode(id, true),
|
||||
t.identifier("default"),
|
||||
),
|
||||
t.cloneNode(id, true),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
path.replaceWith(t.cloneNode(id, true));
|
||||
path.replaceWith(t.cloneNode(id, true));
|
||||
} else {
|
||||
state.set(NEEDS_REQUIRE_IMPORT, true);
|
||||
}
|
||||
} else if (
|
||||
t.isMemberExpression(path.node.callee) &&
|
||||
t.isIdentifier(path.node.callee.object) &&
|
||||
@@ -283,6 +341,24 @@ export function cjsPlugin(
|
||||
},
|
||||
ExpressionStatement: {
|
||||
enter(path, state) {
|
||||
// Check: Object.defineProperty(module.exports) "__esModule" ...)
|
||||
// Check: Object.defineProperty(exports) "__esModule" ...)
|
||||
if (
|
||||
t.isCallExpression(path.node.expression) &&
|
||||
t.isMemberExpression(path.node.expression.callee) &&
|
||||
t.isIdentifier(path.node.expression.callee.object) &&
|
||||
t.isIdentifier(path.node.expression.callee.property) &&
|
||||
path.node.expression.callee.object.name === "Object" &&
|
||||
path.node.expression.callee.property.name === "defineProperty" &&
|
||||
path.node.expression.arguments.length >= 2 &&
|
||||
t.isStringLiteral(path.node.expression.arguments[1]) &&
|
||||
path.node.expression.arguments[1].value === "__esModule"
|
||||
) {
|
||||
state.set(HAS_ES_MODULE, true);
|
||||
path.remove();
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
t.isExpressionStatement(path.node) &&
|
||||
t.isCallExpression(path.node.expression) &&
|
||||
@@ -312,6 +388,92 @@ export function cjsPlugin(
|
||||
const alias = path.node.expression.callee.params[0].name;
|
||||
state.set(ALIASED, alias);
|
||||
}
|
||||
} else if (
|
||||
// Check: Object.defineProperty(exports, "foo", { enumerable: true, get: function () { return foo; } });
|
||||
t.isCallExpression(path.node.expression) &&
|
||||
t.isMemberExpression(path.node.expression.callee) &&
|
||||
t.isIdentifier(path.node.expression.callee.object) &&
|
||||
path.node.expression.callee.object.name === "Object" &&
|
||||
t.isIdentifier(path.node.expression.callee.property) &&
|
||||
path.node.expression.callee.property.name === "defineProperty" &&
|
||||
path.node.expression.arguments.length >= 2 &&
|
||||
t.isIdentifier(path.node.expression.arguments[0]) &&
|
||||
path.node.expression.arguments[0].name === "exports" &&
|
||||
t.isStringLiteral(path.node.expression.arguments[1]) &&
|
||||
t.isObjectExpression(path.node.expression.arguments[2])
|
||||
) {
|
||||
const exported = path.node.expression.arguments[1].value;
|
||||
const obj = path.node.expression.arguments[2];
|
||||
for (let i = 0; i < obj.properties.length; i++) {
|
||||
const prop = obj.properties[i];
|
||||
|
||||
if (
|
||||
t.isObjectProperty(prop) && t.isIdentifier(prop.key) &&
|
||||
prop.key.name === "get" && t.isFunctionExpression(prop.value) &&
|
||||
t.isBlockStatement(prop.value.body) &&
|
||||
prop.value.body.body.length === 1 &&
|
||||
t.isReturnStatement(prop.value.body.body[0])
|
||||
) {
|
||||
const expr = prop.value.body.body[0].argument;
|
||||
if (expr !== null && expr !== undefined) {
|
||||
path.replaceWith(
|
||||
t.assignmentExpression(
|
||||
"=",
|
||||
t.memberExpression(
|
||||
t.identifier("exports"),
|
||||
t.identifier(exported),
|
||||
),
|
||||
t.cloneNode(expr, true),
|
||||
),
|
||||
);
|
||||
}
|
||||
} else if (
|
||||
t.isObjectMethod(prop) && t.isIdentifier(prop.key) &&
|
||||
prop.key.name === "get" && t.isBlockStatement(prop.body) &&
|
||||
prop.body.body.length === 1 &&
|
||||
t.isReturnStatement(prop.body.body[0])
|
||||
) {
|
||||
const expr = prop.body.body[0].argument;
|
||||
if (expr !== null && expr !== undefined) {
|
||||
path.replaceWith(
|
||||
t.assignmentExpression(
|
||||
"=",
|
||||
t.memberExpression(
|
||||
t.identifier("exports"),
|
||||
t.identifier(exported),
|
||||
),
|
||||
t.cloneNode(expr, true),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let depth = 0;
|
||||
let current = path.node.expression;
|
||||
|
||||
while (
|
||||
t.isAssignmentExpression(current) &&
|
||||
t.isMemberExpression(current.left) &&
|
||||
t.isIdentifier(current.left.object) &&
|
||||
current.left.object.name === "exports"
|
||||
) {
|
||||
if (
|
||||
t.isUnaryExpression(current.right) &&
|
||||
current.right.operator === "void" &&
|
||||
t.isNumericLiteral(current.right.argument) &&
|
||||
current.right.argument.value === 0
|
||||
) {
|
||||
if (depth > 0) {
|
||||
path.remove();
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
depth++;
|
||||
current = current.right;
|
||||
}
|
||||
}
|
||||
},
|
||||
exit(path, state) {
|
||||
|
||||
@@ -26,6 +26,8 @@ Object.defineProperty(module, "exports", {
|
||||
|
||||
const DEFAULT_EXPORT = `const _default = exports.default ?? exports;`;
|
||||
const DEFAULT_EXPORT_END = `export default _default;`;
|
||||
const IMPORT_REQUIRE = `import { createRequire } from "node:module";
|
||||
const require = createRequire(import.meta.url);`;
|
||||
|
||||
Deno.test("commonjs - module.exports default", () => {
|
||||
runTest({
|
||||
@@ -239,14 +241,11 @@ Deno.test("commonjs - cleared exports", () => {
|
||||
exports.foo = exports.bar = void 0;
|
||||
exports.foo = 'foo'`,
|
||||
expected: `${INIT}
|
||||
exports.foo = exports.bar = void 0;
|
||||
exports.foo = 'foo';
|
||||
var _foo = exports.foo;
|
||||
var _bar = exports.bar;
|
||||
export { _foo as foo, _bar as bar };
|
||||
export { _foo as foo };
|
||||
${DEFAULT_EXPORT}
|
||||
_default.foo = _foo;
|
||||
_default.bar = _bar;
|
||||
${DEFAULT_EXPORT_END}`,
|
||||
});
|
||||
});
|
||||
@@ -258,12 +257,7 @@ Object.defineProperty(exports, "foo", { enumerable: true, get: function () { ret
|
||||
expected: `${INIT}
|
||||
import * as _mod from "./bar";
|
||||
var utils_1 = _mod.default ?? _mod;
|
||||
Object.defineProperty(exports, "foo", {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return utils_1.foo;
|
||||
}
|
||||
});
|
||||
exports.foo = utils_1.foo;
|
||||
var _foo = exports.foo;
|
||||
export { _foo as foo };
|
||||
${DEFAULT_EXPORT}
|
||||
@@ -279,12 +273,7 @@ Object.defineProperty(exports, "foo", { enumerable: true, get() { return utils_1
|
||||
expected: `${INIT}
|
||||
import * as _mod from "./bar";
|
||||
var utils_1 = _mod.default ?? _mod;
|
||||
Object.defineProperty(exports, "foo", {
|
||||
enumerable: true,
|
||||
get() {
|
||||
return utils_1.foo;
|
||||
}
|
||||
});
|
||||
exports.foo = utils_1.foo;
|
||||
var _foo = exports.foo;
|
||||
export { _foo as foo };
|
||||
${DEFAULT_EXPORT}
|
||||
@@ -471,3 +460,76 @@ _default.foo = _foo;
|
||||
${DEFAULT_EXPORT_END}`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - require non-analyzable arg", () => {
|
||||
runTest({
|
||||
input: `const pkg = require(path.join(basedir, "package.json"))`,
|
||||
expected: `import { createRequire } from "node:module";
|
||||
const require = createRequire(import.meta.url);
|
||||
const pkg = require(path.join(basedir, "package.json"));`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("commonjs - require lazy import", () => {
|
||||
runTest({
|
||||
input: `if (typeof process.env.NODE_PG_FORCE_NATIVE !== 'undefined') {
|
||||
module.exports = new PG(require('./native'))
|
||||
} else {
|
||||
module.exports = new PG(Client)
|
||||
|
||||
// lazy require native module...the native module may not have installed
|
||||
Object.defineProperty(module.exports, 'native', {
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
get() {
|
||||
let native = null
|
||||
try {
|
||||
native = new PG(require('./native'))
|
||||
} catch (err) {
|
||||
if (err.code !== 'MODULE_NOT_FOUND') {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// overwrite module.exports.native so that getter is never called again
|
||||
Object.defineProperty(module.exports, 'native', {
|
||||
value: native,
|
||||
})
|
||||
|
||||
return native
|
||||
},
|
||||
})
|
||||
}`,
|
||||
expected: `${INIT}
|
||||
${IMPORT_REQUIRE}
|
||||
if (typeof process.env.NODE_PG_FORCE_NATIVE !== 'undefined') {
|
||||
module.exports = new PG(require('./native'));
|
||||
} else {
|
||||
module.exports = new PG(Client);
|
||||
|
||||
// lazy require native module...the native module may not have installed
|
||||
Object.defineProperty(module.exports, 'native', {
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
get() {
|
||||
let native = null;
|
||||
try {
|
||||
native = new PG(require('./native'));
|
||||
} catch (err) {
|
||||
if (err.code !== 'MODULE_NOT_FOUND') {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// overwrite module.exports.native so that getter is never called again
|
||||
Object.defineProperty(module.exports, 'native', {
|
||||
value: native
|
||||
});
|
||||
return native;
|
||||
}
|
||||
});
|
||||
}
|
||||
${DEFAULT_EXPORT}
|
||||
${DEFAULT_EXPORT_END}`,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import type { NodePath, PluginObj, types } from "@babel/core";
|
||||
|
||||
export function inlineEnvVarsPlugin(mode: string) {
|
||||
export function inlineEnvVarsPlugin(mode: string, env: Record<string, string>) {
|
||||
const allowed = new Map<string, string>();
|
||||
for (const [name, value] of Object.entries(Deno.env.toObject())) {
|
||||
for (const [name, value] of Object.entries(env)) {
|
||||
if (name.startsWith("FRESH_PUBLIC_")) {
|
||||
allowed.set(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
allowed.set("NODE_ENV", Deno.env.get("NODE_ENV") ?? mode);
|
||||
allowed.set("NODE_ENV", mode);
|
||||
|
||||
return (
|
||||
{ types: t }: { types: typeof types },
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
import { expect } from "@std/expect/expect";
|
||||
import * as babel from "@babel/core";
|
||||
import { inlineEnvVarsPlugin } from "./inline_env_vars.ts";
|
||||
import { usingEnv } from "../../../tests/test_utils.ts";
|
||||
|
||||
function runTest(options: { input: string; expected: string; mode?: string }) {
|
||||
function runTest(
|
||||
options: {
|
||||
input: string;
|
||||
expected: string;
|
||||
mode?: string;
|
||||
env?: Record<string, string>;
|
||||
},
|
||||
) {
|
||||
const res = babel.transformSync(options.input, {
|
||||
filename: "foo.js",
|
||||
babelrc: false,
|
||||
plugins: [inlineEnvVarsPlugin(options.mode ?? "development")],
|
||||
plugins: [
|
||||
inlineEnvVarsPlugin(options.mode ?? "development", options.env ?? {}),
|
||||
],
|
||||
});
|
||||
|
||||
const output = res?.code ?? "";
|
||||
expect(output).toEqual(options.expected);
|
||||
}
|
||||
|
||||
Deno.test("env vars - inline NODE_ENV", () => {
|
||||
using _ = usingEnv("NODE_ENV", "foobar");
|
||||
runTest({
|
||||
input: `() => process.env.NODE_ENV`,
|
||||
expected: `() => "foobar";`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("env vars - inline NODE_ENV mode", () => {
|
||||
runTest({
|
||||
input: `() => process.env.NODE_ENV`,
|
||||
@@ -31,49 +31,49 @@ Deno.test("env vars - inline NODE_ENV mode", () => {
|
||||
});
|
||||
|
||||
Deno.test("env vars - inline custom process.env.*", () => {
|
||||
using _ = usingEnv("FRESH_PUBLIC_FOO", "a");
|
||||
runTest({
|
||||
input: `() => process.env.FRESH_PUBLIC_FOO`,
|
||||
expected: `() => "a";`,
|
||||
env: {
|
||||
FRESH_PUBLIC_FOO: "a",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("env vars - inline Deno.env.get()", () => {
|
||||
using _ = usingEnv("FRESH_PUBLIC_FOO", "b");
|
||||
runTest({
|
||||
input: `() => Deno.env.get("FRESH_PUBLIC_FOO")`,
|
||||
expected: `() => "b";`,
|
||||
env: {
|
||||
FRESH_PUBLIC_FOO: "b",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("env vars - inline Deno.env.get(NODE_ENV)", () => {
|
||||
using _ = usingEnv("NODE_ENV", "c");
|
||||
runTest({
|
||||
input: `() => Deno.env.get("NODE_ENV")`,
|
||||
expected: `() => "c";`,
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("env vars - inline Deno.env.get(NODE_ENV) mode", () => {
|
||||
runTest({
|
||||
input: `() => Deno.env.get("NODE_ENV")`,
|
||||
expected: `() => "test";`,
|
||||
mode: "test",
|
||||
mode: "c",
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("env vars - inline const _ = Deno.env.get()", () => {
|
||||
using _ = usingEnv("FRESH_PUBLIC_FOO", "test");
|
||||
runTest({
|
||||
input: `const deno = Deno.env.get("FRESH_PUBLIC_FOO");`,
|
||||
expected: `const deno = "test";`,
|
||||
env: {
|
||||
FRESH_PUBLIC_FOO: "test",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("env vars - inline import.meta.env.FRESH_PUBLIC_FOO", () => {
|
||||
using _ = usingEnv("FRESH_PUBLIC_FOO", "test");
|
||||
runTest({
|
||||
input: `() => import.meta.env.FRESH_PUBLIC_FOO;`,
|
||||
expected: `() => "test";`,
|
||||
env: {
|
||||
FRESH_PUBLIC_FOO: "test",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { Plugin } from "vite";
|
||||
import * as path from "@std/path";
|
||||
|
||||
const SHIMS: Record<string, string> = {
|
||||
"object.entries": path.join(
|
||||
import.meta.dirname!,
|
||||
"shims",
|
||||
"object.entries",
|
||||
"index.ts",
|
||||
),
|
||||
"supports-color": path.join(
|
||||
import.meta.dirname!,
|
||||
"shims",
|
||||
"supports-color",
|
||||
"index.ts",
|
||||
),
|
||||
};
|
||||
|
||||
export function shims(): Plugin {
|
||||
return {
|
||||
name: "fresh:shims",
|
||||
resolveId: {
|
||||
filter: {
|
||||
id: /(object\.entries|supports-color)/,
|
||||
},
|
||||
handler(id) {
|
||||
const resolved = SHIMS[id];
|
||||
if (resolved !== undefined) {
|
||||
return resolved;
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export default function entries(obj: any) {
|
||||
return Object.entries(obj);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
export interface ColorSupport {
|
||||
level: 1 | 2 | 3;
|
||||
hasBasic: boolean;
|
||||
has256: boolean;
|
||||
has16m: boolean;
|
||||
}
|
||||
|
||||
function toLevel(depth: number): 1 | 2 | 3 {
|
||||
if (depth === 1) return 1;
|
||||
if (depth === 8) return 2;
|
||||
if (depth === 24) return 3;
|
||||
return 1;
|
||||
}
|
||||
|
||||
function toSupport(depth: number): ColorSupport {
|
||||
const level = toLevel(depth);
|
||||
return {
|
||||
level,
|
||||
hasBasic: true,
|
||||
has256: level >= 2,
|
||||
has16m: level >= 3,
|
||||
};
|
||||
}
|
||||
|
||||
export default {
|
||||
// deno-lint-ignore no-process-global
|
||||
stdout: toSupport(process.stdout.getColorDepth()),
|
||||
// deno-lint-ignore no-process-global
|
||||
stderr: toSupport(process.stderr.getColorDepth()),
|
||||
};
|
||||
Reference in New Issue
Block a user