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
+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, "<p>Hello!</p>");
assertStringIncludes(body, "<p>Viewing JIT render.</p>");
assertStringIncludes(body, `>[{"message":"Hello!"}]</script>`);
assertStringIncludes(body, `>[[{"message":"Hello!"}],[]]</script>`);
assertStringIncludes(
body,
`<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,
});