refactor: include router directly in fresh (#1122)

This PR changes from depending on https://deno.land/x/rutt to instead
include a reduced & simplified version of it.
This commit is contained in:
Leo Kettmeir
2023-04-18 13:27:51 +02:00
committed by GitHub
parent 2fe1e45975
commit 94d3082c45
4 changed files with 230 additions and 64 deletions
+72 -59
View File
@@ -3,13 +3,13 @@ import {
extname, extname,
fromFileUrl, fromFileUrl,
RequestHandler, RequestHandler,
rutt,
Status, Status,
toFileUrl, toFileUrl,
typeByExtension, typeByExtension,
walk, walk,
} from "./deps.ts"; } from "./deps.ts";
import { h } from "preact"; import { h } from "preact";
import * as router from "./router.ts";
import { Manifest } from "./mod.ts"; import { Manifest } from "./mod.ts";
import { Bundler, JSXConfig } from "./bundle.ts"; import { Bundler, JSXConfig } from "./bundle.ts";
import { ALIVE_URL, BUILD_ID, JS_PREFIX, REFRESH_JS_URL } from "./constants.ts"; import { ALIVE_URL, BUILD_ID, JS_PREFIX, REFRESH_JS_URL } from "./constants.ts";
@@ -198,7 +198,7 @@ export class ServerContext {
url, url,
name, name,
component, component,
handler: handler ?? ((req) => rutt.defaultOtherHandler(req)), handler: handler ?? ((req) => router.defaultOtherHandler(req)),
csp: Boolean(config?.csp ?? false), csp: Boolean(config?.csp ?? false),
}; };
} else if ( } else if (
@@ -217,7 +217,7 @@ export class ServerContext {
name, name,
component, component,
handler: handler ?? handler: handler ??
((req, ctx) => rutt.defaultErrorHandler(req, ctx, ctx.error)), ((req, ctx) => router.defaultErrorHandler(req, ctx, ctx.error)),
csp: Boolean(config?.csp ?? false), csp: Boolean(config?.csp ?? false),
}; };
} }
@@ -310,7 +310,7 @@ export class ServerContext {
* by fresh, including static files. * by fresh, including static files.
*/ */
handler(): RequestHandler { handler(): RequestHandler {
const inner = rutt.router<RouterState>(...this.#handlers()); const inner = router.router<RouterState>(...this.#handlers());
const withMiddlewares = this.#composeMiddlewares(this.#middlewares); const withMiddlewares = this.#composeMiddlewares(this.#middlewares);
return async function handler(req: Request, connInfo: ConnInfo) { return async function handler(req: Request, connInfo: ConnInfo) {
// Redirect requests that end with a trailing slash // Redirect requests that end with a trailing slash
@@ -350,7 +350,7 @@ export class ServerContext {
return ( return (
req: Request, req: Request,
connInfo: ConnInfo, connInfo: ConnInfo,
inner: rutt.Handler<RouterState>, inner: router.Handler<RouterState>,
) => { ) => {
// identify middlewares to apply, if any. // identify middlewares to apply, if any.
// middlewares should be already sorted from deepest to shallow layer // middlewares should be already sorted from deepest to shallow layer
@@ -390,47 +390,51 @@ export class ServerContext {
* path-to-regex, to handler mapping. * path-to-regex, to handler mapping.
*/ */
#handlers(): [ #handlers(): [
rutt.Routes<RouterState>, router.Routes<RouterState>,
{ {
otherHandler: rutt.Handler<RouterState>; otherHandler: router.Handler<RouterState>;
errorHandler: rutt.ErrorHandler<RouterState>; errorHandler: router.ErrorHandler<RouterState>;
}, },
] { ] {
const routes: rutt.Routes<RouterState> = {}; const routes: router.Routes<RouterState> = {};
routes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = this
.#bundleAssetRoute();
routes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = {
default: this.#bundleAssetRoute(),
};
if (this.#dev) { if (this.#dev) {
routes[REFRESH_JS_URL] = () => { routes[REFRESH_JS_URL] = {
const js = default: () => {
`new EventSource("${ALIVE_URL}").addEventListener("message", function listener(e) { if (e.data !== "${BUILD_ID}") { this.removeEventListener('message', listener); location.reload(); } });`; const js =
return new Response(js, { `new EventSource("${ALIVE_URL}").addEventListener("message", function listener(e) { if (e.data !== "${BUILD_ID}") { this.removeEventListener('message', listener); location.reload(); } });`;
headers: { return new Response(js, {
"content-type": "application/javascript; charset=utf-8", headers: {
}, "content-type": "application/javascript; charset=utf-8",
}); },
});
},
}; };
routes[ALIVE_URL] = () => { routes[ALIVE_URL] = {
let timerId: number | undefined = undefined; default: () => {
const body = new ReadableStream({ let timerId: number | undefined = undefined;
start(controller) { const body = new ReadableStream({
controller.enqueue(`data: ${BUILD_ID}\nretry: 100\n\n`); start(controller) {
timerId = setInterval(() => { controller.enqueue(`data: ${BUILD_ID}\nretry: 100\n\n`);
controller.enqueue(`data: ${BUILD_ID}\n\n`); timerId = setInterval(() => {
}, 1000); controller.enqueue(`data: ${BUILD_ID}\n\n`);
}, }, 1000);
cancel() { },
if (timerId !== undefined) { cancel() {
clearInterval(timerId); if (timerId !== undefined) {
} clearInterval(timerId);
}, }
}); },
return new Response(body.pipeThrough(new TextEncoderStream()), { });
headers: { return new Response(body.pipeThrough(new TextEncoderStream()), {
"content-type": "text/event-stream", headers: {
}, "content-type": "text/event-stream",
}); },
});
},
}; };
} }
@@ -442,12 +446,14 @@ export class ServerContext {
const { localUrl, path, size, contentType, etag } of this.#staticFiles const { localUrl, path, size, contentType, etag } of this.#staticFiles
) { ) {
const route = sanitizePathToRegex(path); const route = sanitizePathToRegex(path);
routes[`GET@${route}`] = this.#staticFileHandler( routes[route] = {
localUrl, "GET": this.#staticFileHandler(
size, localUrl,
contentType, size,
etag, contentType,
); etag,
),
};
} }
const genRender = <Data = undefined>( const genRender = <Data = undefined>(
@@ -521,16 +527,23 @@ export class ServerContext {
for (const route of this.#routes) { for (const route of this.#routes) {
const createRender = genRender(route, Status.OK); const createRender = genRender(route, Status.OK);
if (typeof route.handler === "function") { if (typeof route.handler === "function") {
routes[route.pattern] = (req, ctx, params) => routes[route.pattern] = {
(route.handler as Handler)(req, { default: (req, ctx, params) =>
...ctx, (route.handler as Handler)(req, {
params, ...ctx,
render: createRender(req, params), params,
renderNotFound: createUnknownRender(req, {}), render: createRender(req, params),
}); renderNotFound: createUnknownRender(req, {}),
}),
};
} else { } else {
routes[route.pattern] = {};
for (const [method, handler] of Object.entries(route.handler)) { for (const [method, handler] of Object.entries(route.handler)) {
routes[`${method}@${route.pattern}`] = (req, ctx, params) => routes[route.pattern][method as router.KnownMethod] = (
req,
ctx,
params,
) =>
handler(req, { handler(req, {
...ctx, ...ctx,
params, params,
@@ -541,7 +554,7 @@ export class ServerContext {
} }
} }
const otherHandler: rutt.Handler<RouterState> = ( const otherHandler: router.Handler<RouterState> = (
req, req,
ctx, ctx,
) => ) =>
@@ -557,7 +570,7 @@ export class ServerContext {
this.#error, this.#error,
Status.InternalServerError, Status.InternalServerError,
); );
const errorHandler: rutt.ErrorHandler<RouterState> = ( const errorHandler: router.ErrorHandler<RouterState> = (
req, req,
ctx, ctx,
error, error,
@@ -585,7 +598,7 @@ export class ServerContext {
size: number, size: number,
contentType: string, contentType: string,
etag: string, etag: string,
): rutt.MatchHandler { ): router.MatchHandler {
return async (req: Request) => { return async (req: Request) => {
const url = new URL(req.url); const url = new URL(req.url);
const key = url.searchParams.get(ASSET_CACHE_BUST_KEY); const key = url.searchParams.get(ASSET_CACHE_BUST_KEY);
@@ -623,7 +636,7 @@ export class ServerContext {
* Returns a router that contains all fresh routes. Should be mounted at * Returns a router that contains all fresh routes. Should be mounted at
* constants.INTERNAL_PREFIX * constants.INTERNAL_PREFIX
*/ */
#bundleAssetRoute = (): rutt.MatchHandler => { #bundleAssetRoute = (): router.MatchHandler => {
return async (_req, _ctx, params) => { return async (_req, _ctx, params) => {
const path = `/${params.path}`; const path = `/${params.path}`;
const file = await this.#bundler.get(path); const file = await this.#bundler.get(path);
@@ -663,7 +676,7 @@ const DEFAULT_NOT_FOUND: UnknownPage = {
pattern: "", pattern: "",
url: "", url: "",
name: "_404", name: "_404",
handler: (req) => rutt.defaultOtherHandler(req), handler: (req) => router.defaultOtherHandler(req),
csp: false, csp: false,
}; };
-3
View File
@@ -16,9 +16,6 @@ export {
typeByExtension, typeByExtension,
} from "https://deno.land/std@0.178.0/media_types/mod.ts"; } from "https://deno.land/std@0.178.0/media_types/mod.ts";
// -- rutt --
export * as rutt from "https://deno.land/x/rutt@0.1.0/mod.ts";
// -- esbuild -- // -- esbuild --
// @deno-types="https://deno.land/x/esbuild@v0.17.11/mod.d.ts" // @deno-types="https://deno.land/x/esbuild@v0.17.11/mod.d.ts"
import * as esbuildWasm from "https://deno.land/x/esbuild@v0.17.11/wasm.js"; import * as esbuildWasm from "https://deno.land/x/esbuild@v0.17.11/wasm.js";
+155
View File
@@ -0,0 +1,155 @@
import type { ConnInfo } from "./deps.ts";
type HandlerContext<T = unknown> = T & ConnInfo;
export type Handler<T = unknown> = (
req: Request,
ctx: HandlerContext<T>,
) => Response | Promise<Response>;
export type ErrorHandler<T = unknown> = (
req: Request,
ctx: HandlerContext<T>,
err: unknown,
) => Response | Promise<Response>;
type UnknownMethodHandler<T = unknown> = (
req: Request,
ctx: HandlerContext<T>,
knownMethods: KnownMethod[],
) => Response | Promise<Response>;
export type MatchHandler<T = unknown> = (
req: Request,
ctx: HandlerContext<T>,
match: Record<string, string>,
) => Response | Promise<Response>;
// deno-lint-ignore ban-types
export interface Routes<T = {}> {
[key: string]: { [K in KnownMethod | "default"]?: MatchHandler<T> };
}
// deno-lint-ignore ban-types
export type InternalRoute<T = {}> = {
pattern: URLPattern;
methods: { [K in KnownMethod]?: MatchHandler<T> };
default?: MatchHandler<T>;
};
export interface RouterOptions<T> {
otherHandler?: Handler<T>;
errorHandler?: ErrorHandler<T>;
unknownMethodHandler?: UnknownMethodHandler<T>;
}
export type KnownMethod = typeof knownMethods[number];
export const knownMethods = [
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
"OPTIONS",
"PATCH",
] as const;
export function defaultOtherHandler(_req: Request): Response {
return new Response(null, {
status: 404,
});
}
export function defaultErrorHandler(
_req: Request,
_ctx: HandlerContext,
err: unknown,
): Response {
console.error(err);
return new Response(null, {
status: 500,
});
}
export function defaultUnknownMethodHandler(
_req: Request,
_ctx: HandlerContext,
knownMethods: KnownMethod[],
): Response {
return new Response(null, {
status: 405,
headers: {
Accept: knownMethods.join(", "),
},
});
}
export function router<T = unknown>(
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>[] = [];
for (const [path, methods] of Object.entries(routes)) {
const entry: InternalRoute<T> = {
pattern: new URLPattern({ pathname: path }),
methods: {},
default: undefined,
};
for (const [method, handler] of Object.entries(methods)) {
if (method === "default") {
entry.default = handler;
} else if (knownMethods.includes(method as KnownMethod)) {
entry.methods[method as KnownMethod] = handler;
}
}
internalRoutes.push(entry);
}
return async (req, ctx) => {
try {
for (const route of internalRoutes) {
const res = route.pattern.exec(req.url);
if (res !== null) {
const groups = res?.pathname.groups ?? {};
for (const key in groups) {
groups[key] = decodeURIComponent(groups[key]);
}
for (const [method, handler] of Object.entries(route.methods)) {
if (req.method === method) {
return await handler(req, ctx, groups);
}
}
if (route.default) {
return await route.default(req, ctx, groups);
} else {
return await unknownMethodHandler!(
req,
ctx,
Object.keys(route.methods) as KnownMethod[],
);
}
}
}
return await otherHandler!(req, ctx);
} catch (err) {
return errorHandler!(req, ctx, err);
}
};
}
+3 -2
View File
@@ -1,5 +1,6 @@
import { ComponentType } from "preact"; import { ComponentType } from "preact";
import { ConnInfo, rutt, ServeInit } from "./deps.ts"; import { ConnInfo, ServeInit } from "./deps.ts";
import * as router from "./router.ts";
import { InnerRenderFunction, RenderContext } from "./render.ts"; import { InnerRenderFunction, RenderContext } from "./render.ts";
// --- APPLICATION CONFIGURATION --- // --- APPLICATION CONFIGURATION ---
@@ -87,7 +88,7 @@ export type Handler<T = any, State = Record<string, unknown>> = (
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
export type Handlers<T = any, State = Record<string, unknown>> = { export type Handlers<T = any, State = Record<string, unknown>> = {
[K in typeof rutt.knownMethods[number]]?: Handler<T, State>; [K in router.KnownMethod]?: Handler<T, State>;
}; };
export interface RouteModule { export interface RouteModule {