Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
2535 lines (2213 loc) · 90.7 KB
/
Copy pathindex.js
File metadata and controls
2535 lines (2213 loc) · 90.7 KB
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const crypto = require("crypto");
const os = require("os");
const path = require("path");
const { minify } = require("./minify");
const {
cleanCssMinify,
compress,
cssnanoMinify,
cssoMinify,
esbuildMinify,
esbuildMinifyCss,
getEcmaVersion,
getMinimizerOptionsAt,
htmlMinifierTerser,
imageminGenerate,
imageminMinify,
imageminNormalizeConfig,
interpolateSize,
isDescriptor,
isPresets,
jsonMinify,
lightningCssMinify,
memoize,
minifyHtmlNode,
napiRsImageMinify,
normalizeMinimizers,
readPreset,
sharpGenerate,
sharpMinify,
svgoMinify,
swcMinify,
swcMinifyCss,
swcMinifyHtml,
swcMinifyHtmlFragment,
terserMinify,
throttleAll,
uglifyJsMinify,
} = require("./utils");
/** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
/** @typedef {import("webpack").Compiler} Compiler */
/** @typedef {import("webpack").Compilation} Compilation */
/** @typedef {import("webpack").Asset} Asset */
/** @typedef {import("webpack").AssetInfo} AssetInfo */
/** @typedef {import("webpack").TemplatePath} TemplatePath */
/** @typedef {import("jest-worker").Worker} JestWorker */
/** @typedef {import("@jridgewell/trace-mapping").EncodedSourceMap & { sources: string[], sourcesContent?: string[], file: string }} RawSourceMap */
/** @typedef {import("@jridgewell/trace-mapping").TraceMap} TraceMap */
/** @typedef {RegExp | string} Rule */
/** @typedef {Rule[] | Rule} Rules */
// eslint-disable-next-line jsdoc/reject-any-type
/** @typedef {any} EXPECTED_ANY */
// eslint-disable-next-line jsdoc/require-property
/** @typedef {object} EXPECTED_OBJECT */
/**
* @callback ExtractCommentsFunction
* @param {EXPECTED_ANY} astNode ast Node
* @param {{ value: string, type: "comment1" | "comment2" | "comment3" | "comment4", pos: number, line: number, col: number }} comment comment node
* @returns {boolean} true when need to extract comment, otherwise false
*/
/**
* @typedef {boolean | "all" | "some" | RegExp | ExtractCommentsFunction} ExtractCommentsCondition
*/
/**
* @typedef {TemplatePath} ExtractCommentsFilename
*/
/**
* @typedef {boolean | string | ((commentsFile: string) => string)} ExtractCommentsBanner
*/
/**
* @typedef {object} ExtractCommentsObject
* @property {ExtractCommentsCondition=} condition condition which comments need to be expected
* @property {ExtractCommentsFilename=} filename filename for extracted comments
* @property {ExtractCommentsBanner=} banner banner in filename for extracted comments
*/
/**
* @typedef {ExtractCommentsCondition | ExtractCommentsObject} ExtractCommentsOptions
*/
/**
* @typedef {object} ErrorObject
* @property {string} message message
* @property {number=} line line number
* @property {number=} column column number
* @property {string=} stack error stack trace
*/
/**
* What one embedded source is and where it is going, as
* `renderEmbeddedSource` describes it.
* @typedef {object} EmbeddedSourceInfo
* @property {string} type the embedded source's language, e.g. `"css"`
* @property {string} hostType the language of the output it is embedded in
* @property {import("webpack").Module} module the module being generated
*/
/**
* The two hooks webpack >= 5.110 adds. Declared here rather than read off
* `Compilation`: the plugin supports webpack `^5.1.0`, whose types have
* neither, and it does nothing at all where they are absent.
* @typedef {object} EmbeddedSourceHooks
* @property {{ tapPromise: (name: string, fn: (source: import("webpack").sources.Source, info: EmbeddedSourceInfo) => Promise<import("webpack").sources.Source>) => void }=} renderEmbeddedSource offers each embedded source before it is embedded
* @property {{ tap: (name: string, fn: (module: import("webpack").Module, hash: { update: (data: string) => void }) => void) => void }=} embeddedSourceHash hashes what a `renderEmbeddedSource` tap varies on
*/
/**
* What the loaders produced for one module, as `processResult` hands it over.
* @typedef {[string | Buffer, string | RawSourceMap | undefined, EXPECTED_ANY]} LoaderResult
*/
/**
* The `NormalModule` hook this plugin generates through. Declared here for the
* same reason as `EmbeddedSourceHooks`: it can await only from webpack 5.111,
* and the supported range's types still describe it as synchronous.
* @typedef {object} AwaitableModuleHooks
* @property {{ tapPromise: (name: string, fn: (result: LoaderResult, module: import("webpack").NormalModule) => Promise<LoaderResult>) => void }} processResult offers each module's own bytes as it is built
*/
/**
* @typedef {object} MinimizedResult
* @property {(string | Buffer)=} code code — a `Buffer` from a minimizer that declares `supportsBinary`
* @property {string=} filename the name the result should carry, when re-encoding it changed what the bytes are. Only the `generate` path can honour it: an asset is named while its module is built, before anything downstream refers to it
* @property {number=} width what the result is now wide, where re-encoding knows it. `[width]` in an `asset` generator's `filename` reads it
* @property {number=} height what the result is now tall, where re-encoding knows it
* @property {RawSourceMap=} map source map
* @property {(Error | string)[]=} errors errors
* @property {(Error | string)[]=} warnings warnings
* @property {string[]=} extractedComments extracted comments
*/
/**
* @typedef {{ [file: string]: string | Buffer }} Input
*/
/**
* @typedef {{ [key: string]: EXPECTED_ANY }} CustomOptions
*/
/**
* @template T
* @typedef {T extends infer U ? U : CustomOptions} InferDefaultType
*/
/**
* @template T
* @typedef {T extends EXPECTED_ANY[] ? { [P in keyof T]?: T[P] & InferDefaultType<T[P]> } : T & InferDefaultType<T>} MinimizerOptions
*/
/**
* @template T
* @callback BasicMinimizerImplementation
* @param {Input} input
* @param {RawSourceMap | undefined} sourceMap
* @param {MinimizerOptions<T>} minifyOptions
* @param {ExtractCommentsOptions | undefined} extractComments
* @returns {Promise<MinimizedResult> | MinimizedResult}
*/
/**
* @typedef {object} MinimizeFunctionHelpers
* @property {() => string | undefined=} getMinimizerVersion function that returns version of minimizer
* @property {() => boolean | undefined=} supportsWorkerThreads true when minimizer support worker threads, otherwise false
* @property {() => boolean | undefined=} supportsWorker true when minimizer support worker, otherwise false
* @property {() => boolean | undefined=} supportsBinary true when the minimizer takes the asset's bytes rather than its text — an image minimizer. Its input reaches it as a `Buffer` and its `code` may be one. Only when every minimizer an asset is dispatched to declares it, since one that does not could not read the bytes
* @property {(name: string, info?: AssetInfo) => boolean | undefined=} filter return true when the minimizer supports the asset, otherwise false. When an array of minimizers is configured, each asset is dispatched only to the minimizers whose `filter` accepts it. Assets rejected by every minimizer in the array are skipped entirely.
* @property {() => string[] | undefined=} getTypes the languages this minimizer minifies, e.g. `["css"]`. Source that carries no filename — what a module embeds in another language's output — is dispatched by this rather than by `test` / `filter`, and a minimizer that declares nothing is never handed any
* @property {(minimizerOptions?: EXPECTED_OBJECT) => string[] | undefined=} getEmbeddedTypes the languages this minimizer can hand out from inside what it minifies, through the `renderEmbeddedSource` option. Empty (or absent) means it nests nothing a caller can reach, and the option is not passed
* @property {(compilation: typeof import("webpack").Compilation) => number | undefined=} getStage which `processAssets` stage this minimizer has to run in, named off the `Compilation` it is handed — compressing reads the bytes a user downloads, so it asks for `PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER`. Each runs where it asks, chaining through the asset a later pass reads back, and one asking for nothing runs where minifying belongs — after the bundle is rendered and before its hashes are taken
* @property {() => string | undefined=} getAssetFlag the name this function's work goes under in the asset's info, which is what the asset it wrote is marked with and what stats print. `compress` says `compressed`, another encoding of the bytes being no smaller a version of them; a minimizer saying nothing minified the asset, so `minimized`, and a generator saying nothing wrote a new file, so `generated`. It is also what is not run twice: an asset already marked with every name a function writes is declined, which is how a minified asset a child compilation handed up is left alone
*/
/**
* @template T
* @typedef {T extends EXPECTED_ANY[] ? { [P in keyof T]: BasicMinimizerImplementation<T[P]> & MinimizeFunctionHelpers } : BasicMinimizerImplementation<T> & MinimizeFunctionHelpers} MinimizerImplementation
*/
/**
* @template T
* @typedef {object} InternalOptions
* @property {string} name name
* @property {string | Buffer} input input — bytes for a minimizer that declares `supportsBinary`
* @property {RawSourceMap | undefined} inputSourceMap input source map
* @property {ExtractCommentsOptions | undefined} extractComments extract comments option
* @property {{ implementation: MinimizerImplementation<T>, options: MinimizerOptions<T> }} minimizer minimizer
* @property {{ implementation: MinimizerImplementation<T>, options: MinimizerOptions<T>, claims: string[][], offers: string[][], at: number[] }=} embedded every configured minimizer, for source one language embeds in another: it carries no filename, so `minimizer` — which holds only what this asset's name matched — is not the set to dispatch it across. `claims` is the languages each minifies and `offers` the languages each can hand out, both as data and both parallel to `implementation`, since a minify function reaches a worker as source and carries none of its properties; `at` says which of them `minimizer` holds. Absent when no nested language is reachable at all
* @property {boolean=} module true when code is a EC module, otherwise false
* @property {number | string=} ecma ecma version
*/
/**
* @template T
* @typedef {JestWorker & { transform: (options: string) => Promise<MinimizedResult>, minify: (options: InternalOptions<T>) => Promise<MinimizedResult> }} MinimizerWorker
*/
/**
* @typedef {undefined | boolean | number} Parallel
*/
/**
* One generator, written as an object stating how to run it.
* @typedef {object} GeneratorDescriptor
* @property {MinimizerImplementation<EXPECTED_ANY>} implementation the generator itself
* @property {MinimizerOptions<EXPECTED_ANY>=} options options for this generator, preferred over the deprecated `generatorOptions`
* @property {("import" | "asset")=} type `import` re-encodes a module as it is built, so the import that asked for it is renamed with it; `asset` writes a new file beside one already emitted
* @property {string=} filename name for the generated asset, as a webpack filename template. `asset` generators only
* @property {((name: string) => boolean)=} filter decides per asset whether to generate from it, on top of `test`/`include`/`exclude`
* @property {boolean=} deleteOriginalAssets removes the asset generated from. `asset` generators only
* @property {number=} threshold generate only from assets larger than this, in bytes. `asset` generators only
* @property {number=} minRatio keep the generated asset only when it is this much smaller than the one it was read from. `asset` generators only
* @property {(string | false)=} relatedName the key the generated asset is recorded under in the original's `related` info. `asset` generators only
*/
/**
* What `generate` may be written as: one generator, a list of them, a
* descriptor, or an object naming descriptors an asset asks for with `?as=`.
* @typedef {MinimizerImplementation<EXPECTED_ANY> | MinimizerImplementation<EXPECTED_ANY>[] | GeneratorDescriptor | { [preset: string]: MinimizerImplementation<EXPECTED_ANY> | MinimizerImplementation<EXPECTED_ANY>[] | GeneratorDescriptor }} Generate
*/
/**
* @typedef {object} BasePluginOptions
* @property {Rules=} test test rule
* @property {Rules=} include include rile
* @property {Rules=} exclude exclude rule
* @property {ExtractCommentsOptions=} extractComments extract comments options
* @property {Parallel=} parallel parallel option
* @property {Generate=} generate rewrites a module's own bytes as it is built, so a re-encoding can rename the asset, or writes a new file beside one already emitted
* @property {MinimizerOptions<EXPECTED_ANY>=} generatorOptions options for `generate`
*/
/**
* @template T
* @typedef {T extends import("terser").MinifyOptions ? { minify?: MinimizerImplementation<T> | undefined, minimizerOptions?: MinimizerOptions<T> | undefined, terserOptions?: MinimizerOptions<T> | undefined } : { minify: MinimizerImplementation<T>, minimizerOptions?: MinimizerOptions<T> | undefined, terserOptions?: MinimizerOptions<T> | undefined }} DefinedDefaultMinimizerAndOptions
*/
/**
* @template T
* @typedef {BasePluginOptions & { minimizer: { implementation: MinimizerImplementation<T>, options: MinimizerOptions<T>, filters?: (((name: string, info: AssetInfo) => boolean | undefined) | undefined)[] }, generator?: { implementation: MinimizerImplementation<T>, options: MinimizerOptions<T> } }} InternalPluginOptions
*/
/**
* The `processAssets` stage a minimizer or generator asks for, which is the
* latest of them where several run as one chain.
* @param {Compiler} compiler compiler
* @param {EXPECTED_ANY} implementation one implementation, or an array of them
* @returns {number | undefined} the stage, or undefined where none asks
*/
const declaredStage = (compiler, implementation) => {
const each = Array.isArray(implementation)
? implementation
: [implementation];
let latest;
for (const one of each) {
const asked =
one && typeof one.getStage === "function"
? one.getStage(compiler.webpack.Compilation)
: undefined;
if (
typeof asked === "number" &&
(typeof latest !== "number" || asked > latest)
) {
latest = asked;
}
}
return latest;
};
/**
* The name a chunk's JavaScript asset will take, as far as it is knowable
* while the hash that name contains is still being computed.
* @param {Compilation} compilation compilation
* @param {import("webpack").Chunk} chunk chunk
* @returns {string | undefined} the name, or undefined where a function names it
*/
const chunkAssetName = (compilation, chunk) => {
const { outputOptions } = compilation;
const template =
chunk.filenameTemplate ||
(chunk.canBeInitial()
? outputOptions.filename
: outputOptions.chunkFilename);
if (typeof template !== "string") {
return undefined;
}
// Every placeholder stands for text it has not got yet: what is being asked
// of the name is its path and extension, which none of them carries.
return template
.replace(/\[(?:full|chunk|content)hash(?::\d+)?]/gi, "0")
.replace(/\[name]/gi, String(chunk.name || chunk.id))
.replace(/\[id]/gi, String(chunk.id))
.replace(/\[runtime]/gi, String(chunk.runtime));
};
/**
* The names an implementation's work goes under in an asset's info, which is
* the union where several ran as one chain.
* @param {EXPECTED_ANY} implementation one implementation, or an array of them
* @param {string} fallback the name to use where none says
* @returns {string[]} the names
*/
const declaredFlags = (implementation, fallback) => {
const each = Array.isArray(implementation)
? implementation
: [implementation];
/** @type {string[]} */
const names = [];
for (const one of each) {
const says =
one && typeof one.getAssetFlag === "function"
? one.getAssetFlag()
: undefined;
if (typeof says === "string" && says && !names.includes(says)) {
names.push(says);
}
}
return names.length > 0 ? names : [fallback];
};
/**
* Whether an asset is already marked with every name a function writes,
* counting only what this plugin did not mark it with itself.
* @param {Record<string, EXPECTED_ANY>} says what the asset says about itself
* @param {Set<string> | undefined} written what this plugin marked it with
* @param {string[]} flags the names the function writes
* @returns {boolean} true when it has been through this already
*/
const saysAlready = (says, written, flags) => {
for (const flag of flags) {
if (!says[flag] || (written && written.has(flag))) {
return false;
}
}
return true;
};
const VALIDATION_CONFIGURATION = {
name: "Minimizer Plugin",
baseDataPath: "options",
};
const getTraceMapping = memoize(() => require("@jridgewell/trace-mapping"));
const getSerializeJavascript = memoize(() => require("./serialize-javascript"));
/**
* @template [T=import("terser").MinifyOptions]
*/
class MinimizerPlugin {
/**
* @param {BasePluginOptions & DefinedDefaultMinimizerAndOptions<T>=} options options
*/
constructor(options) {
// Kept for `apply()`, which is where validation runs now: webpack owns when
// it happens, and skips it entirely for `validate: false`.
/**
* @private
* @type {BasePluginOptions & DefinedDefaultMinimizerAndOptions<T>}
*/
this.rawOptions =
/** @type {BasePluginOptions & DefinedDefaultMinimizerAndOptions<T>} */
(options || {});
// TODO handle json and etc in the next major release
// TODO make `minimizer` option instead `minify` and `terserOptions` in the next major release, also rename `terserMinify` to `terserMinimize`
const {
minify: declaredMinify,
minimizerOptions,
terserOptions,
test: declaredTest,
extractComments = true,
parallel = true,
include,
exclude,
generate,
generatorOptions,
} = this.rawOptions;
// The JavaScript minifier and the names it reads are what this plugin is,
// so both stand whether or not a generator was configured too.
const minimizers =
typeof declaredMinify !== "undefined"
? declaredMinify
: /** @type {MinimizerImplementation<T>} */ (
/** @type {unknown} */ (terserMinify)
);
const test =
typeof declaredTest !== "undefined" ? declaredTest : /\.[cm]?js(\?.*)?$/i;
// `terserOptions` is a deprecated alias of `minimizerOptions`; prefer the
// new name when both are provided.
const resolvedMinimizerOptions =
/** @type {MinimizerOptions<T>} */
(
typeof minimizerOptions !== "undefined"
? minimizerOptions
: terserOptions || {}
);
/**
* @private
* @type {InternalPluginOptions<T>}
*/
this.options = {
test,
extractComments,
parallel,
include,
exclude,
minimizer:
/** @type {{ implementation: MinimizerImplementation<T>, options: MinimizerOptions<T>, filters?: (((name: string, info: AssetInfo) => boolean | undefined) | undefined)[] }} */
(normalizeMinimizers(minimizers, resolvedMinimizerOptions)),
// Absent unless asked for: it runs while modules build, where the plugin
// otherwise does nothing.
generator: generate
? {
implementation:
/** @type {MinimizerImplementation<T>} */
(/** @type {unknown} */ (generate)),
options:
/** @type {MinimizerOptions<T>} */
(/** @type {unknown} */ (generatorOptions || {})),
}
: undefined,
};
}
/**
* @private
* @param {unknown} input Input to check
* @returns {boolean} Whether input is a source map
*/
static isSourceMap(input) {
// All required options for `new TraceMap(...options)`
// https://github.com/jridgewell/trace-mapping#usage
return Boolean(
input &&
typeof input === "object" &&
input !== null &&
"version" in input &&
"sources" in input &&
Array.isArray(input.sources) &&
"mappings" in input &&
typeof input.mappings === "string",
);
}
/**
* @private
* @param {unknown} warning warning
* @param {string} file file
* @returns {Error} built warning
*/
static buildWarning(warning, file) {
/**
* @type {Error & { hideStack: true, file: string }}
*/
// @ts-expect-error
const builtWarning = new Error(warning.toString());
builtWarning.name = "Warning";
builtWarning.hideStack = true;
builtWarning.file = file;
return builtWarning;
}
/**
* @private
* @param {Error | ErrorObject | string} error error
* @param {string} file file
* @param {TraceMap=} sourceMap source map
* @param {Compilation["requestShortener"]=} requestShortener request shortener
* @returns {Error} built error
*/
static buildError(error, file, sourceMap, requestShortener) {
/**
* @type {Error & { file?: string }}
*/
let builtError;
if (typeof error === "string") {
builtError = new Error(`${file} from minimizer-webpack-plugin\n${error}`);
builtError.file = file;
return builtError;
}
if (/** @type {ErrorObject} */ (error).line) {
const { line, column } =
/** @type {ErrorObject & { line: number, column: number }} */ (error);
const original =
sourceMap &&
getTraceMapping().originalPositionFor(sourceMap, {
line,
column,
});
if (original && original.source && requestShortener) {
builtError = new Error(
`${file} from minimizer-webpack-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")}`
: ""
}`,
);
builtError.file = file;
return builtError;
}
builtError = new Error(
`${file} from minimizer-webpack-plugin\n${error.message} [${file}:${line},${
column
}]${
error.stack ? `\n${error.stack.split("\n").slice(1).join("\n")}` : ""
}`,
);
builtError.file = file;
return builtError;
}
if (error.stack) {
builtError = new Error(
`${file} from minimizer-webpack-plugin\n${
typeof error.message !== "undefined" ? error.message : ""
}\n${error.stack}`,
);
builtError.file = file;
return builtError;
}
builtError = new Error(
`${file} from minimizer-webpack-plugin\n${error.message}`,
);
builtError.file = file;
return builtError;
}
/**
* @private
* @param {Parallel} parallel value of the `parallel` option
* @returns {number} number of cores for parallelism
*/
static getAvailableNumberOfCores(parallel) {
// In some cases cpus() returns undefined
// https://github.com/nodejs/node/issues/19022
const cpus =
// eslint-disable-next-line n/no-unsupported-features/node-builtins
typeof os.availableParallelism === "function"
? // eslint-disable-next-line n/no-unsupported-features/node-builtins
{ length: os.availableParallelism() }
: os.cpus() || { length: 1 };
return parallel === true || typeof parallel === "undefined"
? cpus.length - 1
: Math.min(parallel || 0, cpus.length - 1);
}
/**
* Whether `test`, `include` and `exclude` accept a name.
*
* An asset name carries the query and fragment of the request that made it
* — `output.assetModuleFilename` is `[hash][ext][query][fragment]` by
* default — so `test: /\.png$/` would match none of them. Both spellings
* are offered: a rule naming the file accepts it whatever it carries, and
* one naming the query still works.
* @private
* @param {Compiler} compiler compiler
* @param {string} name asset name, or a module's resource
* @returns {boolean} true when it is to be minified
*/
matchesName(compiler, name) {
const { matchPart } = compiler.webpack.ModuleFilenameHelpers;
const bare = name.replace(/[?#].*$/, "");
const { test, include, exclude } = this.options;
if (test && !matchPart(name, test) && !matchPart(bare, test)) {
return false;
}
if (include && !matchPart(name, include) && !matchPart(bare, include)) {
return false;
}
// Rejecting on either spelling, so naming the file excludes it whatever
// it carries and naming the query still excludes it.
return !(exclude && (matchPart(name, exclude) || matchPart(bare, exclude)));
}
/**
* @private
* @param {Compiler} compiler compiler
* @param {Compilation} compilation compilation
* @param {Record<string, import("webpack").sources.Source>} assets assets
* @param {{ availableNumberOfCores: number, only?: number[], cacheSuffix?: string, written: Map<string, Set<string>> }} optimizeOptions how many may run at once, which minimizers this pass runs, what keeps its cache apart from another pass over the same asset, and what an earlier pass of this plugin already wrote onto each asset
* @returns {Promise<void>}
*/
async optimize(compiler, compilation, assets, optimizeOptions) {
// The namespace is the name this plugin shipped under, and renaming it
// would throw away every warm pack for nothing a user can see.
const cache = compilation.getCache("TerserWebpackPlugin");
let numberOfAssets = 0;
/**
* @param {string} name asset name
* @returns {boolean} true when the asset is to be minified
*/
const matchesName = (name) => this.matchesName(compiler, name);
// Normalize the implementation list to an array so dispatch and the
// worker-pool capability checks below can iterate uniformly. The
// original shape on `this.options.minimizer.implementation` is preserved
// for chunk hashing.
const implementations = Array.isArray(this.options.minimizer.implementation)
? this.options.minimizer.implementation
: [this.options.minimizer.implementation];
// What each minimizer marks an asset with, asked once here rather than
// again for every asset it is offered.
const flagsByMinimizer = implementations.map((one) =>
declaredFlags(one, "minimized"),
);
// `additionalAssets` hands this pass whatever was emitted after it ran,
// this plugin's own generated files included, and those are not to minify.
const generated = this.generatedFlags();
/**
* Remember what this plugin marked an asset with, which is what a later
* pass of it reads back rather than declining.
* @param {string} name asset name
* @param {string[]} flags the names written
* @returns {void}
*/
const recordWritten = (name, flags) => {
let written = optimizeOptions.written.get(name);
if (!written) {
written = new Set();
optimizeOptions.written.set(name, written);
}
for (const flag of flags) {
written.add(flag);
}
};
/**
* Collect the indices of minimizers whose `filter` accepts `name`.
* Filters returning `undefined` are treated as accept (matches the
* convention used by `supportsWorkerThreads`).
* @param {string} name asset name
* @param {AssetInfo} info asset info
* @returns {number[]} indices into `implementations` that accept the asset
*/
const matchingMinimizers = (name, info) => {
const matched = [];
const { filters } = this.options.minimizer;
const written = optimizeOptions.written.get(name);
const says = /** @type {Record<string, EXPECTED_ANY>} */ (info);
for (let i = 0; i < implementations.length; i++) {
// A pass runs only the minimizers asking for its stage; the rest read
// this same asset at theirs.
if (optimizeOptions.only && !optimizeOptions.only.includes(i)) {
continue;
}
const impl = implementations[i];
// Skip double minimize assets from child compilation: one already
// saying what this minimizer writes has been through it. An earlier
// pass of this plugin is not that — those chain through the asset.
if (saysAlready(says, written, flagsByMinimizer[i])) {
continue;
}
// What `minify` states about this entry answers for it; the property on
// the function is what a minimizer says about itself, and is the
// fallback rather than a second filter to satisfy.
const filter =
filters && typeof filters[i] === "function"
? filters[i]
: impl.filter;
if (typeof filter !== "function" || filter(name, info) !== false) {
matched.push(i);
}
}
return matched;
};
/** @type {Map<string, number[]>} */
const matchedByName = new Map();
const assetsForMinify = await Promise.all(
Object.keys(assets)
.filter((name) => {
const { info } = /** @type {Asset} */ (compilation.getAsset(name));
// Skip minimizing for extracted comments assets
if (info.extractedComments) {
return false;
}
const says = /** @type {Record<string, EXPECTED_ANY>} */ (info);
if (generated.some((flag) => says[flag])) {
return false;
}
if (!matchesName(name)) {
return false;
}
// Compute the matching minimizers once and carry the result to the
// per-asset task via `matchedByName` so the regexes don't run again.
const matched = matchingMinimizers(name, info);
if (matched.length === 0) {
return false;
}
matchedByName.set(name, matched);
return true;
})
.map(async (name) => {
const { info, source } = /** @type {Asset} */ (
compilation.getAsset(name)
);
const eTag = cache.getLazyHashedEtag(source);
const cacheItem = cache.getItemCache(
`${name}${optimizeOptions.cacheSuffix || ""}`,
eTag,
);
const output = await cacheItem.getPromise();
if (!output) {
numberOfAssets += 1;
}
return {
name,
info,
inputSource: source,
output,
cacheItem,
matched: /** @type {number[]} */ (matchedByName.get(name)),
};
}),
);
if (assetsForMinify.length === 0) {
return;
}
/** @type {undefined | (() => MinimizerWorker<T>)} */
let getWorker;
/** @type {undefined | MinimizerWorker<T>} */
let initializedWorker;
/** @type {undefined | number} */
let numberOfWorkers;
// Per implementation rather than over all of them: an asset is dispatched
// only to the minimizers its name matched, so one that cannot run in a
// worker — an image minimizer, whose bytes have no way across — must not
// take the pool away from the JavaScript ones configured beside it.
const workerCapable = implementations.map(
(impl) =>
typeof impl.supportsWorker === "undefined" ||
(typeof impl.supportsWorker === "function" && impl.supportsWorker()),
);
const binaryCapable = implementations.map(
(impl) =>
typeof impl.supportsBinary === "function" && impl.supportsBinary(),
);
const needCreateWorker =
optimizeOptions.availableNumberOfCores > 0 &&
workerCapable.includes(true);
if (needCreateWorker) {
// Do not create unnecessary workers when the number of files is less than the available cores, it saves memory
numberOfWorkers = Math.min(
numberOfAssets,
optimizeOptions.availableNumberOfCores,
);
getWorker = () => {
if (initializedWorker) {
return initializedWorker;
}
const { Worker } = require("jest-worker");
initializedWorker =
/** @type {MinimizerWorker<T>} */
(
new Worker(require.resolve("./minify"), {
numWorkers: numberOfWorkers,
// Only what can reach the pool decides how it is run.
enableWorkerThreads: implementations.every(
(impl, i) =>
!workerCapable[i] ||
typeof impl.supportsWorkerThreads === "undefined" ||
impl.supportsWorkerThreads() !== false,
),
})
);
// https://github.com/facebook/jest/issues/8872#issuecomment-524822081
const workerStdout = initializedWorker.getStdout();
if (workerStdout) {
workerStdout.on("data", (chunk) => process.stdout.write(chunk));
}
const workerStderr = initializedWorker.getStderr();
if (workerStderr) {
workerStderr.on("data", (chunk) => process.stderr.write(chunk));
}
return initializedWorker;
};
}
const { SourceMapSource, ConcatSource, RawSource } =
compiler.webpack.sources;
/**
* @param {InternalOptions<T>} options what to minify
* @param {number[]} matched indices of the minimizers this asset is dispatched to
* @returns {Promise<MinimizedResult>} the result
*/
const run = (options, matched) =>
getWorker && matched.every((i) => workerCapable[i])
? getWorker().transform(getSerializeJavascript()(options))
: minify(options);
/** @typedef {{ extractedCommentsSource: import("webpack").sources.RawSource, commentsFilename: string }} ExtractedCommentsInfo */
/** @type {Map<string, ExtractedCommentsInfo>} */
const allExtractedComments = new Map();
const scheduledTasks = [];
for (const asset of assetsForMinify) {
scheduledTasks.push(async () => {
const { name, inputSource, info, cacheItem, matched } = asset;
let { output } = asset;
if (!output) {
let input;
/** @type {RawSourceMap | undefined} */
let inputSourceMap;
const { source: sourceFromInputSource, map } =
inputSource.sourceAndMap();
input = sourceFromInputSource;
if (map) {
if (!MinimizerPlugin.isSourceMap(map)) {
compilation.warnings.push(
new Error(`${name} contains invalid source map`),
);
} else {
inputSourceMap = /** @type {RawSourceMap} */ (map);
}
}
// Only a minimizer that says it reads bytes gets them: every other
// one is handed the text it has always been handed.
if (
Buffer.isBuffer(input) &&
!matched.every((i) => binaryCapable[i])
) {
input = input.toString();
}
// Dispatch to only the minimizers whose `filter` accepted this
// asset (computed once when collecting `assetsForMinify`).
// `minify.js` already normalizes a single implementation into a
// one-element array, so we always hand it the matching subset.
// Options are sliced as references — `minify.js` overlays
// `module`/`ecma` without mutating the caller's object.
const assetImplementation =
/** @type {MinimizerImplementation<T>} */
(matched.map((i) => implementations[i]));
const sourceOptions = this.options.minimizer.options;
const assetMinimizerOptions =
/** @type {MinimizerOptions<T>} */
(
Array.isArray(sourceOptions)
? matched.map((i) => sourceOptions[i] || {})
: sourceOptions
);
/**
* @type {InternalOptions<T>}
*/
const options = {
name,
input,
inputSourceMap,
minimizer: {
implementation: assetImplementation,
options: assetMinimizerOptions,
},
extractComments: this.options.extractComments,
embedded: this.embeddedMinimizer(matched),
};
if (typeof info.javascriptModule !== "undefined") {
options.module = info.javascriptModule;
} else if (/\.mjs(\?.*)?$/i.test(name)) {
options.module = true;
} else if (/\.cjs(\?.*)?$/i.test(name)) {
options.module = false;
}
options.ecma = getEcmaVersion(compiler.options.output.environment);
try {
output = await run(options, matched);
} catch (error) {
const hasSourceMap =
inputSourceMap && MinimizerPlugin.isSourceMap(inputSourceMap);
compilation.errors.push(
MinimizerPlugin.buildError(
/** @type {Error | ErrorObject | string} */
(error),
name,
hasSourceMap
? new (getTraceMapping().TraceMap)(
/** @type {RawSourceMap} */
(inputSourceMap),
)
: undefined,
hasSourceMap ? compilation.requestShortener : undefined,
),
);
return;
}
if (typeof output.code === "undefined") {
compilation.errors.push(
new Error(
`${name} from minimizer-webpack-plugin\nMinimizer doesn't return result`,
),
);
}
if (output.warnings && output.warnings.length > 0) {
output.warnings = output.warnings.map(
/**
* @param {Error | string} item a warning
* @returns {Error} built warning with extra info
*/
(item) => MinimizerPlugin.buildWarning(item, name),
);
}
if (output.errors && output.errors.length > 0) {
const hasSourceMap =
inputSourceMap && MinimizerPlugin.isSourceMap(inputSourceMap);
output.errors = output.errors.map(
/**
* @param {Error | string} item an error
* @returns {Error} built error with extra info
*/
(item) =>
MinimizerPlugin.buildError(