-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtransform-decaffeinate.js
More file actions
131 lines (109 loc) · 2.74 KB
/
transform-decaffeinate.js
File metadata and controls
131 lines (109 loc) · 2.74 KB
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
export default function transformer(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
/*
1 删除 const Cls = (app.Router = class Router {})
*/
root.find(j.VariableDeclaration).forEach(path => {
const decl = path.node.declarations[0];
if (
decl.init &&
decl.init.type === "AssignmentExpression" &&
decl.init.right.type === "ClassExpression"
) {
j(path).replaceWith(
j.expressionStatement(decl.init)
);
}
});
/*
2 initClass → static field
*/
root.find(j.MethodDefinition, {
key: { name: "initClass" }
}).forEach(path => {
const body = path.node.value.body.body;
body.forEach(stmt => {
if (
stmt.type === "ExpressionStatement" &&
stmt.expression.type === "AssignmentExpression"
) {
const assign = stmt.expression;
if (
assign.left.type === "MemberExpression" &&
assign.left.object.type === "ThisExpression"
) {
const name = assign.left.property.name;
const classProp = j.classProperty(
j.identifier(name),
assign.right
);
j(path).insertBefore(classProp);
}
}
});
j(path).remove();
});
/*
3 删除 Router.initClass()
*/
root.find(j.CallExpression, {
callee: {
property: { name: "initClass" }
}
}).remove();
/*
4 $.extend(this.prototype, Events) → extends Events
*/
root.find(j.CallExpression, {
callee: {
object: { name: "$" },
property: { name: "extend" }
}
}).forEach(path => {
const args = path.node.arguments;
if (
args[0].type === "MemberExpression" &&
args[0].property.name === "prototype"
) {
const className = args[0].object.name;
const parent = args[1].name;
root.find(j.ClassExpression, {
id: { name: className }
}).forEach(cls => {
cls.node.superClass = j.identifier(parent);
});
j(path).remove();
}
});
/*
5 __guard__ → optional chaining
*/
root.find(j.CallExpression, {
callee: { name: "__guard__" }
}).forEach(path => {
const [obj, arrow] = path.node.arguments;
if (arrow && arrow.type === "ArrowFunctionExpression") {
const body = arrow.body;
if (body.type === "MemberExpression") {
const propChain = [];
let current = body;
while (current.type === "MemberExpression") {
propChain.unshift(current.property);
current = current.object;
}
let newExpr = obj;
propChain.forEach(prop => {
newExpr = j.optionalMemberExpression(
newExpr,
prop,
false,
true
);
});
j(path).replaceWith(newExpr);
}
}
});
return root.toSource();
}