Registry / serialization / tosource

tosource

JSON →
library2.0.0-alpha.3jsnpmunverified

tosource is a utility library for JavaScript that serializes complex JavaScript objects, including functions, Date objects, RegExp instances, Maps, Sets, sparse arrays, NaN, Infinity, undefined, and negative zero, into their equivalent JavaScript source code string representations. This extends beyond the capabilities of JSON.stringify, which only handles a subset of these types. The package is currently in a pre-release alpha phase (v2.0.0-alpha.3), indicating active development. It is designed to facilitate sharing trusted data structures and even code between Node.js environments and browsers, useful for isomorphic applications. While there isn't an explicit release cadence, the recent alpha releases suggest ongoing improvements in functionality and toolchain, including TypeScript support and ESM exports.

npm install tosource
INSTALL
IMPORT
SIG · TOSOURCE
T
tosource
serializationjavascriptv2.0.0-alpha.3
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

toSource (ESM Default)
import toSource from 'tosource';
import { toSource } from 'tosource';
Since v2, `tosource` is primarily designed for ESM with a default export. Attempting a named import will result in `toSource is not a function` at runtime.
toSource (CommonJS)
const toSource = require('tosource');
const { toSource } = require('tosource');
While v2 emphasizes ESM, CommonJS is still supported. Ensure you are using a default require, not a destructured named require, as `toSource` is the default export.
Type Definition
import type toSource from 'tosource';
The package ships with TypeScript type definitions. Use `import type` to import the type for the default `toSource` function in TypeScript projects.

Demonstrates serialization of various JavaScript types, including functions, regular expressions, dates, Map, Set, and handling of circular references by marking them.

import toSource from 'tosource'; const complexObject = [ 4, 5, 6, 'hello', { a: 2, b: 3, '1': 4, if: 5, yes: true, no: false, nan: NaN, infinity: Infinity, undefined: undefined, null: null, foo: function (bar) { console.log('woo! a is ' + this.a); console.log('and bar is ' + bar); }, }, /we$/gi, new Date('Wed, 09 Aug 1995 00:00:00 GMT'), new Map([['key1', 'value1'], ['key2', 123]]), new Set([1, 2, 'three']) ]; console.log('Serialized Complex Object:\n', toSource(complexObject)); // Example with a circular reference (tosource handles it by marking) const objWithCircularRef = { id: 1 }; objWithCircularRef.self = objWithCircularRef; objWithCircularRef.nested = { child: objWithCircularRef }; console.log('\nSerialized Object with Circular Reference:\n', toSource(objWithCircularRef));
Debug
Known issues
breakingVersion 2.x introduces a minimum Node.js requirement of 10.x. Older Node.js environments are not supported.
fix
Upgrade your Node.js environment to version 10 or higher. For production, consider using a stable LTS version.
affects: >=2.0.0-alpha.1
breakingThe handling of negative zero (`-0`) was fixed in `v2.0.0-alpha.3` and now correctly uses `Object.is` for comparison during serialization. This might subtly change output if your application relied on previous serialization behavior for negative zero.
fix
Review code that processes serialized output potentially containing negative zero to ensure compatibility with `Object.is` semantics.
affects: >=2.0.0-alpha.3
gotchaFunctions are serialized by calling their `toString()` method. This means only the function's source code is preserved; its lexical environment (closures) and bound `this` context are not serialized.
fix
Be aware that functions serialized by `tosource` are effectively re-created from source when evaluated. Do not rely on them to maintain runtime state or closures from the original context.
affects: >=1.0.0
gotchaMultiple references to the same object in the input will result in multiple independent copies in the serialized output, rather than maintaining shared references.
fix
Understand that the deserialized object graph will not preserve referential equality for objects that were referenced multiple times in the original structure, unless they form a circular reference (which is handled differently).
affects: >=1.0.0
gotchaCircular references within objects are detected and serialized as `{$circularReference:true}`. Attempting to deserialize and execute this without custom handling will result in an object literal, not the original circular structure.
fix
Implement custom logic on the consuming end if you need to reconstruct circular references, or ensure your data structures do not contain them if exact reconstruction is critical.
affects: >=1.0.0
gotchaThe package is currently in an alpha state (`2.0.0-alpha.3`). APIs might change without a full major version bump, and it may contain unresolved bugs. It is not recommended for critical production environments without thorough testing.
fix
Proceed with caution, monitor release notes for breaking changes, and thoroughly test in your specific environment before deploying to production. Consider locking to a specific alpha version.
affects: >=2.0.0-alpha.1
Errors
Common errors & fixes
ReferenceError: toSource is not defined
Incorrect import statement or attempting to use `toSource` before it's properly imported/required.
fix
For ESM, use `import toSource from 'tosource';`. For CommonJS, use `const toSource = require('tosource');`. Ensure `toSource` is within scope.
TypeError: tosource is not a function
Often occurs when using a named import (e.g., `import { toSource } from 'tosource';`) instead of the default import for ESM, or a destructured require for CJS, as `toSource` is a default export.
fix
Use the default import for ESM (`import toSource from 'tosource';`) or a standard `require` for CJS (`const toSource = require('tosource');`).
ERR_REQUIRE_ESM: Must use import to load ES Module
Attempting to use `require()` to import `tosource` in a pure ESM context (e.g., in a package configured with `"type": "module"` in `package.json`).
fix
Switch to `import toSource from 'tosource';` if your environment supports ESM. If you must use CommonJS, ensure your environment is configured for CJS modules.
Node.js version mismatch
The installed Node.js version is below the minimum requirement (10.x) for `tosource` v2.x.
fix
Upgrade your Node.js runtime to version 10 or higher. You can use tools like `nvm` (Node Version Manager) to manage multiple Node.js versions.
Upgrade
Version history
2.0.0-alpha.3latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
7 hits · last 30 days
node
6
OpenAI (training)
1
Resources
tosource — npm install tosource · libregistry