/
compile-dts.ts
143 lines (114 loc) · 5.58 KB
/
compile-dts.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import * as path from 'path';
import * as ts from 'typescript';
import { verboseLog, warnLog } from './logger';
import { getCompilerOptions } from './get-compiler-options';
import { getAbsolutePath } from './helpers/get-absolute-path';
import { checkProgramDiagnosticsErrors, checkDiagnosticsErrors } from './helpers/check-diagnostics-errors';
export interface CompileDtsResult {
program: ts.Program;
rootFilesRemapping: Map<string, string>;
}
export function compileDts(rootFiles: readonly string[], preferredConfigPath?: string, followSymlinks: boolean = true): CompileDtsResult {
const compilerOptions = getCompilerOptions(rootFiles, preferredConfigPath);
// currently we don't support these compiler options
// and removing them shouldn't affect generated code
// so let's just remove them for this run
compilerOptions.outDir = undefined;
compilerOptions.incremental = undefined;
compilerOptions.tsBuildInfoFile = undefined;
compilerOptions.declarationDir = undefined;
if (compilerOptions.composite) {
warnLog(`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`);
compilerOptions.composite = undefined;
}
const dtsFiles = getDeclarationFiles(rootFiles, compilerOptions);
verboseLog(`dts cache:\n ${Object.keys(dtsFiles).join('\n ')}\n`);
const host = ts.createCompilerHost(compilerOptions);
if (!followSymlinks) {
host.realpath = (p: string) => p;
}
host.resolveModuleNames = (moduleNames: string[], containingFile: string) => {
return moduleNames.map((moduleName: string) => {
const resolvedModule = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host).resolvedModule;
if (resolvedModule && !resolvedModule.isExternalLibraryImport && resolvedModule.extension !== ts.Extension.Dts) {
resolvedModule.extension = ts.Extension.Dts;
verboseLog(`Change module from .ts to .d.ts: ${resolvedModule.resolvedFileName}`);
resolvedModule.resolvedFileName = changeExtensionToDts(resolvedModule.resolvedFileName);
}
return resolvedModule as ts.ResolvedModule;
});
};
const originalGetSourceFile = host.getSourceFile;
host.getSourceFile = (fileName: string, languageVersion: ts.ScriptTarget, onError?: (message: string) => void) => {
const absolutePath = getAbsolutePath(fileName);
const storedValue = dtsFiles.get(absolutePath);
if (storedValue !== undefined) {
verboseLog(`dts cache match: ${absolutePath}`);
return ts.createSourceFile(fileName, storedValue, languageVersion);
}
verboseLog(`dts cache mismatch: ${absolutePath} (${fileName})`);
return originalGetSourceFile(fileName, languageVersion, onError);
};
const rootFilesRemapping = new Map<string, string>();
const inputFiles = rootFiles.map((rootFile: string) => {
const rootDtsFile = changeExtensionToDts(rootFile);
rootFilesRemapping.set(rootFile, rootDtsFile);
return rootDtsFile;
});
const program = ts.createProgram(inputFiles, compilerOptions, host);
checkProgramDiagnosticsErrors(program);
warnAboutTypeScriptFilesInProgram(program);
return { program, rootFilesRemapping };
}
function changeExtensionToDts(fileName: string): string {
if (fileName.slice(-5) === '.d.ts') {
return fileName;
}
// .ts, .tsx
const ext = path.extname(fileName);
return fileName.slice(0, -ext.length) + '.d.ts';
}
/**
* @description Compiles source files into d.ts files and returns map of absolute path to file content
*/
function getDeclarationFiles(rootFiles: readonly string[], compilerOptions: ts.CompilerOptions): Map<string, string> {
// we must pass `declaration: true` and `noEmit: false` if we want to generate declaration files
// see https://github.com/microsoft/TypeScript/issues/24002#issuecomment-550549393
// also, we don't want to generate anything apart from declarations so that's why `emitDeclarationOnly: true` is here
// it allows to run the tool for projects with allowJs flag enabled to avoid errors like:
// error TS5055: Cannot write file '<filename>' because it would overwrite input file.
compilerOptions = {
...compilerOptions,
noEmit: false,
declaration: true,
emitDeclarationOnly: true,
};
const program = ts.createProgram(rootFiles, compilerOptions);
const allFilesAreDeclarations = program.getSourceFiles().every((s: ts.SourceFile) => s.isDeclarationFile);
const declarations = new Map<string, string>();
if (allFilesAreDeclarations) {
// if all files are declarations we don't need to compile the project twice
// so let's just return empty map to speed up
verboseLog('Skipping compiling the project to generate d.ts because all files in it are d.ts already');
return declarations;
}
checkProgramDiagnosticsErrors(program);
const emitResult = program.emit(
undefined,
(fileName: string, data: string) => declarations.set(getAbsolutePath(fileName), data),
undefined,
true
);
checkDiagnosticsErrors(emitResult.diagnostics, 'Errors while emitting declarations');
return declarations;
}
function warnAboutTypeScriptFilesInProgram(program: ts.Program): void {
const nonDeclarationFiles = program.getSourceFiles().filter((file: ts.SourceFile) => !file.isDeclarationFile);
if (nonDeclarationFiles.length !== 0) {
warnLog(`WARNING: It seems that some files in the compilation still are not declaration files.
For more information see https://github.com/timocov/dts-bundle-generator/issues/53.
If you think this is a mistake, feel free to open new issue or just ignore this warning.
${nonDeclarationFiles.map((file: ts.SourceFile) => file.fileName).join('\n ')}
`);
}
}