@cqrs-ddd/safe-stringify
Two JSON serializers with opposite goals, and the key-segment helpers that build identity keys. No runtime dependencies and no framework.
Strict: stableStringify, toStrictJsonValue |
Safe: safeStringify, safeSanitize, redactValue |
|
|---|---|---|
| Use for | identity: cache keys, idempotency fingerprints, stored snapshots | display: logs, audit and dead-letter payloads |
| Output | deterministic JSON, object keys sorted at every level, stable across releases | readable JSON in insertion order; the format may evolve |
| Unsupported input | throws a TypeError |
never throws |
| Secrets | never redacts, because a key must not change | excludes and redacts on request |
Use the strict serializer for anything that identifies data. Never use safeStringify
for a key or a fingerprint: its output is not sorted, it replaces values it cannot
represent, and its format may change.
Installation
Section titled “Installation”Requires Node.js 22.12 or later.
Published as an ES module; a CommonJS application loads it with require().
Strict serializer
Section titled “Strict serializer”- Strings, booleans,
nulland finite numbers are kept. Dates become ISO-8601 strings. An object withtoJSON()is replaced by what that method returns. - Everything else throws a
TypeError:undefined, functions,bigint, symbols and symbol-keyed properties, non-finite numbers, invalid dates, cycles, sparse arrays,Map,Set,WeakMap,WeakSet,Error,RegExp,Promise,ArrayBuffer, typed arrays, boxed primitives such asnew Number(1), and an iterable object withouttoJSON(), such asURLSearchParamsorHeaders. stableStringifywraps that failure in aTypeErrorwhosecauseis the original.- Structurally equal values produce byte-identical strings, whatever their property
insertion order. Keys sort by UTF-16 code unit, as
Array.prototype.sortdoes.
Safe serializer
Section titled “Safe serializer”-
safeStringify(value, options?, indent?)andsafeSanitize(value, options?)never throw. Cycles become"[Circular]", errors are expanded toname,message,stackand their own enumerable properties, and values JSON cannot hold are replaced by a readable marker ("[bigint]","[Function]","[Invalid Date]","[Binary Data]","[Stream]"). ASet<string>in place ofoptionsis read asexcludeKeys.safeStringify(undefined)returns the string'undefined'. -
They redact nothing unless you pass
redactKeys.redactValue(value, keys?)appliesDEFAULT_REDACT_KEYSby default and keeps rich types (mode: 'clone'). -
SanitizeOptions:Option Effect excludeKeyskeys or dot-paths removed from the output; exact, case-sensitive match redactKeyskeys or dot-paths masked; matched ignoring case, _and-, sorefreshTokenalso masksrefresh_tokenredactReplacementthe mask; default REDACTED("[REDACTED]")mode'json'(default) turns rich types into JSON-friendly values;'clone'deep-clones them keeping their classes -
Exclusion and redaction, with a key matched at any depth or a dot-path matched at one place only:
-
DEFAULT_REDACT_KEYSlists common secret names (passwords, tokens, API keys, authorization headers, cookies, card data). No list recognizes every secret: add your application’s own names.
Key segments
Section titled “Key segments”joinKeySegments(segments)escapes each segment and joins them with:.undefinedandnullbecomeABSENT_SEGMENT(\-), so['a', undefined]and['a', '']produce different keys.escapeKeySegment(value)escapes\first, then:. A segment that is literally\-is written\\-, so it never collides with an absent segment.
Build a cache key from a tenant, a request name and a strict fingerprint of the payload:
The strict serializer’s output and these key formats are part of the package contract: changing them would orphan every stored cache entry, rate-limit bucket and idempotency fingerprint. The package’s golden-output specs pin them.
License
Section titled “License”Dual-licensed under AGPLv3 and a Commercial License. See the root
LICENSE and
COMMERCIAL_LICENSE.txt
for details.