Socket
Socket
Sign inDemoInstall

serialize-to-js

Package Overview
Dependencies
Maintainers
1
Versions
24
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

serialize-to-js - npm Package Compare versions

Comparing version 3.0.2 to 3.0.3

jest.config.js

138

lib/index.js

@@ -5,9 +5,7 @@ /*

*/
'use strict'; // dependencies
'use strict'
var utils = require('./internal/utils');
// dependencies
var util = require('./internal/utils')
var Ref = require('./internal/reference')
var Ref = require('./internal/reference');
/**

@@ -17,4 +15,4 @@ * serializes an object to javascript

* @example <caption>serializing regex, date, buffer, ...</caption>
* var serialize = require('serialize-to-js').serialize;
* var obj = {
* const serialize = require('serialize-to-js').serialize;
* const obj = {
* str: '<script>var a = 0 > 1</script>',

@@ -35,6 +33,6 @@ * num: 3.1415,

* @example <caption>serializing while respecting references</caption>
* var serialize = require('serialize-to-js').serialize;
* var obj = { object: { regexp: /^test?$/ } };
* const serialize = require('serialize-to-js').serialize;
* const obj = { object: { regexp: /^test?$/ } };
* obj.reference = obj.object;
* var opts = { reference: true };
* const opts = { reference: true };
* console.log(serialize(obj, opts));

@@ -52,83 +50,91 @@ * //> {object: {regexp: /^test?$/}}

*/
function serialize (source, opts) {
var out = ''
var key
var tmp
var type
var i
opts = opts || {}
function serialize(source, opts) {
var type;
opts = opts || {};
if (!opts._visited) {
opts._visited = []
opts._visited = [];
}
if (!opts._refs) {
opts.references = []
opts._refs = new Ref(opts.references)
opts.references = [];
opts._refs = new Ref(opts.references, opts);
}
if (util.isNull(source)) {
out += 'null'
} else if (util.isArray(source)) {
tmp = source.map(function (item) {
return serialize(item, opts)
})
out += '[' + tmp.join(', ') + ']'
} else if (util.isFunction(source)) {
tmp = source.toString()
// append function to es6 function within obj
out += !/^\s*(function|\([^)]*\)\s*=>)/m.test(tmp) ? 'function ' + tmp : tmp
} else if (util.isObject(source)) {
if (util.isRegExp(source)) {
out += 'new RegExp("' + source.source.replace(/<\/script/ig, '<\\/script') + '", "' + source.flags + '")'
} else if (util.isDate(source)) {
out += 'new Date("' + source.toJSON() + '")'
} else if (util.isError(source)) {
out += 'new Error(' + (source.message ? '"' + source.message + '"' : '') + ')'
} else if (util.isBuffer(source)) {
if (utils.isNull(source)) {
return 'null';
} else if (Array.isArray(source)) {
var tmp = source.map(function (item) {
return serialize(item, opts);
});
return "[".concat(tmp.join(', '), "]");
} else if (utils.isFunction(source)) {
// serializes functions only in unsafe mode!
var _tmp = source.toString();
var _tmp2 = opts.unsafe ? _tmp : utils.saferFunctionString(_tmp, opts); // append function to es6 function within obj
return !/^\s*(function|\([^)]*?\)\s*=>)/m.test(_tmp2) ? 'function ' + _tmp2 : _tmp2;
} else if (utils.isObject(source)) {
if (utils.isRegExp(source)) {
return "new RegExp(".concat(utils.quote(source.source, opts), ", \"").concat(source.flags, "\")");
} else if (utils.isDate(source)) {
return "new Date(".concat(utils.quote(source.toJSON(), opts), ")");
} else if (utils.isError(source)) {
return "new Error(".concat(utils.quote(source.message, opts), ")");
} else if (utils.isBuffer(source)) {
// check for buffer first otherwise tests fail on node@4.4
// looks like buffers are accidentially detected as typed arrays
out += "Buffer.from('" + source.toString('base64') + "', 'base64')"
} else if ((type = util.isTypedArray(source))) {
tmp = []
for (i = 0; i < source.length; i++) {
tmp.push(source[i])
return "Buffer.from('".concat(source.toString('base64'), "', 'base64')");
} else if (type = utils.isTypedArray(source)) {
var _tmp3 = [];
for (var i = 0; i < source.length; i++) {
_tmp3.push(source[i]);
}
out += 'new ' + type + '(' +
'[' + tmp.join(', ') + ']' +
')'
return "new ".concat(type, "([").concat(_tmp3.join(', '), "])");
} else {
tmp = []
// copy properties if not circular
var _tmp4 = []; // copy properties if not circular
if (!~opts._visited.indexOf(source)) {
opts._visited.push(source)
for (key in source) {
if (source.hasOwnProperty(key)) {
if (opts.reference && util.isObject(source[key])) {
opts._refs.push(key)
opts._visited.push(source);
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
if (opts.reference && utils.isObject(source[key])) {
opts._refs.push(key);
if (!opts._refs.hasReference(source[key])) {
tmp.push(Ref.wrapkey(key) + ': ' + serialize(source[key], opts))
_tmp4.push(Ref.wrapkey(key, opts) + ': ' + serialize(source[key], opts));
}
opts._refs.pop()
opts._refs.pop();
} else {
tmp.push(Ref.wrapkey(key) + ': ' + serialize(source[key], opts))
_tmp4.push(Ref.wrapkey(key, opts) + ': ' + serialize(source[key], opts));
}
}
}
out += '{' + tmp.join(', ') + '}'
opts._visited.pop()
opts._visited.pop();
return "{".concat(_tmp4.join(', '), "}");
} else {
if (opts.ignoreCircular) {
out += '{/*[Circular]*/}'
return '{/*[Circular]*/}';
} else {
throw new Error('can not convert circular structures.')
throw new Error('can not convert circular structures.');
}
}
}
} else if (util.isString(source)) {
out += '"' + (opts.unsafe ? util.unsafeString(source) : util.safeString(source)) + '"'
} else if (utils.isString(source)) {
return utils.quote(source, opts);
} else {
out += '' + source
return '' + source;
}
return out
}
module.exports = serialize
module.exports = serialize;

@@ -5,7 +5,7 @@ /*

*/
'use strict';
'use strict'
var utils = require('./utils');
var KEY = /^[a-zA-Z$_][a-zA-Z$_0-9]*$/
var KEY = /^[a-zA-Z$_][a-zA-Z$_0-9]*$/;
/**

@@ -15,10 +15,12 @@ * handle references

* @param {Object} references
* @param {boolean} opts.unsafe
*/
function Ref (references) {
this.keys = []
this.refs = []
this.key = []
this.references = references || []
function Ref(references, opts) {
this.keys = [];
this.refs = [];
this.key = [];
this.references = references || [];
this._opts = opts || {};
}
/**

@@ -30,6 +32,8 @@ * wrap an object key

*/
Ref.wrapkey = function (key) {
return (KEY.test(key) ? key : '"' + key.replace(/"/g, '\\"') + '"')
}
Ref.wrapkey = function (key, opts) {
return KEY.test(key) ? key : utils.quote(key, opts);
};
Ref.prototype = {

@@ -40,19 +44,24 @@ /**

*/
push: function (key) {
this.key.push(key)
push: function push(key) {
this.key.push(key);
},
/**
* remove the last key from internal array
*/
pop: function () {
this.key.pop()
pop: function pop() {
this.key.pop();
},
/**
* join the keys
*/
join: function (key) {
var out = ''
key = key || this.key
join: function join(key) {
var _this = this;
var out = '';
key = key || this.key;
if (typeof key === 'string') {
key = [key]
key = [key];
}

@@ -62,9 +71,10 @@

if (KEY.test(k)) {
out += '.' + k
out += '.' + k;
} else {
out += '[' + Ref.wrapkey(k) + ']'
out += '[' + Ref.wrapkey(k, _this._opts) + ']';
}
})
return out
});
return out;
},
/**

@@ -76,12 +86,14 @@ * check if object `source` has an already known reference.

*/
hasReference: function (source) {
var idx
hasReference: function hasReference(source) {
var idx;
if (~(idx = this.refs.indexOf(source))) {
this.references.push([this.join(), this.keys[idx]])
return true
this.references.push([this.join(), this.keys[idx]]);
return true;
} else {
this.refs.push(source)
this.keys.push(this.join())
this.refs.push(source);
this.keys.push(this.join());
}
},
/**

@@ -91,7 +103,6 @@ * get the references array

*/
getReferences: function () {
return this.references
getReferences: function getReferences() {
return this.references;
}
}
module.exports = Ref
};
module.exports = Ref;

@@ -1,10 +0,7 @@

/* eslint
no-new-func: 0
*/
'use strict';
'use strict'
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
var UNSAFE_CHARS_REGEXP = /[\\\r\n\t<>\u2028\u2029"/]/g
var CHARS_REGEXP = /[\\\r\n\t"]/g
var UNSAFE_CHARS_REGEXP = /[<>\u2028\u2029/\\\r\n\t"]/g;
var CHARS_REGEXP = /[\\\r\n\t"]/g;
var UNICODE_CHARS = {

@@ -15,96 +12,99 @@ '"': '\\"',

'\t': '\\t',
'\\': '\\\\',
'<': '\\u003C',
'>': '\\u003E',
'/': '\\u002F',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
}
'\\': "\\u005C",
'<': "\\u003C",
'>': "\\u003E",
'/': "\\u002F",
"\u2028": "\\u2028",
"\u2029": "\\u2029"
};
function safeString (str) {
str = str.replace(UNSAFE_CHARS_REGEXP, function (unsafeChar) {
return UNICODE_CHARS[unsafeChar]
})
return str
function safeString(str) {
return str.replace(UNSAFE_CHARS_REGEXP, function (unsafeChar) {
return UNICODE_CHARS[unsafeChar];
});
}
exports.safeString = safeString
function unsafeString (str) {
function unsafeString(str) {
str = str.replace(CHARS_REGEXP, function (unsafeChar) {
return UNICODE_CHARS[unsafeChar]
})
return str
return UNICODE_CHARS[unsafeChar];
});
return str;
}
exports.unsafeString = unsafeString
var isArray = exports.isArray = Array.isArray
exports.isArray = isArray
function quote(str, opts) {
var fn = opts.unsafe ? unsafeString : safeString;
return str ? "\"".concat(fn(str), "\"") : '';
}
function isString (arg) {
return typeof arg === 'string'
function saferFunctionString(str, opts) {
return opts.unsafe ? str : str.replace(/(<\/?)([a-z][^>]*?>)/ig, function (m, m1, m2) {
return safeString(m1) + m2;
});
}
exports.isString = isString
function isNull (arg) {
return arg === null
function objectToString(o) {
return Object.prototype.toString.call(o);
}
exports.isNull = isNull
function isRegExp (re) {
return isObject(re) && objectToString(re) === '[object RegExp]'
function toType(o) {
var type = objectToString(o);
return type.substring(8, type.length - 1);
}
exports.isRegExp = isRegExp
function isObject (arg) {
return typeof arg === 'object' && arg !== null
function isString(arg) {
return typeof arg === 'string';
}
exports.isObject = isObject
function isDate (d) {
return isObject(d) && objectToString(d) === '[object Date]'
function isNull(arg) {
return arg === null;
}
exports.isDate = isDate
function isError (e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error)
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isError = isError
function isFunction (arg) {
return typeof arg === 'function'
function isObject(arg) {
return _typeof(arg) === 'object' && arg !== null;
}
exports.isFunction = isFunction
function isBuffer (arg) {
return arg instanceof Buffer
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isBuffer = isBuffer
var TYPED_ARRAYS = [
'Int8Array',
'Uint8Array',
'Uint8ClampedArray',
'Int16Array',
'Uint16Array',
'Int32Array',
'Uint32Array',
'Float32Array',
'Float64Array'
]
function isError(e) {
return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error);
}
function isTypedArray (arg) {
var type = toType(arg)
if (TYPED_ARRAYS.indexOf(type) !== -1) {
return type
}
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isTypedArray = isTypedArray
function objectToString (o) {
return Object.prototype.toString.call(o)
function isBuffer(arg) {
return arg instanceof Buffer;
}
function toType (o) {
return objectToString(o).replace(/^\[object (.*)\]$/, '$1')
var TYPED_ARRAYS = ['Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array'];
function isTypedArray(arg) {
var type = toType(arg);
if (TYPED_ARRAYS.indexOf(type) !== -1) {
return type;
}
}
module.exports = {
safeString: safeString,
unsafeString: unsafeString,
quote: quote,
saferFunctionString: saferFunctionString,
isString: isString,
isNull: isNull,
isRegExp: isRegExp,
isObject: isObject,
isDate: isDate,
isError: isError,
isFunction: isFunction,
isBuffer: isBuffer,
isTypedArray: isTypedArray
};
{
"name": "serialize-to-js",
"version": "3.0.2",
"version": "3.0.3",
"description": "serialize objects to javascript",

@@ -21,2 +21,3 @@ "keywords": [

"main": "lib",
"module": "src",
"directories": {

@@ -27,6 +28,7 @@ "lib": "lib",

"scripts": {
"all": "npm run lint && npm test",
"clean": "rimraf doc coverage .nyc_output node_modules *.tgz",
"all": "npm run clean && npm run lint && npm run build && npm test",
"build": "babel -d lib src",
"clean": "rimraf lib doc coverage .nyc_output *.tgz",
"coverage": "nyc -r text -r html npm test",
"lint": "eslint lib test",
"lint": "eslint src test",
"prepublishOnly": "npm run all",

@@ -36,3 +38,11 @@ "readme": "markedpp --githubid -i README.md -o README.md",

},
"babel": {
"presets": [
"@babel/preset-env"
]
},
"eslintConfig": {
"env": {
"mocha": true
},
"extends": "standard",

@@ -48,11 +58,14 @@ "plugins": [

"devDependencies": {
"eslint": "^5.16.0",
"eslint-config-standard": "^12.0.0",
"eslint-plugin-import": "^2.17.2",
"eslint-plugin-node": "^9.1.0",
"eslint-plugin-promise": "^4.1.1",
"eslint-plugin-standard": "^4.0.0",
"mocha": "^6.1.4",
"@babel/cli": "^7.7.5",
"@babel/core": "^7.7.5",
"@babel/preset-env": "^7.7.6",
"eslint": "^6.7.2",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-import": "^2.19.1",
"eslint-plugin-node": "^10.0.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"mocha": "^6.2.2",
"nyc": "^14.1.1",
"rimraf": "^2.6.3"
"rimraf": "^3.0.0"
},

@@ -59,0 +72,0 @@ "engines": {

@@ -28,3 +28,3 @@ # serialize-to-js

> package at [serialize-to-module][]
>
>
> Migrating from 2.x to 3.x for serialize:

@@ -44,2 +44,3 @@ > ```js

* [serialize](#serialize)
* [serializeToModule](#serializetomodule)
* [Contribution and License Agreement](#contribution-and-license-agreement)

@@ -46,0 +47,0 @@ * [License](#license)

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