-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
import-injector.js
454 lines (408 loc) 路 13.9 KB
/
import-injector.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
import assert from "assert";
import * as t from "@babel/types";
import ImportBuilder from "./import-builder";
import isModule from "./is-module";
export type ImportOptions = {
/**
* The module being referenced.
*/
importedSource: string | null,
/**
* The type of module being imported:
*
* * 'es6' - An ES6 module.
* * 'commonjs' - A CommonJS module. (Default)
*/
importedType: "es6" | "commonjs",
/**
* The type of interop behavior for namespace/default/named when loading
* CommonJS modules.
*
* ## 'babel' (Default)
*
* Load using Babel's interop.
*
* If '.__esModule' is true, treat as 'compiled', else:
*
* * Namespace: A copy of the module.exports with .default
* populated by the module.exports object.
* * Default: The module.exports value.
* * Named: The .named property of module.exports.
*
* The 'ensureLiveReference' has no effect on the liveness of these.
*
* ## 'compiled'
*
* Assume the module is ES6 compiled to CommonJS. Useful to avoid injecting
* interop logic if you are confident that the module is a certain format.
*
* * Namespace: The root module.exports object.
* * Default: The .default property of the namespace.
* * Named: The .named property of the namespace.
*
* Will return erroneous results if the imported module is _not_ compiled
* from ES6 with Babel.
*
* ## 'uncompiled'
*
* Assume the module is _not_ ES6 compiled to CommonJS. Used a simplified
* access pattern that doesn't require additional function calls.
*
* Will return erroneous results if the imported module _is_ compiled
* from ES6 with Babel.
*
* * Namespace: The module.exports object.
* * Default: The module.exports object.
* * Named: The .named property of module.exports.
*/
importedInterop: "babel" | "node" | "compiled" | "uncompiled",
/**
* The type of CommonJS interop included in the environment that will be
* loading the output code.
*
* * 'babel' - CommonJS modules load with Babel's interop. (Default)
* * 'node' - CommonJS modules load with Node's interop.
*
* See descriptions in 'importedInterop' for more details.
*/
importingInterop: "babel" | "node",
/**
* Define whether we explicitly care that the import be a live reference.
* Only applies when importing default and named imports, not the namespace.
*
* * true - Force imported values to be live references.
* * false - No particular requirements. Keeps the code simplest. (Default)
*/
ensureLiveReference: boolean,
/**
* Define if we explicitly care that the result not be a property reference.
*
* * true - Force calls to exclude context. Useful if the value is going to
* be used as function callee.
* * false - No particular requirements for context of the access. (Default)
*/
ensureNoContext: boolean,
/**
* Define whether the import should be loaded before or after the existing imports.
* "after" is only allowed inside ECMAScript modules, since it's not possible to
* reliably pick the location _after_ require() calls but _before_ other code in CJS.
*/
importPosition: "before" | "after",
};
/**
* A general helper classes add imports via transforms. See README for usage.
*/
export default class ImportInjector {
/**
* The path used for manipulation.
*/
declare _programPath: NodePath;
/**
* The scope used to generate unique variable names.
*/
declare _programScope;
/**
* The file used to inject helpers and resolve paths.
*/
declare _hub;
/**
* The default options to use with this instance when imports are added.
*/
_defaultOpts: ImportOptions = {
importedSource: null,
importedType: "commonjs",
importedInterop: "babel",
importingInterop: "babel",
ensureLiveReference: false,
ensureNoContext: false,
importPosition: "before",
};
constructor(path, importedSource, opts) {
const programPath = path.find(p => p.isProgram());
this._programPath = programPath;
this._programScope = programPath.scope;
this._hub = programPath.hub;
this._defaultOpts = this._applyDefaults(importedSource, opts, true);
}
addDefault(importedSourceIn, opts) {
return this.addNamed("default", importedSourceIn, opts);
}
addNamed(importName, importedSourceIn, opts) {
assert(typeof importName === "string");
return this._generateImport(
this._applyDefaults(importedSourceIn, opts),
importName,
);
}
addNamespace(importedSourceIn, opts) {
return this._generateImport(
this._applyDefaults(importedSourceIn, opts),
null,
);
}
addSideEffect(importedSourceIn, opts) {
return this._generateImport(
this._applyDefaults(importedSourceIn, opts),
false,
);
}
_applyDefaults(importedSource, opts, isInit = false) {
const optsList = [];
if (typeof importedSource === "string") {
optsList.push({ importedSource });
optsList.push(opts);
} else {
assert(!opts, "Unexpected secondary arguments.");
optsList.push(importedSource);
}
const newOpts = {
...this._defaultOpts,
};
for (const opts of optsList) {
if (!opts) continue;
Object.keys(newOpts).forEach(key => {
if (opts[key] !== undefined) newOpts[key] = opts[key];
});
if (!isInit) {
if (opts.nameHint !== undefined) newOpts.nameHint = opts.nameHint;
if (opts.blockHoist !== undefined) newOpts.blockHoist = opts.blockHoist;
}
}
return newOpts;
}
_generateImport(opts, importName) {
const isDefault = importName === "default";
const isNamed = !!importName && !isDefault;
const isNamespace = importName === null;
const {
importedSource,
importedType,
importedInterop,
importingInterop,
ensureLiveReference,
ensureNoContext,
nameHint,
importPosition,
// Not meant for public usage. Allows code that absolutely must control
// ordering to set a specific hoist value on the import nodes.
// This is ignored when "importPosition" is "after".
blockHoist,
} = opts;
// Provide a hint for generateUidIdentifier for the local variable name
// to use for the import, if the code will generate a simple assignment
// to a variable.
let name = nameHint || importName;
const isMod = isModule(this._programPath);
const isModuleForNode = isMod && importingInterop === "node";
const isModuleForBabel = isMod && importingInterop === "babel";
if (importPosition === "after" && !isMod) {
throw new Error(`"importPosition": "after" is only supported in modules`);
}
const builder = new ImportBuilder(
importedSource,
this._programScope,
this._hub,
);
if (importedType === "es6") {
if (!isModuleForNode && !isModuleForBabel) {
throw new Error("Cannot import an ES6 module from CommonJS");
}
// import * as namespace from ''; namespace
// import def from ''; def
// import { named } from ''; named
builder.import();
if (isNamespace) {
builder.namespace(nameHint || importedSource);
} else if (isDefault || isNamed) {
builder.named(name, importName);
}
} else if (importedType !== "commonjs") {
throw new Error(`Unexpected interopType "${importedType}"`);
} else if (importedInterop === "babel") {
if (isModuleForNode) {
// import _tmp from ''; var namespace = interopRequireWildcard(_tmp); namespace
// import _tmp from ''; var def = interopRequireDefault(_tmp).default; def
// import _tmp from ''; _tmp.named
name = name !== "default" ? name : importedSource;
const es6Default = `${importedSource}$es6Default`;
builder.import();
if (isNamespace) {
builder
.default(es6Default)
.var(name || importedSource)
.wildcardInterop();
} else if (isDefault) {
if (ensureLiveReference) {
builder
.default(es6Default)
.var(name || importedSource)
.defaultInterop()
.read("default");
} else {
builder
.default(es6Default)
.var(name)
.defaultInterop()
.prop(importName);
}
} else if (isNamed) {
builder.default(es6Default).read(importName);
}
} else if (isModuleForBabel) {
// import * as namespace from ''; namespace
// import def from ''; def
// import { named } from ''; named
builder.import();
if (isNamespace) {
builder.namespace(name || importedSource);
} else if (isDefault || isNamed) {
builder.named(name, importName);
}
} else {
// var namespace = interopRequireWildcard(require(''));
// var def = interopRequireDefault(require('')).default; def
// var named = require('').named; named
builder.require();
if (isNamespace) {
builder.var(name || importedSource).wildcardInterop();
} else if ((isDefault || isNamed) && ensureLiveReference) {
if (isDefault) {
name = name !== "default" ? name : importedSource;
builder.var(name).read(importName);
builder.defaultInterop();
} else {
builder.var(importedSource).read(importName);
}
} else if (isDefault) {
builder.var(name).defaultInterop().prop(importName);
} else if (isNamed) {
builder.var(name).prop(importName);
}
}
} else if (importedInterop === "compiled") {
if (isModuleForNode) {
// import namespace from ''; namespace
// import namespace from ''; namespace.default
// import namespace from ''; namespace.named
builder.import();
if (isNamespace) {
builder.default(name || importedSource);
} else if (isDefault || isNamed) {
builder.default(importedSource).read(name);
}
} else if (isModuleForBabel) {
// import * as namespace from ''; namespace
// import def from ''; def
// import { named } from ''; named
// Note: These lookups will break if the module has no __esModule set,
// hence the warning that 'compiled' will not work on standard CommonJS.
builder.import();
if (isNamespace) {
builder.namespace(name || importedSource);
} else if (isDefault || isNamed) {
builder.named(name, importName);
}
} else {
// var namespace = require(''); namespace
// var namespace = require(''); namespace.default
// var namespace = require(''); namespace.named
// var named = require('').named;
builder.require();
if (isNamespace) {
builder.var(name || importedSource);
} else if (isDefault || isNamed) {
if (ensureLiveReference) {
builder.var(importedSource).read(name);
} else {
builder.prop(importName).var(name);
}
}
}
} else if (importedInterop === "uncompiled") {
if (isDefault && ensureLiveReference) {
throw new Error("No live reference for commonjs default");
}
if (isModuleForNode) {
// import namespace from ''; namespace
// import def from ''; def;
// import namespace from ''; namespace.named
builder.import();
if (isNamespace) {
builder.default(name || importedSource);
} else if (isDefault) {
builder.default(name);
} else if (isNamed) {
builder.default(importedSource).read(name);
}
} else if (isModuleForBabel) {
// import namespace from '';
// import def from '';
// import { named } from ''; named;
// Note: These lookups will break if the module has __esModule set,
// hence the warning that 'uncompiled' will not work on ES6 transpiled
// to CommonJS.
builder.import();
if (isNamespace) {
builder.default(name || importedSource);
} else if (isDefault) {
builder.default(name);
} else if (isNamed) {
builder.named(name, importName);
}
} else {
// var namespace = require(''); namespace
// var def = require(''); def
// var namespace = require(''); namespace.named
// var named = require('').named;
builder.require();
if (isNamespace) {
builder.var(name || importedSource);
} else if (isDefault) {
builder.var(name);
} else if (isNamed) {
if (ensureLiveReference) {
builder.var(importedSource).read(name);
} else {
builder.var(name).prop(importName);
}
}
}
} else {
throw new Error(`Unknown importedInterop "${importedInterop}".`);
}
const { statements, resultName } = builder.done();
this._insertStatements(statements, importPosition, blockHoist);
if (
(isDefault || isNamed) &&
ensureNoContext &&
resultName.type !== "Identifier"
) {
return t.sequenceExpression([t.numericLiteral(0), resultName]);
}
return resultName;
}
_insertStatements(statements, importPosition = "before", blockHoist = 3) {
const body = this._programPath.get("body");
if (importPosition === "after") {
for (let i = body.length - 1; i >= 0; i--) {
if (body[i].isImportDeclaration()) {
body[i].insertAfter(statements);
return;
}
}
} else {
statements.forEach(node => {
node._blockHoist = blockHoist;
});
const targetPath = body.find(p => {
const val = p.node._blockHoist;
return Number.isFinite(val) && val < 4;
});
if (targetPath) {
targetPath.insertBefore(statements);
return;
}
}
this._programPath.unshiftContainer("body", statements);
}
}