Skip to content

Commit

Permalink
Add defensive args parsing to stop FUD around this module
Browse files Browse the repository at this point in the history
  • Loading branch information
WebReflection committed Oct 12, 2024
1 parent 8d18fcd commit 67c8c57
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
18 changes: 9 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,12 @@ if (!rawJSON) {
throw new TypeError('Unexpected ' + type);
};

const { apply } = Reflect;

// parse
const p = parse;
parse = (text, reviver) => {
if (reviver) {
if (typeof reviver === 'function') {
const $ = reviver;
const context = new Map;
// parse all primitives in one go: string | number | boolean | null
Expand All @@ -47,7 +49,7 @@ if (!rawJSON) {
}
reviver = function (key, value) {
const ctx = context.get(value);
return $.apply(this, ctx ? [key, value, ctx] : [key, value]);
return apply($, this, ctx ? [key, value, ctx] : [key, value]);
};
}
return p(text, reviver);
Expand All @@ -56,18 +58,16 @@ if (!rawJSON) {
// stringify
const { isArray } = Array;
const noop = (_, value) => value;
const fix = (replacer, raws) => {
const fix = (r, raws) => {
let id = 0;
const suffix = `${Math.random()}00`.slice(2);
const $ = isArray(replacer) ?
(k, v) => (k === '' || replacer.includes(k) ? v : void 0) :
(replacer || noop);
const $ = typeof r === 'function' ? r :
(r && isArray(r) ? (k, v) => (!k || r.includes(k) ? v : void 0) : noop);
return function (key, value) {
value = $.call(this, key, value);
value = apply($, this, [key, value]);
if (isRawJSON(value)) {
const { rawJSON } = value;
value = `'${++id}'${suffix}`;
raws.set(value, rawJSON);
raws.set(value = `'${++id}'${suffix}`, rawJSON);
}
return value;
};
Expand Down
14 changes: 14 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,19 @@ catch (_) {}
console.log('w/out reviver:', JSON.parse(JSON.stringify(value, ['bigint'])));
console.log('with reviver:', JSON.parse(JSON.stringify(value, ['bigint']), JSON.reviver));

console.assert(JSON.stringify({ a: 1, b: 2 }, {
apply() {
console.log('APPLY');
},
call() {
console.log('CALL');
}
}) === '{"a":1,"b":2}');

console.assert(JSON.stringify({ a: 1, b: 2 }, null) === '{"a":1,"b":2}');

console.assert(JSON.stringify({ a: 1, b: 2 }, (_, v) => v) === '{"a":1,"b":2}');


// const s = JSON.rawJSON(JSON.stringify('Hello "there"!'));
// JSON.parse(JSON.stringify({ s }), (key, value, context) => { console.log({ key, value, context }); return value });

0 comments on commit 67c8c57

Please sign in to comment.