Skip to content

Commit

Permalink
Support objects from other contexts in t.valueToNode (#13275)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed May 7, 2021
1 parent 4c1b8cc commit 4c725f8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
11 changes: 9 additions & 2 deletions packages/babel-types/src/converters/valueToNode.ts
Expand Up @@ -40,11 +40,18 @@ function isRegExp(value): value is RegExp {
}

function isPlainObject(value): value is object {
if (typeof value !== "object" || value === null) {
if (
typeof value !== "object" ||
value === null ||
Object.prototype.toString.call(value) !== "[object Object]"
) {
return false;
}
const proto = Object.getPrototypeOf(value);
return proto === null || proto === Object.prototype;
// Object.prototype's __proto__ is null. Every other class's __proto__.__proto__ is
// not null by default. We cannot check if proto === Object.prototype because it
// could come from another realm.
return proto === null || Object.getPrototypeOf(proto) === null;
}

function valueToNode(value: unknown): t.Expression {
Expand Down
20 changes: 20 additions & 0 deletions packages/babel-types/test/regressions.js
@@ -1,4 +1,5 @@
import * as t from "../lib";
import * as vm from "vm";

describe("regressions", () => {
const babel7 = process.env.BABEL_TYPES_8_BREAKING ? it.skip : it;
Expand All @@ -8,4 +9,23 @@ describe("regressions", () => {
t.file(t.program([]), [{ type: "Line" }]);
}).not.toThrow();
});

it(".valueToNode works with objects from different contexts", () => {
const context = {};
const script = new vm.Script(`this.obj = { foo: 2 }`);
script.runInNewContext(context);

expect(t.valueToNode(context.obj)).toMatchObject({
properties: [
{
computed: false,
key: { name: "foo", type: "Identifier" },
shorthand: false,
type: "ObjectProperty",
value: { type: "NumericLiteral", value: 2 },
},
],
type: "ObjectExpression",
});
});
});

0 comments on commit 4c725f8

Please sign in to comment.