major: import Fresh 2.0 code (#2449)

🎉
This commit is contained in:
Marvin Hagemeister
2024-05-24 09:40:08 +02:00
committed by GitHub
parent 990357629e
commit 287929e4d2
958 changed files with 15794 additions and 28287 deletions
+319
View File
@@ -0,0 +1,319 @@
import { DENO_DEPLOYMENT_ID } from "./runtime/build_id.ts";
import * as colors from "@std/fmt/colors";
import { type MiddlewareFn, runMiddlewares } from "./middlewares/mod.ts";
import { FreshReqContext } from "./context.ts";
import {
mergePaths,
type Method,
type Router,
UrlPatternRouter,
} from "./router.ts";
import {
type FreshConfig,
normalizeConfig,
type ResolvedFreshConfig,
} from "./config.ts";
import { type BuildCache, ProdBuildCache } from "./build_cache.ts";
import * as path from "@std/path";
import { type ComponentType, h } from "preact";
import type { ServerIslandRegistry } from "./context.ts";
import { renderToString } from "preact-render-to-string";
import { FinishSetup, ForgotBuild } from "./finish_setup.tsx";
import { HttpError } from "./error.ts";
// TODO: Completed type clashes in older Deno versions
// deno-lint-ignore no-explicit-any
export const DEFAULT_CONN_INFO: any = {
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
};
const DEFAULT_NOT_FOUND = () => {
throw new HttpError(404);
};
const DEFAULT_NOT_ALLOWED_METHOD = () => {
throw new HttpError(405);
};
export type ListenOptions = Partial<Deno.ServeTlsOptions> & {
remoteAddress?: string;
};
export interface RouteCacheEntry<T> {
params: Record<string, string>;
handler: MiddlewareFn<T>;
}
export let getRouter: <State>(app: App<State>) => Router<MiddlewareFn<State>>;
// deno-lint-ignore no-explicit-any
export let getIslandRegistry: (app: App<any>) => ServerIslandRegistry;
// deno-lint-ignore no-explicit-any
export let getBuildCache: (app: App<any>) => BuildCache | null;
// deno-lint-ignore no-explicit-any
export let setBuildCache: (app: App<any>, cache: BuildCache | null) => void;
export class App<State> {
#router: Router<MiddlewareFn<State>> = new UrlPatternRouter<
MiddlewareFn<State>
>();
#islandRegistry: ServerIslandRegistry = new Map();
#buildCache: BuildCache | null = null;
#islandNames = new Set<string>();
static {
getRouter = (app) => app.#router;
getIslandRegistry = (app) => app.#islandRegistry;
getBuildCache = (app) => app.#buildCache;
setBuildCache = (app, cache) => app.#buildCache = cache;
}
/**
* The final resolved Fresh configuration.
*/
config: ResolvedFreshConfig;
constructor(config: FreshConfig = {}) {
this.config = normalizeConfig(config);
}
island(
filePathOrUrl: string | URL,
exportName: string,
// deno-lint-ignore no-explicit-any
fn: ComponentType<any>,
): this {
const filePath = filePathOrUrl instanceof URL
? filePathOrUrl.href
: filePathOrUrl;
// Create unique island name
let name = exportName === "default"
? path.basename(filePath, path.extname(filePath))
: exportName;
if (this.#islandNames.has(name)) {
let i = 0;
while (this.#islandNames.has(`${name}_${i}`)) {
i++;
}
name = `${name}_${i}`;
}
this.#islandRegistry.set(fn, { fn, exportName, name, file: filePathOrUrl });
return this;
}
use(middleware: MiddlewareFn<State>): this {
this.#router.addMiddleware(middleware);
return this;
}
get(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("GET", path, middlewares);
}
post(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("POST", path, middlewares);
}
patch(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("PATCH", path, middlewares);
}
put(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("PUT", path, middlewares);
}
delete(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("DELETE", path, middlewares);
}
head(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("HEAD", path, middlewares);
}
all(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("ALL", path, middlewares);
}
mountApp(path: string, app: App<State>): this {
const routes = app.#router._routes;
app.#islandRegistry.forEach((value, key) => {
this.#islandRegistry.set(key, value);
});
const middlewares = app.#router._middlewares;
// Special case when user calls one of these:
// - `app.mounApp("/", otherApp)`
// - `app.mounApp("*", otherApp)`
const isSelf = path === "*" || path === "/";
if (isSelf && middlewares.length > 0) {
this.#router._middlewares.push(...middlewares);
}
for (let i = 0; i < routes.length; i++) {
const route = routes[i];
const merged = typeof route.path === "string"
? mergePaths(path, route.path)
: route.path;
const combined = isSelf
? route.handlers
: middlewares.concat(route.handlers);
this.#router.add(route.method, merged, combined);
}
return this;
}
#addRoutes(
method: Method | "ALL",
pathname: string | URLPattern,
middlewares: MiddlewareFn<State>[],
): this {
const merged = typeof pathname === "string"
? mergePaths(this.config.basePath, pathname)
: pathname;
this.#router.add(method, merged, middlewares);
return this;
}
async handler(): Promise<
(request: Request, info?: Deno.ServeHandlerInfo) => Promise<Response>
> {
if (this.#buildCache === null) {
this.#buildCache = await ProdBuildCache.fromSnapshot(this.config);
}
if (
!this.#buildCache.hasSnapshot && this.config.mode === "production" &&
DENO_DEPLOYMENT_ID !== undefined
) {
return missingBuildHandler;
}
return async (
req: Request,
conn: Deno.ServeHandlerInfo | Deno.ServeUnixHandlerInfo =
DEFAULT_CONN_INFO,
) => {
const url = new URL(req.url);
// Prevent open redirect attacks
url.pathname = url.pathname.replace(/\/+/g, "/");
const method = req.method.toUpperCase() as Method;
const matched = this.#router.match(method, url);
const next = matched.patternMatch && !matched.methodMatch
? DEFAULT_NOT_ALLOWED_METHOD
: DEFAULT_NOT_FOUND;
const { params, handlers } = matched;
const ctx = new FreshReqContext<State>(
req,
this.config,
next,
this.#islandRegistry,
this.#buildCache!,
conn,
);
ctx.params = params;
try {
if (handlers.length === 1 && handlers[0].length === 1) {
return handlers[0][0](ctx);
}
ctx.next = next;
return await runMiddlewares(handlers, ctx);
} catch (err) {
if (err instanceof HttpError) {
if (err.status >= 500) {
console.error(err);
}
return new Response(err.message, { status: err.status });
}
console.error(err);
return new Response("Internal server error", { status: 500 });
}
};
}
async listen(options: ListenOptions = {}): Promise<void> {
if (!options.onListen) {
options.onListen = (params) => {
const pathname = (this.config.basePath) + "/";
const protocol = options.key && options.cert ? "https:" : "http:";
// Work around https://github.com/denoland/deno/issues/23650
const hostname = params.hostname.startsWith("::")
? `[${params.hostname}]`
: params.hostname;
const address = colors.cyan(
`${protocol}//${hostname}:${params.port}${pathname}`,
);
const localLabel = colors.bold("Local:");
// Print more concise output for deploy logs
if (DENO_DEPLOYMENT_ID) {
console.log(
colors.bgRgb8(colors.rgb8(" 🍋 Fresh ready ", 0), 121),
`${localLabel} ${address}`,
);
} else {
console.log();
console.log(
colors.bgRgb8(colors.rgb8(" 🍋 Fresh ready ", 0), 121),
);
const sep = options.remoteAddress ? "" : "\n";
const space = options.remoteAddress ? " " : "";
console.log(` ${localLabel} ${space}${address}${sep}`);
if (options.remoteAddress) {
const remoteLabel = colors.bold("Remote:");
const remoteAddress = colors.cyan(options.remoteAddress);
console.log(` ${remoteLabel} ${remoteAddress}\n`);
}
}
};
}
const handler = await this.handler();
if (options.port) {
await Deno.serve(options, handler);
} else {
// No port specified, check for a free port. Instead of picking just
// any port we'll check if the next one is free for UX reasons.
// That way the user only needs to increment a number when running
// multiple apps vs having to remember completely different ports.
let firstError;
for (let port = 8000; port < 8020; port++) {
try {
await Deno.serve({ ...options, port }, handler);
firstError = undefined;
break;
} catch (err) {
if (err instanceof Deno.errors.AddrInUse) {
// Throw first EADDRINUSE error
// if no port is free
if (!firstError) {
firstError = err;
}
continue;
}
throw err;
}
}
if (firstError) {
throw firstError;
}
}
}
}
// deno-lint-ignore require-await
const missingBuildHandler = async (): Promise<Response> => {
const headers = new Headers();
headers.set("Content-Type", "text/html; charset=utf-8");
const html = DENO_DEPLOYMENT_ID
? renderToString(h(FinishSetup, null))
: renderToString(h(ForgotBuild, null));
return new Response(html, { headers, status: 500 });
};
+472
View File
@@ -0,0 +1,472 @@
import { expect } from "@std/expect";
import { App, setBuildCache } from "./app.ts";
import { FakeServer } from "./test_utils.ts";
import { ProdBuildCache } from "./build_cache.ts";
Deno.test("FreshApp - .use()", async () => {
const app = new App<{ text: string }>()
.use((ctx) => {
ctx.state.text = "A";
return ctx.next();
})
.use((ctx) => {
ctx.state.text += "B";
return ctx.next();
})
.get("/", (ctx) => new Response(ctx.state.text));
const server = new FakeServer(await app.handler());
const res = await server.get("/");
expect(await res.text()).toEqual("AB");
});
Deno.test("FreshApp - .use() #2", async () => {
const app = new App<{ text: string }>()
.use(() => new Response("ok #1"))
.get("/foo/bar", () => new Response("ok #2"))
.get("/", () => new Response("ok #3"));
const server = new FakeServer(await app.handler());
const res = await server.get("/");
expect(await res.text()).toEqual("ok #1");
});
Deno.test("FreshApp - .get()", async () => {
const app = new App()
.post("/", () => new Response("ok"))
.post("/foo", () => new Response("ok"))
.get("/", () => new Response("ok"))
.get("/foo", () => new Response("ok"));
const server = new FakeServer(await app.handler());
let res = await server.get("/");
expect(await res.text()).toEqual("ok");
res = await server.get("/foo");
expect(await res.text()).toEqual("ok");
});
Deno.test("FreshApp - .get() with basePath", async () => {
const app = new App({ basePath: "/foo/bar" })
.get("/", () => new Response("ok"))
.get("/foo", () => new Response("ok"));
const server = new FakeServer(await app.handler());
let res = await server.get("/");
expect(res.status).toEqual(404);
res = await server.get("/foo");
expect(res.status).toEqual(404);
res = await server.get("/foo/bar");
expect(res.status).toEqual(200);
res = await server.get("/foo/bar/foo");
expect(res.status).toEqual(200);
});
Deno.test("FreshApp - .post()", async () => {
const app = new App<{ text: string }>()
.get("/", () => new Response("fail"))
.get("/foo", () => new Response("fail"))
.post("/", () => new Response("ok"))
.post("/foo", () => new Response("ok"));
const server = new FakeServer(await app.handler());
let res = await server.post("/");
expect(await res.text()).toEqual("ok");
res = await server.post("/foo");
expect(await res.text()).toEqual("ok");
});
Deno.test("FreshApp - .post() with basePath", async () => {
const app = new App({ basePath: "/foo/bar" })
.post("/", () => new Response("ok"))
.post("/foo", () => new Response("ok"));
const server = new FakeServer(await app.handler());
let res = await server.post("/");
expect(res.status).toEqual(404);
res = await server.post("/foo");
expect(res.status).toEqual(404);
res = await server.post("/foo/bar");
expect(res.status).toEqual(200);
res = await server.post("/foo/bar/foo");
expect(res.status).toEqual(200);
});
Deno.test("FreshApp - .patch()", async () => {
const app = new App<{ text: string }>()
.get("/", () => new Response("fail"))
.get("/foo", () => new Response("fail"))
.patch("/", () => new Response("ok"))
.patch("/foo", () => new Response("ok"));
const server = new FakeServer(await app.handler());
let res = await server.patch("/");
expect(await res.text()).toEqual("ok");
res = await server.patch("/foo");
expect(await res.text()).toEqual("ok");
});
Deno.test("FreshApp - .patch() with basePath", async () => {
const app = new App({ basePath: "/foo/bar" })
.patch("/", () => new Response("ok"))
.patch("/foo", () => new Response("ok"));
const server = new FakeServer(await app.handler());
let res = await server.patch("/");
expect(res.status).toEqual(404);
res = await server.patch("/foo");
expect(res.status).toEqual(404);
res = await server.patch("/foo/bar");
expect(res.status).toEqual(200);
res = await server.patch("/foo/bar/foo");
expect(res.status).toEqual(200);
});
Deno.test("FreshApp - .put()", async () => {
const app = new App<{ text: string }>()
.get("/", () => new Response("fail"))
.get("/foo", () => new Response("fail"))
.put("/", () => new Response("ok"))
.put("/foo", () => new Response("ok"));
const server = new FakeServer(await app.handler());
let res = await server.put("/");
expect(await res.text()).toEqual("ok");
res = await server.put("/foo");
expect(await res.text()).toEqual("ok");
});
Deno.test("FreshApp - .put() with basePath", async () => {
const app = new App({ basePath: "/foo/bar" })
.put("/", () => new Response("ok"))
.put("/foo", () => new Response("ok"));
const server = new FakeServer(await app.handler());
let res = await server.put("/");
expect(res.status).toEqual(404);
res = await server.put("/foo");
expect(res.status).toEqual(404);
res = await server.put("/foo/bar");
expect(res.status).toEqual(200);
res = await server.put("/foo/bar/foo");
expect(res.status).toEqual(200);
});
Deno.test("FreshApp - .delete()", async () => {
const app = new App<{ text: string }>()
.get("/", () => new Response("fail"))
.get("/foo", () => new Response("fail"))
.delete("/", () => new Response("ok"))
.delete("/foo", () => new Response("ok"));
const server = new FakeServer(await app.handler());
let res = await server.delete("/");
expect(await res.text()).toEqual("ok");
res = await server.delete("/foo");
expect(await res.text()).toEqual("ok");
});
Deno.test("FreshApp - .delete() with basePath", async () => {
const app = new App({ basePath: "/foo/bar" })
.delete("/", () => new Response("ok"))
.delete("/foo", () => new Response("ok"));
const server = new FakeServer(await app.handler());
let res = await server.delete("/");
expect(res.status).toEqual(404);
res = await server.delete("/foo");
expect(res.status).toEqual(404);
res = await server.delete("/foo/bar");
expect(res.status).toEqual(200);
res = await server.delete("/foo/bar/foo");
expect(res.status).toEqual(200);
});
Deno.test("FreshApp - wrong method match", async () => {
const app = new App<{ text: string }>()
.get("/", () => new Response("ok"))
.post("/", () => new Response("ok"));
const server = new FakeServer(await app.handler());
let res = await server.put("/");
expect(res.status).toEqual(405);
expect(await res.text()).toEqual("Method Not Allowed");
res = await server.post("/");
expect(res.status).toEqual(200);
expect(await res.text()).toEqual("ok");
});
Deno.test("FreshApp - methods with middleware", async () => {
const app = new App<{ text: string }>()
.use((ctx) => {
ctx.state.text = "A";
return ctx.next();
})
.get("/", (ctx) => new Response(ctx.state.text))
.post("/", (ctx) => new Response(ctx.state.text));
const server = new FakeServer(await app.handler());
let res = await server.get("/");
expect(await res.text()).toEqual("A");
res = await server.post("/");
expect(await res.text()).toEqual("A");
});
Deno.test("FreshApp - .mountApp() compose apps", async () => {
const innerApp = new App<{ text: string }>()
.use((ctx) => {
ctx.state.text = "A";
return ctx.next();
})
.get("/", (ctx) => new Response(ctx.state.text))
.post("/", (ctx) => new Response(ctx.state.text));
const app = new App<{ text: string }>()
.get("/", () => new Response("ok"))
.mountApp("/foo", innerApp);
const server = new FakeServer(await app.handler());
let res = await server.get("/");
expect(await res.text()).toEqual("ok");
res = await server.get("/foo");
expect(await res.text()).toEqual("A");
res = await server.post("/foo");
expect(await res.text()).toEqual("A");
});
Deno.test("FreshApp - .mountApp() self mount, no middleware", async () => {
const innerApp = new App<{ text: string }>()
.use((ctx) => {
ctx.state.text = "A";
return ctx.next();
})
.get("/foo", (ctx) => new Response(ctx.state.text))
.post("/foo", (ctx) => new Response(ctx.state.text));
const app = new App<{ text: string }>()
.get("/", () => new Response("ok"))
.mountApp("/", innerApp);
const server = new FakeServer(await app.handler());
let res = await server.get("/");
expect(await res.text()).toEqual("ok");
res = await server.get("/foo");
expect(await res.text()).toEqual("A");
res = await server.post("/foo");
expect(await res.text()).toEqual("A");
});
Deno.test(
"FreshApp - .mountApp() self mount, with middleware",
async () => {
const innerApp = new App<{ text: string }>()
.use(function B(ctx) {
ctx.state.text += "B";
return ctx.next();
})
.get("/foo", (ctx) => new Response(ctx.state.text))
.post("/foo", (ctx) => new Response(ctx.state.text));
const app = new App<{ text: string }>()
.use(function A(ctx) {
ctx.state.text = "A";
return ctx.next();
})
.get("/", () => new Response("ok"))
.mountApp("/", innerApp);
const server = new FakeServer(await app.handler());
let res = await server.get("/");
expect(await res.text()).toEqual("ok");
res = await server.get("/foo");
expect(await res.text()).toEqual("AB");
res = await server.post("/foo");
expect(await res.text()).toEqual("AB");
},
);
Deno.test(
"FreshApp - .mountApp() self mount, different order",
async () => {
const innerApp = new App<{ text: string }>()
.get("/foo", (ctx) => new Response(ctx.state.text))
.use(function B(ctx) {
ctx.state.text += "B";
return ctx.next();
})
.post("/foo", (ctx) => new Response(ctx.state.text));
const app = new App<{ text: string }>()
.use(function A(ctx) {
ctx.state.text = "A";
return ctx.next();
})
.get("/", () => new Response("ok"))
.mountApp("/", innerApp);
const server = new FakeServer(await app.handler());
let res = await server.get("/");
expect(await res.text()).toEqual("ok");
res = await server.get("/foo");
expect(await res.text()).toEqual("AB");
res = await server.post("/foo");
expect(await res.text()).toEqual("AB");
},
);
Deno.test("FreshApp - .mountApp() self mount empty", async () => {
const innerApp = new App<{ text: string }>()
.use((ctx) => {
ctx.state.text = "A";
return ctx.next();
})
.get("/foo", (ctx) => new Response(ctx.state.text));
const app = new App<{ text: string }>()
.mountApp("/", innerApp);
const server = new FakeServer(await app.handler());
const res = await server.get("/foo");
expect(await res.text()).toEqual("A");
});
Deno.test(
"FreshApp - .mountApp() self mount with middleware",
async () => {
const innerApp = new App<{ text: string }>()
.use(function Inner(ctx) {
ctx.state.text += "_Inner";
return ctx.next();
})
.get("/", (ctx) => new Response(ctx.state.text));
const app = new App<{ text: string }>()
.use(function Outer(ctx) {
ctx.state.text = "Outer";
return ctx.next();
})
.mountApp("/", innerApp);
const server = new FakeServer(await app.handler());
const res = await server.get("/");
expect(await res.text()).toEqual("Outer_Inner");
},
);
Deno.test("FreshApp - catches errors", async () => {
let thrownErr: unknown | null = null;
const app = new App<{ text: string }>()
.use(async (ctx) => {
ctx.state.text = "A";
try {
return await ctx.next();
} catch (err) {
thrownErr = err;
throw err;
}
})
.get("/", () => {
throw new Error("fail");
});
const server = new FakeServer(await app.handler());
const res = await server.get("/");
expect(res.status).toEqual(500);
expect(thrownErr).toBeInstanceOf(Error);
});
// TODO: Find a better way to test this
Deno.test.ignore("FreshApp - finish setup", async () => {
const app = new App<{ text: string }>()
.get("/", (ctx) => {
return ctx.render(<div>ok</div>);
});
setBuildCache(
app,
await ProdBuildCache.fromSnapshot({
...app.config,
build: {
outDir: "foo",
},
}),
);
const server = new FakeServer(await app.handler());
const res = await server.get("/");
const text = await res.text();
expect(text).toContain("Finish setting up");
expect(res.status).toEqual(500);
});
Deno.test("FreshApp - sets error on context", async () => {
const thrown: [unknown, unknown][] = [];
const app = new App()
.use(async (ctx) => {
try {
return await ctx.next();
} catch (err) {
thrown.push([err, ctx.error]);
throw err;
}
})
.use(async (ctx) => {
try {
return await ctx.next();
} catch (err) {
thrown.push([err, ctx.error]);
throw err;
}
})
.get("/", () => {
throw "<mock error>";
});
const server = new FakeServer(await app.handler());
const res = await server.get("/");
await res.body?.cancel();
expect(thrown.length).toEqual(2);
expect(thrown[0][0]).toEqual(thrown[0][1]);
expect(thrown[1][0]).toEqual(thrown[1][1]);
});
-77
View File
@@ -1,77 +0,0 @@
import { ResolvedFreshConfig } from "../server/types.ts";
import { colors, join } from "../server/deps.ts";
import type { BuildSnapshot, BuildSnapshotJson } from "./mod.ts";
import { setBuildId } from "../server/build_id.ts";
export class AotSnapshot implements BuildSnapshot {
#files: Map<string, string>;
#dependencies: Map<string, string[]>;
constructor(
files: Map<string, string>,
dependencies: Map<string, string[]>,
) {
this.#files = files;
this.#dependencies = dependencies;
}
get paths(): string[] {
return Array.from(this.#files.keys());
}
async read(path: string): Promise<ReadableStream<Uint8Array> | null> {
const filePath = this.#files.get(path);
if (filePath !== undefined) {
try {
const file = await Deno.open(filePath, { read: true });
return file.readable;
} catch (_err) {
return null;
}
}
// Handler will turn this into a 404
return null;
}
dependencies(path: string): string[] {
return this.#dependencies.get(path) ?? [];
}
}
export async function loadAotSnapshot(
config: ResolvedFreshConfig,
): Promise<AotSnapshot | null> {
const snapshotDirPath = config.build.outDir;
try {
if ((await Deno.stat(snapshotDirPath)).isDirectory) {
console.log(
`Using snapshot found at ${colors.cyan(snapshotDirPath)}`,
);
const snapshotPath = join(snapshotDirPath, "snapshot.json");
const json = JSON.parse(
await Deno.readTextFile(snapshotPath),
) as BuildSnapshotJson;
setBuildId(json.build_id);
const dependencies = new Map<string, string[]>(
Object.entries(json.files),
);
const files = new Map<string, string>();
Object.keys(json.files).forEach((name) => {
const filePath = join(snapshotDirPath, name);
files.set(name, filePath);
});
return new AotSnapshot(files, dependencies);
}
return null;
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
return null;
}
}
-10
View File
@@ -1,10 +0,0 @@
// -- $std --
export {
fromFileUrl,
join,
relative,
toFileUrl,
} from "https://deno.land/std@0.216.0/path/mod.ts";
export { escape as regexpEscape } from "https://deno.land/std@0.216.0/regexp/escape.ts";
export { denoPlugins } from "jsr:@luca/esbuild-deno-loader@0.10.3";
export { assertEquals } from "https://deno.land/std@0.216.0/assert/mod.ts";
-217
View File
@@ -1,217 +0,0 @@
import {
type BuildOptions,
type OnLoadOptions,
type Plugin,
} from "https://deno.land/x/esbuild@v0.20.2/mod.js";
import { denoPlugins, fromFileUrl, regexpEscape, relative } from "./deps.ts";
import { Builder, BuildSnapshot } from "./mod.ts";
export interface EsbuildBuilderOptions {
/** The build ID. */
buildID: string;
/** The entrypoints, mapped from name to URL. */
entrypoints: Record<string, string>;
/** Whether or not this is a dev build. */
dev: boolean;
/** The path to the deno.json / deno.jsonc config file. */
configPath: string;
/** The JSX configuration. */
jsx?: string;
jsxImportSource?: string;
target: string | string[];
absoluteWorkingDir: string;
basePath?: string;
}
let esbuild: typeof import("https://deno.land/x/esbuild@v0.20.2/mod.js");
export async function initializeEsbuild() {
esbuild =
// deno-lint-ignore no-deprecated-deno-api
Deno.run === undefined ||
Deno.env.get("FRESH_ESBUILD_LOADER") === "portable"
? await import("https://deno.land/x/esbuild@v0.20.2/wasm.js")
: await import("https://deno.land/x/esbuild@v0.20.2/mod.js");
const esbuildWasmURL =
new URL("./esbuild_v0.20.2.wasm", import.meta.url).href;
// deno-lint-ignore no-deprecated-deno-api
if (Deno.run === undefined) {
await esbuild.initialize({
wasmURL: esbuildWasmURL,
worker: false,
});
} else {
await esbuild.initialize({});
}
return esbuild;
}
export class EsbuildBuilder implements Builder {
#options: EsbuildBuilderOptions;
constructor(options: EsbuildBuilderOptions) {
this.#options = options;
}
async build(): Promise<EsbuildSnapshot> {
const opts = this.#options;
// Lazily initialize esbuild
const esbuild = await initializeEsbuild();
try {
const absWorkingDir = opts.absoluteWorkingDir;
// 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<BuildOptions> = opts.dev
? {
minifyIdentifiers: false,
minifySyntax: true,
minifyWhitespace: true,
}
: { minify: true };
const bundle = await esbuild.build({
entryPoints: opts.entrypoints,
platform: "browser",
target: this.#options.target,
format: "esm",
bundle: true,
splitting: true,
treeShaking: true,
sourcemap: opts.dev ? "linked" : false,
...minifyOptions,
jsx: opts.jsx === "react"
? "transform"
: opts.jsx === "react-native" || opts.jsx === "preserve"
? "preserve"
: !opts.jsxImportSource
? "transform"
: "automatic",
jsxImportSource: opts.jsxImportSource ?? "preact",
absWorkingDir,
outdir: ".",
write: false,
metafile: true,
plugins: [
devClientUrlPlugin(opts.basePath),
buildIdPlugin(opts.buildID),
...denoPlugins({ configPath: opts.configPath }),
],
});
const files = new Map<string, Uint8Array>();
const dependencies = new Map<string, string[]>();
if (bundle.outputFiles) {
for (const file of bundle.outputFiles) {
const path = relative(absWorkingDir, file.path);
files.set(path, file.contents);
}
}
files.set(
"metafile.json",
new TextEncoder().encode(JSON.stringify(bundle.metafile)),
);
if (bundle.metafile) {
const metaOutputs = new Map(Object.entries(bundle.metafile.outputs));
for (const [path, entry] of metaOutputs.entries()) {
const imports = entry.imports
.filter(({ kind }) => kind === "import-statement")
.map(({ path }) => path);
dependencies.set(path, imports);
}
}
return new EsbuildSnapshot(files, dependencies);
} finally {
await esbuild.stop();
}
}
}
function devClientUrlPlugin(basePath?: string): Plugin {
return {
name: "dev-client-url",
setup(build) {
build.onLoad(
{ filter: /client\.ts$/, namespace: "file" },
async (args) => {
// Load the original script
const contents = await Deno.readTextFile(args.path);
// Replace the URL
const modifiedContents = contents.replace(
"/_frsh/alive",
`${basePath}/_frsh/alive`,
);
return {
contents: modifiedContents,
loader: "ts",
};
},
);
},
};
}
function buildIdPlugin(buildId: string): Plugin {
const file = import.meta.resolve("../runtime/build_id.ts");
const url = new URL(file);
let options: OnLoadOptions;
if (url.protocol === "file:") {
const path = fromFileUrl(url);
const filter = new RegExp(`^${regexpEscape(path)}$`);
options = { filter, namespace: "file" };
} else {
const namespace = url.protocol.slice(0, -1);
const path = url.href.slice(namespace.length + 1);
const filter = new RegExp(`^${regexpEscape(path)}$`);
options = { filter, namespace };
}
return {
name: "fresh-build-id",
setup(build) {
build.onLoad(
options,
() => ({ contents: `export const BUILD_ID = "${buildId}";` }),
);
},
};
}
export class EsbuildSnapshot implements BuildSnapshot {
#files: Map<string, Uint8Array>;
#dependencies: Map<string, string[]>;
constructor(
files: Map<string, Uint8Array>,
dependencies: Map<string, string[]>,
) {
this.#files = files;
this.#dependencies = dependencies;
}
get paths(): string[] {
return Array.from(this.#files.keys());
}
read(path: string): Uint8Array | null {
return this.#files.get(path) ?? null;
}
dependencies(path: string): string[] {
return this.#dependencies.get(path) ?? [];
}
}
-60
View File
@@ -1,60 +0,0 @@
import { assertEquals } from "./deps.ts";
import { fromFileUrl, join, toFileUrl } from "../server/deps.ts";
import { EsbuildBuilder } from "./esbuild.ts";
const denoJson = join(
fromFileUrl(import.meta.url),
"..",
"..",
"..",
"deno.json",
);
const mainEntry = toFileUrl(join(
fromFileUrl(import.meta.url),
"..",
"..",
"runtime",
"entrypoints",
"client.ts",
)).href;
Deno.test("esbuild", async (t) => {
await t.step("esbuild snapshot with cwd=Deno.cwd()", async () => {
const builder = new EsbuildBuilder({
absoluteWorkingDir: Deno.cwd(),
buildID: "foo",
configPath: denoJson,
dev: false,
entrypoints: {
main: mainEntry,
},
jsx: "react-jsx",
target: "es2020",
});
const snapshot = await builder.build();
assertEquals(snapshot.paths, ["main.js", "metafile.json"]);
});
await t.step({
name: "esbuild snapshot with cwd=/",
ignore: Deno.build.os === "windows",
fn: async () => {
const builder = new EsbuildBuilder({
absoluteWorkingDir: "/",
buildID: "foo",
configPath: denoJson,
dev: false,
entrypoints: {
main: mainEntry,
},
jsx: "react-jsx",
target: "es2020",
});
const snapshot = await builder.build();
assertEquals(snapshot.paths, ["main.js", "metafile.json"]);
},
});
});
Binary file not shown.
-34
View File
@@ -1,34 +0,0 @@
export {
EsbuildBuilder,
type EsbuildBuilderOptions,
EsbuildSnapshot,
} from "./esbuild.ts";
export { AotSnapshot } from "./aot_snapshot.ts";
export interface Builder {
build(): Promise<BuildSnapshot>;
}
export interface BuildSnapshot {
/** The list of files contained in this snapshot, not prefixed by a slash. */
readonly paths: string[];
/** For a given file, return it's contents.
* @throws If the file is not contained in this snapshot. */
read(
path: string,
):
| ReadableStream<Uint8Array>
| Uint8Array
| null
| Promise<ReadableStream<Uint8Array> | Uint8Array | null>;
/** For a given entrypoint, return it's list of dependencies.
*
* Returns an empty array if the entrypoint does not exist. */
dependencies(path: string): string[];
}
export interface BuildSnapshotJson {
build_id: string;
files: Record<string, string[]>;
}
+110
View File
@@ -0,0 +1,110 @@
import * as path from "@std/path";
import type { ResolvedFreshConfig } from "./config.ts";
import { setBuildId } from "./runtime/build_id.ts";
export interface FileSnapshot {
generated: boolean;
hash: string | null;
}
export interface BuildSnapshot {
version: number;
buildId: string;
staticFiles: Record<string, FileSnapshot>;
islands: Record<string, string>;
}
export interface StaticFile {
hash: string | null;
size: number;
readable: ReadableStream<Uint8Array> | Uint8Array;
}
export interface BuildCache {
hasSnapshot: boolean;
readFile(pathname: string): Promise<StaticFile | null>;
getIslandChunkName(islandName: string): string | null;
}
export class ProdBuildCache implements BuildCache {
static async fromSnapshot(config: ResolvedFreshConfig) {
const snapshotPath = path.join(config.build.outDir, "snapshot.json");
const staticFiles = new Map<string, FileSnapshot>();
const islandToChunk = new Map<string, string>();
let hasSnapshot = false;
try {
const content = await Deno.readTextFile(snapshotPath);
const snapshot = JSON.parse(content) as BuildSnapshot;
hasSnapshot = true;
setBuildId(snapshot.buildId);
const files = Object.keys(snapshot.staticFiles);
for (let i = 0; i < files.length; i++) {
const pathname = files[i];
const info = snapshot.staticFiles[pathname];
staticFiles.set(pathname, info);
}
const islands = Object.keys(snapshot.islands);
for (let i = 0; i < islands.length; i++) {
const pathname = islands[i];
islandToChunk.set(pathname, snapshot.islands[pathname]);
}
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
return new ProdBuildCache(config, islandToChunk, staticFiles, hasSnapshot);
}
#islands: Map<string, string>;
#fileInfo: Map<string, FileSnapshot>;
#config: ResolvedFreshConfig;
constructor(
config: ResolvedFreshConfig,
islands: Map<string, string>,
files: Map<string, FileSnapshot>,
public hasSnapshot: boolean,
) {
this.#islands = islands;
this.#fileInfo = files;
this.#config = config;
}
async readFile(pathname: string): Promise<StaticFile | null> {
const info = this.#fileInfo.get(pathname);
if (info === undefined) return null;
const base = info.generated
? this.#config.build.outDir
: this.#config.staticDir;
const filePath = info.generated
? path.join(base, "static", pathname)
: path.join(base, pathname);
// Check if path resolves outside of intended directory.
if (path.relative(base, filePath).startsWith(".")) {
return null;
}
const [stat, file] = await Promise.all([
Deno.stat(filePath),
Deno.open(filePath),
]);
return {
hash: info.hash,
size: stat.size,
readable: file.readable,
};
}
getIslandChunkName(islandName: string): string | null {
return this.#islands.get(islandName) ?? null;
}
}
+59
View File
@@ -0,0 +1,59 @@
import type { VNode } from "preact";
import type { FreshContext } from "../context.ts";
import type { HandlerByMethod } from "../handlers.ts";
/**
* @deprecated Use {@link FreshContext} instead
*/
export type AppProps<Data = unknown, T = unknown> = FreshContext<Data, T>;
/**
* @deprecated Use {@link FreshContext} instead
*/
export type LayoutProps<Data = unknown, T = unknown> = FreshContext<Data, T>;
/**
* @deprecated Use {@link FreshContext} instead
*/
export type UnknownPageProps<Data = unknown, T = unknown> = FreshContext<
Data,
T
>;
/**
* @deprecated Use {@link FreshContext} instead
*/
export type ErrorPageProps<Data = unknown, T = unknown> = FreshContext<Data, T>;
/**
* @deprecated Use {@link FreshContext} instead
*/
// deno-lint-ignore no-explicit-any
export type RouteContext<T = any, S = Record<string, unknown>> = FreshContext<
T,
S
>;
// deno-lint-ignore no-explicit-any
export type Handlers<T = any, State = Record<string, unknown>> =
HandlerByMethod<T, State>;
function defineFn<State>(
fn: (
ctx: FreshContext<unknown, State>,
) => Request | VNode | null | Promise<Request | VNode | null>,
): (
ctx: FreshContext<unknown, State>,
) => Request | VNode | null | Promise<Request | VNode | null> {
return fn;
}
/**
* @deprecated Use {@link definePage} instead
*/
export const defineApp = defineFn;
/**
* @deprecated Use {@link definePage} instead
*/
export const defineRoute = defineFn;
/**
* @deprecated Use {@link definePage} instead
*/
export const defineLayout = defineFn;
+74
View File
@@ -0,0 +1,74 @@
import * as path from "@std/path";
import { MODE, type Mode } from "./runtime/server/mod.tsx";
export interface FreshPlugin {
name: string;
}
export interface FreshConfig {
root?: string;
build?: {
/**
* 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.
*/
outDir?: string;
};
/**
* Serve fresh from a base path instead of from the root.
* "/foo/bar" -> http://localhost:8000/foo/bar
* @default {undefined}
*/
basePath?: string;
staticDir?: string;
}
/**
* The final resolved Fresh configuration where fields the user didn't specify are set to the default values.
*/
export interface ResolvedFreshConfig {
root: string;
build: {
outDir: string;
};
basePath: string;
staticDir: string;
/**
* Tells you in which mode Fresh is currently running in.
*/
mode: Mode;
}
export function parseRootPath(root: string): string {
if (root.startsWith("file://")) {
root = path.fromFileUrl(root);
}
const ext = path.extname(root);
if (
ext === ".ts" || ext === ".tsx" || ext === ".js" || ext === ".jsx" ||
ext === ".mjs"
) {
root = path.dirname(root);
}
return root;
}
export function normalizeConfig(options: FreshConfig): ResolvedFreshConfig {
const root = options.root ? parseRootPath(options.root) : Deno.cwd();
return {
root,
build: {
outDir: options.build?.outDir ?? path.join(root, "_fresh"),
},
basePath: options.basePath ?? "",
staticDir: options.staticDir ?? path.join(root, "static"),
mode: MODE,
};
}
export function getSnapshotPath(config: ResolvedFreshConfig): string {
return path.join(config.build.outDir, "snapshot.json");
}
+14
View File
@@ -0,0 +1,14 @@
import { expect } from "@std/expect";
import { parseRootPath } from "./config.ts";
// FIXME: Windows
Deno.test.ignore("parseRootPath", () => {
expect(parseRootPath("file:///foo/bar")).toEqual("/foo/bar");
expect(parseRootPath("file:///foo/bar.ts")).toEqual("/foo");
expect(parseRootPath("/foo/bar")).toEqual("/foo/bar");
expect(parseRootPath("/foo/bar.ts")).toEqual("/foo");
expect(parseRootPath("/foo/bar.tsx")).toEqual("/foo");
expect(parseRootPath("/foo/bar.js")).toEqual("/foo");
expect(parseRootPath("/foo/bar.jsx")).toEqual("/foo");
expect(parseRootPath("/foo/bar.mjs")).toEqual("/foo");
});
+5 -13
View File
@@ -1,13 +1,5 @@
export const PARTIAL_SEARCH_PARAM = "fresh-partial";
export const PARTIAL_ATTR = "f-partial";
export const LOADING_ATTR = "f-loading";
export const CLIENT_NAV_ATTR = "f-client-nav";
export const DATA_KEY_ATTR = "data-fresh-key";
export const DATA_CURRENT = "data-current";
export const DATA_ANCESTOR = "data-ancestor";
export const enum PartialMode {
REPLACE,
APPEND,
PREPEND,
}
export const INTERNAL_PREFIX = "/_frsh";
export const DEV_CLIENT_URL = `${INTERNAL_PREFIX}/fresh_dev_client.js`;
export const DEV_ERROR_OVERLAY_URL = `${INTERNAL_PREFIX}/error_overlay`;
export const ALIVE_URL = `${INTERNAL_PREFIX}/alive`;
export const JS_PREFIX = `/js`;
+203
View File
@@ -0,0 +1,203 @@
import { type ComponentType, h, isValidElement, type VNode } from "preact";
import type { ResolvedFreshConfig } from "./config.ts";
import { renderToString } from "preact-render-to-string";
import type { BuildCache } from "./build_cache.ts";
import {
FreshScripts,
RenderState,
setRenderState,
} from "./runtime/server/preact_hooks.tsx";
import { DEV_ERROR_OVERLAY_URL } from "./constants.ts";
export interface Island {
file: string | URL;
name: string;
exportName: string;
fn: ComponentType;
}
export type ServerIslandRegistry = Map<ComponentType, Island>;
/**
* The context passed to every middleware. It is unique for every request.
*/
export interface FreshContext<Data = unknown, State = unknown> {
/** Reference to the resolved Fresh configuration */
readonly config: ResolvedFreshConfig;
state: State;
data: Data;
/** The original incoming `Request` object` */
req: Request;
/**
* The request url parsed into an `URL` instance. This is typically used
* to apply logic based on the pathname of the incoming url or when
* certain search parameters are set.
*/
url: URL;
params: Record<string, string>;
error: unknown;
info?: Deno.ServeHandlerInfo | Deno.ServeUnixHandlerInfo;
/**
* Return a redirect response to the specified path. This is the
* preferred way to do redirects in Fresh.
*
* ```ts
* ctx.redirect("/foo/bar") // redirect user to "<yoursite>/foo/bar"
*
* // Disallows protocol relative URLs for improved security. This
* // redirects the user to `<yoursite>/evil.com` which is safe,
* // instead of redirecting to `http://evil.com`.
* ctx.redirect("//evil.com/");
* ```
*/
redirect(path: string, status?: number): Response;
/**
* Call the next middleware.
* ```ts
* const myMiddleware: Middleware = (ctx) => {
* // do something
*
* // Call the next middleware
* return ctx.next();
* }
*
* const myMiddleware2: Middleware = async (ctx) => {
* // do something before the next middleware
* doSomething()
*
* const res = await ctx.next();
*
* // do something after the middleware
* doSomethingAfter()
*
* // Return the `Response`
* return res
* }
*/
next(): Promise<Response>;
render(vnode: VNode, init?: ResponseInit): Response | Promise<Response>;
}
export let getBuildCache: (ctx: FreshContext<unknown, unknown>) => BuildCache;
export class FreshReqContext<State> implements FreshContext<unknown, State> {
url: URL;
params = {} as Record<string, string>;
state = {} as State;
data = {} as never;
error: Error | null = null;
#islandRegistry: ServerIslandRegistry;
#buildCache: BuildCache;
static {
getBuildCache = (ctx) => (ctx as FreshReqContext<unknown>).#buildCache;
}
constructor(
public req: Request,
public config: ResolvedFreshConfig,
public next: FreshContext<unknown, State>["next"],
islandRegistry: ServerIslandRegistry,
buildCache: BuildCache,
public info: Deno.ServeHandlerInfo | Deno.ServeUnixHandlerInfo,
) {
this.#islandRegistry = islandRegistry;
this.#buildCache = buildCache;
this.url = new URL(req.url);
}
redirect(pathOrUrl: string, status = 302): Response {
let location = pathOrUrl;
// Disallow protocol relative URLs
if (pathOrUrl !== "/" && pathOrUrl.startsWith("/")) {
let idx = pathOrUrl.indexOf("?");
if (idx === -1) {
idx = pathOrUrl.indexOf("#");
}
const pathname = idx > -1 ? pathOrUrl.slice(0, idx) : pathOrUrl;
const search = idx > -1 ? pathOrUrl.slice(idx) : "";
// Remove double slashes to prevent open redirect vulnerability.
location = `${pathname.replaceAll(/\/+/g, "/")}${search}`;
}
return new Response(null, {
status,
headers: {
location,
},
});
}
render(
// deno-lint-ignore no-explicit-any
vnode: VNode<any>,
init: ResponseInit | undefined = {},
): Response | Promise<Response> {
if (arguments.length === 0) {
throw new Error(`No arguments passed to: ctx.render()`);
} else if (vnode !== null && !isValidElement(vnode)) {
throw new Error(`Non-JSX element passed to: ctx.render()`);
}
const headers = init.headers !== undefined
? init.headers instanceof Headers
? init.headers
: new Headers(init.headers)
: new Headers();
headers.set("Content-Type", "text/html; charset=utf-8");
const responseInit: ResponseInit = { status: init.status ?? 200, headers };
let partialId = "";
if (this.url.searchParams.has("fresh-partial")) {
partialId = crypto.randomUUID();
headers.set("X-Fresh-Id", partialId);
}
const html = preactRender(
vnode,
this,
this.#islandRegistry,
this.#buildCache,
partialId,
);
return new Response(html, responseInit);
}
}
function preactRender<State, Data>(
vnode: VNode,
ctx: FreshContext<Data, State>,
islandRegistry: ServerIslandRegistry,
buildCache: BuildCache,
partialId: string,
) {
const state = new RenderState(ctx, islandRegistry, buildCache, partialId);
setRenderState(state);
try {
let res = renderToString(vnode);
// We require a the full outer DOM structure so that browser put
// comment markers in the right place in the DOM.
if (!state.renderedHtmlBody) {
let scripts = "";
if (ctx.url.pathname !== ctx.config.basePath + DEV_ERROR_OVERLAY_URL) {
scripts = renderToString(h(FreshScripts, null));
}
res = `<body>${res}${scripts}</body>`;
}
if (!state.renderedHtmlHead) {
res = `<head><meta charset="utf-8"></head>${res}`;
}
if (!state.renderedHtmlTag) {
res = `<html>${res}</html>`;
}
return `<!DOCTYPE html>${res}`;
} finally {
state.clear();
setRenderState(null);
}
}
+71
View File
@@ -0,0 +1,71 @@
import { expect } from "@std/expect";
import { FreshReqContext } from "./context.ts";
import { App } from "@fresh/core";
import { asset } from "@fresh/core/runtime";
import { FakeServer } from "./test_utils.ts";
import { BUILD_ID } from "./runtime/build_id.ts";
import { parseHtml } from "../tests/test_utils.tsx";
Deno.test("FreshReqContext.prototype.redirect", () => {
let res = FreshReqContext.prototype.redirect("/");
expect(res.status).toEqual(302);
expect(res.headers.get("Location")).toEqual("/");
res = FreshReqContext.prototype.redirect("//evil.com");
expect(res.status).toEqual(302);
expect(res.headers.get("Location")).toEqual("/evil.com");
res = FreshReqContext.prototype.redirect("//evil.com/foo//bar");
expect(res.status).toEqual(302);
expect(res.headers.get("Location")).toEqual("/evil.com/foo/bar");
res = FreshReqContext.prototype.redirect("https://deno.com");
expect(res.status).toEqual(302);
expect(res.headers.get("Location")).toEqual("https://deno.com");
res = FreshReqContext.prototype.redirect("/", 307);
expect(res.status).toEqual(307);
});
Deno.test("render asset()", async () => {
const app = new App()
.get("/", (ctx) =>
ctx.render(
<>
<p class="raw">{asset("/foo")}</p>
<img src="/foo" srcset="/foo-bar" />
<source src="/foo" />
</>,
));
const server = new FakeServer(await app.handler());
const res = await server.get("/");
const doc = parseHtml(await res.text());
expect(doc.querySelector(".raw")!.textContent).toContain(BUILD_ID);
expect(doc.querySelector("img")!.src).toContain(BUILD_ID);
expect(doc.querySelector("img")!.srcset).toContain(BUILD_ID);
expect(doc.querySelector("source")!.src).toContain(BUILD_ID);
});
Deno.test("ctx.render - throw with no arguments", async () => {
const app = new App()
// deno-lint-ignore no-explicit-any
.get("/", (ctx) => (ctx as any).render());
const server = new FakeServer(await app.handler());
const res = await server.get("/");
await res.body?.cancel();
expect(res.status).toEqual(500);
});
Deno.test("ctx.render - throw with invalid first arg", async () => {
const app = new App()
// deno-lint-ignore no-explicit-any
.get("/", (ctx) => (ctx as any).render({}));
const server = new FakeServer(await app.handler());
const res = await server.get("/");
await res.body?.cancel();
expect(res.status).toEqual(500);
});
-55
View File
@@ -1,55 +0,0 @@
import { getServerContext } from "../server/context.ts";
import { join } from "../server/deps.ts";
import { colors, emptyDir } from "./deps.ts";
import { BuildSnapshotJson } from "../build/mod.ts";
import { BUILD_ID } from "../server/build_id.ts";
import { InternalFreshState } from "../server/types.ts";
export async function build(
state: InternalFreshState,
) {
const outDir = state.config.build.outDir;
const plugins = state.config.plugins;
// Ensure that build dir is empty
await emptyDir(outDir);
// Create a directory for static assets produced during the build
await Deno.mkdir(join(outDir, "static"));
await Promise.all(
plugins.map((plugin) => plugin.configResolved?.(state.config)),
);
await Promise.all(plugins.map((plugin) => plugin.buildStart?.(state.config)));
// Bundle assets
const ctx = await getServerContext(state);
const snapshot = await ctx.buildSnapshot();
// Write output files to disk
await Promise.all(snapshot.paths.map(async (fileName) => {
const data = await snapshot.read(fileName);
if (data === null) return;
return Deno.writeFile(join(outDir, fileName), data);
}));
// Write dependency snapshot file to disk
const jsonSnapshot: BuildSnapshotJson = {
build_id: BUILD_ID,
files: {},
};
for (const filePath of snapshot.paths) {
const dependencies = snapshot.dependencies(filePath);
jsonSnapshot.files[filePath] = dependencies;
}
const snapshotPath = join(outDir, "snapshot.json");
await Deno.writeTextFile(snapshotPath, JSON.stringify(jsonSnapshot, null, 2));
console.log(
`Assets written to: ${colors.green(outDir)}`,
);
await Promise.all(plugins.map((plugin) => plugin.buildEnd?.()));
}
+250
View File
@@ -0,0 +1,250 @@
import {
App,
getBuildCache,
getIslandRegistry,
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,
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 { 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";
export interface BuildOptions {
/**
* This sets the target environment for the generated code. Newer
* language constructs will be transformed to match the specified
* support range. See https://esbuild.github.io/api/#target
* @default {"es2022"}
*/
target?: string | string[];
}
export interface FreshBuilder {
onTransformStaticFile(
options: OnTransformOptions,
callback: TransformFn,
): void;
build<T>(app: App<T>, options?: BuildOptions): Promise<void>;
listen<T>(app: App<T>, options?: ListenOptions & BuildOptions): Promise<void>;
}
export class Builder implements FreshBuilder {
#transformer = new FreshFileTransformer(fsAdapter);
#addedInternalTransforms = false;
#options: { target: string | string[] };
constructor(options: BuildOptions = {}) {
this.#options = {
target: options.target ?? ["chrome99", "firefox99", "safari15"],
};
}
onTransformStaticFile(
options: OnTransformOptions,
callback: TransformFn,
): void {
this.#transformer.onTransform(options, callback);
}
async listen<T>(app: App<T>, options: ListenOptions = {}): Promise<void> {
// Run update check in background
updateCheck(DAY).catch(() => {});
const devApp = new App<T>(app.config)
.use(liveReload())
.use(devErrorOverlay())
.mountApp("*", app);
setBuildCache(
devApp,
new MemoryBuildCache(
devApp.config,
BUILD_ID,
this.#transformer,
this.#options.target,
),
);
await Promise.all([
devApp.listen(options),
this.#build(devApp, true),
]);
return;
}
async build<T>(app: App<T>): Promise<void> {
setBuildCache(
app,
new DiskBuildCache(
app.config,
BUILD_ID,
this.#transformer,
this.#options.target,
),
);
return await this.#build(app, false);
}
async #build<T>(app: App<T>, dev: boolean): Promise<void> {
const { build } = app.config;
const staticOutDir = path.join(build.outDir, "static");
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 entryPoints: Record<string, string> = {
"fresh-runtime": dev ? "@fresh/core/client-dev" : "@fresh/core/client",
};
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 denoJson = await readDenoConfig(app.config.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(", ")
}`,
);
}
}
const output = await bundleJs({
cwd: app.config.root,
outDir: staticOutDir,
dev: dev ?? false,
target,
buildId: BUILD_ID,
entryPoints,
jsxImportSource,
denoJsonPath: denoJson.filePath,
});
for (let i = 0; i < output.files.length; i++) {
const file = output.files[i];
const pathname = `/${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, `/${chunk}`);
}
await buildCache.flush();
if (!dev) {
console.log(
`Assets written to: ${colors.cyan(build.outDir)}`,
);
}
}
}
export interface DenoConfig {
imports?: Record<string, string>;
importMap?: string;
tasks?: Record<string, string>;
lint?: {
rules: { tags?: string[] };
exclude?: string[];
};
fmt?: {
exclude?: string[];
};
exclude?: string[];
compilerOptions?: {
jsx?: string;
jsxImportSource?: string;
jsxPrecompileSkipElements?: string[];
};
}
export async function readDenoConfig(
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);
if (name.endsWith(".jsonc")) {
return { config: JSONC.parse(file) as DenoConfig, filePath };
} else {
return { config: JSON.parse(file), filePath };
}
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
}
const parent = path.dirname(dir);
if (parent === dir) {
throw new Error(
`Could not find a deno.json file in the current directory or any parent directory.`,
);
}
dir = parent;
}
}
+65
View File
@@ -0,0 +1,65 @@
import { expect } from "@std/expect";
import * as path from "@std/path";
import { Builder } from "./builder.ts";
import { App } from "../app.ts";
Deno.test("Builder - chain onTransformStaticFile", async () => {
const logs: string[] = [];
const builder = new Builder();
builder.onTransformStaticFile(
{ pluginName: "A", filter: /\.css$/ },
() => {
logs.push("A");
},
);
builder.onTransformStaticFile(
{ pluginName: "B", filter: /\.css$/ },
() => {
logs.push("B");
},
);
builder.onTransformStaticFile(
{ pluginName: "C", filter: /\.css$/ },
() => {
logs.push("C");
},
);
const tmp = await Deno.makeTempDir();
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);
expect(logs).toEqual(["A", "B", "C"]);
});
Deno.test({
name: "Builder - hashes CSS urls by default",
fn: async () => {
const builder = new Builder();
const tmp = await Deno.makeTempDir();
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);
const css = await Deno.readTextFile(
path.join(tmp, "dist", "static", "foo.css"),
);
expect(css).toContain('body { background: url("/foo.jpg?__frsh_c=');
},
sanitizeOps: false,
sanitizeResources: false,
});
-24
View File
@@ -1,24 +0,0 @@
import { join, toFileUrl } from "./deps.ts";
import { manifest } from "./mod.ts";
import { type FreshConfig } from "../server/mod.ts";
const args = Deno.args;
switch (args[0]) {
case "manifest": {
if (args[1]) {
const CONFIG_TS_PATH = join(args[1], "fresh.config.ts");
const url = toFileUrl(CONFIG_TS_PATH).toString();
const config: FreshConfig = (await import(url)).default;
await manifest(args[1], config?.router?.ignoreFilePattern);
} else {
console.error("Missing input for manifest command");
Deno.exit(1);
}
break;
}
default: {
console.error("Invalid command");
Deno.exit(1);
}
}
-32
View File
@@ -1,32 +0,0 @@
// std
export {
basename,
dirname,
extname,
fromFileUrl,
join,
relative,
resolve,
SEPARATOR,
toFileUrl,
} from "https://deno.land/std@0.216.0/path/mod.ts";
export { normalize } from "https://deno.land/std@0.216.0/path/posix/mod.ts";
export { DAY, WEEK } from "https://deno.land/std@0.216.0/datetime/constants.ts";
export * as colors from "https://deno.land/std@0.216.0/fmt/colors.ts";
export {
walk,
type WalkEntry,
WalkError,
} from "https://deno.land/std@0.216.0/fs/walk.ts";
export { parse } from "https://deno.land/std@0.216.0/flags/mod.ts";
export {
greaterOrEqual,
lessThan,
parse as semverParse,
} from "https://deno.land/std@0.216.0/semver/mod.ts";
export { emptyDir, existsSync } from "https://deno.land/std@0.216.0/fs/mod.ts";
export * as JSONC from "https://deno.land/std@0.216.0/jsonc/mod.ts";
export { assertEquals } from "https://deno.land/std@0.216.0/assert/mod.ts";
// ts-morph
export { Node, Project } from "https://deno.land/x/ts_morph@21.0.1/mod.ts";
+292
View File
@@ -0,0 +1,292 @@
import type { BuildCache, StaticFile } from "../build_cache.ts";
import * as path from "@std/path";
import 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";
export interface MemoryFile {
hash: string | null;
content: Uint8Array;
}
export interface DevBuildCache extends BuildCache {
islands: Map<string, string>;
addUnprocessedFile(pathname: string): void;
addProcessedFile(
pathname: string,
content: Uint8Array,
hash: string | null,
): Promise<void>;
flush(): Promise<void>;
}
export class MemoryBuildCache implements DevBuildCache {
hasSnapshot = true;
islands = new Map<string, string>();
#processedFiles = new Map<string, MemoryFile>();
#unprocessedFiles = new Map<string, string>();
#ready = Promise.withResolvers<void>();
constructor(
public config: ResolvedFreshConfig,
public buildId: string,
public transformer: FreshFileTransformer,
public target: string | string[],
) {
}
async readFile(pathname: string): Promise<StaticFile | null> {
await this.#ready.promise;
const processed = this.#processedFiles.get(pathname);
if (processed !== undefined) {
return {
hash: processed.hash,
readable: processed.content,
size: processed.content.byteLength,
};
}
const unprocessed = this.#unprocessedFiles.get(pathname);
if (unprocessed !== undefined) {
try {
const [stat, file] = await Promise.all([
Deno.stat(unprocessed),
Deno.open(unprocessed, { read: true }),
]);
return {
hash: null,
size: stat.size,
readable: file.readable,
};
} catch (_err) {
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);
if (relative.startsWith(".")) {
throw new Error(
`Processed file resolved outside of static dir ${entry}`,
);
}
// Might be a file that we still need to process
const transformed = await this.transformer.process(
entry,
"development",
this.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);
if (relative.startsWith(".")) {
throw new Error(
`Processed file resolved outside of static dir ${file.path}`,
);
}
const pathname = `/${relative}`;
this.addProcessedFile(pathname, file.content, null);
}
if (this.#processedFiles.has(pathname)) {
return this.readFile(pathname);
}
} else {
try {
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);
return this.readFile(pathname);
}
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
}
return null;
}
getIslandChunkName(islandName: string): string | null {
return this.islands.get(islandName) ?? null;
}
addUnprocessedFile(pathname: string): void {
this.#unprocessedFiles.set(
pathname,
path.join(this.config.staticDir, pathname),
);
}
// deno-lint-ignore require-await
async addProcessedFile(
pathname: string,
content: Uint8Array,
hash: string | null,
): Promise<void> {
this.#processedFiles.set(pathname, { content, hash });
}
// deno-lint-ignore require-await
async flush(): Promise<void> {
this.#ready.resolve();
}
}
// await fsAdapter.mkdirp(staticOutDir);
export class DiskBuildCache implements DevBuildCache {
hasSnapshot = true;
islands = new Map<string, string>();
#processedFiles = new Map<string, string | null>();
#unprocessedFiles = new Map<string, string>();
#transformer: FreshFileTransformer;
#target: string | string[];
constructor(
public config: ResolvedFreshConfig,
public buildId: string,
transformer: FreshFileTransformer,
target: string | string[],
) {
this.#transformer = transformer;
this.#target = target;
}
getIslandChunkName(islandName: string): string | null {
return this.islands.get(islandName) ?? null;
}
addUnprocessedFile(pathname: string): void {
this.#unprocessedFiles.set(
pathname,
path.join(this.config.staticDir, pathname),
);
}
async addProcessedFile(
pathname: string,
content: Uint8Array,
hash: string | null,
) {
this.#processedFiles.set(pathname, hash);
const outDir = pathname === "/metafile.json"
? this.config.build.outDir
: path.join(this.config.build.outDir, "static");
const filePath = path.join(outDir, pathname);
assertInDir(filePath, outDir);
await fsAdapter.mkdirp(path.dirname(filePath));
await Deno.writeFile(filePath, content);
}
// deno-lint-ignore require-await
async readFile(_pathname: string): Promise<StaticFile | null> {
throw new Error("Not implemented in build mode");
}
async flush(): Promise<void> {
const staticDir = this.config.staticDir;
if (await fsAdapter.isDirectory(staticDir)) {
const entries = fsAdapter.walk(staticDir, {
includeDirs: false,
includeFiles: true,
followSymlinks: false,
// Skip any folder or file starting with a "."
skip: [/\/\.[^/]+(\/|$)/],
});
for await (const entry of entries) {
const result = await this.#transformer.process(
entry.path,
"production",
this.#target,
);
if (result !== null) {
for (let i = 0; i < result.length; i++) {
const file = result[i];
assertInDir(file.path, staticDir);
const pathname = `/${path.relative(staticDir, file.path)}`;
await this.addProcessedFile(pathname, file.content, null);
}
} else {
const relative = path.relative(staticDir, entry.path);
const pathname = `/${relative}`;
this.addUnprocessedFile(pathname);
}
}
}
const snapshot: BuildSnapshot = {
version: 1,
buildId: this.buildId,
islands: {},
staticFiles: {},
};
for (const [name, chunk] of this.islands.entries()) {
snapshot.islands[name] = chunk;
}
for (const [name, filePath] of this.#unprocessedFiles.entries()) {
const file = await Deno.open(filePath);
const hash = await hashContent(file.readable);
snapshot.staticFiles[name] = {
hash,
generated: false,
};
}
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;
}
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] = {
hash,
generated: true,
};
}
await Deno.writeTextFile(
path.join(this.config.build.outDir, "snapshot.json"),
JSON.stringify(snapshot, null, 2),
);
}
}
async function hashContent(
content: Uint8Array | ReadableStream<Uint8Array>,
): Promise<string> {
const hashBuf = await crypto.subtle.digest(
"SHA-256",
content,
);
return encodeHex(hashBuf);
}
-78
View File
@@ -1,78 +0,0 @@
import { updateCheck } from "./update_check.ts";
import { DAY, dirname, fromFileUrl, join, toFileUrl } from "./deps.ts";
import { FreshConfig, Manifest as ServerManifest } from "../server/mod.ts";
import { build } from "./build.ts";
import { collect, ensureMinDenoVersion, generate, Manifest } from "./mod.ts";
import { startServer } from "../server/boot.ts";
import { getInternalFreshState } from "../server/config.ts";
import { getServerContext } from "../server/context.ts";
export async function dev(
base: string,
entrypoint: string,
config?: FreshConfig,
) {
ensureMinDenoVersion();
// Run update check in background
updateCheck(DAY).catch(() => {});
const dir = dirname(fromFileUrl(base));
let currentManifest: Manifest;
const prevManifest = Deno.env.get("FRSH_DEV_PREVIOUS_MANIFEST");
if (prevManifest) {
currentManifest = JSON.parse(prevManifest);
} else {
currentManifest = { islands: [], routes: [] };
}
const newManifest = await collect(dir, config?.router?.ignoreFilePattern);
Deno.env.set("FRSH_DEV_PREVIOUS_MANIFEST", JSON.stringify(newManifest));
const manifestChanged =
!arraysEqual(newManifest.routes, currentManifest.routes) ||
!arraysEqual(newManifest.islands, currentManifest.islands);
if (manifestChanged) await generate(dir, newManifest);
const manifest = (await import(toFileUrl(join(dir, "fresh.gen.ts")).href))
.default as ServerManifest;
if (Deno.args.includes("build")) {
const state = await getInternalFreshState(
manifest,
config ?? {},
);
state.config.dev = false;
state.loadSnapshot = false;
state.build = true;
await build(state);
} else if (config) {
const state = await getInternalFreshState(
manifest,
config,
);
state.config.dev = true;
state.loadSnapshot = false;
const ctx = await getServerContext(state);
await startServer(ctx.handler(), {
...state.config.server,
basePath: state.config.basePath,
});
} else {
// Legacy entry point: Back then `dev.ts` would call `main.ts` but
// this causes duplicate plugin instantiation if both `dev.ts` and
// `main.ts` instantiate plugins.
Deno.env.set("__FRSH_LEGACY_DEV", "true");
entrypoint = new URL(entrypoint, base).href;
await import(entrypoint);
}
}
function arraysEqual<T>(a: T[], b: T[]): boolean {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
-8
View File
@@ -1,8 +0,0 @@
export function printError(message: string) {
console.error(`%cerror%c: ${message}`, "color: red; font-weight: bold", "");
}
export function error(message: string): never {
printError(message);
Deno.exit(1);
}
+201
View File
@@ -0,0 +1,201 @@
import { denoPlugins } from "@luca/esbuild-deno-loader";
import type { Plugin as EsbuildPlugin } from "esbuild";
import * as path from "@std/path";
export interface FreshBundleOptions {
dev: boolean;
cwd: string;
buildId: string;
outDir: string;
denoJsonPath: string;
entryPoints: Record<string, string>;
target: string | string[];
jsxImportSource?: string;
}
export interface BuildOutput {
entryToChunk: Map<string, string>;
dependencies: Map<string, string[]>;
files: Array<{ hash: string | null; contents: Uint8Array; path: string }>;
}
let esbuild: null | typeof import("esbuild-wasm") = null;
const PREACT_ENV = Deno.env.get("PREACT_PATH");
export async function bundleJs(
options: FreshBundleOptions,
): Promise<BuildOutput> {
if (esbuild === null) {
esbuild = Deno.env.get("FRESH_ESBUILD_LOADER") === "portable"
? await import("esbuild-wasm")
: await import("esbuild");
await esbuild.initialize({});
}
try {
await Deno.mkdir(options.cwd, { recursive: true });
} catch (err) {
if (!(err instanceof Deno.errors.AlreadyExists)) {
throw err;
}
}
const bundle = await esbuild.build({
entryPoints: options.entryPoints,
platform: "browser",
target: options.target,
format: "esm",
bundle: true,
splitting: true,
treeShaking: true,
sourcemap: options.dev ? "linked" : false,
minify: !options.dev,
jsxDev: options.dev,
jsx: "automatic",
jsxImportSource: options.jsxImportSource ?? "preact",
absWorkingDir: options.cwd,
outdir: ".",
write: false,
metafile: true,
plugins: [
preactDebugger(PREACT_ENV),
buildIdPlugin(options.buildId),
windowsPathFixer(),
...denoPlugins({ configPath: options.denoJsonPath }),
],
});
const files: BuildOutput["files"] = [];
for (let i = 0; i < bundle.outputFiles.length; i++) {
const outputFile = bundle.outputFiles[i];
const relative = path.relative(options.cwd, outputFile.path);
files.push({
path: relative,
contents: outputFile.contents,
hash: outputFile.hash,
});
}
files.push({
path: "metafile.json",
contents: new TextEncoder().encode(JSON.stringify(bundle.metafile)),
hash: null,
});
const entryToChunk = new Map<string, string>();
const dependencies = new Map<string, string[]>();
const entryToName = new Map(
Array.from(Object.entries(options.entryPoints)).map(
(entry) => [entry[1], entry[0]],
),
);
if (bundle.metafile) {
const metaOutputs = new Map(Object.entries(bundle.metafile.outputs));
for (const [entryPath, entry] of metaOutputs.entries()) {
const imports = entry.imports
.filter(({ kind }) => kind === "import-statement")
.map(({ path }) => path);
dependencies.set(entryPath, imports);
if (entryPath !== "fresh-runtime.js" && entry.entryPoint !== undefined) {
const filePath = path.join(options.cwd, entry.entryPoint);
const name = entryToName.get(filePath)!;
entryToChunk.set(name, entryPath);
}
}
}
if (!options.dev) {
await esbuild.stop();
}
return {
files,
entryToChunk,
dependencies,
};
}
function buildIdPlugin(buildId: string): EsbuildPlugin {
return {
name: "fresh-build-id",
setup(build) {
build.onResolve({ filter: /runtime[/\\]+build_id\.ts$/ }, (args) => {
return {
path: args.path,
namespace: "fresh-internal",
};
});
build.onLoad({
filter: /runtime[/\\]build_id\.ts$/,
namespace: "fresh-internal",
}, () => {
return {
contents: `export const BUILD_ID = "${buildId}";`,
};
});
},
};
}
function toPreactModPath(mod: string): string {
if (mod === "preact/debug") {
return path.join("debug", "dist", "debug.module.js");
} else if (mod === "preact/hooks") {
return path.join("hooks", "dist", "hooks.module.js");
} else if (mod === "preact/devtools") {
return path.join("devtools", "dist", "devtools.module.js");
} else if (mod === "preact/compat") {
return path.join("compat", "dist", "compat.module.js");
} else if (mod === "preact/jsx-runtime" || mod === "preact/jsx-dev-runtime") {
return path.join("jsx-runtime", "dist", "jsxRuntime.module.js");
} else {
return path.join("dist", "preact.module.js");
}
}
function preactDebugger(preactPath: string | undefined): EsbuildPlugin {
return {
name: "fresh-preact-debugger",
setup(build) {
if (preactPath === undefined) return;
build.onResolve({ filter: /^preact/ }, (args) => {
const resolved = path.resolve(preactPath, toPreactModPath(args.path));
return {
path: resolved,
};
});
},
};
}
function windowsPathFixer(): EsbuildPlugin {
return {
name: "fresh-fix-windows",
setup(build) {
if (Deno.build.os === "windows") {
build.onResolve({ filter: /\.*/ }, (args) => {
if (args.path.startsWith("\\")) {
const normalized = path.resolve(args.path);
return {
path: normalized,
};
}
});
}
},
};
}
+247
View File
@@ -0,0 +1,247 @@
import type { FsAdapter } from "../fs.ts";
import { BUILD_ID } from "../runtime/build_id.ts";
import { assetInternal } from "../runtime/shared_internal.tsx";
export type TransformMode = "development" | "production";
export interface OnTransformOptions {
pluginName: string;
filter: RegExp;
}
export interface OnTransformResult {
content: string | Uint8Array;
path?: string;
map?: string | Uint8Array;
}
export interface OnTransformArgs {
path: string;
target: string | string[];
text: string;
content: Uint8Array;
mode: TransformMode;
}
export type TransformFn = (
args: OnTransformArgs,
) =>
| void
| OnTransformResult
| Array<{ path: string } & Omit<OnTransformResult, "path">>
| Promise<
| void
| OnTransformResult
| Array<{ path: string } & Omit<OnTransformResult, "path">>
>;
export interface Transformer {
options: OnTransformOptions;
fn: TransformFn;
}
export interface ProcessedFile {
path: string;
content: Uint8Array;
map: Uint8Array | null;
inputFiles: string[];
}
interface TransformReq {
newFile: boolean;
filePath: string;
content: Uint8Array;
map: null | Uint8Array;
inputFiles: string[];
}
export class FreshFileTransformer {
#transformers: Transformer[] = [];
#fs: FsAdapter;
constructor(fs: FsAdapter) {
this.#fs = fs;
}
onTransform(options: OnTransformOptions, callback: TransformFn): void {
this.#transformers.push({ options, fn: callback });
}
async process(
filePath: string,
mode: TransformMode,
target: string | string[],
): Promise<ProcessedFile[] | null> {
// Pre-check if we have any transformer for this file at all
let hasTransformer = false;
for (let i = 0; i < this.#transformers.length; i++) {
if (this.#transformers[i].options.filter.test(filePath)) {
hasTransformer = true;
break;
}
}
if (!hasTransformer) {
return null;
}
let content: Uint8Array;
try {
content = await this.#fs.readFile(filePath);
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
return null;
}
throw err;
}
const queue: TransformReq[] = [{
newFile: false,
content,
filePath,
map: null,
inputFiles: [filePath],
}];
const outFiles: ProcessedFile[] = [];
const seen = new Set<string>();
let req: TransformReq | undefined = undefined;
while ((req = queue.pop()) !== undefined) {
if (seen.has(req.filePath)) continue;
seen.add(req.filePath);
let transformed = false;
for (let i = 0; i < this.#transformers.length; i++) {
const transformer = this.#transformers[i];
const { options, fn } = transformer;
options.filter.lastIndex = 0;
if (!options.filter.test(req.filePath)) {
continue;
}
const result = await fn({
path: req.filePath,
mode,
target,
content: req!.content,
get text() {
return new TextDecoder().decode(req!.content);
},
});
if (result !== undefined) {
if (Array.isArray(result)) {
for (let i = 0; i < result.length; i++) {
const item = result[i];
if (item.path === undefined) {
throw new Error(
`The ".path" property must be set when returning multiple files in a transformer. [${transformer.options.pluginName}]`,
);
}
const outContent = typeof item.content === "string"
? new TextEncoder().encode(item.content)
: item.content;
const outMap = item.map !== undefined
? typeof item.map === "string"
? new TextEncoder().encode(item.map)
: item.map
: null;
if (req.filePath === item.path) {
if (req.content === outContent && req.map === outMap) {
continue;
}
transformed = true;
req.content = outContent;
req.map = outMap;
} else {
let found = false;
for (let i = 0; i < queue.length; i++) {
const req = queue[i];
if (req.filePath === item.path) {
found = true;
transformed = true;
req.content = outContent;
req.map = outMap;
}
}
if (!found) {
queue.push({
newFile: true,
filePath: item.path,
content: outContent,
map: outMap,
inputFiles: req.inputFiles.slice(),
});
}
}
}
} else {
const outContent = typeof result.content === "string"
? new TextEncoder().encode(result.content)
: result.content;
const outMap = result.map !== undefined
? typeof result.map === "string"
? new TextEncoder().encode(result.map)
: result.map
: null;
if (req.content === outContent && req.map === outMap) {
continue;
}
transformed = true;
req.content = outContent;
req.map = outMap;
req.filePath = result.path ?? req.filePath;
}
}
}
// TODO: Keep transforming until no one processes anymore
if (transformed || req.newFile) {
outFiles.push({
content: req.content,
map: req.map,
path: req.filePath,
inputFiles: req.inputFiles,
});
}
}
return outFiles.length > 0 ? outFiles : null;
}
}
const CSS_URL_REGEX = /url\((["'][^'"]+["']|[^)]+)\)/g;
export function cssAssetHash(transformer: FreshFileTransformer) {
transformer.onTransform({
pluginName: "fresh-css",
filter: /\.css$/,
}, (args) => {
const replaced = args.text.replaceAll(CSS_URL_REGEX, (_, str) => {
let rawUrl = str;
if (str[0] === "'" || str[0] === '"') {
rawUrl = str.slice(1, -1);
}
if (rawUrl.length === 0) {
return str;
}
return `url(${JSON.stringify(assetInternal(rawUrl, BUILD_ID))})`;
});
return {
content: replaced,
};
});
}
+229
View File
@@ -0,0 +1,229 @@
import { expect } from "@std/expect";
import type { FsAdapter } from "../fs.ts";
import {
FreshFileTransformer,
type ProcessedFile,
} from "./file_transformer.ts";
import { delay } from "../test_utils.ts";
function testTransformer(files: Record<string, string>) {
const mockFs: FsAdapter = {
isDirectory: () => Promise.resolve(false),
mkdirp: () => Promise.resolve(),
walk: async function* foo() {
},
readFile: (file) => {
if (file instanceof URL) throw new Error("Not supported");
// deno-lint-ignore no-explicit-any
const content = (files as any)[file];
const buf = new TextEncoder().encode(content);
return Promise.resolve(buf);
},
};
return new FreshFileTransformer(mockFs);
}
function consumeResult(result: ProcessedFile[]) {
const out: {
path: string;
content: string;
map: string | null;
inputFiles: string[];
}[] = [];
for (let i = 0; i < result.length; i++) {
const file = result[i];
out.push({
path: file.path,
content: typeof file.content === "string"
? file.content
: new TextDecoder().decode(file.content),
map: file.map !== null
? typeof file.map === "string"
? file.map
: new TextDecoder().decode(file.map)
: null,
inputFiles: file.inputFiles,
});
}
return out.sort((a, b) => a.path.localeCompare(b.path));
}
Deno.test("FileTransformer - transform sync", async () => {
const transformer = testTransformer({
"foo.txt": "foo",
});
transformer.onTransform({ pluginName: "foo", filter: /.*/ }, (args) => {
return {
content: args.text + "bar",
};
});
const result = await transformer.process("foo.txt", "development", "");
const files = await consumeResult(result!);
expect(files).toEqual([
{ content: "foobar", map: null, path: "foo.txt", inputFiles: ["foo.txt"] },
]);
});
Deno.test("FileTransformer - transform async", async () => {
const transformer = testTransformer({
"foo.txt": "foo",
});
transformer.onTransform({ pluginName: "foo", filter: /.*/ }, async (args) => {
await delay(1);
return {
content: args.text + "bar",
};
});
const result = await transformer.process("foo.txt", "development", "");
const files = await consumeResult(result!);
expect(files).toEqual([
{ content: "foobar", map: null, path: "foo.txt", inputFiles: ["foo.txt"] },
]);
});
Deno.test("FileTransformer - transform return Uint8Array", async () => {
const transformer = testTransformer({
"foo.txt": "foo",
});
transformer.onTransform({ pluginName: "foo", filter: /.*/ }, () => {
return {
content: new TextEncoder().encode("foobar"),
};
});
const result = await transformer.process("foo.txt", "development", "");
const files = await consumeResult(result!);
expect(files).toEqual([
{ content: "foobar", map: null, path: "foo.txt", inputFiles: ["foo.txt"] },
]);
});
Deno.test("FileTransformer - pass transformed content", async () => {
const transformer = testTransformer({
"input.txt": "input",
});
transformer.onTransform({ pluginName: "A", filter: /.*/ }, (args) => {
return {
content: args.text + " -> A",
};
});
transformer.onTransform({ pluginName: "B", filter: /.*/ }, (args) => {
return {
content: args.text + " -> B",
};
});
const result = await transformer.process("input.txt", "development", "");
const files = await consumeResult(result!);
expect(files).toEqual([
{
content: "input -> A -> B",
map: null,
path: "input.txt",
inputFiles: ["input.txt"],
},
]);
});
Deno.test(
"FileTransformer - pass transformed content with multiple",
async () => {
const transformer = testTransformer({
"input.txt": "input",
});
transformer.onTransform({ pluginName: "A", filter: /.*/ }, (args) => {
return [{
path: args.path,
content: args.text + " -> A",
}];
});
transformer.onTransform({ pluginName: "B", filter: /.*/ }, (args) => {
return {
content: args.text + " -> B",
};
});
const result = await transformer.process("input.txt", "development", "");
const files = await consumeResult(result!);
expect(files).toEqual([
{
content: "input -> A -> B",
map: null,
path: "input.txt",
inputFiles: ["input.txt"],
},
]);
},
);
Deno.test("FileTransformer - return multiple results", async () => {
const transformer = testTransformer({
"foo.txt": "foo",
});
const received: string[] = [];
transformer.onTransform({ pluginName: "A", filter: /foo\.txt$/ }, () => {
return [{
path: "a.txt",
content: "A",
}, {
path: "b.txt",
content: "B",
}];
});
transformer.onTransform({ pluginName: "B", filter: /.*/ }, (args) => {
received.push(args.path);
});
const result = await transformer.process("foo.txt", "development", "");
const files = await consumeResult(result!);
expect(files).toEqual([
{ content: "A", map: null, path: "a.txt", inputFiles: ["foo.txt"] },
{ content: "B", map: null, path: "b.txt", inputFiles: ["foo.txt"] },
]);
expect(received).toEqual(["foo.txt", "b.txt", "a.txt"]);
});
Deno.test(
"FileTransformer - track input files through temporary results",
async () => {
const transformer = testTransformer({
"foo.txt": "foo",
});
transformer.onTransform({ pluginName: "A", filter: /foo\.txt$/ }, () => {
return [{
path: "a.txt",
content: "A",
}, {
path: "b.txt",
content: "B",
}];
});
transformer.onTransform(
{ pluginName: "B", filter: /[ab]\.txt$/ },
(args) => {
return {
path: "c" + args.path,
content: args.text + "C",
};
},
);
const result = await transformer.process("foo.txt", "development", "");
const files = await consumeResult(result!);
expect(files).toEqual([
{ content: "AC", map: null, path: "ca.txt", inputFiles: ["foo.txt"] },
{ content: "BC", map: null, path: "cb.txt", inputFiles: ["foo.txt"] },
]);
},
);
-39
View File
@@ -1,39 +0,0 @@
export const RECOMMENDED_PREACT_VERSION = "10.22.0";
export const RECOMMENDED_PREACT_SIGNALS_VERSION = "1.2.2";
export const RECOMMENDED_PREACT_SIGNALS_CORE_VERSION = "1.5.1";
export const RECOMMENDED_TWIND_CORE_VERSION = "1.1.3";
export const RECOMMENDED_TWIND_PRESET_AUTOPREFIX_VERSION = "1.0.7";
export const RECOMMENDED_TWIND_PRESET_TAILWIND_VERSION = "1.1.4";
export const RECOMMENDED_STD_VERSION = "0.216.0";
export const RECOMMENDED_TAILIWIND_VERSION = "3.4.1";
export function freshImports(imports: Record<string, string>) {
imports["$fresh/"] = new URL("../../", import.meta.url).href;
imports["preact"] = `https://esm.sh/preact@${RECOMMENDED_PREACT_VERSION}`;
imports["preact/"] = `https://esm.sh/preact@${RECOMMENDED_PREACT_VERSION}/`;
imports["@preact/signals"] =
`https://esm.sh/*@preact/signals@${RECOMMENDED_PREACT_SIGNALS_VERSION}`;
imports["@preact/signals-core"] =
`https://esm.sh/*@preact/signals-core@${RECOMMENDED_PREACT_SIGNALS_CORE_VERSION}`;
}
export function twindImports(imports: Record<string, string>) {
imports["@twind/core"] =
`https://esm.sh/@twind/core@${RECOMMENDED_TWIND_CORE_VERSION}`;
imports["@twind/preset-tailwind"] =
`https://esm.sh/@twind/preset-tailwind@${RECOMMENDED_TWIND_PRESET_TAILWIND_VERSION}/`;
imports["@twind/preset-autoprefix"] =
`https://esm.sh/@twind/preset-autoprefix@${RECOMMENDED_TWIND_PRESET_AUTOPREFIX_VERSION}/`;
}
export function tailwindImports(imports: Record<string, string>) {
imports["tailwindcss"] = `npm:tailwindcss@${RECOMMENDED_TAILIWIND_VERSION}`;
imports["tailwindcss/"] =
`npm:/tailwindcss@${RECOMMENDED_TAILIWIND_VERSION}/`;
imports["tailwindcss/plugin"] =
`npm:/tailwindcss@${RECOMMENDED_TAILIWIND_VERSION}/plugin.js`;
}
export function dotenvImports(imports: Record<string, string>) {
imports["$std/"] = `https://deno.land/std@${RECOMMENDED_STD_VERSION}/`;
}
-134
View File
@@ -1,134 +0,0 @@
import { stringToIdentifier } from "../server/init_safe_deps.ts";
import { extname, join, normalize } from "./deps.ts";
/**
* Import specifiers must have forward slashes
*/
function toImportSpecifier(file: string) {
let specifier = normalize(file).replace(/\\/g, "/");
if (!specifier.startsWith(".")) {
specifier = "./" + specifier;
}
return specifier;
}
// Create a valid JS identifier out of the project relative specifier.
// Note that we only need to deal with strings that _must_ have been
// valid file names in Windows, macOS and Linux and every identifier we
// create here will be prefixed with at least one "$". This greatly
// simplifies the invalid characters we have to account for.
export function specifierToIdentifier(specifier: string, used: Set<string>) {
specifier = specifier.replace(/^(?:\.\/routes|\.\/islands)\//, "");
const ext = extname(specifier);
if (ext) specifier = specifier.slice(0, -ext.length);
// Turn the specifier into a readable JS identifier
let ident = stringToIdentifier(specifier);
if (used.has(ident)) {
let check = ident;
let i = 1;
while (used.has(check)) {
check = `${ident}_${i++}`;
}
ident = check;
}
used.add(ident);
return ident;
}
export interface Manifest {
routes: string[];
islands: string[];
}
export async function generate(directory: string, manifest: Manifest) {
const { routes, islands } = manifest;
// Keep track of which identifier we've already used
const used = new Set<string>();
const normalizedRoutes = new Map<string, string>();
for (let i = 0; i < routes.length; i++) {
const file = routes[i];
const specifier = toImportSpecifier(file);
const identifier = specifierToIdentifier(specifier, used);
normalizedRoutes.set(specifier, identifier);
}
const normalizedIslands: { specifier: string; identifier: string }[] = [];
for (let i = 0; i < islands.length; i++) {
const file = islands[i];
const specifier = toImportSpecifier(file);
const identifier = specifierToIdentifier(specifier, used);
normalizedIslands.push({ specifier, identifier });
}
const output = `// DO NOT EDIT. This file is generated by Fresh.
// This file SHOULD be checked into source version control.
// This file is automatically updated during development when running \`dev.ts\`.
${
Array.from(normalizedRoutes.entries()).map(([specifier, identifier]) =>
`import * as $${identifier} from "${specifier}";`
).join(
"\n",
)
}
${
normalizedIslands.map(({ specifier, identifier }) =>
`import * as $${identifier} from "${specifier}";`
)
.join("\n")
}
import type { Manifest } from "$fresh/server.ts";
const manifest = {
routes: {
${
Array.from(normalizedRoutes.entries()).map(([specifier, identifier]) =>
`${JSON.stringify(`${specifier}`)}: $${identifier},`
)
.join("\n ")
}
},
islands: {
${
normalizedIslands.map(({ specifier, identifier }) =>
`${JSON.stringify(`${specifier}`)}: $${identifier},`
)
.join("\n ")
}
},
baseUrl: import.meta.url,
} satisfies Manifest;
export default manifest;
`;
const proc = new Deno.Command(Deno.execPath(), {
args: ["fmt", "-"],
stdin: "piped",
stdout: "piped",
stderr: "null",
}).spawn();
const raw = new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode(output));
controller.close();
},
});
await raw.pipeTo(proc.stdin);
const { stdout } = await proc.output();
const manifestStr = new TextDecoder().decode(stdout);
const manifestPath = join(directory, "./fresh.gen.ts");
await Deno.writeTextFile(manifestPath, manifestStr);
console.log(
`%cThe manifest has been generated for ${routes.length} routes and ${islands.length} islands.`,
"color: blue; font-weight: bold",
);
}
-24
View File
@@ -1,24 +0,0 @@
import { assertEquals } from "./deps.ts";
import { specifierToIdentifier } from "./manifest.ts";
const run = specifierToIdentifier;
Deno.test("specifierToIdentifier", () => {
const used = new Set<string>();
assertEquals(run("foo/bar.ts", used), "foo_bar");
assertEquals(run("foo/bar.json.ts", used), "foo_bar_json");
assertEquals(run("foo/[id]/bar", used), "foo_id_bar");
assertEquals(run("foo/[...all]/bar", used), "foo_all_bar");
assertEquals(run("foo/[[optional]]/bar", used), "foo_optional_bar");
assertEquals(run("foo/as-df/bar", used), "foo_as_df_bar");
assertEquals(run("foo/as@df", used), "foo_as_df");
assertEquals(run("foo/foo.bar.baz.tsx", used), "foo_foo_bar_baz");
assertEquals(run("404", used), "_404");
assertEquals(run("foo/_middleware", used), "foo_middleware");
});
Deno.test("specifierToIdentifier deals with duplicates", () => {
const used = new Set<string>();
assertEquals(run("foo/bar", used), "foo_bar");
assertEquals(run("foo/bar", used), "foo_bar_1");
});
@@ -1,4 +1,5 @@
import { colors, fromFileUrl } from "./deps.ts";
import * as path from "@std/path";
import * as colors from "@std/fmt/colors";
function tabs2Spaces(str: string) {
return str.replace(/^\t+/, (tabs) => " ".repeat(tabs.length));
@@ -85,7 +86,10 @@ export interface StackFrame {
line: number;
column: number;
}
export function getFirstUserFile(stack: string): StackFrame | undefined {
function getFirstUserFile(
stack: string,
rootDir: string,
): StackFrame | undefined {
const lines = stack.split("\n");
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(STACK_FRAME);
@@ -96,6 +100,11 @@ export function getFirstUserFile(stack: string): StackFrame | undefined {
const column = +match[4];
if (file.startsWith("file://")) {
const filePath = path.fromFileUrl(file);
if (path.relative(rootDir, filePath).startsWith(".")) {
continue;
}
return {
fnName,
file,
@@ -107,20 +116,18 @@ export function getFirstUserFile(stack: string): StackFrame | undefined {
}
}
export async function getCodeFrame(error: Error) {
if (!error.stack) return;
const file = getFirstUserFile(error.stack);
export function getCodeFrame(stack: string, rootDir: string) {
const file = getFirstUserFile(stack, rootDir);
if (file) {
try {
const filePath = fromFileUrl(file.file);
const text = await Deno.readTextFile(filePath);
const filePath = path.fromFileUrl(file.file);
const text = Deno.readTextFileSync(filePath);
return createCodeFrame(
text,
file.line - 1,
file.column - 1,
);
} catch {
} catch (err) {
// Ignore
}
}
@@ -0,0 +1,32 @@
import { DEV_ERROR_OVERLAY_URL } from "../../../constants.ts";
import { HttpError } from "../../../error.ts";
import type { MiddlewareFn } from "../../../middlewares/mod.ts";
import { FreshScripts } from "../../../runtime/server/preact_hooks.tsx";
import { ErrorOverlay } from "./overlay.tsx";
export function devErrorOverlay<T>(): MiddlewareFn<T> {
return async (ctx) => {
const { config, url } = ctx;
if (url.pathname === config.basePath + DEV_ERROR_OVERLAY_URL) {
return ctx.render(<ErrorOverlay url={url} />);
}
try {
return await ctx.next();
} catch (err) {
if (ctx.req.headers.get("accept")?.includes("text/html")) {
let init: ResponseInit | undefined;
if (err instanceof HttpError) {
if (err.status < 500) throw err;
init = { status: err.status };
}
// At this point we're pretty sure to have a server error
console.error(err);
return ctx.render(<FreshScripts />, init);
}
throw err;
}
};
}
@@ -0,0 +1,57 @@
import { expect } from "@std/expect";
import { App } from "../../../app.ts";
import { FakeServer } from "../../../test_utils.ts";
import { devErrorOverlay } from "./middleware.tsx";
import { HttpError } from "../../../error.ts";
Deno.test("error overlay - show when error is thrown", async () => {
const app = new App();
app.use(devErrorOverlay());
app.config.mode = "development";
app.get("/", () => {
throw new Error("fail");
});
const server = new FakeServer(await app.handler());
const res = await server.get("/", {
headers: {
accept: "text/html",
},
});
const content = await res.text();
expect(content).toContain("fresh-error-overlay");
});
Deno.test("error overlay - should not be visible for HttpError <500", async () => {
const app = new App();
app.use(devErrorOverlay());
app.config.mode = "development";
app
.get("/", () => {
throw new HttpError(404);
})
.get("/500", () => {
throw new HttpError(500);
});
const server = new FakeServer(await app.handler());
let res = await server.get("/", {
headers: {
accept: "text/html",
},
});
let content = await res.text();
expect(content).not.toContain("fresh-error-overlay");
expect(res.status).toEqual(404);
res = await server.get("/500", {
headers: {
accept: "text/html",
},
});
content = await res.text();
expect(content).toContain("fresh-error-overlay");
expect(res.status).toEqual(500);
});
@@ -1,6 +1,4 @@
import { ComponentChildren, h } from "preact";
import { render } from "./render.ts";
import { PageProps } from "../server/mod.ts";
import type { ComponentChildren } from "preact";
// Just to get some syntax highlighting
const css = (arr: TemplateStringsArray, ...exts: never[]) => {
@@ -118,12 +116,18 @@ function CodeFrame(props: { codeFrame: string }) {
);
}
export function ErrorOverlay(props: PageProps) {
const DEFAULT_MESSAGE = "Internal Server Error";
export function ErrorOverlay(props: { url: URL }) {
const url = props.url;
const title = url.searchParams.get("message") || "Internal Server Error";
const title = url.searchParams.get("message") || DEFAULT_MESSAGE;
const stack = url.searchParams.get("stack");
const codeFrame = url.searchParams.get("code-frame");
if (title === DEFAULT_MESSAGE && !stack && !codeFrame) {
return null;
}
return (
<>
<div class="frsh-error-page">
+39
View File
@@ -0,0 +1,39 @@
import type { MiddlewareFn } from "../../middlewares/mod.ts";
import { ALIVE_URL } from "../../constants.ts";
// Live reload: Send updates to browser
export function liveReload<T>(): MiddlewareFn<T> {
const revision = Date.now();
return (ctx) => {
const { config, req, url } = ctx;
const aliveUrl = config.basePath + ALIVE_URL;
if (url.pathname === aliveUrl) {
if (req.headers.get("upgrade") !== "websocket") {
return new Response(null, { status: 501 });
}
// TODO: When a change is made the Deno server restarts,
// so for now the WebSocket connection is only used for
// the client to know when the server is back up. Once we
// have HMR we'll actively start sending messages back
// and forth.
const { response, socket } = Deno.upgradeWebSocket(req);
socket.addEventListener("open", () => {
socket.send(
JSON.stringify({
type: "initial-state",
revision,
}),
);
});
return response;
}
return ctx.next();
};
}
+8 -109
View File
@@ -1,111 +1,10 @@
import {
greaterOrEqual,
join,
relative,
semverParse,
walk,
WalkEntry,
} from "./deps.ts";
export { generate, type Manifest } from "./manifest.ts";
import { generate, type Manifest } from "./manifest.ts";
import { error } from "./error.ts";
const MIN_DENO_VERSION = "1.31.0";
const TEST_FILE_PATTERN = /[._]test\.(?:[tj]sx?|[mc][tj]s)$/;
import { setMode } from "../runtime/server/mod.tsx";
export function ensureMinDenoVersion() {
// Check that the minimum supported Deno version is being used.
if (
!greaterOrEqual(
semverParse(Deno.version.deno),
semverParse(MIN_DENO_VERSION),
)
) {
let message =
`Deno version ${MIN_DENO_VERSION} or higher is required. Please update Deno.\n\n`;
export { Builder, type FreshBuilder } from "./builder.ts";
export {
type OnTransformArgs,
type OnTransformOptions,
type TransformFn,
} from "./file_transformer.ts";
if (Deno.execPath().includes("homebrew")) {
message +=
"You seem to have installed Deno via homebrew. To update, run: `brew upgrade deno`\n";
} else {
message += "To update, run: `deno upgrade`\n";
}
error(message);
}
}
async function collectDir(
dir: string,
callback: (entry: WalkEntry, dir: string) => void,
ignoreFilePattern = TEST_FILE_PATTERN,
): Promise<void> {
// Check if provided path is a directory
try {
const stat = await Deno.stat(dir);
if (!stat.isDirectory) return;
} catch (err) {
if (err instanceof Deno.errors.NotFound) return;
throw err;
}
const routesFolder = walk(dir, {
includeDirs: false,
includeFiles: true,
exts: ["tsx", "jsx", "ts", "js"],
skip: [ignoreFilePattern],
});
for await (const entry of routesFolder) {
callback(entry, dir);
}
}
const GROUP_REG = /[/\\\\]\((_[^/\\\\]+)\)[/\\\\]/;
export async function collect(
directory: string,
ignoreFilePattern?: RegExp,
): Promise<Manifest> {
const filePaths = new Set<string>();
const routes: string[] = [];
const islands: string[] = [];
await Promise.all([
collectDir(join(directory, "./routes"), (entry, dir) => {
const rel = join("routes", relative(dir, entry.path));
const normalized = rel.slice(0, rel.lastIndexOf("."));
// A `(_islands)` path segment is a local island folder.
// Any route path segment wrapped in `(_...)` is ignored
// during route collection.
const match = normalized.match(GROUP_REG);
if (match && match[1].startsWith("_")) {
if (match[1] === "_islands") {
islands.push(rel);
}
return;
}
if (filePaths.has(normalized)) {
throw new Error(
`Route conflict detected. Multiple files have the same name: ${dir}${normalized}`,
);
}
filePaths.add(normalized);
routes.push(rel);
}, ignoreFilePattern),
collectDir(join(directory, "./islands"), (entry, dir) => {
const rel = join("islands", relative(dir, entry.path));
islands.push(rel);
}, ignoreFilePattern),
]);
routes.sort();
islands.sort();
return { routes, islands };
}
export async function manifest(path: string, ignoreFilePattern?: RegExp) {
const manifest = await collect(path, ignoreFilePattern);
await generate(path, manifest);
}
setMode("development");
+10 -9
View File
@@ -1,4 +1,6 @@
import { colors, join, lessThan, semverParse } from "./deps.ts";
import * as semver from "@std/semver";
import * as colors from "@std/fmt/colors";
import * as path from "@std/path";
export interface CheckFile {
last_checked: string;
@@ -33,7 +35,7 @@ function getHomeDir(): string | null {
function getFreshCacheDir(): string | null {
const home = getHomeDir();
if (home) return join(home, "fresh");
if (home) return path.join(home, "fresh");
return null;
}
@@ -47,10 +49,9 @@ async function fetchLatestVersion() {
}
async function readCurrentVersion() {
const versions = (await import("../../versions.json", {
return (await import("../../deno.json", {
with: { type: "json" },
})).default as string[];
return versions[0];
})).default.version;
}
export async function updateCheck(
@@ -70,7 +71,7 @@ export async function updateCheck(
const home = getCacheDir();
if (!home) return;
const filePath = join(home, "latest.json");
const filePath = path.join(home, "latest.json");
try {
await Deno.mkdir(home, { recursive: true });
} catch (err) {
@@ -113,12 +114,12 @@ export async function updateCheck(
}
// Only show update message if current version is smaller than latest
const currentVersion = semverParse(checkFile.current_version);
const latestVersion = semverParse(checkFile.latest_version);
const currentVersion = semver.parse(checkFile.current_version);
const latestVersion = semver.parse(checkFile.latest_version);
if (
(!checkFile.last_shown ||
Date.now() >= new Date(checkFile.last_shown).getTime() + interval) &&
lessThan(currentVersion, latestVersion)
semver.lessThan(currentVersion, latestVersion)
) {
checkFile.last_shown = new Date().toISOString();
+394
View File
@@ -0,0 +1,394 @@
import * as path from "@std/path";
import denoJson from "../../deno.json" with { type: "json" };
import { WEEK } from "@std/datetime";
import { getStdOutput } from "../../tests/test_utils.tsx";
import { expect } from "@std/expect";
import type { CheckFile } from "./update_check.ts";
const CURRENT_VERSION = denoJson.version;
const cwd = import.meta.dirname!;
Deno.test("stores update check file in $HOME/fresh", async () => {
const tmpDirName = await Deno.makeTempDir();
const filePath = path.join(tmpDirName, "latest.json");
await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
TEST_HOME: tmpDirName,
},
}).output();
const text = JSON.parse(await Deno.readTextFile(filePath));
expect(text).toEqual({
current_version: CURRENT_VERSION,
latest_version: "99.99.999",
last_checked: text.last_checked,
last_shown: text.last_shown,
});
await Deno.remove(tmpDirName, { recursive: true });
});
Deno.test("skips update check on specific environment variables", async (t) => {
const envs = ["FRESH_NO_UPDATE_CHECK", "CI", "DENO_DEPLOYMENT_ID"];
for (const env of envs) {
await t.step(`checking ${env}`, async () => {
const tmpDirName = await Deno.makeTempDir();
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
[env]: "true",
TEST_HOME: tmpDirName,
LATEST_VERSION: "1.30.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).not.toMatch(/Fresh 1\.30\.0 is available/);
await Deno.remove(tmpDirName, { recursive: true });
});
}
});
Deno.test("shows update message on version mismatch", async () => {
const tmpDirName = await Deno.makeTempDir();
const filePath = path.join(tmpDirName, "latest.json");
await Deno.writeTextFile(
filePath,
JSON.stringify({
current_version: "1.1.0",
latest_version: "1.1.0",
last_checked: new Date(0).toISOString(),
}),
);
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
TEST_HOME: tmpDirName,
LATEST_VERSION: "999.999.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).toMatch(/Fresh 999\.999\.0 is available/);
// Updates check file
const text = JSON.parse(await Deno.readTextFile(filePath));
expect(text).toEqual({
current_version: CURRENT_VERSION,
latest_version: "999.999.0",
last_checked: text.last_checked,
last_shown: text.last_shown,
});
await Deno.remove(tmpDirName, { recursive: true });
});
Deno.test("only fetch new version defined by interval", async (t) => {
const tmpDirName = await Deno.makeTempDir();
await t.step("fetches latest version initially", async () => {
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
UPDATE_INTERVAL: "100000",
TEST_HOME: tmpDirName,
LATEST_VERSION: "1.30.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).toMatch(/fetching latest version/);
});
await t.step("should not fetch if interval has not passed", async () => {
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
UPDATE_INTERVAL: "100000",
TEST_HOME: tmpDirName,
LATEST_VERSION: "1.30.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).not.toMatch(/fetching latest version/);
});
await t.step("fetches if interval has passed", async () => {
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
UPDATE_INTERVAL: "1 ",
TEST_HOME: tmpDirName,
LATEST_VERSION: "1.30.0",
},
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).toMatch(/fetching latest version/);
});
await Deno.remove(tmpDirName, { recursive: true });
});
Deno.test("updates current version in cache file", async () => {
const tmpDirName = await Deno.makeTempDir();
const checkFile: CheckFile = {
current_version: "1.2.0",
latest_version: "1.2.0",
last_checked: new Date(Date.now() - WEEK).toISOString(),
};
await Deno.writeTextFile(
path.join(tmpDirName, "latest.json"),
JSON.stringify(checkFile, null, 2),
);
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
TEST_HOME: tmpDirName,
LATEST_VERSION: CURRENT_VERSION,
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).not.toMatch(/Fresh .* is available/);
await Deno.remove(tmpDirName, { recursive: true });
});
Deno.test("only shows update message when current < latest", async () => {
const tmpDirName = await Deno.makeTempDir();
const checkFile: CheckFile = {
current_version: "9999.999.0",
latest_version: "1.2.0",
last_checked: new Date().toISOString(),
};
await Deno.writeTextFile(
path.join(tmpDirName, "latest.json"),
JSON.stringify(checkFile, null, 2),
);
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
TEST_HOME: tmpDirName,
LATEST_VERSION: CURRENT_VERSION,
CURRENT_VERSION: "99999.9999.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).not.toMatch(/Fresh .* is available/);
await Deno.remove(tmpDirName, { recursive: true });
});
Deno.test("migrates to last_shown property", async () => {
const tmpDirName = await Deno.makeTempDir();
const checkFile: CheckFile = {
latest_version: "1.4.0",
current_version: "1.2.0",
last_checked: new Date().toISOString(),
};
await Deno.writeTextFile(
path.join(tmpDirName, "latest.json"),
JSON.stringify(checkFile, null, 2),
);
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
TEST_HOME: tmpDirName,
CURRENT_VERSION: "1.2.0",
LATEST_VERSION: "99999.9999.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).toMatch(/Fresh .* is available/);
const checkFileAfter = JSON.parse(
await Deno.readTextFile(
path.join(tmpDirName, "latest.json"),
),
);
// Check if last version was written
expect(typeof checkFileAfter.last_shown).toEqual("string");
await Deno.remove(tmpDirName, { recursive: true });
});
Deno.test("doesn't show update if last_shown + interval >= today", async () => {
const tmpDirName = await Deno.makeTempDir();
const todayMinus1Hour = new Date();
todayMinus1Hour.setHours(todayMinus1Hour.getHours() - 1);
const checkFile: CheckFile = {
current_version: "1.2.0",
latest_version: "1.6.0",
last_checked: new Date().toISOString(),
last_shown: todayMinus1Hour.toISOString(),
};
await Deno.writeTextFile(
path.join(tmpDirName, "latest.json"),
JSON.stringify(checkFile, null, 2),
);
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
TEST_HOME: tmpDirName,
CURRENT_VERSION: "1.2.0",
LATEST_VERSION: "99999.9999.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).not.toMatch(/Fresh .* is available/);
await Deno.remove(tmpDirName, { recursive: true });
});
Deno.test(
"shows update if last_shown + interval < today",
async () => {
const tmpDirName = await Deno.makeTempDir();
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const checkFile: CheckFile = {
current_version: "1.2.0",
latest_version: "99.999.99",
last_checked: new Date().toISOString(),
last_shown: yesterday.toISOString(),
};
await Deno.writeTextFile(
path.join(tmpDirName, "latest.json"),
JSON.stringify(checkFile, null, 2),
);
const out = await new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(cwd, "../../tests/fixture_update_check/mod.ts"),
],
cwd,
env: {
CI: "false",
TEST_HOME: tmpDirName,
CURRENT_VERSION: CURRENT_VERSION,
LATEST_VERSION: "99999.9999.0",
},
stderr: "piped",
stdout: "piped",
}).output();
const { stdout } = getStdOutput(out);
expect(stdout).toMatch(/Fresh .* is available/);
const checkFileAfter = JSON.parse(
await Deno.readTextFile(
path.join(tmpDirName, "latest.json"),
),
);
expect(checkFileAfter.last_shown).not.toEqual(yesterday.toISOString());
await Deno.remove(tmpDirName, { recursive: true });
},
);
+155
View File
@@ -0,0 +1,155 @@
import { MODE } from "./runtime/server/mod.tsx";
export function getMessage(status: number): string {
switch (status) {
case 100:
return "Continue";
case 101:
return "Switching Protocols";
case 102:
return "Processing (WebDAV)";
case 103:
return "Early Hints";
case 200:
return "OK";
case 201:
return "Created";
case 202:
return "Accepted";
case 203:
return "Non-Authoritative Information";
case 204:
return "No Content";
case 205:
return "Reset Content";
case 206:
return "Partial Content";
case 207:
return "Multi-Status (WebDAV)";
case 208:
return "Already Reported (WebDAV)";
case 226:
return "IM Used (HTTP Delta encoding)";
case 300:
return "Multiple Choices";
case 301:
return "Moved Permanently";
case 302:
return "Found";
case 303:
return "See Other";
case 304:
return "Not Modified";
case 305:
return "Use Proxy Deprecated";
case 306:
return "unused";
case 307:
return "Temporary Redirect";
case 308:
return "Permanent Redirect";
case 400:
return "Bad Request";
case 401:
return "Unauthorized";
case 402:
return "Payment Required Experimental";
case 403:
return "Forbidden";
case 404:
return "Not Found";
case 405:
return "Method Not Allowed";
case 406:
return "Not Acceptable";
case 407:
return "Proxy Authentication Required";
case 408:
return "Request Timeout";
case 409:
return "Conflict";
case 410:
return "Gone";
case 411:
return "Length Required";
case 412:
return "Precondition Failed";
case 413:
return "Payload Too Large";
case 414:
return "URI Too Long";
case 415:
return "Unsupported Media Type";
case 416:
return "Range Not Satisfiable";
case 417:
return "Expectation Failed";
case 418:
return "I'm a teapot";
case 421:
return "Misdirected Request";
case 422:
return "Unprocessable Content (WebDAV)";
case 423:
return "Locked (WebDAV)";
case 424:
return "Failed Dependency (WebDAV)";
case 425:
return "Too Early Experimental";
case 426:
return "Upgrade Required";
case 428:
return "Precondition Required";
case 429:
return "Too Many Requests";
case 431:
return "Request Header Fields Too Large";
case 451:
return "Unavailable For Legal Reasons";
case 500:
return "Internal Server Error";
case 501:
return "Not Implemented";
case 502:
return "Bad Gateway";
case 503:
return "Service Unavailable";
case 504:
return "Gateway Timeout";
case 505:
return "HTTP Version Not Supported";
case 506:
return "Variant Also Negotiates";
case 507:
return "Insufficient Storage (WebDAV)";
case 508:
return "Loop Detected (WebDAV)";
case 510:
return "Not Extended";
case 511:
return "Network Authentication Required";
default:
return "Internal Server Error";
}
}
export class HttpError {
#error: Error | null = null;
name = "HttpError";
message: string;
constructor(
public status: number,
message: string = getMessage(status),
public options?: ErrorOptions,
) {
this.message = message;
if (MODE !== "production") {
this.#error = new Error();
}
}
get stack(): string | undefined {
return this.#error?.stack;
}
}
+27
View File
@@ -0,0 +1,27 @@
import { expect } from "@std/expect";
import { MODE, setMode } from "./runtime/server/mod.tsx";
import { HttpError } from "./error.ts";
Deno.test("HttpError - contains stack in development", () => {
const tmp = MODE;
setMode("development");
try {
const err = new HttpError(404);
expect(err.status).toEqual(404);
expect(typeof err.stack).toEqual("string");
} finally {
setMode(tmp);
}
});
Deno.test("HttpError - contains no stack in production", () => {
const tmp = MODE;
setMode("production");
try {
const err = new HttpError(404);
expect(err.status).toEqual(404);
expect(err.stack).toEqual(undefined);
} finally {
setMode(tmp);
}
});
+54
View File
@@ -0,0 +1,54 @@
import type { ComponentChildren } from "preact";
export function FinishSetup() {
return (
<Doc>
<div class="frsh-error-page">
<div style="max-width: 48rem; padding: 2rem 1rem; margin: 0 auto; font-family: sans-serif">
<h1>Finish setting up Fresh</h1>
<ol style="line-height: 1.6; margin-bottom: 1.5rem">
<li>
Go to your project in Deno Deploy and click the{" "}
<code>Settings</code> tab.
</li>
<li>
In the Git Integration section, enter <code>deno task build</code>
{" "}
in the <code>Build Command</code> input.
</li>
<li>
Save the changes.
</li>
</ol>
</div>
</div>
</Doc>
);
}
export function ForgotBuild() {
return (
<Doc>
<div class="frsh-error-page">
<div style="max-width: 48rem; padding: 2rem 1rem; margin: 0 auto; font-family: sans-serif">
<h1>Missing build directory</h1>
<p>
Did you forget to run <code>deno task build</code>?
</p>
</div>
</div>
</Doc>
);
}
function Doc(props: { children?: ComponentChildren }) {
return (
<html>
<head>
<meta charset="utf-8" />
<title>Finish setting up Fresh</title>
</head>
<body>{props.children}</body>
</html>
);
}
+39
View File
@@ -0,0 +1,39 @@
import { walk, type WalkEntry, type WalkOptions } from "@std/fs/walk";
export interface FreshFile {
size: number;
readable: ReadableStream<Uint8Array>;
}
export interface FsAdapter {
walk(
root: string | URL,
options?: WalkOptions,
): AsyncIterableIterator<WalkEntry>;
isDirectory(path: string | URL): Promise<boolean>;
mkdirp(dir: string): Promise<void>;
readFile(path: string | URL): Promise<Uint8Array>;
}
export const fsAdapter: FsAdapter = {
walk,
async isDirectory(path) {
try {
const stat = await Deno.stat(path);
return stat.isDirectory;
} catch (err) {
if (err instanceof Deno.errors.NotFound) return false;
throw err;
}
},
async mkdirp(dir: string) {
try {
await Deno.mkdir(dir, { recursive: true });
} catch (err) {
if (!(err instanceof Deno.errors.AlreadyExists)) {
throw err;
}
}
},
readFile: Deno.readFile,
};
+172
View File
@@ -0,0 +1,172 @@
import type { FreshContext } from "./context.ts";
import type { Method } from "./router.ts";
export interface Render<T> {
data: T;
headers?: HeadersInit;
status?: number;
}
/**
* A handler function that can be used to specify how a given route should
* handle requests.
*
* The handler function can either return a {@link Response} object, or some
* data that can be rendered by a page component. See {@link HandlerFn} for more
* information.
*
* ### Per method handlers
*
* A route handler can be specific to a given HTTP method (GET, POST, PUT,
* DELETE, etc). To define a method-specific handler, specify an object that
* maps method names to functions that conform to the {@link HandlerFn}
* signature.
*
* ```ts
* export const handlers = defineHandlers({
* GET: (ctx) => {
* return new Response("Hello from a GET request!");
* },
* POST: (ctx) => {
* return new Response("Hello from a POST request!");
* }
* });
* ```
*
* Any requests to methods not specified in the handler object will result in a
* 405 Method Not Allowed response. If you want to handle these requests, you
* can define a catch-all handler.
*
* If a GET handler is specified, but no HEAD handler is specified, a HEAD
* handler will automatically be generated that calls the GET handler and
* strips the response body.
*
* ### Catch-all handlers
*
* A route handler can also catch all requests in a route. To define a catch-all
* handler, specify a function that conforms to the {@link HandlerFn} signature.
* This function will be called for all requests, regardless of the method.
*
* ```ts
* export const handlers = defineHandlers((ctx) => {
* return new Response(`Hello from a ${ctx.req.method} request!`);
* });
* ```
*/
export type RouteHandler<Data, State> =
| HandlerFn<Data, State>
| HandlerByMethod<Data, State>;
export function isHandlerByMethod<D, S>(
handler: RouteHandler<D, S>,
): handler is HandlerByMethod<D, S> {
return handler !== null && typeof handler === "object";
}
/**
* A handler function that is invoked when a request is made to a route. The
* handler function is passed a {@link FreshContext} object that contains the
* original request object, as well as any state related to the current request.
*
* The handler function can either return a {@link Response} object, which will
* be sent back to the client, or some data that will be passed to the routes'
* page component for rendering.
*
* ### Returning a Response
*
* If the handler function returns a {@link Response} object, the response will
* be sent back to the client. This can be used to send back static content, or
* to redirect the client to another URL.
*
* ```ts
* export const handler = defineHandler((ctx) => {
* return new Response("Hello, world!");
* });
* ```
*
* ### Returning data
*
* If the handler function returns an object with a `data` property, the data
* will be passed to the page component, where it can be rendered into HTML.
*
* ```ts
* export const handler = defineHandler((ctx) => {
* return { data: { message: "Hello, world!" } };
* });
*
* export default definePage<typeof handler>(({ data }) => {
* return <h1>{data.message}</h1>;
* });
* ```
*
* When returning data, you can also specify additional properties that will be
* used when constructing the response object from the HTML generated by the
* page component. For example, you can specify custom headers, a custom status
* code, or a list of elements to include in the `<head>`.
*
* ```tsx
* export const handler = defineHandler((ctx) => {
* return {
* data: { message: "Hello, world!" },
* headers: { "Cache-Control": "public, max-age=3600" },
* status: 201,
* head: [<title>Hello, world!</title>],
* };
* });
* ```
*
* ### Asynchronous handlers
*
* The handler function can also be asynchronous. This can be useful if you need
* to fetch data from an external source, or perform some other asynchronous
* operation before returning a response.
*
* ```ts
* export const handler = defineHandler(async (ctx) => {
* const resp = await fetch("https://api.example.com/data").;
* if (!resp.ok) {
* throw new Error("Failed to fetch data");
* }
* const data = await resp.json();
* return { data };
* });
* ```
*
* If you initiate multiple asynchronous operations in a handler, you can use
* `Promise.all` to wait for all of them to complete at the same time. This can
* speed up the response time of your handler, as it allows you to perform
* multiple operations concurrently.
*
* ```ts
* export const handler = defineHandler(async (ctx) => {
* const [resp1, resp2] = await Promise.all([
* fetch("https://api.example.com/data1")
* .then((resp) => resp.json()),
* fetch("https://api.example.com/data2")
* .then((resp) => resp.json()),
* ]);
* return { data: { data1, data2 } };
* });
* ```
*/
export interface HandlerFn<Data, State> {
(ctx: FreshContext<Data, State>):
| Response
| Render<Data>
| void
| Promise<Response | Render<Data> | void>;
}
/**
* A set of handler functions that routes requests based on the HTTP method.
*
* See {@link RouteHandler} for more information on how to use this type.
*/
export type HandlerByMethod<Data, State> = {
[M in Method]?: HandlerFn<Data, State>;
};
export type RouteData<
Handler extends RouteHandler<unknown, unknown>,
> = Handler extends (RouteHandler<infer Data, unknown>) ? Data
: never;
+155
View File
@@ -0,0 +1,155 @@
import type { AnyComponent } from "preact";
import type { HandlerByMethod, RouteHandler } from "./handlers.ts";
import type { FreshContext } from "./context.ts";
import type { Middleware } from "./middlewares/mod.ts";
/**
* A set of helper functions that enable better type inference and code
* completion when defining routes and middleware.
*
* To create a helpers object, call {@link createHelpers}.
*/
export interface Helpers<State> {
/**
* Define a {@link RouteHandler} object. This function returns the passed
* input as-is.
*
* You can use this function to help the TypeScript compiler infer the types
* of your route handlers. For example:
*
* ```ts
* export const handler = helpers.defineHandlers((ctx) => {
* ctx.url; // ctx is inferred to be a FreshContext object, so this is a URL
* return new Response("Hello, world!");
* });
* ```
*
* This is particularly useful when combined with the {@link definePage}
* helper function, which can infer the data type from the handler function.
* For more information, see {@link definePage}.
*
* You can also pass an explicit type argument to ensure that all data
* returned from the render function is of the correct type:
*
* ```ts
* export const handler = helpers.defineHandlers<{ slug: string }>({
* async GET(ctx) {
* const slug = ctx.params.slug; // slug is inferred to be a string
* return { data: { slug } };
* },
*
* // This method will cause a type error because the data object is missing
* // the required `slug` property.
* async POST(ctx) {
* return { data: { } };
* },
* });
* ```
*
* @typeParam Data The type of data that the handler returns. This will be inferred from the handler methods if not provided.
* @typeParam Handlers This will always be inferred from the input object. Do not manually specify this type.
*/
defineHandlers<
Data,
Handlers extends RouteHandler<Data, State> = RouteHandler<Data, State>,
>(
handlers: Handlers,
): typeof handlers;
/**
* Define a page component that will be rendered when a route handler returns
* data. This function returns the passed input as-is.
*
* You can use this function to help the TypeScript compiler infer the types
* of the data that your page component receives. For example:
*
* ```ts
* export default helpers.definePage((props) => {
* const slug = props.params.slug; // Because props is inferred to be a FreshContext object, slug is inferred to be a string
* return <h1>{slug}</h1>;
* });
* ```
*
* This is particularly useful when combined with the {@link defineHandlers}
* helper function, in which case the data type will be inferred from the
* return type of the handler method.
*
* ```ts
* export const handler = defineHandlers({
* async GET(ctx) {
* const slug = ctx.params.slug; // slug is inferred to be a string
* return { data: { slug } };
* },
* });
*
* export default definePage<typeof handler>(({ data }) => {
* const slug = data.slug; // slug is inferred to be a string here
* return <h1>{slug}</h1>;
* });
* ```
*
* As a rule of thumb, always use this function to define your page
* components. If you also have a handler for this route, pass the handler
* object as a type argument to this function. If you do not have a handler,
* omit the type argument.
*
* @typeParam Handler The type of the handler object that this page component is associated with. If this route has a handler, pass the handler object as a type argument to this function, e.g. `typeof handler`. If this route does not have a handler, omit this type argument.
* @typeParam Data The type of data that the page component receives. This will be inferred from the handler methods if not provided. In very advanced use cases, you can specify `never` to the `Handler` type argument and provide the `Data` type explicitly.
*/
definePage<
Handler extends RouteHandler<unknown, State> = never,
Data = Handler extends HandlerByMethod<infer Data, State> ? Data : never,
>(
render: AnyComponent<FreshContext<Data, State> & { Component: () => null }>,
): typeof render;
/**
* Define a {@link Middleware} that will be used to process requests before
* they are passed to the route handler. This function returns the passed
* input as-is.
*
* You can use this function to help the TypeScript compiler infer the types
* of the context object that your middleware receives. For example:
*
* ```ts
* export const middleware = helpers.defineMiddleware((ctx) => {
* ctx.url; // ctx is inferred to be a FreshContext object, so this is a URL
* return ctx.next();
* });
* ```
*
* You may also pass an array of middleware functions to this function.
*
* @typeParam M The type of the middleware function. This will be inferred from the input function. Do not manually specify this type.
*/
defineMiddleware<M extends Middleware<State>>(
middleware: M,
): typeof middleware;
}
/**
* Create a set of helper functions that enable better type inference and code
* completion when defining routes and middleware.
*
* To use, call this function in a central file and export the result. In your
* route and middleware files, import the {@link Helpers|helpers object} and use
* them to define your routes and middleware using the
* {@link Helpers.defineHandlers|defineHandlers},
* {@link Helpers.definePage|definePage}, and
* {@link Helpers.defineMiddleware|defineMiddleware} functions.
*
* @typeParam State The type of the state object that is passed to all middleware and route handlers.
*/
export function createHelpers<State>(): Helpers<State> {
return {
defineHandlers(handlers) {
return handlers;
},
definePage(render) {
return render;
},
defineMiddleware(middleware) {
return middleware;
},
};
}
+7
View File
@@ -0,0 +1,7 @@
export const UNDEFINED = -1;
export const NULL = -2;
export const NAN = -3;
export const INFINITY_POS = -4;
export const INFINITY_NEG = -5;
export const ZERO_NEG = -6;
export const HOLE = -7;
+54
View File
@@ -0,0 +1,54 @@
import { expect } from "@std/expect";
import { parse } from "./parse.ts";
import { stringify } from "./stringify.ts";
import { Signal, signal } from "@preact/signals";
Deno.test("custom parse - Point", () => {
class Point {
constructor(public x: number, public y: number) {
this.x = x;
this.y = y;
}
}
const str = stringify(new Point(30, 40), {
Point: (value) => value instanceof Point ? [value.x, value.y] : undefined,
});
expect(str).toEqual('[["Point",1],[2,3],30,40]');
const point = parse(str, {
Point: ([x, y]: [number, number]) => new Point(x, y),
});
expect(point).toEqual(new Point(30, 40));
});
Deno.test("custom parse - Signals", () => {
const res = parse<Signal>('[["Signal",1],2]', {
Signal: (value) => signal(value),
});
expect(res).toBeInstanceOf(Signal);
expect(res.peek()).toEqual(2);
});
Deno.test("custom stringify - Signals", () => {
const s = signal(2);
expect(stringify(s, {
Signal: (s2: unknown) => {
return s2 instanceof Signal ? s2.peek() : undefined;
},
})).toEqual(
'[["Signal",1],2]',
);
});
Deno.test("custom stringify - referenced Signals", () => {
const s = signal(2);
expect(stringify([s, s], {
Signal: (s2: unknown) => {
return s2 instanceof Signal ? s2.peek() : undefined;
},
})).toEqual(
'[[1,1],["Signal",2],2]',
);
});
+193
View File
@@ -0,0 +1,193 @@
import {
HOLE,
INFINITY_NEG,
INFINITY_POS,
NAN,
NULL,
UNDEFINED,
ZERO_NEG,
} from "./constants.ts";
// deno-lint-ignore no-explicit-any
export type CustomParser = Record<string, (value: any) => unknown>;
export function parse<T = unknown>(
value: string,
custom?: CustomParser | undefined,
): T {
const data = JSON.parse(value);
const hydrated = new Array(data.length);
// deno-lint-ignore no-explicit-any
unpack(data, hydrated, 0, custom) as any;
return hydrated[0];
}
function unpack(
arr: unknown[],
hydrated: unknown[],
idx: number,
custom: CustomParser | undefined,
): void {
if (idx in hydrated) return;
const current = arr[idx];
if (typeof current === "number") {
switch (current) {
case UNDEFINED:
hydrated[idx] = undefined;
return;
case NULL:
hydrated[idx] = null;
return;
case NAN:
hydrated[idx] = NaN;
return;
case INFINITY_POS:
hydrated[idx] = Infinity;
return;
case INFINITY_NEG:
hydrated[idx] = -Infinity;
return;
case ZERO_NEG:
hydrated[idx] = -0;
return;
default:
hydrated[idx] = current;
return;
}
} else if (
typeof current === "string" || typeof current === "boolean" ||
current === null
) {
hydrated[idx] = current;
return;
} else if (Array.isArray(current)) {
if (current.length > 0 && typeof current[0] === "string") {
const name = current[0];
if (custom !== undefined && name in custom) {
const fn = custom[name];
const ref = current[1];
unpack(arr, hydrated, ref, custom);
const value = hydrated[ref];
hydrated[idx] = fn(value);
return;
}
switch (name) {
case "BigInt":
hydrated[idx] = BigInt(current[1]);
return;
case "Date":
hydrated[idx] = new Date(current[1]);
return;
case "RegExp":
hydrated[idx] = new RegExp(current[1], current[2]);
return;
case "Set": {
const set = new Set();
for (let i = 0; i < current[1].length; i++) {
const ref = current[1][i];
unpack(arr, hydrated, ref, custom);
set.add(hydrated[ref]);
}
hydrated[idx] = set;
return;
}
case "Map": {
const set = new Map();
for (let i = 0; i < current[1].length; i++) {
const refKey = current[1][i++];
unpack(arr, hydrated, refKey, custom);
const refValue = current[1][i];
unpack(arr, hydrated, refValue, custom);
set.set(hydrated[refKey], hydrated[refValue]);
}
hydrated[idx] = set;
return;
}
case "Uint8Array":
hydrated[idx] = b64decode(current[1]);
return;
}
} else {
const actual = new Array(current.length);
hydrated[idx] = actual;
for (let i = 0; i < current.length; i++) {
const ref = current[i];
if (ref < 0) {
switch (ref) {
case UNDEFINED:
actual[i] = undefined;
break;
case NULL:
actual[i] = null;
break;
case NAN:
actual[i] = NaN;
break;
case INFINITY_POS:
actual[i] = Infinity;
break;
case INFINITY_NEG:
actual[i] = -Infinity;
break;
case ZERO_NEG:
actual[i] = -0;
break;
case HOLE:
continue;
}
} else {
unpack(arr, hydrated, ref, custom);
actual[i] = hydrated[ref];
}
}
}
} else if (typeof current === "object") {
const actual: Record<string, unknown> = {};
hydrated[idx] = actual;
const keys = Object.keys(current);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
// deno-lint-ignore no-explicit-any
const ref = (current as any)[key];
if (ref < 0) {
switch (ref) {
case UNDEFINED:
actual[key] = undefined;
break;
case NULL:
actual[key] = null;
break;
case NAN:
actual[key] = NaN;
break;
case INFINITY_POS:
actual[key] = Infinity;
break;
case INFINITY_NEG:
actual[key] = -Infinity;
break;
case ZERO_NEG:
actual[key] = -0;
break;
}
} else {
unpack(arr, hydrated, ref, custom);
actual[key] = hydrated[ref];
}
}
}
}
function b64decode(b64: string): Uint8Array {
const binString = atob(b64);
const size = binString.length;
const bytes = new Uint8Array(size);
for (let i = 0; i < size; i++) {
bytes[i] = binString.charCodeAt(i);
}
return bytes;
}
+99
View File
@@ -0,0 +1,99 @@
import { expect } from "@std/expect";
import { parse } from "./parse.ts";
Deno.test("parse - json", () => {
expect(parse("[2]")).toEqual(2);
expect(parse('["abc"]')).toEqual("abc");
expect(parse("[true]")).toEqual(true);
expect(parse("[false]")).toEqual(false);
expect(parse("[[1,2,3],1,2,3]")).toEqual([1, 2, 3]);
expect(parse('[{"a":1,"b":-2,"c":2},1,[-2]]')).toEqual({
a: 1,
b: null,
c: [null],
});
});
Deno.test("parse - hole array", () => {
expect(parse("[[1,-7,2],1,3]")).toEqual([1, , 3]);
});
Deno.test("parse - undefined", () => {
expect(parse("[-1]")).toEqual(undefined);
});
Deno.test("parse - Infinity", () => {
expect(parse("[-4]")).toEqual(Infinity);
expect(parse("[-5]")).toEqual(-Infinity);
});
Deno.test("parse - NaN", () => {
expect(parse("[-3]")).toEqual(NaN);
});
Deno.test("parse - -0", () => {
expect(parse("[-6]")).toEqual(-0);
});
Deno.test("parse - bigint", () => {
const n = BigInt(9007199254740991);
expect(parse('[["BigInt","9007199254740991"]]')).toEqual(
n,
);
});
Deno.test("parse - Set", () => {
const res = parse('[["Set",[1,2]],1,{"foo":1}]');
expect(res).toEqual(
new Set([1, { foo: 1 }]),
);
});
Deno.test("parse - Map", () => {
expect(parse('[["Map",[1,2,3,4]],1,{"foo":1},2,3]'))
.toEqual(
new Map<number, unknown>([[1, { foo: 1 }], [2, 3]]),
);
});
Deno.test("parse - Date", () => {
const date = new Date("1990-05-31");
expect(parse('[["Date","1990-05-31T00:00:00.000Z"]]')).toEqual(
date,
);
});
Deno.test("parse - RegExp", () => {
let reg = /foo["]/;
expect(parse('[["RegExp","foo[\\"]", ""]]')).toEqual(reg);
reg = /foo["]/g;
expect(parse('[["RegExp","foo[\\"]", "g"]]')).toEqual(reg);
});
Deno.test("parse - Uint8Array", () => {
const value = new Uint8Array([1, 2, 3]);
expect(parse('[["Uint8Array","AQID"]]')).toEqual(
value,
);
});
Deno.test("parse - references", () => {
const inner = { foo: 123 };
const obj = { a: inner, b: [inner, inner] };
const res = parse<typeof obj>('[{"a":1,"b":3},{"foo":2},123,[1,1]]');
expect(res).toEqual(obj);
expect(res.a).toEqual(res.b[0]);
expect(res.a).toEqual(res.b[1]);
});
Deno.test("parse - circular references", () => {
// deno-lint-ignore no-explicit-any
const foo = { foo: null as any };
foo.foo = foo;
expect(parse('[{"foo":0}]')).toEqual(foo);
});
Deno.test("parse - object", () => {
expect(parse('[{"foo":1},42]')).toEqual({ foo: 42 });
});
+186
View File
@@ -0,0 +1,186 @@
import {
INFINITY_NEG,
INFINITY_POS,
NAN,
NULL,
UNDEFINED,
ZERO_NEG,
} from "./constants.ts";
import { HOLE } from "./constants.ts";
// deno-lint-ignore no-explicit-any
export type Stringifiers = Record<string, (value: any) => any>;
/**
* Serializes the following:
*
* - `null`
* - `undefined`
* - `boolean`
* - `number`
* - `bigint`
* - `string`
* - `array`
* - `object` (no prototypes)
* - `Uint8Array`
* - `Date`
* - `RegExp`
* - `Set`
* - `Map`
*
* Circular references are supported and objects with the same reference are
* serialized only once.
*/
export function stringify(data: unknown, custom?: Stringifiers): string {
const out: string[] = [];
const indexes = new Map<unknown, number>();
const res = serializeInner(out, indexes, data, custom);
if (res < 0) {
out.push(String(res));
}
return `[${out.join(",")}]`;
}
function serializeInner(
out: string[],
indexes: Map<unknown, number>,
value: unknown,
custom: Stringifiers | undefined,
): number {
const seenIdx = indexes.get(value);
if (seenIdx !== undefined) return seenIdx;
if (value === undefined) return UNDEFINED;
if (value === null) return NULL;
if (Number.isNaN(value)) return NAN;
if (value === Infinity) return INFINITY_POS;
if (value === -Infinity) return INFINITY_NEG;
if (value === 0 && 1 / value < 0) return ZERO_NEG;
const idx = out.length;
out.push("");
indexes.set(value, idx);
let str = "";
if (typeof value === "number") {
str += String(value);
} else if (typeof value === "boolean") {
str += String(value);
} else if (typeof value === "bigint") {
str += `["BigInt","${value}"]`;
} else if (typeof value === "string") {
str += JSON.stringify(value);
} else if (Array.isArray(value)) {
str += "[";
for (let i = 0; i < value.length; i++) {
if (i in value) {
str += serializeInner(out, indexes, value[i], custom);
} else {
str += HOLE;
}
if (i < value.length - 1) {
str += ",";
}
}
str += "]";
} else if (typeof value === "object") {
if (custom !== undefined) {
for (const k in custom) {
const fn = custom[k];
if (fn === undefined) continue;
const res = fn(value);
if (res === undefined) continue;
serializeInner(out, indexes, res, custom);
str = `["${k}",${idx + 1}]`;
out[idx] = str;
return idx;
}
}
if (value instanceof Date) {
str += `["Date","${value.toISOString()}"]`;
} else if (value instanceof RegExp) {
str += `["RegExp",${JSON.stringify(value.source)}, "${value.flags}"]`;
} else if (value instanceof Uint8Array) {
str += `["Uint8Array","${b64encode(value)}"]`;
} else if (value instanceof Set) {
const items = new Array(value.size);
let i = 0;
value.forEach((v) => {
items[i++] = serializeInner(out, indexes, v, custom);
});
str += `["Set",[${items.join(",")}]]`;
} else if (value instanceof Map) {
const items = new Array(value.size * 2);
let i = 0;
value.forEach((v, k) => {
items[i++] = serializeInner(out, indexes, k, custom);
items[i++] = serializeInner(out, indexes, v, custom);
});
str += `["Map",[${items.join(",")}]]`;
} else {
str += "{";
const keys = Object.keys(value);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
str += JSON.stringify(key) + ":";
// deno-lint-ignore no-explicit-any
str += serializeInner(out, indexes, (value as any)[key], custom);
if (i < keys.length - 1) {
str += ",";
}
}
str += "}";
}
} else if (typeof value === "function") {
throw new Error(`Serializing functions is not supported.`);
}
out[idx] = str;
return idx;
}
// deno-fmt-ignore
const base64abc = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d",
"e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
"t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "+", "/",
];
/**
* CREDIT: https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727
* Encodes a given Uint8Array, ArrayBuffer or string into RFC4648 base64 representation
*/
export function b64encode(buffer: ArrayBuffer): string {
const uint8 = new Uint8Array(buffer);
let result = "",
i;
const l = uint8.length;
for (i = 2; i < l; i += 3) {
result += base64abc[uint8[i - 2] >> 2];
result += base64abc[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)];
result += base64abc[((uint8[i - 1] & 0x0f) << 2) | (uint8[i] >> 6)];
result += base64abc[uint8[i] & 0x3f];
}
if (i === l + 1) {
// 1 octet yet to write
result += base64abc[uint8[i - 2] >> 2];
result += base64abc[(uint8[i - 2] & 0x03) << 4];
result += "==";
}
if (i === l) {
// 2 octets yet to write
result += base64abc[uint8[i - 2] >> 2];
result += base64abc[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)];
result += base64abc[(uint8[i - 1] & 0x0f) << 2];
result += "=";
}
return result;
}
+109
View File
@@ -0,0 +1,109 @@
import { expect } from "@std/expect";
import { stringify } from "./stringify.ts";
Deno.test("stringify - json", () => {
expect(stringify(2)).toEqual("[2]");
expect(stringify("abc")).toEqual('["abc"]');
expect(stringify(true)).toEqual("[true]");
expect(stringify(false)).toEqual("[false]");
expect(stringify([1, 2, 3])).toEqual("[[1,2,3],1,2,3]");
expect(stringify({ a: 1, b: null, c: [null] })).toEqual(
'[{"a":1,"b":-2,"c":2},1,[-2]]',
);
});
Deno.test("stringify - hole array", () => {
expect(stringify([1, , 3])).toEqual("[[1,-7,2],1,3]");
});
Deno.test("stringify - undefined", () => {
expect(stringify(undefined)).toEqual("[-1]");
});
Deno.test("stringify - Infinity", () => {
expect(stringify(Infinity)).toEqual("[-4]");
expect(stringify(-Infinity)).toEqual("[-5]");
});
Deno.test("stringify - NaN", () => {
expect(stringify(NaN)).toEqual("[-3]");
});
Deno.test("stringify - -0", () => {
expect(stringify(-0)).toEqual("[-6]");
});
Deno.test("stringify - bigint", () => {
const n = BigInt(9007199254740991);
expect(stringify(n)).toEqual(
'[["BigInt","9007199254740991"]]',
);
});
Deno.test("stringify - Date", () => {
const date = new Date("1990-05-31");
expect(stringify(date)).toEqual(
'[["Date","1990-05-31T00:00:00.000Z"]]',
);
});
Deno.test("stringify - RegExp", () => {
let reg = /foo["]/;
expect(stringify(reg)).toEqual(
'[["RegExp","foo[\\"]", ""]]',
);
reg = /foo["]/g;
expect(stringify(reg)).toEqual(
'[["RegExp","foo[\\"]", "g"]]',
);
});
Deno.test("stringify - Set", () => {
expect(stringify(new Set([1, { foo: 1 }]))).toEqual(
'[["Set",[1,2]],1,{"foo":1}]',
);
});
Deno.test("stringify - Map", () => {
expect(stringify(new Map<number, unknown>([[1, { foo: 1 }], [2, 3]])))
.toEqual(
'[["Map",[1,2,3,4]],1,{"foo":1},2,3]',
);
});
Deno.test("stringify - Uint8Array", () => {
const value = new Uint8Array([1, 2, 3]);
expect(stringify(value)).toEqual(
'[["Uint8Array","AQID"]]',
);
});
Deno.test("stringify - references", () => {
const inner = { foo: 123 };
const obj = { a: inner, b: [inner, inner] };
expect(stringify(obj)).toEqual(
'[{"a":1,"b":3},{"foo":2},123,[1,1]]',
);
});
Deno.test("stringify - circular references", () => {
// deno-lint-ignore no-explicit-any
const foo = { foo: null as any };
foo.foo = foo;
expect(stringify(foo)).toEqual(
'[{"foo":0}]',
);
});
Deno.test("stringify - object prototype", () => {
const obj = { __proto__: 123, foo: 1 };
expect(stringify(obj)).toEqual(
'[{"foo":1},1]',
);
});
Deno.test("stringify - throw serializing functions", () => {
const fn = () => {};
expect(() => stringify(fn)).toThrow();
});
+107
View File
@@ -0,0 +1,107 @@
import type { FreshContext } from "../context.ts";
import type { App as _App } from "../app.ts";
/**
* A middleware function is the basic building block of Fresh. It allows you
* to respond to an incoming request in any way you want. You can redirect
* routes, serve files, create APIs and much more. Middlewares can be chained by
* calling {@linkcode FreshContext.next|ctx.next()} inside of the function.
*
* Middlewares can be synchronous or asynchronous. If a middleware returns a
* {@linkcode Response} object, the response will be sent back to the client. If
* a middleware returns a `Promise<Response>`, Fresh will wait for the promise
* to resolve before sending the response.
*
* A {@linkcode FreshContext} object is passed to the middleware function. This
* object contains the original request object, as well as any state related to
* the current request. The context object also contains methods to redirect
* the client to another URL, or to call the next middleware in the chain.
*
* Middlewares can be defined as a single function or an array of functions.
* When an array of middlewares is passed to
* {@linkcode _App.prototype.use|app.use}, Fresh will call each middleware in the
* order they are defined.
*
* Middlewares can also be defined using the
* {@linkcode _App.prototype.defineMiddleware|app.defineMiddleware} method. This
* method is optional, but it can be useful for type checking and code
* completion. It does not register the middleware with the app.
*
* ## Examples
*
* ### Logging middleware
*
* This example shows how to create a simple middleware that logs incoming
* requests.
*
* ```ts
* // Define a middleware function that logs incoming requests. Using the
* // `defineMiddleware` method is optional, but it can be useful for type
* // checking and code completion. It does not register the middleware with the
* // app.
* const loggerMiddleware = app.defineMiddleware((ctx) => {
* console.log(`${ctx.req.method} ${ctx.req.url}`);
* // Call the next middleware
* return ctx.next();
* });
*
* // To register the middleware to the app, use `app.use`.
* app.use(loggerMiddleware)
* ```
*
* ### Redirect middleware
*
* This example shows how to create a middleware that redirects requests from
* one URL to another.
*
* ```ts
* // Any request to a URL that starts with "/legacy/" will be redirected to
* // "/modern".
* const redirectMiddleware = app.defineMiddleware((ctx) => {
* if (ctx.url.pathname.startsWith("/legacy/")) {
* return ctx.redirect("/modern");
* }
*
* // Otherwise call the next middleware
* return ctx.next();
* });
*
* // Again, register the middleware with the app.
* app.use(redirectMiddleware);
* ```
*/
export type MiddlewareFn<State> = (
ctx: FreshContext<unknown, State>,
) => Response | Promise<Response>;
/**
* A single middleware function, or an array of middleware functions. For
* further information, see {@link MiddlewareFn}.
*/
export type Middleware<State> = MiddlewareFn<State> | MiddlewareFn<State>[];
export function runMiddlewares<State>(
middlewares: MiddlewareFn<State>[][],
ctx: FreshContext<unknown, State>,
): Promise<Response> {
let fn = ctx.next;
let i = middlewares.length;
while (i--) {
const stack = middlewares[i];
let j = stack.length;
while (j--) {
const local = fn;
const next = stack[j];
fn = async () => {
ctx.next = local;
try {
return await next(ctx);
} catch (err) {
ctx.error = err;
throw err;
}
};
}
}
return fn();
}
+136
View File
@@ -0,0 +1,136 @@
import { runMiddlewares } from "./mod.ts";
import { expect } from "@std/expect";
import { serveMiddleware } from "../test_utils.ts";
import type { MiddlewareFn } from "./mod.ts";
Deno.test("runMiddleware", async () => {
const middlewares: MiddlewareFn<{ text: string }>[] = [
(ctx) => {
ctx.state.text = "A";
return ctx.next();
},
(ctx) => {
ctx.state.text += "B";
return ctx.next();
},
async (ctx) => {
const res = await ctx.next();
ctx.state.text += "C"; // This should not show up
return res;
},
(ctx) => {
return new Response(ctx.state.text);
},
];
const server = serveMiddleware<{ text: string }>((ctx) =>
runMiddlewares([middlewares], ctx)
);
const res = await server.get("/");
expect(await res.text()).toEqual("AB");
});
Deno.test("runMiddleware - middlewares should only be called once", async () => {
const A: MiddlewareFn<{ count: number }> = (ctx) => {
if (ctx.state.count === undefined) {
ctx.state.count = 0;
} else {
ctx.state.count++;
}
return ctx.next();
};
const server = serveMiddleware<{ count: number }>((ctx) =>
runMiddlewares(
[[A, (ctx) => new Response(String(ctx.state.count))]],
ctx,
)
);
const res = await server.get("/");
expect(await res.text()).toEqual("0");
});
Deno.test("runMiddleware - runs multiple stacks", async () => {
type State = { text: string };
const A: MiddlewareFn<State> = (ctx) => {
ctx.state.text += "A";
return ctx.next();
};
const B: MiddlewareFn<State> = (ctx) => {
ctx.state.text += "B";
return ctx.next();
};
const C: MiddlewareFn<State> = (ctx) => {
ctx.state.text += "C";
return ctx.next();
};
const D: MiddlewareFn<State> = (ctx) => {
ctx.state.text += "D";
return ctx.next();
};
const server = serveMiddleware<State>((ctx) => {
ctx.state.text = "";
return runMiddlewares(
[
[A, B],
[C, D, (ctx) => new Response(String(ctx.state.text))],
],
ctx,
);
});
const res = await server.get("/");
expect(await res.text()).toEqual("ABCD");
});
Deno.test("runMiddleware - throws errors", async () => {
let thrownA: unknown = null;
let thrownB: unknown = null;
let thrownC: unknown = null;
const middlewares: MiddlewareFn<{ text: string }>[] = [
async (ctx) => {
try {
return await ctx.next();
} catch (err) {
thrownA = err;
throw err;
}
},
async (ctx) => {
try {
return await ctx.next();
} catch (err) {
thrownB = err;
throw err;
}
},
async (ctx) => {
try {
return await ctx.next();
} catch (err) {
thrownC = err;
throw err;
}
},
() => {
throw new Error("fail");
},
];
const server = serveMiddleware<{ text: string }>((ctx) =>
runMiddlewares([middlewares], ctx)
);
try {
await server.get("/");
} catch {
// ignore
}
expect(thrownA).toBeInstanceOf(Error);
expect(thrownB).toBeInstanceOf(Error);
expect(thrownC).toBeInstanceOf(Error);
});
+77
View File
@@ -0,0 +1,77 @@
import * as path from "@std/path";
import { contentType as getContentType } from "@std/media-types/content-type";
import type { MiddlewareFn } from "@fresh/core";
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
import { BUILD_ID } from "../runtime/build_id.ts";
import { getBuildCache } from "../context.ts";
/**
* Fresh middleware to enable file-system based routing.
* ```ts
* // Enable Fresh static file serving
* app.use(freshStaticFles());
* ```
*/
export function staticFiles<T>(): MiddlewareFn<T> {
return async function freshStaticFiles(ctx) {
const { req, url } = ctx;
const buildCache = getBuildCache(ctx);
// Fast path bail out
const file = await buildCache.readFile(url.pathname);
if (url.pathname === "/" || file === null) {
// Optimization: Prevent long responses for favicon.ico requests
if (url.pathname === "/favicon.ico") {
return new Response(null, { status: 404 });
}
return ctx.next();
}
if (req.method !== "GET" && req.method !== "HEAD") {
return new Response("Method Not Allowed", { status: 405 });
}
const cacheKey = url.searchParams.get(ASSET_CACHE_BUST_KEY);
if (cacheKey !== null && BUILD_ID !== cacheKey) {
url.searchParams.delete(ASSET_CACHE_BUST_KEY);
const location = url.pathname + url.search;
return new Response(null, {
status: 307,
headers: {
location,
},
});
}
const ext = path.extname(url.pathname);
const etag = file.hash;
const contentType = getContentType(ext);
const headers = new Headers({
"Content-Type": contentType ?? "text/plain",
vary: "If-None-Match",
});
if (cacheKey === null || ctx.config.mode === "development") {
headers.append(
"Cache-Control",
"no-cache, no-store, max-age=0, must-revalidate",
);
} else {
const ifNoneMatch = req.headers.get("If-None-Match");
if (
etag !== null &&
(ifNoneMatch === etag || ifNoneMatch === "W/" + etag)
) {
return new Response(null, { status: 304, headers });
}
}
headers.set("Content-Length", String(file.size));
if (req.method === "HEAD") {
return new Response(null, { status: 200, headers });
}
return new Response(file.readable, { headers });
};
}
+150
View File
@@ -0,0 +1,150 @@
import { staticFiles } from "./static_files.ts";
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";
class MockBuildCache implements BuildCache {
buildId = "MockId";
files = new Map<string, StaticFile>();
hasSnapshot = true;
constructor(files: Record<string, { hash: string | null; content: string }>) {
const encoder = new TextEncoder();
for (const [pathname, info] of Object.entries(files)) {
const text = encoder.encode(info.content);
const normalized = pathname.startsWith("/") ? pathname : "/" + pathname;
this.files.set(normalized, {
hash: info.hash,
size: text.byteLength,
readable: text,
});
}
}
// deno-lint-ignore require-await
async readFile(pathname: string): Promise<StaticFile | null> {
return this.files.get(pathname) ?? null;
}
getIslandChunkName(_islandName: string): string | null {
return null;
}
}
Deno.test("static files - 200", async () => {
const buildCache = new MockBuildCache({
"foo.css": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
{ buildCache },
);
const res = await server.get("/foo.css");
const content = await res.text();
expect(res.status).toEqual(200);
expect(res.headers.get("Content-Type")).toEqual("text/css; charset=UTF-8");
expect(res.headers.get("Content-Length")).toEqual("7");
expect(res.headers.get("Cache-Control")).toEqual(
"no-cache, no-store, max-age=0, must-revalidate",
);
expect(content).toEqual("body {}");
});
Deno.test("static files - HEAD 200", async () => {
const buildCache = new MockBuildCache({
"foo.css": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
{ buildCache },
);
const res = await server.head("/foo.css");
const content = await res.text();
expect(res.status).toEqual(200);
expect(res.headers.get("Content-Type")).toEqual("text/css; charset=UTF-8");
expect(res.headers.get("Content-Length")).toEqual("7");
expect(content).toEqual("");
});
Deno.test("static files - etag", async () => {
const buildCache = new MockBuildCache({
"foo.css": { content: "body {}", hash: "123" },
});
const server = serveMiddleware(
staticFiles(),
{ buildCache },
);
const headers = new Headers();
headers.append("If-None-Match", "123");
const cacheUrl = `/foo.css?${ASSET_CACHE_BUST_KEY}=${BUILD_ID}`;
const res = await server.get(cacheUrl, { headers });
await res.body?.cancel();
expect(res.status).toEqual(304);
const headers2 = new Headers();
headers2.append("If-None-Match", "W/123");
const res2 = await server.get(cacheUrl, { headers });
await res2.body?.cancel();
expect(res2.status).toEqual(304);
});
Deno.test("static files - 404 on missing favicon.ico", async () => {
const buildCache = new MockBuildCache({});
const server = serveMiddleware(
staticFiles(),
{ buildCache },
);
const res = await server.get("favicon.ico");
await res.body?.cancel();
expect(res.status).toEqual(404);
});
Deno.test("static files - 405 on wrong HTTP method", async () => {
const buildCache = new MockBuildCache({
"foo.css": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
{ buildCache },
);
for (const method of ["post", "patch", "put", "delete"]) {
// deno-lint-ignore no-explicit-any
const res = await (server as any)[method]("/foo.css");
await res.body?.cancel();
expect(res.status).toEqual(405);
}
});
Deno.test("static files - disables caching in development", async () => {
const buildCache = new MockBuildCache({
"foo.css": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
{
buildCache,
config: {
basePath: "",
build: {
outDir: "",
},
mode: "development",
root: ".",
staticDir: "",
},
},
);
const res = await server.get("/foo.css");
await res.body?.cancel();
expect(res.status).toEqual(200);
expect(res.headers.get("Cache-Control")).toEqual(
"no-cache, no-store, max-age=0, must-revalidate",
);
});
+29
View File
@@ -0,0 +1,29 @@
import type { MiddlewareFn } from "./mod.ts";
/**
* Fresh middleware to force URLs to end with a slash or never end with one.
*
* ```ts
* // Always add trailing slash
* app.use(trailingSlashes("always"));
* // Never add trailing slashes to URLs and remove them if present
* app.use(trailingSlashes("never"));
* ```
*/
export function trailingSlashes<State>(
mode: "always" | "never",
): MiddlewareFn<State> {
return function trailingSlashesMiddleware(ctx) {
const url = ctx.url;
if (url.pathname !== "/") {
if (mode === "always" && !url.pathname.endsWith("/")) {
return ctx.redirect(`${url.pathname}/${url.search}`);
} else if (
mode === "never" && url.pathname.endsWith("/")
) {
return ctx.redirect(`${url.pathname.slice(0, -1)}${url.search}`);
}
}
return ctx.next();
};
}
+55
View File
@@ -0,0 +1,55 @@
// deno-lint-ignore-file require-await
import { trailingSlashes } from "./trailing_slashes.ts";
import { expect } from "@std/expect";
import { serveMiddleware } from "../test_utils.ts";
Deno.test("trailingSlashes - always", async () => {
const middleware = trailingSlashes("always");
const server = serveMiddleware(async (ctx) => {
ctx.next = async () => new Response("ok");
return await middleware(ctx);
});
let res = await server.get("/");
await res.body?.cancel();
expect(res.status).toEqual(200);
expect(res.headers.get("Location")).toEqual(null);
res = await server.get("/foo");
await res.body?.cancel();
expect(res.status).toEqual(302);
expect(res.headers.get("Location")).toEqual("/foo/");
res = await server.get("/foo/bar");
await res.body?.cancel();
expect(res.status).toEqual(302);
expect(res.headers.get("Location")).toEqual("/foo/bar/");
res = await server.get("/foo/bar/");
await res.body?.cancel();
expect(res.status).toEqual(200);
expect(res.headers.get("Location")).toEqual(null);
});
Deno.test("trailingSlashes - never", async () => {
const middleware = trailingSlashes("never");
const server = serveMiddleware(async (ctx) => {
ctx.next = async () => new Response("ok");
return await middleware(ctx);
});
let res = await server.get("/");
await res.body?.cancel();
expect(res.status).toEqual(200);
expect(res.headers.get("Location")).toEqual(null);
res = await server.get("/foo");
await res.body?.cancel();
expect(res.status).toEqual(200);
expect(res.headers.get("Location")).toEqual(null);
res = await server.get("/foo/");
await res.body?.cancel();
expect(res.status).toEqual(302);
expect(res.headers.get("Location")).toEqual("/foo");
});
+33
View File
@@ -0,0 +1,33 @@
export { App, type ListenOptions, type RouteCacheEntry } from "./app.ts";
export { trailingSlashes } from "./middlewares/trailing_slashes.ts";
export { fsRoutes, type FsRoutesOptions } from "./plugins/fs_routes/mod.ts";
export {
type HandlerByMethod,
type HandlerFn,
type Render,
type RouteData,
type RouteHandler,
} from "./handlers.ts";
export { type RouteConfig } from "./types.ts";
export { type Middleware, type MiddlewareFn } from "./middlewares/mod.ts";
export { staticFiles } from "./middlewares/static_files.ts";
export { type Mode, type PageProps } from "./runtime/server/mod.tsx";
export { type FreshConfig, type ResolvedFreshConfig } from "./config.ts";
export { type FreshContext, type Island } from "./context.ts";
export { createHelpers, type Helpers } from "./helpers.ts";
export { type Method } from "./router.ts";
export { HttpError } from "./error.ts";
// Compat with older Fresh versions
export {
type AppProps,
defineApp,
defineLayout,
defineRoute,
type ErrorPageProps,
type Handlers,
type Handlers as Handler,
type LayoutProps,
type RouteContext,
type UnknownPageProps,
} from "./compat/server.ts";
+450
View File
@@ -0,0 +1,450 @@
import type { AnyComponent } from "preact";
import type { App } from "../../app.ts";
import type { WalkEntry } from "@std/fs/walk";
import * as path from "@std/path";
import type { RouteConfig } from "../../types.ts";
import type { RouteHandler } from "../../handlers.ts";
import type { FreshContext } from "../../context.ts";
import type { MiddlewareFn } from "../../middlewares/mod.ts";
import {
type AsyncAnyComponent,
renderMiddleware,
} from "./render_middleware.ts";
import { type Method, pathToPattern } from "../../router.ts";
import { type HandlerFn, isHandlerByMethod } from "../../handlers.ts";
import { type FsAdapter, fsAdapter } from "../../fs.ts";
import type { PageProps } from "../../runtime/server/mod.tsx";
import { HttpError } from "../../error.ts";
import { parseRootPath } from "../../config.ts";
const TEST_FILE_PATTERN = /[._]test\.(?:[tj]sx?|[mc][tj]s)$/;
const GROUP_REG = /(^|[/\\\\])\((_[^/\\\\]+)\)[/\\\\]/;
interface InternalRoute<State> {
path: string;
base: string;
filePath: string;
config: RouteConfig | null;
handlers: RouteHandler<unknown, State> | null;
component: AnyComponent<PageProps<unknown, State>> | null;
}
export interface FreshFsItem<State> {
config?: RouteConfig;
handler?: RouteHandler<unknown, State> | HandlerFn<unknown, State>[];
handlers?: RouteHandler<unknown, State>;
default?:
| AnyComponent<
PageProps<unknown, State> & Pick<FreshContext<unknown, State>, "redirect">
>
| AsyncAnyComponent<
PageProps<unknown, State> & Pick<FreshContext<unknown, State>, "redirect">
>;
}
// deno-lint-ignore no-explicit-any
function isFreshFile<State>(mod: any): mod is FreshFsItem<State> {
return mod !== null && typeof mod === "object" &&
typeof mod.default === "function" ||
typeof mod.config === "object" || typeof mod.handlers === "object" ||
typeof mod.handlers === "function" || typeof mod.handler === "object" ||
typeof mod.handler === "function";
}
export interface FsRoutesOptions {
dir?: string;
ignoreFilePattern?: RegExp[];
loadRoute: (path: string) => Promise<unknown>;
loadIsland: (path: string) => Promise<unknown>;
}
export interface TESTING_ONLY__FsRoutesOptions {
_fs?: FsAdapter;
}
export async function fsRoutes<State>(
app: App<State>,
options_: FsRoutesOptions,
) {
const options = options_ as FsRoutesOptions & TESTING_ONLY__FsRoutesOptions;
const ignore = options.ignoreFilePattern ?? [TEST_FILE_PATTERN];
const fs = options._fs ?? fsAdapter;
const dir = options.dir ? parseRootPath(options.dir) : app.config.root;
const islandDir = path.join(dir, "islands");
const routesDir = path.join(dir, "routes");
const islandPaths: string[] = [];
const relRoutePaths: string[] = [];
// Walk routes folder
await Promise.all([
walkDir(
islandDir,
(entry) => {
islandPaths.push(entry.path);
},
ignore,
fs,
),
walkDir(
routesDir,
(entry) => {
const relative = path.relative(routesDir, entry.path);
// A `(_islands)` path segment is a local island folder.
// Any route path segment wrapped in `(_...)` is ignored
// during route collection.
const match = relative.match(GROUP_REG);
if (match && match[2][0] === "_") {
if (match[2] === "_islands") {
islandPaths.push(entry.path);
}
return;
}
const url = new URL(relative, "http://localhost/");
relRoutePaths.push(url.pathname.slice(1));
},
ignore,
fs,
),
]);
await Promise.all(islandPaths.map(async (islandPath) => {
const relative = path.relative(islandDir, islandPath);
// deno-lint-ignore no-explicit-any
const mod = await options.loadIsland(relative) as any;
for (const key of Object.keys(mod)) {
const maybeFn = mod[key];
if (typeof maybeFn === "function") {
app.island(islandPath, key, maybeFn);
}
}
}));
const routeModules: InternalRoute<State>[] = await Promise.all(
relRoutePaths.map(async (routePath) => {
const mod = await options.loadRoute(routePath);
if (!isFreshFile(mod)) {
throw new Error(
`Expected a route, middleware, layout or error template, but couldn't find relevant exports in: ${routePath}`,
);
}
const handlers = mod.handlers ?? mod.handler ?? null;
if (typeof handlers === "function" && handlers.length > 1) {
throw new Error(
`Handlers must only have one argument but found more than one. Check the function signature in: ${
path.join(routesDir, routePath)
}`,
);
}
const normalizedPath = `/${
routePath.slice(0, routePath.lastIndexOf("."))
}`;
const base = normalizedPath.slice(0, normalizedPath.lastIndexOf("/"));
return {
path: normalizedPath,
filePath: routePath,
base,
handlers: mod.handlers ?? mod.handler ?? null,
config: mod.config ?? null,
component: mod.default ?? null,
} as InternalRoute<State>;
}),
);
routeModules.sort((a, b) => sortRoutePaths(a.path, b.path));
const stack: InternalRoute<State>[] = [];
let hasApp = false;
for (let i = 0; i < routeModules.length; i++) {
const routeMod = routeModules[i];
const normalized = routeMod.path;
let j = stack.length - 1;
while (
j >= 0 && stack[j].base !== "" &&
!routeMod.path.startsWith(stack[j].base + "/")
) {
j--;
stack.pop();
}
if (normalized.endsWith("/_app")) {
hasApp = true;
stack.push(routeMod);
continue;
} else if (normalized.endsWith("/_middleware")) {
stack.push(routeMod);
continue;
} else if (normalized.endsWith("/_layout")) {
stack.push(routeMod);
continue;
} else if (normalized.endsWith("/_error")) {
stack.push(routeMod);
continue;
} else if (normalized.endsWith("/_404")) {
stack.push(routeMod);
continue;
} else if (normalized.endsWith("/_500")) {
stack.push(routeMod);
continue;
}
// Remove any elements not matching our parent path anymore
const middlewares: MiddlewareFn<State>[] = [];
let components: AnyComponent<PageProps<unknown, State>>[] = [];
let skipApp = !!routeMod.config?.skipAppWrapper;
const skipLayouts = !!routeMod.config?.skipInheritedLayouts;
for (let k = 0; k < stack.length; k++) {
const mod = stack[k];
if (mod.path.endsWith("/_middleware")) {
if (mod.handlers !== null && !isHandlerByMethod(mod.handlers)) {
middlewares.push(mod.handlers as MiddlewareFn<State>);
} else if (Array.isArray(mod.handlers)) {
middlewares.push(...mod.handlers);
}
}
// _app template
if (skipApp && mod.path === "/_app") {
hasApp = false;
continue;
} else if (!skipApp && mod.config?.skipAppWrapper) {
skipApp = true;
if (hasApp) {
hasApp = false;
// _app component is always first
components.shift();
}
}
// _layouts
if (skipLayouts && mod.path.endsWith("/_layout")) {
continue;
} else if (!skipLayouts && mod.config?.skipInheritedLayouts) {
const first = components.length > 0 ? components[0] : null;
components = [];
if (!skipApp && hasApp && first !== null) {
components.push(first);
}
}
if (mod.path.endsWith("/_error") || mod.path.endsWith("/_500")) {
const handlers = mod.handlers;
const handler = handlers === null ||
(isHandlerByMethod(handlers) && Object.keys(handlers).length === 0)
? undefined
: typeof handlers === "function"
? handlers
: undefined; // FIXME: Method handler
const errorComponents = components.slice();
if (mod.component !== null) {
errorComponents.push(mod.component);
}
let parent = mod.path.slice(0, -"_error".length);
parent = parent === "/" ? "*" : parent + "*";
app.all(
parent,
errorMiddleware(errorComponents, handler),
);
middlewares.push(errorMiddleware(errorComponents, handler));
continue;
}
if (mod.path.endsWith("/_404")) {
const handlers = mod.handlers;
const handler = handlers === null ||
(isHandlerByMethod(handlers) && Object.keys(handlers).length === 0)
? undefined
: typeof handlers === "function"
? handlers
: undefined; // FIXME: Method handler
const notFoundComponents = components.slice();
if (mod.component !== null) {
notFoundComponents.push(mod.component);
}
app.use(notFoundMiddleware(notFoundComponents, handler));
continue;
}
if (mod.component !== null) {
components.push(mod.component);
}
}
if (routeMod.component !== null) {
components.push(routeMod.component);
}
const handlers = routeMod.handlers;
const routePath = routeMod.config?.routeOverride ??
pathToPattern(normalized.slice(1));
if (
handlers === null ||
(isHandlerByMethod(handlers) && Object.keys(handlers).length === 0)
) {
const combined = middlewares.concat(
renderMiddleware(components, undefined),
);
app.get(routePath, ...combined);
} else if (isHandlerByMethod(handlers)) {
for (const method of Object.keys(handlers) as Method[]) {
const fn = handlers[method];
if (fn !== undefined) {
const combined = middlewares.concat(renderMiddleware(components, fn));
const lower = method.toLowerCase() as Lowercase<Method>;
app[lower](routePath, ...combined);
}
}
} else if (typeof handlers === "function") {
const combined = middlewares.concat(
renderMiddleware(components, handlers),
);
app.all(routePath, ...combined);
}
}
}
function errorMiddleware<State>(
components: AnyComponent<PageProps<unknown, State>>[],
handler: HandlerFn<unknown, State> | undefined,
): MiddlewareFn<State> {
const mid = renderMiddleware<State>(components, handler);
return async function errorMiddleware(ctx) {
try {
return await ctx.next();
} catch (err) {
ctx.error = err;
return mid(ctx);
}
};
}
function notFoundMiddleware<State>(
components: AnyComponent<PageProps<unknown, State>>[],
handler: HandlerFn<unknown, State> | undefined,
): MiddlewareFn<State> {
const mid = renderMiddleware<State>(components, handler);
return async function notFoundMiddleware(ctx) {
try {
return await ctx.next();
} catch (err) {
if (err instanceof HttpError && err.status === 404) {
return mid(ctx);
}
throw err;
}
};
}
async function walkDir(
dir: string,
callback: (entry: WalkEntry) => void,
ignore: RegExp[],
fs: FsAdapter,
) {
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);
}
}
const APP_REG = /_app(?!\.[tj]sx?)?$/;
/**
* Sort route paths where special Fresh files like `_app`,
* `_layout` and `_middleware` are sorted in front.
*/
export function sortRoutePaths(a: string, b: string) {
// The `_app` route should always be the first
if (APP_REG.test(a)) return -1;
else if (APP_REG.test(b)) return 1;
let segmentIdx = 0;
const aLen = a.length;
const bLen = b.length;
const maxLen = aLen > bLen ? aLen : bLen;
for (let i = 0; i < maxLen; i++) {
const charA = a.charAt(i);
const charB = b.charAt(i);
if (charA === "/" || charB === "/") {
segmentIdx = i;
// If the other path doesn't close the segment
// then we don't need to continue
if (charA !== "/") return 1;
if (charB !== "/") return -1;
continue;
}
if (i === segmentIdx + 1) {
const scoreA = getRoutePathScore(charA, a, i);
const scoreB = getRoutePathScore(charB, b, i);
if (scoreA === scoreB) {
if (charA !== charB) {
// TODO: Do we need localeSort here or is this good enough?
return charA < charB ? 0 : 1;
}
continue;
}
return scoreA > scoreB ? -1 : 1;
}
if (charA !== charB) {
// TODO: Do we need localeSort here or is this good enough?
return charA < charB ? 0 : 1;
}
}
return 0;
}
/**
* Assign a score based on the first two characters of a path segment.
* The goal is to sort `_middleware` and `_layout` in front of everything
* and `[` or `[...` last respectively.
*/
function getRoutePathScore(char: string, s: string, i: number): number {
if (char === "_") {
if (i + 1 < s.length) {
if (s[i + 1] === "e") return 6;
if (s[i + 1] === "m") return 5;
}
return 4;
} else if (char === "[") {
if (i + 1 < s.length && s[i + 1] === ".") {
return 0;
}
return 1;
}
if (
i + 4 === s.length - 1 && char === "i" && s[i + 1] === "n" &&
s[i + 2] === "d" && s[i + 3] === "e" && s[i + 4] === "x"
) {
return 3;
}
return 2;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,74 @@
import { type AnyComponent, h, type RenderableProps, type VNode } from "preact";
import type { MiddlewareFn } from "../../middlewares/mod.ts";
import type { HandlerFn, Render } from "../../handlers.ts";
import type { PageProps } from "../../runtime/server/mod.tsx";
export type AsyncAnyComponent<P> = {
(
props: RenderableProps<P>,
// deno-lint-ignore no-explicit-any
context?: any,
// deno-lint-ignore no-explicit-any
): Promise<VNode<any> | Response | null>;
displayName?: string;
defaultProps?: Partial<P> | undefined;
};
export function renderMiddleware<State>(
components: Array<
| AnyComponent<PageProps<unknown, State>>
| AsyncAnyComponent<PageProps<unknown, State>>
>,
handler: HandlerFn<unknown, State> | undefined,
): MiddlewareFn<State> {
return async (ctx) => {
let result: Render<unknown> | undefined;
if (handler !== undefined) {
const res = await handler(ctx);
if (res instanceof Response) {
return res;
}
// deno-lint-ignore no-explicit-any
result = res as any;
}
if (components.length === 0) {
throw new Error(`Did not receive any components to render.`);
}
let vnode: VNode | null = null;
for (let i = components.length - 1; i >= 0; i--) {
const child = vnode;
const Component = () => child;
const fn = components[i];
if (
typeof fn === "function" &&
fn.constructor.name === "AsyncFunction"
) {
const result = (await fn({ ...ctx, Component })) as VNode | Response;
if (result instanceof Response) {
return result;
}
vnode = result;
} else {
// deno-lint-ignore no-explicit-any
vnode = h(components[i] as any, {
config: ctx.config,
url: ctx.url,
req: ctx.req,
params: ctx.params,
state: ctx.state,
Component,
error: ctx.error,
data: result?.data ?? {},
}) as VNode;
}
}
return ctx.render(vnode!);
};
}
@@ -0,0 +1,125 @@
import { expect } from "@std/expect";
import { delay, serveMiddleware } from "../../test_utils.ts";
import { renderMiddleware } from "./render_middleware.ts";
import { parseHtml } from "../../../tests/test_utils.tsx";
Deno.test("renderMiddleware - responds with HTML", async () => {
const server = await serveMiddleware(
renderMiddleware([() => <p>ok</p>], undefined),
);
const res = await server.get("/");
expect(res.headers.get("Content-Type")).toEqual("text/html; charset=utf-8");
const doc = parseHtml(await res.text());
// deno-lint-ignore no-explicit-any
expect((doc.body.firstChild as any).outerHTML).toEqual("<p>ok</p>");
});
Deno.test("renderMiddleware - bypass rendering when handler returns Response", async () => {
const server = await serveMiddleware(
renderMiddleware(
[() => <p>fail</p>],
() => new Response(null, { status: 204 }),
),
);
const res = await server.get("/");
expect(res.status).toEqual(204);
expect(res.body).toEqual(null);
});
Deno.test("renderMiddleware - chain components", async () => {
const server = await serveMiddleware(
renderMiddleware(
[
(ctx) => (
<div>
c1<ctx.Component />
</div>
),
(ctx) => (
<>
c2<ctx.Component />
</>
),
() => <>c3</>,
],
undefined,
),
);
const res = await server.get("/");
expect(res.status).toEqual(200);
const doc = parseHtml(await res.text());
expect(doc.body.firstChild?.textContent).toEqual("c1c2c3");
});
Deno.test("renderMiddleware - chain async components", async () => {
const server = await serveMiddleware(
renderMiddleware(
[
async (ctx) => {
await delay(1);
return (
<div>
c1<ctx.Component />
</div>
);
},
async (ctx) => {
await delay(1);
return (
<>
c2<ctx.Component />
</>
);
},
async () => {
await delay(1);
return <>c3</>;
},
],
undefined,
),
);
const res = await server.get("/");
expect(res.status).toEqual(200);
const doc = parseHtml(await res.text());
expect(doc.body.firstChild!.textContent).toEqual("c1c2c3");
});
Deno.test("renderMiddleware - async components Response bail out", async () => {
const server = await serveMiddleware(
renderMiddleware(
[
async (ctx) => {
await delay(1);
return (
<div>
c1<ctx.Component />
</div>
);
},
async (ctx) => {
await delay(1);
return new Response("foo");
},
async () => {
await delay(1);
return <>c3</>;
},
],
undefined,
),
);
const res = await server.get("/");
expect(res.status).toEqual(200);
expect(await res.text()).toEqual("foo");
});
+231
View File
@@ -0,0 +1,231 @@
export type Method = "HEAD" | "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
export interface Route<T> {
path: string | URLPattern;
method: Method | "ALL";
handlers: T[];
}
export interface RouteResult<T> {
params: Record<string, string>;
handlers: T[][];
methodMatch: boolean;
patternMatch: boolean;
}
export interface Router<T> {
_routes: Route<T>[];
_middlewares: T[];
addMiddleware(fn: T): void;
add(
method: Method | "ALL",
pathname: string | URLPattern,
handlers: T[],
): void;
match(method: Method, url: URL): RouteResult<T>;
}
export const IS_PATTERN = /[*:{}+?()]/;
export function mergePaths(a: string, b: string) {
if (a === "" || a === "/" || a === "*") return b;
if (b === "/") return a;
if (a.endsWith("/")) {
return a.slice(0, -1) + b;
} else if (!b.startsWith("/")) {
return a + "/" + b;
}
return a + b;
}
export class UrlPatternRouter<T> implements Router<T> {
readonly _routes: Route<T>[] = [];
readonly _middlewares: T[] = [];
addMiddleware(fn: T): void {
this._middlewares.push(fn);
}
add(method: Method | "ALL", pathname: string | URLPattern, handlers: T[]) {
if (
typeof pathname === "string" && pathname !== "*" &&
IS_PATTERN.test(pathname)
) {
this._routes.push({
path: new URLPattern({ pathname }),
handlers,
method,
});
} else {
this._routes.push({
path: pathname,
handlers,
method,
});
}
}
match(method: Method, url: URL): RouteResult<T> {
const result: RouteResult<T> = {
params: {},
handlers: [],
methodMatch: false,
patternMatch: false,
};
if (this._middlewares.length > 0) {
result.handlers.push(this._middlewares);
}
for (let i = 0; i < this._routes.length; i++) {
const route = this._routes[i];
// Fast path for string based routes which are expected
// to be either wildcard `*` match or an exact pathname match.
if (
typeof route.path === "string" &&
(route.path === "*" || route.path === url.pathname)
) {
if (route.method !== "ALL") {
result.patternMatch = true;
}
if (route.method === "ALL" || route.method === method) {
result.handlers.push(route.handlers);
if (route.path === "*" && route.method === "ALL") {
continue;
}
result.methodMatch = true;
return result;
}
} else if (route.path instanceof URLPattern) {
const match = route.path.exec(url);
if (match !== null) {
if (route.method !== "ALL") {
result.patternMatch = true;
}
if (route.method === "ALL" || route.method === method) {
result.handlers.push(route.handlers);
// Decode matched params
for (const [key, value] of Object.entries(match.pathname.groups)) {
if (value !== undefined) {
result.params[key] = decodeURI(value);
}
}
if (route.method === "ALL") {
continue;
}
result.methodMatch = true;
return result;
}
}
}
}
return result;
}
}
/**
* Transform a filesystem URL path to a `path-to-regex` style matcher.
*/
export function pathToPattern(path: string): string {
const parts = path.split("/");
if (parts[parts.length - 1] === "index") {
if (parts.length === 1) {
return "/";
}
parts.pop();
}
let route = "";
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
// Case: /[...foo].tsx
if (part.startsWith("[...") && part.endsWith("]")) {
route += `/:${part.slice(4, part.length - 1)}*`;
continue;
}
// Route groups like /foo/(bar) should not be included in URL
// matching. They are transparent and need to be removed here.
// Case: /foo/(bar) -> /foo
// Case: /foo/(bar)/bob -> /foo/bob
// Case: /(foo)/bar -> /bar
if (part.startsWith("(") && part.endsWith(")")) {
continue;
}
// Disallow neighbouring params like `/[id][bar].tsx` because
// it's ambiguous where the `id` param ends and `bar` begins.
if (part.includes("][")) {
throw new SyntaxError(
`Invalid route pattern: "${path}". A parameter cannot be followed by another parameter without any characters in between.`,
);
}
// Case: /[[id]].tsx
// Case: /[id].tsx
// Case: /[id]@[bar].tsx
// Case: /[id]-asdf.tsx
// Case: /[id]-asdf[bar].tsx
// Case: /asdf[bar].tsx
let pattern = "";
let groupOpen = 0;
let optional = false;
for (let j = 0; j < part.length; j++) {
const char = part[j];
if (char === "[") {
if (part[j + 1] === "[") {
// Disallow optional dynamic params like `foo-[[bar]]`
if (part[j - 1] !== "/" && !!part[j - 1]) {
throw new SyntaxError(
`Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`,
);
}
groupOpen++;
optional = true;
pattern += "{/";
j++;
}
pattern += ":";
groupOpen++;
} else if (char === "]") {
if (part[j + 1] === "]") {
// Disallow optional dynamic params like `[[foo]]-bar`
if (part[j + 2] !== "/" && !!part[j + 2]) {
throw new SyntaxError(
`Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`,
);
}
groupOpen--;
pattern += "}?";
j++;
}
if (--groupOpen < 0) {
throw new SyntaxError(`Invalid route pattern: "${path}"`);
}
} else {
pattern += char;
}
}
route += (optional ? "" : "/") + pattern;
}
// Case: /(group)/index.tsx
if (route === "") {
route = "/";
}
return route;
}
+180
View File
@@ -0,0 +1,180 @@
import { expect } from "@std/expect";
import {
IS_PATTERN,
mergePaths,
pathToPattern,
UrlPatternRouter,
} from "./router.ts";
Deno.test("IS_PATTERN", () => {
expect(IS_PATTERN.test("/foo")).toEqual(false);
expect(IS_PATTERN.test("/foo/bar/baz.jpg")).toEqual(false);
expect(IS_PATTERN.test("/foo/:path")).toEqual(true);
expect(IS_PATTERN.test("/foo/*")).toEqual(true);
expect(IS_PATTERN.test("/foo{/bar}?")).toEqual(true);
expect(IS_PATTERN.test("/foo/(\\d+)")).toEqual(true);
expect(IS_PATTERN.test("/foo/(a)")).toEqual(true);
});
Deno.test("UrlPatternRouter - GET get first match", () => {
const router = new UrlPatternRouter();
const A = () => {};
const B = () => {};
const C = () => {};
router.add("GET", "/", [A]);
router.add("GET", "/", [B]);
router.add("GET", "/", [C]);
const res = router.match("GET", new URL("/", "http://localhost"));
expect(res).toEqual({
params: {},
handlers: [[A]],
methodMatch: true,
patternMatch: true,
});
});
Deno.test("UrlPatternRouter - GET get matches with middlewares", () => {
const router = new UrlPatternRouter();
const A = () => {};
const B = () => {};
const C = () => {};
router.add("ALL", "*", [A]);
router.add("ALL", "*", [B]);
router.add("GET", "/", [C]);
const res = router.match("GET", new URL("/", "http://localhost"));
expect(res).toEqual({
params: {},
handlers: [[A], [B], [C]],
methodMatch: true,
patternMatch: true,
});
});
Deno.test("UrlPatternRouter - GET extract params", () => {
const router = new UrlPatternRouter();
const A = () => {};
router.add("GET", new URLPattern({ pathname: "/:foo/:bar/c" }), [A]);
let res = router.match("GET", new URL("/a/b/c", "http://localhost"));
expect(res).toEqual({
params: { foo: "a", bar: "b" },
handlers: [[A]],
methodMatch: true,
patternMatch: true,
});
// Decode params
res = router.match("GET", new URL("/a%20a/b/c", "http://localhost"));
expect(res).toEqual({
params: { foo: "a a", bar: "b" },
handlers: [[A]],
methodMatch: true,
patternMatch: true,
});
});
Deno.test("UrlPatternRouter - Wrong method match", () => {
const router = new UrlPatternRouter();
const A = () => {};
router.add("GET", "/foo", [A]);
const res = router.match("POST", new URL("/foo", "http://localhost"));
expect(res).toEqual({
params: {},
handlers: [],
methodMatch: false,
patternMatch: true,
});
});
Deno.test("UrlPatternRouter - wrong + correct method", () => {
const router = new UrlPatternRouter();
const A = () => {};
const B = () => {};
router.add("GET", "/foo", [A]);
router.add("POST", "/foo", [B]);
const res = router.match("POST", new URL("/foo", "http://localhost"));
expect(res).toEqual({
params: {},
handlers: [[B]],
methodMatch: true,
patternMatch: true,
});
});
Deno.test("UrlPatternRouter - convert patterns automatically", () => {
const router = new UrlPatternRouter();
const A = () => {};
router.add("GET", "/books/:id", [A]);
const res = router.match("GET", new URL("/books/foo", "http://localhost"));
expect(res).toEqual({
params: {
id: "foo",
},
handlers: [[A]],
methodMatch: true,
patternMatch: true,
});
});
Deno.test("pathToPattern", async (t) => {
await t.step("creates pattern", () => {
expect(pathToPattern("foo/bar")).toEqual("/foo/bar");
});
await t.step("parses index routes", () => {
expect(pathToPattern("foo/index")).toEqual("/foo");
});
await t.step("parses parameters", () => {
expect(pathToPattern("foo/[name]")).toEqual("/foo/:name");
expect(pathToPattern("foo/[name]/bar/[bob]")).toEqual(
"/foo/:name/bar/:bob",
);
});
await t.step("parses catchall", () => {
expect(pathToPattern("foo/[...name]")).toEqual("/foo/:name*");
});
await t.step("parses multiple params in same part", () => {
expect(pathToPattern("foo/[mod]@[version]")).toEqual("/foo/:mod@:version");
expect(pathToPattern("foo/[bar].json")).toEqual("/foo/:bar.json");
expect(pathToPattern("foo/foo[bar]")).toEqual("/foo/foo:bar");
});
await t.step("parses optional params", () => {
expect(pathToPattern("foo/[[name]]")).toEqual("/foo{/:name}?");
expect(pathToPattern("foo/[name]/[[bob]]")).toEqual("/foo/:name{/:bob}?");
expect(pathToPattern("foo/[[name]]/bar")).toEqual("/foo{/:name}?/bar");
expect(
pathToPattern("foo/[[name]]/bar/[[bob]]"),
).toEqual(
"/foo{/:name}?/bar{/:bob}?",
);
});
await t.step("throws on invalid patterns", () => {
expect(() => pathToPattern("foo/[foo][bar]")).toThrow();
expect(() => pathToPattern("foo/foo]")).toThrow();
expect(() => pathToPattern("foo/[foo]]")).toThrow();
expect(() => pathToPattern("foo/foo-[[name]]-bar/baz")).toThrow();
expect(() => pathToPattern("foo/[[name]]-bar/baz")).toThrow();
expect(() => pathToPattern("foo/foo-[[name]]/baz")).toThrow();
expect(() => pathToPattern("foo/foo-[[name]]")).toThrow();
expect(() => pathToPattern("foo/[[name]]-bar")).toThrow();
});
});
Deno.test("mergePaths", () => {
expect(mergePaths("", "")).toEqual("");
expect(mergePaths("/", "/foo")).toEqual("/foo");
expect(mergePaths("*", "/foo")).toEqual("/foo");
expect(mergePaths("/foo/bar", "/baz")).toEqual("/foo/bar/baz");
expect(mergePaths("/foo/bar/", "/baz")).toEqual("/foo/bar/baz");
expect(mergePaths("/foo/bar", "baz")).toEqual("/foo/bar/baz");
});
-20
View File
@@ -1,20 +0,0 @@
import { ComponentChildren, VNode } from "preact";
export interface PartialProps {
children?: ComponentChildren;
/**
* The name of the partial. This value must be unique across partials.
*/
name: string;
/**
* Define how the new HTML should be applied.
* @default {"replace"}
*/
mode?: "replace" | "prepend" | "append";
}
export function Partial(props: PartialProps): VNode {
// deno-lint-ignore no-explicit-any
return props.children as any;
}
Partial.displayName = "Partial";
-46
View File
@@ -1,46 +0,0 @@
import { VNode } from "preact";
import { DATA_ANCESTOR, DATA_CURRENT } from "../constants.ts";
export const enum UrlMatchKind {
None,
Ancestor,
Current,
}
export function matchesUrl(current: string, needle: string): UrlMatchKind {
let href = new URL(needle, "http://localhost").pathname;
if (href !== "/" && href.endsWith("/")) {
href = href.slice(0, -1);
}
if (current !== "/" && current.endsWith("/")) {
current = current.slice(0, -1);
}
if (current === href) {
return UrlMatchKind.Current;
} else if (current.startsWith(href + "/") || href === "/") {
return UrlMatchKind.Ancestor;
}
return UrlMatchKind.None;
}
/**
* Mark active or ancestor link
* Note: This function is used both on the server and the client
*/
export function setActiveUrl(vnode: VNode, pathname: string): void {
const props = vnode.props as Record<string, unknown>;
const hrefProp = props.href;
if (typeof hrefProp === "string" && hrefProp.startsWith("/")) {
const match = matchesUrl(pathname, hrefProp);
if (match === UrlMatchKind.Current) {
props[DATA_CURRENT] = "true";
props["aria-current"] = "page";
} else if (match === UrlMatchKind.Ancestor) {
props[DATA_ANCESTOR] = "true";
props["aria-current"] = "true";
}
}
}
+17 -2
View File
@@ -1,2 +1,17 @@
// Note: in the client build this file is replaced with a file exporting a static string
export { BUILD_ID } from "../server/build_id.ts";
import { encodeHex } from "@std/encoding/hex";
export const DENO_DEPLOYMENT_ID = Deno.env.get("DENO_DEPLOYMENT_ID");
const deploymentId = DENO_DEPLOYMENT_ID ||
// For CI
Deno.env.get("GITHUB_SHA") ||
crypto.randomUUID();
const buildIdHash = await crypto.subtle.digest(
"SHA-1",
new TextEncoder().encode(deploymentId),
);
export let BUILD_ID = encodeHex(buildIdHash);
export function setBuildId(buildId: string) {
BUILD_ID = buildId;
}
@@ -1,3 +1,7 @@
import "preact/debug";
export * from "./mod.tsx";
import { IS_BROWSER } from "../shared.ts";
let ws: WebSocket;
let revision = 0;
@@ -67,8 +71,6 @@ function connect() {
ws.addEventListener("error", handleError);
}
connect();
function disconnect() {
ws.removeEventListener("open", onOpenWs);
ws.removeEventListener("close", onCloseWs);
@@ -108,21 +110,25 @@ function handleError(e: Event) {
}
}
addEventListener("message", (ev) => {
if (ev.origin !== location.origin) return;
if (typeof ev.data !== "string" || ev.data !== "close-error-overlay") {
return;
}
if (IS_BROWSER) {
connect();
document.querySelector("#fresh-error-overlay")?.remove();
});
addEventListener("message", (ev) => {
if (ev.origin !== location.origin) return;
if (typeof ev.data !== "string" || ev.data !== "close-error-overlay") {
return;
}
// Disconnect when the tab becomes inactive and re-connect when it
// becomes active again
addEventListener("visibilitychange", () => {
if (document.hidden) {
disconnect();
} else {
connect();
}
});
document.querySelector("#fresh-error-overlay")?.remove();
});
// Disconnect when the tab becomes inactive and re-connect when it
// becomes active again
addEventListener("visibilitychange", () => {
if (document.hidden) {
disconnect();
} else {
connect();
}
});
}
+4
View File
@@ -0,0 +1,4 @@
import "./polyfills.ts";
import "./partials.ts";
export { asset, IS_BROWSER, Partial, type PartialProps } from "../shared.ts";
export { boot, revive } from "./reviver.ts";
+507
View File
@@ -0,0 +1,507 @@
import { type ComponentChildren, h } from "preact";
import {
CLIENT_NAV_ATTR,
DATA_ANCESTOR,
DATA_CURRENT,
matchesUrl,
PartialMode,
UrlMatchKind,
} from "../shared_internal.tsx";
import {
ACTIVE_PARTIALS,
copyOldChildren,
CUSTOM_PARSER,
type DeserializedProps,
domToVNode,
ISLAND_REGISTRY,
Marker,
maybeHideMarker,
PartialComp,
} from "./reviver.ts";
import { createRootFragment, isCommentNode, isElementNode } from "./reviver.ts";
import type { PartialStateJson } from "../server/preact_hooks.tsx";
import { parse } from "../../jsonify/parse.ts";
import { INTERNAL_PREFIX } from "../../constants.ts";
export const PARTIAL_ATTR = "f-partial";
export const PARTIAL_SEARCH_PARAM = "fresh-partial";
class NoPartialsError extends Error {}
export interface FreshHistoryState {
index: number;
scrollX: number;
scrollY: number;
}
function checkClientNavEnabled(el: HTMLElement) {
const setting = el.closest(`[${CLIENT_NAV_ATTR}]`);
if (setting === null) return false;
return setting.getAttribute(CLIENT_NAV_ATTR) !== "false";
}
// Keep track of history state to apply forward or backward animations
let index = history.state?.index || 0;
if (!history.state) {
const state: FreshHistoryState = {
index,
scrollX,
scrollY,
};
history.replaceState(state, document.title);
}
function maybeUpdateHistory(nextUrl: URL) {
// Only add history entry when URL is new. Still apply
// the partials because sometimes users click a link to
// "refresh" the current page.
if (nextUrl.href !== globalThis.location.href) {
const state: FreshHistoryState = {
index,
scrollX: globalThis.scrollX,
scrollY: globalThis.scrollY,
};
// Store current scroll position
history.replaceState({ ...state }, "", location.href);
// Now store the new position
index++;
state.scrollX = 0;
state.scrollY = 0;
history.pushState(state, "", nextUrl.href);
}
}
document.addEventListener("click", async (e) => {
let el = e.target;
if (el && el instanceof HTMLElement) {
const originalEl = el;
// Check if we clicked inside an anchor link
if (el.nodeName !== "A") {
el = el.closest("a");
}
if (
// Check that we're still dealing with an anchor tag
el && el instanceof HTMLAnchorElement &&
// Check if it's an internal link
el.href && (!el.target || el.target === "_self") &&
el.origin === location.origin &&
// Check if it was a left click and not a right click
e.button === 0 &&
// Check that the user doesn't press a key combo to open the
// link in a new tab or something
!(e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.button) &&
// Check that the event isn't aborted already
!e.defaultPrevented
) {
const partial = el.getAttribute(PARTIAL_ATTR);
// Check if the user opted out of client side navigation or if
// we're doing a fragment navigation.
if (
el.getAttribute("href")?.startsWith("#") ||
!checkClientNavEnabled(el)
) {
return;
}
// deno-lint-ignore no-explicit-any
const indicator = (el as any)._freshIndicator;
if (indicator !== undefined) {
indicator.value = true;
}
e.preventDefault();
const nextUrl = new URL(el.href);
try {
maybeUpdateHistory(nextUrl);
const partialUrl = new URL(
partial ? partial : nextUrl.href,
location.href,
);
await fetchPartials(partialUrl);
updateLinks(nextUrl);
scrollTo({ left: 0, top: 0, behavior: "instant" });
} finally {
if (indicator !== undefined) {
indicator.value = false;
}
}
} else {
let button: HTMLButtonElement | HTMLElement | null = originalEl;
// Check if we clicked on a button
if (button.nodeName !== "A") {
button = button.closest("button");
}
if (
button !== null && button instanceof HTMLButtonElement &&
(button.type !== "submit" || button.form === null)
) {
const partial = button.getAttribute(PARTIAL_ATTR);
// Check if the user opted out of client side navigation.
if (
partial === null ||
!checkClientNavEnabled(button)
) {
return;
}
const partialUrl = new URL(
partial,
location.href,
);
await fetchPartials(partialUrl);
}
}
}
});
addEventListener("popstate", async (e) => {
// When state is `null` then the browser navigated to a document
// fragment. In this case we do nothing.
if (e.state === null) {
// Reset to browser default
if (history.scrollRestoration) {
history.scrollRestoration = "auto";
}
return;
}
const state: FreshHistoryState = history.state;
const nextIdx = state.index ?? index + 1;
index = nextIdx;
const setting = document.querySelector(`[${CLIENT_NAV_ATTR}]`);
if (setting === null || setting.getAttribute(CLIENT_NAV_ATTR) === "false") {
location.reload();
return;
}
// We need to keep track of that ourselves since we do client side
// navigation.
if (history.scrollRestoration) {
history.scrollRestoration = "manual";
}
const url = new URL(location.href, location.origin);
try {
await fetchPartials(url);
updateLinks(url);
scrollTo({
left: state.scrollX ?? 0,
top: state.scrollY ?? 0,
behavior: "instant",
});
} catch (err) {
// If the response didn't contain a partial, then we can only
// do a reload.
if (err instanceof NoPartialsError) {
location.reload();
return;
}
throw err;
}
});
// Form submit
document.addEventListener("submit", async (e) => {
const el = e.target;
if (el !== null && el instanceof HTMLFormElement && !e.defaultPrevented) {
if (
// Check if form has client nav enabled
!checkClientNavEnabled(el) ||
// Bail out if submitter is set and client nav is disabled
(e.submitter !== null && !checkClientNavEnabled(e.submitter))
) {
return;
}
const lowerMethod =
e.submitter?.getAttribute("formmethod")?.toLowerCase() ??
el.method.toLowerCase();
if (
lowerMethod !== "get" && lowerMethod !== "post" &&
lowerMethod !== "dialog"
) {
return;
}
const action = e.submitter?.getAttribute(PARTIAL_ATTR) ??
e.submitter?.getAttribute("formaction") ??
el.getAttribute(PARTIAL_ATTR) ?? el.action;
if (action !== "") {
e.preventDefault();
const url = new URL(action, location.href);
let init: RequestInit | undefined;
// GET method appends form data via url search params
if (lowerMethod === "get") {
// TODO: Looks like constructor type for URLSearchParam is wrong
// deno-lint-ignore no-explicit-any
const qs = new URLSearchParams(new FormData(el) as any);
qs.forEach((value, key) => url.searchParams.set(key, value));
} else {
init = { body: new FormData(el), method: lowerMethod };
}
maybeUpdateHistory(url);
await fetchPartials(url, init);
}
}
});
function updateLinks(url: URL) {
document.querySelectorAll("a").forEach((link) => {
const match = matchesUrl(url.pathname, link.href);
if (match === UrlMatchKind.Current) {
link.setAttribute(DATA_CURRENT, "true");
link.setAttribute("aria-current", "page");
link.removeAttribute(DATA_ANCESTOR);
} else if (match === UrlMatchKind.Ancestor) {
link.setAttribute(DATA_ANCESTOR, "true");
link.setAttribute("aria-current", "true");
link.removeAttribute(DATA_CURRENT);
} else {
link.removeAttribute(DATA_CURRENT);
link.removeAttribute(DATA_ANCESTOR);
link.removeAttribute("aria-current");
}
});
}
async function fetchPartials(url: URL, init: RequestInit = {}) {
init.redirect = "follow";
url.searchParams.set(PARTIAL_SEARCH_PARAM, "true");
const res = await fetch(url, init);
await applyPartials(res);
}
interface PartialReviveCtx {
foundPartials: number;
}
/**
* Apply partials from a HTML response
*/
export async function applyPartials(res: Response): Promise<void> {
const contentType = res.headers.get("Content-Type");
if (contentType !== "text/html; charset=utf-8") {
throw new Error(`Unable to process partial response.`);
}
const id = res.headers.get("X-Fresh-Id");
const resText = await res.text();
const doc = new DOMParser().parseFromString(resText, "text/html") as Document;
const state = doc.querySelector(`#__FRSH_STATE_${id}`);
let allProps: DeserializedProps = [];
if (state !== null) {
const json = JSON.parse(state.textContent!) as PartialStateJson;
const promises: Promise<void>[] = [];
allProps = parse<DeserializedProps>(json.props, CUSTOM_PARSER);
for (let i = 0; i < json.islands.length; i++) {
const island = json.islands[i];
promises.push(
import(island.chunk).then((mod) => {
ISLAND_REGISTRY.set(island.name, mod[island.exportName]);
}),
);
}
await Promise.all(promises);
}
const ctx: PartialReviveCtx = {
foundPartials: 0,
};
if (doc.title) {
document.title = doc.title;
}
// Needs to be converted to an array otherwise somehow <link>-tags
// are missing.
Array.from(doc.head.childNodes).forEach((childNode) => {
const child = childNode as HTMLElement;
if (child.nodeName === "TITLE") return;
if (child.nodeName === "META") {
const meta = child as HTMLMetaElement;
// Ignore charset which is usually set site wide anyway
if (meta.hasAttribute("charset")) return;
const name = meta.name;
if (name !== "") {
const existing = document.head.querySelector(`meta[name="${name}"]`) as
| HTMLMetaElement
| null;
if (existing !== null) {
if (existing.content !== meta.content) {
existing.content = meta.content;
}
} else {
document.head.appendChild(meta);
}
} else {
const property = child.getAttribute("property");
const existing = document.head.querySelector(
`meta[property="${property}"]`,
) as HTMLMetaElement | null;
if (existing !== null) {
if (existing.content !== meta.content) {
existing.content = meta.content;
}
} else {
document.head.appendChild(meta);
}
}
} else if (child.nodeName === "LINK") {
const link = child as HTMLLinkElement;
if (link.rel === "modulepreload") return;
if (link.rel === "stylesheet") {
// The `href` attribute may be root relative. This ensures
// that they both have the same format
const existing = Array.from(document.head.querySelectorAll("link"))
.find((existingLink) => existingLink.href === link.href);
if (existing === undefined) {
document.head.appendChild(link);
}
}
} else if (child.nodeName === "SCRIPT") {
const script = child as HTMLScriptElement;
if (script.src === `${INTERNAL_PREFIX}/fresh-runtime.js`) return;
// TODO: What to do with script tags?
} else if (child.nodeName === "STYLE") {
const style = child as HTMLStyleElement;
// TODO: Do we need a smarter merging strategy?
// Don't overwrie existing style sheets that are flagged as unique
if (style.id === "") {
document.head.appendChild(style);
}
}
});
revivePartials(ctx, allProps, doc.body);
if (ctx.foundPartials === 0) {
throw new NoPartialsError(
`Found no partials in HTML response. Please make sure to render at least one partial. Requested url: ${res.url}`,
);
}
}
function revivePartials(
ctx: PartialReviveCtx,
allProps: DeserializedProps,
node: Element,
) {
let startNode = null;
let sib: ChildNode | null = node.firstChild;
let partialCount = 0;
let partialName = "";
let partialKey = "";
let partialMode = PartialMode.Replace;
while (sib !== null) {
if (isCommentNode(sib)) {
const comment = sib.data;
const parts = comment.split(":");
if (parts[0] === "frsh") {
sib = maybeHideMarker(sib);
}
if (parts[0] === "frsh" && parts[1] === "partial") {
if (++partialCount === 1) {
startNode = sib;
partialName = parts[2];
partialMode = +parts[3] as PartialMode;
partialKey = parts[4];
}
} else if (comment === "/frsh:partial") {
ctx.foundPartials++;
// Skip hydrating nested partials, only hydrate the outer one
if (--partialCount > 0) {
sib = sib.nextSibling;
continue;
}
// Create a fake DOM node that spans the partial we discovered.
// We need to include the partial markers itself for _walkInner
// to register them.
const container = createRootFragment(
node,
startNode as Comment,
sib as Comment,
);
const root = h(PartialComp, {
key: partialKey !== "" ? partialKey : undefined,
name: partialName,
mode: partialMode,
children: null,
});
domToVNode(
allProps,
[root],
[Marker.Partial],
container,
sib as Comment,
);
const instance = ACTIVE_PARTIALS.get(partialName);
if (instance === undefined) {
console.warn(`Partial "${partialName}" not found. Skipping...`);
// Partial doesn't exist on the current page
} else {
if (partialMode === PartialMode.Replace) {
instance.props.children = root.props.children;
} else if (partialMode === PartialMode.Append) {
const active = ACTIVE_PARTIALS.get(partialName);
if (active !== undefined) {
copyOldChildren(instance.props, active.props.children);
(instance.props.children as ComponentChildren[]).push(
root.props.children,
);
} else {
instance.props.children = root.props.children;
}
} else if (partialMode === PartialMode.Prepend) {
const active = ACTIVE_PARTIALS.get(partialName);
if (active !== undefined) {
copyOldChildren(instance.props, active.props.children);
(instance.props.children as ComponentChildren[]).unshift(
root.props.children,
);
} else {
instance.props.children = root.props.children;
}
}
instance.setState({});
}
}
} else if (partialCount === 0 && isElementNode(sib)) {
// Do not recurse if we know that we are inisde a partial
revivePartials(ctx, allProps, sib);
}
sib = sib.nextSibling;
}
}
@@ -0,0 +1,9 @@
import { options } from "preact";
import { assetHashingHook } from "../shared_internal.tsx";
import { BUILD_ID } from "../build_id.ts";
const oldVNodeHook = options.vnode;
options.vnode = (vnode) => {
assetHashingHook(vnode, BUILD_ID);
oldVNodeHook?.(vnode);
};
+567
View File
@@ -0,0 +1,567 @@
import {
Component,
type ComponentChildren,
type ComponentType,
Fragment,
h,
render,
type VNode,
} from "preact";
import { type CustomParser, parse } from "../../jsonify/parse.ts";
import { signal } from "@preact/signals";
import { DATA_FRESH_KEY, PartialMode } from "../shared_internal.tsx";
const enum RootKind {
Island,
Partial,
}
interface IslandReq {
kind: RootKind.Island;
name: string;
propsIdx: number;
key: string | null;
start: Comment | Text;
end: Comment | Text | null;
}
interface PartialReq {
kind: RootKind.Partial;
name: string;
key: string | null;
start: Comment | Text;
end: Comment | Text | null;
}
interface ReviveContext {
roots: Array<IslandReq | PartialReq>;
stack: Array<PartialReq | IslandReq>;
slots: Map<number, { name: string; start: Comment; end: Comment | null }>;
slotIdStack: number[];
}
interface SlotRef {
kind: typeof SLOT_SYMBOL;
name: string;
id: number;
}
const SLOT_SYMBOL = Symbol.for("_FRESH_SLOT");
function isSlotRef(x: unknown): x is SlotRef {
return x !== null && typeof x === "object" && "kind" in x &&
x.kind === SLOT_SYMBOL;
}
export type DeserializedProps = {
props: Record<string, unknown>;
slots: SlotRef[];
}[];
export const ACTIVE_PARTIALS = new Map<string, PartialComp>();
export class PartialComp extends Component<
{ children?: ComponentChildren; mode: PartialMode; name: string }
> {
componentDidMount() {
ACTIVE_PARTIALS.set(this.props.name, this);
}
render() {
return this.props.children;
}
}
PartialComp.displayName = "Partial";
export function revive(
props: Record<string, unknown>,
component: ComponentType,
container: HTMLElement,
slots: ReviveContext["slots"],
allProps: DeserializedProps,
) {
const _render = () => {
for (const propName in props) {
const value = props[propName];
if (isSlotRef(value)) {
const marker = slots.get(value.id);
if (marker !== undefined) {
const root = h(Fragment, null);
const slotContainer = createRootFragment(
container,
marker.start,
marker.end!,
);
domToVNode(
allProps,
[root],
[Marker.Slot],
slotContainer,
marker.end!,
);
props[propName] = root;
} else {
const template = document.querySelector(
`#frsh-${value.id}-${value.name}`,
) as HTMLTemplateElement | null;
if (template !== null) {
const root = h(Fragment, null);
domToVNode(allProps, [root], [Marker.Slot], template.content, null);
props[propName] = root;
}
}
}
}
// TODO: explore hydrate?
render(h(component, props), container as unknown as HTMLElement);
};
// deno-lint-ignore no-window
"scheduler" in window
// `scheduler.postTask` is async but that can easily
// fire in the background. We don't want waiting for
// the hydration of an island block us.
// @ts-ignore scheduler API is not in types yet
? scheduler!.postTask(_render)
: setTimeout(_render, 0);
}
export const ISLAND_REGISTRY = new Map<string, ComponentType>();
export const CUSTOM_PARSER: CustomParser = {
Signal: (value: unknown) => signal(value),
Slot: (value: { name: string; id: number }): SlotRef => {
return { kind: SLOT_SYMBOL, name: value.name, id: value.id };
},
};
export function createReviveCtx(): ReviveContext {
return {
roots: [],
stack: [],
slots: new Map(),
slotIdStack: [],
};
}
export function boot(
initialIslands: Record<string, ComponentType>,
islandProps: string,
) {
const ctx = createReviveCtx();
_walkInner(ctx, document.body);
const keys = Object.keys(initialIslands);
for (let i = 0; i < keys.length; i++) {
const name = keys[i];
ISLAND_REGISTRY.set(name, initialIslands[name]);
}
const allProps = parse<DeserializedProps>(
islandProps,
CUSTOM_PARSER,
);
for (let i = 0; i < ctx.roots.length; i++) {
const root = ctx.roots[i];
const container = createRootFragment(
// deno-lint-ignore no-explicit-any
root.start.parentNode as any,
root.start,
root.end!,
);
if (root.kind === RootKind.Island) {
const props = allProps[root.propsIdx].props;
const component = ISLAND_REGISTRY.get(root.name)!;
revive(props, component, container, ctx.slots, allProps);
} else if (root.kind === RootKind.Partial) {
const props: Record<string, unknown> = {
name: root.name,
children: null,
};
const domRoot = h(Fragment, null);
domToVNode(allProps, [domRoot], [Marker.Partial], container, root.end!);
props.children = domRoot.props.children;
// deno-lint-ignore no-explicit-any
revive(props, PartialComp as any, container, ctx.slots, allProps);
}
}
}
const SHOW_MARKERS = false;
interface FreshMarker extends Text {
_frshMarker: string;
}
export function isFreshMarkerText(node: Node): node is FreshMarker {
return node.nodeType === Node.TEXT_NODE &&
// deno-lint-ignore no-explicit-any
typeof (node as any)._frshMarker === "string";
}
/**
* Replace comment markers with empty text nodes to hide them
* in DevTools. This is done to avoid user confusion.
*/
export function maybeHideMarker(marker: Comment): Comment | Text {
if (SHOW_MARKERS) return marker;
const text = new Text("") as FreshMarker;
text._frshMarker = marker.data;
marker.parentNode!.insertBefore(text, marker);
marker.remove();
return text;
}
function _walkInner(
ctx: ReviveContext,
node: Node | Comment,
) {
if (isElementNode(node)) {
// No need to traverse into <script> or <style> tags.
// No need to traverse deeper if we found a slotStart marker.
// We'll parse slots later when the island is revived.
if (
node.nodeName === "SCRIPT" || node.nodeName === "STYLE" ||
ctx.slotIdStack.length > 0
) {
return;
}
for (let i = 0; i < node.childNodes.length; i++) {
const child = node.childNodes[i];
_walkInner(ctx, child);
}
} else if (isCommentNode(node)) {
const comment = node.data;
if (comment.startsWith("frsh:")) {
node = maybeHideMarker(node);
const parts = comment.split(":");
const kind = parts[1];
if (kind === "island") {
const name = parts[2];
const propsIdx = parts[3];
const key = parts[4];
const found: IslandReq = {
kind: RootKind.Island,
name,
propsIdx: Number(propsIdx),
key: key === "" ? null : key,
start: node as Comment,
end: null,
};
if (ctx.stack.length === 0) {
ctx.roots.push(found);
}
ctx.stack.push(found);
} else if (kind === "slot") {
const id = +parts[2];
const slotName = parts[3];
ctx.slotIdStack.push(id);
ctx.slots.set(id, {
name: slotName,
start: node as Comment,
end: null,
});
} else if (kind === "partial") {
const name = parts[2];
const key = parts[3];
const found: PartialReq = {
kind: RootKind.Partial,
name,
key: key === "" ? null : key,
start: node as Comment,
end: null,
};
if (ctx.stack.length === 0) {
ctx.roots.push(found);
}
ctx.stack.push(found);
}
} else if (comment === "/frsh:island" || comment === "/frsh:partial") {
node = maybeHideMarker(node);
const item = ctx.stack.pop();
if (item !== undefined) {
item.end = node as Comment;
}
} else if (comment === "/frsh:slot") {
node = maybeHideMarker(node);
const item = ctx.slotIdStack.pop();
if (item !== undefined) {
ctx.slots.get(item)!.end = node as Comment;
}
}
}
}
export const enum Marker {
Island,
Partial,
Slot,
}
interface ServerSlotProps {
name: string;
id: number;
children?: ComponentChildren;
}
// deno-lint-ignore no-explicit-any
function ServerSlot(props: ServerSlotProps): any {
return props.children;
}
export function domToVNode(
allProps: DeserializedProps,
// deno-lint-ignore no-explicit-any
vnodeStack: VNode<any>[],
markerStack: Marker[],
node: Text | Comment | Node | DocumentFragment,
end: Text | Comment | null,
): void {
let sib: Node | ChildNode | null = node;
while (sib !== null) {
if (sib === end) return;
// deno-lint-ignore no-explicit-any
if ((sib as any)._frshRootFrag || sib instanceof DocumentFragment) {
const firstChild = sib.firstChild;
if (firstChild !== null) {
domToVNode(allProps, vnodeStack, markerStack, firstChild, end);
}
} else if (isElementNode(sib)) {
const props: Record<string, unknown> = {};
for (let i = 0; i < sib.attributes.length; i++) {
const attr = sib.attributes[i];
if (attr.nodeName === DATA_FRESH_KEY) {
props.key = attr.nodeValue;
continue;
}
// Boolean attributes are always `true` when present.
// See: https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML
props[attr.nodeName] =
// deno-lint-ignore no-explicit-any
typeof (sib as any)[attr.nodeName] === "boolean"
? true
: attr.nodeValue;
}
const vnode = h(sib.localName, props);
const marker = markerStack.at(-1);
const appendVNode = marker === Marker.Slot || marker === Marker.Partial;
if (appendVNode) {
addVNodeChild(vnodeStack.at(-1)!, vnode);
vnodeStack.push(vnode);
}
const firstChild = sib.firstChild;
if (firstChild !== null) {
domToVNode(allProps, vnodeStack, markerStack, firstChild, end);
}
if (appendVNode) {
vnodeStack.pop();
}
} else if (isCommentNode(sib) || isFreshMarkerText(sib)) {
const comment = isFreshMarkerText(sib) ? sib._frshMarker : sib.data;
if (comment.startsWith("frsh:")) {
const parts = comment.split(":");
const kind = parts[1];
if (kind === "island") {
sib = maybeHideMarker(sib);
markerStack.push(Marker.Island);
const name = parts[2];
const propsIdx = parts[3];
const key = parts[4];
const island = ISLAND_REGISTRY.get(name);
if (island === undefined) {
throw new Error(`Encountered unknown island: ${name}`);
}
const props = allProps[+propsIdx].props;
props.key = key === "" ? undefined : key;
// deno-lint-ignore no-explicit-any
const islandVNode = h<any>(island, props);
addVNodeChild(vnodeStack.at(-1)!, islandVNode);
vnodeStack.push(islandVNode);
} else if (kind === "slot") {
sib = maybeHideMarker(sib);
markerStack.push(Marker.Slot);
const id = +parts[2];
const slotName = parts[3];
const key = parts[4];
const vnode = h(ServerSlot, {
key: key === "" ? undefined : key,
id,
name: slotName,
children: [],
});
const parentVNode = vnodeStack.at(-1)!;
if (slotName === "children") {
addVNodeChild(parentVNode, vnode);
} else {
parentVNode.props[slotName] = vnode;
}
vnodeStack.push(vnode);
} else if (kind === "partial") {
sib = maybeHideMarker(sib);
markerStack.push(Marker.Partial);
const name = parts[2];
const mode = +parts[3] as PartialMode;
const key = parts[4];
// deno-lint-ignore no-explicit-any
let vnode: VNode<any> = h(PartialComp, {
name,
key: key === "" ? undefined : key,
mode,
});
const parentVNode = vnodeStack.at(-1);
if (parentVNode !== undefined) {
addVNodeChild(parentVNode, vnode);
}
if (mode === PartialMode.Append) {
const active = ACTIVE_PARTIALS.get(name);
if (active !== undefined) {
copyOldChildren(vnode.props, active.props.children);
const wrapper = h(Fragment, null);
addVNodeChild(vnode, wrapper);
vnode = wrapper;
}
} else if (mode === PartialMode.Prepend) {
const active = ACTIVE_PARTIALS.get(name);
if (active !== undefined) {
copyOldChildren(vnode.props, active.props.children);
const wrapper = h(Fragment, null);
if (!vnode.props.children) {
vnode.props.children = [];
}
// deno-lint-ignore no-explicit-any
(vnode.props.children as Array<VNode<any> | string>).unshift(
wrapper,
);
vnode = wrapper;
}
}
vnodeStack.push(vnode);
} else if (kind === "key") {
if (!SHOW_MARKERS) {
const current = sib;
sib = sib.nextSibling;
current.remove();
}
const vnode = h(Fragment, { key: parts[2] });
addVNodeChild(vnodeStack.at(-1)!, vnode);
vnodeStack.push(vnode);
continue;
}
} else if (
comment === "/frsh:island" || comment === "/frsh:slot" ||
comment === "/frsh:partial"
) {
vnodeStack.pop();
markerStack.pop();
sib = maybeHideMarker(sib);
} else if (comment === "/frsh:key") {
vnodeStack.pop();
sib = maybeHideMarker(sib);
}
} else if (isTextNode(sib)) {
const marker = markerStack.at(-1);
if (marker === Marker.Slot || marker === Marker.Partial) {
addVNodeChild(vnodeStack.at(-1)!, sib.data);
}
}
sib = sib.nextSibling;
}
}
// deno-lint-ignore no-explicit-any
function addVNodeChild(parent: VNode<any>, child: VNode<any> | string) {
if (!parent.props.children) {
parent.props.children = [];
}
// deno-lint-ignore no-explicit-any
(parent.props.children as Array<VNode<any> | string>).push(child);
}
export function copyOldChildren(
props: Record<string, unknown>,
oldChildren: ComponentChildren,
) {
props.children = oldChildren !== undefined && oldChildren !== null
? Array.isArray(oldChildren) ? oldChildren : [oldChildren]
: [];
}
export function isCommentNode(node: Node): node is Comment {
return node.nodeType === Node.COMMENT_NODE;
}
export function isTextNode(node: Node): node is Text {
return node.nodeType === Node.TEXT_NODE;
}
export function isElementNode(node: Node): node is HTMLElement {
return node.nodeType === Node.ELEMENT_NODE && !("_frshRootFrag" in node);
}
export function createRootFragment(
parent: Element,
startMarker: Text | Comment,
// We need an end marker for islands because multiple
// islands can share the same parent node. Since
// islands are root-level render calls any calls to
// `.appendChild` would lead to a wrong result.
endMarker: Text | Comment,
): HTMLElement & { _frshRootFrag: boolean } {
// @ts-ignore this is fine
return {
_frshRootFrag: true,
nodeType: 1,
parentNode: parent,
nextSibling: null,
get firstChild() {
const child = startMarker.nextSibling;
if (child === endMarker) return null;
return child;
},
get childNodes() {
const children: ChildNode[] = [];
let child = startMarker.nextSibling;
while (child !== null && child !== endMarker) {
children.push(child);
child = child.nextSibling;
}
return children;
},
insertBefore(node: Node, child: Node | null) {
parent.insertBefore(node, child ?? endMarker);
},
appendChild(child: Node) {
// We cannot blindly call `.append()` as that would add
// the new child to the very end of the parent node. This
// leads to ordering issues when the multiple islands
// share the same parent node.
parent.insertBefore(child, endMarker);
},
removeChild(child: Node) {
parent.removeChild(child);
},
// deno-lint-ignore no-explicit-any
} as any;
}
-140
View File
@@ -1,140 +0,0 @@
import { createContext } from "preact";
import { useContext } from "preact/hooks";
export const SELF = "'self'";
export const UNSAFE_INLINE = "'unsafe-inline'";
export const UNSAFE_EVAL = "'unsafe-eval'";
export const UNSAFE_HASHES = "'unsafe-hashes'";
export const NONE = "'none'";
export const STRICT_DYNAMIC = "'strict-dynamic'";
export function nonce(val: string) {
return `'nonce-${val}'`;
}
export interface ContentSecurityPolicy {
directives: ContentSecurityPolicyDirectives;
reportOnly: boolean;
}
export interface ContentSecurityPolicyDirectives {
// Fetch directives
/**
* Defines the valid sources for web workers and nested browsing contexts
* loaded using elements such as <frame> and <iframe>.
*/
childSrc?: string[];
/**
* Restricts the URLs which can be loaded using script interfaces.
*/
connectSrc?: string[];
/**
* Serves as a fallback for the other fetch directives.
*/
defaultSrc?: string[];
/**
* Specifies valid sources for fonts loaded using @font-face.
*/
fontSrc?: string[];
/**
* Specifies valid sources for nested browsing contexts loading using elements
* such as <frame> and <iframe>.
*/
frameSrc?: string[];
/**
* Specifies valid sources of images and favicons.
*/
imgSrc?: string[];
/**
* Specifies valid sources of application manifest files.
*/
manifestSrc?: string[];
/**
* Specifies valid sources for loading media using the <audio> , <video> and
* <track> elements.
*/
mediaSrc?: string[];
/**
* Specifies valid sources for the <object>, <embed>, and <applet> elements.
*/
objectSrc?: string[];
/**
* Specifies valid sources to be prefetched or prerendered.
*/
prefetchSrc?: string[];
/**
* Specifies valid sources for JavaScript.
*/
scriptSrc?: string[];
/**
* Specifies valid sources for JavaScript <script> elements.
*/
scriptSrcElem?: string[];
/**
* Specifies valid sources for JavaScript inline event handlers.
*/
scriptSrcAttr?: string[];
/**
* Specifies valid sources for stylesheets.
*/
styleSrc?: string[];
/**
* Specifies valid sources for stylesheets <style> elements and <link>
* elements with rel="stylesheet".
*/
styleSrcElem?: string[];
/**
* Specifies valid sources for inline styles applied to individual DOM
* elements.
*/
styleSrcAttr?: string[];
/**
* Specifies valid sources for Worker, SharedWorker, or ServiceWorker scripts.
*/
workerSrc?: string[];
// Document directives
/**
* Restricts the URLs which can be used in a document's <base> element.
*/
baseUri?: string[];
/**
* Enables a sandbox for the requested resource similar to the <iframe>
* sandbox attribute.
*/
sandbox?: string[];
// Navigation directives
/**
* Restricts the URLs which can be used as the target of a form submissions
* from a given context.
*/
formAction?: string[];
/**
* Specifies valid parents that may embed a page using <frame>, <iframe>,
* <object>, <embed>, or <applet>.
*/
frameAncestors?: string[];
/**
* Restricts the URLs to which a document can initiate navigation by any
* means, including <form> (if form-action is not specified), <a>,
* window.location, window.open, etc.
*/
navigateTo?: string[];
/**
* The URI to report CSP violations to.
*/
reportUri?: string;
}
export const CSP_CONTEXT = createContext<ContentSecurityPolicy | undefined>(
undefined,
);
export function useCSP(mutator: (csp: ContentSecurityPolicy) => void) {
const csp = useContext(CSP_CONTEXT);
if (csp) {
mutator(csp);
}
}
-75
View File
@@ -1,75 +0,0 @@
export const KEY = "_f";
interface Signal<T> {
peek(): T;
value: T;
}
function b64decode(b64: string): Uint8Array {
const binString = atob(b64);
const size = binString.length;
const bytes = new Uint8Array(size);
for (let i = 0; i < size; i++) {
bytes[i] = binString.charCodeAt(i);
}
return bytes;
}
const INVALID_REFERENCE_ERROR = "Invalid reference";
function getPropertyFromPath(o: object, path: string[]): object {
for (const key of path) {
if (key === null) continue;
if (key !== "value" && !Object.hasOwn(o, key)) {
throw new Error(INVALID_REFERENCE_ERROR);
}
// deno-lint-ignore no-explicit-any
o = (o as any)[key];
}
return o;
}
export function deserialize(
str: string,
signal?: <T>(a: T) => Signal<T>,
): unknown {
function reviver(this: unknown, _key: string, value: unknown): unknown {
if (typeof value === "object" && value && KEY in value) {
// deno-lint-ignore no-explicit-any
const v: any = value;
if (v[KEY] === "s") {
return signal!(v.v);
}
if (v[KEY] === "b") {
return BigInt(v.d);
}
if (v[KEY] === "u8a") {
return b64decode(v.d);
}
if (v[KEY] === "l") {
const val = v.v;
val[KEY] = v.k;
return val;
}
throw new Error(`Unknown key: ${v[KEY]}`);
}
return value;
}
const { v, r } = JSON.parse(str, reviver);
const references = (r ?? []) as [string[], ...string[][]][];
for (const [targetPath, ...refPaths] of references) {
const target = getPropertyFromPath(v, targetPath);
for (const refPath of refPaths) {
if (refPath.length === 0) throw new Error(INVALID_REFERENCE_ERROR);
// set the reference to the target object
const parent = getPropertyFromPath(v, refPath.slice(0, -1));
const key = refPath[refPath.length - 1]!;
if (key !== "value" && !Object.hasOwn(parent, key)) {
throw new Error(INVALID_REFERENCE_ERROR);
}
// deno-lint-ignore no-explicit-any
(parent as any)[key] = target;
}
}
return v;
}
-1
View File
@@ -1 +0,0 @@
export { deserialize } from "../deserializer.ts";
File diff suppressed because it is too large Load Diff
-2
View File
@@ -1,2 +0,0 @@
import "preact/debug";
export * from "./main.ts";
-1
View File
@@ -1 +0,0 @@
export { signal } from "@preact/signals";
-22
View File
@@ -1,22 +0,0 @@
import { ComponentChildren, createContext } from "preact";
import { useContext } from "preact/hooks";
export interface HeadProps {
children: ComponentChildren;
}
export const HEAD_CONTEXT = createContext<ComponentChildren[]>([]);
export function Head(props: HeadProps) {
let context: ComponentChildren[];
try {
context = useContext(HEAD_CONTEXT);
} catch (err) {
throw new Error(
"<Head> component is not supported in the browser, or during suspense renders.",
{ cause: err },
);
}
context.push(props.children);
return null;
}
+16
View File
@@ -0,0 +1,16 @@
import type { FunctionComponent } from "preact";
import type { FreshContext } from "../../context.ts";
/**
* The mode Fresh can run in.
*/
export type Mode = "development" | "build" | "production";
export let MODE: Mode = "production";
export function setMode(mode: Mode) {
MODE = mode;
}
export type PageProps<Data = unknown, T = unknown> =
& Omit<FreshContext<Data, T>, "next" | "redirect" | "next">
& { Component: FunctionComponent };
+532
View File
@@ -0,0 +1,532 @@
import {
type Component,
type ComponentChildren,
type ComponentType,
Fragment,
h,
isValidElement,
type Options as PreactOptions,
options as preactOptions,
type VNode,
} from "preact";
import type { Signal } from "@preact/signals";
import type { Stringifiers } from "../../jsonify/stringify.ts";
import type { FreshContext } from "../../context.ts";
import { asset, Partial, type PartialProps } from "../shared.ts";
import { stringify } from "../../jsonify/stringify.ts";
import type { ServerIslandRegistry } from "../../context.ts";
import type { Island } from "../../context.ts";
import {
assetHashingHook,
CLIENT_NAV_ATTR,
DATA_FRESH_KEY,
PartialMode,
setActiveUrl,
} from "../shared_internal.tsx";
import type { BuildCache } from "../../build_cache.ts";
import { BUILD_ID } from "../build_id.ts";
import { DEV_ERROR_OVERLAY_URL } from "../../constants.ts";
import {
getCodeFrame,
} from "../../dev/middlewares/error_overlay/code_frame.tsx";
import * as colors from "@std/fmt/colors";
import { escape as escapeHtml } from "@std/html";
const enum OptionsType {
ATTR = "attr",
VNODE = "vnode",
HOOK = "__h",
DIFF = "__b",
RENDER = "__r",
DIFFED = "diffed",
ERROR = "__e",
}
interface InternalPreactOptions extends PreactOptions {
[OptionsType.ATTR](name: string, value: unknown): string | void;
[OptionsType.VNODE](vnode: InternalVNode): void;
[OptionsType.HOOK](component: Component, index: number, type: number): void;
[OptionsType.DIFF](vnode: InternalVNode): void;
[OptionsType.RENDER](vnode: InternalVNode): void;
[OptionsType.DIFFED](vnode: InternalVNode): void;
[OptionsType.ERROR](
error: unknown,
vnode: InternalVNode,
oldVNode: InternalVNode,
): void;
}
interface InternalVNode extends VNode {
__c: Component | null;
__: InternalVNode | null;
}
// deno-lint-ignore no-explicit-any
const options: InternalPreactOptions = preactOptions as any;
export class RenderState {
nonce: string;
partialDepth = 0;
partialCount = 0;
error: Error | null = null;
// deno-lint-ignore no-explicit-any
slots: Array<{ id: number; name: string; vnode: VNode<any> } | null> = [];
basePath = ""; // FIXME
// deno-lint-ignore no-explicit-any
islandProps: any[] = [];
islands = new Set<Island>();
// deno-lint-ignore no-explicit-any
encounteredPartials = new Set<any>();
owners = new Map<VNode, VNode>();
ownerStack: InternalVNode[] = [];
// TODO: merge into bitmask field
renderedHtmlTag = false;
renderedHtmlBody = false;
renderedHtmlHead = false;
hasRuntimeScript = false;
constructor(
public ctx: FreshContext<unknown, unknown>,
public islandRegistry: ServerIslandRegistry,
public buildCache: BuildCache,
public partialId: string,
) {
this.nonce = crypto.randomUUID().replace(/-/g, "");
}
clear() {
this.islands.clear();
this.encounteredPartials.clear();
this.owners.clear();
this.slots = [];
this.islandProps = [];
this.ownerStack = [];
}
}
let RENDER_STATE: RenderState | null = null;
export function setRenderState(state: RenderState | null) {
RENDER_STATE = state;
}
const oldVNodeHook = options[OptionsType.VNODE];
options[OptionsType.VNODE] = (vnode) => {
if (RENDER_STATE !== null) {
RENDER_STATE.owners.set(vnode, RENDER_STATE!.ownerStack.at(-1)!);
if (vnode.type === "a") {
setActiveUrl(vnode, RENDER_STATE.ctx.url.pathname);
}
}
assetHashingHook(vnode, BUILD_ID);
if (typeof vnode.type === "function") {
if (vnode.type === Partial) {
const props = vnode.props as PartialProps;
const key = normalizeKey(vnode.key ?? "");
const mode = !props.mode || props.mode === "replace"
? PartialMode.Replace
: props.mode === "append"
? PartialMode.Append
: PartialMode.Prepend;
props.children = wrapWithMarker(
props.children,
"partial",
`${props.name}:${mode}:${key}`,
);
}
} else if (typeof vnode.type === "string") {
if (vnode.type === "body") {
const scripts = h(FreshScripts, null);
if (vnode.props.children == null) {
vnode.props.children = scripts;
} else if (Array.isArray(vnode.props.children)) {
vnode.props.children.push(scripts);
} else {
vnode.props.children = [vnode.props.children, scripts];
}
}
if (CLIENT_NAV_ATTR in vnode.props) {
vnode.props[CLIENT_NAV_ATTR] = String(vnode.props[CLIENT_NAV_ATTR]);
}
}
oldVNodeHook?.(vnode);
};
const oldAttrHook = options[OptionsType.ATTR];
options[OptionsType.ATTR] = (name, value) => {
if (name === CLIENT_NAV_ATTR) {
return `${CLIENT_NAV_ATTR}="${String(Boolean(value))}"`;
} else if (name === "key") {
return `${DATA_FRESH_KEY}="${escapeHtml(String(value))}"`;
}
return oldAttrHook?.(name, value);
};
const PATCHED = new WeakSet<VNode>();
function normalizeKey(str: string) {
return str.replaceAll(":", "_");
}
const oldDiff = options[OptionsType.DIFF];
options[OptionsType.DIFF] = (vnode) => {
if (RENDER_STATE !== null) {
patcher: if (
typeof vnode.type === "function" && vnode.type !== Fragment
) {
if (vnode.type === Partial) {
RENDER_STATE.partialDepth++;
const name = (vnode.props as PartialProps).name;
if (typeof name === "string") {
if (RENDER_STATE.encounteredPartials.has(name)) {
throw new Error(
`Rendered response contains duplicate partial name: "${name}"`,
);
}
RENDER_STATE.encounteredPartials.add(name);
}
if (hasIslandOwner(RENDER_STATE, vnode)) {
throw new Error(
`<Partial> components cannot be used inside islands.`,
);
}
} else if (
!PATCHED.has(vnode) && !hasIslandOwner(RENDER_STATE, vnode)
) {
const island = RENDER_STATE.islandRegistry.get(vnode.type);
if (island === undefined) {
// Not an island, but we might need to preserve keys
if (vnode.key !== undefined) {
const key = normalizeKey(vnode.key ?? "");
const originalType = vnode.type;
vnode.type = (props) => {
const child = h(originalType, props);
PATCHED.add(child);
return wrapWithMarker(child, "key", key);
};
}
break patcher;
}
const { islands, islandProps } = RENDER_STATE;
islands.add(island);
const originalType = vnode.type;
vnode.type = (props) => {
for (const name in props) {
// deno-lint-ignore no-explicit-any
const value = (props as any)[name];
if (
name === "children" || (isValidElement(value) && !isSignal(value))
) {
const slotId = RENDER_STATE!.slots.length;
RENDER_STATE!.slots.push({ id: slotId, name, vnode: value });
// deno-lint-ignore no-explicit-any
(props as any)[name] = h(Slot, {
name,
id: slotId,
}, value);
}
}
const propsIdx = islandProps.push({ slots: [], props }) - 1;
const child = h(originalType, props);
PATCHED.add(child);
const key = normalizeKey(vnode.key ?? "");
return wrapWithMarker(
child,
"island",
`${island!.name}:${propsIdx}:${key}`,
);
};
}
} else if (typeof vnode.type === "string") {
switch (vnode.type) {
case "html":
RENDER_STATE!.renderedHtmlTag = true;
break;
case "head":
RENDER_STATE!.renderedHtmlHead = true;
break;
case "body":
RENDER_STATE!.renderedHtmlBody = true;
break;
}
if (
vnode.key !== undefined &&
(RENDER_STATE!.partialDepth > 0 || hasIslandOwner(RENDER_STATE!, vnode))
) {
(vnode.props as Record<string, unknown>)[DATA_FRESH_KEY] = String(
vnode.key,
);
}
}
}
oldDiff?.(vnode);
};
const oldRender = options[OptionsType.RENDER];
options[OptionsType.RENDER] = (vnode) => {
if (
typeof vnode.type === "function" && vnode.type !== Fragment &&
RENDER_STATE !== null
) {
RENDER_STATE.ownerStack.push(vnode);
}
oldRender?.(vnode);
};
const oldDiffed = options[OptionsType.DIFFED];
options[OptionsType.DIFFED] = (vnode) => {
if (
typeof vnode.type === "function" && vnode.type !== Fragment &&
RENDER_STATE !== null
) {
RENDER_STATE.ownerStack.pop();
if (vnode.type === Partial) {
RENDER_STATE.partialDepth--;
}
}
oldDiffed?.(vnode);
};
interface SlotProps {
name: string;
id: number;
children?: ComponentChildren;
}
function Slot(props: SlotProps) {
if (RENDER_STATE !== null) {
RENDER_STATE.slots[props.id] = null;
}
return wrapWithMarker(props.children, "slot", `${props.id}:${props.name}`);
}
/**
* Check if the current component was rendered in an island
*/
function hasIslandOwner(current: RenderState, vnode: VNode): boolean {
let tmpVNode = vnode;
let owner;
while ((owner = current.owners.get(tmpVNode)) !== undefined) {
if (current.islandRegistry.has(owner.type as ComponentType)) {
return true;
}
tmpVNode = owner;
}
return false;
}
function wrapWithMarker(
vnode: ComponentChildren,
kind: string,
markerText: string,
) {
return h(
Fragment,
null,
h(Fragment, {
// @ts-ignore unstable property is not typed
UNSTABLE_comment: `frsh:${kind}:${markerText}`,
}),
vnode,
h(Fragment, {
// @ts-ignore unstable property is not typed
UNSTABLE_comment: "/frsh:" + kind,
}),
);
}
// deno-lint-ignore no-explicit-any
function isSignal(x: any): x is Signal {
return (
x !== null &&
typeof x === "object" &&
typeof x.peek === "function" &&
"value" in x
);
}
// deno-lint-ignore no-explicit-any
function isVNode(x: any): x is VNode {
return x !== null && typeof x === "object" && "type" in x && "ref" in x &&
"__k" in x &&
isValidElement(x);
}
const stringifiers: Stringifiers = {
Signal: (value: unknown) => {
return isSignal(value) ? value.peek() : undefined;
},
Slot: (value: unknown) => {
if (isVNode(value) && value.type === Slot) {
const props = value.props as SlotProps;
return {
name: props.name,
id: props.id,
};
}
},
};
export function FreshScripts() {
if (RENDER_STATE === null) return null;
if (RENDER_STATE.hasRuntimeScript) {
return null;
}
RENDER_STATE.hasRuntimeScript = true;
const { slots } = RENDER_STATE;
// Remaining slots must be rendered before creating the Fresh runtime
// script, so that we have the full list of islands rendered
return (
<>
{slots.map((slot) => {
if (slot === null) return null;
// FIXME: Wait for https://github.com/preactjs/preact/pull/4334 to be
// released
return h(
"template",
{ key: slot.id, id: `frsh-${slot.id}-${slot.name}` },
slot.vnode,
// deno-lint-ignore no-explicit-any
) as VNode<any>;
})}
<FreshRuntimeScript />
</>
);
}
export interface PartialStateJson {
islands: {
name: string;
chunk: string;
exportName: string;
}[];
props: string;
}
function FreshRuntimeScript() {
const { islands, nonce, ctx, islandProps, partialId, buildCache } =
RENDER_STATE!;
const basePath = ctx.config.basePath;
const islandArr = Array.from(islands);
if (ctx.url.searchParams.has("fresh-partial")) {
const islands = islandArr.map((island) => {
const chunk = buildCache.getIslandChunkName(island.name);
if (chunk === null) {
throw new Error(
`Could not find chunk for ${island.name} ${island.file}#${island.exportName}`,
);
}
return {
exportName: island.exportName,
chunk: asset(chunk),
name: island.name,
};
});
const serializedProps = stringify(islandProps, stringifiers);
const json: PartialStateJson = {
islands,
props: serializedProps,
};
return (
<script
id={`__FRSH_STATE_${partialId}`}
type="application/json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(json) }}
/>
);
} else {
const islandImports = islandArr.map((island) => {
const chunk = buildCache.getIslandChunkName(island.name);
if (chunk === null) {
throw new Error(
`Could not find chunk for ${island.name} ${island.file}#${island.exportName}`,
);
}
const named = island.exportName === "default"
? island.name
: `{ ${island.exportName} }`;
return `import ${named} from "${asset(chunk)}";`;
}).join("");
const islandObj = "{" + islandArr.map((island) => island.name)
.join(",") +
"}";
const serializedProps = JSON.stringify(
stringify(islandProps, stringifiers),
);
const runtimeUrl = asset(`${basePath}/fresh-runtime.js`);
const scriptContent =
`import { boot } from "${runtimeUrl}";${islandImports}boot(${islandObj},${serializedProps});`;
return (
<>
<script
type="module"
nonce={nonce}
dangerouslySetInnerHTML={{
__html: scriptContent,
}}
/>
<ShowErrorOverlay />
</>
);
}
}
export function ShowErrorOverlay() {
if (RENDER_STATE === null) return null;
const { ctx } = RENDER_STATE;
const error = ctx.error;
if (error === null || error === undefined) return null;
const basePath = ctx.config.basePath;
const searchParams = new URLSearchParams();
if (typeof error === "object") {
if ("message" in error) {
searchParams.append("message", String(error.message));
}
if ("stack" in error && typeof error.stack === "string") {
searchParams.append("stack", error.stack);
const codeFrame = getCodeFrame(error.stack, ctx.config.root);
if (codeFrame !== undefined) {
searchParams.append("code-frame", colors.stripAnsiCode(codeFrame));
}
}
} else {
searchParams.append("message", String(error));
}
return (
<iframe
id="fresh-error-overlay"
src={`${basePath}${DEV_ERROR_OVERLAY_URL}?${searchParams.toString()}`}
style="unset: all; position: fixed; top: 0; left: 0; z-index: 99999; width: 100%; height: 100%; border: none;"
/>
);
}
+54
View File
@@ -0,0 +1,54 @@
import type { ComponentChildren, VNode } from "preact";
import { BUILD_ID } from "./build_id.ts";
import { assetInternal, assetSrcSetInternal } from "./shared_internal.tsx";
/**
* Returns true when the current runtime is the browser and false otherwise. This is used for guard runtime-dependent code.
* Shorthand for the following:
* `typeof document !== "undefined"`
*
* @example
* ```
* if (IS_BROWSER) {
* alert('This is running in the browser!');
* } else {
* console.log('This code is running on the server, no access to window or alert');
* }
* ```
*
* Without this guard, alert pauses the server until return is pressed in the console.
*/
export const IS_BROWSER = typeof document !== "undefined";
/**
* Create a "locked" asset path. This differs from a plain path in that it is
* specific to the current version of the application, and as such can be safely
* served with a very long cache lifetime (1 year).
*/
export function asset(path: string): string {
return assetInternal(path, BUILD_ID);
}
/** Apply the `asset` function to urls in a `srcset` attribute. */
export function assetSrcSet(srcset: string): string {
return assetSrcSetInternal(srcset, BUILD_ID);
}
export interface PartialProps {
children?: ComponentChildren;
/**
* The name of the partial. This value must be unique across partials.
*/
name: string;
/**
* Define how the new HTML should be applied.
* @default {"replace"}
*/
mode?: "replace" | "prepend" | "append";
}
export function Partial(props: PartialProps): VNode {
// deno-lint-ignore no-explicit-any
return props.children as any;
}
Partial.displayName = "Partial";
+122
View File
@@ -0,0 +1,122 @@
import type { VNode } from "preact";
export const DATA_CURRENT = "data-current";
export const DATA_ANCESTOR = "data-ancestor";
export const DATA_FRESH_KEY = "data-frsh-key";
export const CLIENT_NAV_ATTR = "f-client-nav";
export const ASSET_CACHE_BUST_KEY = "__frsh_c";
export const enum UrlMatchKind {
None,
Ancestor,
Current,
}
export function matchesUrl(current: string, needle: string): UrlMatchKind {
let href = new URL(needle, "http://localhost").pathname;
if (href !== "/" && href.endsWith("/")) {
href = href.slice(0, -1);
}
if (current !== "/" && current.endsWith("/")) {
current = current.slice(0, -1);
}
if (current === href) {
return UrlMatchKind.Current;
} else if (current.startsWith(href + "/") || href === "/") {
return UrlMatchKind.Ancestor;
}
return UrlMatchKind.None;
}
/**
* Mark active or ancestor link
* Note: This function is used both on the server and the client
*/
export function setActiveUrl(vnode: VNode, pathname: string): void {
const props = vnode.props as Record<string, unknown>;
const hrefProp = props.href;
if (typeof hrefProp === "string" && hrefProp.startsWith("/")) {
const match = matchesUrl(pathname, hrefProp);
if (match === UrlMatchKind.Current) {
props[DATA_CURRENT] = "true";
props["aria-current"] = "page";
} else if (match === UrlMatchKind.Ancestor) {
props[DATA_ANCESTOR] = "true";
props["aria-current"] = "true";
}
}
}
export const enum PartialMode {
Replace,
Append,
Prepend,
}
/**
* Create a "locked" asset path. This differs from a plain path in that it is
* specific to the current version of the application, and as such can be safely
* served with a very long cache lifetime (1 year).
*/
export function assetInternal(path: string, buildId: string): string {
if (!path.startsWith("/") || path.startsWith("//")) return path;
try {
const url = new URL(path, "https://freshassetcache.local");
if (
url.protocol !== "https:" || url.host !== "freshassetcache.local" ||
url.searchParams.has(ASSET_CACHE_BUST_KEY)
) {
return path;
}
url.searchParams.set(ASSET_CACHE_BUST_KEY, buildId);
return url.pathname + url.search + url.hash;
} catch (err) {
console.warn(
`Failed to create asset() URL, falling back to regular path ('${path}'):`,
err,
);
return path;
}
}
/** Apply the `asset` function to urls in a `srcset` attribute. */
export function assetSrcSetInternal(srcset: string, buildId: string): string {
if (srcset.includes("(")) return srcset; // Bail if the srcset contains complicated syntax.
const parts = srcset.split(",");
const constructed = [];
for (const part of parts) {
const trimmed = part.trimStart();
const leadingWhitespace = part.length - trimmed.length;
if (trimmed === "") return srcset; // Bail if the srcset is malformed.
let urlEnd = trimmed.indexOf(" ");
if (urlEnd === -1) urlEnd = trimmed.length;
const leading = part.substring(0, leadingWhitespace);
const url = trimmed.substring(0, urlEnd);
const trailing = trimmed.substring(urlEnd);
constructed.push(leading + assetInternal(url, buildId) + trailing);
}
return constructed.join(",");
}
export function assetHashingHook(
vnode: VNode<{
src?: string;
srcset?: string;
["data-fresh-disable-lock"]?: boolean;
}>,
buildId: string,
) {
if (vnode.type === "img" || vnode.type === "source") {
const { props } = vnode;
if (props["data-fresh-disable-lock"]) return;
if (typeof props.src === "string") {
props.src = assetInternal(props.src, buildId);
}
if (typeof props.srcset === "string") {
props.srcset = assetSrcSetInternal(props.srcset, buildId);
}
}
}
-87
View File
@@ -1,87 +0,0 @@
import { VNode } from "preact";
import { BUILD_ID } from "./build_id.ts";
export const INTERNAL_PREFIX = "/_frsh";
export const ASSET_CACHE_BUST_KEY = "__frsh_c";
/**
* Returns true when the current runtime is the browser and false otherwise. This is used for guard runtime-dependent code.
* Shorthand for the following:
* `typeof document !== "undefined"`
*
* @example
* ```
* if (IS_BROWSER) {
* alert('This is running in the browser!');
* } else {
* console.log('This code is running on the server, no access to window or alert');
* }
* ```
*
* Without this guard, alert pauses the server until return is pressed in the console.
*/
export const IS_BROWSER = typeof document !== "undefined";
/**
* Create a "locked" asset path. This differs from a plain path in that it is
* specific to the current version of the application, and as such can be safely
* served with a very long cache lifetime (1 year).
*/
export function asset(path: string): string {
if (!path.startsWith("/") || path.startsWith("//")) return path;
try {
const url = new URL(path, "https://freshassetcache.local");
if (
url.protocol !== "https:" || url.host !== "freshassetcache.local" ||
url.searchParams.has(ASSET_CACHE_BUST_KEY)
) {
return path;
}
url.searchParams.set(ASSET_CACHE_BUST_KEY, BUILD_ID);
return url.pathname + url.search + url.hash;
} catch (err) {
console.warn(
`Failed to create asset() URL, falling back to regular path ('${path}'):`,
err,
);
return path;
}
}
/** Apply the `asset` function to urls in a `srcset` attribute. */
export function assetSrcSet(srcset: string): string {
if (srcset.includes("(")) return srcset; // Bail if the srcset contains complicated syntax.
const parts = srcset.split(",");
const constructed = [];
for (const part of parts) {
const trimmed = part.trimStart();
const leadingWhitespace = part.length - trimmed.length;
if (trimmed === "") return srcset; // Bail if the srcset is malformed.
let urlEnd = trimmed.indexOf(" ");
if (urlEnd === -1) urlEnd = trimmed.length;
const leading = part.substring(0, leadingWhitespace);
const url = trimmed.substring(0, urlEnd);
const trailing = trimmed.substring(urlEnd);
constructed.push(leading + asset(url) + trailing);
}
return constructed.join(",");
}
export function assetHashingHook(
vnode: VNode<{
src?: string;
srcset?: string;
["data-fresh-disable-lock"]?: boolean;
}>,
) {
if (vnode.type === "img" || vnode.type === "source") {
const { props } = vnode;
if (props["data-fresh-disable-lock"]) return;
if (typeof props.src === "string") {
props.src = asset(props.src);
}
if (typeof props.srcset === "string") {
props.srcset = assetSrcSet(props.srcset);
}
}
}
-59
View File
@@ -1,59 +0,0 @@
import { assertEquals } from "../../tests/deps.ts";
import { asset, assetSrcSet } from "./utils.ts";
import { BUILD_ID } from "./build_id.ts";
Deno.test("asset", () => {
assertEquals(asset("/test.png"), `/test.png?__frsh_c=${BUILD_ID}`);
assertEquals(asset("/test?f=1"), `/test?f=1&__frsh_c=${BUILD_ID}`);
assertEquals(asset("/test#foo"), `/test?__frsh_c=${BUILD_ID}#foo`);
assertEquals(asset("/test?f=1#foo"), `/test?f=1&__frsh_c=${BUILD_ID}#foo`);
assertEquals(asset("./test.png"), "./test.png");
assertEquals(asset("//example.com/logo.png"), "//example.com/logo.png");
assertEquals(asset("/test.png?__frsh_c=1"), "/test.png?__frsh_c=1");
assertEquals(
asset("https://example.com/logo.png"),
"https://example.com/logo.png",
);
});
Deno.test("assetSrcSet", () => {
assertEquals(assetSrcSet("/img.png"), `/img.png?__frsh_c=${BUILD_ID}`);
assertEquals(
assetSrcSet("/img.png, /img.png 2x"),
`/img.png?__frsh_c=${BUILD_ID}, /img.png?__frsh_c=${BUILD_ID} 2x`,
);
assertEquals(assetSrcSet("/img.png 1x"), `/img.png?__frsh_c=${BUILD_ID} 1x`);
assertEquals(
assetSrcSet("/img.png 1x, /img.png 2x"),
`/img.png?__frsh_c=${BUILD_ID} 1x, /img.png?__frsh_c=${BUILD_ID} 2x`,
);
assertEquals(
assetSrcSet("/img.png 1.5x, /img.png 3x"),
`/img.png?__frsh_c=${BUILD_ID} 1.5x, /img.png?__frsh_c=${BUILD_ID} 3x`,
);
//test with queries
assertEquals(
assetSrcSet("/img.png?w=140, /img.png?w=200 2x"),
`/img.png?w=140&__frsh_c=${BUILD_ID}, /img.png?w=200&__frsh_c=${BUILD_ID} 2x`,
);
// test with extra spaces
assertEquals(
assetSrcSet("/img-s.png 300w, /img-l.png 600w , /img-xl.png 900w"),
`/img-s.png?__frsh_c=${BUILD_ID} 300w, /img-l.png?__frsh_c=${BUILD_ID} 600w , /img-xl.png?__frsh_c=${BUILD_ID} 900w`,
);
// test with ( syntax
assertEquals(
assetSrcSet("/img.png ( 140,0w)"),
"/img.png ( 140,0w)",
);
// test with invalid parts
assertEquals(
assetSrcSet("/img.png,, /img-s.png 300w"),
"/img.png,, /img-s.png 300w",
);
});
@@ -1,58 +0,0 @@
export const snapshot = {};
snapshot[`createCodeFrame markers 1`] = `
"
1 | foo
> 2 | bar
| ^
3 | baz
"
`;
snapshot[`createCodeFrame markers 2`] = `
"
> 1 | foo
| ^
2 | bar
3 | baz
"
`;
snapshot[`createCodeFrame markers 3`] = `
"
1 | foo
2 | bar
> 3 | baz
| ^
"
`;
snapshot[`createCodeFrame markers 4`] = `
"
7 |
8 |
> 9 | bar
| ^
10 |
11 |
12 | bar
"
`;
snapshot[`createCodeFrame with indentation 1`] = `
"
1 | foo
> 2 | bar
| ^
3 | baz
"
`;
snapshot[`createCodeFrame with indentation 2`] = `
"
1 | foo
> 2 | bar
| ^
3 | baz
"
`;
@@ -1,31 +0,0 @@
export const snapshot = {};
snapshot[`serializer - primitives & plain objects 1`] = `'{"v":{"a":1,"b":"2","c":true,"d":null,"f":[1,2,3],"g":{"a":1,"b":2,"c":3}}}'`;
snapshot[`serializer - bigint 1`] = `'{"v":{"a":{"_f":"b","d":"999999999999999999"}}}'`;
snapshot[`serializer - Uint8Array 1`] = `'{"v":{"a":{"_f":"u8a","d":"AQID"}}}'`;
snapshot[`serializer - signals 1`] = `'{"v":{"a":1,"b":{"_f":"s","v":2}}}'`;
snapshot[`serializer - @preact/signals-core 1.2.3 1`] = `'{"v":{"a":1,"b":{"_f":"s","v":2}}}'`;
snapshot[`serializer - @preact/signals-core 1.3.0 1`] = `'{"v":{"a":1,"b":{"_f":"s","v":2}}}'`;
snapshot[`serializer - multiple versions of @preact/signals-core 1`] = `'{"v":{"a":1,"b":{"_f":"s","v":2},"c":{"_f":"s","v":2},"d":{"_f":"s","v":2}}}'`;
snapshot[`serializer - magic key 1`] = `'{"v":{"_f":"l","k":"f","v":{"a":1}}}'`;
snapshot[`serializer - circular reference objects 1`] = `'{"v":{"a":1,"b":0},"r":[[[],["b"]]]}'`;
snapshot[`serializer - circular reference nested objects 1`] = `'{"v":{"a":1,"b":{"c":2,"d":0}},"r":[[[],["b","d"]]]}'`;
snapshot[`serializer - circular reference array 1`] = `'{"v":[1,2,3,0],"r":[[[],["3"]]]}'`;
snapshot[`serializer - multiple reference 1`] = `'{"v":{"a":1,"b":{"c":2},"d":0},"r":[[["b"],["d"]]]}'`;
snapshot[`serializer - multiple reference signals 1`] = `'{"v":{"inner":{"_f":"l","k":"x","v":{"x":1,"y":0}},"a":{"_f":"s","v":0},"b":{"c":0}},"r":[[["inner"],["inner",null,"y"],["a","value"]],[["a"],["b","c"]]]}'`;
snapshot[`serializer - multiple reference in magic key 1`] = `'{"v":{"literal":{"_f":"l","k":"x","v":{"inner":{"foo":"bar"}}},"inner":0},"r":[[["literal",null,"inner"],["inner"]]]}'`;
snapshot[`serializer - multiple reference in signal 1`] = `'{"v":{"s":{"_f":"s","v":{"foo":"bar"}},"inner":0},"r":[[["s","value"],["inner"]]]}'`;
-125
View File
@@ -1,125 +0,0 @@
import { DENO_DEPLOYMENT_ID } from "./build_id.ts";
import { colors } from "./deps.ts";
import { ServeHandler } from "./types.ts";
const defaultOnListenFor = <T>(getAddress: (params: T) => string) => {
return (params: T) => {
const address = colors.cyan(
getAddress(params),
);
const localLabel = colors.bold("Local:");
// Print more concise output for deploy logs
if (DENO_DEPLOYMENT_ID) {
console.log(
colors.bgRgb8(colors.rgb8(" 🍋 Fresh ready ", 0), 121),
`${localLabel} ${address}`,
);
} else {
console.log();
console.log(
colors.bgRgb8(colors.rgb8(" 🍋 Fresh ready ", 0), 121),
);
console.log(` ${localLabel} ${address}\n`);
}
};
};
export async function startUnixServer(
handler: Deno.ServeUnixHandler,
opts: Deno.ServeUnixOptions,
) {
if (!opts.onListen) {
opts.onListen = defaultOnListenFor((params) => {
return `socket://${params.path}`;
});
// @ts-ignore Ignore type error when type checking with Deno versions
if (typeof Deno.serve === "function") {
await Deno.serve(
opts,
handler,
).finished;
}
throw new Error(
`unix domain sockets are not supported in your current deno version.`,
);
}
}
export async function startServer(
handler: Deno.ServeHandler,
opts: Partial<Deno.ServeTlsOptions> & { basePath: string },
) {
if (!opts.onListen) {
opts.onListen = defaultOnListenFor((params) => {
const pathname = opts.basePath + "/";
const https = !!(opts.key && opts.cert);
const protocol = https ? "https:" : "http:";
return `${protocol}//localhost:${params.port}${pathname}`;
});
}
const portEnv = Deno.env.get("PORT");
if (portEnv !== undefined) {
opts.port ??= parseInt(portEnv, 10);
}
if (opts.port) {
await bootServer(handler, opts);
} else {
// No port specified, check for a free port. Instead of picking just
// any port we'll check if the next one is free for UX reasons.
// That way the user only needs to increment a number when running
// multiple apps vs having to remember completely different ports.
let firstError;
for (let port = 8000; port < 8020; port++) {
try {
await bootServer(handler, { ...opts, port });
firstError = undefined;
break;
} catch (err) {
if (err instanceof Deno.errors.AddrInUse) {
// Throw first EADDRINUSE error
// if no port is free
if (!firstError) {
firstError = err;
}
continue;
}
throw err;
}
}
if (firstError) {
throw firstError;
}
}
}
async function bootServer(
handler: ServeHandler,
opts: Partial<Deno.ServeTlsOptions>,
) {
// @ts-ignore Ignore type error when type checking with Deno versions
if (typeof Deno.serve === "function") {
// @ts-ignore Ignore type error when type checking with Deno versions
await Deno.serve(
opts,
(r, info) =>
handler(
r,
{
...info,
remoteAddr: info.remoteAddr,
localAddr: {
transport: "tcp",
hostname: opts.hostname ?? "localhost",
port: opts.port,
} as Deno.NetAddr,
},
),
).finished;
} else {
// @ts-ignore Deprecated std serve way
await serve(handler, opts);
}
}
-17
View File
@@ -1,17 +0,0 @@
import { encodeHex } from "./deps.ts";
export const DENO_DEPLOYMENT_ID = Deno.env.get("DENO_DEPLOYMENT_ID");
const deploymentId = DENO_DEPLOYMENT_ID ||
// For CI
Deno.env.get("GITHUB_SHA") ||
crypto.randomUUID();
const buildIdHash = await crypto.subtle.digest(
"SHA-1",
new TextEncoder().encode(deploymentId),
);
export let BUILD_ID = encodeHex(buildIdHash);
export function setBuildId(buildId: string) {
BUILD_ID = buildId;
}
-57
View File
@@ -1,57 +0,0 @@
import { createCodeFrame, getFirstUserFile } from "./code_frame.ts";
import { assertEquals, assertSnapshot, colors } from "./deps.ts";
function testCodeFrame(text: string, line: number, column: number) {
const codeFrame = createCodeFrame(text, line, column);
if (codeFrame !== undefined) {
return "\n" + colors.stripColor(codeFrame);
}
return codeFrame;
}
const FILE = `file://example.com/foo.js`;
Deno.test("getFirstUserFile", () => {
let stack = `Some message
at asdf.foo (https://example.com/foo.js:8:20)
at asdf.foo (${FILE}:8:20)
`;
assertEquals(getFirstUserFile(stack), {
fnName: "asdf.foo",
file: FILE,
column: 20,
line: 8,
});
stack = `Some message
at asdf.foo (https://example.com/foo.js:8:20)
at (${FILE}:8:20)
`;
assertEquals(getFirstUserFile(stack), {
fnName: "",
file: FILE,
column: 20,
line: 8,
});
});
Deno.test("createCodeFrame invalid ranges", () => {
assertEquals(createCodeFrame("", 2, 10), undefined);
assertEquals(createCodeFrame("asdf", 2, 10), undefined);
assertEquals(createCodeFrame("asdf", 1, 10), undefined);
});
Deno.test("createCodeFrame markers", async (t) => {
await assertSnapshot(t, testCodeFrame("foo\nbar\nbaz", 1, 2));
await assertSnapshot(t, testCodeFrame("foo\nbar\nbaz", 0, 0));
await assertSnapshot(t, testCodeFrame("foo\nbar\nbaz", 2, 2));
await assertSnapshot(
t,
testCodeFrame("foo\n\n\n\n\n\n\n\nbar\n\n\nbar", 8, 0),
);
});
Deno.test("createCodeFrame with indentation", async (t) => {
await assertSnapshot(t, testCodeFrame("foo\n bar\nbaz", 1, 6));
await assertSnapshot(t, testCodeFrame("foo\n\t\tbar\nbaz", 1, 2));
});
-126
View File
@@ -1,126 +0,0 @@
import { SEPARATOR } from "./deps.ts";
import { ErrorHandler, FinalHandler, RouteResult, withBase } from "./router.ts";
import {
BaseRoute,
FreshContext,
MiddlewareRoute,
UnknownRenderFunction,
} from "./types.ts";
export const ROOT_BASE_ROUTE = toBaseRoute("/");
export function toBaseRoute(input: string): BaseRoute {
input = input.replaceAll(SEPARATOR, "/");
if (input.endsWith("_layout")) {
input = input.slice(0, -"_layout".length);
} else if (input.endsWith("_middleware")) {
input = input.slice(0, -"_middleware".length);
} else if (input.endsWith("index")) {
input = input.slice(0, -"index".length);
}
if (input.endsWith("/")) {
input = input.slice(0, -1);
}
const suffix = !input.startsWith("/") ? "/" : "";
return (suffix + input) as BaseRoute;
}
export function selectSharedRoutes<T extends { baseRoute: BaseRoute }>(
curBaseRoute: BaseRoute,
items: T[],
): T[] {
const selected: T[] = [];
for (const item of items) {
const { baseRoute } = item;
const res = curBaseRoute === baseRoute ||
curBaseRoute.startsWith(
baseRoute.length > 1 ? baseRoute + "/" : baseRoute,
);
if (res) {
selected.push(item);
}
}
return selected;
}
/**
* Identify which middlewares should be applied for a request,
* chain them and return a handler response
*/
export function composeMiddlewares(
middlewares: MiddlewareRoute[],
errorHandler: ErrorHandler,
paramsAndRoute: (
url: URL,
) => RouteResult,
renderNotFound: UnknownRenderFunction,
basePath: string,
) {
return (
req: Request,
ctx: FreshContext,
inner: FinalHandler,
) => {
const handlers: (() => Response | Promise<Response>)[] = [];
const paramsAndRouteResult = paramsAndRoute(ctx.url);
ctx.params = paramsAndRouteResult.params;
// identify middlewares to apply, if any.
// middlewares should be already sorted from deepest to shallow layer
const mws = selectSharedRoutes(
paramsAndRouteResult.route?.baseRoute ??
toBaseRoute(withBase(ROOT_BASE_ROUTE, basePath)),
middlewares,
);
if (paramsAndRouteResult.route) {
ctx.route = paramsAndRouteResult.route.originalPattern;
}
ctx.next = () => {
const handler = handlers.shift()!;
try {
// As the `handler` can be either sync or async, depending on the user's code,
// the current shape of our wrapper, that is `() => handler(req, middlewareCtx)`,
// doesn't guarantee that all possible errors will be captured.
// `Promise.resolve` accept the value that should be returned to the promise
// chain, however, if that value is produced by the external function call,
// the possible `Error`, will *not* be caught by any `.catch()` attached to that chain.
// Because of that, we need to make sure that the produced value is pushed
// through the pipeline only if function was called successfully, and handle
// the error case manually, by returning the `Error` as rejected promise.
return Promise.resolve(handler());
} catch (e) {
if (e instanceof Deno.errors.NotFound) {
return renderNotFound(req, ctx);
}
return Promise.reject(e);
}
};
for (const { module } of mws) {
if (module.handler instanceof Array) {
for (const handler of module.handler) {
handlers.push(() => handler(req, ctx));
}
} else {
const handler = module.handler;
handlers.push(() => handler(req, ctx));
}
}
const { destination, handler } = inner(
req,
ctx,
paramsAndRouteResult.route,
);
handlers.push(handler);
ctx.destination = destination;
return ctx.next().catch((e) => errorHandler(req, ctx, e));
};
}
-143
View File
@@ -1,143 +0,0 @@
import { dirname, fromFileUrl, isAbsolute, join, JSONC } from "./deps.ts";
import { FromManifestConfig, Manifest } from "./mod.ts";
import { DEFAULT_RENDER_FN } from "./render.ts";
import {
DenoConfig,
InternalFreshState,
ResolvedFreshConfig,
} from "./types.ts";
export async function readDenoConfig(
directory: string,
): Promise<{ config: DenoConfig; path: string }> {
let dir = directory;
while (true) {
for (const name of ["deno.json", "deno.jsonc"]) {
const path = join(dir, name);
try {
const file = await Deno.readTextFile(path);
if (name.endsWith(".jsonc")) {
return { config: JSONC.parse(file) as DenoConfig, path };
} else {
return { config: JSON.parse(file), path };
}
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
}
const parent = dirname(dir);
if (parent === dir) {
throw new Error(
`Could not find a deno.json file in the current directory or any parent directory.`,
);
}
dir = parent;
}
}
function isObject(value: unknown) {
return value !== null && typeof value === "object" &&
!Array.isArray(value);
}
export async function getInternalFreshState(
manifest: Manifest,
config: FromManifestConfig,
): Promise<InternalFreshState> {
const base = dirname(fromFileUrl(manifest.baseUrl));
const { config: denoJson, path: denoJsonPath } = await readDenoConfig(base);
if (typeof denoJson.importMap !== "string" && !isObject(denoJson.imports)) {
throw new Error(
"deno.json must contain an 'importMap' or 'imports' property.",
);
}
const isLegacyDev = Deno.env.get("__FRSH_LEGACY_DEV") === "true";
/**
* assume a basePath is declared like this:
* basePath: "/foo/bar"
* it must start with a slash, and not have a trailing slash
*/
let basePath = "";
if (config.router?.basePath) {
basePath = config.router?.basePath;
if (!basePath.startsWith("/")) {
throw new TypeError(
`"basePath" option must start with "/". Received: "${basePath}"`,
);
}
if (basePath.endsWith("/")) {
throw new TypeError(
`"basePath" option must not end with "/". Received: "${basePath}"`,
);
}
}
const internalConfig: ResolvedFreshConfig = {
dev: isLegacyDev || Boolean(config.dev),
build: {
outDir: config.build?.outDir
? parseFileOrUrl(config.build.outDir, base)
: join(base, "_fresh"),
target: config.build?.target ?? ["chrome99", "firefox99", "safari15"],
},
plugins: config.plugins ?? [],
staticDir: config.staticDir
? parseFileOrUrl(config.staticDir, base)
: join(base, "static"),
render: config.render ?? DEFAULT_RENDER_FN,
router: config.router,
server: config.server ?? {},
basePath,
};
if (config.cert) {
internalConfig.server.cert = config.cert;
}
if (config.hostname) {
internalConfig.server.hostname = config.hostname;
}
if (config.key) {
internalConfig.server.key = config.key;
}
if (config.onError) {
internalConfig.server.onError = config.onError;
}
if (config.onListen) {
internalConfig.server.onListen = config.onListen;
}
if (config.port) {
internalConfig.server.port = config.port;
}
if (config.reusePort) {
internalConfig.server.reusePort = config.reusePort;
}
if (config.signal) {
internalConfig.server.signal = config.signal;
}
return {
config: internalConfig,
manifest,
loadSnapshot: !isLegacyDev && !config.dev,
didLoadSnapshot: false,
denoJsonPath,
denoJson,
build: false,
};
}
function parseFileOrUrl(input: string, base: string) {
if (input.startsWith("file://")) {
return fromFileUrl(input);
} else if (!isAbsolute(input)) {
return join(base, input);
}
return input;
}
-12
View File
@@ -1,12 +0,0 @@
import { INTERNAL_PREFIX } from "../runtime/utils.ts";
import { BUILD_ID } from "./build_id.ts";
export const DEV_CLIENT_URL = `${INTERNAL_PREFIX}/fresh_dev_client.js`;
export const DEV_ERROR_OVERLAY_URL = `${INTERNAL_PREFIX}/error_overlay`;
export const ALIVE_URL = `${INTERNAL_PREFIX}/alive`;
export const JS_PREFIX = `/js`;
export const DEBUG = !Deno.env.get("DENO_DEPLOYMENT_ID");
export function bundleAssetUrl(path: string) {
return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`;
}
-831
View File
@@ -1,831 +0,0 @@
import { contentType, extname, SEPARATOR, STATUS_CODE } from "./deps.ts";
import * as router from "./router.ts";
import { FreshConfig, FreshContext, Manifest } from "./mod.ts";
import {
ALIVE_URL,
DEV_CLIENT_URL,
DEV_ERROR_OVERLAY_URL,
JS_PREFIX,
} from "./constants.ts";
import { BUILD_ID, DENO_DEPLOYMENT_ID } from "./build_id.ts";
import {
ErrorPage,
Handler,
InternalFreshState,
Island,
Plugin,
RenderFunction,
RenderOptions,
Route,
ServeHandlerInfo,
UnknownPage,
UnknownRenderFunction,
} from "./types.ts";
import { render as internalRender } from "./render.ts";
import {
ContentSecurityPolicy,
ContentSecurityPolicyDirectives,
SELF,
} from "../runtime/csp.ts";
import { ASSET_CACHE_BUST_KEY, INTERNAL_PREFIX } from "../runtime/utils.ts";
import { Builder, BuildSnapshot, EsbuildBuilder } from "../build/mod.ts";
import { setAllIslands } from "./rendering/preact_hooks.ts";
import { getCodeFrame } from "./code_frame.ts";
import { getInternalFreshState } from "./config.ts";
import {
composeMiddlewares,
ROOT_BASE_ROUTE,
selectSharedRoutes,
toBaseRoute,
} from "./compose.ts";
import { extractRoutes, FsExtractResult } from "./fs_extract.ts";
import { loadAotSnapshot } from "../build/aot_snapshot.ts";
import { ErrorOverlay } from "./error_overlay.tsx";
import { withBase } from "./router.ts";
import { PARTIAL_SEARCH_PARAM } from "../constants.ts";
import TailwindErrorPage from "./tailwind_aot_error_page.tsx";
// TODO: Completed type clashes in older Deno versions
// deno-lint-ignore no-explicit-any
const DEFAULT_CONN_INFO: any = {
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
};
// deno-lint-ignore no-explicit-any
const NOOP_COMPONENT = () => null as any;
const NOOP_NEXT = () => Promise.resolve(new Response(null, { status: 500 }));
/**
* @deprecated Use {@linkcode FromManifestConfig} instead
*/
export type FromManifestOptions = FromManifestConfig;
export type FromManifestConfig = FreshConfig & {
dev?: boolean;
};
export async function getServerContext(state: InternalFreshState) {
const { config, denoJson, denoJsonPath: configPath } = state;
if (config.dev) {
// Ensure that debugging hooks are set up for SSR rendering
await import("preact/debug");
}
// Plugins are already instantiated in build mode
if (!state.build) {
await Promise.all(
config.plugins.map((plugin) => plugin.configResolved?.(state.config)),
);
}
const extractResult = await extractRoutes(state);
// Restore snapshot if available
let snapshot: Builder | BuildSnapshot | Promise<BuildSnapshot> | null = null;
if (state.loadSnapshot) {
const loadedSnapshot = await loadAotSnapshot(config);
if (loadedSnapshot !== null) {
snapshot = loadedSnapshot;
state.didLoadSnapshot = true;
}
}
const finalSnapshot = snapshot ?? new EsbuildBuilder({
buildID: BUILD_ID,
entrypoints: collectEntrypoints(
config.dev,
extractResult.islands,
config.plugins,
),
configPath,
dev: config.dev,
jsx: denoJson.compilerOptions?.jsx,
jsxImportSource: denoJson.compilerOptions?.jsxImportSource,
target: state.config.build.target,
absoluteWorkingDir: Deno.cwd(),
basePath: state.config.basePath,
});
return new ServerContext(
state,
extractResult,
finalSnapshot,
);
}
export class ServerContext {
#renderFn: RenderFunction;
#plugins: Plugin[];
#builder: Builder | Promise<BuildSnapshot> | BuildSnapshot;
#state: InternalFreshState;
#extractResult: FsExtractResult;
#dev: boolean;
#revision = 0;
constructor(
state: InternalFreshState,
extractResult: FsExtractResult,
snapshot: Builder | BuildSnapshot | Promise<BuildSnapshot>,
) {
this.#state = state;
this.#extractResult = extractResult;
this.#renderFn = state.config.render;
this.#plugins = state.config.plugins;
this.#dev = state.config.dev;
this.#builder = snapshot;
}
/**
* Process the manifest into individual components and pages.
*/
static async fromManifest(
manifest: Manifest,
config: FromManifestConfig,
): Promise<ServerContext> {
const configWithDefaults = await getInternalFreshState(
manifest,
config,
);
return getServerContext(configWithDefaults);
}
/**
* This functions returns a request handler that handles all routes required
* by Fresh, including static files.
*/
handler(): (req: Request, connInfo?: ServeHandlerInfo) => Promise<Response> {
const basePath = this.#state.config.basePath;
const renderNotFound = createRenderNotFound(
this.#extractResult,
this.#dev,
this.#plugins,
this.#renderFn,
this.#maybeBuildSnapshot(),
);
const handlers = this.#handlers(renderNotFound);
const inner = router.router(handlers);
const withMiddlewares = composeMiddlewares(
this.#extractResult.middlewares,
handlers.errorHandler,
router.getParamsAndRoute(handlers),
renderNotFound,
basePath,
);
const trailingSlashEnabled = this.#state.config.router?.trailingSlash;
const isDev = this.#dev;
if (this.#dev) {
this.#revision = Date.now();
}
// deno-lint-ignore no-this-alias
const _self = this;
return async function handler(
req: Request,
connInfo: ServeHandlerInfo = DEFAULT_CONN_INFO,
) {
const url = new URL(req.url);
// Syntactically having double slashes in the pathname is valid per
// spec, but there is no behavior defined for that. Practically all
// servers normalize the pathname of a URL to not include double
// forward slashes.
url.pathname = url.pathname.replaceAll(/\/+/g, "/");
const aliveUrl = basePath + ALIVE_URL;
if (isDev) {
// Live reload: Send updates to browser
if (url.pathname === aliveUrl) {
if (req.headers.get("upgrade") !== "websocket") {
return new Response(null, { status: 501 });
}
// TODO: When a change is made the Deno server restarts,
// so for now the WebSocket connection is only used for
// the client to know when the server is back up. Once we
// have HMR we'll actively start sending messages back
// and forth.
const { response, socket } = Deno.upgradeWebSocket(req);
socket.addEventListener("open", () => {
socket.send(
JSON.stringify({
type: "initial-state",
revision: _self.#revision,
}),
);
});
return response;
} else if (
url.pathname === withBase(DEV_CLIENT_URL, basePath) ||
url.pathname === withBase(`${DEV_CLIENT_URL}.map`, basePath)
) {
const bundlePath = (url.pathname.endsWith(".map"))
? "fresh_dev_client.js.map"
: "fresh_dev_client.js";
return _self.#bundleAssetRoute(bundlePath);
}
}
// Redirect requests that end with a trailing slash to their non-trailing
// slash counterpart.
// Ex: /about/ -> /about
if (
url.pathname.length > 1 && url.pathname.endsWith("/") &&
!trailingSlashEnabled
) {
// Remove trailing slashes
const path = url.pathname.replace(/\/+$/, "");
const location = `${path}${url.search}`;
return new Response(null, {
status: STATUS_CODE.TemporaryRedirect,
headers: { location },
});
} else if (trailingSlashEnabled && !url.pathname.endsWith("/")) {
// If the last element of the path has a "." it's a file
const isFile = url.pathname.split("/").at(-1)?.includes(".");
// If the path uses the internal prefix, don't redirect it
const isInternal = url.pathname.startsWith(INTERNAL_PREFIX);
if (!isFile && !isInternal) {
url.pathname += "/";
return Response.redirect(url, STATUS_CODE.PermanentRedirect);
}
}
// Redirect to base path if not present in url
if (basePath && !url.pathname.startsWith(basePath)) {
const to = new URL(basePath + url.pathname, url.origin);
return Response.redirect(to, 302);
}
const ctx: FreshContext = {
url,
params: {},
config: _self.#state.config,
basePath: _self.#state.config.basePath,
localAddr: connInfo.localAddr,
remoteAddr: connInfo.remoteAddr,
state: {},
isPartial: url.searchParams.has(PARTIAL_SEARCH_PARAM),
destination: "route",
error: undefined,
codeFrame: undefined,
Component: NOOP_COMPONENT,
next: NOOP_NEXT,
render: NOOP_NEXT,
renderNotFound: async (data) => {
ctx.data = data;
return await renderNotFound(req, ctx);
},
route: "",
get pattern() {
return ctx.route;
},
data: undefined,
};
return await withMiddlewares(req, ctx, inner);
};
}
#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;
}
/**
* This function returns all routes required by Fresh as an extended
* path-to-regex, to handler mapping.
*/
#handlers(
renderNotFound: UnknownRenderFunction,
): {
internalRoutes: router.Routes;
staticRoutes: router.Routes;
routes: router.Routes;
otherHandler: router.Handler;
errorHandler: router.ErrorHandler;
} {
const internalRoutes: router.Routes = {};
const staticRoutes: router.Routes = {};
let routes: router.Routes = {};
const assetRoute = withBase(
`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`,
this.#state.config.basePath,
);
internalRoutes[assetRoute] = {
baseRoute: toBaseRoute(assetRoute),
methods: {
default: (_req, ctx) => this.#bundleAssetRoute(ctx.params.path),
},
};
// Add the static file routes.
// each files has 2 static routes:
// - one serving the file at its location without a "cache bursting" mechanism
// - one containing the BUILD_ID in the path that can be cached
for (
const { localUrl, path, size, contentType, etag } of this.#extractResult
.staticFiles
) {
staticRoutes[path.replaceAll(SEPARATOR, "/")] = {
baseRoute: toBaseRoute(path),
methods: {
"HEAD": this.#staticFileHandler(
localUrl,
size,
contentType,
etag,
),
"GET": this.#staticFileHandler(
localUrl,
size,
contentType,
etag,
),
},
};
}
// Tell renderer about all globally available islands
setAllIslands(this.#extractResult.islands);
const dependenciesFn = (path: string) => {
const snapshot = this.#maybeBuildSnapshot();
return snapshot?.dependencies(path) ?? [];
};
const genRender = <Data = undefined>(
route: Route<Data> | UnknownPage | ErrorPage,
status: number,
) => {
const imports: string[] = [];
if (this.#dev) imports.push(this.#state.config.basePath + DEV_CLIENT_URL);
return (
req: Request,
ctx: FreshContext,
error?: unknown,
codeFrame?: string,
) => {
return async (data?: Data, options?: RenderOptions) => {
if (route.component === undefined) {
throw new Error("This page does not have a component to render.");
}
const layouts = selectSharedRoutes(
route.baseRoute,
this.#extractResult.layouts,
);
ctx.error = error;
ctx.data = data;
const resp = await internalRender({
request: req,
context: ctx,
route,
plugins: this.#plugins,
app: this.#extractResult.app,
layouts,
imports,
dependenciesFn,
renderFn: this.#renderFn,
codeFrame,
});
if (resp instanceof Response) {
return resp;
}
return sendResponse(resp, {
status: options?.status ?? status,
statusText: options?.statusText,
headers: options?.headers,
isDev: this.#dev,
});
};
};
};
for (const route of this.#extractResult.routes) {
if (
this.#state.config.router?.trailingSlash && route.pattern != "/"
) {
route.pattern += "/";
}
const createRender = genRender(route, STATUS_CODE.OK);
if (typeof route.handler === "function") {
routes[route.pattern] = {
baseRoute: route.baseRoute,
methods: {
default: (req, ctx) => {
ctx.render = createRender(req, ctx);
return (route.handler as Handler)(req, ctx);
},
},
};
} else {
routes[route.pattern] = {
baseRoute: route.baseRoute,
methods: {},
};
for (const [method, handler] of Object.entries(route.handler)) {
routes[route.pattern].methods[method as router.KnownMethod] = (
req,
ctx,
) => {
ctx.render = createRender(req, ctx);
return handler(req, ctx);
};
}
}
}
let otherHandler: router.Handler = (req, ctx) => {
ctx.render = (data) => {
ctx.data = data;
return renderNotFound(req, ctx);
};
return this.#extractResult.notFound.handler(req, ctx);
};
const errorHandlerRender = genRender(
this.#extractResult.error,
STATUS_CODE.InternalServerError,
);
const errorHandler: router.ErrorHandler = async (
req,
ctx,
error,
) => {
console.error(
"%cAn error occurred during route handling or page rendering.",
"color:red",
);
let codeFrame: string | undefined;
if (this.#dev && error instanceof Error) {
codeFrame = await getCodeFrame(error);
if (codeFrame) {
console.error();
console.error(codeFrame);
}
}
console.error(error);
ctx.error = error;
ctx.render = errorHandlerRender(req, ctx, error, codeFrame);
return this.#extractResult.error.handler(req, ctx);
};
if (this.#dev) {
const devErrorUrl = withBase(
DEV_ERROR_OVERLAY_URL,
this.#state.config.basePath,
);
const baseRoute = toBaseRoute(devErrorUrl);
internalRoutes[devErrorUrl] = {
baseRoute,
methods: {
default: async (req, ctx) => {
const resp = await internalRender({
request: req,
context: ctx,
route: {
component: ErrorOverlay,
inheritLayouts: false,
appWrapper: false,
csp: false,
url: req.url,
name: "error overlay route",
handler: (_req: Request, ctx: FreshContext) => ctx.render(),
baseRoute,
pattern: baseRoute,
},
plugins: this.#plugins,
app: this.#extractResult.app,
layouts: [],
imports: [],
dependenciesFn: () => [],
renderFn: this.#renderFn,
codeFrame: undefined,
});
if (resp instanceof Response) {
return resp;
}
return sendResponse(resp, {
status: 200,
isDev: this.#dev,
statusText: undefined,
headers: undefined,
});
},
},
};
}
// This page is shown when the user uses the tailwindcss plugin and
// hasn't configured AOT builds.
if (
!this.#state.config.dev &&
this.#state.loadSnapshot && !this.#state.didLoadSnapshot &&
this.#state.config.plugins.some((plugin) => plugin.name === "tailwind")
) {
if (DENO_DEPLOYMENT_ID !== undefined) {
// Don't fail hard here and instead rewrite all routes to a special
// error route. Otherwise the first user experience of deploying a
// Fresh project would be pretty disruptive
console.error(
"%cError: Ahead of time builds not configured but required by the tailwindcss plugin.\nTo resolve this error, set up ahead of time builds: https://fresh.deno.dev/docs/concepts/ahead-of-time-builds",
"color: red",
);
console.log();
// Clear all routes so that everything redirects to the tailwind
// error page.
routes = {};
const freshErrorPage = genRender({
appWrapper: false,
inheritLayouts: false,
component: TailwindErrorPage,
csp: false,
name: "tailwind_error_route",
pattern: "*",
url: "",
baseRoute: toBaseRoute("*"),
handler: (_req: Request, ctx: FreshContext) => ctx.render(),
}, STATUS_CODE.InternalServerError);
otherHandler = (req, ctx) => {
const render = freshErrorPage(req, ctx);
return render();
};
} else {
// Not on Deno Deploy. The user likely forgot to run `deno task build`
console.warn(
'%cNo pre-compiled tailwind styles found.\n\nDid you forget to run "deno task build" prior to starting the production server?',
"color: yellow",
);
}
}
return { internalRoutes, staticRoutes, routes, otherHandler, errorHandler };
}
#staticFileHandler(
localUrl: URL,
size: number,
contentType: string,
etag: string,
): router.MatchHandler {
return async (req: Request) => {
const url = new URL(req.url);
const key = url.searchParams.get(ASSET_CACHE_BUST_KEY);
if (key !== null && BUILD_ID !== key) {
url.searchParams.delete(ASSET_CACHE_BUST_KEY);
const location = url.pathname + url.search;
return new Response(null, {
status: 307,
headers: {
location,
},
});
}
const headers = new Headers({
"content-type": contentType,
etag,
vary: "If-None-Match",
});
if (key !== null) {
headers.set("Cache-Control", "public, max-age=31536000, immutable");
}
const ifNoneMatch = req.headers.get("if-none-match");
if (ifNoneMatch === etag || ifNoneMatch === "W/" + etag) {
return new Response(null, { status: 304, headers });
} else if (req.method === "HEAD") {
headers.set("content-length", String(size));
return new Response(null, { status: 200, headers });
} else {
const file = await Deno.open(localUrl);
headers.set("content-length", String(size));
return new Response(file.readable, { headers });
}
};
}
async #bundleAssetRoute(filePath: string) {
const snapshot = await this.buildSnapshot();
const contents = await snapshot.read(filePath);
if (!contents) return new Response(null, { status: 404 });
const headers: Record<string, string> = {
"Cache-Control": this.#dev
? "no-cache, no-store, max-age=0, must-revalidate"
: "public, max-age=604800, immutable",
};
const type = contentType(extname(filePath));
if (type) headers["Content-Type"] = type;
return new Response(contents, {
status: 200,
headers,
});
}
}
const createRenderNotFound = (
extractResult: FsExtractResult,
dev: boolean,
plugins: Plugin<Record<string, unknown>>[],
renderFunction: RenderFunction,
buildSnapshot: BuildSnapshot | null,
): UnknownRenderFunction => {
const dependenciesFn = (path: string) => {
const snapshot = buildSnapshot;
return snapshot?.dependencies(path) ?? [];
};
return async (req, ctx) => {
const notFound = extractResult.notFound;
if (!notFound.component) {
return sendResponse(["Not found.", "", undefined], {
status: STATUS_CODE.NotFound,
isDev: dev,
statusText: undefined,
headers: undefined,
});
}
const layouts = selectSharedRoutes(
ROOT_BASE_ROUTE,
extractResult.layouts,
);
const imports: string[] = [];
const resp = await internalRender({
request: req,
context: ctx,
route: notFound,
plugins: plugins,
app: extractResult.app,
layouts,
imports,
dependenciesFn,
renderFn: renderFunction,
});
if (resp instanceof Response) {
return resp;
}
return sendResponse(resp, {
status: STATUS_CODE.NotFound,
isDev: dev,
statusText: undefined,
headers: undefined,
});
};
};
// Normalize a path for use in a URL. Returns null if the path is unparsable.
export function normalizeURLPath(path: string): string | null {
try {
const pathUrl = new URL("file:///");
pathUrl.pathname = path;
return pathUrl.pathname;
} catch {
return null;
}
}
function serializeCSPDirectives(csp: ContentSecurityPolicyDirectives): string {
return Object.entries(csp)
.filter(([_key, value]) => value !== undefined)
.map(([k, v]: [string, string | string[]]) => {
// Turn camel case into snake case.
const key = k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
const value = Array.isArray(v) ? v.join(" ") : v;
return `${key} ${value}`;
})
.join("; ");
}
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`),
};
if (dev) {
entryPoints.fresh_dev_client = import.meta.resolve(
`${entrypointBase}/client.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.name}`] = island.url;
}
for (const plugin of plugins) {
for (const [name, url] of Object.entries(plugin.entrypoints ?? {})) {
entryPoints[`plugin-${plugin.name}-${name}`] = url;
}
}
return entryPoints;
}
function sendResponse(
resp: [string, string, ContentSecurityPolicy | undefined],
options: {
status: number;
statusText: string | undefined;
headers?: HeadersInit;
isDev: boolean;
},
) {
const [body, uuid, csp] = resp;
const headers: Headers = new Headers({
"content-type": "text/html; charset=utf-8",
"x-fresh-uuid": uuid,
});
if (csp) {
if (options.isDev) {
csp.directives.connectSrc = [
...(csp.directives.connectSrc ?? []),
SELF,
];
}
const directive = serializeCSPDirectives(csp.directives);
if (csp.reportOnly) {
headers.set("content-security-policy-report-only", directive);
} else {
headers.set("content-security-policy", directive);
}
}
if (options.headers) {
if (Array.isArray(options.headers)) {
for (const [key, value] of options.headers) {
headers.append(key, value);
}
} else if (options.headers instanceof Headers) {
options.headers.forEach((value, key) => {
headers.append(key, value);
});
} else {
for (const [key, value] of Object.entries(options.headers)) {
headers.append(key, value);
}
}
}
return new Response(body, {
status: options.status,
statusText: options.statusText,
headers,
});
}
-11
View File
@@ -1,11 +0,0 @@
export default function DefaultErrorPage() {
return (
<div class="frsh-error-page">
<div style="max-width: 48rem; padding: 2rem 1rem; margin: 0 auto; font-family: sans-serif">
<h1>
An error occurred during route handling or page rendering.
</h1>
</div>
</div>
);
}
-48
View File
@@ -1,48 +0,0 @@
import { ComponentChildren } from "preact";
import { AsyncLayout, AsyncRoute, FreshConfig, RouteContext } from "./types.ts";
import { checkAsyncComponent } from "./render.ts";
export function defineConfig(config: FreshConfig): FreshConfig {
return config;
}
// Route creation helpers
export function defineRoute<
T,
>(
fn: (
req: Request,
ctx: RouteContext<void, T>,
) => ComponentChildren | Response | Promise<ComponentChildren | Response>,
): AsyncRoute<void, T> {
// deno-lint-ignore no-explicit-any
if (checkAsyncComponent(fn)) return fn as any;
// deno-lint-ignore require-await
return async (req, ctx) => fn(req, ctx);
}
// Layout creation helper
export function defineLayout<T>(
fn: (
req: Request,
ctx: RouteContext<void, T>,
) => ComponentChildren | Response | Promise<ComponentChildren | Response>,
): AsyncLayout<void, T> {
// deno-lint-ignore no-explicit-any
if (checkAsyncComponent(fn)) return fn as any;
// deno-lint-ignore require-await
return async (req, ctx) => fn(req, ctx);
}
// App creation helper
export function defineApp<T>(
fn: (
req: Request,
ctx: RouteContext<void, T>,
) => ComponentChildren | Response | Promise<ComponentChildren | Response>,
): AsyncLayout<void, T> {
// deno-lint-ignore no-explicit-any
if (checkAsyncComponent(fn)) return fn as any;
// deno-lint-ignore require-await
return async (req, ctx) => fn(req, ctx);
}
-35
View File
@@ -1,35 +0,0 @@
// -- std --
export {
basename,
dirname,
extname,
fromFileUrl,
isAbsolute,
join,
SEPARATOR,
toFileUrl,
} from "https://deno.land/std@0.216.0/path/mod.ts";
export { walk } from "https://deno.land/std@0.216.0/fs/walk.ts";
export * as colors from "https://deno.land/std@0.216.0/fmt/colors.ts";
export {
type Handler as ServeHandler,
serve,
} from "https://deno.land/std@0.216.0/http/server.ts";
export { STATUS_CODE } from "https://deno.land/std@0.216.0/http/status.ts";
export {
contentType,
} from "https://deno.land/std@0.216.0/media_types/content_type.ts";
export { encodeHex } from "https://deno.land/std@0.216.0/encoding/hex.ts";
export { escape } from "https://deno.land/std@0.216.0/regexp/escape.ts";
export * as JSONC from "https://deno.land/std@0.216.0/jsonc/mod.ts";
export { renderToString } from "https://esm.sh/*preact-render-to-string@6.3.1";
export {
assertEquals,
assertThrows,
} from "https://deno.land/std@0.216.0/assert/mod.ts";
export {
isIdentifierChar,
isIdentifierStart,
} from "https://esm.sh/@babel/helper-validator-identifier@7.22.20";
export { normalize } from "https://deno.land/std@0.216.0/path/posix/mod.ts";
export { assertSnapshot } from "https://deno.land/std@0.216.0/testing/snapshot.ts";
-565
View File
@@ -1,565 +0,0 @@
import { ComponentType, h } from "preact";
import {
AppModule,
ErrorPage,
ErrorPageModule,
InternalFreshState,
Island,
IslandModule,
LayoutModule,
LayoutRoute,
MiddlewareHandler,
MiddlewareModule,
MiddlewareRoute,
Plugin,
Route,
RouteModule,
StaticFile,
UnknownPage,
UnknownPageModule,
} from "./types.ts";
import * as router from "./router.ts";
import DefaultErrorHandler from "./default_error_page.tsx";
import {
basename,
contentType,
dirname,
extname,
join,
SEPARATOR,
toFileUrl,
walk,
} from "./deps.ts";
import { BUILD_ID } from "./build_id.ts";
import { toBaseRoute } from "./compose.ts";
import { stringToIdentifier } from "./init_safe_deps.ts";
export const ROOT_BASE_ROUTE = toBaseRoute("/");
const DEFAULT_APP: AppModule = {
default: ({ Component }: { Component: ComponentType }) => h(Component, {}),
};
const DEFAULT_NOT_FOUND: UnknownPage = {
baseRoute: toBaseRoute("/"),
pattern: "",
url: "",
name: "_404",
handler: (req) => router.defaultOtherHandler(req),
csp: false,
appWrapper: true,
inheritLayouts: true,
};
const DEFAULT_ERROR: ErrorPage = {
baseRoute: toBaseRoute("/"),
pattern: "",
url: "",
name: "_500",
component: DefaultErrorHandler,
handler: (_req, ctx) => ctx.render(),
csp: false,
appWrapper: true,
inheritLayouts: true,
};
export interface FsExtractResult {
app: AppModule;
layouts: LayoutRoute[];
notFound: UnknownPage;
error: ErrorPage;
middlewares: MiddlewareRoute[];
islands: Island[];
routes: Route[];
staticFiles: StaticFile[];
}
/**
* Extract all routes, and prepare them into the `Page` structure.
*/
export async function extractRoutes(
state: InternalFreshState,
): Promise<FsExtractResult> {
const { config, manifest } = state;
// Get the manifest' base URL.
const baseUrl = new URL("./", manifest.baseUrl).href;
const routes: Route[] = [];
const islands: Island[] = [];
const middlewares: MiddlewareRoute[] = [];
let app: AppModule = DEFAULT_APP;
const layouts: LayoutRoute[] = [];
let notFound: UnknownPage = DEFAULT_NOT_FOUND;
let error: ErrorPage = DEFAULT_ERROR;
const allRoutes = [
...Object.entries(manifest.routes),
...(config.plugins ? getMiddlewareRoutesFromPlugins(config.plugins) : []),
...(config.plugins ? getRoutesFromPlugins(config.plugins) : []),
];
// Presort all routes so that we only need to sort once
allRoutes.sort((a, b) => sortRoutePaths(a[0], b[0]));
for (
const [self, module] of allRoutes
) {
const url = new URL(self, baseUrl).href;
if (!url.startsWith(baseUrl + "routes")) {
throw new TypeError("Page is not a child of the basepath.");
}
const path = url.substring(baseUrl.length + "routes".length);
let baseRoute = path.substring(1, path.length - extname(path).length);
baseRoute = join(state.config.basePath.slice(1), baseRoute).replaceAll(
SEPARATOR,
"/",
);
const name = baseRoute.replace(/\//g, "-");
const isLayout = path.endsWith("/_layout.tsx") ||
path.endsWith("/_layout.ts") || path.endsWith("/_layout.jsx") ||
path.endsWith("/_layout.js");
const isMiddleware = path.endsWith("/_middleware.tsx") ||
path.endsWith("/_middleware.ts") || path.endsWith("/_middleware.jsx") ||
path.endsWith("/_middleware.js");
if (
!path.startsWith("/_") && !isLayout && !isMiddleware
) {
const { default: component, config } = module as RouteModule;
let pattern = pathToPattern(baseRoute);
if (config?.routeOverride) {
pattern = String(config.routeOverride);
}
let { handler } = module as RouteModule;
if (!handler && "handlers" in module) {
throw new Error(
`Found named export "handlers" in ${self} instead of "handler". Did you mean "handler"?`,
);
}
handler ??= {};
if (
component && typeof handler === "object" && handler.GET === undefined
) {
handler.GET = (_req, { render }) => render();
}
if (
typeof handler === "object" && handler.GET !== undefined &&
handler.HEAD === undefined
) {
const GET = handler.GET;
handler.HEAD = async (req, ctx) => {
const resp = await GET(req, ctx);
resp.body?.cancel();
return new Response(null, {
headers: resp.headers,
status: resp.status,
statusText: resp.statusText,
});
};
}
const route: Route = {
baseRoute: toBaseRoute(baseRoute),
pattern,
url,
name,
component,
handler,
csp: Boolean(config?.csp ?? false),
appWrapper: !config?.skipAppWrapper,
inheritLayouts: !config?.skipInheritedLayouts,
};
routes.push(route);
} else if (isMiddleware) {
middlewares.push({
baseRoute: toBaseRoute(baseRoute),
module: module as MiddlewareModule,
});
} else if (
path === "/_app.tsx" || path === "/_app.ts" ||
path === "/_app.jsx" || path === "/_app.js"
) {
app = module as AppModule;
} else if (isLayout) {
const mod = module as LayoutModule;
const config = mod.config;
layouts.push({
baseRoute: toBaseRoute(baseRoute),
handler: mod.handler,
component: mod.default,
appWrapper: !config?.skipAppWrapper,
inheritLayouts: !config?.skipInheritedLayouts,
});
} else if (
path === "/_404.tsx" || path === "/_404.ts" ||
path === "/_404.jsx" || path === "/_404.js"
) {
const { default: component, config } = module as UnknownPageModule;
let { handler } = module as UnknownPageModule;
if (component && handler === undefined) {
handler = (_req, { render }) => render();
}
notFound = {
baseRoute: ROOT_BASE_ROUTE,
pattern: pathToPattern(baseRoute),
url,
name,
component,
handler: handler ?? ((req) => router.defaultOtherHandler(req)),
csp: Boolean(config?.csp ?? false),
appWrapper: !config?.skipAppWrapper,
inheritLayouts: !config?.skipInheritedLayouts,
};
} else if (
path === "/_500.tsx" || path === "/_500.ts" ||
path === "/_500.jsx" || path === "/_500.js"
) {
const { default: component, config: routeConfig } =
module as ErrorPageModule;
let { handler } = module as ErrorPageModule;
if (component && handler === undefined) {
handler = (_req, { render }) => render();
}
error = {
baseRoute: toBaseRoute("/"),
pattern: pathToPattern(baseRoute),
url,
name,
component,
handler: handler ?? router.defaultErrorHandler,
csp: Boolean(routeConfig?.csp ?? false),
appWrapper: !routeConfig?.skipAppWrapper,
inheritLayouts: !routeConfig?.skipInheritedLayouts,
};
}
}
const processedIslands: {
name: string;
path: string;
module: IslandModule;
}[] = [];
for (const plugin of config.plugins || []) {
if (!plugin.islands) continue;
const base = dirname(plugin.islands.baseLocation);
for (const specifier of plugin.islands.paths) {
const full = join(base, specifier);
const module = await import(full);
const name = sanitizeIslandName(basename(full, extname(full)));
processedIslands.push({
name,
path: full,
module,
});
}
}
for (const [self, module] of Object.entries(manifest.islands)) {
const url = new URL(self, baseUrl).href;
if (!url.startsWith(baseUrl)) {
throw new TypeError("Island is not a child of the basepath.");
}
let path = url.substring(baseUrl.length);
if (path.startsWith("islands")) {
path = path.slice("islands".length + 1);
}
const baseRoute = path.substring(0, path.length - extname(path).length);
processedIslands.push({
name: sanitizeIslandName(baseRoute),
path: url,
module,
});
}
for (const processedIsland of processedIslands) {
for (
const [exportName, exportedFunction] of Object.entries(
processedIsland.module,
)
) {
if (typeof exportedFunction !== "function") continue;
const name = processedIsland.name.toLowerCase();
const id = `${name}_${exportName.toLowerCase()}`;
islands.push({
id,
name,
url: processedIsland.path,
// deno-lint-ignore no-explicit-any
component: exportedFunction as ComponentType<any>,
exportName,
});
}
}
const staticFiles: StaticFile[] = [];
try {
const staticDirs = [config.staticDir];
// Only fall through to files in /_fresh/static when not in dev
if (state.loadSnapshot) {
const outDirStatic = join(config.build.outDir, "static");
staticDirs.push(outDirStatic);
}
for (const staticDir of staticDirs) {
const staticDirUrl = toFileUrl(staticDir);
const entries = walk(staticDir, {
includeFiles: true,
includeDirs: false,
followSymlinks: false,
});
const encoder = new TextEncoder();
for await (const entry of entries) {
const localUrl = toFileUrl(entry.path);
const path = localUrl.href.substring(staticDirUrl.href.length);
const stat = await Deno.stat(localUrl);
const type = contentType(extname(path)) ??
"application/octet-stream";
const etag = await crypto.subtle.digest(
"SHA-1",
encoder.encode(BUILD_ID + path),
).then((hash) =>
Array.from(new Uint8Array(hash))
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("")
);
const staticFile: StaticFile = {
localUrl,
path: join(state.config.basePath, path),
size: stat.size,
contentType: type,
etag,
};
staticFiles.push(staticFile);
}
}
} catch (err) {
if (err.cause instanceof Deno.errors.NotFound) {
// Do nothing.
} else {
throw err;
}
}
return {
app,
error,
islands,
layouts,
middlewares,
notFound,
routes,
staticFiles,
};
}
const APP_REG = /_app\.[tj]sx?$/;
/**
* Sort route paths where special Fresh files like `_app`,
* `_layout` and `_middleware` are sorted in front.
*/
export function sortRoutePaths(a: string, b: string) {
// The `_app` route should always be the first
if (APP_REG.test(a)) return -1;
else if (APP_REG.test(b)) return 1;
let segmentIdx = 0;
const aLen = a.length;
const bLen = b.length;
const maxLen = aLen > bLen ? aLen : bLen;
for (let i = 0; i < maxLen; i++) {
const charA = a.charAt(i);
const charB = b.charAt(i);
const nextA = i + 1 < aLen ? a.charAt(i + 1) : "";
const nextB = i + 1 < bLen ? b.charAt(i + 1) : "";
if (charA === "/" || charB === "/") {
segmentIdx = i;
// If the other path doesn't close the segment
// then we don't need to continue
if (charA !== "/") return -1;
if (charB !== "/") return 1;
continue;
}
if (i === segmentIdx + 1) {
const scoreA = getRoutePathScore(charA, nextA);
const scoreB = getRoutePathScore(charB, nextB);
if (scoreA === scoreB) continue;
return scoreA > scoreB ? -1 : 1;
}
}
return 0;
}
/**
* Assign a score based on the first two characters of a path segment.
* The goal is to sort `_middleware` and `_layout` in front of everything
* and `[` or `[...` last respectively.
*/
function getRoutePathScore(char: string, nextChar: string): number {
if (char === "_") {
if (nextChar === "m") return 4;
return 3;
} else if (char === "[") {
if (nextChar === ".") {
return 0;
}
return 1;
}
return 2;
}
/**
* Transform a filesystem URL path to a `path-to-regex` style matcher. */
export function pathToPattern(path: string): string {
const parts = path.split("/");
if (parts[parts.length - 1] === "index") {
if (parts.length === 1) {
return "/";
}
parts.pop();
}
let route = "";
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
// Case: /[...foo].tsx
if (part.startsWith("[...") && part.endsWith("]")) {
route += `/:${part.slice(4, part.length - 1)}*`;
continue;
}
// Route groups like /foo/(bar) should not be included in URL
// matching. They are transparent and need to be removed here.
// Case: /foo/(bar) -> /foo
// Case: /foo/(bar)/bob -> /foo/bob
// Case: /(foo)/bar -> /bar
if (part.startsWith("(") && part.endsWith(")")) {
continue;
}
// Disallow neighbouring params like `/[id][bar].tsx` because
// it's ambiguous where the `id` param ends and `bar` begins.
if (part.includes("][")) {
throw new SyntaxError(
`Invalid route pattern: "${path}". A parameter cannot be followed by another parameter without any characters in between.`,
);
}
// Case: /[[id]].tsx
// Case: /[id].tsx
// Case: /[id]@[bar].tsx
// Case: /[id]-asdf.tsx
// Case: /[id]-asdf[bar].tsx
// Case: /asdf[bar].tsx
let pattern = "";
let groupOpen = 0;
let optional = false;
for (let j = 0; j < part.length; j++) {
const char = part[j];
if (char === "[") {
if (part[j + 1] === "[") {
// Disallow optional dynamic params like `foo-[[bar]]`
if (part[j - 1] !== "/" && !!part[j - 1]) {
throw new SyntaxError(
`Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`,
);
}
groupOpen++;
optional = true;
pattern += "{/";
j++;
}
pattern += ":";
groupOpen++;
} else if (char === "]") {
if (part[j + 1] === "]") {
// Disallow optional dynamic params like `[[foo]]-bar`
if (part[j + 2] !== "/" && !!part[j + 2]) {
throw new SyntaxError(
`Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`,
);
}
groupOpen--;
pattern += "}?";
j++;
}
if (--groupOpen < 0) {
throw new SyntaxError(`Invalid route pattern: "${path}"`);
}
} else {
pattern += char;
}
}
route += (optional ? "" : "/") + pattern;
}
// Case: /(group)/index.tsx
if (route === "") {
route = "/";
}
return route;
}
function toPascalCase(text: string): string {
return text.replace(
/(^\w|-\w)/g,
(substring) => substring.replace(/-/, "").toUpperCase(),
);
}
function sanitizeIslandName(name: string): string {
const fileName = stringToIdentifier(name);
return toPascalCase(fileName);
}
function formatMiddlewarePath(path: string): string {
const prefix = !path.startsWith("/") ? "/" : "";
const suffix = !path.endsWith("/") ? "/" : "";
return prefix + path + suffix;
}
function getMiddlewareRoutesFromPlugins(
plugins: Plugin[],
): [string, MiddlewareModule][] {
const middlewares = plugins.flatMap((plugin) => plugin.middlewares ?? []);
const mws: Record<
string,
[string, { handler: MiddlewareHandler[] }]
> = {};
for (let i = 0; i < middlewares.length; i++) {
const mw = middlewares[i];
const handler = mw.middleware.handler;
const key = `./routes${formatMiddlewarePath(mw.path)}_middleware.ts`;
if (!mws[key]) mws[key] = [key, { handler: [] }];
mws[key][1].handler.push(...Array.isArray(handler) ? handler : [handler]);
}
return Object.values(mws);
}
function formatRoutePath(path: string) {
return path.startsWith("/") ? path : "/" + path;
}
function getRoutesFromPlugins(plugins: Plugin[]): [string, RouteModule][] {
return plugins.flatMap((plugin) => plugin.routes ?? [])
.map((route) => {
return [`./routes${formatRoutePath(route.path)}.ts`, {
// deno-lint-ignore no-explicit-any
default: route.component as any,
handler: route.handler,
}];
});
}
-79
View File
@@ -1,79 +0,0 @@
import { assertEquals, assertThrows } from "./deps.ts";
import { pathToPattern, sortRoutePaths } from "./fs_extract.ts";
Deno.test("pathToPattern", async (t) => {
await t.step("creates pattern", () => {
assertEquals(pathToPattern("foo/bar"), "/foo/bar");
});
await t.step("parses index routes", () => {
assertEquals(pathToPattern("foo/index"), "/foo");
});
await t.step("parses parameters", () => {
assertEquals(pathToPattern("foo/[name]"), "/foo/:name");
assertEquals(pathToPattern("foo/[name]/bar/[bob]"), "/foo/:name/bar/:bob");
});
await t.step("parses catchall", () => {
assertEquals(pathToPattern("foo/[...name]"), "/foo/:name*");
});
await t.step("parses multiple params in same part", () => {
assertEquals(pathToPattern("foo/[mod]@[version]"), "/foo/:mod@:version");
assertEquals(pathToPattern("foo/[bar].json"), "/foo/:bar.json");
assertEquals(pathToPattern("foo/foo[bar]"), "/foo/foo:bar");
});
await t.step("parses optional params", () => {
assertEquals(pathToPattern("foo/[[name]]"), "/foo{/:name}?");
assertEquals(pathToPattern("foo/[name]/[[bob]]"), "/foo/:name{/:bob}?");
assertEquals(pathToPattern("foo/[[name]]/bar"), "/foo{/:name}?/bar");
assertEquals(
pathToPattern("foo/[[name]]/bar/[[bob]]"),
"/foo{/:name}?/bar{/:bob}?",
);
});
await t.step("throws on invalid patterns", () => {
assertThrows(() => pathToPattern("foo/[foo][bar]"));
assertThrows(() => pathToPattern("foo/foo]"));
assertThrows(() => pathToPattern("foo/[foo]]"));
assertThrows(() => pathToPattern("foo/foo-[[name]]-bar/baz"));
assertThrows(() => pathToPattern("foo/[[name]]-bar/baz"));
assertThrows(() => pathToPattern("foo/foo-[[name]]/baz"));
assertThrows(() => pathToPattern("foo/foo-[[name]]"));
assertThrows(() => pathToPattern("foo/[[name]]-bar"));
});
});
Deno.test("sortRoutePaths", () => {
const routes = [
"/foo/[id]",
"/foo/[...slug]",
"/foo/bar",
"/foo/_layout",
"/foo/index",
"/foo/_middleware",
"/foo/bar/_middleware",
"/foo/bar/index",
"/foo/bar/[...foo]",
"/foo/bar/baz",
"/foo/bar/_layout",
];
const sorted = [
"/foo/_middleware",
"/foo/_layout",
"/foo/bar",
"/foo/index",
"/foo/bar/_middleware",
"/foo/bar/_layout",
"/foo/bar/index",
"/foo/bar/baz",
"/foo/bar/[...foo]",
"/foo/[id]",
"/foo/[...slug]",
];
routes.sort(sortRoutePaths);
assertEquals(routes, sorted);
});
-15
View File
@@ -1,15 +0,0 @@
// This utility is based on https://github.com/zertosh/htmlescape
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
const ESCAPE_LOOKUP: { [match: string]: string } = {
">": "\\u003e",
"<": "\\u003c",
"\u2028": "\\u2028",
"\u2029": "\\u2029",
};
const ESCAPE_REGEX = /[><\u2028\u2029]/g;
export function htmlEscapeJsonString(str: string): string {
return str.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
}
-18
View File
@@ -1,18 +0,0 @@
import { htmlEscapeJsonString } from "./htmlescape.ts";
import { assertEquals } from "../../tests/deps.ts";
Deno.test("with angle brackets should escape", () => {
const evilObj = { evil: "<script></script>" };
assertEquals(
htmlEscapeJsonString(JSON.stringify(evilObj)),
'{"evil":"\\u003cscript\\u003e\\u003c/script\\u003e"}',
);
});
Deno.test("with angle brackets should parse back", () => {
const evilObj = { evil: "<script></script>" };
assertEquals(
JSON.parse(htmlEscapeJsonString(JSON.stringify(evilObj))),
evilObj,
);
});

Some files were not shown because too many files have changed in this diff Show More