├── .github
├── dependabot.yml
└── workflows
│ └── test.yml
├── .gitignore
├── .npmignore
├── LICENSE
├── README.md
├── index.js
├── package-lock.json
├── package.json
└── test
├── benchmark
└── serialize.js
└── unit
└── serialize.js
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: npm
4 | directory: "/"
5 | schedule:
6 | interval: monthly
7 | time: "13:00"
8 | open-pull-requests-limit: 10
9 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Test
2 |
3 | on:
4 | push:
5 | branches: [main]
6 | pull_request:
7 | branches: [main]
8 |
9 | jobs:
10 | build:
11 | runs-on: ubuntu-latest
12 | strategy:
13 | matrix:
14 | node-version: [18.x, 20.x, 22.x]
15 | steps:
16 | - uses: actions/checkout@v3
17 | - name: Use Node.js ${{ matrix.node-version }}
18 | uses: actions/setup-node@v3
19 | with:
20 | node-version: ${{ matrix.node-version }}
21 | - run: npm ci
22 | - run: npm test
23 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | test/
2 | .gitignore
3 | .npmignore
4 | .github
5 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright 2014 Yahoo! Inc.
2 | All rights reserved.
3 |
4 | Redistribution and use in source and binary forms, with or without
5 | modification, are permitted provided that the following conditions are met:
6 |
7 | * Redistributions of source code must retain the above copyright
8 | notice, this list of conditions and the following disclaimer.
9 |
10 | * Redistributions in binary form must reproduce the above copyright
11 | notice, this list of conditions and the following disclaimer in the
12 | documentation and/or other materials provided with the distribution.
13 |
14 | * Neither the name of the Yahoo! Inc. nor the
15 | names of its contributors may be used to endorse or promote products
16 | derived from this software without specific prior written permission.
17 |
18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 | DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. BE LIABLE FOR ANY
22 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Serialize JavaScript
2 | ====================
3 |
4 | Serialize JavaScript to a _superset_ of JSON that includes regular expressions, dates and functions.
5 |
6 | [![npm Version][npm-badge]][npm]
7 | [![Dependency Status][david-badge]][david]
8 | 
9 |
10 | ## Overview
11 |
12 | 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.
13 |
14 | You're probably wondering: **What about `JSON.stringify()`!?** We've found that sometimes we need to serialize JavaScript **functions**, **regexps**, **dates**, **sets** or **maps**. 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. But this module is also great for communicating between node processes.
15 |
16 | 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 `'
69 | });
70 | ```
71 |
72 | 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:
73 |
74 | ```js
75 | '{"haxorXSS":"\\u003C\\u002Fscript\\u003E"}'
76 | ```
77 |
78 | > You can pass an optional `unsafe` argument to `serialize()` for straight serialization.
79 |
80 | ### Options
81 |
82 | The `serialize()` function accepts an `options` object as its second argument. All options are being defaulted to `undefined`:
83 |
84 | #### `options.space`
85 |
86 | 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.
87 |
88 | ```js
89 | serialize(obj, {space: 2});
90 | ```
91 |
92 | #### `options.isJSON`
93 |
94 | 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.
95 |
96 | **Note:** That when using this option, the output will still be escaped to protect against XSS.
97 |
98 | ```js
99 | serialize(obj, {isJSON: true});
100 | ```
101 |
102 | #### `options.unsafe`
103 |
104 | This option is to signal `serialize()` that we want to do a straight conversion, without the XSS protection. This options needs to be explicitly set to `true`. HTML characters and JavaScript line terminators will not be escaped. You will have to roll your own.
105 |
106 | ```js
107 | serialize(obj, {unsafe: true});
108 | ```
109 |
110 | #### `options.ignoreFunction`
111 |
112 | This option is to signal `serialize()` that we do not want serialize JavaScript function.
113 | Just treat function like `JSON.stringify` do, but other features will work as expected.
114 |
115 | ```js
116 | serialize(obj, {ignoreFunction: true});
117 | ```
118 |
119 | ## Deserializing
120 |
121 | For some use cases you might also need to deserialize the string. This is explicitly not part of this module. However, you can easily write it yourself:
122 |
123 | ```js
124 | function deserialize(serializedJavascript){
125 | return eval('(' + serializedJavascript + ')');
126 | }
127 | ```
128 |
129 | **Note:** Don't forget the parentheses around the serialized javascript, as the opening bracket `{` will be considered to be the start of a body.
130 |
131 | ## License
132 |
133 | This software is free to use under the Yahoo! Inc. BSD license.
134 | See the [LICENSE file][LICENSE] for license text and copyright information.
135 |
136 |
137 | [npm]: https://www.npmjs.org/package/serialize-javascript
138 | [npm-badge]: https://img.shields.io/npm/v/serialize-javascript.svg?style=flat-square
139 | [david]: https://david-dm.org/yahoo/serialize-javascript
140 | [david-badge]: https://img.shields.io/david/yahoo/serialize-javascript.svg?style=flat-square
141 | [express-state]: https://github.com/yahoo/express-state
142 | [JSON.stringify]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
143 | [LICENSE]: https://github.com/yahoo/serialize-javascript/blob/main/LICENSE
144 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (c) 2014, Yahoo! Inc. All rights reserved.
3 | Copyrights licensed under the New BSD License.
4 | See the accompanying LICENSE file for terms.
5 | */
6 |
7 | 'use strict';
8 |
9 | var randomBytes = require('randombytes');
10 |
11 | // Generate an internal UID to make the regexp pattern harder to guess.
12 | var UID_LENGTH = 16;
13 | var UID = generateUID();
14 | var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|A|U|I|B|L)-' + UID + '-(\\d+)__@"', 'g');
15 |
16 | var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g;
17 | var IS_PURE_FUNCTION = /function.*?\(/;
18 | var IS_ARROW_FUNCTION = /.*?=>.*?/;
19 | var UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g;
20 |
21 | var RESERVED_SYMBOLS = ['*', 'async'];
22 |
23 | // Mapping of unsafe HTML and invalid JavaScript line terminator chars to their
24 | // Unicode char counterparts which are safe to use in JavaScript strings.
25 | var ESCAPED_CHARS = {
26 | '<' : '\\u003C',
27 | '>' : '\\u003E',
28 | '/' : '\\u002F',
29 | '\u2028': '\\u2028',
30 | '\u2029': '\\u2029'
31 | };
32 |
33 | function escapeUnsafeChars(unsafeChar) {
34 | return ESCAPED_CHARS[unsafeChar];
35 | }
36 |
37 | function generateUID() {
38 | var bytes = randomBytes(UID_LENGTH);
39 | var result = '';
40 | for(var i=0; i arg1+5
155 | if(IS_ARROW_FUNCTION.test(serializedFn)) {
156 | return serializedFn;
157 | }
158 |
159 | var argsStartsAt = serializedFn.indexOf('(');
160 | var def = serializedFn.substr(0, argsStartsAt)
161 | .trim()
162 | .split(' ')
163 | .filter(function(val) { return val.length > 0 });
164 |
165 | var nonReservedSymbols = def.filter(function(val) {
166 | return RESERVED_SYMBOLS.indexOf(val) === -1
167 | });
168 |
169 | // enhanced literal objects, example: {key() {}}
170 | if(nonReservedSymbols.length > 0) {
171 | return (def.indexOf('async') > -1 ? 'async ' : '') + 'function'
172 | + (def.join('').indexOf('*') > -1 ? '*' : '')
173 | + serializedFn.substr(argsStartsAt);
174 | }
175 |
176 | // arrow functions
177 | return serializedFn;
178 | }
179 |
180 | // Check if the parameter is function
181 | if (options.ignoreFunction && typeof obj === "function") {
182 | obj = undefined;
183 | }
184 | // Protects against `JSON.stringify()` returning `undefined`, by serializing
185 | // to the literal string: "undefined".
186 | if (obj === undefined) {
187 | return String(obj);
188 | }
189 |
190 | var str;
191 |
192 | // Creates a JSON string representation of the value.
193 | // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args.
194 | if (options.isJSON && !options.space) {
195 | str = JSON.stringify(obj);
196 | } else {
197 | str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space);
198 | }
199 |
200 | // Protects against `JSON.stringify()` returning `undefined`, by serializing
201 | // to the literal string: "undefined".
202 | if (typeof str !== 'string') {
203 | return String(str);
204 | }
205 |
206 | // Replace unsafe HTML and invalid JavaScript line terminator chars with
207 | // their safe Unicode char counterpart. This _must_ happen before the
208 | // regexps and functions are serialized and added back to the string.
209 | if (options.unsafe !== true) {
210 | str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars);
211 | }
212 |
213 | if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && arrays.length === 0 && undefs.length === 0 && infinities.length === 0 && bigInts.length === 0 && urls.length === 0) {
214 | return str;
215 | }
216 |
217 | // Replaces all occurrences of function, regexp, date, map and set placeholders in the
218 | // JSON string with their string representations. If the original value can
219 | // not be found, then `undefined` is used.
220 | return str.replace(PLACE_HOLDER_REGEXP, function (match, backSlash, type, valueIndex) {
221 | // The placeholder may not be preceded by a backslash. This is to prevent
222 | // replacing things like `"a\"@__R--0__@"` and thus outputting
223 | // invalid JS.
224 | if (backSlash) {
225 | return match;
226 | }
227 |
228 | if (type === 'D') {
229 | return "new Date(\"" + dates[valueIndex].toISOString() + "\")";
230 | }
231 |
232 | if (type === 'R') {
233 | return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")";
234 | }
235 |
236 | if (type === 'M') {
237 | return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")";
238 | }
239 |
240 | if (type === 'S') {
241 | return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")";
242 | }
243 |
244 | if (type === 'A') {
245 | return "Array.prototype.slice.call(" + serialize(Object.assign({ length: arrays[valueIndex].length }, arrays[valueIndex]), options) + ")";
246 | }
247 |
248 | if (type === 'U') {
249 | return 'undefined'
250 | }
251 |
252 | if (type === 'I') {
253 | return infinities[valueIndex];
254 | }
255 |
256 | if (type === 'B') {
257 | return "BigInt(\"" + bigInts[valueIndex] + "\")";
258 | }
259 |
260 | if (type === 'L') {
261 | return "new URL(" + serialize(urls[valueIndex].toString(), options) + ")";
262 | }
263 |
264 | var fn = functions[valueIndex];
265 |
266 | return serializeFunc(fn);
267 | });
268 | }
269 |
--------------------------------------------------------------------------------
/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "serialize-javascript",
3 | "version": "6.0.2",
4 | "lockfileVersion": 3,
5 | "requires": true,
6 | "packages": {
7 | "": {
8 | "name": "serialize-javascript",
9 | "version": "6.0.2",
10 | "license": "BSD-3-Clause",
11 | "dependencies": {
12 | "randombytes": "^2.1.0"
13 | },
14 | "devDependencies": {
15 | "benchmark": "^2.1.4"
16 | }
17 | },
18 | "node_modules/benchmark": {
19 | "version": "2.1.4",
20 | "resolved": "https://registry.npmjs.org/benchmark/-/benchmark-2.1.4.tgz",
21 | "integrity": "sha1-CfPeMckWQl1JjMLuVloOvzwqVik=",
22 | "dev": true,
23 | "dependencies": {
24 | "lodash": "^4.17.4",
25 | "platform": "^1.3.3"
26 | }
27 | },
28 | "node_modules/lodash": {
29 | "version": "4.17.21",
30 | "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
31 | "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
32 | "dev": true
33 | },
34 | "node_modules/platform": {
35 | "version": "1.3.5",
36 | "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.5.tgz",
37 | "integrity": "sha512-TuvHS8AOIZNAlE77WUDiR4rySV/VMptyMfcfeoMgs4P8apaZM3JrnbzBiixKUv+XR6i+BXrQh8WAnjaSPFO65Q==",
38 | "dev": true
39 | },
40 | "node_modules/randombytes": {
41 | "version": "2.1.0",
42 | "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz",
43 | "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==",
44 | "dependencies": {
45 | "safe-buffer": "^5.1.0"
46 | }
47 | },
48 | "node_modules/safe-buffer": {
49 | "version": "5.1.2",
50 | "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
51 | "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "serialize-javascript",
3 | "version": "6.0.2",
4 | "description": "Serialize JavaScript to a superset of JSON that includes regular expressions and functions.",
5 | "main": "index.js",
6 | "scripts": {
7 | "benchmark": "node -v && node test/benchmark/serialize.js",
8 | "test": "node --test test/unit/*.js"
9 | },
10 | "repository": {
11 | "type": "git",
12 | "url": "git+https://github.com/yahoo/serialize-javascript.git"
13 | },
14 | "keywords": [
15 | "serialize",
16 | "serialization",
17 | "javascript",
18 | "js",
19 | "json"
20 | ],
21 | "author": "Eric Ferraiuolo ",
22 | "license": "BSD-3-Clause",
23 | "bugs": {
24 | "url": "https://github.com/yahoo/serialize-javascript/issues"
25 | },
26 | "homepage": "https://github.com/yahoo/serialize-javascript",
27 | "devDependencies": {
28 | "benchmark": "^2.1.4"
29 | },
30 | "dependencies": {
31 | "randombytes": "^2.1.0"
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/test/benchmark/serialize.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var Benchmark = require('benchmark');
4 | var serialize = require('../../');
5 |
6 | var suiteConfig = {
7 | onStart: function (e) {
8 | console.log(e.currentTarget.name + ':');
9 | },
10 |
11 | onCycle: function (e) {
12 | console.log(String(e.target));
13 | },
14 |
15 | onComplete: function () {
16 | console.log('');
17 | }
18 | };
19 |
20 | // -- simpleOjb ----------------------------------------------------------------
21 |
22 | var simpleObj = {
23 | foo: 'foo',
24 | bar: false,
25 | num: 100,
26 | arr: [1, 2, 3, 4],
27 | obj: {baz: 'baz'}
28 | };
29 |
30 | new Benchmark.Suite('simpleObj', suiteConfig)
31 | .add('JSON.stringify( simpleObj )', function () {
32 | JSON.stringify(simpleObj);
33 | })
34 | .add('JSON.stringify( simpleObj ) with replacer', function () {
35 | JSON.stringify(simpleObj, function (key, value) {
36 | return value;
37 | });
38 | })
39 | .add('serialize( simpleObj, {isJSON: true} )', function () {
40 | serialize(simpleObj, {isJSON: true});
41 | })
42 | .add('serialize( simpleObj, {unsafe: true} )', function () {
43 | serialize(simpleObj, {unsafe: true});
44 | })
45 | .add('serialize( simpleObj, {unsafe: true, isJSON: true} )', function () {
46 | serialize(simpleObj, {unsafe: true, isJSON: true});
47 | })
48 | .add('serialize( simpleObj )', function () {
49 | serialize(simpleObj);
50 | })
51 | .run();
52 |
--------------------------------------------------------------------------------
/test/unit/serialize.js:
--------------------------------------------------------------------------------
1 | const { beforeEach, describe, it } = require('node:test');
2 | const { deepStrictEqual, strictEqual, throws } = require('node:assert');
3 |
4 | var serialize = require('../../');
5 |
6 | // temporarily monkeypatch `crypto.randomBytes` so we'll have a
7 | // predictable UID for our tests
8 | var crypto = require('crypto');
9 | var oldRandom = crypto.randomBytes;
10 | crypto.randomBytes = function(len, cb) {
11 | var buf = Buffer.alloc(len);
12 | buf.fill(0x00);
13 | if (cb)
14 | cb(null, buf);
15 | return buf;
16 | };
17 |
18 | crypto.randomBytes = oldRandom;
19 |
20 | describe('serialize( obj )', function () {
21 | it('should be a function', function () {
22 | strictEqual(typeof serialize, 'function');
23 | });
24 |
25 | describe('undefined', function () {
26 | it('should serialize `undefined` to a string', function () {
27 | strictEqual(typeof serialize(), 'string');
28 | strictEqual(serialize(), 'undefined');
29 | strictEqual(typeof serialize(undefined), 'string');
30 | strictEqual(serialize(undefined), 'undefined');
31 | });
32 |
33 | it('should deserialize "undefined" to `undefined`', function () {
34 | strictEqual(eval(serialize()), undefined);
35 | strictEqual(eval(serialize(undefined)), undefined);
36 | });
37 | });
38 |
39 | describe('null', function () {
40 | it('should serialize `null` to a string', function () {
41 | strictEqual(typeof serialize(null), 'string');
42 | strictEqual(serialize(null), 'null');
43 | });
44 |
45 | it('should deserialize "null" to `null`', function () {
46 | strictEqual(eval(serialize(null)), null);
47 | });
48 | });
49 |
50 | describe('JSON', function () {
51 | var data;
52 |
53 | beforeEach(function () {
54 | data = {
55 | str : 'string',
56 | num : 0,
57 | obj : {foo: 'foo'},
58 | arr : [1, 2, 3],
59 | bool: true,
60 | nil : null
61 | };
62 | });
63 |
64 | it('should serialize JSON to a JSON string', function () {
65 | deepStrictEqual(serialize(data), JSON.stringify(data));
66 | });
67 |
68 | it('should deserialize a JSON string to a JSON object', function () {
69 | deepStrictEqual(JSON.parse(serialize(data)), data);
70 | });
71 |
72 | it('should serialize weird whitespace characters correctly', function () {
73 | var ws = String.fromCharCode(8232);
74 | deepStrictEqual(eval(serialize(ws)), ws);
75 | });
76 |
77 | it('should serialize undefined correctly', function () {
78 | var obj;
79 | var str = '{"undef":undefined,"nest":{"undef":undefined}}';
80 | eval('obj = ' + str);
81 | deepStrictEqual(serialize(obj), str);
82 | });
83 | });
84 |
85 | describe('functions', function () {
86 | it('should serialize annonymous functions', function () {
87 | var fn = function () {};
88 | strictEqual(typeof serialize(fn), 'string');
89 | strictEqual(serialize(fn), 'function () {}');
90 | });
91 |
92 | it('should deserialize annonymous functions', function () {
93 | var fn; eval('fn = ' + serialize(function () {}));
94 | strictEqual(typeof fn, 'function');
95 | });
96 |
97 | it('should serialize named functions', function () {
98 | function fn() {}
99 | strictEqual(typeof serialize(fn), 'string');
100 | strictEqual(serialize(fn), 'function fn() {}');
101 | });
102 |
103 | it('should deserialize named functions', function () {
104 | var fn; eval('fn = ' + serialize(function fn() {}));
105 | strictEqual(typeof fn, 'function');
106 | strictEqual(fn.name, 'fn');
107 | });
108 |
109 | it('should serialize functions with arguments', function () {
110 | function fn(arg1, arg2) {}
111 | strictEqual(serialize(fn), 'function fn(arg1, arg2) {}');
112 | });
113 |
114 | it('should deserialize functions with arguments', function () {
115 | var fn; eval('fn = ' + serialize(function (arg1, arg2) {}));
116 | strictEqual(typeof fn, 'function');
117 | strictEqual(fn.length, 2);
118 | });
119 |
120 | it('should serialize functions with bodies', function () {
121 | function fn() { return true; }
122 | strictEqual(serialize(fn), 'function fn() { return true; }');
123 | });
124 |
125 | it('should deserialize functions with bodies', function () {
126 | var fn; eval('fn = ' + serialize(function () { return true; }));
127 | strictEqual(typeof fn, 'function');
128 | strictEqual(fn(), true);
129 | });
130 |
131 | it('should throw a TypeError when serializing native built-ins', function () {
132 | var err;
133 | strictEqual(Number.toString(), 'function Number() { [native code] }');
134 | try { serialize(Number); } catch (e) { err = e; }
135 | strictEqual(err instanceof TypeError, true);
136 | });
137 |
138 | it('should serialize enhanced literal objects', function () {
139 | var obj = {
140 | foo() { return true; },
141 | *bar() { return true; }
142 | };
143 |
144 | deepStrictEqual(serialize(obj), '{"foo":function() { return true; },"bar":function*() { return true; }}');
145 | });
146 |
147 | it('should deserialize enhanced literal objects', function () {
148 | var obj;
149 | eval('obj = ' + serialize({ hello() { return true; } }));
150 |
151 | strictEqual(obj.hello(), true);
152 | });
153 |
154 | it('should serialize functions that contain dates', function () {
155 | function fn(arg1) {return new Date('2016-04-28T22:02:17.156Z')};
156 | strictEqual(typeof serialize(fn), 'string');
157 | strictEqual(serialize(fn), 'function fn(arg1) {return new Date(\'2016-04-28T22:02:17.156Z\')}');
158 | });
159 |
160 | it('should deserialize functions that contain dates', function () {
161 | var fn; eval('fn = ' + serialize(function () { return new Date('2016-04-28T22:02:17.156Z') }));
162 | strictEqual(typeof fn, 'function');
163 | strictEqual(fn().getTime(), new Date('2016-04-28T22:02:17.156Z').getTime());
164 | });
165 |
166 | it('should serialize functions that return other functions', function () {
167 | function fn() {return function(arg1) {return arg1 + 5}};
168 | strictEqual(typeof serialize(fn), 'string');
169 | strictEqual(serialize(fn), 'function fn() {return function(arg1) {return arg1 + 5}}');
170 | });
171 |
172 | it('should deserialize functions that return other functions', function () {
173 | var fn; eval('fn = ' + serialize(function () { return function(arg1) {return arg1 + 5} }));
174 | strictEqual(typeof fn, 'function');
175 | strictEqual(fn()(7), 12);
176 | });
177 | });
178 |
179 | describe('arrow-functions', function () {
180 | it('should serialize arrow functions', function () {
181 | var fn = () => {};
182 | strictEqual(typeof serialize(fn), 'string');
183 | strictEqual(serialize(fn), '() => {}');
184 | });
185 |
186 | it('should deserialize arrow functions', function () {
187 | var fn; eval('fn = ' + serialize(() => true));
188 | strictEqual(typeof fn, 'function');
189 | strictEqual(fn(), true);
190 | });
191 |
192 | it('should serialize arrow functions with one argument', function () {
193 | var fn = arg1 => {}
194 | strictEqual(typeof serialize(fn), 'string');
195 | strictEqual(serialize(fn), 'arg1 => {}');
196 | });
197 |
198 | it('should deserialize arrow functions with one argument', function () {
199 | var fn; eval('fn = ' + serialize(arg1 => {}));
200 | strictEqual(typeof fn, 'function');
201 | strictEqual(fn.length, 1);
202 | });
203 |
204 | it('should serialize arrow functions with multiple arguments', function () {
205 | var fn = (arg1, arg2) => {}
206 | strictEqual(serialize(fn), '(arg1, arg2) => {}');
207 | });
208 |
209 | it('should deserialize arrow functions with multiple arguments', function () {
210 | var fn; eval('fn = ' + serialize( (arg1, arg2) => {}));
211 | strictEqual(typeof fn, 'function');
212 | strictEqual(fn.length, 2);
213 | });
214 |
215 | it('should serialize arrow functions with bodies', function () {
216 | var fn = () => { return true; }
217 | strictEqual(serialize(fn), '() => { return true; }');
218 | });
219 |
220 | it('should deserialize arrow functions with bodies', function () {
221 | var fn; eval('fn = ' + serialize( () => { return true; }));
222 | strictEqual(typeof fn, 'function');
223 | strictEqual(fn(), true);
224 | });
225 |
226 | it('should serialize enhanced literal objects', function () {
227 | var obj = {
228 | foo: () => { return true; },
229 | bar: arg1 => { return true; },
230 | baz: (arg1, arg2) => { return true; }
231 | };
232 |
233 | strictEqual(serialize(obj), '{"foo":() => { return true; },"bar":arg1 => { return true; },"baz":(arg1, arg2) => { return true; }}');
234 | });
235 |
236 | it('should deserialize enhanced literal objects', function () {
237 | var obj;
238 | eval('obj = ' + serialize({ foo: () => { return true; },
239 | foo: () => { return true; },
240 | bar: arg1 => { return true; },
241 | baz: (arg1, arg2) => { return true; }
242 | }));
243 |
244 | strictEqual(obj.foo(), true);
245 | strictEqual(obj.bar('arg1'), true);
246 | strictEqual(obj.baz('arg1', 'arg1'), true);
247 | });
248 |
249 | it('should serialize arrow functions with added properties', function () {
250 | var fn = () => {};
251 | fn.property1 = 'a string'
252 | strictEqual(typeof serialize(fn), 'string');
253 | strictEqual(serialize(fn), '() => {}');
254 | });
255 |
256 | it('should deserialize arrow functions with added properties', function () {
257 | var fn; eval('fn = ' + serialize( () => { this.property1 = 'a string'; return 5 }));
258 | strictEqual(typeof fn, 'function');
259 | strictEqual(fn(), 5);
260 | });
261 |
262 | it('should serialize arrow functions that return other functions', function () {
263 | var fn = arg1 => { return arg2 => arg1 + arg2 };
264 | strictEqual(typeof serialize(fn), 'string');
265 | strictEqual(serialize(fn), 'arg1 => { return arg2 => arg1 + arg2 }');
266 | });
267 |
268 | it('should deserialize arrow functions that return other functions', function () {
269 | var fn; eval('fn = ' + serialize(arg1 => { return arg2 => arg1 + arg2 } ));
270 | strictEqual(typeof fn, 'function');
271 | strictEqual(fn(2)(3), 5);
272 | });
273 | });
274 |
275 | describe('regexps', function () {
276 | it('should serialize constructed regexps', function () {
277 | var re = new RegExp('asdf');
278 | strictEqual(typeof serialize(re), 'string');
279 | strictEqual(serialize(re), 'new RegExp("asdf", "")');
280 | });
281 |
282 | it('should deserialize constructed regexps', function () {
283 | var re = eval(serialize(new RegExp('asdf')));
284 | strictEqual(re instanceof RegExp, true);
285 | strictEqual(re.source, 'asdf');
286 | });
287 |
288 | it('should serialize literal regexps', function () {
289 | var re = /asdf/;
290 | strictEqual(typeof serialize(re), 'string');
291 | strictEqual(serialize(re), 'new RegExp("asdf", "")');
292 | });
293 |
294 | it('should deserialize literal regexps', function () {
295 | var re = eval(serialize(/asdf/));
296 | strictEqual(re instanceof RegExp, true);
297 | strictEqual(re.source, 'asdf');
298 | });
299 |
300 | it('should serialize regexps with flags', function () {
301 | var re = /^asdf$/gi;
302 | strictEqual(serialize(re), 'new RegExp("^asdf$", "gi")');
303 | });
304 |
305 | it('should deserialize regexps with flags', function () {
306 | var re = eval(serialize(/^asdf$/gi));
307 | strictEqual(re instanceof RegExp, true);
308 | strictEqual(re.global, true);
309 | strictEqual(re.ignoreCase, true);
310 | strictEqual(re.multiline, false);
311 | });
312 |
313 | it('should serialize regexps with escaped chars', function () {
314 | strictEqual(serialize(/\..*/), 'new RegExp("\\\\..*", "")');
315 | strictEqual(serialize(new RegExp('\\..*')), 'new RegExp("\\\\..*", "")');
316 | });
317 |
318 | it('should deserialize regexps with escaped chars', function () {
319 | var re = eval(serialize(/\..*/));
320 | strictEqual(re instanceof RegExp, true);
321 | strictEqual(re.source, '\\..*');
322 | re = eval(serialize(new RegExp('\\..*')));
323 | strictEqual(re instanceof RegExp, true);
324 | strictEqual(re.source, '\\..*');
325 | });
326 |
327 | it('should serialize dangerous regexps', function () {
328 | var re = /[<\/script>'), '"\\u003C\\u002Fscript\\u003E"');
507 | strictEqual(JSON.parse(serialize('')), '');
508 | strictEqual(eval(serialize('')), '');
509 | strictEqual(serialize(new URL('x:')), 'new URL("x:\\u003C\\u002Fscript\\u003E")');
510 | strictEqual(eval(serialize(new URL('x:'))).href, 'x:');
511 | });
512 | });
513 |
514 | describe('options', function () {
515 | it('should accept options as the second argument', function () {
516 | strictEqual(serialize('foo', {}), '"foo"');
517 | });
518 |
519 | it('should accept a `space` option', function () {
520 | strictEqual(serialize([1], {space: 0}), '[1]');
521 | strictEqual(serialize([1], {space: ''}), '[1]');
522 | strictEqual(serialize([1], {space: undefined}), '[1]');
523 | strictEqual(serialize([1], {space: null}), '[1]');
524 | strictEqual(serialize([1], {space: false}), '[1]');
525 |
526 | strictEqual(serialize([1], {space: 1}), '[\n 1\n]');
527 | strictEqual(serialize([1], {space: ' '}), '[\n 1\n]');
528 | strictEqual(serialize([1], {space: 2}), '[\n 1\n]');
529 | });
530 |
531 | it('should accept a `isJSON` option', function () {
532 | strictEqual(serialize('foo', {isJSON: true}), '"foo"');
533 | strictEqual(serialize('foo', {isJSON: false}), '"foo"');
534 |
535 | function fn() { return true; }
536 |
537 | strictEqual(serialize(fn), 'function fn() { return true; }');
538 | strictEqual(serialize(fn, {isJSON: false}), 'function fn() { return true; }');
539 |
540 | strictEqual(serialize(fn, {isJSON: true}), 'undefined');
541 | strictEqual(serialize([1], {isJSON: true, space: 2}), '[\n 1\n]');
542 | });
543 |
544 | it('should accept a `unsafe` option', function () {
545 | strictEqual(serialize('foo', {unsafe: true}), '"foo"');
546 | strictEqual(serialize('foo', {unsafe: false}), '"foo"');
547 |
548 | function fn() { return true; }
549 |
550 | strictEqual(serialize(fn), 'function fn() { return true; }');
551 | strictEqual(serialize(fn, {unsafe: false}), 'function fn() { return true; }');
552 | strictEqual(serialize(fn, {unsafe: undefined}), 'function fn() { return true; }');
553 | strictEqual(serialize(fn, {unsafe: "true"}), 'function fn() { return true; }');
554 |
555 | strictEqual(serialize(fn, {unsafe: true}), 'function fn() { return true; }');
556 | strictEqual(serialize(["1"], {unsafe: false, space: 2}), '[\n "1"\n]');
557 | strictEqual(serialize(["1"], {unsafe: true, space: 2}), '[\n "1"\n]');
558 | strictEqual(serialize(["<"], {space: 2}), '[\n "\\u003C"\n]');
559 | strictEqual(serialize(["<"], {unsafe: true, space: 2}), '[\n "<"\n]');
560 | });
561 |
562 | it("should accept a `ignoreFunction` option", function() {
563 | function fn() { return true; }
564 | var obj = {
565 | fn: fn,
566 | fn_arrow: () => {
567 | return true;
568 | }
569 | };
570 | var obj2 = {
571 | num: 123,
572 | str: 'str',
573 | fn: fn
574 | }
575 | // case 1. Pass function to serialize
576 | strictEqual(serialize(fn, { ignoreFunction: true }), 'undefined');
577 | // case 2. Pass function(arrow) in object to serialze
578 | strictEqual(serialize(obj, { ignoreFunction: true }), '{}');
579 | // case 3. Other features should work
580 | strictEqual(serialize(obj2, { ignoreFunction: true }),
581 | '{"num":123,"str":"str"}'
582 | );
583 | });
584 | });
585 |
586 | describe('backwards-compatability', function () {
587 | it('should accept `space` as the second argument', function () {
588 | strictEqual(serialize([1], 0), '[1]');
589 | strictEqual(serialize([1], ''), '[1]');
590 | strictEqual(serialize([1], undefined), '[1]');
591 | strictEqual(serialize([1], null), '[1]');
592 | strictEqual(serialize([1], false), '[1]');
593 |
594 | strictEqual(serialize([1], 1), '[\n 1\n]');
595 | strictEqual(serialize([1], ' '), '[\n 1\n]');
596 | strictEqual(serialize([1], 2), '[\n 1\n]');
597 | });
598 | });
599 |
600 | describe('placeholders', function() {
601 | it('should not be replaced within string literals', function () {
602 | // Since we made the UID deterministic this should always be the placeholder
603 | var fakePlaceholder = '"@__R-0000000000000000-0__@';
604 | var serialized = serialize({bar: /1/i, foo: fakePlaceholder}, {uid: 'foo'});
605 | var obj = eval('(' + serialized + ')');
606 | strictEqual(typeof obj, 'object');
607 | strictEqual(typeof obj.foo, 'string');
608 | strictEqual(obj.foo, fakePlaceholder);
609 | });
610 | });
611 |
612 | });
613 |
--------------------------------------------------------------------------------