feat: support async route components (#1388)

This commit is contained in:
Marvin Hagemeister
2023-07-12 21:09:56 +02:00
committed by GitHub
parent e2a1bf8643
commit 62a5613a46
20 changed files with 564 additions and 96 deletions
+2 -2
View File
@@ -15,9 +15,9 @@ export default function(state) { hydrate(options, state); }`;
return {
name: "twind",
entrypoints: { "main": main },
render(ctx) {
async renderAsync(ctx) {
sheet.reset(undefined);
const res = ctx.render();
const res = await ctx.renderAsync();
const cssTexts = [...sheet.target];
const snapshot = sheet.reset();
const scripts = [];
+2 -2
View File
@@ -15,8 +15,8 @@ export default function(state) { hydrate(options, state); }`;
return {
name: "twind",
entrypoints: { "main": main },
render(ctx) {
const res = ctx.render();
async renderAsync(ctx) {
const res = await ctx.renderAsync();
const cssText = stringify(sheet.target);
const scripts = [];
if (res.requiresHydration) {
+122 -54
View File
@@ -32,12 +32,17 @@ import {
Route,
RouteModule,
RouterOptions,
RouterState,
ServeHandlerInfo,
UnknownPage,
UnknownPageModule,
} from "./types.ts";
import { render as internalRender } from "./render.ts";
import { ContentSecurityPolicyDirectives, SELF } from "../runtime/csp.ts";
import { DEFAULT_RENDER_FN, render as internalRender } from "./render.ts";
import {
ContentSecurityPolicy,
ContentSecurityPolicyDirectives,
SELF,
} from "../runtime/csp.ts";
import { ASSET_CACHE_BUST_KEY, INTERNAL_PREFIX } from "../runtime/utils.ts";
import {
Builder,
@@ -52,10 +57,6 @@ const DEFAULT_CONN_INFO: ServeHandlerInfo = {
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
};
interface RouterState {
state: Record<string, unknown>;
}
function isObject(value: unknown) {
return typeof value === "object" &&
!Array.isArray(value) &&
@@ -595,6 +596,58 @@ export class ServerContext {
};
}
const dependenciesFn = (path: string) => {
const snapshot = this.#maybeBuildSnapshot();
return snapshot?.dependencies(path) ?? [];
};
const renderNotFound = async <Data = undefined>(
req: Request,
params: Record<string, string>,
// deno-lint-ignore no-explicit-any
ctx?: any,
data?: Data,
error?: unknown,
) => {
const notFound = this.#notFound;
if (!notFound.component) {
return sendResponse(["Not found.", undefined], {
status: Status.NotFound,
isDev: this.#dev,
statusText: undefined,
headers: undefined,
});
}
const imports: string[] = [];
const resp = await internalRender({
request: req,
context: ctx,
route: notFound,
islands: this.#islands,
plugins: this.#plugins,
app: this.#app,
imports,
dependenciesFn,
renderFn: this.#renderFn,
url: new URL(req.url),
params,
data,
state: ctx?.state,
error,
});
if (resp instanceof Response) {
return resp;
}
return sendResponse(resp, {
status: Status.NotFound,
isDev: this.#dev,
statusText: undefined,
headers: undefined,
});
};
const genRender = <Data = undefined>(
route: Route<Data> | UnknownPage | ErrorPage,
status: number,
@@ -604,7 +657,8 @@ export class ServerContext {
return (
req: Request,
params: Record<string, string>,
state?: Record<string, unknown>,
// deno-lint-ignore no-explicit-any
ctx?: any,
error?: unknown,
) => {
return async (data?: Data, options?: RenderOptions) => {
@@ -612,65 +666,42 @@ export class ServerContext {
throw new Error("This page does not have a component to render.");
}
if (
typeof route.component === "function" &&
route.component.constructor.name === "AsyncFunction"
) {
throw new Error(
"Async components are not supported. Fetch data inside of a route handler, as described in the docs: https://fresh.deno.dev/docs/getting-started/fetching-data",
);
}
const resp = await internalRender({
request: req,
context: {
...ctx,
async renderNotFound() {
return await renderNotFound(req, params, ctx, data, error);
},
},
route,
islands: this.#islands,
plugins: this.#plugins,
app: this.#app,
imports,
dependenciesFn: (path) => {
const snapshot = this.#maybeBuildSnapshot();
return snapshot?.dependencies(path) ?? [];
},
dependenciesFn,
renderFn: this.#renderFn,
url: new URL(req.url),
params,
data,
state,
state: ctx?.state,
error,
});
const headers: Record<string, string> = {
"content-type": "text/html; charset=utf-8",
};
const [body, csp] = resp;
if (csp) {
if (this.#dev) {
csp.directives.connectSrc = [
...(csp.directives.connectSrc ?? []),
SELF,
];
}
const directive = serializeCSPDirectives(csp.directives);
if (csp.reportOnly) {
headers["content-security-policy-report-only"] = directive;
} else {
headers["content-security-policy"] = directive;
}
if (resp instanceof Response) {
return resp;
}
return new Response(body, {
return sendResponse(resp, {
status: options?.status ?? status,
statusText: options?.statusText,
headers: options?.headers
? { ...headers, ...options.headers }
: headers,
headers: options?.headers,
isDev: this.#dev,
});
};
};
};
const createUnknownRender = genRender(this.#notFound, Status.NotFound);
for (const route of this.#routes) {
if (this.#routerOptions.trailingSlash && route.pattern != "/") {
route.pattern += "/";
@@ -682,8 +713,10 @@ export class ServerContext {
(route.handler as Handler)(req, {
...ctx,
params,
render: createRender(req, params, ctx.state),
renderNotFound: createUnknownRender(req, params, ctx.state),
render: createRender(req, params, ctx),
async renderNotFound<Data = undefined>(data: Data) {
return await renderNotFound(req, params, ctx, data);
},
}),
};
} else {
@@ -697,8 +730,10 @@ export class ServerContext {
handler(req, {
...ctx,
params,
render: createRender(req, params, ctx.state),
renderNotFound: createUnknownRender(req, params, ctx.state),
render: createRender(req, params, ctx),
async renderNotFound<Data = undefined>(data: Data) {
return await renderNotFound(req, params, ctx, data);
},
});
}
}
@@ -712,7 +747,9 @@ export class ServerContext {
req,
{
...ctx,
render: createUnknownRender(req, {}),
render() {
return renderNotFound(req, {}, ctx);
},
},
);
@@ -843,10 +880,6 @@ export class ServerContext {
};
}
const DEFAULT_RENDER_FN: RenderFunction = (_ctx, render) => {
render();
};
const DEFAULT_ROUTER_OPTIONS: RouterOptions = {
trailingSlash: false,
};
@@ -1099,3 +1132,38 @@ async function readDenoConfig(
dir = parent;
}
}
function sendResponse(
resp: [string, ContentSecurityPolicy | undefined],
options: {
status: number;
statusText: string | undefined;
headers?: HeadersInit;
isDev: boolean;
},
) {
const headers: Record<string, string> = {
"content-type": "text/html; charset=utf-8",
};
const [body, csp] = resp;
if (csp) {
if (options.isDev) {
csp.directives.connectSrc = [
...(csp.directives.connectSrc ?? []),
SELF,
];
}
const directive = serializeCSPDirectives(csp.directives);
if (csp.reportOnly) {
headers["content-security-policy-report-only"] = directive;
} else {
headers["content-security-policy"] = directive;
}
}
return new Response(body, {
status: options.status,
statusText: options.statusText,
headers: options.headers ? { ...headers, ...options.headers } : headers,
});
}
+1
View File
@@ -37,6 +37,7 @@ export type {
PluginRenderStyleTag,
RenderFunction,
RouteConfig,
RouteContext,
ServeHandlerInfo,
StartOptions,
UnknownHandler,
+80 -31
View File
@@ -11,6 +11,7 @@ import {
} from "preact";
import {
AppModule,
AsyncRoute,
ErrorPage,
Island,
Plugin,
@@ -29,6 +30,10 @@ import { assetHashingHook } from "../runtime/utils.ts";
import { htmlEscapeJsonString } from "./htmlescape.ts";
import { serialize } from "./serializer.ts";
export const DEFAULT_RENDER_FN: RenderFunction = (_ctx, render) => {
render();
};
// These hooks are long stable, but when we originally added them we
// weren't sure if they should be public.
export interface AdvancedPreactOptions extends PreactOptions {
@@ -44,6 +49,9 @@ const options = preactOptions as AdvancedPreactOptions;
options.errorBoundaries = true;
export interface RenderOptions<Data> {
request: Request;
// deno-lint-ignore no-explicit-any
context: any;
route: Route<Data> | UnknownPage | ErrorPage;
islands: Island[];
plugins: Plugin[];
@@ -133,7 +141,11 @@ function defaultCsp() {
*/
export async function render<Data>(
opts: RenderOptions<Data>,
): Promise<[string, ContentSecurityPolicy | undefined]> {
): Promise<[string, ContentSecurityPolicy | undefined] | Response> {
const component = opts.route.component;
const isAsyncComponent = typeof component === "function" &&
component.constructor.name === "AsyncFunction";
const props: Record<string, unknown> = {
params: opts.params,
url: opts.url,
@@ -149,31 +161,6 @@ export async function render<Data>(
? defaultCsp()
: undefined;
const headComponents: ComponentChildren[] = [];
const vnode = h(CSP_CONTEXT.Provider, {
value: csp,
children: h(HEAD_CONTEXT.Provider, {
value: headComponents,
children: h(opts.app.default, {
params: opts.params as Record<string, string>,
url: opts.url,
route: opts.route.pattern,
data: opts.data,
state: opts.state!,
Component() {
return h(opts.route.component! as ComponentType<unknown>, props);
},
}),
}),
});
const ctx = new RenderContext(
crypto.randomUUID(),
opts.url,
opts.route.pattern,
opts.lang ?? "en",
);
if (csp) {
// Clear the csp
const newCsp = defaultCsp();
@@ -192,15 +179,46 @@ export async function render<Data>(
// Clear the island props
ISLAND_PROPS = [];
const ctx = new RenderContext(
crypto.randomUUID(),
opts.url,
opts.route.pattern,
opts.lang ?? "en",
);
let bodyHtml: string | null = null;
function renderInner(): string {
bodyHtml = renderToString(vnode);
function renderInner(vnode: ComponentChildren): string {
const root = h(CSP_CONTEXT.Provider, {
value: csp,
children: h(HEAD_CONTEXT.Provider, {
value: headComponents,
children: h(opts.app.default, {
params: opts.params as Record<string, string>,
url: opts.url,
route: opts.route.pattern,
data: opts.data,
state: opts.state!,
Component() {
// deno-lint-ignore no-explicit-any
return vnode as any;
},
}),
}),
});
bodyHtml = renderToString(root);
return bodyHtml;
}
const syncPlugins = opts.plugins.filter((p) => p.render);
const renderResults: [Plugin, PluginRenderResult][] = [];
const syncPlugins = opts.plugins.filter((p) => p.render);
if (isAsyncComponent && syncPlugins.length > 0) {
throw new Error(
`Async server components cannot be rendered synchronously. The following plugins use a synchronous render method: "${
syncPlugins.map((plugin) => plugin.name).join('", "')
}"`,
);
}
function renderSync(): PluginRenderFunctionResult {
const plugin = syncPlugins.shift();
@@ -213,7 +231,7 @@ export async function render<Data>(
}
renderResults.push([plugin, res]);
} else {
renderInner();
renderInner(h(component as ComponentType, props));
}
if (bodyHtml === null) {
throw new Error(
@@ -228,6 +246,7 @@ export async function render<Data>(
const asyncPlugins = opts.plugins.filter((p) => p.renderAsync);
let asyncRenderResponse: Response | undefined;
async function renderAsync(): Promise<PluginRenderFunctionResult> {
const plugin = asyncPlugins.shift();
if (plugin) {
@@ -244,7 +263,33 @@ export async function render<Data>(
);
}
} else {
await opts.renderFn(ctx, () => renderSync().htmlText);
if (isAsyncComponent) {
if (opts.renderFn !== DEFAULT_RENDER_FN) {
throw new Error(
`Async server components are not supported with custom render functions.`,
);
}
// deno-lint-ignore no-explicit-any
const res = await (component as AsyncRoute<any>)(opts.request, {
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 ?? {},
});
if (res instanceof Response) {
asyncRenderResponse = res;
bodyHtml = "";
} else {
renderInner(res);
}
} else {
await opts.renderFn(ctx, () => renderSync().htmlText);
}
if (bodyHtml === null) {
throw new Error(
`The 'render' function was not called by the legacy async render hook.`,
@@ -258,6 +303,10 @@ export async function render<Data>(
}
await renderAsync();
if (asyncRenderResponse !== undefined) {
return asyncRenderResponse;
}
bodyHtml = bodyHtml as unknown as string;
const moduleScripts: [string, string][] = [];
+31 -7
View File
@@ -1,4 +1,4 @@
import { ComponentType } from "preact";
import { ComponentChildren, ComponentType, VNode } from "preact";
import { ServeInit } from "./deps.ts";
import * as router from "./router.ts";
import { InnerRenderFunction, RenderContext } from "./render.ts";
@@ -56,6 +56,16 @@ export interface PageProps<T = any, S = Record<string, unknown>> {
state: S;
}
/**
* Context passed to async route components.
*/
export type RouteContext<T = unknown, S = Record<string, unknown>> =
& Omit<
HandlerContext<T, S>,
"render"
>
& Omit<PageProps<unknown, S>, "data">;
export interface RouteConfig {
/**
* A route override for the page. This is useful for pages where the route
@@ -119,22 +129,36 @@ export type Handlers<T = any, State = Record<string, unknown>> = {
export type MultiHandler<T> = Handlers<T>;
export interface RouteModule {
default?: ComponentType<PageProps>;
default?: PageComponent<PageProps>;
// deno-lint-ignore no-explicit-any
handler?: Handler<any, any> | Handlers<any, any>;
config?: RouteConfig;
}
export type AsyncRoute<T> = (
req: Request,
ctx: RouteContext<T>,
) => Promise<ComponentChildren | Response>;
export type PageComponent<T> =
| ComponentType<PageProps<T>>
| AsyncRoute<T>
// deno-lint-ignore no-explicit-any
| ((props: any) => VNode<any> | ComponentChildren);
// deno-lint-ignore no-explicit-any
export interface Route<Data = any> {
pattern: string;
url: string;
name: string;
component?: ComponentType<PageProps<Data>>;
component?: PageComponent<Data>;
handler: Handler<Data> | Handlers<Data>;
csp: boolean;
}
export interface RouterState {
state: Record<string, unknown>;
}
// --- APP ---
export interface AppProps extends PageProps {
@@ -175,7 +199,7 @@ export type UnknownHandler = (
) => Response | Promise<Response>;
export interface UnknownPageModule {
default?: ComponentType<UnknownPageProps>;
default?: PageComponent<UnknownPageProps>;
handler?: UnknownHandler;
config?: RouteConfig;
}
@@ -184,7 +208,7 @@ export interface UnknownPage {
pattern: string;
url: string;
name: string;
component?: ComponentType<UnknownPageProps>;
component?: PageComponent<UnknownPageProps>;
handler: UnknownHandler;
csp: boolean;
}
@@ -216,7 +240,7 @@ export type ErrorHandler = (
) => Response | Promise<Response>;
export interface ErrorPageModule {
default?: ComponentType<ErrorPageProps>;
default?: PageComponent<ErrorPageProps>;
handler?: ErrorHandler;
config?: RouteConfig;
}
@@ -225,7 +249,7 @@ export interface ErrorPage {
pattern: string;
url: string;
name: string;
component?: ComponentType<ErrorPageProps>;
component?: PageComponent<ErrorPageProps>;
handler: ErrorHandler;
csp: boolean;
}
+20
View File
@@ -0,0 +1,20 @@
{
"lock": false,
"tasks": {
"start": "deno run -A --watch=static/,routes/ dev.ts"
},
"imports": {
"$fresh/": "../../",
"twind": "https://esm.sh/twind@0.16.19",
"twind/": "https://esm.sh/twind@0.16.19/",
"preact": "https://esm.sh/preact@10.15.1",
"preact/": "https://esm.sh/preact@10.15.1/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.1.0",
"@preact/signals": "https://esm.sh/*@preact/signals@1.1.3",
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3"
},
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "preact"
}
}
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env -S deno run -A --watch=static/,routes/
import dev from "$fresh/dev.ts";
await dev(import.meta.url, "./main.ts");
@@ -0,0 +1,30 @@
// DO NOT EDIT. This file is generated by fresh.
// This file SHOULD be checked into source version control.
// This file is automatically updated during development when running `dev.ts`.
import * as $0 from "./routes/basic.tsx";
import * as $1 from "./routes/context/[id].tsx";
import * as $2 from "./routes/fail.tsx";
import * as $3 from "./routes/index.tsx";
import * as $4 from "./routes/island.tsx";
import * as $5 from "./routes/response.tsx";
import * as $6 from "./routes/twind.tsx";
import * as $$0 from "./islands/FooIsland.tsx";
const manifest = {
routes: {
"./routes/basic.tsx": $0,
"./routes/context/[id].tsx": $1,
"./routes/fail.tsx": $2,
"./routes/index.tsx": $3,
"./routes/island.tsx": $4,
"./routes/response.tsx": $5,
"./routes/twind.tsx": $6,
},
islands: {
"./islands/FooIsland.tsx": $$0,
},
baseUrl: import.meta.url,
};
export default manifest;
@@ -0,0 +1,13 @@
import { useSignal } from "@preact/signals";
export default function FooIsland() {
const sig = useSignal(0);
return (
<button
onClick={() => sig.value += 1}
class="bg-gray-200 py-2 px-4 rounded m-8"
>
update {sig}
</button>
);
}
+11
View File
@@ -0,0 +1,11 @@
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
import { start } from "$fresh/server.ts";
import twind from "$fresh/plugins/twind.ts";
import manifest from "./fresh.gen.ts";
import twindConfig from "./twind.config.ts";
await start(manifest, { plugins: [twind(twindConfig)] });
@@ -0,0 +1,4 @@
export default async function Home() {
await new Promise((r) => setTimeout(r, 10));
return <h1>it works</h1>;
}
@@ -0,0 +1,15 @@
import { RouteContext } from "../../../../server.ts";
import { delay } from "../../../deps.ts";
export default async function Foo(_req: Request, context: RouteContext) {
await delay(1);
const value = JSON.stringify(context, (_key, value) => {
if (typeof value === "function") return value.constructor.name;
return value;
}, 2);
return new Response(value, {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
@@ -0,0 +1,6 @@
import { RouteContext } from "$fresh/server.ts";
// deno-lint-ignore require-await
export default async function Home(_req: Request, ctx: RouteContext) {
return ctx.renderNotFound();
}
@@ -0,0 +1,27 @@
import * as path from "https://deno.land/std@0.192.0/path/mod.ts";
const __dirname = path.dirname(path.fromFileUrl(import.meta.url));
const links: string[] = [];
for (const file of Deno.readDirSync(__dirname)) {
if (file.name.startsWith("index")) continue;
const name = path.basename(file.name, path.extname(file.name));
links.push(name);
}
export default function Home() {
return (
<div class="mx-auto max-w-md">
<h1 class="text-3xl font-bold my-8">Tests</h1>
<ul class="pl-4">
{links.map((link) => {
return (
<li key={link} class="list-disc">
<a href={`/${link}`} class="underline">{link}</a>
</li>
);
})}
</ul>
</div>
);
}
@@ -0,0 +1,6 @@
import FooIsland from "../islands/FooIsland.tsx";
export default async function Island() {
await new Promise((r) => setTimeout(r, 10));
return <FooIsland />;
}
@@ -0,0 +1,6 @@
import { delay } from "../../deps.ts";
export default async function Foo() {
await delay(1);
return new Response("it works", { status: 200 });
}
@@ -0,0 +1,4 @@
export default async function Twind() {
await new Promise((r) => setTimeout(r, 10));
return <h1 class="text-3xl text-red-600 font-bold">it works</h1>;
}
@@ -0,0 +1,17 @@
import * as colors from "twind/colors";
export default {
selfURL: import.meta.url,
theme: {
colors: {
blue: colors.blue,
black: colors.black,
gray: colors.gray,
green: colors.green,
red: colors.red,
white: colors.white,
yellow: colors.yellow,
transparent: "transparent",
},
},
};
+162
View File
@@ -0,0 +1,162 @@
import { assertEquals } from "./deps.ts";
import { startFreshServer, withPageName } from "./test_utils.ts";
import { Status } from "../server.ts";
Deno.test({
name: "render async server component",
async fn() {
await withPageName(
"./tests/fixture_server_components/main.ts",
async (page, address) => {
await page.goto(`${address}/basic`);
await page.waitForSelector("h1");
const text = await page.$eval("h1", (el) => el.textContent);
assertEquals(text, "it works");
},
);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "uses returned response",
async fn() {
await withPageName(
"./tests/fixture_server_components/main.ts",
async (page, address) => {
await page.goto(`${address}/response`);
const text = await page.$eval("body", (el) => el.textContent);
assertEquals(text, "it works");
},
);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "revives islands in async server component",
async fn() {
await withPageName(
"./tests/fixture_server_components/main.ts",
async (page, address) => {
await page.goto(`${address}/island`);
await page.waitForSelector("button");
let text = await page.$eval("button", (el) => el.textContent);
assertEquals(text, "update 0");
await page.click("button");
text = await page.$eval("button", (el) => el.textContent);
assertEquals(text, "update 1");
},
);
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "passes context to server component",
async fn() {
const { lines, serverProcess, address } = await startFreshServer({
args: ["run", "-A", "./tests/fixture_server_components/main.ts"],
});
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(
json,
{
localAddr: {
hostname: "localhost",
port: 8000,
transport: "tcp",
},
remoteAddr: {
hostname: "localhost",
port: 8000,
transport: "tcp",
},
renderNotFound: "AsyncFunction",
url: `${address}/context/foo`,
route: "/context/:id",
params: {
id: "foo",
},
state: {},
},
);
await lines.cancel();
serverProcess.kill("SIGTERM");
await serverProcess.status;
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "can call context.renderNotFound()",
async fn() {
const { lines, serverProcess, address } = await startFreshServer({
args: ["run", "-A", "./tests/fixture_server_components/main.ts"],
});
const res = await fetch(`${address}/fail`);
assertEquals(res.status, Status.NotFound);
const html = await res.text();
assertEquals(html, "Not found.");
await lines.cancel();
serverProcess.kill("SIGTERM");
await serverProcess.status;
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "works with async plugins",
async fn() {
await withPageName(
"./tests/fixture_server_components/main.ts",
async (page, address) => {
await page.goto(`${address}/twind`);
await page.waitForSelector("h1");
const text = await page.$eval("body", (el) => el.textContent);
assertEquals(text, "it works");
// Check that CSS was applied accordingly
const color = await page.$eval("h1", (el) => {
return window.getComputedStyle(el).color;
});
assertEquals(color, "rgb(220, 38, 38)");
},
);
},
sanitizeOps: false,
sanitizeResources: false,
});