fix(vite): npm resolution + cjs + duplicated preact signals (#3211)

This commit is contained in:
Marvin Hagemeister
2025-08-16 19:26:39 +02:00
committed by GitHub
parent 71071171ed
commit 59549c9532
18 changed files with 1047 additions and 466 deletions
+9 -12
View File
@@ -38,18 +38,15 @@ export function fresh(config?: FreshViteConfig): Plugin[] {
"react-dom": "preact/compat",
react: "preact/compat",
},
// Disallow externals, because it leads to duplicate
// modules with `preact` vs `npm:preact@*` in the server
// environment.
noExternal: true,
},
optimizeDeps: {
include: [
"preact",
"preact/compat",
"preact/debug",
"preact/devtools",
"preact/hooks",
"preact/jsx-runtime",
"preact/jsx-dev-runtime",
"@preact/signals",
],
// Optimize deps somehow leads to duplicate modules or them
// being placed in the wrong chunks...
noDiscovery: true,
},
publicDir: pathWithRoot("static", config.root),
@@ -88,7 +85,7 @@ export function fresh(config?: FreshViteConfig): Plugin[] {
},
ssr: {
build: {
manifest: false,
manifest: true,
copyPublicDir: false,
outDir: config.environments?.ssr?.build?.outDir ??
@@ -108,8 +105,8 @@ export function fresh(config?: FreshViteConfig): Plugin[] {
fConfig.routeDir = pathWithRoot(fConfig.routeDir, config.root);
},
},
patches(),
serverEntryPlugin(fConfig),
patches(),
...serverSnapshot(fConfig),
clientEntryPlugin(),
clientSnapshot(fConfig),
@@ -1,268 +0,0 @@
import type { types } from "@babel/core";
export function cjsPlugin(
{ types: t }: { types: typeof types },
): babel.PluginObj {
const HAS_ES_MODULE = "esModule";
const REQUIRE_CALLS = "requireCalls";
const ROOT_SCOPE = "rootScope";
return {
name: "fresh-cjs-esm",
visitor: {
Program: {
enter(path, state) {
state.set(ROOT_SCOPE, path.scope);
},
exit(path, state) {
const body = path.get("body");
const requires = state.get(REQUIRE_CALLS);
if (requires !== undefined) {
for (let i = 0; i < requires.length; i++) {
const { specifier, id } = requires[i];
path.unshiftContainer(
"body",
t.importDeclaration(
[t.importNamespaceSpecifier(id)],
specifier,
),
);
}
}
if (body.length === 0 && state.get(HAS_ES_MODULE)) {
path.pushContainer("body", t.exportNamedDeclaration(null));
} else {
const seen = new Set<string>();
const children = path.get("body");
for (let i = children.length - 1; i >= 0; i--) {
const child = children[i];
if (child.isExportNamedDeclaration()) {
if (
t.isVariableDeclaration(child.node.declaration) &&
child.node.declaration.declarations.length > 0 &&
t.isIdentifier(child.node.declaration.declarations[0].id)
) {
const name = child.node.declaration.declarations[0].id.name;
if (seen.has(name)) {
child.remove();
} else {
seen.add(name);
}
}
}
}
}
},
},
CallExpression(path, state) {
if (isObjEsModuleFlag(t, path.node)) {
state.set(HAS_ES_MODULE, true);
path.remove();
return;
}
if (
t.isIdentifier(path.node.callee) &&
path.node.callee.name === "require"
) {
const root = state.get(ROOT_SCOPE);
const id = root.generateUidIdentifier("mod");
const mods = state.get(REQUIRE_CALLS) ?? [];
state.set(REQUIRE_CALLS, mods);
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),
),
);
return;
}
path.replaceWith(t.cloneNode(id, true));
}
},
ExpressionStatement(path, state) {
const expr = path.get("expression");
if (expr.isAssignmentExpression()) {
const left = expr.get("left");
if (isEsModuleFlag(t, expr.node)) {
state.set(HAS_ES_MODULE, true);
path.remove();
} else if (left.isMemberExpression()) {
if (isModuleExports(t, left.node)) {
const right = t.cloneNode(expr.node.right, true);
path.replaceWith(t.exportDefaultDeclaration(right));
} else {
const named = getExportsAssignName(t, left.node);
if (named === null) return;
const right = t.cloneNode(expr.node.right, true);
if (named === "default") {
path.replaceWith(t.exportDefaultDeclaration(right));
} else {
path.scope.rename(named);
path.replaceWith(
t.exportNamedDeclaration(
t.variableDeclaration("let", [
t.variableDeclarator(t.identifier(named), right),
]),
),
);
}
}
}
} else if (expr.isCallExpression()) {
if (
t.isMemberExpression(expr.node.callee) &&
t.isIdentifier(expr.node.callee.object) &&
expr.node.callee.object.name === "Object" &&
t.isIdentifier(expr.node.callee.property) &&
expr.node.callee.property.name === "defineProperty" &&
expr.node.arguments.length === 3 &&
t.isIdentifier(expr.node.arguments[0]) &&
expr.node.arguments[0].name === "exports" &&
t.isStringLiteral(expr.node.arguments[1]) &&
expr.node.arguments[1].value !== "__esModule" &&
t.isObjectExpression(expr.node.arguments[2])
) {
const named = expr.node.arguments[1].value;
const obj = expr.node.arguments[2];
let right: types.Expression = t.nullLiteral();
for (let i = 0; i < obj.properties.length; i++) {
const prop = obj.properties[i];
if (t.isObjectProperty(prop)) {
if (t.isIdentifier(prop.key)) {
if (prop.key.name === "get") {
if (
t.isFunctionExpression(prop.value) ||
t.isArrowFunctionExpression(prop.value)
) {
right = t.callExpression(
t.parenthesizedExpression(
t.cloneNode(prop.value, true),
),
[],
);
}
}
}
} else if (t.isObjectMethod(prop)) {
if (t.isIdentifier(prop.key)) {
if (prop.key.name === "get") {
right = t.callExpression(
t.parenthesizedExpression(
t.functionExpression(
null,
[],
t.cloneNode(prop.body, true),
),
),
[],
);
}
}
}
}
path.replaceWith(
t.exportNamedDeclaration(
t.variableDeclaration("let", [
t.variableDeclarator(t.identifier(named), right),
]),
),
);
}
}
},
},
};
}
function isModuleExports(
t: typeof types,
node: types.MemberExpression,
): boolean {
return t.isIdentifier(node.object) && node.object.name === "module" &&
t.isIdentifier(node.property) && node.property.name === "exports";
}
function getExportsAssignName(
t: typeof types,
node: types.MemberExpression,
): string | null {
if (
(t.isMemberExpression(node.object) &&
isModuleExports(t, node.object) ||
t.isIdentifier(node.object) && node.object.name === "exports") &&
t.isIdentifier(node.property)
) {
return node.property.name;
}
return null;
}
/**
* Detect `exports.__esModule = true;`
*/
function isEsModuleFlag(
t: typeof types,
node: types.AssignmentExpression,
): boolean {
if (!t.isMemberExpression(node.left)) return false;
const { left, right } = node;
return (t.isMemberExpression(left.object) &&
isModuleExports(t, left.object) ||
t.isIdentifier(left.object) && left.object.name === "exports") &&
t.isIdentifier(left.property) && left.property.name === "__esModule" &&
t.isBooleanLiteral(right);
}
/**
* Check for `Object.defineProperty(exports, '__esModule', { value: true })`
*/
function isObjEsModuleFlag(
t: typeof types,
node: types.CallExpression,
): boolean {
return t.isMemberExpression(node.callee) &&
t.isIdentifier(node.callee.object) &&
node.callee.object.name === "Object" &&
t.isIdentifier(node.callee.property) &&
node.callee.property.name === "defineProperty" &&
node.arguments.length === 3 &&
(t.isMemberExpression(node.arguments[0]) &&
isModuleExports(t, node.arguments[0]) ||
t.isIdentifier(node.arguments[0]) &&
node.arguments[0].name === "exports") &&
t.isStringLiteral(node.arguments[1]) &&
node.arguments[1].value === "__esModule" &&
t.isObjectExpression(node.arguments[2]);
}
+114 -16
View File
@@ -6,34 +6,71 @@ import {
Workspace,
} from "@deno/loader";
import * as path from "@std/path";
import * as babel from "@babel/core";
import babelReact from "@babel/preset-react";
interface DenoState {
type: RequestedModuleType;
}
export function deno(): Plugin {
let loader: Loader;
let ssrLoader: Loader;
let browserLoader: Loader;
let isDev = false;
return {
name: "deno",
// We must be first to be able to resolve before the
// Vite's own`vite:resolve` plugin. It always treats bare
// specifiers as external during SSR.
enforce: "pre",
config(_, env) {
isDev = env.command === "serve";
},
async configResolved() {
// TODO: Pass conditions
loader = await new Workspace({}).createLoader();
ssrLoader = await new Workspace({}).createLoader();
browserLoader = await new Workspace({
platform: "browser",
preserveJsx: true,
})
.createLoader();
},
applyToEnvironment() {
return true;
},
async resolveId(id, importer, options) {
// Workaround until upstream PR is merged and released,
// see: https://github.com/vitejs/vite/pull/20558
if (id.startsWith("deno-npm:")) {
id = id.slice("deno-".length);
}
const loader = options?.ssr ? ssrLoader : browserLoader;
importer = isDenoSpecifier(importer)
? parseDenoSpecifier(importer).specifier
: importer;
// We still want to allow other plugins to participate in
// resolution, with us being in front due to `enforce: "pre"`.
// But we still want to ignore everything `vite:resolve` does
// because we're kinda replacing that plugin here.
const tmp = await this.resolve(id, importer, options);
if (tmp && tmp.resolvedBy !== "vite:resolve") {
if (tmp.external) {
return tmp;
}
// A plugin namespaced it, we should not attempt to resolve it.
if (tmp.id.startsWith("\0")) {
return tmp;
}
id = tmp.id;
}
// Plugins may return lower cased drive letters on windows
if (path.isAbsolute(id)) {
id = path.toFileUrl(path.normalize(id))
.href;
}
try {
// Ensure we're passing a valid importer that Deno understands
const denoImporter = importer && !importer.startsWith("\0")
@@ -47,15 +84,13 @@ export function deno(): Plugin {
);
if (id === resolved) {
return id;
return null;
}
const type = getDenoType(id, options.attributes.type ?? "default");
if (
type !== RequestedModuleType.Default ||
/^(https?|jsr|npm):/.test(resolved) ||
// Vite does weird things to windows file paths
Deno.build.os === "windows"
/^(https?|jsr|npm):/.test(resolved)
) {
return toDenoSpecifier(resolved, type);
}
@@ -76,7 +111,9 @@ export function deno(): Plugin {
// ignore
}
},
async load(id) {
async load(id, options) {
const loader = options?.ssr ? ssrLoader : browserLoader;
if (isDenoSpecifier(id)) {
const { type, specifier } = parseDenoSpecifier(id);
@@ -85,8 +122,20 @@ export function deno(): Plugin {
return null;
}
const code = new TextDecoder().decode(result.code);
const maybeJsx = maybeTransformJsxBrowser({
ssr: !!options?.ssr,
code,
id: specifier,
isDev,
});
if (maybeJsx !== null) {
return maybeJsx;
}
return {
code: new TextDecoder().decode(result.code),
code,
};
}
@@ -108,8 +157,20 @@ export function deno(): Plugin {
return null;
}
const code = new TextDecoder().decode(result.code);
const maybeJsx = maybeTransformJsxBrowser({
ssr: !!options?.ssr,
id,
code,
isDev,
});
if (maybeJsx) {
return maybeJsx;
}
return {
code: new TextDecoder().decode(result.code),
code,
};
},
async transform(_, id, options) {
@@ -128,12 +189,15 @@ export function deno(): Plugin {
actualId = path.toFileUrl(actualId).href;
}
const resolved = await loader.resolve(
const resolved = await ssrLoader.resolve(
actualId,
undefined,
ResolutionMode.Import,
);
const result = await loader.load(resolved, RequestedModuleType.Default);
const result = await ssrLoader.load(
resolved,
RequestedModuleType.Default,
);
if (result.kind === "external") {
return;
}
@@ -176,6 +240,10 @@ function parseDenoSpecifier(
specifier = `${protocol}://${rest}`;
}
if (path.isAbsolute(specifier)) {
specifier = path.toFileUrl(specifier).href;
}
return { type: +match[1], specifier };
}
@@ -194,3 +262,33 @@ function getDenoType(id: string, type: string): RequestedModuleType {
return RequestedModuleType.Default;
}
}
function maybeTransformJsxBrowser(
options: { ssr: boolean; code: string; id: string; isDev: boolean },
) {
const { ssr, code, id, isDev } = options;
if (
!ssr && id.endsWith(".tsx") || id.endsWith(".jsx")
) {
const babelResult = babel.transformSync(code, {
filename: id,
babelrc: false,
sourceMaps: "inline",
presets: [[babelReact, {
runtime: "automatic",
importSource: "preact",
development: isDev,
}]],
});
if (babelResult !== null && babelResult.code) {
return {
code: babelResult.code,
map: babelResult.map,
};
}
}
return null;
}
@@ -1,39 +0,0 @@
import type { types } from "@babel/core";
// Workaround until upstream PR is merged and released,
// see: https://github.com/vitejs/vite/pull/20558
export function npmWorkaround(
{ types: t }: { types: typeof types },
): babel.PluginObj {
return {
name: "fresh-npm-workaround",
visitor: {
ImportDeclaration(path) {
const source = path.node.source;
if (source.value.startsWith("npm:")) {
source.value = `deno-${source.value}`;
}
},
ExportNamedDeclaration(path) {
const source = path.node.source;
if (source === null || source === undefined) return;
if (source.value.startsWith("npm:")) {
source.value = `deno-${source.value}`;
}
},
CallExpression(path) {
if (!t.isImport(path.node.callee)) return;
if (path.node.arguments.length < 1) return;
const source = path.node.arguments[0];
if (t.isStringLiteral(source)) {
if (source.value.startsWith("npm:")) {
source.value = `deno-${source.value}`;
return;
}
}
},
},
};
}
@@ -1,47 +0,0 @@
import { expect } from "@std/expect/expect";
import * as babel from "@babel/core";
import { npmWorkaround } from "./npm_workaround.ts";
function runTest(options: { input: string; expected: string }) {
const res = babel.transformSync(options.input, {
filename: "foo.js",
babelrc: false,
plugins: [npmWorkaround],
});
const output = res?.code ?? "";
expect(output).toEqual(options.expected);
}
Deno.test("npm workaround - import declaration", () => {
runTest({
input: `import * as foo from "npm:foo";
import foo2 from "npm:foo";
import { bar } from "npm:foo";
import baz, { bar2 } from "npm:foo";`,
expected: `import * as foo from "deno-npm:foo";
import foo2 from "deno-npm:foo";
import { bar } from "deno-npm:foo";
import baz, { bar2 } from "deno-npm:foo";`,
});
});
Deno.test("npm workaround - export declaration", () => {
runTest({
input: `export * as foo from "npm:foo";
export { bar } from "npm:foo";`,
expected: `export * as foo from "deno-npm:foo";
export { bar } from "deno-npm:foo";`,
});
});
Deno.test("npm workaround - import()", () => {
runTest({
input: `import("npm:foo");
import("npm:foo", { type: "json" })`,
expected: `import("deno-npm:foo");
import("deno-npm:foo", {
type: "json"
});`,
});
});
+24 -3
View File
@@ -1,18 +1,39 @@
import type { Plugin } from "vite";
import * as babel from "@babel/core";
import { npmWorkaround } from "./npm_workaround.ts";
import { cjsPlugin } from "./patches/commonjs.ts";
import { jsxComments } from "./patches/jsx_comment.ts";
import babelReact from "@babel/preset-react";
export function patches(): Plugin {
let isDev = false;
return {
name: "fresh:patches",
config(_, env) {
isDev = env.command === "serve";
},
applyToEnvironment() {
return true;
},
transform(code, id) {
transform(code, id, options) {
if (code.includes("__commonJS") || /\.(tsx?|m[jt]s)$/.test(id)) {
return;
}
const presets = [];
if (!options?.ssr) {
presets.push([babelReact, {
runtime: "automatic",
importSource: "preact",
development: isDev,
}]);
}
const res = babel.transformSync(code, {
filename: id,
babelrc: false,
plugins: [npmWorkaround],
plugins: [cjsPlugin, jsxComments],
presets,
});
if (res?.code) {
@@ -0,0 +1,340 @@
import type { types } from "@babel/core";
export function cjsPlugin(
{ types: t }: { types: typeof types },
): babel.PluginObj {
const HAS_ES_MODULE = "esModule";
const REQUIRE_CALLS = "requireCalls";
const ROOT_SCOPE = "rootScope";
const EXPORTED = "exported";
return {
name: "fresh-cjs-esm",
visitor: {
Program: {
enter(path, state) {
state.set(ROOT_SCOPE, path.scope);
state.set(EXPORTED, new Set<string>());
},
exit(path, state) {
const body = path.get("body");
const requires = state.get(REQUIRE_CALLS);
if (requires !== undefined) {
for (let i = 0; i < requires.length; i++) {
const { specifier, id } = requires[i];
path.unshiftContainer(
"body",
t.importDeclaration(
[t.importNamespaceSpecifier(id)],
specifier,
),
);
}
}
const exported = state.get(EXPORTED);
if (exported.size > 0) {
path.unshiftContainer(
"body",
t.variableDeclaration("var", [
t.variableDeclarator(
t.identifier("exports"),
t.objectExpression([]),
),
t.variableDeclarator(
t.identifier("module"),
t.objectExpression([
t.objectProperty(
t.identifier("exports"),
t.identifier("exports"),
false,
true,
),
]),
),
]),
);
}
const exportNamed = new Map<string, string>();
const idExports: types.ExportSpecifier[] = [];
for (const name of exported) {
if (name === "default") {
exportNamed.set(name, name);
continue;
}
const id = path.scope.generateUidIdentifier(name);
exportNamed.set(id.name, name);
path.pushContainer(
"body",
t.variableDeclaration(
"var",
[t.variableDeclarator(
id,
t.memberExpression(
t.identifier("exports"),
t.identifier(name),
),
)],
),
);
idExports.push(
t.exportSpecifier(id, t.identifier(name)),
);
}
if (idExports.length > 0) {
path.pushContainer(
"body",
t.exportNamedDeclaration(null, idExports),
);
}
if (exportNamed.size > 0) {
const id = path.scope.generateUidIdentifier("__default");
path.pushContainer(
"body",
t.variableDeclaration("const", [
t.variableDeclarator(
id,
t.logicalExpression(
"??",
t.logicalExpression(
"??",
t.memberExpression(
t.memberExpression(
t.identifier("module"),
t.identifier("exports"),
),
t.identifier("default"),
),
t.memberExpression(
t.identifier("exports"),
t.identifier("default"),
),
),
t.memberExpression(
t.identifier("module"),
t.identifier("exports"),
),
),
),
]),
);
for (const [local, exported] of exportNamed.entries()) {
if (exported === "default") continue;
path.pushContainer(
"body",
t.expressionStatement(
t.assignmentExpression(
"=",
t.memberExpression(id, t.identifier(exported)),
t.identifier(local),
),
),
);
}
path.pushContainer("body", t.exportDefaultDeclaration(id));
}
if (body.length === 0 && state.get(HAS_ES_MODULE)) {
path.pushContainer("body", t.exportNamedDeclaration(null));
}
},
},
CallExpression(path, state) {
const exported = state.get(EXPORTED);
if (isObjEsModuleFlag(t, path.node)) {
state.set(HAS_ES_MODULE, true);
path.remove();
return;
}
if (
t.isIdentifier(path.node.callee) &&
path.node.callee.name === "require"
) {
const root = state.get(ROOT_SCOPE);
const id = root.generateUidIdentifier("mod");
const mods = state.get(REQUIRE_CALLS) ?? [];
state.set(REQUIRE_CALLS, mods);
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),
),
);
return;
}
path.replaceWith(t.cloneNode(id, true));
} else if (
t.isMemberExpression(path.node.callee) &&
t.isIdentifier(path.node.callee.object) &&
path.node.callee.object.name === "Object" &&
t.isIdentifier(path.node.callee.property) &&
path.node.callee.property.name === "defineProperty" &&
path.node.arguments.length > 0 &&
t.isIdentifier(path.node.arguments[0]) &&
path.node.arguments[0].name === "exports" &&
t.isStringLiteral(path.node.arguments[1])
) {
const name = path.node.arguments[1].value;
exported.add(name);
}
},
EmptyStatement(path) {
path.remove();
},
MemberExpression: {
exit(path, state) {
if (
t.isIdentifier(path.node.object) &&
path.node.object.name === "exports" &&
t.isIdentifier(path.node.property)
) {
const name = t.cloneNode(path.node.property);
if (name.name === "__esModule") return;
state.get(EXPORTED).add(name.name);
}
},
},
ExpressionStatement: {
enter(path) {
if (
t.isExpressionStatement(path.node) &&
t.isCallExpression(path.node.expression) &&
t.isIdentifier(path.node.expression.callee) &&
path.node.expression.callee.name === "__exportStar" &&
path.node.expression.arguments.length > 0 &&
t.isCallExpression(path.node.expression.arguments[0]) &&
t.isIdentifier(path.node.expression.arguments[0].callee) &&
path.node.expression.arguments[0].callee.name === "require" &&
t.isStringLiteral(path.node.expression.arguments[0].arguments[0])
) {
const spec = t.cloneNode(
path.node.expression.arguments[0].arguments[0],
true,
);
path.replaceWith(t.exportAllDeclaration(spec));
}
},
exit(path, state) {
const exported = state.get(EXPORTED);
const expr = path.get("expression");
if (expr.isAssignmentExpression()) {
const left = expr.get("left");
if (isEsModuleFlag(t, expr.node)) {
state.set(HAS_ES_MODULE, true);
path.remove();
} else if (left.isMemberExpression()) {
if (isModuleExports(t, left.node)) {
exported.add("default");
} else {
const named = getExportsAssignName(t, left.node);
if (named === null) return;
exported.add(named);
}
}
} else if (expr.isCallExpression()) {
if (isObjEsModuleFlag(t, expr.node)) {
state.set(HAS_ES_MODULE, true);
path.remove();
}
}
},
},
},
};
}
function isModuleExports(
t: typeof types,
node: types.MemberExpression,
): boolean {
return t.isIdentifier(node.object) && node.object.name === "module" &&
t.isIdentifier(node.property) && node.property.name === "exports";
}
function getExportsAssignName(
t: typeof types,
node: types.MemberExpression,
): string | null {
if (
(t.isMemberExpression(node.object) &&
isModuleExports(t, node.object) ||
t.isIdentifier(node.object) && node.object.name === "exports") &&
t.isIdentifier(node.property)
) {
return node.property.name;
}
return null;
}
/**
* Detect `exports.__esModule = true;`
*/
function isEsModuleFlag(
t: typeof types,
node: types.AssignmentExpression,
): boolean {
if (!t.isMemberExpression(node.left)) return false;
const { left, right } = node;
return (t.isMemberExpression(left.object) &&
isModuleExports(t, left.object) ||
t.isIdentifier(left.object) && left.object.name === "exports") &&
t.isIdentifier(left.property) && left.property.name === "__esModule" &&
t.isBooleanLiteral(right);
}
/**
* Check for `Object.defineProperty(exports, '__esModule', { value: true })`
*/
function isObjEsModuleFlag(
t: typeof types,
node: types.CallExpression,
): boolean {
return t.isMemberExpression(node.callee) &&
t.isIdentifier(node.callee.object) &&
node.callee.object.name === "Object" &&
t.isIdentifier(node.callee.property) &&
node.callee.property.name === "defineProperty" &&
node.arguments.length === 3 &&
(t.isMemberExpression(node.arguments[0]) &&
isModuleExports(t, node.arguments[0]) ||
t.isIdentifier(node.arguments[0]) &&
node.arguments[0].name === "exports") &&
t.isStringLiteral(node.arguments[1]) &&
node.arguments[1].value === "__esModule" &&
t.isObjectExpression(node.arguments[2]);
}
@@ -1,6 +1,6 @@
import { expect } from "@std/expect/expect";
import * as babel from "@babel/core";
import { cjsPlugin } from "./commonjs.ts";
import { cjsPlugin } from "../patches/commonjs.ts";
function runTest(options: { input: string; expected: string }) {
const res = babel.transformSync(options.input, {
@@ -13,17 +13,32 @@ function runTest(options: { input: string; expected: string }) {
expect(output).toEqual(options.expected);
}
const INIT = `var exports = {},
module = {
exports
};`;
const DEFAULT_EXPORT =
`const _default = module.exports.default ?? exports.default ?? module.exports;`;
const DEFAULT_EXPORT_END = `export default _default;`;
Deno.test("commonjs - module.exports default", () => {
runTest({
input: `module.exports = async function () {};`,
expected: "export default (async function () {});",
expected: `${INIT}
module.exports = async function () {};
${DEFAULT_EXPORT}
${DEFAULT_EXPORT_END}`,
});
});
Deno.test("commonjs - module.exports default primitive", () => {
runTest({
input: `module.exports = 42;`,
expected: "export default 42;",
expected: `${INIT}
module.exports = 42;
${DEFAULT_EXPORT}
${DEFAULT_EXPORT_END}`,
});
});
@@ -32,8 +47,14 @@ Deno.test("commonjs - exports with default + named", () => {
input: `exports.__esModule = true;
exports.default = 'x';
exports.foo = 'foo';`,
expected: `export default 'x';
export let foo = 'foo';`,
expected: `${INIT}
exports.default = 'x';
exports.foo = 'foo';
var _foo = exports.foo;
export { _foo as foo };
${DEFAULT_EXPORT}
_default.foo = _foo;
${DEFAULT_EXPORT_END}`,
});
});
@@ -42,8 +63,14 @@ Deno.test("commonjs - module.exports with default + named", () => {
input: `module.exports.__esModule = true;
module.exports.default = 'x';
module.exports.foo = 'foo';`,
expected: `export default 'x';
export let foo = 'foo';`,
expected: `${INIT}
module.exports.default = 'x';
module.exports.foo = 'foo';
var _foo = exports.foo;
export { _foo as foo };
${DEFAULT_EXPORT}
_default.foo = _foo;
${DEFAULT_EXPORT_END}`,
});
});
@@ -53,8 +80,14 @@ Deno.test("commonjs - Object es module flag with named clash", () => {
exports.foo = 'bar';
const foo = 'also bar';
`,
expected: `export let foo = 'bar';
const _foo = 'also bar';`,
expected: `${INIT}
exports.foo = 'bar';
const foo = 'also bar';
var _foo = exports.foo;
export { _foo as foo };
${DEFAULT_EXPORT}
_default.foo = _foo;
${DEFAULT_EXPORT_END}`,
});
});
@@ -64,8 +97,14 @@ Deno.test("commonjs - Object es module flag with named + default", () => {
exports.default = 'foo';
exports.foo = 'bar';
`,
expected: `export default 'foo';
export let foo = 'bar';`,
expected: `${INIT}
exports.default = 'foo';
exports.foo = 'bar';
var _foo = exports.foo;
export { _foo as foo };
${DEFAULT_EXPORT}
_default.foo = _foo;
${DEFAULT_EXPORT_END}`,
});
});
@@ -97,8 +136,16 @@ Deno.test("commonjs - exports only named", () => {
exports.foo = 'bar';
exports.bar = 'foo';
`,
expected: `export let foo = 'bar';
export let bar = 'foo';`,
expected: `${INIT}
exports.foo = 'bar';
exports.bar = 'foo';
var _foo = exports.foo;
var _bar = exports.bar;
export { _foo as foo, _bar as bar };
${DEFAULT_EXPORT}
_default.foo = _foo;
_default.bar = _bar;
${DEFAULT_EXPORT_END}`,
});
});
@@ -170,7 +217,14 @@ Deno.test("commonjs - duplicate exports", () => {
input: `Object.defineProperty(exports, "__esModule", { value: true });
exports.trace = void 0;
exports.trace = 'foo'`,
expected: `export let trace = 'foo';`,
expected: `${INIT}
exports.trace = void 0;
exports.trace = 'foo';
var _trace = exports.trace;
export { _trace as trace };
${DEFAULT_EXPORT}
_default.trace = _trace;
${DEFAULT_EXPORT_END}`,
});
});
@@ -179,7 +233,16 @@ Deno.test("commonjs - cleared exports", () => {
input: `Object.defineProperty(exports, "__esModule", { value: true });
exports.foo = exports.bar = void 0;
exports.foo = 'foo'`,
expected: `export let 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 };
${DEFAULT_EXPORT}
_default.foo = _foo;
_default.bar = _bar;
${DEFAULT_EXPORT_END}`,
});
});
@@ -187,11 +250,20 @@ Deno.test("commonjs - define exports", () => {
runTest({
input: `var utils_1 = require("./bar");
Object.defineProperty(exports, "foo", { enumerable: true, get: function () { return utils_1.foo; } });`,
expected: `import * as _mod from "./bar";
expected: `${INIT}
import * as _mod from "./bar";
var utils_1 = _mod.default ?? _mod;
export let foo = (function () {
return utils_1.foo;
})();`,
Object.defineProperty(exports, "foo", {
enumerable: true,
get: function () {
return utils_1.foo;
}
});
var _foo = exports.foo;
export { _foo as foo };
${DEFAULT_EXPORT}
_default.foo = _foo;
${DEFAULT_EXPORT_END}`,
});
});
@@ -199,11 +271,20 @@ Deno.test("commonjs - define exports #2", () => {
runTest({
input: `var utils_1 = require("./bar");
Object.defineProperty(exports, "foo", { enumerable: true, get() { return utils_1.foo; } });`,
expected: `import * as _mod from "./bar";
expected: `${INIT}
import * as _mod from "./bar";
var utils_1 = _mod.default ?? _mod;
export let foo = (function () {
return utils_1.foo;
})();`,
Object.defineProperty(exports, "foo", {
enumerable: true,
get() {
return utils_1.foo;
}
});
var _foo = exports.foo;
export { _foo as foo };
${DEFAULT_EXPORT}
_default.foo = _foo;
${DEFAULT_EXPORT_END}`,
});
});
@@ -212,17 +293,99 @@ Deno.test("commonjs - define exports #3", () => {
input: `Object.defineProperty(exports, "__esModule", { value: true });
exports._globalThis = void 0;
exports._globalThis = typeof globalThis === 'object' ? globalThis : global;`,
expected:
`export let _globalThis = typeof globalThis === 'object' ? globalThis : global;`,
expected: `${INIT}
exports._globalThis = void 0;
exports._globalThis = typeof globalThis === 'object' ? globalThis : global;
var _globalThis = exports._globalThis;
export { _globalThis };
${DEFAULT_EXPORT}
_default._globalThis = _globalThis;
${DEFAULT_EXPORT_END}`,
});
});
// I've never seen this, seems rare. Skipping for now.
Deno.test.ignore("commonjs - require", () => {
Deno.test("commonjs - named function", () => {
runTest({
input: `Object.defineProperty(exports, "__esModule", { value: true });
function foo() {};
exports.foo = foo;`,
expected: `${INIT}
function foo() {}
exports.foo = foo;
var _foo = exports.foo;
export { _foo as foo };
${DEFAULT_EXPORT}
_default.foo = _foo;
${DEFAULT_EXPORT_END}`,
});
});
Deno.test("commonjs - detect esbuild shims", () => {
runTest({
input: `__exportStar(require("./globalThis"), exports);`,
expected: `export * from "./globalThis";`,
});
});
Deno.test("commonjs - exports.default", () => {
runTest({
input: `exports.default = {}`,
expected: `${INIT}
exports.default = {};
${DEFAULT_EXPORT}
${DEFAULT_EXPORT_END}`,
});
});
Deno.test("commonjs - multiple same name", () => {
runTest({
input: `exports.VERSION = void 0;
exports.VERSION = '1.9.0';`,
expected: `${INIT}
exports.VERSION = void 0;
exports.VERSION = '1.9.0';
var _VERSION = exports.VERSION;
export { _VERSION as VERSION };
${DEFAULT_EXPORT}
_default.VERSION = _VERSION;
${DEFAULT_EXPORT_END}`,
});
});
Deno.test("commonjs - export enum", () => {
runTest({
input: `Object.defineProperty(exports, "__esModule", { value: true });
exports.DiagLogLevel = void 0;
var DiagLogLevel;
(function (DiagLogLevel) {
DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL";
})(DiagLogLevel = exports.DiagLogLevel || (exports.DiagLogLevel = {}));`,
expected: `${INIT}
exports.DiagLogLevel = void 0;
var DiagLogLevel;
(function (DiagLogLevel) {
DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL";
})(DiagLogLevel = exports.DiagLogLevel || (exports.DiagLogLevel = {}));
var _DiagLogLevel = exports.DiagLogLevel;
export { _DiagLogLevel as DiagLogLevel };
${DEFAULT_EXPORT}
_default.DiagLogLevel = _DiagLogLevel;
${DEFAULT_EXPORT_END}`,
});
});
Deno.test("commonjs - require", () => {
runTest({
input: `module.exports = { __esModule: true, default: { foo: 'bar' }}`,
expected: `import * as foo from "tape";
console.log(foo)`,
expected: `${INIT}
module.exports = {
__esModule: true,
default: {
foo: 'bar'
}
};
${DEFAULT_EXPORT}
${DEFAULT_EXPORT_END}`,
});
});
@@ -232,7 +395,14 @@ Deno.test.ignore("commonjs - export default object", () => {
input: `Object.defineProperty(exports, '__esModule', { value: true });
module.exports = { foo: 'bar' };
`,
expected: `export let foo = 'bar';
export let bar = 'foo';`,
expected: `${INIT}
module.exports = {
foo: 'bar'
};
var _foo = module.exports.foo;
export let foo = _foo;
${DEFAULT_EXPORT}
_default.foo = _foo;
${DEFAULT_EXPORT_END}`,
});
});
@@ -0,0 +1,19 @@
import type { types } from "@babel/core";
export function jsxComments(): babel.PluginObj {
return {
name: "fresh-jsx-comment",
visitor: {
Program(path) {
const comments = (path.parent as types.File).comments;
if (comments) {
for (let i = 0; i < comments.length; i++) {
const comment = comments[i];
comment.value = comment.value.replaceAll(/@jsx\w+\s+[^\s*]+/g, "");
}
}
},
},
};
}
@@ -0,0 +1,22 @@
import { expect } from "@std/expect/expect";
import * as babel from "@babel/core";
import { jsxComments } from "./jsx_comment.ts";
function runTest(options: { input: string; expected: string }) {
const res = babel.transformSync(options.input, {
filename: "foo.js",
babelrc: false,
plugins: [jsxComments],
});
const output = res?.code ?? "";
expect(output).toEqual(options.expected);
}
Deno.test("jsx comments - import declaration", () => {
runTest({
input:
`/** @jsxRuntime classic */ /** @jsxImportSource npm:preact@^10.27.0 */ /** @jsxImportSourceTypes npm:preact@^10.27.0 */ /** @jsxFactory React.createElement */ /** @jsxFragmentFactory React.Fragment */ foo;`,
expected: `/** */ /** */ /** */ /** */ /** */foo;`,
});
});
@@ -172,6 +172,10 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
fsRoutesFiles: result.routes,
islands: islandMods,
writeSpecifier: (file) => {
const def = islands.get(file);
if (def) {
return `fresh-island::${def.name}`;
}
return path.toFileUrl(file).href;
},
});