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.
This commit is contained in:
Luca Casonato
2023-05-31 10:12:07 +02:00
committed by GitHub
parent 060e2bb50d
commit a6852fa58f
16 changed files with 335 additions and 77 deletions
+11 -9
View File
@@ -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.
+36
View File
@@ -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;
}
+1
View File
@@ -0,0 +1 @@
export { deserialize } from "../deserializer.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,
+2
View File
@@ -0,0 +1,2 @@
import "preact/debug";
export * from "./main.ts";
-2
View File
@@ -1,2 +0,0 @@
import "preact/debug";
export { revive } from "./main.ts";
@@ -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"]]]}'`;
+6 -5
View File
@@ -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<string, string> = {
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<BuildOptions> = this.#dev
const minifyOptions: Partial<esbuildTypes.BuildOptions> = 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
+1 -3
View File
@@ -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<string, string>,
+59 -48
View File
@@ -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<Data> {
route: Route<Data> | UnknownPage | ErrorPage;
@@ -203,7 +204,8 @@ export async function render<Data>(
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<Data>(
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 <script id=__FRSH_STATE> tag and generate the
// inline script to deserialize it. This script starts by deserializing the
// state in the tag. This potentially requires importing @preact/signals.
if (state[0].length > 0 || state[1].length > 0) {
const res = serialize(state);
const escapedState = htmlEscapeJsonString(res.serialized);
bodyHtml +=
`<script id="__FRSH_STATE" type="application/json">${escapedState}</script>`;
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 += `<script id="__FRSH_STATE" type="application/json">${
htmlEscapeJsonString(JSON.stringify(state))
}</script>`;
// Append the inline script to the body
// Append the inline script.
if (script !== "") {
const randomNonce = crypto.randomUUID().replace(/-/g, "");
if (csp) {
csp.directives.scriptSrc = [
+111
View File
@@ -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<unknown, (string | null)[]>();
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 };
}
+82
View File
@@ -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);
});
+1
View File
@@ -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";
+2 -2
View File
@@ -39,7 +39,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, `>{"v":[[{"message":"Hello!"}],[]]}</script>`);
assertStringIncludes(
body,
`<meta name="description" content="Hello world!" />`,
@@ -646,7 +646,7 @@ Deno.test("experimental Deno.serve", {
assertStringIncludes(body, "test.js");
assertStringIncludes(body, "<p>Hello!</p>");
assertStringIncludes(body, "<p>Viewing JIT render.</p>");
assertStringIncludes(body, `>[[{"message":"Hello!"}],[]]</script>`);
assertStringIncludes(body, `>{"v":[[{"message":"Hello!"}],[]]}</script>`);
assertStringIncludes(
body,
`<meta name="description" content="Hello world!" />`,
+2 -2
View File
@@ -33,7 +33,7 @@ Deno.test("/static page prerender", async () => {
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(`>{"v":[[],[]]}</script>`));
assert(!body.includes(`import`));
});
@@ -46,7 +46,7 @@ Deno.test("/with-island prerender", async () => {
body,
'<style id="abc">body { color: red; } h1 { color: blue; }</style>',
);
assertStringIncludes(body, `>[[{}],["JS injected!"]]</script>`);
assertStringIncludes(body, `>{"v":[[{}],["JS injected!"]]}</script>`);
assertStringIncludes(body, `/plugin-js-inject-main.js"`);
});
+5 -5
View File
@@ -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 (
<div class="bg-gray-100 p-4 border border-gray-200 flex items-center justify-around">
<RoundedButton
title="Subtract 1"
onClick={() => setCount(count - 1)}
disabled={!IS_BROWSER || count <= 0}
onClick={() => count.value -= 1}
disabled={!IS_BROWSER || count.value <= 0}
>
<IconMinus />
</RoundedButton>
<div class="text-3xl tabular-nums">{count}</div>
<RoundedButton
title="Add 1"
onClick={() => setCount(count + 1)}
onClick={() => count.value += 1}
disabled={!IS_BROWSER}
>
<IconPlus />