chore: clean up esbuild builder logic (#1231)

This will allow us to add various caches and similar around the esbuild
builder easily in follow up PRs.

It also makes doing an AOT build-step + load assets from disk much
simpler.
This commit is contained in:
Luca Casonato
2023-06-03 10:24:15 +02:00
committed by GitHub
parent 736c5524d5
commit 3857a49f1c
7 changed files with 318 additions and 217 deletions
-188
View File
@@ -1,188 +0,0 @@
import {
denoPlugins,
esbuild,
esbuildTypes,
escape,
fromFileUrl,
toFileUrl,
} from "./deps.ts";
import { Island, Plugin } from "./types.ts";
import { BUILD_ID } from "./build_id.ts";
export interface JSXConfig {
jsx: "react" | "react-jsx";
jsxImportSource?: string;
}
let esbuildInitialized: boolean | Promise<void> = false;
async function ensureEsbuildInitialized() {
if (esbuildInitialized === false) {
// deno-lint-ignore no-deprecated-deno-api
if (Deno.run === undefined) {
const wasmURL = new URL("./esbuild_v0.17.11.wasm", import.meta.url).href;
esbuildInitialized = fetch(wasmURL).then(async (r) => {
const resp = new Response(r.body, {
headers: { "Content-Type": "application/wasm" },
});
const wasmModule = await WebAssembly.compileStreaming(resp);
await esbuild.initialize({
wasmModule,
worker: false,
});
});
} else {
esbuild.initialize({});
}
await esbuildInitialized;
esbuildInitialized = true;
} else if (esbuildInitialized instanceof Promise) {
await esbuildInitialized;
}
}
const JSX_RUNTIME_MODE = {
"react": "transform",
"react-jsx": "automatic",
} as const;
export class Bundler {
#importMapURL: URL;
#jsxConfig: JSXConfig;
#islands: Island[];
#plugins: Plugin[];
#cache: Map<string, Uint8Array> | Promise<void> | undefined = undefined;
#dev: boolean;
dependencyMap = new Map<string, string[]>();
constructor(
islands: Island[],
plugins: Plugin[],
importMapURL: URL,
jsxConfig: JSXConfig,
dev: boolean,
) {
this.#islands = islands;
this.#plugins = plugins;
this.#importMapURL = importMapURL;
this.#jsxConfig = jsxConfig;
this.#dev = dev;
}
async bundle() {
const entrypointBase = "../../src/runtime/entrypoints";
const entryPoints: Record<string, string> = {
main: this.#dev
? import.meta.resolve(`${entrypointBase}/main_dev.ts`)
: import.meta.resolve(`${entrypointBase}/main.ts`),
deserializer: import.meta.resolve(`${entrypointBase}/deserializer.ts`),
};
try {
import.meta.resolve("@preact/signals");
entryPoints.signals = import.meta.resolve(`${entrypointBase}/signals.ts`);
} catch {
// @preact/signals is not in the import map
}
for (const island of this.#islands) {
entryPoints[`island-${island.id}`] = island.url;
}
for (const plugin of this.#plugins) {
for (const [name, url] of Object.entries(plugin.entrypoints ?? {})) {
entryPoints[`plugin-${plugin.name}-${name}`] = url;
}
}
const absWorkingDir = Deno.cwd();
await ensureEsbuildInitialized();
// In dev-mode we skip identifier minification to be able to show proper
// component names in Preact DevTools instead of single characters.
const minifyOptions: Partial<esbuildTypes.BuildOptions> = this.#dev
? { minifyIdentifiers: false, minifySyntax: true, minifyWhitespace: true }
: { minify: true };
const bundle = await esbuild.build({
bundle: true,
entryPoints,
format: "esm",
metafile: true,
...minifyOptions,
outdir: ".",
// This is requried to ensure the format of the outputFiles path is the same
// between windows and linux
absWorkingDir,
outfile: "",
platform: "neutral",
plugins: [
buildIdPlugin(BUILD_ID),
...denoPlugins({ importMapURL: this.#importMapURL.href }),
],
sourcemap: this.#dev ? "linked" : false,
splitting: true,
target: ["chrome99", "firefox99", "safari15"],
treeShaking: true,
write: false,
jsx: JSX_RUNTIME_MODE[this.#jsxConfig.jsx],
jsxImportSource: this.#jsxConfig.jsxImportSource,
});
const metafileOutputs = bundle.metafile!.outputs;
for (const path in metafileOutputs) {
const meta = metafileOutputs[path];
const imports = meta.imports
.filter(({ kind }) => kind === "import-statement")
.map(({ path }) => `/${path}`);
this.dependencyMap.set(`/${path}`, imports);
}
const cache = new Map<string, Uint8Array>();
const absDirUrlLength = toFileUrl(absWorkingDir).href.length;
for (const file of bundle.outputFiles) {
cache.set(
toFileUrl(file.path).href.substring(absDirUrlLength),
file.contents,
);
}
this.#cache = cache;
return;
}
async cache(): Promise<Map<string, Uint8Array>> {
if (this.#cache === undefined) {
this.#cache = this.bundle();
}
if (this.#cache instanceof Promise) {
await this.#cache;
}
return this.#cache as Map<string, Uint8Array>;
}
async get(path: string): Promise<Uint8Array | null> {
const cache = await this.cache();
return cache.get(path) ?? null;
}
}
function buildIdPlugin(buildId: string): esbuildTypes.Plugin {
const file = import.meta.resolve("../runtime/build_id.ts");
const url = new URL(file);
let options: esbuildTypes.OnLoadOptions;
if (url.protocol === "file:") {
const path = fromFileUrl(url);
options = { filter: new RegExp(escape(path)), namespace: "file" };
} else {
const namespace = url.protocol.slice(0, -1);
const path = url.href.slice(namespace.length + 1);
options = { filter: new RegExp(escape(path)), namespace };
}
return {
name: "fresh-build-id",
setup(build) {
build.onLoad(
options,
() => ({ contents: `export const BUILD_ID = "${buildId}";` }),
);
},
};
}
+83 -26
View File
@@ -11,7 +11,6 @@ import {
import { h } from "preact";
import * as router from "./router.ts";
import { Manifest } from "./mod.ts";
import { Bundler, JSXConfig } from "./bundle.ts";
import { ALIVE_URL, JS_PREFIX, REFRESH_JS_URL } from "./constants.ts";
import { BUILD_ID } from "./build_id.ts";
import DefaultErrorHandler from "./default_error_page.ts";
@@ -37,6 +36,13 @@ import {
import { render as internalRender } from "./render.ts";
import { ContentSecurityPolicyDirectives, SELF } from "../runtime/csp.ts";
import { ASSET_CACHE_BUST_KEY, INTERNAL_PREFIX } from "../runtime/utils.ts";
import {
Builder,
BuildSnapshot,
EsbuildBuilder,
JSXConfig,
} from "../build/mod.ts";
interface RouterState {
state: Record<string, unknown>;
}
@@ -59,13 +65,13 @@ export class ServerContext {
#routes: Route[];
#islands: Island[];
#staticFiles: StaticFile[];
#bundler: Bundler;
#renderFn: RenderFunction;
#middlewares: MiddlewareRoute[];
#app: AppModule;
#notFound: UnknownPage;
#error: ErrorPage;
#plugins: Plugin[];
#builder: Builder | Promise<BuildSnapshot> | BuildSnapshot;
constructor(
routes: Route[],
@@ -90,13 +96,13 @@ export class ServerContext {
this.#error = error;
this.#plugins = plugins;
this.#dev = typeof Deno.env.get("DENO_DEPLOYMENT_ID") !== "string"; // Env var is only set in prod (on Deploy).
this.#bundler = new Bundler(
this.#islands,
this.#plugins,
this.#builder = new EsbuildBuilder({
buildID: BUILD_ID,
entrypoints: collectEntrypoints(this.#dev, this.#islands, this.#plugins),
importMapURL,
dev: this.#dev,
jsxConfig,
this.#dev,
);
});
}
/**
@@ -347,6 +353,28 @@ export class ServerContext {
};
}
#maybeBuildSnapshot(): BuildSnapshot | null {
if ("build" in this.#builder || this.#builder instanceof Promise) {
return null;
}
return this.#builder;
}
async #buildSnapshot() {
if ("build" in this.#builder) {
const builder = this.#builder;
this.#builder = builder.build();
try {
const snapshot = await this.#builder;
this.#builder = snapshot;
} catch (err) {
this.#builder = builder;
throw err;
}
}
return this.#builder;
}
/**
* Identify which middlewares should be applied for a request,
* chain them and return a handler response
@@ -509,7 +537,10 @@ export class ServerContext {
plugins: this.#plugins,
app: this.#app,
imports,
dependencyMap: this.#bundler.dependencyMap,
dependenciesFn: (path) => {
const snapshot = this.#maybeBuildSnapshot();
return snapshot?.dependencies(path) ?? [];
},
renderFn: this.#renderFn,
url: new URL(req.url),
params,
@@ -699,27 +730,20 @@ export class ServerContext {
*/
#bundleAssetRoute = (): router.MatchHandler => {
return async (_req, _ctx, params) => {
const path = `/${params.path}`;
const file = await this.#bundler.get(path);
let res;
if (file) {
const headers = new Headers({
"Cache-Control": "public, max-age=604800, immutable",
});
const snapshot = await this.#buildSnapshot();
const contents = snapshot.read(params.path);
if (!contents) return new Response(null, { status: 404 });
const contentType = typeByExtension(extname(path));
if (contentType) {
headers.set("Content-Type", contentType);
}
const headers: Record<string, string> = {
"Cache-Control": "public, max-age=604800, immutable",
};
res = new Response(file, {
status: 200,
headers,
});
}
const contentType = typeByExtension(extname(params.path));
if (contentType) headers["Content-Type"] = contentType;
return res ?? new Response(null, {
status: 404,
return new Response(contents, {
status: 200,
headers,
});
};
};
@@ -880,3 +904,36 @@ es.addEventListener("message", function listener(e) {
}
});`;
}
function collectEntrypoints(
dev: boolean,
islands: Island[],
plugins: Plugin[],
): Record<string, string> {
const entrypointBase = "../runtime/entrypoints";
const entryPoints: Record<string, string> = {
main: dev
? import.meta.resolve(`${entrypointBase}/main_dev.ts`)
: import.meta.resolve(`${entrypointBase}/main.ts`),
deserializer: import.meta.resolve(`${entrypointBase}/deserializer.ts`),
};
try {
import.meta.resolve("@preact/signals");
entryPoints.signals = import.meta.resolve(`${entrypointBase}/signals.ts`);
} catch {
// @preact/signals is not in the import map
}
for (const island of islands) {
entryPoints[`island-${island.id}`] = island.url;
}
for (const plugin of plugins) {
for (const [name, url] of Object.entries(plugin.entrypoints ?? {})) {
entryPoints[`plugin-${plugin.name}-${name}`] = url;
}
}
return entryPoints;
}
Binary file not shown.
+3 -3
View File
@@ -26,7 +26,7 @@ export interface RenderOptions<Data> {
plugins: Plugin[];
app: AppModule;
imports: string[];
dependencyMap: Map<string, string[]>;
dependenciesFn: (path: string) => string[];
url: URL;
params: Record<string, string | string[]>;
renderFn: RenderFunction;
@@ -221,8 +221,8 @@ export async function render<Data>(
const url = bundleAssetUrl(path);
imports.push([url, randomNonce]);
preloadSet.add(url);
for (const depPath of opts.dependencyMap.get(path) ?? []) {
const url = bundleAssetUrl(depPath);
for (const depPath of opts.dependenciesFn(path)) {
const url = bundleAssetUrl(`/${depPath}`);
preloadSet.add(url);
}
return url;