{"id":12156,"library":"tosource","title":"tosource: Object to Source Code Converter","description":"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.","status":"active","version":"2.0.0-alpha.3","language":"javascript","source_language":"en","source_url":"git://github.com/marcello3d/node-tosource","tags":["javascript","source","tosource","json","javascript object","object","typescript"],"install":[{"cmd":"npm install tosource","lang":"bash","label":"npm"},{"cmd":"yarn add tosource","lang":"bash","label":"yarn"},{"cmd":"pnpm add tosource","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"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.","wrong":"import { toSource } from 'tosource';","symbol":"toSource (ESM Default)","correct":"import toSource from 'tosource';"},{"note":"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.","wrong":"const { toSource } = require('tosource');","symbol":"toSource (CommonJS)","correct":"const toSource = require('tosource');"},{"note":"The package ships with TypeScript type definitions. Use `import type` to import the type for the default `toSource` function in TypeScript projects.","symbol":"Type Definition","correct":"import type toSource from 'tosource';"}],"quickstart":{"code":"import toSource from 'tosource';\n\nconst complexObject = [\n  4,\n  5,\n  6,\n  'hello',\n  {\n    a: 2,\n    b: 3,\n    '1': 4,\n    if: 5,\n    yes: true,\n    no: false,\n    nan: NaN,\n    infinity: Infinity,\n    undefined: undefined,\n    null: null,\n    foo: function (bar) {\n      console.log('woo! a is ' + this.a);\n      console.log('and bar is ' + bar);\n    },\n  },\n  /we$/gi,\n  new Date('Wed, 09 Aug 1995 00:00:00 GMT'),\n  new Map([['key1', 'value1'], ['key2', 123]]),\n  new Set([1, 2, 'three'])\n];\n\nconsole.log('Serialized Complex Object:\\n', toSource(complexObject));\n\n// Example with a circular reference (tosource handles it by marking)\nconst objWithCircularRef = { id: 1 };\nobjWithCircularRef.self = objWithCircularRef;\nobjWithCircularRef.nested = { child: objWithCircularRef };\n\nconsole.log('\\nSerialized Object with Circular Reference:\\n', toSource(objWithCircularRef));","lang":"typescript","description":"Demonstrates serialization of various JavaScript types, including functions, regular expressions, dates, Map, Set, and handling of circular references by marking them."},"warnings":[{"fix":"Upgrade your Node.js environment to version 10 or higher. For production, consider using a stable LTS version.","message":"Version 2.x introduces a minimum Node.js requirement of 10.x. Older Node.js environments are not supported.","severity":"breaking","affected_versions":">=2.0.0-alpha.1"},{"fix":"Review code that processes serialized output potentially containing negative zero to ensure compatibility with `Object.is` semantics.","message":"The 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.","severity":"breaking","affected_versions":">=2.0.0-alpha.3"},{"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.","message":"Functions 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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).","message":"Multiple references to the same object in the input will result in multiple independent copies in the serialized output, rather than maintaining shared references.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"Circular 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"The 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.","severity":"gotcha","affected_versions":">=2.0.0-alpha.1"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"For ESM, use `import toSource from 'tosource';`. For CommonJS, use `const toSource = require('tosource');`. Ensure `toSource` is within scope.","cause":"Incorrect import statement or attempting to use `toSource` before it's properly imported/required.","error":"ReferenceError: toSource is not defined"},{"fix":"Use the default import for ESM (`import toSource from 'tosource';`) or a standard `require` for CJS (`const toSource = require('tosource');`).","cause":"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.","error":"TypeError: tosource is not a function"},{"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.","cause":"Attempting to use `require()` to import `tosource` in a pure ESM context (e.g., in a package configured with `\"type\": \"module\"` in `package.json`).","error":"ERR_REQUIRE_ESM: Must use import to load ES Module"},{"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.","cause":"The installed Node.js version is below the minimum requirement (10.x) for `tosource` v2.x.","error":"Node.js version mismatch"}],"ecosystem":"npm"}