Skip to content

Commit 4c803e5

Browse files
authored
feat: custom seroval plugins via serialization.plugins (#2250)
1 parent d8f1ea8 commit 4c803e5

15 files changed

Lines changed: 366 additions & 6 deletions
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
"@solidjs/start": minor
3+
---
4+
5+
Add `serialization.plugins` to configure custom Seroval plugins for server functions.
6+
7+
Values Seroval has no built-in support for (Mongo's `ObjectId`, Prisma's `Decimal`, `Temporal`, and other custom classes) previously threw when returned from or passed to a server function. Point the new option at a module whose default export is an array of plugins:
8+
9+
```ts
10+
// vite.config.ts
11+
solidStart({
12+
serialization: {
13+
plugins: "src/seroval-plugins.ts",
14+
},
15+
});
16+
```
17+
18+
```ts
19+
// src/seroval-plugins.ts
20+
import { createPlugin } from "@solidjs/start/serialization";
21+
```
22+
23+
The module is bundled into both the client and the server so both ends of a server function agree on the format, so it must not import server-only code. SolidStart's built-in plugins keep precedence. Only server-function and action payloads are affected; the SSR hydration payload is serialized by `solid-js/web`.
24+
25+
Also adds a `@solidjs/start/serialization` entrypoint re-exporting Seroval's `createPlugin`, `OpaqueReference`, and plugin types, so plugin authors stay on the same Seroval version SolidStart serializes with.

‎apps/tests/src/e2e/server-function.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,19 @@ test.describe("server-function", () => {
7373
await expect(page.locator("#server-fn-test")).toContainText('{"result":true}');
7474
});
7575

76+
/**
77+
* A custom Seroval plugin registered through `serialization.plugins` must
78+
* apply to both the request and the response payload, so a class Seroval has
79+
* no built-in support for survives the round trip with its prototype intact.
80+
* https://github.com/solidjs/solid-start/issues/1474
81+
*/
82+
test("should round-trip a custom class through a custom seroval plugin", async ({ page }) => {
83+
await page.goto("http://localhost:3000/server-function-custom-class");
84+
await expect(page.locator("#server-fn-test")).toContainText(
85+
'{"receivedInstance":true,"receivedHex":"507f191e810c19729de860ea","returnedInstance":true,"returnedHex":"507f1f77bcf86cd799439011"}',
86+
);
87+
});
88+
7689
test("should build with a server function w/ form data", async ({ page }) => {
7790
await page.goto("http://localhost:3000/server-function-form-data");
7891
await expect(page.locator("#server-fn-test")).toContainText('{"result":true}');
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { createEffect, createSignal } from "solid-js";
2+
import { ObjectId } from "../utils/object-id.ts";
3+
4+
/**
5+
* Exercises `serialization.plugins`: a class Seroval has no built-in support
6+
* for has to survive both directions of a server function call.
7+
*
8+
* @see https://github.com/solidjs/solid-start/issues/1474
9+
*/
10+
async function echoObjectId(id: ObjectId) {
11+
"use server";
12+
13+
return {
14+
receivedInstance: id instanceof ObjectId,
15+
receivedHex: id.toHexString(),
16+
returned: new ObjectId("507f1f77bcf86cd799439011"),
17+
};
18+
}
19+
20+
export default function App() {
21+
const [output, setOutput] = createSignal<Record<string, unknown>>({});
22+
23+
createEffect(async () => {
24+
const result = await echoObjectId(new ObjectId("507f191e810c19729de860ea"));
25+
26+
setOutput({
27+
receivedInstance: result.receivedInstance,
28+
receivedHex: result.receivedHex,
29+
returnedInstance: result.returned instanceof ObjectId,
30+
returnedHex: result.returned.toHexString(),
31+
});
32+
});
33+
34+
return (
35+
<main>
36+
<span id="server-fn-test">{JSON.stringify(output())}</span>
37+
</main>
38+
);
39+
}

‎apps/tests/src/seroval-plugins.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { createPlugin } from "@solidjs/start/serialization";
2+
import { ObjectId } from "./utils/object-id.ts";
3+
4+
/**
5+
* Bundled into both the client and the server via `serialization.plugins`, so
6+
* this module must not import server-only code.
7+
*
8+
* `deserialize` is what rebuilds the value under the default `"json"`
9+
* serialization mode. `serialize` is only used by `mode: "js"`, where the
10+
* payload is evaluated on the client and can therefore reference globals only,
11+
* which is why it reaches for `globalThis` rather than the imported class.
12+
*/
13+
const ObjectIdPlugin = createPlugin<ObjectId, { hex: any }>({
14+
tag: "tests/ObjectId",
15+
test: value => value instanceof ObjectId,
16+
parse: {
17+
sync: (value, ctx) => ({ hex: ctx.parse(value.hex) }),
18+
async: async (value, ctx) => ({ hex: await ctx.parse(value.hex) }),
19+
stream: (value, ctx) => ({ hex: ctx.parse(value.hex) }),
20+
},
21+
serialize: (node, ctx) => `globalThis.ObjectId(${ctx.serialize(node.hex)})`,
22+
deserialize: (node, ctx) => new ObjectId(ctx.deserialize(node.hex) as string),
23+
});
24+
25+
(globalThis as any).ObjectId = (hex: string) => new ObjectId(hex);
26+
27+
export default [ObjectIdPlugin];

‎apps/tests/src/utils/object-id.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/**
2+
* Stands in for a custom class that Seroval has no built-in support for, such
3+
* as Mongo's `ObjectId` or Prisma's `Decimal`. Serializing one of these across
4+
* a server function boundary requires a custom Seroval plugin.
5+
*
6+
* @see https://github.com/solidjs/solid-start/issues/1474
7+
*/
8+
export class ObjectId {
9+
constructor(readonly hex: string) {}
10+
11+
toHexString() {
12+
return this.hex;
13+
}
14+
}

‎apps/tests/vite.config.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ export default defineConfig({
88
},
99
plugins: [
1010
solidStart({
11+
serialization: {
12+
plugins: "src/seroval-plugins.ts",
13+
},
1114
env: {
1215
server: {
1316
load() {

‎packages/start/package.json‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@
2424
"./http": "./src/http/index.ts",
2525
"./env": "./env.d.ts",
2626
"./fns/server": "./src/fns/server.ts",
27-
"./fns/client": "./src/fns/client.ts"
27+
"./fns/client": "./src/fns/client.ts",
28+
"./serialization": "./src/fns/plugins.ts"
2829
},
2930
"publishConfig": {
3031
"exports": {
@@ -39,7 +40,8 @@
3940
"./http": "./dist/http/index.js",
4041
"./env": "./env.d.ts",
4142
"./fns/server": "./dist/fns/server.js",
42-
"./fns/client": "./dist/fns/client.js"
43+
"./fns/client": "./dist/fns/client.js",
44+
"./serialization": "./dist/fns/plugins.js"
4345
},
4446
"access": "public"
4547
},

‎packages/start/src/config/constants.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ export const VIRTUAL_MODULES = {
77
getClientManifest: "solid-start:get-client-manifest",
88
getManifest: "solid-start:get-manifest",
99
middleware: "solid-start:middleware",
10+
serovalPlugins: "solid-start:seroval-plugins",
1011
serverFnManifest: "solid-start:server-fn-manifest",
1112
clientEntry: "solid-start:client-entry",
1213
serverEntry: "solid-start:server-entry",

‎packages/start/src/config/index.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,30 @@ export interface SolidStartOptions {
107107
* @default "json"
108108
*/
109109
mode?: "js" | "json";
110+
111+
/**
112+
* Path to a module whose default export is an array of custom Seroval
113+
* plugins, used to serialize values Seroval doesn't understand natively
114+
* (ORM id types, decimals, `Temporal`, and other custom classes).
115+
*
116+
* Build plugins with `createPlugin` from `seroval`. The module is bundled
117+
* into both the client and the server so that both ends of a server
118+
* function agree on the format, so it must not import server-only code.
119+
*
120+
* SolidStart's built-in plugins take precedence: Seroval uses the first
121+
* plugin whose `test()` passes, and these are appended after the built-ins.
122+
*
123+
* A plugin's `deserialize` rebuilds the value under {@link mode} `"json"`.
124+
* `serialize` is only used by `mode: "js"`, where the payload is evaluated
125+
* on the client and may therefore reference globals only, not the plugin
126+
* module's own imports.
127+
*
128+
* Only applies to server-function and action payloads. The SSR hydration
129+
* payload is serialized by `solid-js/web` and is unaffected.
130+
*
131+
* @example "src/seroval-plugins.ts"
132+
*/
133+
plugins?: string;
110134
};
111135

112136
/**

‎packages/start/src/config/manifest.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ export function manifest(start: SolidStartOptions): PluginOption {
3636
if (start.middleware) return await this.resolve(start.middleware);
3737
return `\0${VIRTUAL_MODULES.middleware}`;
3838
}
39+
if (id === VIRTUAL_MODULES.serovalPlugins) {
40+
const plugins = start.serialization?.plugins;
41+
if (plugins) return await this.resolve(plugins);
42+
return `\0${VIRTUAL_MODULES.serovalPlugins}`;
43+
}
3944
},
4045
async load(id) {
4146
if (id === `\0${VIRTUAL_MODULES.clientViteManifest}`) {
@@ -88,6 +93,7 @@ export function manifest(start: SolidStartOptions): PluginOption {
8893
}
8994
return `export const clientViteManifest = ${JSON.stringify(clientViteManifest)};`;
9095
} else if (id === `\0${VIRTUAL_MODULES.middleware}`) return "export default {};";
96+
else if (id === `\0${VIRTUAL_MODULES.serovalPlugins}`) return "export default [];";
9197
else if (id.startsWith("/@manifest")) {
9298
if (this.environment.mode !== "dev")
9399
throw new Error("@manifest queries are only allowed in dev");

0 commit comments

Comments
 (0)