Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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/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/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
39 changes: 34 additions & 5 deletions FORMAT.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ stringify([new Uint8Array(buffer), new Uint16Array(buffer)]);

### Custom types

Custom types are what tagged arrays are for. On the writing side you pass reducers to `stringify`. Each reducer is named after a type and returns something truthy for the values it handles. The value is then written as `["$:Name", whatever the reducer returned]`. Reducers are tried in order, before any built-in handling, and the first truthy result wins.
Custom types are what tagged arrays are for. On the writing side you pass reducers to `stringify`. Each reducer is named after a type and returns something truthy for the values it handles. The value is then written as `["$:Name", whatever the reducer returned]`. Reducers are tried in order, before any built-in handling, and the first truthy result wins. They are only tried on objects and functions: strings, numbers, booleans, BigInts, `null` and `undefined` are always written as themselves.

```js
class Vector {
Expand All @@ -204,6 +204,36 @@ parse('["$:Vector",[30,40]]', { Vector: ([x, y]) => new Vector(x, y) });

On the reading side, `parse` needs a reviver with the same name, which is given the payload after it has been read. A tag with no reviver and no built-in meaning is an error (`Unknown type Name`).

A reviver is called once, with the whole payload. That means a custom value's payload can't refer back to the custom value itself, because the value doesn't exist until the reviver returns: the reader throws `Invalid circular reference`. A type whose values can contain themselves needs a two-stage reviver instead. `create` makes the value before its payload is read, so a reference to it from inside the payload is that value, and `fill` is given the value and the whole payload:

```js
class Node {
constructor(name) {
this.name = name;
this.next = null;
}
}

const node = new Node('a');
node.next = node;

stringify(node, { Node: (n) => n instanceof Node && { name: n.name, next: n.next } });
// ["$G",["$:Node",{"name":"a","next":"$R0"}]]

parse('["$G",["$:Node",{"name":"a","next":"$R0"}]]', {
Node: {
create: () => new Node(''),
fill: (n, payload) => {
n.name = payload.name;
n.next = payload.next;
}
}
});
// <ref *1> Node { name: 'a', next: [Circular *1] }
```

In a cycle through several custom types, only the ones that are referred to before their payload is complete need to be two-stage.

### Revivers named after built-in types

A reviver named after a built-in type takes that type over. It is given what the type was written as:
Expand Down Expand Up @@ -293,7 +323,7 @@ Within a wrapped root, the reader numbers values in the order it meets them as i
These get a number:

- Every object, including arrays, sparse arrays, Dates, RegExps, URLs, URLSearchParams, Temporal values, ArrayBuffers (`$B`), Maps, Sets, boxed primitives, null-prototype objects, typed arrays and DataViews.
- Every custom value, even when the value the reducer matched was a primitive.
- Every custom value.
- Every string at least 32 characters long (`MIN_SHARED_STRING`, counted in UTF-16 code units, as JavaScript's `length` counts them). The first time such a string appears it is written out. After that it is a reference.
- The payload inside a tagged array, if it is an object or array. It takes the number right after its owner. So the array inside `["$:Map", [...]]`, the array inside `["$:Set", [...]]`, the `[buffer, byteOffset, length]` array of a partial view and the object inside `["$:null", {...}]` each take one number. A custom type's payload is numbered in the same way.

Expand Down Expand Up @@ -375,13 +405,11 @@ stringify([Object(long), long]);
// ["$G",[["$:Object","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"],"$R2"]]
```

A custom value whose reducer matched a primitive still takes a number, but is written out again each time it appears. Only objects and long strings are shared.

### How a reference is written

A reference is `$R` followed by the number in plain decimal digits, with no leading zeros, no sign and no decimal point. It always points to a value that has already been numbered, which means earlier in the text, or a value that contains the reference. A forward reference is rejected.

If a custom value's payload refers back to the custom value itself, the reader calls that reviver early, with the payload as far as it has been read, and calls it again once the payload is complete. If there is no payload yet to give it, the reader throws `Invalid circular reference`.
If a custom value's payload refers back to the custom value itself, the reader throws `Invalid circular reference`, unless its reviver is a two-stage one (see [Custom types](#custom-types)).

### Writing without references

Expand Down Expand Up @@ -517,6 +545,7 @@ Unless noted, the reader throws `Error('Invalid input')`. The reader checks what
- A number that is not plain digits: `"$R01"`, `"$R1.5"`, `"$R-1"`, `"$R 1"`, `"$R1e0"`, `"$R"`.
- A reference into a root that is missing, comes later or is not wrapped: `["$G",[{},"$R0:1"]]` (no `$A`), `["$A",{"a":{},"p":"$P1"},1,["$R0:1"]]` (main root not wrapped), `["$A",["$G",{"a":"$R1:0","p":"$P1"}],1,["$G",[{}]]]` (root 1 comes later).
- A custom value that refers to itself before its payload exists: `["$G",["$:Custom","$R0"]]` throws `Invalid circular reference`.
- A boxed primitive or typed array that refers to itself from inside its payload, such as `["$G",["$:Object","$R0"]]` or `["$G",["$:Uint8Array","$R0"]]`, throws `Invalid circular reference` too.

### Tagged arrays with the wrong shape

Expand Down
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,21 @@ 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:

Expand Down
123 changes: 59 additions & 64 deletions src/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ import { is_valid_array_index, is_valid_array_len } from './utils.js';
const PROTO = 'Cannot parse an object with a `__proto__` property';
const REPEATED = 'Cannot parse a repeated reference when `references` is `false`';

// holds the number of a value that is still being read, such as a custom value
// whose reviver hasn't returned yet. a reference to it is a cycle with nothing
// to refer to yet, which is an error. a two-stage reviver puts its value in
// the slot before its payload is read, so it never leaves this there
const PENDING = {};

/** @returns {never} */
function invalid() {
throw new Error('Invalid input');
Expand Down Expand Up @@ -39,7 +45,7 @@ function digits(s, start, end) {
/**
* Revive a value serialized with `devalue.stringify`
* @param {string} serialized
* @param {Record<string, (value: any) => any>} [revivers]
* @param {Record<string, import('./types.js').Reviver>} [revivers]
* @param {import('./types.js').ParseOptions} [options]
*/
export function parse(serialized, revivers, options) {
Expand All @@ -50,7 +56,7 @@ export function parse(serialized, revivers, options) {
* Revive a value that was serialized with `devalue.stringify` and has
* already been through `JSON.parse`.
* @param {any} parsed
* @param {Record<string, (value: any) => any>} [revivers]
* @param {Record<string, import('./types.js').Reviver>} [revivers]
* @param {import('./types.js').ParseOptions} [options]
*/
export function unflatten(parsed, revivers, options) {
Expand All @@ -59,7 +65,7 @@ export function unflatten(parsed, revivers, options) {

/**
* @param {any} payload
* @param {Record<string, (value: any) => any> | undefined} revivers
* @param {Record<string, import('./types.js').Reviver> | undefined} revivers
* @param {import('./types.js').ParseOptions | undefined} options
* @param {boolean} copy whether to copy containers. If `false`, `revive` may modify `payload` or any of its children
*/
Expand Down Expand Up @@ -93,12 +99,6 @@ function revive(payload, revivers, options, copy) {
/** @type {any[] | null} */
let values = null;

// custom values such as ["$:Vector", ...] whose reviver hasn't run yet,
// because their payload is still being read, by number. a reference to one
// of these is a cycle through a custom type, which `reference` handles
/** @type {Map<number, (value: any) => any> | null} */
let unrevived = null;

// A value with promises in it is ["$A", root, id, result, id, result, ...].
// The root and each result are roots of their own, and each numbers its
// values from 0. A reference into another root names it: "$R3:12" is value
Expand Down Expand Up @@ -130,17 +130,33 @@ function revive(payload, revivers, options, copy) {
/**
* A custom reviver named after a built-in type that is written as text takes
* over that type. It is given what the text stands for: the time for a Date,
* `[source, flags]` for a RegExp, and the text itself otherwise
* `[source, flags]` for a RegExp, and the text itself otherwise. Without one,
* `fallback` is used
* @template {((payload: any) => any) | undefined} F
* @param {string} name
* @param {F} fallback
* @returns {((payload: any) => any) | F}
*/
function shadow(name) {
return revivers && Object.hasOwn(revivers, name) ? revivers[name] : undefined;
function shadow(name, fallback) {
if (!revivers || !Object.hasOwn(revivers, name)) return fallback;

const reviver = revivers[name];
if (typeof reviver === 'function') return reviver;

// a value written as text can't refer to itself, so the two stages run together
return (/** @type {any} */ payload) => {
const value = reviver.create();
reviver.fill(value, payload);
return value;
};
}

const date_reviver = shadow('Date');
const regexp_reviver = shadow('RegExp');
const bigint_reviver = shadow('BigInt');
const buffer_reviver = shadow('ArrayBuffer');
const date_reviver = shadow('Date', (time) => ops.fromTime(time));
const regexp_reviver = shadow('RegExp', ([source, flags]) =>
ops.fromRegExpInfo(source, flags || undefined)
);
const bigint_reviver = shadow('BigInt', (s) => ops.fromPrimitive(BigInt(s)));
const buffer_reviver = shadow('ArrayBuffer', (s) => ops.fromArrayBuffer(decode64(s)));

/**
* @template T
Expand Down Expand Up @@ -199,22 +215,10 @@ function revive(payload, revivers, options, copy) {

if (values === null || n >= values.length) invalid();

const reviver = unrevived?.get(n);

if (reviver) {
// a custom value that refers to itself from inside its own payload.
// the payload is the next numbered value. if it exists the reviver
// is called early, with the payload as it is so far, and is called
// again once the payload is complete
if (n + 1 >= values.length || unrevived?.has(n + 1)) {
throw new Error('Invalid circular reference');
}
const value = values[n];
if (value === PENDING) throw new Error('Invalid circular reference');

unrevived?.delete(n);
return (values[n] = reviver(values[n + 1]));
}

return values[n];
return value;
}

/** @param {number} id */
Expand Down Expand Up @@ -262,7 +266,7 @@ function revive(payload, revivers, options, copy) {
* @param {string} value
*/
function text(tag, value) {
const reviver = shadow(tag);
const reviver = shadow(tag, undefined);
return reviver ? reviver(value) : ops.fromStringValue(tag, value);
}

Expand Down Expand Up @@ -292,8 +296,7 @@ function revive(payload, revivers, options, copy) {

// n
case 110:
if (bigint_reviver) return bigint_reviver(s.slice(2));
return ops.fromPrimitive(BigInt(s.slice(2)));
return bigint_reviver(s.slice(2));

// R
case 82:
Expand All @@ -309,8 +312,7 @@ function revive(payload, revivers, options, copy) {
const negative = s.charCodeAt(2) === 45;
const n = digits(s, negative ? 3 : 2, s.length);
const time = n === -1 ? NaN : negative ? -n : n;
if (date_reviver) return register(date_reviver(time));
return register(ops.fromTime(time));
return register(date_reviver(time));
}

// X
Expand All @@ -320,15 +322,12 @@ function revive(payload, revivers, options, copy) {

const source = s.slice(slash + 1);
const flags = s.slice(2, slash);
if (regexp_reviver) return register(regexp_reviver([source, flags]));

return register(ops.fromRegExpInfo(source, flags || undefined));
return register(regexp_reviver([source, flags]));
}

// B
case 66:
if (buffer_reviver) return register(buffer_reviver(s.slice(2)));
return register(ops.fromArrayBuffer(decode64(s.slice(2))));
return register(buffer_reviver(s.slice(2)));

// U
case 85:
Expand All @@ -351,29 +350,27 @@ function revive(payload, revivers, options, copy) {

/**
* @param {any} v
* @param {boolean} [fresh] build a new array or object even when reviving in place
* @returns {any}
*/
function build(v, fresh) {
function build(v) {
if (typeof v === 'string') return string(v);
if (v === null || typeof v !== 'object') return ops.fromPrimitive(v);
return Array.isArray(v) ? array(v, fresh) : object(v, fresh);
return Array.isArray(v) ? array(v) : object(v);
}

/**
* @param {any[]} v
* @param {boolean} [fresh] build a new array even when reviving in place
* @returns {any}
*/
function array(v, fresh) {
function array(v) {
const first = v[0];

if (typeof first === 'string' && first.charCodeAt(0) === 36) {
if (first.charCodeAt(1) === 58) return tagged(v, first.slice(2));
if (first === '$S') return sparse(v);
}

if (in_place && !fresh) {
if (in_place) {
if (copy) v = v.slice();
if (values !== null) values.push(v);

Expand Down Expand Up @@ -435,11 +432,10 @@ function revive(payload, revivers, options, copy) {

/**
* @param {Record<string, any>} v
* @param {boolean} [fresh] build a new object even when reviving in place
* @returns {any}
*/
function object(v, fresh) {
if (in_place && !fresh) {
function object(v) {
if (in_place) {
// own enumerable properties only, whatever the prototype was
if (copy) v = { ...v };
if (values !== null) values.push(v);
Expand Down Expand Up @@ -504,18 +500,18 @@ function revive(payload, revivers, options, copy) {

const reviver = revivers[name];

if (values === null) return reviver(build(v[1]));

const n = values.push(undefined) - 1;
(unrevived ??= new Map()).set(n, reviver);
// `{ create, fill }`: the value exists before its payload is read, so
// the payload can refer to it
if (typeof reviver !== 'function') {
const value = register(reviver.create());
reviver.fill(value, build(v[1]));
return value;
}

// if the value refers to itself, its reviver is called early with
// the payload as it is so far. a payload revived in place would
// still hold unrevived children then, so it is built afresh, and a
// child only appears in it once that child is complete
const value = reviver(build(v[1], true));
if (values === null) return reviver(build(v[1]));

unrevived.delete(n);
const n = values.push(PENDING) - 1;
const value = reviver(build(v[1]));
values[n] = value;

return value;
Expand Down Expand Up @@ -557,7 +553,7 @@ function revive(payload, revivers, options, copy) {
if (v.length !== 2) invalid();

// the box is numbered before the primitive inside it
const n = values === null ? -1 : values.push(undefined) - 1;
const n = values === null ? -1 : values.push(PENDING) - 1;
const boxed = ops.box(build(v[1]));
if (values !== null) values[n] = boxed;

Expand Down Expand Up @@ -592,8 +588,8 @@ function revive(payload, revivers, options, copy) {

// the view is numbered before its buffer, and so is the array
// holding the buffer. here the view and that array are one value
const n = values === null ? -1 : values.push(undefined) - 1;
if (part && values !== null) values.push(undefined);
const n = values === null ? -1 : values.push(PENDING) - 1;
if (part && values !== null) values.push(PENDING);

const view = ops.fromViewInfo(
/** @type {import('./types.js').ViewTag} */ (name),
Expand Down Expand Up @@ -628,7 +624,6 @@ function revive(payload, revivers, options, copy) {
}

values = graph ? [] : null;
unrevived = null;

const result = build(raw);

Expand Down
Loading
Loading