-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
hoist.js
833 lines (732 loc) Β· 25.2 KB
/
hoist.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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
// @flow
import type {AST, MutableAsset} from '@parcel/types';
import type {Visitor, NodePath} from '@babel/traverse';
import type {
ExportNamedDeclaration,
ImportDeclaration,
VariableDeclaration,
Identifier,
Expression,
LVal,
StringLiteral,
Statement,
CallExpression,
} from '@babel/types';
import * as t from '@babel/types';
import {
isAssignmentExpression,
isClassDeclaration,
isExportDefaultSpecifier,
isExportNamespaceSpecifier,
isExportSpecifier,
isExpression,
isFunctionDeclaration,
isIdentifier,
isImportDefaultSpecifier,
isImportNamespaceSpecifier,
isImportSpecifier,
isMemberExpression,
isStringLiteral,
isUnaryExpression,
} from '@babel/types';
import traverse from '@babel/traverse';
import template from '@babel/template';
import nullthrows from 'nullthrows';
import invariant from 'assert';
import {convertBabelLoc} from '@parcel/babel-ast-utils';
import rename from './renamer';
import {getName, getIdentifier, getExportIdentifier} from './utils';
const WRAPPER_TEMPLATE = template.statement<
{|NAME: LVal, BODY: Array<Statement>|},
VariableDeclaration,
>(`
var NAME = (function () {
var exports = this;
var module = {exports: this};
BODY;
return module.exports;
}).call({});
`);
const ESMODULE_TEMPLATE = template.statement<null, Statement>(
`exports.__esModule = true;`,
);
const EXPORT_ASSIGN_TEMPLATE = template.statement<
{|EXPORTS: Identifier, NAME: Identifier, LOCAL: Expression|},
Statement,
>('EXPORTS.NAME = LOCAL;');
const REEXPORT_TEMPLATE = template.statement<
{|EXPORTS: Identifier, NAME: StringLiteral, LOCAL: Expression|},
Statement,
>('$parcel$reexport(EXPORTS, NAME, function(){return LOCAL;});');
const EXPORT_ALL_TEMPLATE = template.statement<
{|OLD_NAME: Identifier, ID: StringLiteral, SOURCE: StringLiteral|},
Statement,
>('$parcel$exportWildcard(OLD_NAME, $parcel$require(ID, SOURCE));');
const REQUIRE_CALL_TEMPLATE = template.expression<
{|ID: StringLiteral, SOURCE: StringLiteral|},
CallExpression,
>('$parcel$require(ID, SOURCE)');
const REQUIRE_RESOLVE_CALL_TEMPLATE = template.expression<
{|ID: StringLiteral, SOURCE: StringLiteral|},
CallExpression,
>('$parcel$require$resolve(ID, SOURCE)');
const TYPEOF = {
module: 'object',
require: 'function',
};
export function hoist(asset: MutableAsset, ast: AST) {
if (ast.type !== 'babel' || ast.version !== '7.0.0') {
throw new Error('Asset does not have a babel AST');
}
traverse(ast.program, VISITOR, null, asset);
asset.setAST(ast);
}
const VISITOR: Visitor<MutableAsset> = {
Program: {
enter(path, asset: MutableAsset) {
asset.meta.id = asset.id;
asset.meta.exportsIdentifier = getName(asset, 'exports');
traverse.cache.clearScope();
path.scope.crawl();
let shouldWrap = false;
path.traverse({
CallExpression(path) {
// If we see an `eval` call, wrap the module in a function.
// Otherwise, local variables accessed inside the eval won't work.
let callee = path.node.callee;
if (
isIdentifier(callee) &&
callee.name === 'eval' &&
!path.scope.hasBinding('eval', true)
) {
asset.meta.isCommonJS = true;
shouldWrap = true;
path.stop();
}
},
ReturnStatement(path) {
// Wrap in a function if we see a top-level return statement.
if (!path.getFunctionParent()) {
shouldWrap = true;
asset.meta.isCommonJS = true;
path.replaceWith(
t.returnStatement(
t.memberExpression(
t.identifier('module'),
t.identifier('exports'),
),
),
);
path.stop();
}
},
ReferencedIdentifier(path) {
let {parent, node} = path;
// We must wrap if `module` is referenced as a free identifier rather
// than a statically resolvable member expression.
if (
node.name === 'module' &&
(!isMemberExpression(parent) || parent.computed) &&
!(isUnaryExpression(parent) && parent.operator === 'typeof') &&
!path.scope.hasBinding('module') &&
!path.scope.getData('shouldWrap')
) {
asset.meta.isCommonJS = true;
shouldWrap = true;
path.stop();
}
// We must disable resolving $..$exports.foo if `exports`
// is referenced as a free identifier rather
// than a statically resolvable member expression.
if (
node.name === 'exports' &&
!isAssignmentExpression(parent, {left: node}) &&
(!isMemberExpression(parent) ||
!(isIdentifier(parent.property) && !parent.computed) ||
isStringLiteral(parent.property)) &&
!path.scope.hasBinding('exports') &&
!path.scope.getData('shouldWrap')
) {
asset.meta.isCommonJS = true;
asset.meta.resolveExportsBailedOut = true;
}
},
MemberExpression(path) {
let {node, parent} = path;
// We must disable resolving $..$exports.foo if `exports`
// is referenced as a free identifier rather
// than a statically resolvable member expression.
if (
t.matchesPattern(node, 'module.exports') &&
!isAssignmentExpression(parent, {left: node}) &&
(!isMemberExpression(parent) ||
!(isIdentifier(parent.property) && !parent.computed) ||
isStringLiteral(parent.property)) &&
!path.scope.hasBinding('module') &&
!path.scope.getData('shouldWrap')
) {
asset.meta.resolveExportsBailedOut = true;
}
},
});
path.scope.setData('shouldWrap', shouldWrap);
path.scope.setData('cjsExportsReassigned', false);
},
exit(path, asset: MutableAsset) {
let scope = path.scope;
if (scope.getData('shouldWrap')) {
if (asset.meta.isES6Module) {
path.unshiftContainer('body', [ESMODULE_TEMPLATE()]);
}
path.replaceWith(
t.program([
WRAPPER_TEMPLATE({
NAME: getIdentifier(asset, 'exports'),
BODY: path.node.body,
}),
]),
);
asset.symbols.clear();
asset.meta.isCommonJS = true;
asset.meta.isES6Module = false;
} else {
// Re-crawl scope so we are sure to have all bindings.
traverse.cache.clearScope();
scope.crawl();
// Rename each binding in the top-level scope to something unique.
for (let name in scope.bindings) {
if (!name.startsWith('$' + t.toIdentifier(asset.id))) {
let newName = getName(asset, 'var', name);
rename(scope, name, newName);
}
}
let exportsIdentifier = getIdentifier(asset, 'exports');
// Add variable that represents module.exports if it is referenced and not declared.
if (
scope.hasGlobal(exportsIdentifier.name) &&
!scope.hasBinding(exportsIdentifier.name)
) {
scope.push({id: exportsIdentifier, init: t.objectExpression([])});
}
}
path.stop();
},
},
DirectiveLiteral(path) {
// Remove 'use strict' directives, since modules are concatenated - one strict mode
// module should not apply to all other modules in the same scope.
if (path.node.value === 'use strict') {
path.parentPath.remove();
}
},
MemberExpression(path, asset: MutableAsset) {
if (path.scope.hasBinding('module') || path.scope.getData('shouldWrap')) {
return;
}
if (t.matchesPattern(path.node, 'module.exports')) {
let exportsId = getExportsIdentifier(asset, path.scope);
path.replaceWith(exportsId);
asset.meta.isCommonJS = true;
asset.symbols.set('*', exportsId.name, convertBabelLoc(path.node.loc));
if (!path.scope.hasBinding(exportsId.name)) {
path.scope
.getProgramParent()
.push({id: exportsId, init: t.objectExpression([])});
}
}
if (t.matchesPattern(path.node, 'module.id')) {
path.replaceWith(t.stringLiteral(asset.id));
}
if (t.matchesPattern(path.node, 'module.hot')) {
path.replaceWith(t.identifier('null'));
}
if (t.matchesPattern(path.node, 'module.require') && !asset.env.isNode()) {
path.replaceWith(t.identifier('null'));
}
if (
t.matchesPattern(path.node, 'module.bundle.root') ||
t.matchesPattern(path.node, 'module.bundle')
) {
path.replaceWith(t.identifier('parcelRequire'));
}
},
ReferencedIdentifier(path, asset: MutableAsset) {
if (
path.node.name === 'exports' &&
!path.scope.hasBinding('exports') &&
!path.scope.getData('shouldWrap')
) {
path.replaceWith(getCJSExportsIdentifier(asset, path.scope));
asset.meta.isCommonJS = true;
}
if (path.node.name === 'global' && !path.scope.hasBinding('global')) {
path.replaceWith(t.identifier('$parcel$global'));
}
},
ThisExpression(path, asset: MutableAsset) {
if (!path.scope.getData('shouldWrap')) {
let retainThis = false;
let scope = path.scope;
while (scope?.parent) {
if (
scope.path.isFunction() &&
!scope.path.isArrowFunctionExpression()
) {
retainThis = true;
break;
}
scope = scope.parent.getFunctionParent();
}
if (retainThis) {
return;
}
if (asset.meta.isES6Module) {
path.replaceWith(t.identifier('undefined'));
} else {
path.replaceWith(getExportsIdentifier(asset, path.scope));
asset.meta.isCommonJS = true;
}
}
},
AssignmentExpression(path, asset: MutableAsset) {
if (path.scope.getData('shouldWrap')) {
return;
}
let {left, right} = path.node;
// Match module.exports = expression; assignments and replace with a variable declaration
// if this is the first assignemnt. This avoids the extra empty object assignment in many cases.
//
// TODO: Re-introduce this when it can handle both exports and module.exports concurrently
//
// if (
// t.matchesPattern(left, 'module.exports') &&
// !path.scope.hasBinding('module')
// ) {
// let exportsId = getExportsIdentifier(asset, path.scope);
// asset.meta.isCommonJS = true;
// asset.symbols.set('*', exportsId.name);
// if (
// path.scope === path.scope.getProgramParent() &&
// !path.scope.getBinding(exportsId.name) &&
// path.parentPath.isStatement()
// ) {
// let [decl] = path.parentPath.replaceWith(
// t.variableDeclaration('var', [
// t.variableDeclarator(exportsId, right),
// ]),
// );
// path.scope.registerDeclaration(decl);
// }
// }
if (
isIdentifier(left) &&
left.name === 'exports' &&
!path.scope.hasBinding('exports')
) {
path.scope.getProgramParent().setData('cjsExportsReassigned', true);
path
.get<NodePath<LVal>>('left')
.replaceWith(getCJSExportsIdentifier(asset, path.scope));
asset.meta.isCommonJS = true;
}
// If we can statically evaluate the name of a CommonJS export, create an ES6-style export for it.
// This allows us to remove the CommonJS export object completely in many cases.
if (
isMemberExpression(left) &&
((isIdentifier(left.object, {name: 'exports'}) &&
!path.scope.hasBinding('exports')) ||
(t.matchesPattern(left.object, 'module.exports') &&
!path.scope.hasBinding('module'))) &&
((isIdentifier(left.property) && !left.computed) ||
isStringLiteral(left.property))
) {
let name = isIdentifier(left.property)
? left.property.name
: left.property.value;
let identifier = getExportIdentifier(asset, name);
// Replace the CommonJS assignment with a reference to the ES6 identifier.
path
.get<NodePath<Identifier>>('left.object')
.replaceWith(getExportsIdentifier(asset, path.scope));
path.get('right').replaceWith(identifier);
// If this is the first assignment, create a binding for the ES6-style export identifier.
// Otherwise, assign to the existing export binding.
let scope = path.scope.getProgramParent();
if (!scope.hasBinding(identifier.name)) {
asset.symbols.set(
name,
identifier.name,
convertBabelLoc(path.node.loc),
);
// If in the program scope, create a variable declaration and initialize with the exported value.
// Otherwise, declare the variable in the program scope, and assign to it here.
if (path.scope === scope) {
let [decl] = path.insertBefore(
t.variableDeclaration('var', [
t.variableDeclarator(t.clone(identifier), right),
]),
);
scope.registerDeclaration(decl);
} else {
scope.push({id: t.clone(identifier)});
path.insertBefore(
t.expressionStatement(
t.assignmentExpression('=', t.clone(identifier), right),
),
);
}
} else {
path.insertBefore(
t.expressionStatement(
t.assignmentExpression('=', t.clone(identifier), right),
),
);
}
asset.meta.isCommonJS = true;
}
},
UnaryExpression(path) {
// Replace `typeof module` with "object"
if (
path.node.operator === 'typeof' &&
isIdentifier(path.node.argument) &&
TYPEOF[path.node.argument.name] &&
!path.scope.hasBinding(path.node.argument.name) &&
!path.scope.getData('shouldWrap')
) {
path.replaceWith(t.stringLiteral(TYPEOF[path.node.argument.name]));
}
},
CallExpression(path, asset: MutableAsset) {
let {callee, arguments: args} = path.node;
let isRequire = isIdentifier(callee, {name: 'require'});
let [arg] = args;
if (
args.length !== 1 ||
!isStringLiteral(arg) ||
path.scope.hasBinding('require')
) {
return;
}
if (isRequire) {
let source = arg.value;
// Ignore require calls that were ignored earlier.
let dep = asset
.getDependencies()
.find(dep => dep.moduleSpecifier === source);
if (!dep) {
return;
}
asset.meta.isCommonJS = true;
// If this require call does not occur in the top-level, e.g. in a function
// or inside an if statement, or if it might potentially happen conditionally,
// the module must be wrapped in a function so that the module execution order is correct.
let parent = path.getStatementParent().parentPath;
if (
!parent.isProgram() ||
path.findParent(
p =>
p.isConditionalExpression() ||
p.isLogicalExpression() ||
p.isFunction(),
)
) {
dep.meta.shouldWrap = true;
}
dep.meta.isCommonJS = true;
dep.symbols.set(
'*',
getName(asset, 'require', source),
convertBabelLoc(path.node.loc),
);
// Generate a variable name based on the current asset id and the module name to require.
// This will be replaced by the final variable name of the resolved asset in the packager.
let replacement = REQUIRE_CALL_TEMPLATE({
ID: t.stringLiteral(asset.id),
SOURCE: t.stringLiteral(arg.value),
});
replacement.loc = path.node.loc;
path.replaceWith(replacement);
}
if (t.matchesPattern(callee, 'require.resolve')) {
let replacement = REQUIRE_RESOLVE_CALL_TEMPLATE({
ID: t.stringLiteral(asset.id),
SOURCE: arg,
});
replacement.loc = path.node.loc;
path.replaceWith(replacement);
}
},
ImportDeclaration(path, asset: MutableAsset) {
let dep = asset
.getDependencies()
.find(dep => dep.moduleSpecifier === path.node.source.value);
// For each specifier, rename the local variables to point to the imported name.
// This will be replaced by the final variable name of the resolved asset in the packager.
for (let specifier of path.node.specifiers) {
let id = getIdentifier(asset, 'import', specifier.local.name);
if (dep) {
let imported: string;
if (isImportDefaultSpecifier(specifier)) {
imported = 'default';
} else if (isImportSpecifier(specifier)) {
imported = specifier.imported.name;
} else if (isImportNamespaceSpecifier(specifier)) {
imported = '*';
} else {
throw new Error('Unknown import construct');
}
let existing = dep.symbols.get(imported)?.local;
if (existing) {
id.name = existing;
} else {
dep.symbols.set(imported, id.name, convertBabelLoc(specifier.loc));
}
}
rename(path.scope, specifier.local.name, id.name);
}
addImport(asset, path);
path.remove();
},
ExportDefaultDeclaration(path, asset: MutableAsset) {
let {declaration, loc} = path.node;
let identifier = getExportIdentifier(asset, 'default');
let name: ?string;
if (
(isClassDeclaration(declaration) || isFunctionDeclaration(declaration)) &&
declaration.id
) {
name = declaration.id.name;
} else if (isIdentifier(declaration)) {
name = declaration.name;
}
if (name && (hasImport(asset, name) || hasExport(asset, name))) {
identifier = t.identifier(name);
}
// Add assignment to exports object for namespace imports and commonjs.
path.insertAfter(
EXPORT_ASSIGN_TEMPLATE({
EXPORTS: getExportsIdentifier(asset, path.scope),
NAME: t.identifier('default'),
LOCAL: t.clone(identifier),
}),
);
if (isIdentifier(declaration) && path.scope.hasBinding(declaration.name)) {
// Rename the variable being exported.
safeRename(path, asset, declaration.name, identifier.name);
path.remove();
} else if (isExpression(declaration) || !declaration.id) {
// $FlowFixMe
let declarationExpr = t.toExpression(declaration);
// Declare a variable to hold the exported value.
path.replaceWith(
t.variableDeclaration('var', [
t.variableDeclarator(identifier, declarationExpr),
]),
);
path.scope.registerDeclaration(path);
} else {
invariant(isIdentifier(declaration.id));
// Rename the declaration to the exported name.
safeRename(path, asset, declaration.id.name, identifier.name);
path.replaceWith(declaration);
}
if (!asset.symbols.hasExportSymbol('default')) {
asset.symbols.set('default', identifier.name, convertBabelLoc(loc));
}
},
ExportNamedDeclaration(path, asset: MutableAsset) {
let {declaration, source, specifiers} = path.node;
if (source) {
for (let specifier of nullthrows(specifiers)) {
let exported = specifier.exported;
let imported;
if (isExportDefaultSpecifier(specifier)) {
imported = 'default';
} else if (isExportNamespaceSpecifier(specifier)) {
imported = '*';
} else if (isExportSpecifier(specifier)) {
imported = specifier.local.name;
} else {
throw new Error('Unknown export construct');
}
let id = getIdentifier(asset, 'import', exported.name);
let dep = asset
.getDependencies()
.find(dep => dep.moduleSpecifier === source.value);
if (dep && imported) {
let existing = dep.symbols.get(imported)?.local;
if (existing) {
id.name = existing;
} else {
// this will merge with the existing dependency
let loc = convertBabelLoc(specifier.loc);
asset.addDependency({
moduleSpecifier: dep.moduleSpecifier,
symbols: new Map([[imported, {local: id.name, loc}]]),
isWeak: true,
});
}
}
asset.symbols.set(
exported.name,
id.name,
convertBabelLoc(specifier.loc),
);
id.loc = specifier.loc;
path.insertAfter(
REEXPORT_TEMPLATE({
EXPORTS: getExportsIdentifier(asset, path.scope),
NAME: t.stringLiteral(exported.name),
LOCAL: id,
}),
);
}
addImport(asset, path);
path.remove();
} else if (declaration) {
path.replaceWith(declaration);
if (isIdentifier(declaration.id)) {
addExport(asset, path, declaration.id, declaration.id);
} else {
let identifiers = t.getBindingIdentifiers(declaration);
for (let id of Object.keys(identifiers)) {
addExport(asset, path, identifiers[id], identifiers[id]);
}
}
} else {
for (let specifier of specifiers) {
invariant(isExportSpecifier(specifier)); // because source is empty
addExport(asset, path, specifier.local, specifier.exported);
}
path.remove();
}
},
ExportAllDeclaration(path, asset: MutableAsset) {
let dep = asset
.getDependencies()
.find(dep => dep.moduleSpecifier === path.node.source.value);
if (dep) {
dep.symbols.set('*', '*', convertBabelLoc(path.node.loc));
}
let replacement = EXPORT_ALL_TEMPLATE({
OLD_NAME: getExportsIdentifier(asset, path.scope),
SOURCE: t.stringLiteral(path.node.source.value),
ID: t.stringLiteral(asset.id),
});
let {parentPath, scope} = path;
path.remove();
// Make sure that the relative order of imports and reexports is retained.
let lastImport = scope.getData('hoistedImport');
if (lastImport) {
[lastImport] = lastImport.insertAfter(replacement);
} else {
[lastImport] = parentPath.unshiftContainer('body', [replacement]);
}
path.scope.setData('hoistedImport', lastImport);
},
};
function addImport(
asset: MutableAsset,
path: NodePath<ImportDeclaration | ExportNamedDeclaration>,
) {
// Replace with a $parcel$require call so we know where to insert side effects.
let replacement = REQUIRE_CALL_TEMPLATE({
ID: t.stringLiteral(asset.id),
SOURCE: t.stringLiteral(nullthrows(path.node.source).value),
});
replacement.loc = path.node.loc;
let requireStmt = t.expressionStatement(replacement);
// Hoist the call to the top of the file.
let lastImport = path.scope.getData('hoistedImport');
if (lastImport) {
[lastImport] = lastImport.insertAfter(requireStmt);
} else {
[lastImport] = path.parentPath.unshiftContainer('body', [requireStmt]);
}
path.scope.setData('hoistedImport', lastImport);
}
function addExport(asset: MutableAsset, path, local, exported) {
let scope = path.scope.getProgramParent();
let identifier = getExportIdentifier(asset, exported.name);
if (hasImport(asset, local.name)) {
identifier = t.identifier(local.name);
}
if (hasExport(asset, local.name)) {
identifier = t.identifier(local.name);
}
let assignNode = EXPORT_ASSIGN_TEMPLATE({
EXPORTS: getExportsIdentifier(asset, scope),
NAME: t.identifier(exported.name),
LOCAL: identifier,
});
let binding = scope.getBinding(local.name);
let constantViolations = binding
? binding.constantViolations.concat(binding.path.getStatementParent())
: [path];
if (!asset.symbols.hasExportSymbol(exported.name)) {
asset.symbols.set(
exported.name,
identifier.name,
convertBabelLoc(exported.loc),
);
}
rename(scope, local.name, identifier.name);
for (let p of constantViolations) {
p.insertAfter(t.cloneDeep(assignNode));
}
}
function hasImport(asset: MutableAsset, id) {
for (let dep of asset.getDependencies()) {
if (dep.symbols.hasLocalSymbol(id)) {
return true;
}
}
return false;
}
function hasExport(asset: MutableAsset, id) {
return asset.symbols.hasLocalSymbol(id);
}
function safeRename(path, asset: MutableAsset, from, to) {
if (from === to) {
return;
}
// If the binding that we're renaming is constant, it's safe to rename it.
// Otherwise, create a new binding that references the original.
let binding = nullthrows(path.scope.getBinding(from));
if (binding && binding.constant) {
rename(path.scope, from, to);
} else {
let [decl] = path.insertAfter(
t.variableDeclaration('var', [
t.variableDeclarator(t.identifier(to), t.identifier(from)),
]),
);
binding.reference(decl.get<NodePath<Identifier>>('declarations.0.init'));
path.scope.registerDeclaration(decl);
}
}
function getExportsIdentifier(asset: MutableAsset, scope) {
if (scope.getProgramParent().getData('shouldWrap')) {
return t.identifier('exports');
} else {
let id = getIdentifier(asset, 'exports');
if (!scope.hasBinding(id.name)) {
scope.getProgramParent().addGlobal(id);
}
return id;
}
}
function getCJSExportsIdentifier(asset: MutableAsset, scope) {
if (scope.getProgramParent().getData('shouldWrap')) {
return t.identifier('exports');
} else if (scope.getProgramParent().getData('cjsExportsReassigned')) {
let id = getIdentifier(asset, 'cjs_exports');
if (!scope.hasBinding(id.name)) {
scope.getProgramParent().push({id});
}
return id;
} else {
return getExportsIdentifier(asset, scope);
}
}