refactor: improved reviving of islands (#100)
This commit is contained in:
@@ -8,4 +8,4 @@ test:
|
|||||||
deno test -A --no-check=remote
|
deno test -A --no-check=remote
|
||||||
|
|
||||||
dev:
|
dev:
|
||||||
deno run -A --watch=www/static --no-check www/main.ts
|
deno run -A --watch=www/static,src/ --no-check www/main.ts
|
||||||
@@ -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
@@ -1,4 +1,4 @@
|
|||||||
import { denoPlugin, esbuild, esbuildTypes, toFileUrl } from "./deps.ts";
|
import { denoPlugin, esbuild, toFileUrl } from "./deps.ts";
|
||||||
import { Island } from "./types.ts";
|
import { Island } from "./types.ts";
|
||||||
|
|
||||||
let esbuildInitalized: boolean | Promise<void> = false;
|
let esbuildInitalized: boolean | Promise<void> = false;
|
||||||
@@ -28,10 +28,12 @@ export class Bundler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async bundle() {
|
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) {
|
for (const island of this.#islands) {
|
||||||
entryPoints[island.id] = `fresh:///${island.id}`;
|
entryPoints[`island-${island.id}`] = island.url;
|
||||||
}
|
}
|
||||||
|
|
||||||
const absWorkingDir = Deno.cwd();
|
const absWorkingDir = Deno.cwd();
|
||||||
@@ -48,7 +50,7 @@ export class Bundler {
|
|||||||
absWorkingDir,
|
absWorkingDir,
|
||||||
outfile: "",
|
outfile: "",
|
||||||
platform: "neutral",
|
platform: "neutral",
|
||||||
plugins: [freshPlugin(this.#islands), denoPlugin()],
|
plugins: [denoPlugin()],
|
||||||
splitting: true,
|
splitting: true,
|
||||||
target: ["chrome90", "firefox88", "safari13"],
|
target: ["chrome90", "firefox88", "safari13"],
|
||||||
treeShaking: true,
|
treeShaking: true,
|
||||||
@@ -96,54 +98,3 @@ export class Bundler {
|
|||||||
// return this.#preloads.get(path) ?? [];
|
// 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" };
|
|
||||||
},
|
|
||||||
);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ export const BUILD_ID = Deno.env.get("DENO_DEPLOYMENT_ID") ||
|
|||||||
crypto.randomUUID();
|
crypto.randomUUID();
|
||||||
export const JS_PREFIX = `/js`;
|
export const JS_PREFIX = `/js`;
|
||||||
|
|
||||||
|
export function bundleAssetUrl(path: string) {
|
||||||
|
return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`;
|
||||||
|
}
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
interface Crypto {
|
interface Crypto {
|
||||||
randomUUID(): string;
|
randomUUID(): string;
|
||||||
|
|||||||
@@ -8,7 +8,12 @@ import {
|
|||||||
} from "./deps.ts";
|
} from "./deps.ts";
|
||||||
import { Manifest } from "./mod.ts";
|
import { Manifest } from "./mod.ts";
|
||||||
import { Bundler } from "./bundle.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 { JS_PREFIX } from "./constants.ts";
|
||||||
import { BUILD_ID } from "./constants.ts";
|
import { BUILD_ID } from "./constants.ts";
|
||||||
import {
|
import {
|
||||||
@@ -294,7 +299,7 @@ export class ServerContext {
|
|||||||
page: Page<Data> | UnknownPage | ErrorPage,
|
page: Page<Data> | UnknownPage | ErrorPage,
|
||||||
status: number,
|
status: number,
|
||||||
) => {
|
) => {
|
||||||
const imports: string[] = [];
|
const imports: string[] = [bundleAssetUrl("/main.js")];
|
||||||
if (this.#dev) {
|
if (this.#dev) {
|
||||||
imports.push(REFRESH_JS_URL);
|
imports.push(REFRESH_JS_URL);
|
||||||
}
|
}
|
||||||
|
|||||||
+33
-7
@@ -18,7 +18,7 @@ import {
|
|||||||
import { HEAD_CONTEXT } from "../runtime/head.ts";
|
import { HEAD_CONTEXT } from "../runtime/head.ts";
|
||||||
import { CSP_CONTEXT, nonce, NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
|
import { CSP_CONTEXT, nonce, NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
|
||||||
import { ContentSecurityPolicy } 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> {
|
export interface RenderOptions<Data> {
|
||||||
page: Page<Data> | UnknownPage | ErrorPage;
|
page: Page<Data> | UnknownPage | ErrorPage;
|
||||||
@@ -169,6 +169,9 @@ export function render<Data>(
|
|||||||
// Clear the encountered vnodes
|
// Clear the encountered vnodes
|
||||||
ENCOUNTERED_ISLANDS.clear();
|
ENCOUNTERED_ISLANDS.clear();
|
||||||
|
|
||||||
|
// Clear the island props
|
||||||
|
ISLAND_PROPS = [];
|
||||||
|
|
||||||
let bodyHtml: string | null = null;
|
let bodyHtml: string | null = null;
|
||||||
|
|
||||||
function render() {
|
function render() {
|
||||||
@@ -193,6 +196,8 @@ export function render<Data>(
|
|||||||
return [url, randomNonce] as const;
|
return [url, randomNonce] as const;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let islandImports = "";
|
||||||
|
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, "");
|
||||||
if (csp) {
|
if (csp) {
|
||||||
@@ -201,10 +206,29 @@ export function render<Data>(
|
|||||||
nonce(randomNonce),
|
nonce(randomNonce),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
const url = bundleAssetUrl(`/${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}";`;
|
||||||
|
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({
|
const html = template({
|
||||||
bodyHtml,
|
bodyHtml,
|
||||||
headComponents,
|
headComponents,
|
||||||
@@ -217,10 +241,6 @@ export function render<Data>(
|
|||||||
return [html, csp];
|
return [html, csp];
|
||||||
}
|
}
|
||||||
|
|
||||||
function bundleAssetUrl(path: string) {
|
|
||||||
return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TemplateOptions {
|
export interface TemplateOptions {
|
||||||
bodyHtml: string;
|
bodyHtml: string;
|
||||||
headComponents: ComponentChildren[];
|
headComponents: ComponentChildren[];
|
||||||
@@ -258,6 +278,7 @@ export function template(opts: TemplateOptions): string {
|
|||||||
// created.
|
// created.
|
||||||
const ISLANDS: Island[] = [];
|
const ISLANDS: Island[] = [];
|
||||||
const ENCOUNTERED_ISLANDS: Set<Island> = new Set([]);
|
const ENCOUNTERED_ISLANDS: Set<Island> = new Set([]);
|
||||||
|
let ISLAND_PROPS: unknown[] = [];
|
||||||
const originalHook = options.vnode;
|
const originalHook = options.vnode;
|
||||||
let ignoreNext = false;
|
let ignoreNext = false;
|
||||||
options.vnode = (vnode) => {
|
options.vnode = (vnode) => {
|
||||||
@@ -273,7 +294,12 @@ options.vnode = (vnode) => {
|
|||||||
vnode.type = (props) => {
|
vnode.type = (props) => {
|
||||||
ignoreNext = true;
|
ignoreNext = true;
|
||||||
const child = h(originalType, props);
|
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
@@ -16,10 +16,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(
|
assertStringIncludes(body, `>[{"message":"Hello!"}]</script>`);
|
||||||
body,
|
|
||||||
`props="{"message":"Hello!"}">`,
|
|
||||||
);
|
|
||||||
assertStringIncludes(
|
assertStringIncludes(
|
||||||
body,
|
body,
|
||||||
`<meta name="description" content="Hello world!" />`,
|
`<meta name="description" content="Hello world!" />`,
|
||||||
|
|||||||
Reference in New Issue
Block a user