major: build islands + scan routeDir without importing user code (#3122)

This fixes a bunch of long standing issues in our tracker where a build
wouldn't finish because of importing user code. It's common for backend
apps to spawn some open ended tasks like subscribing to Deno KV or other
things. This addresses another problem of having to set up ENV vars just
for the build, even though they are technically not required to build
islands.

This also gives a roughly ~30% performance boost on cold starts (at
least on `deno.com`). Unfortunately, this does require some breaking
changes. But I believe the performance improvements + removing the
footgun of loading user code during build is well worth it. This work is
also a precursor in case we want to exploring moving to vite at some
point in the future.

## Breaking changes

1. Build options have moved to the builder.
```diff
  // main.ts
- const app = new App({ build: { outDir: "dist/" } })
+ const app = new App()

  // dev.ts
- const builder = new Builder();
+ const builder = new Builder({ outDir: "dist/" });
```

2. Another breaking change is how file based routes are loaded. Since
they're prepared and loaded by the builder the API changed.

```diff
  // main.ts
  const app = new App()
    .use(staticFiles())
  
- await fsRoutes(app, {
-   loadIsland: (path) => import(`./islands/${path}`),
-   loadRoute: (path) => import(`./routes/${path}`),
- }); 
+ app.fsRoutes()
```
You can optionally change the `islandDir` or `routeDir` by passing that
to the `Builder`:

```ts
// dev.ts
const builder = new Builder({
  islandDir: "/path/to/islands", 
  routeDir: "/path/to/routes"
});
```

3. Import `app` lazily in `dev.ts`. Passing `app` to `builder.build()`
is not necessary anymore.

```diff
- import { app } from "./main.ts";

  const builder = new Builder({ target: "safari12" });
  
  if (Deno.args.includes("build")) {
-    await builder.build(app);
+    await builder.build();
  } else {
-   await builder.listen(app);
+   await builder.listen(() => import("./main.ts"));
  }
```

4. The production run command has changed. It's now using `deno serve`
```diff
  // deno.json
  {
    "tasks": {
      "dev": "deno run -A --watch=static/,routes/ dev.ts",
      "dev": "deno run -A dev.ts build",
-     "start": "deno run -A main.ts",
+     "start": "deno serve -A _fresh/server.js",
    }
  }
```
Remove this bit in `main.ts`:

```diff
  // main.ts
  
- if (import.meta.main) {
-   await app.listen()
- }
```

Fixes https://github.com/denoland/fresh/issues/2240
Fixes https://github.com/denoland/fresh/issues/2640
Fixes https://github.com/denoland/fresh/issues/2592
Fixes https://github.com/denoland/fresh/issues/1843
This commit is contained in:
Marvin Hagemeister
2025-07-24 15:04:05 +02:00
committed by GitHub
parent 69af00ef65
commit 118242eaa6
54 changed files with 1911 additions and 1770 deletions
+271 -143
View File
@@ -1,29 +1,31 @@
import {
App,
getBuildCache,
getIslandRegistry,
type ListenOptions,
setBuildCache,
} from "../app.ts";
import { App, type ListenOptions, setBuildCache } from "../app.ts";
import { fsAdapter } from "../fs.ts";
import * as path from "@std/path";
import * as colors from "@std/fmt/colors";
import { bundleJs } from "./esbuild.ts";
import * as JSONC from "@std/jsonc";
import { liveReload } from "./middlewares/live_reload.ts";
import {
cssAssetHash,
FreshFileTransformer,
FileTransformer,
type OnTransformOptions,
} from "./file_transformer.ts";
import type { TransformFn } from "./file_transformer.ts";
import { DiskBuildCache, MemoryBuildCache } from "./dev_build_cache.ts";
import type { Island } from "../context.ts";
import {
type DevBuildCache,
DiskBuildCache,
type FsRoute,
MemoryBuildCache,
} from "./dev_build_cache.ts";
import { BUILD_ID } from "../runtime/build_id.ts";
import { updateCheck } from "./update_check.ts";
import { DAY } from "@std/datetime";
import { devErrorOverlay } from "./middlewares/error_overlay/middleware.tsx";
import { automaticWorkspaceFolders } from "./middlewares/automatic_workspace_folders.ts";
import { parseDirPath } from "../config.ts";
import { pathToExportName, UniqueNamer } from "../utils.ts";
import { checkDenoCompilerOptions } from "./check.ts";
import { crawlRouteDir, walkDir } from "./fs_crawl.ts";
export interface BuildOptions {
/**
@@ -33,20 +35,99 @@ export interface BuildOptions {
* @default {"es2022"}
*/
target?: string | string[];
/**
* The root directory of the Fresh project.
*
* Other paths, such as `build.outDir`, `staticDir`, and `fsRoutes()`
* are resolved relative to this directory.
* @default Deno.cwd()
*/
root?: string;
/**
* The directory to write generated files to when `dev.ts build` is run.
*
* This can be an absolute path, a file URL or a relative path.
* Relative paths are resolved against the `root` option.
* @default "_fresh"
*/
outDir?: string;
/**
* The directory to serve static files from.
*
* This can be an absolute path, a file URL or a relative path.
* Relative paths are resolved against the `root` option.
* @default "static"
*/
staticDir?: string;
/**
* The directory which contains islands.
*
* This can be an absolute path, a file URL or a relative path.
* Relative paths are resolved against the `root` option.
* @default "islands"
*/
islandDir?: string;
/**
* The directory which contains routes.
*
* This can be an absolute path, a file URL or a relative path.
* Relative paths are resolved against the `root` option.
* @default "routes"
*/
routeDir?: string;
/**
* File paths which should be ignored when crawling the file system.
*/
ignore?: RegExp[];
}
export class Builder {
#transformer = new FreshFileTransformer(fsAdapter);
/**
* The final resolved Builder configuration.
*/
export type ResolvedBuildConfig = Required<BuildOptions> & {
mode: "development" | "production";
buildId: string;
};
const TEST_FILE_PATTERN = /[._]test\.(?:[tj]sx?|[mc][tj]s)$/;
// deno-lint-ignore no-explicit-any
export class Builder<State = any> {
#transformer: FileTransformer;
#addedInternalTransforms = false;
#options: Required<BuildOptions>;
#chunksReady = Promise.withResolvers<void>();
config: ResolvedBuildConfig;
#islandSpecifiers = new Set<string>();
#fsRoutes: FsRoute<State>;
#ready = Promise.withResolvers<void>();
constructor(options?: BuildOptions) {
this.#options = {
const root = parseDirPath(options?.root ?? ".", Deno.cwd());
const outDir = parseDirPath(options?.outDir ?? "_fresh", root);
const staticDir = parseDirPath(options?.staticDir ?? "static", root);
const islandDir = parseDirPath(options?.islandDir ?? "islands", root);
const routeDir = parseDirPath(options?.routeDir ?? "routes", root);
this.#fsRoutes = { dir: routeDir, files: [], id: "default" };
this.#transformer = new FileTransformer(fsAdapter, root);
this.config = {
target: options?.target ?? ["chrome99", "firefox99", "safari15"],
root,
outDir,
staticDir,
islandDir,
routeDir,
ignore: options?.ignore ?? [TEST_FILE_PATTERN],
mode: "production",
buildId: BUILD_ID,
};
}
registerIsland(specifier: string): void {
this.#islandSpecifiers.add(specifier);
}
onTransformStaticFile(
options: OnTransformOptions,
callback: TransformFn,
@@ -54,75 +135,144 @@ export class Builder {
this.#transformer.onTransform(options, callback);
}
async listen<T>(app: App<T>, options: ListenOptions = {}): Promise<void> {
async listen(
importApp: () => Promise<{ app: App<State> } | App<State>>,
options: ListenOptions = {},
): Promise<void> {
// Run update check in background
updateCheck(DAY).catch(() => {});
const devApp = new App<T>(app.config)
this.config.mode = "development";
await this.#crawlFsItems();
let app = await importApp();
if (!(app instanceof App) && "app" in app) {
app = app.app;
}
const buildCache = new MemoryBuildCache<State>(
this.config,
this.#fsRoutes,
this.#transformer,
);
await buildCache.prepare();
const devApp = new App<State>(app.config)
.use(liveReload())
.use(devErrorOverlay())
.use(automaticWorkspaceFolders(app.config.root))
// Wait for island chunks to be ready before attempting to serve them
.use(automaticWorkspaceFolders(this.config.root))
// Wait for islands to be ready
.use(async (ctx) => {
await this.#chunksReady.promise;
return await ctx.next();
await this.#ready.promise;
return ctx.next();
})
.mountApp("/*", app);
devApp.config.root = this.config.root;
devApp.config.mode = "development";
setBuildCache(
devApp,
new MemoryBuildCache(
devApp.config,
BUILD_ID,
this.#transformer,
this.#options.target,
),
);
setBuildCache(devApp, buildCache);
// Boot in parallel to spin up the server quicker. We'll hold
// requests until the required assets are processed.
await Promise.all([
devApp.listen(options),
this.#build(devApp, true),
this.#build(buildCache, true),
]);
return;
}
async build<T>(app: App<T>): Promise<void> {
setBuildCache(
app,
new DiskBuildCache(
app.config,
BUILD_ID,
this.#transformer,
this.#options.target,
),
);
/**
* Build optimized assets for your app. By default this will create
* a production build.
*
* This can also be used for testing to apply a snapshot to a particular
* {@linkcode App} instance.
*
* @example
* ```ts
* const builder = new Builder();
* const applySnapshot = await builder.build({ snapshot: "memory" });
*
* Deno.test("My Test", () => {
* const app = new App()
* .get("/", () => new Response("hello"))
*
* applySnapshot(app)
*
* // ... your usual testing
* })
* ```
* @param options
* @returns Apply a snapshot to a particular {@linkcode App} instance.
*/
async build(
options?: {
mode?: ResolvedBuildConfig["mode"];
snapshot?: "disk" | "memory";
},
): Promise<(app: App<State>) => void> {
this.config.mode = options?.mode ?? "production";
return await this.#build(app, false);
await this.#crawlFsItems();
const buildCache = options?.snapshot === "memory"
? new MemoryBuildCache(
this.config,
this.#fsRoutes,
this.#transformer,
)
: new DiskBuildCache(
this.config,
this.#fsRoutes,
this.#transformer,
);
await this.#build(buildCache, this.config.mode === "development");
await buildCache.prepare();
return (app) => {
setBuildCache(app, buildCache);
};
}
async #build<T>(app: App<T>, dev: boolean): Promise<void> {
const { build } = app.config;
const staticOutDir = path.join(build.outDir, "static");
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,
),
]);
}
async #build<T>(buildCache: DevBuildCache<T>, dev: boolean): Promise<void> {
const { target, outDir, root } = this.config;
const staticOutDir = path.join(outDir, "static");
const { denoJson, jsxImportSource } = await checkDenoCompilerOptions(root);
if (!this.#addedInternalTransforms) {
this.#addedInternalTransforms = true;
cssAssetHash(this.#transformer);
}
const target = this.#options.target;
try {
await Deno.remove(staticOutDir);
} catch {
// Ignore
}
const buildCache = getBuildCache(app)! as
| MemoryBuildCache
| DiskBuildCache;
const runtimePath = dev
? "../runtime/client/dev.ts"
: "../runtime/client/mod.tsx";
@@ -130,130 +280,108 @@ export class Builder {
const entryPoints: Record<string, string> = {
"fresh-runtime": new URL(runtimePath, import.meta.url).href,
};
const seenEntries = new Map<string, Island>();
const mapIslandToEntry = new Map<Island, string>();
const islandRegistry = getIslandRegistry(app);
for (const island of islandRegistry.values()) {
const filePath = island.file instanceof URL
? island.file.href
: island.file;
const seen = seenEntries.get(filePath);
if (seen !== undefined) {
mapIslandToEntry.set(island, seen.name);
} else {
entryPoints[island.name] = filePath;
seenEntries.set(filePath, island);
mapIslandToEntry.set(island, island.name);
}
}
const namer = new UniqueNamer();
for (const spec of this.#islandSpecifiers) {
const specName = specToName(spec);
const name = namer.getUniqueName(specName);
const denoJson = await findNearestDenoConfigWithCompilerOptions(
app.config.root,
);
entryPoints[name] = spec;
const jsxImportSource = denoJson.config.compilerOptions?.jsxImportSource;
if (jsxImportSource === undefined) {
throw new Error(
`Option compilerOptions > jsxImportSource not set in: ${denoJson.filePath}`,
);
}
// Check precompile option
if (denoJson.config.compilerOptions?.jsx === "precompile") {
const expected = ["a", "img", "source", "body", "html", "head"];
const skipped = denoJson.config.compilerOptions.jsxPrecompileSkipElements;
if (!skipped || expected.some((name) => !skipped.includes(name))) {
throw new Error(
`Expected option compilerOptions > jsxPrecompileSkipElements to contain ${
expected.map((name) => `"${name}"`).join(", ")
}`,
);
}
buildCache.islandModNameToChunk.set(name, {
name,
server: spec,
browser: null,
});
}
const output = await bundleJs({
cwd: app.config.root,
cwd: root,
outDir: staticOutDir,
dev: dev ?? false,
target,
buildId: BUILD_ID,
entryPoints,
jsxImportSource,
denoJsonPath: denoJson.filePath,
denoJsonPath: denoJson,
});
const prefix = `/_fresh/js/${BUILD_ID}/`;
for (const name of buildCache.islandModNameToChunk.keys()) {
const chunkName = output.entryToChunk.get(name);
if (chunkName === undefined) {
throw new Error(`Could not find chunk for island ${name}`);
}
const pathname = `${prefix}${chunkName}`;
buildCache.islandModNameToChunk.get(name)!.browser = pathname;
}
for (let i = 0; i < output.files.length; i++) {
const file = output.files[i];
const pathname = `${prefix}${file.path}`;
await buildCache.addProcessedFile(pathname, file.contents, file.hash);
}
// Go through same entry islands
for (const [island, entry] of mapIslandToEntry.entries()) {
const chunk = output.entryToChunk.get(entry);
if (chunk === undefined) {
throw new Error(
`Missing chunk for ${island.file}#${island.exportName}`,
);
}
buildCache.islands.set(island.name, `${prefix}${chunk}`);
}
await buildCache.flush();
this.#chunksReady.resolve();
if (!dev) {
// deno-lint-ignore no-console
console.log(
`Assets written to: ${colors.cyan(build.outDir)}`,
`Assets written to: ${colors.cyan(outDir)}`,
);
}
this.#ready.resolve();
}
}
export interface DenoConfig {
workspace?: string[];
compilerOptions?: {
jsx?: string;
jsxImportSource?: string;
jsxPrecompileSkipElements?: string[];
};
}
export async function findNearestDenoConfigWithCompilerOptions(
directory: string,
): Promise<{ config: DenoConfig; filePath: string }> {
let dir = directory;
while (true) {
for (const name of ["deno.json", "deno.jsonc"]) {
const filePath = path.join(dir, name);
try {
const file = await Deno.readTextFile(filePath);
let config;
if (name.endsWith(".jsonc")) {
config = JSONC.parse(file);
} else {
config = JSON.parse(file);
}
if (config.compilerOptions) return { config, filePath };
if (config.workspace) break;
break;
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
export function specToName(spec: string): string {
if (/^(https?:|file:)/.test(spec)) {
const url = new URL(spec);
if (url.pathname === "/") {
return pathToExportName(url.hostname);
}
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
const idx = spec.lastIndexOf("/");
return spec.slice(idx + 1);
} else if (spec.startsWith("jsr:")) {
const match = spec.match(
/jsr:@([^/]+)\/([^@/]+)(@[\^~]?\d+\.\d+\.\d+([^/]+)?)?(\/.*)?$/,
)!;
if (match[5] === undefined) {
return pathToExportName(`${match[1]}_${match[2]}`);
}
return pathToExportName(match[5]);
} else if (spec.startsWith("npm:")) {
const match = spec.match(
/npm:(@([^/]+)\/([^@/]+)|[^@/]+)(@[\^~]?\d+\.\d+\.\d+([^/]+)?)?(\/.*)?$/,
)!;
if (match[6] === undefined) {
if (match[2] === undefined) {
return pathToExportName(match[1]);
}
return pathToExportName(`${match[2]}_${match[3]}`);
}
return pathToExportName(match[6]);
}
throw new Error(
`Could not find a deno.json or deno.jsonc file in the current directory or any parent directory that contains a 'compilerOptions' field.`,
);
const match = spec.match(/^(@([^/]+)\/([^@/]+)|[^@/]+)(\/.*)?$/);
if (match !== null) {
if (match[4] === undefined) {
if (match[2] !== undefined) {
return pathToExportName(`${match[2]}_${match[3]}`);
}
return pathToExportName(match[1]);
}
return pathToExportName(match[4]);
}
return pathToExportName(spec);
}
+101 -65
View File
@@ -1,16 +1,21 @@
import { expect } from "@std/expect";
import * as path from "@std/path";
import { Builder } from "./builder.ts";
import { Builder, specToName } from "./builder.ts";
import { App } from "../app.ts";
import { RemoteIsland } from "@marvinh-test/fresh-island";
import { BUILD_ID } from "../runtime/build_id.ts";
import { withTmpDir } from "../test_utils.ts";
Deno.test({
name: "Builder - chain onTransformStaticFile",
fn: async () => {
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const logs: string[] = [];
const builder = new Builder();
const builder = new Builder({
outDir: path.join(tmp, "dist"),
staticDir: tmp,
});
builder.onTransformStaticFile(
{ pluginName: "A", filter: /\.css$/ },
() => {
@@ -30,16 +35,8 @@ Deno.test({
},
);
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
await Deno.writeTextFile(path.join(tmp, "foo.css"), "body { color: red; }");
const app = new App({
staticDir: tmp,
build: {
outDir: path.join(tmp, "dist"),
},
});
await builder.build(app);
await builder.build();
expect(logs).toEqual(["A", "B", "C"]);
},
@@ -50,24 +47,22 @@ Deno.test({
Deno.test({
name: "Builder - handles Windows paths",
fn: async () => {
const builder = new Builder();
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const builder = new Builder({
outDir: path.join(tmp, "dist"),
staticDir: tmp,
});
await Deno.mkdir(path.join(tmp, "images"));
await Deno.writeTextFile(
path.join(tmp, "images", "batman.svg"),
"<svg></svg>",
);
const app = new App({
staticDir: tmp,
build: {
outDir: path.join(tmp, "dist"),
},
});
await builder.build(app);
await builder.build();
const snapshotJson = await Deno.readTextFile(
path.join(tmp, "dist", "snapshot.json"),
path.join(tmp, "dist", "static-files.json"),
);
expect(snapshotJson).toContain("/images/batman.svg");
},
@@ -78,20 +73,18 @@ Deno.test({
Deno.test({
name: "Builder - hashes CSS urls by default",
fn: async () => {
const builder = new Builder();
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const builder = new Builder({
outDir: path.join(tmp, "dist"),
staticDir: tmp,
});
await Deno.writeTextFile(
path.join(tmp, "foo.css"),
"body { background: url('/foo.jpg'); }",
);
const app = new App({
staticDir: tmp,
build: {
outDir: path.join(tmp, "dist"),
},
});
await builder.build(app);
await builder.build();
const css = await Deno.readTextFile(
path.join(tmp, "dist", "static", "foo.css"),
@@ -106,20 +99,17 @@ Deno.test({
Deno.test({
name: "Builder - hashes CSS urls by default",
fn: async () => {
const builder = new Builder();
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const builder = new Builder({
outDir: path.join(tmp, "dist"),
staticDir: tmp,
});
await Deno.writeTextFile(
path.join(tmp, "foo.css"),
`:root { --icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(76, 154.5, 137.5)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E"); }`,
);
const app = new App({
staticDir: tmp,
build: {
outDir: path.join(tmp, "dist"),
},
});
await builder.build(app);
await builder.build();
const css = await Deno.readTextFile(
path.join(tmp, "dist", "static", "foo.css"),
@@ -135,20 +125,18 @@ Deno.test({
Deno.test({
name: "Builder - can bundle islands from JSR",
fn: async () => {
const builder = new Builder();
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const app = new App({
staticDir: tmp,
build: {
outDir: path.join(tmp, "dist"),
},
});
app.island("jsr:@marvinh-test/fresh-island", "RemoteIsland", RemoteIsland);
const outDir = path.join(tmp, "dist");
const builder = new Builder({ outDir });
await builder.build(app);
const specifier = "jsr:@marvinh-test/fresh-island";
builder.registerIsland(specifier);
await builder.build();
const name = specToName(specifier);
const code = await Deno.readTextFile(
path.join(
tmp,
@@ -157,7 +145,7 @@ Deno.test({
"_fresh",
"js",
BUILD_ID,
"RemoteIsland.js",
`${name}.js`,
),
);
expect(code).toContain('"remote-island"');
@@ -169,8 +157,14 @@ Deno.test({
Deno.test({
name: "Builder - exclude files",
fn: async () => {
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const logs: string[] = [];
const builder = new Builder();
const builder = new Builder({
outDir: path.join(tmp, "dist"),
staticDir: tmp,
});
// String
builder.onTransformStaticFile(
@@ -196,20 +190,12 @@ Deno.test({
},
);
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
await Deno.writeTextFile(path.join(tmp, "foo.css"), "body { color: red; }");
await Deno.writeTextFile(
path.join(tmp, "bar.css"),
"body { color: blue; }",
);
const app = new App({
staticDir: tmp,
build: {
outDir: path.join(tmp, "dist"),
},
});
await builder.build(app);
await builder.build();
expect(logs).toEqual(["A: bar.css", "B: bar.css", "C: bar.css"]);
},
@@ -220,17 +206,20 @@ Deno.test({
Deno.test({
name: "Builder - workspace folder middleware on listen",
fn: async () => {
const builder = new Builder();
const tmp = await Deno.makeTempDir();
const app = new App({
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const builder = new Builder({
outDir: path.join(tmp, "dist"),
staticDir: tmp,
build: {
outDir: path.join(tmp, "dist"),
},
});
const app = new App();
const abort = new AbortController();
const port = 8011;
await builder.listen(app, { port, signal: abort.signal });
await builder.listen(() => Promise.resolve(app), {
port,
signal: abort.signal,
});
const res = await fetch(
`http://localhost:${port}/.well-known/appspecific/com.chrome.devtools.json`,
@@ -243,7 +232,7 @@ Deno.test({
expect(res.headers.get("etag")).toEqual(expect.any(String));
expect(json).toEqual({
workspace: {
root: app.config.root,
root: builder.config.root,
uuid: expect.any(String),
},
});
@@ -251,3 +240,50 @@ Deno.test({
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test("specToName", () => {
// HTTP
expect(specToName("http://example.com")).toEqual("example");
expect(specToName("http://example.com:8000")).toEqual("example");
expect(specToName("http://example.com:8000/foo/bar")).toEqual(
"bar",
);
// HTTPS
expect(specToName("https://example.com")).toEqual("example");
expect(specToName("https://example.com:8000")).toEqual("example");
expect(specToName("https://example.com:8000/foo/bar")).toEqual(
"bar",
);
// JSR
expect(specToName("jsr:@foo/bar")).toEqual("foo_bar");
expect(specToName("jsr:@foo/bar@1.0.0")).toEqual("foo_bar");
expect(specToName("jsr:@foo/bar@^1.0.0")).toEqual("foo_bar");
expect(specToName("jsr:@foo/bar@~1.0.0")).toEqual("foo_bar");
expect(specToName("jsr:@foo/bar@~1.0.0-alpha.32")).toEqual("foo_bar");
expect(specToName("jsr:@foo/bar@~1.0.0-alpha.32/asdf")).toEqual("asdf");
expect(specToName("jsr:@foo/bar/asdf")).toEqual("asdf");
// npm
expect(specToName("npm:foo")).toEqual("foo");
expect(specToName("npm:foo/bar")).toEqual("bar");
expect(specToName("npm:foo@1.0.0")).toEqual("foo");
expect(specToName("npm:foo@^1.0.0")).toEqual("foo");
expect(specToName("npm:foo@~1.0.0-alpha.32")).toEqual("foo");
expect(specToName("npm:@foo/bar")).toEqual("foo_bar");
expect(specToName("npm:@foo/bar/asdf")).toEqual("asdf");
expect(specToName("npm:@foo/bar@1.0.0")).toEqual("foo_bar");
expect(specToName("npm:@foo/bar@^1.0.0")).toEqual("foo_bar");
expect(specToName("npm:@foo/bar@~1.0.0-alpha.32")).toEqual("foo_bar");
// other
expect(specToName("foo")).toEqual("foo");
expect(specToName("@foo/bar")).toEqual("foo_bar");
expect(specToName("foo/bar")).toEqual("bar");
expect(specToName("@foo/bar/asdf")).toEqual("asdf");
expect(specToName("islands/foo.v2.tsx")).toEqual("foo_v2");
expect(specToName("/islands/_bar-baz-...-$.tsx")).toEqual("_bar_baz_$");
expect(specToName("/islands/1_hello.tsx")).toEqual("_hello");
});
+73
View File
@@ -0,0 +1,73 @@
import * as JSONC from "@std/jsonc";
import * as path from "@std/path";
export interface DenoConfig {
workspace?: string[];
compilerOptions?: {
jsx?: string;
jsxImportSource?: string;
jsxPrecompileSkipElements?: string[];
};
}
export async function checkDenoCompilerOptions(root: string) {
const denoJson = await findNearestDenoConfigWithCompilerOptions(
root,
);
const jsxImportSource = denoJson.config.compilerOptions?.jsxImportSource;
if (jsxImportSource === undefined) {
throw new Error(
`Option compilerOptions > jsxImportSource not set in: ${denoJson.filePath}`,
);
}
// Check precompile option
if (denoJson.config.compilerOptions?.jsx === "precompile") {
const expected = ["a", "img", "source", "body", "html", "head"];
const skipped = denoJson.config.compilerOptions.jsxPrecompileSkipElements;
if (!skipped || expected.some((name) => !skipped.includes(name))) {
throw new Error(
`Expected option compilerOptions > jsxPrecompileSkipElements to contain ${
expected.map((name) => `"${name}"`).join(", ")
}`,
);
}
}
return { jsxImportSource, denoJson: denoJson.filePath };
}
export async function findNearestDenoConfigWithCompilerOptions(
directory: string,
): Promise<{ config: DenoConfig; filePath: string }> {
let dir = directory;
while (true) {
for (const name of ["deno.json", "deno.jsonc"]) {
const filePath = path.join(dir, name);
try {
const file = await Deno.readTextFile(filePath);
let config;
if (name.endsWith(".jsonc")) {
config = JSONC.parse(file);
} else {
config = JSON.parse(file);
}
if (config.compilerOptions) return { config, filePath };
if (config.workspace) break;
break;
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
}
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
throw new Error(
`Could not find a deno.json or deno.jsonc file in the current directory or any parent directory that contains a 'compilerOptions' field.`,
);
}
+221 -76
View File
@@ -1,50 +1,79 @@
import type { BuildCache, StaticFile } from "../build_cache.ts";
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 { getSnapshotPath, type ResolvedFreshConfig } from "../config.ts";
import type { BuildSnapshot } from "../build_cache.ts";
import { encodeHex } from "@std/encoding/hex";
import { crypto } from "@std/crypto";
import { fsAdapter } from "../fs.ts";
import type { FreshFileTransformer } from "./file_transformer.ts";
import { assertInDir } from "../utils.ts";
import type { FileTransformer } from "./file_transformer.ts";
import { assertInDir, pathToSpec } from "../utils.ts";
import type { ResolvedBuildConfig } from "./builder.ts";
import { fsItemsToCommands, type FsRouteFile } from "../fs_routes.ts";
import type { Command } from "../commands.ts";
import type { ServerIslandRegistry } from "../context.ts";
export interface MemoryFile {
hash: string | null;
content: Uint8Array;
}
export interface DevBuildCache extends BuildCache {
islands: Map<string, string>;
export interface IslandModChunk {
name: string;
server: string;
browser: string | null;
}
addUnprocessedFile(pathname: string): void;
export type FsRouteFileNoMod<State> = Omit<FsRouteFile<State>, "mod">;
export interface FsRoute<State> {
id: string;
dir: string;
files: FsRouteFileNoMod<State>[];
}
export interface DevBuildCache<State> extends BuildCache<State> {
islandModNameToChunk: Map<string, IslandModChunk>;
addUnprocessedFile(pathname: string, dir: string): void;
addProcessedFile(
pathname: string,
content: Uint8Array,
hash: string | null,
): Promise<void>;
flush(): Promise<void>;
prepare(): Promise<void>;
}
export class MemoryBuildCache implements DevBuildCache {
hasSnapshot = true;
islands = new Map<string, string>();
export class MemoryBuildCache<State> implements DevBuildCache<State> {
#processedFiles = new Map<string, MemoryFile>();
#unprocessedFiles = new Map<string, string>();
#ready = Promise.withResolvers<void>();
#config: ResolvedBuildConfig;
#transformer: FileTransformer;
islandModNameToChunk = new Map<string, IslandModChunk>();
#fsRoutes: FsRoute<State>;
#commands: Command<State>[] = [];
root: string;
islandRegistry: ServerIslandRegistry = new Map();
constructor(
public config: ResolvedFreshConfig,
public buildId: string,
public transformer: FreshFileTransformer,
public target: string | string[],
config: ResolvedBuildConfig,
fsRoutes: FsRoute<State>,
transformer: FileTransformer,
) {
this.#config = config;
this.#fsRoutes = fsRoutes;
this.#transformer = transformer;
this.root = config.root;
}
getFsRoutes(): Command<State>[] {
return this.#commands;
}
async readFile(pathname: string): Promise<StaticFile | null> {
await this.#ready.promise;
const processed = this.#processedFiles.get(pathname);
if (processed !== undefined) {
return {
@@ -69,14 +98,14 @@ export class MemoryBuildCache implements DevBuildCache {
readable: file.readable,
close: () => file.close(),
};
} catch (_err) {
} catch {
return null;
}
}
let entry = pathname.startsWith("/") ? pathname.slice(1) : pathname;
entry = path.join(this.config.staticDir, entry);
const relative = path.relative(this.config.staticDir, entry);
entry = path.join(this.#config.staticDir, entry);
const relative = path.relative(this.#config.staticDir, entry);
if (relative.startsWith("..")) {
throw new Error(
`Processed file resolved outside of static dir ${entry}`,
@@ -84,16 +113,16 @@ export class MemoryBuildCache implements DevBuildCache {
}
// Might be a file that we still need to process
const transformed = await this.transformer.process(
const transformed = await this.#transformer.process(
entry,
"development",
this.target,
this.#config.target,
);
if (transformed !== null) {
for (let i = 0; i < transformed.length; i++) {
const file = transformed[i];
const relative = path.relative(this.config.staticDir, file.path);
const relative = path.relative(this.#config.staticDir, file.path);
if (relative.startsWith(".")) {
throw new Error(
`Processed file resolved outside of static dir ${file.path}`,
@@ -108,10 +137,10 @@ export class MemoryBuildCache implements DevBuildCache {
}
} else {
try {
const filePath = path.join(this.config.staticDir, pathname);
const relative = path.relative(this.config.staticDir, filePath);
const filePath = path.join(this.#config.staticDir, pathname);
const relative = path.relative(this.#config.staticDir, filePath);
if (!relative.startsWith(".") && (await Deno.stat(filePath)).isFile) {
this.addUnprocessedFile(pathname);
this.addUnprocessedFile(pathname, this.#config.staticDir);
return this.readFile(pathname);
}
} catch (err) {
@@ -124,14 +153,10 @@ export class MemoryBuildCache implements DevBuildCache {
return null;
}
getIslandChunkName(islandName: string): string | null {
return this.islands.get(islandName) ?? null;
}
addUnprocessedFile(pathname: string): void {
addUnprocessedFile(pathname: string, dir: string): void {
this.#unprocessedFiles.set(
pathname,
path.join(this.config.staticDir, pathname),
path.join(dir, pathname),
);
}
@@ -144,39 +169,68 @@ export class MemoryBuildCache implements DevBuildCache {
this.#processedFiles.set(pathname, { content, hash });
}
// deno-lint-ignore require-await
async flush(): Promise<void> {
this.#ready.resolve();
const preparer = new IslandPreparer();
// Load islands
await Promise.all(
Array.from(this.islandModNameToChunk.entries()).map(
async ([name, chunk]) => {
const fileUrl = path.toFileUrl(chunk.server);
const mod = await import(fileUrl.href);
if (chunk.browser === null) {
throw new Error(`Unexpected missing browser chunk`);
}
preparer.prepare(this.islandRegistry, mod, chunk.browser, name);
},
),
);
}
async prepare(): Promise<void> {
// Load FS routes
const files = await Promise.all(this.#fsRoutes.files.map(async (file) => {
const fileUrl = path.toFileUrl(file.filePath);
return {
...file,
mod: await import(fileUrl.href),
};
}));
this.#commands = fsItemsToCommands(files);
}
}
// await fsAdapter.mkdirp(staticOutDir);
export class DiskBuildCache implements DevBuildCache {
hasSnapshot = true;
islands = new Map<string, string>();
export class DiskBuildCache<State> implements DevBuildCache<State> {
#processedFiles = new Map<string, string | null>();
#unprocessedFiles = new Map<string, string>();
#transformer: FreshFileTransformer;
#target: string | string[];
#transformer: FileTransformer;
#config: ResolvedBuildConfig;
islandModNameToChunk = new Map<string, IslandModChunk>();
#fsRoutes: FsRoute<State>;
root: string;
islandRegistry: ServerIslandRegistry = new Map();
constructor(
public config: ResolvedFreshConfig,
public buildId: string,
transformer: FreshFileTransformer,
target: string | string[],
config: ResolvedBuildConfig,
fsRoutes: FsRoute<State>,
transformer: FileTransformer,
) {
this.#fsRoutes = fsRoutes;
this.#transformer = transformer;
this.#target = target;
this.#config = config;
this.root = config.root;
}
getIslandChunkName(islandName: string): string | null {
return this.islands.get(islandName) ?? null;
getFsRoutes(): Command<State>[] {
return [];
}
addUnprocessedFile(pathname: string): void {
addUnprocessedFile(pathname: string, dir: string): void {
this.#unprocessedFiles.set(
pathname.replaceAll(WINDOWS_SEPARATOR, "/"),
path.join(this.config.staticDir, pathname),
path.join(dir, pathname),
);
}
@@ -188,8 +242,8 @@ export class DiskBuildCache implements DevBuildCache {
this.#processedFiles.set(pathname, hash);
const outDir = pathname === "/metafile.json"
? this.config.build.outDir
: path.join(this.config.build.outDir, "static");
? this.#config.outDir
: path.join(this.#config.outDir, "static");
const filePath = path.join(outDir, pathname);
assertInDir(filePath, outDir);
@@ -202,9 +256,12 @@ export class DiskBuildCache implements DevBuildCache {
throw new Error("Not implemented in build mode");
}
async prepare(): Promise<void> {
// not needed
}
async flush(): Promise<void> {
const staticDir = this.config.staticDir;
const outDir = this.config.build.outDir;
const { staticDir, outDir, target, root } = this.#config;
if (await fsAdapter.isDirectory(staticDir)) {
const entries = fsAdapter.walk(staticDir, {
@@ -224,7 +281,7 @@ export class DiskBuildCache implements DevBuildCache {
const result = await this.#transformer.process(
entry.path,
"production",
this.#target,
target,
);
if (result !== null) {
@@ -237,30 +294,21 @@ export class DiskBuildCache implements DevBuildCache {
} else {
const relative = path.relative(staticDir, entry.path);
const pathname = `/${relative}`;
this.addUnprocessedFile(pathname);
this.addUnprocessedFile(pathname, staticDir);
}
}
}
const snapshot: BuildSnapshot = {
version: 1,
buildId: this.buildId,
islands: {},
staticFiles: {},
};
for (const [name, chunk] of this.islands.entries()) {
snapshot.islands[name] = chunk;
}
const staticFiles = new Map<string, FileSnapshot>();
for (const [name, filePath] of this.#unprocessedFiles.entries()) {
const file = await Deno.open(filePath);
const hash = await hashContent(file.readable);
snapshot.staticFiles[name] = {
staticFiles.set(name, {
name,
hash,
generated: false,
};
filePath: path.relative(root, filePath),
});
}
for (const [name, maybeHash] of this.#processedFiles.entries()) {
@@ -271,21 +319,118 @@ export class DiskBuildCache implements DevBuildCache {
continue;
}
const filePath = path.join(outDir, "static", name);
if (maybeHash === null) {
const filePath = path.join(this.config.build.outDir, "static", name);
const file = await Deno.open(filePath);
hash = await hashContent(file.readable);
}
snapshot.staticFiles[name] = {
staticFiles.set(name, {
name,
hash,
generated: true,
};
filePath: path.relative(root, filePath),
});
}
await Deno.writeTextFile(
getSnapshotPath(this.config),
JSON.stringify(snapshot, null, 2),
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(path.relative(outDir, item.server));
return `import * as ${item.name} from "${spec}";`;
})
.join("\n")
}
// Import routes
${
this.#fsRoutes.files
.map((item, i) => {
const spec = pathToSpec(path.relative(outDir, item.filePath));
return `import * as fsRoute_${i} from "${spec}"`;
})
.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);
return ` { id: ${id}, mod: fsRoute_${i}, type: ${
JSON.stringify(item.type)
}, pattern: ${pattern} },`;
})
.join("\n")
}
];
`,
);
// 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()
}`,
);
}
}
+12 -12
View File
@@ -1,30 +1,30 @@
import { expect } from "@std/expect";
import * as path from "@std/path";
import { MemoryBuildCache } from "./dev_build_cache.ts";
import { FreshFileTransformer } from "./file_transformer.ts";
import { FileTransformer } from "./file_transformer.ts";
import { createFakeFs, withTmpDir } from "../test_utils.ts";
import type { ResolvedFreshConfig } from "../mod.ts";
import type { ResolvedBuildConfig } from "./builder.ts";
Deno.test({
name: "MemoryBuildCache - should error if reading outside of staticDir",
fn: async () => {
await using _tmp = await withTmpDir();
const tmp = _tmp.dir;
const config: ResolvedFreshConfig = {
const config: ResolvedBuildConfig = {
root: tmp,
mode: "development",
basePath: "/",
staticDir: path.join(tmp, "static"),
build: {
outDir: path.join(tmp, "dist"),
},
buildId: "",
ignore: [],
islandDir: "",
outDir: "",
routeDir: "",
staticDir: "",
target: "latest",
};
const fileTransformer = new FreshFileTransformer(createFakeFs({}));
const fileTransformer = new FileTransformer(createFakeFs({}), tmp);
const buildCache = new MemoryBuildCache(
config,
"testing",
{ dir: "", files: [], id: "" },
fileTransformer,
"latest",
);
const thrown = buildCache.readFile("../SECRETS.txt");
+7 -3
View File
@@ -23,6 +23,7 @@ export interface OnTransformArgs {
text: string;
content: Uint8Array;
mode: TransformMode;
root: string;
}
export type TransformFn = (
args: OnTransformArgs,
@@ -56,12 +57,14 @@ interface TransformReq {
inputFiles: string[];
}
export class FreshFileTransformer {
export class FileTransformer {
#transformers: Transformer[] = [];
#fs: FsAdapter;
#root: string;
constructor(fs: FsAdapter) {
constructor(fs: FsAdapter, root: string) {
this.#fs = fs;
this.#root = root;
}
onTransform(options: OnTransformOptions, callback: TransformFn): void {
@@ -147,6 +150,7 @@ export class FreshFileTransformer {
mode,
target,
content: req!.content,
root: this.#root,
get text() {
return new TextDecoder().decode(req!.content);
},
@@ -243,7 +247,7 @@ export class FreshFileTransformer {
const CSS_URL_REGEX = /url\(("[^"]+"|'[^']+'|[^)]+)\)/g;
export function cssAssetHash(transformer: FreshFileTransformer) {
export function cssAssetHash(transformer: FileTransformer) {
transformer.onTransform({
pluginName: "fresh-css",
filter: /\.css$/,
+18 -7
View File
@@ -1,14 +1,11 @@
import { expect } from "@std/expect";
import type { FsAdapter } from "../fs.ts";
import {
FreshFileTransformer,
type ProcessedFile,
} from "./file_transformer.ts";
import { FileTransformer, type ProcessedFile } from "./file_transformer.ts";
import { delay } from "../test_utils.ts";
function testTransformer(files: Record<string, string>) {
function testTransformer(files: Record<string, string>, root = "/") {
const mockFs: FsAdapter = {
cwd: () => "/",
cwd: () => root,
isDirectory: () => Promise.resolve(false),
mkdirp: () => Promise.resolve(),
walk: async function* foo() {
@@ -21,7 +18,7 @@ function testTransformer(files: Record<string, string>) {
return Promise.resolve(buf);
},
};
return new FreshFileTransformer(mockFs);
return new FileTransformer(mockFs, root);
}
function consumeResult(result: ProcessedFile[]) {
@@ -228,3 +225,17 @@ Deno.test(
]);
},
);
Deno.test("FileTransformer - pass root to args", async () => {
const transformer = testTransformer({ "foo.txt": "foo" }, "/<root>/");
let root = "";
transformer.onTransform({ pluginName: "A", filter: /.*/ }, (args) => {
root = args.root;
return undefined;
});
await transformer.process("foo.txt", "development", "");
expect(root).toEqual("/<root>/");
});
+102
View File
@@ -0,0 +1,102 @@
import type { 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";
import { pathToPattern } from "../router.ts";
import { CommandType } from "../commands.ts";
import { sortRoutePaths } from "../fs_routes.ts";
const GROUP_REG = /[/\\\\]\((_[^/\\\\]+)\)[/\\\\]/;
export async function crawlRouteDir<State>(
fs: FsAdapter,
routeDir: string,
ignore: RegExp[],
onIslandSpecifier: (spec: string) => void,
files: FsRouteFileNoMod<State>[],
) {
await walkDir(
fs,
routeDir,
(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;
}
const relative = path.relative(routeDir, entry.path);
const url = new URL(relative, "http://localhost/");
const id = url.pathname.slice(0, url.pathname.lastIndexOf("."));
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 += "/";
}
}
routePattern = pathToPattern(id.slice(1));
}
files.push({ id, filePath: entry.path, type, pattern, routePattern });
},
ignore,
);
files.sort((a, b) => sortRoutePaths(a.id, b.id));
}
export async function walkDir(
fs: FsAdapter,
dir: string,
callback: (entry: WalkEntry) => void,
ignore: RegExp[],
) {
if (!await fs.isDirectory(dir)) return;
const entries = fs.walk(dir, {
includeDirs: false,
includeFiles: true,
exts: ["tsx", "jsx", "ts", "js"],
skip: ignore,
});
for await (const entry of entries) {
callback(entry);
}
}
+5 -1
View File
@@ -1,4 +1,8 @@
export { Builder } from "./builder.ts";
export {
Builder,
type BuildOptions,
type ResolvedBuildConfig,
} from "./builder.ts";
export {
type OnTransformArgs,
type OnTransformOptions,