-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·1251 lines (1102 loc) · 49.4 KB
/
Copy pathcli.js
File metadata and controls
executable file
·1251 lines (1102 loc) · 49.4 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
#!/usr/bin/env node
/**
* html-minifier-next CLI tool
*
* MIT License
*
* Copyright 2014–2016 Zoltan Frombach
* Copyright Juriy “kangax” Zaytsev
* Copyright 2025 Jens Oliver Meiert
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
import fs from 'fs';
import path from 'path';
import { pathToFileURL } from 'url';
import os from 'os';
import readline from 'readline';
import { Command, Option } from 'commander';
/** @param {string} str */
const camelCase = (str) => paramCase(str).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
// Commander derives its internal option key by applying paramCase then camelCase to the flag name,
// stripping a leading `no-` first for negated flags (e.g., `--no-foo-bar` → `fooBar`);
// because option definition keys may differ from the result of that round-trip (e.g.,
// `minifyURLs` → Commander key `minifyUrls`, `noNewlinesBeforeTagClose` → `newlinesBeforeTagClose`),
// `commanderOptionKey` uses the same paramCase + camelCase path to compute the key Commander will use
/** @param {string} key */
const commanderOptionKey = (key) => {
const pc = paramCase(key);
return pc.startsWith('no-') ? camelCase(pc.slice(3)) : camelCase(pc);
};
// Lazy-load HMN to reduce CLI cold-start overhead
import { getPreset, getPresetNames } from './src/presets.js';
import { paramCase, parseRegExp } from './src/lib/utils.js';
import { optionDefinitions } from './src/lib/option-definitions.js';
import { writeFileAtomic } from './src/lib/file-write.js';
const pkg = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
const EXTENSIONS_DEFAULT = ['html', 'htm', 'shtml', 'shtm'];
const EXTENSIONS_NON_HTML = new Set(['css', 'js', 'mjs', 'cjs', 'jsx', 'ts', 'tsx', 'svg']);
const MARK_ERROR = process.stderr.isTTY ? '\x1b[31m' : '';
const MARK_SUCCESS = process.stderr.isTTY ? '\x1b[32m' : '';
const MARK_WARNING = process.stderr.isTTY ? '\x1b[33m' : '';
const MARK_RESET = process.stderr.isTTY ? '\x1b[0m' : '';
const program = new Command();
program.name(pkg.name);
/**
* @param {string} message
* @returns {never}
*/
function fatal(message) {
console.error(`${MARK_ERROR}${message}${MARK_RESET}`);
process.exit(1);
}
// `catch` bindings are `unknown`, and throw values need not be `Error`s
/** @param {unknown} err */
const errorMessage = (err) => err instanceof Error ? err.message : String(err);
// Handle broken pipe (e.g., when piping to `head`)
process.stdout.on('error', (/** @type {NodeJS.ErrnoException} */ err) => {
if (err && err.code === 'EPIPE') {
process.exit(0);
}
fatal('STDOUT error\n' + (err && err.message ? err.message : String(err)));
});
/**
* JSON does not support regexes, so, e.g., `JSON.parse()` will not create
* a RegExp from the JSON value `[ "/matchString/" ]`, which is
* technically just an array containing a string that begins and end with
* a forward slash. To get a RegExp from a JSON string, it must be
* constructed explicitly in JavaScript.
*
* The likelihood of actually wanting to match text that is enclosed in
* forward slashes is probably quite rare, so if forward slashes were
* included in an argument that requires a regex, the user most likely
* thought they were part of the syntax for specifying a regex.
*
* In the unlikely case that forward slashes are indeed desired in the
* search string, the user would need to enclose the expression in a
* second set of slashes:
*
* --customAttrSurround "[\"//matchString//\"]"
*/
/** @param {string} value */
function parseJSON(value) {
if (value) {
try {
return JSON.parse(value);
} catch {
if (/^\s*[{[]/.test(value)) {
fatal('Could not parse JSON value `' + value + '`');
}
return value;
}
}
}
/** @param {string} value */
function parseJSONArray(value) {
if (!value) return undefined;
const parsed = parseJSON(value);
return Array.isArray(parsed) ? parsed : [parsed];
}
/** @param {string} value */
function parseJSONRegExpArray(value) {
const values = parseJSONArray(value);
return values && values.map(parseRegExp);
}
/** @param {string} value */
const parseString = value => value;
/** @param {string} optionName */
const parseValidInt = (optionName) => (/** @type {string} */ value) => {
const s = String(value).trim();
// Accept only non-negative whole integers
if (!/^\d+$/.test(s)) {
fatal(`Invalid number for \`--${paramCase(optionName)}: "${value}"\``);
}
const num = Number(s);
return num;
};
// Map option types to CLI parsers—`int` is resolved by `getParser`, as its
// parser closes over the option name for error messages
/** @type {Record<string, (value: string) => any>} */
const typeParsers = {
regexp: parseRegExp,
regexpArray: parseJSONRegExpArray,
json: parseJSON,
jsonObject: parseJSON,
jsonArray: parseJSONArray,
string: parseString
};
/**
* @param {string} key Option definition key, for the `int` parser’s error messages
* @param {string} type Option definition type
* @returns {(value: string) => any}
*/
function getParser(key, type) {
const parser = type === 'int' ? parseValidInt(key) : typeParsers[type];
if (!parser) {
fatal(`No CLI parser for option \`${key}\` (type \`${type}\`)—add the type to \`typeParsers\` in cli.js`);
}
return parser;
}
// Configure command-line flags from shared option definitions
const mainOptionKeys = Object.keys(optionDefinitions);
Object.entries(optionDefinitions).forEach(function ([key, { description, descriptionAffirmative, type }]) {
const flag = paramCase(key);
if (type === 'invertedBoolean') {
// The positive form (to re-enable after a preset/config disables it) is hidden from
// help—the footer note covers the convention; the negative form is the primary use case
program.addOption(new Option('--' + flag, descriptionAffirmative ?? 'Enable --' + flag).hideHelp());
program.option('--no-' + flag, description);
} else if (type === 'boolean') {
program.option('--' + flag, description);
// The negation form is hidden from help—the footer note covers the convention;
// skip options whose flag already starts with `no-` (currently only
// `noNewlinesBeforeTagClose`), as `--no-no-X` is not usable
if (!flag.startsWith('no-')) {
program.addOption(new Option('--no-' + flag, 'Disable --' + flag).hideHelp());
}
} else {
const cliFlag = '--' + flag + (type === 'json' || type === 'jsonObject' ? ' [value]' : ' <value>');
program.option(cliFlag, description, getParser(key, type));
}
});
program.option('-i --input <file>', 'Specify input file (alternative to positional argument; pair with `--output` for output)');
program.option('-o --output <file>', 'Specify output file (reads from `--input` file argument or STDIN; outputs to STDOUT if not specified)');
program.option('-v --verbose', 'Show detailed processing information (active options, worker thread count, file statistics, and minifier warnings)');
program.option('-d --dry', 'Dry run: Process and report statistics without writing output');
program.addHelpText('after', '\nBoolean options support a `--no-<flag>` form to disable them, overriding a preset or config file (e.g., `--preset=comprehensive --no-collapse-whitespace`).');
// Lazy import wrapper for HMN
/** @type {Promise<typeof import('./src/htmlminifier.js').minify> | undefined} */
let minifyFnPromise;
async function getMinify() {
if (!minifyFnPromise) {
minifyFnPromise = import('./src/htmlminifier.js').then(m => m.minify);
}
return minifyFnPromise;
}
/** @param {string} file */
function readFile(file) {
try {
return fs.readFileSync(file, { encoding: 'utf8' });
} catch (err) {
fatal('Cannot read ' + file + '\n' + errorMessage(err));
}
}
/**
* Load config from a file path. Extensions .json, .js, and .mjs are handled
* directly; for unknown extensions, JSON is tried first, then module import.
* @param {string} configPath - Path to config file
* @returns {Promise<Record<string, any>>} Loaded config object
*/
async function loadConfigFromPath(configPath) {
const abs = path.resolve(configPath);
const ext = path.extname(configPath).toLowerCase();
if (ext === '.json') {
try { return JSON.parse(readFile(abs).replace(/^\uFEFF/, '')); }
catch (err) { fatal(`Cannot parse config file as JSON: ${errorMessage(err)}`); }
}
if (ext === '.js' || ext === '.mjs') {
// `import()` handles both ESM and CJS .js files—Node resolves the type via the
// nearest package.json `type` field, same as it does for regular module loading
try { const mod = await import(pathToFileURL(abs).href); return 'default' in mod ? mod.default : mod; }
catch (err) { fatal(`Cannot load config file: ${errorMessage(err)}`); }
}
// Unknown extension: Try JSON, then module import
/** @type {unknown} */
let jsonErr;
try { return JSON.parse(readFile(abs).replace(/^\uFEFF/, '')); }
catch (err) { jsonErr = err; }
try { const mod = await import(pathToFileURL(abs).href); return 'default' in mod ? mod.default : mod; }
catch (esmErr) {
fatal(`Cannot read the specified config file.\nAs JSON: ${errorMessage(jsonErr)}\nAs module: ${errorMessage(esmErr)}`);
}
}
// Config keys the CLI handles itself, beyond the options in `optionDefinitions`
const CONFIG_KEYS_EXTRA = new Set(['$schema', 'preset', 'fileExt', 'ignoreDir']);
// Default config files, looked up in the working directory in this order when
// `--config-file` isn’t specified
const CONFIG_FILES_DEFAULT = ['html-minifier-next.config.json', 'htmlminifier.config.json'];
/**
* Parse a config value—strings as on the command line, anything else as it is, since
* a JSON round trip would drop what only a module config can hold (functions, regexes)
* @param {string} key Option definition key
* @param {string} type Option definition type
* @param {unknown} value
*/
function parseConfigValue(key, type, value) {
if (typeof value === 'string') return getParser(key, type)(value);
switch (type) {
case 'int':
return getParser(key, type)(String(value));
// A single value is wrapped as its string form is; `null` and `undefined` leave the option unset
case 'regexpArray':
return value == null ? undefined : (Array.isArray(value) ? value : [value]).map(parseRegExp);
case 'jsonArray':
return value == null ? undefined : (Array.isArray(value) ? value : [value]);
default:
return value;
}
}
/**
* Normalize and validate config object by applying parsers and transforming values.
* @param {Record<string, any>} config - Raw config object
* @returns {Record<string, any>} Normalized config object
*/
function normalizeConfig(config) {
/** @type {Record<string, any>} */
const normalized = { ...config };
// Warn about unrecognized config keys—catches typos as well as options removed in earlier versions
Object.keys(normalized).forEach(function (key) {
if (!Object.hasOwn(optionDefinitions, key) && !CONFIG_KEYS_EXTRA.has(key)) {
console.error(`Ignoring unknown or deprecated config option \`${key}\` (see \`--help\` or README for available options)`);
}
});
// Apply parsers to main options
Object.entries(optionDefinitions).forEach(function ([key, { type }]) {
if (key in normalized) {
if (type !== 'boolean' && type !== 'invertedBoolean') {
normalized[key] = parseConfigValue(key, type, normalized[key]);
}
}
});
// Handle `fileExt` in config file
if ('fileExt' in normalized) {
// Support both string (`html,htm`) and array (`["html", "htm"]`) formats
if (Array.isArray(normalized.fileExt)) {
normalized.fileExt = normalized.fileExt.join(',');
}
}
// Handle `ignoreDir` in config file
if ('ignoreDir' in normalized) {
// Support both string (`libs,vendor`) and array (`["libs", "vendor"]`) formats
if (Array.isArray(normalized.ignoreDir)) {
normalized.ignoreDir = normalized.ignoreDir.join(',');
}
}
return normalized;
}
/** @type {Record<string, any>} */
let config = {};
program.option('-z, --zero', 'Minify all HTML files in the current folder and its subfolders in place (except node_modules), using comprehensive settings (standalone—the flag is ignored when combined with other options)');
program.option('-I --input-dir <dir>', 'Specify an input directory');
program.option('-X --ignore-dir <patterns>', 'Exclude directories—relative to input directory—from processing (comma-separated, overrides config file setting)');
program.option('-O --output-dir <dir>', 'Specify an output directory');
program.option('-w --workers <n>', 'Number of worker threads for multi-file runs; defaults to half the available cores (at most 6) for runs large enough to justify them', parseValidInt('workers'));
program.option('-f --file-ext <extensions>', 'Specify file extension(s) to process (comma-separated, overrides config file setting); defaults to `html,htm,shtml,shtm`; use `*` for all files');
program.option('-p --preset <name>', `Use a preset configuration (${getPresetNames().join(', ')})`);
program.option('-c --config-file <file>', 'Use a configuration file (defaults to html-minifier-next.config.json in the working directory, if present)');
program.version(pkg.version, '-V, --version', 'Output the version number');
program.helpOption('-h, --help', 'Display help for command');
/**
* Progress state shared between the file walk and the indicator; `total` stays
* `null` until the background count finishes
* @typedef {{current: number, total: number | null}} Progress
*/
(async () => {
/** @type {string} */
let content;
let filesProvided = false;
/** @type {string[]} */
let capturedFiles = [];
await program.arguments('[files...]').action(function (files) {
capturedFiles = files;
filesProvided = files.length > 0;
// Defer reading files until after check for consumed filenames
}).parseAsync(process.argv);
const programOptions = program.opts();
// Check if any `parseJSON` options consumed a filename as their value
// If so, treat the option as boolean true and add the filename back to the files list
const jsonOptionKeys = ['minifyCss', 'minifyJs', 'minifyUrls'];
for (const key of jsonOptionKeys) {
const value = programOptions[key];
if (typeof value === 'string' && /\.(html?|shtml?|xhtml?|php|xml|svg|jsx|tsx|vue|ejs|hbs|mustache|twig)$/i.test(value)) {
// The option consumed a filename—inject it back
programOptions[key] = true;
capturedFiles.push(value);
filesProvided = true;
}
}
// If `--input` was specified, treat it as a positional file argument
if (programOptions.input) {
capturedFiles.unshift(programOptions.input);
filesProvided = true;
}
// Handle zero config mode (standalone in-place minification of the current folder)
if (programOptions.zero) {
const hasOtherArgs = process.argv.slice(2).some(arg => arg !== '--zero' && arg !== '-z');
if (hasOtherArgs) {
console.error('Note: `--zero` was ignored—it can only be used on its own, to minify the current folder at comprehensive settings.');
} else {
const cwd = process.cwd();
const [execPath = '', scriptPath = ''] = process.argv;
const commandName = process.env.npm_command === 'exec'
? 'npx html-minifier-next'
: scriptPath.endsWith('.js')
? `${path.basename(execPath)} ${scriptPath}`
: path.basename(scriptPath);
process.stderr.write(
`${MARK_WARNING}Zero-config mode minifies all HTML files in the current folder and its subfolders (${cwd}) in place, using comprehensive settings. If you want to compare results and be able to revert, do this under version control.${MARK_RESET}\n` +
`Equivalent to: ${commandName} --input-dir=. --output-dir=. --ignore-dir=node_modules --preset=comprehensive\n\n` +
`Do you want to continue? [y/N] `
);
const answer = await new Promise((resolve) => {
const rl = readline.createInterface({ input: process.stdin });
rl.once('line', (line) => {
resolve(line.trim().toLowerCase());
rl.close();
});
rl.once('close', () => resolve(''));
});
if (answer !== 'y') {
process.stderr.write(`${MARK_ERROR}In-place minification aborted.${MARK_RESET}\n`);
process.exit(0);
}
// Apply comprehensive preset for all processing
programOptions.preset = 'comprehensive';
const inputDirResolved = await fs.promises.realpath(cwd).catch(() => cwd);
const extensions = EXTENSIONS_DEFAULT;
const ignorePatterns = ['node_modules'];
const showProgress = process.stderr.isTTY;
/** @type {Progress | null} */
let progress = null;
if (showProgress) {
progress = { current: 0, total: null };
}
const allFiles = await collectFiles(cwd, extensions, undefined, ignorePatterns, inputDirResolved);
const concurrency = Math.max(1, Math.min(os.cpus().length || 4, 8));
if (progress) {
progress.total = allFiles.length;
}
await runWithConcurrency(allFiles, concurrency, async (file) => {
await processFile(file, file, false, false);
if (progress) {
progress.current++;
updateProgress(progress.current, progress.total);
}
});
if (progress) {
clearProgress();
}
console.error(`${MARK_SUCCESS}Processed ${allFiles.length.toLocaleString()} file${allFiles.length === 1 ? '' : 's'}.${MARK_RESET}`);
process.exit(0);
}
}
// Load and normalize config if `--config-file` was specified; otherwise look
// for a default config file in the working directory
if (programOptions.configFile) {
config = await loadConfigFromPath(programOptions.configFile);
config = normalizeConfig(config);
} else {
const configFileDefault = CONFIG_FILES_DEFAULT.find(name => fs.existsSync(path.resolve(name)));
if (configFileDefault) {
console.error(`Using config file ${configFileDefault}`);
config = normalizeConfig(await loadConfigFromPath(configFileDefault));
}
}
function createOptions() {
/** @type {Record<string, any>} */
const options = {};
// Priority order: preset < config < CLI
// 1. Apply preset if specified (CLI `--preset` takes priority over config.preset)
const presetName = programOptions.preset || config.preset;
if (presetName) {
const preset = getPreset(presetName);
if (!preset) {
fatal(`Unknown preset “${presetName}”. Available presets: ${getPresetNames().join(', ')}`);
}
Object.assign(options, preset);
}
// 2. Apply config file options (overrides preset)
mainOptionKeys.forEach(function (key) {
if (key in config) {
options[key] = config[key];
}
});
// 3. Apply CLI options (overrides config and preset)
Object.entries(optionDefinitions).forEach(function ([key, { type }]) {
const ck = commanderOptionKey(key);
if (program.getOptionValueSource(ck) === 'cli') {
const val = programOptions[ck];
// For boolean options whose param-case name starts with `no-`, Commander treats
// the flag as a negation and stores the inverted value under the stripped key;
// invert back so the option definition key gets the intended value
options[key] = (type === 'boolean' && paramCase(key).startsWith('no-')) ? !val : val;
}
});
// 4. Surface minifier diagnostics when verbose
if (programOptions.verbose || programOptions.dry) {
options.log = createLog();
}
return options;
}
/**
* Diagnostics name no file of their own, so a run over a directory—where several are in
* flight at once and lines interleave—says which file each came from
* @param {string} [fileLabel]
*/
function createLog(fileLabel) {
const where = fileLabel ? ` (${fileLabel})` : '';
return (/** @type {unknown} */ message) => {
// The hook carries the minifier’s per-call timing as well, which the run's own
// per-file statistics already cover
if (typeof message === 'string' && message.startsWith('minified in: ')) {
return;
}
// Only `continueOnMinifyError` passes `Error` objects, always after leaving the
// offending content unminified—so say that
if (message instanceof Error) {
console.error(` ${MARK_WARNING}Warning: Minification failed, content left as-is: ${message.message || message}${where}${MARK_RESET}`);
} else if (String(message).startsWith('Warning: ') || String(message).startsWith('HTML Minifier Next: ')) {
console.error(` ${MARK_WARNING}${message}${where}${MARK_RESET}`);
} else {
console.error(` ${message}${where}`);
}
};
}
/** @param {Record<string, unknown>} minifierOptions */
function getActiveOptionsDisplay(minifierOptions) {
const presetName = programOptions.preset || config.preset;
if (presetName) {
console.error(`Using preset: ${presetName}`);
}
const activeOptions = Object.entries(minifierOptions)
.filter(([k]) => program.getOptionValueSource(commanderOptionKey(k)) === 'cli')
.map(([k, v]) => (typeof v === 'boolean' ? (v ? k : `no-${k}`) : k));
if (activeOptions.length > 0) {
console.error('CLI options: ' + activeOptions.join(', '));
}
}
/**
* @param {string} original
* @param {string} minified
*/
function calculateStats(original, minified) {
return calculateSizeStats(Buffer.byteLength(original, 'utf8'), Buffer.byteLength(minified, 'utf8'));
}
/**
* @param {number} originalSize
* @param {number} minifiedSize
*/
function calculateSizeStats(originalSize, minifiedSize) {
const saved = originalSize - minifiedSize;
const sign = saved >= 0 ? '-' : '+';
const percentage = originalSize ? ((Math.abs(saved) / originalSize) * 100).toFixed(1) : '0.0';
return { originalSize, minifiedSize, saved, sign, percentage };
}
// A run with many files earns back each worker’s isolate/JIT startup cost. A smaller
// run can do so too when it carries enough bytes to share out, which a file count
// alone cannot see.
const FILES_PER_RUN_MIN = 128;
const PARALLEL_BYTES_MIN = 2 * 1024 * 1024;
// Each worker warms up its own JIT, so the useful count tops out well short of the cores
const WORKERS_MAX = 6;
/** @type {WeakMap<string[], Promise<number[]>>} */
const fileSizesByList = new WeakMap();
/**
* Byte size per file, read once per list whichever step asks first; a failed stat counts
* as 0, leaving normal file processing to report the read error with its usual wording
* @param {string[]} files
*/
function getFileSizes(files) {
let sizes = fileSizesByList.get(files);
if (!sizes) {
sizes = Promise.all(files.map(file => fs.promises.stat(file).then(stat => stat.size, () => 0)));
fileSizesByList.set(files, sizes);
}
return sizes;
}
/**
* A pool for this run, or `null` where one wouldn’t pay or wouldn’t work—in which case
* the caller minifies in-process exactly as before
* @param {string[]} files
*/
async function createPool(files) {
const fileCount = files.length;
const requested = programOptions.workers;
const isVerbose = Boolean(programOptions.verbose || programOptions.dry);
// Whether the run went wide is worth saying, since the default weighs the file
// count and the bytes there are to share out, neither of which the caller sees
const inProcess = () => {
if (isVerbose) console.error('Worker threads: none (minifying in-process)');
return null;
};
// `availableParallelism` reports what this process may actually use, which under a
// CPU affinity mask—a container, commonly—is less than the machine’s core count
const isDefault = requested === undefined;
const size = isDefault
? Math.max(1, Math.min(Math.floor(os.availableParallelism() / 2), WORKERS_MAX))
: requested;
// The file count only decides the default; asking for workers outright is the
// caller’s judgment to make, whatever the run looks like
if (size <= 1) {
return inProcess();
}
if (isDefault && fileCount < FILES_PER_RUN_MIN) {
// `stat()` is cheaper than starting workers, and a pooled run reuses the sizes
const sizes = await getFileSizes(files);
// No single file is split across workers, so the largest one sets a floor no
// pool can beat; what the rest carry is the work there is to share out
const parallelBytes = sizes.reduce((sum, byteSize) => sum + byteSize, 0) - Math.max(0, ...sizes);
if (parallelBytes < PARALLEL_BYTES_MIN) {
return inProcess();
}
}
// `log` is a closure over this process’s console and is rebuilt inside the worker;
// anything else unclonable (such as a function from a module config) stays in-process
const { log, ...options } = createOptions();
try {
structuredClone(options);
} catch {
return inProcess();
}
// A pool this small has nothing to share out and still pays for its workers, so an
// explicit request for them lands in-process as `--workers=1` does
const poolSize = Math.min(size, fileCount);
if (poolSize <= 1) {
return inProcess();
}
try {
const { createFilePool } = await import('./src/lib/file-pool.js');
const pool = createFilePool({
options,
size: poolSize,
// `log` is only set when the run asks for diagnostics
onLog: log
? (/** @type {string} */ message, /** @type {boolean} */ isError, /** @type {string} */ file) =>
createLog(path.relative(process.cwd(), file))(isError ? new Error(message) : message)
: undefined
});
if (isVerbose) console.error(`Worker threads: ${poolSize}`);
return pool;
} catch {
return inProcess();
}
}
// Print a one-line-per-cache hits/misses/size summary to STDERR, skipping caches
// that were never touched (e.g., their minifier is disabled)
async function printCacheStats() {
const { getCacheStats } = await import('./src/htmlminifier.js');
const cacheStats = getCacheStats();
/** @type {Record<string, string>} */
const labels = { css: 'CSS', js: 'JS', svg: 'SVG' };
/** @type {string[]} */
const lines = [];
for (const [key, { gets, hits, size, limit }] of Object.entries(cacheStats)) {
if (gets === 0) continue;
const misses = gets - hits;
lines.push(` ${labels[key]} cache: ${hits.toLocaleString()} hit${hits === 1 ? '' : 's'}, ${misses.toLocaleString()} miss${misses === 1 ? '' : 'es'}, ${size.toLocaleString()}/${limit.toLocaleString()} entries`);
}
if (lines.length === 0) return;
console.error('Cache stats:');
lines.forEach(line => console.error(line));
}
/**
* @param {string} inputFile
* @param {string} outputFile
* @param {boolean} [isDryRun]
* @param {boolean} [isVerbose]
*/
async function processFile(inputFile, outputFile, isDryRun = false, isVerbose = false) {
const data = await fs.promises.readFile(inputFile, { encoding: 'utf8' }).catch(err => {
fatal('Cannot read ' + inputFile + '\n' + errorMessage(err));
});
let minified;
try {
const minify = await getMinify();
const fileOptions = createOptions();
if (fileOptions.log) {
fileOptions.log = createLog(path.relative(process.cwd(), inputFile));
}
minified = await minify(data, fileOptions);
} catch (err) {
fatal('Minification error on ' + inputFile + '\n' + errorMessage(err));
}
const stats = calculateStats(data, minified);
// Show stats if dry run or verbose mode
if (isDryRun || isVerbose) {
console.error(` ${MARK_SUCCESS}✓${MARK_RESET} ${path.relative(process.cwd(), inputFile)}: ${stats.originalSize.toLocaleString()} → ${stats.minifiedSize.toLocaleString()} bytes (${stats.sign}${Math.abs(stats.saved).toLocaleString()}, ${stats.percentage}%)`);
}
if (isDryRun) {
return { originalSize: stats.originalSize, minifiedSize: stats.minifiedSize, saved: stats.saved };
}
await writeFileAtomic(outputFile, minified).catch(err => {
fatal('Cannot write ' + outputFile + '\n' + err.message);
});
return { originalSize: stats.originalSize, minifiedSize: stats.minifiedSize, saved: stats.saved };
}
/**
* @param {string} fileExt
* @returns {string[]}
*/
function parseFileExtensions(fileExt) {
if (!fileExt) return [];
if (fileExt.trim() === '*') return ['*'];
const list = fileExt
.split(',')
.map(ext => ext.trim().replace(/^\.+/, '').toLowerCase())
.filter(ext => ext.length > 0);
return [...new Set(list)];
}
/**
* @param {string} filename
* @param {string[]} fileExtensions
*/
function shouldProcessFile(filename, fileExtensions) {
// Wildcard: process all files
if (fileExtensions.includes('*')) {
return true;
}
const fileExt = path.extname(filename).replace(/^\.+/, '').toLowerCase();
return fileExtensions.includes(fileExt);
}
/**
* Parse comma-separated ignore patterns into an array.
* @param {string} patterns - Comma-separated directory patterns (e.g., "libs,vendor")
* @returns {string[]} Array of trimmed pattern strings with normalized separators
*/
function parseIgnorePatterns(patterns) {
if (!patterns) return [];
return patterns
.split(',')
.map(p => p.trim().replace(/\\/g, '/').replace(/\/+$/, ''))
.filter(p => p.length > 0);
}
/**
* Check if a directory should be ignored based on ignore patterns.
* Supports matching by directory name or relative path.
* @param {string} dirPath - Absolute path to the directory
* @param {string[]} ignorePatterns - Array of patterns to match against (with forward slashes)
* @param {string} baseDir - Base directory for relative path calculation
* @returns {boolean} True if directory should be ignored
*/
function shouldIgnoreDirectory(dirPath, ignorePatterns, baseDir) {
if (!ignorePatterns || ignorePatterns.length === 0) return false;
// Normalize to forward slashes for cross-platform comparison
const relativePath = path.relative(baseDir, dirPath).replace(/\\/g, '/');
const dirName = path.basename(dirPath);
return ignorePatterns.some(pattern => {
// Support both exact directory names and relative paths
return dirName === pattern || relativePath === pattern || relativePath.startsWith(pattern + '/');
});
}
/**
* @param {string} dir
* @param {string[]} extensions
* @param {string | undefined} skipRootAbs
* @param {string[]} ignorePatterns
* @param {string} baseDir
* @returns {Promise<number>}
*/
async function countFiles(dir, extensions, skipRootAbs, ignorePatterns, baseDir) {
let count = 0;
const files = await fs.promises.readdir(dir).catch(() => []);
for (const file of files) {
const filePath = path.join(dir, file);
// Skip anything inside the output root
if (skipRootAbs) {
const real = await fs.promises.realpath(filePath).catch(() => undefined);
if (real && (real === skipRootAbs || real.startsWith(skipRootAbs + path.sep))) {
continue;
}
}
const lst = await fs.promises.lstat(filePath).catch(() => null);
if (!lst || lst.isSymbolicLink()) {
continue;
}
if (lst.isDirectory()) {
// Skip ignored directories
if (shouldIgnoreDirectory(filePath, ignorePatterns, baseDir)) {
continue;
}
count += await countFiles(filePath, extensions, skipRootAbs, ignorePatterns, baseDir);
} else if (shouldProcessFile(file, extensions)) {
count++;
}
}
return count;
}
/**
* @param {number} current
* @param {number | null} total
*/
function updateProgress(current, total) {
// Clear the line first, then write simple progress
process.stderr.write(`\r\x1b[K`);
if (total) {
const ratio = Math.min(current / total, 1);
const percentage = (ratio * 100).toFixed(1);
process.stderr.write(`Processing ${current.toLocaleString()}/${total.toLocaleString()} (${percentage}%)`);
} else {
// Indeterminate progress - no total known yet
process.stderr.write(`Processing ${current.toLocaleString()} files…`);
}
}
function clearProgress() {
process.stderr.write('\r\x1b[K'); // Clear the line
}
// Utility: concurrency runner
/**
* @template T, R
* @param {T[]} items
* @param {number} limit
* @param {(item: T, index: number) => Promise<R>} worker
* @returns {Promise<R[]>}
*/
async function runWithConcurrency(items, limit, worker) {
/** @type {R[]} */
const results = new Array(items.length);
let next = 0;
let active = 0;
return new Promise((resolve, reject) => {
const launch = () => {
while (active < limit && next < items.length) {
const current = next++;
const item = /** @type {T} */ (items[current]);
active++;
Promise.resolve(worker(item, current))
.then((res) => {
results[current] = res;
active--;
launch();
})
.catch(reject);
}
if (next >= items.length && active === 0) {
resolve(results);
}
};
launch();
});
}
/**
* @param {string} dir
* @param {string[]} extensions
* @param {string | undefined} skipRootAbs
* @param {string[]} ignorePatterns
* @param {string} baseDir
* @returns {Promise<string[]>}
*/
async function collectFiles(dir, extensions, skipRootAbs, ignorePatterns, baseDir) {
/** @type {string[]} */
const out = [];
const entries = await fs.promises.readdir(dir).catch(() => []);
for (const name of entries) {
const filePath = path.join(dir, name);
if (skipRootAbs) {
const real = await fs.promises.realpath(filePath).catch(() => undefined);
if (real && (real === skipRootAbs || real.startsWith(skipRootAbs + path.sep))) continue;
}
const lst = await fs.promises.lstat(filePath).catch(() => null);
if (!lst || lst.isSymbolicLink()) continue;
if (lst.isDirectory()) {
if (shouldIgnoreDirectory(filePath, ignorePatterns, baseDir)) continue;
const sub = await collectFiles(filePath, extensions, skipRootAbs, ignorePatterns, baseDir);
out.push(...sub);
} else if (shouldProcessFile(name, extensions)) {
out.push(filePath);
}
}
return out;
}
/**
* @param {string} inputDir
* @param {string} outputDir
* @param {string | string[]} extensions
* @param {boolean} [isDryRun]
* @param {boolean} [isVerbose]
* @param {string} [skipRootAbs]
* @param {Progress | null} [progress]
* @param {string[]} [ignorePatterns]
* @param {string | null} [baseDir]
*/
async function processDirectory(inputDir, outputDir, extensions, isDryRun = false, isVerbose = false, skipRootAbs, progress = null, ignorePatterns = [], baseDir = null) {
// If first call provided a string, normalize once; otherwise assume pre-parsed array
if (typeof extensions === 'string') {
extensions = parseFileExtensions(extensions);
}
// Set `baseDir` on first call
if (baseDir === null) {
baseDir = inputDir;
}
// Collect all files first for bounded parallel processing
const list = await collectFiles(inputDir, extensions, skipRootAbs, ignorePatterns, baseDir);
const allStats = new Array(list.length);
const prepareOutDir = async (/** @type {string} */ inputFile) => {
const outFile = path.join(outputDir, path.relative(inputDir, inputFile));
if (!isDryRun) {
await fs.promises.mkdir(path.dirname(outFile), { recursive: true }).catch(err => {
fatal('Cannot create directory ' + path.dirname(outFile) + '\n' + errorMessage(err));
});
}
return outFile;
};
const advanceProgress = () => {
if (progress) {
progress.current++;
updateProgress(progress.current, progress.total);
}
};
const pool = await createPool(list);
if (pool) {
try {
const { orderLargestFirst } = await import('./src/lib/file-pool.js');
const [fileSizes, tasks] = await Promise.all([
getFileSizes(list),
Promise.all(list.map(async (inputFile, idx) => ({ inputFile, outFile: await prepareOutDir(inputFile), idx })))
]);
// `run()` queues synchronously, so the files reach the pool in exactly this order
await Promise.all(orderLargestFirst(tasks, fileSizes).map(async ({ inputFile, outFile, idx }) => {
const sizes = await pool.run({ inputFile, outputFile: outFile, dryRun: isDryRun })
.catch(err => {
// A worker names the step it failed at, so the wording matches what this
// file would have got had it been minified in this process
if (err?.stage === 'read') fatal('Cannot read ' + inputFile + '\n' + errorMessage(err));
if (err?.stage === 'write') fatal('Cannot write ' + outFile + '\n' + errorMessage(err));
fatal('Minification error on ' + inputFile + '\n' + errorMessage(err));
});
const stats = calculateSizeStats(sizes.originalSize, sizes.minifiedSize);
if (isDryRun || isVerbose) {
console.error(` ${MARK_SUCCESS}✓${MARK_RESET} ${path.relative(process.cwd(), inputFile)}: ${stats.originalSize.toLocaleString()} → ${stats.minifiedSize.toLocaleString()} bytes (${stats.sign}${Math.abs(stats.saved).toLocaleString()}, ${stats.percentage}%)`);
}
allStats[idx] = { originalSize: stats.originalSize, minifiedSize: stats.minifiedSize, saved: stats.saved };
advanceProgress();
}));
} finally {
await pool.close();
}
return allStats.filter(Boolean);
}
const concurrency = Math.max(1, Math.min(os.cpus().length || 4, 8));
await runWithConcurrency(list, concurrency, async (inputFile, idx) => {
const outFile = await prepareOutDir(inputFile);
const stats = await processFile(inputFile, outFile, isDryRun, isVerbose);
allStats[idx] = stats;
advanceProgress();
});