@ohos-ports/html-minifier-next 8.4.2-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE.txt +23 -0
  2. package/README.md +776 -0
  3. package/cli.js +1209 -0
  4. package/dist/types/htmlminifier.d.ts +556 -0
  5. package/dist/types/htmlminifier.d.ts.map +1 -0
  6. package/dist/types/htmlparser.d.ts +25 -0
  7. package/dist/types/htmlparser.d.ts.map +1 -0
  8. package/dist/types/lib/attributes.d.ts +155 -0
  9. package/dist/types/lib/attributes.d.ts.map +1 -0
  10. package/dist/types/lib/constants.d.ts +110 -0
  11. package/dist/types/lib/constants.d.ts.map +1 -0
  12. package/dist/types/lib/content.d.ts +51 -0
  13. package/dist/types/lib/content.d.ts.map +1 -0
  14. package/dist/types/lib/elements.d.ts +57 -0
  15. package/dist/types/lib/elements.d.ts.map +1 -0
  16. package/dist/types/lib/fragments.d.ts +46 -0
  17. package/dist/types/lib/fragments.d.ts.map +1 -0
  18. package/dist/types/lib/option-definitions.d.ts +33 -0
  19. package/dist/types/lib/option-definitions.d.ts.map +1 -0
  20. package/dist/types/lib/options.d.ts +120 -0
  21. package/dist/types/lib/options.d.ts.map +1 -0
  22. package/dist/types/lib/unused-css.d.ts +46 -0
  23. package/dist/types/lib/unused-css.d.ts.map +1 -0
  24. package/dist/types/lib/urls.d.ts +15 -0
  25. package/dist/types/lib/urls.d.ts.map +1 -0
  26. package/dist/types/lib/utils.d.ts +102 -0
  27. package/dist/types/lib/utils.d.ts.map +1 -0
  28. package/dist/types/lib/whitespace.d.ts +45 -0
  29. package/dist/types/lib/whitespace.d.ts.map +1 -0
  30. package/dist/types/presets.d.ts +49 -0
  31. package/dist/types/presets.d.ts.map +1 -0
  32. package/dist/types/tokenchain.d.ts +26 -0
  33. package/dist/types/tokenchain.d.ts.map +1 -0
  34. package/html-minifier-next.schema.json +306 -0
  35. package/package.json +100 -0
  36. package/src/htmlminifier.js +2294 -0
  37. package/src/htmlparser.js +1069 -0
  38. package/src/lib/attributes.js +928 -0
  39. package/src/lib/constants.js +285 -0
  40. package/src/lib/content.js +190 -0
  41. package/src/lib/elements.js +274 -0
  42. package/src/lib/file-pool.js +177 -0
  43. package/src/lib/fragments.js +274 -0
  44. package/src/lib/option-definitions.js +231 -0
  45. package/src/lib/options.js +730 -0
  46. package/src/lib/unused-css.js +379 -0
  47. package/src/lib/urls.js +155 -0
  48. package/src/lib/utils.js +861 -0
  49. package/src/lib/whitespace.js +321 -0
  50. package/src/presets.js +57 -0
  51. package/src/tokenchain.js +123 -0
@@ -0,0 +1,730 @@
1
+ /**
2
+ * Options processing and per-document minification state
3
+ */
4
+
5
+ import { createUrlMinifier } from './urls.js';
6
+ import { LRU, MAX_CACHE_ENTRY_SIZE, stableStringify, hashContent, identity, lowercase, paramCase, replaceAsync, parseRegExp, describeQuantifierRisk, lostFlag } from './utils.js';
7
+ import { RE_TRAILING_SEMICOLON } from './constants.js';
8
+ import { canCollapseWhitespace, canTrimWhitespace } from './whitespace.js';
9
+ import { wrapCSS, unwrapCSS } from './content.js';
10
+ import { findUnusedSymbols, normalizeUnusedCSSOptions } from './unused-css.js';
11
+ import { getPreset, getPresetNames } from '../presets.js';
12
+ import { optionDefinitions, optionDefaults } from './option-definitions.js';
13
+
14
+ /** @import { MinifierOptions, HTMLAttribute } from '../htmlminifier.js' */
15
+
16
+ // Type definitions
17
+
18
+ /**
19
+ * Per-document state handed to `minifyCSS`. Its closure hangs off the memoized
20
+ * options object that every `minify()` call with those options shares, so state
21
+ * belonging to one document has to be passed in rather than captured.
22
+ *
23
+ * @typedef {{usedSymbols?: Set<string>, warned: Set<string>}} CSSContext
24
+ */
25
+
26
+ /**
27
+ * Minified style sheet plus the warnings its transform produced, cached together
28
+ * so that a cache hit can report what the transform reported
29
+ *
30
+ * @typedef {{css: string, warnings: string[]}} CSSResult
31
+ */
32
+
33
+ /**
34
+ * Options object produced by `processOptions` and consumed by `minifyHTML` and
35
+ * the lib/ helpers; normalization guarantees that the function-valued options
36
+ * below are always present (defaulting to identity/built-in functions), and
37
+ * minification adds writable internal state on top of the public options
38
+ * (set on prototype-chain forks during SVG/MathML namespace transitions)
39
+ *
40
+ * @typedef {Omit<MinifierOptions, 'preset' | 'canCollapseWhitespace' | 'canTrimWhitespace' | 'ignoreCustomComments' | 'log' | 'minifyCSS' | 'minifyJS' | 'minifyURLs' | 'minifySVG' | 'removeUnusedCSS'> & {
41
+ * name: (name: string) => string,
42
+ * log: (message: any) => unknown,
43
+ * ignoreCustomComments: RegExp[],
44
+ * canCollapseWhitespace: (tag: string, attrs: HTMLAttribute[], defaultFn: (tag: string) => boolean) => boolean,
45
+ * canTrimWhitespace: (tag: string, attrs: HTMLAttribute[], defaultFn: (tag: string) => boolean) => boolean,
46
+ * minifyCSS: (text: string, type?: string, context?: CSSContext) => string | Promise<string>,
47
+ * minifyJS: (text: string, inline?: boolean, isModule?: boolean) => string | Promise<string>,
48
+ * minifyURLs: (text: string) => string | Promise<string>,
49
+ * minifySVG: ((svgContent: string) => string | Promise<string>) | null,
50
+ * removeUnusedCSS: {safelist: Array<string | RegExp>, scripts: boolean} | null,
51
+ * cssContext?: CSSContext,
52
+ * parallelJS?: boolean,
53
+ * nameParent?: (name: string) => string,
54
+ * nameHTML?: (name: string) => string,
55
+ * keepClosingSlashHTML?: boolean,
56
+ * insideSVG?: boolean,
57
+ * insideForeignContent?: boolean
58
+ * }} ProcessedOptions
59
+ */
60
+
61
+ // Helper functions
62
+
63
+ /** @param {ProcessedOptions} options */
64
+ function shouldMinifyInnerHTML(options) {
65
+ return Boolean(
66
+ options.collapseWhitespace ||
67
+ options.removeComments ||
68
+ options.removeOptionalTags ||
69
+ options.minifyJS !== identity ||
70
+ options.minifyCSS !== identity ||
71
+ options.minifyURLs !== identity ||
72
+ options.minifySVG
73
+ );
74
+ }
75
+
76
+ // Persistent per-site URL minification caches—results depend only on the `site`
77
+ // configuration, so entries can be shared across `minify()` calls; bounded so
78
+ // batch runs with many distinct sites can’t grow memory without limit
79
+ const MAX_URL_CACHE_SITES = 20;
80
+ /** @type {Map<string, LRU>} */
81
+ const urlMinifyCaches = new Map();
82
+
83
+ /** @param {string} site */
84
+ function getUrlMinifyCache(site) {
85
+ let cache = urlMinifyCaches.get(site);
86
+ if (!cache) {
87
+ if (urlMinifyCaches.size >= MAX_URL_CACHE_SITES) {
88
+ const oldestSite = urlMinifyCaches.keys().next().value;
89
+ if (oldestSite !== undefined) {
90
+ urlMinifyCaches.delete(oldestSite);
91
+ }
92
+ }
93
+ cache = new LRU(500);
94
+ urlMinifyCaches.set(site, cache);
95
+ }
96
+ return cache;
97
+ }
98
+
99
+ // User-facing option keys that are valid but not listed in `optionDefinitions`
100
+ const optionKeysExtra = new Set(['preset', 'log', 'canCollapseWhitespace', 'canTrimWhitespace']);
101
+
102
+ // Unknown option keys and preset names already warned about—warn once per
103
+ // key per process, so repeated `minify` calls (e.g., batch runs) don’t flood STDERR
104
+ const optionKeysWarned = new Set();
105
+ const presetNamesWarned = new Set();
106
+ // Custom fragments whose shape risks ReDoS, warned about once per pattern per process
107
+ const customFragmentsWarned = new Set();
108
+ // Options set without the option they need, warned about once per message per process
109
+ const dependenciesWarned = new Set();
110
+ // Unused-CSS configuration that does not hold up, warned about once per message per process
111
+ const unusedCSSWarned = new Set();
112
+ // Object-valued options handed a string, warned about once per distinct value
113
+ const stringValuesWarned = new Set();
114
+
115
+ /**
116
+ * Options that do nothing on their own, and the option each one needs to take effect
117
+ *
118
+ * Cache sizes are deliberately absent: They never change output, so they are
119
+ * configuration for a subsystem rather than a transform that silently fails.
120
+ *
121
+ * @typedef {object} OptionDependency
122
+ * @property {string} option
123
+ * @property {string} requires
124
+ * @property {(input: Record<string, any>) => string | false} [unusable] Clause saying why the prerequisite does not count even though it is set
125
+ * @property {boolean} [clear] Whether to null the option out, where leaving it set would cost work downstream
126
+ *
127
+ * @type {OptionDependency[]}
128
+ */
129
+ const optionDependencies = [
130
+ { option: 'collapseInlineTagWhitespace', requires: 'collapseWhitespace' },
131
+ { option: 'conservativeCollapse', requires: 'collapseWhitespace' },
132
+ { option: 'customEventAttributes', requires: 'minifyJS' },
133
+ { option: 'inlineCustomElements', requires: 'collapseWhitespace' },
134
+ { option: 'noNewlinesBeforeTagClose', requires: 'maxLineLength' },
135
+ { option: 'preserveLineBreaks', requires: 'collapseWhitespace' },
136
+ { option: 'removeEmptyElementsExcept', requires: 'removeEmptyElements' },
137
+ {
138
+ option: 'removeUnusedCSS',
139
+ requires: 'minifyCSS',
140
+ // Removal rides along with Lightning CSS, which a function of one’s own replaces
141
+ unusable: (/** @type {Record<string, any>} */ input) => typeof input.minifyCSS === 'function' && 'which a function of your own replaces',
142
+ clear: true
143
+ },
144
+ { option: 'trimCustomFragments', requires: 'collapseWhitespace' }
145
+ ];
146
+
147
+ // An empty array is a value the user supplied but did not populate, and so asks for
148
+ // nothing; `identity` is what a minifier that could not be loaded resolves to
149
+ /** @param {unknown} value */
150
+ function isRequested(value) {
151
+ if (value === identity) return false;
152
+ return Array.isArray(value) ? value.length > 0 : Boolean(value);
153
+ }
154
+
155
+ // Main options processor
156
+
157
+ /**
158
+ * @param {MinifierOptions} inputOptions - User-provided options
159
+ * @param {{getLightningCSS?: Function | undefined, getTerser?: Function | undefined, getSwc?: Function | undefined, getSvgo?: Function | undefined, cssMinifyCache?: LRU | undefined, jsMinifyCache?: LRU | undefined, svgMinifyCache?: LRU | undefined}} [deps] - Dependencies from htmlminifier.js
160
+ * @returns {ProcessedOptions} Normalized options with defaults applied
161
+ */
162
+ const processOptions = (inputOptions, { getLightningCSS, getTerser, getSwc, getSvgo, cssMinifyCache, jsMinifyCache, svgMinifyCache } = {}) => {
163
+ /** @type {ProcessedOptions} */
164
+ const options = {
165
+ name: lowercase,
166
+ canCollapseWhitespace,
167
+ canTrimWhitespace,
168
+ ...optionDefaults,
169
+ log: identity,
170
+ minifyCSS: identity,
171
+ minifyJS: identity,
172
+ minifyURLs: identity,
173
+ minifySVG: null,
174
+ removeUnusedCSS: null
175
+ };
176
+
177
+ const parseRegExpArray = (/** @type {unknown} */ arr) => {
178
+ return Array.isArray(arr) ? arr.map(parseRegExp) : [];
179
+ };
180
+
181
+ // Helper for nested arrays (e.g., `customAttrSurround: [[start, end], …]`)
182
+ const parseNestedRegExpArray = (/** @type {unknown} */ arr) => {
183
+ if (!Array.isArray(arr)) return [];
184
+ return arr.map(item => {
185
+ // If item is an array (a pair), recursively convert each element
186
+ if (Array.isArray(item)) {
187
+ return item.map(parseRegExp);
188
+ }
189
+ // Otherwise, convert single item
190
+ return parseRegExp(item);
191
+ });
192
+ };
193
+
194
+ // Route warnings through the user-provided `log` hook so API consumers can
195
+ // capture or suppress them consistently; fall back to `console.warn`.
196
+ //
197
+ // Message convention: Strings that may reach the console unsolicited (via
198
+ // this fallback) carry the “HTML Minifier Next: ” prefix for attribution and
199
+ // no “Warning:” label—the channel already conveys severity. Strings sent
200
+ // only to an explicitly provided `log` hook carry “Warning: ” instead, since
201
+ // the hook mixes severities (info strings, warnings, `Error` objects) and
202
+ // its consumer already knows the source.
203
+ const warn = typeof inputOptions.log === 'function' ? inputOptions.log : console.warn;
204
+
205
+ // Warn about unrecognized options—catches typos as well as options removed in earlier versions
206
+ Object.keys(inputOptions).forEach(function (key) {
207
+ if (!Object.hasOwn(optionDefinitions, key) && !optionKeysExtra.has(key) && !optionKeysWarned.has(key)) {
208
+ optionKeysWarned.add(key);
209
+ warn(`HTML Minifier Next: Ignoring unknown or deprecated option \`${key}\` (see README for available options)`);
210
+ }
211
+ });
212
+
213
+ // Merge preset with user options so all values go through normalization
214
+ // User options take precedence over preset values
215
+ let effectiveInput = inputOptions;
216
+ if (inputOptions.preset) {
217
+ const preset = getPreset(inputOptions.preset);
218
+ if (preset) {
219
+ effectiveInput = { ...preset, ...inputOptions };
220
+ } else if (!presetNamesWarned.has(inputOptions.preset)) {
221
+ presetNamesWarned.add(inputOptions.preset);
222
+ const available = getPresetNames().join(', ');
223
+ warn(`HTML Minifier Next: Unknown preset “${inputOptions.preset}”; available presets: ${available}`);
224
+ }
225
+ }
226
+
227
+ // Escape hatch for the loop below, which reads and assigns user-provided values by dynamic key
228
+ const optionsDynamic = /** @type {Record<string, any>} */ (options);
229
+
230
+ Object.keys(effectiveInput).forEach(function (key) {
231
+ const option = /** @type {Record<string, any>} */ (effectiveInput)[key];
232
+
233
+ // Skip `preset` (already processed) and unrecognized keys (warned about above)—
234
+ // the latter also keeps internal keys from being overridden
235
+ if (key === 'preset' || (!Object.hasOwn(optionDefinitions, key) && !optionKeysExtra.has(key))) {
236
+ return;
237
+ }
238
+
239
+ // A string carries no configuration for these options. The CLI parses config
240
+ // values as JSON first, so only a value that is not JSON reaches this from
241
+ // there. (`minifyURLs` is deliberately excluded—there, a string names the site.)
242
+ const definition = optionDefinitions[key];
243
+ if (typeof option === 'string' && definition?.type === 'jsonObject') {
244
+ const message = `HTML Minifier Next: Ignoring \`${key}\`—it takes a boolean or an object, not a string (“${option}”)`;
245
+ if (!stringValuesWarned.has(message)) {
246
+ stringValuesWarned.add(message);
247
+ warn(message);
248
+ }
249
+ return;
250
+ }
251
+
252
+ if (key === 'caseSensitive') {
253
+ if (option) {
254
+ options.name = identity;
255
+ }
256
+ } else if (key === 'removeUnusedCSS') {
257
+ optionsDynamic.removeUnusedCSS = normalizeUnusedCSSOptions(option, message => {
258
+ if (!unusedCSSWarned.has(message)) {
259
+ unusedCSSWarned.add(message);
260
+ warn(`HTML Minifier Next: ${message}`);
261
+ }
262
+ });
263
+ } else if (key === 'log') {
264
+ if (typeof option === 'function') {
265
+ options.log = option;
266
+ }
267
+ } else if (key === 'minifyCSS' && typeof option !== 'function') {
268
+ if (!option || !getLightningCSS || !cssMinifyCache) {
269
+ return;
270
+ }
271
+
272
+ const lightningCssOptions = typeof option === 'object' ? option : {};
273
+ // Capture to preserve TypeScript narrowing across the async closure boundary below
274
+ const cssLoader = getLightningCSS;
275
+ const cssCache = cssMinifyCache;
276
+
277
+ options.minifyCSS = async function (/** @type {string} */ text, /** @type {string | undefined} */ type, /** @type {CSSContext | undefined} */ context) {
278
+ // Fast path: Nothing to minify
279
+ if (!text || !text.trim()) {
280
+ return text;
281
+ }
282
+
283
+ // Warnings are stored with the minified result and replayed on every hit, so a
284
+ // second document with the same defect hears about it, too; `context.warned`
285
+ // then keeps one document from repeating itself. Reporting from the cache
286
+ // rather than only from the transform keeps the output independent of cache
287
+ // size and eviction. They are built and cached even when `log` is the default
288
+ // no-op, so a later document that does pass a `log` hook still gets them.
289
+ const report = (/** @type {string[]} */ messages) => {
290
+ if (!messages.length || options.log === identity) {
291
+ return;
292
+ }
293
+ const warned = context?.warned;
294
+ for (const message of messages) {
295
+ if (warned) {
296
+ if (warned.has(message)) {
297
+ continue;
298
+ }
299
+ warned.add(message);
300
+ }
301
+ options.log(message);
302
+ }
303
+ };
304
+
305
+ // Optimization: Only process URLs if minification is enabled (not identity function)
306
+ // This avoids expensive `replaceAsync` when URL minification is disabled
307
+ if (options.minifyURLs !== identity) {
308
+ text = await replaceAsync(
309
+ text,
310
+ /(url\s*\(\s*)(?:"([^"]*)"|'([^']*)'|([^\s)]+))(\s*\))/ig,
311
+ async function (/** @type {string} */ match, /** @type {string} */ prefix, /** @type {string | undefined} */ dq, /** @type {string | undefined} */ sq, /** @type {string | undefined} */ unq, /** @type {string} */ suffix) {
312
+ const quote = dq != null ? '"' : (sq != null ? "'" : '');
313
+ const url = dq ?? sq ?? unq ?? '';
314
+ try {
315
+ const out = await options.minifyURLs(url);
316
+ return prefix + quote + (typeof out === 'string' ? out : url) + quote + suffix;
317
+ } catch (err) {
318
+ if (!options.continueOnMinifyError) {
319
+ throw err;
320
+ }
321
+ options.log && options.log(err);
322
+ return match;
323
+ }
324
+ }
325
+ );
326
+ }
327
+
328
+ // Unused-symbol removal applies to style sheets only
329
+ const unusedCSSConfig = type === undefined ? options.removeUnusedCSS : undefined;
330
+ const unusedSymbols = (unusedCSSConfig && context?.usedSymbols)
331
+ ? findUnusedSymbols(text, context.usedSymbols, unusedCSSConfig.safelist)
332
+ : undefined;
333
+
334
+ // Cache key: Content + type + options signature; large inputs are hashed to avoid huge Map keys.
335
+ // The symbol list belongs in the signature: The cache outlives a single `minify()` call, so
336
+ // identical style sheets in differently marked-up documents must not share an entry.
337
+ const inputCSS = wrapCSS(text, type);
338
+ const cssSig = stableStringify({
339
+ type,
340
+ opts: lightningCssOptions,
341
+ cont: !!options.continueOnMinifyError,
342
+ unused: unusedSymbols && unusedSymbols.length ? unusedSymbols.slice().sort() : undefined
343
+ });
344
+ const isCacheable = inputCSS.length <= MAX_CACHE_ENTRY_SIZE;
345
+ const cssKey = isCacheable
346
+ ? (inputCSS.length > 2048
347
+ ? (hashContent(inputCSS) + '|' + type + '|' + cssSig)
348
+ : (inputCSS + '|' + type + '|' + cssSig))
349
+ : undefined;
350
+
351
+ try {
352
+ if (cssKey !== undefined) {
353
+ const cached = /** @type {CSSResult | Promise<CSSResult> | undefined} */ (cssCache.get(cssKey));
354
+ if (cached !== undefined) {
355
+ // Support both resolved values and in-flight promises
356
+ const settled = await cached;
357
+ report(settled.warnings);
358
+ return settled.css;
359
+ }
360
+ }
361
+
362
+ // In-flight promise caching: Prevent duplicate concurrent minifications
363
+ // of the same CSS content (same pattern as JS minification)
364
+ const inFlight = (async () => {
365
+ const transformCSS = await cssLoader();
366
+ // Note: `Buffer.from()` is required—Lightning CSS API expects Uint8Array
367
+ const result = transformCSS({
368
+ filename: 'input.css',
369
+ code: Buffer.from(inputCSS),
370
+ minify: true,
371
+ errorRecovery: !!options.continueOnMinifyError,
372
+ ...lightningCssOptions,
373
+ // Union, so that a manually supplied `unusedSymbols` list survives
374
+ ...(unusedSymbols && unusedSymbols.length
375
+ ? { unusedSymbols: lightningCssOptions.unusedSymbols ? [...new Set([...lightningCssOptions.unusedSymbols, ...unusedSymbols])] : unusedSymbols }
376
+ : {})
377
+ });
378
+
379
+ // With `errorRecovery` enabled, Lightning CSS reports what it takes issue
380
+ // with instead of throwing—dropping the rule in some cases (`@property`
381
+ // with a bad `syntax`) and passing it through in others (an unknown
382
+ // at-rule), which is why the wording stops at “reported”
383
+ /** @type {string[]} */
384
+ const warnings = [];
385
+ if (result.warnings) {
386
+ for (const warning of result.warnings) {
387
+ const at = warning.loc ? ` (line ${warning.loc.line}, column ${warning.loc.column})` : '';
388
+ warnings.push(`Warning: Lightning CSS reported invalid CSS${at}: ${warning.message}`);
389
+ }
390
+ }
391
+
392
+ const outputCSS = unwrapCSS(result.code.toString(), type);
393
+
394
+ // If Lightning CSS removed significant content that looks like template syntax or UIDs, return original
395
+ // This preserves:
396
+ // 1. Template code like `<?php ?>`, `<%= ?>`, `{{ }}`, etc. (contain `<` or `>` but not `CDATA`)
397
+ // 2. UIDs representing custom fragments (only lowercase letters and digits, no spaces)
398
+ // CDATA sections, HTML entities, and other invalid CSS are allowed to be removed
399
+ const isCDATA = text.includes('<![CDATA[');
400
+ const uidPattern = /[a-z0-9]{10,}/; // UIDs are long alphanumeric strings
401
+ const hasUID = uidPattern.test(text) && !isCDATA; // Exclude CDATA from UID detection
402
+ const looksLikeTemplate = (text.includes('<') || text.includes('>')) && !isCDATA;
403
+
404
+ // Preserve if output is empty and input had template syntax or UIDs
405
+ // This catches cases where Lightning CSS removed content that should be preserved
406
+ const css = (text.trim() && !outputCSS.trim() && (looksLikeTemplate || hasUID)) ? text : outputCSS;
407
+ return { css, warnings };
408
+ })();
409
+
410
+ if (cssKey !== undefined) cssCache.set(cssKey, inFlight);
411
+ const resolved = await inFlight;
412
+ if (cssKey !== undefined) cssCache.set(cssKey, resolved);
413
+ report(resolved.warnings);
414
+ return resolved.css;
415
+ } catch (err) {
416
+ if (cssKey !== undefined) cssCache.delete(cssKey);
417
+ if (!options.continueOnMinifyError) {
418
+ throw err;
419
+ }
420
+ options.log && options.log(err);
421
+ return text;
422
+ }
423
+ };
424
+ } else if (key === 'minifyJS' && typeof option !== 'function') {
425
+ if (!option || !getTerser || !getSwc || !jsMinifyCache) {
426
+ return;
427
+ }
428
+
429
+ // Capture to preserve TypeScript narrowing across the async closure boundary below
430
+ const loadTerser = getTerser;
431
+ const loadSwc = getSwc;
432
+ const jsCache = jsMinifyCache;
433
+
434
+ // Parse configuration
435
+ const config = typeof option === 'object' ? option : {};
436
+ const engine = (config.engine || 'terser').toLowerCase();
437
+
438
+ // Validate engine
439
+ const supportedEngines = ['terser', 'swc'];
440
+ if (!supportedEngines.includes(engine)) {
441
+ throw new Error(`Unsupported JS minifier engine: “${engine}”. Supported engines: ${supportedEngines.join(', ')}`);
442
+ }
443
+
444
+ // Extract engine-specific options (excluding `engine` field itself)
445
+ const engineOptions = { ...config };
446
+ delete engineOptions.engine;
447
+
448
+ // Terser options (needed for inline JS and when engine is `terser`)
449
+ const terserOptions = engine === 'terser' ? engineOptions : {};
450
+ terserOptions.parse = {
451
+ ...terserOptions.parse,
452
+ bare_returns: false
453
+ };
454
+
455
+ // SWC options (when engine is `swc`)
456
+ const swcOptions = engine === 'swc' ? engineOptions : {};
457
+
458
+ // Pre-compute option signatures once for performance (avoid repeated stringification)
459
+ const terserSig = stableStringify({
460
+ ...terserOptions,
461
+ cont: !!options.continueOnMinifyError
462
+ });
463
+ const swcSig = stableStringify({
464
+ ...swcOptions,
465
+ cont: !!options.continueOnMinifyError
466
+ });
467
+
468
+ options.minifyJS = async function (/** @type {string} */ text, /** @type {boolean | undefined} */ inline, /** @type {boolean | undefined} */ isModule) {
469
+ const start = text.match(/^\s*<!--.*/);
470
+ const code = start ? text.slice(start[0].length).replace(/\n\s*-->\s*$/, '') : text;
471
+
472
+ // Fast path: Avoid invoking minifier for empty/whitespace-only content
473
+ if (!code || !code.trim()) {
474
+ return '';
475
+ }
476
+
477
+ // Hybrid strategy: Always use Terser for inline JS (needs bare returns support)
478
+ // Use user’s chosen engine for script blocks
479
+ const useEngine = inline ? 'terser' : engine;
480
+ let jsKey;
481
+ const isCacheable = code.length <= MAX_CACHE_ENTRY_SIZE;
482
+
483
+ try {
484
+ // Select pre-computed signature based on engine
485
+ const optsSig = useEngine === 'terser' ? terserSig : swcSig;
486
+
487
+ if (isCacheable) {
488
+ // For large inputs, hash the full content to avoid storing huge strings as Map keys
489
+ jsKey = (code.length > 2048 ? (hashContent(code) + '|') : (code + '|'))
490
+ + (inline ? '1' : '0') + '|' + (isModule ? 'm' : '') + '|' + useEngine + '|' + optsSig;
491
+
492
+ const cached = /** @type {string | Promise<string> | undefined} */ (jsCache.get(jsKey));
493
+ if (cached !== undefined) {
494
+ return await cached;
495
+ }
496
+ }
497
+
498
+ const inFlight = (async () => {
499
+ // Dispatch to appropriate minifier
500
+ if (useEngine === 'terser') {
501
+ // Create a copy to avoid mutating shared `terserOptions` (race condition)
502
+ const terserCallOptions = {
503
+ ...terserOptions,
504
+ parse: {
505
+ ...terserOptions.parse,
506
+ bare_returns: inline
507
+ },
508
+ ...(isModule ? { module: true } : {}) // Overrides user options: module detection takes precedence for `<script type=module>`
509
+ };
510
+ const terser = await loadTerser();
511
+ const result = await terser(code, terserCallOptions);
512
+ return result.code.replace(RE_TRAILING_SEMICOLON, '');
513
+ } else if (useEngine === 'swc') {
514
+ const swc = await loadSwc();
515
+ // `swc.minify()` takes compress and mangle directly as options
516
+ const result = await swc.minify(code, {
517
+ compress: true,
518
+ mangle: true,
519
+ ...swcOptions,
520
+ ...(isModule ? { module: true } : {}) // Overrides user options: module detection takes precedence for `<script type=module>`
521
+ });
522
+ return result.code.replace(RE_TRAILING_SEMICOLON, '');
523
+ }
524
+ throw new Error(`Unknown JS minifier engine: ${useEngine}`);
525
+ })();
526
+
527
+ if (jsKey !== undefined) jsCache.set(jsKey, inFlight);
528
+ const resolved = await inFlight;
529
+ if (jsKey !== undefined) jsCache.set(jsKey, resolved);
530
+ return resolved;
531
+ } catch (err) {
532
+ if (jsKey !== undefined) jsCache.delete(jsKey);
533
+ if (!options.continueOnMinifyError) {
534
+ throw err;
535
+ }
536
+ options.log && options.log(err);
537
+ return text;
538
+ }
539
+ };
540
+
541
+ // Whether dispatching script bodies ahead of the parse pays off. It needs a minifier
542
+ // that leaves the main thread—SWC hands work to its own threadpool, where overlapping
543
+ // calls genuinely run at once, while Terser would only compete with the parse for the
544
+ // one thread both share. A user-supplied `minifyJS` is excluded either way—only this
545
+ // wrapper is content-keyed and free of side effects.
546
+ options.parallelJS = engine === 'swc';
547
+ } else if (key === 'minifyURLs' && typeof option !== 'function') {
548
+ if (!option) {
549
+ return;
550
+ }
551
+
552
+ let urlOptions = option;
553
+
554
+ if (typeof option === 'string') {
555
+ urlOptions = { site: option };
556
+ } else if (typeof option !== 'object') {
557
+ urlOptions = {};
558
+ }
559
+
560
+ const relate = createUrlMinifier(urlOptions.site || '');
561
+
562
+ // Reuse the persistent cache for this site configuration
563
+ const instanceCache = getUrlMinifyCache(urlOptions.site || '');
564
+
565
+ options.minifyURLs = function (/** @type {string} */ text) {
566
+ // Fast-path: Skip if text doesn’t look like a URL that needs processing
567
+ // Only process if contains URL-like characters (`/`, `:`, `#`, `?`) or spaces that need encoding
568
+ if (!/[/:?#\s]/.test(text)) {
569
+ return text;
570
+ }
571
+
572
+ // Check cache
573
+ const cached = /** @type {string | undefined} */ (instanceCache.get(text));
574
+ if (cached !== undefined) {
575
+ return cached;
576
+ }
577
+
578
+ try {
579
+ const result = relate(text);
580
+ instanceCache.set(text, result);
581
+ return result;
582
+ } catch (err) {
583
+ // Don’t cache errors
584
+ if (!options.continueOnMinifyError) {
585
+ throw err;
586
+ }
587
+ options.log && options.log(err);
588
+ return text;
589
+ }
590
+ };
591
+ } else if (key === 'minifySVG' && typeof option !== 'function') {
592
+ if (!option || !getSvgo || !svgMinifyCache) {
593
+ return;
594
+ }
595
+
596
+ // Capture to preserve TypeScript narrowing across the async closure boundary below
597
+ const loadSvgo = getSvgo;
598
+ const svgCache = svgMinifyCache;
599
+
600
+ const svgoOptions = typeof option === 'object' ? option : {};
601
+
602
+ // Pre-compute option signature for cache keys
603
+ const svgSig = stableStringify({
604
+ ...svgoOptions,
605
+ cont: !!options.continueOnMinifyError
606
+ });
607
+
608
+ options.minifySVG = async function (/** @type {string} */ svgContent) {
609
+ if (!svgContent || !svgContent.trim()) {
610
+ return svgContent;
611
+ }
612
+
613
+ const isCacheable = svgContent.length <= MAX_CACHE_ENTRY_SIZE;
614
+ const svgKey = isCacheable
615
+ ? (svgContent.length > 2048
616
+ ? (hashContent(svgContent) + '|' + svgSig)
617
+ : (svgContent + '|' + svgSig))
618
+ : undefined;
619
+
620
+ try {
621
+ if (svgKey !== undefined) {
622
+ const cached = /** @type {string | Promise<string> | undefined} */ (svgCache.get(svgKey));
623
+ if (cached !== undefined) {
624
+ return await cached;
625
+ }
626
+ }
627
+
628
+ const inFlight = (async () => {
629
+ const optimize = await loadSvgo();
630
+ const result = optimize(svgContent, svgoOptions);
631
+ return result.data;
632
+ })();
633
+
634
+ if (svgKey !== undefined) svgCache.set(svgKey, inFlight);
635
+ const resolved = await inFlight;
636
+ if (svgKey !== undefined) svgCache.set(svgKey, resolved);
637
+ return resolved;
638
+ } catch (err) {
639
+ if (svgKey !== undefined) svgCache.delete(svgKey);
640
+ if (!options.continueOnMinifyError) {
641
+ throw err;
642
+ }
643
+ options.log && options.log(err);
644
+ return svgContent;
645
+ }
646
+ };
647
+ } else if (key === 'customAttrCollapse') {
648
+ // Single regex pattern
649
+ optionsDynamic[key] = parseRegExp(option);
650
+ } else if (key === 'customAttrSurround') {
651
+ // Nested array of RegExp pairs: `[[openRegExp, closeRegExp], …]`
652
+ optionsDynamic[key] = parseNestedRegExpArray(option);
653
+ } else if (['customAttrAssign', 'customEventAttributes', 'ignoreCustomComments', 'ignoreCustomFragments'].includes(key)) {
654
+ // Array of regex patterns
655
+ optionsDynamic[key] = parseRegExpArray(option);
656
+ } else {
657
+ optionsDynamic[key] = option;
658
+ }
659
+ });
660
+
661
+ // The parser merges these into one attribute pattern, and a merged pattern
662
+ // carries no flags of its own. `i` and `s` are written into the source instead,
663
+ // but `u` and `v` change how a source reads and cannot be: dropped, `\p{L}`
664
+ // stops being a property escape and matches the literal text `p{L}`, silently
665
+ // and without failing to compile. Refusing them beats matching the wrong thing.
666
+ /** @type {[string, RegExp[]][]} */
667
+ const merged = [
668
+ ['customAttrAssign', options.customAttrAssign || []],
669
+ ['customAttrSurround', (options.customAttrSurround || []).flat()]
670
+ ];
671
+ for (const [key, patterns] of merged) {
672
+ for (const re of patterns) {
673
+ if (!(re instanceof RegExp)) continue;
674
+ const flag = lostFlag(re);
675
+ if (!flag) continue;
676
+ throw new Error(`HTML Minifier Next: \`${key}\` pattern \`/${re.source}/${re.flags}\` carries \`${flag}\`, which the merged attribute pattern cannot carry—rewrite it without \`${flag}\``);
677
+ }
678
+ }
679
+
680
+ // Fragments that compound quantifiers or alternation under unbounded repetition
681
+ // are the shapes that backtrack catastrophically, and they are also the ones a
682
+ // linear scan cannot stand in for; so are patterns too long or too deeply
683
+ // nested to read, which are refused for that rather than for a shape. A lone
684
+ // `[\s\S]*?` up to a literal terminator is linear and passes; HMN’s default
685
+ // fragments have exactly that shape, so the check flagging it would mean
686
+ // warning about the defaults themselves.
687
+ for (const re of options.ignoreCustomFragments || []) {
688
+ const risk = describeQuantifierRisk(re);
689
+ if (!risk) continue;
690
+ const problem = `Custom fragment \`/${re.source}/\` ${risk}`;
691
+ if (options.strictCustomFragments) {
692
+ throw new Error(`HTML Minifier Next: ${problem}`);
693
+ }
694
+ if (!customFragmentsWarned.has(re.source)) {
695
+ customFragmentsWarned.add(re.source);
696
+ warn(`HTML Minifier Next: ${problem}`);
697
+ }
698
+ }
699
+
700
+ // Options that silently do nothing without the option they build on say so rather
701
+ // than let them pass. The option is read from `effectiveInput` (user options
702
+ // over preset), so that a default filled in above doesn’t count as the user asking
703
+ // for it; the option it needs is read from the settled options, so that a minifier
704
+ // asked for but not loadable counts as absent rather than as present.
705
+ const requestedOptions = /** @type {Record<string, any>} */ (effectiveInput);
706
+ const settledOptions = /** @type {Record<string, any>} */ (options);
707
+ for (const { option, requires, unusable, clear } of optionDependencies) {
708
+ if (!isRequested(requestedOptions[option])) continue;
709
+ const aside = unusable && unusable(requestedOptions);
710
+ if (!aside && isRequested(settledOptions[requires])) continue;
711
+ const message = `HTML Minifier Next: Ignoring \`${option}\`—use with \`${requires}\` (\`--${paramCase(requires)}\`)${aside ? `, ${aside}` : ''}`;
712
+ if (!dependenciesWarned.has(message)) {
713
+ dependenciesWarned.add(message);
714
+ warn(message);
715
+ }
716
+ if (clear) {
717
+ settledOptions[option] = null;
718
+ }
719
+ }
720
+
721
+ return options;
722
+ };
723
+
724
+ // Exports
725
+
726
+ export {
727
+ optionDependencies,
728
+ shouldMinifyInnerHTML,
729
+ processOptions
730
+ };