blob: cf14df47402c68d88fe60235188fedbf9ddd3130 [file] [log] [blame]
Tim van der Lippe97eeaf02020-05-20 14:32:51 +01001/*
2Copyright (c) 2014, Yahoo! Inc. All rights reserved.
3Copyrights licensed under the New BSD License.
4See the accompanying LICENSE file for terms.
5*/
6
7'use strict';
8
Tim van der Lippe59b55bb2020-11-13 15:46:08 +00009var randomBytes = require('randombytes');
10
Tim van der Lippe97eeaf02020-05-20 14:32:51 +010011// Generate an internal UID to make the regexp pattern harder to guess.
Tim van der Lippe59b55bb2020-11-13 15:46:08 +000012var UID_LENGTH = 16;
13var UID = generateUID();
14var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|U|I|B)-' + UID + '-(\\d+)__@"', 'g');
Tim van der Lippe97eeaf02020-05-20 14:32:51 +010015
16var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g;
17var IS_PURE_FUNCTION = /function.*?\(/;
18var IS_ARROW_FUNCTION = /.*?=>.*?/;
19var UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g;
20
21var 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.
25var ESCAPED_CHARS = {
26 '<' : '\\u003C',
27 '>' : '\\u003E',
28 '/' : '\\u002F',
29 '\u2028': '\\u2028',
30 '\u2029': '\\u2029'
31};
32
33function escapeUnsafeChars(unsafeChar) {
34 return ESCAPED_CHARS[unsafeChar];
35}
36
Tim van der Lippe59b55bb2020-11-13 15:46:08 +000037function generateUID() {
38 var bytes = randomBytes(UID_LENGTH);
39 var result = '';
40 for(var i=0; i<UID_LENGTH; ++i) {
41 result += bytes[i].toString(16);
42 }
43 return result;
44}
45
Tim van der Lippe97eeaf02020-05-20 14:32:51 +010046function deleteFunctions(obj){
47 var functionKeys = [];
48 for (var key in obj) {
49 if (typeof obj[key] === "function") {
50 functionKeys.push(key);
51 }
52 }
53 for (var i = 0; i < functionKeys.length; i++) {
54 delete obj[functionKeys[i]];
55 }
56}
57
58module.exports = function serialize(obj, options) {
59 options || (options = {});
60
61 // Backwards-compatibility for `space` as the second argument.
62 if (typeof options === 'number' || typeof options === 'string') {
63 options = {space: options};
64 }
65
66 var functions = [];
67 var regexps = [];
68 var dates = [];
69 var maps = [];
70 var sets = [];
71 var undefs = [];
Tim van der Lippe59b55bb2020-11-13 15:46:08 +000072 var infinities= [];
73 var bigInts = [];
Tim van der Lippe97eeaf02020-05-20 14:32:51 +010074
75 // Returns placeholders for functions and regexps (identified by index)
76 // which are later replaced by their string representation.
77 function replacer(key, value) {
78
79 // For nested function
80 if(options.ignoreFunction){
81 deleteFunctions(value);
82 }
83
84 if (!value && value !== undefined) {
85 return value;
86 }
87
88 // If the value is an object w/ a toJSON method, toJSON is called before
89 // the replacer runs, so we use this[key] to get the non-toJSONed value.
90 var origValue = this[key];
91 var type = typeof origValue;
92
93 if (type === 'object') {
94 if(origValue instanceof RegExp) {
95 return '@__R-' + UID + '-' + (regexps.push(origValue) - 1) + '__@';
96 }
97
98 if(origValue instanceof Date) {
99 return '@__D-' + UID + '-' + (dates.push(origValue) - 1) + '__@';
100 }
101
102 if(origValue instanceof Map) {
103 return '@__M-' + UID + '-' + (maps.push(origValue) - 1) + '__@';
104 }
105
106 if(origValue instanceof Set) {
107 return '@__S-' + UID + '-' + (sets.push(origValue) - 1) + '__@';
108 }
109 }
110
111 if (type === 'function') {
112 return '@__F-' + UID + '-' + (functions.push(origValue) - 1) + '__@';
113 }
114
115 if (type === 'undefined') {
116 return '@__U-' + UID + '-' + (undefs.push(origValue) - 1) + '__@';
117 }
118
Tim van der Lippe59b55bb2020-11-13 15:46:08 +0000119 if (type === 'number' && !isNaN(origValue) && !isFinite(origValue)) {
120 return '@__I-' + UID + '-' + (infinities.push(origValue) - 1) + '__@';
121 }
122
123 if (type === 'bigint') {
124 return '@__B-' + UID + '-' + (bigInts.push(origValue) - 1) + '__@';
125 }
126
Tim van der Lippe97eeaf02020-05-20 14:32:51 +0100127 return value;
128 }
129
130 function serializeFunc(fn) {
131 var serializedFn = fn.toString();
132 if (IS_NATIVE_CODE_REGEXP.test(serializedFn)) {
133 throw new TypeError('Serializing native function: ' + fn.name);
134 }
135
136 // pure functions, example: {key: function() {}}
137 if(IS_PURE_FUNCTION.test(serializedFn)) {
138 return serializedFn;
139 }
140
141 // arrow functions, example: arg1 => arg1+5
142 if(IS_ARROW_FUNCTION.test(serializedFn)) {
143 return serializedFn;
144 }
145
146 var argsStartsAt = serializedFn.indexOf('(');
147 var def = serializedFn.substr(0, argsStartsAt)
148 .trim()
149 .split(' ')
150 .filter(function(val) { return val.length > 0 });
151
152 var nonReservedSymbols = def.filter(function(val) {
153 return RESERVED_SYMBOLS.indexOf(val) === -1
154 });
155
156 // enhanced literal objects, example: {key() {}}
157 if(nonReservedSymbols.length > 0) {
158 return (def.indexOf('async') > -1 ? 'async ' : '') + 'function'
159 + (def.join('').indexOf('*') > -1 ? '*' : '')
160 + serializedFn.substr(argsStartsAt);
161 }
162
163 // arrow functions
164 return serializedFn;
165 }
166
167 // Check if the parameter is function
168 if (options.ignoreFunction && typeof obj === "function") {
169 obj = undefined;
170 }
171 // Protects against `JSON.stringify()` returning `undefined`, by serializing
172 // to the literal string: "undefined".
173 if (obj === undefined) {
174 return String(obj);
175 }
176
177 var str;
178
179 // Creates a JSON string representation of the value.
180 // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args.
181 if (options.isJSON && !options.space) {
182 str = JSON.stringify(obj);
183 } else {
184 str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space);
185 }
186
187 // Protects against `JSON.stringify()` returning `undefined`, by serializing
188 // to the literal string: "undefined".
189 if (typeof str !== 'string') {
190 return String(str);
191 }
192
193 // Replace unsafe HTML and invalid JavaScript line terminator chars with
194 // their safe Unicode char counterpart. This _must_ happen before the
195 // regexps and functions are serialized and added back to the string.
196 if (options.unsafe !== true) {
197 str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars);
198 }
199
Tim van der Lippe59b55bb2020-11-13 15:46:08 +0000200 if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && undefs.length === 0 && infinities.length === 0 && bigInts.length === 0) {
Tim van der Lippe97eeaf02020-05-20 14:32:51 +0100201 return str;
202 }
203
204 // Replaces all occurrences of function, regexp, date, map and set placeholders in the
205 // JSON string with their string representations. If the original value can
206 // not be found, then `undefined` is used.
Tim van der Lippe59b55bb2020-11-13 15:46:08 +0000207 return str.replace(PLACE_HOLDER_REGEXP, function (match, backSlash, type, valueIndex) {
208 // The placeholder may not be preceded by a backslash. This is to prevent
209 // replacing things like `"a\"@__R-<UID>-0__@"` and thus outputting
210 // invalid JS.
211 if (backSlash) {
212 return match;
213 }
214
Tim van der Lippe97eeaf02020-05-20 14:32:51 +0100215 if (type === 'D') {
216 return "new Date(\"" + dates[valueIndex].toISOString() + "\")";
217 }
218
219 if (type === 'R') {
220 return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")";
221 }
222
223 if (type === 'M') {
224 return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")";
225 }
226
227 if (type === 'S') {
228 return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")";
229 }
230
231 if (type === 'U') {
232 return 'undefined'
233 }
234
Tim van der Lippe59b55bb2020-11-13 15:46:08 +0000235 if (type === 'I') {
236 return infinities[valueIndex];
237 }
238
239 if (type === 'B') {
240 return "BigInt(\"" + bigInts[valueIndex] + "\")";
241 }
242
Tim van der Lippe97eeaf02020-05-20 14:32:51 +0100243 var fn = functions[valueIndex];
244
245 return serializeFunc(fn);
246 });
247}