diff --git a/CHANGELOG.md b/CHANGELOG.md index 95ff6082..5630e1fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ As of version 5.0.0, all notable changes to HTML Minifier (HM) are documented in The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and the project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [5.4.0] - 2026-11-20 ### Fixed @@ -12,6 +12,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Changed +* Changed `collapseWhitespace` to keep whitespace at either end of `partialMarkup` fragments as a single space (or line break, with `preserveLineBreaks`) where it may separate the fragment from what surrounds it, as next to text, inline elements, and elements that don’t render (previously, ` Jane\n` became `Jane`, and `a ` became `a`), while it still goes next to block elements * Made pages with inline SVG or MathML faster to minify, as the first `svg` or `math` element slowed down the minification of the rest of the page (by 10–20% on pages without much SVG or MathML) ## [5.3.1] - 2026-11-19 diff --git a/README.md b/README.md index 6531eb1b..95cb4209 100644 --- a/README.md +++ b/README.md @@ -265,7 +265,7 @@ Where the modifiers disagree, the preserving one wins—`conservativeCollapse` a `collapseWhitespace` goes by the element, not by CSS, so whitespace in an element styled `white-space: pre` collapses unless you protect it with [`canCollapseWhitespace` and `canTrimWhitespace`](#api-only-options). -Regardless of these options, whitespace at the start and end of the output goes, and so do lines that a removed comment or tag leaves with nothing but whitespace (blank lines of the source stay). Whitespace stays, however, where it’s kept verbatim (in `pre` or `textarea`, or in `pre`, `textarea`, or `script` content left open at the end), next to custom fragments where their handling keeps it (see `trimCustomFragments`), at either end of partial markup (cf. `partialMarkup`), and where `conservativeCollapse` or `preserveLineBreaks` keep it. +Regardless of these options, whitespace at the start and end of the output goes, and so do lines that a removed comment or tag leaves with nothing but whitespace (blank lines of the source stay). Whitespace stays, however, where it’s kept verbatim (in `pre` or `textarea`, or in `pre`, `textarea`, or `script` content left open at the end), next to custom fragments where their handling keeps it (see `trimCustomFragments`), at either end of partial markup (cf. `partialMarkup`; `collapseWhitespace` collapses it there), and where `conservativeCollapse` or `preserveLineBreaks` keep it. Note: `preserveLineBreaks` keeps line breaks, not indentation. HTML Minifier doesn’t format: To keep the source formatting, leave `collapseWhitespace` off (as in the first row of the table above). Line breaks and indentation then stay as written, while other options still apply. @@ -707,7 +707,13 @@ By default, HM parses markup into a complete tree structure, then modifies it (r _Input markup (e.g., `

foo`) → Internal representation of markup in a form of tree (e.g., `{ tag: "p", attr: "id", children: ["foo"] }`) → Transformation of internal representation (e.g., removal of `id` attribute) → Output of resulting markup (e.g., `

foo

`)_ -For partial HTML fragments (such as template includes, SSI fragments, or closing tags without opening tags), use the `partialMarkup: true` option. This preserves stray end tags and prevents auto-closing of unclosed tags at the end of input. Note that normal HTML auto-closing rules still apply during parsing—for example, a closing parent tag will still auto-close its unclosed child elements, and an end tag browsers ignore because a block element is still open inside its element is removed (use `` to keep such markup as written). Whitespace at the start and end of a fragment stays, too, as it may separate the fragment from what surrounds it (unless `collapseWhitespace` removes it). `removeRedundantAttributes` keeps `target="_self"` in partial markup, as there may be a `base` element setting another target elsewhere. (Where an external script adds such a `base` element, wrap links whose `target="_self"` needs to stay in ``.) +For partial HTML fragments (such as template includes, SSI fragments, or closing tags without opening tags), use the `partialMarkup: true` option. This preserves stray end tags and prevents auto-closing of unclosed tags at the end of input. Note that normal HTML auto-closing rules still apply during parsing—for example, a closing parent tag will still auto-close its unclosed child elements, and an end tag browsers ignore because a block element is still open inside its element is removed (use `` to keep such markup as written). + +Whitespace at the start and end of a fragment stays, too, as it may separate the fragment from what surrounds it. `collapseWhitespace` collapses it to a space (or line break, with `preserveLineBreaks`) where text in its place would keep one, as next to text and inline elements, and removes it next to block elements (e.g., with `␣` marking a space, `␣Jane\n` becomes `␣Jane␣`, while `\n
…
\n` becomes `
…
`). + +With `removeOptionalTags`, end tags at the end of a fragment may be omitted (e.g., `

a

` becomes `

a`), so content following the fragment would end up inside those elements. + +`removeRedundantAttributes` keeps `target="_self"` in partial markup, as there may be a `base` element setting another target elsewhere. (Where an external script adds such a `base` element, wrap links whose `target="_self"` needs to stay in ``.) Markup with [parse errors](https://html.spec.whatwg.org/multipage/parsing.html#parse-errors) that HM cannot read, like a stray `` or an `=` in an unquoted attribute value, makes it abort with the line and column of the error, so that the error can be fixed. With `continueOnParseError`, HM handles such errors the way browsers do instead. diff --git a/package-lock.json b/package-lock.json index 3b7ce61a..01ac564c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,19 +1,19 @@ { "name": "html-minifier", - "version": "5.3.1", + "version": "5.4.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "html-minifier", - "version": "5.3.1", + "version": "5.4.0", "license": "MIT", "dependencies": { "commander": "^15.1.0", "entities": "^9.0.0", "lightningcss": "^1.33.0", "svgo": "^4.1.0", - "terser": "^5.51.2" + "terser": "^5.51.3" }, "bin": { "hm": "cli.js", @@ -2519,9 +2519,9 @@ } }, "node_modules/terser": { - "version": "5.51.2", - "resolved": "https://registry.npmjs.org/terser/-/terser-5.51.2.tgz", - "integrity": "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==", + "version": "5.51.3", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.51.3.tgz", + "integrity": "sha512-j5jPZZ6Sz0Eg2unusKhdRzUhUlHXJ3Bw2AkIXyJ6AqajWwihUlZOdJS+KSnZzmtVk6mFGdm3hHg0+M2sgyEz5Q==", "license": "BSD-2-Clause", "dependencies": { "@jridgewell/source-map": "^0.3.3", @@ -4114,9 +4114,9 @@ } }, "terser": { - "version": "5.51.2", - "resolved": "https://registry.npmjs.org/terser/-/terser-5.51.2.tgz", - "integrity": "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==", + "version": "5.51.3", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.51.3.tgz", + "integrity": "sha512-j5jPZZ6Sz0Eg2unusKhdRzUhUlHXJ3Bw2AkIXyJ6AqajWwihUlZOdJS+KSnZzmtVk6mFGdm3hHg0+M2sgyEz5Q==", "requires": { "@jridgewell/source-map": "^0.3.3", "acorn": "^8.15.0", diff --git a/package.json b/package.json index caa9bcf4..f8da4f4b 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "entities": "^9.0.0", "lightningcss": "^1.33.0", "svgo": "^4.1.0", - "terser": "^5.51.2" + "terser": "^5.51.3" }, "description": "Highly effective, super-configurable, well-tested web page minifier", "devDependencies": { @@ -98,5 +98,5 @@ }, "type": "module", "types": "dist/types/htmlminifier.d.ts", - "version": "5.3.1" + "version": "5.4.0" } \ No newline at end of file diff --git a/src/htmlminifier.js b/src/htmlminifier.js index 42f6b42f..c30db66a 100644 --- a/src/htmlminifier.js +++ b/src/htmlminifier.js @@ -39,6 +39,7 @@ import { pClosingParents, namesForeignMixedCase, integrationPointsForeign, + processingInstructionTag, MISSING_DEPENDENCY } from './lib/constants.js'; @@ -973,6 +974,13 @@ function matchPlainEndTag(str) { return str.slice(2, end - 1); } +// At either end of partial markup, collapsed whitespace may separate the fragment from what +// surrounds it, and so stays where text in its place would keep it +/** @param {ProcessedOptions} options */ +function keepsEdgeWhitespace(options) { + return Boolean(options.collapseWhitespace && options.partialMarkup && !options.conservativeCollapse); +} + /** * @param {string} value * @param {ProcessedOptions} options @@ -985,7 +993,9 @@ async function minifyHTML(value, options, partialMarkup) { throw new Error(`Input length (${value.length}) exceeds maximum allowed length (${options.maxInputLength})`); } - if (options.collapseWhitespace) { + const keepsEdges = keepsEdgeWhitespace(options); + + if (options.collapseWhitespace && !keepsEdges) { value = collapseWhitespace(value, options, true, true); } @@ -1534,7 +1544,7 @@ async function minifyHTML(value, options, partialMarkup) { const [, after] = findNeighbors(last.end + 1); const textBefore = buffer[before] ?? ''; const textAfter = buffer[after] ?? ''; - if (before < 0 || after >= buffer.length || RE_WS_END.test(textBefore) || RE_WS_START.test(textAfter)) { + if ((!keepsEdges && (before < 0 || after >= buffer.length)) || RE_WS_END.test(textBefore) || RE_WS_START.test(textAfter)) { for (let i = gapFrom; i < gapTo; i++) bufferSet(i, ''); } } @@ -1949,7 +1959,8 @@ async function minifyHTML(value, options, partialMarkup) { index--; } } - return false; + // What precedes partial markup may run into it, too + return keepsEdges; } // Per-text-node context for `charsCollapse`/`charsFinalize`, set by the `chars` @@ -2046,7 +2057,10 @@ async function minifyHTML(value, options, partialMarkup) { } } if (textPrevTag || textNextTag) { - let collapsed = collapseWhitespaceSmart(text, effectivePrevTag, textNextTag, textPrevAttrs, textNextAttrs, options, inlineSets, !stackNoCollapseWhitespace.length); + // Beyond an edge of partial markup, anything may render, as for a processing instruction + const smartPrevTag = keepsEdges && effectivePrevTag === '' ? processingInstructionTag : effectivePrevTag; + const smartNextTag = keepsEdges && textNextTag === '' ? processingInstructionTag : textNextTag; + let collapsed = collapseWhitespaceSmart(text, smartPrevTag, smartNextTag, textPrevAttrs, textNextAttrs, options, inlineSets, !stackNoCollapseWhitespace.length); if (!transparentDepth && inlineElementsTransparentAfter.has(textPrevTag)) { // Between elements that don’t render, whitespace stays pending when it may // separate text, and one space does @@ -2084,7 +2098,8 @@ async function minifyHTML(value, options, partialMarkup) { } } } else { - text = collapseWhitespace(text, options, true, true); + // Raw text has no tag on either side, unlike an edge of partial markup + text = collapseWhitespace(text, options, !keepsEdges || textPrevTag !== '', !keepsEdges || textNextTag !== ''); } if (!text && RE_TRAILING_WHITESPACE.test(currentChars) && textPrevTag && textPrevTag.charAt(0) === '/' && !holdTransparentGap(buffer.length - 1, textNextTag)) { trimTrailingWhitespace(buffer.length - 1, textNextTag); @@ -2995,15 +3010,16 @@ async function minifyHTML(value, options, partialMarkup) { } } }, - chars: function (/** @type {string} */ text, /** @type {string} */ prevTag, /** @type {string} */ nextTag, /** @type {HTMLAttribute[]} */ prevAttrs, /** @type {HTMLAttribute[]} */ nextAttrs, /** @type {boolean} */ source) { + 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 - textPrevTag = followsRemovedBlock ? charsPrevTag || 'comment' : prevTag === '' ? 'comment' : prevTag; - textNextTag = nextTag === '' ? 'comment' : nextTag; + // 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 || []; @@ -3103,7 +3119,7 @@ async function minifyHTML(value, options, partialMarkup) { // Nothing follows at the end, so pending whitespace goes (before SVG blocks shift the buffer) if (transparentGapIndex !== -1) { - settleTransparentGap(Boolean(options.conservativeCollapse)); + settleTransparentGap(Boolean(options.conservativeCollapse) || keepsEdges); } if (mergeRecords && (mergeRecords.length > 1 || mergeRecords[0]?.deferred)) { @@ -3144,14 +3160,16 @@ async function minifyHTML(value, options, partialMarkup) { 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)) { + // Except for `` or ``, end tags may be omitted if no more content in parent; + // whitespace kept at the end of partial markup follows the tag, which then stays + if (optionalEndTag && optionalEndTagEmitted && !trailingElements.has(optionalEndTag) && + !(keepsEdges && !RE_END_TAG.test(buffer[skipRun(runEmpty, buffer.length - 1)] ?? ''))) { 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) { + if (options.collapseWhitespace && !keepsEdges) { squashTrailingWhitespace('br'); } trimOutputWhitespace(); @@ -3264,7 +3282,11 @@ function joinResultSegments(results, resultTags, markers, options, restoreCustom } else { str = restoreIgnore(restoreCustom(results.join(''))); } - return options.collapseWhitespace ? collapseWhitespace(str, options, true, true) : str; + if (!options.collapseWhitespace) { + return str; + } + const trims = !keepsEdgeWhitespace(options); + return collapseWhitespace(str, options, trims, trims); } /** diff --git a/src/htmlparser.js b/src/htmlparser.js index 63cc5ce4..9e6cd9c3 100644 --- a/src/htmlparser.js +++ b/src/htmlparser.js @@ -808,8 +808,9 @@ export class HTMLParser { } if (handler.chars) { - // An element whose end tag follows its start tag’s text alone has that text for content - const result = handler.chars(text, prevTag, nextTag, prevAttrs, nextAttrs, sourcePos !== -1 && isSource(pos - text.length)); + // An element whose end tag follows its start tag’s text alone has that text for content; + // the last two arguments say whether the text starts or ends the input + const result = handler.chars(text, prevTag, nextTag, prevAttrs, nextAttrs, sourcePos !== -1 && isSource(pos - text.length), pos === text.length, pos === fullLength); if (isThenable(result)) await result; } prevTag = ''; diff --git a/test/html.test.js b/test/html.test.js index a1871c8e..4957a449 100644 --- a/test/html.test.js +++ b/test/html.test.js @@ -3446,11 +3446,13 @@ describe('HTML', () => { assert.strictEqual(await minify('

a

', { collapseWhitespace: true, conservativeCollapse: true }), '

a

'); assert.strictEqual(await minify('\n

a

\n', { collapseWhitespace: true, preserveLineBreaks: true }), '\n

a

\n'); - // Partial markup ends where other markup joins it, so `collapseWhitespace` alone decides + // Partial markup ends where other markup joins it, so `collapseWhitespace` collapses + // whitespace there as next to text assert.strictEqual(await minify('Hello ', { partialMarkup: true }), 'Hello '); assert.strictEqual(await minify(' x ', { partialMarkup: true }), ' x '); assert.strictEqual(await minify(' world', { partialMarkup: true, removeComments: true }), ' world'); - assert.strictEqual(await minify(' x ', { partialMarkup: true, collapseWhitespace: true }), 'x'); + assert.strictEqual(await minify(' \nx\n ', { partialMarkup: true, collapseWhitespace: true }), ' x '); + assert.strictEqual(await minify('

x

', { partialMarkup: true, collapseWhitespace: true }), '

x

'); }); // https://github.com/kangax/html-minifier/issues/10 @@ -7971,6 +7973,65 @@ describe('HTML', () => { 'partialMarkup and removeOptionalTags work independently (optional

is removed)'); }); + test('Collapses whitespace at the edges of partial markup', async () => { + const options = { partialMarkup: true, collapseWhitespace: true }; + const cases = [ + // Text and inline elements may join what surrounds the fragment + [' foo ', ' foo '], + [' x ', ' x '], + ['\n\tx\n', ' x '], + ['

foo ', '

foo '], + [' \n ', ' '], + // So may what precedes elements that don’t render + ['a ', 'a '], + ['a ', 'a '], + [' b', ' b'], + ['x ', 'x '], + // And what follows them, as does an edge where nothing but such elements stand + [' y', ' y'], + ['y ', 'y '], + [' b', ' b'], + [' ', ' '], + ['

y

', '

y

'], + ['

y

', '

y

'], + // Next to block elements, whitespace doesn’t render + ['\n

x

\n', '

x

'], + [' ', ''], + ['
x
', '
x
'], + // Whitespace inside stays collapsed as before + ['
x
', '
x
'], + ['
', '
'] + ]; + for (const [input, output] of cases) { + assert.strictEqual(await minify(input, options), output, JSON.stringify(input)); + } + + // Comments, kept or removed + assert.strictEqual(await minify('foo ', options), 'foo '); + assert.strictEqual(await minify('foo ', { ...options, removeComments: true }), 'foo '); + + // Kept whitespace keeps the end tag before it, and merged scripts keep it, too + assert.strictEqual(await minify('ab ', { ...options, removeOptionalTags: true }), 'ab '); + assert.strictEqual(await minify('ab', { ...options, removeOptionalTags: true }), 'ab'); + assert.strictEqual(await minify('a ', { ...options, mergeScripts: true }), 'a '); + assert.strictEqual(await minify('a ', { collapseWhitespace: true, mergeScripts: true }), 'a'); + + // Script and style content isn’t an edge + assert.strictEqual(await minify('', options), ''); + assert.strictEqual(await minify('', options), ''); + + // `preserveLineBreaks` keeps a line break, and a space where there is none + assert.strictEqual(await minify('\nx\n', { ...options, preserveLineBreaks: true }), '\nx\n'); + assert.strictEqual(await minify(' foo ', { ...options, preserveLineBreaks: true }), ' foo '); + assert.strictEqual(await minify('\n

x

\n', { ...options, preserveLineBreaks: true }), '\n

x

\n'); + + // Unchanged: Full documents, `conservativeCollapse`, and no `collapseWhitespace` + assert.strictEqual(await minify(' foo ', { collapseWhitespace: true }), 'foo'); + assert.strictEqual(await minify('a ', { collapseWhitespace: true }), 'a'); + assert.strictEqual(await minify('\n

x

\n', { ...options, conservativeCollapse: true }), '

x

'); + assert.strictEqual(await minify(' foo ', { partialMarkup: true }), ' foo '); + }); + test('Runs the code minifiers once with `sortAttributes` and `sortClassNames`', async () => { const input = '

x

'; const calls = { css: 0, js: 0, urls: 0, svg: 0 };