Router cleanup (#2099)

This commit is contained in:
Marvin Hagemeister
2023-11-30 14:08:05 +01:00
committed by GitHub
parent a0a756a1ec
commit 8ddc21eb90
15 changed files with 398 additions and 496 deletions
+32 -58
View File
@@ -2,10 +2,8 @@ import { SEP } from "./deps.ts";
import { ErrorHandler, FinalHandler, RouteResult } from "./router.ts";
import {
BaseRoute,
MiddlewareHandlerContext,
FreshContext,
MiddlewareRoute,
RouterState,
ServeHandlerInfo,
UnknownRenderFunction,
} from "./types.ts";
@@ -56,20 +54,20 @@ export function selectSharedRoutes<T extends { baseRoute: BaseRoute }>(
*/
export function composeMiddlewares(
middlewares: MiddlewareRoute[],
errorHandler: ErrorHandler<RouterState>,
errorHandler: ErrorHandler,
paramsAndRoute: (
url: string,
) => RouteResult<RouterState>,
) => RouteResult,
renderNotFound: UnknownRenderFunction,
basePath: string,
) {
return (
req: Request,
connInfo: ServeHandlerInfo,
inner: FinalHandler<RouterState>,
ctx: FreshContext,
inner: FinalHandler,
) => {
const handlers: (() => Response | Promise<Response>)[] = [];
const paramsAndRouteResult = paramsAndRoute(req.url);
ctx.params = paramsAndRouteResult.params;
// identify middlewares to apply, if any.
// middlewares should be already sorted from deepest to shallow layer
@@ -78,73 +76,49 @@ export function composeMiddlewares(
middlewares,
);
let state: Record<string, unknown> = {};
const middlewareCtx: MiddlewareHandlerContext = {
next() {
const handler = handlers.shift()!;
try {
// As the `handler` can be either sync or async, depending on the user's code,
// the current shape of our wrapper, that is `() => handler(req, middlewareCtx)`,
// doesn't guarantee that all possible errors will be captured.
// `Promise.resolve` accept the value that should be returned to the promise
// chain, however, if that value is produced by the external function call,
// the possible `Error`, will *not* be caught by any `.catch()` attached to that chain.
// Because of that, we need to make sure that the produced value is pushed
// through the pipeline only if function was called successfully, and handle
// the error case manually, by returning the `Error` as rejected promise.
return Promise.resolve(handler());
} catch (e) {
if (e instanceof Deno.errors.NotFound) {
return renderNotFound(req, paramsAndRouteResult.params, ctx);
}
return Promise.reject(e);
if (paramsAndRouteResult.route) {
ctx.route = paramsAndRouteResult.route.originalPattern;
}
ctx.next = () => {
const handler = handlers.shift()!;
try {
// As the `handler` can be either sync or async, depending on the user's code,
// the current shape of our wrapper, that is `() => handler(req, middlewareCtx)`,
// doesn't guarantee that all possible errors will be captured.
// `Promise.resolve` accept the value that should be returned to the promise
// chain, however, if that value is produced by the external function call,
// the possible `Error`, will *not* be caught by any `.catch()` attached to that chain.
// Because of that, we need to make sure that the produced value is pushed
// through the pipeline only if function was called successfully, and handle
// the error case manually, by returning the `Error` as rejected promise.
return Promise.resolve(handler());
} catch (e) {
if (e instanceof Deno.errors.NotFound) {
return renderNotFound(req, ctx);
}
},
...connInfo,
get state() {
return state;
},
set state(v) {
state = v;
},
destination: "route",
params: paramsAndRouteResult.params,
renderNotFound: async () => {
return await renderNotFound(req, paramsAndRouteResult.params, ctx);
},
isPartial: paramsAndRouteResult.isPartial,
basePath,
return Promise.reject(e);
}
};
for (const { module } of mws) {
if (module.handler instanceof Array) {
for (const handler of module.handler) {
handlers.push(() => handler(req, middlewareCtx));
handlers.push(() => handler(req, ctx));
}
} else {
const handler = module.handler;
handlers.push(() => handler(req, middlewareCtx));
handlers.push(() => handler(req, ctx));
}
}
const ctx = {
...connInfo,
get state() {
return state;
},
set state(v) {
state = v;
},
isPartial: paramsAndRouteResult.isPartial,
};
const { destination, handler } = inner(
req,
ctx,
paramsAndRouteResult.params,
paramsAndRouteResult.route,
);
handlers.push(handler);
middlewareCtx.destination = destination;
return middlewareCtx.next().catch((e) => errorHandler(req, ctx, e));
ctx.destination = destination;
return ctx.next().catch((e) => errorHandler(req, ctx, e));
};
}
+84 -124
View File
@@ -1,6 +1,6 @@
import { contentType, extname, SEP, STATUS_CODE } from "./deps.ts";
import * as router from "./router.ts";
import { FreshConfig, Manifest, UnknownHandlerContext } from "./mod.ts";
import { FreshConfig, FreshContext, Manifest } from "./mod.ts";
import {
ALIVE_URL,
DEV_CLIENT_URL,
@@ -18,7 +18,6 @@ import {
RenderFunction,
RenderOptions,
Route,
RouterState,
ServeHandlerInfo,
UnknownPage,
UnknownRenderFunction,
@@ -44,12 +43,17 @@ import { extractRoutes, FsExtractResult } from "./fs_extract.ts";
import { loadAotSnapshot } from "../build/aot_snapshot.ts";
import { ErrorOverlay } from "./error_overlay.tsx";
import { withBase } from "./router.ts";
import { PARTIAL_SEARCH_PARAM } from "../constants.ts";
const DEFAULT_CONN_INFO: ServeHandlerInfo = {
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
};
// deno-lint-ignore no-explicit-any
const NOOP_COMPONENT = () => null as any;
const NOOP_NEXT = () => Promise.resolve(new Response(null, { status: 500 }));
/**
* @deprecated Use {@linkcode FromManifestConfig} instead
*/
@@ -154,20 +158,17 @@ export class ServerContext {
this.#plugins,
this.#renderFn,
this.#maybeBuildSnapshot(),
basePath,
);
const handlers = this.#handlers(renderNotFound);
const inner = router.router<RouterState>(handlers);
const inner = router.router(handlers);
const withMiddlewares = composeMiddlewares(
this.#extractResult.middlewares,
handlers.errorHandler,
router.getParamsAndRoute<RouterState>(handlers),
router.getParamsAndRoute(handlers),
renderNotFound,
basePath,
);
const trailingSlashEnabled = this.#state.config.router?.trailingSlash;
const isDev = this.#dev;
const bundleAssetRoute = this.#bundleAssetRoute();
if (this.#dev) {
this.#revision = Date.now();
@@ -215,9 +216,8 @@ export class ServerContext {
const bundlePath = (url.pathname.endsWith(".map"))
? "fresh_dev_client.js.map"
: "fresh_dev_client.js";
return bundleAssetRoute(req, { ...connInfo, isPartial: false }, {
path: bundlePath,
});
return _self.#bundleAssetRoute(bundlePath);
}
}
@@ -254,7 +254,28 @@ export class ServerContext {
return Response.redirect(to, 302);
}
return await withMiddlewares(req, connInfo, inner);
const ctx: FreshContext = {
url,
params: {},
basePath: _self.#state.config.basePath,
localAddr: connInfo.localAddr,
remoteAddr: connInfo.remoteAddr,
state: {},
isPartial: url.searchParams.has(PARTIAL_SEARCH_PARAM),
destination: "route",
error: undefined,
Component: NOOP_COMPONENT,
next: NOOP_NEXT,
render: NOOP_NEXT,
renderNotFound: async (data) => {
ctx.data = data;
return await renderNotFound(req, ctx);
},
route: "",
data: undefined,
};
return await withMiddlewares(req, ctx, inner);
};
}
@@ -287,16 +308,16 @@ export class ServerContext {
#handlers(
renderNotFound: UnknownRenderFunction,
): {
internalRoutes: router.Routes<RouterState>;
staticRoutes: router.Routes<RouterState>;
routes: router.Routes<RouterState>;
internalRoutes: router.Routes;
staticRoutes: router.Routes;
routes: router.Routes;
otherHandler: router.Handler<RouterState>;
errorHandler: router.ErrorHandler<RouterState>;
otherHandler: router.Handler;
errorHandler: router.ErrorHandler;
} {
const internalRoutes: router.Routes<RouterState> = {};
const staticRoutes: router.Routes<RouterState> = {};
const routes: router.Routes<RouterState> = {};
const internalRoutes: router.Routes = {};
const staticRoutes: router.Routes = {};
const routes: router.Routes = {};
const assetRoute = withBase(
`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`,
@@ -305,7 +326,7 @@ export class ServerContext {
internalRoutes[assetRoute] = {
baseRoute: toBaseRoute(assetRoute),
methods: {
default: this.#bundleAssetRoute(),
default: (_req, ctx) => this.#bundleAssetRoute(ctx.params.path),
},
};
@@ -352,9 +373,7 @@ export class ServerContext {
if (this.#dev) imports.push(this.#state.config.basePath + DEV_CLIENT_URL);
return (
req: Request,
params: Record<string, string>,
// deno-lint-ignore no-explicit-any
ctx?: any,
ctx: FreshContext,
error?: unknown,
codeFrame?: string,
) => {
@@ -367,14 +386,11 @@ export class ServerContext {
this.#extractResult.layouts,
);
ctx.error = error;
ctx.data = data;
const resp = await internalRender({
request: req,
context: {
...ctx,
async renderNotFound() {
return await renderNotFound(req, params, ctx, data, error);
},
},
context: ctx,
route,
plugins: this.#plugins,
app: this.#extractResult.app,
@@ -382,13 +398,7 @@ export class ServerContext {
imports,
dependenciesFn,
renderFn: this.#renderFn,
url: new URL(req.url),
params,
data,
state: ctx?.state,
error,
codeFrame,
basePath: this.#state.config.basePath,
});
if (resp instanceof Response) {
@@ -416,16 +426,10 @@ export class ServerContext {
routes[route.pattern] = {
baseRoute: route.baseRoute,
methods: {
default: (req, ctx, params) =>
(route.handler as Handler)(req, {
...ctx,
params,
render: createRender(req, params, ctx),
async renderNotFound<Data = undefined>(data: Data) {
return await renderNotFound(req, params, ctx, data);
},
basePath: this.#state.config.basePath,
}),
default: (req, ctx) => {
ctx.render = createRender(req, ctx);
return (route.handler as Handler)(req, ctx);
},
},
};
} else {
@@ -437,40 +441,27 @@ export class ServerContext {
routes[route.pattern].methods[method as router.KnownMethod] = (
req,
ctx,
params,
) =>
handler(req, {
...ctx,
params,
render: createRender(req, params, ctx),
async renderNotFound<Data = undefined>(data: Data) {
return await renderNotFound(req, params, ctx, data);
},
basePath: this.#state.config.basePath,
});
) => {
ctx.render = createRender(req, ctx);
return handler(req, ctx);
};
}
}
}
const otherHandler: router.Handler<RouterState> = (
req,
ctx,
) =>
this.#extractResult.notFound.handler(
req,
{
...ctx,
render() {
return renderNotFound(req, {}, ctx);
},
},
);
const otherHandler: router.Handler = (req, ctx) => {
ctx.render = (data) => {
ctx.data = data;
return renderNotFound(req, ctx);
};
return this.#extractResult.notFound.handler(req, ctx);
};
const errorHandlerRender = genRender(
this.#extractResult.error,
STATUS_CODE.InternalServerError,
);
const errorHandler: router.ErrorHandler<RouterState> = async (
const errorHandler: router.ErrorHandler = async (
req,
ctx,
error,
@@ -490,14 +481,9 @@ export class ServerContext {
}
console.error(error);
return this.#extractResult.error.handler(
req,
{
...ctx,
error,
render: errorHandlerRender(req, {}, ctx, error, codeFrame),
},
);
ctx.error = error;
ctx.render = errorHandlerRender(req, ctx, error, codeFrame);
return this.#extractResult.error.handler(req, ctx);
};
if (this.#dev) {
@@ -520,8 +506,7 @@ export class ServerContext {
csp: false,
url: req.url,
name: "error overlay route",
handler: (_req: Request, ctx: UnknownHandlerContext) =>
ctx.render(),
handler: (_req: Request, ctx: FreshContext) => ctx.render(),
baseRoute,
pattern: baseRoute,
},
@@ -531,16 +516,7 @@ export class ServerContext {
imports: [],
dependenciesFn: () => [],
renderFn: this.#renderFn,
url: new URL(req.url),
params: {},
data: undefined,
state: {
...ctx?.state,
error: null,
},
error: null,
codeFrame: undefined,
basePath: this.#state.config.basePath,
});
if (resp instanceof Response) {
@@ -602,31 +578,25 @@ export class ServerContext {
};
}
/**
* Returns a router that contains all Fresh routes. Should be mounted at
* constants.INTERNAL_PREFIX
*/
#bundleAssetRoute = (): router.MatchHandler => {
return async (_req, _ctx, params) => {
const snapshot = await this.buildSnapshot();
const contents = await snapshot.read(params.path);
if (!contents) return new Response(null, { status: 404 });
async #bundleAssetRoute(filePath: string) {
const snapshot = await this.buildSnapshot();
const contents = await snapshot.read(filePath);
if (!contents) return new Response(null, { status: 404 });
const headers: Record<string, string> = {
"Cache-Control": this.#dev
? "no-cache, no-store, max-age=0, must-revalidate"
: "public, max-age=604800, immutable",
};
const type = contentType(extname(params.path));
if (type) headers["Content-Type"] = type;
return new Response(contents, {
status: 200,
headers,
});
const headers: Record<string, string> = {
"Cache-Control": this.#dev
? "no-cache, no-store, max-age=0, must-revalidate"
: "public, max-age=604800, immutable",
};
};
const type = contentType(extname(filePath));
if (type) headers["Content-Type"] = type;
return new Response(contents, {
status: 200,
headers,
});
}
}
const createRenderNotFound = (
@@ -635,17 +605,13 @@ const createRenderNotFound = (
plugins: Plugin<Record<string, unknown>>[],
renderFunction: RenderFunction,
buildSnapshot: BuildSnapshot | null,
basePath: string,
) => {
): UnknownRenderFunction => {
const dependenciesFn = (path: string) => {
const snapshot = buildSnapshot;
return snapshot?.dependencies(path) ?? [];
};
return async (
...args: Parameters<UnknownRenderFunction>
) => {
const [req, params, ctx, data, error] = args;
return async (req, ctx) => {
const notFound = extractResult.notFound;
if (!notFound.component) {
return sendResponse(["Not found.", undefined], {
@@ -672,12 +638,6 @@ const createRenderNotFound = (
imports,
dependenciesFn,
renderFn: renderFunction,
url: new URL(req.url),
params,
data,
state: ctx?.state,
error,
basePath,
});
if (resp instanceof Response) {
+3 -10
View File
@@ -1,12 +1,5 @@
import { ComponentChildren } from "preact";
import {
AppContext,
AsyncLayout,
AsyncRoute,
FreshConfig,
LayoutContext,
RouteContext,
} from "./types.ts";
import { AsyncLayout, AsyncRoute, FreshConfig, RouteContext } from "./types.ts";
import { checkAsyncComponent } from "./render.ts";
export function defineConfig(config: FreshConfig): FreshConfig {
@@ -32,7 +25,7 @@ export function defineRoute<
export function defineLayout<T>(
fn: (
req: Request,
ctx: LayoutContext<void, T>,
ctx: RouteContext<void, T>,
) => ComponentChildren | Response | Promise<ComponentChildren | Response>,
): AsyncLayout<void, T> {
// deno-lint-ignore no-explicit-any
@@ -45,7 +38,7 @@ export function defineLayout<T>(
export function defineApp<T>(
fn: (
req: Request,
ctx: AppContext<void, T>,
ctx: RouteContext<void, T>,
) => ComponentChildren | Response | Promise<ComponentChildren | Response>,
): AsyncLayout<void, T> {
// deno-lint-ignore no-explicit-any
+1
View File
@@ -28,6 +28,7 @@ export type {
ErrorHandlerContext,
ErrorPageProps,
FreshConfig,
FreshContext,
FreshOptions,
Handler,
HandlerContext,
+25 -40
View File
@@ -4,13 +4,13 @@ import {
AsyncLayout,
AsyncRoute,
ErrorPage,
FreshContext,
LayoutRoute,
Plugin,
PluginRenderFunctionResult,
PluginRenderResult,
RenderFunction,
Route,
RouteContext,
UnknownPage,
} from "./types.ts";
import { NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
@@ -28,23 +28,16 @@ export const DEFAULT_RENDER_FN: RenderFunction = (_ctx, render) => {
export interface RenderOptions<Data> {
request: Request;
// deno-lint-ignore no-explicit-any
context: any;
context: FreshContext;
route: Route<Data> | UnknownPage | ErrorPage;
plugins: Plugin[];
app: AppModule;
layouts: LayoutRoute[];
imports: string[];
dependenciesFn: (path: string) => string[];
url: URL;
params: Record<string, string | string[]>;
renderFn: RenderFunction;
data?: Data;
state?: Record<string, unknown>;
error?: unknown;
codeFrame?: string;
lang?: string;
basePath: string;
}
export type InnerRenderFunction = () => string;
@@ -148,15 +141,17 @@ export async function render<Data>(
layouts = [];
}
const { params, data, state, error, url, basePath } = opts.context;
const props: Record<string, unknown> = {
params: opts.params,
url: opts.url,
params,
url,
route: opts.route.pattern,
data: opts.data,
state: opts.state,
data,
state,
};
if (opts.error) {
props.error = opts.error;
if (error) {
props.error = error;
}
if (opts.codeFrame) {
props.codeFrame = opts.codeFrame;
@@ -174,22 +169,12 @@ export async function render<Data>(
const ctx = new RenderContext(
crypto.randomUUID(),
opts.url,
url,
opts.route.pattern,
opts.lang ?? "en",
);
const context: RouteContext = {
localAddr: opts.context.localAddr,
remoteAddr: opts.context.remoteAddr,
renderNotFound: opts.context.renderNotFound,
url: opts.url,
route: opts.route.pattern,
params: opts.params as Record<string, string>,
state: opts.state ?? {},
data: opts.data,
isPartial: opts.context.isPartial,
};
const context = opts.context;
// Prepare render order
// deno-lint-ignore no-explicit-any
@@ -253,16 +238,16 @@ export async function render<Data>(
// data.
const renderState = new RenderState(
{
url: opts.url,
url,
route: opts.route.pattern,
data: opts.data,
state: opts.state,
params: opts.params,
basePath: opts.basePath,
data,
state,
params,
basePath,
},
componentStack,
csp,
opts.error,
error,
);
let bodyHtml: string | null = null;
@@ -370,20 +355,20 @@ export async function render<Data>(
});
// Append error overlay
const devErrorUrl = withBase(DEV_ERROR_OVERLAY_URL, opts.basePath);
if (opts.error !== undefined && opts.url.pathname !== devErrorUrl) {
const devErrorUrl = withBase(DEV_ERROR_OVERLAY_URL, basePath);
if (error !== undefined && url.pathname !== devErrorUrl) {
const url = new URL(devErrorUrl, "https://localhost/");
if (opts.error instanceof Error) {
let message = opts.error.message;
if (error instanceof Error) {
let message = error.message;
const idx = message.indexOf("\n");
if (idx > -1) message = message.slice(0, idx);
url.searchParams.append("message", message);
if (opts.error.stack) {
const stack = colors.stripAnsiCode(opts.error.stack);
if (error.stack) {
const stack = colors.stripAnsiCode(error.stack);
url.searchParams.append("stack", stack);
}
} else {
url.searchParams.append("message", String(opts.error));
url.searchParams.append("message", String(error));
}
if (opts.codeFrame) {
const codeFrame = colors.stripAnsiCode(opts.codeFrame);
+48 -45
View File
@@ -1,72 +1,74 @@
import { PARTIAL_SEARCH_PARAM } from "../constants.ts";
import { BaseRoute, ErrorHandlerContext, ServeHandlerInfo } from "./types.ts";
import {
BaseRoute,
ErrorHandlerContext,
FreshContext,
ServeHandlerInfo,
} from "./types.ts";
import { isIdentifierChar, isIdentifierStart } from "./init_safe_deps.ts";
type HandlerContext<T = unknown> = T & ServeHandlerInfo & {
isPartial: boolean;
};
export type Handler<T = unknown> = (
export type Handler<T = Record<string, unknown>> = (
req: Request,
ctx: HandlerContext<T>,
ctx: FreshContext<T>,
) => Response | Promise<Response>;
export type FinalHandler<T = unknown> = (
export type FinalHandler = (
req: Request,
ctx: HandlerContext<T>,
params: Record<string, string>,
route?: InternalRoute<T>,
ctx: FreshContext,
route?: InternalRoute,
) => {
destination: DestinationKind;
handler: () => Response | Promise<Response>;
};
export type ErrorHandler<T = unknown> = (
export type ErrorHandler<T = Record<string, unknown>> = (
req: Request,
ctx: HandlerContext<T>,
ctx: FreshContext<T>,
err: unknown,
) => Response | Promise<Response>;
type UnknownMethodHandler<T = unknown> = (
type UnknownMethodHandler = (
req: Request,
ctx: HandlerContext<T>,
ctx: FreshContext,
knownMethods: KnownMethod[],
) => Response | Promise<Response>;
export type MatchHandler<T = unknown> = (
export type MatchHandler = (
req: Request,
ctx: HandlerContext<T>,
match: Record<string, string>,
ctx: FreshContext,
) => Response | Promise<Response>;
// deno-lint-ignore ban-types
export interface Routes<T = {}> {
export interface Routes {
[key: string]: {
baseRoute: BaseRoute;
methods: {
[K in KnownMethod | "default"]?: MatchHandler<T>;
[K in KnownMethod | "default"]?: MatchHandler;
};
};
}
export type DestinationKind = "internal" | "static" | "route" | "notFound";
// deno-lint-ignore ban-types
export type InternalRoute<T = {}> = {
export type InternalRoute = {
baseRoute: BaseRoute;
originalPattern: string;
pattern: RegExp | string;
methods: { [K in KnownMethod]?: MatchHandler<T> };
default?: MatchHandler<T>;
methods: { [K in KnownMethod]?: MatchHandler };
default?: MatchHandler;
destination: DestinationKind;
};
export interface RouterOptions<T> {
internalRoutes: Routes<T>;
staticRoutes: Routes<T>;
routes: Routes<T>;
otherHandler: Handler<T>;
errorHandler: ErrorHandler<T>;
unknownMethodHandler?: UnknownMethodHandler<T>;
export interface RouterOptions {
internalRoutes: Routes;
staticRoutes: Routes;
routes: Routes;
otherHandler: Handler;
errorHandler: ErrorHandler;
unknownMethodHandler?: UnknownMethodHandler;
}
export type KnownMethod = typeof knownMethods[number];
@@ -214,9 +216,9 @@ export function patternToRegExp(input: string): RegExp {
export const IS_PATTERN = /[*:{}+?()]/;
function processRoutes<T>(
processedRoutes: Array<InternalRoute<T> | null>,
routes: Routes<T>,
function processRoutes(
processedRoutes: Array<InternalRoute | null>,
routes: Routes,
destination: DestinationKind,
) {
for (const [path, def] of Object.entries(routes)) {
@@ -224,9 +226,10 @@ function processRoutes<T>(
? path
: patternToRegExp(path);
const entry: InternalRoute<T> = {
const entry: InternalRoute = {
baseRoute: def.baseRoute,
pattern,
originalPattern: path,
methods: {},
default: undefined,
destination,
@@ -244,27 +247,27 @@ function processRoutes<T>(
}
}
export interface RouteResult<T> {
route: InternalRoute<T> | undefined;
export interface RouteResult {
route: InternalRoute | undefined;
params: Record<string, string>;
isPartial: boolean;
}
export function getParamsAndRoute<T>(
export function getParamsAndRoute(
{
internalRoutes,
staticRoutes,
routes,
}: RouterOptions<T>,
}: RouterOptions,
): (
url: string,
) => RouteResult<T> {
const processedRoutes: Array<InternalRoute<T> | null> = [];
) => RouteResult {
const processedRoutes: Array<InternalRoute | null> = [];
processRoutes(processedRoutes, internalRoutes, "internal");
processRoutes(processedRoutes, staticRoutes, "static");
processRoutes(processedRoutes, routes, "route");
const statics = new Map<string, RouteResult<T>>();
const statics = new Map<string, RouteResult>();
return (url: string) => {
const urlObject = new URL(url);
@@ -323,15 +326,15 @@ export function getParamsAndRoute<T>(
};
}
export function router<T = unknown>(
export function router(
{
otherHandler,
unknownMethodHandler,
}: RouterOptions<T>,
): FinalHandler<T> {
}: RouterOptions,
): FinalHandler {
unknownMethodHandler ??= defaultUnknownMethodHandler;
return (req, ctx, groups, route) => {
return (req, ctx, route) => {
if (route) {
// If not overridden, HEAD requests should be handled as GET requests but without the body.
if (req.method === "HEAD" && !route.methods["HEAD"]) {
@@ -342,7 +345,7 @@ export function router<T = unknown>(
if (req.method === method) {
return {
destination: route.destination,
handler: () => handler(req, ctx, groups),
handler: () => handler(req, ctx),
};
}
}
@@ -350,7 +353,7 @@ export function router<T = unknown>(
if (route.default) {
return {
destination: route.destination,
handler: () => route.default!(req, ctx, groups),
handler: () => route.default!(req, ctx),
};
} else {
return {
+106 -96
View File
@@ -22,17 +22,6 @@ export interface DenoConfig {
}
// --- APPLICATION CONFIGURATION ---
/**
* @deprecated Use {@linkcode FreshConfig} instead
*/
export type StartOptions = FreshConfig;
/**
* @deprecated Use {@linkcode FreshConfig} interface instead.
*/
export type FreshOptions = FreshConfig;
export interface FreshConfig {
build?: {
/**
@@ -201,22 +190,46 @@ export interface StaticFile {
etag: string;
}
export interface FreshContext<
State = Record<string, unknown>,
// deno-lint-ignore no-explicit-any
Data = any,
NotFoundData = Data,
> {
/** @types deprecated */
localAddr?: Deno.NetAddr;
remoteAddr: Deno.NetAddr;
url: URL;
basePath: string;
route: string;
destination: router.DestinationKind;
params: Record<string, string>;
isPartial: boolean;
state: State;
/** @deprecated Pass values to state instead */
data: Data;
error?: unknown;
// These properties may be different
renderNotFound: (data?: NotFoundData) => Response | Promise<Response>;
render: (
data?: Data,
options?: RenderOptions,
) => Response | Promise<Response>;
Component: () => VNode;
next: () => Promise<Response>;
}
/**
* Context passed to async route components.
*/
// deno-lint-ignore no-explicit-any
export type RouteContext<T = any, S = Record<string, unknown>> = {
/** @types deprecated */
localAddr?: Deno.NetAddr;
remoteAddr: Deno.NetAddr;
renderNotFound: (data?: T) => Response | Promise<Response>;
url: URL;
route: string;
params: Record<string, string>;
state: S;
data: T;
isPartial: boolean;
};
export type RouteContext<T = any, S = Record<string, unknown>> = Omit<
FreshContext<
S,
T
>,
"next" | "render"
>;
export interface RouteConfig {
/**
@@ -265,26 +278,10 @@ export type ServeHandler = (
info: ServeHandlerInfo,
) => Response | Promise<Response>;
export interface HandlerContext<
Data = unknown,
State = Record<string, unknown>,
NotFoundData = Data,
> extends ServeHandlerInfo {
params: Record<string, string>;
basePath: string;
render: (
data?: Data,
options?: RenderOptions,
) => Response | Promise<Response>;
renderNotFound: (data?: NotFoundData) => Response | Promise<Response>;
state: State;
isPartial: boolean;
}
// deno-lint-ignore no-explicit-any
export type Handler<T = any, State = Record<string, unknown>> = (
req: Request,
ctx: HandlerContext<T, State>,
ctx: FreshContext<State, T>,
) => Response | Promise<Response>;
// deno-lint-ignore no-explicit-any
@@ -292,11 +289,6 @@ export type Handlers<T = any, State = Record<string, unknown>> = {
[K in router.KnownMethod]?: Handler<T, State>;
};
/**
* @deprecated This type was a short-lived alternative to `Handlers`. Please use `Handlers` instead.
*/
export type MultiHandler<T> = Handlers<T>;
export interface RouteModule {
default?: PageComponent<PageProps>;
// deno-lint-ignore no-explicit-any
@@ -307,7 +299,7 @@ export interface RouteModule {
// deno-lint-ignore no-explicit-any
export type AsyncRoute<T = any, S = Record<string, unknown>> = (
req: Request,
ctx: RouteContext<T, S>,
ctx: FreshContext<S, T>,
) => Promise<ComponentChildren | Response>;
// deno-lint-ignore no-explicit-any
export type PageComponent<T = any, S = Record<string, unknown>> =
@@ -329,10 +321,6 @@ export interface Route<Data = any> {
inheritLayouts: boolean;
}
export interface RouterState {
state: Record<string, unknown>;
}
// --- APP ---
// deno-lint-ignore no-explicit-any
@@ -342,18 +330,6 @@ export interface AppModule {
default: ComponentType<AppProps> | AsyncLayout;
}
// deno-lint-ignore no-explicit-any
export type AppContext<T = any, S = Record<string, unknown>> =
& RouteContext<T, S>
& {
Component: () => VNode;
};
// deno-lint-ignore no-explicit-any
export type LayoutContext<T = any, S = Record<string, unknown>> = AppContext<
T,
S
>;
// deno-lint-ignore no-explicit-any
export interface LayoutProps<T = any, S = Record<string, unknown>>
extends PageProps<T, S> {
@@ -362,7 +338,7 @@ export interface LayoutProps<T = any, S = Record<string, unknown>>
// deno-lint-ignore no-explicit-any
export type AsyncLayout<T = any, S = Record<string, unknown>> = (
req: Request,
ctx: LayoutContext<T, S>,
ctx: FreshContext<S, T>,
) => Promise<ComponentChildren | Response>;
export interface LayoutConfig {
@@ -413,15 +389,9 @@ export interface UnknownPageProps<T = any, S = Record<string, unknown>> {
state: S;
}
export interface UnknownHandlerContext<State = Record<string, unknown>>
extends ServeHandlerInfo {
render: () => Response | Promise<Response>;
state: State;
}
export type UnknownHandler = (
req: Request,
ctx: UnknownHandlerContext,
ctx: FreshContext,
) => Response | Promise<Response>;
export interface UnknownPageModule {
@@ -444,11 +414,7 @@ export interface UnknownPage {
export type UnknownRenderFunction = (
req: Request,
params: Record<string, string>,
// deno-lint-ignore no-explicit-any
ctx?: any,
data?: unknown,
error?: unknown,
ctx: FreshContext,
) => Promise<Response>;
// --- ERROR PAGE ---
@@ -468,19 +434,12 @@ export interface ErrorPageProps {
codeFrame?: string;
}
export interface ErrorHandlerContext<State = Record<string, unknown>>
extends ServeHandlerInfo {
error: unknown;
render: () => Response | Promise<Response>;
state: State;
}
// Nominal/Branded type. Ensures that the string has the expected format
export type BaseRoute = string & { readonly __brand: unique symbol };
export type ErrorHandler = (
req: Request,
ctx: ErrorHandlerContext,
ctx: FreshContext,
) => Response | Promise<Response>;
export interface ErrorPageModule {
@@ -502,18 +461,6 @@ export interface ErrorPage {
}
// --- MIDDLEWARES ---
export interface MiddlewareHandlerContext<State = Record<string, unknown>>
extends ServeHandlerInfo {
next: () => Promise<Response>;
renderNotFound: (state?: State) => Response | Promise<Response>;
state: State;
destination: router.DestinationKind;
params: Record<string, string>;
isPartial: boolean;
basePath: string;
}
export interface MiddlewareRoute {
baseRoute: BaseRoute;
module: Middleware;
@@ -521,7 +468,7 @@ export interface MiddlewareRoute {
export type MiddlewareHandler<State = Record<string, unknown>> = (
req: Request,
ctx: MiddlewareHandlerContext<State>,
ctx: FreshContext<State>,
) => Response | Promise<Response>;
// deno-lint-ignore no-explicit-any
@@ -688,3 +635,66 @@ export interface PluginIslands {
baseLocation: string;
paths: string[];
}
// --- Deprecated types ---
/**
* @deprecated This type was a short-lived alternative to `Handlers`. Please use `Handlers` instead.
*/
export type MultiHandler<T> = Handlers<T>;
/**
* @deprecated Use {@linkcode FreshConfig} instead
*/
export type StartOptions = FreshConfig;
/**
* @deprecated Use {@linkcode FreshConfig} interface instead.
*/
export type FreshOptions = FreshConfig;
/**
* @deprecated Use {@linkcode FreshContext} interface instead
*/
export type HandlerContext<
Data = unknown,
State = Record<string, unknown>,
NotFoundData = Data,
> = FreshContext<State, Data, NotFoundData>;
/**
* @deprecated Use {@linkcode FreshContext} interface instead
*/
// deno-lint-ignore no-explicit-any
export type AppContext<T = any, S = Record<string, unknown>> = FreshContext<
S,
T
>;
/**
* @deprecated Use {@linkcode FreshContext} interface instead
*/
// deno-lint-ignore no-explicit-any
export type LayoutContext<T = any, S = Record<string, unknown>> = FreshContext<
S,
T
>;
/**
* @deprecated Use {@linkcode FreshContext} interface instead
*/
export type UnknownHandlerContext<State = Record<string, unknown>> =
FreshContext<State>;
/**
* @deprecated Use {@linkcode FreshContext} interface instead
*/
export type ErrorHandlerContext<State = Record<string, unknown>> = FreshContext<
State
>;
/**
* @deprecated Use {@linkcode FreshContext} interface instead
*/
export type MiddlewareHandlerContext<State = Record<string, unknown>> =
FreshContext<State>;
+8 -11
View File
@@ -36,17 +36,14 @@ Deno.test("dev_command config: shows codeframe", async () => {
);
});
Deno.test({
name: "dev_command legacy",
async fn() {
await withPageName(
"./tests/fixture_dev_legacy/main.ts",
async (page, address) => {
await page.goto(`${address}`);
await waitForStyle(page, "h1", "color", "rgb(220, 38, 38)");
},
);
},
Deno.test("dev_command legacy", async () => {
await withPageName(
"./tests/fixture_dev_legacy/main.ts",
async (page, address) => {
await page.goto(`${address}`);
await waitForStyle(page, "h1", "color", "rgb(220, 38, 38)");
},
);
});
Deno.test("dev_command legacy: shows codeframe", async () => {
+31 -35
View File
@@ -79,22 +79,22 @@ import * as $static from "./routes/static.tsx";
import * as $status_overwrite from "./routes/status_overwrite.tsx";
import * as $umlaut_äöüß from "./routes/umlaut-äöüß.tsx";
import * as $wildcard from "./routes/wildcard.tsx";
import * as $$Counter from "./islands/Counter.tsx";
import * as $$FormIsland from "./islands/FormIsland.tsx";
import * as $$Greeter from "./islands/Greeter.tsx";
import * as $$HookIsland from "./islands/HookIsland.tsx";
import * as $$MultipleCounters from "./islands/MultipleCounters.tsx";
import * as $$ReturningNull from "./islands/ReturningNull.tsx";
import * as $$RootFragment from "./islands/RootFragment.tsx";
import * as $$RootFragmentWithConditionalFirst from "./islands/RootFragmentWithConditionalFirst.tsx";
import * as $$StringEventIsland from "./islands/StringEventIsland.tsx";
import * as $$Test from "./islands/Test.tsx";
import * as $$folder_Counter from "./islands/folder/Counter.tsx";
import * as $$folder_subfolder_Counter from "./islands/folder/subfolder/Counter.tsx";
import * as $$kebab_case_counter_test from "./islands/kebab-case-counter-test.tsx";
import * as $$route_groups_islands_islands_Counter from "./routes/route-groups-islands/(_islands)/Counter.tsx";
import * as $$route_groups_islands_islands_invalid from "./routes/route-groups-islands/(_islands)/invalid.tsx";
import { Manifest } from "$fresh/server.ts";
import * as $Counter from "./islands/Counter.tsx";
import * as $FormIsland from "./islands/FormIsland.tsx";
import * as $Greeter from "./islands/Greeter.tsx";
import * as $HookIsland from "./islands/HookIsland.tsx";
import * as $MultipleCounters from "./islands/MultipleCounters.tsx";
import * as $ReturningNull from "./islands/ReturningNull.tsx";
import * as $RootFragment from "./islands/RootFragment.tsx";
import * as $RootFragmentWithConditionalFirst from "./islands/RootFragmentWithConditionalFirst.tsx";
import * as $StringEventIsland from "./islands/StringEventIsland.tsx";
import * as $Test from "./islands/Test.tsx";
import * as $folder_Counter from "./islands/folder/Counter.tsx";
import * as $folder_subfolder_Counter from "./islands/folder/subfolder/Counter.tsx";
import * as $kebab_case_counter_test from "./islands/kebab-case-counter-test.tsx";
import * as $route_groups_islands_islands_Counter from "./routes/route-groups-islands/(_islands)/Counter.tsx";
import * as $route_groups_islands_islands_invalid from "./routes/route-groups-islands/(_islands)/invalid.tsx";
import { type Manifest } from "$fresh/server.ts";
const manifest = {
routes: {
@@ -195,28 +195,24 @@ const manifest = {
"./routes/wildcard.tsx": $wildcard,
},
islands: {
"./islands/Counter.tsx": $$Counter,
"./islands/FormIsland.tsx": $$FormIsland,
"./islands/Greeter.tsx": $$Greeter,
"./islands/HookIsland.tsx": $$HookIsland,
"./islands/MultipleCounters.tsx": {
CounterOne: $$MultipleCounters.CounterOne,
CounterTwo: $$MultipleCounters.CounterTwo,
default: $$MultipleCounters.default,
},
"./islands/ReturningNull.tsx": $$ReturningNull,
"./islands/RootFragment.tsx": $$RootFragment,
"./islands/Counter.tsx": $Counter,
"./islands/FormIsland.tsx": $FormIsland,
"./islands/Greeter.tsx": $Greeter,
"./islands/HookIsland.tsx": $HookIsland,
"./islands/MultipleCounters.tsx": $MultipleCounters,
"./islands/ReturningNull.tsx": $ReturningNull,
"./islands/RootFragment.tsx": $RootFragment,
"./islands/RootFragmentWithConditionalFirst.tsx":
$$RootFragmentWithConditionalFirst,
"./islands/StringEventIsland.tsx": $$StringEventIsland,
"./islands/Test.tsx": $$Test,
"./islands/folder/Counter.tsx": $$folder_Counter,
"./islands/folder/subfolder/Counter.tsx": $$folder_subfolder_Counter,
"./islands/kebab-case-counter-test.tsx": $$kebab_case_counter_test,
$RootFragmentWithConditionalFirst,
"./islands/StringEventIsland.tsx": $StringEventIsland,
"./islands/Test.tsx": $Test,
"./islands/folder/Counter.tsx": $folder_Counter,
"./islands/folder/subfolder/Counter.tsx": $folder_subfolder_Counter,
"./islands/kebab-case-counter-test.tsx": $kebab_case_counter_test,
"./routes/route-groups-islands/(_islands)/Counter.tsx":
$$route_groups_islands_islands_Counter,
$route_groups_islands_islands_Counter,
"./routes/route-groups-islands/(_islands)/invalid.tsx":
$$route_groups_islands_islands_invalid,
$route_groups_islands_islands_invalid,
},
baseUrl: import.meta.url,
} satisfies Manifest;
@@ -1,8 +1,5 @@
import { MiddlewareHandlerContext } from "$fresh/server.ts";
import { FreshContext } from "$fresh/server.ts";
export async function handler(
_req: Request,
ctx: MiddlewareHandlerContext,
) {
export async function handler(_req: Request, ctx: FreshContext) {
return await ctx.renderNotFound();
}
+5 -17
View File
@@ -1,10 +1,7 @@
import { MiddlewareHandler, MiddlewareHandlerContext } from "$fresh/server.ts";
import { FreshContext, MiddlewareHandler } from "$fresh/server.ts";
// cors middleware
async function corsHandler(
_req: Request,
ctx: MiddlewareHandlerContext,
) {
async function corsHandler(_req: Request, ctx: FreshContext) {
if (_req.method == "OPTIONS") {
return new Response(null, {
status: 204,
@@ -29,10 +26,7 @@ async function corsHandler(
}
// log middleware
async function logHandler(
_req: Request,
ctx: MiddlewareHandlerContext,
) {
async function logHandler(_req: Request, ctx: FreshContext) {
const since = new Date();
const resp = await ctx.next();
const latency = (+new Date()) - (+since);
@@ -40,20 +34,14 @@ async function logHandler(
return resp;
}
async function rootHandler(
_req: Request,
ctx: MiddlewareHandlerContext,
) {
async function rootHandler(_req: Request, ctx: FreshContext) {
ctx.state.root = "root_mw";
const resp = await ctx.next();
resp.headers.set("server", "fresh test server");
return resp;
}
async function kindHandler(
_req: Request,
ctx: MiddlewareHandlerContext,
) {
async function kindHandler(_req: Request, ctx: FreshContext) {
const resp = await ctx.next();
resp.headers.set("destination", ctx.destination);
return resp;
+3 -3
View File
@@ -9,8 +9,8 @@ import * as $index from "./routes/index.tsx";
import * as $island from "./routes/island.tsx";
import * as $response from "./routes/response.tsx";
import * as $twind from "./routes/twind.tsx";
import * as $$FooIsland from "./islands/FooIsland.tsx";
import { Manifest } from "$fresh/server.ts";
import * as $FooIsland from "./islands/FooIsland.tsx";
import { type Manifest } from "$fresh/server.ts";
const manifest = {
routes: {
@@ -23,7 +23,7 @@ const manifest = {
"./routes/twind.tsx": $twind,
},
islands: {
"./islands/FooIsland.tsx": $$FooIsland,
"./islands/FooIsland.tsx": $FooIsland,
},
baseUrl: import.meta.url,
} satisfies Manifest;
+8 -11
View File
@@ -671,17 +671,14 @@ Deno.test({
},
});
Deno.test({
name: "/not_found",
fn: async () => {
const resp = await handler(new Request("https://fresh.deno.dev/not_found"));
assert(resp);
assertEquals(resp.status, 404);
const body = await resp.text();
assertStringIncludes(body, "404 not found: /not_found");
assertStringIncludes(body, "Hello Dino");
assertStringIncludes(body, "State root: root_mw");
},
Deno.test("/not_found", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/not_found"));
assert(resp);
assertEquals(resp.status, 404);
const body = await resp.text();
assertStringIncludes(body, "404 not found: /not_found");
assertStringIncludes(body, "Hello Dino");
assertStringIncludes(body, "State root: root_mw");
});
Deno.test("middleware destination", async (t) => {
+39 -38
View File
@@ -58,47 +58,48 @@ Deno.test({
},
});
Deno.test({
name: "passes context to server component",
Deno.test("passes context to server component", async () => {
await withFresh(
"./tests/fixture_server_components/main.ts",
async (address) => {
const res = await fetch(`${address}/context/foo`);
const json = await res.json();
async fn() {
await withFresh(
"./tests/fixture_server_components/main.ts",
async (address) => {
const res = await fetch(`${address}/context/foo`);
const json = await res.json();
assertEquals(typeof json.localAddr, "object");
assertEquals(typeof json.remoteAddr, "object");
json.localAddr.port = 8000;
json.remoteAddr.port = 8000;
assertEquals(typeof json.localAddr, "object");
assertEquals(typeof json.remoteAddr, "object");
json.localAddr.port = 8000;
json.remoteAddr.port = 8000;
assertEquals(
json,
{
localAddr: {
hostname: "localhost",
port: 8000,
transport: "tcp",
},
remoteAddr: {
hostname: "127.0.0.1",
port: 8000,
transport: "tcp",
},
renderNotFound: "AsyncFunction",
url: `${address}/context/foo`,
route: "/context/:id",
params: {
id: "foo",
},
state: {},
isPartial: false,
assertEquals(
json,
{
localAddr: {
hostname: "localhost",
port: 8000,
transport: "tcp",
},
);
},
);
},
remoteAddr: {
hostname: "127.0.0.1",
port: 8000,
transport: "tcp",
},
render: "AsyncFunction",
Component: "Function",
destination: "route",
next: "Function",
basePath: "",
renderNotFound: "AsyncFunction",
url: `${address}/context/foo`,
route: "/context/:id",
params: {
id: "foo",
},
state: {},
isPartial: false,
},
);
},
);
});
Deno.test({
+3 -3
View File
@@ -1,4 +1,4 @@
import { MiddlewareHandlerContext } from "$fresh/server.ts";
import { type FreshContext } from "$fresh/server.ts";
import type { Event } from "$ga4";
import { GA4Report, isDocument, isServerError } from "$ga4";
@@ -8,7 +8,7 @@ let showedMissingEnvWarning = false;
function ga4(
request: Request,
conn: MiddlewareHandlerContext,
conn: FreshContext,
response: Response,
_start: number,
error?: unknown,
@@ -80,7 +80,7 @@ function ga4(
export async function handler(
req: Request,
ctx: MiddlewareHandlerContext,
ctx: FreshContext,
): Promise<Response> {
let err;
let res: Response;