forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathangular-host.ts
More file actions
289 lines (248 loc) · 8.81 KB
/
angular-host.ts
File metadata and controls
289 lines (248 loc) · 8.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type * as ng from '@angular/compiler-cli';
import assert from 'node:assert';
import { createHash } from 'node:crypto';
import nodePath from 'node:path';
import type ts from 'typescript';
export type AngularCompilerOptions = ng.CompilerOptions;
export type AngularCompilerHost = ng.CompilerHost;
export interface AngularHostOptions {
fileReplacements?: Record<string, string>;
sourceFileCache?: Map<string, ts.SourceFile>;
modifiedFiles?: Set<string>;
externalStylesheets?: Map<string, string>;
transformStylesheet(
data: string,
containingFile: string,
stylesheetFile?: string,
order?: number,
className?: string,
): Promise<string | null>;
processWebWorker(workerFile: string, containingFile: string): string;
}
/**
* Patches in-place the `getSourceFiles` function on an instance of a TypeScript
* `Program` to ensure that all returned SourceFile instances have a `version`
* field. The `version` field is required when used with a TypeScript BuilderProgram.
* @param program The TypeScript Program instance to patch.
*/
export function ensureSourceFileVersions(program: ts.Program): void {
const baseGetSourceFiles = program.getSourceFiles;
// TODO: Update Angular compiler to add versions to all internal files and remove this
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;
};
}
function augmentHostWithCaching(host: ts.CompilerHost, cache: Map<string, ts.SourceFile>): void {
const baseGetSourceFile = host.getSourceFile;
host.getSourceFile = function (
fileName,
languageVersion,
onError,
shouldCreateNewSourceFile,
...parameters
) {
if (!shouldCreateNewSourceFile && cache.has(fileName)) {
return cache.get(fileName);
}
const file = baseGetSourceFile.call(
host,
fileName,
languageVersion,
onError,
true,
...parameters,
);
if (file) {
cache.set(fileName, file);
}
return file;
};
}
function augmentResolveModuleNames(
typescript: typeof ts,
host: ts.CompilerHost,
resolvedModuleModifier: (
resolvedModule: ts.ResolvedModule | undefined,
moduleName: string,
) => ts.ResolvedModule | undefined,
moduleResolutionCache?: ts.ModuleResolutionCache,
): void {
if (host.resolveModuleNames) {
const baseResolveModuleNames = host.resolveModuleNames;
host.resolveModuleNames = function (moduleNames: string[], ...parameters) {
return moduleNames.map((name) => {
const result = baseResolveModuleNames.call(host, [name], ...parameters);
return resolvedModuleModifier(result[0], name);
});
};
} else {
host.resolveModuleNames = function (
moduleNames: string[],
containingFile: string,
_reusedNames: string[] | undefined,
redirectedReference: ts.ResolvedProjectReference | undefined,
options: ts.CompilerOptions,
) {
return moduleNames.map((name) => {
const result = typescript.resolveModuleName(
name,
containingFile,
options,
host,
moduleResolutionCache,
redirectedReference,
).resolvedModule;
return resolvedModuleModifier(result, name);
});
};
}
}
function normalizePath(path: string): string {
return nodePath.win32.normalize(path).replace(/\\/g, nodePath.posix.sep);
}
function augmentHostWithReplacements(
typescript: typeof ts,
host: ts.CompilerHost,
replacements: Record<string, string>,
moduleResolutionCache?: ts.ModuleResolutionCache,
): void {
if (Object.keys(replacements).length === 0) {
return;
}
const normalizedReplacements: Record<string, string> = {};
for (const [key, value] of Object.entries(replacements)) {
normalizedReplacements[normalizePath(key)] = normalizePath(value);
}
const tryReplace = (resolvedModule: ts.ResolvedModule | undefined) => {
const replacement = resolvedModule && normalizedReplacements[resolvedModule.resolvedFileName];
if (replacement) {
return {
resolvedFileName: replacement,
isExternalLibraryImport: /[/\\]node_modules[/\\]/.test(replacement),
};
} else {
return resolvedModule;
}
};
augmentResolveModuleNames(typescript, host, tryReplace, moduleResolutionCache);
}
export function createAngularCompilerHost(
typescript: typeof ts,
compilerOptions: AngularCompilerOptions,
hostOptions: AngularHostOptions,
packageJsonCache: ts.PackageJsonInfoCache | undefined,
): AngularCompilerHost {
// Create TypeScript compiler host
const host: AngularCompilerHost = typescript.createIncrementalCompilerHost(compilerOptions);
// Set the parsing mode to the same as TS 5.3+ default for tsc. This provides a parse
// performance improvement by skipping non-type related JSDoc parsing.
host.jsDocParsingMode = typescript.JSDocParsingMode.ParseForTypeErrors;
// The AOT compiler currently requires this hook to allow for a transformResource hook.
// Once the AOT compiler allows only a transformResource hook, this can be reevaluated.
host.readResource = async function (filename) {
return this.readFile(filename) ?? '';
};
// Add an AOT compiler resource transform hook
host.transformResource = async function (data, context) {
// Only style resources are transformed currently
if (context.type !== 'style') {
return null;
}
assert(
!context.resourceFile || !hostOptions.externalStylesheets?.has(context.resourceFile),
'External runtime stylesheets should not be transformed: ' + context.resourceFile,
);
// No transformation required if the resource is empty
if (data.trim().length === 0) {
return { content: '' };
}
const result = await hostOptions.transformStylesheet(
data,
context.containingFile,
context.resourceFile ?? undefined,
context.order,
context.className,
);
return typeof result === 'string' ? { content: result } : null;
};
host.resourceNameToFileName = function (resourceName, containingFile) {
const resolvedPath = nodePath.join(nodePath.dirname(containingFile), resourceName);
if (!this.fileExists(resolvedPath)) {
return null;
}
// Reject TypeScript files used as component resources (e.g., styleUrl pointing to a .ts file).
// Processing a TypeScript file as a stylesheet or template causes confusing downstream errors.
if (hasTypeScriptExtension(resolvedPath)) {
return null;
}
// All resource names that have template file extensions are assumed to be templates
// TODO: Update compiler to provide the resource type to avoid extension matching here.
if (!hostOptions.externalStylesheets || hasTemplateExtension(resolvedPath)) {
return resolvedPath;
}
// For external stylesheets, create a unique identifier and store the mapping
let externalId = hostOptions.externalStylesheets.get(resolvedPath);
if (externalId === undefined) {
externalId = createHash('sha256').update(resolvedPath).digest('hex');
hostOptions.externalStylesheets.set(resolvedPath, externalId);
}
return externalId + '.css';
};
// Allow the AOT compiler to request the set of changed templates and styles
host.getModifiedResourceFiles = function () {
return hostOptions.modifiedFiles;
};
// Provide a resolution cache to ensure package.json lookups are cached
const resolutionCache = typescript.createModuleResolutionCache(
host.getCurrentDirectory(),
host.getCanonicalFileName.bind(host),
compilerOptions,
packageJsonCache,
);
host.getModuleResolutionCache = () => resolutionCache;
// Augment TypeScript Host for file replacements option
if (hostOptions.fileReplacements) {
augmentHostWithReplacements(typescript, host, hostOptions.fileReplacements, resolutionCache);
}
// Augment TypeScript Host with source file caching if provided
if (hostOptions.sourceFileCache) {
augmentHostWithCaching(host, hostOptions.sourceFileCache);
}
return host;
}
function hasTemplateExtension(file: string): boolean {
const extension = nodePath.extname(file).toLowerCase();
switch (extension) {
case '.htm':
case '.html':
case '.svg':
return true;
}
return false;
}
function hasTypeScriptExtension(file: string): boolean {
const extension = nodePath.extname(file).toLowerCase();
switch (extension) {
case '.ts':
case '.tsx':
case '.mts':
case '.cts':
return true;
}
return false;
}