chore: improve bundling + refactor router (#10)
This commit changes how bundling works, by bundling all routes at once. Static JS assets are now cached immutably. Additionally this PR completly refactors how the router works to make it more modular. This allows users to opt out of the default oak server, and instead create their own.
This commit is contained in:
+92
-20
@@ -1,10 +1,10 @@
|
||||
import { denoPlugin, esbuild } from "./deps.ts";
|
||||
import { Page } from "./routes.ts";
|
||||
import { Page } from "./page.ts";
|
||||
|
||||
let esbuildInitalized: boolean | Promise<void> = false;
|
||||
async function ensureEsbuildInialized() {
|
||||
if (esbuildInitalized === false) {
|
||||
esbuildInitalized = await esbuild.initialize({
|
||||
esbuildInitalized = esbuild.initialize({
|
||||
wasmURL: "https://unpkg.com/esbuild-wasm@0.11.19/esbuild.wasm",
|
||||
worker: false,
|
||||
});
|
||||
@@ -15,9 +15,93 @@ async function ensureEsbuildInialized() {
|
||||
}
|
||||
}
|
||||
|
||||
export async function bundle(page: Page): Promise<string> {
|
||||
export class Bundler {
|
||||
#pages: Page[];
|
||||
#cache: Map<string, Uint8Array> | Promise<void> | undefined = undefined;
|
||||
|
||||
constructor(pages: Page[]) {
|
||||
this.#pages = pages;
|
||||
}
|
||||
|
||||
async bundle() {
|
||||
const entryPoints: Record<string, string> = {};
|
||||
|
||||
for (const page of this.#pages) {
|
||||
entryPoints[page.name] = `fresh:///${page.name}`;
|
||||
}
|
||||
|
||||
await ensureEsbuildInialized();
|
||||
const bundle = await esbuild.build({
|
||||
plugins: [freshPlugin(this.#pages), denoPlugin({ loader: "portable" })],
|
||||
write: false,
|
||||
bundle: true,
|
||||
minify: true,
|
||||
treeShaking: true,
|
||||
splitting: true,
|
||||
platform: "neutral",
|
||||
outfile: "",
|
||||
jsxFactory: "h",
|
||||
jsxFragment: "Fragment",
|
||||
outdir: `/`,
|
||||
entryPoints,
|
||||
});
|
||||
|
||||
const cache = new Map<string, Uint8Array>();
|
||||
for (const file of bundle.outputFiles) {
|
||||
cache.set(file.path, 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 freshPlugin(pageList: Page[]): esbuild.Plugin {
|
||||
const runtime = new URL("../../runtime.ts", import.meta.url);
|
||||
const contents = `
|
||||
|
||||
const pageMap = new Map<string, Page>();
|
||||
|
||||
for (const page of pageList) {
|
||||
pageMap.set(`/${page.name}`, page);
|
||||
}
|
||||
|
||||
return {
|
||||
name: "fresh",
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /fresh:\/\/.*/ }, function onResolve(
|
||||
args: esbuild.OnResolveArgs,
|
||||
): esbuild.OnResolveResult | null | undefined {
|
||||
return ({
|
||||
path: args.path,
|
||||
namespace: "fresh",
|
||||
});
|
||||
});
|
||||
|
||||
build.onLoad(
|
||||
{ filter: /.*/, namespace: "fresh" },
|
||||
function onLoad(
|
||||
args: esbuild.OnLoadArgs,
|
||||
): esbuild.OnLoadResult | null | undefined {
|
||||
const url = new URL(args.path);
|
||||
const path = url.pathname;
|
||||
const page = pageMap.get(path);
|
||||
if (!page) return null;
|
||||
const contents = `
|
||||
import Page from "${page.url}";
|
||||
import { h, render } from "${runtime.href}";
|
||||
|
||||
@@ -26,21 +110,9 @@ addEventListener("DOMContentLoaded", () => {
|
||||
render(h(Page, props), document.body);
|
||||
});
|
||||
`;
|
||||
await ensureEsbuildInialized();
|
||||
const bundle = await esbuild.build({
|
||||
plugins: [denoPlugin({ loader: "portable" })],
|
||||
write: false,
|
||||
bundle: true,
|
||||
minify: true,
|
||||
treeShaking: true,
|
||||
platform: "neutral",
|
||||
outfile: "",
|
||||
jsxFactory: "h",
|
||||
jsxFragment: "Fragment",
|
||||
stdin: {
|
||||
contents,
|
||||
sourcefile: `fresh://entrypoint/${page.name}`,
|
||||
return { contents, loader: "js" };
|
||||
},
|
||||
);
|
||||
},
|
||||
});
|
||||
return bundle.outputFiles[0].text;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { generateUuid } from "./deps.ts";
|
||||
|
||||
export const INTERNAL_PREFIX = "/_frsh";
|
||||
export const BUILD_ID = Deno.env.get("DENO_DEPLOYMENT_ID") || generateUuid();
|
||||
export const JS_PREFIX = `/js`;
|
||||
+2
-1
@@ -3,12 +3,13 @@ export { renderToString } from "https://x.lcas.dev/preact@10.5.12/ssr.js";
|
||||
|
||||
// -- std --
|
||||
export { extname } from "https://deno.land/std@0.95.0/path/mod.ts";
|
||||
export { generate as generateUuid } from "https://deno.land/std@0.95.0/uuid/v4.ts";
|
||||
|
||||
// -- oak --
|
||||
export * as oak from "https://deno.land/x/oak@v7.4.0/mod.ts";
|
||||
|
||||
// -- esbuild --
|
||||
let start = new Date().getTime();
|
||||
const start = new Date().getTime();
|
||||
globalThis.performance = {
|
||||
now() {
|
||||
return new Date().getTime() - start;
|
||||
|
||||
+26
-6
@@ -1,13 +1,33 @@
|
||||
import { createPages, PageModules } from "./routes.ts";
|
||||
import { createServer } from "./server.ts";
|
||||
import { oak } from "./deps.ts";
|
||||
import { Page, PageModule, processRoutes } from "./page.ts";
|
||||
import { installRoutes } from "./router.ts";
|
||||
|
||||
export function setup(pageModules: [PageModules, string][], selfUrl: string) {
|
||||
const baseUrl = new URL("./", selfUrl).href;
|
||||
const pages = createPages(pageModules, baseUrl);
|
||||
const app = createServer(pages);
|
||||
export interface Routes {
|
||||
pages: Record<string, PageModule>;
|
||||
baseUrl: string;
|
||||
}
|
||||
|
||||
export { installRoutes };
|
||||
|
||||
export function start(routes: Routes) {
|
||||
const pages = processRoutes(routes);
|
||||
const app = createDefaultServer(pages);
|
||||
app.addEventListener("error", (err) => {
|
||||
console.error(err.error);
|
||||
});
|
||||
|
||||
addEventListener("fetch", app.fetchEventHandler());
|
||||
}
|
||||
|
||||
export function createDefaultServer(pages: Page[]): oak.Application {
|
||||
const router = new oak.Router();
|
||||
|
||||
installRoutes(router, pages);
|
||||
|
||||
const app = new oak.Application();
|
||||
|
||||
app.use(router.routes());
|
||||
app.use(router.allowedMethods());
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { extname } from "./deps.ts";
|
||||
import * as rt from "../runtime/deps.ts";
|
||||
import { PageProps } from "../runtime/types.ts";
|
||||
import { Routes } from "./mod.ts";
|
||||
|
||||
export interface PageModules {
|
||||
export interface PageModule {
|
||||
default: rt.ComponentType<PageProps>;
|
||||
}
|
||||
|
||||
@@ -13,12 +14,16 @@ export interface Page {
|
||||
component: rt.ComponentType<PageProps>;
|
||||
}
|
||||
|
||||
export function createPages(
|
||||
pageModules: [PageModules, string][],
|
||||
baseUrl: string,
|
||||
): Page[] {
|
||||
/**
|
||||
* Process the routes into individual pages.
|
||||
*/
|
||||
export function processRoutes(routes: Routes): Page[] {
|
||||
// Get the routes' base URL.
|
||||
const baseUrl = new URL("./", routes.baseUrl).href;
|
||||
|
||||
// Extract all pages, and prepare them into this `Page` structure.
|
||||
const pages: Page[] = [];
|
||||
for (const [pageModule, self] of pageModules) {
|
||||
for (const [self, pageModule] of Object.entries(routes.pages)) {
|
||||
const url = new URL(self, baseUrl).href;
|
||||
if (!url.startsWith(baseUrl)) {
|
||||
throw new TypeError("Page is not a child of the basepath.");
|
||||
@@ -35,6 +40,8 @@ export function createPages(
|
||||
pages.push(page);
|
||||
}
|
||||
|
||||
// Sort pages by theur relative routing priority, based on the parts in the
|
||||
// route matcher.
|
||||
pages.sort((a, b) => {
|
||||
const partsA = a.route.split("/");
|
||||
const partsB = b.route.split("/");
|
||||
@@ -54,6 +61,7 @@ export function createPages(
|
||||
return pages;
|
||||
}
|
||||
|
||||
/** Transform a filesystem URL path to a `path-to-regex` style matcher. */
|
||||
function pathToRoute(path: string): string {
|
||||
const parts = path.split("/");
|
||||
if (parts[parts.length - 1] === "index") {
|
||||
@@ -1,11 +1,12 @@
|
||||
import { renderToString } from "./deps.ts";
|
||||
import * as rt from "../runtime/deps.ts";
|
||||
import { Page } from "./routes.ts";
|
||||
import { Page } from "./page.ts";
|
||||
import { BUILD_ID, INTERNAL_PREFIX, JS_PREFIX } from "./constants.ts";
|
||||
|
||||
export function render(page: Page, params: Record<string, string>): string {
|
||||
const props = { params };
|
||||
const body = renderToString(rt.h(page.component, props));
|
||||
return `<!DOCTYPE html><html><head><script src="/_frsh/s/p/${page.name}.module.js" type="module"></script></head><body>${body}<script id="__FRSH_PROPS" type="application/json">${
|
||||
return `<!DOCTYPE html><html><head><script src="${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/${page.name}.js" type="module"></script></head><body>${body}<script id="__FRSH_PROPS" type="application/json">${
|
||||
JSON.stringify(props)
|
||||
}</script></body></html>`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { extname, oak } from "./deps.ts";
|
||||
import { Bundler } from "./bundle.ts";
|
||||
import { render } from "./render.ts";
|
||||
import { Page } from "./page.ts";
|
||||
import { BUILD_ID, INTERNAL_PREFIX, JS_PREFIX } from "./constants.ts";
|
||||
|
||||
/** This function installs all routes required by fresh onto an oak router. */
|
||||
export function installRoutes(router: oak.Router, pages: Page[]) {
|
||||
for (const page of pages) {
|
||||
router.get<Record<string, string>>(page.route, (ctx) => {
|
||||
ctx.response.status = 200;
|
||||
ctx.response.type = "html";
|
||||
ctx.response.body = render(page, ctx.params);
|
||||
});
|
||||
}
|
||||
|
||||
const internal = internalRouter(pages);
|
||||
|
||||
router.use(
|
||||
INTERNAL_PREFIX,
|
||||
internal.routes(),
|
||||
internal.allowedMethods(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a router that contains all fresh routes. Should be mounted at
|
||||
* constants.INTERNAL_PREFIX
|
||||
*/
|
||||
function internalRouter(pages: Page[]): oak.Router {
|
||||
const bundler = new Bundler(pages);
|
||||
|
||||
const router = new oak.Router();
|
||||
|
||||
router.get(`${JS_PREFIX}/${BUILD_ID}/:path*`, async (ctx) => {
|
||||
const path = `/${ctx.params.path}`;
|
||||
const file = await bundler.get(path);
|
||||
if (file) {
|
||||
ctx.response.status = 200;
|
||||
ctx.response.type = extname(path);
|
||||
ctx.response.body = file;
|
||||
ctx.response.headers.set(
|
||||
"Cache-Control",
|
||||
"public, max-age=604800, immutable",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import { oak } from "./deps.ts";
|
||||
import { bundle } from "./bundle.ts";
|
||||
import { render } from "./render.ts";
|
||||
import { Page } from "./routes.ts";
|
||||
|
||||
export function createServer(pages: Page[]): oak.Application {
|
||||
const router = new oak.Router();
|
||||
|
||||
for (const page of pages) {
|
||||
router.get<Record<string, string>>(page.route, (ctx) => {
|
||||
ctx.response.status = 200;
|
||||
ctx.response.type = "html";
|
||||
ctx.response.body = render(page, ctx.params);
|
||||
});
|
||||
|
||||
router.get(`/_frsh/s/p/${page.name}.module.js`, async (ctx) => {
|
||||
const js = await bundle(page);
|
||||
ctx.response.status = 200;
|
||||
ctx.response.type = "js";
|
||||
ctx.response.body = js;
|
||||
});
|
||||
}
|
||||
|
||||
const app = new oak.Application();
|
||||
|
||||
app.use(router.routes());
|
||||
app.use(router.allowedMethods());
|
||||
|
||||
return app;
|
||||
}
|
||||
Reference in New Issue
Block a user