feat: expose layouts and pages on App (#3086)

This PR extracts the functionality from the `fs_routes` plugin and
exposes it onto `App`. These are the new APIs:

- `app.layout(pattern, route)`
- `app.onError(pattern, route)`
- `app.notFound(pattern, route)`
- `app.route(pattern, route)`

This also removes the need for `.use(staticFiles())`. This line can be
safely removed.

Fixes https://github.com/denoland/fresh/issues/3040
Fixes https://github.com/denoland/fresh/issues/3033
Fixes https://github.com/denoland/fresh/issues/2591
Fixes https://github.com/denoland/fresh/issues/950
Fixes https://github.com/denoland/fresh/issues/1918
This commit is contained in:
Marvin Hagemeister
2025-07-14 19:27:48 +02:00
committed by GitHub
parent ccb621d2a3
commit c11cf7b41a
35 changed files with 1328 additions and 971 deletions
+1 -3
View File
@@ -360,13 +360,11 @@ ${GRADIENT_CSS}`;
// Skip this and be silent if there is a network issue.
}
const MAIN_TS = `import { App, fsRoutes, staticFiles } from "fresh";
const MAIN_TS = `import { App, fsRoutes } from "fresh";
import { define, type State } from "./utils.ts";
export const app = new App<State>();
app.use(staticFiles());
// this is the same as the /api/:name route defined via a file. feel free to delete this!
app.get("/api2/:name", (ctx) => {
const name = ctx.params.name;
+259 -80
View File
@@ -5,18 +5,32 @@ import { trace } from "@opentelemetry/api";
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 { type Method, type Router, UrlPatternRouter } from "./router.ts";
import { Context, type ServerIslandRegistry } from "./context.ts";
import {
mergePath,
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 type { ServerIslandRegistry } from "./context.ts";
import { FinishSetup, ForgotBuild } from "./finish_setup.tsx";
import { HttpError } from "./error.ts";
import { mergePaths, pathToExportName } from "./utils.ts";
import { pathToExportName } from "./utils.ts";
import type { LayoutConfig, Route } from "./types.ts";
import {
getOrCreateSegment,
newSegment,
renderRoute,
type RouteComponent,
segmentToMiddlewares,
} from "./segments.ts";
import { isHandlerByMethod, type PageResponse } from "./handlers.ts";
import { serveInternalStaticFiles } from "./middlewares/static_files.ts";
// TODO: Completed type clashes in older Deno versions
// deno-lint-ignore no-explicit-any
@@ -25,12 +39,44 @@ export const DEFAULT_CONN_INFO: any = {
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
};
const DEFAULT_NOT_FOUND = () => {
/** Used to group mounted apps. Only internal */
let INTERNAL_ID = 0;
const DEFAULT_RENDER = <State>(): Promise<PageResponse<State>> =>
// deno-lint-ignore no-explicit-any
Promise.resolve({ data: {} as any });
const DEFAULT_NOT_FOUND = (): Promise<Response> => {
throw new HttpError(404);
};
const DEFAULT_NOT_ALLOWED_METHOD = () => {
const DEFAULT_NOT_ALLOWED_METHOD = (): Promise<Response> => {
throw new HttpError(405);
};
const defaultOptionsHandler = (methods: string[]): () => Promise<Response> => {
return () =>
Promise.resolve(
new Response(null, {
status: 204,
headers: { Allow: methods.join(", ") },
}),
);
};
// deno-lint-ignore require-await
const DEFAULT_ERROR_HANDLER = async <State>(ctx: Context<State>) => {
const { error } = ctx;
if (error instanceof HttpError) {
if (error.status >= 500) {
// deno-lint-ignore no-console
console.error(error);
}
return new Response(error.message, { status: error.status });
}
// deno-lint-ignore no-console
console.error(error);
return new Response("Internal server error", { status: 500 });
};
export type ListenOptions =
& Partial<
@@ -117,7 +163,6 @@ async function listenOnFreePort(
throw firstError;
}
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
@@ -132,9 +177,15 @@ export class App<State> {
#islandRegistry: ServerIslandRegistry = new Map();
#buildCache: BuildCache | null = null;
#islandNames = new Set<string>();
#root = newSegment<State>("", null);
#routeDefs: {
method: Method | "ALL";
pattern: string;
fns: MiddlewareFn<State>[];
unshift: boolean;
}[] = [];
static {
getRouter = (app) => app.#router;
getIslandRegistry = (app) => app.#islandRegistry;
getBuildCache = (app) => app.#buildCache;
setBuildCache = (app, cache) => app.#buildCache = cache;
@@ -175,76 +226,170 @@ export class App<State> {
return this;
}
use(middleware: MiddlewareFn<State>): this {
this.#router.addMiddleware(middleware);
use(...middleware: MiddlewareFn<State>[]): this;
use(path: string, ...middleware: MiddlewareFn<State>[]): this;
use(
pathOrMiddleware: string | MiddlewareFn<State>,
...middlewares: MiddlewareFn<State>[]
): this {
let path: string;
let fns: MiddlewareFn<State>[];
if (typeof pathOrMiddleware === "string") {
path = pathOrMiddleware;
fns = middlewares!;
} else {
path = "*";
middlewares.unshift(pathOrMiddleware);
fns = middlewares;
}
const segment = getOrCreateSegment(this.#root, path, false);
segment.middlewares.push(...fns);
return this;
}
notFound(routeOrMiddleware: Route<State> | MiddlewareFn<State>): this {
const route = typeof routeOrMiddleware === "function"
? { handler: routeOrMiddleware }
: routeOrMiddleware;
ensureHandler(route);
this.#root.notFound = (ctx) => renderRoute(ctx, route);
return this;
}
onError(
path: string,
routeOrMiddleware: Route<State> | MiddlewareFn<State>,
): this {
const segment = getOrCreateSegment(this.#root, path, true);
segment.errorRoute = typeof routeOrMiddleware === "function"
? { handler: routeOrMiddleware }
: routeOrMiddleware;
ensureHandler(segment.errorRoute);
return this;
}
appWrapper(component: RouteComponent<State>) {
const segment = getOrCreateSegment<State>(this.#root, "", false);
segment.app = component;
}
layout(
path: string,
component: RouteComponent<State>,
config?: LayoutConfig,
): this {
const segment = getOrCreateSegment<State>(this.#root, path, true);
segment.layout = { component, config: config ?? null };
return this;
}
route(path: string, route: Route<State>): this {
const segment = getOrCreateSegment<State>(this.#root, path, false);
const middlewares = segmentToMiddlewares(segment);
ensureHandler(route);
middlewares.push((ctx) => renderRoute(ctx, route));
const routePath = route.config?.routeOverride ?? path;
if (typeof route.handler === "function") {
this.#addRoute("ALL", routePath, middlewares);
} else if (isHandlerByMethod(route.handler!)) {
for (const method of Object.keys(route.handler)) {
this.#addRoute(method as Method, routePath, middlewares);
}
}
return this;
}
get(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("GET", path, middlewares);
this.#addMiddleware("GET", path, middlewares);
return this;
}
post(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("POST", path, middlewares);
this.#addMiddleware("POST", path, middlewares);
return this;
}
patch(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("PATCH", path, middlewares);
this.#addMiddleware("PATCH", path, middlewares);
return this;
}
put(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("PUT", path, middlewares);
this.#addMiddleware("PUT", path, middlewares);
return this;
}
delete(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("DELETE", path, middlewares);
this.#addMiddleware("DELETE", path, middlewares);
return this;
}
head(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("HEAD", path, middlewares);
this.#addMiddleware("HEAD", path, middlewares);
return this;
}
all(path: string, ...middlewares: MiddlewareFn<State>[]): this {
return this.#addRoutes("ALL", path, middlewares);
this.#addMiddleware("ALL", path, middlewares);
return this;
}
#addMiddleware(
method: Method | "ALL",
path: string,
fns: MiddlewareFn<State>[],
unshift = false,
) {
const segment = getOrCreateSegment<State>(this.#root, path, false);
const result = segmentToMiddlewares(segment);
result.push(...fns);
const resPath = mergePath(this.config.basePath, path);
this.#addRoute(method, resPath, result, unshift);
}
#addRoute(
method: Method | "ALL",
path: string,
fns: MiddlewareFn<State>[],
unshift = false,
) {
this.#routeDefs.push({ method, pattern: path, fns, unshift });
}
mountApp(path: string, app: App<State>): this {
const routes = app.#router._routes;
const segmentPath = mergePath(path, `/__${INTERNAL_ID++}/`);
const segment = getOrCreateSegment(this.#root, segmentPath, true);
const fns = segmentToMiddlewares(segment);
const routes = app.#routeDefs;
for (let i = 0; i < routes.length; i++) {
const route = routes[i];
const merged = mergePath(path, route.pattern);
const mergedFns = [...fns, ...route.fns];
this.#addRoute(route.method, merged, mergedFns, route.unshift);
}
app.#islandRegistry.forEach((value, key) => {
this.#islandRegistry.set(key, value);
});
const middlewares = app.#router._middlewares;
// Special case when user calls one of these:
// - `app.mountApp("/", otherApp)`
// - `app.mountApp("/*", 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);
}
app.#root.notFound = this.#root.notFound;
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;
}
/**
* Create handler function for `Deno.serve` or to be used in
* testing.
*/
handler(): (
request: Request,
info?: Deno.ServeHandlerInfo,
@@ -263,6 +408,27 @@ export class App<State> {
return missingBuildHandler;
}
const staticMids: MiddlewareFn<State>[] = [];
if (this.#root.middlewares.length > 0) {
staticMids.push(...this.#root.middlewares);
}
staticMids.push(serveInternalStaticFiles());
this.#addMiddleware(
"ALL",
"*",
staticMids,
true,
);
for (let i = 0; i < this.#routeDefs.length; i++) {
const route = this.#routeDefs[i];
this.#router.add(route.method, route.pattern, route.fns, route.unshift);
}
const rootMiddlewares = this.#root.middlewares;
return async (
req: Request,
conn: Deno.ServeHandlerInfo = DEFAULT_CONN_INFO,
@@ -273,13 +439,32 @@ export class App<State> {
const method = req.method.toUpperCase() as Method;
const matched = this.#router.match(method, url);
let { params, pattern, handlers, methodMatch } = matched;
const next = matched.patternMatch && !matched.methodMatch
? DEFAULT_NOT_ALLOWED_METHOD
: DEFAULT_NOT_FOUND;
const span = trace.getActiveSpan();
if (span && pattern) {
span.updateName(`${method} ${pattern}`);
span.setAttribute("http.route", pattern);
}
const { params, handlers, pattern } = matched;
const ctx = new FreshReqContext<State>(
let next: () => Promise<Response>;
if (pattern === null || !methodMatch) {
handlers = rootMiddlewares;
}
if (matched.pattern !== null && !methodMatch) {
if (method === "OPTIONS") {
const allowed = this.#router.getAllowedMethods(matched.pattern);
next = defaultOptionsHandler(allowed);
} else {
next = DEFAULT_NOT_ALLOWED_METHOD;
}
} else {
next = DEFAULT_NOT_FOUND;
}
const ctx = new Context<State>(
req,
url,
conn,
@@ -290,19 +475,10 @@ export class App<State> {
this.#buildCache!,
);
const span = trace.getActiveSpan();
if (span && pattern) {
span.updateName(`${method} ${pattern}`);
span.setAttribute("http.route", pattern);
}
try {
let result: unknown;
if (handlers.length === 1 && handlers[0].length === 1) {
result = await handlers[0][0](ctx);
} else {
result = await runMiddlewares(handlers, ctx);
}
if (handlers.length === 0) return await next();
const result = await runMiddlewares(handlers, ctx);
if (!(result instanceof Response)) {
throw new Error(
`Expected a "Response" instance to be returned, but got: ${result}`,
@@ -311,17 +487,8 @@ export class App<State> {
return result;
} catch (err) {
if (err instanceof HttpError) {
if (err.status >= 500) {
// deno-lint-ignore no-console
console.error(err);
}
return new Response(err.message, { status: err.status });
}
// deno-lint-ignore no-console
console.error(err);
return new Response("Internal server error", { status: 500 });
ctx.error = err;
return await DEFAULT_ERROR_HANDLER(ctx);
}
};
}
@@ -331,7 +498,7 @@ export class App<State> {
options.onListen = createOnListen(this.config.basePath, options);
}
const handler = await this.handler();
const handler = this.handler();
if (options.port) {
await Deno.serve(options, handler);
return;
@@ -351,3 +518,15 @@ const missingBuildHandler = async (): Promise<Response> => {
: renderToString(h(ForgotBuild, null));
return new Response(html, { headers, status: 500 });
};
function ensureHandler<State>(route: Route<State>) {
if (route.handler === undefined) {
route.handler = route.component !== undefined
? DEFAULT_RENDER
: DEFAULT_NOT_FOUND;
} else if (isHandlerByMethod(route.handler)) {
if (route.component !== undefined && !route.handler.GET) {
route.handler.GET = DEFAULT_RENDER;
}
}
}
+79 -3
View File
@@ -2,6 +2,7 @@ import { expect } from "@std/expect";
import { App, getIslandRegistry, setBuildCache } from "./app.ts";
import { FakeServer } from "./test_utils.ts";
import { ProdBuildCache } from "./build_cache.ts";
import { HttpError } from "./error.ts";
Deno.test("App - .use()", async () => {
const app = new App<{ text: string }>()
@@ -35,8 +36,6 @@ Deno.test("App - .use() #2", async () => {
Deno.test("App - .get()", async () => {
const app = new App()
.post("/", () => new Response("ok"))
.post("/foo", () => new Response("ok"))
.get("/", () => new Response("ok"))
.get("/foo", () => new Response("ok"));
@@ -323,11 +322,11 @@ Deno.test(
"App - .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();
})
.get("/foo", (ctx) => new Response(ctx.state.text))
.post("/foo", (ctx) => new Response(ctx.state.text));
const app = new App<{ text: string }>()
@@ -392,6 +391,27 @@ Deno.test(
},
);
// https://github.com/denoland/fresh/issues/3033
Deno.test(
"App - .mountApp() self mount with dynamic routes",
async () => {
const innerApp = new App<{ text: string }>()
.get("/", () => new Response("list authors"))
.get("/:name", (ctx) => new Response(`show: ${ctx.params.name}`));
const app = new App<{ text: string }>()
.mountApp("/api/authors", innerApp);
const server = new FakeServer(app.handler());
let res = await server.get("/api/authors");
expect(await res.text()).toEqual("list authors");
res = await server.get("/api/authors/foo");
expect(await res.text()).toEqual("show: foo");
},
);
Deno.test("App - catches errors", async () => {
let thrownErr: unknown | null = null;
const app = new App<{ text: string }>()
@@ -532,3 +552,59 @@ Deno.test("App - adding Island should convert to valid export names", () => {
fn: component3,
});
});
Deno.test("App - overwrite default 404 handler", async () => {
const app = new App()
.notFound(() => new Response("bar", { status: 404 }))
.get("/foo", () => new Response("foo"))
.get("/thrower", () => {
throw new HttpError(404);
});
const server = new FakeServer(app.handler());
let res = await server.get("/invalid");
expect(await res.text()).toEqual("bar");
res = await server.get("/thrower");
expect(await res.text()).toEqual("bar");
});
Deno.test("App - uses error route", async () => {
const app = new App()
.onError("*", () => new Response("error route", { status: 200 }))
.get("/thrower", () => {
throw new HttpError(404);
});
const server = new FakeServer(app.handler());
let res = await server.get("/invalid");
expect(await res.text()).toEqual("error route");
res = await server.get("/thrower");
expect(await res.text()).toEqual("error route");
});
Deno.test("App - uses notFound route on 404", async () => {
const app = new App()
.notFound(() => new Response("not found route", { status: 404 }))
.onError("*", () => new Response("error route", { status: 500 }))
.get("/thrower", () => {
throw new HttpError(404);
})
.get("/thrower_2", () => {
throw new HttpError(500);
});
const server = new FakeServer(app.handler());
let res = await server.get("/invalid");
expect(await res.text()).toEqual("not found route");
res = await server.get("/thrower");
expect(await res.text()).toEqual("not found route");
res = await server.get("/thrower_2");
expect(await res.text()).toEqual("error route");
});
+2 -1
View File
@@ -1,5 +1,6 @@
import type { ComponentChildren } from "preact";
import type { FreshContext, PageProps } from "./context.ts";
import type { FreshContext } from "./context.ts";
import type { PageProps } from "./render.ts";
import type { HandlerFn, RouteHandler } from "./handlers.ts";
/**
+1 -1
View File
@@ -1,4 +1,4 @@
import type { PageProps } from "./context.ts";
import type { PageProps } from "./render.ts";
import { assertType, type IsExact } from "@std/testing/types";
import { expect } from "@std/expect";
import { type defineApp, type defineLayout, defineRoute } from "./compat.ts";
+119 -112
View File
@@ -1,22 +1,26 @@
import {
type AnyComponent,
type ComponentType,
Fragment,
type FunctionComponent,
h,
isValidElement,
type VNode,
} from "preact";
import { renderToString } from "preact-render-to-string";
import { SpanStatusCode } from "@opentelemetry/api";
import type { ResolvedFreshConfig } from "./config.ts";
import type { BuildCache } from "./build_cache.ts";
import {
FreshScripts,
RenderState,
setRenderState,
} from "./runtime/server/preact_hooks.tsx";
import { DEV_ERROR_OVERLAY_URL, PARTIAL_SEARCH_PARAM } from "./constants.ts";
import { BUILD_ID } from "./runtime/build_id.ts";
import { RenderState, setRenderState } from "./runtime/server/preact_hooks.tsx";
import { PARTIAL_SEARCH_PARAM } from "./constants.ts";
import { tracer } from "./otel.ts";
import {
type ComponentDef,
isAsyncAnyComponent,
type PageProps,
preactRender,
renderAsyncAnyComponent,
renderRouteComponent,
} from "./render.ts";
export interface Island {
file: string | URL;
@@ -27,24 +31,44 @@ export interface Island {
export type ServerIslandRegistry = Map<ComponentType, Island>;
export const internals: unique symbol = Symbol("fresh_internal");
export interface UiTree<Data, State> {
app: AnyComponent<PageProps<Data, State>> | null;
layouts: ComponentDef<Data, State>[];
}
/**
* @deprecated Use {@linkcode Context} instead.
*/
export type FreshContext<State = unknown> = Context<State>;
export let getBuildCache: <T>(ctx: Context<T>) => BuildCache;
export let getInternals: <T>(ctx: Context<T>) => UiTree<unknown, T>;
/**
* The context passed to every middleware. It is unique for every request.
*/
export interface FreshContext<State = unknown> {
export class Context<State> {
#internal: UiTree<unknown, State> = {
app: null,
layouts: [],
};
/** Reference to the resolved Fresh configuration */
readonly config: ResolvedFreshConfig;
readonly state: State;
/** The original incoming `Request` object` */
readonly 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.
*/
readonly url: URL;
/** The original incoming `Request` object` */
readonly req: Request;
readonly params: Record<string, string>;
readonly error: unknown;
readonly info: Deno.ServeHandlerInfo;
readonly state: State = {} as State;
data: unknown = undefined;
error: unknown | null = null;
readonly info: Deno.ServeHandlerInfo | Deno.ServeHandlerInfo;
/**
* Whether the current Request is a partial request.
*
@@ -53,20 +77,7 @@ export interface FreshContext<State = unknown> {
* be used to determine if only `<Partial>`'s need to be rendered.
*/
readonly isPartial: boolean;
/**
* 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
@@ -90,25 +101,7 @@ export interface FreshContext<State = unknown> {
* return res
* }
*/
next(): Promise<Response>;
render(vnode: VNode, init?: ResponseInit): Response | Promise<Response>;
}
export let getBuildCache: (ctx: FreshContext<unknown>) => BuildCache;
export class FreshReqContext<State>
implements FreshContext<State>, PageProps<unknown, State> {
readonly config: ResolvedFreshConfig;
readonly url: URL;
readonly req: Request;
readonly params: Record<string, string>;
readonly state: State = {} as State;
data: unknown = undefined;
error: unknown | null = null;
readonly info: Deno.ServeHandlerInfo | Deno.ServeHandlerInfo;
readonly isPartial: boolean;
next: FreshContext<State>["next"];
next: () => Promise<Response>;
#islandRegistry: ServerIslandRegistry;
#buildCache: BuildCache;
@@ -117,7 +110,9 @@ export class FreshReqContext<State>
Component!: FunctionComponent;
static {
getBuildCache = (ctx) => (ctx as FreshReqContext<unknown>).#buildCache;
// deno-lint-ignore no-explicit-any
getInternals = (ctx) => (ctx as Context<unknown>).#internal as any;
getBuildCache = (ctx) => (ctx as Context<unknown>).#buildCache;
}
constructor(
@@ -126,7 +121,7 @@ export class FreshReqContext<State>
info: Deno.ServeHandlerInfo,
params: Record<string, string>,
config: ResolvedFreshConfig,
next: FreshContext<State>["next"],
next: () => Promise<Response>,
islandRegistry: ServerIslandRegistry,
buildCache: BuildCache,
) {
@@ -141,6 +136,19 @@ export class FreshReqContext<State>
this.#buildCache = buildCache;
}
/**
* 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(pathOrUrl: string, status = 302): Response {
let location = pathOrUrl;
@@ -166,17 +174,61 @@ export class FreshReqContext<State>
});
}
render(
async render(
// deno-lint-ignore no-explicit-any
vnode: VNode<any>,
vnode: VNode<any> | null,
init: ResponseInit | undefined = {},
): Response | Promise<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 defs = this.#internal.layouts;
const appDef = this.#internal.app;
const props = this as Context<State>;
// Compose final vnode tree
for (let i = defs.length - 1; i >= 0; i--) {
const child = vnode;
props.Component = () => child;
const def = defs[i];
const result = await renderRouteComponent(this, def, () => child);
if (result instanceof Response) {
return result;
}
vnode = result;
}
if (isAsyncAnyComponent(appDef)) {
const child = vnode;
props.Component = () => child;
const result = await renderAsyncAnyComponent(appDef, props);
if (result instanceof Response) {
return result;
}
vnode = result;
} else if (appDef !== null) {
const child = vnode;
vnode = h(appDef, {
Component: () => child,
config: this.config,
data: null,
error: this.error,
info: this.info,
isPartial: this.isPartial,
params: this.params,
req: this.req,
state: this.state,
url: this.url,
});
}
const headers = init.headers !== undefined
? init.headers instanceof Headers
? init.headers
@@ -198,13 +250,21 @@ export class FreshReqContext<State>
const html = tracer.startActiveSpan("render", (span) => {
span.setAttribute("fresh.span_type", "render");
const state = new RenderState(
this,
this.#islandRegistry,
this.#buildCache,
partialId,
);
try {
setRenderState(state);
return preactRender(
vnode,
vnode ?? h(Fragment, null),
this,
this.#islandRegistry,
state,
this.#buildCache,
partialId,
headers,
);
} catch (err) {
@@ -218,6 +278,9 @@ export class FreshReqContext<State>
}
throw err;
} finally {
state.clear();
setRenderState(null);
span.end();
}
});
@@ -225,7 +288,7 @@ export class FreshReqContext<State>
}
}
Object.defineProperties(FreshReqContext.prototype, {
Object.defineProperties(Context.prototype, {
config: { enumerable: true },
url: { enumerable: true },
req: { enumerable: true },
@@ -236,59 +299,3 @@ Object.defineProperties(FreshReqContext.prototype, {
next: { enumerable: true },
info: { enumerable: true },
});
function preactRender<State, Data>(
vnode: VNode,
ctx: PageProps<Data, State>,
islandRegistry: ServerIslandRegistry,
buildCache: BuildCache,
partialId: string,
headers: Headers,
) {
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 {
// Add preload headers
const basePath = ctx.config.basePath;
const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
let link = `<${encodeURI(runtimeUrl)}>; rel="modulepreload"; as="script"`;
state.islands.forEach((island) => {
const chunk = buildCache.getIslandChunkName(island.name);
if (chunk !== null) {
link += `, <${
encodeURI(`${basePath}${chunk}`)
}>; rel="modulepreload"; as="script"`;
}
});
if (link !== "") {
headers.append("Link", link);
}
state.clear();
setRenderState(null);
}
}
export type PageProps<Data = unknown, T = unknown> =
& Omit<FreshContext<T>, "next" | "render" | "redirect">
& { data: Data; Component: FunctionComponent };
+6 -6
View File
@@ -1,5 +1,5 @@
import { expect } from "@std/expect";
import { FreshReqContext } from "./context.ts";
import { Context } from "./context.ts";
import { App } from "fresh";
import { asset } from "fresh/runtime";
import { FakeServer } from "./test_utils.ts";
@@ -7,23 +7,23 @@ 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("/");
let res = Context.prototype.redirect("/");
expect(res.status).toEqual(302);
expect(res.headers.get("Location")).toEqual("/");
res = FreshReqContext.prototype.redirect("//evil.com");
res = Context.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");
res = Context.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");
res = Context.prototype.redirect("https://deno.com");
expect(res.status).toEqual(302);
expect(res.headers.get("Location")).toEqual("https://deno.com");
res = FreshReqContext.prototype.redirect("/", 307);
res = Context.prototype.redirect("/", 307);
expect(res.status).toEqual(307);
});
+1 -1
View File
@@ -1,7 +1,7 @@
import type { AnyComponent } from "preact";
import type { HandlerByMethod, HandlerFn, RouteHandler } from "./handlers.ts";
import type { Middleware } from "./middlewares/mod.ts";
import type { PageProps } from "./context.ts";
import type { PageProps } from "./render.ts";
/**
* A set of define functions that enable better type inference and code
+8
View File
@@ -48,6 +48,7 @@ export class Builder implements FreshBuilder {
#transformer = new FreshFileTransformer(fsAdapter);
#addedInternalTransforms = false;
#options: { target: string | string[] };
#chunksReady = Promise.withResolvers<void>();
constructor(options: BuildOptions = {}) {
this.#options = {
@@ -70,6 +71,11 @@ export class Builder implements FreshBuilder {
.use(liveReload())
.use(devErrorOverlay())
.use(automaticWorkspaceFolders(app.config.root))
// Wait for island chunks to be ready before attempting to serve them
.use(async (ctx) => {
await this.#chunksReady.promise;
return await ctx.next();
})
.mountApp("/*", app);
devApp.config.mode = "development";
@@ -205,6 +211,8 @@ export class Builder implements FreshBuilder {
await buildCache.flush();
this.#chunksReady.resolve();
if (!dev) {
// deno-lint-ignore no-console
console.log(
+4 -10
View File
@@ -30,16 +30,10 @@ Deno.test("CORS - Preflight default", async () => {
const res = await handler(req);
expect(res.status).toBe(204);
expect(res.statusText).toBe("No Content");
expect(res.headers.get("Access-Control-Allow-Methods")?.split(",")[0]).toBe(
"GET",
);
expect(res.headers.get("Access-Control-Allow-Headers")?.split(",")).toEqual(
[
"X-PINGOTHER",
"Content-Type",
],
);
expect(res.headers.get("Access-Control-Allow-Methods")?.split(",")[0])
.toBe("GET");
expect(res.headers.get("Access-Control-Allow-Headers")?.split(","))
.toEqual(["X-PINGOTHER", "Content-Type"]);
});
Deno.test("CORS - Preflight with options", async () => {
+23 -21
View File
@@ -1,4 +1,4 @@
import type { FreshContext, FreshReqContext } from "../context.ts";
import { type Context, getInternals } from "../context.ts";
import type { App as _App } from "../app.ts";
import type { Define as _Define } from "../define.ts";
@@ -6,14 +6,14 @@ import type { Define as _Define } from "../define.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.
* calling {@linkcode Context.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
* A {@linkcode Context} 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.
@@ -72,7 +72,7 @@ import type { Define as _Define } from "../define.ts";
* ```
*/
export type MiddlewareFn<State> = (
ctx: FreshContext<State>,
ctx: Context<State>,
) => Response | Promise<Response>;
/**
@@ -82,27 +82,29 @@ export type MiddlewareFn<State> = (
export type Middleware<State> = MiddlewareFn<State> | MiddlewareFn<State>[];
export function runMiddlewares<State>(
middlewares: MiddlewareFn<State>[][],
ctx: FreshReqContext<State>,
middlewares: MiddlewareFn<State>[],
ctx: Context<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;
}
};
}
const local = fn;
const next = middlewares[i];
fn = async () => {
const internals = getInternals(ctx);
const { app: prevApp, layouts: prevLayouts } = internals;
ctx.next = local;
try {
return await next(ctx);
} catch (err) {
ctx.error = err;
throw err;
} finally {
internals.app = prevApp;
internals.layouts = prevLayouts;
}
};
}
return fn();
}
+8 -5
View File
@@ -24,7 +24,7 @@ Deno.test("runMiddleware", async () => {
];
const server = serveMiddleware<{ text: string }>((ctx) =>
runMiddlewares([middlewares], ctx)
runMiddlewares(middlewares, ctx)
);
const res = await server.get("/");
@@ -43,7 +43,7 @@ Deno.test("runMiddleware - middlewares should only be called once", async () =>
const server = serveMiddleware<{ count: number }>((ctx) =>
runMiddlewares(
[[A, (ctx) => new Response(String(ctx.state.count))]],
[A, (ctx) => new Response(String(ctx.state.count))],
ctx,
)
);
@@ -75,8 +75,11 @@ Deno.test("runMiddleware - runs multiple stacks", async () => {
ctx.state.text = "";
return runMiddlewares(
[
[A, B],
[C, D, (ctx) => new Response(String(ctx.state.text))],
A,
B,
C,
D,
(ctx) => new Response(String(ctx.state.text)),
],
ctx,
);
@@ -122,7 +125,7 @@ Deno.test("runMiddleware - throws errors", async () => {
];
const server = serveMiddleware<{ text: string }>((ctx) =>
runMiddlewares([middlewares], ctx)
runMiddlewares(middlewares, ctx)
);
try {
+11 -8
View File
@@ -3,8 +3,8 @@ import { contentType as getContentType } from "@std/media-types/content-type";
import type { MiddlewareFn } from "./mod.ts";
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
import { BUILD_ID } from "../runtime/build_id.ts";
import { tracer } from "../otel.ts";
import { getBuildCache } from "../context.ts";
import { trace, tracer } from "../otel.ts";
/**
* Fresh middleware to enable file-system based routing.
@@ -12,11 +12,20 @@ import { trace, tracer } from "../otel.ts";
* // Enable Fresh static file serving
* app.use(staticFiles());
* ```
* @deprecated This is not needed anymore. Remove this middleware.
*/
export function staticFiles<T>(): MiddlewareFn<T> {
return async function freshStaticFiles(ctx) {
return await ctx.next();
};
}
export function serveInternalStaticFiles<T>(): MiddlewareFn<T> {
return async function freshServeStaticFiles(ctx) {
const { req, url, config } = ctx;
const buildCache = getBuildCache(ctx);
if (buildCache === null) return await ctx.next();
let pathname = decodeURIComponent(url.pathname);
if (config.basePath) {
@@ -33,7 +42,7 @@ export function staticFiles<T>(): MiddlewareFn<T> {
if (pathname === "/favicon.ico") {
return new Response(null, { status: 404 });
}
return ctx.next();
return await ctx.next();
}
if (req.method !== "GET" && req.method !== "HEAD") {
@@ -41,12 +50,6 @@ export function staticFiles<T>(): MiddlewareFn<T> {
return new Response("Method Not Allowed", { status: 405 });
}
const parentSpan = trace.getActiveSpan();
if (parentSpan) {
parentSpan.updateName(`${req.method} /*`);
parentSpan.setAttribute("http.route", "/*");
}
const span = tracer.startSpan("static file", {
attributes: { "fresh.span_type": "static_file" },
startTime,
+9 -9
View File
@@ -1,4 +1,4 @@
import { staticFiles } from "./static_files.ts";
import { serveInternalStaticFiles } from "./static_files.ts";
import { serveMiddleware } from "../test_utils.ts";
import type { BuildCache, StaticFile } from "../build_cache.ts";
import { expect } from "@std/expect";
@@ -39,7 +39,7 @@ Deno.test("static files - 200", async () => {
"foo.css": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
serveInternalStaticFiles(),
{ buildCache },
);
@@ -59,7 +59,7 @@ Deno.test("static files - HEAD 200", async () => {
"foo.css": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
serveInternalStaticFiles(),
{ buildCache },
);
@@ -76,7 +76,7 @@ Deno.test("static files - etag", async () => {
"foo.css": { content: "body {}", hash: "123" },
});
const server = serveMiddleware(
staticFiles(),
serveInternalStaticFiles(),
{ buildCache },
);
@@ -101,7 +101,7 @@ Deno.test("static files - etag", async () => {
Deno.test("static files - 404 on missing favicon.ico", async () => {
const buildCache = new MockBuildCache({});
const server = serveMiddleware(
staticFiles(),
serveInternalStaticFiles(),
{ buildCache },
);
const res = await server.get("favicon.ico");
@@ -114,7 +114,7 @@ Deno.test("static files - 405 on wrong HTTP method", async () => {
"foo.css": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
serveInternalStaticFiles(),
{ buildCache },
);
@@ -131,7 +131,7 @@ Deno.test("static files - disables caching in development", async () => {
"foo.css": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
serveInternalStaticFiles(),
{
buildCache,
config: {
@@ -159,7 +159,7 @@ Deno.test("static files - enables caching in production", async () => {
"foo.css": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
serveInternalStaticFiles(),
{
buildCache,
config: {
@@ -189,7 +189,7 @@ Deno.test("static files - decoded pathname", async () => {
"인천.avif": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
serveInternalStaticFiles(),
{ buildCache },
);
+2 -1
View File
@@ -14,7 +14,8 @@ export type { Middleware, MiddlewareFn } from "./middlewares/mod.ts";
export { staticFiles } from "./middlewares/static_files.ts";
export { cors, type CORSOptions } from "./middlewares/cors.ts";
export type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
export type { FreshContext, Island, PageProps } from "./context.ts";
export type { Context, FreshContext, Island } from "./context.ts";
export { createDefine, type Define } from "./define.ts";
export type { Method } from "./router.ts";
export { HttpError } from "./error.ts";
export type { PageProps } from "./render.ts";
+12 -1
View File
@@ -1,7 +1,18 @@
import { trace } from "@opentelemetry/api";
import { type Span, SpanStatusCode, trace } from "@opentelemetry/api";
import denoJson from "../deno.json" with { type: "json" };
export const CURRENT_FRESH_VERSION = denoJson.version;
export const tracer = trace.getTracer("fresh", CURRENT_FRESH_VERSION);
export { trace };
export function recordSpanError(span: Span, err: unknown) {
if (err instanceof Error) {
span.recordException(err);
} else {
span.setStatus({
code: SpanStatusCode.ERROR,
message: String(err),
});
}
}
+80 -209
View File
@@ -5,16 +5,12 @@ import * as path from "@std/path";
import type { RouteConfig } from "../../types.ts";
import type { RouteHandler } from "../../handlers.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 { AsyncAnyComponent } from "../../render.ts";
import { pathToPattern } from "../../router.ts";
import { type HandlerFn, isHandlerByMethod } from "../../handlers.ts";
import { type FsAdapter, fsAdapter } from "../../fs.ts";
import { HttpError } from "../../error.ts";
import { parseRootPath } from "../../config.ts";
import type { FreshReqContext, PageProps } from "../../context.ts";
import type { PageProps } from "../../render.ts";
const TEST_FILE_PATTERN = /[._]test\.(?:[tj]sx?|[mc][tj]s)$/;
const GROUP_REG = /(^|[/\\\\])\((_[^/\\\\]+)\)[/\\\\]/;
@@ -25,7 +21,7 @@ interface InternalRoute<State> {
filePath: string;
config: RouteConfig | null;
handlers:
| RouteHandler<unknown, State>[]
| MiddlewareFn<State>[]
| RouteHandler<unknown, State>
| null;
component: AnyComponent<PageProps<unknown, State>> | null;
@@ -165,233 +161,108 @@ export async function fsRoutes<State>(
);
routeModules.sort((a, b) => sortRoutePaths(a.path, b.path));
const stack: InternalRoute<State>[] = [];
let hasApp = false;
const specialPaths = new Set<string>();
const errorPaths = new Set<string>();
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);
const component = routeMod.component;
if (component !== null) {
app.appWrapper(component);
}
continue;
} else if (normalized.endsWith("/_middleware")) {
stack.push(routeMod);
if (routeMod.handlers === null) continue;
if (isHandlerByMethod(routeMod.handlers)) {
warnInvalidRoute(
"Middleware does not support object handlers with GET, POST, etc.",
);
continue;
}
const pattern = pathToPattern(
normalized.slice(1, -"/_middleware".length),
{ keepGroups: true },
);
const handlers = (Array.isArray(routeMod.handlers)
? routeMod.handlers
: [routeMod.handlers]) as MiddlewareFn<State>[];
app.use(pattern, ...handlers);
continue;
} else if (normalized.endsWith("/_layout")) {
stack.push(routeMod);
if (routeMod.handlers !== null) {
warnInvalidRoute("Layout does not support handlers");
}
const pattern = pathToPattern(normalized.slice(1, -"/_layout".length), {
keepGroups: true,
});
const { component, config } = routeMod;
if (component !== null) {
app.layout(pattern, component, config ?? undefined);
}
continue;
} else if (normalized.endsWith("/_error")) {
stack.push(routeMod);
const pattern = pathToPattern(normalized.slice(1, -"/_error".length), {
keepGroups: true,
});
errorPaths.add(pattern);
app.onError(pattern, {
config: routeMod.config ?? undefined,
component: routeMod.component ?? undefined,
// deno-lint-ignore no-explicit-any
handler: routeMod.handlers as any ?? undefined,
});
continue;
} else if (normalized.endsWith("/_404")) {
stack.push(routeMod);
app.notFound({
config: routeMod.config ?? undefined,
component: routeMod.component ?? undefined,
// deno-lint-ignore no-explicit-any
handler: routeMod.handlers as any ?? undefined,
});
continue;
} else if (normalized.endsWith("/_500")) {
stack.push(routeMod);
const pattern = pathToPattern(normalized.slice(1, -"/_500".length), {
keepGroups: true,
});
if (errorPaths.has(pattern)) continue;
app.onError(pattern, {
config: routeMod.config ?? undefined,
component: routeMod.component ?? undefined,
// deno-lint-ignore no-explicit-any
handler: routeMod.handlers as any ?? undefined,
});
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 (Array.isArray(mod.handlers)) {
middlewares.push(...(mod.handlers as MiddlewareFn<State>[]));
} else if (typeof mod.handlers === "function") {
middlewares.push(mod.handlers as MiddlewareFn<State>);
} else if (isHandlerByMethod(mod.handlers)) {
warnInvalidRoute(
"Middleware does not support object handlers with GET, POST, etc.",
);
}
}
// _app template
if (skipApp && mod.path === "/_app") {
continue;
} else if (!skipApp && mod.config?.skipAppWrapper) {
skipApp = true;
if (hasApp) {
// _app component is always first
components.shift();
}
}
// _layouts
if (skipLayouts && mod.path.endsWith("/_layout")) {
continue;
} else if (mod.handlers !== null && mod.path.endsWith("/_layout")) {
warnInvalidRoute("Layout does not support handlers");
} 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
: ((ctx) => {
const { method } = ctx.req;
if (!Array.isArray(handlers)) {
const maybeFn = handlers[method as Method];
if (maybeFn !== undefined) {
return maybeFn(ctx);
}
}
return ctx.next();
}) as HandlerFn<unknown, State>;
const errorComponents = components.slice();
if (mod.component !== null) {
errorComponents.push(mod.component);
}
let parent = mod.path.slice(0, -"_error".length);
parent = parent + "*";
// Add error route as its own route
if (!specialPaths.has(mod.path)) {
specialPaths.add(mod.path);
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
: ((ctx) => {
const { method } = ctx.req;
if (!Array.isArray(handlers)) {
const maybeFn = handlers[method as Method];
if (maybeFn !== undefined) {
return maybeFn(ctx);
}
}
return ctx.next();
}) as HandlerFn<unknown, State>;
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);
let pattern = pathToPattern(normalized.slice(1), { keepGroups: true });
if (normalized.endsWith("/index")) {
if (!pattern.endsWith("/")) {
pattern += "/";
}
}
const handlers = routeMod.handlers;
const routePath = routeMod.config?.routeOverride ??
pathToPattern(normalized.slice(1));
const routePattern = pathToPattern(normalized.slice(1));
if (routeMod.component !== null) {
components.push(routeMod.component);
const missingGetHandler = isHandlerByMethod(handlers) &&
!Object.keys(handlers).includes("GET");
if (missingGetHandler) {
const combined = middlewares.concat(
renderMiddleware(components, undefined),
);
app.get(routePath, ...combined);
}
}
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);
}
app.route(pattern, {
config: {
...routeMod.config ?? undefined,
routeOverride: routeMod.config?.routeOverride ?? routePattern,
},
component: routeMod.component ?? undefined,
// deno-lint-ignore no-explicit-any
handler: routeMod.handlers as any ?? undefined,
});
}
}
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 as FreshReqContext<State>).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;
}
};
}
function warnInvalidRoute(message: string) {
// deno-lint-ignore no-console
console.warn(
+37 -38
View File
@@ -13,7 +13,8 @@ import { stub } from "@std/testing/mock";
import { type HandlerByMethod, type HandlerFn, page } from "../../handlers.ts";
import type { Method } from "../../router.ts";
import { parseHtml } from "../../../tests/test_utils.tsx";
import type { FreshContext } from "fresh";
import type { FreshContext } from "../../context.ts";
import { HttpError } from "../../error.ts";
async function createServer<T>(
files: Record<string, string | Uint8Array | FreshFsItem<T>>,
@@ -193,13 +194,13 @@ Deno.test("fsRoutes - middleware", async () => {
Deno.test("fsRoutes - nested middlewares", async () => {
const server = await createServer<{ text: string }>({
"routes/_middleware.ts": {
handler: (ctx) => {
handler: function A(ctx) {
ctx.state.text = "A";
return ctx.next();
},
},
"routes/foo/_middleware.ts": {
handler: (ctx) => {
handler: function B(ctx) {
ctx.state.text += "B";
return ctx.next();
},
@@ -332,18 +333,22 @@ Deno.test("fsRoutes - nested _layout", async () => {
default: () => <>foo</>,
},
"routes/foo/_layout.tsx": {
default: (ctx) => (
<>
layout_foo_bar/<ctx.Component />
</>
),
default: function fooBar(ctx) {
return (
<>
layout_foo_bar/<ctx.Component />
</>
);
},
},
"routes/_layout.tsx": {
default: (ctx) => (
<>
layout/<ctx.Component />
</>
),
default: function rootLayout(ctx) {
return (
<>
layout/<ctx.Component />
</>
);
},
},
"routes/_app.tsx": {
default: (ctx) => (
@@ -806,7 +811,7 @@ Deno.test("fsRoutes - _error render component", async () => {
},
"routes/foo/index.tsx": {
handlers: () => {
throw new Error("ok");
throw new Error("failing");
},
},
});
@@ -816,7 +821,8 @@ Deno.test("fsRoutes - _error render component", async () => {
expect(doc.body.firstChild?.textContent).toEqual("ok");
});
Deno.test("fsRoutes - _error render on 404", async () => {
// 404 pages go to the root error page if available
Deno.test.ignore("fsRoutes - _error render on 404", async () => {
// deno-lint-ignore no-explicit-any
let error: any = null;
const server = await createServer({
@@ -828,7 +834,7 @@ Deno.test("fsRoutes - _error render on 404", async () => {
},
},
"routes/foo/_error.tsx": {
default: (ctx) => {
default: function foo2(ctx) {
// deno-lint-ignore no-explicit-any
error = ctx.error as any;
return <p>ok foo</p>;
@@ -1110,34 +1116,23 @@ Deno.test(
"fsRoutes - returns response code from error route",
async () => {
const server = await createServer<{ text: string }>({
"routes/_app.tsx": {
default: (ctx) => {
return (
<div>
_app/<ctx.Component />
</div>
);
},
},
"routes/_error.tsx": {
default: () => <div>fail</div>,
},
"routes/index.tsx": {
default: () => <div>index</div>,
},
"routes/bar.tsx": {
default: () => <div>index</div>,
},
"routes/foo/index.tsx": {
default: () => <div>foo/index</div>,
},
"routes/foo/_error.tsx": {
"routes/fail.tsx": {
default: () => {
throw new Error("fail");
},
},
"routes/foo/bar.tsx": {
default: () => <div>foo/index</div>,
"routes/foo/_error.tsx": {
default: () => {
throw new HttpError(501);
},
},
"routes/foo/fail.tsx": {
default: () => {
throw new Error("fail");
},
},
});
@@ -1145,9 +1140,13 @@ Deno.test(
await res.body?.cancel();
expect(res.status).toEqual(404);
res = await server.get("/foo/asdf");
res = await server.get("/fail");
await res.body?.cancel();
expect(res.status).toEqual(500);
res = await server.get("/foo/fail");
await res.body?.cancel();
expect(res.status).toEqual(501);
},
);
-139
View File
@@ -1,139 +0,0 @@
import { type AnyComponent, h, type RenderableProps, type VNode } from "preact";
import type { MiddlewareFn } from "../../middlewares/mod.ts";
import type { HandlerFn, PageResponse } from "../../handlers.ts";
import type { FreshReqContext, PageProps } from "../../context.ts";
import { HttpError } from "../../error.ts";
import { tracer } from "../../otel.ts";
import { SpanStatusCode } from "@opentelemetry/api";
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;
};
// deno-lint-ignore no-explicit-any
export function isAsyncAnyComponent(fn: any): fn is AsyncAnyComponent<any> {
return typeof fn === "function" && fn.constructor.name === "AsyncFunction";
}
export function renderMiddleware<State>(
components: Array<
| AnyComponent<PageProps<unknown, State>>
| AsyncAnyComponent<PageProps<unknown, State>>
>,
handler: HandlerFn<unknown, State> | undefined,
init?: ResponseInit | undefined,
): MiddlewareFn<State> {
return async (ctx) => {
let result: PageResponse<unknown> | undefined;
if (handler !== undefined) {
const res = await tracer.startActiveSpan("handler", {
attributes: { "fresh.span_type": "fs_routes/handler" },
}, async (span) => {
try {
const res = await handler(ctx);
span.setAttribute(
"fresh.handler_response",
res instanceof Response ? "http" : "data",
);
return res;
} catch (err) {
if (err instanceof Error) {
span.recordException(err);
} else {
span.setStatus({
code: SpanStatusCode.ERROR,
message: String(err),
});
}
throw err;
} finally {
span.end();
}
});
if (res instanceof Response) {
return res;
}
result = res;
}
if (components.length === 0) {
throw new Error(`Did not receive any components to render.`);
}
const props = ctx as FreshReqContext<State>;
props.data = result?.data;
let vnode: VNode | null = null;
for (let i = components.length - 1; i >= 0; i--) {
const child = vnode;
// FIXME: remove when we're using `<Slot />`
props.Component = () => child;
const fn = components[i];
if (isAsyncAnyComponent(fn)) {
const result = await tracer.startActiveSpan(
"invoke async component",
async (span) => {
span.setAttribute("fresh.span_type", "fs_routes/async_component");
try {
const result = (await fn(props)) as VNode | Response;
span.setAttribute(
"fresh.component_response",
result instanceof Response ? "http" : "jsx",
);
return result;
} catch (err) {
if (err instanceof Error) {
span.recordException(err);
} else {
span.setStatus({
code: SpanStatusCode.ERROR,
message: String(err),
});
}
throw err;
} finally {
span.end();
}
},
);
if (result instanceof Response) {
return result;
}
vnode = result;
} else {
// deno-lint-ignore no-explicit-any
vnode = h(components[i] as any, props) as VNode;
}
}
let status: number | undefined = init?.status ?? result?.status;
if (
ctx.error !== null && ctx.error !== undefined
) {
if (
ctx.error instanceof HttpError
) {
status = ctx.error.status;
} else {
status = 500;
}
}
return ctx.render(vnode!, {
status,
statusText: init?.statusText,
headers: init?.headers ?? result?.headers,
});
};
}
@@ -1,125 +0,0 @@
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 () => {
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");
});
+158
View File
@@ -0,0 +1,158 @@
import {
type AnyComponent,
type FunctionComponent,
h,
type RenderableProps,
type VNode,
} from "preact";
import {
FreshScripts,
type RenderState,
setRenderState,
} from "./runtime/server/preact_hooks.tsx";
import type { Context } from "./context.ts";
import { recordSpanError, tracer } from "./otel.ts";
import type { BuildCache } from "./build_cache.ts";
import { DEV_ERROR_OVERLAY_URL } from "./constants.ts";
import { renderToString } from "preact-render-to-string";
import { BUILD_ID } from "./runtime/build_id.ts";
export type AsyncAnyComponent<P> = {
(
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;
};
// deno-lint-ignore no-explicit-any
export function isAsyncAnyComponent(fn: any): fn is AsyncAnyComponent<any> {
return typeof fn === "function" && fn.constructor.name === "AsyncFunction";
}
export async function renderAsyncAnyComponent<Props>(
fn: AsyncAnyComponent<Props>,
props: RenderableProps<Props>,
) {
return await tracer.startActiveSpan(
"invoke async component",
async (span) => {
span.setAttribute("fresh.span_type", "fs_routes/async_component");
try {
const result = (await fn(props)) as VNode | Response;
span.setAttribute(
"fresh.component_response",
result instanceof Response ? "http" : "jsx",
);
return result;
} catch (err) {
recordSpanError(span, err);
throw err;
} finally {
span.end();
}
},
);
}
export function preactRender<State, Data>(
vnode: VNode,
ctx: PageProps<Data, State>,
state: RenderState,
buildCache: BuildCache,
headers: Headers,
) {
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 {
// Add preload headers
const basePath = ctx.config.basePath;
const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
let link = `<${encodeURI(runtimeUrl)}>; rel="modulepreload"; as="script"`;
state.islands.forEach((island) => {
const chunk = buildCache.getIslandChunkName(island.name);
if (chunk !== null) {
link += `, <${
encodeURI(`${basePath}${chunk}`)
}>; rel="modulepreload"; as="script"`;
}
});
if (link !== "") {
headers.append("Link", link);
}
state.clear();
setRenderState(null);
}
}
export type PageProps<Data = unknown, T = unknown> =
& Pick<
Context<T>,
| "config"
| "url"
| "req"
| "params"
| "info"
| "state"
| "isPartial"
| "Component"
| "error"
>
& { data: Data };
export interface ComponentDef<Data, State> {
props: PageProps<Data, State> | null;
component: AnyComponent<PageProps<Data, State>>;
}
export async function renderRouteComponent<State>(
ctx: Context<State>,
def: ComponentDef<unknown, State>,
child: FunctionComponent,
): Promise<VNode | Response> {
const vnodeProps: PageProps<unknown, State> = {
Component: child,
config: ctx.config,
data: def.props,
error: ctx.error,
info: ctx.info,
isPartial: ctx.isPartial,
params: ctx.params,
req: ctx.req,
state: ctx.state,
url: ctx.url,
};
if (isAsyncAnyComponent(def.component)) {
const result = await renderAsyncAnyComponent(def.component, vnodeProps);
if (result instanceof Response) {
return result;
}
return result;
}
return h(def.component, vnodeProps) as VNode;
}
+184 -81
View File
@@ -1,119 +1,180 @@
export type Method = "HEAD" | "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
export type Method =
| "HEAD"
| "GET"
| "POST"
| "PATCH"
| "PUT"
| "DELETE"
| "OPTIONS";
export interface Route<T> {
path: string | URLPattern;
method: Method | "ALL";
handlers: T[];
export type RouteByMethod<T> = {
[m in Method]: T[];
};
export interface StaticRouteDef<T> {
pattern: string | URLPattern;
byMethod: RouteByMethod<T>;
}
export interface DynamicRouteDef<T> {
pattern: URLPattern;
byMethod: RouteByMethod<T>;
}
export interface RouteResult<T> {
params: Record<string, string>;
handlers: T[][];
handlers: T[];
methodMatch: boolean;
patternMatch: boolean;
pattern: string | null;
}
export interface Router<T> {
_routes: Route<T>[];
_middlewares: T[];
addMiddleware(fn: T): void;
add(
method: Method | "ALL",
pathname: string | URLPattern,
method: Method | "OPTIONS" | "ALL",
pathname: string,
handlers: T[],
unshift?: boolean,
): void;
match(method: Method, url: URL): RouteResult<T>;
match(method: Method, url: URL, init?: T[]): RouteResult<T>;
getAllowedMethods(pattern: string): string[];
}
export const IS_PATTERN = /[*:{}+?()]/;
export class UrlPatternRouter<T> implements Router<T> {
readonly _routes: Route<T>[] = [];
readonly _middlewares: T[] = [];
const EMPTY: string[] = [];
addMiddleware(fn: T): void {
this._middlewares.push(fn);
export class UrlPatternRouter<T> implements Router<T> {
#statics = new Map<string, StaticRouteDef<T>>();
#dynamics = new Map<string, DynamicRouteDef<T>>();
#dynamicArr: DynamicRouteDef<T>[] = [];
#allowed = new Map<string, Set<string>>();
getAllowedMethods(pattern: string): string[] {
const allowed = this.#allowed.get(pattern);
if (allowed === undefined) return EMPTY;
return Array.from(allowed);
}
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,
});
add(
method: Method | "ALL",
pathname: string,
handlers: T[],
unshift = false,
) {
let allowed = this.#allowed.get(pathname);
if (allowed === undefined) {
allowed = new Set();
this.#allowed.set(pathname, allowed);
}
if (method === "ALL") {
allowed.add("GET");
allowed.add("POST");
allowed.add("PATCH");
allowed.add("PUT");
allowed.add("DELETE");
allowed.add("HEAD");
allowed.add("OPTIONS");
} else {
this._routes.push({
path: pathname,
handlers,
method,
});
allowed.add(method);
}
let byMethod: RouteByMethod<T>;
if (IS_PATTERN.test(pathname)) {
let def = this.#dynamics.get(pathname);
if (def === undefined) {
def = {
pattern: new URLPattern({ pathname }),
byMethod: {
DELETE: [],
GET: [],
HEAD: [],
OPTIONS: [],
PATCH: [],
POST: [],
PUT: [],
},
};
this.#dynamics.set(pathname, def);
this.#dynamicArr.push(def);
}
byMethod = def.byMethod;
} else {
let def = this.#statics.get(pathname);
if (def === undefined) {
def = {
pattern: pathname,
byMethod: {
DELETE: [],
GET: [],
HEAD: [],
OPTIONS: [],
PATCH: [],
POST: [],
PUT: [],
},
};
this.#statics.set(pathname, def);
}
byMethod = def.byMethod;
}
const fn = unshift ? "unshift" : "push";
if (method === "ALL") {
byMethod.DELETE[fn](...handlers);
byMethod.GET[fn](...handlers);
byMethod.HEAD[fn](...handlers);
byMethod.OPTIONS[fn](...handlers);
byMethod.PATCH[fn](...handlers);
byMethod.POST[fn](...handlers);
byMethod.PUT[fn](...handlers);
} else {
byMethod[method][fn](...handlers);
}
}
match(method: Method, url: URL): RouteResult<T> {
match(method: Method, url: URL, init: T[] = []): RouteResult<T> {
const result: RouteResult<T> = {
params: {},
handlers: [],
params: Object.create(null),
handlers: init,
methodMatch: false,
patternMatch: false,
pattern: null,
};
if (this._middlewares.length > 0) {
result.handlers.push(this._middlewares);
const staticMatch = this.#statics.get(url.pathname);
if (staticMatch !== undefined) {
result.pattern = url.pathname;
const handlers = staticMatch.byMethod[method];
if (handlers.length > 0) {
result.methodMatch = true;
result.handlers.push(...handlers);
}
return result;
}
for (let i = 0; i < this._routes.length; i++) {
const route = this._routes[i];
for (let i = 0; i < this.#dynamicArr.length; i++) {
const route = this.#dynamicArr[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;
result.pattern = route.path;
const match = route.pattern.exec(url);
if (match === null) continue;
if (route.method === "ALL" || route.method === method) {
result.handlers.push(route.handlers);
result.pattern = route.pattern.pathname;
if (route.path === "/*" && route.method === "ALL") {
continue;
}
const handlers = route.byMethod[method];
if (handlers.length > 0) {
result.methodMatch = true;
result.handlers.push(...handlers);
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;
result.pattern = route.path.pathname;
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)) {
result.params[key] = value === undefined ? "" : decodeURI(value);
}
if (route.method === "ALL") {
continue;
}
result.methodMatch = true;
return result;
}
// Decode matched params
for (const [key, value] of Object.entries(match.pathname.groups)) {
result.params[key] = value === undefined ? "" : decodeURI(value);
}
}
break;
}
return result;
@@ -123,7 +184,10 @@ export class UrlPatternRouter<T> implements Router<T> {
/**
* Transform a filesystem URL path to a `path-to-regex` style matcher.
*/
export function pathToPattern(path: string): string {
export function pathToPattern(
path: string,
options?: { keepGroups: boolean },
): string {
const parts = path.split("/");
if (parts[parts.length - 1] === "index") {
if (parts.length === 1) {
@@ -148,7 +212,7 @@ export function pathToPattern(path: string): string {
// Case: /foo/(bar) -> /foo
// Case: /foo/(bar)/bob -> /foo/bob
// Case: /(foo)/bar -> /bar
if (part.startsWith("(") && part.endsWith(")")) {
if (!options?.keepGroups && part.startsWith("(") && part.endsWith(")")) {
continue;
}
@@ -216,3 +280,42 @@ export function pathToPattern(path: string): string {
return route;
}
export function patternToSegments(
path: string,
root: string,
includeLast: boolean = false,
): string[] {
const out: string[] = [root];
if (path === "/" || path === "*" || path === "/*") return out;
let start = -1;
for (let i = 0; i < path.length; i++) {
const ch = path[i];
if (ch === "/") {
if (i > 0) {
const raw = path.slice(start + 1, i);
out.push(raw);
}
start = i;
}
}
if (includeLast && start < path.length - 1) {
out.push(path.slice(start + 1));
}
return out;
}
export function mergePath(basePath: string, path: string): string {
if (basePath.endsWith("*")) basePath = basePath.slice(0, -1);
if (basePath === "/") basePath = "";
if (path === "*" || path === "/*") path = "/*";
const s = (basePath !== "" && path === "/") ? "" : path;
return basePath + s;
}
+44 -51
View File
@@ -1,5 +1,11 @@
import { expect } from "@std/expect";
import { IS_PATTERN, pathToPattern, UrlPatternRouter } from "./router.ts";
import {
IS_PATTERN,
mergePath,
pathToPattern,
patternToSegments,
UrlPatternRouter,
} from "./router.ts";
Deno.test("IS_PATTERN", () => {
expect(IS_PATTERN.test("/foo")).toEqual(false);
@@ -11,66 +17,26 @@ Deno.test("IS_PATTERN", () => {
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,
pattern: "/",
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,
pattern: "/",
patternMatch: true,
});
});
Deno.test("UrlPatternRouter - GET extract params", () => {
const router = new UrlPatternRouter();
const A = () => {};
router.add("GET", new URLPattern({ pathname: "/:foo/:bar/c" }), [A]);
router.add("GET", "/: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]],
handlers: [A],
methodMatch: true,
pattern: "/:foo/:bar/c",
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]],
handlers: [A],
methodMatch: true,
pattern: "/:foo/:bar/c",
patternMatch: true,
});
});
@@ -81,11 +47,10 @@ Deno.test("UrlPatternRouter - Wrong method match", () => {
const res = router.match("POST", new URL("/foo", "http://localhost"));
expect(res).toEqual({
params: {},
params: Object.create(null),
handlers: [],
methodMatch: false,
pattern: "/foo",
patternMatch: true,
});
});
@@ -98,11 +63,10 @@ Deno.test("UrlPatternRouter - wrong + correct method", () => {
const res = router.match("POST", new URL("/foo", "http://localhost"));
expect(res).toEqual({
params: {},
handlers: [[B]],
params: Object.create(null),
handlers: [B],
methodMatch: true,
pattern: "/foo",
patternMatch: true,
});
});
@@ -116,10 +80,9 @@ Deno.test("UrlPatternRouter - convert patterns automatically", () => {
params: {
id: "foo",
},
handlers: [[A]],
handlers: [A],
methodMatch: true,
pattern: "/books/:id",
patternMatch: true,
});
});
@@ -170,4 +133,34 @@ Deno.test("pathToPattern", async (t) => {
expect(() => pathToPattern("foo/foo-[[name]]")).toThrow();
expect(() => pathToPattern("foo/[[name]]-bar")).toThrow();
});
await t.step("keep groups", () => {
expect(pathToPattern("foo/(foo)/bar", { keepGroups: true })).toEqual(
"/foo/(foo)/bar",
);
});
});
Deno.test("patternToSegments", () => {
expect(patternToSegments("/", "")).toEqual([""]);
expect(patternToSegments("/foo", "")).toEqual([""]);
expect(patternToSegments("/foo/bar", "")).toEqual(["", "foo"]);
expect(patternToSegments("/:foo", "")).toEqual([""]);
expect(patternToSegments("/:foo/:bar", "")).toEqual(["", ":foo"]);
expect(patternToSegments("/:foo-:bar/foo", "")).toEqual(["", ":foo-:bar"]);
expect(patternToSegments("/foo/", "")).toEqual(["", "foo"]);
expect(patternToSegments("/foo/bar", "", true)).toEqual(["", "foo", "bar"]);
});
Deno.test("mergePath", () => {
expect(mergePath("", "/foo")).toEqual("/foo");
expect(mergePath("/", "/foo")).toEqual("/foo");
expect(mergePath("/foo/bar", "/")).toEqual("/foo/bar");
expect(mergePath("/foo/bar", "/baz")).toEqual("/foo/bar/baz");
expect(mergePath("*", "/baz")).toEqual("/baz");
expect(mergePath("/*", "/baz")).toEqual("/baz");
expect(mergePath("/foo", "*")).toEqual("/foo/*");
expect(mergePath("/foo", "/*")).toEqual("/foo/*");
});
+3 -2
View File
@@ -11,7 +11,7 @@ import {
} from "preact";
import type { Signal } from "@preact/signals";
import type { Stringifiers } from "../../jsonify/stringify.ts";
import type { PageProps } from "../../context.ts";
import type { PageProps } from "../../render.ts";
import { Partial, type PartialProps } from "../shared.ts";
import { stringify } from "../../jsonify/stringify.ts";
import type { ServerIslandRegistry } from "../../context.ts";
@@ -88,7 +88,8 @@ export class RenderState {
hasRuntimeScript = false;
constructor(
public ctx: PageProps<unknown, unknown>,
// deno-lint-ignore no-explicit-any
public ctx: PageProps<any, any>,
public islandRegistry: ServerIslandRegistry,
public buildCache: BuildCache,
public partialId: string,
+214
View File
@@ -0,0 +1,214 @@
import type { AnyComponent } from "preact";
import type { MiddlewareFn } from "./middlewares/mod.ts";
import { type Method, patternToSegments } from "./router.ts";
import type { LayoutConfig, Route } from "./types.ts";
import { type Context, getInternals } from "./context.ts";
import { recordSpanError, tracer } from "./otel.ts";
import { isHandlerByMethod } from "./handlers.ts";
import {
type AsyncAnyComponent,
type PageProps,
renderRouteComponent,
} from "./render.ts";
import { HttpError } from "./error.ts";
export type RouteComponent<State> =
| AsyncAnyComponent<PageProps<unknown, State>>
| AnyComponent<PageProps<unknown, State>>;
export interface Segment<State> {
pattern: string;
middlewares: MiddlewareFn<State>[];
layout: {
component: RouteComponent<State>;
config: LayoutConfig | null;
} | null;
errorRoute: Route<State> | null;
notFound: MiddlewareFn<State> | null;
app: RouteComponent<State> | null;
children: Map<string, Segment<State>>;
parent: Segment<State> | null;
}
export function newSegment<State>(
pattern: string,
parent: Segment<State> | null,
): Segment<State> {
return {
pattern,
middlewares: [],
layout: null,
app: null,
errorRoute: null,
notFound: null,
parent,
children: new Map(),
};
}
export function getOrCreateSegment<State>(
root: Segment<State>,
path: string,
includeLast: boolean,
): Segment<State> {
let current = root;
const segments = patternToSegments(path, root.pattern, includeLast);
for (let i = 0; i < segments.length; i++) {
const seg = segments[i];
if (seg === root.pattern) {
current = root;
} else {
let child = current.children.get(seg);
if (child === undefined) {
child = newSegment(seg, current);
current.children.set(seg, child);
}
current = child;
}
}
return current;
}
export function segmentToMiddlewares<State>(
segment: Segment<State>,
): MiddlewareFn<State>[] {
const result: MiddlewareFn<State>[] = [];
const stack: Segment<State>[] = [];
let current: Segment<State> | null = segment;
while (current !== null) {
stack.push(current);
current = current.parent;
}
const root = stack.at(-1)!;
for (let i = stack.length - 1; i >= 0; i--) {
const seg = stack[i];
const { layout, app, errorRoute } = seg;
result.push(async function segmentMiddleware(ctx) {
const internals = getInternals(ctx);
const prevApp = internals.app;
const prevLayouts = internals.layouts;
if (app !== null) {
internals.app = app;
}
if (layout !== null) {
if (layout.config?.skipAppWrapper) {
internals.app = null;
}
const def = { props: null, component: layout.component };
if (layout.config?.skipInheritedLayouts) {
internals.layouts = [def];
} else {
internals.layouts = [...internals.layouts, def];
}
}
try {
return await ctx.next();
} catch (err) {
const status = err instanceof HttpError ? err.status : 500;
if (root.notFound !== null && status === 404) {
return await root.notFound(ctx);
}
if (errorRoute !== null) {
return await renderRoute(ctx, errorRoute, status);
}
throw err;
} finally {
internals.app = prevApp;
internals.layouts = prevLayouts;
}
});
if (seg.middlewares.length > 0) {
result.push(...seg.middlewares);
}
}
return result;
}
export async function renderRoute<State>(
ctx: Context<State>,
route: Route<State>,
status = 200,
): Promise<Response> {
const internals = getInternals(ctx);
if (route.config?.skipAppWrapper) {
internals.app = null;
}
if (route.config?.skipInheritedLayouts) {
internals.layouts = [];
}
const method = ctx.req.method as Method;
const handlers = route.handler;
if (handlers === undefined) {
throw new Error(`Unexpected missing handlers`);
}
const headers = new Headers();
headers.set("Content-Type", "text/html;charset=utf-8");
const res = await tracer.startActiveSpan("handler", {
attributes: { "fresh.span_type": "fs_routes/handler" },
}, async (span) => {
try {
const fn = isHandlerByMethod(handlers)
? handlers[method] ?? null
: handlers;
if (fn === null) return await ctx.next();
return await fn(ctx);
} catch (err) {
recordSpanError(span, err);
throw err;
} finally {
span.end();
}
});
if (res instanceof Response) {
return res;
}
if (typeof res.status === "number") {
status = res.status;
}
if (res.headers) {
for (const [name, value] of Object.entries(res.headers)) {
headers.set(name, value);
}
}
let vnode = null;
if (route.component !== undefined) {
const result = await renderRouteComponent(ctx, {
component: route.component,
// deno-lint-ignore no-explicit-any
props: res.data as any,
}, () => null);
if (result instanceof Response) {
return result;
}
vnode = result;
}
return ctx.render(vnode, { headers, status });
}
+34
View File
@@ -0,0 +1,34 @@
import { expect } from "@std/expect";
import { getOrCreateSegment, newSegment } from "./segments.ts";
Deno.test("findOrCreateSegment - root", () => {
const root = newSegment("", null);
const found = getOrCreateSegment(root, "", false);
expect(found).toEqual(root);
});
Deno.test("findOrCreateSegment - /foo/bar", () => {
const root = newSegment("", null);
const found = getOrCreateSegment(root, "/foo/bar", false);
expect(found).toEqual(root.children.get("foo"));
});
Deno.test("findOrCreateSegment - /:foo/bar/:baz", () => {
const root = newSegment("", null);
const found = getOrCreateSegment(root, "/:foo/bar/:baz", false);
expect(found).toEqual(
root.children.get(":foo")?.children.get("bar"),
);
});
Deno.test("findOrCreateSegment - /foo/bar/", () => {
const root = newSegment("", null);
const found = getOrCreateSegment(root, "/foo/bar/", false);
expect(found).toEqual(root.children.get("foo")?.children.get("bar"));
});
Deno.test("findOrCreateSegment - /foo/bar with last", () => {
const root = newSegment("", null);
const found = getOrCreateSegment(root, "/foo/bar", true);
expect(found).toEqual(root.children.get("foo")?.children.get("bar"));
});
+12 -3
View File
@@ -1,4 +1,4 @@
import { FreshReqContext } from "./context.ts";
import { Context } from "./context.ts";
import type { FsAdapter } from "./fs.ts";
import { type BuildCache, ProdBuildCache } from "./build_cache.ts";
import type { ResolvedFreshConfig } from "./config.ts";
@@ -45,6 +45,15 @@ export class FakeServer {
const req = new Request(url, { method: "head" });
return await this.handler(req, STUB);
}
async options(path: string): Promise<Response> {
const url = this.toUrl(path);
const req = new Request(url, { method: "options" });
return await this.handler(req, STUB);
}
async request(req: Request): Promise<Response> {
return await this.handler(req, STUB);
}
private toUrl(path: string) {
return new URL(path, "http://localhost/");
@@ -62,7 +71,7 @@ const DEFAULT_CONFIG: ResolvedFreshConfig = {
};
export function serveMiddleware<T>(
middleware: (ctx: FreshReqContext<T>) => Response | Promise<Response>,
middleware: (ctx: Context<T>) => Response | Promise<Response>,
options: {
config?: ResolvedFreshConfig;
buildCache?: BuildCache;
@@ -76,7 +85,7 @@ export function serveMiddleware<T>(
const buildCache = options.buildCache ??
new ProdBuildCache(config, new Map(), new Map(), true);
const ctx = new FreshReqContext<T>(
const ctx = new Context<T>(
req,
new URL(req.url),
DEFAULT_CONN_INFO,
+9
View File
@@ -1,3 +1,6 @@
import type { RouteHandler } from "./handlers.ts";
import type { RouteComponent } from "./segments.ts";
export interface RouteConfig {
/**
* A route override for the page. This is useful for pages where the route
@@ -42,6 +45,12 @@ export interface LayoutConfig {
skipAppWrapper?: boolean;
}
export interface Route<State> {
component?: RouteComponent<State>;
config?: RouteConfig;
handler?: RouteHandler<unknown, State>;
}
// TODO: Uncomment once JSR supports global types
// declare global {
// namespace preact.createElement.JSX {
-19
View File
@@ -14,25 +14,6 @@ export function assertInDir(
}
}
/**
* Joins two path segments into a single normalized path.
* @example
* ```ts
* mergePaths("/api", "users"); // "/api/users"
* mergePaths("/api/", "/users"); // "/api/users"
* mergePaths("/", "/users"); // "/users"
* mergePaths("", "/users"); // "/users"
* mergePaths("/api", "/users"); // "/api/users"
* ```
*/
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;
if (!b.startsWith("/")) return a + "/" + b;
return a + b;
}
/**
* Converts a file path to a valid JS export name.
*
+1 -10
View File
@@ -1,14 +1,5 @@
import { expect } from "@std/expect";
import { escapeScript, mergePaths, pathToExportName } from "./utils.ts";
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");
});
import { escapeScript, pathToExportName } from "./utils.ts";
Deno.test("filenameToExportName", () => {
expect(pathToExportName("/islands/foo.tsx")).toBe("foo");
+2 -3
View File
@@ -1,4 +1,4 @@
import { App, staticFiles } from "fresh";
import { App } from "fresh";
import {
allIslandApp,
assertNotSelector,
@@ -27,8 +27,7 @@ function testApp<T>(): App<T> {
const app = new App<T>()
.island(selfCounter, "SelfCounter", SelfCounter)
.island(partialInIsland, "PartialInIsland", PartialInIsland)
.island(jsonIsland, "JsonIsland", JsonIsland)
.use(staticFiles());
.island(jsonIsland, "JsonIsland", JsonIsland);
setBuildCache(app, getBuildCache(allIslandApp));
return app;
}
+1 -23
View File
@@ -19,7 +19,6 @@ import {
withBrowserApp,
} from "./test_utils.tsx";
import { parseHtml, waitForText } from "./test_utils.tsx";
import { staticFiles } from "../src/middlewares/static_files.ts";
import { expect } from "@std/expect";
import { JsxConditional } from "./fixtures_islands/JsxConditional.tsx";
import { FnIsland } from "./fixtures_islands/FnIsland.tsx";
@@ -47,7 +46,6 @@ Deno.test({
const counterIsland = getIsland("Counter.tsx");
const app = testApp()
.use(staticFiles())
.island(counterIsland, "Counter", Counter)
.get("/", (ctx) => {
const sig = signal(3);
@@ -73,7 +71,6 @@ Deno.test({
const multipleIslands = getIsland("Multiple.tsx");
const app = testApp()
.use(staticFiles())
.island(multipleIslands, "Multiple1", Multiple1)
.island(multipleIslands, "Multiple2", Multiple2)
.get("/", (ctx) => {
@@ -103,7 +100,6 @@ Deno.test({
const counterIsland = getIsland("Counter.tsx");
const app = testApp()
.use(staticFiles())
.island(counterIsland, "Counter", Counter)
.get("/", (ctx) => {
const sig = signal(0);
@@ -132,7 +128,6 @@ Deno.test({
const jsonIsland = getIsland("JsonIsland.tsx");
const app = testApp()
.use(staticFiles())
.island(jsonIsland, "JsonIsland", Counter)
.get("/", (ctx) => {
return ctx.render(
@@ -160,7 +155,6 @@ Deno.test({
const nullIsland = getIsland("NullIsland.tsx");
const app = testApp()
.use(staticFiles())
.island(nullIsland, "NullIsland", NullIsland)
.get("/", (ctx) => {
return ctx.render(
@@ -184,7 +178,6 @@ Deno.test({
const islandInIsland = getIsland("IslandInIsland.tsx");
const app = testApp()
.use(staticFiles())
.island(counter, "Counter", Counter)
.island(islandInIsland, "IslandInIsland", IslandInIsland)
.get("/", (ctx) => {
@@ -213,7 +206,6 @@ Deno.test({
const jsxIsland = getIsland("JsxIsland.tsx");
const app = testApp()
.use(staticFiles())
.island(jsxIsland, "JsxIsland", JsxIsland)
.get("/", (ctx) => {
return ctx.render(
@@ -241,7 +233,6 @@ Deno.test({
const jsxIsland = getIsland("JsxIsland.tsx");
const app = testApp()
.use(staticFiles())
.island(jsxIsland, "JsxIsland", JsxIsland)
.get("/", (ctx) => {
return ctx.render(
@@ -271,7 +262,6 @@ Deno.test({
const jsxChildrenIsland = getIsland("JsxChildrenIsland.tsx");
const app = testApp()
.use(staticFiles())
.island(jsxChildrenIsland, "JsxChildrenIsland", JsxChildrenIsland)
.get("/", (ctx) => {
return ctx.render(
@@ -307,7 +297,6 @@ Deno.test({
const selfCounter = getIsland("SelfCounter.tsx");
const app = testApp()
.use(staticFiles())
.island(passThrough, "PassThrough", PassThrough)
.island(selfCounter, "SelfCounter", SelfCounter)
.get("/", (ctx) => {
@@ -339,7 +328,6 @@ Deno.test({
const selfCounter = getIsland("SelfCounter.tsx");
const app = testApp()
.use(staticFiles())
.island(counterWithSlots, "CounterWithSlots", CounterWithSlots)
.island(selfCounter, "SelfCounter", SelfCounter)
.get("/", (ctx) => {
@@ -382,7 +370,6 @@ Deno.test({
const selfCounter = getIsland("SelfCounter.tsx");
const app = testApp()
.use(staticFiles())
.island(passThrough, "PassThrough", PassThrough)
.island(selfCounter, "SelfCounter", SelfCounter)
.get("/", (ctx) => {
@@ -424,7 +411,6 @@ Deno.test({
const selfCounter = getIsland("SelfCounter.tsx");
const app = testApp()
.use(staticFiles())
.island(jsxConditional, "JsxConditional", JsxConditional)
.island(selfCounter, "SelfCounter", SelfCounter)
.get("/", (ctx) => {
@@ -466,7 +452,6 @@ Deno.test({
const jsxConditional = getIsland("JsxConditional.tsx");
const app = testApp()
.use(staticFiles())
.island(jsxConditional, "JsxConditional", JsxConditional)
.get("/", (ctx) => {
return ctx.render(
@@ -541,7 +526,6 @@ Deno.test({
const fnIsland = getIsland("FnIsland.tsx");
const app = testApp()
.use(staticFiles())
.island(fragmentIsland, "FragmentIsland", FragmentIsland)
.island(fnIsland, "FnIsland", FnIsland)
.get("/", (ctx) => {
@@ -570,7 +554,6 @@ Deno.test({
const escapeIsland = getIsland("EscapeIsland.tsx");
const app = testApp()
.use(staticFiles())
.island(escapeIsland, "EscapeIsland", EscapeIsland)
.get("/", (ctx) => {
return ctx.render(
@@ -667,7 +650,6 @@ Deno.test({
const nodeProcess = getIsland("NodeProcess.tsx");
const app = testApp()
.use(staticFiles())
.island(nodeProcess, "NodeProcess", NodeProcess)
.get("/", (ctx) =>
ctx.render(
@@ -695,7 +677,6 @@ Deno.test({
const selfCounter = getIsland("SelfCounter.tsx");
const app = testApp({ basePath: "/foo" })
.use(staticFiles())
.island(selfCounter, "SelfCounter", SelfCounter)
.get("/", (ctx) =>
ctx.render(
@@ -720,7 +701,6 @@ Deno.test({
const freshAttrs = getIsland("FreshAttrs.tsx");
const app = testApp()
.use(staticFiles())
.island(freshAttrs, "FreshAttrs", FreshAttrs)
.get("/", (ctx) =>
ctx.render(
@@ -747,8 +727,7 @@ Deno.test({
Deno.test({
name: "fsRoutes - load islands from group folder",
fn: async () => {
const app = testApp()
.use(staticFiles());
const app = testApp();
await fsRoutes(app, {
dir: path.join(
@@ -778,7 +757,6 @@ Deno.test({
const selfCounter = getIsland("SelfCounter.tsx");
const app = testApp()
.use(staticFiles())
.island(selfCounter, "SelfCounter", SelfCounter)
.get("/", (ctx) =>
ctx.render(
+2 -3
View File
@@ -1,4 +1,4 @@
import { App, staticFiles } from "fresh";
import { App } from "fresh";
import { Partial } from "fresh/runtime";
import {
allIslandApp,
@@ -40,8 +40,7 @@ function testApp<T>(): App<T> {
.island(selfCounter, "SelfCounter", SelfCounter)
.island(partialInIsland, "PartialInIsland", PartialInIsland)
.island(jsonIsland, "JsonIsland", JsonIsland)
.island(optOutPartialLink, "OptOutPartialLink", OptOutPartialLink)
.use(staticFiles());
.island(optOutPartialLink, "OptOutPartialLink", OptOutPartialLink);
setBuildCache(app, getBuildCache(allIslandApp));
return app;
+1 -2
View File
@@ -1,7 +1,6 @@
import { App, fsRoutes, staticFiles, trailingSlashes } from "fresh";
import { App, fsRoutes, trailingSlashes } from "fresh";
export const app = new App({ root: import.meta.url })
.use(staticFiles())
.use(trailingSlashes("never"));
await fsRoutes(app, {
+1 -1
View File
@@ -1,4 +1,4 @@
import type { PageProps } from "../../../src/context.ts";
import type { PageProps } from "@fresh/core";
export default function Layout({ Component }: PageProps) {
return (