From a6852fa58ff9ff5bee3d57c8eac8a01fea409fa1 Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Wed, 31 May 2023 10:12:07 +0200 Subject: [PATCH] feat: more advanced prop serializer for islands (#1224) This commit adds support for an advanced (de)serializer that is used for page state (island props and plugin state). This new serializer supports maintaining references (thus supporting circular objects, and multi-referenced objects). This is a pre-requisite for allowing to pass signals, JSX, Uint8Arrays, Date, and many other "advanced" values. --- docs/concepts/islands.md | 20 ++-- src/runtime/deserializer.ts | 36 ++++++ src/runtime/entrypoints/deserializer.ts | 1 + src/runtime/{ => entrypoints}/main.ts | 2 +- src/runtime/entrypoints/main_dev.ts | 2 + src/runtime/main_dev.ts | 2 - .../__snapshots__/serializer_test.ts.snap | 15 +++ src/server/bundle.ts | 11 +- src/server/context.ts | 4 +- src/server/render.ts | 107 +++++++++-------- src/server/serializer.ts | 111 ++++++++++++++++++ src/server/serializer_test.ts | 82 +++++++++++++ tests/deps.ts | 1 + tests/main_test.ts | 4 +- tests/plugin_test.ts | 4 +- www/islands/Counter.tsx | 10 +- 16 files changed, 335 insertions(+), 77 deletions(-) create mode 100644 src/runtime/deserializer.ts create mode 100644 src/runtime/entrypoints/deserializer.ts rename src/runtime/{ => entrypoints}/main.ts (97%) create mode 100644 src/runtime/entrypoints/main_dev.ts delete mode 100644 src/runtime/main_dev.ts create mode 100644 src/server/__snapshots__/serializer_test.ts.snap create mode 100644 src/server/serializer.ts create mode 100644 src/server/serializer_test.ts diff --git a/docs/concepts/islands.md b/docs/concepts/islands.md index e7e709ad..c9fa8109 100644 --- a/docs/concepts/islands.md +++ b/docs/concepts/islands.md @@ -31,19 +31,21 @@ export default function MyIsland() { An island can be used in a page like a regular Preact component. Fresh will take care of automatically re-hydrating the island on the client. -Passing props to islands is supported, but only if the props are JSON -serializable. This means that you can only pass: +Passing props to islands is supported, but only if the props are serializable. +Fresh can serialize the following types of values: - Primitive types `string`, `boolean`, and `null` - Most `number`s (`Infinity`, `-Infinity`, and `NaN` are silently converted to `null`, and `bigint`s are not supported) -- Plain objects with string keys and primitive, plain object, or array values -- Arrays containing primitives, plain objects, or other arrays +- Plain objects with string keys and serializable values +- Arrays containing serializable values -It is currently not possible to pass complex objects like `Date`, custom -classes, or functions. This means that it is not possible to pass `children` to -an island, as `children` are VNodes, which are not serializable. To find out -more about JSON serializable values, check out -[how `JSON.stringify()` works](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description). +Circular references are supported. If an object or signal is referenced multiple +times, it is only serialized once and the references are restored upon +deserialization. + +Passing complex objects like `Date`, custom classes, or functions is not +supported. This means that it is not possible to pass `children` to an island, +as `children` are VNodes, which are not serializable. It is also not supported to nest islands within other islands. diff --git a/src/runtime/deserializer.ts b/src/runtime/deserializer.ts new file mode 100644 index 00000000..8ad9f125 --- /dev/null +++ b/src/runtime/deserializer.ts @@ -0,0 +1,36 @@ +// Run `deno run -A npm:esbuild --minify src/runtime/deserializer.ts` to minify +// this file. It is embedded into src/server/deserializer_code.ts. + +export const KEY = "_f"; + +export function deserialize(str: string): unknown { + function reviver(this: unknown, _key: string, value: unknown): unknown { + if (typeof value === "object" && value && KEY in value) { + // deno-lint-ignore no-explicit-any + const v: any = value; + if (v[KEY] === "l") { + const val = v.v; + val[KEY] = v.k; + return val; + } + throw new Error(`Unknown key: ${v[KEY]}`); + } + return value; + } + + const { v, r } = JSON.parse(str, reviver); + const references = (r ?? []) as [string[], ...string[][]][]; + for (const [targetPath, ...refPaths] of references) { + const target = targetPath.reduce((o, k) => k === null ? o : o[k], v); + for (const refPath of refPaths) { + if (refPath.length === 0) throw new Error("Invalid reference"); + // set the reference to the target object + const parent = refPath.slice(0, -1).reduce( + (o, k) => k === null ? o : o[k], + v, + ); + parent[refPath.at(-1)!] = target; + } + } + return v; +} diff --git a/src/runtime/entrypoints/deserializer.ts b/src/runtime/entrypoints/deserializer.ts new file mode 100644 index 00000000..b031787c --- /dev/null +++ b/src/runtime/entrypoints/deserializer.ts @@ -0,0 +1 @@ +export { deserialize } from "../deserializer.ts"; diff --git a/src/runtime/main.ts b/src/runtime/entrypoints/main.ts similarity index 97% rename from src/runtime/main.ts rename to src/runtime/entrypoints/main.ts index d3451996..50e2c6bd 100644 --- a/src/runtime/main.ts +++ b/src/runtime/entrypoints/main.ts @@ -1,5 +1,5 @@ import { ComponentType, h, options, render } from "preact"; -import { assetHashingHook } from "./utils.ts"; +import { assetHashingHook } from "../utils.ts"; function createRootFragment( parent: Element, diff --git a/src/runtime/entrypoints/main_dev.ts b/src/runtime/entrypoints/main_dev.ts new file mode 100644 index 00000000..4e4f0c56 --- /dev/null +++ b/src/runtime/entrypoints/main_dev.ts @@ -0,0 +1,2 @@ +import "preact/debug"; +export * from "./main.ts"; diff --git a/src/runtime/main_dev.ts b/src/runtime/main_dev.ts deleted file mode 100644 index 2551dd5e..00000000 --- a/src/runtime/main_dev.ts +++ /dev/null @@ -1,2 +0,0 @@ -import "preact/debug"; -export { revive } from "./main.ts"; diff --git a/src/server/__snapshots__/serializer_test.ts.snap b/src/server/__snapshots__/serializer_test.ts.snap new file mode 100644 index 00000000..ef0ca2b8 --- /dev/null +++ b/src/server/__snapshots__/serializer_test.ts.snap @@ -0,0 +1,15 @@ +export const snapshot = {}; + +snapshot[`serializer - primitives & plain objects 1`] = `'{"v":{"a":1,"b":"2","c":true,"d":null,"f":[1,2,3],"g":{"a":1,"b":2,"c":3}}}'`; + +snapshot[`serializer - magic key 1`] = `'{"v":{"_f":"l","k":"f","v":{"a":1}}}'`; + +snapshot[`serializer - circular reference objects 1`] = `'{"v":{"a":1,"b":0},"r":[[[],["b"]]]}'`; + +snapshot[`serializer - circular reference nested objects 1`] = `'{"v":{"a":1,"b":{"c":2,"d":0}},"r":[[[],["b","d"]]]}'`; + +snapshot[`serializer - circular reference array 1`] = `'{"v":[1,2,3,0],"r":[[[],["3"]]]}'`; + +snapshot[`serializer - multiple reference 1`] = `'{"v":{"a":1,"b":{"c":2},"d":0},"r":[[["b"],["d"]]]}'`; + +snapshot[`serializer - multiple reference in magic key 1`] = `'{"v":{"literal":{"_f":"l","k":"x","v":{"inner":{"foo":"bar"}}},"inner":0},"r":[[["literal",null,"inner"],["inner"]]]}'`; diff --git a/src/server/bundle.ts b/src/server/bundle.ts index 3cbfc19c..9e096cde 100644 --- a/src/server/bundle.ts +++ b/src/server/bundle.ts @@ -1,4 +1,3 @@ -import { BuildOptions } from "https://deno.land/x/esbuild@v0.17.11/mod.js"; import { denoPlugin, esbuild, @@ -69,10 +68,12 @@ export class Bundler { } async bundle() { + const entrypointBase = "../../src/runtime/entrypoints"; const entryPoints: Record = { main: this.#dev - ? new URL("../../src/runtime/main_dev.ts", import.meta.url).href - : new URL("../../src/runtime/main.ts", import.meta.url).href, + ? import.meta.resolve(`${entrypointBase}/main_dev.ts`) + : import.meta.resolve(`${entrypointBase}/main.ts`), + deserializer: import.meta.resolve(`${entrypointBase}/deserializer.ts`), }; for (const island of this.#islands) { @@ -89,7 +90,7 @@ export class Bundler { await ensureEsbuildInitialized(); // In dev-mode we skip identifier minification to be able to show proper // component names in Preact DevTools instead of single characters. - const minifyOptions: Partial = this.#dev + const minifyOptions: Partial = this.#dev ? { minifyIdentifiers: false, minifySyntax: true, minifyWhitespace: true } : { minify: true }; const bundle = await esbuild.build({ @@ -116,8 +117,8 @@ export class Bundler { jsx: JSX_RUNTIME_MODE[this.#jsxConfig.jsx], jsxImportSource: this.#jsxConfig.jsxImportSource, }); - // const metafileOutputs = bundle.metafile!.outputs; + // const metafileOutputs = bundle.metafile!.outputs; // for (const path in metafileOutputs) { // const meta = metafileOutputs[path]; // const imports = meta.imports diff --git a/src/server/context.ts b/src/server/context.ts index 00b22063..9f59d05c 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -483,9 +483,7 @@ export class ServerContext { status: number, ) => { const imports: string[] = []; - if (this.#dev) { - imports.push(REFRESH_JS_URL); - } + if (this.#dev) imports.push(REFRESH_JS_URL); return ( req: Request, params: Record, diff --git a/src/server/render.ts b/src/server/render.ts index 347c7960..f46ec3ee 100644 --- a/src/server/render.ts +++ b/src/server/render.ts @@ -18,6 +18,7 @@ import { ContentSecurityPolicy } from "../runtime/csp.ts"; import { bundleAssetUrl } from "./constants.ts"; import { assetHashingHook } from "../runtime/utils.ts"; import { htmlEscapeJsonString } from "./htmlescape.ts"; +import { serialize } from "./serializer.ts"; export interface RenderOptions { route: Route | UnknownPage | ErrorPage; @@ -203,7 +204,8 @@ export async function render( bodyHtml = bodyHtml as string; - const imports = opts.imports.map((url) => { + const imports: [string, string][] = []; + function addImport(path: string): string { const randomNonce = crypto.randomUUID().replace(/-/g, ""); if (csp) { csp.directives.scriptSrc = [ @@ -211,76 +213,85 @@ export async function render( nonce(randomNonce), ]; } - return [url, randomNonce] as const; - }); + const url = bundleAssetUrl(path); + imports.push([url, randomNonce]); + return url; + } + + for (const url of opts.imports) { + const randomNonce = crypto.randomUUID().replace(/-/g, ""); + if (csp) { + csp.directives.scriptSrc = [ + ...csp.directives.scriptSrc ?? [], + nonce(randomNonce), + ]; + } + imports.push([url, randomNonce]); + } 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 ?? "[[],[]]");`; + const pluginScripts: [string, string, number][] = []; 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}]);`; + pluginScripts.push([plugin.name, hydrate.entrypoint, i]); } styleTags.splice(styleTags.length, 0, ...res.styles ?? []); } + // The inline script that will hydrate the page. + let script = ""; + + // Serialize the state into the `; + + if (res.requiresDeserializer) { + const url = addImport("/deserializer.js"); + script += `import { deserialize } from "${url}";`; + } + script += `const ST = document.getElementById("__FRSH_STATE").textContent;`; + script += `const STATE = `; + if (res.requiresDeserializer) { + script += `deserialize(ST);`; + } else { + script += `JSON.parse(ST).v;`; + } + } + + // Then it imports all plugin scripts and executes them (with their respective + // state). + for (const [pluginName, entrypoint, i] of pluginScripts) { + const url = addImport(`/plugin-${pluginName}-${entrypoint}.js`); + script += `import p${i} from "${url}";p${i}(STATE[1][${i}]);`; + } + + // Finally, it loads all island scripts and hydrates the islands using the + // reviver from the "main" script. if (ENCOUNTERED_ISLANDS.size > 0) { // Load the main.js script - { - const randomNonce = crypto.randomUUID().replace(/-/g, ""); - if (csp) { - csp.directives.scriptSrc = [ - ...csp.directives.scriptSrc ?? [], - nonce(randomNonce), - ]; - } - const url = bundleAssetUrl("/main.js"); - imports.push([url, randomNonce] as const); - } - - script += `import { revive } from "${bundleAssetUrl("/main.js")}";`; + const url = addImport("/main.js"); + script += `import { revive } from "${url}";`; // Prepare the inline script that loads and revives the islands let islandRegistry = ""; for (const island of ENCOUNTERED_ISLANDS) { - const randomNonce = crypto.randomUUID().replace(/-/g, ""); - if (csp) { - csp.directives.scriptSrc = [ - ...csp.directives.scriptSrc ?? [], - nonce(randomNonce), - ]; - } - const url = bundleAssetUrl(`/island-${island.id}.js`); - imports.push([url, randomNonce] as const); + const url = addImport(`/island-${island.id}.js`); script += `import ${island.name} from "${url}";`; islandRegistry += `${island.id}:${island.name},`; } script += `revive({${islandRegistry}}, STATE[0]);`; } - if (state[0].length > 0 || state[1].length > 0) { - // Append state to the body - bodyHtml += ``; - - // Append the inline script to the body + // Append the inline script. + if (script !== "") { const randomNonce = crypto.randomUUID().replace(/-/g, ""); if (csp) { csp.directives.scriptSrc = [ diff --git a/src/server/serializer.ts b/src/server/serializer.ts new file mode 100644 index 00000000..6e7058b0 --- /dev/null +++ b/src/server/serializer.ts @@ -0,0 +1,111 @@ +/** + * This module contains a serializer for island props. The serializer is capable + * of serializing the following: + * + * - `null` + * - `boolean` + * - `number` + * - `string` + * - `array` + * - `object` (no prototypes) + * + * Circular references are supported and objects with the same reference are + * serialized only once. + * + * The corresponding deserializer is in `src/runtime/deserializer.ts`. + */ +import { KEY } from "../runtime/deserializer.ts"; + +interface SerializeResult { + /** The string serialization. */ + serialized: string; + /** If the deserializer is required to deserialize this string. If this is + * `false` the serialized string can be deserialized with `JSON.parse`. */ + requiresDeserializer: boolean; +} + +export function serialize(data: unknown): SerializeResult { + let requiresDeserializer = false; + const seen = new Map(); + const references = new Map<(string | null)[], (string | null)[][]>(); + + const keyStack: (string | null)[] = []; + const parentStack: unknown[] = []; + + let earlyReturn = false; + + const toSerialize = { + v: data, + get r() { + earlyReturn = true; + if (references.size > 0) { + const refs = []; + for (const [targetPath, refPaths] of references) { + refs.push([targetPath, ...refPaths]); + } + return refs; + } + return undefined; + }, + }; + + function replacer( + this: unknown, + key: string | null, + value: unknown, + ): unknown { + if (value === toSerialize || earlyReturn) { + return value; + } + + // For some object types, the path in the object graph from root is not the + // same between the serialized representation, and deserialized objects. For + // these cases, we have to change the contents of the key stack to match the + // deserialized object. + if (typeof this === "object" && this !== null && KEY in this) { + if (this[KEY] === "l" && key === "v") key = null; + } + + if (this !== toSerialize) { + const parentIndex = parentStack.indexOf(this); + parentStack.splice(parentIndex + 1); + keyStack.splice(parentIndex); + keyStack.push(key); + // the parent is pushed before return + } + + if (typeof value === "object" && value !== null) { + const path = seen.get(value); + const currentPath = [...keyStack]; + if (path !== undefined) { + requiresDeserializer = true; + const referenceArr = references.get(path); + if (referenceArr === undefined) { + references.set(path, [currentPath]); + } else { + referenceArr.push(currentPath); + } + return 0; + } else { + seen.set(value, currentPath); + } + } + + if (typeof value === "object" && value && KEY in value) { + requiresDeserializer = true; + // deno-lint-ignore no-explicit-any + const v: any = { ...value }; + const k = v[KEY]; + delete v[KEY]; + const res = { [KEY]: "l", k, v }; + parentStack.push(res); + return res; + } else { + parentStack.push(value); + return value; + } + } + + const serialized = JSON.stringify(toSerialize, replacer); + return { serialized, requiresDeserializer }; +} diff --git a/src/server/serializer_test.ts b/src/server/serializer_test.ts new file mode 100644 index 00000000..bf735e6d --- /dev/null +++ b/src/server/serializer_test.ts @@ -0,0 +1,82 @@ +// deno-lint-ignore-file no-explicit-any + +import { serialize } from "./serializer.ts"; +import { assert, assertEquals, assertSnapshot } from "../../tests/deps.ts"; +import { deserialize, KEY } from "../runtime/deserializer.ts"; + +Deno.test("serializer - primitives & plain objects", async (t) => { + const data = { + a: 1, + b: "2", + c: true, + d: null, + f: [1, 2, 3], + g: { a: 1, b: 2, c: 3 }, + }; + const res = serialize(data); + assert(!res.requiresDeserializer); + await assertSnapshot(t, res.serialized); + const deserialized = deserialize(res.serialized); + assertEquals(deserialized, data); +}); + +Deno.test("serializer - magic key", async (t) => { + const data = { [KEY]: "f", a: 1 }; + const res = serialize(data); + assert(res.requiresDeserializer); + await assertSnapshot(t, res.serialized); + const deserialized = deserialize(res.serialized); + assertEquals(deserialized, data); +}); + +Deno.test("serializer - circular reference objects", async (t) => { + const data: any = { a: 1 }; + data.b = data; + const res = serialize(data); + assert(res.requiresDeserializer); + await assertSnapshot(t, res.serialized); + const deserialized = deserialize(res.serialized); + assertEquals(deserialized, data); +}); + +Deno.test("serializer - circular reference nested objects", async (t) => { + const data: any = { a: 1, b: { c: 2 } }; + data.b.d = data; + const res = serialize(data); + assert(res.requiresDeserializer); + await assertSnapshot(t, res.serialized); + const deserialized = deserialize(res.serialized); + assertEquals(deserialized, data); +}); + +Deno.test("serializer - circular reference array", async (t) => { + const data: any = [1, 2, 3]; + data.push(data); + const res = serialize(data); + assert(res.requiresDeserializer); + await assertSnapshot(t, res.serialized); + const deserialized: any = deserialize(res.serialized); + assertEquals(deserialized, data); + assertEquals(deserialized.length, 4); +}); + +Deno.test("serializer - multiple reference", async (t) => { + const data: any = { a: 1, b: { c: 2 } }; + data.d = data.b; + const res = serialize(data); + assert(res.requiresDeserializer); + await assertSnapshot(t, res.serialized); + const deserialized = deserialize(res.serialized); + assertEquals(deserialized, data); +}); + +Deno.test("serializer - multiple reference in magic key", async (t) => { + const inner = { foo: "bar" }; + const literal: any = { [KEY]: "x", inner }; + const data = { literal, inner }; + const res = serialize(data); + assert(res.requiresDeserializer); + await assertSnapshot(t, res.serialized); + const deserialized: any = deserialize(res.serialized); + assertEquals(deserialized, data); +}); diff --git a/tests/deps.ts b/tests/deps.ts index c0903d7a..74529efd 100644 --- a/tests/deps.ts +++ b/tests/deps.ts @@ -9,6 +9,7 @@ export { assertEquals, assertStringIncludes, } from "https://deno.land/std@0.189.0/testing/asserts.ts"; +export { assertSnapshot } from "https://deno.land/std@0.189.0/testing/snapshot.ts"; export { TextLineStream, } from "https://deno.land/std@0.189.0/streams/text_line_stream.ts"; diff --git a/tests/main_test.ts b/tests/main_test.ts index 36de5650..e823997f 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -39,7 +39,7 @@ Deno.test("/ page prerender", async () => { assertStringIncludes(body, "test.js"); assertStringIncludes(body, "

Hello!

"); assertStringIncludes(body, "

Viewing JIT render.

"); - assertStringIncludes(body, `>[[{"message":"Hello!"}],[]]`); + assertStringIncludes(body, `>{"v":[[{"message":"Hello!"}],[]]}`); assertStringIncludes( body, ``, @@ -646,7 +646,7 @@ Deno.test("experimental Deno.serve", { assertStringIncludes(body, "test.js"); assertStringIncludes(body, "

Hello!

"); assertStringIncludes(body, "

Viewing JIT render.

"); - assertStringIncludes(body, `>[[{"message":"Hello!"}],[]]`); + assertStringIncludes(body, `>{"v":[[{"message":"Hello!"}],[]]}`); assertStringIncludes( body, ``, diff --git a/tests/plugin_test.ts b/tests/plugin_test.ts index 0f1f067e..a1ab0d60 100644 --- a/tests/plugin_test.ts +++ b/tests/plugin_test.ts @@ -33,7 +33,7 @@ Deno.test("/static page prerender", async () => { assertEquals(resp.status, Status.OK); const body = await resp.text(); assertStringIncludes(body, ''); - assert(!body.includes(`>[[],[]]`)); + assert(!body.includes(`>{"v":[[],[]]}`)); assert(!body.includes(`import`)); }); @@ -46,7 +46,7 @@ Deno.test("/with-island prerender", async () => { body, '', ); - assertStringIncludes(body, `>[[{}],["JS injected!"]]`); + assertStringIncludes(body, `>{"v":[[{}],["JS injected!"]]}`); assertStringIncludes(body, `/plugin-js-inject-main.js"`); }); diff --git a/www/islands/Counter.tsx b/www/islands/Counter.tsx index 449bb046..55cea51e 100644 --- a/www/islands/Counter.tsx +++ b/www/islands/Counter.tsx @@ -1,4 +1,4 @@ -import { useState } from "preact/hooks"; +import { useSignal } from "@preact/signals"; import { IS_BROWSER } from "$fresh/runtime.ts"; import { RoundedButton } from "../components/Button.tsx"; import { IconMinus, IconPlus } from "../components/Icons.tsx"; @@ -8,20 +8,20 @@ interface CounterProps { } export default function Counter(props: CounterProps) { - const [count, setCount] = useState(props.start); + const count = useSignal(props.start); return (
setCount(count - 1)} - disabled={!IS_BROWSER || count <= 0} + onClick={() => count.value -= 1} + disabled={!IS_BROWSER || count.value <= 0} >
{count}
setCount(count + 1)} + onClick={() => count.value += 1} disabled={!IS_BROWSER} >