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
+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);
});