1 | "use strict";
|
---|
2 | /**
|
---|
3 | * @license
|
---|
4 | * Copyright Google LLC 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 | */
|
---|
9 | var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
---|
10 | if (k2 === undefined) k2 = k;
|
---|
11 | Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
---|
12 | }) : (function(o, m, k, k2) {
|
---|
13 | if (k2 === undefined) k2 = k;
|
---|
14 | o[k2] = m[k];
|
---|
15 | }));
|
---|
16 | var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
---|
17 | Object.defineProperty(o, "default", { enumerable: true, value: v });
|
---|
18 | }) : function(o, v) {
|
---|
19 | o["default"] = v;
|
---|
20 | });
|
---|
21 | var __importStar = (this && this.__importStar) || function (mod) {
|
---|
22 | if (mod && mod.__esModule) return mod;
|
---|
23 | var result = {};
|
---|
24 | if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
---|
25 | __setModuleDefault(result, mod);
|
---|
26 | return result;
|
---|
27 | };
|
---|
28 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
---|
29 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
---|
30 | };
|
---|
31 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
32 | const path = __importStar(require("path"));
|
---|
33 | const glob = __importStar(require("glob"));
|
---|
34 | const webpack_1 = __importDefault(require("webpack"));
|
---|
35 | const webpackDevMiddleware = require('webpack-dev-middleware');
|
---|
36 | const stats_1 = require("../../utils/stats");
|
---|
37 | const node_1 = require("@angular-devkit/core/node");
|
---|
38 | const index_1 = require("../../../utils/index");
|
---|
39 | const KARMA_APPLICATION_PATH = '_karma_webpack_';
|
---|
40 | let blocked = [];
|
---|
41 | let isBlocked = false;
|
---|
42 | let webpackMiddleware;
|
---|
43 | let successCb;
|
---|
44 | let failureCb;
|
---|
45 | // Add files to the Karma files array.
|
---|
46 | function addKarmaFiles(files, newFiles, prepend = false) {
|
---|
47 | const defaults = {
|
---|
48 | included: true,
|
---|
49 | served: true,
|
---|
50 | watched: true,
|
---|
51 | };
|
---|
52 | const processedFiles = newFiles
|
---|
53 | // Remove globs that do not match any files, otherwise Karma will show a warning for these.
|
---|
54 | .filter((file) => glob.sync(file.pattern, { nodir: true }).length != 0)
|
---|
55 | // Fill in pattern properties with defaults.
|
---|
56 | .map((file) => ({ ...defaults, ...file }));
|
---|
57 | // It's important to not replace the array, because
|
---|
58 | // karma already has a reference to the existing array.
|
---|
59 | if (prepend) {
|
---|
60 | files.unshift(...processedFiles);
|
---|
61 | }
|
---|
62 | else {
|
---|
63 | files.push(...processedFiles);
|
---|
64 | }
|
---|
65 | }
|
---|
66 | const init = (config, emitter) => {
|
---|
67 | if (!config.buildWebpack) {
|
---|
68 | throw new Error(`The '@angular-devkit/build-angular/plugins/karma' karma plugin is meant to` +
|
---|
69 | ` be used from within Angular CLI and will not work correctly outside of it.`);
|
---|
70 | }
|
---|
71 | const options = config.buildWebpack.options;
|
---|
72 | const logger = config.buildWebpack.logger || node_1.createConsoleLogger();
|
---|
73 | successCb = config.buildWebpack.successCb;
|
---|
74 | failureCb = config.buildWebpack.failureCb;
|
---|
75 | // Add a reporter that fixes sourcemap urls.
|
---|
76 | if (index_1.normalizeSourceMaps(options.sourceMap).scripts) {
|
---|
77 | config.reporters.unshift('@angular-devkit/build-angular--sourcemap-reporter');
|
---|
78 | // Code taken from https://github.com/tschaub/karma-source-map-support.
|
---|
79 | // We can't use it directly because we need to add it conditionally in this file, and karma
|
---|
80 | // frameworks cannot be added dynamically.
|
---|
81 | const smsPath = path.dirname(require.resolve('source-map-support'));
|
---|
82 | const ksmsPath = path.dirname(require.resolve('karma-source-map-support'));
|
---|
83 | addKarmaFiles(config.files, [
|
---|
84 | { pattern: path.join(smsPath, 'browser-source-map-support.js'), watched: false },
|
---|
85 | { pattern: path.join(ksmsPath, 'client.js'), watched: false },
|
---|
86 | ], true);
|
---|
87 | }
|
---|
88 | config.reporters.unshift('@angular-devkit/build-angular--event-reporter');
|
---|
89 | // When using code-coverage, auto-add karma-coverage.
|
---|
90 | if (options.codeCoverage) {
|
---|
91 | config.plugins = config.plugins || [];
|
---|
92 | config.reporters = config.reporters || [];
|
---|
93 | const { plugins, reporters } = config;
|
---|
94 | const hasCoveragePlugin = plugins.some(isPlugin('karma-coverage', 'reporter:coverage'));
|
---|
95 | const hasIstanbulPlugin = plugins.some(isPlugin('karma-coverage-istanbul-reporter', 'reporter:coverage-istanbul'));
|
---|
96 | const hasCoverageReporter = reporters.includes('coverage');
|
---|
97 | const hasIstanbulReporter = reporters.includes('coverage-istanbul');
|
---|
98 | if (hasCoveragePlugin && !hasCoverageReporter) {
|
---|
99 | reporters.push('coverage');
|
---|
100 | }
|
---|
101 | else if (hasIstanbulPlugin && !hasIstanbulReporter) {
|
---|
102 | // coverage-istanbul is deprecated in favor of karma-coverage
|
---|
103 | reporters.push('coverage-istanbul');
|
---|
104 | }
|
---|
105 | else if (!hasCoveragePlugin && !hasIstanbulPlugin) {
|
---|
106 | throw new Error('karma-coverage must be installed in order to run code coverage.');
|
---|
107 | }
|
---|
108 | if (hasIstanbulPlugin) {
|
---|
109 | logger.warn(`'karma-coverage-istanbul-reporter' usage has been deprecated since version 11.\n` +
|
---|
110 | `Please install 'karma-coverage' and update 'karma.conf.js.' ` +
|
---|
111 | 'For more info, see https://github.com/karma-runner/karma-coverage/blob/master/README.md');
|
---|
112 | }
|
---|
113 | }
|
---|
114 | // Add webpack config.
|
---|
115 | const webpackConfig = config.buildWebpack.webpackConfig;
|
---|
116 | const webpackMiddlewareConfig = {
|
---|
117 | // Hide webpack output because its noisy.
|
---|
118 | stats: false,
|
---|
119 | publicPath: `/${KARMA_APPLICATION_PATH}/`,
|
---|
120 | };
|
---|
121 | // Use existing config if any.
|
---|
122 | config.webpack = { ...webpackConfig, ...config.webpack };
|
---|
123 | config.webpackMiddleware = { ...webpackMiddlewareConfig, ...config.webpackMiddleware };
|
---|
124 | // Our custom context and debug files list the webpack bundles directly instead of using
|
---|
125 | // the karma files array.
|
---|
126 | config.customContextFile = `${__dirname}/karma-context.html`;
|
---|
127 | config.customDebugFile = `${__dirname}/karma-debug.html`;
|
---|
128 | // Add the request blocker and the webpack server fallback.
|
---|
129 | config.beforeMiddleware = config.beforeMiddleware || [];
|
---|
130 | config.beforeMiddleware.push('@angular-devkit/build-angular--blocker');
|
---|
131 | config.middleware = config.middleware || [];
|
---|
132 | config.middleware.push('@angular-devkit/build-angular--fallback');
|
---|
133 | if (config.singleRun) {
|
---|
134 | // There's no option to turn off file watching in webpack-dev-server, but
|
---|
135 | // we can override the file watcher instead.
|
---|
136 | webpackConfig.plugins.unshift({
|
---|
137 | apply: (compiler) => {
|
---|
138 | compiler.hooks.afterEnvironment.tap('karma', () => {
|
---|
139 | compiler.watchFileSystem = { watch: () => { } };
|
---|
140 | });
|
---|
141 | },
|
---|
142 | });
|
---|
143 | }
|
---|
144 | // Files need to be served from a custom path for Karma.
|
---|
145 | webpackConfig.output.path = `/${KARMA_APPLICATION_PATH}/`;
|
---|
146 | webpackConfig.output.publicPath = `/${KARMA_APPLICATION_PATH}/`;
|
---|
147 | const compiler = webpack_1.default(webpackConfig, (error, stats) => {
|
---|
148 | var _a;
|
---|
149 | if (error) {
|
---|
150 | throw error;
|
---|
151 | }
|
---|
152 | if (stats === null || stats === void 0 ? void 0 : stats.hasErrors()) {
|
---|
153 | // Only generate needed JSON stats and when needed.
|
---|
154 | const statsJson = stats === null || stats === void 0 ? void 0 : stats.toJson({
|
---|
155 | all: false,
|
---|
156 | children: true,
|
---|
157 | errors: true,
|
---|
158 | warnings: true,
|
---|
159 | });
|
---|
160 | logger.error(stats_1.statsErrorsToString(statsJson, { colors: true }));
|
---|
161 | // Notify potential listeners of the compile error.
|
---|
162 | emitter.emit('compile_error', {
|
---|
163 | errors: (_a = statsJson.errors) === null || _a === void 0 ? void 0 : _a.map((e) => e.message),
|
---|
164 | });
|
---|
165 | // Finish Karma run early in case of compilation error.
|
---|
166 | emitter.emit('run_complete', [], { exitCode: 1 });
|
---|
167 | // Emit a failure build event if there are compilation errors.
|
---|
168 | failureCb();
|
---|
169 | }
|
---|
170 | });
|
---|
171 | function handler(callback) {
|
---|
172 | isBlocked = true;
|
---|
173 | callback === null || callback === void 0 ? void 0 : callback();
|
---|
174 | }
|
---|
175 | compiler.hooks.invalid.tap('karma', () => handler());
|
---|
176 | compiler.hooks.watchRun.tapAsync('karma', (_, callback) => handler(callback));
|
---|
177 | compiler.hooks.run.tapAsync('karma', (_, callback) => handler(callback));
|
---|
178 | function unblock() {
|
---|
179 | isBlocked = false;
|
---|
180 | blocked.forEach((cb) => cb());
|
---|
181 | blocked = [];
|
---|
182 | }
|
---|
183 | let lastCompilationHash;
|
---|
184 | compiler.hooks.done.tap('karma', (stats) => {
|
---|
185 | if (stats.hasErrors()) {
|
---|
186 | lastCompilationHash = undefined;
|
---|
187 | }
|
---|
188 | else if (stats.hash != lastCompilationHash) {
|
---|
189 | // Refresh karma only when there are no webpack errors, and if the compilation changed.
|
---|
190 | lastCompilationHash = stats.hash;
|
---|
191 | emitter.refreshFiles();
|
---|
192 | }
|
---|
193 | unblock();
|
---|
194 | });
|
---|
195 | webpackMiddleware = webpackDevMiddleware(compiler, webpackMiddlewareConfig);
|
---|
196 | emitter.on('exit', (done) => {
|
---|
197 | webpackMiddleware.close();
|
---|
198 | done();
|
---|
199 | });
|
---|
200 | };
|
---|
201 | init.$inject = ['config', 'emitter'];
|
---|
202 | // Block requests until the Webpack compilation is done.
|
---|
203 | function requestBlocker() {
|
---|
204 | return function (_request, _response, next) {
|
---|
205 | if (isBlocked) {
|
---|
206 | blocked.push(next);
|
---|
207 | }
|
---|
208 | else {
|
---|
209 | next();
|
---|
210 | }
|
---|
211 | };
|
---|
212 | }
|
---|
213 | // Copied from "karma-jasmine-diff-reporter" source code:
|
---|
214 | // In case, when multiple reporters are used in conjunction
|
---|
215 | // with initSourcemapReporter, they both will show repetitive log
|
---|
216 | // messages when displaying everything that supposed to write to terminal.
|
---|
217 | // So just suppress any logs from initSourcemapReporter by doing nothing on
|
---|
218 | // browser log, because it is an utility reporter,
|
---|
219 | // unless it's alone in the "reporters" option and base reporter is used.
|
---|
220 | function muteDuplicateReporterLogging(context, config) {
|
---|
221 | context.writeCommonMsg = () => { };
|
---|
222 | const reporterName = '@angular/cli';
|
---|
223 | const hasTrailingReporters = config.reporters.slice(-1).pop() !== reporterName;
|
---|
224 | if (hasTrailingReporters) {
|
---|
225 | context.writeCommonMsg = () => { };
|
---|
226 | }
|
---|
227 | }
|
---|
228 | // Emits builder events.
|
---|
229 | const eventReporter = function (baseReporterDecorator, config) {
|
---|
230 | baseReporterDecorator(this);
|
---|
231 | muteDuplicateReporterLogging(this, config);
|
---|
232 | this.onRunComplete = function (_browsers, results) {
|
---|
233 | if (results.exitCode === 0) {
|
---|
234 | successCb();
|
---|
235 | }
|
---|
236 | else {
|
---|
237 | failureCb();
|
---|
238 | }
|
---|
239 | };
|
---|
240 | // avoid duplicate failure message
|
---|
241 | this.specFailure = () => { };
|
---|
242 | };
|
---|
243 | eventReporter.$inject = ['baseReporterDecorator', 'config'];
|
---|
244 | // Strip the server address and webpack scheme (webpack://) from error log.
|
---|
245 | const sourceMapReporter = function (baseReporterDecorator, config) {
|
---|
246 | baseReporterDecorator(this);
|
---|
247 | muteDuplicateReporterLogging(this, config);
|
---|
248 | const urlRegexp = /http:\/\/localhost:\d+\/_karma_webpack_\/(webpack:\/)?/gi;
|
---|
249 | this.onSpecComplete = function (_browser, result) {
|
---|
250 | if (!result.success) {
|
---|
251 | result.log = result.log.map((l) => l.replace(urlRegexp, ''));
|
---|
252 | }
|
---|
253 | };
|
---|
254 | // avoid duplicate complete message
|
---|
255 | this.onRunComplete = () => { };
|
---|
256 | // avoid duplicate failure message
|
---|
257 | this.specFailure = () => { };
|
---|
258 | };
|
---|
259 | sourceMapReporter.$inject = ['baseReporterDecorator', 'config'];
|
---|
260 | // When a request is not found in the karma server, try looking for it from the webpack server root.
|
---|
261 | function fallbackMiddleware() {
|
---|
262 | return function (request, response, next) {
|
---|
263 | if (webpackMiddleware) {
|
---|
264 | if (request.url && !new RegExp(`\\/${KARMA_APPLICATION_PATH}\\/.*`).test(request.url)) {
|
---|
265 | request.url = '/' + KARMA_APPLICATION_PATH + request.url;
|
---|
266 | }
|
---|
267 | webpackMiddleware(request, response, () => {
|
---|
268 | const alwaysServe = [
|
---|
269 | `/${KARMA_APPLICATION_PATH}/runtime.js`,
|
---|
270 | `/${KARMA_APPLICATION_PATH}/polyfills.js`,
|
---|
271 | `/${KARMA_APPLICATION_PATH}/polyfills-es5.js`,
|
---|
272 | `/${KARMA_APPLICATION_PATH}/scripts.js`,
|
---|
273 | `/${KARMA_APPLICATION_PATH}/styles.css`,
|
---|
274 | `/${KARMA_APPLICATION_PATH}/vendor.js`,
|
---|
275 | ];
|
---|
276 | if (request.url && alwaysServe.includes(request.url)) {
|
---|
277 | response.statusCode = 200;
|
---|
278 | response.end();
|
---|
279 | }
|
---|
280 | else {
|
---|
281 | next();
|
---|
282 | }
|
---|
283 | });
|
---|
284 | }
|
---|
285 | else {
|
---|
286 | next();
|
---|
287 | }
|
---|
288 | };
|
---|
289 | }
|
---|
290 | /**
|
---|
291 | * Returns a function that returns true if the plugin identifier matches the
|
---|
292 | * `moduleId` or `pluginName`. A plugin identifier can be either a string or
|
---|
293 | * an object according to https://karma-runner.github.io/5.2/config/plugins.html
|
---|
294 | * @param moduleId name of the node module (e.g. karma-coverage)
|
---|
295 | * @param pluginName name of the karma plugin (e.g. reporter:coverage)
|
---|
296 | */
|
---|
297 | function isPlugin(moduleId, pluginName) {
|
---|
298 | return (plugin) => {
|
---|
299 | if (typeof plugin === 'string') {
|
---|
300 | if (!plugin.includes('*')) {
|
---|
301 | return plugin === moduleId;
|
---|
302 | }
|
---|
303 | const regexp = new RegExp(`^${plugin.replace('*', '.*')}`);
|
---|
304 | if (regexp.test(moduleId)) {
|
---|
305 | try {
|
---|
306 | require.resolve(moduleId);
|
---|
307 | return true;
|
---|
308 | }
|
---|
309 | catch { }
|
---|
310 | }
|
---|
311 | return false;
|
---|
312 | }
|
---|
313 | return pluginName in plugin;
|
---|
314 | };
|
---|
315 | }
|
---|
316 | module.exports = {
|
---|
317 | 'framework:@angular-devkit/build-angular': ['factory', init],
|
---|
318 | 'reporter:@angular-devkit/build-angular--sourcemap-reporter': ['type', sourceMapReporter],
|
---|
319 | 'reporter:@angular-devkit/build-angular--event-reporter': ['type', eventReporter],
|
---|
320 | 'middleware:@angular-devkit/build-angular--blocker': ['factory', requestBlocker],
|
---|
321 | 'middleware:@angular-devkit/build-angular--fallback': ['factory', fallbackMiddleware],
|
---|
322 | };
|
---|