feat: serialize bigints for islands (#1317)
This commit is contained in:
@@ -34,9 +34,9 @@ care of automatically re-hydrating the island on the client.
|
||||
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`
|
||||
- Primitive types `string`, `boolean`, `bigint`, and `null`
|
||||
- Most `number`s (`Infinity`, `-Infinity`, and `NaN` are silently converted to
|
||||
`null`, and `bigint`s are not supported)
|
||||
`null`)
|
||||
- Plain objects with string keys and serializable values
|
||||
- Arrays containing serializable values
|
||||
- Uint8Array
|
||||
|
||||
@@ -29,6 +29,9 @@ export function deserialize(
|
||||
if (v[KEY] === "s") {
|
||||
return signal!(v.v);
|
||||
}
|
||||
if (v[KEY] === "b") {
|
||||
return BigInt(v.d);
|
||||
}
|
||||
if (v[KEY] === "u8a") {
|
||||
return b64decode(v.d);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ 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 - bigint 1`] = `'{"v":{"a":{"_f":"b","d":"999999999999999999"}}}'`;
|
||||
|
||||
snapshot[`serializer - Uint8Array 1`] = `'{"v":{"a":{"_f":"u8a","d":"AQID"}}}'`;
|
||||
|
||||
snapshot[`serializer - signals 1`] = `'{"v":{"a":1,"b":{"_f":"s","v":2}}}'`;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
* - `null`
|
||||
* - `boolean`
|
||||
* - `number`
|
||||
* - `bigint`
|
||||
* - `string`
|
||||
* - `array`
|
||||
* - `object` (no prototypes)
|
||||
@@ -134,6 +135,11 @@ export function serialize(data: unknown): SerializeResult {
|
||||
const res = { [KEY]: "s", v: value.peek() };
|
||||
parentStack.push(res);
|
||||
return res;
|
||||
} else if (typeof value === "bigint") {
|
||||
requiresDeserializer = true;
|
||||
const res = { [KEY]: "b", d: value.toString() };
|
||||
parentStack.push(res);
|
||||
return res;
|
||||
} else if (value instanceof Uint8Array) {
|
||||
requiresDeserializer = true;
|
||||
const res = { [KEY]: "u8a", d: b64encode(value) };
|
||||
|
||||
@@ -22,6 +22,16 @@ Deno.test("serializer - primitives & plain objects", async (t) => {
|
||||
assertEquals(deserialized, data);
|
||||
});
|
||||
|
||||
Deno.test("serializer - bigint", async (t) => {
|
||||
const data = { a: 999999999999999999n };
|
||||
const res = serialize(data);
|
||||
assert(res.requiresDeserializer);
|
||||
assert(!res.hasSignals);
|
||||
await assertSnapshot(t, res.serialized);
|
||||
const deserialized = deserialize(res.serialized);
|
||||
assertEquals(deserialized, data);
|
||||
});
|
||||
|
||||
Deno.test("serializer - Uint8Array", async (t) => {
|
||||
const data = { a: new Uint8Array([1, 2, 3]) };
|
||||
const res = serialize(data);
|
||||
|
||||
Reference in New Issue
Block a user