UNPKG

7.85 kBJavaScriptView Raw
1"use strict";
2/**
3 * @license
4 * Copyright Google Inc. All Rights Reserved.
5 *
6 * Use of this source code is governed by an MIT-style license that can be
7 * found in the LICENSE file at https://angular.io/license
8 */
9Object.defineProperty(exports, "__esModule", { value: true });
10const ngcc_1 = require("@angular/compiler-cli/ngcc");
11const child_process_1 = require("child_process");
12const fs_1 = require("fs");
13const path = require("path");
14const benchmark_1 = require("./benchmark");
15// We cannot create a plugin for this, because NGTSC requires addition type
16// information which ngcc creates when processing a package which was compiled with NGC.
17// Example of such errors:
18// ERROR in node_modules/@angular/platform-browser/platform-browser.d.ts(42,22):
19// error TS-996002: Appears in the NgModule.imports of AppModule,
20// but could not be resolved to an NgModule class
21// We now transform a package and it's typings when NGTSC is resolving a module.
22class NgccProcessor {
23 constructor(propertiesToConsider, inputFileSystem, compilationWarnings, compilationErrors, basePath, compilerOptions, tsConfigPath) {
24 this.propertiesToConsider = propertiesToConsider;
25 this.inputFileSystem = inputFileSystem;
26 this.compilationWarnings = compilationWarnings;
27 this.compilationErrors = compilationErrors;
28 this.basePath = basePath;
29 this.compilerOptions = compilerOptions;
30 this.tsConfigPath = tsConfigPath;
31 this._processedModules = new Set();
32 this._logger = new NgccLogger(this.compilationWarnings, this.compilationErrors);
33 this._nodeModulesDirectory = this.findNodeModulesDirectory(this.basePath);
34 const { baseUrl, paths } = this.compilerOptions;
35 if (baseUrl && paths) {
36 this._pathMappings = {
37 baseUrl,
38 paths,
39 };
40 }
41 }
42 /** Process the entire node modules tree. */
43 process() {
44 // Under Bazel when running in sandbox mode parts of the filesystem is read-only.
45 if (process.env.BAZEL_TARGET) {
46 return;
47 }
48 // Skip if node_modules are read-only
49 const corePackage = this.tryResolvePackage('@angular/core', this._nodeModulesDirectory);
50 if (corePackage && isReadOnlyFile(corePackage)) {
51 return;
52 }
53 const timeLabel = 'NgccProcessor.process';
54 benchmark_1.time(timeLabel);
55 // We spawn instead of using the API because:
56 // - NGCC Async uses clustering which is problematic when used via the API which means
57 // that we cannot setup multiple cluster masters with different options.
58 // - We will not be able to have concurrent builds otherwise Ex: App-Shell,
59 // as NGCC will create a lock file for both builds and it will cause builds to fails.
60 const { status, error } = child_process_1.spawnSync(process.execPath, [
61 require.resolve('@angular/compiler-cli/ngcc/main-ngcc.js'),
62 '--source',
63 this._nodeModulesDirectory,
64 '--properties',
65 ...this.propertiesToConsider,
66 '--first-only',
67 '--create-ivy-entry-points',
68 '--async',
69 '--tsconfig',
70 this.tsConfigPath,
71 ], {
72 stdio: ['inherit', process.stderr, process.stderr],
73 });
74 if (status !== 0) {
75 const errorMessage = (error === null || error === void 0 ? void 0 : error.message) || '';
76 throw new Error(errorMessage + `NGCC failed${errorMessage ? ', see above' : ''}.`);
77 }
78 benchmark_1.timeEnd(timeLabel);
79 }
80 /** Process a module and it's depedencies. */
81 processModule(moduleName, resolvedModule) {
82 const resolvedFileName = resolvedModule.resolvedFileName;
83 if (!resolvedFileName || moduleName.startsWith('.')
84 || this._processedModules.has(resolvedFileName)) {
85 // Skip when module is unknown, relative or NGCC compiler is not found or already processed.
86 return;
87 }
88 const packageJsonPath = this.tryResolvePackage(moduleName, resolvedFileName);
89 // If the package.json is read only we should skip calling NGCC.
90 // With Bazel when running under sandbox the filesystem is read-only.
91 if (!packageJsonPath || isReadOnlyFile(packageJsonPath)) {
92 // add it to processed so the second time round we skip this.
93 this._processedModules.add(resolvedFileName);
94 return;
95 }
96 const timeLabel = `NgccProcessor.processModule.ngcc.process+${moduleName}`;
97 benchmark_1.time(timeLabel);
98 ngcc_1.process({
99 basePath: this._nodeModulesDirectory,
100 targetEntryPointPath: path.dirname(packageJsonPath),
101 propertiesToConsider: this.propertiesToConsider,
102 compileAllFormats: false,
103 createNewEntryPointFormats: true,
104 logger: this._logger,
105 // Path mappings are not longer required since NGCC 9.1
106 // We keep using them to be backward compatible with NGCC 9.0
107 pathMappings: this._pathMappings,
108 tsConfigPath: this.tsConfigPath,
109 });
110 benchmark_1.timeEnd(timeLabel);
111 // Purge this file from cache, since NGCC add new mainFields. Ex: module_ivy_ngcc
112 // which are unknown in the cached file.
113 // tslint:disable-next-line:no-any
114 this.inputFileSystem.purge(packageJsonPath);
115 this._processedModules.add(resolvedFileName);
116 }
117 invalidate(fileName) {
118 this._processedModules.delete(fileName);
119 }
120 /**
121 * Try resolve a package.json file from the resolved .d.ts file.
122 */
123 tryResolvePackage(moduleName, resolvedFileName) {
124 try {
125 // This is based on the logic in the NGCC compiler
126 // tslint:disable-next-line:max-line-length
127 // See: https://github.com/angular/angular/blob/b93c1dffa17e4e6900b3ab1b9e554b6da92be0de/packages/compiler-cli/src/ngcc/src/packages/dependency_host.ts#L85-L121
128 return require.resolve(`${moduleName}/package.json`, {
129 paths: [resolvedFileName],
130 });
131 }
132 catch (_a) {
133 // if it fails this might be a deep import which doesn't have a package.json
134 // Ex: @angular/compiler/src/i18n/i18n_ast/package.json
135 // or local libraries which don't reside in node_modules
136 const packageJsonPath = path.resolve(resolvedFileName, '../package.json');
137 return fs_1.existsSync(packageJsonPath) ? packageJsonPath : undefined;
138 }
139 }
140 findNodeModulesDirectory(startPoint) {
141 let current = startPoint;
142 while (path.dirname(current) !== current) {
143 const nodePath = path.join(current, 'node_modules');
144 if (fs_1.existsSync(nodePath)) {
145 return nodePath;
146 }
147 current = path.dirname(current);
148 }
149 throw new Error(`Cannot locate the 'node_modules' directory.`);
150 }
151}
152exports.NgccProcessor = NgccProcessor;
153class NgccLogger {
154 constructor(compilationWarnings, compilationErrors) {
155 this.compilationWarnings = compilationWarnings;
156 this.compilationErrors = compilationErrors;
157 this.level = ngcc_1.LogLevel.info;
158 }
159 debug(..._args) { }
160 info(...args) {
161 // Log to stderr because it's a progress-like info message.
162 process.stderr.write(`\n${args.join(' ')}\n`);
163 }
164 warn(...args) {
165 this.compilationWarnings.push(args.join(' '));
166 }
167 error(...args) {
168 this.compilationErrors.push(new Error(args.join(' ')));
169 }
170}
171function isReadOnlyFile(fileName) {
172 try {
173 fs_1.accessSync(fileName, fs_1.constants.W_OK);
174 return false;
175 }
176 catch (_a) {
177 return true;
178 }
179}