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 `