chore: update to vite's hook filter (#3333)

Fixes https://github.com/denoland/fresh/issues/3331
This commit is contained in:
Marvin Hagemeister
2025-09-04 11:16:06 +02:00
committed by GitHub
parent baf774517b
commit b94aab2a1a
10 changed files with 432 additions and 418 deletions
+7 -4
View File
@@ -26,14 +26,17 @@ export function buildIdPlugin(): Plugin {
return `\0fresh/build-id`;
}
},
load(id) {
if (id !== `\0fresh/build-id`) return;
return `export let BUILD_ID = ${JSON.stringify(buildId)};
load: {
filter: {
id: /\0fresh\/build-id/,
},
handler() {
return `export let BUILD_ID = ${JSON.stringify(buildId)};
export const DENO_DEPLOYMENT_ID = undefined;
export function setBuildId(id) {
BUILD_ID = id;
}`;
},
},
};
}
@@ -19,25 +19,32 @@ export function clientEntryPlugin(options: ResolvedFreshViteConfig): Plugin {
configResolved(config) {
clientEntry = pathWithRoot(options.clientEntry, config.root);
},
resolveId(id) {
if (id === modName) {
return `\0${modName}`;
} else if (id === modNameUser) {
return clientEntry;
}
resolveId: {
filter: {
id: /(fresh:client-entry|fresh:client-entry-user)/,
},
handler(id) {
if (id === modName) {
return `\0${modName}`;
} else if (id === modNameUser) {
return clientEntry;
}
},
},
async load(id) {
if (id !== `\0${modName}`) return;
load: {
filter: {
id: /\0fresh:client-entry/,
},
async handler() {
let exists = false;
try {
const stat = await Deno.stat(clientEntry);
exists = stat.isFile;
} catch {
exists = false;
}
let exists = false;
try {
const stat = await Deno.stat(clientEntry);
exists = stat.isFile;
} catch {
exists = false;
}
return `
return `
${isDev ? 'import "preact/debug"' : ""}
export * from "fresh/runtime-client";
${exists ? `import "fresh:client-entry-user";` : ""}
@@ -52,6 +59,7 @@ if (import.meta.hot) {
});
}
`;
},
},
};
}
@@ -48,37 +48,47 @@ export function clientSnapshot(options: ResolvedFreshViteConfig): Plugin {
islands.add(filePath);
}
},
resolveId(id) {
if (id === modName) {
return `\0${modName}`;
}
},
configureServer(devServer) {
server = devServer;
},
load(id) {
if (id !== `\0${modName}`) return;
const imports = Array.from(islands.keys()).map((file, i) => {
return `export const mod_${i} = await import(${JSON.stringify(file)});`;
}).join("\n");
if (isDev && server !== undefined) {
const mod = server.environments.ssr.moduleGraph.getModuleById(
"\0fresh:server-snapshot",
);
if (mod) {
server.environments.ssr.moduleGraph.invalidateModule(mod);
resolveId: {
filter: {
id: /fresh:client-snapshot/,
},
handler(id) {
if (id === modName) {
return `\0${modName}`;
}
}
},
},
load: {
filter: {
id: /\0fresh:client-snapshot/,
},
handler() {
const imports = Array.from(islands.keys()).map((file, i) => {
return `export const mod_${i} = await import(${
JSON.stringify(file)
});`;
}).join("\n");
return `${imports}
if (isDev && server !== undefined) {
const mod = server.environments.ssr.moduleGraph.getModuleById(
"\0fresh:server-snapshot",
);
if (mod) {
server.environments.ssr.moduleGraph.invalidateModule(mod);
}
}
return `${imports}
if (import.meta.hot) {
import.meta.hot.accept(() => {
console.log("accepting client-snapshot")
});
}
`;
},
},
};
}
+41 -31
View File
@@ -10,7 +10,7 @@ import * as path from "@std/path";
import * as babel from "@babel/core";
import babelReact from "@babel/preset-react";
import { httpAbsolute } from "./patches/http_absolute.ts";
import { JS_REG } from "../utils.ts";
import { JS_REG, JSX_REG } from "../utils.ts";
interface DenoState {
type: RequestedModuleType;
@@ -210,40 +210,50 @@ export function deno(): Plugin {
code,
};
},
async transform(_, id, options) {
// This transform is a hack to be able to re-use Deno's precompile
// jsx transform.
if (!options?.ssr || !id.endsWith(".tsx") || id.endsWith(".jsx")) {
return;
}
transform: {
filter: {
id: JSX_REG,
},
async handler(_, id, options) {
// This transform is a hack to be able to re-use Deno's precompile
// jsx transform.
if (!options?.ssr) {
return;
}
let actualId = id;
if (isDenoSpecifier(id)) {
const { specifier } = parseDenoSpecifier(id);
actualId = specifier;
}
if (path.isAbsolute(actualId)) {
actualId = path.toFileUrl(actualId).href;
}
let actualId = id;
if (isDenoSpecifier(id)) {
const { specifier } = parseDenoSpecifier(id);
actualId = specifier;
}
actualId = actualId.replace("?commonjs-es-import", "");
const resolved = await ssrLoader.resolve(
actualId,
undefined,
ResolutionMode.Import,
);
const result = await ssrLoader.load(
resolved,
RequestedModuleType.Default,
);
if (result.kind === "external") {
return;
}
if (actualId.startsWith("\0")) {
actualId = actualId.slice(1);
}
if (path.isAbsolute(actualId)) {
actualId = path.toFileUrl(actualId).href;
}
const code = new TextDecoder().decode(result.code);
const resolved = await ssrLoader.resolve(
actualId,
undefined,
ResolutionMode.Import,
);
const result = await ssrLoader.load(
resolved,
RequestedModuleType.Default,
);
if (result.kind === "external") {
return;
}
return {
code,
};
const code = new TextDecoder().decode(result.code);
return {
code,
};
},
},
};
}
+38 -35
View File
@@ -19,45 +19,48 @@ export function patches(): Plugin {
applyToEnvironment() {
return true;
},
transform(code, id, options) {
if (!JS_REG.test(id)) return;
transform: {
filter: {
id: JS_REG,
},
handler(code, id, options) {
const presets = [];
if (!options?.ssr && JSX_REG.test(id)) {
presets.push([babelReact, {
runtime: "automatic",
importSource: "preact",
development: isDev,
}]);
}
const presets = [];
if (!options?.ssr && JSX_REG.test(id)) {
presets.push([babelReact, {
runtime: "automatic",
importSource: "preact",
development: isDev,
}]);
}
const plugins: babel.PluginItem[] = [
cjsPlugin,
removePolyfills,
jsxComments,
inlineEnvVarsPlugin(
isDev ? "development" : "production",
),
];
const plugins: babel.PluginItem[] = [
cjsPlugin,
removePolyfills,
jsxComments,
inlineEnvVarsPlugin(
isDev ? "development" : "production",
),
];
if (!options?.ssr) {
plugins.push(denoGlobal);
}
if (!options?.ssr) {
plugins.push(denoGlobal);
}
const res = babel.transformSync(code, {
filename: id,
babelrc: false,
compact: true,
plugins,
presets,
});
const res = babel.transformSync(code, {
filename: id,
babelrc: false,
compact: true,
plugins,
presets,
});
if (res?.code) {
return {
code: res.code,
map: res.map,
};
}
if (res?.code) {
return {
code: res.code,
map: res.map,
};
}
},
},
};
}
@@ -39,21 +39,28 @@ export function serverEntryPlugin(
config.root,
);
},
resolveId(id) {
if (id === modName) {
return `\0${modName}`;
}
resolveId: {
filter: {
id: /fresh:server_entry/,
},
handler(id) {
if (id === modName) {
return `\0${modName}`;
}
},
},
load(id) {
if (id !== `\0${modName}`) return;
load: {
filter: {
id: /\0fresh:server_entry/,
},
handler() {
let code = generateServerEntry({
root: isDev ? path.relative(serverOutDir, root) : "..",
serverEntry: path.toFileUrl(serverEntry).href,
snapshotSpecifier: "fresh:server-snapshot",
});
let code = generateServerEntry({
root: isDev ? path.relative(serverOutDir, root) : "..",
serverEntry: path.toFileUrl(serverEntry).href,
snapshotSpecifier: "fresh:server-snapshot",
});
code += `
code += `
export function registerStaticFile(prepared) {
snapshot.staticFiles.set(prepared.name, {
@@ -64,13 +71,14 @@ export function registerStaticFile(prepared) {
}
`;
if (isDev) {
code = `import "preact/debug";
if (isDev) {
code = `import "preact/debug";
${code}
if (import.meta.hot) import.meta.hot.accept();`;
}
}
return code;
return code;
},
},
async writeBundle(_options, bundle) {
const manifest = bundle[".vite/manifest.json"];
@@ -111,202 +111,214 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
viteServer.ws.send("fresh:reload");
});
},
resolveId(id) {
if (id === modName) {
return `\0${modName}`;
}
resolveId: {
filter: {
id: /fresh:server-snapshot/,
},
handler(id) {
if (id === modName) {
return `\0${modName}`;
}
},
},
async load(id) {
if (id !== `\0${modName}`) return;
load: {
filter: {
id: /\0fresh:server-snapshot/,
},
const result = await crawlFsItem({
islandDir: options.islandsDir,
routeDir: options.routeDir,
ignore: options.ignore,
});
for (let i = 0; i < result.islands.length; i++) {
const spec = result.islands[i];
const specName = specToName(spec);
const name = options.namer.getUniqueName(specName);
islands.set(spec, { name, chunk: null });
islandSpecByName.set(name, spec);
islandsByFile.add(spec);
}
const staticFiles: PendingStaticFile[] = [];
let islandMods: IslandModChunk[] = [];
let clientEntry = "/@id/fresh:client-entry";
let buildId = "";
const entryAssets: string[] = [];
if (isDev && server !== undefined) {
for (const id of islands.keys()) {
const mod = server.environments.client.moduleGraph.getModuleById(
id,
);
if (mod !== undefined) {
const def = islands.get(id);
if (def !== undefined) def.chunk = mod.url;
}
}
islandMods = Array.from(islands.entries()).map(([id, def]) => {
return {
name: def.name,
server: id,
browser: def.chunk ?? `/@id/fresh-island::${def.name}`,
css: [],
};
async handler() {
const result = await crawlFsItem({
islandDir: options.islandsDir,
routeDir: options.routeDir,
ignore: options.ignore,
});
} else {
buildId = await getBuildId(false);
const manifest = JSON.parse(
await Deno.readTextFile(
path.join(clientOutDir, ".vite", "manifest.json"),
),
) as Manifest;
const resolvedIslandSpecs = new Map<string, string>();
for (const spec of options.islandSpecifiers.keys()) {
const resolved = await this.resolve(spec);
for (let i = 0; i < result.islands.length; i++) {
const spec = result.islands[i];
const specName = specToName(spec);
const name = options.namer.getUniqueName(specName);
if (resolved === null) continue;
const id = resolved.id.startsWith("\0")
? resolved.id.slice(1)
: resolved.id;
resolvedIslandSpecs.set(id, spec);
islands.set(spec, { name, chunk: null });
islandSpecByName.set(name, spec);
islandsByFile.add(spec);
}
const clientEntryName = "client-entry";
const staticFiles: PendingStaticFile[] = [];
let islandMods: IslandModChunk[] = [];
let clientEntry = "/@id/fresh:client-entry";
let buildId = "";
const entryAssets: string[] = [];
for (const chunk of Object.values(manifest)) {
if (chunk.name === clientEntryName) {
clientEntry = pathToSpec(clientOutDir, chunk.file);
if (isDev && server !== undefined) {
for (const id of islands.keys()) {
const mod = server.environments.client.moduleGraph.getModuleById(
id,
);
if (mod !== undefined) {
const def = islands.get(id);
if (def !== undefined) def.chunk = mod.url;
}
}
staticFiles.push({
filePath: path.join(clientOutDir, chunk.file),
pathname: chunk.file,
hash: null,
islandMods = Array.from(islands.entries()).map(([id, def]) => {
return {
name: def.name,
server: id,
browser: def.chunk ?? `/@id/fresh-island::${def.name}`,
css: [],
};
});
} else {
buildId = await getBuildId(false);
const manifest = JSON.parse(
await Deno.readTextFile(
path.join(clientOutDir, ".vite", "manifest.json"),
),
) as Manifest;
const resolvedIslandSpecs = new Map<string, string>();
if (chunk.css !== undefined) {
for (let i = 0; i < chunk.css.length; i++) {
const id = chunk.css[i];
for (const spec of options.islandSpecifiers.keys()) {
const resolved = await this.resolve(spec);
const pathname = `/${id}`;
if (resolved === null) continue;
staticFiles.push({
filePath: path.join(clientOutDir, id),
hash: null,
pathname,
});
const id = resolved.id.startsWith("\0")
? resolved.id.slice(1)
: resolved.id;
if (chunk.name === clientEntryName) {
entryAssets.push(pathname);
}
}
resolvedIslandSpecs.set(id, spec);
}
const namer = new UniqueNamer();
if (chunk.name === "client-snapshot") {
for (const id of chunk.dynamicImports ?? []) {
const mod = manifest[id];
const clientEntryName = "client-entry";
let serverPath = path.join(root, mod.src ?? id);
const idx = mod.src?.indexOf("deno::") ?? -1;
if (idx > -1 && mod.src) {
const src = mod.src
.slice(idx)
.replace(
/(https?):\/([^/])/,
(_m, protocol, rest) => {
return `${protocol}://${rest}`;
},
);
serverPath = resolvedIslandSpecs.get(src)!;
}
let spec = pathToSpec(clientOutDir, mod.file);
if (spec.startsWith("./")) {
spec = spec.slice(1);
}
const chunkCss = mod.css?.map((id) => `/${id}`) ?? [];
const name = namer.getUniqueName(specToName(id));
islandMods.push({
name,
browser: spec,
server: serverPath,
css: chunkCss,
});
for (const chunk of Object.values(manifest)) {
if (chunk.name === clientEntryName) {
clientEntry = pathToSpec(clientOutDir, chunk.file);
}
}
}
if (await fsAdapter.isDirectory(publicDir)) {
const entries = await fsAdapter.walk(
publicDir,
{
followSymlinks: false,
includeDirs: false,
includeFiles: true,
skip: options.ignore,
},
);
for await (const entry of entries) {
const relative = path.relative(publicDir, entry.path);
const filePath = path.join(clientOutDir, relative);
try {
await Deno.mkdir(path.dirname(filePath), { recursive: true });
} catch (err) {
if (!(err instanceof Deno.errors.AlreadyExists)) {
throw err;
}
}
await Deno.copyFile(entry.path, filePath);
staticFiles.push({
filePath,
filePath: path.join(clientOutDir, chunk.file),
pathname: chunk.file,
hash: null,
pathname: relative,
});
if (chunk.css !== undefined) {
for (let i = 0; i < chunk.css.length; i++) {
const id = chunk.css[i];
const pathname = `/${id}`;
staticFiles.push({
filePath: path.join(clientOutDir, id),
hash: null,
pathname,
});
if (chunk.name === clientEntryName) {
entryAssets.push(pathname);
}
}
}
const namer = new UniqueNamer();
if (chunk.name === "client-snapshot") {
for (const id of chunk.dynamicImports ?? []) {
const mod = manifest[id];
let serverPath = path.join(root, mod.src ?? id);
const idx = mod.src?.indexOf("deno::") ?? -1;
if (idx > -1 && mod.src) {
const src = mod.src
.slice(idx)
.replace(
/(https?):\/([^/])/,
(_m, protocol, rest) => {
return `${protocol}://${rest}`;
},
);
serverPath = resolvedIslandSpecs.get(src)!;
}
let spec = pathToSpec(clientOutDir, mod.file);
if (spec.startsWith("./")) {
spec = spec.slice(1);
}
const chunkCss = mod.css?.map((id) => `/${id}`) ?? [];
const name = namer.getUniqueName(specToName(id));
islandMods.push({
name,
browser: spec,
server: serverPath,
css: chunkCss,
});
}
}
}
if (await fsAdapter.isDirectory(publicDir)) {
const entries = await fsAdapter.walk(
publicDir,
{
followSymlinks: false,
includeDirs: false,
includeFiles: true,
skip: options.ignore,
},
);
for await (const entry of entries) {
const relative = path.relative(publicDir, entry.path);
const filePath = path.join(clientOutDir, relative);
try {
await Deno.mkdir(path.dirname(filePath), { recursive: true });
} catch (err) {
if (!(err instanceof Deno.errors.AlreadyExists)) {
throw err;
}
}
await Deno.copyFile(entry.path, filePath);
staticFiles.push({
filePath,
hash: null,
pathname: relative,
});
}
}
}
}
const code = await generateSnapshotServer({
outDir: path.join(clientOutDir, ".."),
staticFiles,
buildId,
clientEntry,
entryAssets,
fsRoutesFiles: result.routes,
islands: islandMods,
writeSpecifier: (file) => {
const def = islands.get(file);
if (def) {
return `fresh-island::${def.name}`;
}
return path.toFileUrl(file).href;
},
});
const code = await generateSnapshotServer({
outDir: path.join(clientOutDir, ".."),
staticFiles,
buildId,
clientEntry,
entryAssets,
fsRoutesFiles: result.routes,
islands: islandMods,
writeSpecifier: (file) => {
const def = islands.get(file);
if (def) {
return `fresh-island::${def.name}`;
}
return path.toFileUrl(file).href;
},
});
return code;
return code;
},
},
}, {
name: "fresh:island-resolver",
resolveId(id) {
if (id.startsWith("fresh-island::")) {
resolveId: {
filter: {
id: /^fresh-island::.*/,
},
handler(id) {
let name = id.slice("fresh-island::".length);
if (JS_REG.test(name)) {
@@ -315,7 +327,7 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
const spec = islandSpecByName.get(name);
if (spec !== undefined) return spec;
}
},
},
}];
}
@@ -51,91 +51,98 @@ export function checkImports(pluginOptions: CheckImportOptions): Plugin {
configResolved(config) {
root = pathWithRoot(config.root);
},
async resolveId(id, importer, options) {
if (
id.startsWith("\0") || id.startsWith("/@fs/") ||
id.startsWith("fresh-island::") || id.startsWith("fresh:") ||
id.includes("node_modules") ||
importer &&
resolveId: {
filter: {
id: [
/^(?!\0|[\\/]@fs[\\/]|fresh-island::|fresh:)/,
/[\\/]node_modules[\\/]/,
],
},
async handler(id, importer, options) {
if (
importer &&
(importer.startsWith("\0") || importer.includes("node_modules") ||
importer.includes("deno::"))
) {
return;
}
const env = options.ssr ? "ssr" : "client";
) {
return;
}
const env = options.ssr ? "ssr" : "client";
let result: ImportCheckDiagnostic | undefined;
if (id.startsWith(".")) {
const resolved = await this.resolve(id, importer, options);
let result: ImportCheckDiagnostic | undefined;
if (id.startsWith(".")) {
const resolved = await this.resolve(id, importer, options);
if (resolved !== null) {
const key = `${env}::${resolved.id}::${importer}`;
if (!seen.has(key)) {
result = check(pluginOptions, resolved.id, env);
if (resolved !== null) {
const key = `${env}::${resolved.id}::${importer}`;
if (!seen.has(key)) {
result = check(pluginOptions, resolved.id, env);
}
seen.add(key);
}
} else {
const key = `${env}::${id}::${importer}`;
if (!seen.has(key)) {
result = check(pluginOptions, id, env);
}
seen.add(key);
}
} else {
const key = `${env}::${id}::${importer}`;
if (!seen.has(key)) {
result = check(pluginOptions, id, env);
}
seen.add(key);
}
if (result) {
const label = result.type === "warn"
? cl.inverse(cl.yellow(` WARN `))
: cl.inverse(cl.red(` ERROR `));
if (result) {
const label = result.type === "warn"
? cl.inverse(cl.yellow(` WARN `))
: cl.inverse(cl.red(` ERROR `));
// deno-lint-ignore no-console
console.log();
// deno-lint-ignore no-console
console.log();
// deno-lint-ignore no-console
console.log(`${label} ${result.message}`);
// deno-lint-ignore no-console
console.log();
// deno-lint-ignore no-console
console.log();
// deno-lint-ignore no-console
console.log();
// deno-lint-ignore no-console
console.log(`${label} ${result.message}`);
// deno-lint-ignore no-console
console.log();
if (importer !== undefined) {
const ancestors = findAncestors(this, importer, isDev);
if (importer !== undefined) {
const ancestors = findAncestors(this, importer, isDev);
if (ancestors && ancestors.length > 0) {
// deno-lint-ignore no-console
console.log(`The specifier ${cl.cyan(`"${id}"`)} was imported in:`);
ancestors.forEach((spec) => {
if (path.isAbsolute(spec)) {
spec = path.relative(root, spec);
}
if (ancestors && ancestors.length > 0) {
// deno-lint-ignore no-console
console.log(` - ${cl.cyan(spec)}`);
});
console.log(
`The specifier ${cl.cyan(`"${id}"`)} was imported in:`,
);
ancestors.forEach((spec) => {
if (path.isAbsolute(spec)) {
spec = path.relative(root, spec);
}
// deno-lint-ignore no-console
console.log(` - ${cl.cyan(spec)}`);
});
// deno-lint-ignore no-console
console.log();
}
}
if (result.hint) {
// deno-lint-ignore no-console
console.log(cl.bold(` hint: `) + result.hint);
// deno-lint-ignore no-console
console.log();
}
}
if (result.hint) {
// deno-lint-ignore no-console
console.log(cl.bold(` hint: `) + result.hint);
// deno-lint-ignore no-console
console.log();
if (result.type === "error") {
this.error({
message: result.message,
id: importer,
});
} else {
this.warn({
message: result.message,
id: importer,
});
}
}
if (result.type === "error") {
this.error({
message: result.message,
id: importer,
});
} else {
this.warn({
message: result.message,
id: importer,
});
}
}
},
},
};
}