diff --git a/src/app.ts b/src/app.ts index d2a7b451..8e5b871f 100644 --- a/src/app.ts +++ b/src/app.ts @@ -205,21 +205,18 @@ export class App { const { params, handlers } = matched; const ctx = new FreshReqContext( req, + conn, + params, this.config, next, this.#islandRegistry, this.#buildCache!, - conn, ); - ctx.params = params; - try { if (handlers.length === 1 && handlers[0].length === 1) { return handlers[0][0](ctx); } - - ctx.next = next; return await runMiddlewares(handlers, ctx); } catch (err) { if (err instanceof HttpError) { diff --git a/src/compat/server.ts b/src/compat/server.ts index b0757ad1..43ff0b56 100644 --- a/src/compat/server.ts +++ b/src/compat/server.ts @@ -5,31 +5,25 @@ import type { HandlerByMethod } from "../handlers.ts"; /** * @deprecated Use {@link FreshContext} instead */ -export type AppProps = FreshContext; +export type AppProps<_Data = unknown, T = unknown> = FreshContext; /** * @deprecated Use {@link FreshContext} instead */ -export type LayoutProps = FreshContext; +export type LayoutProps<_Data = unknown, T = unknown> = FreshContext; /** * @deprecated Use {@link FreshContext} instead */ -export type UnknownPageProps = FreshContext< - Data, - T ->; +export type UnknownPageProps<_Data = unknown, T = unknown> = FreshContext; /** * @deprecated Use {@link FreshContext} instead */ -export type ErrorPageProps = FreshContext; +export type ErrorPageProps<_Data = unknown, T = unknown> = FreshContext; /** * @deprecated Use {@link FreshContext} instead */ -// deno-lint-ignore no-explicit-any -export type RouteContext> = FreshContext< - T, - S ->; +export type RouteContext<_T = never, S = Record> = + FreshContext; // deno-lint-ignore no-explicit-any export type Handlers> = @@ -37,10 +31,10 @@ export type Handlers> = function defineFn( fn: ( - ctx: FreshContext, + ctx: FreshContext, ) => Request | VNode | null | Promise, ): ( - ctx: FreshContext, + ctx: FreshContext, ) => Request | VNode | null | Promise { return fn; } diff --git a/src/config.ts b/src/config.ts index 399e00ba..9db284b2 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,5 +1,5 @@ import * as path from "@std/path"; -import { MODE, type Mode } from "./runtime/server/mod.tsx"; +import { MODE, type Mode } from "./runtime/server/mod.ts"; export interface FreshPlugin { name: string; diff --git a/src/context.ts b/src/context.ts index 5c4fb5be..b4cdc144 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,6 +1,12 @@ -import { type ComponentType, h, isValidElement, type VNode } from "preact"; -import type { ResolvedFreshConfig } from "./config.ts"; +import { + type ComponentType, + type FunctionComponent, + h, + isValidElement, + type VNode, +} from "preact"; import { renderToString } from "preact-render-to-string"; +import type { ResolvedFreshConfig } from "./config.ts"; import type { BuildCache } from "./build_cache.ts"; import { FreshScripts, @@ -21,22 +27,21 @@ export type ServerIslandRegistry = Map; /** * The context passed to every middleware. It is unique for every request. */ -export interface FreshContext { +export interface FreshContext { /** Reference to the resolved Fresh configuration */ readonly config: ResolvedFreshConfig; - state: State; - data: Data; + readonly state: State; /** The original incoming `Request` object` */ - req: Request; + 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. */ - url: URL; - params: Record; - error: unknown; - info?: Deno.ServeHandlerInfo | Deno.ServeUnixHandlerInfo; + readonly url: URL; + readonly params: Record; + readonly error: unknown; + readonly info: Deno.ServeHandlerInfo | Deno.ServeUnixHandlerInfo; /** * Return a redirect response to the specified path. This is the * preferred way to do redirects in Fresh. @@ -78,32 +83,48 @@ export interface FreshContext { render(vnode: VNode, init?: ResponseInit): Response | Promise; } -export let getBuildCache: (ctx: FreshContext) => BuildCache; +export let getBuildCache: (ctx: FreshContext) => BuildCache; -export class FreshReqContext implements FreshContext { +export class FreshReqContext + implements FreshContext, PageProps { + config: ResolvedFreshConfig; url: URL; - params = {} as Record; - state = {} as State; - data = {} as never; - error: Error | null = null; + req: Request; + params: Record; + state: State = {} as State; + data: unknown = undefined; + error: unknown | null = null; + info: Deno.ServeHandlerInfo | Deno.ServeUnixHandlerInfo; + + next: FreshContext["next"]; + #islandRegistry: ServerIslandRegistry; #buildCache: BuildCache; + // FIXME: remove after switching to + Component!: FunctionComponent; + static { getBuildCache = (ctx) => (ctx as FreshReqContext).#buildCache; } constructor( - public req: Request, - public config: ResolvedFreshConfig, - public next: FreshContext["next"], + req: Request, + info: Deno.ServeHandlerInfo | Deno.ServeUnixHandlerInfo, + params: Record, + config: ResolvedFreshConfig, + next: FreshContext["next"], islandRegistry: ServerIslandRegistry, buildCache: BuildCache, - public info: Deno.ServeHandlerInfo | Deno.ServeUnixHandlerInfo, ) { + this.url = new URL(req.url); + this.req = req; + this.info = info; + this.params = params; + this.config = config; + this.next = next; this.#islandRegistry = islandRegistry; this.#buildCache = buildCache; - this.url = new URL(req.url); } redirect(pathOrUrl: string, status = 302): Response { @@ -168,9 +189,21 @@ export class FreshReqContext implements FreshContext { } } +Object.defineProperties(FreshReqContext.prototype, { + config: { enumerable: true }, + url: { enumerable: true }, + req: { enumerable: true }, + params: { enumerable: true }, + state: { enumerable: true }, + data: { enumerable: true }, + error: { enumerable: true }, + next: { enumerable: true }, + info: { enumerable: true }, +}); + function preactRender( vnode: VNode, - ctx: FreshContext, + ctx: PageProps, islandRegistry: ServerIslandRegistry, buildCache: BuildCache, partialId: string, @@ -201,3 +234,7 @@ function preactRender( setRenderState(null); } } + +export type PageProps = + & Omit, "next" | "render" | "redirect"> + & { data: Data; Component: FunctionComponent }; diff --git a/src/define.ts b/src/define.ts index 16402bc5..916a67ae 100644 --- a/src/define.ts +++ b/src/define.ts @@ -1,7 +1,7 @@ import type { AnyComponent } from "preact"; import type { HandlerByMethod, RouteHandler } from "./handlers.ts"; -import type { FreshContext } from "./context.ts"; import type { Middleware } from "./middlewares/mod.ts"; +import type { PageProps } from "./context.ts"; /** * A set of define functions that enable better type inference and code @@ -57,9 +57,7 @@ export interface Define { handlers< Data, Handlers extends RouteHandler = RouteHandler, - >( - handlers: Handlers, - ): typeof handlers; + >(handlers: Handlers): typeof handlers; /** * Define a page component that will be rendered when a route handler returns @@ -110,9 +108,7 @@ export interface Define { // deno-lint-ignore no-explicit-any Handler extends RouteHandler = never, Data = Handler extends HandlerByMethod ? Data : never, - >( - render: AnyComponent & { Component: () => null }>, - ): typeof render; + >(render: AnyComponent>): typeof render; /** * Define a {@link Middleware} that will be used to process requests before @@ -135,9 +131,7 @@ export interface Define { * * @typeParam M The type of the middleware function. This will be inferred from the input function. Do not manually specify this type. */ - middleware>( - middleware: M, - ): typeof middleware; + middleware>(middleware: M): typeof middleware; } /** diff --git a/src/dev/mod.ts b/src/dev/mod.ts index 7046d688..ec59712e 100644 --- a/src/dev/mod.ts +++ b/src/dev/mod.ts @@ -1,4 +1,4 @@ -import { setMode } from "../runtime/server/mod.tsx"; +import { setMode } from "../runtime/server/mod.ts"; export { Builder, type FreshBuilder } from "./builder.ts"; export { diff --git a/src/handlers.ts b/src/handlers.ts index b9f59d0b..b9308999 100644 --- a/src/handlers.ts +++ b/src/handlers.ts @@ -192,7 +192,7 @@ export function isHandlerByMethod( * ``` */ export interface HandlerFn { - (ctx: FreshContext): + (ctx: FreshContext): | Response | PageResponse | Promise>; diff --git a/src/middlewares/mod.ts b/src/middlewares/mod.ts index a6b5028f..15d62ea2 100644 --- a/src/middlewares/mod.ts +++ b/src/middlewares/mod.ts @@ -1,4 +1,4 @@ -import type { FreshContext } from "../context.ts"; +import type { FreshContext, FreshReqContext } from "../context.ts"; import type { App as _App } from "../app.ts"; /** @@ -71,7 +71,7 @@ import type { App as _App } from "../app.ts"; * ``` */ export type MiddlewareFn = ( - ctx: FreshContext, + ctx: FreshContext, ) => Response | Promise; /** @@ -82,7 +82,7 @@ export type Middleware = MiddlewareFn | MiddlewareFn[]; export function runMiddlewares( middlewares: MiddlewareFn[][], - ctx: FreshContext, + ctx: FreshReqContext, ): Promise { let fn = ctx.next; let i = middlewares.length; diff --git a/src/middlewares/trailing_slashes_test.ts b/src/middlewares/trailing_slashes_test.ts index 17a5d2c1..b1c37e79 100644 --- a/src/middlewares/trailing_slashes_test.ts +++ b/src/middlewares/trailing_slashes_test.ts @@ -5,9 +5,8 @@ import { serveMiddleware } from "../test_utils.ts"; Deno.test("trailingSlashes - always", async () => { const middleware = trailingSlashes("always"); - const server = serveMiddleware(async (ctx) => { - ctx.next = async () => new Response("ok"); - return await middleware(ctx); + const server = serveMiddleware(middleware, { + next: async () => new Response("ok"), }); let res = await server.get("/"); @@ -33,9 +32,8 @@ Deno.test("trailingSlashes - always", async () => { Deno.test("trailingSlashes - never", async () => { const middleware = trailingSlashes("never"); - const server = serveMiddleware(async (ctx) => { - ctx.next = async () => new Response("ok"); - return await middleware(ctx); + const server = serveMiddleware(middleware, { + next: async () => new Response("ok"), }); let res = await server.get("/"); diff --git a/src/mod.ts b/src/mod.ts index f71a72a5..a7b15da6 100644 --- a/src/mod.ts +++ b/src/mod.ts @@ -9,14 +9,14 @@ export { type RouteData, type RouteHandler, } from "./handlers.ts"; -export { type RouteConfig } from "./types.ts"; -export { type Middleware, type MiddlewareFn } from "./middlewares/mod.ts"; +export type { RouteConfig } from "./types.ts"; +export type { Middleware, MiddlewareFn } from "./middlewares/mod.ts"; export { staticFiles } from "./middlewares/static_files.ts"; -export { type Mode, type PageProps } from "./runtime/server/mod.tsx"; -export { type FreshConfig, type ResolvedFreshConfig } from "./config.ts"; -export { type FreshContext, type Island } from "./context.ts"; +export type { Mode } from "./runtime/server/mod.ts"; +export type { FreshConfig, ResolvedFreshConfig } from "./config.ts"; +export type { FreshContext, Island, PageProps } from "./context.ts"; export { createDefine, type Define } from "./define.ts"; -export { type Method } from "./router.ts"; +export type { Method } from "./router.ts"; export { HttpError } from "./error.ts"; // Compat with older Fresh versions diff --git a/src/plugins/fs_routes/mod.ts b/src/plugins/fs_routes/mod.ts index 19ea5ef6..7a28157f 100644 --- a/src/plugins/fs_routes/mod.ts +++ b/src/plugins/fs_routes/mod.ts @@ -4,7 +4,6 @@ import type { WalkEntry } from "@std/fs/walk"; import * as path from "@std/path"; import type { RouteConfig } from "../../types.ts"; import type { RouteHandler } from "../../handlers.ts"; -import type { FreshContext } from "../../context.ts"; import type { MiddlewareFn } from "../../middlewares/mod.ts"; import { type AsyncAnyComponent, @@ -13,9 +12,9 @@ import { import { type Method, pathToPattern } from "../../router.ts"; import { type HandlerFn, isHandlerByMethod } from "../../handlers.ts"; import { type FsAdapter, fsAdapter } from "../../fs.ts"; -import type { PageProps } from "../../runtime/server/mod.tsx"; import { HttpError } from "../../error.ts"; import { parseRootPath } from "../../config.ts"; +import type { FreshReqContext, PageProps } from "../../context.ts"; const TEST_FILE_PATTERN = /[._]test\.(?:[tj]sx?|[mc][tj]s)$/; const GROUP_REG = /(^|[/\\\\])\((_[^/\\\\]+)\)[/\\\\]/; @@ -34,12 +33,8 @@ export interface FreshFsItem { handler?: RouteHandler | HandlerFn[]; handlers?: RouteHandler; default?: - | AnyComponent< - PageProps & Pick, "redirect"> - > - | AsyncAnyComponent< - PageProps & Pick, "redirect"> - >; + | AnyComponent> + | AsyncAnyComponent>; } // deno-lint-ignore no-explicit-any @@ -324,7 +319,7 @@ function errorMiddleware( try { return await ctx.next(); } catch (err) { - ctx.error = err; + (ctx as FreshReqContext).error = err; return mid(ctx); } }; diff --git a/src/plugins/fs_routes/render_middleware.ts b/src/plugins/fs_routes/render_middleware.ts index 85a39286..d8fd7a1f 100644 --- a/src/plugins/fs_routes/render_middleware.ts +++ b/src/plugins/fs_routes/render_middleware.ts @@ -1,7 +1,7 @@ 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 { PageProps } from "../../runtime/server/mod.tsx"; +import type { FreshReqContext, PageProps } from "../../context.ts"; export type AsyncAnyComponent

= { ( @@ -30,18 +30,21 @@ export function renderMiddleware( return res; } - // deno-lint-ignore no-explicit-any - result = res as any; + result = res; } if (components.length === 0) { throw new Error(`Did not receive any components to render.`); } + const props = ctx as FreshReqContext; + props.data = result?.data; + let vnode: VNode | null = null; for (let i = components.length - 1; i >= 0; i--) { const child = vnode; - const Component = () => child; + // FIXME: remove when we're using `` + props.Component = () => child; const fn = components[i]; @@ -49,23 +52,14 @@ export function renderMiddleware( typeof fn === "function" && fn.constructor.name === "AsyncFunction" ) { - const result = (await fn({ ...ctx, Component })) as VNode | Response; + const result = (await fn(props)) as VNode | Response; if (result instanceof Response) { return result; } vnode = result; } else { // deno-lint-ignore no-explicit-any - vnode = h(components[i] as any, { - config: ctx.config, - url: ctx.url, - req: ctx.req, - params: ctx.params, - state: ctx.state, - Component, - error: ctx.error, - data: result?.data ?? {}, - }) as VNode; + vnode = h(components[i] as any, props) as VNode; } } diff --git a/src/runtime/server/mod.ts b/src/runtime/server/mod.ts new file mode 100644 index 00000000..6909a30c --- /dev/null +++ b/src/runtime/server/mod.ts @@ -0,0 +1,9 @@ +/** + * The mode Fresh can run in. + */ +export type Mode = "development" | "build" | "production"; +export let MODE: Mode = "production"; + +export function setMode(mode: Mode) { + MODE = mode; +} diff --git a/src/runtime/server/mod.tsx b/src/runtime/server/mod.tsx deleted file mode 100644 index 9d984b37..00000000 --- a/src/runtime/server/mod.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import type { FunctionComponent } from "preact"; -import type { FreshContext } from "../../context.ts"; - -/** - * The mode Fresh can run in. - */ -export type Mode = "development" | "build" | "production"; -export let MODE: Mode = "production"; - -export function setMode(mode: Mode) { - MODE = mode; -} - -export type PageProps = - & Omit, "next" | "redirect" | "next"> - & { Component: FunctionComponent }; diff --git a/src/runtime/server/preact_hooks.tsx b/src/runtime/server/preact_hooks.tsx index 74a9fadc..9f1ad994 100644 --- a/src/runtime/server/preact_hooks.tsx +++ b/src/runtime/server/preact_hooks.tsx @@ -11,7 +11,7 @@ import { } from "preact"; import type { Signal } from "@preact/signals"; import type { Stringifiers } from "../../jsonify/stringify.ts"; -import type { FreshContext } from "../../context.ts"; +import type { PageProps } from "../../context.ts"; import { asset, Partial, type PartialProps } from "../shared.ts"; import { stringify } from "../../jsonify/stringify.ts"; import type { ServerIslandRegistry } from "../../context.ts"; @@ -88,7 +88,7 @@ export class RenderState { hasRuntimeScript = false; constructor( - public ctx: FreshContext, + public ctx: PageProps, public islandRegistry: ServerIslandRegistry, public buildCache: BuildCache, public partialId: string, @@ -396,14 +396,14 @@ export function FreshScripts() { <> {slots.map((slot) => { if (slot === null) return null; - // FIXME: Wait for https://github.com/preactjs/preact/pull/4334 to be - // released - return h( - "template", - { key: slot.id, id: `frsh-${slot.id}-${slot.name}` }, - slot.vnode, - // deno-lint-ignore no-explicit-any - ) as VNode; + return ( + + ); })} diff --git a/src/test_utils.ts b/src/test_utils.ts index 7291b64f..c522e868 100644 --- a/src/test_utils.ts +++ b/src/test_utils.ts @@ -1,5 +1,4 @@ import { FreshReqContext } from "./context.ts"; -import type { MiddlewareFn } from "./middlewares/mod.ts"; import type { FsAdapter } from "./fs.ts"; import { type BuildCache, ProdBuildCache } from "./build_cache.ts"; import type { ResolvedFreshConfig } from "./config.ts"; @@ -63,22 +62,28 @@ const DEFAULT_CONFIG: ResolvedFreshConfig = { }; export function serveMiddleware( - middleware: MiddlewareFn, - options: { config?: ResolvedFreshConfig; buildCache?: BuildCache } = {}, + middleware: (ctx: FreshReqContext) => Response | Promise, + options: { + config?: ResolvedFreshConfig; + buildCache?: BuildCache; + next?: () => Promise; + } = {}, ): FakeServer { return new FakeServer(async (req) => { - const next = () => new Response("not found", { status: 404 }); + const next = options.next ?? + (() => new Response("not found", { status: 404 })); const config = options.config ?? DEFAULT_CONFIG; const buildCache = options.buildCache ?? new ProdBuildCache(config, new Map(), new Map(), true); const ctx = new FreshReqContext( req, + DEFAULT_CONN_INFO, + {}, config, () => Promise.resolve(next()), new Map(), buildCache, - DEFAULT_CONN_INFO, ); return await middleware(ctx); });