pax_global_header00006660000000000000000000000064131324065670014521gustar00rootroot0000000000000052 comment=11fdd024ab3829f1b22d1ea76e4f7671b1f6df22 serialize-javascript-1.4.0/000077500000000000000000000000001313240656700156565ustar00rootroot00000000000000serialize-javascript-1.4.0/.gitignore000066400000000000000000000000431313240656700176430ustar00rootroot00000000000000artifacts/ coverage/ node_modules/ serialize-javascript-1.4.0/.npmignore000066400000000000000000000000751313240656700176570ustar00rootroot00000000000000artifacts/ coverage/ test/ .gitignore .npmignore .travis.yml serialize-javascript-1.4.0/.travis.yml000066400000000000000000000000711313240656700177650ustar00rootroot00000000000000language: node_js node_js: - "4" - "6" - "8" serialize-javascript-1.4.0/LICENSE000066400000000000000000000027161313240656700166710ustar00rootroot00000000000000Copyright 2014 Yahoo! Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yahoo! Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. serialize-javascript-1.4.0/README.md000066400000000000000000000110731313240656700171370ustar00rootroot00000000000000Serialize JavaScript ==================== Serialize JavaScript to a _superset_ of JSON that includes regular expressions, dates and functions. [![npm Version][npm-badge]][npm] [![Dependency Status][david-badge]][david] [![Build Status][travis-badge]][travis] ## Overview The code in this package began its life as an internal module to [express-state][]. To expand its usefulness, it now lives as `serialize-javascript` — an independent package on npm. You're probably wondering: **What about `JSON.stringify()`!?** We've found that sometimes we need to serialize JavaScript **functions**, **regexps** or **dates**. A great example is a web app that uses client-side URL routing where the route definitions are regexps that need to be shared from the server to the client. The string returned from this package's single export function is literal JavaScript which can be saved to a `.js` file, or be embedded into an HTML document by making the content of a `' }); ``` The above will produce the following string, HTML-escaped output which is safe to put into an HTML document as it will not cause the inline script element to terminate: ```js '{"haxorXSS":"\\u003C\\u002Fscript\\u003E"}' ``` ### Options The `serialize()` function accepts `options` as its second argument. There are two options, both default to being `undefined`: #### `options.space` This option is the same as the `space` argument that can be passed to [`JSON.stringify`][JSON.stringify]. It can be used to add whitespace and indentation to the serialized output to make it more readable. ```js serialize(obj, {space: 2}); ``` #### `options.isJSON` This option is a signal to `serialize()` that the object being serialized does not contain any function or regexps values. This enables a hot-path that allows serialization to be over 3x faster. If you're serializing a lot of data, and know its pure JSON, then you can enable this option for a speed-up. **Note:** That when using this option, the output will still be escaped to protect against XSS. ```js serialize(obj, {isJSON: true}); ``` ## Deserializing For some use cases you might also need to deserialize the string. This is explicitely not part of this module. However, you can easily write it yourself: ```js function deserialize(serializedJavascript){ return eval('(' + serializedJavascript + ')'); } ``` **Note:** Don't forget the parentheses around the serialized javascript, as the opening bracket `{` will be considered to be the start of a body. ## License This software is free to use under the Yahoo! Inc. BSD license. See the [LICENSE file][LICENSE] for license text and copyright information. [npm]: https://www.npmjs.org/package/serialize-javascript [npm-badge]: https://img.shields.io/npm/v/serialize-javascript.svg?style=flat-square [david]: https://david-dm.org/yahoo/serialize-javascript [david-badge]: https://img.shields.io/david/yahoo/serialize-javascript.svg?style=flat-square [travis]: https://travis-ci.org/yahoo/serialize-javascript [travis-badge]: https://img.shields.io/travis/yahoo/serialize-javascript.svg?style=flat-square [express-state]: https://github.com/yahoo/express-state [JSON.stringify]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify [LICENSE]: https://github.com/yahoo/serialize-javascript/blob/master/LICENSE serialize-javascript-1.4.0/index.js000066400000000000000000000074531313240656700173340ustar00rootroot00000000000000/* Copyright (c) 2014, Yahoo! Inc. All rights reserved. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ 'use strict'; // Generate an internal UID to make the regexp pattern harder to guess. var UID = Math.floor(Math.random() * 0x10000000000).toString(16); var PLACE_HOLDER_REGEXP = new RegExp('"@__(F|R|D)-' + UID + '-(\\d+)__@"', 'g'); var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g; var UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g; // Mapping of unsafe HTML and invalid JavaScript line terminator chars to their // Unicode char counterparts which are safe to use in JavaScript strings. var ESCAPED_CHARS = { '<' : '\\u003C', '>' : '\\u003E', '/' : '\\u002F', '\u2028': '\\u2028', '\u2029': '\\u2029' }; function escapeUnsafeChars(unsafeChar) { return ESCAPED_CHARS[unsafeChar]; } module.exports = function serialize(obj, options) { options || (options = {}); // Backwards-compatability for `space` as the second argument. if (typeof options === 'number' || typeof options === 'string') { options = {space: options}; } var functions = []; var regexps = []; var dates = []; // Returns placeholders for functions and regexps (identified by index) // which are later replaced by their string representation. function replacer(key, value) { if (!value) { return value; } // If the value is an object w/ a toJSON method, toJSON is called before // the replacer runs, so we use this[key] to get the non-toJSONed value. var origValue = this[key]; var type = typeof origValue; if (type === 'object') { if(origValue instanceof RegExp) { return '@__R-' + UID + '-' + (regexps.push(origValue) - 1) + '__@'; } if(origValue instanceof Date) { return '@__D-' + UID + '-' + (dates.push(origValue) - 1) + '__@'; } } if (type === 'function') { return '@__F-' + UID + '-' + (functions.push(origValue) - 1) + '__@'; } return value; } var str; // Creates a JSON string representation of the value. // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args. if (options.isJSON && !options.space) { str = JSON.stringify(obj); } else { str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space); } // Protects against `JSON.stringify()` returning `undefined`, by serializing // to the literal string: "undefined". if (typeof str !== 'string') { return String(str); } // Replace unsafe HTML and invalid JavaScript line terminator chars with // their safe Unicode char counterpart. This _must_ happen before the // regexps and functions are serialized and added back to the string. str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars); if (functions.length === 0 && regexps.length === 0 && dates.length === 0) { return str; } // Replaces all occurrences of function, regexp and date placeholders in the // JSON string with their string representations. If the original value can // not be found, then `undefined` is used. return str.replace(PLACE_HOLDER_REGEXP, function (match, type, valueIndex) { if (type === 'D') { return "new Date(\"" + dates[valueIndex].toISOString() + "\")"; } if (type === 'R') { return regexps[valueIndex].toString(); } var fn = functions[valueIndex]; var serializedFn = fn.toString(); if (IS_NATIVE_CODE_REGEXP.test(serializedFn)) { throw new TypeError('Serializing native function: ' + fn.name); } return serializedFn; }); } serialize-javascript-1.4.0/package.json000066400000000000000000000016651313240656700201540ustar00rootroot00000000000000{ "name": "serialize-javascript", "version": "1.4.0", "description": "Serialize JavaScript to a superset of JSON that includes regular expressions and functions.", "main": "index.js", "scripts": { "benchmark": "node -v && node test/benchmark/serialize.js", "test": "istanbul cover -- ./node_modules/mocha/bin/_mocha test/unit/ --reporter spec" }, "repository": { "type": "git", "url": "git+https://github.com/yahoo/serialize-javascript.git" }, "keywords": [ "serialize", "serialization", "javascript", "js", "json" ], "author": "Eric Ferraiuolo ", "license": "BSD-3-Clause", "bugs": { "url": "https://github.com/yahoo/serialize-javascript/issues" }, "homepage": "https://github.com/yahoo/serialize-javascript", "devDependencies": { "benchmark": "^1.0.0", "chai": "^1.9.1", "istanbul": "^0.3.2", "mocha": "^1.21.4", "xunit-file": "0.0.5" } } serialize-javascript-1.4.0/test/000077500000000000000000000000001313240656700166355ustar00rootroot00000000000000serialize-javascript-1.4.0/test/benchmark/000077500000000000000000000000001313240656700205675ustar00rootroot00000000000000serialize-javascript-1.4.0/test/benchmark/serialize.js000066400000000000000000000020421313240656700231120ustar00rootroot00000000000000'use strict'; var Benchmark = require('benchmark'); var serialize = require('../../'); var suiteConfig = { onStart: function (e) { console.log(e.currentTarget.name + ':'); }, onCycle: function (e) { console.log(String(e.target)); }, onComplete: function () { console.log(''); } }; // -- simpleOjb ---------------------------------------------------------------- var simpleObj = { foo: 'foo', bar: false, num: 100, arr: [1, 2, 3, 4], obj: {baz: 'baz'} }; new Benchmark.Suite('simpleObj', suiteConfig) .add('JSON.stringify( simpleObj )', function () { JSON.stringify(simpleObj); }) .add('JSON.stringify( simpleObj ) with replacer', function () { JSON.stringify(simpleObj, function (key, value) { return value; }); }) .add('serialize( simpleObj, {isJSON: true} )', function () { serialize(simpleObj, {isJSON: true}); }) .add('serialize( simpleObj )', function () { serialize(simpleObj); }) .run(); serialize-javascript-1.4.0/test/unit/000077500000000000000000000000001313240656700176145ustar00rootroot00000000000000serialize-javascript-1.4.0/test/unit/serialize.js000066400000000000000000000217271313240656700221520ustar00rootroot00000000000000/* global describe, it, beforeEach */ 'use strict'; var serialize = require('../../'), expect = require('chai').expect; describe('serialize( obj )', function () { it('should be a function', function () { expect(serialize).to.be.a('function'); }); describe('undefined', function () { it('should serialize `undefined` to a string', function () { expect(serialize()).to.be.a('string').equal('undefined'); expect(serialize(undefined)).to.be.a('string').equal('undefined'); }); it('should deserialize "undefined" to `undefined`', function () { expect(eval(serialize())).to.equal(undefined); expect(eval(serialize(undefined))).to.equal(undefined); }); }); describe('null', function () { it('should serialize `null` to a string', function () { expect(serialize(null)).to.be.a('string').equal('null'); }); it('should deserialize "null" to `null`', function () { expect(eval(serialize(null))).to.equal(null); }); }); describe('JSON', function () { var data; beforeEach(function () { data = { str : 'string', num : 0, obj : {foo: 'foo'}, arr : [1, 2, 3], bool: true, nil : null }; }); it('should serialize JSON to a JSON string', function () { expect(serialize(data)).to.equal(JSON.stringify(data)); }); it('should deserialize a JSON string to a JSON object', function () { expect(JSON.parse(serialize(data))).to.deep.equal(data); }); it('should serialize weird whitespace characters correctly', function () { var ws = String.fromCharCode(8232); expect(eval(serialize(ws))).to.equal(ws); }); }); describe('functions', function () { it('should serialize annonymous functions', function () { var fn = function () {}; expect(serialize(fn)).to.be.a('string').equal('function () {}'); }); it('should deserialize annonymous functions', function () { var fn; eval('fn = ' + serialize(function () {})); expect(fn).to.be.a('function'); }); it('should serialize named functions', function () { function fn() {} expect(serialize(fn)).to.be.a('string').equal('function fn() {}'); }); it('should deserialize named functions', function () { var fn; eval('fn = ' + serialize(function fn() {})); expect(fn).to.be.a('function'); expect(fn.name).to.equal('fn'); }); it('should serialize functions with arguments', function () { function fn(arg1, arg2) {} expect(serialize(fn)).to.equal('function fn(arg1, arg2) {}'); }); it('should deserialize functions with arguments', function () { var fn; eval('fn = ' + serialize(function (arg1, arg2) {})); expect(fn).to.be.a('function'); expect(fn.length).to.equal(2); }); it('should serialize functions with bodies', function () { function fn() { return true; } expect(serialize(fn)).to.equal('function fn() { return true; }'); }); it('should deserialize functions with bodies', function () { var fn; eval('fn = ' + serialize(function () { return true; })); expect(fn).to.be.a('function'); expect(fn()).to.equal(true); }); it('should throw a TypeError when serializing native built-ins', function () { var err; expect(Number.toString()).to.equal('function Number() { [native code] }'); try { serialize(Number); } catch (e) { err = e; } expect(err).to.be.an.instanceOf(TypeError); }); }); describe('regexps', function () { it('should serialize constructed regexps', function () { var re = new RegExp('asdf'); expect(serialize(re)).to.be.a('string').equal('/asdf/'); }); it('should deserialize constructed regexps', function () { var re = eval(serialize(new RegExp('asdf'))); expect(re).to.be.a('RegExp'); expect(re.source).to.equal('asdf'); }); it('should serialize literal regexps', function () { var re = /asdf/; expect(serialize(re)).to.be.a('string').equal('/asdf/'); }); it('should deserialize literal regexps', function () { var re = eval(serialize(/asdf/)); expect(re).to.be.a('RegExp'); expect(re.source).to.equal('asdf'); }); it('should serialize regexps with flags', function () { var re = /^asdf$/gi; expect(serialize(re)).to.equal('/^asdf$/gi'); }); it('should deserialize regexps with flags', function () { var re = eval(serialize(/^asdf$/gi)); expect(re).to.be.a('RegExp'); expect(re.global).to.equal(true); expect(re.ignoreCase).to.equal(true); expect(re.multiline).to.equal(false); }); it('should serialize regexps with escaped chars', function () { expect(serialize(/\..*/)).to.equal('/\\..*/'); expect(serialize(new RegExp('\\..*'))).to.equal('/\\..*/'); }); it('should deserialize regexps with escaped chars', function () { var re = eval(serialize(/\..*/)); expect(re).to.be.a('RegExp'); expect(re.source).to.equal('\\..*'); re = eval(serialize(new RegExp('\\..*'))); expect(re).to.be.a('RegExp'); expect(re.source).to.equal('\\..*'); }); }); describe('dates', function () { it('should serialize dates', function () { var d = new Date('2016-04-28T22:02:17.156Z'); expect(serialize(d)).to.be.a('string').equal('new Date("2016-04-28T22:02:17.156Z")'); expect(serialize({t: [d]})).to.be.a('string').equal('{"t":[new Date("2016-04-28T22:02:17.156Z")]}'); }); it('should deserialize a date', function () { var d = eval(serialize(new Date('2016-04-28T22:02:17.156Z'))); expect(d).to.be.a('Date'); expect(d.toISOString()).to.equal('2016-04-28T22:02:17.156Z'); }); it('should deserialize a string that is not a valid date', function () { var d = eval(serialize('2016-04-28T25:02:17.156Z')); expect(d).to.be.a('string'); expect(d).to.equal('2016-04-28T25:02:17.156Z'); }); }); describe('XSS', function () { it('should encode unsafe HTML chars to Unicode', function () { expect(serialize('')).to.equal('"\\u003C\\u002Fscript\\u003E"'); expect(JSON.parse(serialize(''))).to.equal(''); expect(eval(serialize(''))).to.equal(''); }); }); describe('options', function () { it('should accept options as the second argument', function () { expect(serialize('foo', {})).to.equal('"foo"'); }); it('should accept a `space` option', function () { expect(serialize([1], {space: 0})).to.equal('[1]'); expect(serialize([1], {space: ''})).to.equal('[1]'); expect(serialize([1], {space: undefined})).to.equal('[1]'); expect(serialize([1], {space: null})).to.equal('[1]'); expect(serialize([1], {space: false})).to.equal('[1]'); expect(serialize([1], {space: 1})).to.equal('[\n 1\n]'); expect(serialize([1], {space: ' '})).to.equal('[\n 1\n]'); expect(serialize([1], {space: 2})).to.equal('[\n 1\n]'); }); it('should accept a `isJSON` option', function () { expect(serialize('foo', {isJSON: true})).to.equal('"foo"'); expect(serialize('foo', {isJSON: false})).to.equal('"foo"'); function fn() { return true; } expect(serialize(fn)).to.equal('function fn() { return true; }'); expect(serialize(fn, {isJSON: false})).to.equal('function fn() { return true; }'); expect(serialize(fn, {isJSON: true})).to.equal('undefined'); expect(serialize([1], {isJSON: true, space: 2})).to.equal('[\n 1\n]'); }); }); describe('backwards-compatability', function () { it('should accept `space` as the second argument', function () { expect(serialize([1], 0)).to.equal('[1]'); expect(serialize([1], '')).to.equal('[1]'); expect(serialize([1], undefined)).to.equal('[1]'); expect(serialize([1], null)).to.equal('[1]'); expect(serialize([1], false)).to.equal('[1]'); expect(serialize([1], 1)).to.equal('[\n 1\n]'); expect(serialize([1], ' ')).to.equal('[\n 1\n]'); expect(serialize([1], 2)).to.equal('[\n 1\n]'); }); }); });