/
module.ts
2004 lines (1831 loc) · 97 KB
/
module.ts
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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*@internal*/
namespace ts {
export function transformModule(context: TransformationContext) {
interface AsynchronousDependencies {
aliasedModuleNames: Expression[];
unaliasedModuleNames: Expression[];
importAliasNames: ParameterDeclaration[];
}
function getTransformModuleDelegate(moduleKind: ModuleKind): (node: SourceFile) => SourceFile {
switch (moduleKind) {
case ModuleKind.AMD: return transformAMDModule;
case ModuleKind.UMD: return transformUMDModule;
default: return transformCommonJSModule;
}
}
const {
factory,
getEmitHelperFactory: emitHelpers,
startLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration
} = context;
const compilerOptions = context.getCompilerOptions();
const resolver = context.getEmitResolver();
const host = context.getEmitHost();
const languageVersion = getEmitScriptTarget(compilerOptions);
const moduleKind = getEmitModuleKind(compilerOptions);
const previousOnSubstituteNode = context.onSubstituteNode;
const previousOnEmitNode = context.onEmitNode;
context.onSubstituteNode = onSubstituteNode;
context.onEmitNode = onEmitNode;
context.enableSubstitution(SyntaxKind.CallExpression); // Substitute calls to imported/exported symbols to avoid incorrect `this`.
context.enableSubstitution(SyntaxKind.TaggedTemplateExpression); // Substitute calls to imported/exported symbols to avoid incorrect `this`.
context.enableSubstitution(SyntaxKind.Identifier); // Substitutes expression identifiers with imported/exported symbols.
context.enableSubstitution(SyntaxKind.BinaryExpression); // Substitutes assignments to exported symbols.
context.enableSubstitution(SyntaxKind.ShorthandPropertyAssignment); // Substitutes shorthand property assignments for imported/exported symbols.
context.enableEmitNotification(SyntaxKind.SourceFile); // Restore state when substituting nodes in a file.
const moduleInfoMap: ExternalModuleInfo[] = []; // The ExternalModuleInfo for each file.
const deferredExports: (Statement[] | undefined)[] = []; // Exports to defer until an EndOfDeclarationMarker is found.
let currentSourceFile: SourceFile; // The current file.
let currentModuleInfo: ExternalModuleInfo; // The ExternalModuleInfo for the current file.
const noSubstitution: boolean[] = []; // Set of nodes for which substitution rules should be ignored.
let needUMDDynamicImportHelper: boolean;
return chainBundle(context, transformSourceFile);
/**
* Transforms the module aspects of a SourceFile.
*
* @param node The SourceFile node.
*/
function transformSourceFile(node: SourceFile) {
if (node.isDeclarationFile ||
!(isEffectiveExternalModule(node, compilerOptions) ||
node.transformFlags & TransformFlags.ContainsDynamicImport ||
(isJsonSourceFile(node) && hasJsonModuleEmitEnabled(compilerOptions) && outFile(compilerOptions)))) {
return node;
}
currentSourceFile = node;
currentModuleInfo = collectExternalModuleInfo(context, node, resolver, compilerOptions);
moduleInfoMap[getOriginalNodeId(node)] = currentModuleInfo;
// Perform the transformation.
const transformModule = getTransformModuleDelegate(moduleKind);
const updated = transformModule(node);
currentSourceFile = undefined!;
currentModuleInfo = undefined!;
needUMDDynamicImportHelper = false;
return updated;
}
function shouldEmitUnderscoreUnderscoreESModule() {
if (!currentModuleInfo.exportEquals && isExternalModule(currentSourceFile)) {
return true;
}
return false;
}
/**
* Transforms a SourceFile into a CommonJS module.
*
* @param node The SourceFile node.
*/
function transformCommonJSModule(node: SourceFile) {
startLexicalEnvironment();
const statements: Statement[] = [];
const ensureUseStrict = getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile));
const statementOffset = factory.copyPrologue(node.statements, statements, ensureUseStrict && !isJsonSourceFile(node), topLevelVisitor);
if (shouldEmitUnderscoreUnderscoreESModule()) {
append(statements, createUnderscoreUnderscoreESModule());
}
if (length(currentModuleInfo.exportedNames)) {
const chunkSize = 50;
for (let i=0; i<currentModuleInfo.exportedNames!.length; i += chunkSize) {
append(
statements,
factory.createExpressionStatement(
reduceLeft(
currentModuleInfo.exportedNames!.slice(i, i + chunkSize),
(prev, nextId) => factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(idText(nextId))), prev),
factory.createVoidZero() as Expression
)
)
);
}
}
append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, topLevelVisitor, isStatement));
addRange(statements, visitNodes(node.statements, topLevelVisitor, isStatement, statementOffset));
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
const updated = factory.updateSourceFile(node, setTextRange(factory.createNodeArray(statements), node.statements));
addEmitHelpers(updated, context.readEmitHelpers());
return updated;
}
/**
* Transforms a SourceFile into an AMD module.
*
* @param node The SourceFile node.
*/
function transformAMDModule(node: SourceFile) {
const define = factory.createIdentifier("define");
const moduleName = tryGetModuleNameFromFile(factory, node, host, compilerOptions);
const jsonSourceFile = isJsonSourceFile(node) && node;
// An AMD define function has the following shape:
//
// define(id?, dependencies?, factory);
//
// This has the shape of the following:
//
// define(name, ["module1", "module2"], function (module1Alias) { ... }
//
// The location of the alias in the parameter list in the factory function needs to
// match the position of the module name in the dependency list.
//
// To ensure this is true in cases of modules with no aliases, e.g.:
//
// import "module"
//
// or
//
// /// <amd-dependency path= "a.css" />
//
// we need to add modules without alias names to the end of the dependencies list
const { aliasedModuleNames, unaliasedModuleNames, importAliasNames } = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true);
// Create an updated SourceFile:
//
// define(mofactory.updateSourceFile", "module2"], function ...
const updated = factory.updateSourceFile(node,
setTextRange(
factory.createNodeArray([
factory.createExpressionStatement(
factory.createCallExpression(
define,
/*typeArguments*/ undefined,
[
// Add the module name (if provided).
...(moduleName ? [moduleName] : []),
// Add the dependency array argument:
//
// ["require", "exports", module1", "module2", ...]
factory.createArrayLiteralExpression(jsonSourceFile ? emptyArray : [
factory.createStringLiteral("require"),
factory.createStringLiteral("exports"),
...aliasedModuleNames,
...unaliasedModuleNames
]),
// Add the module body function argument:
//
// function (require, exports, module1, module2) ...
jsonSourceFile ?
jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : factory.createObjectLiteralExpression() :
factory.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
[
factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports"),
...importAliasNames
],
/*type*/ undefined,
transformAsynchronousModuleBody(node)
)
]
)
)
]),
/*location*/ node.statements
)
);
addEmitHelpers(updated, context.readEmitHelpers());
return updated;
}
/**
* Transforms a SourceFile into a UMD module.
*
* @param node The SourceFile node.
*/
function transformUMDModule(node: SourceFile) {
const { aliasedModuleNames, unaliasedModuleNames, importAliasNames } = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false);
const moduleName = tryGetModuleNameFromFile(factory, node, host, compilerOptions);
const umdHeader = factory.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
[factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")],
/*type*/ undefined,
setTextRange(
factory.createBlock(
[
factory.createIfStatement(
factory.createLogicalAnd(
factory.createTypeCheck(factory.createIdentifier("module"), "object"),
factory.createTypeCheck(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), "object")
),
factory.createBlock([
factory.createVariableStatement(
/*modifiers*/ undefined,
[
factory.createVariableDeclaration(
"v",
/*exclamationToken*/ undefined,
/*type*/ undefined,
factory.createCallExpression(
factory.createIdentifier("factory"),
/*typeArguments*/ undefined,
[
factory.createIdentifier("require"),
factory.createIdentifier("exports")
]
)
)
]
),
setEmitFlags(
factory.createIfStatement(
factory.createStrictInequality(
factory.createIdentifier("v"),
factory.createIdentifier("undefined")
),
factory.createExpressionStatement(
factory.createAssignment(
factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"),
factory.createIdentifier("v")
)
)
),
EmitFlags.SingleLine
)
]),
factory.createIfStatement(
factory.createLogicalAnd(
factory.createTypeCheck(factory.createIdentifier("define"), "function"),
factory.createPropertyAccessExpression(factory.createIdentifier("define"), "amd")
),
factory.createBlock([
factory.createExpressionStatement(
factory.createCallExpression(
factory.createIdentifier("define"),
/*typeArguments*/ undefined,
[
// Add the module name (if provided).
...(moduleName ? [moduleName] : []),
factory.createArrayLiteralExpression([
factory.createStringLiteral("require"),
factory.createStringLiteral("exports"),
...aliasedModuleNames,
...unaliasedModuleNames
]),
factory.createIdentifier("factory")
]
)
)
])
)
)
],
/*multiLine*/ true
),
/*location*/ undefined
)
);
// Create an updated SourceFile:
//
// (function (factory) {
// if (typeof module === "object" && typeof module.exports === "object") {
// var v = factory(require, exports);
// if (v !== undefined) module.exports = v;
// }
// else if (typeof define === 'function' && define.amd) {
// define(["require", "exports"], factory);
// }
// })(function ...)
const updated = factory.updateSourceFile(
node,
setTextRange(
factory.createNodeArray([
factory.createExpressionStatement(
factory.createCallExpression(
umdHeader,
/*typeArguments*/ undefined,
[
// Add the module body function argument:
//
// function (require, exports) ...
factory.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
[
factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports"),
...importAliasNames
],
/*type*/ undefined,
transformAsynchronousModuleBody(node)
)
]
)
)
]),
/*location*/ node.statements
)
);
addEmitHelpers(updated, context.readEmitHelpers());
return updated;
}
/**
* Collect the additional asynchronous dependencies for the module.
*
* @param node The source file.
* @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
*/
function collectAsynchronousDependencies(node: SourceFile, includeNonAmdDependencies: boolean): AsynchronousDependencies {
// names of modules with corresponding parameter in the factory function
const aliasedModuleNames: Expression[] = [];
// names of modules with no corresponding parameters in factory function
const unaliasedModuleNames: Expression[] = [];
// names of the parameters in the factory function; these
// parameters need to match the indexes of the corresponding
// module names in aliasedModuleNames.
const importAliasNames: ParameterDeclaration[] = [];
// Fill in amd-dependency tags
for (const amdDependency of node.amdDependencies) {
if (amdDependency.name) {
aliasedModuleNames.push(factory.createStringLiteral(amdDependency.path));
importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
}
else {
unaliasedModuleNames.push(factory.createStringLiteral(amdDependency.path));
}
}
for (const importNode of currentModuleInfo.externalImports) {
// Find the name of the external module
const externalModuleName = getExternalModuleNameLiteral(factory, importNode, currentSourceFile, host, resolver, compilerOptions);
// Find the name of the module alias, if there is one
const importAliasName = getLocalNameForExternalImport(factory, importNode, currentSourceFile);
// It is possible that externalModuleName is undefined if it is not string literal.
// This can happen in the invalid import syntax.
// E.g : "import * from alias from 'someLib';"
if (externalModuleName) {
if (includeNonAmdDependencies && importAliasName) {
// Set emitFlags on the name of the classDeclaration
// This is so that when printer will not substitute the identifier
setEmitFlags(importAliasName, EmitFlags.NoSubstitution);
aliasedModuleNames.push(externalModuleName);
importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
}
else {
unaliasedModuleNames.push(externalModuleName);
}
}
}
return { aliasedModuleNames, unaliasedModuleNames, importAliasNames };
}
function getAMDImportExpressionForImport(node: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration) {
if (isImportEqualsDeclaration(node) || isExportDeclaration(node) || !getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions)) {
return undefined;
}
const name = getLocalNameForExternalImport(factory, node, currentSourceFile)!; // TODO: GH#18217
const expr = getHelperExpressionForImport(node, name);
if (expr === name) {
return undefined;
}
return factory.createExpressionStatement(factory.createAssignment(name, expr));
}
/**
* Transforms a SourceFile into an AMD or UMD module body.
*
* @param node The SourceFile node.
*/
function transformAsynchronousModuleBody(node: SourceFile) {
startLexicalEnvironment();
const statements: Statement[] = [];
const statementOffset = factory.copyPrologue(node.statements, statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, topLevelVisitor);
if (shouldEmitUnderscoreUnderscoreESModule()) {
append(statements, createUnderscoreUnderscoreESModule());
}
if (length(currentModuleInfo.exportedNames)) {
append(statements, factory.createExpressionStatement(reduceLeft(currentModuleInfo.exportedNames, (prev, nextId) => factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(idText(nextId))), prev), factory.createVoidZero() as Expression)));
}
// Visit each statement of the module body.
append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, topLevelVisitor, isStatement));
if (moduleKind === ModuleKind.AMD) {
addRange(statements, mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
}
addRange(statements, visitNodes(node.statements, topLevelVisitor, isStatement, statementOffset));
// Append the 'export =' statement if provided.
addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
// End the lexical environment for the module body
// and merge any new lexical declarations.
insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
const body = factory.createBlock(statements, /*multiLine*/ true);
if (needUMDDynamicImportHelper) {
addEmitHelper(body, dynamicImportUMDHelper);
}
return body;
}
/**
* Adds the down-level representation of `export=` to the statement list if one exists
* in the source file.
*
* @param statements The Statement list to modify.
* @param emitAsReturn A value indicating whether to emit the `export=` statement as a
* return statement.
*/
function addExportEqualsIfNeeded(statements: Statement[], emitAsReturn: boolean) {
if (currentModuleInfo.exportEquals) {
const expressionResult = visitNode(currentModuleInfo.exportEquals.expression, visitor);
if (expressionResult) {
if (emitAsReturn) {
const statement = factory.createReturnStatement(expressionResult);
setTextRange(statement, currentModuleInfo.exportEquals);
setEmitFlags(statement, EmitFlags.NoTokenSourceMaps | EmitFlags.NoComments);
statements.push(statement);
}
else {
const statement = factory.createExpressionStatement(
factory.createAssignment(
factory.createPropertyAccessExpression(
factory.createIdentifier("module"),
"exports"
),
expressionResult
)
);
setTextRange(statement, currentModuleInfo.exportEquals);
setEmitFlags(statement, EmitFlags.NoComments);
statements.push(statement);
}
}
}
}
//
// Top-Level Source Element Visitors
//
/**
* Visits a node at the top level of the source file.
*
* @param node The node to visit.
*/
function topLevelVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(node as ImportDeclaration);
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(node as ImportEqualsDeclaration);
case SyntaxKind.ExportDeclaration:
return visitExportDeclaration(node as ExportDeclaration);
case SyntaxKind.ExportAssignment:
return visitExportAssignment(node as ExportAssignment);
case SyntaxKind.VariableStatement:
return visitVariableStatement(node as VariableStatement);
case SyntaxKind.FunctionDeclaration:
return visitFunctionDeclaration(node as FunctionDeclaration);
case SyntaxKind.ClassDeclaration:
return visitClassDeclaration(node as ClassDeclaration);
case SyntaxKind.MergeDeclarationMarker:
return visitMergeDeclarationMarker(node as MergeDeclarationMarker);
case SyntaxKind.EndOfDeclarationMarker:
return visitEndOfDeclarationMarker(node as EndOfDeclarationMarker);
default:
return visitor(node);
}
}
function visitorWorker(node: Node, valueIsDiscarded: boolean): VisitResult<Node> {
// This visitor does not need to descend into the tree if there is no dynamic import, destructuring assignment, or update expression
// as export/import statements are only transformed at the top level of a file.
if (!(node.transformFlags & (TransformFlags.ContainsDynamicImport | TransformFlags.ContainsDestructuringAssignment | TransformFlags.ContainsUpdateExpressionForIdentifier))) {
return node;
}
switch (node.kind) {
case SyntaxKind.ForStatement:
return visitForStatement(node as ForStatement);
case SyntaxKind.ExpressionStatement:
return visitExpressionStatement(node as ExpressionStatement);
case SyntaxKind.ParenthesizedExpression:
return visitParenthesizedExpression(node as ParenthesizedExpression, valueIsDiscarded);
case SyntaxKind.PartiallyEmittedExpression:
return visitPartiallyEmittedExpression(node as PartiallyEmittedExpression, valueIsDiscarded);
case SyntaxKind.CallExpression:
if (isImportCall(node) && currentSourceFile.impliedNodeFormat === undefined) {
return visitImportCallExpression(node);
}
break;
case SyntaxKind.BinaryExpression:
if (isDestructuringAssignment(node)) {
return visitDestructuringAssignment(node, valueIsDiscarded);
}
break;
case SyntaxKind.PrefixUnaryExpression:
case SyntaxKind.PostfixUnaryExpression:
return visitPreOrPostfixUnaryExpression(node as PrefixUnaryExpression | PostfixUnaryExpression, valueIsDiscarded);
}
return visitEachChild(node, visitor, context);
}
function visitor(node: Node): VisitResult<Node> {
return visitorWorker(node, /*valueIsDiscarded*/ false);
}
function discardedValueVisitor(node: Node): VisitResult<Node> {
return visitorWorker(node, /*valueIsDiscarded*/ true);
}
function destructuringNeedsFlattening(node: Expression): boolean {
if (isObjectLiteralExpression(node)) {
for (const elem of node.properties) {
switch (elem.kind) {
case SyntaxKind.PropertyAssignment:
if (destructuringNeedsFlattening(elem.initializer)) {
return true;
}
break;
case SyntaxKind.ShorthandPropertyAssignment:
if (destructuringNeedsFlattening(elem.name)) {
return true;
}
break;
case SyntaxKind.SpreadAssignment:
if (destructuringNeedsFlattening(elem.expression)) {
return true;
}
break;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return false;
default: Debug.assertNever(elem, "Unhandled object member kind");
}
}
}
else if (isArrayLiteralExpression(node)) {
for (const elem of node.elements) {
if (isSpreadElement(elem)) {
if (destructuringNeedsFlattening(elem.expression)) {
return true;
}
}
else if (destructuringNeedsFlattening(elem)) {
return true;
}
}
}
else if (isIdentifier(node)) {
return length(getExports(node)) > (isExportName(node) ? 1 : 0);
}
return false;
}
function visitDestructuringAssignment(node: DestructuringAssignment, valueIsDiscarded: boolean): Expression {
if (destructuringNeedsFlattening(node.left)) {
return flattenDestructuringAssignment(node, visitor, context, FlattenLevel.All, !valueIsDiscarded, createAllExportExpressions);
}
return visitEachChild(node, visitor, context);
}
function visitForStatement(node: ForStatement) {
return factory.updateForStatement(
node,
visitNode(node.initializer, discardedValueVisitor, isForInitializer),
visitNode(node.condition, visitor, isExpression),
visitNode(node.incrementor, discardedValueVisitor, isExpression),
visitIterationBody(node.statement, visitor, context)
);
}
function visitExpressionStatement(node: ExpressionStatement) {
return factory.updateExpressionStatement(
node,
visitNode(node.expression, discardedValueVisitor, isExpression)
);
}
function visitParenthesizedExpression(node: ParenthesizedExpression, valueIsDiscarded: boolean) {
return factory.updateParenthesizedExpression(node, visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, isExpression));
}
function visitPartiallyEmittedExpression(node: PartiallyEmittedExpression, valueIsDiscarded: boolean) {
return factory.updatePartiallyEmittedExpression(node, visitNode(node.expression, valueIsDiscarded ? discardedValueVisitor : visitor, isExpression));
}
function visitPreOrPostfixUnaryExpression(node: PrefixUnaryExpression | PostfixUnaryExpression, valueIsDiscarded: boolean) {
// When we see a prefix or postfix increment expression whose operand is an exported
// symbol, we should ensure all exports of that symbol are updated with the correct
// value.
//
// - We do not transform generated identifiers for any reason.
// - We do not transform identifiers tagged with the LocalName flag.
// - We do not transform identifiers that were originally the name of an enum or
// namespace due to how they are transformed in TypeScript.
// - We only transform identifiers that are exported at the top level.
if ((node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken)
&& isIdentifier(node.operand)
&& !isGeneratedIdentifier(node.operand)
&& !isLocalName(node.operand)
&& !isDeclarationNameOfEnumOrNamespace(node.operand)) {
const exportedNames = getExports(node.operand);
if (exportedNames) {
let temp: Identifier | undefined;
let expression: Expression = visitNode(node.operand, visitor, isExpression);
if (isPrefixUnaryExpression(node)) {
expression = factory.updatePrefixUnaryExpression(node, expression);
}
else {
expression = factory.updatePostfixUnaryExpression(node, expression);
if (!valueIsDiscarded) {
temp = factory.createTempVariable(hoistVariableDeclaration);
expression = factory.createAssignment(temp, expression);
setTextRange(expression, node);
}
expression = factory.createComma(expression, factory.cloneNode(node.operand));
setTextRange(expression, node);
}
for (const exportName of exportedNames) {
noSubstitution[getNodeId(expression)] = true;
expression = createExportExpression(exportName, expression);
setTextRange(expression, node);
}
if (temp) {
noSubstitution[getNodeId(expression)] = true;
expression = factory.createComma(expression, temp);
setTextRange(expression, node);
}
return expression;
}
}
return visitEachChild(node, visitor, context);
}
function visitImportCallExpression(node: ImportCall): Expression {
const externalModuleName = getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions);
const firstArgument = visitNode(firstOrUndefined(node.arguments), visitor);
// Only use the external module name if it differs from the first argument. This allows us to preserve the quote style of the argument on output.
const argument = externalModuleName && (!firstArgument || !isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument;
const containsLexicalThis = !!(node.transformFlags & TransformFlags.ContainsLexicalThis);
switch (compilerOptions.module) {
case ModuleKind.AMD:
return createImportCallExpressionAMD(argument, containsLexicalThis);
case ModuleKind.UMD:
return createImportCallExpressionUMD(argument ?? factory.createVoidZero(), containsLexicalThis);
case ModuleKind.CommonJS:
default:
return createImportCallExpressionCommonJS(argument);
}
}
function createImportCallExpressionUMD(arg: Expression, containsLexicalThis: boolean): Expression {
// (function (factory) {
// ... (regular UMD)
// }
// })(function (require, exports, useSyncRequire) {
// "use strict";
// Object.defineProperty(exports, "__esModule", { value: true });
// var __syncRequire = typeof module === "object" && typeof module.exports === "object";
// var __resolved = new Promise(function (resolve) { resolve(); });
// .....
// __syncRequire
// ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
// : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
// });
needUMDDynamicImportHelper = true;
if (isSimpleCopiableExpression(arg)) {
const argClone = isGeneratedIdentifier(arg) ? arg : isStringLiteral(arg) ? factory.createStringLiteralFromNode(arg) : setEmitFlags(setTextRange(factory.cloneNode(arg), arg), EmitFlags.NoComments);
return factory.createConditionalExpression(
/*condition*/ factory.createIdentifier("__syncRequire"),
/*questionToken*/ undefined,
/*whenTrue*/ createImportCallExpressionCommonJS(arg),
/*colonToken*/ undefined,
/*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis)
);
}
else {
const temp = factory.createTempVariable(hoistVariableDeclaration);
return factory.createComma(factory.createAssignment(temp, arg), factory.createConditionalExpression(
/*condition*/ factory.createIdentifier("__syncRequire"),
/*questionToken*/ undefined,
/*whenTrue*/ createImportCallExpressionCommonJS(temp, /* isInlineable */ true),
/*colonToken*/ undefined,
/*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis)
));
}
}
function createImportCallExpressionAMD(arg: Expression | undefined, containsLexicalThis: boolean): Expression {
// improt("./blah")
// emit as
// define(["require", "exports", "blah"], function (require, exports) {
// ...
// new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
// });
const resolve = factory.createUniqueName("resolve");
const reject = factory.createUniqueName("reject");
const parameters = [
factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)
];
const body = factory.createBlock([
factory.createExpressionStatement(
factory.createCallExpression(
factory.createIdentifier("require"),
/*typeArguments*/ undefined,
[factory.createArrayLiteralExpression([arg || factory.createOmittedExpression()]), resolve, reject]
)
)
]);
let func: FunctionExpression | ArrowFunction;
if (languageVersion >= ScriptTarget.ES2015) {
func = factory.createArrowFunction(
/*modifiers*/ undefined,
/*typeParameters*/ undefined,
parameters,
/*type*/ undefined,
/*equalsGreaterThanToken*/ undefined,
body);
}
else {
func = factory.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
parameters,
/*type*/ undefined,
body);
// if there is a lexical 'this' in the import call arguments, ensure we indicate
// that this new function expression indicates it captures 'this' so that the
// es2015 transformer will properly substitute 'this' with '_this'.
if (containsLexicalThis) {
setEmitFlags(func, EmitFlags.CapturesThis);
}
}
const promise = factory.createNewExpression(factory.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
if (getESModuleInterop(compilerOptions)) {
return factory.createCallExpression(factory.createPropertyAccessExpression(promise, factory.createIdentifier("then")), /*typeArguments*/ undefined, [emitHelpers().createImportStarCallbackHelper()]);
}
return promise;
}
function createImportCallExpressionCommonJS(arg: Expression | undefined, isInlineable?: boolean): Expression {
// import(x)
// emit as
// var _a;
// (_a = x, Promise.resolve().then(() => require(_a)) /*CommonJs Require*/
// We have to wrap require in then callback so that require is done in asynchronously
// if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
// If the arg is not inlineable, we have to evaluate it in the current scope with a temp var
const temp = arg && !isSimpleInlineableExpression(arg) && !isInlineable ? factory.createTempVariable(hoistVariableDeclaration) : undefined;
const promiseResolveCall = factory.createCallExpression(
factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"),
/*typeArguments*/ undefined,
/*argumentsArray*/ [],
);
let requireCall: Expression = factory.createCallExpression(
factory.createIdentifier("require"),
/*typeArguments*/ undefined,
temp ? [temp] : arg ? [arg] : [],
);
if (getESModuleInterop(compilerOptions)) {
requireCall = emitHelpers().createImportStarHelper(requireCall);
}
let func: FunctionExpression | ArrowFunction;
if (languageVersion >= ScriptTarget.ES2015) {
func = factory.createArrowFunction(
/*modifiers*/ undefined,
/*typeParameters*/ undefined,
/*parameters*/ [],
/*type*/ undefined,
/*equalsGreaterThanToken*/ undefined,
requireCall);
}
else {
func = factory.createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
/*parameters*/ [],
/*type*/ undefined,
factory.createBlock([factory.createReturnStatement(requireCall)]));
}
const downleveledImport = factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
return temp === undefined ? downleveledImport : factory.createCommaListExpression([factory.createAssignment(temp, arg!), downleveledImport]);
}
function getHelperExpressionForExport(node: ExportDeclaration, innerExpr: Expression) {
if (!getESModuleInterop(compilerOptions) || getEmitFlags(node) & EmitFlags.NeverApplyImportHelper) {
return innerExpr;
}
if (getExportNeedsImportStarHelper(node)) {
return emitHelpers().createImportStarHelper(innerExpr);
}
return innerExpr;
}
function getHelperExpressionForImport(node: ImportDeclaration, innerExpr: Expression) {
if (!getESModuleInterop(compilerOptions) || getEmitFlags(node) & EmitFlags.NeverApplyImportHelper) {
return innerExpr;
}
if (getImportNeedsImportStarHelper(node)) {
return emitHelpers().createImportStarHelper(innerExpr);
}
if (getImportNeedsImportDefaultHelper(node)) {
return emitHelpers().createImportDefaultHelper(innerExpr);
}
return innerExpr;
}
/**
* Visits an ImportDeclaration node.
*
* @param node The node to visit.
*/
function visitImportDeclaration(node: ImportDeclaration): VisitResult<Statement> {
let statements: Statement[] | undefined;
const namespaceDeclaration = getNamespaceDeclarationNode(node);
if (moduleKind !== ModuleKind.AMD) {
if (!node.importClause) {
// import "mod";
return setOriginalNode(setTextRange(factory.createExpressionStatement(createRequireCall(node)), node), node);
}
else {
const variables: VariableDeclaration[] = [];
if (namespaceDeclaration && !isDefaultImport(node)) {
// import * as n from "mod";
variables.push(
factory.createVariableDeclaration(
factory.cloneNode(namespaceDeclaration.name),
/*exclamationToken*/ undefined,
/*type*/ undefined,
getHelperExpressionForImport(node, createRequireCall(node))
)
);
}
else {
// import d from "mod";
// import { x, y } from "mod";
// import d, { x, y } from "mod";
// import d, * as n from "mod";
variables.push(
factory.createVariableDeclaration(
factory.getGeneratedNameForNode(node),
/*exclamationToken*/ undefined,
/*type*/ undefined,
getHelperExpressionForImport(node, createRequireCall(node))
)
);
if (namespaceDeclaration && isDefaultImport(node)) {
variables.push(
factory.createVariableDeclaration(
factory.cloneNode(namespaceDeclaration.name),
/*exclamationToken*/ undefined,
/*type*/ undefined,
factory.getGeneratedNameForNode(node)
)
);
}
}
statements = append(statements,
setOriginalNode(
setTextRange(
factory.createVariableStatement(
/*modifiers*/ undefined,
factory.createVariableDeclarationList(
variables,
languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None
)
),
/*location*/ node),
/*original*/ node
)
);
}
}
else if (namespaceDeclaration && isDefaultImport(node)) {
// import d, * as n from "mod";
statements = append(statements,
factory.createVariableStatement(
/*modifiers*/ undefined,
factory.createVariableDeclarationList(
[
setOriginalNode(
setTextRange(
factory.createVariableDeclaration(
factory.cloneNode(namespaceDeclaration.name),
/*exclamationToken*/ undefined,
/*type*/ undefined,
factory.getGeneratedNameForNode(node)
),
/*location*/ node),
/*original*/ node
)
],
languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None
)
)
);
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
}
else {
statements = appendExportsOfImportDeclaration(statements, node);
}
return singleOrMany(statements);
}
/**