Giter Club home page Giter Club logo

node-tosource's Introduction

node-tosource

Actions Status npm version codecov

toSource is a super simple function that converts JavaScript objects back to source code.

Introduction

Motivation: JSON doesn't support serializing functions, dates, or regular expressions. I wanted a quick and simple way to push trusted data structures with code from Node down to the browser.

This should make it easier to share code and modules between the server and client.

Installation

npm install tosource

Examples

The following code:

import toSource from 'tosource';

console.log(
  toSource([
    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 ' + a);
        console.log('and bar is ' + bar);
      },
    },
    /we$/gi,
    new Date('Wed, 09 Aug 1995 00:00:00 GMT'),
  ]),
);

Output:

[ 4,
  5,
  6,
  "hello",
  { 1:4,
    a:2,
    b:3,
    "if":5,
    yes:true,
    no:false,
    nan:NaN,
    infinity:Infinity,
    "undefined":undefined,
    "null":null,
    foo:function (bar) {
        console.log('woo! a is ' + a);
        console.log('and bar is ' + bar);
      } },
  /we$/gi,
  new Date(807926400000) ]

See tosource.test.ts for more examples.

Supported Types

  • numbers (including NaN, Infinity, and -0)
  • strings
  • Arrays (including sparse arrays)
  • object literals
  • function
  • RegExp instances
  • Date instances
  • Map
  • Set
  • true / false
  • undefined
  • null

Notes

  • Functions are serialized with func.toString(), no closure properties are serialized
  • Multiple references to the same object become copies
  • Circular references are encoded as {$circularReference:true}

License

toSource is open source software under the zlib license.

node-tosource's People

Contributors

dependabot[bot] avatar dotboris avatar esco avatar johnjohndoe avatar kapouer avatar marcello3d avatar rich-harris avatar sapphi-red avatar unbyte avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

node-tosource's Issues

Always resolves to CJS even when using ESM

When using the usual ESM stuff, I still resolve to index.js instead of index.esm.js.

import { createRequire } from "node:module";
const require = createRequire(import.meta.url);

console.table({
  "is-what": {
    esm: import.meta.resolve("is-what"),
    cjs: require.resolve("is-what"),
  },
  tosource: {
    esm: import.meta.resolve("tosource"),
    cjs: require.resolve("tosource"),
  },
});

(Using is-what as an example of it done OK-ly)

image

I think this could be solved by using modern exports: {} conditions instead of main and module? But even this is not recommended so as to avoid the dual package hazard https://nodejs.org/api/packages.html#packages_dual_package_hazard where you can get two copies of the package code in your webpack/vite/rollup/parcel/whatever bundle.js file.

The idealized solution is to either a) only export an ESM version or b) export an ESM wrapper that just export {} from "./module.cjs" so that there's only one canonical source of code or c) only export a CJS version.

Funnily enough, in the package's current state it doesn't suffer from the dual package hazard since it currently only exports CommonJS ๐Ÿคฃ

toSource(new RegExp("/slash/killed/me"))

Hi,

it gives //slash/killed/me/ which isn't evaluable.
just got bitten by this, using an old nodejs 0.10 + v8 3.14 version from debian.
Maybe 0.12 or io.js don't have that problem (i.e. properly escape regexp toString).

install instructions

It is not obvious how to use npm to install this... since the github project name is different than the npm name...

Just might save your more ignorant users (like me) some forehead wrinkling...

Incorrect $circularReference

I don't have time to file a PR right now but can try and do so later - just thought I'd flag this in the meantime:

foo = [];
obj = { foo: foo, bar: foo };

toSource( obj );
// -> "{ foo:[  ], bar:{$circularReference:1} }"

Expected would be { foo:[], bar:[] } since foo doesn't contain bar.

Array with hole support

Array with last element as a hole will generate wrong output.

eval(tosource(Array(3))).length // should be 3, but get 2 

Fix native code

In my case, the output contains function () { [native code] } so that it's invalid to be read by the browser.

Issue with license

Hello,

We want to use the tosource package, but in NPM, the license is showing as "none" on the right hand side(under weekly downloads).

Because of this our automated package checker is unable to download and rejecting the package I guess. Could you please help update the license on NPM?

Thanks a lot!!! @marcello3d

NPM package is missing `dist` folder

Package on NPM ([email protected]) is missing the dist folder, so does not function.

The NPM package also includes src folder, which is unnecessary. It could be excluded from the NPM release with a files field in package.json, or an .npmignore file.

toSource(new Error)

Is it possible?

I want to catch and rewrite it as 'console.trace(' + toSource(e) + ')'

Change double quotes to single quotes

Standard on Javascript for source code are the single quotes (') instead of the double quote (") to distingish from HTML attributes, and in fact Node.js use single quotes when showing an object on the console. Double quoted strings has the advantage that they can be easily generated with JSON.stringify(), but it should be better to use single quotes and the encode() function or another similar one.

Numbers casted to Strings

Hi,

I want to inject the following options to a google chart within an html page:
slices: { 0: { color: 'yellow' }, 1: { color: 'transparent' } }
(see gchart help)

So I first build a slice object:

slices= {};
slices[0]={ color: 'yellow' }; 
slices[1]={ color: 'transparent' };

Then I call toSource(slices) and get the following result:

{ "0":{ color:"yellow" }, "1":{ color:"transparent" } }

Sadly, google charts doesnt like the String keys instead of integers. I'll find a workaround for that, but I think toSource is misbehaviying. I know it is not really part of a standard, but I can't see why the integers should get casted into Strings. Firefox's toSource() is keeping integers as integers, I think it would make more sense to do so.

support string templates

toSource(`test${process.env.HOME}`)

i'm not sure it's possible.

Luckily

toSource(function() {`test${process.env.HOME}`})

already works all right.

Make a polyfill

Split the code in several functions and set it to the prototype object of the diferent classes to polyfill the functionality that Firefox offer. The current tosource() could still be exported to be backwards compatible, only that internally would call the per-object functions.

Support Map when keys are strings

Hi, first off: thanks for the nice piece of code!

My issue:

m = new Map
m.set("key1", 42)
m.set("key2", "some value")
toSource(m)

Returns "{}"
It would be nice if it returned
{"key1": 42, "key2": "some value"}

Any chance you would have time to implement something like this?

Negative zero support

tosource(-0) should return '-0' instead of '0'

Object.is(eval(tosource(-0)), -0); // should be true

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.