forked from babel/babel
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
111 lines (97 loc) 路 2.9 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import { declare } from "@babel/helper-plugin-utils";
import { types as t, type File } from "@babel/core";
export default declare(api => {
api.assertVersion(7);
function isProtoKey(node: t.ObjectExpression["properties"][number]) {
return (
!t.isSpreadElement(node) &&
t.isStringLiteral(t.toComputedKey(node, node.key), {
value: "__proto__",
})
);
}
function isProtoAssignmentExpression(
node: t.Node,
): node is t.MemberExpression {
const left = node;
return (
t.isMemberExpression(left) &&
t.isStringLiteral(t.toComputedKey(left, left.property), {
value: "__proto__",
})
);
}
function buildDefaultsCallExpression(
expr: t.AssignmentExpression,
ref: t.MemberExpression["object"],
file: File,
) {
return t.expressionStatement(
t.callExpression(file.addHelper("defaults"), [
// @ts-ignore(Babel 7 vs Babel 8) Fixme: support `super.__proto__ = ...`
ref,
expr.right,
]),
);
}
return {
name: "transform-proto-to-assign",
visitor: {
AssignmentExpression(path, { file }) {
if (!isProtoAssignmentExpression(path.node.left)) return;
const nodes = [];
const left = path.node.left.object;
const temp = path.scope.maybeGenerateMemoised(left);
if (temp) {
nodes.push(
t.expressionStatement(
t.assignmentExpression(
"=",
temp,
// left must not be Super when `temp` is an identifier
left as t.Expression,
),
),
);
}
nodes.push(
buildDefaultsCallExpression(
path.node,
t.cloneNode(temp || left),
file,
),
);
if (temp) nodes.push(t.cloneNode(temp));
path.replaceWithMultiple(nodes);
},
ExpressionStatement(path, { file }) {
const expr = path.node.expression;
if (!t.isAssignmentExpression(expr, { operator: "=" })) return;
if (isProtoAssignmentExpression(expr.left)) {
path.replaceWith(
buildDefaultsCallExpression(expr, expr.left.object, file),
);
}
},
ObjectExpression(path, { file }) {
let proto;
const { node } = path;
const { properties } = node;
for (let i = 0; i < properties.length; i++) {
const prop = properties[i];
if (isProtoKey(prop)) {
// @ts-expect-error Fixme: we should also handle ObjectMethod with __proto__ key
proto = prop.value;
properties.splice(i, 1);
break;
}
}
if (proto) {
const args = [t.objectExpression([]), proto];
if (node.properties.length) args.push(node);
path.replaceWith(t.callExpression(file.addHelper("extends"), args));
}
},
},
};
});