feat: expose config in context + simplify page props (#2102)

This commit is contained in:
Marvin Hagemeister
2023-11-30 16:11:31 +01:00
committed by GitHub
parent aafe048243
commit 9e11c5c56b
11 changed files with 254 additions and 123 deletions
+25 -23
View File
@@ -19,29 +19,10 @@ const mainEntry = toFileUrl(join(
"client.ts",
)).href;
Deno.test("esbuild snapshot with cwd=Deno.cwd()", async () => {
const builder = new EsbuildBuilder({
absoluteWorkingDir: Deno.cwd(),
buildID: "foo",
configPath: denoJson,
dev: false,
entrypoints: {
main: mainEntry,
},
jsx: "react-jsx",
target: "es2020",
});
const snapshot = await builder.build();
assertEquals(snapshot.paths, ["main.js", "metafile.json"]);
});
Deno.test({
name: "esbuild snapshot with cwd=/",
ignore: Deno.build.os === "windows",
fn: async () => {
Deno.test("esbuild", async (t) => {
await t.step("esbuild snapshot with cwd=Deno.cwd()", async () => {
const builder = new EsbuildBuilder({
absoluteWorkingDir: "/",
absoluteWorkingDir: Deno.cwd(),
buildID: "foo",
configPath: denoJson,
dev: false,
@@ -54,5 +35,26 @@ Deno.test({
const snapshot = await builder.build();
assertEquals(snapshot.paths, ["main.js", "metafile.json"]);
},
});
await t.step({
name: "esbuild snapshot with cwd=/",
ignore: Deno.build.os === "windows",
fn: async () => {
const builder = new EsbuildBuilder({
absoluteWorkingDir: "/",
buildID: "foo",
configPath: denoJson,
dev: false,
entrypoints: {
main: mainEntry,
},
jsx: "react-jsx",
target: "es2020",
});
const snapshot = await builder.build();
assertEquals(snapshot.paths, ["main.js", "metafile.json"]);
},
});
});
+5
View File
@@ -257,6 +257,7 @@ export class ServerContext {
const ctx: FreshContext = {
url,
params: {},
config: _self.#state.config,
basePath: _self.#state.config.basePath,
localAddr: connInfo.localAddr,
remoteAddr: connInfo.remoteAddr,
@@ -264,6 +265,7 @@ export class ServerContext {
isPartial: url.searchParams.has(PARTIAL_SEARCH_PARAM),
destination: "route",
error: undefined,
codeFrame: undefined,
Component: NOOP_COMPONENT,
next: NOOP_NEXT,
render: NOOP_NEXT,
@@ -272,6 +274,9 @@ export class ServerContext {
return await renderNotFound(req, ctx);
},
route: "",
get pattern() {
return ctx.route;
},
data: undefined,
};
+13 -8
View File
@@ -6,6 +6,7 @@ import {
ErrorPage,
FreshContext,
LayoutRoute,
PageProps,
Plugin,
PluginRenderFunctionResult,
PluginRenderResult,
@@ -143,19 +144,23 @@ export async function render<Data>(
const { params, data, state, error, url, basePath } = opts.context;
const props: Record<string, unknown> = {
const props: PageProps = {
basePath,
config: opts.context.config,
destination: opts.context.destination,
isPartial: opts.context.isPartial,
params,
error,
codeFrame: opts.context.codeFrame,
remoteAddr: opts.context.remoteAddr,
localAddr: opts.context.localAddr,
Component: () => null,
pattern: opts.context.pattern,
url,
route: opts.route.pattern,
route: opts.context.route,
data,
state,
};
if (error) {
props.error = error;
}
if (opts.codeFrame) {
props.codeFrame = opts.codeFrame;
}
const csp: ContentSecurityPolicy | undefined = opts.route.csp
? defaultCsp()
+46 -73
View File
@@ -151,31 +151,13 @@ export type RenderFunction = (
/// --- ROUTES ---
// deno-lint-ignore no-explicit-any
export interface PageProps<T = any, S = Record<string, unknown>> {
/** 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 parameters 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;
state: S;
}
export type PageProps<T = any, S = Record<string, unknown>> = Omit<
FreshContext<
S,
T
>,
"render" | "next" | "renderNotFound"
>;
export interface StaticFile {
/** The URL to the static file on disk. */
@@ -202,13 +184,19 @@ export interface FreshContext<
url: URL;
basePath: string;
route: string;
/** @deprecated Use `.route` instead */
pattern: string;
destination: router.DestinationKind;
params: Record<string, string>;
isPartial: boolean;
state: State;
config: ResolvedFreshConfig;
/** @deprecated Pass values to state instead */
data: Data;
/** The error that caused the error page to be loaded. */
error?: unknown;
/** Sringified code frame of the error rendering failed (only in development mode) */
codeFrame?: unknown;
// These properties may be different
renderNotFound: (data?: NotFoundData) => Response | Promise<Response>;
@@ -216,7 +204,7 @@ export interface FreshContext<
data?: Data,
options?: RenderOptions,
) => Response | Promise<Response>;
Component: () => VNode;
Component: ComponentType<unknown>;
next: () => Promise<Response>;
}
/**
@@ -322,19 +310,10 @@ export interface Route<Data = any> {
}
// --- APP ---
// deno-lint-ignore no-explicit-any
export type AppProps<T = any, S = Record<string, unknown>> = LayoutProps<T, S>;
export interface AppModule {
default: ComponentType<AppProps> | AsyncLayout;
default: ComponentType<PageProps> | AsyncLayout;
}
// deno-lint-ignore no-explicit-any
export interface LayoutProps<T = any, S = Record<string, unknown>>
extends PageProps<T, S> {
Component: ComponentType<Record<never, never>>;
}
// deno-lint-ignore no-explicit-any
export type AsyncLayout<T = any, S = Record<string, unknown>> = (
req: Request,
@@ -357,7 +336,7 @@ export interface LayoutConfig {
export interface LayoutModule {
// deno-lint-ignore no-explicit-any
handler?: Handler<any, any> | Handlers<any, any>;
default: ComponentType<LayoutProps> | AsyncLayout;
default: ComponentType<PageProps> | AsyncLayout;
config?: LayoutConfig;
}
@@ -372,30 +351,13 @@ export interface LayoutRoute {
// --- UNKNOWN PAGE ---
// deno-lint-ignore no-explicit-any
export interface UnknownPageProps<T = any, S = Record<string, unknown>> {
/** 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;
/**
* Additional data passed into `HandlerContext.renderNotFound`. Defaults to
* `undefined`.
*/
data: T;
state: S;
}
export type UnknownHandler = (
req: Request,
ctx: FreshContext,
) => Response | Promise<Response>;
export interface UnknownPageModule {
default?: PageComponent<UnknownPageProps>;
default?: PageComponent<PageProps>;
handler?: UnknownHandler;
config?: RouteConfig;
}
@@ -405,7 +367,7 @@ export interface UnknownPage {
pattern: string;
url: string;
name: string;
component?: PageComponent<UnknownPageProps>;
component?: PageComponent<PageProps>;
handler: UnknownHandler;
csp: boolean;
appWrapper: boolean;
@@ -419,21 +381,6 @@ export type UnknownRenderFunction = (
// --- 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;
/** Sringified code frame (only in development mode) */
codeFrame?: string;
}
// Nominal/Branded type. Ensures that the string has the expected format
export type BaseRoute = string & { readonly __brand: unique symbol };
@@ -443,7 +390,7 @@ export type ErrorHandler = (
) => Response | Promise<Response>;
export interface ErrorPageModule {
default?: PageComponent<ErrorPageProps>;
default?: PageComponent<PageProps>;
handler?: ErrorHandler;
config?: RouteConfig;
}
@@ -453,7 +400,7 @@ export interface ErrorPage {
pattern: string;
url: string;
name: string;
component?: PageComponent<ErrorPageProps>;
component?: PageComponent<PageProps>;
handler: ErrorHandler;
csp: boolean;
appWrapper: boolean;
@@ -698,3 +645,29 @@ export type ErrorHandlerContext<State = Record<string, unknown>> = FreshContext<
*/
export type MiddlewareHandlerContext<State = Record<string, unknown>> =
FreshContext<State>;
/**
* @deprecated Use {@linkcode PageProps} instead
*/
// deno-lint-ignore no-explicit-any
export type LayoutProps<T = any, S = Record<string, unknown>> = PageProps<T, S>;
/**
* @deprecated Use {@linkcode PageProps} instead
*/
// deno-lint-ignore no-explicit-any
export type UnknownPageProps<T = any, S = Record<string, unknown>> = PageProps<
T,
S
>;
/**
* @deprecated Use {@linkcode PageProps} instead
*/
// deno-lint-ignore no-explicit-any
export type AppProps<T = any, S = Record<string, unknown>> = PageProps<T, S>;
/**
* @deprecated Use {@linkcode PageProps} instead
*/
export type ErrorPageProps = PageProps;
+1
View File
@@ -40,6 +40,7 @@ export {
fromFileUrl,
join,
relative,
SEP,
toFileUrl,
} from "https://deno.land/std@0.208.0/path/mod.ts";
export * as JSONC from "https://deno.land/std@0.208.0/jsonc/mod.ts";
+4
View File
@@ -18,6 +18,8 @@ import * as $api_head_override from "./routes/api/head_override.ts";
import * as $assetsCaching_index from "./routes/assetsCaching/index.tsx";
import * as $books_id_ from "./routes/books/[id].tsx";
import * as $connInfo from "./routes/connInfo.ts";
import * as $ctx_config from "./routes/ctx_config.tsx";
import * as $ctx_config_props from "./routes/ctx_config_props.tsx";
import * as $error_boundary from "./routes/error_boundary.tsx";
import * as $event_handler_string from "./routes/event_handler_string.tsx";
import * as $event_handler_string_island from "./routes/event_handler_string_island.tsx";
@@ -117,6 +119,8 @@ const manifest = {
"./routes/assetsCaching/index.tsx": $assetsCaching_index,
"./routes/books/[id].tsx": $books_id_,
"./routes/connInfo.ts": $connInfo,
"./routes/ctx_config.tsx": $ctx_config,
"./routes/ctx_config_props.tsx": $ctx_config_props,
"./routes/error_boundary.tsx": $error_boundary,
"./routes/event_handler_string.tsx": $event_handler_string,
"./routes/event_handler_string_island.tsx": $event_handler_string_island,
+19
View File
@@ -0,0 +1,19 @@
import { defineRoute } from "$fresh/server.ts";
import { relative, SEP } from "$fresh/tests/deps.ts";
export default defineRoute((_req, ctx) => {
const value = JSON.stringify(ctx, (key, value) => {
if (key === "outDir" || key == "staticDir") {
return relative(Deno.cwd(), value).split(SEP).join("/");
}
if (typeof value === "function") return value.constructor.name;
if (value === undefined) return "<undefined>";
return value;
}, 2);
return (
<pre>
{value}
</pre>
);
});
+15
View File
@@ -0,0 +1,15 @@
import { PageProps } from "$fresh/server.ts";
import { relative, SEP } from "../../deps.ts";
export default function Page(props: PageProps) {
const value = JSON.stringify(props, (key, value) => {
if (key === "outDir" || key == "staticDir") {
return relative(Deno.cwd(), value).split(SEP).join("/");
}
if (typeof value === "function") return value.constructor.name;
if (value === undefined) return "<undefined>";
return value;
}, 2);
return <pre>{value}</pre>;
}
@@ -1,10 +1,16 @@
import { RouteContext } from "../../../../server.ts";
import { delay } from "../../../deps.ts";
import { delay, relative, SEP } from "../../../deps.ts";
export default async function Foo(_req: Request, context: RouteContext) {
await delay(1);
const value = JSON.stringify(context, (_key, value) => {
const value = JSON.stringify(context, (key, value) => {
if (key === "outDir" || key == "staticDir") {
return relative(Deno.cwd(), value).split(SEP).join("/");
} else if (key === "entrypoints") {
return {};
}
if (typeof value === "function") return value.constructor.name;
if (value === undefined) return "<undefined>";
return value;
}, 2);
+95 -17
View File
@@ -52,23 +52,6 @@ Deno.test("/ page prerender", async () => {
assertStringIncludes(body, `<link rel="modulepreload"`);
});
Deno.test("/props/123 page prerender", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/props/123"));
assert(resp);
assertEquals(resp.status, STATUS_CODE.OK);
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
const body = await resp.text();
const doc = parseHtml(body);
const data = JSON.parse(doc.querySelector("body > div")!.textContent!);
assertEquals(data, {
"params": { "id": "123" },
"url": "https://fresh.deno.dev/props/123",
"route": "/props/:id",
"state": { "root": "root_mw" },
});
});
Deno.test("/greet/[name] page prerender", async () => {
const resp = await handler(new Request("https://fresh.deno.dev/bar"));
assert(resp);
@@ -1127,3 +1110,98 @@ Deno.test("pass options in config dev.ts", async (t) => {
}
});
});
Deno.test("Expose config in ctx", async () => {
await withFakeServe("./tests/fixture/main.ts", async (server) => {
const doc = await server.getHtml(`/ctx_config`);
const data = JSON.parse(doc.querySelector("pre")?.textContent!);
assertEquals(data, {
config: {
basePath: "",
build: {
outDir: "tests/fixture/_fresh",
target: [
"chrome99",
"firefox99",
"safari15",
],
},
dev: false,
plugins: [],
render: "Function",
router: "<undefined>",
server: {},
staticDir: "tests/fixture/static",
},
Component: "Function",
params: {},
route: "/ctx_config",
state: {
root: "root_mw",
},
url: "https://127.0.0.1/ctx_config",
basePath: "",
codeFrame: "<undefined>",
destination: "route",
error: "<undefined>",
isPartial: false,
remoteAddr: {
hostname: "127.0.0.1",
port: 80,
transport: "tcp",
},
next: "Function",
render: "AsyncFunction",
renderNotFound: "AsyncFunction",
localAddr: "<undefined>",
pattern: "/ctx_config",
data: "<undefined>",
});
});
});
Deno.test("Expose config in ctx", async () => {
await withFakeServe("./tests/fixture/main.ts", async (server) => {
const doc = await server.getHtml(`/ctx_config_props`);
const data = JSON.parse(doc.querySelector("pre")?.textContent!);
assertEquals(data, {
config: {
basePath: "",
build: {
outDir: "tests/fixture/_fresh",
target: [
"chrome99",
"firefox99",
"safari15",
],
},
dev: false,
plugins: [],
render: "Function",
router: "<undefined>",
server: {},
staticDir: "tests/fixture/static",
},
Component: "Function",
params: {},
route: "/ctx_config_props",
state: {
root: "root_mw",
},
url: "https://127.0.0.1/ctx_config_props",
basePath: "",
codeFrame: "<undefined>",
destination: "route",
error: "<undefined>",
isPartial: false,
remoteAddr: {
hostname: "127.0.0.1",
port: 80,
transport: "tcp",
},
localAddr: "<undefined>",
pattern: "/ctx_config_props",
data: "<undefined>",
});
});
});
+23
View File
@@ -83,6 +83,29 @@ Deno.test("passes context to server component", async () => {
port: 8000,
transport: "tcp",
},
config: {
basePath: "",
build: {
outDir: "tests/fixture_server_components/_fresh",
target: [
"chrome99",
"firefox99",
"safari15",
],
},
dev: false,
plugins: [
{ entrypoints: {}, name: "twind", renderAsync: "AsyncFunction" },
],
render: "Function",
router: "<undefined>",
server: {},
staticDir: "tests/fixture_server_components/static",
},
data: "<undefined>",
error: "<undefined>",
codeFrame: "<undefined>",
pattern: "/context/:id",
render: "AsyncFunction",
Component: "Function",
destination: "route",