/
cache-compiler-host.ts
240 lines (199 loc) · 7.76 KB
/
cache-compiler-host.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import type { CompilerHost, CompilerOptions } from '@angular/compiler-cli';
import convertSourceMap from 'convert-source-map';
import { createHash } from 'crypto';
import assert from 'node:assert';
import * as path from 'path';
import ts from 'typescript';
import { NgPackageConfig } from '../../ng-package.schema';
import { FileCache } from '../file-system/file-cache';
import { BuildGraph } from '../graph/build-graph';
import { Node } from '../graph/node';
import { EntryPointNode, fileUrl } from '../ng-package/nodes';
import { StylesheetProcessor } from '../styles/stylesheet-processor';
import { ensureUnixPath } from '../utils/path';
export function cacheCompilerHost(
graph: BuildGraph,
entryPoint: EntryPointNode,
compilerOptions: CompilerOptions,
moduleResolutionCache: ts.ModuleResolutionCache,
emittedFiles?: Set<string>,
stylesheetProcessor?: StylesheetProcessor,
inlineStyleLanguage?: NgPackageConfig['inlineStyleLanguage'],
sourcesFileCache: FileCache = entryPoint.cache.sourcesFileCache,
): CompilerHost {
const compilerHost = ts.createIncrementalCompilerHost(compilerOptions);
const getNode = (fileName: string) => {
const nodeUri = fileUrl(ensureUnixPath(fileName));
let node = graph.get(nodeUri);
if (!node) {
node = new Node(nodeUri);
graph.put(node);
}
return node;
};
const addDependee = (fileName: string) => {
const node = getNode(fileName);
entryPoint.dependsOn(node);
};
const { flatModuleFile, destinationPath, entryFile } = entryPoint.data.entryPoint;
const flatModuleFileDtsFilename = `${flatModuleFile}.d.ts`;
const flatModuleFileDtsPath = ensureUnixPath(path.join(destinationPath, flatModuleFileDtsFilename));
const hasIndexEntryFile = path.basename(entryFile.toLowerCase()) === 'index.ts';
return {
...compilerHost,
// ts specific
fileExists: (fileName: string) => {
const cache = sourcesFileCache.getOrCreate(fileName);
if (cache.exists === undefined) {
cache.exists = compilerHost.fileExists.call(this, fileName);
}
return cache.exists;
},
getSourceFile: (fileName: string, languageVersion: ts.ScriptTarget) => {
addDependee(fileName);
const cache = sourcesFileCache.getOrCreate(fileName);
if (!cache.sourceFile) {
cache.sourceFile = compilerHost.getSourceFile.call(this, fileName, languageVersion);
}
return cache.sourceFile;
},
writeFile: (
fileName: string,
data: string,
writeByteOrderMark: boolean,
onError?: (message: string) => void,
sourceFiles?: ReadonlyArray<ts.SourceFile>,
) => {
if (fileName.includes('.ngtypecheck.')) {
return;
}
if (!sourceFiles?.length && fileName.endsWith('.tsbuildinfo')) {
// Save builder info contents to specified location
compilerHost.writeFile.call(this, fileName, data, writeByteOrderMark, onError, sourceFiles);
return;
}
assert(sourceFiles?.length === 1, 'Invalid TypeScript program emit for ' + fileName);
if (fileName.endsWith('.d.ts')) {
if (fileName === flatModuleFileDtsPath) {
if (hasIndexEntryFile) {
// In case the entry file is index.ts, we should not emit the `d.ts` which are a re-export of the `index.ts`.
// Because it will cause a conflict.
return;
} else {
// Rename file to index.d.ts so that TypeScript can resolve types without
// them needing to be referenced in the package.json manifest.
fileName = fileName.replace(flatModuleFileDtsFilename, 'index.d.ts');
}
}
sourceFiles.forEach(source => {
emittedFiles?.add(source.fileName);
const cache = sourcesFileCache.getOrCreate(source.fileName);
if (!cache.declarationFileName) {
cache.declarationFileName = ensureUnixPath(fileName);
}
});
} else {
fileName = fileName.replace(/\.js(\.map)?$/, '.mjs$1');
const outputCache = entryPoint.cache.outputCache;
// Extract inline sourcemap which will later be used by rolluo.
const version = createHash('sha256').update(data).digest('hex');
let map = undefined;
if (fileName.endsWith('.mjs')) {
const cachedData = outputCache.get(fileName);
map = cachedData?.version === version ? cachedData.map : convertSourceMap.fromComment(data).toJSON();
}
outputCache.set(fileName, {
content: data,
version,
map,
});
sourceFiles.forEach(source => {
emittedFiles?.add(source.fileName);
});
}
compilerHost.writeFile.call(this, fileName, data, writeByteOrderMark, onError, sourceFiles);
},
readFile: (fileName: string) => {
addDependee(fileName);
const cache = sourcesFileCache.getOrCreate(fileName);
if (cache.content === undefined) {
cache.content = compilerHost.readFile.call(this, fileName);
}
return cache.content;
},
resolveModuleNames: (moduleNames: string[], containingFile: string) => {
return moduleNames.map(moduleName => {
const { resolvedModule } = ts.resolveModuleName(
moduleName,
ensureUnixPath(containingFile),
compilerOptions,
compilerHost,
moduleResolutionCache,
);
return resolvedModule;
});
},
resourceNameToFileName: (resourceName: string, containingFilePath: string) => {
const resourcePath = path.resolve(path.dirname(containingFilePath), resourceName);
const containingNode = getNode(containingFilePath);
const resourceNode = getNode(resourcePath);
containingNode.dependsOn(resourceNode);
return resourcePath;
},
readResource: async (fileName: string) => {
addDependee(fileName);
const cache = sourcesFileCache.getOrCreate(fileName);
if (cache.content === undefined) {
if (!compilerHost.fileExists(fileName)) {
throw new Error(`Cannot read file ${fileName}.`);
}
if (/(?:html?|svg)$/.test(path.extname(fileName))) {
// template
cache.content = compilerHost.readFile.call(this, fileName);
} else {
// stylesheet
cache.content = await stylesheetProcessor.process({
filePath: fileName,
content: compilerHost.readFile.call(this, fileName),
});
}
cache.exists = true;
}
return cache.content;
},
transformResource: async (data, context) => {
if (context.resourceFile || context.type !== 'style') {
return null;
}
if (inlineStyleLanguage) {
const key = createHash('sha1').update(data).digest('hex');
const fileName = `${context.containingFile}-${key}.${inlineStyleLanguage}`;
const cache = sourcesFileCache.getOrCreate(fileName);
if (cache.content === undefined) {
cache.content = await stylesheetProcessor.process({
filePath: fileName,
content: data,
});
const virtualFileNode = getNode(fileName);
const containingFileNode = getNode(context.containingFile);
virtualFileNode.dependsOn(containingFileNode);
}
cache.exists = true;
return { content: cache.content };
}
return null;
},
};
}
export function augmentProgramWithVersioning(program: ts.Program): void {
const baseGetSourceFiles = program.getSourceFiles;
program.getSourceFiles = function (...parameters) {
const files: readonly (ts.SourceFile & { version?: string })[] = baseGetSourceFiles(...parameters);
for (const file of files) {
if (file.version === undefined) {
file.version = createHash('sha256').update(file.text).digest('hex');
}
}
return files;
};
}