+42
-23
@@ -22,6 +22,7 @@ import {
|
||||
Handler,
|
||||
Island,
|
||||
Middleware,
|
||||
MiddlewareHandlerContext,
|
||||
MiddlewareModule,
|
||||
MiddlewareRoute,
|
||||
Plugin,
|
||||
@@ -310,8 +311,12 @@ export class ServerContext {
|
||||
* by fresh, including static files.
|
||||
*/
|
||||
handler(): RequestHandler {
|
||||
const inner = router.router<RouterState>(...this.#handlers());
|
||||
const withMiddlewares = this.#composeMiddlewares(this.#middlewares);
|
||||
const handlers = this.#handlers();
|
||||
const inner = router.router<RouterState>(handlers);
|
||||
const withMiddlewares = this.#composeMiddlewares(
|
||||
this.#middlewares,
|
||||
handlers.errorHandler,
|
||||
);
|
||||
return async function handler(req: Request, connInfo: ConnInfo) {
|
||||
// Redirect requests that end with a trailing slash
|
||||
// to their non-trailing slash counterpart.
|
||||
@@ -346,11 +351,14 @@ export class ServerContext {
|
||||
* Identify which middlewares should be applied for a request,
|
||||
* chain them and return a handler response
|
||||
*/
|
||||
#composeMiddlewares(middlewares: MiddlewareRoute[]) {
|
||||
#composeMiddlewares(
|
||||
middlewares: MiddlewareRoute[],
|
||||
errorHandler: router.ErrorHandler<RouterState>,
|
||||
) {
|
||||
return (
|
||||
req: Request,
|
||||
connInfo: ConnInfo,
|
||||
inner: router.Handler<RouterState>,
|
||||
inner: router.FinalHandler<RouterState>,
|
||||
) => {
|
||||
// identify middlewares to apply, if any.
|
||||
// middlewares should be already sorted from deepest to shallow layer
|
||||
@@ -358,30 +366,38 @@ export class ServerContext {
|
||||
|
||||
const handlers: (() => Response | Promise<Response>)[] = [];
|
||||
|
||||
const ctx = {
|
||||
const middlewareCtx: MiddlewareHandlerContext = {
|
||||
next() {
|
||||
const handler = handlers.shift()!;
|
||||
return Promise.resolve(handler());
|
||||
},
|
||||
...connInfo,
|
||||
state: {},
|
||||
destination: "route",
|
||||
};
|
||||
|
||||
for (const mw of mws) {
|
||||
if (mw.handler instanceof Array) {
|
||||
for (const handler of mw.handler) {
|
||||
handlers.push(() => handler(req, ctx));
|
||||
handlers.push(() => handler(req, middlewareCtx));
|
||||
}
|
||||
} else {
|
||||
const handler = mw.handler;
|
||||
handlers.push(() => handler(req, ctx));
|
||||
handlers.push(() => handler(req, middlewareCtx));
|
||||
}
|
||||
}
|
||||
|
||||
handlers.push(() => inner(req, ctx));
|
||||
|
||||
const handler = handlers.shift()!;
|
||||
return handler();
|
||||
const ctx = {
|
||||
...connInfo,
|
||||
state: middlewareCtx.state,
|
||||
};
|
||||
const { destination, handler } = inner(
|
||||
req,
|
||||
ctx,
|
||||
);
|
||||
handlers.push(handler);
|
||||
middlewareCtx.destination = destination;
|
||||
return middlewareCtx.next().catch((e) => errorHandler(req, ctx, e));
|
||||
};
|
||||
}
|
||||
|
||||
@@ -389,20 +405,23 @@ export class ServerContext {
|
||||
* This function returns all routes required by fresh as an extended
|
||||
* path-to-regex, to handler mapping.
|
||||
*/
|
||||
#handlers(): [
|
||||
router.Routes<RouterState>,
|
||||
{
|
||||
otherHandler: router.Handler<RouterState>;
|
||||
errorHandler: router.ErrorHandler<RouterState>;
|
||||
},
|
||||
] {
|
||||
#handlers(): {
|
||||
internalRoutes: router.Routes<RouterState>;
|
||||
staticRoutes: router.Routes<RouterState>;
|
||||
routes: router.Routes<RouterState>;
|
||||
|
||||
otherHandler: router.Handler<RouterState>;
|
||||
errorHandler: router.ErrorHandler<RouterState>;
|
||||
} {
|
||||
const internalRoutes: router.Routes<RouterState> = {};
|
||||
const staticRoutes: router.Routes<RouterState> = {};
|
||||
const routes: router.Routes<RouterState> = {};
|
||||
|
||||
routes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = {
|
||||
internalRoutes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = {
|
||||
default: this.#bundleAssetRoute(),
|
||||
};
|
||||
if (this.#dev) {
|
||||
routes[REFRESH_JS_URL] = {
|
||||
internalRoutes[REFRESH_JS_URL] = {
|
||||
default: () => {
|
||||
const js =
|
||||
`new EventSource("${ALIVE_URL}").addEventListener("message", function listener(e) { if (e.data !== "${BUILD_ID}") { this.removeEventListener('message', listener); location.reload(); } });`;
|
||||
@@ -413,7 +432,7 @@ export class ServerContext {
|
||||
});
|
||||
},
|
||||
};
|
||||
routes[ALIVE_URL] = {
|
||||
internalRoutes[ALIVE_URL] = {
|
||||
default: () => {
|
||||
let timerId: number | undefined = undefined;
|
||||
const body = new ReadableStream({
|
||||
@@ -446,7 +465,7 @@ export class ServerContext {
|
||||
const { localUrl, path, size, contentType, etag } of this.#staticFiles
|
||||
) {
|
||||
const route = sanitizePathToRegex(path);
|
||||
routes[route] = {
|
||||
staticRoutes[route] = {
|
||||
"GET": this.#staticFileHandler(
|
||||
localUrl,
|
||||
size,
|
||||
@@ -590,7 +609,7 @@ export class ServerContext {
|
||||
);
|
||||
};
|
||||
|
||||
return [routes, { otherHandler, errorHandler }];
|
||||
return { internalRoutes, staticRoutes, routes, otherHandler, errorHandler };
|
||||
}
|
||||
|
||||
#staticFileHandler(
|
||||
|
||||
+74
-41
@@ -7,6 +7,14 @@ export type Handler<T = unknown> = (
|
||||
ctx: HandlerContext<T>,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
export type FinalHandler<T = unknown> = (
|
||||
req: Request,
|
||||
ctx: HandlerContext<T>,
|
||||
) => {
|
||||
destination: DestinationKind;
|
||||
handler: () => Response | Promise<Response>;
|
||||
};
|
||||
|
||||
export type ErrorHandler<T = unknown> = (
|
||||
req: Request,
|
||||
ctx: HandlerContext<T>,
|
||||
@@ -30,16 +38,22 @@ export interface Routes<T = {}> {
|
||||
[key: string]: { [K in KnownMethod | "default"]?: MatchHandler<T> };
|
||||
}
|
||||
|
||||
export type DestinationKind = "internal" | "static" | "route" | "notFound";
|
||||
|
||||
// deno-lint-ignore ban-types
|
||||
export type InternalRoute<T = {}> = {
|
||||
pattern: URLPattern;
|
||||
methods: { [K in KnownMethod]?: MatchHandler<T> };
|
||||
default?: MatchHandler<T>;
|
||||
destination: DestinationKind;
|
||||
};
|
||||
|
||||
export interface RouterOptions<T> {
|
||||
otherHandler?: Handler<T>;
|
||||
errorHandler?: ErrorHandler<T>;
|
||||
internalRoutes: Routes<T>;
|
||||
staticRoutes: Routes<T>;
|
||||
routes: Routes<T>;
|
||||
otherHandler: Handler<T>;
|
||||
errorHandler: ErrorHandler<T>;
|
||||
unknownMethodHandler?: UnknownMethodHandler<T>;
|
||||
}
|
||||
|
||||
@@ -86,24 +100,17 @@ export function defaultUnknownMethodHandler(
|
||||
});
|
||||
}
|
||||
|
||||
export function router<T = unknown>(
|
||||
function processRoutes<T>(
|
||||
processedRoutes: InternalRoute<T>[],
|
||||
routes: Routes<T>,
|
||||
{ otherHandler, errorHandler, unknownMethodHandler }: RouterOptions<T> = {
|
||||
otherHandler: defaultOtherHandler,
|
||||
errorHandler: defaultErrorHandler,
|
||||
unknownMethodHandler: defaultUnknownMethodHandler,
|
||||
},
|
||||
): Handler<T> {
|
||||
otherHandler ??= defaultOtherHandler;
|
||||
errorHandler ??= defaultErrorHandler;
|
||||
unknownMethodHandler ??= defaultUnknownMethodHandler;
|
||||
|
||||
const internalRoutes: InternalRoute<T>[] = [];
|
||||
destination: DestinationKind,
|
||||
) {
|
||||
for (const [path, methods] of Object.entries(routes)) {
|
||||
const entry: InternalRoute<T> = {
|
||||
pattern: new URLPattern({ pathname: path }),
|
||||
methods: {},
|
||||
default: undefined,
|
||||
destination,
|
||||
};
|
||||
|
||||
for (const [method, handler] of Object.entries(methods)) {
|
||||
@@ -114,42 +121,68 @@ export function router<T = unknown>(
|
||||
}
|
||||
}
|
||||
|
||||
internalRoutes.push(entry);
|
||||
processedRoutes.push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
return async (req, ctx) => {
|
||||
try {
|
||||
for (const route of internalRoutes) {
|
||||
const res = route.pattern.exec(req.url);
|
||||
export function router<T = unknown>(
|
||||
{
|
||||
internalRoutes,
|
||||
staticRoutes,
|
||||
routes,
|
||||
otherHandler,
|
||||
unknownMethodHandler,
|
||||
}: RouterOptions<T>,
|
||||
): FinalHandler<T> {
|
||||
unknownMethodHandler ??= defaultUnknownMethodHandler;
|
||||
|
||||
if (res !== null) {
|
||||
const groups = res?.pathname.groups ?? {};
|
||||
const processedRoutes: InternalRoute<T>[] = [];
|
||||
processRoutes(processedRoutes, internalRoutes, "internal");
|
||||
processRoutes(processedRoutes, staticRoutes, "static");
|
||||
processRoutes(processedRoutes, routes, "route");
|
||||
|
||||
for (const key in groups) {
|
||||
groups[key] = decodeURIComponent(groups[key]);
|
||||
}
|
||||
return (req, ctx) => {
|
||||
for (const route of processedRoutes) {
|
||||
const res = route.pattern.exec(req.url);
|
||||
|
||||
for (const [method, handler] of Object.entries(route.methods)) {
|
||||
if (req.method === method) {
|
||||
return await handler(req, ctx, groups);
|
||||
}
|
||||
}
|
||||
if (res !== null) {
|
||||
const groups = res?.pathname.groups ?? {};
|
||||
|
||||
if (route.default) {
|
||||
return await route.default(req, ctx, groups);
|
||||
} else {
|
||||
return await unknownMethodHandler!(
|
||||
req,
|
||||
ctx,
|
||||
Object.keys(route.methods) as KnownMethod[],
|
||||
);
|
||||
for (const key in groups) {
|
||||
groups[key] = decodeURIComponent(groups[key]);
|
||||
}
|
||||
|
||||
for (const [method, handler] of Object.entries(route.methods)) {
|
||||
if (req.method === method) {
|
||||
return {
|
||||
destination: route.destination,
|
||||
handler: () => handler(req, ctx, groups),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return await otherHandler!(req, ctx);
|
||||
} catch (err) {
|
||||
return errorHandler!(req, ctx, err);
|
||||
if (route.default) {
|
||||
return {
|
||||
destination: route.destination,
|
||||
handler: () => route.default!(req, ctx, groups),
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
destination: route.destination,
|
||||
handler: () =>
|
||||
unknownMethodHandler!(
|
||||
req,
|
||||
ctx,
|
||||
Object.keys(route.methods) as KnownMethod[],
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
destination: "notFound",
|
||||
handler: () => otherHandler!(req, ctx),
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -201,6 +201,7 @@ export interface MiddlewareHandlerContext<State = Record<string, unknown>>
|
||||
extends ConnInfo {
|
||||
next: () => Promise<Response>;
|
||||
state: State;
|
||||
destination: router.DestinationKind;
|
||||
}
|
||||
|
||||
export interface MiddlewareRoute extends Middleware {
|
||||
|
||||
@@ -50,8 +50,18 @@ async function rootHandler(
|
||||
return resp;
|
||||
}
|
||||
|
||||
async function kindHandler(
|
||||
_req: Request,
|
||||
ctx: MiddlewareHandlerContext,
|
||||
) {
|
||||
const resp = await ctx.next();
|
||||
resp.headers.set("destination", ctx.destination);
|
||||
return resp;
|
||||
}
|
||||
|
||||
export const handler: MiddlewareHandler | MiddlewareHandler[] = [
|
||||
rootHandler,
|
||||
logHandler,
|
||||
kindHandler,
|
||||
corsHandler,
|
||||
];
|
||||
|
||||
@@ -494,6 +494,38 @@ Deno.test({
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test("middleware destination", async (t) => {
|
||||
await t.step("internal", async () => {
|
||||
const resp = await router(
|
||||
new Request("https://fresh.deno.dev/_frsh/refresh.js"),
|
||||
);
|
||||
assert(resp);
|
||||
assertEquals(resp.headers.get("destination"), "internal");
|
||||
await resp.body?.cancel();
|
||||
});
|
||||
|
||||
await t.step("static", async () => {
|
||||
const resp = await router(new Request("https://fresh.deno.dev/foo.txt"));
|
||||
assert(resp);
|
||||
assertEquals(resp.headers.get("destination"), "static");
|
||||
await resp.body?.cancel();
|
||||
});
|
||||
|
||||
await t.step("route", async () => {
|
||||
const resp = await router(new Request("https://fresh.deno.dev/"));
|
||||
assert(resp);
|
||||
assertEquals(resp.headers.get("destination"), "route");
|
||||
await resp.body?.cancel();
|
||||
});
|
||||
|
||||
await t.step("notFound", async () => {
|
||||
const resp = await router(new Request("https://fresh.deno.dev/bar/bar"));
|
||||
assert(resp);
|
||||
assertEquals(resp.headers.get("destination"), "notFound");
|
||||
await resp.body?.cancel();
|
||||
});
|
||||
});
|
||||
|
||||
Deno.test("experimental Deno.serve", {
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
|
||||
Reference in New Issue
Block a user