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

[utils] Fix isPlainObject to work across realm #39981

Merged
merged 5 commits into from
Jan 8, 2024
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
14 changes: 14 additions & 0 deletions packages/mui-utils/src/deepmerge.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect } from 'chai';
import { runInNewContext } from 'vm';
import deepmerge from './deepmerge';

describe('deepmerge', () => {
Expand All @@ -11,6 +12,19 @@ describe('deepmerge', () => {
expect({}).not.to.have.property('isAdmin');
});

it('should merge objects across realms', function test() {
if (!/jsdom/.test(window.navigator.userAgent)) {
// vm is only available in Node.js.
// We could use https://github.com/browserify/vm-browserify to run the test in an iframe when
// in Karma but it doesn't seem we need to go as far.
this.skip();
}

const vmObject = runInNewContext('({hello: "realm"})');
const result = deepmerge({ hello: 'original' }, vmObject);
expect(result.hello).to.equal('realm');
});

// https://github.com/mui/material-ui/issues/20095
it('should not merge HTML elements', () => {
const element = document.createElement('div');
Expand Down
14 changes: 13 additions & 1 deletion packages/mui-utils/src/deepmerge.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
// https://github.com/sindresorhus/is-plain-obj/blob/main/index.js
export function isPlainObject(item: unknown): item is Record<keyof any, unknown> {
return item !== null && typeof item === 'object' && item.constructor === Object;
if (typeof item !== 'object' || item === null) {
return false;
}

const prototype = Object.getPrototypeOf(item);
return (
(prototype === null ||
prototype === Object.prototype ||
Object.getPrototypeOf(prototype) === null) &&
!(Symbol.toStringTag in item) &&
!(Symbol.iterator in item)
);
}

export interface DeepmergeOptions {
Expand Down
1 change: 1 addition & 0 deletions test/karma.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ module.exports = function setKarmaConfig(config) {
stream: false,
// required by enzyme > cheerio > parse5
util: require.resolve('util/'),
vm: false,
},
},
// TODO: 'browserslist:modern'
Expand Down
Loading