forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
/
resource_loader.ts
226 lines (192 loc) · 7.15 KB
/
resource_loader.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
/**
* @license
* Copyright Google Inc. 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.io/license
*/
import * as vm from 'vm';
import { Compiler, compilation } from 'webpack';
import { RawSource } from 'webpack-sources';
import { normalizePath } from './ivy/paths';
import { isWebpackFiveOrHigher } from './webpack-version';
const NodeTemplatePlugin = require('webpack/lib/node/NodeTemplatePlugin');
const NodeTargetPlugin = require('webpack/lib/node/NodeTargetPlugin');
const LibraryTemplatePlugin = require('webpack/lib/LibraryTemplatePlugin');
const SingleEntryPlugin = require('webpack/lib/SingleEntryPlugin');
type WebpackCompilation = compilation.Compilation & {
createChildCompiler(
name: string,
outputOptions: {},
plugins: ((compiler: Compiler) => void)[],
): WebpackCompiler;
};
type WebpackCompiler = Compiler & {
runAsChild(
callback: (
error?: Error,
entries?: unknown,
compilation?: compilation.Compilation,
) => void,
): void;
};
interface CompilationOutput {
content: string;
map?: string;
success: boolean;
}
export class WebpackResourceLoader {
private _parentCompilation?: WebpackCompilation;
private _fileDependencies = new Map<string, Set<string>>();
private _reverseDependencies = new Map<string, Set<string>>();
private cache = new Map<string, CompilationOutput>();
private modifiedResources = new Set<string>();
update(
parentCompilation: compilation.Compilation,
changedFiles?: Iterable<string>,
) {
this._parentCompilation = parentCompilation as WebpackCompilation;
// Update resource cache and modified resources
this.modifiedResources.clear();
if (changedFiles) {
for (const changedFile of changedFiles) {
for (const affectedResource of this.getAffectedResources(changedFile)) {
this.cache.delete(normalizePath(affectedResource));
this.modifiedResources.add(affectedResource);
}
}
} else {
this.cache.clear();
}
}
getModifiedResourceFiles() {
return this.modifiedResources;
}
getResourceDependencies(filePath: string) {
return this._fileDependencies.get(filePath) || [];
}
getAffectedResources(file: string) {
return this._reverseDependencies.get(file) || [];
}
setAffectedResources(file: string, resources: Iterable<string>) {
this._reverseDependencies.set(file, new Set(resources));
}
private async _compile(filePath: string): Promise<CompilationOutput> {
if (!this._parentCompilation) {
throw new Error('WebpackResourceLoader cannot be used without parentCompilation');
}
// Simple sanity check.
if (filePath.match(/\.[jt]s$/)) {
return Promise.reject(
`Cannot use a JavaScript or TypeScript file (${filePath}) in a component's styleUrls or templateUrl.`,
);
}
const outputOptions = { filename: filePath };
const context = this._parentCompilation.compiler.context;
const childCompiler = this._parentCompilation.createChildCompiler(
'angular-compiler:resource',
outputOptions,
[
new NodeTemplatePlugin(outputOptions),
new NodeTargetPlugin(),
new SingleEntryPlugin(context, filePath, 'resource'),
new LibraryTemplatePlugin('resource', 'var'),
],
);
childCompiler.hooks.thisCompilation.tap('angular-compiler', (compilation) => {
compilation.hooks.additionalAssets.tap('angular-compiler', () => {
const asset = compilation.assets[filePath];
if (!asset) {
return;
}
try {
const output = this._evaluate(filePath, asset.source().toString());
if (typeof output === 'string') {
// `webpack-sources` package has incomplete typings
// tslint:disable-next-line: no-any
compilation.assets[filePath] = new RawSource(output) as any;
}
} catch (error) {
// Use compilation errors, as otherwise webpack will choke
compilation.errors.push(error);
}
});
});
let finalContent: string | undefined;
let finalMap: string | undefined;
if (isWebpackFiveOrHigher()) {
childCompiler.hooks.compilation.tap('angular-compiler', (childCompilation) => {
// tslint:disable-next-line: no-any
(childCompilation.hooks as any).processAssets.tap({name: 'angular-compiler', stage: 5000}, () => {
finalContent = childCompilation.assets[filePath]?.source().toString();
finalMap = childCompilation.assets[filePath + '.map']?.source().toString();
delete childCompilation.assets[filePath];
delete childCompilation.assets[filePath + '.map'];
});
});
} else {
childCompiler.hooks.afterCompile.tap('angular-compiler', (childCompilation) => {
finalContent = childCompilation.assets[filePath]?.source().toString();
finalMap = childCompilation.assets[filePath + '.map']?.source().toString();
delete childCompilation.assets[filePath];
delete childCompilation.assets[filePath + '.map'];
});
}
return new Promise<CompilationOutput>((resolve, reject) => {
childCompiler.runAsChild((error, _, childCompilation) => {
if (error) {
reject(error);
return;
} else if (!childCompilation) {
reject(new Error('Unknown child compilation error'));
return;
}
// Save the dependencies for this resource.
this._fileDependencies.set(filePath, new Set(childCompilation.fileDependencies));
for (const file of childCompilation.fileDependencies) {
const resolvedFile = normalizePath(file);
const entry = this._reverseDependencies.get(resolvedFile);
if (entry) {
entry.add(filePath);
} else {
this._reverseDependencies.set(resolvedFile, new Set([filePath]));
}
}
resolve({
content: finalContent ?? '',
map: finalMap,
success: childCompilation.errors?.length === 0,
});
});
});
}
private _evaluate(filename: string, source: string): string | null {
// Evaluate code
const context: { resource?: string | { default?: string } } = {};
try {
vm.runInNewContext(source, context, { filename });
} catch {
// Error are propagated through the child compilation.
return null;
}
if (typeof context.resource === 'string') {
return context.resource;
} else if (typeof context.resource?.default === 'string') {
return context.resource.default;
}
throw new Error(`The loader "${filename}" didn't return a string.`);
}
async get(filePath: string): Promise<string> {
const normalizedFile = normalizePath(filePath);
let compilationResult = this.cache.get(normalizedFile);
if (compilationResult === undefined) {
// cache miss so compile resource
compilationResult = await this._compile(filePath);
// Only cache if compilation was successful
if (compilationResult.success) {
this.cache.set(normalizedFile, compilationResult);
}
}
return compilationResult.content;
}
}