Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
153c304
breaking: new wire format for stringify and parse
elliott-with-the-longest-name-on-github Dec 2, 2026
cb278ab
chore: split the tree-format changeset into one per change
elliott-with-the-longest-name-on-github Dec 2, 2026
f39b841
fix: reject a promise result that is a thenable, however it was written
elliott-with-the-longest-name-on-github Dec 2, 2026
4726b32
breaking: reducers only see objects; revivers are called once, with t…
elliott-with-the-longest-name-on-github Dec 2, 2026
ce7cc07
perf: mark values still being read in their slot instead of tracking …
elliott-with-the-longest-name-on-github Dec 2, 2026
2d9f25b
docs: boxes and views that refer to themselves are rejected
elliott-with-the-longest-name-on-github Dec 2, 2026
1e91d10
refactor: find a promise's path by walking again with the writer
elliott-with-the-longest-name-on-github Dec 2, 2026
041ac36
style: collapse a few single-statement blocks in parse and stringify
elliott-with-the-longest-name-on-github Dec 2, 2026
4506cf1
refactor: type the async-only state honestly instead of casting null
elliott-with-the-longest-name-on-github Dec 2, 2026
cb45a64
chore: explain why path_to_root may clear the writer's state
elliott-with-the-longest-name-on-github Dec 2, 2026
fbc8d1b
chore: clearer comments on numbering, references and inlined loops; o…
elliott-with-the-longest-name-on-github Dec 2, 2026
dbebe9c
chore: fix benchmark imports
elliott-with-the-longest-name-on-github Oct 8, 2026
fb27932
chore: add uneval benchmarks for plain rows
Nov 10, 2026
5cdbef2
chore: benchmark plain rows followed by a Map of every row
Nov 10, 2026
4c209c2
shorten labels so they fit the table printed by pnpm bench
Nov 10, 2026
0656237
drop two benchmarks that existing ones already cover
Nov 10, 2026
ff0c46b
chore: add parse benchmarks, and benchmarks for shared and custom values
elliott-with-the-longest-name-on-github Dec 2, 2026
d8a023b
chore: remove scratch files committed by mistake
elliott-with-the-longest-name-on-github Dec 2, 2026
2c6d263
chore: shorten a benchmark label to fit the table
elliott-with-the-longest-name-on-github Dec 2, 2026
4449f1c
perf: splice base64 text in after JSON.stringify instead of having it…
elliott-with-the-longest-name-on-github Dec 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/async-fail-fast.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'devalue': minor
---

feat: `stringifyAsync` rejects with the first failure it sees, without waiting for promises that come before it in the value
5 changes: 5 additions & 0 deletions .changeset/async-promises.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'devalue': major
---

breaking: a value written by `stringifyAsync` is parsed with a promise wherever it had one, where earlier versions put what the promise resolved to

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
breaking: a value written by `stringifyAsync` is parsed with a promise wherever it had one, where earlier versions put what the promise resolved to
breaking: `stringifyAsync` no longer elides promises

5 changes: 5 additions & 0 deletions .changeset/builtin-reviver-payloads.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'devalue': major
---

breaking: a reviver named after a built-in type such as `Map` or `Set` is given the whole of what it was written as, for example every key and value of a `Map`, instead of only the first
5 changes: 5 additions & 0 deletions .changeset/date-operations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'devalue': major
---

breaking: the `toISOString` and `fromISOString` operations are replaced by `timeOf(date)`, which returns the time in milliseconds, and `fromTime(time)`, which creates a Date from it
5 changes: 5 additions & 0 deletions .changeset/date-reviver-time.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'devalue': major
---

breaking: a reviver named `Date` is given the time in milliseconds (`NaN` for an invalid date) instead of an ISO string
5 changes: 5 additions & 0 deletions .changeset/reducers-objects-only.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'devalue': major
---

breaking: reducers passed to `stringify` and `stringifyAsync` are only called on objects and functions. Strings, numbers, booleans, BigInts, `null` and `undefined` are always written as themselves
5 changes: 5 additions & 0 deletions .changeset/references-option.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'devalue': minor
---

feat: add a `references: false` option to `parse`, `unflatten`, `stringify` and `stringifyAsync` that rules out repeated and cyclical references
5 changes: 5 additions & 0 deletions .changeset/regexp-reviver-flags.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'devalue': major
---

breaking: a reviver named `RegExp` is given `[source, flags]` instead of only the source
5 changes: 5 additions & 0 deletions .changeset/reread-properties.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'devalue': major
---

breaking: `stringify` and `stringifyAsync` can read a property of the value more than once
5 changes: 5 additions & 0 deletions .changeset/symbol-keys.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'devalue': major
---

breaking: `stringify` and `stringifyAsync` skip an object's symbol keys, as `JSON.stringify` does, instead of throwing `Cannot stringify POJOs with symbolic keys`. `uneval` still throws

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should just skip them in uneval too. Probably unlocks extra perf there as well

5 changes: 5 additions & 0 deletions .changeset/tree-format.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'devalue': major
---

breaking: `stringify` and `stringifyAsync` write a new format, which is faster to write and to parse and compresses better. Payloads written by earlier versions can no longer be parsed
5 changes: 5 additions & 0 deletions .changeset/two-stage-revivers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'devalue': major
---

breaking: a reviver is called once, with its whole payload. A custom value whose payload refers back to the value itself now throws `Invalid circular reference`, where before its reviver was called early with the payload so far and then again. For types whose values can contain themselves, pass a two-stage reviver, `{ create, fill }`: `create` makes the value before its payload is read, and `fill` is given the value and the whole payload
650 changes: 650 additions & 0 deletions FORMAT.md

Large diffs are not rendered by default.

67 changes: 57 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,17 +58,33 @@ import * as devalue from 'devalue';

let obj = { message: 'hello' };

let stringified = devalue.stringify(obj); // '[{"message":1},"hello"]'
let stringified = devalue.stringify(obj); // '{"message":"hello"}'
devalue.parse(stringified); // { message: 'hello' }

obj.self = obj;

stringified = devalue.stringify(obj); // '[{"message":1,"self":0},"hello"]'
stringified = devalue.stringify(obj); // '["$G",{"message":"hello","self":"$R0"}]'
devalue.parse(stringified); // { message: 'hello', self: [Circular] }
```

Use `stringify` and `parse` when evaluating JavaScript isn't an option (such as when sending untrusted data from client to server).

#### Parsing untrusted input

Because `parse` preserves repeated and cyclical references, a small payload can describe a value that is expensive for other code to work with. An array that is referenced a thousand times costs a few bytes each time in the payload, but code that copies or walks the parsed value — a schema validator, `JSON.stringify`, `structuredClone` — handles the whole array every time it is reached.

Therefore, when parsing untrusted input (for example, data from the client being sent back to the server), use the `references: false` option. It rejects any payload that contains a reference, so the result has no repeated or cyclical values and what `parse` builds is no larger than the payload describes, just like with `JSON.parse`. On the sending side, pass the same option to `stringify` or `stringifyAsync`. Repeated values are then written out in full each time, and cyclical values throw:

```js
// client
const serialized = devalue.stringify(data, undefined, { references: false });

// server
const value = devalue.parse(serialized, undefined, { references: false });
```

The option is also accepted by `unflatten`. Custom revivers and `operations` are not constrained by it: a reviver that returns something larger than its input, or the same object each time, is not covered, so avoid such revivers when parsing untrusted input. The declared length of a sparse array is not covered either.

### `stringifyAsync`

`stringifyAsync` is an async version of `stringify` that can handle promises:
Expand All @@ -82,10 +98,14 @@ let obj = {
};

let stringified = await devalue.stringifyAsync(obj);
devalue.parse(stringified); // { quick: 'data', slow: { ... } }

let data = devalue.parse(stringified); // { quick: 'data', slow: Promise }
await data.slow; // { ... }
```

Promises are awaited and their resolved values are serialized. The output format is identical to `stringify`, so `parse` and `unflatten` work unchanged.
A promise goes in and a promise comes out: wherever the value held a promise, the parsed value holds a promise for what it resolved to. `parse` and `unflatten` are still synchronous, and every promise they return has already been fulfilled. The same promise in two places comes back as one promise, a thenable comes back as a native promise, and a value with no promises in it is written exactly as `stringify` writes it.

`stringifyAsync` attaches to each promise as soon as it finds it, so one that rejects while another is still pending is not left unhandled. Promises inside what another promise resolved to are found when that promise settles. It rejects with the first failure it sees, whether that is a promise that rejects or a value that cannot be serialized. Everything that is not behind a promise is read straight away, and what a promise resolved to is read when it settles, so changing the value afterwards has no effect on the output.

### `unflatten`

Expand Down Expand Up @@ -136,7 +156,7 @@ const stringified = devalue.stringify(new Vector(30, 40), {
Vector: (value) => value instanceof Vector && [value.x, value.y]
});

console.log(stringified); // [["Vector",1],[2,3],30,40]
console.log(stringified); // ["$:Vector",[30,40]]

const vector = devalue.parse(stringified, {
Vector: ([x, y]) => new Vector(x, y)
Expand All @@ -145,7 +165,34 @@ const vector = devalue.parse(stringified, {
console.log(vector.magnitude()); // 50
```

If a function passed to `stringify` returns a truthy value, it's treated as a match.
If a function passed to `stringify` returns a truthy value, it's treated as a match. Reducers are only called on objects and functions, never on strings, numbers, booleans, BigInts, `null` or `undefined`.

A reviver is called once, with the whole payload, so a custom value that contains itself (directly or through other values) can't be revived by a plain function: `parse` throws `Invalid circular reference`. For those types, use a two-stage reviver. `create` makes the value before its payload is read, so anything inside the payload that refers back to it gets that value, and `fill` completes it:

```js
const node = devalue.parse(stringified, {
Node: {
create: () => new Node(),
fill: (node, payload) => {
node.name = payload.name;
node.next = payload.next;
}
}
});
```

A reviver named after a built-in type takes it over, and is given what that type was written as:

| Reviver | Is given |
| ---------------------------------------- | ------------------------------------------------------------------------------ |
| `Map` | `[key, value, key, value, ...]` |
| `Set` | `[value, ...]` |
| `null` (null-prototype objects) | a plain object with the same properties |
| `Uint8Array`, `DataView` and other views | the `ArrayBuffer`, or `[buffer, byteOffset, length]` for a view of part of one |
| `Date` | the time in milliseconds, or `NaN` for an invalid date |
| `RegExp` | `[source, flags]` |
| `URL`, `URLSearchParams`, `BigInt` | the text or the digits |
| `ArrayBuffer` | the base64 text |

You can also use custom types with `uneval` by specifying a custom replacer:

Expand All @@ -167,15 +214,15 @@ Every introspection `stringify` performs on the value being serialized — prope

This is useful in two situations:

**Side-effect-free serialization.** By default, serializing a value can execute user code: getters and proxy traps fire during property reads, `Object.prototype.toString` consults (potentially getter-defined) `Symbol.toStringTag`, and patched prototype methods like `Date.prototype.toISOString` or `Map.prototype[Symbol.iterator]` are invoked. Deterministic or sandboxed runtimes can replace these operations with implementations based on captured intrinsics and property descriptors:
**Side-effect-free serialization.** By default, serializing a value can execute user code: getters and proxy traps fire during property reads, `Object.prototype.toString` consults (potentially getter-defined) `Symbol.toStringTag`, and patched prototype methods like `Date.prototype.getTime` or `Map.prototype[Symbol.iterator]` are invoked. Deterministic or sandboxed runtimes can replace these operations with implementations based on captured intrinsics and property descriptors:

```js
const originalToISOString = Date.prototype.toISOString;
const originalGetTime = Date.prototype.getTime;

const stringified = devalue.stringify(value, undefined, {
operations: {
// use a captured intrinsic instead of a (possibly patched) prototype method
toISOString: (date) => originalToISOString.call(date),
timeOf: (date) => originalGetTime.call(date),

// read through descriptors so getters are never invoked
get: (object, key) => {
Expand Down Expand Up @@ -217,7 +264,7 @@ The mirror image: `parse` and `unflatten` build every value through construction
```js
const revived = devalue.parse(serialized, undefined, {
operations: {
fromISOString: (iso) => new sandbox.Date(iso),
fromTime: (time) => new sandbox.Date(time),
createMap: () => new sandbox.Map(),
createObject: () => sandbox.makeObject()
}
Expand Down
51 changes: 51 additions & 0 deletions benchmarking/benchmarks/parse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { parse, stringify } from '../../src/index.js';
import { records } from '../records.js';
import { reducers, revivers, shared_records, shared_vectors, vectors } from '../shapes.js';
import { fastest_test } from '../utils.js';

/**
* Parses what this version's `stringify` writes for `value`
* @param {string} label
* @param {any} value
* @param {number} iterations
* @param {boolean} [custom] whether `value` has custom types in it
*/
function benchmark(label, value, iterations, custom = false) {
const json = custom ? stringify(value, reducers) : stringify(value);
const r = custom ? revivers : undefined;

return {
label: `parse: ${label}`,
async fn() {
for (let i = 0; i < iterations; i += 1) parse(json, r);
return fastest_test(3, () => {
for (let i = 0; i < iterations; i += 1) parse(json, r);
});
}
};
}

export default [
benchmark('small object', { id: 42, name: 'Jane Smith', roles: ['admin', 'editor'] }, 100000),
benchmark('100 records', records(100), 500),
benchmark('1000 records', records(1000), 50),
benchmark('1000 records, shared authors', shared_records(1000), 50),
benchmark(
'unique short strings',
Array.from({ length: 1000 }, (_, i) => `item-${i}`),
2000
),
benchmark('repeated long strings', Array(1000).fill('x'.repeat(256)), 200),
benchmark(
'string Map',
new Map(Array.from({ length: 1000 }, (_, i) => [`key-${i}`, `value-${i}`])),
500
),
benchmark(
'1000 numbers',
Array.from({ length: 1000 }, (_, i) => i / 7),
1000
),
benchmark('2000 custom values', vectors, 50, true),
benchmark('2000 refs, 200 custom values', shared_vectors, 50, true)
];
12 changes: 9 additions & 3 deletions benchmarking/benchmarks/stringify.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import { stringify } from '../../src/index.js';
import { records } from '../records.js';
import { reducers, shared_records, shared_vectors, vectors } from '../shapes.js';
import { fastest_test } from '../utils.js';

/**
* @param {string} label
* @param {any} value
* @param {number} iterations
* @param {Record<string, (value: any) => any>} [reducers]
*/
function benchmark(label, value, iterations) {
function benchmark(label, value, iterations, reducers) {
return {
label: `stringify: ${label}`,
async fn() {
for (let i = 0; i < iterations; i += 1) stringify(value);
for (let i = 0; i < iterations; i += 1) stringify(value, reducers);
return fastest_test(3, () => {
for (let i = 0; i < iterations; i += 1) stringify(value);
for (let i = 0; i < iterations; i += 1) stringify(value, reducers);
});
}
};
Expand All @@ -26,6 +28,7 @@ export default [
benchmark('small object', { id: 42, name: 'Jane Smith', roles: ['admin', 'editor'] }, 100000),
benchmark('100 records', records(100), 500),
benchmark('1000 records', records(1000), 50),
benchmark('1000 records, shared authors', shared_records(1000), 50),
benchmark(
'unique short strings',
Array.from({ length: 1000 }, (_, i) => `item-${i}`),
Expand Down Expand Up @@ -61,5 +64,8 @@ export default [
Array.from({ length: 1000 }, (_, i) => i / 7),
1000
),
benchmark('repeated long strings', Array(1000).fill('x'.repeat(256)), 200),
benchmark('2000 custom values', vectors, 50, reducers),
benchmark('2000 refs, 200 custom values', shared_vectors, 50, reducers),
benchmark('sparse array', sparse, 20000)
];
2 changes: 1 addition & 1 deletion benchmarking/benchmarks/typed-array.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { fastest_test } from '../utils.js';

import { parse, stringify } from '../../index.js';
import { parse, stringify } from '../../src/index.js';

const value_small = new Uint8Array(Array.from({ length: 100 }, (_, i) => i));
const value_medium = new Uint8Array(Array.from({ length: 10 * 1024 }, (_, i) => i % 256));
Expand Down
31 changes: 27 additions & 4 deletions benchmarking/benchmarks/uneval.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,51 @@
import { uneval } from '../../index.js';
import { uneval } from '../../src/index.js';
import { records } from '../records.js';
import { fastest_test } from '../utils.js';

/**
* @param {string} label
* @param {any} value
* @param {number} iterations
* @param {import('../../src/index.js').UnevalReplacer} [replacer]
*/
function benchmark(label, value, iterations) {
function benchmark(label, value, iterations, replacer) {
return {
label: `uneval: ${label}`,
async fn() {
for (let i = 0; i < iterations; i += 1) uneval(value);
for (let i = 0; i < iterations; i += 1) uneval(value, replacer);
return fastest_test(3, () => {
for (let i = 0; i < iterations; i += 1) uneval(value);
for (let i = 0; i < iterations; i += 1) uneval(value, replacer);
});
}
};
}

/** Rows of strings and numbers only, as a database query might return */
const rows = Array.from({ length: 1000 }, (_, i) => ({
id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`,
name: `Row number ${i}`,
count: i
}));

const shared = { role: 'admin' };

export default [
benchmark('small object', { id: 42, name: 'Jane Smith', roles: ['admin', 'editor'] }, 100000),
benchmark('100 records', records(100), 500),
benchmark('1000 records', records(1000), 50),
benchmark('rows, with a replacer', { rows }, 100, () => undefined),
benchmark('rows, then a Map', { rows, map: new Map([[1, 2]]) }, 100),
benchmark('rows, then a repeated reference', [...rows, { shared }, { shared }], 100),
benchmark(
'rows, then a Map of every row',
{ rows, by_id: new Map(rows.map((row) => [row.id, row])) },
50
),
benchmark(
'rows sharing one object',
rows.map((row) => ({ ...row, shared })),
100
),
benchmark(
'unique short strings',
Array.from({ length: 1000 }, (_, i) => `item-${i}`),
Expand Down
8 changes: 7 additions & 1 deletion benchmarking/compare/runner.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import parse_benchmarks from '../benchmarks/parse.js';
import stringify_benchmarks from '../benchmarks/stringify.js';
import typed_array_benchmarks from '../benchmarks/typed-array.js';
import uneval_benchmarks from '../benchmarks/uneval.js';

const benchmarks = [...stringify_benchmarks, ...typed_array_benchmarks, ...uneval_benchmarks];
const benchmarks = [
...parse_benchmarks,
...stringify_benchmarks,
...typed_array_benchmarks,
...uneval_benchmarks
];
const results = [];

for (let i = 0; i < benchmarks.length; i += 1) {
Expand Down
5 changes: 5 additions & 0 deletions benchmarking/run.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import parse_benchmarks from './benchmarks/parse.js';
import stringify_benchmarks from './benchmarks/stringify.js';
import typed_array_benchmarks from './benchmarks/typed-array.js';
import uneval_benchmarks from './benchmarks/uneval.js';
Expand All @@ -13,6 +14,10 @@ const suites = [
name: 'TypedArray benchmarks',
benchmarks: typed_array_benchmarks.filter(filter_fn)
},
{
name: 'parse benchmarks',
benchmarks: parse_benchmarks.filter(filter_fn)
},
{
name: 'stringify benchmarks',
benchmarks: stringify_benchmarks.filter(filter_fn)
Expand Down
Loading
Loading