devalue
- Version 6.0.3
- Published
- 135 kB
- No dependencies
- MIT license
Install
npm i devalueyarn add devaluepnpm add devalueOverview
Gets the job done when JSON.stringify can't
Index
Variables
Functions
Classes
Interfaces
Type Aliases
Variables
variable defaultParseOperations
const defaultParseOperations: Readonly<DefaultParseOperations>;variable defaultStringifyOperations
const defaultStringifyOperations: Readonly<DefaultStringifyOperations>;Functions
function filterArrayIndices
filterArrayIndices: (keys: readonly string[]) => string[];Given the own enumerable string keys of an array-like value, in property order, returns the leading run of them that are valid array indices.
This is the filtering half of the
indicesOfstringify operation, exposed so that custom operations — which typically already have the keys in hand, e.g. from a foreign runtime — don't have to reimplement it.Does not modify
keys.Parameter keys
Returns
{string[]}
function parse
parse: ( serialized: string, revivers?: Record<string, (value: any) => any>, options?: import('./types.js').ParseOptions) => any;Revive a value serialized with
devalue.stringifyParameter serialized
Parameter revivers
Parameter options
function stringify
stringify: ( value: any, reducers?: Record<string, (value: any) => any>, options?: import('./types.js').StringifyOptions) => string;Turn a value into a JSON string that can be parsed with
devalue.parseParameter value
Parameter reducers
Parameter options
function stringifyAsync
stringifyAsync: ( value: any, reducers?: Record<string, (value: any) => any>, options?: import('./types.js').StringifyOptions) => Promise<string>;Turn a value into a JSON string that can be parsed with
devalue.parseParameter value
Parameter reducers
Parameter options
function uneval
uneval: (value: any, replacer?: UnevalReplacer) => string;Turn a value into the JavaScript that creates an equivalent value
Parameter value
Parameter replacer
function unflatten
unflatten: ( parsed: number | any[], revivers?: Record<string, (value: any) => any>, options?: import('./types.js').ParseOptions) => any;Revive a value flattened with
devalue.stringifyParameter parsed
Parameter revivers
Parameter options
Classes
class DevalueError
class DevalueError extends Error {}constructor
constructor(message: string, keys: string[], value?: any, root?: any);Parameter message
Parameter keys
Parameter value
The value that failed to be serialized
Parameter root
The root value being serialized
property path
path: string;property root
root: any;property value
value: any;Interfaces
interface DefaultParseOperations
interface DefaultParseOperations extends ParseOperations {}The native JavaScript implementation exported as
defaultParseOperations.
method addEntry
addEntry: (map: Map<any, any>, key: any, value: any) => void;method addValue
addValue: (set: Set<any>, value: any) => void;method box
box: (value: any) => object;method createArray
createArray: (length: number) => any[];method createMap
createMap: () => Map<any, any>;method createNullPrototypeObject
createNullPrototypeObject: () => Record<string, any>;method createObject
createObject: () => Record<string, any>;method createSet
createSet: () => Set<any>;method createSparseArray
createSparseArray: (length: number) => any[];method fromArrayBuffer
fromArrayBuffer: (buffer: ArrayBuffer) => ArrayBuffer;method fromISOString
fromISOString: (iso: string) => Date;method fromPrimitive
fromPrimitive: ( primitive: string | number | boolean | bigint | null | undefined) => string | number | boolean | bigint | null | undefined;method fromRegExpInfo
fromRegExpInfo: (source: string, flags: string | undefined) => RegExp;method fromStringValue
fromStringValue: ( tag: StringValueTag, text: string) => URL | URLSearchParams | object;method fromViewInfo
fromViewInfo: ( tag: ViewTag, buffer: ArrayBufferLike, byteOffset: number | undefined, length: number | undefined) => TypedArray | DataView;interface DefaultStringifyOperations
interface DefaultStringifyOperations extends StringifyOperations {}The native JavaScript implementation exported as
defaultStringifyOperations.
method entriesOf
entriesOf: (map: Map<any, any>) => Map<any, any>;method identify
identify: (value: any) => any;method indicesOf
indicesOf: (array: any[]) => string[];method lengthOf
lengthOf: (array: any[]) => number;method regExpInfo
regExpInfo: (regexp: RegExp) => { source: string; flags: string };method toArrayBuffer
toArrayBuffer: (buffer: ArrayBuffer) => ArrayBuffer;method toISOString
toISOString: (date: Date) => string;method toPrimitive
toPrimitive: ( value: undefined | null | boolean | number | bigint | string) => undefined | null | boolean | number | bigint | string;method valuesOf
valuesOf: (set: Set<any>) => Set<any>;method viewInfo
viewInfo: (view: any) => { buffer: ArrayBufferLike; byteOffset: number; byteLength: number; length?: number; bufferByteLength: number;};interface JavaScriptTag
interface JavaScriptTag {}A tagged template function for building trusted JavaScript. The string bits are emitted verbatim, while the "holes" are recursively serialized. Identifier-like words in the string bits are reserved when generating names.
call signature
(strings: TemplateStringsArray, ...values: unknown[]): JavaScriptFragment;interface ParseOperations
interface ParseOperations {}The construction operations
parseandunflattenperform while reviving a value. Every value the algorithm creates — primitives, built-in instances, containers — and every mutation it performs to populate those containers goes through this interface, so overriding members lets you control exactly what gets built.Use cases: - **Cross-realm revival**: construct values from the intrinsics of a different realm (e.g. a
node:vmcontext) so that the result passesinstanceofchecks inside that realm. - **Foreign-runtime revival**: build values inside another JavaScript runtime (a WASM-hosted engine, a remote process) by implementing the operations over handle objects. The algorithm never inspects the values it creates — it only passes them back into other operations — so "value" can be any opaque token.The naming follows the same scheme as
StringifyOperations, with the host/value-space boundary running the other way:-
fromXxx— conversions whose input is entirely host data and whose result crosses into value space; each is the inverse of the correspondingtoXxx(fromPrimitive/toPrimitive,fromISOString/toISOString,fromStringValue/toStringValue,fromArrayBuffer/toArrayBuffer). -fromXxxInfo— construction from a multi-field descriptor, the inverse of the correspondingxxxInfo(fromRegExpInfo/regExpInfo,fromViewInfo/viewInfo). -createXxx— empty value-space containers, populated afterwards by the mutators. That ordering is what makes cyclic values possible: the empty container is cached before its contents are revived. - bare verbs — value-space operations whose operands and results stay in value space (boxinvertsunbox,setinvertsget,addValueinvertsvaluesOf,addEntryinvertsentriesOf).All members are optional when passed to
parse/unflatten— omitted members fall back to the defaults (native behavior, exported asdefaultParseOperations).
method addEntry
addEntry: (map: any, key: any, value: any) => void;Adds an entry to a
Mapcreated bycreateMap. The inverse ofentriesOf.
method addValue
addValue: (set: any, value: any) => void;Adds a value to a
Setcreated bycreateSet. The inverse ofvaluesOf.
method box
box: (value: any) => any;Creates a boxed primitive object (
Number,String,Boolean,BigIntwrapper) around an already-revived inner primitive. The inverse ofunbox. Equivalent toObject(value).
method createArray
createArray: (length: number) => any;Creates an array of the given length, to be populated with
set. The length is bounded by the size of the input, so it is safe to allocate eagerly. Indices that are never set must remain holes.
method createMap
createMap: () => any;Creates an empty
Map, to be populated withaddEntry.
method createNullPrototypeObject
createNullPrototypeObject: () => any;Creates an empty null-prototype object, to be populated with
set. Equivalent toObject.create(null).
method createObject
createObject: () => any;Creates an empty object, to be populated with
set.
method createSet
createSet: () => any;Creates an empty
Set, to be populated withaddValue.
method createSparseArray
createSparseArray: (length: number) => any;Creates a sparse array of the given length, to be populated with
set. UnlikecreateArray, the length comes from the input rather than being bounded by it, so implementations must not allocate storage proportional to it.
method fromArrayBuffer
fromArrayBuffer: (buffer: ArrayBuffer) => any;Creates an
ArrayBufferfrom a hostArrayBufferholding the decoded bytes. The inverse oftoArrayBuffer. Default: the buffer itself. Foreign-runtime implementations should copy the bytes into the target runtime.
method fromISOString
fromISOString: (iso: string) => any;Creates a
Datefrom an ISO string. The inverse oftoISOString. An empty string represents an invalid date (as produced fornew Date(NaN)).
method fromPrimitive
fromPrimitive: ( primitive: string | number | boolean | bigint | null | undefined) => any;Wraps a host primitive (
string,number,boolean,bigint,null,undefined, and the special valuesNaN,±Infinity,-0) into the representation the other operations expect. The inverse oftoPrimitive. Default: the value itself.
method fromRegExpInfo
fromRegExpInfo: (source: string, flags: string | undefined) => any;Creates a
RegExpfrom its source and flags. The inverse ofregExpInfo.flagsisundefinedwhen the pattern had no flags.
method fromStringValue
fromStringValue: (tag: StringValueTag, text: string) => any;Creates a
URL,URLSearchParamsorTemporal.*value from its string form — the same tagstoStringValueserializes, and its inverse.tagdistinguishes them (e.g.'URL','Temporal.Instant').
method fromViewInfo
fromViewInfo: ( tag: ViewTag, buffer: any, byteOffset: number | undefined, length: number | undefined) => any;Creates a typed array or
DataViewover an already-revived buffer. The inverse ofviewInfo.tagis the constructor name (e.g.'Uint8Array','DataView').byteOffsetandlengthareundefinedwhen the view spans the whole buffer; otherwiselengthis the element count for typed arrays and the byte length forDataView, matching the constructor signatures.Implementations must validate that
bufferrepresents a genuine backing buffer, since custom revivers can return other values. In particular, passing a number or array-like value to a native typed array constructor can allocate storage unrelated to the size of the serialized input.
method set
set: (target: any, key: string | number, value: any) => void;Sets an element or property on a value created by
createArray,createSparseArray,createObjectorcreateNullPrototypeObject. The inverse ofget, which likewise serves both arrays and objects.
interface ParseOptions
interface ParseOptions {}Options for
parseandunflatten.
property operations
operations?: Partial<ParseOperations>;Overrides for the construction operations used while reviving. Omitted members fall back to
defaultParseOperations.
interface StringifyOperations
interface StringifyOperations {}The introspection/extraction operations
stringifyperforms on the value being serialized. Every dynamic operation — property reads, prototype method calls, iteration, type classification — goes through this interface, so overriding members lets you control exactly how values are inspected.Use cases: - **Side-effect-free serialization**: replace operations that can execute user code (getters, proxy traps, patched prototypes,
Symbol.toStringTagaccessors) with implementations based on captured intrinsics, internal slots, or property descriptors. - **Foreign-runtime serialization**: serialize values that live in another JavaScript runtime (anode:vmcontext, a WASM-hosted engine, a remote process) by implementing the operations over handle objects. Thestringifyalgorithm never touches the value directly, so "value" can be any opaque token as long as the operations agree on what it means.All members are optional when passed to
stringify— omitted members fall back to the defaults (native behavior, exported asdefaultStringifyOperations).Members are named by what they do with the value: -
isXxx/hasXxx— predicates returning booleans -toXxx— conversions whose whole result crosses into host JavaScript (toPrimitive,toISOString) or into a native container (toPromise) -xxxOf— queries returning host data *about* the value (typeOf,tagOf,lengthOf) or its constituents, which remain in value space (valuesOf,entriesOf) -xxxInfo— multi-field descriptors mixing host data and constituent values (viewInfo,regExpInfo) - bare verbs (get,unbox,identify) — accessors whose results remain in value space(
toStringValueandunboxdeliberately avoid the namestoStringandvalueOf, which would shadowObject.prototypemethods on the operations object.)
method entriesOf
entriesOf: (map: any) => Iterable<[any, any]>;Returns an iterable over the
[key, value]entries of aMapvalue. The iterable is consumed on the host; keys/values may be foreign values/handles.
method get
get: (value: any, key: string | number) => any;Reads a property from an
Arrayor plain-object value. Equivalent tovalue[key]. Hardened implementations can read through property descriptors to control what happens for accessor properties.
method hasOwn
hasOwn: (value: any, key: string | number) => boolean;Returns true if a value has an own property at
key. Same contract asObject.hasOwn(value, key).
method identify
identify: (value: any) => unknown;Returns the key used for deduplication and cycle detection (compared with
Mapkey semantics). Two values that represent the same logical object must return the same key. Default: the value itself.Override this when serializing through handles, where two distinct handle objects may refer to the same underlying value.
Keys are compared across *every* value in the payload, including primitives, so an implementation that derives keys for objects must make sure they cannot collide with a primitive that appears in the same payload — returning e.g. the string
'42'as an object's key would alias it to the string'42'elsewhere in the payload and emit a wrong back-reference. Prefer keys that are unforgeable, such as the underlying object itself, a symbol, or a wrapper object.
method indicesOf
indicesOf: (array: any) => string[];Returns the populated indices of a (sparse)
Arrayvalue as strings, in ascending order.Implementations that already have the value's own enumerable string keys — as a foreign-runtime implementation typically does — should pass them through the exported
filterArrayIndiceshelper rather than reimplementing the filtering, which encodes the sparse-array heuristic.Equivalent to
Object.keys(array)filtered to valid array indices.
method isThenable
isThenable: (value: any) => boolean;Returns true if the object value should be treated as a thenable.
method lengthOf
lengthOf: (array: any) => number;Returns the length of an
Arrayvalue.
method regExpInfo
regExpInfo: (regexp: any) => { source: string; flags: string };Returns the source and flags of a
RegExpvalue.
method shapeOf
shapeOf: ( value: any) => | { kind: 'plain' | 'null-proto'; keys: string[] } | { kind: 'not-plain' } | { kind: 'symbol-keys' };Classifies a plain-object candidate: -
{ kind: 'plain' | 'null-proto', keys }— a serializable POJO and its own enumerable string keys -{ kind: 'not-plain' }— a non-POJO (stringify throws) -{ kind: 'symbol-keys' }— a POJO with enumerable symbol keys (stringify throws)
method tagOf
tagOf: (value: any) => string;Returns the brand of an object value — the strings produced by
Object.prototype.toStringwithout the wrapping ('Date','Array','Map','Object','Temporal.Instant', …). This decides which serialization strategy is used, so hardened implementations should use engine-level brand checks rather than (spoofable, getter-invoking)Symbol.toStringTaglookups.
method toArrayBuffer
toArrayBuffer: (buffer: any) => ArrayBuffer;Returns a host
ArrayBufferwith the bytes of anArrayBuffervalue. Default: the value itself. Foreign-runtime implementations should copy the bytes into a host buffer.
method toISOString
toISOString: (date: any) => string;Returns the ISO string for a
Datevalue, or''for an invalid date. Equivalent todate.toISOString().
method toPrimitive
toPrimitive: ( value: any) => undefined | null | boolean | number | bigint | string;Extracts the host-JavaScript primitive from a value whose
typeOfis'null','boolean','number','bigint'or'string'. Default: the value itself (it already is the primitive).
method toPromise
toPromise: (thenable: any) => Promise<any>;Converts a thenable into a native promise, whose settled value is then serialized. The returned promise may reject, in which case
stringifyAsyncrejects. Only called fromstringifyAsync, for values whereisThenablereturned true.
method toStringValue
toStringValue: (value: any) => string;Returns the string form of a
URL,URLSearchParamsorTemporal.*value. Equivalent tovalue.toString().
method typeOf
typeOf: ( value: any) => | 'undefined' | 'null' | 'boolean' | 'number' | 'bigint' | 'string' | 'symbol' | 'function' | 'object';Classifies a value. Same contract as the
typeofoperator, exceptnullmust be reported as'null'(not'object').
method unbox
unbox: (boxed: any) => any;Extracts the inner value of a boxed primitive (
Number,String,Boolean,BigIntobjects). Equivalent toboxed.valueOf(). The result is serialized recursively, so it may be a foreign value/handle.
method valuesOf
valuesOf: (set: any) => Iterable<any>;Returns an iterable over the elements of a
Setvalue. The iterable is consumed on the host; elements may be foreign values/handles.
method viewInfo
viewInfo: (view: any) => { buffer: any; byteOffset: number; byteLength: number; length?: number; bufferByteLength: number;};Returns the view metadata of a typed array or
DataViewvalue.lengthis only meaningful for typed arrays.bufferis serialized recursively in full, so it may be a foreign value/handle. The default copies Node Buffers into an exact-sized backing buffer with byteOffset 0 to avoid exposing unrelated bytes from Node's shared pool. Overrides must take equivalent care with pooled views.
interface StringifyOptions
interface StringifyOptions {}Options for
stringifyandstringifyAsync.
property operations
operations?: Partial<StringifyOperations>;Overrides for the introspection/extraction operations used while serializing. Omitted members fall back to
defaultStringifyOperations.
Type Aliases
type JavaScriptFragment
type JavaScriptFragment = { readonly [SOURCE]: JavaScriptSource;};type StringValueTag
type StringValueTag = | 'URL' | 'URLSearchParams' | 'Temporal.Duration' | 'Temporal.Instant' | 'Temporal.PlainDate' | 'Temporal.PlainTime' | 'Temporal.PlainDateTime' | 'Temporal.PlainMonthDay' | 'Temporal.PlainYearMonth' | 'Temporal.ZonedDateTime';type TypedArray
type TypedArray = | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Float16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;type UnevalReplacer
type UnevalReplacer = ( value: unknown, js: JavaScriptTag) => JavaScriptFragment | false | null | void;A function that replaces a value with a JavaScript expression that can be evaluated to reproduce that value. The expression is trusted JavaScript. Return
undefined,nullorfalsewhen the value should be serialized normally.
type ViewTag
type ViewTag = | 'Int8Array' | 'Uint8Array' | 'Uint8ClampedArray' | 'Int16Array' | 'Uint16Array' | 'Float16Array' | 'Int32Array' | 'Uint32Array' | 'Float32Array' | 'Float64Array' | 'BigInt64Array' | 'BigUint64Array' | 'DataView';Package Files (7)
Dependencies (0)
No dependencies.
Dev Dependencies (8)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/devalue.
- Markdown[](https://www.jsdocs.io/package/devalue)
- HTML<a href="https://www.jsdocs.io/package/devalue"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 4029 ms. - Missing or incorrect documentation? Open an issue for this package.
