This repository has been archived by the owner on Apr 9, 2020. It is now read-only.
/
index.js
293 lines (263 loc) · 8.92 KB
/
index.js
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import path from 'path';
export default function ({ Plugin, types: t }) {
const parentDir = path.resolve(path.join(__dirname, '..', '..'));
function resolvePathConservatively(specifiedPath, filePath) {
if (specifiedPath[0] === '.') {
throw new Error(
`Relative path like ${specifiedPath} is only allowed if ` +
`babel-plugin-react-transform is inside a node_modules folder.`
);
}
return specifiedPath;
}
function resolvePathAssumingWeAreInNodeModules(specifiedPath, filePath) {
if (specifiedPath[0] === '.') {
return '.' + path.sep + path.relative(
path.dirname(filePath),
path.resolve(path.join(parentDir, '..', specifiedPath))
);
}
return specifiedPath;
}
const resolvePath = path.basename(parentDir) === 'node_modules' ?
resolvePathAssumingWeAreInNodeModules :
resolvePathConservatively;
const depthKey = Symbol('depth');
const recordsKey = Symbol('records');
const wrapComponentIdKey = Symbol('wrapComponentId');
function isRenderMethod(member) {
return member.kind === 'method' &&
member.key.name === 'render';
}
/**
* Does this class have a render function?
*/
function isComponentishClass(cls) {
return cls.body.body.filter(isRenderMethod).length > 0;
}
const isCreateClassCallExpression = t.buildMatchMemberExpression('React.createClass');
/**
* Does this node look like a createClass() call?
*/
function isCreateClass(node) {
if (!node || !t.isCallExpression(node)) {
return false;
}
if (!isCreateClassCallExpression(node.callee)) {
return false;
}
const args = node.arguments;
if (args.length !== 1) {
return false;
}
const first = args[0];
if (!t.isObjectExpression(first)) {
return false;
}
return true;
}
/**
* Infers a displayName from either a class node, or a createClass() call node.
*/
function findDisplayName(node) {
if (node.id) {
return node.id.name;
}
if (!node.arguments) {
return;
}
const props = node.arguments[0].properties;
for (let i = 0; i < props.length; i++) {
const prop = props[i];
const key = t.toComputedKey(prop);
if (t.isLiteral(key, { value: 'displayName' })) {
return prop.value.value;
}
}
}
/**
* Enforces plugin options to be defined and returns them.
*/
function getPluginOptions(file) {
if (!file.opts || !file.opts.extra) {
return;
}
const pluginOptions = file.opts.extra['react-transform'];
if (!Array.isArray(pluginOptions) || pluginOptions.length === 0) {
throw new Error(
'babel-plugin-react-transform requires that you specify ' +
'extras["react-transform"] in .babelrc ' +
'or in your Babel Node API call options, and that it is an array ' +
'with more than zero elements.'
);
}
return pluginOptions;
}
/**
* Creates a record about us having visited a valid React component.
* Such records will later be merged into a single object.
*/
function createComponentRecord(node, scope, file, state) {
const displayName = findDisplayName(node) || undefined;
const uniqueId = scope.generateUidIdentifier(
'$' + (displayName || 'Unknown')
).name;
let props = [];
if (typeof displayName === 'string') {
props.push(t.property('init',
t.identifier('displayName'),
t.literal(displayName)
));
}
if (state[depthKey] > 0) {
props.push(t.property('init',
t.identifier('isInFunction'),
t.literal(true)
));
}
return [uniqueId, t.objectExpression(props)];
}
/**
* Memorizes the fact that we have visited a valid component in the plugin state.
* We will later retrieved memorized records to compose an object out of them.
*/
function addComponentRecord(node, scope, file, state) {
const [uniqueId, definition] = createComponentRecord(node, scope, file, state);
state[recordsKey] = state[recordsKey] || [];
state[recordsKey].push(t.property('init',
t.identifier(uniqueId),
definition
));
return uniqueId;
}
/**
* Have we visited any components so far?
*/
function foundComponentRecords(state) {
const records = state[recordsKey];
return records && records.length > 0;
}
/**
* Turns all component records recorded so far, into a variable.
*/
function defineComponentRecords(scope, state) {
const records = state[recordsKey];
state[recordsKey] = [];
const id = scope.generateUidIdentifier('components');
return [id, t.variableDeclaration('var', [
t.variableDeclarator(id, t.objectExpression(records))
])];
}
/**
* Imports and calls a particular transformation target function.
* You may specify several such transformations, so they are handled separately.
*/
function defineInitTransformCall(scope, file, recordsId, targetOptions) {
const id = scope.generateUidIdentifier('reactComponentWrapper');
const { target, imports = [], locals = [] } = targetOptions;
const { filename } = file.opts;
return [id, t.variableDeclaration('var', [
t.variableDeclarator(id,
t.callExpression(file.addImport(resolvePath(target, filename)), [
t.objectExpression([
t.property('init', t.identifier('filename'), t.literal(filename)),
t.property('init', t.identifier('components'), recordsId),
t.property('init', t.identifier('locals'), t.arrayExpression(
locals.map(local => t.identifier(local))
)),
t.property('init', t.identifier('imports'), t.arrayExpression(
imports.map(imp => file.addImport(resolvePath(imp, filename), imp, 'absolute'))
))
])
])
)
])];
}
/**
* Defines the function that calls every transform.
* This is the function every component will be wrapped with.
*/
function defineWrapComponent(wrapComponentId, initTransformIds) {
return t.functionDeclaration(wrapComponentId, [t.identifier('uniqueId')],
t.blockStatement([
t.returnStatement(
t.functionExpression(null, [t.identifier('ReactClass')], t.blockStatement([
t.returnStatement(
initTransformIds.reduce((composed, initTransformId) =>
t.callExpression(initTransformId, [composed, t.identifier('uniqueId')]),
t.identifier('ReactClass')
)
)
]))
)
])
);
}
return new Plugin('babel-plugin-react-transform', {
visitor: {
Function: {
enter(node, parent, scope, file) {
if (!this.state[depthKey]) {
this.state[depthKey] = 0;
}
this.state[depthKey]++;
},
exit(node, parent, scope, file) {
this.state[depthKey]--;
}
},
Class(node, parent, scope, file) {
if (!isComponentishClass(node)) {
return;
}
const wrapReactComponentId = this.state[wrapComponentIdKey];
const uniqueId = addComponentRecord(node, scope, file, this.state);
node.decorators = node.decorators || [];
node.decorators.push(t.decorator(
t.callExpression(wrapReactComponentId, [t.literal(uniqueId)])
));
},
CallExpression: {
exit(node, parent, scope, file) {
if (!isCreateClass(node)) {
return;
}
const wrapReactComponentId = this.state[wrapComponentIdKey];
const uniqueId = addComponentRecord(node, scope, file, this.state);
return t.callExpression(
t.callExpression(wrapReactComponentId, [t.literal(uniqueId)]),
[node]
);
}
},
Program: {
enter(node, parent, scope, file) {
this.state[wrapComponentIdKey] = scope.generateUidIdentifier('wrapComponent');
},
exit(node, parent, scope, file) {
if (!foundComponentRecords(this.state)) {
return;
}
// Generate a variable holding component records
const allTransformOptions = getPluginOptions(file);
const [recordsId, recordsVar] = defineComponentRecords(scope, this.state);
// Import transformation functions and initialize them
const initTransformCalls = allTransformOptions.map(transformOptions =>
defineInitTransformCall(scope, file, recordsId, transformOptions)
);
const initTransformIds = initTransformCalls.map(c => c[0]);
const initTransformVars = initTransformCalls.map(c => c[1]);
// Create one uber function calling each transformation
const wrapComponentId = this.state[wrapComponentIdKey];
const wrapComponent = defineWrapComponent(wrapComponentId, initTransformIds);
return t.program([
recordsVar,
...initTransformVars,
wrapComponent,
...node.body
]);
}
}
}
});
}