@ssets/dts 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2801 @@
1
+ // src/bundle-generator.ts
2
+ import * as ts9 from "typescript";
3
+
4
+ // src/compile-dts.ts
5
+ import * as ts3 from "typescript";
6
+
7
+ // src/logger.ts
8
+ function verboseLog(message) {
9
+ logMessage(message, 0 /* Verbose */);
10
+ }
11
+ function normalLog(message) {
12
+ logMessage(message, 1 /* Normal */);
13
+ }
14
+ function warnLog(message) {
15
+ logMessage(message, 2 /* Warning */);
16
+ }
17
+ function errorLog(message) {
18
+ logMessage(message, 3 /* Error */);
19
+ }
20
+ var currentLogLevel = 3 /* Error */;
21
+ function logMessage(message, level = 0 /* Verbose */) {
22
+ if (level < currentLogLevel) {
23
+ return;
24
+ }
25
+ switch (level) {
26
+ case 3 /* Error */:
27
+ console.error(`\x1B[0;31m${message}\x1B[0m`);
28
+ break;
29
+ case 2 /* Warning */:
30
+ console.warn(`\x1B[1;33m${message}\x1B[0m`);
31
+ break;
32
+ case 1 /* Normal */:
33
+ case 0 /* Verbose */:
34
+ console.log(message);
35
+ }
36
+ }
37
+
38
+ // src/get-compiler-options.ts
39
+ import * as ts2 from "typescript";
40
+ import * as path2 from "path";
41
+
42
+ // src/helpers/get-absolute-path.ts
43
+ import * as path from "path";
44
+ import * as process2 from "process";
45
+
46
+ // src/helpers/fix-path.ts
47
+ function fixPath(path5) {
48
+ return path5.replace(/\\/g, "/");
49
+ }
50
+
51
+ // src/helpers/get-absolute-path.ts
52
+ function getAbsolutePath(fileName, cwd2) {
53
+ if (!path.isAbsolute(fileName)) {
54
+ fileName = path.join(cwd2 !== void 0 ? cwd2 : process2.cwd(), fileName);
55
+ }
56
+ return fixPath(fileName);
57
+ }
58
+
59
+ // src/helpers/check-diagnostics-errors.ts
60
+ import * as ts from "typescript";
61
+ var formatDiagnosticsHost = {
62
+ getCanonicalFileName: (fileName) => ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(),
63
+ getCurrentDirectory: ts.sys.getCurrentDirectory,
64
+ getNewLine: () => ts.sys.newLine
65
+ };
66
+ function checkProgramDiagnosticsErrors(program) {
67
+ if (!program.getCompilerOptions().declaration) {
68
+ throw new Error(
69
+ `Something went wrong - the program doesn't have declaration option enabled`
70
+ );
71
+ }
72
+ checkDiagnosticsErrors(
73
+ ts.getPreEmitDiagnostics(program),
74
+ "Compiled with errors"
75
+ );
76
+ }
77
+ function checkDiagnosticsErrors(diagnostics, failMessage) {
78
+ if (diagnostics.length === 0) {
79
+ return;
80
+ }
81
+ errorLog(ts.formatDiagnostics(diagnostics, formatDiagnosticsHost).trim());
82
+ throw new Error(failMessage);
83
+ }
84
+
85
+ // src/get-compiler-options.ts
86
+ var parseConfigHost = {
87
+ useCaseSensitiveFileNames: ts2.sys.useCaseSensitiveFileNames,
88
+ readDirectory: ts2.sys.readDirectory,
89
+ fileExists: ts2.sys.fileExists,
90
+ readFile: ts2.sys.readFile
91
+ };
92
+ function getCompilerOptions(inputFileNames, preferredConfigPath) {
93
+ const configFileName = preferredConfigPath !== void 0 ? preferredConfigPath : findConfig(inputFileNames);
94
+ verboseLog(`Using config: ${configFileName}`);
95
+ const configParseResult = ts2.readConfigFile(configFileName, ts2.sys.readFile);
96
+ checkDiagnosticsErrors(
97
+ configParseResult.error !== void 0 ? [configParseResult.error] : [],
98
+ "Error while processing tsconfig file"
99
+ );
100
+ const compilerOptionsParseResult = ts2.parseJsonConfigFileContent(
101
+ configParseResult.config,
102
+ parseConfigHost,
103
+ path2.resolve(path2.dirname(configFileName)),
104
+ void 0,
105
+ getAbsolutePath(configFileName)
106
+ );
107
+ const diagnostics = compilerOptionsParseResult.errors.filter(
108
+ (d) => d.code !== 18003 /* NoInputsWereFoundDiagnosticCode */
109
+ );
110
+ checkDiagnosticsErrors(
111
+ diagnostics,
112
+ "Error while processing tsconfig compiler options"
113
+ );
114
+ return compilerOptionsParseResult.options;
115
+ }
116
+ function findConfig(inputFiles) {
117
+ if (inputFiles.length !== 1) {
118
+ throw new Error(
119
+ "Cannot find tsconfig for multiple files. Please specify preferred tsconfig file"
120
+ );
121
+ }
122
+ const searchPath = getAbsolutePath(inputFiles[0]);
123
+ const configFileName = ts2.findConfigFile(searchPath, ts2.sys.fileExists);
124
+ if (!configFileName) {
125
+ throw new Error(`Cannot find config file for file ${searchPath}`);
126
+ }
127
+ return configFileName;
128
+ }
129
+
130
+ // src/compile-dts.ts
131
+ var declarationExtsRemapping = {
132
+ [ts3.Extension.Js]: ts3.Extension.Js,
133
+ [ts3.Extension.Jsx]: ts3.Extension.Jsx,
134
+ [ts3.Extension.Json]: ts3.Extension.Json,
135
+ [ts3.Extension.TsBuildInfo]: ts3.Extension.TsBuildInfo,
136
+ [ts3.Extension.Mjs]: ts3.Extension.Mjs,
137
+ [ts3.Extension.Cjs]: ts3.Extension.Cjs,
138
+ [ts3.Extension.Ts]: ts3.Extension.Dts,
139
+ [ts3.Extension.Tsx]: ts3.Extension.Dts,
140
+ [ts3.Extension.Dts]: ts3.Extension.Dts,
141
+ [ts3.Extension.Mts]: ts3.Extension.Dmts,
142
+ [ts3.Extension.Dmts]: ts3.Extension.Dmts,
143
+ [ts3.Extension.Cts]: ts3.Extension.Dcts,
144
+ [ts3.Extension.Dcts]: ts3.Extension.Dcts
145
+ };
146
+ function compileDts(rootFiles, preferredConfigPath, followSymlinks = true) {
147
+ const compilerOptions = getCompilerOptions(rootFiles, preferredConfigPath);
148
+ compilerOptions.outDir = void 0;
149
+ compilerOptions.incremental = void 0;
150
+ compilerOptions.tsBuildInfoFile = void 0;
151
+ compilerOptions.declarationDir = void 0;
152
+ compilerOptions.declaration = true;
153
+ if (compilerOptions.composite) {
154
+ warnLog(
155
+ `Composite projects aren't supported at the time. Prefer to use non-composite project to generate declarations instead or just ignore this message if everything works fine. See https://github.com/timocov/dts-bundle-generator/issues/93`
156
+ );
157
+ compilerOptions.composite = void 0;
158
+ }
159
+ const host = createCachingCompilerHost(compilerOptions);
160
+ const dtsFiles = getDeclarationFiles(rootFiles, compilerOptions, host);
161
+ if (!followSymlinks) {
162
+ host.realpath = (p) => p;
163
+ }
164
+ const moduleResolutionCache = ts3.createModuleResolutionCache(
165
+ host.getCurrentDirectory(),
166
+ host.getCanonicalFileName,
167
+ compilerOptions
168
+ );
169
+ host.resolveModuleNameLiterals = (moduleLiterals, containingFile) => {
170
+ return moduleLiterals.map(
171
+ (moduleLiteral) => {
172
+ const resolvedModule = ts3.resolveModuleName(
173
+ moduleLiteral.text,
174
+ containingFile,
175
+ compilerOptions,
176
+ host,
177
+ moduleResolutionCache
178
+ ).resolvedModule;
179
+ if (resolvedModule && !resolvedModule.isExternalLibraryImport) {
180
+ const newExt = declarationExtsRemapping[resolvedModule.extension];
181
+ if (newExt === void 0) {
182
+ verboseLog(
183
+ `Skipping module ${resolvedModule.resolvedFileName} because it has unsupported extension "${resolvedModule.extension}"`
184
+ );
185
+ return { resolvedModule };
186
+ }
187
+ if (newExt !== resolvedModule.extension) {
188
+ verboseLog(
189
+ `Changing module from ${resolvedModule.extension} to ${newExt} for ${resolvedModule.resolvedFileName}`
190
+ );
191
+ resolvedModule.extension = newExt;
192
+ resolvedModule.resolvedFileName = changeExtensionToDts(
193
+ resolvedModule.resolvedFileName
194
+ );
195
+ }
196
+ }
197
+ return { resolvedModule };
198
+ }
199
+ );
200
+ };
201
+ const originalGetSourceFile = host.getSourceFile;
202
+ host.getSourceFile = (fileName, languageVersion, onError) => {
203
+ const storedValue = dtsFiles.get(host.getCanonicalFileName(fileName));
204
+ if (storedValue !== void 0) {
205
+ return ts3.createSourceFile(fileName, storedValue, languageVersion);
206
+ }
207
+ return originalGetSourceFile(fileName, languageVersion, onError);
208
+ };
209
+ const rootFilesRemapping = /* @__PURE__ */ new Map();
210
+ const inputFiles = rootFiles.map((rootFile) => {
211
+ const rootDtsFile = changeExtensionToDts(rootFile);
212
+ rootFilesRemapping.set(rootFile, rootDtsFile);
213
+ return rootDtsFile;
214
+ });
215
+ const program = ts3.createProgram(inputFiles, compilerOptions, host);
216
+ checkProgramDiagnosticsErrors(program);
217
+ warnAboutTypeScriptFilesInProgram(program);
218
+ return { program, rootFilesRemapping };
219
+ }
220
+ function createCachingCompilerHost(compilerOptions) {
221
+ const host = ts3.createIncrementalCompilerHost(compilerOptions);
222
+ const sourceFilesCache = /* @__PURE__ */ new Map();
223
+ const originalGetSourceFile = host.getSourceFile;
224
+ host.getSourceFile = (fileName, languageVersion, onError) => {
225
+ const key = host.getCanonicalFileName(fileName);
226
+ let cacheValue = sourceFilesCache.get(key);
227
+ if (cacheValue === void 0) {
228
+ cacheValue = originalGetSourceFile(fileName, languageVersion, onError);
229
+ sourceFilesCache.set(key, cacheValue);
230
+ }
231
+ return cacheValue;
232
+ };
233
+ return host;
234
+ }
235
+ function changeExtensionToDts(fileName) {
236
+ let ext;
237
+ if (fileName.endsWith(ts3.Extension.Dts)) {
238
+ return fileName;
239
+ }
240
+ if (fileName.endsWith(ts3.Extension.Cts)) {
241
+ ext = ts3.Extension.Cts;
242
+ } else if (fileName.endsWith(ts3.Extension.Mts)) {
243
+ ext = ts3.Extension.Mts;
244
+ } else if (fileName.endsWith(ts3.Extension.Ts)) {
245
+ ext = ts3.Extension.Ts;
246
+ } else if (fileName.endsWith(ts3.Extension.Tsx)) {
247
+ ext = ts3.Extension.Tsx;
248
+ }
249
+ if (ext === void 0) {
250
+ return fileName;
251
+ }
252
+ return fileName.slice(0, -ext.length) + declarationExtsRemapping[ext];
253
+ }
254
+ function getDeclarationFiles(rootFiles, compilerOptions, host) {
255
+ compilerOptions = {
256
+ ...compilerOptions,
257
+ noEmit: false,
258
+ declaration: true,
259
+ emitDeclarationOnly: true
260
+ };
261
+ const program = ts3.createProgram(rootFiles, compilerOptions, host);
262
+ const allFilesAreDeclarations = program.getSourceFiles().every((s) => s.isDeclarationFile);
263
+ const declarations = /* @__PURE__ */ new Map();
264
+ if (allFilesAreDeclarations) {
265
+ verboseLog(
266
+ "Skipping compiling the project to generate d.ts because all files in it are d.ts already"
267
+ );
268
+ return declarations;
269
+ }
270
+ checkProgramDiagnosticsErrors(program);
271
+ const emitResult = program.emit(
272
+ void 0,
273
+ (fileName, data) => declarations.set(host.getCanonicalFileName(fileName), data),
274
+ void 0,
275
+ true
276
+ );
277
+ checkDiagnosticsErrors(
278
+ emitResult.diagnostics,
279
+ "Errors while emitting declarations"
280
+ );
281
+ return declarations;
282
+ }
283
+ function warnAboutTypeScriptFilesInProgram(program) {
284
+ const nonDeclarationFiles = program.getSourceFiles().filter((file) => !file.isDeclarationFile);
285
+ if (nonDeclarationFiles.length !== 0) {
286
+ warnLog(`WARNING: It seems that some files in the compilation still are not declaration files.
287
+ For more information see https://github.com/timocov/dts-bundle-generator/issues/53.
288
+ If you think this is a mistake, feel free to open new issue or just ignore this warning.
289
+ ${nonDeclarationFiles.map((file) => file.fileName).join("\n ")}
290
+ `);
291
+ }
292
+ }
293
+
294
+ // src/types-usage-evaluator.ts
295
+ import * as ts5 from "typescript";
296
+
297
+ // src/helpers/typescript.ts
298
+ import * as ts4 from "typescript";
299
+ var namedDeclarationKinds = [
300
+ ts4.SyntaxKind.InterfaceDeclaration,
301
+ ts4.SyntaxKind.ClassDeclaration,
302
+ ts4.SyntaxKind.EnumDeclaration,
303
+ ts4.SyntaxKind.TypeAliasDeclaration,
304
+ ts4.SyntaxKind.ModuleDeclaration,
305
+ ts4.SyntaxKind.FunctionDeclaration,
306
+ ts4.SyntaxKind.VariableDeclaration,
307
+ ts4.SyntaxKind.PropertySignature,
308
+ ts4.SyntaxKind.NamespaceExport,
309
+ ts4.SyntaxKind.NamespaceImport,
310
+ ts4.SyntaxKind.ExportSpecifier,
311
+ ts4.SyntaxKind.BindingElement
312
+ ];
313
+ function isNodeNamedDeclaration(node) {
314
+ return namedDeclarationKinds.indexOf(node.kind) !== -1;
315
+ }
316
+ function hasNodeModifier(node, modifier) {
317
+ const modifiers = getModifiers2(node);
318
+ return Boolean(
319
+ modifiers && modifiers.some(
320
+ (nodeModifier) => nodeModifier.kind === modifier
321
+ )
322
+ );
323
+ }
324
+ function getNodeName(node) {
325
+ const nodeName = node.name;
326
+ if (nodeName === void 0) {
327
+ const modifiers = getModifiers2(node);
328
+ const defaultModifier = modifiers?.find(
329
+ (mod) => mod.kind === ts4.SyntaxKind.DefaultKeyword
330
+ );
331
+ if (defaultModifier !== void 0) {
332
+ return defaultModifier;
333
+ }
334
+ }
335
+ return nodeName;
336
+ }
337
+ function getActualSymbol(symbol, typeChecker) {
338
+ if (symbol.flags & ts4.SymbolFlags.Alias) {
339
+ symbol = typeChecker.getAliasedSymbol(symbol);
340
+ }
341
+ return typeChecker.getMergedSymbol(symbol);
342
+ }
343
+ function getDeclarationNameSymbol(name, typeChecker) {
344
+ const symbol = typeChecker.getSymbolAtLocation(name);
345
+ if (symbol === void 0) {
346
+ return null;
347
+ }
348
+ return getActualSymbol(symbol, typeChecker);
349
+ }
350
+ function splitTransientSymbol(symbol, typeChecker) {
351
+ if ((symbol.flags & ts4.SymbolFlags.Transient) === 0) {
352
+ return /* @__PURE__ */ new Set([symbol]);
353
+ }
354
+ const declarations = getDeclarationsForSymbol(symbol);
355
+ const result = /* @__PURE__ */ new Set();
356
+ for (const declaration of declarations) {
357
+ if (!isNodeNamedDeclaration(declaration) || declaration.name === void 0) {
358
+ continue;
359
+ }
360
+ const sym = typeChecker.getSymbolAtLocation(declaration.name);
361
+ if (sym === void 0) {
362
+ continue;
363
+ }
364
+ result.add(getActualSymbol(sym, typeChecker));
365
+ }
366
+ return result;
367
+ }
368
+ function isGlobalScopeAugmentation(module) {
369
+ return Boolean(module.flags & ts4.NodeFlags.GlobalAugmentation);
370
+ }
371
+ function isAmbientModule(node) {
372
+ return ts4.isModuleDeclaration(node) && (node.name.kind === ts4.SyntaxKind.StringLiteral || isGlobalScopeAugmentation(node));
373
+ }
374
+ function isDeclareModule(node) {
375
+ return ts4.isModuleDeclaration(node) && !(node.flags & ts4.NodeFlags.Namespace) && !isGlobalScopeAugmentation(node);
376
+ }
377
+ function isDeclareGlobalStatement(statement) {
378
+ return ts4.isModuleDeclaration(statement) && isGlobalScopeAugmentation(statement);
379
+ }
380
+ function getDeclarationsForSymbol(symbol) {
381
+ const result = [];
382
+ if (symbol.declarations !== void 0) {
383
+ result.push(...symbol.declarations);
384
+ }
385
+ if (symbol.valueDeclaration !== void 0) {
386
+ if (!result.includes(symbol.valueDeclaration)) {
387
+ result.push(symbol.valueDeclaration);
388
+ }
389
+ }
390
+ return result;
391
+ }
392
+ function getExportsForSourceFile(typeChecker, sourceFileSymbol) {
393
+ if (sourceFileSymbol.exports !== void 0) {
394
+ const commonJsExport = sourceFileSymbol.exports.get(
395
+ ts4.InternalSymbolName.ExportEquals
396
+ );
397
+ if (commonJsExport !== void 0) {
398
+ const symbol = getActualSymbol(commonJsExport, typeChecker);
399
+ return [
400
+ {
401
+ symbol,
402
+ originalSymbol: commonJsExport,
403
+ type: 0 /* CommonJS */,
404
+ exportedName: ""
405
+ }
406
+ ];
407
+ }
408
+ }
409
+ const result = typeChecker.getExportsOfModule(sourceFileSymbol).map((symbol) => ({
410
+ symbol,
411
+ originalSymbol: symbol,
412
+ exportedName: symbol.name,
413
+ type: 1 /* ES6Named */
414
+ }));
415
+ if (sourceFileSymbol.exports !== void 0) {
416
+ const defaultExportSymbol = sourceFileSymbol.exports.get(
417
+ ts4.InternalSymbolName.Default
418
+ );
419
+ if (defaultExportSymbol !== void 0) {
420
+ const defaultExport = result.find(
421
+ (exp) => exp.symbol === defaultExportSymbol
422
+ );
423
+ if (defaultExport !== void 0) {
424
+ defaultExport.type = 2 /* ES6Default */;
425
+ } else {
426
+ result.push({
427
+ symbol: defaultExportSymbol,
428
+ originalSymbol: defaultExportSymbol,
429
+ type: 2 /* ES6Default */,
430
+ exportedName: "default"
431
+ });
432
+ }
433
+ }
434
+ }
435
+ const symbolsMergingResolvedExports = [];
436
+ result.forEach((exp) => {
437
+ exp.symbol = getActualSymbol(exp.symbol, typeChecker);
438
+ const symbolsDeclarations = getDeclarationsForSymbol(exp.symbol);
439
+ const importSpecifierDeclaration = symbolsDeclarations.find(
440
+ ts4.isImportSpecifier
441
+ );
442
+ if (symbolsDeclarations.length > 1 && importSpecifierDeclaration !== void 0) {
443
+ const referencedModule = resolveReferencedModule(
444
+ importSpecifierDeclaration.parent.parent.parent,
445
+ typeChecker
446
+ );
447
+ if (referencedModule !== null) {
448
+ const referencedModuleSymbol = getNodeSymbol(
449
+ referencedModule,
450
+ typeChecker
451
+ );
452
+ if (referencedModuleSymbol !== null) {
453
+ const importedName = (importSpecifierDeclaration.propertyName ?? importSpecifierDeclaration.name).getText();
454
+ const exportedItemSymbol = typeChecker.getExportsOfModule(referencedModuleSymbol).find(
455
+ (exportSymbol) => exportSymbol.getName() === importedName
456
+ );
457
+ if (exportedItemSymbol !== void 0) {
458
+ symbolsMergingResolvedExports.push({
459
+ ...exp,
460
+ symbol: getActualSymbol(exportedItemSymbol, typeChecker)
461
+ });
462
+ }
463
+ }
464
+ }
465
+ }
466
+ });
467
+ return [...result, ...symbolsMergingResolvedExports];
468
+ }
469
+ function getExportsForStatement(exportedSymbols, typeChecker, statement) {
470
+ if (ts4.isVariableStatement(statement)) {
471
+ if (statement.declarationList.declarations.length === 0) {
472
+ return [];
473
+ }
474
+ const firstDeclarationExports = getExportsForName(
475
+ exportedSymbols,
476
+ typeChecker,
477
+ statement.declarationList.declarations[0].name
478
+ );
479
+ const allDeclarationsHaveSameExportType = statement.declarationList.declarations.every(
480
+ (variableDecl) => {
481
+ return getExportsForName(
482
+ exportedSymbols,
483
+ typeChecker,
484
+ variableDecl.name
485
+ )[0]?.type === firstDeclarationExports[0]?.type;
486
+ }
487
+ );
488
+ if (!allDeclarationsHaveSameExportType) {
489
+ return [];
490
+ }
491
+ return firstDeclarationExports;
492
+ }
493
+ const nodeName = getNodeName(statement);
494
+ if (nodeName === void 0) {
495
+ return [];
496
+ }
497
+ return getExportsForName(exportedSymbols, typeChecker, nodeName);
498
+ }
499
+ function getExportsForName(exportedSymbols, typeChecker, name) {
500
+ if (ts4.isArrayBindingPattern(name) || ts4.isObjectBindingPattern(name)) {
501
+ return [];
502
+ }
503
+ const declarationSymbol = typeChecker.getSymbolAtLocation(name);
504
+ return exportedSymbols.filter(
505
+ (rootExport) => rootExport.symbol === declarationSymbol
506
+ );
507
+ }
508
+ var modifiersPriority = {
509
+ [ts4.SyntaxKind.ExportKeyword]: 4,
510
+ [ts4.SyntaxKind.DefaultKeyword]: 3,
511
+ [ts4.SyntaxKind.DeclareKeyword]: 2,
512
+ [ts4.SyntaxKind.AsyncKeyword]: 1,
513
+ [ts4.SyntaxKind.ConstKeyword]: 1
514
+ };
515
+ function modifiersToMap(modifiers) {
516
+ modifiers = modifiers || [];
517
+ return modifiers.reduce(
518
+ (result, modifier) => {
519
+ result[modifier.kind] = true;
520
+ return result;
521
+ },
522
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
523
+ {}
524
+ );
525
+ }
526
+ function modifiersMapToArray(modifiersMap) {
527
+ return Object.entries(modifiersMap).filter(([kind, include]) => include).map(([kind]) => {
528
+ return ts4.factory.createModifier(Number(kind));
529
+ }).sort((a, b) => {
530
+ const aValue = modifiersPriority[a.kind] || 0;
531
+ const bValue = modifiersPriority[b.kind] || 0;
532
+ return bValue - aValue;
533
+ });
534
+ }
535
+ function recreateRootLevelNodeWithModifiers(node, modifiersMap, newName, keepComments = true) {
536
+ const newNode = recreateRootLevelNodeWithModifiersImpl(
537
+ node,
538
+ modifiersMap,
539
+ newName
540
+ );
541
+ if (keepComments) {
542
+ ts4.setCommentRange(newNode, ts4.getCommentRange(node));
543
+ }
544
+ return newNode;
545
+ }
546
+ function recreateRootLevelNodeWithModifiersImpl(node, modifiersMap, newName) {
547
+ const modifiers = modifiersMapToArray(modifiersMap);
548
+ if (ts4.isArrowFunction(node)) {
549
+ return ts4.factory.createArrowFunction(
550
+ modifiers,
551
+ node.typeParameters,
552
+ node.parameters,
553
+ node.type,
554
+ node.equalsGreaterThanToken,
555
+ node.body
556
+ );
557
+ }
558
+ if (ts4.isClassDeclaration(node)) {
559
+ return ts4.factory.createClassDeclaration(
560
+ modifiers,
561
+ newName || node.name,
562
+ node.typeParameters,
563
+ node.heritageClauses,
564
+ node.members
565
+ );
566
+ }
567
+ if (ts4.isClassExpression(node)) {
568
+ return ts4.factory.createClassExpression(
569
+ modifiers,
570
+ newName || node.name,
571
+ node.typeParameters,
572
+ node.heritageClauses,
573
+ node.members
574
+ );
575
+ }
576
+ if (ts4.isEnumDeclaration(node)) {
577
+ return ts4.factory.createEnumDeclaration(
578
+ modifiers,
579
+ newName || node.name,
580
+ node.members
581
+ );
582
+ }
583
+ if (ts4.isExportAssignment(node)) {
584
+ return ts4.factory.createExportAssignment(
585
+ modifiers,
586
+ node.isExportEquals,
587
+ node.expression
588
+ );
589
+ }
590
+ if (ts4.isExportDeclaration(node)) {
591
+ return ts4.factory.createExportDeclaration(
592
+ modifiers,
593
+ node.isTypeOnly,
594
+ node.exportClause,
595
+ node.moduleSpecifier,
596
+ // eslint-disable-next-line deprecation/deprecation
597
+ node.attributes || node.assertClause
598
+ );
599
+ }
600
+ if (ts4.isFunctionDeclaration(node)) {
601
+ return ts4.factory.createFunctionDeclaration(
602
+ modifiers,
603
+ node.asteriskToken,
604
+ newName || node.name,
605
+ node.typeParameters,
606
+ node.parameters,
607
+ node.type,
608
+ node.body
609
+ );
610
+ }
611
+ if (ts4.isFunctionExpression(node)) {
612
+ return ts4.factory.createFunctionExpression(
613
+ modifiers,
614
+ node.asteriskToken,
615
+ newName || node.name,
616
+ node.typeParameters,
617
+ node.parameters,
618
+ node.type,
619
+ node.body
620
+ );
621
+ }
622
+ if (ts4.isImportDeclaration(node)) {
623
+ return ts4.factory.createImportDeclaration(
624
+ modifiers,
625
+ node.importClause,
626
+ node.moduleSpecifier,
627
+ // eslint-disable-next-line deprecation/deprecation
628
+ node.attributes || node.assertClause
629
+ );
630
+ }
631
+ if (ts4.isImportEqualsDeclaration(node)) {
632
+ return ts4.factory.createImportEqualsDeclaration(
633
+ modifiers,
634
+ node.isTypeOnly,
635
+ newName || node.name,
636
+ node.moduleReference
637
+ );
638
+ }
639
+ if (ts4.isInterfaceDeclaration(node)) {
640
+ return ts4.factory.createInterfaceDeclaration(
641
+ modifiers,
642
+ newName || node.name,
643
+ node.typeParameters,
644
+ node.heritageClauses,
645
+ node.members
646
+ );
647
+ }
648
+ if (ts4.isModuleDeclaration(node)) {
649
+ return ts4.factory.createModuleDeclaration(
650
+ modifiers,
651
+ node.name,
652
+ node.body,
653
+ node.flags
654
+ );
655
+ }
656
+ if (ts4.isTypeAliasDeclaration(node)) {
657
+ return ts4.factory.createTypeAliasDeclaration(
658
+ modifiers,
659
+ newName || node.name,
660
+ node.typeParameters,
661
+ node.type
662
+ );
663
+ }
664
+ if (ts4.isVariableStatement(node)) {
665
+ return ts4.factory.createVariableStatement(modifiers, node.declarationList);
666
+ }
667
+ throw new Error(`Unknown top-level node kind (with modifiers): ${ts4.SyntaxKind[node.kind]}.
668
+ If you're seeing this error, please report a bug on https://github.com/timocov/dts-bundle-generator/issues`);
669
+ }
670
+ function getModifiers2(node) {
671
+ if (!ts4.canHaveModifiers(node)) {
672
+ return void 0;
673
+ }
674
+ return ts4.getModifiers(node);
675
+ }
676
+ function getRootSourceFile(program, rootFileName) {
677
+ if (program.getRootFileNames().indexOf(rootFileName) === -1) {
678
+ throw new Error(`There is no such root file ${rootFileName}`);
679
+ }
680
+ const sourceFile = program.getSourceFile(rootFileName);
681
+ if (sourceFile === void 0) {
682
+ throw new Error(`Cannot get source file for root file ${rootFileName}`);
683
+ }
684
+ return sourceFile;
685
+ }
686
+ function getNodeOwnSymbol(node, typeChecker) {
687
+ const nodeSymbol = typeChecker.getSymbolAtLocation(node);
688
+ if (nodeSymbol === void 0) {
689
+ throw new Error(
690
+ `Cannot find symbol for node "${node.getText()}" in "${node.parent.getText()}" from "${node.getSourceFile().fileName}"`
691
+ );
692
+ }
693
+ return nodeSymbol;
694
+ }
695
+ function getNodeSymbol(node, typeChecker) {
696
+ if (ts4.isSourceFile(node)) {
697
+ const fileSymbol = typeChecker.getSymbolAtLocation(node);
698
+ if (fileSymbol === void 0) {
699
+ return null;
700
+ }
701
+ return getActualSymbol(fileSymbol, typeChecker);
702
+ }
703
+ const nodeName = getNodeName(node);
704
+ if (nodeName === void 0) {
705
+ return null;
706
+ }
707
+ return getDeclarationNameSymbol(nodeName, typeChecker);
708
+ }
709
+ function getClosestModuleLikeNode(node) {
710
+ while (!ts4.isModuleBlock(node) && !ts4.isSourceFile(node)) {
711
+ node = node.parent;
712
+ }
713
+ return ts4.isSourceFile(node) ? node : node.parent;
714
+ }
715
+ function getClosestSourceFileLikeNode(node) {
716
+ while (!(ts4.isModuleBlock(node) && ts4.isStringLiteral(node.parent.name)) && !ts4.isSourceFile(node)) {
717
+ node = node.parent;
718
+ }
719
+ return ts4.isSourceFile(node) ? node : node.parent;
720
+ }
721
+ function resolveReferencedModule(node, typeChecker) {
722
+ let moduleName;
723
+ if (ts4.isExportDeclaration(node) || ts4.isImportDeclaration(node)) {
724
+ moduleName = node.moduleSpecifier;
725
+ } else if (ts4.isModuleDeclaration(node)) {
726
+ moduleName = node.name;
727
+ } else if (ts4.isImportEqualsDeclaration(node)) {
728
+ if (ts4.isExternalModuleReference(node.moduleReference)) {
729
+ moduleName = node.moduleReference.expression;
730
+ }
731
+ } else if (ts4.isLiteralTypeNode(node.argument) && ts4.isStringLiteral(node.argument.literal)) {
732
+ moduleName = node.argument.literal;
733
+ }
734
+ if (moduleName === void 0) {
735
+ return null;
736
+ }
737
+ const moduleSymbol = typeChecker.getSymbolAtLocation(moduleName);
738
+ if (moduleSymbol === void 0) {
739
+ return null;
740
+ }
741
+ const symbol = getActualSymbol(moduleSymbol, typeChecker);
742
+ if (symbol.valueDeclaration === void 0) {
743
+ return null;
744
+ }
745
+ return ts4.isSourceFile(symbol.valueDeclaration) || ts4.isModuleDeclaration(symbol.valueDeclaration) ? symbol.valueDeclaration : null;
746
+ }
747
+ function getImportModuleName(imp) {
748
+ if (ts4.isImportDeclaration(imp)) {
749
+ return imp.importClause === void 0 ? null : imp.moduleSpecifier.text;
750
+ }
751
+ if (ts4.isExportDeclaration(imp)) {
752
+ return imp.moduleSpecifier === void 0 ? null : imp.moduleSpecifier.text;
753
+ }
754
+ if (ts4.isExternalModuleReference(imp.moduleReference)) {
755
+ if (!ts4.isStringLiteral(imp.moduleReference.expression)) {
756
+ warnLog(
757
+ `Cannot handle non string-literal-like import expression: ${imp.moduleReference.expression.getText()}`
758
+ );
759
+ return null;
760
+ }
761
+ return imp.moduleReference.expression.text;
762
+ }
763
+ return null;
764
+ }
765
+ function getImportExportReferencedSymbol(importExportSpecifier, typeChecker) {
766
+ return importExportSpecifier.propertyName !== void 0 ? (
767
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
768
+ typeChecker.getSymbolAtLocation(importExportSpecifier.propertyName)
769
+ ) : (
770
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
771
+ typeChecker.getImmediateAliasedSymbol(
772
+ typeChecker.getSymbolAtLocation(importExportSpecifier.name)
773
+ )
774
+ );
775
+ }
776
+ function getSymbolExportStarDeclarations(symbol) {
777
+ if (symbol.escapedName !== ts4.InternalSymbolName.ExportStar) {
778
+ throw new Error(
779
+ `Only ExportStar symbol can have export star declaration, but got ${symbol.escapedName}`
780
+ );
781
+ }
782
+ return getDeclarationsForSymbol(symbol).filter(
783
+ (decl) => ts4.isExportDeclaration(decl) && decl.moduleSpecifier !== void 0
784
+ );
785
+ }
786
+ function getDeclarationsForExportedValues(exp, typeChecker) {
787
+ const nodeForSymbol = ts4.isExportAssignment(exp) ? exp.expression : exp.moduleSpecifier;
788
+ if (nodeForSymbol === void 0) {
789
+ return [];
790
+ }
791
+ const symbolForExpression = typeChecker.getSymbolAtLocation(nodeForSymbol);
792
+ if (symbolForExpression === void 0) {
793
+ return [];
794
+ }
795
+ const symbol = getActualSymbol(symbolForExpression, typeChecker);
796
+ return getDeclarationsForSymbol(symbol);
797
+ }
798
+ function resolveGlobalName(typeChecker, name) {
799
+ const tsSymbolFlagsAll = (
800
+ /* ts.SymbolFlags.All */
801
+ -1
802
+ );
803
+ return typeChecker.resolveName(
804
+ name,
805
+ void 0,
806
+ tsSymbolFlagsAll,
807
+ false
808
+ );
809
+ }
810
+
811
+ // src/types-usage-evaluator.ts
812
+ var TypesUsageEvaluator = class {
813
+ typeChecker;
814
+ nodesParentsMap = /* @__PURE__ */ new Map();
815
+ usageResultCache = /* @__PURE__ */ new Map();
816
+ constructor(files, typeChecker) {
817
+ this.typeChecker = typeChecker;
818
+ this.computeUsages(files);
819
+ }
820
+ isSymbolUsedBySymbol(symbol, by) {
821
+ return this.isSymbolUsedBySymbolImpl(
822
+ this.getActualSymbol(symbol),
823
+ this.getActualSymbol(by),
824
+ /* @__PURE__ */ new Set()
825
+ );
826
+ }
827
+ getSymbolsUsingSymbol(symbol) {
828
+ return this.nodesParentsMap.get(this.getActualSymbol(symbol)) || null;
829
+ }
830
+ isSymbolUsedBySymbolImpl(fromSymbol, toSymbol, visitedSymbols) {
831
+ if (fromSymbol === toSymbol) {
832
+ return this.setUsageCacheValue(fromSymbol, toSymbol, true);
833
+ }
834
+ const cacheResult = this.usageResultCache.get(fromSymbol)?.get(toSymbol);
835
+ if (cacheResult !== void 0) {
836
+ return cacheResult;
837
+ }
838
+ const reachableNodes = this.nodesParentsMap.get(fromSymbol);
839
+ if (reachableNodes !== void 0) {
840
+ for (const symbol of reachableNodes) {
841
+ if (visitedSymbols.has(symbol)) {
842
+ continue;
843
+ }
844
+ visitedSymbols.add(symbol);
845
+ if (this.isSymbolUsedBySymbolImpl(symbol, toSymbol, visitedSymbols)) {
846
+ return this.setUsageCacheValue(fromSymbol, toSymbol, true);
847
+ }
848
+ }
849
+ }
850
+ visitedSymbols.add(fromSymbol);
851
+ return false;
852
+ }
853
+ setUsageCacheValue(fromSymbol, toSymbol, value) {
854
+ let fromSymbolCacheMap = this.usageResultCache.get(fromSymbol);
855
+ if (fromSymbolCacheMap === void 0) {
856
+ fromSymbolCacheMap = /* @__PURE__ */ new Map();
857
+ this.usageResultCache.set(fromSymbol, fromSymbolCacheMap);
858
+ }
859
+ fromSymbolCacheMap.set(toSymbol, value);
860
+ return value;
861
+ }
862
+ computeUsages(files) {
863
+ this.nodesParentsMap.clear();
864
+ for (const file of files) {
865
+ ts5.forEachChild(file, this.computeUsageForNode.bind(this));
866
+ }
867
+ }
868
+ // eslint-disable-next-line complexity
869
+ computeUsageForNode(node) {
870
+ if (isDeclareModule(node) && node.body !== void 0 && ts5.isModuleBlock(node.body)) {
871
+ const moduleSymbol = this.getSymbol(node.name);
872
+ for (const statement of node.body.statements) {
873
+ this.computeUsageForNode(statement);
874
+ if (isNodeNamedDeclaration(statement)) {
875
+ const nodeName = getNodeName(statement);
876
+ if (nodeName !== void 0) {
877
+ const statementSymbol = this.getSymbol(nodeName);
878
+ this.addUsages(statementSymbol, moduleSymbol);
879
+ }
880
+ }
881
+ }
882
+ }
883
+ if (isNodeNamedDeclaration(node)) {
884
+ const nodeName = getNodeName(node);
885
+ if (nodeName !== void 0) {
886
+ if (ts5.isObjectBindingPattern(nodeName) || ts5.isArrayBindingPattern(nodeName)) {
887
+ for (const element of nodeName.elements) {
888
+ this.computeUsageForNode(element);
889
+ }
890
+ } else {
891
+ const childSymbol = this.getSymbol(nodeName);
892
+ if (childSymbol !== null) {
893
+ this.computeUsagesRecursively(node, childSymbol);
894
+ }
895
+ }
896
+ }
897
+ }
898
+ if (ts5.isVariableStatement(node)) {
899
+ for (const varDeclaration of node.declarationList.declarations) {
900
+ this.computeUsageForNode(varDeclaration);
901
+ }
902
+ }
903
+ if (ts5.isExportDeclaration(node) && node.moduleSpecifier !== void 0 && node.exportClause !== void 0 && ts5.isNamespaceExport(node.exportClause)) {
904
+ this.addUsagesForNamespacedModule(
905
+ node.exportClause,
906
+ node.moduleSpecifier
907
+ );
908
+ }
909
+ if (ts5.isImportDeclaration(node) && node.moduleSpecifier !== void 0 && node.importClause?.namedBindings !== void 0 && ts5.isNamespaceImport(node.importClause.namedBindings)) {
910
+ this.addUsagesForNamespacedModule(
911
+ node.importClause.namedBindings,
912
+ node.moduleSpecifier,
913
+ false
914
+ );
915
+ }
916
+ if (ts5.isExportDeclaration(node) && node.exportClause !== void 0 && ts5.isNamedExports(node.exportClause)) {
917
+ for (const exportElement of node.exportClause.elements) {
918
+ const exportElementSymbol = getImportExportReferencedSymbol(
919
+ exportElement,
920
+ this.typeChecker
921
+ );
922
+ const namespaceImportForElement = getDeclarationsForSymbol(
923
+ exportElementSymbol
924
+ ).find(ts5.isNamespaceImport);
925
+ if (namespaceImportForElement !== void 0) {
926
+ this.addUsagesForNamespacedModule(
927
+ namespaceImportForElement,
928
+ namespaceImportForElement.parent.parent.moduleSpecifier
929
+ );
930
+ }
931
+ const exportElementOwnSymbol = this.getNodeOwnSymbol(
932
+ exportElement.name
933
+ );
934
+ this.addUsages(exportElementSymbol, exportElementOwnSymbol);
935
+ this.addUsages(
936
+ this.getActualSymbol(exportElementSymbol),
937
+ exportElementOwnSymbol
938
+ );
939
+ }
940
+ }
941
+ if (ts5.isExportAssignment(node) && node.isExportEquals) {
942
+ this.addUsagesForExportAssignment(node);
943
+ }
944
+ }
945
+ addUsagesForExportAssignment(exportAssignment) {
946
+ for (const declaration of getDeclarationsForExportedValues(
947
+ exportAssignment,
948
+ this.typeChecker
949
+ )) {
950
+ if (ts5.isModuleDeclaration(declaration) && ts5.isIdentifier(declaration.name) && declaration.body !== void 0 && ts5.isModuleBlock(declaration.body)) {
951
+ const moduleSymbol = this.getSymbol(declaration.name);
952
+ for (const statement of declaration.body.statements) {
953
+ if (isNodeNamedDeclaration(statement) && statement.name !== void 0) {
954
+ const statementSymbol = this.getSymbol(statement.name);
955
+ if (statementSymbol !== null) {
956
+ this.addUsages(moduleSymbol, statementSymbol);
957
+ }
958
+ }
959
+ }
960
+ }
961
+ }
962
+ }
963
+ addUsagesForNamespacedModule(namespaceNode, moduleSpecifier, includeExports = true) {
964
+ const namespaceSymbol = this.getNodeOwnSymbol(namespaceNode.name);
965
+ const referencedSourceFileSymbol = this.getSymbol(moduleSpecifier);
966
+ this.addUsages(referencedSourceFileSymbol, namespaceSymbol);
967
+ const resolvedNamespaceSymbol = this.getSymbol(namespaceNode.name);
968
+ this.addUsages(resolvedNamespaceSymbol, namespaceSymbol);
969
+ if (includeExports) {
970
+ this.addExportsToSymbol(
971
+ referencedSourceFileSymbol.exports,
972
+ referencedSourceFileSymbol
973
+ );
974
+ }
975
+ }
976
+ addExportsToSymbol(exports, parentSymbol, visitedSymbols = /* @__PURE__ */ new Set()) {
977
+ exports?.forEach((moduleExportedSymbol, name) => {
978
+ if (name === ts5.InternalSymbolName.ExportStar) {
979
+ for (const exportStarDeclaration of getSymbolExportStarDeclarations(
980
+ moduleExportedSymbol
981
+ )) {
982
+ if (exportStarDeclaration.moduleSpecifier === void 0) {
983
+ throw new Error(
984
+ `Export star declaration does not have a module specifier '${exportStarDeclaration.getText()}'`
985
+ );
986
+ }
987
+ const referencedSourceFileSymbol = this.getSymbol(
988
+ exportStarDeclaration.moduleSpecifier
989
+ );
990
+ if (visitedSymbols.has(referencedSourceFileSymbol)) {
991
+ continue;
992
+ }
993
+ visitedSymbols.add(referencedSourceFileSymbol);
994
+ this.addExportsToSymbol(
995
+ referencedSourceFileSymbol.exports,
996
+ parentSymbol,
997
+ visitedSymbols
998
+ );
999
+ }
1000
+ return;
1001
+ }
1002
+ this.addUsages(moduleExportedSymbol, parentSymbol);
1003
+ });
1004
+ }
1005
+ computeUsagesRecursively(parent, parentSymbol) {
1006
+ ts5.forEachChild(parent, (child) => {
1007
+ if (child.kind === ts5.SyntaxKind.JSDoc) {
1008
+ return;
1009
+ }
1010
+ this.computeUsagesRecursively(child, parentSymbol);
1011
+ if (ts5.isIdentifier(child) || child.kind === ts5.SyntaxKind.DefaultKeyword) {
1012
+ if (ts5.isNamedTupleMember(child.parent) && child.parent.name === child) {
1013
+ return;
1014
+ }
1015
+ if (ts5.isBindingElement(child.parent) && child.parent.propertyName === child) {
1016
+ return;
1017
+ }
1018
+ this.addUsages(this.getSymbol(child), parentSymbol);
1019
+ if (!ts5.isQualifiedName(child.parent)) {
1020
+ const childOwnSymbol = this.getNodeOwnSymbol(child);
1021
+ const namespaceImport = getDeclarationsForSymbol(childOwnSymbol).find(
1022
+ ts5.isNamespaceImport
1023
+ );
1024
+ if (namespaceImport !== void 0) {
1025
+ this.addUsagesForNamespacedModule(
1026
+ namespaceImport,
1027
+ namespaceImport.parent.parent.moduleSpecifier,
1028
+ true
1029
+ );
1030
+ }
1031
+ }
1032
+ }
1033
+ });
1034
+ }
1035
+ addUsages(childSymbol, parentSymbol) {
1036
+ const childSymbols = splitTransientSymbol(childSymbol, this.typeChecker);
1037
+ for (const childSplitSymbol of childSymbols) {
1038
+ let symbols = this.nodesParentsMap.get(childSplitSymbol);
1039
+ if (symbols === void 0) {
1040
+ symbols = /* @__PURE__ */ new Set();
1041
+ this.nodesParentsMap.set(childSplitSymbol, symbols);
1042
+ }
1043
+ if (childSplitSymbol !== parentSymbol) {
1044
+ symbols.add(parentSymbol);
1045
+ }
1046
+ }
1047
+ }
1048
+ getSymbol(node) {
1049
+ return this.getActualSymbol(this.getNodeOwnSymbol(node));
1050
+ }
1051
+ getNodeOwnSymbol(node) {
1052
+ return getNodeOwnSymbol(node, this.typeChecker);
1053
+ }
1054
+ getActualSymbol(symbol) {
1055
+ return getActualSymbol(symbol, this.typeChecker);
1056
+ }
1057
+ };
1058
+
1059
+ // src/module-info.ts
1060
+ import * as path3 from "path";
1061
+ import * as ts6 from "typescript";
1062
+
1063
+ // src/helpers/node-modules.ts
1064
+ var nodeModulesFolderName = "node_modules/";
1065
+ var libraryNameRegex = /node_modules\/((?:(?=@)[^/]+\/[^/]+|[^/]+))\//;
1066
+ function getLibraryName(fileName) {
1067
+ const lastNodeModulesIndex = fileName.lastIndexOf(nodeModulesFolderName);
1068
+ if (lastNodeModulesIndex === -1) {
1069
+ return null;
1070
+ }
1071
+ const match = libraryNameRegex.exec(fileName.slice(lastNodeModulesIndex));
1072
+ if (match === null) {
1073
+ return null;
1074
+ }
1075
+ return match[1];
1076
+ }
1077
+ function getTypesLibraryName(path5) {
1078
+ const libraryName = getLibraryName(path5);
1079
+ if (libraryName === null) {
1080
+ return null;
1081
+ }
1082
+ const typesFolderPrefix = "@types/";
1083
+ if (!libraryName.startsWith(typesFolderPrefix)) {
1084
+ return null;
1085
+ }
1086
+ return libraryName.substring(typesFolderPrefix.length);
1087
+ }
1088
+
1089
+ // src/module-info.ts
1090
+ function getFileModuleInfo(fileName, criteria) {
1091
+ return getModuleInfoImpl(fileName, fileName, criteria);
1092
+ }
1093
+ function getReferencedModuleInfo(moduleDecl, criteria, typeChecker) {
1094
+ const referencedModule = resolveReferencedModule(moduleDecl, typeChecker);
1095
+ if (referencedModule === null) {
1096
+ return null;
1097
+ }
1098
+ const moduleFilePath = ts6.isSourceFile(referencedModule) ? referencedModule.fileName : resolveModuleFileName(
1099
+ referencedModule.getSourceFile().fileName,
1100
+ referencedModule.name.text
1101
+ );
1102
+ return getFileModuleInfo(moduleFilePath, criteria);
1103
+ }
1104
+ function getModuleLikeModuleInfo(moduleLike, criteria, typeChecker) {
1105
+ const resolvedModuleLike = ts6.isSourceFile(moduleLike) ? moduleLike : resolveReferencedModule(moduleLike, typeChecker) ?? moduleLike;
1106
+ const fileName = ts6.isSourceFile(resolvedModuleLike) ? resolvedModuleLike.fileName : resolveModuleFileName(
1107
+ resolvedModuleLike.getSourceFile().fileName,
1108
+ resolvedModuleLike.name.text
1109
+ );
1110
+ return getFileModuleInfo(fileName, criteria);
1111
+ }
1112
+ function resolveModuleFileName(currentFileName, moduleName) {
1113
+ return moduleName.startsWith(".") ? fixPath(path3.join(currentFileName, "..", moduleName)) : `node_modules/${moduleName}/`;
1114
+ }
1115
+ function getModuleInfoImpl(currentFilePath, originalFileName, criteria) {
1116
+ const npmLibraryName = getLibraryName(currentFilePath);
1117
+ if (npmLibraryName === null) {
1118
+ if (criteria.typeRoots !== void 0) {
1119
+ for (const root of criteria.typeRoots) {
1120
+ const relativePath = fixPath(path3.relative(root, originalFileName));
1121
+ if (!relativePath.startsWith("../")) {
1122
+ return getModuleInfoImpl(
1123
+ remapToTypesFromNodeModules(relativePath),
1124
+ originalFileName,
1125
+ criteria
1126
+ );
1127
+ }
1128
+ }
1129
+ }
1130
+ return {
1131
+ type: 0 /* ShouldBeInlined */,
1132
+ fileName: originalFileName,
1133
+ isExternal: false
1134
+ };
1135
+ }
1136
+ const typesLibraryName = getTypesLibraryName(currentFilePath);
1137
+ if (shouldLibraryBeInlined(
1138
+ npmLibraryName,
1139
+ typesLibraryName,
1140
+ criteria.inlinedLibraries
1141
+ )) {
1142
+ return {
1143
+ type: 0 /* ShouldBeInlined */,
1144
+ fileName: originalFileName,
1145
+ isExternal: true
1146
+ };
1147
+ }
1148
+ if (shouldLibraryBeImported(
1149
+ npmLibraryName,
1150
+ typesLibraryName,
1151
+ criteria.importedLibraries,
1152
+ criteria.allowedTypesLibraries
1153
+ )) {
1154
+ return {
1155
+ type: 1 /* ShouldBeImported */,
1156
+ fileName: originalFileName,
1157
+ isExternal: true
1158
+ };
1159
+ }
1160
+ if (typesLibraryName !== null && isLibraryAllowed(typesLibraryName, criteria.allowedTypesLibraries)) {
1161
+ return {
1162
+ type: 2 /* ShouldBeReferencedAsTypes */,
1163
+ fileName: originalFileName,
1164
+ typesLibraryName,
1165
+ isExternal: true
1166
+ };
1167
+ }
1168
+ return {
1169
+ type: 3 /* ShouldBeUsedForModulesOnly */,
1170
+ fileName: originalFileName,
1171
+ isExternal: true
1172
+ };
1173
+ }
1174
+ function shouldLibraryBeInlined(npmLibraryName, typesLibraryName, inlinedLibraries) {
1175
+ return isLibraryAllowed(npmLibraryName, inlinedLibraries) || typesLibraryName !== null && isLibraryAllowed(typesLibraryName, inlinedLibraries);
1176
+ }
1177
+ function shouldLibraryBeImported(npmLibraryName, typesLibraryName, importedLibraries, allowedTypesLibraries) {
1178
+ if (typesLibraryName === null) {
1179
+ return isLibraryAllowed(npmLibraryName, importedLibraries);
1180
+ }
1181
+ if (allowedTypesLibraries === void 0 || !isLibraryAllowed(typesLibraryName, allowedTypesLibraries)) {
1182
+ return isLibraryAllowed(typesLibraryName, importedLibraries);
1183
+ }
1184
+ return false;
1185
+ }
1186
+ function isLibraryAllowed(libraryName, allowedArray) {
1187
+ return allowedArray === void 0 || allowedArray.indexOf(libraryName) !== -1;
1188
+ }
1189
+ function remapToTypesFromNodeModules(pathRelativeToTypesRoot) {
1190
+ return `node_modules/@types/${pathRelativeToTypesRoot}`;
1191
+ }
1192
+
1193
+ // src/generate-output.ts
1194
+ import * as ts7 from "typescript";
1195
+
1196
+ // src/helpers/package-info.ts
1197
+ import * as fs from "fs";
1198
+ import * as path4 from "path";
1199
+ function getPackageInfo() {
1200
+ let dirName = process.cwd();
1201
+ while (dirName.length !== 0) {
1202
+ const packageJsonFilePath = path4.join(dirName, "package.json");
1203
+ if (fs.existsSync(packageJsonFilePath)) {
1204
+ const pkgContent = fs.readFileSync(packageJsonFilePath, "utf8");
1205
+ const pkg = JSON.parse(pkgContent);
1206
+ let authorName = void 0;
1207
+ if (pkg.author) {
1208
+ authorName = typeof pkg.author === "string" ? pkg.author : pkg.author.name;
1209
+ }
1210
+ return {
1211
+ name: pkg.name || "@sse-ui/locale",
1212
+ version: pkg.version,
1213
+ license: pkg.license || "MIT",
1214
+ author: authorName
1215
+ };
1216
+ }
1217
+ const parentDir = path4.join(dirName, "..");
1218
+ if (parentDir === dirName) {
1219
+ break;
1220
+ }
1221
+ dirName = parentDir;
1222
+ }
1223
+ throw new Error(`Cannot find up package.json in ${__dirname}`);
1224
+ }
1225
+
1226
+ // src/generate-output.ts
1227
+ function generateOutput(params, options = {}) {
1228
+ const resultOutputParts = [];
1229
+ if (!options.noBanner) {
1230
+ const pkg = getPackageInfo();
1231
+ const authorLine = pkg.author ? `
1232
+ * @author ${pkg.author}` : "";
1233
+ resultOutputParts.push(`/**
1234
+ * ${pkg.name} v${pkg.version}${authorLine}
1235
+ *
1236
+ * @license ${pkg.license}
1237
+ * This source code is licensed under the ${pkg.license} license found in the
1238
+ * LICENSE file in the root directory of this source tree.
1239
+ */`);
1240
+ }
1241
+ if (params.typesReferences.size !== 0) {
1242
+ const header = generateReferenceTypesDirective(
1243
+ Array.from(params.typesReferences)
1244
+ );
1245
+ resultOutputParts.push(header);
1246
+ }
1247
+ if (params.imports.size !== 0) {
1248
+ const sortedEntries = Array.from(params.imports.entries()).sort(
1249
+ (firstEntry, secondEntry) => {
1250
+ return firstEntry[0].localeCompare(secondEntry[0]);
1251
+ }
1252
+ );
1253
+ const importsArray = [];
1254
+ for (const [libraryName, libraryImports] of sortedEntries) {
1255
+ importsArray.push(...generateImports(libraryName, libraryImports));
1256
+ }
1257
+ if (importsArray.length !== 0) {
1258
+ resultOutputParts.push(importsArray.join("\n"));
1259
+ }
1260
+ }
1261
+ const statements = params.statements.map(
1262
+ (statement) => getStatementText(statement, Boolean(options.sortStatements), params)
1263
+ );
1264
+ if (options.sortStatements) {
1265
+ statements.sort(compareStatementText);
1266
+ }
1267
+ if (statements.length !== 0) {
1268
+ resultOutputParts.push(statementsTextToString(statements));
1269
+ }
1270
+ if (params.wrappedNamespaces.size !== 0) {
1271
+ resultOutputParts.push(
1272
+ Array.from(params.wrappedNamespaces.entries()).map(
1273
+ ([namespaceName, exportedNames]) => {
1274
+ return `declare namespace ${namespaceName} {
1275
+ export { ${Array.from(
1276
+ exportedNames.entries()
1277
+ ).map(
1278
+ ([exportedName, localName]) => renamedExportValue(exportedName, localName)
1279
+ ).sort().join(", ")} };
1280
+ }`;
1281
+ }
1282
+ ).join("\n")
1283
+ );
1284
+ }
1285
+ if (params.renamedExports.size !== 0) {
1286
+ resultOutputParts.push(
1287
+ `export {
1288
+ ${Array.from(params.renamedExports.entries()).map(
1289
+ ([exportedName, localName]) => renamedExportValue(exportedName, localName)
1290
+ ).sort().join(",\n ")},
1291
+ };`
1292
+ );
1293
+ }
1294
+ if (options.umdModuleName !== void 0) {
1295
+ resultOutputParts.push(`export as namespace ${options.umdModuleName};`);
1296
+ }
1297
+ resultOutputParts.push(`export {};
1298
+ `);
1299
+ return resultOutputParts.join("\n\n");
1300
+ }
1301
+ function statementsTextToString(statements) {
1302
+ const statementsText = statements.map((statement) => statement.text).join("\n");
1303
+ return spacesToTabs(prettifyStatementsText(statementsText));
1304
+ }
1305
+ function renamedExportValue(exportedName, localName) {
1306
+ return exportedName !== localName ? `${localName} as ${exportedName}` : exportedName;
1307
+ }
1308
+ function renamedImportValue(importedName, localName) {
1309
+ return importedName !== localName ? `${importedName} as ${localName}` : importedName;
1310
+ }
1311
+ function prettifyStatementsText(statementsText) {
1312
+ const sourceFile = ts7.createSourceFile(
1313
+ "output.d.ts",
1314
+ statementsText,
1315
+ ts7.ScriptTarget.Latest,
1316
+ false,
1317
+ ts7.ScriptKind.TS
1318
+ );
1319
+ const printer = ts7.createPrinter({
1320
+ newLine: ts7.NewLineKind.LineFeed,
1321
+ removeComments: false
1322
+ });
1323
+ return printer.printFile(sourceFile).trim();
1324
+ }
1325
+ function compareStatementText(a, b) {
1326
+ if (a.sortingValue > b.sortingValue) {
1327
+ return 1;
1328
+ } else if (a.sortingValue < b.sortingValue) {
1329
+ return -1;
1330
+ }
1331
+ return 0;
1332
+ }
1333
+ function recreateEntityName(node, helpers) {
1334
+ const resolvedName = helpers.resolveIdentifierName(node);
1335
+ if (resolvedName !== null && resolvedName !== node.getText()) {
1336
+ const identifiers = resolvedName.split(".");
1337
+ let result = ts7.factory.createIdentifier(identifiers[0]);
1338
+ for (let index = 1; index < identifiers.length; index += 1) {
1339
+ result = ts7.factory.createQualifiedName(
1340
+ result,
1341
+ ts7.factory.createIdentifier(identifiers[index])
1342
+ );
1343
+ }
1344
+ return result;
1345
+ }
1346
+ return node;
1347
+ }
1348
+ function getStatementText(statement, includeSortingValue, helpers) {
1349
+ const { shouldHaveExportKeyword, shouldHaveJSDoc } = helpers.getStatementSettings(statement);
1350
+ const needResolveIdentifiers = !ts7.isExportDeclaration(statement) || statement.moduleSpecifier === void 0;
1351
+ const printer = ts7.createPrinter(
1352
+ {
1353
+ newLine: ts7.NewLineKind.LineFeed,
1354
+ removeComments: false
1355
+ },
1356
+ {
1357
+ // eslint-disable-next-line complexity
1358
+ substituteNode: (hint, node) => {
1359
+ if (node.parent === void 0) {
1360
+ return node;
1361
+ }
1362
+ if (needResolveIdentifiers) {
1363
+ if (ts7.isPropertyAccessExpression(node)) {
1364
+ const resolvedName = helpers.resolveIdentifierName(
1365
+ node
1366
+ );
1367
+ if (resolvedName !== null && resolvedName !== node.getText()) {
1368
+ const identifiers = resolvedName.split(".");
1369
+ let result = ts7.factory.createIdentifier(identifiers[0]);
1370
+ for (let index = 1; index < identifiers.length; index += 1) {
1371
+ result = ts7.factory.createPropertyAccessExpression(
1372
+ result,
1373
+ ts7.factory.createIdentifier(identifiers[index])
1374
+ );
1375
+ }
1376
+ return result;
1377
+ }
1378
+ return node;
1379
+ }
1380
+ if (ts7.isIdentifier(node) || ts7.isQualifiedName(node)) {
1381
+ if (ts7.isIdentifier(node) && (ts7.isQualifiedName(node.parent) || ts7.isPropertyAccessExpression(node.parent))) {
1382
+ return node;
1383
+ }
1384
+ if (ts7.isIdentifier(node) && ts7.isImportTypeNode(node.parent) && node.parent.qualifier === node) {
1385
+ return node;
1386
+ }
1387
+ return recreateEntityName(node, helpers);
1388
+ }
1389
+ }
1390
+ if (ts7.isImportTypeNode(node) && node.qualifier !== void 0 && helpers.needStripImportFromImportTypeNode(node)) {
1391
+ const newQualifier = recreateEntityName(node.qualifier, helpers);
1392
+ if (node.isTypeOf) {
1393
+ return ts7.factory.createTypeQueryNode(newQualifier);
1394
+ }
1395
+ return ts7.factory.createTypeReferenceNode(
1396
+ newQualifier,
1397
+ node.typeArguments
1398
+ );
1399
+ }
1400
+ if (node !== statement) {
1401
+ return node;
1402
+ }
1403
+ const modifiersMap = modifiersToMap(getModifiers2(node));
1404
+ if (ts7.isEnumDeclaration(node) && modifiersMap[ts7.SyntaxKind.ConstKeyword] && helpers.needStripConstFromConstEnum(node)) {
1405
+ modifiersMap[ts7.SyntaxKind.ConstKeyword] = false;
1406
+ }
1407
+ const nodeName = getNodeName(node);
1408
+ const resolvedStatementName = nodeName !== void 0 ? helpers.resolveIdentifierName(nodeName) || void 0 : void 0;
1409
+ if (modifiersMap[ts7.SyntaxKind.DefaultKeyword]) {
1410
+ modifiersMap[ts7.SyntaxKind.DefaultKeyword] = false;
1411
+ if (ts7.isClassDeclaration(node)) {
1412
+ modifiersMap[ts7.SyntaxKind.DeclareKeyword] = true;
1413
+ }
1414
+ }
1415
+ if (!shouldHaveExportKeyword) {
1416
+ modifiersMap[ts7.SyntaxKind.ExportKeyword] = false;
1417
+ } else {
1418
+ modifiersMap[ts7.SyntaxKind.ExportKeyword] = true;
1419
+ }
1420
+ if (!modifiersMap[ts7.SyntaxKind.ExportKeyword] && (ts7.isClassDeclaration(node) || ts7.isFunctionDeclaration(node) || ts7.isVariableStatement(node) || ts7.isEnumDeclaration(node) || ts7.isModuleDeclaration(node))) {
1421
+ modifiersMap[ts7.SyntaxKind.DeclareKeyword] = true;
1422
+ }
1423
+ return recreateRootLevelNodeWithModifiers(
1424
+ node,
1425
+ modifiersMap,
1426
+ resolvedStatementName,
1427
+ shouldHaveJSDoc
1428
+ );
1429
+ }
1430
+ }
1431
+ );
1432
+ const statementText = printer.printNode(ts7.EmitHint.Unspecified, statement, statement.getSourceFile()).trim();
1433
+ let sortingValue = "";
1434
+ if (includeSortingValue) {
1435
+ const tempSourceFile = ts7.createSourceFile(
1436
+ "temp.d.ts",
1437
+ statementText,
1438
+ ts7.ScriptTarget.ESNext
1439
+ );
1440
+ sortingValue = tempSourceFile.getChildren()[0].getText();
1441
+ }
1442
+ return { text: statementText, sortingValue };
1443
+ }
1444
+ function generateImports(libraryName, imports) {
1445
+ const fromEnding = `from '${libraryName}';`;
1446
+ const result = [];
1447
+ if (imports.nsImport !== null) {
1448
+ result.push(`import * as ${imports.nsImport} ${fromEnding}`);
1449
+ }
1450
+ Array.from(imports.requireImports).sort().forEach(
1451
+ (importName) => result.push(`import ${importName} = require('${libraryName}');`)
1452
+ );
1453
+ Array.from(imports.defaultImports).sort().forEach(
1454
+ (importName) => result.push(`import ${importName} ${fromEnding}`)
1455
+ );
1456
+ if (imports.namedImports.size !== 0) {
1457
+ result.push(
1458
+ `import { ${Array.from(imports.namedImports.entries()).map(
1459
+ ([localName, importedName]) => renamedImportValue(importedName, localName)
1460
+ ).sort().join(", ")} } ${fromEnding}`
1461
+ );
1462
+ }
1463
+ if (imports.reExports.size !== 0) {
1464
+ result.push(
1465
+ `export { ${Array.from(imports.reExports.entries()).map(
1466
+ ([localName, importedName]) => renamedImportValue(importedName, localName)
1467
+ ).sort().join(", ")} } ${fromEnding}`
1468
+ );
1469
+ }
1470
+ return result;
1471
+ }
1472
+ function generateReferenceTypesDirective(libraries) {
1473
+ return libraries.sort().map((library) => {
1474
+ return `/// <reference types="${library}" />`;
1475
+ }).join("\n");
1476
+ }
1477
+ function spacesToTabs(text) {
1478
+ return text.replace(/^( )+/gm, (substring) => {
1479
+ return " ".repeat(substring.length / 4);
1480
+ });
1481
+ }
1482
+
1483
+ // src/collisions-resolver.ts
1484
+ import * as ts8 from "typescript";
1485
+ var renamingSupportedSymbols = [
1486
+ ts8.SymbolFlags.Alias,
1487
+ ts8.SymbolFlags.Variable,
1488
+ ts8.SymbolFlags.Class,
1489
+ ts8.SymbolFlags.Enum,
1490
+ ts8.SymbolFlags.Function,
1491
+ ts8.SymbolFlags.Interface,
1492
+ ts8.SymbolFlags.NamespaceModule,
1493
+ ts8.SymbolFlags.TypeAlias,
1494
+ ts8.SymbolFlags.ValueModule
1495
+ ];
1496
+ var CollisionsResolver = class {
1497
+ typeChecker;
1498
+ collisionsMap = /* @__PURE__ */ new Map();
1499
+ generatedNames = /* @__PURE__ */ new Map();
1500
+ constructor(typeChecker) {
1501
+ this.typeChecker = typeChecker;
1502
+ }
1503
+ /**
1504
+ * Adds (or "registers") a top-level {@link identifier} (which takes a top-level scope name to use).
1505
+ */
1506
+ addTopLevelIdentifier(identifier) {
1507
+ const symbol = getDeclarationNameSymbol(identifier, this.typeChecker);
1508
+ if (symbol === null) {
1509
+ throw new Error(`Something went wrong - cannot find a symbol for top-level identifier ${identifier.getText()} (from ${identifier.parent.parent.getText()})`);
1510
+ }
1511
+ const newLocalName = this.registerSymbol(symbol, identifier.getText());
1512
+ if (newLocalName === null) {
1513
+ throw new Error(`Something went wrong - a symbol ${symbol.name} for top-level identifier ${identifier.getText()} cannot be renamed`);
1514
+ }
1515
+ return newLocalName;
1516
+ }
1517
+ /**
1518
+ * Returns a set of all already registered names for a given {@link symbol}.
1519
+ */
1520
+ namesForSymbol(symbol) {
1521
+ return this.generatedNames.get(getActualSymbol(symbol, this.typeChecker)) || /* @__PURE__ */ new Set();
1522
+ }
1523
+ /**
1524
+ * Resolves given {@link referencedIdentifier} to a name.
1525
+ * It assumes that a symbol for this identifier has been registered before by calling {@link addTopLevelIdentifier} method.
1526
+ * Otherwise it will return `null`.
1527
+ *
1528
+ * Note that a returned value might be of a different type of the identifier (e.g. {@link ts.QualifiedName} for a given {@link ts.Identifier})
1529
+ */
1530
+ resolveReferencedIdentifier(referencedIdentifier) {
1531
+ const identifierSymbol = getDeclarationNameSymbol(referencedIdentifier, this.typeChecker);
1532
+ if (identifierSymbol === null) {
1533
+ return null;
1534
+ }
1535
+ const symbolScopePath = this.getSymbolScope(identifierSymbol);
1536
+ const currentIdentifierScope = this.getNodeScope(referencedIdentifier);
1537
+ if (symbolScopePath.length > 0 && currentIdentifierScope.length > 0 && symbolScopePath[0] === currentIdentifierScope[0]) {
1538
+ return referencedIdentifier.getText();
1539
+ }
1540
+ const topLevelIdentifierSymbol = symbolScopePath.length === 0 ? identifierSymbol : symbolScopePath[0];
1541
+ const namesForTopLevelSymbol = this.namesForSymbol(topLevelIdentifierSymbol);
1542
+ if (namesForTopLevelSymbol.size === 0) {
1543
+ return null;
1544
+ }
1545
+ let topLevelName = symbolScopePath.length === 0 ? referencedIdentifier.getText() : topLevelIdentifierSymbol.getName();
1546
+ if (!namesForTopLevelSymbol.has(topLevelName)) {
1547
+ const topLevelNamesArray = Array.from(namesForTopLevelSymbol);
1548
+ let suitableTopLevelName = topLevelNamesArray[0];
1549
+ for (const name of topLevelNamesArray) {
1550
+ if (name.startsWith(`${topLevelName}$`)) {
1551
+ suitableTopLevelName = name;
1552
+ break;
1553
+ }
1554
+ }
1555
+ topLevelName = suitableTopLevelName;
1556
+ }
1557
+ const newIdentifierParts = [
1558
+ ...symbolScopePath.map((symbol) => symbol.getName()),
1559
+ referencedIdentifier.getText()
1560
+ ];
1561
+ newIdentifierParts[0] = topLevelName;
1562
+ return newIdentifierParts.join(".");
1563
+ }
1564
+ /**
1565
+ * Similar to {@link resolveReferencedIdentifier}, but works with qualified names (Ns.Ns1.Interface).
1566
+ * The main point of this resolver is that it might change the first part of the qualifier only (as it drives uniqueness of a name).
1567
+ */
1568
+ resolveReferencedQualifiedName(referencedIdentifier) {
1569
+ let topLevelIdentifier = referencedIdentifier;
1570
+ if (ts8.isQualifiedName(topLevelIdentifier) || ts8.isPropertyAccessExpression(topLevelIdentifier)) {
1571
+ let leftmostIdentifier = ts8.isQualifiedName(topLevelIdentifier) ? topLevelIdentifier.left : topLevelIdentifier.expression;
1572
+ while (ts8.isQualifiedName(leftmostIdentifier) || ts8.isPropertyAccessExpression(leftmostIdentifier)) {
1573
+ leftmostIdentifier = ts8.isQualifiedName(leftmostIdentifier) ? leftmostIdentifier.left : leftmostIdentifier.expression;
1574
+ }
1575
+ topLevelIdentifier = leftmostIdentifier;
1576
+ }
1577
+ const topLevelName = this.resolveReferencedIdentifier(topLevelIdentifier);
1578
+ if (topLevelName === null) {
1579
+ const identifierSymbol = getDeclarationNameSymbol(referencedIdentifier, this.typeChecker);
1580
+ if (identifierSymbol === null) {
1581
+ return null;
1582
+ }
1583
+ const namesForSymbol = this.namesForSymbol(identifierSymbol);
1584
+ if (namesForSymbol.size !== 0) {
1585
+ return Array.from(namesForSymbol)[0];
1586
+ }
1587
+ return null;
1588
+ }
1589
+ const identifierParts = referencedIdentifier.getText().split(".");
1590
+ identifierParts[0] = topLevelName;
1591
+ return identifierParts.join(".");
1592
+ }
1593
+ getSymbolScope(identifierSymbol) {
1594
+ const identifierDeclarations = getDeclarationsForSymbol(identifierSymbol);
1595
+ if (identifierDeclarations.length === 0) {
1596
+ return [];
1597
+ }
1598
+ return this.getNodeScope(identifierDeclarations[0]);
1599
+ }
1600
+ /**
1601
+ * Returns a node's scope where it is located in terms of namespaces/modules.
1602
+ * E.g. A scope for `Opt` in `declare module foo { type Opt = number; }` is `[Symbol(foo)]`
1603
+ */
1604
+ getNodeScope(node) {
1605
+ const scopeIdentifiersPath = [];
1606
+ let currentNode = getClosestModuleLikeNode(node);
1607
+ while (ts8.isModuleDeclaration(currentNode) && ts8.isIdentifier(currentNode.name)) {
1608
+ const nameSymbol = getDeclarationNameSymbol(currentNode.name, this.typeChecker);
1609
+ if (nameSymbol === null) {
1610
+ throw new Error(`Cannot find symbol for identifier '${currentNode.name.getText()}'`);
1611
+ }
1612
+ scopeIdentifiersPath.push(nameSymbol);
1613
+ currentNode = getClosestModuleLikeNode(currentNode.parent);
1614
+ }
1615
+ return scopeIdentifiersPath.reverse();
1616
+ }
1617
+ registerSymbol(identifierSymbol, preferredName) {
1618
+ if (!renamingSupportedSymbols.some((flag) => identifierSymbol.flags & flag)) {
1619
+ verboseLog(`Symbol ${identifierSymbol.name} cannot be renamed because its flag (${identifierSymbol.flags}) isn't supported`);
1620
+ return null;
1621
+ }
1622
+ if (identifierSymbol.flags & ts8.SymbolFlags.NamespaceModule && identifierSymbol.escapedName === ts8.InternalSymbolName.Global) {
1623
+ return null;
1624
+ }
1625
+ let symbolName = preferredName;
1626
+ if (symbolName === "default") {
1627
+ symbolName = "_default";
1628
+ }
1629
+ const collisionsKey = symbolName;
1630
+ let collisionSymbols = this.collisionsMap.get(collisionsKey);
1631
+ if (collisionSymbols === void 0) {
1632
+ collisionSymbols = /* @__PURE__ */ new Map();
1633
+ this.collisionsMap.set(collisionsKey, collisionSymbols);
1634
+ }
1635
+ const storedSymbolName = collisionSymbols.get(identifierSymbol);
1636
+ if (storedSymbolName !== void 0) {
1637
+ return storedSymbolName;
1638
+ }
1639
+ let nameIndex = collisionSymbols.size;
1640
+ let newName = collisionSymbols.size === 0 ? symbolName : `${symbolName}$${nameIndex}`;
1641
+ let resolvedGlobalSymbol = resolveGlobalName(this.typeChecker, newName);
1642
+ while (resolvedGlobalSymbol !== void 0 && resolvedGlobalSymbol !== identifierSymbol) {
1643
+ nameIndex += 1;
1644
+ newName = `${symbolName}$${nameIndex}`;
1645
+ resolvedGlobalSymbol = resolveGlobalName(this.typeChecker, newName);
1646
+ }
1647
+ collisionSymbols.set(identifierSymbol, newName);
1648
+ let symbolNames = this.generatedNames.get(identifierSymbol);
1649
+ if (symbolNames === void 0) {
1650
+ symbolNames = /* @__PURE__ */ new Set();
1651
+ this.generatedNames.set(identifierSymbol, symbolNames);
1652
+ }
1653
+ symbolNames.add(newName);
1654
+ return newName;
1655
+ }
1656
+ };
1657
+
1658
+ // src/bundle-generator.ts
1659
+ function generateDtsBundle(entries, options = {}) {
1660
+ normalLog("Compiling input files...");
1661
+ const { program, rootFilesRemapping } = compileDts(
1662
+ entries.map((entry) => entry.filePath),
1663
+ options.preferredConfigPath,
1664
+ options.followSymlinks
1665
+ );
1666
+ const typeChecker = program.getTypeChecker();
1667
+ const typeRoots = ts9.getEffectiveTypeRoots(program.getCompilerOptions(), {});
1668
+ const sourceFiles = program.getSourceFiles().filter((file) => {
1669
+ return !program.isSourceFileDefaultLibrary(file);
1670
+ });
1671
+ const typesUsageEvaluator = new TypesUsageEvaluator(sourceFiles, typeChecker);
1672
+ return entries.map((entryConfig) => {
1673
+ normalLog(`Processing ${entryConfig.filePath}`);
1674
+ const newRootFilePath = rootFilesRemapping.get(entryConfig.filePath);
1675
+ if (newRootFilePath === void 0) {
1676
+ throw new Error(`Cannot remap root source file ${entryConfig.filePath}`);
1677
+ }
1678
+ const rootSourceFile = getRootSourceFile(program, newRootFilePath);
1679
+ const rootSourceFileSymbol = typeChecker.getSymbolAtLocation(rootSourceFile);
1680
+ if (rootSourceFileSymbol === void 0) {
1681
+ throw new Error(
1682
+ `Symbol for root source file ${newRootFilePath} not found`
1683
+ );
1684
+ }
1685
+ const librariesOptions = entryConfig.libraries || {};
1686
+ const criteria = {
1687
+ allowedTypesLibraries: librariesOptions.allowedTypesLibraries,
1688
+ importedLibraries: librariesOptions.importedLibraries,
1689
+ inlinedLibraries: librariesOptions.inlinedLibraries || [],
1690
+ typeRoots
1691
+ };
1692
+ const rootFileExports = getExportsForSourceFile(
1693
+ typeChecker,
1694
+ rootSourceFileSymbol
1695
+ );
1696
+ const rootFileExportSymbols = rootFileExports.map(
1697
+ (exp) => exp.symbol
1698
+ );
1699
+ const collectionResult = {
1700
+ typesReferences: /* @__PURE__ */ new Set(),
1701
+ imports: /* @__PURE__ */ new Map(),
1702
+ statements: [],
1703
+ renamedExports: /* @__PURE__ */ new Map(),
1704
+ wrappedNamespaces: /* @__PURE__ */ new Map()
1705
+ };
1706
+ const outputOptions = entryConfig.output || {};
1707
+ const inlineDeclareGlobals = Boolean(outputOptions.inlineDeclareGlobals);
1708
+ const inlineDeclareExternals = Boolean(
1709
+ outputOptions.inlineDeclareExternals
1710
+ );
1711
+ const collisionsResolver = new CollisionsResolver(typeChecker);
1712
+ function updateResultForAnyModule(statements, currentModule) {
1713
+ const visitedModules = /* @__PURE__ */ new Set();
1714
+ function updateResultForExternalExport(exportAssignment) {
1715
+ for (const declaration of getDeclarationsForExportedValues(
1716
+ exportAssignment,
1717
+ typeChecker
1718
+ )) {
1719
+ if (ts9.isVariableDeclaration(declaration)) {
1720
+ continue;
1721
+ }
1722
+ let exportedDeclarations = [];
1723
+ if (ts9.isExportDeclaration(exportAssignment) && ts9.isSourceFile(declaration)) {
1724
+ const referencedModule = getReferencedModuleInfo(
1725
+ exportAssignment,
1726
+ criteria,
1727
+ typeChecker
1728
+ );
1729
+ if (referencedModule !== null) {
1730
+ if (visitedModules.has(referencedModule.fileName)) {
1731
+ continue;
1732
+ }
1733
+ visitedModules.add(referencedModule.fileName);
1734
+ }
1735
+ exportedDeclarations = declaration.statements;
1736
+ } else if (ts9.isModuleDeclaration(declaration)) {
1737
+ if (declaration.body !== void 0 && ts9.isModuleBlock(declaration.body)) {
1738
+ const referencedModule = getReferencedModuleInfo(
1739
+ declaration,
1740
+ criteria,
1741
+ typeChecker
1742
+ );
1743
+ if (referencedModule !== null) {
1744
+ if (visitedModules.has(referencedModule.fileName)) {
1745
+ continue;
1746
+ }
1747
+ visitedModules.add(referencedModule.fileName);
1748
+ }
1749
+ exportedDeclarations = declaration.body.statements;
1750
+ }
1751
+ } else {
1752
+ exportedDeclarations = [declaration];
1753
+ }
1754
+ updateResultImpl(exportedDeclarations);
1755
+ }
1756
+ }
1757
+ function updateResultImpl(statementsToProcess) {
1758
+ for (const statement of statementsToProcess) {
1759
+ if (statement.kind === ts9.SyntaxKind.ImportDeclaration || statement.kind === ts9.SyntaxKind.ImportEqualsDeclaration) {
1760
+ continue;
1761
+ }
1762
+ if (isDeclareModule(statement)) {
1763
+ updateResultForModuleDeclaration(statement, currentModule);
1764
+ if (ts9.isStringLiteral(statement.name)) {
1765
+ continue;
1766
+ }
1767
+ }
1768
+ if (currentModule.type === 3 /* ShouldBeUsedForModulesOnly */) {
1769
+ continue;
1770
+ }
1771
+ if (isDeclareGlobalStatement(statement) && inlineDeclareGlobals && currentModule.type === 0 /* ShouldBeInlined */) {
1772
+ collectionResult.statements.push(statement);
1773
+ continue;
1774
+ }
1775
+ if (ts9.isExportDeclaration(statement)) {
1776
+ if (currentModule.type === 0 /* ShouldBeInlined */) {
1777
+ continue;
1778
+ }
1779
+ if (statement.exportClause === void 0) {
1780
+ updateResultForExternalExport(statement);
1781
+ continue;
1782
+ }
1783
+ if (ts9.isNamedExports(statement.exportClause) && currentModule.type === 1 /* ShouldBeImported */) {
1784
+ updateImportsForStatement(statement);
1785
+ continue;
1786
+ }
1787
+ }
1788
+ if (ts9.isExportAssignment(statement) && statement.isExportEquals && currentModule.type !== 0 /* ShouldBeInlined */) {
1789
+ updateResultForExternalExport(statement);
1790
+ continue;
1791
+ }
1792
+ if (!isNodeUsed(statement)) {
1793
+ continue;
1794
+ }
1795
+ switch (currentModule.type) {
1796
+ case 2 /* ShouldBeReferencedAsTypes */:
1797
+ forEachNodeThatShouldBeImported(
1798
+ statement,
1799
+ () => addTypesReference(currentModule.typesLibraryName)
1800
+ );
1801
+ break;
1802
+ case 1 /* ShouldBeImported */:
1803
+ updateImportsForStatement(statement);
1804
+ break;
1805
+ case 0 /* ShouldBeInlined */:
1806
+ if (ts9.isVariableStatement(statement)) {
1807
+ for (const variableDeclaration of statement.declarationList.declarations) {
1808
+ if (ts9.isIdentifier(variableDeclaration.name)) {
1809
+ collisionsResolver.addTopLevelIdentifier(
1810
+ variableDeclaration.name
1811
+ );
1812
+ continue;
1813
+ }
1814
+ for (const element of variableDeclaration.name.elements) {
1815
+ if (!ts9.isOmittedExpression(element) && ts9.isIdentifier(element.name)) {
1816
+ collisionsResolver.addTopLevelIdentifier(element.name);
1817
+ }
1818
+ }
1819
+ }
1820
+ } else if (isNodeNamedDeclaration(statement)) {
1821
+ const statementName = getNodeName(statement);
1822
+ if (statementName !== void 0) {
1823
+ collisionsResolver.addTopLevelIdentifier(
1824
+ statementName
1825
+ );
1826
+ }
1827
+ }
1828
+ collectionResult.statements.push(statement);
1829
+ break;
1830
+ }
1831
+ }
1832
+ }
1833
+ updateResultImpl(statements);
1834
+ }
1835
+ function isReferencedModuleImportable(statement) {
1836
+ return getReferencedModuleInfo(statement, criteria, typeChecker)?.type === 1 /* ShouldBeImported */;
1837
+ }
1838
+ function handleExportDeclarationFromRootModule(exportDeclaration) {
1839
+ function handleExportStarStatement(exportStarStatement, visitedSymbols = /* @__PURE__ */ new Set()) {
1840
+ if (exportStarStatement.moduleSpecifier === void 0 || exportStarStatement.exportClause !== void 0) {
1841
+ throw new Error(
1842
+ `Invalid export-star declaration statement provided, ${exportStarStatement.getText()}`
1843
+ );
1844
+ }
1845
+ const importModuleSpecifier = getImportModuleName(exportStarStatement);
1846
+ if (importModuleSpecifier === null) {
1847
+ return;
1848
+ }
1849
+ const referencedModuleInfo = getReferencedModuleInfo(
1850
+ exportStarStatement,
1851
+ criteria,
1852
+ typeChecker
1853
+ );
1854
+ if (referencedModuleInfo === null) {
1855
+ return;
1856
+ }
1857
+ switch (referencedModuleInfo.type) {
1858
+ case 0 /* ShouldBeInlined */: {
1859
+ const referencedModuleSymbol = getNodeOwnSymbol(
1860
+ exportStarStatement.moduleSpecifier,
1861
+ typeChecker
1862
+ );
1863
+ const referencedSourceFileExportStarSymbol = referencedModuleSymbol.exports?.get(
1864
+ ts9.InternalSymbolName.ExportStar
1865
+ );
1866
+ if (referencedSourceFileExportStarSymbol !== void 0) {
1867
+ if (visitedSymbols.has(referencedSourceFileExportStarSymbol)) {
1868
+ return;
1869
+ }
1870
+ visitedSymbols.add(referencedSourceFileExportStarSymbol);
1871
+ for (const exportDecl of getSymbolExportStarDeclarations(
1872
+ referencedSourceFileExportStarSymbol
1873
+ )) {
1874
+ handleExportStarStatement(exportDecl, visitedSymbols);
1875
+ }
1876
+ }
1877
+ break;
1878
+ }
1879
+ case 1 /* ShouldBeImported */: {
1880
+ collectionResult.statements.push(exportStarStatement);
1881
+ break;
1882
+ }
1883
+ }
1884
+ }
1885
+ function findExportingExportStarExportFromImportableModule(referencedModuleSymbol, nodeSymbol) {
1886
+ function findResultRecursively(referencedModuleSym, exportedNodeSym, visitedSymbols) {
1887
+ if (visitedSymbols.has(referencedModuleSym)) {
1888
+ return null;
1889
+ }
1890
+ visitedSymbols.add(referencedModuleSym);
1891
+ const exportStarExport = referencedModuleSym.exports?.get(
1892
+ ts9.InternalSymbolName.ExportStar
1893
+ );
1894
+ if (exportStarExport === void 0) {
1895
+ return null;
1896
+ }
1897
+ for (const exportStarDeclaration of getDeclarationsForSymbol(
1898
+ exportStarExport
1899
+ ).filter(ts9.isExportDeclaration)) {
1900
+ if (exportStarDeclaration.moduleSpecifier === void 0) {
1901
+ continue;
1902
+ }
1903
+ const exportStarModuleSymbol = getNodeOwnSymbol(
1904
+ exportStarDeclaration.moduleSpecifier,
1905
+ typeChecker
1906
+ );
1907
+ if (exportStarModuleSymbol.exports === void 0) {
1908
+ continue;
1909
+ }
1910
+ if (isReferencedModuleImportable(exportStarDeclaration)) {
1911
+ const referencedModuleExports = typeChecker.getExportsOfModule(
1912
+ exportStarModuleSymbol
1913
+ );
1914
+ const exportedNodeSymbol = referencedModuleExports.find(
1915
+ (exp) => getActualSymbol(exp, typeChecker) === nodeSymbol
1916
+ );
1917
+ if (exportedNodeSymbol !== void 0) {
1918
+ return { exportStarDeclaration, exportedNodeSymbol };
1919
+ }
1920
+ continue;
1921
+ }
1922
+ const result = findResultRecursively(
1923
+ exportStarModuleSymbol,
1924
+ exportedNodeSym,
1925
+ visitedSymbols
1926
+ );
1927
+ if (result !== null) {
1928
+ return result;
1929
+ }
1930
+ }
1931
+ return null;
1932
+ }
1933
+ if (referencedModuleSymbol.exports === void 0) {
1934
+ throw new Error(
1935
+ `No exports found for "${referencedModuleSymbol.getName()}" symbol`
1936
+ );
1937
+ }
1938
+ const hasExplicitExportOfSymbol = Array.from(
1939
+ referencedModuleSymbol.exports.values()
1940
+ ).some((exp) => {
1941
+ if (exp.escapedName === ts9.InternalSymbolName.ExportStar) {
1942
+ return false;
1943
+ }
1944
+ return getActualSymbol(exp, typeChecker) === nodeSymbol;
1945
+ });
1946
+ if (hasExplicitExportOfSymbol) {
1947
+ return null;
1948
+ }
1949
+ return findResultRecursively(
1950
+ referencedModuleSymbol,
1951
+ nodeSymbol,
1952
+ /* @__PURE__ */ new Set()
1953
+ );
1954
+ }
1955
+ if (exportDeclaration.exportClause === void 0) {
1956
+ handleExportStarStatement(exportDeclaration);
1957
+ return;
1958
+ }
1959
+ if (exportDeclaration.exportClause !== void 0 && ts9.isNamedExports(exportDeclaration.exportClause)) {
1960
+ if (exportDeclaration.moduleSpecifier === void 0) {
1961
+ for (const exportElement of exportDeclaration.exportClause.elements) {
1962
+ const exportElementSymbol = getImportExportReferencedSymbol(
1963
+ exportElement,
1964
+ typeChecker
1965
+ );
1966
+ const namespaceImportFromImportableModule = getDeclarationsForSymbol(exportElementSymbol).find(
1967
+ (importDecl) => {
1968
+ return ts9.isNamespaceImport(importDecl) && isReferencedModuleImportable(
1969
+ importDecl.parent.parent
1970
+ );
1971
+ }
1972
+ );
1973
+ if (namespaceImportFromImportableModule !== void 0) {
1974
+ const importModuleSpecifier = getImportModuleName(
1975
+ namespaceImportFromImportableModule.parent.parent
1976
+ );
1977
+ if (importModuleSpecifier === null) {
1978
+ throw new Error(
1979
+ `Cannot get import module name from '${namespaceImportFromImportableModule.parent.parent.getText()}'`
1980
+ );
1981
+ }
1982
+ addNsImport(
1983
+ getImportItem(importModuleSpecifier),
1984
+ namespaceImportFromImportableModule.name
1985
+ );
1986
+ }
1987
+ }
1988
+ return;
1989
+ }
1990
+ if (exportDeclaration.moduleSpecifier !== void 0) {
1991
+ const referencedModuleSymbol = getNodeOwnSymbol(
1992
+ exportDeclaration.moduleSpecifier,
1993
+ typeChecker
1994
+ );
1995
+ for (const exportElement of exportDeclaration.exportClause.elements) {
1996
+ const exportedNodeSymbol = getActualSymbol(
1997
+ getImportExportReferencedSymbol(exportElement, typeChecker),
1998
+ typeChecker
1999
+ );
2000
+ const exportingExportStarResult = findExportingExportStarExportFromImportableModule(
2001
+ referencedModuleSymbol,
2002
+ exportedNodeSymbol
2003
+ );
2004
+ if (exportingExportStarResult === null) {
2005
+ continue;
2006
+ }
2007
+ const importModuleSpecifier = getImportModuleName(
2008
+ exportingExportStarResult.exportStarDeclaration
2009
+ );
2010
+ if (importModuleSpecifier === null) {
2011
+ throw new Error(
2012
+ `Cannot get import module name from '${exportingExportStarResult.exportStarDeclaration.getText()}'`
2013
+ );
2014
+ }
2015
+ addReExport(
2016
+ getImportItem(importModuleSpecifier),
2017
+ exportingExportStarResult.exportedNodeSymbol.getName(),
2018
+ exportElement.name.text
2019
+ );
2020
+ }
2021
+ return;
2022
+ }
2023
+ }
2024
+ }
2025
+ function updateResultForRootModule(statements, currentModule) {
2026
+ updateResultForAnyModule(statements, currentModule);
2027
+ for (const statement of statements) {
2028
+ if (ts9.isExportDeclaration(statement)) {
2029
+ handleExportDeclarationFromRootModule(statement);
2030
+ continue;
2031
+ }
2032
+ if (ts9.isExportAssignment(statement)) {
2033
+ if (statement.isExportEquals || !ts9.isIdentifier(statement.expression)) {
2034
+ collectionResult.statements.push(statement);
2035
+ }
2036
+ continue;
2037
+ }
2038
+ }
2039
+ }
2040
+ function updateResultForModuleDeclaration(moduleDecl, currentModule) {
2041
+ if (moduleDecl.body === void 0 || !ts9.isModuleBlock(moduleDecl.body)) {
2042
+ return;
2043
+ }
2044
+ const referencedModuleInfo = getModuleLikeModuleInfo(
2045
+ moduleDecl,
2046
+ criteria,
2047
+ typeChecker
2048
+ );
2049
+ if (referencedModuleInfo === null) {
2050
+ return;
2051
+ }
2052
+ if (!currentModule.isExternal && referencedModuleInfo.isExternal) {
2053
+ if (inlineDeclareExternals) {
2054
+ collectionResult.statements.push(moduleDecl);
2055
+ }
2056
+ return;
2057
+ }
2058
+ updateResultForAnyModule(
2059
+ moduleDecl.body.statements,
2060
+ referencedModuleInfo
2061
+ );
2062
+ }
2063
+ function addTypesReference(library) {
2064
+ if (!collectionResult.typesReferences.has(library)) {
2065
+ normalLog(`Library "${library}" will be added via reference directive`);
2066
+ collectionResult.typesReferences.add(library);
2067
+ }
2068
+ }
2069
+ function forEachNodeThatShouldBeImported(statement, callback) {
2070
+ const statementsToImport = ts9.isVariableStatement(statement) ? statement.declarationList.declarations : ts9.isExportDeclaration(statement) && statement.exportClause !== void 0 ? ts9.isNamespaceExport(statement.exportClause) ? [statement.exportClause] : statement.exportClause.elements : [statement];
2071
+ for (const statementToImport of statementsToImport) {
2072
+ if (shouldNodeBeImported(statementToImport)) {
2073
+ callback(statementToImport);
2074
+ }
2075
+ }
2076
+ }
2077
+ function updateImportsForStatement(statement) {
2078
+ forEachNodeThatShouldBeImported(
2079
+ statement,
2080
+ (statementToImport) => {
2081
+ addImport(statementToImport);
2082
+ const sourceFile = statementToImport.getSourceFile();
2083
+ const moduleInfo = getFileModuleInfo(sourceFile.fileName, criteria);
2084
+ if (moduleInfo.type === 2 /* ShouldBeReferencedAsTypes */) {
2085
+ addTypesReference(moduleInfo.typesLibraryName);
2086
+ }
2087
+ }
2088
+ );
2089
+ }
2090
+ function getDeclarationUsagesSourceFiles(declaration) {
2091
+ return new Set(
2092
+ getExportedSymbolsUsingStatement(declaration).map((symbol) => getDeclarationsForSymbol(symbol)).reduce(
2093
+ (acc, val) => acc.concat(val),
2094
+ []
2095
+ ).map(getClosestModuleLikeNode)
2096
+ );
2097
+ }
2098
+ function getImportItem(importModuleSpecifier) {
2099
+ let importItem = collectionResult.imports.get(importModuleSpecifier);
2100
+ if (importItem === void 0) {
2101
+ importItem = {
2102
+ defaultImports: /* @__PURE__ */ new Set(),
2103
+ namedImports: /* @__PURE__ */ new Map(),
2104
+ nsImport: null,
2105
+ requireImports: /* @__PURE__ */ new Set(),
2106
+ reExports: /* @__PURE__ */ new Map()
2107
+ };
2108
+ collectionResult.imports.set(importModuleSpecifier, importItem);
2109
+ }
2110
+ return importItem;
2111
+ }
2112
+ function addRequireImport(importItem, preferredLocalName) {
2113
+ importItem.requireImports.add(
2114
+ collisionsResolver.addTopLevelIdentifier(preferredLocalName)
2115
+ );
2116
+ }
2117
+ function addNamedImport(importItem, preferredLocalName, importedIdentifier) {
2118
+ const newLocalName = collisionsResolver.addTopLevelIdentifier(preferredLocalName);
2119
+ const importedName = importedIdentifier.text;
2120
+ importItem.namedImports.set(newLocalName, importedName);
2121
+ }
2122
+ function addReExport(importItem, moduleExportedName, reExportedName) {
2123
+ importItem.reExports.set(reExportedName, moduleExportedName);
2124
+ }
2125
+ function addNsImport(importItem, preferredLocalName) {
2126
+ if (importItem.nsImport === null) {
2127
+ importItem.nsImport = collisionsResolver.addTopLevelIdentifier(preferredLocalName);
2128
+ }
2129
+ }
2130
+ function addDefaultImport(importItem, preferredLocalName) {
2131
+ importItem.defaultImports.add(
2132
+ collisionsResolver.addTopLevelIdentifier(preferredLocalName)
2133
+ );
2134
+ }
2135
+ function addImport(statement) {
2136
+ forEachImportOfStatement(
2137
+ statement,
2138
+ (imp, referencedModuleInfo, importModuleSpecifier) => {
2139
+ if (referencedModuleInfo.type !== 1 /* ShouldBeImported */) {
2140
+ return;
2141
+ }
2142
+ const importItem = getImportItem(importModuleSpecifier);
2143
+ if (ts9.isImportEqualsDeclaration(imp)) {
2144
+ addRequireImport(importItem, imp.name);
2145
+ return;
2146
+ }
2147
+ if (ts9.isExportSpecifier(imp)) {
2148
+ addNamedImport(
2149
+ importItem,
2150
+ imp.name,
2151
+ imp.propertyName || imp.name
2152
+ );
2153
+ return;
2154
+ }
2155
+ if (ts9.isNamespaceExport(imp)) {
2156
+ addNsImport(importItem, imp.name);
2157
+ return;
2158
+ }
2159
+ if (ts9.isImportClause(imp) && imp.name !== void 0) {
2160
+ addDefaultImport(importItem, imp.name);
2161
+ return;
2162
+ }
2163
+ if (ts9.isImportSpecifier(imp)) {
2164
+ addNamedImport(
2165
+ importItem,
2166
+ imp.name,
2167
+ imp.propertyName || imp.name
2168
+ );
2169
+ return;
2170
+ }
2171
+ if (ts9.isNamespaceImport(imp)) {
2172
+ addNsImport(importItem, imp.name);
2173
+ return;
2174
+ }
2175
+ }
2176
+ );
2177
+ }
2178
+ function forEachImportOfStatement(statement, callback) {
2179
+ if (!ts9.isSourceFile(statement) && statement.name === void 0) {
2180
+ throw new Error(
2181
+ `Import/usage unnamed declaration: ${statement.getText()}`
2182
+ );
2183
+ }
2184
+ getDeclarationUsagesSourceFiles(statement).forEach(
2185
+ (sourceFile) => {
2186
+ if (getModuleLikeModuleInfo(sourceFile, criteria, typeChecker).type !== 0 /* ShouldBeInlined */) {
2187
+ return;
2188
+ }
2189
+ const sourceFileStatements = ts9.isSourceFile(
2190
+ sourceFile
2191
+ ) ? sourceFile.statements : sourceFile.body !== void 0 && ts9.isModuleBlock(sourceFile.body) ? sourceFile.body.statements : [];
2192
+ sourceFileStatements.forEach((st) => {
2193
+ if (!ts9.isImportEqualsDeclaration(st) && !ts9.isImportDeclaration(st) && !ts9.isExportDeclaration(st)) {
2194
+ return;
2195
+ }
2196
+ const importModuleSpecifier = getImportModuleName(st);
2197
+ if (importModuleSpecifier === null) {
2198
+ return;
2199
+ }
2200
+ const referencedModuleInfo = getReferencedModuleInfo(
2201
+ st,
2202
+ criteria,
2203
+ typeChecker
2204
+ );
2205
+ if (referencedModuleInfo === null) {
2206
+ return;
2207
+ }
2208
+ if (ts9.isImportEqualsDeclaration(st)) {
2209
+ if (areDeclarationSame(statement, st)) {
2210
+ callback(st, referencedModuleInfo, importModuleSpecifier);
2211
+ }
2212
+ return;
2213
+ }
2214
+ if (ts9.isExportDeclaration(st) && st.exportClause !== void 0) {
2215
+ if (ts9.isNamedExports(st.exportClause)) {
2216
+ st.exportClause.elements.filter(areDeclarationSame.bind(null, statement)).forEach((specifier) => {
2217
+ callback(
2218
+ specifier,
2219
+ referencedModuleInfo,
2220
+ importModuleSpecifier
2221
+ );
2222
+ });
2223
+ } else {
2224
+ if (isNodeUsed(st.exportClause)) {
2225
+ callback(
2226
+ st.exportClause,
2227
+ referencedModuleInfo,
2228
+ importModuleSpecifier
2229
+ );
2230
+ }
2231
+ }
2232
+ } else if (ts9.isImportDeclaration(st) && st.importClause !== void 0) {
2233
+ if (st.importClause.name !== void 0 && areDeclarationSame(statement, st.importClause)) {
2234
+ callback(
2235
+ st.importClause,
2236
+ referencedModuleInfo,
2237
+ importModuleSpecifier
2238
+ );
2239
+ }
2240
+ if (st.importClause.namedBindings !== void 0) {
2241
+ if (ts9.isNamedImports(st.importClause.namedBindings)) {
2242
+ st.importClause.namedBindings.elements.filter(areDeclarationSame.bind(null, statement)).forEach((specifier) => {
2243
+ callback(
2244
+ specifier,
2245
+ referencedModuleInfo,
2246
+ importModuleSpecifier
2247
+ );
2248
+ });
2249
+ } else {
2250
+ if (isNodeUsed(st.importClause)) {
2251
+ callback(
2252
+ st.importClause.namedBindings,
2253
+ referencedModuleInfo,
2254
+ importModuleSpecifier
2255
+ );
2256
+ }
2257
+ }
2258
+ }
2259
+ }
2260
+ });
2261
+ }
2262
+ );
2263
+ }
2264
+ function getInlinedSymbolsUsingSymbol(symbol, predicate) {
2265
+ return Array.from(
2266
+ typesUsageEvaluator.getSymbolsUsingSymbol(symbol) ?? []
2267
+ ).filter((usedInSymbol) => {
2268
+ if (!predicate(usedInSymbol)) {
2269
+ return false;
2270
+ }
2271
+ return getDeclarationsForSymbol(usedInSymbol).some(
2272
+ (decl) => {
2273
+ const closestModuleLike = getClosestSourceFileLikeNode(decl);
2274
+ const moduleInfo = getModuleLikeModuleInfo(
2275
+ closestModuleLike,
2276
+ criteria,
2277
+ typeChecker
2278
+ );
2279
+ return moduleInfo.type === 0 /* ShouldBeInlined */;
2280
+ }
2281
+ );
2282
+ });
2283
+ }
2284
+ function isSymbolUsedByInlinedSymbols(symbol, predicate, visitedSymbols = /* @__PURE__ */ new Set()) {
2285
+ if (visitedSymbols.has(symbol)) {
2286
+ return false;
2287
+ }
2288
+ visitedSymbols.add(symbol);
2289
+ return Array.from(
2290
+ typesUsageEvaluator.getSymbolsUsingSymbol(symbol) ?? []
2291
+ ).some((usedInSymbol) => {
2292
+ if (!predicate(usedInSymbol)) {
2293
+ return isSymbolUsedByInlinedSymbols(
2294
+ usedInSymbol,
2295
+ predicate,
2296
+ visitedSymbols
2297
+ );
2298
+ }
2299
+ const usedByThisSymbol = getDeclarationsForSymbol(usedInSymbol).some(
2300
+ (decl) => {
2301
+ const closestModuleLike = getClosestSourceFileLikeNode(decl);
2302
+ const moduleInfo = getModuleLikeModuleInfo(
2303
+ closestModuleLike,
2304
+ criteria,
2305
+ typeChecker
2306
+ );
2307
+ return moduleInfo.type === 0 /* ShouldBeInlined */;
2308
+ }
2309
+ );
2310
+ if (usedByThisSymbol) {
2311
+ return true;
2312
+ }
2313
+ return isSymbolUsedByInlinedSymbols(
2314
+ usedInSymbol,
2315
+ predicate,
2316
+ visitedSymbols
2317
+ );
2318
+ });
2319
+ }
2320
+ function isSymbolUsedByRootFileExports(symbol) {
2321
+ return rootFileExportSymbols.some(
2322
+ (rootSymbol) => typesUsageEvaluator.isSymbolUsedBySymbol(symbol, rootSymbol)
2323
+ );
2324
+ }
2325
+ function isSymbolForGlobalDeclaration(symbol) {
2326
+ return symbol.escapedName === ts9.InternalSymbolName.Global;
2327
+ }
2328
+ function isSymbolForDeclareModuleDeclaration(symbol) {
2329
+ return getDeclarationsForSymbol(symbol).some(isDeclareModule);
2330
+ }
2331
+ function isNodeUsed(node) {
2332
+ if (isNodeNamedDeclaration(node) || ts9.isSourceFile(node)) {
2333
+ const nodeSymbol = getNodeSymbol(node, typeChecker);
2334
+ if (nodeSymbol === null) {
2335
+ return false;
2336
+ }
2337
+ const nodeUsedByDirectExports = isSymbolUsedByRootFileExports(nodeSymbol);
2338
+ if (nodeUsedByDirectExports) {
2339
+ return true;
2340
+ }
2341
+ if (inlineDeclareGlobals && isSymbolUsedByInlinedSymbols(nodeSymbol, isSymbolForGlobalDeclaration)) {
2342
+ return true;
2343
+ }
2344
+ if (inlineDeclareExternals && isSymbolUsedByInlinedSymbols(
2345
+ nodeSymbol,
2346
+ isSymbolForDeclareModuleDeclaration
2347
+ )) {
2348
+ return true;
2349
+ }
2350
+ return false;
2351
+ }
2352
+ if (ts9.isVariableStatement(node)) {
2353
+ return node.declarationList.declarations.some(
2354
+ (declaration) => {
2355
+ if (ts9.isObjectBindingPattern(declaration.name) || ts9.isArrayBindingPattern(declaration.name)) {
2356
+ return declaration.name.elements.some(isNodeUsed);
2357
+ }
2358
+ return isNodeUsed(declaration);
2359
+ }
2360
+ );
2361
+ }
2362
+ if (ts9.isExportDeclaration(node) && node.exportClause !== void 0 && ts9.isNamespaceExport(node.exportClause)) {
2363
+ return isNodeUsed(node.exportClause);
2364
+ }
2365
+ if (ts9.isImportClause(node) && node.namedBindings !== void 0) {
2366
+ return isNodeUsed(node.namedBindings);
2367
+ }
2368
+ return false;
2369
+ }
2370
+ function shouldNodeBeImported(node) {
2371
+ const nodeSymbol = getNodeSymbol(node, typeChecker);
2372
+ if (nodeSymbol === null) {
2373
+ return false;
2374
+ }
2375
+ return shouldSymbolBeImported(nodeSymbol);
2376
+ }
2377
+ function shouldSymbolBeImported(nodeSymbol) {
2378
+ const isSymbolDeclaredInDefaultLibrary = getDeclarationsForSymbol(
2379
+ nodeSymbol
2380
+ ).some(
2381
+ (declaration) => program.isSourceFileDefaultLibrary(declaration.getSourceFile())
2382
+ );
2383
+ if (isSymbolDeclaredInDefaultLibrary) {
2384
+ return false;
2385
+ }
2386
+ const symbolsDeclarations = getDeclarationsForSymbol(nodeSymbol);
2387
+ const shouldSymbolBeInlined = symbolsDeclarations.every(
2388
+ (decl) => getModuleLikeModuleInfo(
2389
+ getClosestSourceFileLikeNode(decl),
2390
+ criteria,
2391
+ typeChecker
2392
+ ).type === 0 /* ShouldBeInlined */
2393
+ );
2394
+ if (shouldSymbolBeInlined) {
2395
+ return false;
2396
+ }
2397
+ return getExportedSymbolsUsingSymbol(nodeSymbol).length !== 0;
2398
+ }
2399
+ function getExportedSymbolsUsingStatement(node) {
2400
+ const nodeSymbol = getNodeSymbol(node, typeChecker);
2401
+ if (nodeSymbol === null) {
2402
+ return [];
2403
+ }
2404
+ return getExportedSymbolsUsingSymbol(nodeSymbol);
2405
+ }
2406
+ function getExportedSymbolsUsingSymbol(nodeSymbol) {
2407
+ const symbolsUsingNode = typesUsageEvaluator.getSymbolsUsingSymbol(nodeSymbol);
2408
+ if (symbolsUsingNode === null) {
2409
+ throw new Error(
2410
+ `Something went wrong - getSymbolsUsingSymbol returned null but expected to be a set of symbols (symbol=${nodeSymbol.name})`
2411
+ );
2412
+ }
2413
+ return [
2414
+ ...rootFileExportSymbols.includes(nodeSymbol) ? [nodeSymbol] : [],
2415
+ // symbols which are used in types directly
2416
+ ...getInlinedSymbolsUsingSymbol(
2417
+ nodeSymbol,
2418
+ isSymbolUsedByRootFileExports
2419
+ ),
2420
+ // symbols which are used in global types i.e. in `declare global`s
2421
+ ...inlineDeclareGlobals ? getInlinedSymbolsUsingSymbol(
2422
+ nodeSymbol,
2423
+ isSymbolForGlobalDeclaration
2424
+ ) : [],
2425
+ // symbols which are used in "declare module" types
2426
+ ...inlineDeclareExternals ? getInlinedSymbolsUsingSymbol(
2427
+ nodeSymbol,
2428
+ isSymbolForDeclareModuleDeclaration
2429
+ ) : []
2430
+ ];
2431
+ }
2432
+ function areDeclarationSame(left, right) {
2433
+ const leftSymbols = splitTransientSymbol(
2434
+ getNodeSymbol(left, typeChecker),
2435
+ typeChecker
2436
+ );
2437
+ const rightSymbols = splitTransientSymbol(
2438
+ getNodeSymbol(right, typeChecker),
2439
+ typeChecker
2440
+ );
2441
+ for (const leftSymbol of leftSymbols) {
2442
+ if (rightSymbols.has(leftSymbol)) {
2443
+ return true;
2444
+ }
2445
+ }
2446
+ return false;
2447
+ }
2448
+ function createNamespaceForExports(exports, namespaceSymbol) {
2449
+ function addSymbolToNamespaceExports(namespaceExports2, symbol) {
2450
+ if (!typesUsageEvaluator.isSymbolUsedBySymbol(symbol, namespaceSymbol)) {
2451
+ return;
2452
+ }
2453
+ const symbolKnownNames = collisionsResolver.namesForSymbol(symbol);
2454
+ if (symbolKnownNames.size === 0) {
2455
+ throw new Error(
2456
+ `Cannot get local names for symbol '${symbol.getName()}' while generating namespaced export`
2457
+ );
2458
+ }
2459
+ namespaceExports2.set(symbol.getName(), Array.from(symbolKnownNames)[0]);
2460
+ }
2461
+ function handleNamespacedImportOrExport(namespacedImportOrExport, namespaceExports2, symbol) {
2462
+ if (namespacedImportOrExport.moduleSpecifier === void 0) {
2463
+ return;
2464
+ }
2465
+ if (isReferencedModuleImportable(namespacedImportOrExport)) {
2466
+ addSymbolToNamespaceExports(namespaceExports2, symbol);
2467
+ return;
2468
+ }
2469
+ const referencedSourceFileSymbol = getNodeOwnSymbol(
2470
+ namespacedImportOrExport.moduleSpecifier,
2471
+ typeChecker
2472
+ );
2473
+ if (referencedSourceFileSymbol.exports === void 0) {
2474
+ return;
2475
+ }
2476
+ if (ts9.isImportDeclaration(namespacedImportOrExport) && referencedSourceFileSymbol.exports.has(
2477
+ ts9.InternalSymbolName.ExportEquals
2478
+ )) {
2479
+ return;
2480
+ }
2481
+ const localNamespaceName = createNamespaceForExports(
2482
+ referencedSourceFileSymbol.exports,
2483
+ symbol
2484
+ );
2485
+ if (localNamespaceName !== null) {
2486
+ namespaceExports2.set(symbol.getName(), localNamespaceName);
2487
+ }
2488
+ }
2489
+ function processExportSymbol(namespaceExports2, symbol) {
2490
+ if (symbol.escapedName === ts9.InternalSymbolName.ExportStar) {
2491
+ for (const exportStarDeclaration of getSymbolExportStarDeclarations(
2492
+ symbol
2493
+ )) {
2494
+ if (exportStarDeclaration.moduleSpecifier === void 0) {
2495
+ throw new Error(
2496
+ `Export star declaration does not have a module specifier '${exportStarDeclaration.getText()}'`
2497
+ );
2498
+ }
2499
+ if (isReferencedModuleImportable(exportStarDeclaration)) {
2500
+ throw new Error(
2501
+ `Having a re-export from an importable module as a part of namespaced export is not supported yet.`
2502
+ );
2503
+ }
2504
+ const referencedSourceFileSymbol = getNodeOwnSymbol(
2505
+ exportStarDeclaration.moduleSpecifier,
2506
+ typeChecker
2507
+ );
2508
+ referencedSourceFileSymbol.exports?.forEach(
2509
+ processExportSymbol.bind(null, namespaceExports2)
2510
+ );
2511
+ }
2512
+ return;
2513
+ }
2514
+ symbol.declarations?.forEach((decl) => {
2515
+ if (ts9.isNamespaceExport(decl) && decl.parent.moduleSpecifier !== void 0) {
2516
+ handleNamespacedImportOrExport(
2517
+ decl.parent,
2518
+ namespaceExports2,
2519
+ symbol
2520
+ );
2521
+ return;
2522
+ }
2523
+ if (ts9.isExportSpecifier(decl)) {
2524
+ const exportElementSymbol = getImportExportReferencedSymbol(
2525
+ decl,
2526
+ typeChecker
2527
+ );
2528
+ const namespaceImport = getDeclarationsForSymbol(
2529
+ exportElementSymbol
2530
+ ).find(ts9.isNamespaceImport);
2531
+ if (namespaceImport !== void 0) {
2532
+ handleNamespacedImportOrExport(
2533
+ namespaceImport.parent.parent,
2534
+ namespaceExports2,
2535
+ symbol
2536
+ );
2537
+ }
2538
+ return;
2539
+ }
2540
+ });
2541
+ addSymbolToNamespaceExports(namespaceExports2, symbol);
2542
+ }
2543
+ function getIdentifierOfNamespaceImportFromInlinedModule(nsSymbol) {
2544
+ for (const decl of getDeclarationsForSymbol(nsSymbol)) {
2545
+ if (!ts9.isNamespaceExport(decl) && !ts9.isExportSpecifier(decl) && !ts9.isNamespaceImport(decl)) {
2546
+ continue;
2547
+ }
2548
+ if (ts9.isNamespaceExport(decl) && !isReferencedModuleImportable(decl.parent)) {
2549
+ return decl.name;
2550
+ }
2551
+ if (ts9.isNamespaceImport(decl) && !isReferencedModuleImportable(
2552
+ decl.parent.parent
2553
+ )) {
2554
+ return decl.name;
2555
+ }
2556
+ if (ts9.isExportSpecifier(decl)) {
2557
+ if (decl.parent.parent.moduleSpecifier !== void 0) {
2558
+ if (isReferencedModuleImportable(decl.parent.parent)) {
2559
+ continue;
2560
+ }
2561
+ if (getIdentifierOfNamespaceImportFromInlinedModule(
2562
+ getImportExportReferencedSymbol(decl, typeChecker)
2563
+ )) {
2564
+ return decl.name;
2565
+ }
2566
+ }
2567
+ const result = getDeclarationsForSymbol(
2568
+ getImportExportReferencedSymbol(decl, typeChecker)
2569
+ ).some((importDecl) => {
2570
+ if (ts9.isNamespaceImport(importDecl)) {
2571
+ return !isReferencedModuleImportable(
2572
+ importDecl.parent.parent
2573
+ );
2574
+ }
2575
+ if (ts9.isImportSpecifier(importDecl)) {
2576
+ return getIdentifierOfNamespaceImportFromInlinedModule(
2577
+ getImportExportReferencedSymbol(importDecl, typeChecker)
2578
+ );
2579
+ }
2580
+ return false;
2581
+ });
2582
+ if (result) {
2583
+ return decl.name;
2584
+ }
2585
+ }
2586
+ }
2587
+ return null;
2588
+ }
2589
+ const namespaceNameIdentifier = getIdentifierOfNamespaceImportFromInlinedModule(namespaceSymbol);
2590
+ if (namespaceNameIdentifier === null) {
2591
+ return null;
2592
+ }
2593
+ const namespaceExports = /* @__PURE__ */ new Map();
2594
+ exports.forEach(processExportSymbol.bind(null, namespaceExports));
2595
+ if (namespaceExports.size !== 0) {
2596
+ const namespaceLocalName = collisionsResolver.addTopLevelIdentifier(
2597
+ namespaceNameIdentifier
2598
+ );
2599
+ collectionResult.wrappedNamespaces.set(
2600
+ namespaceLocalName,
2601
+ namespaceExports
2602
+ );
2603
+ return namespaceLocalName;
2604
+ }
2605
+ return null;
2606
+ }
2607
+ function syncExports() {
2608
+ for (const exp of rootFileExports) {
2609
+ if (exp.type === 0 /* CommonJS */) {
2610
+ continue;
2611
+ }
2612
+ const namespaceLocalName = exp.symbol.flags & ts9.SymbolFlags.ValueModule && exp.symbol.exports !== void 0 ? createNamespaceForExports(exp.symbol.exports, exp.originalSymbol) : null;
2613
+ if (namespaceLocalName !== null) {
2614
+ collectionResult.renamedExports.set(
2615
+ exp.exportedName,
2616
+ namespaceLocalName
2617
+ );
2618
+ }
2619
+ const symbolKnownNames = collisionsResolver.namesForSymbol(exp.symbol);
2620
+ if (symbolKnownNames.size === 0) {
2621
+ continue;
2622
+ }
2623
+ if (symbolKnownNames.has(exp.exportedName)) {
2624
+ if (shouldSymbolBeImported(exp.symbol)) {
2625
+ collectionResult.renamedExports.set(
2626
+ exp.exportedName,
2627
+ exp.exportedName
2628
+ );
2629
+ }
2630
+ continue;
2631
+ }
2632
+ collectionResult.renamedExports.set(
2633
+ exp.exportedName,
2634
+ Array.from(symbolKnownNames)[0]
2635
+ );
2636
+ }
2637
+ }
2638
+ for (const sourceFile of sourceFiles) {
2639
+ verboseLog(`======= Processing ${sourceFile.fileName} =======`);
2640
+ const updateFn = sourceFile === rootSourceFile ? updateResultForRootModule : updateResultForAnyModule;
2641
+ const currentModule = getFileModuleInfo(sourceFile.fileName, criteria);
2642
+ updateFn(sourceFile.statements, currentModule);
2643
+ if (isNodeUsed(sourceFile)) {
2644
+ switch (currentModule.type) {
2645
+ case 1 /* ShouldBeImported */: {
2646
+ updateImportsForStatement(sourceFile);
2647
+ break;
2648
+ }
2649
+ case 0 /* ShouldBeInlined */: {
2650
+ const sourceFileSymbol = getNodeSymbol(sourceFile, typeChecker);
2651
+ if (sourceFileSymbol === null || sourceFileSymbol.exports === void 0) {
2652
+ throw new Error(
2653
+ `Cannot find symbol or exports for source file ${sourceFile.fileName}`
2654
+ );
2655
+ }
2656
+ let namespaceIdentifier = null;
2657
+ forEachImportOfStatement(sourceFile, (imp) => {
2658
+ if (ts9.isNamespaceExport(imp) || ts9.isNamespaceImport(imp)) {
2659
+ namespaceIdentifier = imp.name;
2660
+ }
2661
+ });
2662
+ if (namespaceIdentifier === null) {
2663
+ break;
2664
+ }
2665
+ createNamespaceForExports(
2666
+ sourceFileSymbol.exports,
2667
+ getNodeOwnSymbol(namespaceIdentifier, typeChecker)
2668
+ );
2669
+ break;
2670
+ }
2671
+ }
2672
+ }
2673
+ }
2674
+ if (entryConfig.failOnClass) {
2675
+ const classes = collectionResult.statements.filter(ts9.isClassDeclaration);
2676
+ if (classes.length !== 0) {
2677
+ const classesNames = classes.map(
2678
+ (c) => c.name === void 0 ? "anonymous class" : c.name.text
2679
+ );
2680
+ throw new Error(
2681
+ `${classes.length} class statement(s) are found in generated dts: ${classesNames.join(", ")}`
2682
+ );
2683
+ }
2684
+ }
2685
+ syncExports();
2686
+ const exportReferencedTypes = outputOptions.exportReferencedTypes !== false;
2687
+ function isExportedWithLocalName(namedDeclaration, exportedName) {
2688
+ const nodeName = getNodeName(namedDeclaration);
2689
+ if (nodeName === void 0) {
2690
+ throw new Error(`Cannot find node name ${namedDeclaration.getText()}`);
2691
+ }
2692
+ return collisionsResolver.resolveReferencedIdentifier(
2693
+ nodeName
2694
+ ) === exportedName;
2695
+ }
2696
+ const renamedAndNotExplicitlyExportedTypes = [];
2697
+ const output = generateOutput(
2698
+ {
2699
+ ...collectionResult,
2700
+ resolveIdentifierName: (identifier) => {
2701
+ if (ts9.isPropertyAccessOrQualifiedName(identifier)) {
2702
+ return collisionsResolver.resolveReferencedQualifiedName(
2703
+ identifier
2704
+ );
2705
+ } else {
2706
+ return collisionsResolver.resolveReferencedIdentifier(identifier);
2707
+ }
2708
+ },
2709
+ // eslint-disable-next-line complexity
2710
+ getStatementSettings: (statement) => {
2711
+ if (isAmbientModule(statement) || ts9.isExportDeclaration(statement)) {
2712
+ return { shouldHaveExportKeyword: false, shouldHaveJSDoc: true };
2713
+ }
2714
+ const statementExports = getExportsForStatement(
2715
+ rootFileExports,
2716
+ typeChecker,
2717
+ statement
2718
+ );
2719
+ const isExplicitlyExportedWithOriginalName = statementExports.find((exp) => {
2720
+ if (ts9.isVariableStatement(statement)) {
2721
+ for (const variableDeclaration of statement.declarationList.declarations) {
2722
+ if (ts9.isIdentifier(variableDeclaration.name)) {
2723
+ const resolvedName = collisionsResolver.resolveReferencedIdentifier(
2724
+ variableDeclaration.name
2725
+ );
2726
+ if (exp.exportedName === resolvedName) {
2727
+ return true;
2728
+ }
2729
+ continue;
2730
+ }
2731
+ warnLog(
2732
+ `Unhandled variable identifier type detected (${ts9.SyntaxKind[variableDeclaration.name.kind]}). Please report this issue to https://github.com/timocov/dts-bundle-generator`
2733
+ );
2734
+ }
2735
+ return false;
2736
+ }
2737
+ return isNodeNamedDeclaration(statement) && isExportedWithLocalName(statement, exp.exportedName);
2738
+ }) !== void 0;
2739
+ const onlyExplicitlyExportedShouldBeExported = !exportReferencedTypes || ts9.isClassDeclaration(statement) || ts9.isEnumDeclaration(statement) && !hasNodeModifier(statement, ts9.SyntaxKind.ConstKeyword) || ts9.isFunctionDeclaration(statement) || ts9.isVariableStatement(statement) || ts9.isModuleDeclaration(statement);
2740
+ if (onlyExplicitlyExportedShouldBeExported) {
2741
+ return {
2742
+ shouldHaveExportKeyword: isExplicitlyExportedWithOriginalName,
2743
+ shouldHaveJSDoc: statementExports.length !== 0
2744
+ };
2745
+ }
2746
+ if (isNodeNamedDeclaration(statement) && !isExportedWithLocalName(
2747
+ statement,
2748
+ getNodeName(statement).getText()
2749
+ )) {
2750
+ renamedAndNotExplicitlyExportedTypes.push(statement);
2751
+ return {
2752
+ shouldHaveExportKeyword: false,
2753
+ shouldHaveJSDoc: statementExports.length !== 0
2754
+ };
2755
+ }
2756
+ return {
2757
+ shouldHaveExportKeyword: isExplicitlyExportedWithOriginalName || statementExports.length === 0,
2758
+ shouldHaveJSDoc: true
2759
+ };
2760
+ },
2761
+ needStripConstFromConstEnum: (constEnum) => {
2762
+ if (!program.getCompilerOptions().preserveConstEnums || !outputOptions.respectPreserveConstEnum) {
2763
+ return false;
2764
+ }
2765
+ const enumSymbol = getNodeSymbol(constEnum, typeChecker);
2766
+ if (enumSymbol === null) {
2767
+ return false;
2768
+ }
2769
+ return rootFileExportSymbols.includes(enumSymbol);
2770
+ },
2771
+ needStripImportFromImportTypeNode: (node) => {
2772
+ if (node.qualifier === void 0) {
2773
+ return false;
2774
+ }
2775
+ if (!ts9.isLiteralTypeNode(node.argument) || !ts9.isStringLiteral(node.argument.literal)) {
2776
+ return false;
2777
+ }
2778
+ return getReferencedModuleInfo(node, criteria, typeChecker)?.type === 0 /* ShouldBeInlined */;
2779
+ }
2780
+ },
2781
+ {
2782
+ sortStatements: outputOptions.sortNodes,
2783
+ umdModuleName: outputOptions.umdModuleName,
2784
+ noBanner: outputOptions.noBanner
2785
+ }
2786
+ );
2787
+ if (renamedAndNotExplicitlyExportedTypes.length !== 0) {
2788
+ warnLog(
2789
+ `The following type nodes were renamed because of the name collisions and will not be exported from the generated bundle:
2790
+ - ${// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2791
+ renamedAndNotExplicitlyExportedTypes.map(
2792
+ (node) => `${getNodeName(node).getText()} (from ${node.getSourceFile().fileName})`
2793
+ ).join("\n- ")}${"\n"}This might lead to unpredictable and unexpected output, and possible breaking changes to your API.${"\n"}Consider either (re-)exporting them explicitly from the entry point, or disable --export-referenced-types option ('output.exportReferencedTypes' in the config).`
2794
+ );
2795
+ }
2796
+ return output;
2797
+ });
2798
+ }
2799
+ export {
2800
+ generateDtsBundle
2801
+ };