-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathbundle-generator.ts
1272 lines (1049 loc) · 49.1 KB
/
bundle-generator.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
import * as ts from 'typescript';
import { compileDts } from './compile-dts';
import { TypesUsageEvaluator } from './types-usage-evaluator';
import {
ExportType,
getActualSymbol,
getClosestModuleLikeNode,
getClosestSourceFileLikeNode,
getDeclarationsForExportedValues,
getDeclarationsForSymbol,
getExportReferencedSymbol,
getExportsForSourceFile,
getExportsForStatement,
getImportModuleName,
getNodeName,
getNodeOwnSymbol,
getNodeSymbol,
getRootSourceFile,
getSymbolExportStarDeclarations,
hasNodeModifier,
isAmbientModule,
isDeclareGlobalStatement,
isDeclareModule,
isNodeNamedDeclaration,
SourceFileExport,
splitTransientSymbol,
} from './helpers/typescript';
import {
getFileModuleInfo,
getModuleLikeModuleInfo,
getReferencedModuleInfo,
ModuleCriteria,
ModuleInfo,
ModuleType,
} from './module-info';
import { generateOutput, ModuleImportsSet, OutputInputData } from './generate-output';
import {
normalLog,
verboseLog,
warnLog,
} from './logger';
import { CollisionsResolver } from './collisions-resolver';
export interface CompilationOptions {
/**
* EXPERIMENTAL!
* Allows disable resolving of symlinks to the original path.
* By default following is enabled.
* @see https://github.com/timocov/dts-bundle-generator/issues/39
*/
followSymlinks?: boolean;
/**
* Path to the tsconfig file that will be used for the compilation.
*/
preferredConfigPath?: string;
}
export interface OutputOptions {
/**
* Sort output nodes in ascendant order.
*/
sortNodes?: boolean;
/**
* Name of the UMD module.
* If specified then `export as namespace ModuleName;` will be emitted.
*/
umdModuleName?: string;
/**
* Enables inlining of `declare global` statements contained in files which should be inlined (all local files and packages from inlined libraries).
*/
inlineDeclareGlobals?: boolean;
/**
* Enables inlining of `declare module` statements of the global modules
* (e.g. `declare module 'external-module' {}`, but NOT `declare module './internal-module' {}`)
* contained in files which should be inlined (all local files and packages from inlined libraries)
*/
inlineDeclareExternals?: boolean;
/**
* Allows remove "Generated by dts-bundle-generator" comment from the output
*/
noBanner?: boolean;
/**
* Enables stripping the `const` keyword from every direct-exported (or re-exported) from entry file `const enum`.
* This allows you "avoid" the issue described in https://github.com/microsoft/TypeScript/issues/37774.
*/
respectPreserveConstEnum?: boolean;
/**
* By default all interfaces, types and const enums are marked as exported even if they aren't exported directly.
* This option allows you to disable this behavior so a node will be exported if it is exported from root source file only.
*/
exportReferencedTypes?: boolean;
}
export interface LibrariesOptions {
/**
* Array of package names from node_modules to inline typings from.
* Used types will be inlined into the output file.
*/
inlinedLibraries?: string[];
/**
* Array of package names from node_modules to import typings from.
* Used types will be imported using `import { First, Second } from 'library-name';`.
* By default all libraries will be imported (except inlined libraries and libraries from @types).
*/
importedLibraries?: string[];
/**
* Array of package names from @types to import typings from via the triple-slash reference directive.
* By default all packages are allowed and will be used according to their usages.
*/
allowedTypesLibraries?: string[];
}
export interface EntryPointConfig {
/**
* Path to input file.
*/
filePath: string;
libraries?: LibrariesOptions;
/**
* Fail if generated dts contains class declaration.
*/
failOnClass?: boolean;
output?: OutputOptions;
}
export function generateDtsBundle(entries: readonly EntryPointConfig[], options: CompilationOptions = {}): string[] {
normalLog('Compiling input files...');
const { program, rootFilesRemapping } = compileDts(entries.map((entry: EntryPointConfig) => entry.filePath), options.preferredConfigPath, options.followSymlinks);
const typeChecker = program.getTypeChecker();
const typeRoots = ts.getEffectiveTypeRoots(program.getCompilerOptions(), {});
const sourceFiles = program.getSourceFiles().filter((file: ts.SourceFile) => {
return !program.isSourceFileDefaultLibrary(file);
});
verboseLog(`Input source files:\n ${sourceFiles.map((file: ts.SourceFile) => file.fileName).join('\n ')}`);
const typesUsageEvaluator = new TypesUsageEvaluator(sourceFiles, typeChecker);
return entries.map((entryConfig: EntryPointConfig) => {
normalLog(`Processing ${entryConfig.filePath}`);
const newRootFilePath = rootFilesRemapping.get(entryConfig.filePath);
if (newRootFilePath === undefined) {
throw new Error(`Cannot remap root source file ${entryConfig.filePath}`);
}
const rootSourceFile = getRootSourceFile(program, newRootFilePath);
const rootSourceFileSymbol = typeChecker.getSymbolAtLocation(rootSourceFile);
if (rootSourceFileSymbol === undefined) {
throw new Error(`Symbol for root source file ${newRootFilePath} not found`);
}
const librariesOptions: LibrariesOptions = entryConfig.libraries || {};
const criteria: ModuleCriteria = {
allowedTypesLibraries: librariesOptions.allowedTypesLibraries,
importedLibraries: librariesOptions.importedLibraries,
inlinedLibraries: librariesOptions.inlinedLibraries || [],
typeRoots,
};
const rootFileExports = getExportsForSourceFile(typeChecker, rootSourceFileSymbol);
const rootFileExportSymbols = rootFileExports.map((exp: SourceFileExport) => exp.symbol);
interface CollectingResult extends Omit<OutputInputData, 'statements'> {
statements: ts.Statement[];
}
const collectionResult: CollectingResult = {
typesReferences: new Set(),
imports: new Map(),
statements: [],
renamedExports: new Map(),
wrappedNamespaces: new Map(),
};
const outputOptions: OutputOptions = entryConfig.output || {};
const inlineDeclareGlobals = Boolean(outputOptions.inlineDeclareGlobals);
const collisionsResolver = new CollisionsResolver(typeChecker);
function updateResultForAnyModule(statements: readonly ts.Statement[], currentModule: ModuleInfo): void {
// contains a set of modules that were visited already
// can be used to prevent infinite recursion in updating results in re-exports
const visitedModules = new Set<string>();
function updateResultForExternalExport(exportAssignment: ts.ExportAssignment | ts.ExportDeclaration): void {
// if we have `export =` or `export * from` somewhere so we can decide that every declaration of exported symbol in this way
// is "part of the exported module" and we need to update result according every member of each declaration
// but treat they as current module (we do not need to update module info)
for (const declaration of getDeclarationsForExportedValues(exportAssignment, typeChecker)) {
if (ts.isVariableDeclaration(declaration)) {
// variables will be processed separately anyway so no need to process them again here
continue;
}
let exportedDeclarations: readonly ts.Statement[] = [];
if (ts.isExportDeclaration(exportAssignment) && ts.isSourceFile(declaration)) {
const referencedModule = getReferencedModuleInfo(exportAssignment, criteria, typeChecker);
if (referencedModule !== null) {
if (visitedModules.has(referencedModule.fileName)) {
continue;
}
visitedModules.add(referencedModule.fileName);
}
exportedDeclarations = declaration.statements;
} else if (ts.isModuleDeclaration(declaration)) {
if (declaration.body !== undefined && ts.isModuleBlock(declaration.body)) {
const referencedModule = getReferencedModuleInfo(declaration, criteria, typeChecker);
if (referencedModule !== null) {
if (visitedModules.has(referencedModule.fileName)) {
continue;
}
visitedModules.add(referencedModule.fileName);
}
exportedDeclarations = declaration.body.statements;
}
} else {
exportedDeclarations = [declaration as unknown as ts.Statement];
}
updateResultImpl(exportedDeclarations);
}
}
// eslint-disable-next-line complexity
function updateResultImpl(statementsToProcess: readonly ts.Statement[]): void {
for (const statement of statementsToProcess) {
// we should skip import statements
if (statement.kind === ts.SyntaxKind.ImportDeclaration || statement.kind === ts.SyntaxKind.ImportEqualsDeclaration) {
continue;
}
if (isDeclareModule(statement)) {
updateResultForModuleDeclaration(statement, currentModule);
// if a statement is `declare module "module" {}` then don't process it below
// as it is handled already in `updateResultForModuleDeclaration`
// but if it is `declare module Module {}` then it can be used in types and imports
// so in this case it needs to be checked for "usages" below
if (ts.isStringLiteral(statement.name)) {
continue;
}
}
if (currentModule.type === ModuleType.ShouldBeUsedForModulesOnly) {
continue;
}
if (isDeclareGlobalStatement(statement) && inlineDeclareGlobals && currentModule.type === ModuleType.ShouldBeInlined) {
collectionResult.statements.push(statement);
continue;
}
if (ts.isExportDeclaration(statement)) {
if (currentModule.type === ModuleType.ShouldBeInlined) {
continue;
}
// `export * from`
if (statement.exportClause === undefined) {
updateResultForExternalExport(statement);
continue;
}
// `export { val }`
if (ts.isNamedExports(statement.exportClause) && currentModule.type === ModuleType.ShouldBeImported) {
updateImportsForStatement(statement);
continue;
}
}
if (ts.isExportAssignment(statement) && statement.isExportEquals && currentModule.type !== ModuleType.ShouldBeInlined) {
updateResultForExternalExport(statement);
continue;
}
if (!isNodeUsed(statement)) {
continue;
}
switch (currentModule.type) {
case ModuleType.ShouldBeReferencedAsTypes:
addTypesReference(currentModule.typesLibraryName);
break;
case ModuleType.ShouldBeImported:
updateImportsForStatement(statement);
break;
case ModuleType.ShouldBeInlined: {
if (ts.isVariableStatement(statement)) {
for (const variableDeclaration of statement.declarationList.declarations) {
if (ts.isIdentifier(variableDeclaration.name)) {
const name = collisionsResolver.addTopLevelIdentifier(variableDeclaration.name);
if (!isSymbolOfNonValue(getNodeSymbol(variableDeclaration, typeChecker)!)) {
const statementExports = getExportsForStatement(rootFileExports, typeChecker, statement);
statementExports.forEach((exp: SourceFileExport) => {
if (isSymbolOfNonValue(exp.originalSymbol)) {
collectionResult.renamedExports.set(exp.exportedName, { localSymbolName: name, asType: true });
}
});
}
}
// it seems that the compiler doesn't produce anything else (e.g. binding elements) in declaration files
// but it is still possible to write such code manually
// this feels like quite rare case so no support for now
}
} else if (isNodeNamedDeclaration(statement)) {
const statementName = getNodeName(statement);
if (statementName !== undefined) {
const name = collisionsResolver.addTopLevelIdentifier(statementName as ts.Identifier | ts.DefaultKeyword);
if (!isSymbolOfNonValue(getNodeSymbol(statement, typeChecker)!)) {
const statementExports = getExportsForStatement(rootFileExports, typeChecker, statement);
statementExports.forEach((exp: SourceFileExport) => {
if (isSymbolOfNonValue(exp.originalSymbol)) {
collectionResult.renamedExports.set(exp.exportedName, { localSymbolName: name, asType: true });
}
});
}
}
}
collectionResult.statements.push(statement);
break;
}
}
}
}
updateResultImpl(statements);
}
function isReferencedModuleImportable(statement: ts.ExportDeclaration | ts.ImportDeclaration): boolean {
return getReferencedModuleInfo(statement, criteria, typeChecker)?.type === ModuleType.ShouldBeImported;
}
function handleExportDeclarationFromRootModule(exportDeclaration: ts.ExportDeclaration): void {
function handleExportStarStatement(exportStarStatement: ts.ExportDeclaration, visitedSymbols: Set<ts.Symbol> = new Set()): void {
if (exportStarStatement.moduleSpecifier === undefined || exportStarStatement.exportClause !== undefined) {
throw new Error(`Invalid export-star declaration statement provided, ${exportStarStatement.getText()}`);
}
const importModuleSpecifier = getImportModuleName(exportStarStatement);
if (importModuleSpecifier === null) {
return;
}
const referencedModuleInfo = getReferencedModuleInfo(exportStarStatement, criteria, typeChecker);
if (referencedModuleInfo === null) {
return;
}
switch (referencedModuleInfo.type) {
case ModuleType.ShouldBeInlined: {
// `export * from './inlined-module'`
const referencedModuleSymbol = getNodeOwnSymbol(exportStarStatement.moduleSpecifier, typeChecker);
const referencedSourceFileExportStarSymbol = referencedModuleSymbol.exports?.get(ts.InternalSymbolName.ExportStar);
if (referencedSourceFileExportStarSymbol !== undefined) {
if (visitedSymbols.has(referencedSourceFileExportStarSymbol)) {
return;
}
visitedSymbols.add(referencedSourceFileExportStarSymbol);
// we need to go recursive for all `export * from` statements and add all that are from imported modules
for (const exportDecl of getSymbolExportStarDeclarations(referencedSourceFileExportStarSymbol)) {
handleExportStarStatement(exportDecl, visitedSymbols);
}
}
break;
}
case ModuleType.ShouldBeImported: {
// `export * from 'importable-package'`
collectionResult.statements.push(exportStarStatement);
break;
}
}
}
interface ExportingExportStarExport {
exportStarDeclaration: ts.ExportDeclaration;
exportedNodeSymbol: ts.Symbol;
}
/**
* This function returns an export-star object that exports given {@link nodeSymbol} symbol.
* If an exporting export declaration object is not from an importable module then `null` is returned.
* Also if the symbol is exported explicitly (i.e. via `export { Name }` or specifying `export` keyword next to the node) then `null` is returned as well.
*/
function findExportingExportStarExportFromImportableModule(referencedModuleSymbol: ts.Symbol, nodeSymbol: ts.Symbol): ExportingExportStarExport | null {
function findResultRecursively(referencedModuleSym: ts.Symbol, exportedNodeSym: ts.Symbol, visitedSymbols: Set<ts.Symbol>): ExportingExportStarExport | null {
// prevent infinite recursion
if (visitedSymbols.has(referencedModuleSym)) {
return null;
}
visitedSymbols.add(referencedModuleSym);
// `export * from` exports always have less priority over explicit exports so it should go last
const exportStarExport = referencedModuleSym.exports?.get(ts.InternalSymbolName.ExportStar);
if (exportStarExport === undefined) {
return null;
}
for (const exportStarDeclaration of getDeclarationsForSymbol(exportStarExport).filter(ts.isExportDeclaration)) {
if (exportStarDeclaration.moduleSpecifier === undefined) {
// this seems impossible, but to make the compiler/types happy
continue;
}
const exportStarModuleSymbol = getNodeOwnSymbol(exportStarDeclaration.moduleSpecifier, typeChecker);
if (exportStarModuleSymbol.exports === undefined) {
continue;
}
if (isReferencedModuleImportable(exportStarDeclaration)) {
// for "importable" modules we don't need to go deeper or even check "explicit" exports
// as it doesn't matter how its done internally and we care about "public" interface only
// so we can just check whether it exports a symbol or not (irregardless of how it is exported exactly internally)
const referencedModuleExports = typeChecker.getExportsOfModule(exportStarModuleSymbol);
const exportedNodeSymbol = referencedModuleExports.find((exp: ts.Symbol) => getActualSymbol(exp, typeChecker) === nodeSymbol);
if (exportedNodeSymbol !== undefined) {
return { exportStarDeclaration, exportedNodeSymbol };
}
continue;
}
const result = findResultRecursively(exportStarModuleSymbol, exportedNodeSym, visitedSymbols);
if (result !== null) {
return result;
}
}
return null;
}
if (referencedModuleSymbol.exports === undefined) {
throw new Error(`No exports found for "${referencedModuleSymbol.getName()}" symbol`);
}
const hasExplicitExportOfSymbol = Array.from(referencedModuleSymbol.exports.values()).some((exp: ts.Symbol) => {
if (exp.escapedName === ts.InternalSymbolName.ExportStar) {
return false;
}
return getActualSymbol(exp, typeChecker) === nodeSymbol;
});
if (hasExplicitExportOfSymbol) {
// symbol is exported explicitly ¯\_(ツ)_/¯
return null;
}
return findResultRecursively(referencedModuleSymbol, nodeSymbol, new Set());
}
// `export * from 'module'`
if (exportDeclaration.exportClause === undefined) {
handleExportStarStatement(exportDeclaration);
return;
}
if (exportDeclaration.exportClause !== undefined && ts.isNamedExports(exportDeclaration.exportClause)) {
// `export { val, val2 }`
if (exportDeclaration.moduleSpecifier === undefined) {
for (const exportElement of exportDeclaration.exportClause.elements) {
const exportElementSymbol = getExportReferencedSymbol(exportElement, typeChecker);
const namespaceImportFromImportableModule = getDeclarationsForSymbol(exportElementSymbol).find((importDecl: ts.Declaration): importDecl is ts.NamespaceImport => {
return ts.isNamespaceImport(importDecl) && isReferencedModuleImportable(importDecl.parent.parent);
});
if (namespaceImportFromImportableModule !== undefined) {
const importModuleSpecifier = getImportModuleName(namespaceImportFromImportableModule.parent.parent);
if (importModuleSpecifier === null) {
throw new Error(`Cannot get import module name from '${namespaceImportFromImportableModule.parent.parent.getText()}'`);
}
addNsImport(
getImportItem(importModuleSpecifier),
namespaceImportFromImportableModule.name
);
}
}
return;
}
// `export { val, val2 } from 'module'`
if (exportDeclaration.moduleSpecifier !== undefined) {
const referencedModuleSymbol = getNodeOwnSymbol(exportDeclaration.moduleSpecifier, typeChecker);
// in this case we want to find all elements that we re-exported via `export * from` exports as they aren't handled elsewhere
for (const exportElement of exportDeclaration.exportClause.elements) {
const exportedNodeSymbol = getActualSymbol(getExportReferencedSymbol(exportElement, typeChecker), typeChecker);
const exportingExportStarResult = findExportingExportStarExportFromImportableModule(
referencedModuleSymbol,
exportedNodeSymbol
);
if (exportingExportStarResult === null) {
continue;
}
const importModuleSpecifier = getImportModuleName(exportingExportStarResult.exportStarDeclaration);
if (importModuleSpecifier === null) {
throw new Error(`Cannot get import module name from '${exportingExportStarResult.exportStarDeclaration.getText()}'`);
}
// technically we could use named imports and then add re-exports
// but this solution affects names scope (re-exports don't affect it)
// and also it is slightly complicated to find a name declaration (identifier) that needs to be imported
// so it feels better to go this way, but happy to change in the future if there would be any issues
addReExport(
getImportItem(importModuleSpecifier),
exportingExportStarResult.exportedNodeSymbol.getName(),
exportElement.name.text
);
}
return;
}
}
}
function updateResultForRootModule(statements: readonly ts.Statement[], currentModule: ModuleInfo): void {
updateResultForAnyModule(statements, currentModule);
// add skipped by `updateResult` exports
for (const statement of statements) {
if (ts.isExportDeclaration(statement)) {
handleExportDeclarationFromRootModule(statement);
continue;
}
if (ts.isExportAssignment(statement)) {
// `"export ="` or `export default 123` or `export default "str"`
if (statement.isExportEquals || !ts.isIdentifier(statement.expression)) {
collectionResult.statements.push(statement);
}
continue;
}
}
}
function updateResultForModuleDeclaration(moduleDecl: ts.ModuleDeclaration, currentModule: ModuleInfo): void {
if (moduleDecl.body === undefined || !ts.isModuleBlock(moduleDecl.body)) {
return;
}
const referencedModuleInfo = getReferencedModuleInfo(moduleDecl, criteria, typeChecker);
if (referencedModuleInfo === null) {
return;
}
// if we have declaration of external module inside internal one
if (!currentModule.isExternal && referencedModuleInfo.isExternal) {
// if it's allowed - we need to just add it to result without any processing
if (outputOptions.inlineDeclareExternals) {
collectionResult.statements.push(moduleDecl);
}
return;
}
updateResultForAnyModule(moduleDecl.body.statements, referencedModuleInfo);
}
function addTypesReference(library: string): void {
if (!collectionResult.typesReferences.has(library)) {
normalLog(`Library "${library}" will be added via reference directive`);
collectionResult.typesReferences.add(library);
}
}
function updateImportsForStatement(statement: ts.Statement | ts.SourceFile | ts.ExportSpecifier): void {
const statementsToImport = ts.isVariableStatement(statement)
? statement.declarationList.declarations
: ts.isExportDeclaration(statement) && statement.exportClause !== undefined
? ts.isNamespaceExport(statement.exportClause)
? [statement.exportClause]
: statement.exportClause.elements
: [statement];
for (const statementToImport of statementsToImport) {
if (shouldNodeBeImported(statementToImport as ts.DeclarationStatement)) {
addImport(statementToImport as ts.DeclarationStatement);
// if we're going to add import of any statement in the bundle
// we should check whether the library of that statement
// could be referenced via triple-slash reference-types directive
// because the project which will use bundled declaration file
// can have `types: []` in the tsconfig and it'll fail
// this is especially related to the types packages
// which declares different modules in their declarations
// e.g. @types/node has declaration for "packages" events, fs, path and so on
const sourceFile = statementToImport.getSourceFile();
const moduleInfo = getFileModuleInfo(sourceFile.fileName, criteria);
if (moduleInfo.type === ModuleType.ShouldBeReferencedAsTypes) {
addTypesReference(moduleInfo.typesLibraryName);
}
}
}
}
function getDeclarationUsagesSourceFiles(declaration: ts.NamedDeclaration): Set<ts.SourceFile | ts.ModuleDeclaration> {
return new Set(
getExportedSymbolsUsingStatement(declaration)
.map((symbol: ts.Symbol) => getDeclarationsForSymbol(symbol))
.reduce((acc: ts.Declaration[], val: ts.Declaration[]) => acc.concat(val), [])
.map(getClosestModuleLikeNode)
);
}
function getImportItem(importModuleSpecifier: string): ModuleImportsSet {
let importItem = collectionResult.imports.get(importModuleSpecifier);
if (importItem === undefined) {
importItem = {
defaultImports: new Set(),
namedImports: new Map(),
nsImport: null,
requireImports: new Set(),
reExports: new Map(),
};
collectionResult.imports.set(importModuleSpecifier, importItem);
}
return importItem;
}
function addRequireImport(importItem: ModuleImportsSet, preferredLocalName: ts.Identifier): void {
importItem.requireImports.add(collisionsResolver.addTopLevelIdentifier(preferredLocalName));
}
function addNamedImport(importItem: ModuleImportsSet, preferredLocalName: ts.Identifier, importedIdentifier: ts.Identifier): void {
const newLocalName = collisionsResolver.addTopLevelIdentifier(preferredLocalName);
const importedName = importedIdentifier.text;
importItem.namedImports.set(newLocalName, importedName);
}
function addReExport(importItem: ModuleImportsSet, moduleExportedName: string, reExportedName: string): void {
// re-exports don't affect local names scope so we don't need to register them in collisions resolver
importItem.reExports.set(reExportedName, moduleExportedName);
}
function addNsImport(importItem: ModuleImportsSet, preferredLocalName: ts.Identifier): void {
if (importItem.nsImport === null) {
importItem.nsImport = collisionsResolver.addTopLevelIdentifier(preferredLocalName);
}
}
function addDefaultImport(importItem: ModuleImportsSet, preferredLocalName: ts.Identifier): void {
importItem.defaultImports.add(collisionsResolver.addTopLevelIdentifier(preferredLocalName));
}
function addImport(statement: ts.DeclarationStatement | ts.SourceFile): void {
if (!ts.isSourceFile(statement) && statement.name === undefined) {
throw new Error(`Import/usage unnamed declaration: ${statement.getText()}`);
}
getDeclarationUsagesSourceFiles(statement).forEach((sourceFile: ts.SourceFile | ts.ModuleDeclaration) => {
if (getModuleLikeModuleInfo(sourceFile, criteria, typeChecker).type !== ModuleType.ShouldBeInlined) {
// we should ignore source files that aren't inlined
return;
}
const sourceFileStatements: readonly ts.Statement[] = ts.isSourceFile(sourceFile)
? sourceFile.statements
: sourceFile.body !== undefined && ts.isModuleBlock(sourceFile.body)
? sourceFile.body.statements
: []
;
// eslint-disable-next-line complexity
sourceFileStatements.forEach((st: ts.Statement) => {
if (!ts.isImportEqualsDeclaration(st) && !ts.isImportDeclaration(st) && !ts.isExportDeclaration(st)) {
return;
}
const importModuleSpecifier = getImportModuleName(st);
if (importModuleSpecifier === null) {
return;
}
const referencedModuleInfo = getReferencedModuleInfo(st, criteria, typeChecker);
// if a referenced module should be inlined we can just ignore it
if (referencedModuleInfo === null || referencedModuleInfo.type !== ModuleType.ShouldBeImported) {
return;
}
const importItem = getImportItem(importModuleSpecifier);
if (ts.isImportEqualsDeclaration(st)) {
if (areDeclarationSame(statement, st)) {
addRequireImport(importItem, st.name);
}
return;
}
if (ts.isExportDeclaration(st) && st.exportClause !== undefined) {
if (ts.isNamedExports(st.exportClause)) {
// export { El1, El2 as ExportedName } from 'module';
st.exportClause.elements
.filter(areDeclarationSame.bind(null, statement))
.forEach((specifier: ts.ExportSpecifier) => {
addNamedImport(importItem, specifier.name, specifier.propertyName || specifier.name);
});
} else {
// export * as name from 'module';
if (isNodeUsed(st.exportClause)) {
addNsImport(importItem, st.exportClause.name);
}
}
} else if (ts.isImportDeclaration(st) && st.importClause !== undefined) {
if (st.importClause.name !== undefined && areDeclarationSame(statement, st.importClause)) {
// import name from 'module';
addDefaultImport(importItem, st.importClause.name);
}
if (st.importClause.namedBindings !== undefined) {
if (ts.isNamedImports(st.importClause.namedBindings)) {
// import { El1, El2 as ImportedName } from 'module';
st.importClause.namedBindings.elements
.filter(areDeclarationSame.bind(null, statement))
.forEach((specifier: ts.ImportSpecifier) => {
addNamedImport(importItem, specifier.name, specifier.propertyName || specifier.name);
});
} else {
// import * as name from 'module';
if (isNodeUsed(st.importClause)) {
addNsImport(importItem, st.importClause.namedBindings.name);
}
}
}
}
});
});
}
function getGlobalSymbolsUsingSymbol(symbol: ts.Symbol): ts.Symbol[] {
return Array.from(typesUsageEvaluator.getSymbolsUsingSymbol(symbol) ?? []).filter((usedInSymbol: ts.Symbol) => {
if (usedInSymbol.escapedName !== ts.InternalSymbolName.Global) {
return false;
}
return getDeclarationsForSymbol(usedInSymbol).some((decl: ts.Declaration) => {
const closestModuleLike = getClosestSourceFileLikeNode(decl);
const moduleInfo = getModuleLikeModuleInfo(closestModuleLike, criteria, typeChecker);
return moduleInfo.type === ModuleType.ShouldBeInlined;
});
});
}
function isNodeUsed(node: ts.Node): boolean {
if (isNodeNamedDeclaration(node) || ts.isSourceFile(node)) {
const nodeSymbol = getNodeSymbol(node, typeChecker);
if (nodeSymbol === null) {
return false;
}
const nodeUsedByDirectExports = rootFileExportSymbols.some((rootExport: ts.Symbol) => typesUsageEvaluator.isSymbolUsedBySymbol(nodeSymbol, rootExport));
if (nodeUsedByDirectExports) {
return true;
}
return inlineDeclareGlobals && getGlobalSymbolsUsingSymbol(nodeSymbol).length !== 0;
} else if (ts.isVariableStatement(node)) {
return node.declarationList.declarations.some((declaration: ts.VariableDeclaration) => {
return isNodeUsed(declaration);
});
} else if (ts.isExportDeclaration(node) && node.exportClause !== undefined && ts.isNamespaceExport(node.exportClause)) {
return isNodeUsed(node.exportClause);
} else if (ts.isImportClause(node) && node.namedBindings !== undefined) {
return isNodeUsed(node.namedBindings);
}
return false;
}
function shouldNodeBeImported(node: ts.NamedDeclaration): boolean {
const nodeSymbol = getNodeSymbol(node, typeChecker);
if (nodeSymbol === null) {
return false;
}
return shouldSymbolBeImported(nodeSymbol);
}
function shouldSymbolBeImported(nodeSymbol: ts.Symbol): boolean {
const isSymbolDeclaredInDefaultLibrary = getDeclarationsForSymbol(nodeSymbol).some(
(declaration: ts.Declaration) => program.isSourceFileDefaultLibrary(declaration.getSourceFile())
);
if (isSymbolDeclaredInDefaultLibrary) {
// we shouldn't import a node declared in the default library (such dom, es2015)
// yeah, actually we should check that node is declared only in the default lib
// but it seems we can check that at least one declaration is from default lib
// to treat the node as un-importable
// because we can't re-export declared somewhere else node with declaration merging
// also, if some lib file will not be added to the project
// for example like it is described in the react declaration file (e.g. React Native)
// then here we still have a bug with "importing global declaration from a package"
// (see https://github.com/timocov/dts-bundle-generator/issues/71)
// but I don't think it is a big problem for now
// and it's possible that it will be fixed in https://github.com/timocov/dts-bundle-generator/issues/59
return false;
}
const symbolsDeclarations = getDeclarationsForSymbol(nodeSymbol);
// if all declarations of the symbol are in modules that should be inlined then this symbol must be inlined, not imported
const shouldSymbolBeInlined = symbolsDeclarations.every(
(decl: ts.Declaration) => getModuleLikeModuleInfo(
getClosestSourceFileLikeNode(decl),
criteria,
typeChecker
).type === ModuleType.ShouldBeInlined
);
if (shouldSymbolBeInlined) {
return false;
}
return getExportedSymbolsUsingSymbol(nodeSymbol).length !== 0;
}
function getExportedSymbolsUsingStatement(node: ts.NamedDeclaration): readonly ts.Symbol[] {
const nodeSymbol = getNodeSymbol(node, typeChecker);
if (nodeSymbol === null) {
return [];
}
return getExportedSymbolsUsingSymbol(nodeSymbol);
}
function getExportedSymbolsUsingSymbol(nodeSymbol: ts.Symbol): readonly ts.Symbol[] {
const symbolsUsingNode = typesUsageEvaluator.getSymbolsUsingSymbol(nodeSymbol);
if (symbolsUsingNode === null) {
throw new Error(`Something went wrong - getSymbolsUsingSymbol returned null but expected to be a set of symbols (symbol=${nodeSymbol.name})`);
}
return [
...(rootFileExportSymbols.includes(nodeSymbol) ? [nodeSymbol] : []),
// symbols which are used in types directly
...Array.from(symbolsUsingNode).filter((symbol: ts.Symbol) => {
const symbolsDeclarations = getDeclarationsForSymbol(symbol);
if (symbolsDeclarations.length === 0 || symbolsDeclarations.every((decl: ts.Declaration) => {
// we need to make sure that at least 1 declaration is inlined
return getModuleLikeModuleInfo(getClosestSourceFileLikeNode(decl), criteria, typeChecker).type !== ModuleType.ShouldBeInlined;
})) {
return false;
}
return rootFileExportSymbols.some((rootSymbol: ts.Symbol) => typesUsageEvaluator.isSymbolUsedBySymbol(symbol, rootSymbol));
}),
// symbols which are used in global types i.e. in `declare global`s
...(inlineDeclareGlobals ? getGlobalSymbolsUsingSymbol(nodeSymbol) : []),
];
}
function areDeclarationSame(left: ts.NamedDeclaration, right: ts.NamedDeclaration): boolean {
const leftSymbols = splitTransientSymbol(getNodeSymbol(left, typeChecker) as ts.Symbol, typeChecker);
const rightSymbols = splitTransientSymbol(getNodeSymbol(right, typeChecker) as ts.Symbol, typeChecker);
for (const leftSymbol of leftSymbols) {
if (rightSymbols.has(leftSymbol)) {
return true;
}
}
return false;
}
function createNamespaceForExports(exports: ts.SymbolTable, namespaceSymbol: ts.Symbol): string | null {
function addSymbolToNamespaceExports(namespaceExports: Map<string, string>, symbol: ts.Symbol): void {
const symbolKnownNames = collisionsResolver.namesForSymbol(symbol);
if (symbolKnownNames.size === 0) {
throw new Error(`Cannot get local names for symbol '${symbol.getName()}' while generating namespaced export`);
}
namespaceExports.set(symbol.getName(), Array.from(symbolKnownNames)[0]);
}
function handleNamespacedImportOrExport(namespacedImportOrExport: ts.ExportDeclaration | ts.ImportDeclaration, namespaceExports: Map<string, string>, symbol: ts.Symbol): void {
if (namespacedImportOrExport.moduleSpecifier === undefined) {
return;
}
if (isReferencedModuleImportable(namespacedImportOrExport)) {
// in case of an external export statement we should copy it as is
// here we assume that a namespace import will be added in other places
// so here we can just add re-export
addSymbolToNamespaceExports(namespaceExports, symbol);
return;
}
const referencedSourceFileSymbol = getNodeOwnSymbol(namespacedImportOrExport.moduleSpecifier, typeChecker);
if (referencedSourceFileSymbol.exports === undefined) {
return;
}
if (ts.isImportDeclaration(namespacedImportOrExport) && referencedSourceFileSymbol.exports.has(ts.InternalSymbolName.ExportEquals)) {
// in case of handling `import * as Ns` statements with `export =` export in a module we need to ignore it
// as that import will be renamed later
return;
}
const localNamespaceName = createNamespaceForExports(referencedSourceFileSymbol.exports, symbol);
if (localNamespaceName !== null) {
namespaceExports.set(symbol.getName(), localNamespaceName);
}
}
function processExportSymbol(namespaceExports: Map<string, string>, symbol: ts.Symbol): void {
if (symbol.escapedName === ts.InternalSymbolName.ExportStar) {
// this means that an export contains `export * from 'module'` statement
for (const exportStarDeclaration of getSymbolExportStarDeclarations(symbol)) {
if (exportStarDeclaration.moduleSpecifier === undefined) {
throw new Error(`Export star declaration does not have a module specifier '${exportStarDeclaration.getText()}'`);
}
if (isReferencedModuleImportable(exportStarDeclaration)) {
// in case of re-exporting from other modules directly we should import everything and re-export manually
// but it is not supported yet so lets just fail for now
throw new Error(`Having a re-export from an importable module as a part of namespaced export is not supported yet.`);
}
const referencedSourceFileSymbol = getNodeOwnSymbol(exportStarDeclaration.moduleSpecifier, typeChecker);
referencedSourceFileSymbol.exports?.forEach(
processExportSymbol.bind(null, namespaceExports)
);
}
return;
}
symbol.declarations?.forEach((decl: ts.Declaration) => {
if (ts.isNamespaceExport(decl) && decl.parent.moduleSpecifier !== undefined) {
handleNamespacedImportOrExport(decl.parent, namespaceExports, symbol);
return;
}
if (ts.isExportSpecifier(decl)) {
const exportElementSymbol = getExportReferencedSymbol(decl, typeChecker);
const namespaceImport = getDeclarationsForSymbol(exportElementSymbol).find(ts.isNamespaceImport);
if (namespaceImport !== undefined) {
handleNamespacedImportOrExport(namespaceImport.parent.parent, namespaceExports, symbol);
}
return;
}
});
addSymbolToNamespaceExports(namespaceExports, symbol);
}
// handling namespaced re-exports/imports
// e.g. `export * as NS from './local-module';` or `import * as NS from './local-module'; export { NS }`
for (const decl of getDeclarationsForSymbol(namespaceSymbol)) {
if (!ts.isNamespaceExport(decl) && !ts.isExportSpecifier(decl)) {
continue;
}
// if it is namespace export then it should be from a inlined module (e.g. `export * as NS from './local-module';`)