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

enhance POJO detection #7

Merged
merged 1 commit into from
Mar 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
const reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
const unsafe = /[<>\/\u2028\u2029]/g;
const escaped: Record<string, string> = { '<': '\\u003C', '>' : '\\u003E', '/': '\\u002F', '\u2028': '\\u2028', '\u2029': '\\u2029' };
const objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join('\0');

export default function devalue(value: any) {
const repeated = new Map();
Expand Down Expand Up @@ -44,8 +45,16 @@ export default function devalue(value: any) {
default:
const proto = Object.getPrototypeOf(thing);

if (proto !== Object.prototype && proto !== null) {
throw new Error(`Cannot stringify arbitrary non-POJOs`);
if (
proto !== Object.prototype &&
proto !== null &&
Object.getOwnPropertyNames(proto).sort().join('\0') !== objectProtoOwnPropertyNames
) {
throw new Error(`Cannot stringify arbitrary non-POJOs`);
}

if (Object.getOwnPropertySymbols(thing).length > 0) {
throw new Error(`Cannot stringify POJOs with symbolic keys`);
}

Object.keys(thing).forEach(key => walk(thing[key]));
Expand Down
13 changes: 13 additions & 0 deletions test/test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as assert from 'assert';
import * as vm from 'vm';
import devalue from '../src/index';

describe('devalue', () => {
Expand Down Expand Up @@ -80,5 +81,17 @@ describe('devalue', () => {
// let arr = [];
// arr.x = 42;
// test('Array with named properties', arr, `TODO`);

test('cross-realm POJO', vm.runInNewContext('({})'), '{}');

it('throws for non-POJOs', () => {
class Foo {}
const foo = new Foo();
assert.throws(() => devalue(foo));
});

it('throws for symbolic keys', () => {
assert.throws(() => devalue({ [Symbol()]: null }));
});
});
});