/
Module.js
374 lines (304 loc) · 10.2 KB
/
Module.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import { relative } from 'path';
import { Promise } from 'sander';
import { parse } from 'acorn';
import MagicString from 'magic-string';
import Statement from './Statement';
import walk from './ast/walk';
import analyse from './ast/analyse';
import { blank, has, keys } from './utils/object';
import { sequence } from './utils/promise';
import { isImportDeclaration, isExportDeclaration } from './utils/map-helpers';
import getLocation from './utils/getLocation';
import makeLegalIdentifier from './utils/makeLegalIdentifier';
const emptyArrayPromise = Promise.resolve([]);
export default class Module {
constructor ({ path, source, bundle }) {
this.source = source;
this.bundle = bundle;
this.path = path;
this.magicString = new MagicString( source, {
filename: path
});
this.suggestedNames = {};
this.comments = [];
// Try to extract a list of top-level statements/declarations. If
// the parse fails, attach file info and abort
try {
const ast = parse( source, {
ecmaVersion: 6,
sourceType: 'module',
onComment: ( block, text, start, end ) => this.comments.push({ block, text, start, end })
});
walk( ast, {
enter: node => {
this.magicString.addSourcemapLocation( node.start );
}
});
this.statements = ast.body.map( node => {
const magicString = this.magicString.snip( node.start, node.end );
return new Statement( node, magicString, this );
});
} catch ( err ) {
err.code = 'PARSE_ERROR';
err.file = path;
throw err;
}
this.importDeclarations = this.statements.filter( isImportDeclaration );
this.exportDeclarations = this.statements.filter( isExportDeclaration );
this.analyse();
}
analyse () {
// imports and exports, indexed by ID
this.imports = {};
this.exports = {};
this.importDeclarations.forEach( statement => {
const node = statement.node;
const source = node.source.value;
node.specifiers.forEach( specifier => {
const isDefault = specifier.type === 'ImportDefaultSpecifier';
const isNamespace = specifier.type === 'ImportNamespaceSpecifier';
const localName = specifier.local.name;
const name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
if ( has( this.imports, localName ) ) {
const err = new Error( `Duplicated import '${localName}'` );
err.file = this.path;
err.loc = getLocation( this.source, specifier.start );
throw err;
}
this.imports[ localName ] = {
source,
name,
localName
};
});
});
this.exportDeclarations.forEach( statement => {
const node = statement.node;
const source = node.source && node.source.value;
// export default function foo () {}
// export default foo;
// export default 42;
if ( node.type === 'ExportDefaultDeclaration' ) {
const isDeclaration = /Declaration$/.test( node.declaration.type );
this.exports.default = {
statement,
name: 'default',
localName: isDeclaration ? node.declaration.id.name : 'default',
isDeclaration
};
}
// export { foo, bar, baz }
// export var foo = 42;
// export function foo () {}
else if ( node.type === 'ExportNamedDeclaration' ) {
if ( node.specifiers.length ) {
// export { foo, bar, baz }
node.specifiers.forEach( specifier => {
const localName = specifier.local.name;
const exportedName = specifier.exported.name;
this.exports[ exportedName ] = {
localName,
exportedName
};
// export { foo } from './foo';
if ( source ) {
this.imports[ localName ] = {
source,
localName,
name: localName
};
}
});
}
else {
let declaration = node.declaration;
let name;
if ( declaration.type === 'VariableDeclaration' ) {
// export var foo = 42
name = declaration.declarations[0].id.name;
} else {
// export function foo () {}
name = declaration.id.name;
}
this.exports[ name ] = {
statement,
localName: name,
expression: declaration
};
}
}
});
analyse( this.magicString, this );
this.canonicalNames = {};
this.definitions = {};
this.definitionPromises = {};
this.modifications = {};
this.statements.forEach( statement => {
Object.keys( statement.defines ).forEach( name => {
this.definitions[ name ] = statement;
});
Object.keys( statement.modifies ).forEach( name => {
if ( !has( this.modifications, name ) ) {
this.modifications[ name ] = [];
}
this.modifications[ name ].push( statement );
});
});
}
getCanonicalName ( localName ) {
if ( has( this.suggestedNames, localName ) ) {
localName = this.suggestedNames[ localName ];
}
if ( !has( this.canonicalNames, localName ) ) {
let canonicalName;
if ( has( this.imports, localName ) ) {
const importDeclaration = this.imports[ localName ];
const module = importDeclaration.module;
if ( importDeclaration.name === '*' ) {
canonicalName = module.suggestedNames[ '*' ];
} else {
let exporterLocalName;
if ( module.isExternal ) {
exporterLocalName = importDeclaration.name;
} else {
const exportDeclaration = module.exports[ importDeclaration.name ];
exporterLocalName = exportDeclaration.localName;
}
canonicalName = module.getCanonicalName( exporterLocalName );
}
}
else {
canonicalName = localName;
}
this.canonicalNames[ localName ] = canonicalName;
}
return this.canonicalNames[ localName ];
}
define ( name ) {
// shortcut cycles. TODO this won't work everywhere...
if ( has( this.definitionPromises, name ) ) {
return emptyArrayPromise;
}
let promise;
// The definition for this name is in a different module
if ( has( this.imports, name ) ) {
const importDeclaration = this.imports[ name ];
promise = this.bundle.fetchModule( importDeclaration.source, this.path )
.then( module => {
importDeclaration.module = module;
// suggest names. TODO should this apply to non default/* imports?
if ( importDeclaration.name === 'default' ) {
// TODO this seems ropey
const localName = importDeclaration.localName;
let suggestion = has( this.suggestedNames, localName ) ? this.suggestedNames[ localName ] : localName;
// special case - the module has its own import by this name
while ( !module.isExternal && has( module.imports, suggestion ) ) {
suggestion = `_${suggestion}`;
}
module.suggestName( 'default', suggestion );
} else if ( importDeclaration.name === '*' ) {
const localName = importDeclaration.localName;
const suggestion = has( this.suggestedNames, localName ) ? this.suggestedNames[ localName ] : localName;
module.suggestName( '*', suggestion );
module.suggestName( 'default', `${suggestion}__default` );
}
if ( module.isExternal ) {
if ( importDeclaration.name === 'default' ) {
module.needsDefault = true;
} else {
module.needsNamed = true;
}
module.importedByBundle.push( importDeclaration );
return emptyArrayPromise;
}
if ( importDeclaration.name === '*' ) {
// we need to create an internal namespace
if ( !~this.bundle.internalNamespaceModules.indexOf( module ) ) {
this.bundle.internalNamespaceModules.push( module );
}
return module.expandAllStatements();
}
const exportDeclaration = module.exports[ importDeclaration.name ];
if ( !exportDeclaration ) {
throw new Error( `Module ${module.path} does not export ${importDeclaration.name} (imported by ${this.path})` );
}
return module.define( exportDeclaration.localName );
});
}
// The definition is in this module
else if ( name === 'default' && this.exports.default.isDeclaration ) {
// We have something like `export default foo` - so we just start again,
// searching for `foo` instead of default
promise = this.define( this.exports.default.name );
}
else {
let statement;
if ( name === 'default' ) {
statement = this.exports.default.statement;
} else {
statement = this.definitions[ name ];
}
if ( statement && !statement.isIncluded ) {
promise = statement.expand();
}
}
this.definitionPromises[ name ] = promise || emptyArrayPromise;
return this.definitionPromises[ name ];
}
expandAllStatements ( isEntryModule ) {
let allStatements = [];
return sequence( this.statements, statement => {
// A statement may have already been included, in which case we need to
// curb rollup's enthusiasm and move it down here. It remains to be seen
// if this approach is bulletproof
if ( statement.isIncluded ) {
const index = allStatements.indexOf( statement );
if ( ~index ) {
allStatements.splice( index, 1 );
allStatements.push( statement );
}
return;
}
// skip import declarations...
if ( statement.isImportDeclaration ) {
// ...unless they're empty, in which case assume we're importing them for the side-effects
// THIS IS NOT FOOLPROOF. Probably need /*rollup: include */ or similar
if ( !statement.node.specifiers.length ) {
return this.bundle.fetchModule( statement.node.source.value, this.path )
.then( module => {
statement.module = module; // TODO what is this for? what does it do? why not _module?
return module.expandAllStatements();
})
.then( statements => {
allStatements.push.apply( allStatements, statements );
});
}
return;
}
// skip `export { foo, bar, baz }`...
if ( statement.node.type === 'ExportNamedDeclaration' && statement.node.specifiers.length ) {
// ...but ensure they are defined, if this is the entry module
if ( isEntryModule ) {
return statement.expand().then( statements => {
allStatements.push.apply( allStatements, statements );
});
}
return;
}
// include everything else
return statement.expand().then( statements => {
allStatements.push.apply( allStatements, statements );
});
}).then( () => {
return allStatements;
});
}
rename ( name, replacement ) {
this.canonicalNames[ name ] = replacement;
}
suggestName ( exportName, suggestion ) {
if ( !this.suggestedNames[ exportName ] ) {
this.suggestedNames[ exportName ] = makeLegalIdentifier( suggestion );
}
}
}