Repository navigation
breaking: new wire format, and reducer and reviver changes - #246
elliott-with-the-longest-name-on-github wants to merge 20 commits into
Conversation
|
Install the latest version of pnpm add https://pkg.svelte.dev/devalue/c/4449f1cc45bdbef1aa73635bb2a170915b1f0dbcOpen in |
🦋 Changeset detectedLatest commit: 4449f1c The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Plain JSON with $-marked values, $G-wrapped roots when there are references, ["$:Name", payload] for tagged types, and $A for promises in stringifyAsync. Also adds the references: false option, skips symbol keys, and makes stringifyAsync fail fast.
b244b93 to
cb278ab
Compare
A box (`Object()` of a promise is the promise itself) or a reviver could make two promises resolve with each other, so neither ever settled. Every result is now checked once it is built, which replaces the two narrower checks on bare `$P` results and on a promise resolving to itself.
…wo-stage revivers for cycles
…them in a Set A reference to a custom value whose function reviver hasn't returned, or to a box or view whose contents are still being read, now always throws `Invalid circular reference`.
`path_to_root` walks the root the promise was found in again, up to the promise, so its path is collected the way an error's is. That replaces `locate`, which repeated the whole walk. Also inlines two one-use helpers in parse.js, reuses `at` in `plain_object` and finds Temporal types with `indexOf`. About 600 B smaller minified.
The writer keeps one array of root records, always created, instead of four parallel arrays that were `null` in `stringify` behind an `any` cast. The reader creates its map of promises when it meets the first one.
…nly() writes value `only` no longer takes the value `writer` already has.
| '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 |
There was a problem hiding this comment.
| 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 |
| '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 |
There was a problem hiding this comment.
We should just skip them in uneval too. Probably unlocks extra perf there as well
|
|
||
| createNullPrototypeObject: () => Object.create(null), | ||
|
|
||
| createPromise: () => { |
There was a problem hiding this comment.
This should probably return { promise, resolve, reject } so that in the future, when we need rejections, we don't have to make a breaking change.
| * @param {import('./types.js').StringValueTag} tag | ||
| * @param {string} value | ||
| */ | ||
| function text(tag, value) { |
There was a problem hiding this comment.
Why isn't this just const text = (tag, value) => shadow(tag, () => ops.fromStringValue(tag, value));
A parse suite that mirrors the stringify one, parsing what the same version's stringify writes, plus benchmarks for records that share their authors, custom values, references to custom values and repeated long strings. The shared values live in benchmarking/shapes.js.
… scanned JSON.stringify scans every string for characters to escape, which for the base64 text of an ArrayBuffer costs more than encoding it and never finds any. Each buffer is written as a placeholder, "$B-0", and swapped in once the root is text. Only a whole string value that is exactly "$B-<digits>" counts as one, which nothing in the value can produce. `digits` moves to utils.js so the reader and writer share it.
First of two stacked PRs for the next major version. It also includes the reducer and reviver changes that were #247. The full wire format is specified in the new
FORMAT.md.What changes
tree-format): the payload is plain JSON. Plain data is written as itself, and other values are$-marked strings ("$D1700000000000","$n123","$R4", ...). A root that contains references is wrapped as["$G", value], and every tagged type is["$:Name", payload], with exactly one payload. Payloads written by earlier versions can no longer be parsed.builtin-reviver-payloads): a reviver named after a built-in type gets the whole payload, for example every entry of aMap.RegExpreviver (regexp-reviver-flags): gets[source, flags]instead of only the source. breaking: drop sparse arrays; regular expressions are opt-in #248 removes this changeset, because RegExp stops being a built-in type there.Datereviver (date-reviver-time): gets the time in milliseconds instead of an ISO string.date-operations):toISOString/fromISOStringare replaced bytimeOf/fromTime.reread-properties). The writer's fast path depends on this.stringify/stringifyAsync, asJSON.stringifyskips them (symbol-keys).unevalstill throws.async-promises):stringifyAsyncwrites["$A", root, id, result, ...], andparsegives back a promise wherever the value had one. Results are written in the order the promises settle.stringifyAsyncfails fast (async-fail-fast): it rejects with the first failure, without waiting for promises earlier in the value.references: false(references-option): a new option onparse,unflatten,stringifyandstringifyAsyncthat rules out repeated and cyclical references.Reducers and revivers
Reducers only see objects and functions (
reducers-objects-only). Strings, numbers, booleans, BigInts,nullandundefinedare always written as themselves, so they stay on the fast path even when reducers are passed. Functions are tracked by identity, so a reducer that returns its own input is an ordinary cycle. This removes theREDUCER_LOOPerror and its bookkeeping.Revivers are called once, with the whole payload (
two-stage-revivers). A custom value whose payload refers back to the value itself now throwsInvalid circular reference. For types that can contain themselves, a reviver can be{ create, fill }:createmakes the value before its payload is read;fill(value, payload)completes it.The two-stage form also works for revivers named after built-ins. Adds the
ReviverandTwoStageRevivertypes.Values still being read hold a marker in their slot. This replaces a separate
Setof unrevived values, and makes parsing payloads with custom values about 10% faster. A box or typed array that refers to itself from inside its payload now throwsInvalid circular referencetoo, like a custom value.Refactor: in
parse.js,shadow(name, fallback)returns the built-in's own reader when there is no user reviver, which removes a conditional at each call site.Benchmarks
This PR also brings in #235 by @teemingc, which makes
pnpm benchrun again and addsunevalbenchmarks. On top of that it adds aparsesuite, which parses what the same version'sstringifywrites, and benchmarks for records that share objects, custom types, and references to custom types (benchmarking/shapes.js).Both columns run exactly the same benchmark files, against
main'ssrc/and this PR's. Times are per call, in microseconds: each benchmark's total time divided by its number of iterations, taking the best of 3 alternating runs of the whole suite on Node 24.19 (Apple Silicon). Lower is better.parsemain(µs per call)Uint8Array, 100 BUint8Array, 10 KBUint8Array, 1 MBstringifymain(µs per call)Uint8Array, 100 BUint8Array, 10 KBUint8Array, 1 MBPayload size
The new format is also smaller, and compresses much better. Compressed sizes use gzip at level 6 (Node's default, and so Express's
compressionmiddleware's) and brotli at quality 4, typical settings for responses compressed as they are sent:mainrawmaingzipmainbrotliUint8Array, 10 KBWhat isn't better
stringifyof small typed arrays is slower: 61% for 100 bytes, where the fixed cost of each call and each value outweighs the bytes. From around 10 KB they're faster than onmain: 8% at 10 KB and 72% at 1 MB. Base64 text skipsJSON.stringifyentirely: each buffer is written as a placeholder,"$B-0", and its text is spliced in afterwards.stringifyof repeated long strings is 8% slower.unevalis unchanged, within −2% and +5%.To reproduce:
pnpm bench, orpnpm bench:compare main(that one checks out each branch, so it runsmain's own benchmark files there).Tests
format.test.js(the spec's cases),fuzz.test.js(round trips and damaged payloads) andreferences-option.test.js.