BREAKING: move a bunch of types into server/ (#263)

Moved some server only types like `RouteConfig` into server/. They were
previously in runtime/.
This commit is contained in:
Luca Casonato
2022-06-21 15:21:07 +02:00
committed by GitHub
parent 3458e35d8e
commit da340daeb2
22 changed files with 245 additions and 231 deletions
+2 -3
View File
@@ -42,7 +42,7 @@ Now, let's render some HTML using the route component. Another example:
/** @jsx h */ /** @jsx h */
import { h } from "preact"; import { h } from "preact";
import { PageProps } from "$fresh/runtime.ts"; import { PageProps } from "$fresh/server.ts";
export default function Page(props: PageProps) { export default function Page(props: PageProps) {
return <div>You are on the page '{props.url.href}'.</div>; return <div>You are on the page '{props.url.href}'.</div>;
@@ -65,8 +65,7 @@ response after rendering the page component.
/** @jsx h */ /** @jsx h */
import { h } from "preact"; import { h } from "preact";
import { PageProps } from "$fresh/runtime.ts"; import { HandlerContext, Handlers, PageProps } from "$fresh/server.ts";
import { HandlerContext, Handlers } from "$fresh/server.ts";
export const handler: Handlers = { export const handler: Handlers = {
async GET(ctx: HandlerContext) { async GET(ctx: HandlerContext) {
+1 -1
View File
@@ -29,7 +29,7 @@ as arguments in it's `props` object though.
/** @jsx h */ /** @jsx h */
import { h } from "preact"; import { h } from "preact";
import { PageProps } from "$fresh/runtime.ts"; import { PageProps } from "$fresh/server.ts";
export default function GreetPage(props: PageProps) { export default function GreetPage(props: PageProps) {
const { name } = props.params; const { name } = props.params;
+1 -2
View File
@@ -25,8 +25,7 @@ renders it in a page component.
/** @jsx h */ /** @jsx h */
import { h } from "preact"; import { h } from "preact";
import { PageProps } from "$fresh/runtime.ts"; import { Handlers, PageProps } from "$fresh/server.ts";
import { Handlers } from "$fresh/server.ts";
interface User { interface User {
login: string; login: string;
+1 -2
View File
@@ -34,8 +34,7 @@ server side:
/** @jsx h */ /** @jsx h */
import { h } from "preact"; import { h } from "preact";
import { PageProps } from "$fresh/runtime.ts"; import { Handlers, PageProps } from "$fresh/server.ts";
import { Handlers } from "$fresh/server.ts";
const NAMES = ["Alice", "Bob", "Charlie", "Dave", "Eve", "Frank"]; const NAMES = ["Alice", "Bob", "Charlie", "Dave", "Eve", "Frank"];
+1 -1
View File
@@ -166,7 +166,7 @@ await Deno.writeTextFile(
const ROUTES_GREET_TSX = `/** @jsx h */ const ROUTES_GREET_TSX = `/** @jsx h */
import { h } from "preact"; import { h } from "preact";
import { PageProps } from "$fresh/runtime.ts"; import { PageProps } from "$fresh/server.ts";
export default function Greet(props: PageProps) { export default function Greet(props: PageProps) {
return <div>Hello {props.params.name}</div>; return <div>Hello {props.params.name}</div>;
-1
View File
@@ -1,4 +1,3 @@
export * from "./src/runtime/types.ts";
export * from "./src/runtime/utils.ts"; export * from "./src/runtime/utils.ts";
export * from "./src/runtime/head.ts"; export * from "./src/runtime/head.ts";
export * from "./src/runtime/csp.ts"; export * from "./src/runtime/csp.ts";
-70
View File
@@ -1,70 +0,0 @@
import { ComponentType } from "preact";
// deno-lint-ignore no-explicit-any
export interface PageProps<T = any> {
/** The URL of the request that resulted in this page being rendered. */
url: URL;
/** The route matcher (e.g. /blog/:id) that the request matched for this page
* to be rendered. */
route: string;
/**
* The paramteres that were matched from the route.
*
* For the `/foo/:bar` route with url `/foo/123`, `params` would be
* `{ bar: '123' }`. For a route with no matchers, `params` would be `{}`. For
* a wildcard route, like `/foo/:path*` with url `/foo/bar/baz`, `params` would
* be `{ path: 'bar/baz' }`.
*/
params: Record<string, string>;
/**
* Additional data passed into `HandlerContext.render`. Defaults to
* `undefined`.
*/
data: T;
}
export interface AppProps {
Component: ComponentType<Record<never, never>>;
}
export interface UnknownPageProps {
/** The URL of the request that resulted in this page being rendered. */
url: URL;
/** The route matcher (e.g. /blog/:id) that the request matched for this page
* to be rendered. */
route: string;
}
export interface ErrorPageProps {
/** The URL of the request that resulted in this page being rendered. */
url: URL;
/** The route matcher (e.g. /blog/:id) that the request matched for this page
* to be rendered. */
route: string;
/** The error that caused the error page to be loaded. */
error: unknown;
}
export interface RouteConfig {
/**
* A route override for the page. This is useful for pages where the route
* can not be expressed through the filesystem routing capabilities.
*
* The route override must be a path-to-regexp compatible route matcher.
*/
routeOverride?: string;
/**
* If Content-Security-Policy should be enabled for this page. If 'true', a
* locked down policy will be used that allows only the scripts and styles
* that are generated by fresh. Additional scripts and styles can be added
* using the `useCSP` hook.
*/
csp?: boolean;
}
+44 -41
View File
@@ -23,10 +23,9 @@ import {
Middleware, Middleware,
MiddlewareModule, MiddlewareModule,
MiddlewareRoute, MiddlewareRoute,
Page,
PageModule,
RenderFunction, RenderFunction,
RouterState, Route,
RouteModule,
UnknownPage, UnknownPage,
UnknownPageModule, UnknownPageModule,
} from "./types.ts"; } from "./types.ts";
@@ -34,6 +33,10 @@ import { render as internalRender } from "./render.tsx";
import { ContentSecurityPolicyDirectives, SELF } from "../runtime/csp.ts"; import { ContentSecurityPolicyDirectives, SELF } from "../runtime/csp.ts";
import { ASSET_CACHE_BUST_KEY, INTERNAL_PREFIX } from "../runtime/utils.ts"; import { ASSET_CACHE_BUST_KEY, INTERNAL_PREFIX } from "../runtime/utils.ts";
interface RouterState {
state: Record<string, unknown>;
}
interface StaticFile { interface StaticFile {
/** The URL to the static file on disk. */ /** The URL to the static file on disk. */
localUrl: URL; localUrl: URL;
@@ -49,7 +52,7 @@ interface StaticFile {
export class ServerContext { export class ServerContext {
#dev: boolean; #dev: boolean;
#pages: Page[]; #routes: Route[];
#islands: Island[]; #islands: Island[];
#staticFiles: StaticFile[]; #staticFiles: StaticFile[];
#bundler: Bundler; #bundler: Bundler;
@@ -60,7 +63,7 @@ export class ServerContext {
#error: ErrorPage; #error: ErrorPage;
constructor( constructor(
pages: Page[], routes: Route[],
islands: Island[], islands: Island[],
staticFiles: StaticFile[], staticFiles: StaticFile[],
renderfn: RenderFunction, renderfn: RenderFunction,
@@ -70,7 +73,7 @@ export class ServerContext {
error: ErrorPage, error: ErrorPage,
importMapURL: URL, importMapURL: URL,
) { ) {
this.#pages = pages; this.#routes = routes;
this.#islands = islands; this.#islands = islands;
this.#staticFiles = staticFiles; this.#staticFiles = staticFiles;
this.#renderFn = renderfn; this.#renderFn = renderfn;
@@ -94,7 +97,7 @@ export class ServerContext {
const importMapURL = new URL("./import_map.json", manifest.baseUrl); const importMapURL = new URL("./import_map.json", manifest.baseUrl);
// Extract all routes, and prepare them into the `Page` structure. // Extract all routes, and prepare them into the `Page` structure.
const pages: Page[] = []; const routes: Route[] = [];
const islands: Island[] = []; const islands: Island[] = [];
const middlewares: MiddlewareRoute[] = []; const middlewares: MiddlewareRoute[] = [];
let app: AppModule = DEFAULT_APP; let app: AppModule = DEFAULT_APP;
@@ -112,12 +115,12 @@ export class ServerContext {
path.endsWith("/_middleware.ts") || path.endsWith("/_middleware.jsx") || path.endsWith("/_middleware.ts") || path.endsWith("/_middleware.jsx") ||
path.endsWith("/_middleware.js"); path.endsWith("/_middleware.js");
if (!path.startsWith("/_") && !isMiddleware) { if (!path.startsWith("/_") && !isMiddleware) {
const { default: component, config } = (module as PageModule); const { default: component, config } = (module as RouteModule);
let route = pathToRoute(baseRoute); let pattern = pathToPattern(baseRoute);
if (config?.routeOverride) { if (config?.routeOverride) {
route = String(config.routeOverride); pattern = String(config.routeOverride);
} }
let { handler } = (module as PageModule); let { handler } = (module as RouteModule);
handler ??= {}; handler ??= {};
if ( if (
component && component &&
@@ -125,15 +128,15 @@ export class ServerContext {
) { ) {
handler.GET = (_req, { render }) => render(); handler.GET = (_req, { render }) => render();
} }
const page: Page = { const route: Route = {
route, pattern,
url, url,
name, name,
component, component,
handler, handler,
csp: Boolean(config?.csp ?? false), csp: Boolean(config?.csp ?? false),
}; };
pages.push(page); routes.push(route);
} else if (isMiddleware) { } else if (isMiddleware) {
middlewares.push({ middlewares.push({
...middlewarePathToPattern(baseRoute), ...middlewarePathToPattern(baseRoute),
@@ -155,7 +158,7 @@ export class ServerContext {
} }
notFound = { notFound = {
route: pathToRoute(baseRoute), pattern: pathToPattern(baseRoute),
url, url,
name, name,
component, component,
@@ -173,7 +176,7 @@ export class ServerContext {
} }
error = { error = {
route: pathToRoute(baseRoute), pattern: pathToPattern(baseRoute),
url, url,
name, name,
component, component,
@@ -183,7 +186,7 @@ export class ServerContext {
}; };
} }
} }
sortRoutes(pages); sortRoutes(routes);
sortRoutes(middlewares); sortRoutes(middlewares);
for (const [self, module] of Object.entries(manifest.islands)) { for (const [self, module] of Object.entries(manifest.islands)) {
@@ -249,7 +252,7 @@ export class ServerContext {
} }
return new ServerContext( return new ServerContext(
pages, routes,
islands, islands,
staticFiles, staticFiles,
opts.render ?? DEFAULT_RENDER_FN, opts.render ?? DEFAULT_RENDER_FN,
@@ -266,7 +269,7 @@ export class ServerContext {
* by fresh, including static files. * by fresh, including static files.
*/ */
handler(): RequestHandler { handler(): RequestHandler {
const inner = router.router<RouterState>(...this.#routes()); const inner = router.router<RouterState>(...this.#handlers());
const withMiddlewares = this.#composeMiddlewares(this.#middlewares); const withMiddlewares = this.#composeMiddlewares(this.#middlewares);
return function handler(req: Request, connInfo: ConnInfo) { return function handler(req: Request, connInfo: ConnInfo) {
// Redirect requests that end with a trailing slash // Redirect requests that end with a trailing slash
@@ -321,7 +324,7 @@ export class ServerContext {
* This function returns all routes required by fresh as an extended * This function returns all routes required by fresh as an extended
* path-to-regex, to handler mapping. * path-to-regex, to handler mapping.
*/ */
#routes(): [ #handlers(): [
router.Routes<RouterState>, router.Routes<RouterState>,
router.Handler<RouterState>, router.Handler<RouterState>,
router.ErrorHandler<RouterState>, router.ErrorHandler<RouterState>,
@@ -381,7 +384,7 @@ export class ServerContext {
} }
const genRender = <Data = undefined>( const genRender = <Data = undefined>(
page: Page<Data> | UnknownPage | ErrorPage, route: Route<Data> | UnknownPage | ErrorPage,
status: number, status: number,
) => { ) => {
const imports: string[] = []; const imports: string[] = [];
@@ -394,12 +397,12 @@ export class ServerContext {
error?: unknown, error?: unknown,
) => { ) => {
return async (data?: Data) => { return async (data?: Data) => {
if (page.component === undefined) { if (route.component === undefined) {
throw new Error("This page does not have a component to render."); throw new Error("This page does not have a component to render.");
} }
const preloads: string[] = []; const preloads: string[] = [];
const resp = await internalRender({ const resp = await internalRender({
page, route,
islands: this.#islands, islands: this.#islands,
app: this.#app, app: this.#app,
imports, imports,
@@ -435,18 +438,18 @@ export class ServerContext {
}; };
}; };
for (const page of this.#pages) { for (const route of this.#routes) {
const createRender = genRender(page, 200); const createRender = genRender(route, 200);
if (typeof page.handler === "function") { if (typeof route.handler === "function") {
routes[page.route] = (req, ctx, params) => routes[route.pattern] = (req, ctx, params) =>
(page.handler as Handler)(req, { (route.handler as Handler)(req, {
...ctx, ...ctx,
params, params,
render: createRender(req, params), render: createRender(req, params),
}); });
} else { } else {
for (const [method, handler] of Object.entries(page.handler)) { for (const [method, handler] of Object.entries(route.handler)) {
routes[`${method}@${page.route}`] = (req, ctx, params) => routes[`${method}@${route.pattern}`] = (req, ctx, params) =>
handler(req, { handler(req, {
...ctx, ...ctx,
params, params,
@@ -573,7 +576,7 @@ const DEFAULT_APP: AppModule = {
}; };
const DEFAULT_NOT_FOUND: UnknownPage = { const DEFAULT_NOT_FOUND: UnknownPage = {
route: "", pattern: "",
url: "", url: "",
name: "_404", name: "_404",
handler: (req) => router.defaultOtherHandler(req), handler: (req) => router.defaultOtherHandler(req),
@@ -581,7 +584,7 @@ const DEFAULT_NOT_FOUND: UnknownPage = {
}; };
const DEFAULT_ERROR: ErrorPage = { const DEFAULT_ERROR: ErrorPage = {
route: "", pattern: "",
url: "", url: "",
name: "_500", name: "_500",
component: DefaultErrorHandler, component: DefaultErrorHandler,
@@ -598,8 +601,8 @@ export function selectMiddlewares(url: string, middlewares: MiddlewareRoute[]) {
const selectedMws: Middleware[] = []; const selectedMws: Middleware[] = [];
const reqURL = new URL(url); const reqURL = new URL(url);
for (const { pattern, handler } of middlewares) { for (const { compiledPattern, handler } of middlewares) {
const res = pattern.exec(reqURL); const res = compiledPattern.exec(reqURL);
if (res) { if (res) {
selectedMws.push({ handler }); selectedMws.push({ handler });
} }
@@ -612,10 +615,10 @@ export function selectMiddlewares(url: string, middlewares: MiddlewareRoute[]) {
* Sort pages by their relative routing priority, based on the parts in the * Sort pages by their relative routing priority, based on the parts in the
* route matcher * route matcher
*/ */
function sortRoutes<T extends { route: string }>(routes: T[]) { function sortRoutes<T extends { pattern: string }>(routes: T[]) {
routes.sort((a, b) => { routes.sort((a, b) => {
const partsA = a.route.split("/"); const partsA = a.pattern.split("/");
const partsB = b.route.split("/"); const partsB = b.pattern.split("/");
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) { for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
const partA = partsA[i]; const partA = partsA[i];
const partB = partsB[i]; const partB = partsB[i];
@@ -631,7 +634,7 @@ function sortRoutes<T extends { route: string }>(routes: T[]) {
} }
/** Transform a filesystem URL path to a `path-to-regex` style matcher. */ /** Transform a filesystem URL path to a `path-to-regex` style matcher. */
function pathToRoute(path: string): string { function pathToPattern(path: string): string {
const parts = path.split("/"); const parts = path.split("/");
if (parts[parts.length - 1] === "index") { if (parts[parts.length - 1] === "index") {
parts.pop(); parts.pop();
@@ -687,7 +690,7 @@ function serializeCSPDirectives(csp: ContentSecurityPolicyDirectives): string {
export function middlewarePathToPattern(baseRoute: string) { export function middlewarePathToPattern(baseRoute: string) {
baseRoute = baseRoute.slice(0, -"_middleware".length); baseRoute = baseRoute.slice(0, -"_middleware".length);
const regRoute = pathToRoute(baseRoute); const pattern = pathToPattern(baseRoute);
const pattern = new URLPattern({ pathname: `${regRoute}*` }); const compiledPattern = new URLPattern({ pathname: `${pattern}*` });
return { route: regRoute, pattern }; return { pattern, compiledPattern };
} }
+1 -1
View File
@@ -2,7 +2,7 @@
import { h } from "preact"; import { h } from "preact";
import { DEBUG } from "./constants.ts"; import { DEBUG } from "./constants.ts";
import type { ErrorPageProps } from "../runtime/types.ts"; import type { ErrorPageProps } from "./types.ts";
export default function DefaultErrorPage(props: ErrorPageProps) { export default function DefaultErrorPage(props: ErrorPageProps) {
const { error } = props; const { error } = props;
+12 -2
View File
@@ -5,17 +5,27 @@ import {
ErrorPageModule, ErrorPageModule,
IslandModule, IslandModule,
MiddlewareModule, MiddlewareModule,
PageModule, RouteModule,
StartOptions, StartOptions,
UnknownPageModule, UnknownPageModule,
} from "./types.ts"; } from "./types.ts";
export type { export type {
AppProps,
ErrorHandler,
ErrorHandlerContext,
ErrorPageProps,
FreshOptions, FreshOptions,
Handler, Handler,
HandlerContext, HandlerContext,
Handlers, Handlers,
MiddlewareHandlerContext, MiddlewareHandlerContext,
PageProps,
RenderFunction, RenderFunction,
RouteConfig,
StartOptions,
UnknownHandler,
UnknownHandlerContext,
UnknownPageProps,
} from "./types.ts"; } from "./types.ts";
export { RenderContext } from "./render.tsx"; export { RenderContext } from "./render.tsx";
export type { InnerRenderFunction } from "./render.tsx"; export type { InnerRenderFunction } from "./render.tsx";
@@ -23,7 +33,7 @@ export type { InnerRenderFunction } from "./render.tsx";
export interface Manifest { export interface Manifest {
routes: Record< routes: Record<
string, string,
| PageModule | RouteModule
| MiddlewareModule | MiddlewareModule
| AppModule | AppModule
| ErrorPageModule | ErrorPageModule
+10 -6
View File
@@ -5,8 +5,8 @@ import {
AppModule, AppModule,
ErrorPage, ErrorPage,
Island, Island,
Page,
RenderFunction, RenderFunction,
Route,
UnknownPage, UnknownPage,
} from "./types.ts"; } from "./types.ts";
import { HEAD_CONTEXT } from "../runtime/head.ts"; import { HEAD_CONTEXT } from "../runtime/head.ts";
@@ -16,7 +16,7 @@ import { bundleAssetUrl } from "./constants.ts";
import { assetHashingHook } from "../runtime/utils.ts"; import { assetHashingHook } from "../runtime/utils.ts";
export interface RenderOptions<Data> { export interface RenderOptions<Data> {
page: Page<Data> | UnknownPage | ErrorPage; route: Route<Data> | UnknownPage | ErrorPage;
islands: Island[]; islands: Island[];
app: AppModule; app: AppModule;
imports: string[]; imports: string[];
@@ -123,14 +123,14 @@ export async function render<Data>(
const props: Record<string, unknown> = { const props: Record<string, unknown> = {
params: opts.params, params: opts.params,
url: opts.url, url: opts.url,
route: opts.page.route, route: opts.route.pattern,
data: opts.data, data: opts.data,
}; };
if (opts.error) { if (opts.error) {
props.error = opts.error; props.error = opts.error;
} }
const csp: ContentSecurityPolicy | undefined = opts.page.csp const csp: ContentSecurityPolicy | undefined = opts.route.csp
? defaultCsp() ? defaultCsp()
: undefined; : undefined;
const headComponents: ComponentChildren[] = []; const headComponents: ComponentChildren[] = [];
@@ -141,13 +141,17 @@ export async function render<Data>(
value: headComponents, value: headComponents,
children: h(opts.app.default, { children: h(opts.app.default, {
Component() { Component() {
return h(opts.page.component! as ComponentType<unknown>, props); return h(opts.route.component! as ComponentType<unknown>, props);
}, },
}), }),
}), }),
}); });
const ctx = new RenderContext(crypto.randomUUID(), opts.url, opts.page.route); const ctx = new RenderContext(
crypto.randomUUID(),
opts.url,
opts.route.pattern,
);
if (csp) { if (csp) {
// Clear the csp // Clear the csp
+159 -87
View File
@@ -1,17 +1,8 @@
import { ComponentType } from "preact"; import { ComponentType } from "preact";
import { ConnInfo, router, ServeInit } from "./deps.ts"; import { ConnInfo, router, ServeInit } from "./deps.ts";
import {
AppProps,
ErrorPageProps,
PageProps,
RouteConfig,
UnknownPageProps,
} from "../runtime/types.ts";
import { InnerRenderFunction, RenderContext } from "./render.tsx"; import { InnerRenderFunction, RenderContext } from "./render.tsx";
export interface RouterState { // --- APPLICATION CONFIGURATION ---
state: Record<string, unknown>;
}
export type StartOptions = ServeInit & FreshOptions; export type StartOptions = ServeInit & FreshOptions;
@@ -24,28 +15,50 @@ export type RenderFunction = (
render: InnerRenderFunction, render: InnerRenderFunction,
) => void | Promise<void>; ) => void | Promise<void>;
export interface PageModule { /// --- ROUTES ---
default?: ComponentType<PageProps>;
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
handler?: Handler<any, any> | Handlers<any, any>; export interface PageProps<T = any> {
config?: RouteConfig; /** The URL of the request that resulted in this page being rendered. */
url: URL;
/** The route matcher (e.g. /blog/:id) that the request matched for this page
* to be rendered. */
route: string;
/**
* The paramteres that were matched from the route.
*
* For the `/foo/:bar` route with url `/foo/123`, `params` would be
* `{ bar: '123' }`. For a route with no matchers, `params` would be `{}`. For
* a wildcard route, like `/foo/:path*` with url `/foo/bar/baz`, `params` would
* be `{ path: 'bar/baz' }`.
*/
params: Record<string, string>;
/**
* Additional data passed into `HandlerContext.render`. Defaults to
* `undefined`.
*/
data: T;
} }
export interface UnknownPageModule { export interface RouteConfig {
default?: ComponentType<UnknownPageProps>; /**
handler?: UnknownHandler; * A route override for the page. This is useful for pages where the route
config?: RouteConfig; * can not be expressed through the filesystem routing capabilities.
} *
* The route override must be a path-to-regexp compatible route matcher.
*/
routeOverride?: string;
export interface ErrorPageModule { /**
default?: ComponentType<ErrorPageProps>; * If Content-Security-Policy should be enabled for this page. If 'true', a
handler?: ErrorHandler; * locked down policy will be used that allows only the scripts and styles
config?: RouteConfig; * that are generated by fresh. Additional scripts and styles can be added
} * using the `useCSP` hook.
*/
export interface IslandModule { csp?: boolean;
// deno-lint-ignore no-explicit-any
default: ComponentType<any>;
} }
export interface HandlerContext<Data = unknown, State = Record<string, unknown>> export interface HandlerContext<Data = unknown, State = Record<string, unknown>>
@@ -55,18 +68,122 @@ export interface HandlerContext<Data = unknown, State = Record<string, unknown>>
state: State; state: State;
} }
// deno-lint-ignore no-explicit-any
export type Handler<T = any, State = Record<string, unknown>> = (
req: Request,
ctx: HandlerContext<T, State>,
) => Response | Promise<Response>;
// deno-lint-ignore no-explicit-any
export type Handlers<T = any, State = Record<string, unknown>> = {
[K in typeof router.METHODS[number]]?: Handler<T, State>;
};
export interface RouteModule {
default?: ComponentType<PageProps>;
// deno-lint-ignore no-explicit-any
handler?: Handler<any, any> | Handlers<any, any>;
config?: RouteConfig;
}
// deno-lint-ignore no-explicit-any
export interface Route<Data = any> {
pattern: string;
url: string;
name: string;
component?: ComponentType<PageProps<Data>>;
handler: Handler<Data> | Handlers<Data>;
csp: boolean;
}
// --- APP ---
export interface AppProps {
Component: ComponentType<Record<never, never>>;
}
export interface AppModule {
default: ComponentType<AppProps>;
}
// --- UNKNOWN PAGE ---
export interface UnknownPageProps {
/** The URL of the request that resulted in this page being rendered. */
url: URL;
/** The route matcher (e.g. /blog/:id) that the request matched for this page
* to be rendered. */
route: string;
}
export interface UnknownHandlerContext<State = Record<string, unknown>> export interface UnknownHandlerContext<State = Record<string, unknown>>
extends ConnInfo { extends ConnInfo {
render: () => Response | Promise<Response>; render: () => Response | Promise<Response>;
state: State; state: State;
} }
export type UnknownHandler = (
req: Request,
ctx: UnknownHandlerContext,
) => Response | Promise<Response>;
export interface UnknownPageModule {
default?: ComponentType<UnknownPageProps>;
handler?: UnknownHandler;
config?: RouteConfig;
}
export interface UnknownPage {
pattern: string;
url: string;
name: string;
component?: ComponentType<UnknownPageProps>;
handler: UnknownHandler;
csp: boolean;
}
// --- ERROR PAGE ---
export interface ErrorPageProps {
/** The URL of the request that resulted in this page being rendered. */
url: URL;
/** The route matcher (e.g. /blog/:id) that the request matched for this page
* to be rendered. */
pattern: string;
/** The error that caused the error page to be loaded. */
error: unknown;
}
export interface ErrorHandlerContext<State = Record<string, unknown>> export interface ErrorHandlerContext<State = Record<string, unknown>>
extends ConnInfo { extends ConnInfo {
error: unknown; error: unknown;
render: () => Response | Promise<Response>; render: () => Response | Promise<Response>;
state: State; state: State;
} }
export type ErrorHandler = (
req: Request,
ctx: ErrorHandlerContext,
) => Response | Promise<Response>;
export interface ErrorPageModule {
default?: ComponentType<ErrorPageProps>;
handler?: ErrorHandler;
config?: RouteConfig;
}
export interface ErrorPage {
pattern: string;
url: string;
name: string;
component?: ComponentType<ErrorPageProps>;
handler: ErrorHandler;
csp: boolean;
}
// --- MIDDLEWARES ---
export interface MiddlewareHandlerContext<State = Record<string, unknown>> export interface MiddlewareHandlerContext<State = Record<string, unknown>>
extends ConnInfo { extends ConnInfo {
@@ -74,51 +191,15 @@ export interface MiddlewareHandlerContext<State = Record<string, unknown>>
state: State; state: State;
} }
// deno-lint-ignore no-explicit-any export interface MiddlewareRoute extends Middleware {
export type Handler<T = any, State = Record<string, unknown>> = ( /**
req: Request, * path-to-regexp style url path
ctx: HandlerContext<T, State>, */
) => Response | Promise<Response>; pattern: string;
export type UnknownHandler = ( /**
req: Request, * URLPattern of the route
ctx: UnknownHandlerContext, */
) => Response | Promise<Response>; compiledPattern: URLPattern;
export type ErrorHandler = (
req: Request,
ctx: ErrorHandlerContext,
) => Response | Promise<Response>;
// deno-lint-ignore no-explicit-any
export type Handlers<T = any, State = Record<string, unknown>> = {
[K in typeof router.METHODS[number]]?: Handler<T, State>;
};
// deno-lint-ignore no-explicit-any
export interface Page<Data = any> {
route: string;
url: string;
name: string;
component?: ComponentType<PageProps<Data>>;
handler: Handler<Data> | Handlers<Data>;
csp: boolean;
}
export interface UnknownPage {
route: string;
url: string;
name: string;
component?: ComponentType<UnknownPageProps>;
handler: UnknownHandler;
csp: boolean;
}
export interface ErrorPage {
route: string;
url: string;
name: string;
component?: ComponentType<ErrorPageProps>;
handler: ErrorHandler;
csp: boolean;
} }
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
@@ -136,20 +217,11 @@ export interface Middleware<State = Record<string, unknown>> {
): Response | Promise<Response>; ): Response | Promise<Response>;
} }
export interface MiddlewareRoute extends Middleware { // --- ISLANDS ---
/**
* path-to-regexp style url path
*/
route: string;
/**
* URLPattern of the route
*/
// deno-lint-ignore no-explicit-any
pattern: any;
}
export interface AppModule { export interface IslandModule {
default: ComponentType<AppProps>; // deno-lint-ignore no-explicit-any
default: ComponentType<any>;
} }
export interface Island { export interface Island {
+1 -1
View File
@@ -1,6 +1,6 @@
/** @jsx h */ /** @jsx h */
import { h } from "preact"; import { h } from "preact";
import { UnknownPageProps } from "$fresh/runtime.ts"; import { UnknownPageProps } from "$fresh/server.ts";
export default function NotFoundPage({ url }: UnknownPageProps) { export default function NotFoundPage({ url }: UnknownPageProps) {
return <p>404 not found: {url.pathname}</p>; return <p>404 not found: {url.pathname}</p>;
+1 -1
View File
@@ -1,6 +1,6 @@
/** @jsx h */ /** @jsx h */
import { h } from "preact"; import { h } from "preact";
import { ErrorPageProps } from "$fresh/runtime.ts"; import { ErrorPageProps } from "$fresh/server.ts";
export default function Error500Page({ error }: ErrorPageProps) { export default function Error500Page({ error }: ErrorPageProps) {
return <p>500 internal error: {(error as Error).message}</p>; return <p>500 internal error: {(error as Error).message}</p>;
+2 -1
View File
@@ -1,7 +1,8 @@
/** @jsx h */ /** @jsx h */
/** @jsxFrag Fragment */ /** @jsxFrag Fragment */
import { Fragment, h } from "preact"; import { Fragment, h } from "preact";
import { AppProps, Head } from "$fresh/runtime.ts"; import { Head } from "$fresh/runtime.ts";
import { AppProps } from "$fresh/server.ts";
export default function App(props: AppProps) { export default function App(props: AppProps) {
return ( return (
+1 -1
View File
@@ -1,6 +1,6 @@
/** @jsx h */ /** @jsx h */
import { h } from "preact"; import { h } from "preact";
import { PageProps, RouteConfig } from "$fresh/runtime.ts"; import { PageProps, RouteConfig } from "$fresh/server.ts";
export default function Page(props: PageProps) { export default function Page(props: PageProps) {
return <div>Book {props.params.id}</div>; return <div>Book {props.params.id}</div>;
+1 -2
View File
@@ -1,7 +1,6 @@
/** @jsx h */ /** @jsx h */
import { h } from "preact"; import { h } from "preact";
import { PageProps } from "$fresh/runtime.ts"; import { Handlers, PageProps } from "$fresh/server.ts";
import { Handlers } from "$fresh/server.ts";
interface Data extends Record<string, unknown> { interface Data extends Record<string, unknown> {
info: string; info: string;
+1 -3
View File
@@ -1,7 +1,5 @@
/** @jsx h */ /** @jsx h */
import { h } from "preact"; import { HandlerContext, RouteConfig } from "$fresh/server.ts";
import { RouteConfig } from "$fresh/runtime.ts";
import { HandlerContext } from "../../../server.ts";
export const handler = { export const handler = {
GET(_req: Request, { params }: HandlerContext) { GET(_req: Request, { params }: HandlerContext) {
+1 -1
View File
@@ -1,6 +1,6 @@
/** @jsx h */ /** @jsx h */
import { h } from "preact"; import { h } from "preact";
import { PageProps } from "$fresh/runtime.ts"; import { PageProps } from "$fresh/server.ts";
export default function Home(props: PageProps) { export default function Home(props: PageProps) {
return <div>{JSON.stringify(props)}</div>; return <div>{JSON.stringify(props)}</div>;
+1 -1
View File
@@ -1,6 +1,6 @@
/** @jsx h */ /** @jsx h */
import { h } from "preact"; import { h } from "preact";
import { PageProps, RouteConfig } from "$fresh/runtime.ts"; import { PageProps, RouteConfig } from "$fresh/server.ts";
export default function WildcardPage({ params }: PageProps) { export default function WildcardPage({ params }: PageProps) {
if (typeof params.path === "string") { if (typeof params.path === "string") {
+2 -2
View File
@@ -1,8 +1,8 @@
/** @jsx h */ /** @jsx h */
/** @jsxFrag Fragment */ /** @jsxFrag Fragment */
import { Fragment, h } from "preact"; import { Fragment, h } from "preact";
import { Head, PageProps } from "$fresh/runtime.ts"; import { Head } from "$fresh/runtime.ts";
import { Handlers } from "$fresh/server.ts"; import { Handlers, PageProps } from "$fresh/server.ts";
import { apply, tw } from "../../utils/twind.ts"; import { apply, tw } from "../../utils/twind.ts";
import { frontMatter, gfm } from "../../utils/markdown.ts"; import { frontMatter, gfm } from "../../utils/markdown.ts";
+2 -1
View File
@@ -1,7 +1,8 @@
/** @jsx h */ /** @jsx h */
/** @jsxFrag Fragment */ /** @jsxFrag Fragment */
import { ComponentChildren, Fragment, h } from "preact"; import { ComponentChildren, Fragment, h } from "preact";
import { asset, Head, PageProps } from "$fresh/runtime.ts"; import { asset, Head } from "$fresh/runtime.ts";
import { PageProps } from "$fresh/server.ts";
import { tw } from "../utils/twind.ts"; import { tw } from "../utils/twind.ts";
import Counter from "../islands/Counter.tsx"; import Counter from "../islands/Counter.tsx";
import LemonDrop from "../islands/LemonDrop.tsx"; import LemonDrop from "../islands/LemonDrop.tsx";