Skip to content

fix: Account for object's prototype possibly being null #6925

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

Merged
merged 1 commit into from
Jan 30, 2023
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
8 changes: 7 additions & 1 deletion packages/utils/src/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,12 +233,18 @@ function stringifyValue(
// them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as
// `"[object Object]"`. If we instead look at the constructor's name (which is the same as the name of the class),
// we can make sure that only plain objects come out that way.
return `[object ${(Object.getPrototypeOf(value) as Prototype).constructor.name}]`;
return `[object ${getConstructorName(value)}]`;
} catch (err) {
return `**non-serializable** (${err})`;
}
}

function getConstructorName(value: unknown): string {
const prototype: Prototype | null = Object.getPrototypeOf(value);

return prototype ? prototype.constructor.name : 'null prototype';
}

/** Calculates bytes size of input string */
function utf8Length(value: string): number {
// eslint-disable-next-line no-bitwise
Expand Down
5 changes: 5 additions & 0 deletions packages/utils/test/normalize.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,11 @@ describe('normalize()', () => {
expect(normalize([{ a }, { b: new B() }, c])).toEqual([{ a: 1 }, { b: 2 }, 3]);
});

test('should return a normalized object even if a property was created without a prototype', () => {
const subject = { a: 1, foo: Object.create(null), bar: Object.assign(Object.create(null), { baz: true }) } as any;
expect(normalize(subject)).toEqual({ a: 1, foo: {}, bar: { baz: true } });
});

test('should return a normalized object even if toJSON throws', () => {
const subject = { a: 1, foo: 'bar' } as any;
subject.toJSON = () => {
Expand Down