feat: add initial plugin support (#512)

This commit adds initial support for fresh "plugins". These are bundles
of functionality that can be added to a fresh plugin through a simple
addition in the `main.ts` file.

Right now plugins are only able to hook into the render steps. This
means that they can inject styling and scripts. They can not yet hook
into routing.

Things that I think should be possible now:
- styling integrations for twind, unocss, and probably a few other tools

Things that are not possible yet:
- google analytics middleware
- database connectors
- CMS connectors

The routing additions to plugins can be added in a follow-up though.
This commit is contained in:
Luca Casonato
2022-08-09 21:27:58 +02:00
committed by GitHub
parent 49092ed83a
commit fd4e2bbe17
20 changed files with 410 additions and 31 deletions
+2 -7
View File
@@ -24,13 +24,8 @@ function createRootFragment(
}; };
} }
const ISLAND_PROPS_COMPONENT = document.getElementById("__FRSH_ISLAND_PROPS");
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
const ISLAND_PROPS: any[] = JSON.parse( export function revive(islands: Record<string, ComponentType>, props: any[]) {
ISLAND_PROPS_COMPONENT?.textContent ?? "[]",
);
export function revive(islands: Record<string, ComponentType>) {
function walk(node: Node | null) { function walk(node: Node | null) {
const tag = node!.nodeType === 8 && const tag = node!.nodeType === 8 &&
((node as Comment).data.match(/^\s*frsh-(.*)\s*$/) || [])[1]; ((node as Comment).data.match(/^\s*frsh-(.*)\s*$/) || [])[1];
@@ -47,7 +42,7 @@ export function revive(islands: Record<string, ComponentType>) {
const [id, n] = tag.split(":"); const [id, n] = tag.split(":");
render( render(
h(islands[id], ISLAND_PROPS[Number(n)]), h(islands[id], props[Number(n)]),
createRootFragment( createRootFragment(
parent! as HTMLElement, parent! as HTMLElement,
children, children,
+10 -2
View File
@@ -1,6 +1,6 @@
import { BUILD_ID } from "./constants.ts"; import { BUILD_ID } from "./constants.ts";
import { denoPlugin, esbuild, toFileUrl } from "./deps.ts"; import { denoPlugin, esbuild, toFileUrl } from "./deps.ts";
import { Island } from "./types.ts"; import { Island, Plugin } from "./types.ts";
let esbuildInitialized: boolean | Promise<void> = false; let esbuildInitialized: boolean | Promise<void> = false;
async function ensureEsbuildInitialized() { async function ensureEsbuildInitialized() {
@@ -23,10 +23,12 @@ async function ensureEsbuildInitialized() {
export class Bundler { export class Bundler {
#importMapURL: URL; #importMapURL: URL;
#islands: Island[]; #islands: Island[];
#plugins: Plugin[];
#cache: Map<string, Uint8Array> | Promise<void> | undefined = undefined; #cache: Map<string, Uint8Array> | Promise<void> | undefined = undefined;
constructor(islands: Island[], importMapURL: URL) { constructor(islands: Island[], plugins: Plugin[], importMapURL: URL) {
this.#islands = islands; this.#islands = islands;
this.#plugins = plugins;
this.#importMapURL = importMapURL; this.#importMapURL = importMapURL;
} }
@@ -39,6 +41,12 @@ export class Bundler {
entryPoints[`island-${island.id}`] = island.url; entryPoints[`island-${island.id}`] = island.url;
} }
for (const plugin of this.#plugins) {
for (const [name, url] of Object.entries(plugin.entrypoints ?? {})) {
entryPoints[`plugin-${plugin.name}-${name}`] = url;
}
}
const absWorkingDir = Deno.cwd(); const absWorkingDir = Deno.cwd();
await ensureEsbuildInitialized(); await ensureEsbuildInitialized();
const bundle = await esbuild.build({ const bundle = await esbuild.build({
+7 -1
View File
@@ -24,6 +24,7 @@ import {
Middleware, Middleware,
MiddlewareModule, MiddlewareModule,
MiddlewareRoute, MiddlewareRoute,
Plugin,
RenderFunction, RenderFunction,
Route, Route,
RouteModule, RouteModule,
@@ -61,6 +62,7 @@ export class ServerContext {
#app: AppModule; #app: AppModule;
#notFound: UnknownPage; #notFound: UnknownPage;
#error: ErrorPage; #error: ErrorPage;
#plugins: Plugin[];
constructor( constructor(
routes: Route[], routes: Route[],
@@ -71,6 +73,7 @@ export class ServerContext {
app: AppModule, app: AppModule,
notFound: UnknownPage, notFound: UnknownPage,
error: ErrorPage, error: ErrorPage,
plugins: Plugin[],
importMapURL: URL, importMapURL: URL,
) { ) {
this.#routes = routes; this.#routes = routes;
@@ -81,7 +84,8 @@ export class ServerContext {
this.#app = app; this.#app = app;
this.#notFound = notFound; this.#notFound = notFound;
this.#error = error; this.#error = error;
this.#bundler = new Bundler(this.#islands, importMapURL); this.#plugins = plugins;
this.#bundler = new Bundler(this.#islands, this.#plugins, importMapURL);
this.#dev = typeof Deno.env.get("DENO_DEPLOYMENT_ID") !== "string"; // Env var is only set in prod (on Deploy). this.#dev = typeof Deno.env.get("DENO_DEPLOYMENT_ID") !== "string"; // Env var is only set in prod (on Deploy).
} }
@@ -260,6 +264,7 @@ export class ServerContext {
app, app,
notFound, notFound,
error, error,
opts.plugins ?? [],
importMapURL, importMapURL,
); );
} }
@@ -414,6 +419,7 @@ export class ServerContext {
const resp = await internalRender({ const resp = await internalRender({
route, route,
islands: this.#islands, islands: this.#islands,
plugins: this.#plugins,
app: this.#app, app: this.#app,
imports, imports,
preloads, preloads,
+4
View File
@@ -21,6 +21,10 @@ export type {
Handlers, Handlers,
MiddlewareHandlerContext, MiddlewareHandlerContext,
PageProps, PageProps,
Plugin,
PluginRenderResult,
PluginRenderScripts,
PluginRenderStyleTag,
RenderFunction, RenderFunction,
RouteConfig, RouteConfig,
StartOptions, StartOptions,
+94 -18
View File
@@ -5,6 +5,10 @@ import {
AppModule, AppModule,
ErrorPage, ErrorPage,
Island, Island,
Plugin,
PluginRenderFunctionResult,
PluginRenderResult,
PluginRenderStyleTag,
RenderFunction, RenderFunction,
Route, Route,
UnknownPage, UnknownPage,
@@ -14,10 +18,12 @@ import { CSP_CONTEXT, nonce, NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
import { ContentSecurityPolicy } from "../runtime/csp.ts"; import { ContentSecurityPolicy } from "../runtime/csp.ts";
import { bundleAssetUrl } from "./constants.ts"; import { bundleAssetUrl } from "./constants.ts";
import { assetHashingHook } from "../runtime/utils.ts"; import { assetHashingHook } from "../runtime/utils.ts";
import { f } from "https://dev.jspm.io/npm:@jspm/core@1.1.1/nodelibs/chunk-0c2d1322.js";
export interface RenderOptions<Data> { export interface RenderOptions<Data> {
route: Route<Data> | UnknownPage | ErrorPage; route: Route<Data> | UnknownPage | ErrorPage;
islands: Island[]; islands: Island[];
plugins: Plugin[];
app: AppModule; app: AppModule;
imports: string[]; imports: string[];
preloads: string[]; preloads: string[];
@@ -176,17 +182,46 @@ export async function render<Data>(
let bodyHtml: string | null = null; let bodyHtml: string | null = null;
function render() { function realRender(): string {
bodyHtml = renderToString(vnode); bodyHtml = renderToString(vnode);
return bodyHtml; return bodyHtml;
} }
await opts.renderFn(ctx, render as InnerRenderFunction); const plugins = opts.plugins.filter((p) => p.render !== null);
const renderResults: [Plugin, PluginRenderResult][] = [];
function render(): PluginRenderFunctionResult {
const plugin = plugins.shift();
if (plugin) {
const res = plugin.render!({ render });
if (res === undefined) {
throw new Error(
`${plugin?.name}'s render hook did not return a PluginRenderResult object.`,
);
}
renderResults.push([plugin, res]);
} else {
realRender();
}
if (bodyHtml === null) {
throw new Error(
`The 'render' function was not called by ${plugin?.name}'s render hook.`,
);
}
return {
htmlText: bodyHtml,
requiresHydration: ENCOUNTERED_ISLANDS.size > 0,
};
}
await opts.renderFn(ctx, () => render().htmlText);
if (bodyHtml === null) { if (bodyHtml === null) {
throw new Error("The `render` function was not called by the renderer."); throw new Error("The `render` function was not called by the renderer.");
} }
bodyHtml = bodyHtml as string;
const imports = opts.imports.map((url) => { const imports = opts.imports.map((url) => {
const randomNonce = crypto.randomUUID().replace(/-/g, ""); const randomNonce = crypto.randomUUID().replace(/-/g, "");
if (csp) { if (csp) {
@@ -198,6 +233,32 @@ export async function render<Data>(
return [url, randomNonce] as const; return [url, randomNonce] as const;
}); });
const state: [islands: unknown[], plugins: unknown[]] = [ISLAND_PROPS, []];
const styleTags: PluginRenderStyleTag[] = [];
let script =
`const STATE_COMPONENT = document.getElementById("__FRSH_STATE");const STATE = JSON.parse(STATE_COMPONENT?.textContent ?? "[[],[]]");`;
for (const [plugin, res] of renderResults) {
for (const hydrate of res.scripts ?? []) {
const i = state[1].push(hydrate.state) - 1;
const randomNonce = crypto.randomUUID().replace(/-/g, "");
if (csp) {
csp.directives.scriptSrc = [
...csp.directives.scriptSrc ?? [],
nonce(randomNonce),
];
}
const url = bundleAssetUrl(
`/plugin-${plugin.name}-${hydrate.entrypoint}.js`,
);
imports.push([url, randomNonce] as const);
script += `import p${i} from "${url}";p${i}(STATE[1][${i}]);`;
}
styleTags.splice(styleTags.length, 0, ...res.styles ?? []);
}
if (ENCOUNTERED_ISLANDS.size > 0) { if (ENCOUNTERED_ISLANDS.size > 0) {
// Load the main.js script // Load the main.js script
{ {
@@ -212,8 +273,9 @@ export async function render<Data>(
imports.push([url, randomNonce] as const); imports.push([url, randomNonce] as const);
} }
script += `import { revive } from "${bundleAssetUrl("/main.js")}";`;
// Prepare the inline script that loads and revives the islands // Prepare the inline script that loads and revives the islands
let islandImports = "";
let islandRegistry = ""; let islandRegistry = "";
for (const island of ENCOUNTERED_ISLANDS) { for (const island of ENCOUNTERED_ISLANDS) {
const randomNonce = crypto.randomUUID().replace(/-/g, ""); const randomNonce = crypto.randomUUID().replace(/-/g, "");
@@ -225,12 +287,17 @@ export async function render<Data>(
} }
const url = bundleAssetUrl(`/island-${island.id}.js`); const url = bundleAssetUrl(`/island-${island.id}.js`);
imports.push([url, randomNonce] as const); imports.push([url, randomNonce] as const);
islandImports += `\nimport ${island.name} from "${url}";`; script += `import ${island.name} from "${url}";`;
islandRegistry += `\n ${island.id}: ${island.name},`; islandRegistry += `${island.id}:${island.name},`;
} }
const initCode = `import { revive } from "${ script += `revive({${islandRegistry}}, STATE[0]);`;
bundleAssetUrl("/main.js") }
}";${islandImports}\nrevive({${islandRegistry}\n});`;
if (state[0].length > 0 || state[1].length > 0) {
// Append state to the body
bodyHtml += `<script id="__FRSH_STATE" type="application/json">${
JSON.stringify(state)
}</script>`;
// Append the inline script to the body // Append the inline script to the body
const randomNonce = crypto.randomUUID().replace(/-/g, ""); const randomNonce = crypto.randomUUID().replace(/-/g, "");
@@ -240,10 +307,25 @@ export async function render<Data>(
nonce(randomNonce), nonce(randomNonce),
]; ];
} }
(bodyHtml as string) += bodyHtml +=
`<script id="__FRSH_ISLAND_PROPS" type="application/json">${ `<script type="module" nonce="${randomNonce}">${script}</script>`;
JSON.stringify(ISLAND_PROPS) }
}</script><script type="module" nonce="${randomNonce}">${initCode}</script>`;
if (ctx.styles.length > 0) {
const node = h("style", {
id: "__FRSH_STYLE",
dangerouslySetInnerHTML: { __html: ctx.styles.join("\n") },
});
headComponents.splice(0, 0, node);
}
for (const style of styleTags) {
const node = h("style", {
id: style.id,
dangerouslySetInnerHTML: { __html: style.cssText },
media: style.media,
});
headComponents.splice(0, 0, node);
} }
const html = template({ const html = template({
@@ -251,7 +333,6 @@ export async function render<Data>(
headComponents, headComponents,
imports, imports,
preloads: opts.preloads, preloads: opts.preloads,
styles: ctx.styles,
lang: ctx.lang, lang: ctx.lang,
}); });
@@ -262,7 +343,6 @@ export interface TemplateOptions {
bodyHtml: string; bodyHtml: string;
headComponents: ComponentChildren[]; headComponents: ComponentChildren[];
imports: (readonly [string, string])[]; imports: (readonly [string, string])[];
styles: string[];
preloads: string[]; preloads: string[];
lang: string; lang: string;
} }
@@ -277,10 +357,6 @@ export function template(opts: TemplateOptions): string {
{opts.imports.map(([src, nonce]) => ( {opts.imports.map(([src, nonce]) => (
<script src={src} nonce={nonce} type="module"></script> <script src={src} nonce={nonce} type="module"></script>
))} ))}
<style
id="__FRSH_STYLE"
dangerouslySetInnerHTML={{ __html: opts.styles.join("\n") }}
/>
{opts.headComponents} {opts.headComponents}
</head> </head>
<body dangerouslySetInnerHTML={{ __html: opts.bodyHtml }} /> <body dangerouslySetInnerHTML={{ __html: opts.bodyHtml }} />
+2 -2
View File
@@ -1,5 +1,6 @@
import { template } from "./render.tsx"; import { template } from "./render.tsx";
import { assertStringIncludes } from "../../tests/deps.ts"; import { assertStringIncludes } from "../../tests/deps.ts";
Deno.test("check lang", () => { Deno.test("check lang", () => {
const lang = "fr"; const lang = "fr";
const body = template({ const body = template({
@@ -7,8 +8,7 @@ Deno.test("check lang", () => {
headComponents: [], headComponents: [],
imports: [], imports: [],
preloads: [], preloads: [],
styles: [], lang,
lang: lang,
}); });
assertStringIncludes(body, `<html lang="${lang}">`); assertStringIncludes(body, `<html lang="${lang}">`);
}); });
+65
View File
@@ -8,6 +8,7 @@ export type StartOptions = ServeInit & FreshOptions;
export interface FreshOptions { export interface FreshOptions {
render?: RenderFunction; render?: RenderFunction;
plugins?: Plugin[];
} }
export type RenderFunction = ( export type RenderFunction = (
@@ -231,3 +232,67 @@ export interface Island {
url: string; url: string;
component: ComponentType<unknown>; component: ComponentType<unknown>;
} }
// --- PLUGINS ---
export interface Plugin {
/** The name of the plugin. Must be snake-case. */
name: string;
/** A map of a snake-case names to a import specifiers. The entrypoints
* declared here can later be used in the "hydrate" option of
* `PluginRenderResult` to load the entrypoint's code on the client.
*/
entrypoints?: Record<string, string>;
/** The render hook is called on the server every time some JSX needs to
* be turned into HTML. The render hook needs to call the `ctx.render`
* function exactly once.
*
* The hook can return a `PluginRenderResult` object that can do things like
* inject CSS into the page, or load additional JS files on the client.
*/
render?(ctx: PluginRenderContext): PluginRenderResult;
}
export interface PluginRenderContext {
render: PluginRenderFunction;
}
export interface PluginRenderResult {
/** CSS styles to be injected into the page. */
styles?: PluginRenderStyleTag[];
/** JS scripts to ship to the client. */
scripts?: PluginRenderScripts[];
}
export interface PluginRenderStyleTag {
cssText: string;
media?: string;
id?: string;
}
export interface PluginRenderScripts {
/** The "key" of the entrypoint (as specified in `Plugin.entrypoints`) for the
* script that should be loaded. The script must be an ES module that exports
* a default function.
*
* The default function is invoked with the `state` argument specified below.
*/
entrypoint: string;
/** The state argument that is passed to the default export invocation of the
* entrypoint's default export. The state must be JSON-serializable.
*/
state: unknown;
}
export type PluginRenderFunction = () => PluginRenderFunctionResult;
export interface PluginRenderFunctionResult {
/** The HTML text that was rendered. */
htmlText: string;
/** If the renderer encountered any islands that require hydration on the
* client.
*/
requiresHydration: boolean;
}
+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");
+20
View File
@@ -0,0 +1,20 @@
// 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/static.tsx";
import * as $1 from "./routes/with-island.tsx";
import * as $$0 from "./islands/Island.tsx";
const manifest = {
routes: {
"./routes/static.tsx": $0,
"./routes/with-island.tsx": $1,
},
islands: {
"./islands/Island.tsx": $$0,
},
baseUrl: import.meta.url,
};
export default manifest;
+8
View File
@@ -0,0 +1,8 @@
{
"imports": {
"$fresh/": "../../",
"preact": "https://esm.sh/preact@10.10.0",
"preact/": "https://esm.sh/preact@10.10.0/",
"preact-render-to-string": "https://esm.sh/preact-render-to-string@5.2.1?external=preact"
}
}
+12
View File
@@ -0,0 +1,12 @@
/** @jsx h */
import { h } from "preact";
import { IS_BROWSER } from "../../../src/runtime/utils.ts";
export default function Island() {
const id = IS_BROWSER ? "csr" : "ssr";
return (
<div>
<p id={id}>{id}</p>
</div>
);
}
+9
View File
@@ -0,0 +1,9 @@
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
import { start } from "$fresh/server.ts";
import manifest from "./fresh.gen.ts";
import options from "./options.ts";
await start(manifest, options);
+5
View File
@@ -0,0 +1,5 @@
import { FreshOptions } from "$fresh/server.ts";
import cssInjectPlugin from "./utils/css-inject-plugin.ts";
import jsInjectPlugin from "./utils/js-inject-plugin.ts";
export default { plugins: [cssInjectPlugin, jsInjectPlugin] } as FreshOptions;
+12
View File
@@ -0,0 +1,12 @@
/** @jsx h */
import { h } from "preact";
import { inject } from "../utils/css-inject-plugin.ts";
export default function Home() {
inject("body { color: red; }");
return (
<div>
<h1>Hello World</h1>
</div>
);
}
@@ -0,0 +1,14 @@
/** @jsx h */
import { h } from "preact";
import Island from "../islands/Island.tsx";
import { inject } from "../utils/css-inject-plugin.ts";
export default function Home() {
inject("body { color: red; }");
return (
<div>
<h1>Hello World</h1>
<Island />
</div>
);
}
@@ -0,0 +1,18 @@
import { Plugin } from "$fresh/server.ts";
let CSS_TO_INJECT = "";
export function inject(cssText: string) {
CSS_TO_INJECT = cssText;
}
export default {
name: "css-inject",
render(ctx) {
CSS_TO_INJECT = "";
const res = ctx.render();
if (res.requiresHydration) {
CSS_TO_INJECT += " h1 { color: blue; }";
}
return { styles: [{ cssText: CSS_TO_INJECT, id: "abc" }] };
},
} as Plugin;
@@ -0,0 +1,3 @@
export default function (state: string) {
document.title = state;
}
@@ -0,0 +1,15 @@
import { Plugin } from "$fresh/server.ts";
export default {
name: "js-inject",
entrypoints: {
"main": new URL("./js-inject-main.ts", import.meta.url).href,
},
render(ctx) {
const res = ctx.render();
if (res.requiresHydration) {
return { scripts: [{ entrypoint: "main", state: "JS injected!" }] };
}
return {};
},
} as Plugin;
+1 -1
View File
@@ -30,7 +30,7 @@ Deno.test("/ page prerender", async () => {
assertStringIncludes(body, "test.js"); assertStringIncludes(body, "test.js");
assertStringIncludes(body, "<p>Hello!</p>"); assertStringIncludes(body, "<p>Hello!</p>");
assertStringIncludes(body, "<p>Viewing JIT render.</p>"); assertStringIncludes(body, "<p>Viewing JIT render.</p>");
assertStringIncludes(body, `>[{"message":"Hello!"}]</script>`); assertStringIncludes(body, `>[[{"message":"Hello!"}],[]]</script>`);
assertStringIncludes( assertStringIncludes(
body, body,
`<meta name="description" content="Hello world!" />`, `<meta name="description" content="Hello world!" />`,
+104
View File
@@ -0,0 +1,104 @@
import { ServerContext, Status } from "../server.ts";
import {
assert,
assertEquals,
assertStringIncludes,
delay,
puppeteer,
TextLineStream,
} from "./deps.ts";
import manifest from "./fixture_plugin/fresh.gen.ts";
import options from "./fixture_plugin/options.ts";
const ctx = await ServerContext.fromManifest(manifest, options);
const router = (req: Request) => {
return ctx.handler()(req, {
localAddr: {
transport: "tcp",
hostname: "127.0.0.1",
port: 80,
},
remoteAddr: {
transport: "tcp",
hostname: "127.0.0.1",
port: 80,
},
});
};
Deno.test("/static page prerender", async () => {
const resp = await router(new Request("https://fresh.deno.dev/static"));
assert(resp);
assertEquals(resp.status, Status.OK);
const body = await resp.text();
assertStringIncludes(body, '<style id="abc">body { color: red; }</style>');
assert(!body.includes(`>[[],[]]</script>`));
assert(!body.includes(`import`));
});
Deno.test("/with-island prerender", async () => {
const resp = await router(new Request("https://fresh.deno.dev/with-island"));
assert(resp);
assertEquals(resp.status, Status.OK);
const body = await resp.text();
assertStringIncludes(
body,
'<style id="abc">body { color: red; } h1 { color: blue; }</style>',
);
assertStringIncludes(body, `>[[{}],["JS injected!"]]</script>`);
assertStringIncludes(body, `/plugin-js-inject-main.js"`);
});
Deno.test({
name: "/with-island hydration",
async fn(t) {
// Preparation
const serverProcess = Deno.run({
cmd: ["deno", "run", "-A", "./tests/fixture_plugin/main.ts"],
stdout: "piped",
stderr: "inherit",
});
const decoder = new TextDecoderStream();
const lines = serverProcess.stdout.readable
.pipeThrough(decoder)
.pipeThrough(new TextLineStream());
let started = false;
for await (const line of lines) {
if (line.includes("Listening on http://")) {
started = true;
break;
}
}
if (!started) {
throw new Error("Server didn't start up");
}
await delay(100);
const browser = await puppeteer.launch({ args: ["--no-sandbox"] });
const page = await browser.newPage();
await page.goto("http://localhost:8000/with-island", {
waitUntil: "networkidle2",
});
await t.step("island is revived", async () => {
await page.waitForSelector("#csr");
});
await t.step("title was updated", async () => {
const title = await page.title();
assertEquals(title, "JS injected!");
});
await browser.close();
await lines.cancel();
serverProcess.kill("SIGTERM");
serverProcess.close();
},
sanitizeOps: false,
sanitizeResources: false,
});