feat: Add experimental vite plugin (#3184)

This PR adds a vite plugin for Fresh. This enables:

- HMR (only for islands for now)
- self-contained output bundles for both server and client
- smarter chunking

It uses vite's new Environment API under the hood.
This commit is contained in:
Marvin Hagemeister
2025-08-04 18:30:05 +02:00
committed by GitHub
parent 57596dc406
commit a1571b76ed
54 changed files with 2181 additions and 742 deletions
+4
View File
@@ -42,6 +42,10 @@ jobs:
working-directory: ./update
run: deno publish
- name: Publish @fresh/plugin-vite
working-directory: ./plugin-vite
run: deno publish
- name: Publish @fresh/examples
working-directory: ./examples
run: deno publish
+1
View File
@@ -1,4 +1,5 @@
_fresh/
.vite/
vendor/
node_modules/
.docs/
+13 -2
View File
@@ -5,6 +5,7 @@
"./init",
"./plugin-tailwindcss",
"./plugin-tailwindcss-v3",
"./plugin-vite",
"./update",
"./www"
],
@@ -14,9 +15,12 @@
"exports": {
".": "./src/mod.ts",
"./runtime": "./src/runtime/shared.ts",
"./runtime-client": "./src/runtime/client/mod.tsx",
"./dev": "./src/dev/mod.ts",
"./compat": "./src/compat.ts",
"./do-not-use": "./src/internals.ts"
"./internal": "./src/internals.ts",
"./internal-dev": "./src/internals_dev.ts",
"./build-id": "./src/runtime/build_id.ts"
},
"tasks": {
"test": "deno test -A --parallel",
@@ -30,7 +34,14 @@
"test:www": "deno test -A www/main_test.*",
"release": "deno run -A tools/release.ts"
},
"exclude": ["**/_fresh/*", "**/tmp/*", "*/tests_OLD/**"],
"exclude": [
"**/_fresh/*",
"**/tmp/*",
"*/tests_OLD/**",
"**/vite.config.ts.*",
"*/vite.config.ts.*",
"vite.config.ts.*"
],
"publish": {
"include": [
"src/**",
Generated
+438 -468
View File
File diff suppressed because it is too large Load Diff
+35
View File
@@ -0,0 +1,35 @@
# EXPERIMENTAL: vite plugin for Fresh
> **Warning** This package is experimental. Please report bugs to
> https://github.com/denoland/fresh/issues
## Usage
1. Run `deno install jsr:@fresh/plugin-vite npm:vite`
2. Ensure that your `deno.json` has the `fresh` import mapping:
```json
{
"imports": {
"fresh": "jsr:@fresh/core"
}
}
```
3. Update your `vite.config.ts` file:
```diff
import { defineConfig } from "vite";
+ import { fresh } from "@fresh/plugin-vite";
export default defineConfig({
plugins: [
+ fresh(),
],
});
```
4. Update your deno tasks respectively:
- Dev: `vite`
- Build: `vite build`
+13
View File
@@ -0,0 +1,13 @@
import { useState } from "preact/hooks";
export function Bar() {
const [count, set] = useState(0);
return (
<div>
<h1>island asdf</h1>
<button type="button" onClick={() => set((v) => v + 1)}>
update {count}
</button>
</div>
);
}
+13
View File
@@ -0,0 +1,13 @@
import { useSignal } from "@preact/signals";
export function Foo() {
const count = useSignal(0);
return (
<div>
<h1>island</h1>
<button type="button" onClick={() => count.value++}>
update {count}
</button>
</div>
);
}
@@ -0,0 +1,13 @@
import { useState } from "preact/hooks";
export function CounterHooks() {
const [count, set] = useState(0);
return (
<div class="counter-hooks">
<button type="button" onClick={() => set((v) => v + 1)}>
count: {count}
</button>
</div>
);
}
+7
View File
@@ -0,0 +1,7 @@
import { App, staticFiles, trailingSlashes } from "fresh";
export const app = new App()
.use(staticFiles())
.use(trailingSlashes("never"))
.get("/", () => new Response("it works"))
.fsRoutes();
+17
View File
@@ -0,0 +1,17 @@
import { Bar } from "../islands/Bar.tsx";
import { Foo } from "../islands/Foo.tsx";
export const handler = () => {
return { data: {} };
};
export default function About() {
return (
<div>
<h1>Hello from Vite</h1>
<p>This page is the prod Fresh build and served by vite</p>
<Foo />
<Bar />
</div>
);
}
+3
View File
@@ -0,0 +1,3 @@
export default function Index() {
return <h1>index page2</h1>;
}
@@ -0,0 +1,5 @@
import { CounterHooks } from "../../islands/tests/CounterHooks.tsx";
export default function Page() {
return <CounterHooks />;
}
@@ -0,0 +1,3 @@
export default function Page() {
return <h1>it works</h1>;
}
+1
View File
@@ -0,0 +1 @@
foo
@@ -0,0 +1 @@
it works
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from "vite";
import { fresh } from "@fresh/plugin-vite";
import inspect from "vite-plugin-inspect";
export default defineConfig({
plugins: [
inspect(),
fresh(),
],
});
+26
View File
@@ -0,0 +1,26 @@
{
"name": "@fresh/plugin-vite",
"version": "0.0.1",
"license": "MIT",
"exports": {
".": "./src/mod.ts"
},
"compilerOptions": {
"jsx": "precompile",
"jsxImportSource": "preact"
},
"tasks": {
"demo": "vite demo",
"debug": "deno run -A --inspect-brk npm:vite demo",
"demo:build": "vite build demo",
"demo:start": "cd demo && deno serve -A _fresh/server/server-entry.mjs"
},
"imports": {
"@deno/loader": "jsr:@deno/loader@^0.3.2",
"@prefresh/vite": "npm:@prefresh/vite@^2.4.8",
"@types/node": "npm:@types/node@^24.1.0",
"preact": "npm:preact@^10.26.9",
"vite": "npm:vite@^7.0.6",
"vite-plugin-inspect": "npm:vite-plugin-inspect@^11.3.2"
}
}
+128
View File
@@ -0,0 +1,128 @@
import type { Plugin } from "vite";
import {
type FreshViteConfig,
pathWithRoot,
type ResolvedFreshViteConfig,
} from "./utils.ts";
import { deno } from "./plugins/deno.ts";
import prefresh from "@prefresh/vite";
import { serverEntryPlugin } from "./plugins/server_entry.ts";
import { clientEntryPlugin } from "./plugins/client_entry.ts";
import { devServer } from "./plugins/dev_server.ts";
import { buildIdPlugin } from "./plugins/build_id.ts";
import { clientSnapshot } from "./plugins/client_snapshot.ts";
import { serverSnapshot } from "./plugins/server_snapshot.ts";
export function fresh(config?: FreshViteConfig): Plugin[] {
const fConfig: ResolvedFreshViteConfig = {
serverEntry: config?.serverEntry ?? "main.ts",
islandsDir: config?.islandsDir ?? "islands",
routeDir: config?.routeDir ?? "routes",
ignore: config?.ignore ?? [],
};
return [
{
name: "fresh",
config(config, env) {
return {
esbuild: {
jsx: "automatic",
jsxImportSource: "preact",
jsxDev: env.command === "serve",
},
resolve: {
alias: {
"react-dom/test-utils": "preact/test-utils",
"react-dom": "preact/compat",
react: "preact/compat",
},
noExternal: true,
},
optimizeDeps: {
include: [
"preact",
"preact/compat",
"preact/debug",
"preact/devtools",
"preact/hooks",
"preact/jsx-runtime",
"preact/jsx-dev-runtime",
"@preact/signals",
],
},
publicDir: pathWithRoot("static", config.root),
builder: {
async buildApp(builder) {
// Build client env first
const clientEnv = builder.environments.client;
if (clientEnv !== undefined) {
await builder.build(clientEnv);
}
await Promise.all(
Object.values(builder.environments).filter((env) =>
env !== clientEnv
).map((env) => builder.build(env)),
);
},
},
environments: {
client: {
build: {
copyPublicDir: false,
manifest: true,
outDir: config.environments?.client?.build?.outDir ??
"_fresh/client",
rollupOptions: {
preserveEntrySignatures: "strict",
input: {
"client-entry": "fresh:client-entry",
"client-snapshot": "fresh:client-snapshot",
},
},
},
},
ssr: {
build: {
manifest: false,
copyPublicDir: false,
outDir: config.environments?.ssr?.build?.outDir ??
"_fresh/server",
rollupOptions: {
input: {
"server-entry": "fresh:server_entry",
},
},
},
},
},
};
},
configResolved(config) {
fConfig.islandsDir = pathWithRoot(fConfig.islandsDir, config.root);
fConfig.routeDir = pathWithRoot(fConfig.routeDir, config.root);
},
},
serverEntryPlugin(fConfig),
...serverSnapshot(fConfig),
clientEntryPlugin(),
clientSnapshot(fConfig),
buildIdPlugin(),
...devServer(),
prefresh({
include: [/\.[cm]?[tj]sx?$/],
exclude: [/node_modules/],
parserPlugins: [
"importMeta",
"explicitResourceManagement",
"topLevelAwait",
],
}),
deno(),
];
}
+51
View File
@@ -0,0 +1,51 @@
import type { Plugin } from "vite";
export function buildIdPlugin(): Plugin {
let buildId = "";
return {
name: "fresh:build-id",
async config(_, env) {
const isDev = env.command === "serve";
buildId = await getBuildId(isDev);
return {
define: {
BUILD_ID: JSON.stringify(buildId),
},
};
},
applyToEnvironment() {
return true;
},
resolveId(id) {
if (id === "fresh/build-id") {
return `\0fresh/build-id`;
}
},
load(id) {
if (id !== `\0fresh/build-id`) return;
return `export let BUILD_ID = ${JSON.stringify(buildId)};
export const DENO_DEPLOYMENT_ID = undefined;
export function setBuildId(id) {
BUILD_ID = id;
}`;
},
};
}
export async function getBuildId(dev: boolean): Promise<string> {
if (!dev) {
const bin = Deno.build.os === "windows" ? "git.exe" : "git";
const res = await new Deno.Command(bin, { args: ["rev-parse", "HEAD"] })
.output();
return new TextDecoder().decode(res.stdout);
}
const arr = new Uint32Array(1);
crypto.getRandomValues(arr);
return String(arr[0]);
}
+33
View File
@@ -0,0 +1,33 @@
import type { Plugin } from "vite";
export function clientEntryPlugin(): Plugin {
const modName = "fresh:client-entry";
return {
name: "fresh:client-entry",
applyToEnvironment(env) {
return env.name === "client";
},
resolveId(id) {
if (id === modName) {
return `\0${modName}`;
}
},
load(id) {
if (id !== `\0${modName}`) return;
return `export * from "fresh/runtime-client";
if (import.meta.hot) {
import.meta.hot.accept(() => {
console.log("accepting")
});
import.meta.hot.on("fresh:reload", ev => {
console.log(ev)
window.location.reload();
});
}
`;
},
};
}
@@ -0,0 +1,79 @@
import type { Plugin, ViteDevServer } from "vite";
import type { ResolvedFreshViteConfig } from "../utils.ts";
import { crawlFsItem } from "fresh/internal-dev";
export function clientSnapshot(options: ResolvedFreshViteConfig): Plugin {
const modName = "fresh:client-snapshot";
const islands = new Set<string>();
let server: ViteDevServer | undefined;
let isDev = false;
return {
name: "fresh:client-snapshot",
applyToEnvironment(env) {
return env.name === "client";
},
config(_, env) {
isDev = env.command === "serve";
return {
environments: {
client: {
build: {
rollupOptions: {
input: {
"client-snapshot": "fresh:client-snapshot",
},
},
},
},
},
};
},
async buildStart() {
const result = await crawlFsItem({
islandDir: options.islandsDir,
routeDir: options.routeDir,
ignore: options.ignore,
});
for (let i = 0; i < result.islands.length; i++) {
const filePath = result.islands[i];
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);
}
}
return `${imports}
if (import.meta.hot) {
import.meta.hot.accept(() => {
console.log("accepting client-snapshot")
});
}
`;
},
};
}
+187
View File
@@ -0,0 +1,187 @@
import type { Plugin } from "vite";
import {
type Loader,
RequestedModuleType,
ResolutionMode,
Workspace,
} from "@deno/loader";
import * as path from "@std/path";
interface DenoState {
type: RequestedModuleType;
}
export function deno(): Plugin {
let loader: Loader;
return {
name: "deno",
async configResolved() {
// TODO: Pass conditions
loader = await new Workspace({}).createLoader();
},
applyToEnvironment() {
return true;
},
async resolveId(id, importer, options) {
importer = isDenoSpecifier(importer)
? parseDenoSpecifier(importer).specifier
: importer;
try {
// Ensure we're passing a valid importer that Deno understands
const denoImporter = importer && !importer.startsWith("\0")
? importer
: undefined;
let resolved = await loader.resolve(
id,
denoImporter,
ResolutionMode.Import,
);
if (id === resolved) {
return id;
}
const type = getDenoType(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"
) {
return toDenoSpecifier(resolved, type);
}
if (resolved.startsWith("file://")) {
resolved = path.fromFileUrl(resolved);
}
return {
id: resolved,
meta: {
deno: {
type,
},
},
};
} catch {
// ignore
}
},
async load(id) {
if (isDenoSpecifier(id)) {
const { type, specifier } = parseDenoSpecifier(id);
const result = await loader.load(specifier, type);
if (result.kind === "external") {
return null;
}
return {
code: new TextDecoder().decode(result.code),
};
}
if (id.startsWith("\0")) {
id = id.slice(1);
}
const meta = this.getModuleInfo(id)?.meta.deno as
| DenoState
| undefined
| null;
if (meta === null || meta === undefined) return;
const url = path.toFileUrl(id);
const result = await loader.load(url.href, meta.type);
if (result.kind === "external") {
return null;
}
return {
code: new TextDecoder().decode(result.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;
}
let actualId = id;
if (isDenoSpecifier(id)) {
const { specifier } = parseDenoSpecifier(id);
actualId = specifier;
}
if (path.isAbsolute(actualId)) {
actualId = path.toFileUrl(actualId).href;
}
const resolved = await loader.resolve(
actualId,
undefined,
ResolutionMode.Import,
);
const result = await loader.load(resolved, RequestedModuleType.Default);
if (result.kind === "external") {
return;
}
const code = new TextDecoder().decode(result.code);
return {
code,
};
},
};
}
export type DenoSpecifier = string & { __deno: string };
function isDenoSpecifier(str: unknown): str is DenoSpecifier {
return typeof str === "string" && str.startsWith("\0deno::");
}
function toDenoSpecifier(spec: string, type: RequestedModuleType) {
return `\0deno::${type}::${spec}`;
}
function parseDenoSpecifier(
spec: DenoSpecifier,
): { type: RequestedModuleType; specifier: string } {
const match = spec.match(/^\0deno::([^:]+)::(.*)$/)!;
let specifier = match[2];
const specMatch = specifier.match(/^(\w+):\/([^/].*)$/);
if (specMatch !== null) {
const protocol = specMatch[1];
let rest = specMatch[2];
if (protocol === "file") {
rest = "/" + rest;
}
specifier = `${protocol}://${rest}`;
}
return { type: +match[1], specifier };
}
function getDenoType(type: string): RequestedModuleType {
switch (type) {
case "json":
return RequestedModuleType.Json;
case "bytes":
return RequestedModuleType.Bytes;
case "text":
return RequestedModuleType.Text;
default:
return RequestedModuleType.Default;
}
}
+79
View File
@@ -0,0 +1,79 @@
import type { Plugin } from "vite";
import { nodeToRequest, responseToNode } from "../request.ts";
import * as path from "@std/path";
import { pathWithRoot } from "../utils.ts";
export function devServer(): Plugin[] {
let publicDir = "";
return [
{
name: "fresh:dev_server",
configResolved(cfg) {
publicDir = pathWithRoot(cfg.publicDir, cfg.root);
},
configureServer(server) {
const IGNORE_URLS = /^\/(@(vite|fs|id)|\.vite)\//;
server.middlewares.use(async (nodeReq, nodeRes, next) => {
const serverCfg = server.config.server;
const protocol = serverCfg.https ? "https" : "http";
const host = serverCfg.host ? serverCfg.host : "localhost";
const port = serverCfg.port;
const url = new URL(
`${protocol}://${host}:${port}${nodeReq.url ?? "/"}`,
);
// Check if it's a vite url
if (
IGNORE_URLS.test(url.pathname) ||
server.environments.client.moduleGraph.urlToModuleMap.has(
url.pathname,
)
) {
return next();
}
// Check if it's a static file first
// FIXME: Should this still go through fresh?
if (url.pathname !== "/") {
try {
await Deno.stat(path.join(publicDir, url.pathname));
return next();
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
return next(err);
}
}
}
const mod = await server.ssrLoadModule("fresh:server_entry");
try {
const req = nodeToRequest(nodeReq, url);
const res = await mod.default.fetch(req);
await responseToNode(res, nodeRes);
return nodeRes;
} catch (err) {
return next(err);
}
});
},
},
{
name: "fresh:server_hmr",
applyToEnvironment(env) {
return env.name === "ssr";
},
hotUpdate(options) {
const clientMod = options.server.environments.client.moduleGraph
.getModulesByFile(options.file);
if (clientMod === undefined) {
options.server.hot.send("fresh:reload");
}
},
},
];
}
+65
View File
@@ -0,0 +1,65 @@
import type { Plugin } from "vite";
import { generateServerEntry } from "fresh/internal-dev";
import { pathWithRoot, type ResolvedFreshViteConfig } from "../utils.ts";
import * as path from "@std/path";
export function serverEntryPlugin(
options: ResolvedFreshViteConfig,
): Plugin {
const modName = "fresh:server_entry";
let serverEntry = "";
let serverOutDir = "";
let root = "";
let isDev = false;
return {
name: "fresh:server_entry",
applyToEnvironment(env) {
return env.name === "ssr";
},
config(_, env) {
isDev = env.command === "serve";
},
configResolved(config) {
root = config.root;
serverEntry = pathWithRoot(options.serverEntry, config.root);
serverOutDir = pathWithRoot(
config.environments.ssr.build.outDir,
config.root,
);
},
resolveId(id) {
if (id === modName) {
return `\0${modName}`;
}
},
load(id) {
if (id !== `\0${modName}`) return;
let code = generateServerEntry({
root,
serverEntry: path.toFileUrl(serverEntry).href,
snapshotSpecifier: "fresh:server-snapshot",
});
if (isDev) {
code += `if (import.meta.hot) import.meta.hot.accept();\n`;
}
return code;
},
async writeBundle() {
const outDir = path.dirname(serverOutDir);
await Deno.writeTextFile(
path.join(outDir, "server.js"),
`import server from "./server/server-entry.mjs";
export default {
fetch: server.fetch
};
`,
);
},
};
}
+189
View File
@@ -0,0 +1,189 @@
import type { Manifest, Plugin, ViteDevServer } from "vite";
import {
crawlFsItem,
fsAdapter,
generateSnapshotServer,
type IslandModChunk,
pathToSpec,
type PendingStaticFile,
specToName,
UniqueNamer,
} from "fresh/internal-dev";
import { pathWithRoot, type ResolvedFreshViteConfig } from "../utils.ts";
import * as path from "@std/path";
import { getBuildId } from "./build_id.ts";
export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
const modName = "fresh:server-snapshot";
let isDev = false;
let server: ViteDevServer | undefined;
const namer = new UniqueNamer();
let clientOutDir = "";
let root = "";
let publicDir = "";
const islands = new Map<string, { name: string; chunk: string | null }>();
const islandSpecByName = new Map<string, string>();
return [{
name: "fresh:server-snapshot",
applyToEnvironment(env) {
return env.name === "ssr";
},
config(_, env) {
isDev = env.command === "serve";
},
configResolved(config) {
root = config.root;
publicDir = pathWithRoot(config.publicDir, config.root);
clientOutDir = pathWithRoot(
config.environments.client.build.outDir,
config.root,
);
},
configureServer(viteServer) {
server = viteServer;
},
async buildStart() {
},
resolveId(id) {
if (id === modName) {
return `\0${modName}`;
}
},
async load(id) {
if (id !== `\0${modName}`) return;
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 = namer.getUniqueName(specName);
islands.set(spec, { name, chunk: null });
islandSpecByName.set(name, spec);
}
const staticFiles: PendingStaticFile[] = [];
let islandMods: IslandModChunk[] = [];
let clientEntry = "/@id/fresh:client-entry";
let buildId = "";
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}`,
};
});
} else {
buildId = await getBuildId(false);
const manifest = JSON.parse(
await Deno.readTextFile(
path.join(clientOutDir, ".vite", "manifest.json"),
),
) as Manifest;
for (const chunk of Object.values(manifest)) {
if (chunk.name === "client-entry") {
clientEntry = pathToSpec(clientOutDir, chunk.file);
}
staticFiles.push({
filePath: path.join(clientOutDir, chunk.file),
pathname: chunk.file,
hash: null,
});
const namer = new UniqueNamer();
if (chunk.name === "client-snapshot") {
for (const id of chunk.dynamicImports ?? []) {
const mod = manifest[id];
const serverPath = path.join(root, mod.src ?? id);
const name = namer.getUniqueName(specToName(id));
islandMods.push({
name,
browser: pathToSpec(clientOutDir, mod.file),
server: serverPath,
});
}
}
}
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: root,
staticFiles,
buildId,
clientEntry,
fsRoutesFiles: result.routes,
islands: islandMods,
writeSpecifier: (file) => {
return path.toFileUrl(file).href;
},
});
return code;
},
}, {
name: "fresh:island-resolver",
resolveId(id) {
if (id.startsWith("fresh-island::")) {
const name = id.slice("fresh-island::".length);
const spec = islandSpecByName.get(name);
if (spec !== undefined) return spec;
}
},
}];
}
+84
View File
@@ -0,0 +1,84 @@
import type { IncomingMessage, ServerResponse } from "node:http";
export function nodeToRequest(node: IncomingMessage, url: URL): Request {
const controller = new AbortController();
node.once("aborted", () => controller.abort());
const body = undefined;
if (
node.method !== "HEAD" && node.method !== "GET" && node.method !== "OPTIONS"
) {
// FIXME
}
return new Request(url, {
headers: node.headers as Record<string, string>,
method: node.method,
body,
signal: controller.signal,
});
}
export async function responseToNode(
res: Response,
node: ServerResponse<IncomingMessage>,
): Promise<void> {
res.headers.forEach((value, key) => {
node.setHeader(key, value);
});
node.writeHead(res.status);
if (res.body === null) {
node.end();
return;
}
if (res.body.locked) {
node.end(`Error: Response body is locked.`);
return;
}
const reader = res.body.getReader();
if (node.destroyed) {
await reader.cancel();
return;
}
const cancel = (error: unknown) => {
node.off("close", cancel);
node.off("error", cancel);
// Can't respond anymore with error
reader.cancel(error).catch(() => {});
if (error) {
node.destroy(error instanceof Error ? error : new Error(String(error)));
}
};
node.on("close", cancel);
node.on("error", cancel);
async function next() {
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (!node.write(value)) {
node.once("drain", next);
return;
}
}
node.end();
} catch (error) {
cancel(error);
}
}
next();
}
+41
View File
@@ -0,0 +1,41 @@
import * as path from "@std/path";
import type { FsRouteFileNoMod, UniqueNamer } from "fresh/internal-dev";
export function pathWithRoot(fileOrDir: string, root?: string): string {
if (path.isAbsolute(fileOrDir)) return fileOrDir;
if (root === undefined) {
return path.join(Deno.cwd(), fileOrDir);
}
if (path.isAbsolute(root)) return path.join(root, fileOrDir);
return path.join(Deno.cwd(), root, fileOrDir);
}
export interface FreshState {
namer: UniqueNamer;
root: string;
serverEntry: string;
islandDir: string;
routeDir: string;
dev: boolean;
islands: Map<string, { name: string; chunk: string | null }>;
// deno-lint-ignore no-explicit-any
routes: FsRouteFileNoMod<any>[];
clientOutDir: string;
serverOutDir: string;
}
export interface ClientSnapshot {
entry: string;
}
export interface FreshViteConfig {
serverEntry?: string;
islandsDir?: string;
routeDir?: string;
ignore?: RegExp[];
}
export type ResolvedFreshViteConfig = Required<FreshViteConfig>;
+71
View File
@@ -0,0 +1,71 @@
import { expect } from "@std/expect";
import {
waitForText,
withBrowser,
withChildProcessServer,
} from "../../tests/test_utils.tsx";
import { buildVite } from "./test_utils.ts";
Deno.test({
name: "vite build - launches",
fn: async () => {
await using res = await buildVite();
await withChildProcessServer(
res.tmp,
["serve", "-A", "--port", "0", "_fresh/server.js"],
async (address) => {
const res = await fetch(address);
const text = await res.text();
expect(text).toEqual("it works");
},
);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "vite build - serves static files",
fn: async () => {
await using res = await buildVite();
await withChildProcessServer(
res.tmp,
["serve", "-A", "--port", "0", "_fresh/server.js"],
async (address) => {
const res = await fetch(`${address}/test_static/foo.txt`);
const text = await res.text();
expect(text).toEqual("it works");
},
);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "vite build - loads islands",
fn: async () => {
await using res = await buildVite();
await withChildProcessServer(
res.tmp,
["serve", "-A", "--port", "0", "_fresh/server.js"],
async (address) => {
await withBrowser(async (page) => {
await page.goto(`${address}/tests/island_hooks`, {
waitUntil: "networkidle2",
});
await waitForText(page, "button", "count: 0");
await page.locator("button").click();
await waitForText(page, "button", "count: 1");
});
},
);
},
sanitizeOps: false,
sanitizeResources: false,
});
+83
View File
@@ -0,0 +1,83 @@
import * as path from "@std/path";
import { expect } from "@std/expect";
import { waitForText, withBrowser } from "../../tests/test_utils.tsx";
import { updateFile, withDevServer } from "./test_utils.ts";
Deno.test({
name: "vite dev - launches",
fn: async () => {
await withDevServer(async (address) => {
const res = await fetch(`${address}/tests/it_works`);
const text = await res.text();
expect(text).toContain("it works");
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "vite dev - serves static files",
fn: async () => {
await withDevServer(async (address) => {
const res = await fetch(`${address}/test_static/foo.txt`);
const text = await res.text();
expect(text).toContain("it works");
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "vite dev - loads islands",
fn: async () => {
await withDevServer(async (address) => {
await withBrowser(async (page) => {
await page.goto(`${address}/tests/island_hooks`, {
waitUntil: "networkidle2",
});
await waitForText(page, "button", "count: 0");
await page.locator("button").click();
await waitForText(page, "button", "count: 1");
});
});
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "vite dev - can apply HMR to islands (hooks)",
ignore: true, // Test is very flaky
fn: async () => {
await withDevServer(async (address, dir) => {
await withBrowser(async (page) => {
await page.goto(`${address}/tests/island_hooks`, {
waitUntil: "networkidle2",
});
await waitForText(page, "button", "count: 0");
await page.locator("button").click();
await waitForText(page, "button", "count: 1");
const island = path.join(
dir,
"islands",
"tests",
"CounterHooks.tsx",
);
await using _ = await updateFile(
island,
(text) => text.replace("count:", "hmr:"),
);
await waitForText(page, "button", "hmr: 1");
await page.locator("button").click();
await waitForText(page, "button", "hmr: 2");
});
});
},
sanitizeResources: false,
sanitizeOps: false,
});
+108
View File
@@ -0,0 +1,108 @@
import { createBuilder } from "vite";
import * as path from "@std/path";
import { walk } from "@std/fs/walk";
import { withTmpDir } from "../../src/test_utils.ts";
import { withChildProcessServer } from "../../tests/test_utils.tsx";
export const DEMO_DIR = path.join(import.meta.dirname!, "..", "demo");
export async function updateFile(
filePath: string,
fn: (text: string) => string | Promise<string>,
) {
const original = await Deno.readTextFile(filePath);
const result = await fn(original);
await Deno.writeTextFile(filePath, result);
return {
async [Symbol.asyncDispose]() {
await Deno.writeTextFile(filePath, original);
},
};
}
async function copyDir(from: string, to: string) {
const entries = walk(from, {
includeFiles: true,
includeDirs: false,
skip: [/([\\/]+(_fresh|node_modules|vendor)[\\/]+|[\\/]+vite\.config\.ts)/],
});
for await (const entry of entries) {
if (entry.isFile) {
const relative = path.relative(from, entry.path);
const target = path.join(to, relative);
try {
await Deno.mkdir(path.dirname(target), { recursive: true });
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
await Deno.copyFile(entry.path, target);
}
}
}
export async function withDevServer(
fn: (address: string, dir: string) => void | Promise<void>,
) {
await using tmp = await withTmpDir({
dir: path.join(import.meta.dirname!, ".."),
prefix: "tmp_",
});
await copyDir(DEMO_DIR, tmp.dir);
await Deno.writeTextFile(
path.join(tmp.dir, "vite.config.ts"),
`import { defineConfig } from "vite";
import { fresh } from "@fresh/plugin-vite";
export default defineConfig({
plugins: [
fresh(),
],
});
`,
);
await withChildProcessServer(
tmp.dir,
["run", "-A", "npm:vite"],
(address) => fn(address, tmp.dir),
);
}
export async function buildVite() {
const tmp = await withTmpDir();
const builder = await createBuilder({
root: DEMO_DIR,
build: {
emptyOutDir: true,
},
environments: {
ssr: {
build: {
outDir: path.join(tmp.dir, "_fresh", "server"),
},
},
client: {
build: {
outDir: path.join(tmp.dir, "_fresh", "client"),
},
},
},
});
await builder.buildApp();
return {
tmp: tmp.dir,
async [Symbol.asyncDispose]() {
return await tmp[Symbol.asyncDispose]();
},
};
}
+6 -4
View File
@@ -1,6 +1,6 @@
import { trace } from "@opentelemetry/api";
import { DENO_DEPLOYMENT_ID } from "./runtime/build_id.ts";
import { DENO_DEPLOYMENT_ID } from "fresh/build-id";
import * as colors from "@std/fmt/colors";
import {
type MaybeLazyMiddleware,
@@ -152,6 +152,7 @@ export let getBuildCache: <State>(app: App<State>) => BuildCache<State> | null;
export let setBuildCache: <State>(
app: App<State>,
cache: BuildCache<State>,
mode: "development" | "production",
) => void;
/**
@@ -164,8 +165,9 @@ export class App<State> {
static {
getBuildCache = (app) => app.#getBuildCache();
setBuildCache = (app, cache) => {
setBuildCache = (app, cache, mode: "development" | "production") => {
app.config.root = cache.root;
app.config.mode = mode;
app.#getBuildCache = () => cache;
};
}
@@ -179,7 +181,7 @@ export class App<State> {
this.config = {
root: Deno.cwd(),
basePath: config.basePath ?? "",
mode: "production",
mode: config.mode ?? "production",
};
}
@@ -363,7 +365,7 @@ export class App<State> {
`Could not find _fresh directory. Maybe you forgot to run "deno task build"?`,
);
} else {
buildCache = new MockBuildCache([]);
buildCache = new MockBuildCache([], this.config.mode);
}
}
+9 -1
View File
@@ -1,10 +1,10 @@
import * as path from "@std/path";
import { setBuildId } from "./runtime/build_id.ts";
import type { Command } from "./commands.ts";
import { fsItemsToCommands, type FsRouteFile } from "./fs_routes.ts";
import type { ServerIslandRegistry } from "./context.ts";
import type { AnyComponent } from "preact";
import { UniqueNamer } from "./utils.ts";
import { setBuildId } from "fresh/build-id";
export interface FileSnapshot {
name: string;
@@ -15,6 +15,7 @@ export interface FileSnapshot {
export interface BuildSnapshot<State> {
version: string;
clientEntry: string;
fsRoutes: FsRouteFile<State>[];
staticFiles: Map<string, FileSnapshot>;
islands: ServerIslandRegistry;
@@ -32,6 +33,10 @@ export interface StaticFile {
export interface BuildCache<State = any> {
root: string;
islandRegistry: ServerIslandRegistry;
clientEntry: string;
features: {
errorOverlay: boolean;
};
getFsRoutes(): Command<State>[];
readFile(pathname: string): Promise<StaticFile | null>;
}
@@ -39,11 +44,14 @@ export interface BuildCache<State = any> {
export class ProdBuildCache<State> implements BuildCache<State> {
#snapshot: BuildSnapshot<State>;
islandRegistry: ServerIslandRegistry;
clientEntry: string;
features = { errorOverlay: false };
constructor(public root: string, snapshot: BuildSnapshot<State>) {
setBuildId(snapshot.version);
this.#snapshot = snapshot;
this.islandRegistry = snapshot.islands;
this.clientEntry = snapshot.clientEntry;
}
getFsRoutes(): Command<State>[] {
+4
View File
@@ -7,6 +7,10 @@ export interface FreshConfig {
* @default undefined
*/
basePath?: string;
/**
* The mode Fresh can run in.
*/
mode?: "development" | "production";
}
/**
-12
View File
@@ -296,15 +296,3 @@ export class Context<State> {
return new Response(html, responseInit);
}
}
Object.defineProperties(Context.prototype, {
config: { enumerable: true },
url: { enumerable: true },
req: { enumerable: true },
params: { enumerable: true },
state: { enumerable: true },
data: { enumerable: true },
error: { enumerable: true },
next: { enumerable: true },
info: { enumerable: true },
});
+1 -1
View File
@@ -3,7 +3,7 @@ import { Context } from "./context.ts";
import { App } from "fresh";
import { asset } from "fresh/runtime";
import { FakeServer } from "./test_utils.ts";
import { BUILD_ID } from "./runtime/build_id.ts";
import { BUILD_ID } from "fresh/build-id";
import { parseHtml } from "../tests/test_utils.tsx";
Deno.test("FreshReqContext.prototype.redirect", () => {
+17 -19
View File
@@ -24,7 +24,7 @@ import { automaticWorkspaceFolders } from "./middlewares/automatic_workspace_fol
import { parseDirPath } from "../config.ts";
import { pathToExportName, UniqueNamer } from "../utils.ts";
import { checkDenoCompilerOptions } from "./check.ts";
import { crawlRouteDir, walkDir } from "./fs_crawl.ts";
import { crawlFsItem } from "./fs_crawl.ts";
import { DAY } from "../constants.ts";
export interface BuildOptions {
@@ -169,7 +169,7 @@ export class Builder<State = any> {
app.config.root = this.config.root;
app.config.mode = "development";
setBuildCache(app, buildCache);
setBuildCache(app, buildCache, "development");
const appHandler = app.handler();
@@ -187,7 +187,7 @@ export class Builder<State = any> {
devApp.config.root = this.config.root;
devApp.config.mode = "development";
setBuildCache(devApp, buildCache);
setBuildCache(devApp, buildCache, "development");
// Boot in parallel to spin up the server quicker. We'll hold
// requests until the required assets are processed.
@@ -248,26 +248,24 @@ export class Builder<State = any> {
await buildCache.prepare();
return (app) => {
setBuildCache(app, buildCache);
setBuildCache(app, buildCache, app.config.mode);
};
}
async #crawlFsItems() {
await Promise.all([
walkDir(
fsAdapter,
this.config.islandDir,
(entry) => this.registerIsland(entry.path),
this.config.ignore,
),
crawlRouteDir(
fsAdapter,
this.config.routeDir,
this.config.ignore,
(entry) => this.registerIsland(entry),
this.#fsRoutes.files,
),
]);
const { islands, routes } = await crawlFsItem(
{
islandDir: this.config.islandDir,
routeDir: this.config.routeDir,
ignore: this.config.ignore,
},
);
for (let i = 0; i < islands.length; i++) {
this.registerIsland(islands[i]);
}
this.#fsRoutes.files = routes;
}
async #build<T>(buildCache: DevBuildCache<T>, dev: boolean): Promise<void> {
+2 -2
View File
@@ -3,7 +3,7 @@ import * as path from "@std/path";
import { Builder, specToName } from "./builder.ts";
import { App } from "../app.ts";
import { DEV_ERROR_OVERLAY_URL } from "../constants.ts";
import { BUILD_ID } from "../runtime/build_id.ts";
import { BUILD_ID } from "fresh/build-id";
import { withTmpDir, writeFiles } from "../test_utils.ts";
import { withChildProcessServer } from "../../tests/test_utils.tsx";
@@ -64,7 +64,7 @@ Deno.test({
await builder.build();
const snapshotJson = await Deno.readTextFile(
path.join(tmp, "dist", "static-files.json"),
path.join(tmp, "dist", "snapshot.js"),
);
expect(snapshotJson).toContain("/images/batman.svg");
},
+175 -120
View File
@@ -1,11 +1,10 @@
import {
type BuildCache,
type FileSnapshot,
IslandPreparer,
type StaticFile,
} from "../build_cache.ts";
import * as path from "@std/path";
import { SEPARATOR as WINDOWS_SEPARATOR } from "@std/path/windows/constants";
import * as pathWin32 from "@std/path/windows";
import { encodeHex } from "@std/encoding/hex";
import { fsAdapter } from "../fs.ts";
import type { FileTransformer } from "./file_transformer.ts";
@@ -16,6 +15,8 @@ import type { Command } from "../commands.ts";
import type { ServerIslandRegistry } from "../context.ts";
import { contentType as getStdContentType } from "@std/media-types/content-type";
const WINDOWS_SEPARATOR = pathWin32.SEPARATOR;
export interface MemoryFile {
hash: string | null;
contentType: string;
@@ -60,16 +61,24 @@ export class MemoryBuildCache<State> implements DevBuildCache<State> {
#commands: Command<State>[] = [];
root: string;
islandRegistry: ServerIslandRegistry = new Map();
clientEntry: string;
features = { errorOverlay: false };
constructor(
config: ResolvedBuildConfig,
fsRoutes: FsRoute<State>,
transformer: FileTransformer,
) {
if (config.mode === "development") {
this.features.errorOverlay = true;
}
this.#config = config;
this.#fsRoutes = fsRoutes;
this.#transformer = transformer;
this.root = config.root;
this.clientEntry = getClientEntry(config.buildId);
}
getFsRoutes(): Command<State>[] {
@@ -220,12 +229,17 @@ export class DiskBuildCache<State> implements DevBuildCache<State> {
#fsRoutes: FsRoute<State>;
root: string;
islandRegistry: ServerIslandRegistry = new Map();
clientEntry: string = "";
features = { errorOverlay: false };
constructor(
config: ResolvedBuildConfig,
fsRoutes: FsRoute<State>,
transformer: FileTransformer,
) {
if (config.mode === "development") {
this.features.errorOverlay = true;
}
this.#fsRoutes = fsRoutes;
this.#transformer = transformer;
this.#config = config;
@@ -308,155 +322,62 @@ export class DiskBuildCache<State> implements DevBuildCache<State> {
}
}
const staticFiles = new Map<string, FileSnapshot>();
const staticFiles: PendingStaticFile[] = [];
for (const [name, filePath] of this.#unprocessedFiles.entries()) {
const file = await Deno.open(filePath);
const hash = await hashContent(file.readable);
staticFiles.set(name, {
name,
hash,
filePath: path.relative(root, filePath),
contentType: getContentType(filePath),
});
staticFiles.push({ filePath, pathname: name, hash: null });
}
for (const [name, maybeHash] of this.#processedFiles.entries()) {
let hash = maybeHash;
// Ignore esbuild meta file. It's not intended for serving
if (name === "/metafile.json") {
continue;
}
const filePath = path.join(outDir, "static", name);
if (maybeHash === null) {
const file = await Deno.open(filePath);
hash = await hashContent(file.readable);
}
staticFiles.set(name, {
name,
hash,
filePath: path.relative(root, filePath),
contentType: getContentType(filePath),
});
staticFiles.push({ filePath, pathname: name, hash: maybeHash });
}
await Deno.writeTextFile(
path.join(outDir, "static-files.json"),
JSON.stringify(Array.from(staticFiles.values()), null, 2),
);
const islandSpecifiers: string[] = [];
for (const spec of this.islandModNameToChunk.keys()) {
islandSpecifiers.push(spec);
}
const editWarning =
`// WARNING: DO NOT EDIT THIS FILE. It is autogenerated by Fresh.`;
const islands = Array.from(this.islandModNameToChunk.values());
await Deno.writeTextFile(
path.join(outDir, "snapshot.js"),
`${editWarning}
import { IslandPreparer } from "fresh/do-not-use";
import staticFileData from "./static-files.json" with { type: "json" };
// Import islands
${
islands
.map((item) => {
const spec = pathToSpec(outDir, item.server);
return `import * as ${item.name} from "${spec}";`;
})
.join("\n")
}
// Import routes
${
this.#fsRoutes.files
.map((item, i) => {
if (item.lazy) return null;
const spec = pathToSpec(outDir, item.filePath);
return `import * as fsRoute_${i} from "${spec}"`;
})
.filter(Boolean)
.join("\n")
}
export const version = ${JSON.stringify(this.#config.buildId)};
const prefix = \`/_fresh/js/\${version}\`;
export const islands = new Map();
const islandPreparer = new IslandPreparer();
${
islands.map((item) => {
// Strip prefix
const prefix = `/_fresh/js/${this.#config.buildId}`;
const chunkName = item.browser
? item.browser.slice(prefix.length)
: item.browser;
return `islandPreparer.prepare(islands, ${item.name}, \`\${prefix}${chunkName}\`, ${
JSON.stringify(item.name)
});`;
}).join("\n")
}
export const staticFiles = new Map();
for (let i = 0; i < staticFileData.length; i++) {
const data = staticFileData[i];
staticFiles.set(data.name, data);
}
export const fsRoutes = [
${
this.#fsRoutes.files
.map((item, i) => {
const id = JSON.stringify(item.id);
const pattern = JSON.stringify(item.pattern);
const type = JSON.stringify(item.type);
const routePattern = JSON.stringify(item.routePattern);
let mod = "";
if (item.lazy) {
const spec = pathToSpec(outDir, item.filePath);
mod = `() => import(${JSON.stringify(spec)})`;
} else {
mod = `fsRoute_${i}`;
}
return ` { id: ${id}, mod: ${mod}, type: ${type}, pattern: ${pattern}, routePattern: ${routePattern} },`;
})
.join("\n")
}
];
`,
await generateSnapshotServer({
buildId: this.#config.buildId,
clientEntry: getClientEntry(this.#config.buildId),
staticFiles,
islands,
writeSpecifier: (filePath) => {
return pathToSpec(outDir, filePath);
},
fsRoutesFiles: this.#fsRoutes.files,
outDir: root,
}),
);
// TODO: Make main file configurable
const appPath = path.relative(outDir, root);
await Deno.writeTextFile(
path.join(outDir, "server.js"),
`${editWarning}
import { setBuildCache, ProdBuildCache, path } from "fresh/do-not-use";
import * as snapshot from "./snapshot.js";
import { app } from "${appPath}/main.ts";
const root = path.join(import.meta.dirname, ${JSON.stringify(appPath)});
setBuildCache(app, new ProdBuildCache(root, snapshot));
export default {
fetch: app.handler()
}`,
generateServerEntry({
root: appPath,
serverEntry: path
.join(appPath, "main.ts")
.replaceAll(/[\\/]+/g, "/"),
snapshotSpecifier: "./snapshot.js",
}),
);
}
}
async function hashContent(
const EDIT_WARNING =
`// WARNING: DO NOT EDIT THIS FILE. It is autogenerated by Fresh.`;
export async function hashContent(
content: Uint8Array | ReadableStream<Uint8Array>,
): Promise<string> {
const buffer = await new Response(content).arrayBuffer();
@@ -476,3 +397,137 @@ export function getContentType(filePath: string): string {
function maybeToFileUrl(file: string) {
return file.startsWith("file://") ? file : path.toFileUrl(file).href;
}
export interface PendingStaticFile {
pathname: string;
filePath: string;
hash: string | null;
}
export async function generateSnapshotServer(
options: {
outDir: string;
buildId: string;
clientEntry: string;
islands: IslandModChunk[];
// deno-lint-ignore no-explicit-any
fsRoutesFiles: FsRouteFileNoMod<any>[];
staticFiles: PendingStaticFile[];
writeSpecifier: (filePath: string) => string;
},
): Promise<string> {
const {
islands,
writeSpecifier,
fsRoutesFiles,
outDir,
} = options;
const islandImports = islands
.map((item) => {
const spec = writeSpecifier(item.server);
return `import * as ${item.name} from "${spec}";`;
})
.join("\n");
const fsRouteImports = fsRoutesFiles
.map((item, i) => {
if (item.lazy) return null;
const spec = writeSpecifier(item.filePath);
return `import * as fsRoute_${i} from "${spec}"`;
})
.filter(Boolean)
.join("\n");
const islandMarkers = islands.map((item) => {
const browser = JSON.stringify(item.browser);
const name = JSON.stringify(item.name);
return `islandPreparer.prepare(islands, ${item.name}, ${browser}, ${name});`;
}).join("\n");
const serializedFsRoutes = fsRoutesFiles
.map((item, i) => {
const id = JSON.stringify(item.id);
const pattern = JSON.stringify(item.pattern);
const type = JSON.stringify(item.type);
const routePattern = JSON.stringify(item.routePattern);
let mod = "";
if (item.lazy) {
const spec = writeSpecifier(item.filePath);
mod = `() => import(${JSON.stringify(spec)})`;
} else {
mod = `fsRoute_${i}`;
}
return ` { id: ${id}, mod: ${mod}, type: ${type}, pattern: ${pattern}, routePattern: ${routePattern} },`;
})
.join("\n");
const staticFiles = await Promise.all(
options.staticFiles.map(async (item) => {
const file = await Deno.open(item.filePath);
const hash = item.hash ? item.hash : await hashContent(file.readable);
const url = new URL(item.pathname, "http://localhost");
return {
name: url.pathname,
hash,
filePath: path.isAbsolute(item.filePath)
? path.relative(outDir, item.filePath)
: item.filePath,
contentType: getContentType(item.filePath),
};
}),
);
return `${EDIT_WARNING}
import { IslandPreparer } from "fresh/internal";
${islandImports}
${fsRouteImports}
export const clientEntry = ${JSON.stringify(options.clientEntry)}
export const version = ${JSON.stringify(options.buildId)}
export const islands = new Map();
const islandPreparer = new IslandPreparer();
${islandMarkers}
export const staticFiles = new Map([
${
staticFiles.map((def) =>
` [${JSON.stringify(def.name)}, ${JSON.stringify(def)}]`
).join(",\n")
}
]);
export const fsRoutes = [
${serializedFsRoutes}
];
`.replaceAll(/\n[\n]+/g, "\n\n");
}
export function generateServerEntry(
options: {
root: string;
serverEntry: string;
snapshotSpecifier: string;
},
): string {
return `${EDIT_WARNING}
import { setBuildCache, ProdBuildCache, path } from "fresh/internal";
import * as snapshot from "${options.snapshotSpecifier}";
import { app } from "${options.serverEntry}";
const root = "";
setBuildCache(app, new ProdBuildCache(root, snapshot), "production");
export default {
fetch: app.handler()
};
`;
}
function getClientEntry(buildId: string) {
return `/_fresh/js/${buildId}/fresh-runtime.js`;
}
+2 -2
View File
@@ -166,14 +166,14 @@ function buildIdPlugin(buildId: string): EsbuildPlugin {
return {
name: "fresh-build-id",
setup(build) {
build.onResolve({ filter: /[/\\]+build_id\.ts$/ }, (args) => {
build.onResolve({ filter: /^fresh\/build-id$/ }, (args) => {
return {
path: args.path,
namespace: "fresh-internal",
};
});
build.onLoad({
filter: /[/\\]build_id\.ts$/,
filter: /^fresh\/build-id$/,
namespace: "fresh-internal",
}, () => {
return {
+102 -79
View File
@@ -1,4 +1,4 @@
import type { FsAdapter } from "../fs.ts";
import { type FsAdapter, fsAdapter } from "../fs.ts";
import type { WalkEntry } from "@std/fs/walk";
import type { FsRouteFileNoMod } from "./dev_build_cache.ts";
import * as path from "@std/path";
@@ -14,92 +14,90 @@ export async function crawlRouteDir<State>(
routeDir: string,
ignore: RegExp[],
onIslandSpecifier: (spec: string) => void,
files: FsRouteFileNoMod<State>[],
) {
await walkDir(
fs,
routeDir,
async (entry) => {
// A `(_islands)` path segment is a local island folder.
// Any route path segment wrapped in `(_...)` is ignored
// during route collection.
const match = entry.path.match(GROUP_REG);
if (match !== null) {
if (match[1] === "_islands") {
onIslandSpecifier(entry.path);
): Promise<FsRouteFileNoMod<State>[]> {
const files: FsRouteFileNoMod<State>[] = [];
await walkDir(fs, routeDir, async (entry) => {
// A `(_islands)` path segment is a local island folder.
// Any route path segment wrapped in `(_...)` is ignored
// during route collection.
const match = entry.path.match(GROUP_REG);
if (match !== null) {
if (match[1] === "_islands") {
onIslandSpecifier(entry.path);
}
return;
}
let lazy = false;
const relative = path.relative(routeDir, entry.path);
const url = new URL(relative, "http://localhost/");
const id = url.pathname.slice(0, url.pathname.lastIndexOf("."));
let overrideConfig: RouteConfig | undefined;
let pattern = "*";
let routePattern = pattern;
let type = CommandType.Route;
if (id.endsWith("/_middleware")) {
type = CommandType.Middleware;
pattern = pathToPattern(
id.slice(1, -"/_middleware".length),
{ keepGroups: true },
);
routePattern = pattern;
} else if (id.endsWith("/_layout")) {
type = CommandType.Layout;
pattern = pathToPattern(
id.slice(1, -"/_layout".length),
{ keepGroups: true },
);
routePattern = pattern;
} else if (id.endsWith("/_app")) {
type = CommandType.App;
} else if (id.endsWith("/_404")) {
type = CommandType.NotFound;
} else if (id.endsWith("/_error") || id.endsWith("/_500")) {
type = CommandType.Error;
pattern = pathToPattern(
id.slice(1, -"/_error".length),
{ keepGroups: true },
);
routePattern = pattern;
} else {
pattern = pathToPattern(id.slice(1), { keepGroups: true });
if (id.endsWith("/index")) {
if (!pattern.endsWith("/")) {
pattern += "/";
}
return;
}
let lazy = false;
const relative = path.relative(routeDir, entry.path);
const url = new URL(relative, "http://localhost/");
const id = url.pathname.slice(0, url.pathname.lastIndexOf("."));
routePattern = pathToPattern(id.slice(1));
let overrideConfig: RouteConfig | undefined;
let pattern = "*";
let routePattern = pattern;
let type = CommandType.Route;
if (id.endsWith("/_middleware")) {
type = CommandType.Middleware;
pattern = pathToPattern(
id.slice(1, -"/_middleware".length),
{ keepGroups: true },
);
routePattern = pattern;
} else if (id.endsWith("/_layout")) {
type = CommandType.Layout;
pattern = pathToPattern(
id.slice(1, -"/_layout".length),
{ keepGroups: true },
);
routePattern = pattern;
} else if (id.endsWith("/_app")) {
type = CommandType.App;
} else if (id.endsWith("/_404")) {
type = CommandType.NotFound;
} else if (id.endsWith("/_error") || id.endsWith("/_500")) {
type = CommandType.Error;
pattern = pathToPattern(
id.slice(1, -"/_error".length),
{ keepGroups: true },
);
routePattern = pattern;
} else {
pattern = pathToPattern(id.slice(1), { keepGroups: true });
if (id.endsWith("/index")) {
if (!pattern.endsWith("/")) {
pattern += "/";
}
}
const code = await fs.readTextFile(entry.path);
lazy = !code.includes("routeOverride");
routePattern = pathToPattern(id.slice(1));
// TODO: We could do an AST parse here to detect the
// kind of handler that's used to get a more accurate
// list of methods this route supports.
overrideConfig = {
methods: "ALL",
};
}
const code = await fs.readTextFile(entry.path);
lazy = !code.includes("routeOverride");
// TODO: We could do an AST parse here to detect the
// kind of handler that's used to get a more accurate
// list of methods this route supports.
overrideConfig = {
methods: "ALL",
};
}
files.push({
id,
filePath: entry.path,
type,
pattern,
routePattern,
lazy,
overrideConfig,
});
},
ignore,
);
files.push({
id,
filePath: entry.path,
type,
pattern,
routePattern,
lazy,
overrideConfig,
});
}, ignore);
files.sort((a, b) => sortRoutePaths(a.id, b.id));
return files;
}
export async function walkDir(
@@ -121,3 +119,28 @@ export async function walkDir(
await callback(entry);
}
}
export async function crawlFsItem(
options: { islandDir: string; routeDir: string; ignore: RegExp[] },
): Promise<{ islands: string[]; routes: FsRouteFileNoMod<unknown>[] }> {
const islands: string[] = [];
const [, routes] = await Promise.all([
walkDir(
fsAdapter,
options.islandDir,
(entry) => {
islands.push(entry.path);
},
options.ignore,
),
crawlRouteDir(
fsAdapter,
options.routeDir,
options.ignore,
(entry) => islands.push(entry),
),
]);
return { islands, routes };
}
@@ -89,7 +89,7 @@ function getFirstUserFile(
const lines = stack.split("\n");
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(STACK_FRAME);
if (match && match) {
if (match) {
const fnName = match[1] ?? "";
const file = match[2];
const line = +match[3];
@@ -86,9 +86,8 @@ Deno.test(
);
Deno.test("error overlay - should not be visible in prod", async () => {
const app = new App();
const app = new App({ mode: "production" });
app.use(devErrorOverlay());
app.config.mode = "production";
app.get("/", () => {
throw new HttpError(500);
+6 -6
View File
@@ -9,7 +9,6 @@ import type { Method } from "./router.ts";
import { parseHtml } from "../tests/test_utils.tsx";
import type { Context } from "./context.ts";
import { HttpError } from "./error.ts";
import type { FsRouteFileNoMod } from "./dev/dev_build_cache.ts";
import { crawlRouteDir } from "./dev/fs_crawl.ts";
import * as path from "@std/path";
@@ -19,8 +18,7 @@ async function createServer<T>(
const fs = createFakeFs(files);
const routeDir = path.join(fs.cwd(), "routes");
const rawFiles: FsRouteFileNoMod<T>[] = [];
await crawlRouteDir(fs, routeDir, [], () => {}, rawFiles);
const rawFiles = await crawlRouteDir(fs, routeDir, [], () => {});
const fsFiles = rawFiles.map((file) => {
// deno-lint-ignore no-explicit-any
@@ -30,8 +28,8 @@ async function createServer<T>(
const app = new App<T>()
.fsRoutes();
const buildCache = new MockBuildCache<T>(fsFiles);
setBuildCache<T>(app, buildCache);
const buildCache = new MockBuildCache<T>(fsFiles, "development");
setBuildCache<T>(app, buildCache, "development");
return new FakeServer(app.handler());
}
@@ -229,7 +227,9 @@ Deno.test("fsRoutes - middleware array", async () => {
return ctx.next();
},
},
"routes/foo/index.ts": { default: (ctx) => <div>{ctx.state.text}</div> },
"routes/foo/index.ts": {
default: (ctx) => <div class="full-">{ctx.state.text}</div>,
},
});
const res = await server.get("/foo");
+11
View File
@@ -0,0 +1,11 @@
export { crawlFsItem } from "./dev/fs_crawl.ts";
export { type FsAdapter, fsAdapter } from "./fs.ts";
export {
type FsRouteFileNoMod,
generateServerEntry,
generateSnapshotServer,
type IslandModChunk,
type PendingStaticFile,
} from "./dev/dev_build_cache.ts";
export { specToName } from "./dev/builder.ts";
export { pathToSpec, UniqueNamer } from "./utils.ts";
+1 -1
View File
@@ -1,6 +1,6 @@
import type { Middleware } from "./mod.ts";
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
import { BUILD_ID } from "../runtime/build_id.ts";
import { BUILD_ID } from "fresh/build-id";
import { tracer } from "../otel.ts";
import { getBuildCache } from "../context.ts";
+3 -1
View File
@@ -3,7 +3,7 @@ import { serveMiddleware } from "../test_utils.ts";
import type { BuildCache, StaticFile } from "../build_cache.ts";
import { expect } from "@std/expect";
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
import { BUILD_ID } from "../runtime/build_id.ts";
import { BUILD_ID } from "fresh/build-id";
import type { Command } from "../commands.ts";
import type { ServerIslandRegistry } from "../context.ts";
import { getContentType } from "../dev/dev_build_cache.ts";
@@ -13,6 +13,8 @@ class MockBuildCache implements BuildCache {
buildId = "MockId";
files = new Map<string, StaticFile>();
islandRegistry: ServerIslandRegistry = new Map();
clientEntry = "";
features = { errorOverlay: false };
constructor(files: Record<string, { hash: string | null; content: string }>) {
const encoder = new TextEncoder();
+10 -6
View File
@@ -14,7 +14,6 @@ import type { Context } from "./context.ts";
import { recordSpanError, tracer } from "./otel.ts";
import { DEV_ERROR_OVERLAY_URL } from "./constants.ts";
import { renderToString } from "preact-render-to-string";
import { BUILD_ID } from "./runtime/build_id.ts";
export type AsyncAnyComponent<P> = {
(
@@ -85,12 +84,17 @@ export function preactRender<State, Data>(
} finally {
// Add preload headers
const basePath = ctx.config.basePath;
const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
let link = `<${encodeURI(runtimeUrl)}>; rel="modulepreload"; as="script"`;
const runtimeUrl = state.buildCache.clientEntry.startsWith(".")
? state.buildCache.clientEntry.slice(1)
: state.buildCache.clientEntry;
let link = `<${
encodeURI(`${basePath}${runtimeUrl}`)
}>; rel="modulepreload"; as="script"`;
state.islands.forEach((island) => {
link += `, <${
encodeURI(`${basePath}${island.file}`)
}>; rel="modulepreload"; as="script"`;
const specifier = `${basePath}${
island.file.startsWith(".") ? island.file.slice(1) : island.file
}`;
link += `, <${encodeURI(specifier)}>; rel="modulepreload"; as="script"`;
});
if (link !== "") {
+5 -3
View File
@@ -1,6 +1,8 @@
import { encodeHex } from "@std/encoding/hex";
export const DENO_DEPLOYMENT_ID = Deno.env.get("DENO_DEPLOYMENT_ID");
export const DENO_DEPLOYMENT_ID: string | undefined = Deno.env.get(
"DENO_DEPLOYMENT_ID",
);
const deploymentId = DENO_DEPLOYMENT_ID ||
// For CI
Deno.env.get("GITHUB_SHA") ||
@@ -10,8 +12,8 @@ const buildIdHash = await crypto.subtle.digest(
new TextEncoder().encode(deploymentId),
);
export let BUILD_ID = encodeHex(buildIdHash);
export let BUILD_ID: string = encodeHex(buildIdHash);
export function setBuildId(buildId: string) {
export function setBuildId(buildId: string): void {
BUILD_ID = buildId;
}
+1 -1
View File
@@ -329,7 +329,7 @@ export async function applyPartials(res: Response): Promise<void> {
for (let i = 0; i < json.islands.length; i++) {
const island = json.islands[i];
promises.push(
import(island.chunk).then((mod) => {
import(/* @vite-ignore */ island.chunk).then((mod) => {
ISLAND_REGISTRY.set(island.name, mod[island.exportName]);
}),
);
+1 -1
View File
@@ -1,6 +1,6 @@
import { options } from "preact";
import { assetHashingHook, CLIENT_NAV_ATTR } from "../shared_internal.tsx";
import { BUILD_ID } from "../build_id.ts";
import { BUILD_ID } from "fresh/build-id";
const oldVNodeHook = options.vnode;
options.vnode = (vnode) => {
+14 -6
View File
@@ -23,7 +23,7 @@ import {
setActiveUrl,
} from "../shared_internal.tsx";
import type { BuildCache } from "../../build_cache.ts";
import { BUILD_ID } from "../build_id.ts";
import { BUILD_ID } from "fresh/build-id";
import {
DEV_ERROR_OVERLAY_URL,
PARTIAL_SEARCH_PARAM,
@@ -433,7 +433,8 @@ export interface PartialStateJson {
}
function FreshRuntimeScript() {
const { islands, nonce, ctx, islandProps, partialId } = RENDER_STATE!;
const { islands, nonce, ctx, islandProps, partialId, buildCache } =
RENDER_STATE!;
const basePath = ctx.config.basePath;
const islandArr = Array.from(islands);
@@ -470,7 +471,11 @@ function FreshRuntimeScript() {
: island.exportName === island.name
? `{ ${island.exportName} }`
: `{ ${island.exportName} as ${island.name} }`;
return `import ${named} from "${`${basePath}${island.file}`}";`;
const islandSpec = island.file.startsWith(".")
? island.file.slice(1)
: island.file;
return `import ${named} from "${basePath}${islandSpec}";`;
}).join("");
const islandObj = "{" + islandArr.map((island) => island.name)
@@ -482,9 +487,12 @@ function FreshRuntimeScript() {
{ json: true },
);
const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
// const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
const runtimeUrl = buildCache.clientEntry.startsWith(".")
? buildCache.clientEntry.slice(1)
: buildCache.clientEntry;
const scriptContent =
`import { boot } from "${runtimeUrl}";${islandImports}boot(${islandObj},${serializedProps});`;
`import { boot } from "${basePath}${runtimeUrl}";${islandImports}boot(${islandObj},${serializedProps});`;
return (
<>
@@ -496,7 +504,7 @@ function FreshRuntimeScript() {
__html: scriptContent,
}}
/>
{ctx.config.mode === "development" ? <ShowErrorOverlay /> : null}
{buildCache.features.errorOverlay ? <ShowErrorOverlay /> : null}
</>
);
}
+1 -1
View File
@@ -1,5 +1,5 @@
import type { ComponentChildren, VNode } from "preact";
import { BUILD_ID } from "./build_id.ts";
import { BUILD_ID } from "fresh/build-id";
import { assetInternal, assetSrcSetInternal } from "./shared_internal.tsx";
/**
+5 -2
View File
@@ -83,7 +83,7 @@ export function serveMiddleware<T>(
(() => new Response("not found", { status: 404 }));
const config = options.config ?? DEFAULT_CONFIG;
const buildCache = options.buildCache ??
new MockBuildCache<T>([]);
new MockBuildCache<T>([], options.config?.mode ?? "production");
const ctx = new Context<T>(
req,
@@ -149,9 +149,12 @@ export async function withTmpDir(
export class MockBuildCache<State> implements BuildCache<State> {
#files: FsRouteFile<State>[];
root = "";
clientEntry = "";
islandRegistry: ServerIslandRegistry = new Map();
features = { errorOverlay: false };
constructor(files: FsRouteFile<State>[]) {
constructor(files: FsRouteFile<State>[], mode: "development" | "production") {
this.features.errorOverlay = mode === "development";
this.#files = files;
}
+2 -1
View File
@@ -124,7 +124,8 @@ export async function withChildProcessServer(
let address = "";
let found = false;
// @ts-ignore yes it does
for await (const line of lines.values({ preventCancel: true })) {
for await (const raw of lines.values({ preventCancel: true })) {
const line = colors.stripAnsiCode(raw);
output.push(line);
const match = line.match(
/https?:\/\/[^:]+:\d+(\/\w+[-\w]*)*/g,