Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make sure the internal UID won't appear in the object #40

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 19 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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) {
Expand Down
13 changes: 13 additions & 0 deletions test/unit/serialize.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
})
});