forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathplugin.ts
381 lines (330 loc) · 13 KB
/
plugin.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
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
import {NgModule} from '@angular/core';
import * as ngCompiler from '@angular/compiler-cli';
import {tsc} from '@angular/tsc-wrapped/src/tsc';
import {patchReflectorHost} from './reflector_host';
import {WebpackResourceLoader} from './resource_loader';
import {createResolveDependenciesFromContextMap} from './utils';
import {WebpackCompilerHost} from './compiler_host';
import {resolveEntryModuleFromMain} from './entry_resolver';
import {StaticSymbol} from '@angular/compiler-cli';
/**
* Option Constants
*/
export interface AotPluginOptions {
tsConfigPath: string;
basePath?: string;
entryModule?: string;
mainPath?: string;
typeChecking?: boolean;
}
export interface LazyRoute {
moduleRoute: ModuleRoute;
moduleAbsolutePath: string;
}
export interface LazyRouteMap {
[path: string]: LazyRoute;
}
export class ModuleRoute {
constructor(public readonly path: string, public readonly className: string = null) {}
toString() {
return `${this.path}#${this.className}`;
}
static fromString(entry: string): ModuleRoute {
const split = entry.split('#');
return new ModuleRoute(split[0], split[1]);
}
}
export class AotPlugin {
private _entryModule: ModuleRoute;
private _compilerOptions: ts.CompilerOptions;
private _angularCompilerOptions: ngCompiler.AngularCompilerOptions;
private _program: ts.Program;
private _reflector: ngCompiler.StaticReflector;
private _reflectorHost: ngCompiler.ReflectorHost;
private _rootFilePath: string[];
private _compilerHost: WebpackCompilerHost;
private _resourceLoader: WebpackResourceLoader;
private _lazyRoutes: { [route: string]: string };
private _donePromise: Promise<void>;
private _compiler: any = null;
private _compilation: any = null;
private _typeCheck: boolean = true;
private _basePath: string;
private _genDir: string;
constructor(options: AotPluginOptions) {
this._setupOptions(options);
}
get basePath() { return this._basePath; }
get compilation() { return this._compilation; }
get compilerOptions() { return this._compilerOptions; }
get done() { return this._donePromise; }
get entryModule() { return this._entryModule; }
get genDir() { return this._genDir; }
get program() { return this._program; }
get typeCheck() { return this._typeCheck; }
private _setupOptions(options: AotPluginOptions) {
// Fill in the missing options.
if (!options.hasOwnProperty('tsConfigPath')) {
throw new Error('Must specify "tsConfigPath" in the configuration of @ngtools/webpack.');
}
// Check the base path.
let basePath = path.resolve(process.cwd(), path.dirname(options.tsConfigPath));
if (fs.statSync(options.tsConfigPath).isDirectory()) {
basePath = options.tsConfigPath;
}
if (options.hasOwnProperty('basePath')) {
basePath = options.basePath;
}
const tsConfig = tsc.readConfiguration(options.tsConfigPath, basePath);
this._rootFilePath = tsConfig.parsed.fileNames;
// Check the genDir.
let genDir = basePath;
if (tsConfig.ngOptions.hasOwnProperty('genDir')) {
genDir = tsConfig.ngOptions.genDir;
}
this._compilerOptions = tsConfig.parsed.options;
if (options.entryModule) {
this._entryModule = ModuleRoute.fromString(options.entryModule);
} else {
if (options.mainPath) {
this._entryModule = ModuleRoute.fromString(resolveEntryModuleFromMain(options.mainPath));
} else {
this._entryModule = ModuleRoute.fromString((tsConfig.ngOptions as any).entryModule);
}
}
this._angularCompilerOptions = Object.assign({}, tsConfig.ngOptions, {
basePath,
entryModule: this._entryModule.toString(),
genDir
});
this._basePath = basePath;
this._genDir = genDir;
if (options.hasOwnProperty('typeChecking')) {
this._typeCheck = options.typeChecking;
}
this._compilerHost = new WebpackCompilerHost(this._compilerOptions);
this._program = ts.createProgram(
this._rootFilePath, this._compilerOptions, this._compilerHost);
this._reflectorHost = new ngCompiler.ReflectorHost(
this._program, this._compilerHost, this._angularCompilerOptions);
this._reflector = new ngCompiler.StaticReflector(this._reflectorHost);
}
// registration hook for webpack plugin
apply(compiler: any) {
this._compiler = compiler;
compiler.plugin('context-module-factory', (cmf: any) => {
cmf.plugin('before-resolve', (request: any, callback: (err?: any, request?: any) => void) => {
if (!request) {
return callback();
}
request.request = this.genDir;
request.recursive = true;
request.dependencies.forEach((d: any) => d.critical = false);
return callback(null, request);
});
cmf.plugin('after-resolve', (result: any, callback: (err?: any, request?: any) => void) => {
if (!result) {
return callback();
}
this.done.then(() => {
result.resource = this.genDir;
result.recursive = true;
result.dependencies.forEach((d: any) => d.critical = false);
result.resolveDependencies = createResolveDependenciesFromContextMap(
(_: any, cb: any) => cb(null, this._lazyRoutes));
return callback(null, result);
});
});
});
compiler.plugin('make', (compilation: any, cb: any) => this._make(compilation, cb));
compiler.plugin('after-emit', (compilation: any, cb: any) => {
this._donePromise = null;
this._compilation = null;
compilation._ngToolsWebpackPluginInstance = null;
cb();
});
// Virtual file system.
compiler.resolvers.normal.plugin('resolve', (request: any, cb?: () => void) => {
if (request.request.match(/\.ts$/)) {
this.done.then(() => cb());
} else {
cb();
}
});
}
private _make(compilation: any, cb: (err?: any, request?: any) => void) {
this._compilation = compilation;
if (this._compilation._ngToolsWebpackPluginInstance) {
cb(new Error('An @ngtools/webpack plugin already exist for this compilation.'));
}
this._compilation._ngToolsWebpackPluginInstance = this;
this._resourceLoader = new WebpackResourceLoader(compilation);
const i18nOptions: ngCompiler.NgcCliOptions = {
i18nFile: undefined,
i18nFormat: undefined,
locale: undefined,
basePath: this.basePath
};
// Create the Code Generator.
const codeGenerator = ngCompiler.CodeGenerator.create(
this._angularCompilerOptions,
i18nOptions,
this._program,
this._compilerHost,
new ngCompiler.NodeReflectorHostContext(this._compilerHost),
this._resourceLoader
);
// We need to temporarily patch the CodeGenerator until either it's patched or allows us
// to pass in our own ReflectorHost.
patchReflectorHost(codeGenerator);
this._donePromise = codeGenerator.codegen({transitiveModules: true})
.then(() => {
// Create a new Program, based on the old one. This will trigger a resolution of all
// transitive modules, which include files that might just have been generated.
this._program = ts.createProgram(
this._rootFilePath, this._compilerOptions, this._compilerHost, this._program);
const diagnostics = this._program.getGlobalDiagnostics();
if (diagnostics.length > 0) {
const message = diagnostics
.map(diagnostic => {
const {line, character} = diagnostic.file.getLineAndCharacterOfPosition(
diagnostic.start);
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
return `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message})`;
})
.join('\n');
throw new Error(message);
}
})
.then(() => {
// Populate the file system cache with the virtual module.
this._compilerHost.populateWebpackResolver(this._compiler.resolvers.normal);
})
.then(() => {
// Process the lazy routes
this._lazyRoutes = {};
const allLazyRoutes = this._processNgModule(this._entryModule, null);
Object.keys(allLazyRoutes)
.forEach(k => {
const lazyRoute = allLazyRoutes[k];
this._lazyRoutes[k + '.ngfactory'] = lazyRoute.moduleAbsolutePath + '.ngfactory.ts';
});
})
.then(() => cb(), (err: any) => { cb(err); });
}
private _resolveModulePath(module: ModuleRoute, containingFile: string) {
return this._reflectorHost.findDeclaration(module.path, module.className, containingFile)
.filePath;
}
private _processNgModule(module: ModuleRoute, containingFile: string | null): LazyRouteMap {
const modulePath = containingFile ? module.path : ('./' + path.basename(module.path));
if (containingFile === null) {
containingFile = module.path + '.ts';
}
const relativeModulePath = this._resolveModulePath(module, containingFile);
const staticSymbol = this._reflectorHost
.findDeclaration(modulePath, module.className, containingFile);
const entryNgModuleMetadata = this.getNgModuleMetadata(staticSymbol);
const loadChildrenRoute: LazyRoute[] = this.extractLoadChildren(entryNgModuleMetadata)
.map(route => {
const moduleRoute = ModuleRoute.fromString(route);
const moduleAbsolutePath = this._resolveModulePath(moduleRoute, relativeModulePath);
return { moduleRoute, moduleAbsolutePath };
});
const resultMap: LazyRouteMap = loadChildrenRoute
.reduce((acc: LazyRouteMap, curr: LazyRoute) => {
const key = curr.moduleRoute.path;
if (acc[key]) {
if (acc[key].moduleAbsolutePath != curr.moduleAbsolutePath) {
throw new Error(`Duplicated path in loadChildren detected: "${key}" is used in 2 ` +
'loadChildren, but they point to different modules. Webpack cannot distinguish ' +
'between the two based on context and would fail to load the proper one.');
}
} else {
acc[key] = curr;
}
return acc;
}, {});
// Also concatenate every child of child modules.
for (const lazyRoute of loadChildrenRoute) {
const mr = lazyRoute.moduleRoute;
const children = this._processNgModule(mr, relativeModulePath);
Object.keys(children).forEach(p => {
const child = children[p];
const key = child.moduleRoute.path;
if (resultMap[key]) {
if (resultMap[key].moduleAbsolutePath != child.moduleAbsolutePath) {
throw new Error(`Duplicated path in loadChildren detected: "${key}" is used in 2 ` +
'loadChildren, but they point to different modules. Webpack cannot distinguish ' +
'between the two based on context and would fail to load the proper one.');
}
} else {
resultMap[key] = child;
}
});
}
return resultMap;
}
private getNgModuleMetadata(staticSymbol: ngCompiler.StaticSymbol) {
const ngModules = this._reflector.annotations(staticSymbol).filter(s => s instanceof NgModule);
if (ngModules.length === 0) {
throw new Error(`${staticSymbol.name} is not an NgModule`);
}
return ngModules[0];
}
private extractLoadChildren(ngModuleDecorator: any): any[] {
const routes = (ngModuleDecorator.imports || []).reduce((mem: any[], m: any) => {
return mem.concat(this.collectRoutes(m.providers));
}, this.collectRoutes(ngModuleDecorator.providers));
return this.collectLoadChildren(routes)
.concat((ngModuleDecorator.imports || [])
// Also recursively extractLoadChildren of modules we import.
.map((staticSymbol: any) => {
if (staticSymbol instanceof StaticSymbol) {
const entryNgModuleMetadata = this.getNgModuleMetadata(staticSymbol);
return this.extractLoadChildren(entryNgModuleMetadata);
} else {
return [];
}
})
// Poor man's flat map.
.reduce((acc: any[], i: any) => acc.concat(i), [])
)
.filter(x => !!x);
}
private collectRoutes(providers: any[]): any[] {
if (!providers) {
return [];
}
const ROUTES = this._reflectorHost.findDeclaration(
'@angular/router/src/router_config_loader', 'ROUTES', undefined);
return providers.reduce((m, p) => {
if (p.provide === ROUTES) {
return m.concat(p.useValue);
} else if (Array.isArray(p)) {
return m.concat(this.collectRoutes(p));
} else {
return m;
}
}, []);
}
private collectLoadChildren(routes: any[]): any[] {
if (!routes) {
return [];
}
return routes.reduce((m, r) => {
if (r.loadChildren) {
return m.concat(r.loadChildren);
} else if (Array.isArray(r)) {
return m.concat(this.collectLoadChildren(r));
} else if (r.children) {
return m.concat(this.collectLoadChildren(r.children));
} else {
return m;
}
}, []);
}
}