import { HTMLParser } from './htmlparser.js';
import TokenChain from './tokenchain.js';
import { presets, getPreset, getPresetNames } from './presets.js';
import { LRU, decodeForeignText, describeDependencyFailure, escapeXML, identity, isThenable, lowercase, replaceNUL, uniqueId } from './lib/utils.js';
import { collectUsage } from './lib/unused-css.js';
import {
RE_CR,
RE_LEGACY_ENTITIES,
RE_LINE_BREAK_CR,
RE_ESCAPE_LT,
RE_ESCAPE_LT_RAW_TEXT,
RE_HTML_ENCODING,
RE_WS_START,
RE_WS_END,
RE_WS_ONLY,
RE_WS_NBSP_END,
RE_STYLE_ELEMENT,
RE_ENDS_COLLAPSIBLE,
RE_DOCTYPE_SEGMENT,
formattingElements,
inlineElementsToKeepWhitespace,
inlineElementsToKeepWhitespaceAround,
inlineElementsToKeepWhitespaceWithin,
inlineElementsTransparent,
inlineElementsTransparentAfter,
inlineElementsTransparentVoid,
specialContentElements,
rawTextElements,
htmlElements,
optionalStartTags,
optionalEndTags,
topLevelElements,
compactElements,
looseElements,
trailingElements,
specialOptionalEndTags,
pClosingParents,
namesForeignMixedCase,
integrationPointsForeign,
MISSING_DEPENDENCY
} from './lib/constants.js';
import {
buildInlineSets,
defaultInlineSets,
endsWithWhitespace,
trimWhitespace,
collapseWhitespaceAll,
collapseNoBreakSpaces,
collapseWhitespace,
collapseWhitespaceSmart,
canCollapseWhitespace as defaultCanCollapseWhitespace,
canTrimWhitespace as defaultCanTrimWhitespace,
isAllWhitespace
} from './lib/whitespace.js';
import {
isIgnoredComment,
isExecutableScript,
isStyleElement,
isMetaWithoutEffect,
normalizeAttr,
buildAttr,
deduplicateAttributes,
replaceContentTypePragma
} from './lib/attributes.js';
import {
canRemoveParentTag,
isStartTagMandatory,
canRemovePrecedingTag,
canRemoveElement,
parseRemoveEmptyElementsExcept,
shouldPreserveEmptyElement
} from './lib/elements.js';
import {
hasJsonScriptType,
extractScriptBodies,
processScript
} from './lib/content.js';
import { declinesMinify, processOptions } from './lib/options.js';
import { canScriptFollow, canStyleSheetsJoin, getMergeKey, holdsHashbang, joinScripts, joinStyleSheets } from './lib/merging.js';
import { toFragment, replaceCustomFragments, isMinifiedCodeSafe } from './lib/fragments.js';
/** @import { ProcessedOptions } from './lib/options.js' */
/**
* @typedef {Object} HTMLAttribute
* Representation of an attribute from the HTML parser.
* Internal counterpart: `HTMLAttribute` in lib/attributes.js—keep in sync.
*
* @prop {string} name
* @prop {string} [value]
* @prop {string} [quote]
* @prop {string} [customAssign]
* @prop {string} [customOpen]
* @prop {string} [customClose]
*/
/**
* @typedef {Object} MergeRecord
* A `script` or `style` element for `mergeScripts` or `mergeStyles`, by where its parts sit
* in the output buffer.
*
* @prop {'script' | 'style'} kind
* @prop {number} start - Index of the start tag’s first entry
* @prop {number} content - Index of the first content entry
* @prop {number} end - Index of the end tag
* @prop {string | null} key - What its attributes make of it (`null` to keep it apart)
* @prop {string} tail - For style sheets, the last CSS of its run that isn’t blank, once parsed
* @prop {boolean} deferred - For style sheets, whether its CSS is left to be minified with its run’s
*/
/**
* @typedef {Object} MinifierOptions
* Options that control how HTML is minified. All of these are optional
* and usually default to a disabled/safe value unless noted.
*
* @prop {(tag: string, attrs: HTMLAttribute[], canCollapseWhitespace: (tag: string) => boolean) => boolean} [canCollapseWhitespace]
* Predicate that determines whether runs of whitespace inside a given element
* can be collapsed (whether its content may be trimmed is up to `canTrimWhitespace`).
*
* Default: Built-in `canCollapseWhitespace` function
*
* @prop {((text: string, type?: 'inline' | 'media') => boolean) | null} [canMinifyCSS]
* Synchronous predicate that determines whether the built-in `minifyCSS` may
* process a given piece of CSS—`type` is `undefined` for `style` elements,
* `'inline'` for `style` attributes, and `'media'` for `media` attributes.
* Returning false leaves that CSS as if `minifyCSS` were off, including its URLs
* and unused rules (within `svg` elements, SVGO still minifies it under `minifySVG`).
*
* Default: `null` (all CSS is minified)
*
* @prop {((text: string, inline?: boolean) => boolean) | null} [canMinifyJS]
* Synchronous predicate that determines whether the built-in `minifyJS` may
* process a given piece of JavaScript—`inline` is true for event handler
* attributes. Returning false leaves that JavaScript unminified (`mergeScripts`
* still applies).
*
* Default: `null` (all JavaScript is minified)
*
* @prop {((text: string) => boolean) | null} [canMinifySVG]
* Synchronous predicate that determines whether the built-in `minifySVG` may
* pass a given outermost `svg` element, nested ones included, to SVGO. It
* receives the element as serialized by the HTML pass (e.g., without comments
* under `removeComments`); returning false leaves it as that pass wrote it.
*
* Default: `null` (all SVG is minified)
*
* @prop {(tag: string | null, attrs: HTMLAttribute[] | undefined, canTrimWhitespace: (tag: string) => boolean) => boolean} [canTrimWhitespace]
* Predicate that determines whether whitespace inside the element may be
* trimmed; where not, it stays as written, as in `pre`.
*
* Default: Built-in `canTrimWhitespace` function
*
* @prop {number} [cacheCSS]
* The maximum number of entries for the CSS minification cache. Higher values
* improve performance for inputs with repeated CSS (e.g., batch processing).
* - Cache is created on first `minify()` call and persists for the process lifetime
* - Cache size is locked after first call—subsequent calls reuse the same cache
* - `0` switches the cache off; negative and non-finite values fall back to the default size
*
* Default: `500`
*
* @prop {number} [cacheJS]
* The maximum number of entries for the JavaScript minification cache. Higher
* values improve performance for inputs with repeated JavaScript.
* - Cache is created on first `minify()` call and persists for the process lifetime
* - Cache size is locked after first call—subsequent calls reuse the same cache
* - `0` switches the cache off; negative and non-finite values fall back to the default size
*
* Default: `500`
*
* @prop {number} [cacheSVG]
* The maximum number of entries for the SVG minification cache. Higher
* values improve performance for inputs with repeated SVG content.
* - Cache is created on first `minify()` call and persists for the process lifetime
* - Cache size is locked after first call—subsequent calls reuse the same cache
* - `0` switches the cache off; negative and non-finite values fall back to the default size
*
* Default: `500`
*
* @prop {boolean} [caseSensitive]
* When true, tag and attribute names are written as in the source rather than in lowercase.
* Useful for framework components like ``. HTML names are still read in any case,
* so every option applies to them as without it; hooks get names as written.
*
* Default: `false`
*
* @prop {boolean} [collapseAttributeWhitespace]
* Collapse multiple whitespace characters within attribute values into a
* single space. Also trims leading and trailing whitespace from attribute
* values. Applied as an early normalization step before special attribute
* handlers (CSS minification, class sorting, etc.) run.
*
* Default: `false`
*
* @prop {boolean} [collapseBooleanAttributes]
* Collapse boolean attributes to their name only (for example
* `disabled="disabled"` → `disabled`).
* See also: https://perfectionkills.com/experimenting-with-html-minifier/#collapse_boolean_attributes
*
* Default: `false`
*
* @prop {boolean} [collapseEmptyAttributes]
* Collapse attributes with empty values to their name only (for example
* `alt=""` → `alt`), which the HTML parser reads the same way.
*
* Default: `false`
*
* @prop {boolean} [collapseInlineTagWhitespace]
* When false (default) whitespace around `inline` tags is preserved in
* more cases. When true, whitespace between inline tags may be collapsed,
* except around text-level elements (like `a`, `code`, or `em`); whitespace
* next to text is kept as without the option.
* Must also enable `collapseWhitespace` to have effect.
*
* Default: `false`
*
* @prop {boolean} [collapseNoBreakSpaces]
* Remove whitespace next to a no-break space (`U+00A0`), narrow no-break
* space (`U+202F`), or figure space (`U+2007`) in text (for example
* `a b` → `a b`), which changes how the text renders. Runs of
* no-break spaces are kept.
* Must also enable `collapseWhitespace` to have effect.
*
* Default: `false`
*
* @prop {boolean} [collapseWhitespace]
* Collapse multiple whitespace characters into one where allowed. Also
* controls trimming behaviour in several code paths.
* See also: https://perfectionkills.com/experimenting-with-html-minifier/#collapse_whitespace
*
* Default: `false`
*
* @prop {boolean} [conservativeCollapse]
* If true, be conservative when collapsing whitespace (preserve more
* whitespace in edge cases). Affects collapse algorithms.
* Must also enable `collapseWhitespace` to have effect.
*
* Default: `false`
*
* @prop {boolean} [continueOnMinifyError]
* When set to `false`, minification errors may throw.
* By default, the minifier will attempt to recover from minification
* errors, or ignore them and preserve the original content.
*
* Default: `true`
*
* @prop {boolean} [continueOnParseError]
* When true, the parser will attempt to continue on recoverable parse
* errors. Otherwise, parsing errors may throw.
*
* Default: `false`
*
* @prop {RegExp[]} [customAttrAssign]
* Array of regexes used to recognise custom attribute assignment
* operators (e.g., `''`).
* These are concatenated with the built-in assignment patterns.
*
* Default: `[]`
*
* @prop {RegExp} [customAttrCollapse]
* Regex matching attribute names whose values should be collapsed.
* Basically used to remove newlines and excess spaces inside attribute values,
* e.g., `/ng-class/`.
*
* @prop {[RegExp, RegExp][]} [customAttrSurround]
* Array of `[openRegExp, closeRegExp]` pairs used by the parser to
* detect custom attribute surround patterns (for non-standard syntaxes,
* e.g., ``).
*
* @prop {RegExp[]} [customEventAttributes]
* Array of regexes used to detect event handler attributes for `minifyJS`
* (e.g., `ng-click`). The default matches standard `on…` event attributes.
*
* Default: `[/^on[a-z]{3,}$/]`
*
* @prop {boolean} [strictCustomFragments]
* Rejects `ignoreCustomFragments` patterns that risk catastrophic backtracking,
* rather than warning about them: those that compound quantifiers or alternation
* (`(a+)+`, `(a|b)*`), those that repeat the same unbounded atom twice in a row
* (`.*.*`), and those too long or too deeply nested to analyze at all.
*
* Default: `false`
*
* @prop {boolean} [decodeEntities]
* When true, decodes HTML entities in text and attributes before
* processing, and re-encodes ambiguous ampersands when outputting.
*
* Default: `false`
*
*
* @prop {RegExp[]} [ignoreCustomComments]
* Comments matching any pattern in this array of regexes will be
* preserved when `removeComments` is enabled. The default preserves
* “bang” comments and comments starting with `#`.
*
* Default: `[/^!/, /^\s*#/]`
*
* @prop {RegExp[]} [ignoreCustomFragments]
* Array of regexes used to identify fragments that should be
* preserved (for example server templates). These fragments are temporarily
* replaced during minification to avoid corrupting template code.
* The default preserves ASP/PHP-style tags and XML declarations.
*
* Default: `[/<%[\s\S]*?%>/, /<\?(?:php[\t\n\r ]|=|\$|xml(?:-stylesheet)?(?![\w-])|\s)[\s\S]*?\?>/i]`
*
* @prop {boolean} [includeAutoGeneratedTags]
* If false, tags marked as auto-generated by the parser will be omitted
* from output. Useful to skip injected tags.
*
* Default: `false`
*
* @prop {ArrayLike} [inlineCustomElements]
* Collection of custom element tag names that should be treated as inline
* elements for white-space handling, alongside the built-in inline elements.
*
* Default: `[]`
*
* @prop {boolean} [keepClosingSlash]
* Keep the trailing slash on void elements and other start tags that carry one, and read it
* as closing the element. The default drops the slash and ignores it, as HTML does; in SVG
* and MathML a slash closes the element either way.
*
* Default: `false`
*
* @prop {(message: unknown) => void} [log]
* Logging function used by the minifier for warnings/errors/info.
* You can directly provide `console.log`, but `message` may also be an `Error`
* object or other non-string value.
*
* Default: `() => {}` (no-op function)
*
* @prop {number} [maxInputLength]
* The maximum allowed input length. Used as a guard against ReDoS via
* pathological inputs. If the input exceeds this length an error is
* thrown.
*
* Default: No limit
*
* @prop {number} [maxLineLength]
* Maximum line length for the output. When set the minifier will wrap
* output to the given number of characters where possible, splitting
* lines only in tags—between attributes or before a tag’s `>`.
*
* Default: No limit
*
* @prop {boolean} [mergeScripts]
* When true, consecutive inline ` c`)
followsRemovedBlock = !inlineElements.has(lowerTag || tag) && !inlineElementsTransparent.has(lowerTag || tag);
// What it made optional is up to what comes next now
if (openElement?.omittedEndTag) {
bufferPush(openElement.omittedEndTag.text, true);
optionalEndTag = openElement.omittedEndTag.tag;
optionalEndTagEmitted = true;
}
if (openElement?.omittedStartTag) {
bufferPush(openElement.omittedStartTag.text, true);
optionalStartTag = openElement.omittedStartTag.tag;
}
if (openElement?.impliedEnds) {
// Browsers reopen formatting elements after what closed them, which their end tags
// would prevent and whitespace following an omitted end tag would change
const written = openElement.impliedEnds.filter(implied => !formattingElements.has(implied.tag));
for (const implied of written) {
bufferPush(implied.text, true);
}
const last = written[written.length - 1];
if (last && written.length === openElement.impliedEnds.length && optionalEndTags.has(last.tag)) {
optionalEndTag = last.tag;
optionalEndTagEmitted = true;
}
}
} else {
// Preserve the element—add closing tag
if (skipsEndTag) {
optionalEndTagEmitted = false;
} else {
bufferPush(endTagText, true);
}
charsPrevTag = '/' + tag;
if (!inlineElements.has(lowerTag || tag)) {
currentChars = '';
} else if (isElementEmpty || !inlineTextSet.has(lowerTag || tag)) {
currentChars += '|';
}
}
} else {
if (skipsEndTag) {
optionalEndTagEmitted = false;
} else if (!selfCloses || !closeLastStartTag()) {
bufferPush(endTagText, true);
}
charsPrevTag = '/' + tag;
if (!inlineElements.has(lowerTag || tag)) {
currentChars = '';
} else if (isElementEmpty || !inlineTextSet.has(lowerTag || tag)) {
// What is not text counts as content for the whitespace after it
currentChars += '|';
}
}
if (skipsEndTag && !isElementRemoved && options.removeEmptyElements) {
if (impliedEndsIndex !== buffer.length) {
impliedEnds = [];
impliedEndsIndex = buffer.length;
}
impliedEnds.push({ tag, text: holdsTable ? '' : endTagText });
}
if (closesNoTrim && !isElementRemoved) {
noTrimEndIndex = buffer.length - 1;
}
if (closesNoCollapse && !isElementRemoved) {
noCollapseEndIndex = buffer.length - 1;
}
// A kept element fills the one it sits in
if (openElement && !isElementRemoved) {
markOpenElementFilled();
}
if (endsMergeRecord) {
if (mergeRecords && mergeRecord && buffer.length - 1 > mergeRecord.content && RE_END_TAG.test(buffer[buffer.length - 1] ?? '')) {
mergeRecord.end = buffer.length - 1;
if (mergeRecord.kind === 'style') {
const css = recordContentOf(mergeRecord);
mergeRecord.tail = css.trim() || !mergeRecord.deferred ? css : mergeRecords[mergeRecords.length - 1]?.tail ?? '';
}
mergeRecords.push(mergeRecord);
} else if (mergeRecords && mergeRecord && mergeRecord.deferred && mergeRecord.content < buffer.length) {
// Without an end tag, it stays apart, but its CSS is still to be minified
mergeRecord.key = null;
mergeRecord.end = buffer.length;
mergeRecords.push(mergeRecord);
}
mergeRecord = null;
}
// SVG subtree capture: Record end position for post-processing with SVGO
if (lowerTag === 'svg' && options.minifySVG && svgDepth > 0) {
svgDepth--;
if (svgDepth === 0 && svgBufferStartIndex >= 0) {
svgBlocks.push({ start: svgBufferStartIndex, end: buffer.length });
svgBufferStartIndex = -1;
}
}
},
chars: function (/** @type {string} */ text, /** @type {string} */ prevTag, /** @type {string} */ nextTag, /** @type {HTMLAttribute[]} */ prevAttrs, /** @type {HTMLAttribute[]} */ nextAttrs, /** @type {boolean} */ source, /** @type {boolean} */ first, /** @type {boolean} */ last) {
if (mergeRecord) {
if (mergeRecord.content === -1) mergeRecord.content = buffer.length;
// Custom fragments may hold anything, which minified CSS can’t take as written
if (mergeRecord.kind === 'style' && markers.length && markers.some(marker => text.includes(marker))) mergeRecord.key = null;
}
// Publish this node’s context for the `charsCollapse`/`charsFinalize` phases
// An edge of partial markup reads as no tag, so that whitespace there may stay
textPrevTag = followsRemovedBlock ? charsPrevTag || 'comment' : first && keepsEdges ? '' : prevTag === '' ? 'comment' : prevTag;
textNextTag = last && keepsEdges ? '' : nextTag === '' ? 'comment' : nextTag;
textPrevAttrs = prevAttrs || [];
textNextAttrs = nextAttrs || [];
// Whether this text node needs any async work. In foreign content, text reads references
// and CDATA sections, and `script` and `style` hold markup, so their text is a source only
// where it is all they hold (and in SVG, where they run and apply)
const foreign = Boolean(options.insideForeignContent);
textForeign = foreign;
const holdsSource = !foreign || Boolean(source);
const needsProcessScript = holdsSource && specialContentElements.has(currentTag) && (options.processScripts || (options.minifyJSON && currentTag === 'script' && hasJsonScriptType(currentAttrs)));
const needsMinifyJS = holdsSource && options.minifyJS !== identity && isExecutableScript(currentTag, currentAttrs);
const isModuleScript = needsMinifyJS && currentAttrs.some(
a => a.name.toLowerCase() === 'type' && (a.value ?? '').trim().toLowerCase() === 'module'
);
const needsMinifyCSS = holdsSource && options.minifyCSS !== identity && isStyleElement(currentTag, currentAttrs);
textForeignDecoded = foreign && Boolean(options.decodeEntities || needsProcessScript || needsMinifyJS || needsMinifyCSS);
const needsDecode = Boolean(text) && (foreign
? textForeignDecoded && (text.indexOf('&') !== -1 || text.indexOf(' {
if (needsDecode) {
const decode = /** @type {(text: string) => string} */ (await getDecodeHTML());
text = foreign ? decodeForeignText(text, decode) : decode(text);
}
text = charsCollapse(text);
if (needsProcessScript) {
text = await processScript(text, options, currentTag, currentAttrs, minifyHTML);
}
if (needsMinifyJS || needsMinifyCSS) {
text = replaceNUL(text);
}
if (needsMinifyJS) {
const prewarmed = jsPrewarmed?.get((isModuleScript ? 'm|' : '|') + text);
text = prewarmed ? await prewarmed : await options.minifyJS(text, false, isModuleScript);
}
if (needsMinifyCSS) {
// Style sheets that may be merged are minified once that is known, by run; except
// under `removeEmptyElements`, which needs to know now whether CSS minifies to nothing,
// where that only goes for CSS that joins a run
if (mergeRecord?.kind === 'style' && mergeRecord.key !== null && (!options.removeEmptyElements || joinsStyleRun(mergeRecord, text))) {
mergeRecord.deferred = true;
} else {
text = await options.minifyCSS(text, undefined, options.cssContext);
}
}
charsFinalize(text);
})();
},
// `markup` is the comment as written, where it is to stay that way (` x>`)
comment: function (/** @type {string} */ text, /** @type {boolean} */ nonStandard, /** @type {string | undefined} */ markup) {
const prefix = nonStandard ? '' : '-->';
if (options.removeComments && !isIgnoredComment(text, options)) {
text = '';
removed = true;
} else {
text = markup ?? prefix + text + suffix;
}
commentFinalize(text);
},
// Kept as written, as content may be inserted at one (``)
processingInstruction: function (/** @type {string} */ text) {
hasChars = true;
markOpenElementFilled();
commentFinalize(text);
},
strayEnd: function () {
removed = true;
},
doctype: function (/** @type {string} */ doctype, /** @type {boolean} */ noQuirksMode, /** @type {boolean} */ isIgnored) {
tableClosesP = noQuirksMode;
if (isIgnored) {
removed = true;
return;
}
bufferPush(options.useShortDoctype
? ''
: doctype.replace(RE_DOCTYPE_SEGMENT, (segment, quoted) => quoted ?? collapseWhitespaceAll(segment)), false);
}
});
await parser.parse();
// Nothing follows at the end, so pending whitespace goes (before SVG blocks shift the buffer)
if (transparentGapIndex !== -1) {
settleTransparentGap(Boolean(options.conservativeCollapse) || keepsEdges);
}
if (mergeRecords && (mergeRecords.length > 1 || mergeRecords[0]?.deferred)) {
await mergeElements(mergeRecords);
}
// Post-processing: Optimize SVG blocks with SVGO
// Run all SVGO calls in parallel, then splice results in reverse to preserve indices
const minifySVG = options.minifySVG;
if (minifySVG && svgBlocks.length) {
const optimized = await Promise.all(
svgBlocks.map(({ start, end }) =>
minifySVG(buffer.slice(start, end).join(''))
)
);
for (let i = svgBlocks.length - 1; i >= 0; i--) {
const block = svgBlocks[i];
if (block) {
buffer.splice(block.start, block.end - block.start, optimized[i] ?? '');
bufferTags?.splice(block.start, block.end - block.start, false);
}
}
}
// Also where an SVG left open never reached SVGO
if (svgRawTexts.length) {
const pattern = new RegExp('/\\*!' + uidSVGRawText + '([0-9]+)\\*/', 'g');
for (let i = 0; i < buffer.length; i++) {
const segment = /** @type {string} */ (buffer[i]);
if (segment.indexOf(uidSVGRawText) !== -1) {
bufferSet(i, segment.replace(pattern, (/** @type {string} */ match, /** @type {string} */ index) => svgRawTexts[+index] ?? match));
}
}
}
if (options.removeOptionalTags) {
// `` may be omitted if first thing inside is not a comment
// `` or `` may be omitted if empty
if (topLevelElements.has(optionalStartTag)) {
removeStartTag();
}
// Except for `` or ``, end tags may be omitted if no more content in parent
if (optionalEndTag && optionalEndTagEmitted && !trailingElements.has(optionalEndTag)) {
removeEndTag();
}
}
// Collapsing also trims whitespace before trailing inline end tags; trimming the output
// catches what it leaves at either end, like a space after a removed leading comment
if (options.collapseWhitespace && !keepsEdges) {
squashTrailingWhitespace('br');
}
trimOutputWhitespace();
return joinResultSegments(buffer, bufferTags ?? [], markers, options, uidPattern
? function (/** @type {string} */ str) {
return str.replace(/** @type {RegExp} */ (uidPattern), function (/** @type {string} */ match, /** @type {string} */ prefix, /** @type {string} */ index, /** @type {string} */ suffix, /** @type {number} */ offset, /** @type {string} */ string) {
const chunks = ignoredCustomMarkupChunks[+index];
if (!chunks) {
return match;
}
if (!options.collapseWhitespace) {
// The fragment took the whitespace around it along, so other whitespace here was
// written by the minifier (e.g., by sorting) and is needed where the fragment has none
return (chunks[1] ? '' : prefix.replace(RE_TABS, '')) + chunks[0] + (chunks[2] ? '' : suffix.replace(RE_TABS, ''));
}
const leading = chunks[1] ?? '';
const trailing = chunks[2] ?? '';
const fragment = chunks[0].slice(leading.length, chunks[0].length - trailing.length);
const inTag = customMarkupInTags.has(+index);
const keep = inTag || customMarkupInCode.has(+index) || !options.trimCustomFragments;
// The padding tabs are whitespace to the minifier, so where one is gone, the
// minifier removed the whitespace, which makes it safe to trim
const trimLeading = !keep && prefix === '';
const trimTrailing = inTag ? string.charCodeAt(offset + match.length) === 62 /* > */ : !keep && suffix === '';
return restoreFragmentSide(prefix.replace(RE_TABS, '') + leading, trimLeading, true) +
fragment +
restoreFragmentSide(suffix.replace(RE_TABS, '') + trailing, trimTrailing, false);
});
}
: identity, uidIgnore
? function (/** @type {string} */ str) {
return str.replace(new RegExp('', 'g'), function (/** @type {string} */ _match, /** @type {string} */ index) {
return ignoredMarkupChunks[+index] ?? '';
});
}
: identity);
}
/**
* @param {string[]} results
* @param {boolean[]} resultTags Whether each result belongs to a start or end tag
* @param {string[]} markers Custom fragment and `htmlmin:ignore` placeholder markers
* @param {ProcessedOptions} options
* @param {Function} restoreCustom
* @param {Function} restoreIgnore
*/
function joinResultSegments(results, resultTags, markers, options, restoreCustom, restoreIgnore) {
let str;
const maxLineLength = options.maxLineLength;
if (maxLineLength) {
// Whitespace in tags is the only whitespace that can’t change the output, so lines break
// there alone—in place of the space between attributes, or right before a tag’s `>`
const noNewlinesBeforeTagClose = options.noNewlinesBeforeTagClose;
/** @type {string[]} */
const lines = [];
let lineLength = 0;
// Output since the last break opportunity, and what that opportunity is when not taken;
// fragments are restored by chunk, as whitespace around them decides how they come back
let chunk = '';
/** @type {string | null} */
let separator = null;
const flush = (/** @type {string | null} */ nextSeparator) => {
chunk = restoreIgnore(restoreCustom(chunk));
const newline = chunk.indexOf('\n');
const head = newline < 0 ? chunk.length : newline;
// A line already too long gains nothing from moving a `>` that ends a line of its own
const isUseless = separator === '' && head === 1 && lineLength > maxLineLength;
if (separator !== null) {
if (lineLength > 0 && lineLength + separator.length + head > maxLineLength && !isUseless) {
lines.push('\n');
lineLength = 0;
} else if (separator) {
lines.push(separator);
lineLength += separator.length;
}
}
lines.push(chunk);
lineLength = newline < 0 ? lineLength + chunk.length : chunk.length - chunk.lastIndexOf('\n') - 1;
chunk = '';
separator = nextSeparator;
};
for (let index = 0; index < results.length; index++) {
const result = results[index] ?? '';
if (!resultTags[index]) {
chunk += result;
} else if (markers.length && markers.some(marker => result.includes(marker))) {
// Whitespace next to a fragment stays as is, as it may belong to it
if (!chunk && separator !== null) {
chunk = separator;
separator = null;
}
chunk += result;
} else if (result.charCodeAt(result.length - 1) === 32 /* space */) {
chunk += result.slice(0, -1);
flush(' ');
} else if (result.charCodeAt(result.length - 1) === 62 /* > */ &&
result.charCodeAt(result.length - 2) !== 47 /* / */ &&
!(noNewlinesBeforeTagClose && result.startsWith(''))) {
chunk += result.slice(0, -1);
flush('');
chunk = '>';
} else {
chunk += result;
}
}
flush(null);
str = lines.join('');
} else {
str = restoreIgnore(restoreCustom(results.join('')));
}
if (!options.collapseWhitespace) {
return str;
}
const trims = !keepsEdgeWhitespace(options);
return collapseWhitespace(str, options, trims, trims);
}
/**
* Initialize minification caches with configurable sizes.
*
* Important behavior notes:
* - Caches are created on the first `minify()` call and persist for the lifetime of the process
* - Cache sizes are locked after first initialization—subsequent calls use the same caches
* even if different `cacheCSS`/`cacheJS`/`cacheSVG` options are provided
* - Invalid values (NaN, Infinity, negative) fall back to the default size (500)
*/
/**
* @param {MinifierOptions} options
* @returns {{cssMinifyCache: LRU, jsMinifyCache: LRU, svgMinifyCache: LRU}}
*/
function initCaches(options) {
if (!cssMinifyCache || !jsMinifyCache || !svgMinifyCache) {
const defaultSize = 500;
// Precedence: Options > env > default; non-finite and negative sizes fall back to the default
const cacheSize = (/** @type {number | undefined} */ option, /** @type {string | undefined} */ envVar) => {
const size = option !== undefined ? option : (envVar !== undefined ? Number(envVar) : defaultSize);
return Number.isFinite(size) && size >= 0 ? Math.floor(size) : defaultSize;
};
cssMinifyCache = new LRU(cacheSize(options.cacheCSS, process.env.HM_CACHE_CSS));
jsMinifyCache = new LRU(cacheSize(options.cacheJS, process.env.HM_CACHE_JS));
svgMinifyCache = new LRU(cacheSize(options.cacheSVG, process.env.HM_CACHE_SVG));
}
return { cssMinifyCache, jsMinifyCache, svgMinifyCache };
}
/**
* Get hit/miss statistics for the CSS, JavaScript, and SVG minification caches.
*
* Each cache is created lazily on the first `minify()` call (see `initCaches`); before
* that first call, or for a cache never exercised (e.g., `minifyCSS` disabled), its
* entry reports all-zero stats.
*
* @returns {{ css: CacheStats, js: CacheStats, svg: CacheStats }}
*/
export function getCacheStats() {
return {
css: cacheStatsOrEmpty(cssMinifyCache),
js: cacheStatsOrEmpty(jsMinifyCache),
svg: cacheStatsOrEmpty(svgMinifyCache)
};
}
// Memoized options processing: Batch runs pass one options object to many `minify()` calls, and
// processing it (regex parsing, closures, option signatures) is expensive. The cache is keyed on
// the object and checked against a deep snapshot, so mutating a reused object, nested values
// included, still triggers reprocessing. Each call works on a shallow copy, as `minifyHTML`
// reassigns top-level keys (wrapped minifiers, sorters, UID comment patterns) per call.
/** @type {MinifierOptions} */
const EMPTY_OPTIONS = {};
/** @type {WeakMap