diff --git a/index.js b/index.js index 4578984..32603b2 100644 --- a/index.js +++ b/index.js @@ -6,10 +6,6 @@ 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; @@ -67,9 +63,27 @@ module.exports = function serialize(obj, options) { return value; } + // Generate an internal UID, and make sure it won't appear in the object + var UID = Math.random().toString(16); + var raw = JSON.stringify(obj, function (key, value) { + var type = typeof value; + // the key could contain a placeholder + if ( + type === 'function' || + (type === 'object' && (value instanceof RegExp || value instanceof Date)) + ) { + return key; + } + return value; + }); + if (typeof raw === 'string') { + while (raw.indexOf(UID) !== -1) { + UID += '@'; + } + } + var PLACE_HOLDER_REGEXP = new RegExp('"@__(F|R|D)-' + UID + '-(\\d+)__@"', 'g'); 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) { diff --git a/test/unit/serialize.js b/test/unit/serialize.js index bec4dae..7ab3dc0 100644 --- a/test/unit/serialize.js +++ b/test/unit/serialize.js @@ -252,4 +252,17 @@ describe('serialize( obj )', function () { expect(serialize([1], 2)).to.equal('[\n 1\n]'); }); }); + + describe('magic placeholder', function () { + it('should handle magic placeholder', function () { + var origRand = Math.random + Math.random = function () { return 1 } + var data = { + '@__F-1-0__@': function () {} + } + + expect(serialize(data)).to.equal('{"@__F-1-0__@":function () {}}') + Math.random = origRand + }) + }) });