source: frontend/node_modules/css-minimizer-webpack-plugin/dist/index.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 19.3 KB
Line 
1"use strict";
2
3const os = require("os");
4
5const {
6 SourceMapConsumer
7} = require("source-map");
8
9const {
10 validate
11} = require("schema-utils");
12
13const serialize = require("serialize-javascript");
14
15const {
16 Worker
17} = require("jest-worker");
18
19const {
20 throttleAll,
21 cssnanoMinify,
22 cssoMinify,
23 cleanCssMinify,
24 esbuildMinify,
25 parcelCssMinify
26} = require("./utils");
27
28const schema = require("./options.json");
29
30const {
31 minify
32} = require("./minify");
33/** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
34
35/** @typedef {import("webpack").Compiler} Compiler */
36
37/** @typedef {import("webpack").Compilation} Compilation */
38
39/** @typedef {import("webpack").WebpackError} WebpackError */
40
41/** @typedef {import("jest-worker").Worker} JestWorker */
42
43/** @typedef {import("source-map").RawSourceMap} RawSourceMap */
44
45/** @typedef {import("webpack").Asset} Asset */
46
47/** @typedef {import("postcss").ProcessOptions} ProcessOptions */
48
49/** @typedef {import("postcss").Syntax} Syntax */
50
51/** @typedef {import("postcss").Parser} Parser */
52
53/** @typedef {import("postcss").Stringifier} Stringifier */
54
55/**
56 * @typedef {Object} CssNanoOptions
57 * @property {string} [configFile]
58 * @property {[string, object] | string | undefined} [preset]
59 */
60
61/** @typedef {Error & { plugin?: string, text?: string, source?: string } | string} Warning */
62
63/**
64 * @typedef {Object} WarningObject
65 * @property {string} message
66 * @property {string} [plugin]
67 * @property {string} [text]
68 * @property {number} [line]
69 * @property {number} [column]
70 */
71
72/**
73 * @typedef {Object} ErrorObject
74 * @property {string} message
75 * @property {number} [line]
76 * @property {number} [column]
77 * @property {string} [stack]
78 */
79
80/**
81 * @typedef {Object} MinimizedResult
82 * @property {string} code
83 * @property {RawSourceMap} [map]
84 * @property {Array<Error | ErrorObject| string>} [errors]
85 * @property {Array<Warning | WarningObject | string>} [warnings]
86 */
87
88/**
89 * @typedef {{ [file: string]: string }} Input
90 */
91
92/**
93 * @typedef {{ [key: string]: any }} CustomOptions
94 */
95
96/**
97 * @template T
98 * @typedef {T extends infer U ? U : CustomOptions} InferDefaultType
99 */
100
101/**
102 * @template T
103 * @callback BasicMinimizerImplementation
104 * @param {Input} input
105 * @param {RawSourceMap | undefined} sourceMap
106 * @param {InferDefaultType<T>} minifyOptions
107 * @returns {Promise<MinimizedResult>}
108 */
109
110/**
111 * @template T
112 * @typedef {T extends any[] ? { [P in keyof T]: BasicMinimizerImplementation<T[P]>; } : BasicMinimizerImplementation<T>} MinimizerImplementation
113 */
114
115/**
116 * @template T
117 * @typedef {T extends any[] ? { [P in keyof T]?: InferDefaultType<T[P]> } : InferDefaultType<T>} MinimizerOptions
118 */
119
120/**
121 * @template T
122 * @typedef {Object} InternalOptions
123 * @property {string} name
124 * @property {string} input
125 * @property {RawSourceMap | undefined} inputSourceMap
126 * @property {{ implementation: MinimizerImplementation<T>, options: MinimizerOptions<T> }} minimizer
127 */
128
129/**
130 * @typedef InternalResult
131 * @property {Array<{ code: string, map: RawSourceMap | undefined }>} outputs
132 * @property {Array<Warning | WarningObject | string>} warnings
133 * @property {Array<Error | ErrorObject | string>} errors
134 */
135
136/** @typedef {undefined | boolean | number} Parallel */
137
138/** @typedef {RegExp | string} Rule */
139
140/** @typedef {Rule[] | Rule} Rules */
141
142/** @typedef {(warning: Warning | WarningObject | string, file: string, source?: string) => boolean} WarningsFilter */
143
144/**
145 * @typedef {Object} BasePluginOptions
146 * @property {Rules} [test]
147 * @property {Rules} [include]
148 * @property {Rules} [exclude]
149 * @property {WarningsFilter} [warningsFilter]
150 * @property {Parallel} [parallel]
151 */
152
153/**
154 * @template T
155 * @typedef {JestWorker & { transform: (options: string) => InternalResult, minify: (options: InternalOptions<T>) => InternalResult }} MinimizerWorker
156 */
157
158/**
159 * @typedef{ProcessOptions | { from?: string, to?: string, parser?: string | Syntax | Parser, stringifier?: string | Syntax | Stringifier, syntax?: string | Syntax } } ProcessOptionsExtender
160 */
161
162/**
163 * @typedef {CssNanoOptions & { processorOptions?: ProcessOptionsExtender }} CssNanoOptionsExtended
164 */
165
166/**
167 * @template T
168 * @typedef {T extends CssNanoOptionsExtended ? { minify?: MinimizerImplementation<T> | undefined, minimizerOptions?: MinimizerOptions<T> | undefined } : { minify: MinimizerImplementation<T>, minimizerOptions?: MinimizerOptions<T> | undefined }} DefinedDefaultMinimizerAndOptions
169 */
170
171/**
172 * @template T
173 * @typedef {BasePluginOptions & { minimizer: { implementation: MinimizerImplementation<T>, options: MinimizerOptions<T> } }} InternalPluginOptions
174 */
175
176
177const warningRegex = /\s.+:+([0-9]+):+([0-9]+)/;
178/**
179 * @template [T=CssNanoOptionsExtended]
180 */
181
182class CssMinimizerPlugin {
183 /**
184 * @param {BasePluginOptions & DefinedDefaultMinimizerAndOptions<T>} [options]
185 */
186 constructor(options) {
187 validate(
188 /** @type {Schema} */
189 schema, options || {}, {
190 name: "Css Minimizer Plugin",
191 baseDataPath: "options"
192 });
193 const {
194 minify =
195 /** @type {BasicMinimizerImplementation<T>} */
196 cssnanoMinify,
197 minimizerOptions =
198 /** @type {MinimizerOptions<T>} */
199 {},
200 test = /\.css(\?.*)?$/i,
201 warningsFilter = () => true,
202 parallel = true,
203 include,
204 exclude
205 } = options || {};
206 /**
207 * @private
208 * @type {InternalPluginOptions<T>}
209 */
210
211 this.options = {
212 test,
213 warningsFilter,
214 parallel,
215 include,
216 exclude,
217 minimizer: {
218 implementation:
219 /** @type {MinimizerImplementation<T>} */
220 minify,
221 options: minimizerOptions
222 }
223 };
224 }
225 /**
226 * @private
227 * @param {any} input
228 * @returns {boolean}
229 */
230
231
232 static isSourceMap(input) {
233 // All required options for `new SourceMapConsumer(...options)`
234 // https://github.com/mozilla/source-map#new-sourcemapconsumerrawsourcemap
235 return Boolean(input && input.version && input.sources && Array.isArray(input.sources) && typeof input.mappings === "string");
236 }
237 /**
238 * @private
239 * @param {Warning | WarningObject | string} warning
240 * @param {string} file
241 * @param {WarningsFilter} [warningsFilter]
242 * @param {SourceMapConsumer} [sourceMap]
243 * @param {Compilation["requestShortener"]} [requestShortener]
244 * @returns {Error & { hideStack?: boolean, file?: string } | undefined}
245 */
246
247
248 static buildWarning(warning, file, warningsFilter, sourceMap, requestShortener) {
249 let warningMessage = typeof warning === "string" ? warning : `${warning.plugin ? `[${warning.plugin}] ` : ""}${warning.text || warning.message}`;
250 let locationMessage = "";
251 let source;
252
253 if (sourceMap) {
254 let line;
255 let column;
256
257 if (typeof warning === "string") {
258 const match = warningRegex.exec(warning);
259
260 if (match) {
261 line = +match[1];
262 column = +match[2];
263 }
264 } else {
265 ({
266 line,
267 column
268 } =
269 /** @type {WarningObject} */
270 warning);
271 }
272
273 if (line && column) {
274 const original = sourceMap.originalPositionFor({
275 line,
276 column
277 });
278
279 if (original && original.source && original.source !== file && requestShortener) {
280 ({
281 source
282 } = original);
283 warningMessage = `${warningMessage.replace(warningRegex, "")}`;
284 locationMessage = `${requestShortener.shorten(original.source)}:${original.line}:${original.column}`;
285 }
286 }
287 }
288
289 if (warningsFilter && !warningsFilter(warning, file, source)) {
290 return;
291 }
292 /**
293 * @type {Error & { hideStack?: boolean, file?: string }}
294 */
295
296
297 const builtWarning = new Error(`${file} from Css Minimizer plugin\n${warningMessage}${locationMessage ? ` ${locationMessage}` : ""}`);
298 builtWarning.name = "Warning";
299 builtWarning.hideStack = true;
300 builtWarning.file = file; // eslint-disable-next-line consistent-return
301
302 return builtWarning;
303 }
304 /**
305 * @private
306 * @param {Error | ErrorObject | string} error
307 * @param {string} file
308 * @param {SourceMapConsumer} [sourceMap]
309 * @param {Compilation["requestShortener"]} [requestShortener]
310 * @returns {Error}
311 */
312
313
314 static buildError(error, file, sourceMap, requestShortener) {
315 /**
316 * @type {Error & { file?: string }}
317 */
318 let builtError;
319
320 if (typeof error === "string") {
321 builtError = new Error(`${file} from Css Minimizer plugin\n${error}`);
322 builtError.file = file;
323 return builtError;
324 }
325
326 if (
327 /** @type {ErrorObject} */
328 error.line &&
329 /** @type {ErrorObject} */
330 error.column) {
331 const {
332 line,
333 column
334 } =
335 /** @type {ErrorObject & { line: number, column: number }} */
336 error;
337 const original = sourceMap && sourceMap.originalPositionFor({
338 line,
339 column
340 });
341
342 if (original && original.source && requestShortener) {
343 builtError = new Error(`${file} from Css Minimizer plugin\n${error.message} [${requestShortener.shorten(original.source)}:${original.line},${original.column}][${file}:${line},${column}]${error.stack ? `\n${error.stack.split("\n").slice(1).join("\n")}` : ""}`);
344 builtError.file = file;
345 return builtError;
346 }
347
348 builtError = new Error(`${file} from Css Minimizer plugin\n${error.message} [${file}:${line},${column}]${error.stack ? `\n${error.stack.split("\n").slice(1).join("\n")}` : ""}`);
349 builtError.file = file;
350 return builtError;
351 }
352
353 if (error.stack) {
354 builtError = new Error(`${file} from Css Minimizer plugin\n${error.stack}`);
355 builtError.file = file;
356 return builtError;
357 }
358
359 builtError = new Error(`${file} from Css Minimizer plugin\n${error.message}`);
360 builtError.file = file;
361 return builtError;
362 }
363 /**
364 * @private
365 * @param {Parallel} parallel
366 * @returns {number}
367 */
368
369
370 static getAvailableNumberOfCores(parallel) {
371 // In some cases cpus() returns undefined
372 // https://github.com/nodejs/node/issues/19022
373 const cpus = os.cpus() || {
374 length: 1
375 };
376 return parallel === true ? cpus.length - 1 : Math.min(Number(parallel) || 0, cpus.length - 1);
377 }
378 /**
379 * @private
380 * @param {Compiler} compiler
381 * @param {Compilation} compilation
382 * @param {Record<string, import("webpack").sources.Source>} assets
383 * @param {{availableNumberOfCores: number}} optimizeOptions
384 * @returns {Promise<void>}
385 */
386
387
388 async optimize(compiler, compilation, assets, optimizeOptions) {
389 const cache = compilation.getCache("CssMinimizerWebpackPlugin");
390 let numberOfAssetsForMinify = 0;
391 const assetsForMinify = await Promise.all(Object.keys(typeof assets === "undefined" ? compilation.assets : assets).filter(name => {
392 const {
393 info
394 } =
395 /** @type {Asset} */
396 compilation.getAsset(name);
397
398 if ( // Skip double minimize assets from child compilation
399 info.minimized) {
400 return false;
401 }
402
403 if (!compiler.webpack.ModuleFilenameHelpers.matchObject.bind( // eslint-disable-next-line no-undefined
404 undefined, this.options)(name)) {
405 return false;
406 }
407
408 return true;
409 }).map(async name => {
410 const {
411 info,
412 source
413 } =
414 /** @type {Asset} */
415 compilation.getAsset(name);
416 const eTag = cache.getLazyHashedEtag(source);
417 const cacheItem = cache.getItemCache(name, eTag);
418 const output = await cacheItem.getPromise();
419
420 if (!output) {
421 numberOfAssetsForMinify += 1;
422 }
423
424 return {
425 name,
426 info,
427 inputSource: source,
428 output,
429 cacheItem
430 };
431 }));
432
433 if (assetsForMinify.length === 0) {
434 return;
435 }
436 /** @type {undefined | (() => MinimizerWorker<T>)} */
437
438
439 let getWorker;
440 /** @type {undefined | MinimizerWorker<T>} */
441
442 let initializedWorker;
443 /** @type {undefined | number} */
444
445 let numberOfWorkers;
446
447 if (optimizeOptions.availableNumberOfCores > 0) {
448 // Do not create unnecessary workers when the number of files is less than the available cores, it saves memory
449 numberOfWorkers = Math.min(numberOfAssetsForMinify, optimizeOptions.availableNumberOfCores);
450
451 getWorker = () => {
452 if (initializedWorker) {
453 return initializedWorker;
454 }
455
456 initializedWorker =
457 /** @type {MinimizerWorker<T>} */
458 new Worker(require.resolve("./minify"), {
459 numWorkers: numberOfWorkers,
460 enableWorkerThreads: true
461 }); // https://github.com/facebook/jest/issues/8872#issuecomment-524822081
462
463 const workerStdout = initializedWorker.getStdout();
464
465 if (workerStdout) {
466 workerStdout.on("data", chunk => process.stdout.write(chunk));
467 }
468
469 const workerStderr = initializedWorker.getStderr();
470
471 if (workerStderr) {
472 workerStderr.on("data", chunk => process.stderr.write(chunk));
473 }
474
475 return initializedWorker;
476 };
477 }
478
479 const {
480 SourceMapSource,
481 RawSource
482 } = compiler.webpack.sources;
483 const scheduledTasks = [];
484
485 for (const asset of assetsForMinify) {
486 scheduledTasks.push(async () => {
487 const {
488 name,
489 inputSource,
490 cacheItem
491 } = asset;
492 let {
493 output
494 } = asset;
495
496 if (!output) {
497 let input;
498 /** @type {RawSourceMap | undefined} */
499
500 let inputSourceMap;
501 const {
502 source: sourceFromInputSource,
503 map
504 } = inputSource.sourceAndMap();
505 input = sourceFromInputSource;
506
507 if (map) {
508 if (!CssMinimizerPlugin.isSourceMap(map)) {
509 compilation.warnings.push(
510 /** @type {WebpackError} */
511 new Error(`${name} contains invalid source map`));
512 } else {
513 inputSourceMap =
514 /** @type {RawSourceMap} */
515 map;
516 }
517 }
518
519 if (Buffer.isBuffer(input)) {
520 input = input.toString();
521 }
522 /**
523 * @type {InternalOptions<T>}
524 */
525
526
527 const options = {
528 name,
529 input,
530 inputSourceMap,
531 minimizer: {
532 implementation: this.options.minimizer.implementation,
533 options: this.options.minimizer.options
534 }
535 };
536 let result;
537
538 try {
539 result = await (getWorker ? getWorker().transform(serialize(options)) : minify(options));
540 } catch (error) {
541 const hasSourceMap = inputSourceMap && CssMinimizerPlugin.isSourceMap(inputSourceMap);
542 compilation.errors.push(
543 /** @type {WebpackError} */
544 CssMinimizerPlugin.buildError(
545 /** @type {any} */
546 error, name, hasSourceMap ? new SourceMapConsumer(
547 /** @type {RawSourceMap} */
548 inputSourceMap) : // eslint-disable-next-line no-undefined
549 undefined, // eslint-disable-next-line no-undefined
550 hasSourceMap ? compilation.requestShortener : undefined));
551 return;
552 }
553
554 output = {
555 warnings: [],
556 errors: []
557 };
558
559 for (const item of result.outputs) {
560 if (item.map) {
561 let originalSource;
562 let innerSourceMap;
563
564 if (output.source) {
565 ({
566 source: originalSource,
567 map: innerSourceMap
568 } = output.source.sourceAndMap());
569 } else {
570 originalSource = input;
571 innerSourceMap = inputSourceMap;
572 } // TODO need API for merging source maps in `webpack-source`
573
574
575 output.source = new SourceMapSource(item.code, name, item.map, originalSource, innerSourceMap, true);
576 } else {
577 output.source = new RawSource(item.code);
578 }
579 }
580
581 if (result.errors && result.errors.length > 0) {
582 const hasSourceMap = inputSourceMap && CssMinimizerPlugin.isSourceMap(inputSourceMap);
583
584 for (const error of result.errors) {
585 output.warnings.push(CssMinimizerPlugin.buildError(error, name, hasSourceMap ? new SourceMapConsumer(
586 /** @type {RawSourceMap} */
587 inputSourceMap) : // eslint-disable-next-line no-undefined
588 undefined, // eslint-disable-next-line no-undefined
589 hasSourceMap ? compilation.requestShortener : undefined));
590 }
591 }
592
593 if (result.warnings && result.warnings.length > 0) {
594 const hasSourceMap = inputSourceMap && CssMinimizerPlugin.isSourceMap(inputSourceMap);
595
596 for (const warning of result.warnings) {
597 const buildWarning = CssMinimizerPlugin.buildWarning(warning, name, this.options.warningsFilter, hasSourceMap ? new SourceMapConsumer(
598 /** @type {RawSourceMap} */
599 inputSourceMap) : // eslint-disable-next-line no-undefined
600 undefined, // eslint-disable-next-line no-undefined
601 hasSourceMap ? compilation.requestShortener : undefined);
602
603 if (buildWarning) {
604 output.warnings.push(buildWarning);
605 }
606 }
607 }
608
609 await cacheItem.storePromise({
610 source: output.source,
611 warnings: output.warnings,
612 errors: output.errors
613 });
614 }
615
616 if (output.warnings && output.warnings.length > 0) {
617 for (const warning of output.warnings) {
618 compilation.warnings.push(warning);
619 }
620 }
621
622 if (output.errors && output.errors.length > 0) {
623 for (const error of output.errors) {
624 compilation.errors.push(error);
625 }
626 }
627
628 const newInfo = {
629 minimized: true
630 };
631 const {
632 source
633 } = output;
634 compilation.updateAsset(name, source, newInfo);
635 });
636 }
637
638 const limit = getWorker && numberOfAssetsForMinify > 0 ?
639 /** @type {number} */
640 numberOfWorkers : scheduledTasks.length;
641 await throttleAll(limit, scheduledTasks);
642
643 if (initializedWorker) {
644 await initializedWorker.end();
645 }
646 }
647 /**
648 * @param {Compiler} compiler
649 * @returns {void}
650 */
651
652
653 apply(compiler) {
654 const pluginName = this.constructor.name;
655 const availableNumberOfCores = CssMinimizerPlugin.getAvailableNumberOfCores(this.options.parallel);
656 compiler.hooks.compilation.tap(pluginName, compilation => {
657 compilation.hooks.processAssets.tapPromise({
658 name: pluginName,
659 stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
660 additionalAssets: true
661 }, assets => this.optimize(compiler, compilation, assets, {
662 availableNumberOfCores
663 }));
664 compilation.hooks.statsPrinter.tap(pluginName, stats => {
665 stats.hooks.print.for("asset.info.minimized").tap("css-minimizer-webpack-plugin", (minimized, {
666 green,
667 formatFlag
668 }) => // eslint-disable-next-line no-undefined
669 minimized ?
670 /** @type {Function} */
671 green(
672 /** @type {Function} */
673 formatFlag("minimized")) : "");
674 });
675 });
676 }
677
678}
679
680CssMinimizerPlugin.cssnanoMinify = cssnanoMinify;
681CssMinimizerPlugin.cssoMinify = cssoMinify;
682CssMinimizerPlugin.cleanCssMinify = cleanCssMinify;
683CssMinimizerPlugin.esbuildMinify = esbuildMinify;
684CssMinimizerPlugin.parcelCssMinify = parcelCssMinify;
685module.exports = CssMinimizerPlugin;
Note: See TracBrowser for help on using the repository browser.