diff --git a/makefile b/makefile index 1f976997..52bb2619 100644 --- a/makefile +++ b/makefile @@ -8,4 +8,4 @@ test: deno test -A --no-check=remote dev: - deno run -A --watch=www/static --no-check www/main.ts \ No newline at end of file + deno run -A --watch=www/static,src/ --no-check www/main.ts \ No newline at end of file diff --git a/src/runtime/main.ts b/src/runtime/main.ts new file mode 100644 index 00000000..ceb260d1 --- /dev/null +++ b/src/runtime/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) { + 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); +} diff --git a/src/server/bundle.ts b/src/server/bundle.ts index 02a01185..464a4315 100644 --- a/src/server/bundle.ts +++ b/src/server/bundle.ts @@ -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 = false; @@ -28,10 +28,12 @@ export class Bundler { } async bundle() { - const entryPoints: Record = {}; + const entryPoints: Record = { + "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(); - - 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" }; - }, - ); - }, - }; -} diff --git a/src/server/constants.ts b/src/server/constants.ts index b36b9c33..f009289e 100644 --- a/src/server/constants.ts +++ b/src/server/constants.ts @@ -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; diff --git a/src/server/context.ts b/src/server/context.ts index dc2e7096..78211ea9 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -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 | UnknownPage | ErrorPage, status: number, ) => { - const imports: string[] = []; + const imports: string[] = [bundleAssetUrl("/main.js")]; if (this.#dev) { imports.push(REFRESH_JS_URL); } diff --git a/src/server/render.tsx b/src/server/render.tsx index 4e09c796..17c487b5 100644 --- a/src/server/render.tsx +++ b/src/server/render.tsx @@ -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 { page: Page | UnknownPage | ErrorPage; @@ -169,6 +169,9 @@ export function render( // 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( 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( 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) += + ``; + const html = template({ bodyHtml, headComponents, @@ -217,10 +241,6 @@ export function render( 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 = 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, + ); }; } } diff --git a/tests/main_test.ts b/tests/main_test.ts index 646f1450..114031bb 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -16,10 +16,7 @@ Deno.test("/ page prerender", async () => { assertStringIncludes(body, "test.js"); assertStringIncludes(body, "

Hello!

"); assertStringIncludes(body, "

Viewing JIT render.

"); - assertStringIncludes( - body, - `props="{"message":"Hello!"}">`, - ); + assertStringIncludes(body, `>[{"message":"Hello!"}]`); assertStringIncludes( body, ``,