New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

seroval

Package Overview
Dependencies
Maintainers
1
Versions
65
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

seroval

Stringify JS values

  • 0.4.0-alpha.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
169K
decreased by-32.95%
Maintainers
1
Weekly downloads
 
Created
Source

seroval

Stringify JS values

NPM JavaScript Style Guide

Install

npm install --save seroval
yarn add seroval
pnpm add seroval

Usage

import { serialize } from 'seroval';

const object = {
  number: [Math.random(), -0, NaN, Infinity, -Infinity],
  string: ['hello world', '<script>Hello World</script>'],
  boolean: [true, false],
  null: null,
  undefined: undefined,
  bigint: 9007199254740991n,
  array: [,,,], // holes
  regexp: /[a-z0-9]+/i,
  date: new Date(),
  map: new Map([['hello', 'world']]),
  set: new Set(['hello', 'world']),
};

// self cyclic references
// recursive objects
object.self = object;
// recursive arrays
object.array.push(object.array);
// recursive maps
object.map.set('self', object.map);
// recursive sets
object.set.add(object.set);

// mutual cyclic references
object.array.push(object.map);
object.map.set('mutual', object.set);
object.set.add(object.array);

const result = serialize(object);

Output (as a string):

((h,j,k,m)=>(m={number:[0.5623457676854244,-0,NaN,1/0,-1/0],string:["hello world","\x3Cscript>Hello World\x3C/script>"],boolean:[!0,!1],null:null,undefined:void 0,bigint:9007199254740991n,array:h=[,,,,j=new Map([["hello","world"],["mutual",k=new Set(["hello","world"])]])],regexp:/[a-z0-9]+/i,date:new Date("2023-03-14T11:16:24.879Z"),map:j,set:k},h[3]=h,j.set("self",j),k.add(k).add(h),m.self=m,m))()

// Formatted for readability
((h, j, k, m) => (m = {
  number: [0.5623457676854244, -0, NaN, 1 / 0, -1 / 0],
  string: ["hello world", "\x3Cscript>Hello World\x3C/script>"],
  boolean: [!0, !1],
  null: null,
  undefined: void 0,
  bigint: 9007199254740991n,
  array: h = [, , , , j = new Map([
    ["hello", "world"],
    ["mutual", k = new Set(["hello", "world"])]
  ])],
  regexp: /[a-z0-9]+/i,
  date: new Date("2023-03-14T11:16:24.879Z"),
  map: j,
  set: k
}, h[3] = h, j.set("self", j), k.add(k).add(h), m.self = m, m))()

Mutual cyclic example

import { serialize } from 'seroval';

const a = new Map([['name', 'a']]);
const b = new Map([['name', 'b']]);
const c = new Map([['name', 'c']]);
const d = new Map([['name', 'd']]);

c.set('left', a);
d.set('left', a);
c.set('right', b);
d.set('right', b);
a.set('children', [c, d]);
b.set('children', [c, d]);

const result = serialize({ a, b, c, d });

Output (as a string):

((h,j,k,m,o,q)=>(q={a:h=new Map([["name","a"],["children",[j=new Map([["name","c"],["right",o=new Map([["name","b"],["children",k=[,m=new Map([["name","d"]])]]])]]),m]]]),b:o,c:j,d:m},j.set("left",h),k[0]=j,m.set("left",h).set("right",o),q))()

// Formatted
((h, j, k, m, o, q) => (q = {
  a: h = new Map([
    ["name", "a"],
    ["children", [j = new Map([
      ["name", "c"],
      ["right", o = new Map([
        ["name", "b"],
        ["children", k = [, m = new Map([
          ["name", "d"]
        ])]]
      ])]
    ]), m]]
  ]),
  b: o,
  c: j,
  d: m
}, j.set("left", h), k[0] = j, m.set("left", h).set("right", o), q))()

Deserialization

import { serialize, deserialize } from 'seroval';

const value = undefined;
console.log(deserialize(serialize(value)) === value);

Promise serialization

seroval allows Promise serialization through serializeAsync.

import { serializeAsync } from 'seroval';

const value = Promise.resolve(100);

const result = await serializeAsync(value); // "Promise.resolve(100)"

console.log(await deserialize(result)); // 100

Note seroval can only serialize the resolved value and so the output will always be using Promise.resolve. If the Promise fulfills with rejection, the rejected value is thrown before serialization happens.

Supports

The following values are the only values accepted by seroval:

  • Exact values
    • NaN
    • Infinity
    • -Infinity
    • -0
  • Primitives
    • number
    • string
    • boolean
    • null
    • undefined
    • bigint
  • Array + holes
  • Object
    • RegExp
    • Date
    • Map
    • Set
  • TypedArray
    • Int8Array
    • Int16Array
    • Int32Array
    • Uint8Array
    • Uint16Array
    • Uint32Array
    • Uint8ClampedArray
    • Float32Array
    • Float64Array
    • BigInt64Array
    • BigUint64Array
  • Error
    • AggregateError
    • EvalError
    • RangeError
    • ReferenceError
    • SyntaxError
    • TypeError
    • URIError
  • Promise (with serializeAsync)
  • Iterable
  • Cyclic references (both self and mutual)

Compat

serialize and serializeAsync can accept a { target: string | string[] } options. The target property decides what the serialization output would look like. The default target is es2023.

import { serialize } from 'seroval';

const y = Object.create(null);
y.self = y;
y.example = 'Hello World';

function serializeWithTarget(value, target) {
  console.log('Target is', target)
  const result = serialize(value, {
    target,
  });
  console.log(result);
}

serializeWithTarget(y, 'es5');
serializeWithTarget(y, 'es2023');

Output

Target is es5
(function(h){return (h=Object.create(null),h.self=h,h.example="Hello World",h)})()
Target is es2023
(h=>(h=Object.assign(Object.create(null),{example:"Hello World"}),h.self=h,h))()

You can also combine targets:

serialize(value, {
  targets: ['chrome85', 'edge85'],
});

Supported runtimes:

  • es
    • Valid values are es5, es6 and above (e.g. es2020).
  • Desktop
    • chrome
    • edge
    • safari
    • firefox
    • opera
  • Mobile
    • ios
    • samsung
  • Runtimes
    • deno
    • node

Note Version for runtimes excluding es can use semver format (major.minor.patch) e.g. chrome110, node0.12

Feature flags and compat attempt:

  • AggregateError
    • Compiles down to Error instead.
  • Array.prototype.values
    • Used for iterables, uses Symbol.iterator instead.
  • Arrow functions
    • Uses function expressions for top-level, and either method shorthands or function expressions for iterables.
  • BigInt
    • Throws when attempted to use, includes BigInt64Array and BigUint64Array
  • Map
    • Throws when attempted to use.
  • Method shorthands
    • Uses function expressions instead.
  • Object.assign
    • Uses manual object assignments instead.
  • Promise
    • Throws when attempted to use, specially in serializeAsync.
  • Set
    • Throws when attempted to use.
  • Symbol.iterator
    • Throws when attempted to use.
  • TypedArray
    • Throws when attempted to use.

Sponsors

Sponsors

License

MIT © lxsmnsyc

Keywords

FAQs

Package last updated on 14 Mar 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc