refactor: improved reviving of islands (#100)

This commit is contained in:
Luca Casonato
2022-03-05 01:20:54 +01:00
committed by GitHub
parent 8daa280862
commit 4970663721
7 changed files with 110 additions and 69 deletions
+1 -1
View File
@@ -8,4 +8,4 @@ test:
deno test -A --no-check=remote
dev:
deno run -A --watch=www/static --no-check www/main.ts
deno run -A --watch=www/static,src/ --no-check www/main.ts
+58
View File
@@ -0,0 +1,58 @@
import { ComponentType, h, render } from "./deps.ts";
function createRootFragment(
parent: Element,
replaceNode: Node | Node[],
) {
replaceNode = ([] as Node[]).concat(replaceNode);
const s = replaceNode[replaceNode.length - 1].nextSibling;
function insert(c: Node, r: Node) {
parent.insertBefore(c, r || s);
}
// @ts-ignore this is fine
return parent.__k = {
nodeType: 1,
parentNode: parent,
firstChild: replaceNode[0],
childNodes: replaceNode,
insertBefore: insert,
appendChild: insert,
removeChild: function (c: Node) {
parent.removeChild(c);
},
};
}
const ISLAND_PROPS_COMPONENT = document.getElementById("__FRSH_ISLAND_PROPS");
// deno-lint-ignore no-explicit-any
const ISLAND_PROPS: any[] = JSON.parse(
ISLAND_PROPS_COMPONENT?.textContent ?? "[]",
);
export function revive(islands: Record<string, ComponentType>) {
function walk(node: Node | null) {
const tag = node!.nodeType === 8 &&
((node as Comment).data.match(/^\s*frsh-(.*)\s*$/) || [])[1];
if (tag) {
const children = [];
const parent = node!.parentNode;
while ((node = node!.nextSibling) && node.nodeType !== 8) {
children.push(node);
}
const [id, n] = tag.split(":");
render(
h(islands[id], ISLAND_PROPS[Number(n)]),
createRootFragment(
parent! as HTMLElement,
children,
// deno-lint-ignore no-explicit-any
) as any as HTMLElement,
);
}
const sib = node!.nextSibling;
if (sib) walk(sib as Comment);
const fc = node!.firstChild;
if (fc) walk(fc as Comment);
}
walk(document.body);
}
+6 -55
View File
@@ -1,4 +1,4 @@
import { denoPlugin, esbuild, esbuildTypes, toFileUrl } from "./deps.ts";
import { denoPlugin, esbuild, toFileUrl } from "./deps.ts";
import { Island } from "./types.ts";
let esbuildInitalized: boolean | Promise<void> = false;
@@ -28,10 +28,12 @@ export class Bundler {
}
async bundle() {
const entryPoints: Record<string, string> = {};
const entryPoints: Record<string, string> = {
"main": new URL("../../src/runtime/main.ts", import.meta.url).href,
};
for (const island of this.#islands) {
entryPoints[island.id] = `fresh:///${island.id}`;
entryPoints[`island-${island.id}`] = island.url;
}
const absWorkingDir = Deno.cwd();
@@ -48,7 +50,7 @@ export class Bundler {
absWorkingDir,
outfile: "",
platform: "neutral",
plugins: [freshPlugin(this.#islands), denoPlugin()],
plugins: [denoPlugin()],
splitting: true,
target: ["chrome90", "firefox88", "safari13"],
treeShaking: true,
@@ -96,54 +98,3 @@ export class Bundler {
// return this.#preloads.get(path) ?? [];
// }
}
function freshPlugin(islands: Island[]): esbuildTypes.Plugin {
const runtime = new URL("../../runtime.ts", import.meta.url);
const islandMap = new Map<string, Island>();
for (const island of islands) {
islandMap.set(`/${island.id}`, island);
}
return {
name: "fresh",
setup(build) {
build.onResolve({ filter: /fresh:\/\/.*/ }, function onResolve(
args: esbuildTypes.OnResolveArgs,
): esbuildTypes.OnResolveResult | null | undefined {
return ({
path: args.path,
namespace: "fresh",
});
});
build.onLoad(
{ filter: /.*/, namespace: "fresh" },
function onLoad(
args: esbuildTypes.OnLoadArgs,
): esbuildTypes.OnLoadResult | null | undefined {
const url = new URL(args.path);
const path = url.pathname;
const island = islandMap.get(path);
if (!island) return null;
const contents = `
import ${island.name} from "${island.url}";
import { h, render } from "${runtime.href}";
class ${island.name}Island extends HTMLElement {
constructor() {
super();
const props = JSON.parse(this.getAttribute("props"));
render(h(${island.name}, props), this);
}
}
customElements.define("frsh-${island.id}", ${island.name}Island);
`;
return { contents, loader: "js" };
},
);
},
};
}
+4
View File
@@ -5,6 +5,10 @@ export const BUILD_ID = Deno.env.get("DENO_DEPLOYMENT_ID") ||
crypto.randomUUID();
export const JS_PREFIX = `/js`;
export function bundleAssetUrl(path: string) {
return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`;
}
declare global {
interface Crypto {
randomUUID(): string;
+7 -2
View File
@@ -8,7 +8,12 @@ import {
} from "./deps.ts";
import { Manifest } from "./mod.ts";
import { Bundler } from "./bundle.ts";
import { ALIVE_URL, INTERNAL_PREFIX, REFRESH_JS_URL } from "./constants.ts";
import {
ALIVE_URL,
bundleAssetUrl,
INTERNAL_PREFIX,
REFRESH_JS_URL,
} from "./constants.ts";
import { JS_PREFIX } from "./constants.ts";
import { BUILD_ID } from "./constants.ts";
import {
@@ -294,7 +299,7 @@ export class ServerContext {
page: Page<Data> | UnknownPage | ErrorPage,
status: number,
) => {
const imports: string[] = [];
const imports: string[] = [bundleAssetUrl("/main.js")];
if (this.#dev) {
imports.push(REFRESH_JS_URL);
}
+33 -7
View File
@@ -18,7 +18,7 @@ import {
import { HEAD_CONTEXT } from "../runtime/head.ts";
import { CSP_CONTEXT, nonce, NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
import { ContentSecurityPolicy } from "../runtime/csp.ts";
import { BUILD_ID, INTERNAL_PREFIX, JS_PREFIX } from "./constants.ts";
import { bundleAssetUrl } from "./constants.ts";
export interface RenderOptions<Data> {
page: Page<Data> | UnknownPage | ErrorPage;
@@ -169,6 +169,9 @@ export function render<Data>(
// Clear the encountered vnodes
ENCOUNTERED_ISLANDS.clear();
// Clear the island props
ISLAND_PROPS = [];
let bodyHtml: string | null = null;
function render() {
@@ -193,6 +196,8 @@ export function render<Data>(
return [url, randomNonce] as const;
});
let islandImports = "";
let islandRegistry = "";
for (const island of ENCOUNTERED_ISLANDS) {
const randomNonce = crypto.randomUUID().replace(/-/g, "");
if (csp) {
@@ -201,10 +206,29 @@ export function render<Data>(
nonce(randomNonce),
];
}
const url = bundleAssetUrl(`/${island.id}.js`);
const url = bundleAssetUrl(`/island-${island.id}.js`);
imports.push([url, randomNonce] as const);
islandImports += `\nimport ${island.name} from "${url}";`;
islandRegistry += `\n ${island.id}: ${island.name},`;
}
const initCode = `import { revive } from "${
bundleAssetUrl("/main.js")
}";${islandImports}\nrevive({${islandRegistry}\n});`;
const randomNonce = crypto.randomUUID().replace(/-/g, "");
if (csp) {
csp.directives.scriptSrc = [
...csp.directives.scriptSrc ?? [],
nonce(randomNonce),
];
}
(bodyHtml as string) +=
`<script id="__FRSH_ISLAND_PROPS" type="application/json">${
JSON.stringify(ISLAND_PROPS)
}</script><script type="module" nonce="${randomNonce}">${initCode}</script>`;
const html = template({
bodyHtml,
headComponents,
@@ -217,10 +241,6 @@ export function render<Data>(
return [html, csp];
}
function bundleAssetUrl(path: string) {
return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`;
}
export interface TemplateOptions {
bodyHtml: string;
headComponents: ComponentChildren[];
@@ -258,6 +278,7 @@ export function template(opts: TemplateOptions): string {
// created.
const ISLANDS: Island[] = [];
const ENCOUNTERED_ISLANDS: Set<Island> = new Set([]);
let ISLAND_PROPS: unknown[] = [];
const originalHook = options.vnode;
let ignoreNext = false;
options.vnode = (vnode) => {
@@ -273,7 +294,12 @@ options.vnode = (vnode) => {
vnode.type = (props) => {
ignoreNext = true;
const child = h(originalType, props);
return h(`frsh-${island.id}`, { props: JSON.stringify(props) }, child);
ISLAND_PROPS.push(props);
return h(
`!--frsh-${island.id}:${ISLAND_PROPS.length - 1}--`,
null,
child,
);
};
}
}
+1 -4
View File
@@ -16,10 +16,7 @@ Deno.test("/ page prerender", async () => {
assertStringIncludes(body, "test.js");
assertStringIncludes(body, "<p>Hello!</p>");
assertStringIncludes(body, "<p>Viewing JIT render.</p>");
assertStringIncludes(
body,
`props="{&quot;message&quot;:&quot;Hello!&quot;}">`,
);
assertStringIncludes(body, `>[{"message":"Hello!"}]</script>`);
assertStringIncludes(
body,
`<meta name="description" content="Hello world!" />`,