Skip to content

Commit b53f3fb

Browse files
authored
fix(minify): keep CSS/HTML minification meaning-preserving in edge cases (#21560)
CSS: An+B selector arguments and unicode-range values print verbatim, mixed-channel rgb() stays invalid, hashes in non-color functions keep their case, and the value-context flag resets between parses. HTML: adoption-agency clones and reconstructed formatting elements are materialized instead of silently dropped, noscript children are re-escaped, downlevel-revealed conditional closers survive, and plaintext never gets an end tag.
1 parent aafc985 commit b53f3fb

4 files changed

Lines changed: 286 additions & 15 deletions

File tree

‎lib/css/syntax.js‎

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1783,6 +1783,8 @@ const _setupParse = (input, lc) => {
17831783
// Only `grammar` re-enables it (after this call); the standalone `parseA*`
17841784
// entry points never print, so they must not inherit a previous parse's flag.
17851785
_printing = false;
1786+
// A visitor throw mid-value can leave the flag set; never carry it over.
1787+
_inValue = false;
17861788
};
17871789

17881790
/**
@@ -4166,6 +4168,20 @@ const _normalizeNumericToken = (text) =>
41664168
_normalizeNumber(text.slice(0, _numberEnd(text))) +
41674169
text.slice(_numberEnd(text));
41684170

4171+
// Value functions whose hash arguments are colors. A hash in any other function
4172+
// (`-moz-element(#id)`, `url()`-like references) is a case-sensitive reference.
4173+
const _COLOR_HASH_FUNCTIONS = new Set([
4174+
"linear-gradient",
4175+
"radial-gradient",
4176+
"conic-gradient",
4177+
"repeating-linear-gradient",
4178+
"repeating-radial-gradient",
4179+
"repeating-conic-gradient",
4180+
"color-mix",
4181+
"cross-fade",
4182+
"image"
4183+
]);
4184+
41694185
const _HEX = "0123456789abcdef";
41704186

41714187
/**
@@ -4307,15 +4323,23 @@ const _minifyColorFunction = (name, inner) => {
43074323
/** @type {number[]} */
43084324
const channels = [];
43094325
let alpha = 1;
4326+
let percentChannelCount = 0;
43104327
for (let i = 0; i < args.length; i++) {
43114328
const s = args[i];
43124329
if (!/^[+-]?(?:\d+\.?\d*|\.\d+)%?$/.test(s)) return null;
43134330
const pct = s.endsWith("%");
43144331
const v = Number.parseFloat(pct ? s.slice(0, -1) : s);
43154332
if (Number.isNaN(v)) return null;
4316-
if (i === 3) alpha = pct ? v / 100 : v;
4317-
else channels.push(_clamp255(pct ? (v * 255) / 100 : v));
4333+
if (i === 3) {
4334+
alpha = pct ? v / 100 : v;
4335+
} else {
4336+
if (pct) percentChannelCount++;
4337+
channels.push(_clamp255(pct ? (v * 255) / 100 : v));
4338+
}
43184339
}
4340+
// Mixed number/percentage channels are invalid CSS (ignored by browsers);
4341+
// rewriting would activate a dead declaration.
4342+
if (percentChannelCount !== 0 && percentChannelCount !== 3) return null;
43194343
// Fully transparent *black* only — `transparent` is `rgba(0,0,0,0)`, so a
43204344
// non-black transparent (e.g. `rgba(255,0,0,0)`) is a different value.
43214345
if (
@@ -4358,7 +4382,9 @@ const printer = (path, writer) => {
43584382
case T_PERCENTAGE:
43594383
case T_DIMENSION: {
43604384
const raw = path.source();
4361-
return minify ? _normalizeNumericToken(raw) : raw;
4385+
// Only declaration values: a prelude number is An+B (`2n+1`) or similar,
4386+
// where stripping a `+` breaks the selector.
4387+
return minify && path.inValue() ? _normalizeNumericToken(raw) : raw;
43624388
}
43634389
case T_FUNCTION: {
43644390
const name = path.name();
@@ -4385,9 +4411,11 @@ const printer = (path, writer) => {
43854411
const children = path.children();
43864412
let value = "";
43874413
if (children.length !== 0) {
4388-
if (name.startsWith("--")) {
4414+
if (name.startsWith("--") || name.toLowerCase() === "unicode-range") {
43894415
// Custom-property value: verbatim (its internal whitespace matters), so
43904416
// concatenate the children's raw source rather than their printed text.
4417+
// unicode-range too: its `U+…` tokenizes as numbers, which numeric
4418+
// normalization would corrupt.
43914419
value = children.map((c) => path.source(c)).join("");
43924420
} else {
43934421
// Value hashes were already shortened by the hash printer (they print
@@ -4455,6 +4483,15 @@ const printer = (path, writer) => {
44554483
// (`#Abc{}`, `:not(#Abc)`) — ids are case-sensitive, so shorten only the
44564484
// former. Works at any value depth (e.g. inside a gradient).
44574485
if (!minify || !path.inValue()) return raw;
4486+
// Inside a function, only known color functions take color hashes.
4487+
const parent = path.parent;
4488+
if (
4489+
parent !== null &&
4490+
path.type(parent) === T_FUNCTION &&
4491+
!_COLOR_HASH_FUNCTIONS.has(path.name(parent).toLowerCase())
4492+
) {
4493+
return raw;
4494+
}
44584495
const short = _minifyHash(raw);
44594496
return short === null ? raw : short;
44604497
}

‎lib/html/syntax.js‎

Lines changed: 71 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8403,10 +8403,22 @@ const _LITERAL_TEXT_PARENTS = new Set([
84038403
"iframe",
84048404
"noembed",
84058405
"noframes",
8406-
"noscript",
84078406
"plaintext"
84088407
]);
84098408

8409+
// The only elements this printer may leave transparent when they lack a source
8410+
// tag: the parser re-implies them identically on re-parse. Any other tag-less
8411+
// element (adoption-agency clone, reconstructed formatting element, renamed
8412+
// token) must be materialized or the DOM changes.
8413+
const _TRANSPARENT_IMPLIED_ELEMENTS = new Set([
8414+
"html",
8415+
"head",
8416+
"body",
8417+
"colgroup",
8418+
"tbody",
8419+
"tr"
8420+
]);
8421+
84108422
// Elements the parser strips one leading newline from: when the serialized body
84118423
// still begins with a newline, one is re-added so it round-trips to the same DOM.
84128424
const _LEADING_NEWLINE_ELEMENTS = new Set(["pre", "textarea", "listing"]);
@@ -8435,6 +8447,29 @@ const _escapeTextContent = (s) => {
84358447
return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
84368448
};
84378449

8450+
/**
8451+
* Rebuild an opening tag from the node's name and attributes, for elements with
8452+
* no matching source tag (adoption-agency clones, reconstructed formatting
8453+
* elements, renamed tokens like `<image>`). Attribute values are raw
8454+
* (undecoded), so they re-parse to the original decoded values.
8455+
* @param {HtmlPath} path the accessor positioned on the element
8456+
* @returns {string} serialized opening tag
8457+
*/
8458+
const _synthesizeOpenTag = (path) => {
8459+
let out = `<${path.tagName()}`;
8460+
for (const attribute of path.attributes()) {
8461+
const name =
8462+
attribute.serializedName !== undefined
8463+
? attribute.serializedName
8464+
: attribute.name;
8465+
out +=
8466+
attribute.value === ""
8467+
? ` ${name}`
8468+
: ` ${name}="${attribute.value.replace(/"/g, "&quot;")}"`;
8469+
}
8470+
return `${out}>`;
8471+
};
8472+
84388473
/**
84398474
* Whether a comment must survive minification: downlevel conditional comments
84408475
* (`<!--[if …]>` / `<![endif]-->`) drive IE branching, server-side includes
@@ -8450,7 +8485,14 @@ const _keepComment = (data, source) => {
84508485
// are server-side directives, so they outrank the inert-comment rule.
84518486
if (source.charCodeAt(1) === 63) return true;
84528487
const s = data.trimStart();
8453-
return s.startsWith("[if") || s.startsWith("[endif") || s.startsWith("#");
8488+
// `<![` covers the downlevel-revealed forms: `<!--<![endif]-->` closers and
8489+
// standalone `<![if …]>` openers.
8490+
return (
8491+
s.startsWith("[if") ||
8492+
s.startsWith("[endif") ||
8493+
s.startsWith("<![") ||
8494+
s.startsWith("#")
8495+
);
84548496
};
84558497

84568498
/**
@@ -8474,8 +8516,11 @@ const printer = (path, writer) => {
84748516
switch (path.type()) {
84758517
case NodeType.Element: {
84768518
const open = path.openTag();
8477-
// Void / self-closing elements have no children and no end tag.
8478-
if (path.selfClosing()) return open;
8519+
// Void / self-closing elements have no children and no end tag; a
8520+
// tag-less one (`<image>` → img, `</br>` → br) is rebuilt, not dropped.
8521+
if (path.selfClosing()) {
8522+
return open !== "" ? open : _synthesizeOpenTag(path);
8523+
}
84798524
// `<template>` holds its children in a content fragment, not the child
84808525
// chain; every other element reconstructs from its children in order.
84818526
const tc = path.templateContent();
@@ -8495,13 +8540,28 @@ const printer = (path, writer) => {
84958540
inner = `\n${inner}`;
84968541
}
84978542
}
8498-
// A parser-inserted element (auto `html`/`head`/`body`/`tbody`, …) has no
8499-
// source tag; it stays transparent — emit only its children — so the
8500-
// output keeps the source's element shape instead of materializing it.
8501-
if (open === "") return inner;
8502-
// A source self-closing tag (`<rect/>` in foreign content) with no
8503-
// children needs no end tag; only `>`-closed elements get one.
8504-
const close = inner === "" && open.endsWith("/>") ? "" : path.closeTag();
8543+
const name = path.tagName();
8544+
if (open === "") {
8545+
// A parser-implied structural element stays transparent — the parser
8546+
// re-implies it — but only when attribute-less (repeated `<html>` /
8547+
// `<body>` tags merge attributes onto the implied element).
8548+
if (
8549+
path.attributeCount() === 0 &&
8550+
_TRANSPARENT_IMPLIED_ELEMENTS.has(name)
8551+
) {
8552+
return inner;
8553+
}
8554+
// Anything else tag-less (adoption-agency clone, reconstructed
8555+
// formatting element) must materialize or its formatting is lost.
8556+
return `${_synthesizeOpenTag(path) + inner}</${name}>`;
8557+
}
8558+
// Everything after `<plaintext>` is text; an emitted end tag would
8559+
// re-parse as literal text. A source self-closing tag (`<rect/>` in
8560+
// foreign content) with no children needs no end tag either.
8561+
const close =
8562+
name === "plaintext" || (inner === "" && open.endsWith("/>"))
8563+
? ""
8564+
: path.closeTag();
85058565
return open + inner + close;
85068566
}
85078567
case NodeType.Text: {

‎test/CssSyntax.unittest.js‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -925,6 +925,81 @@ describe("CssSyntax — minify keeps input the grammar rejects", () => {
925925
});
926926
});
927927

928+
describe("CssSyntax — minify value-safety edge cases", () => {
929+
/**
930+
* @param {string} src css source
931+
* @returns {string} the minified serialization
932+
*/
933+
const min = (src) =>
934+
new SourceProcessor().process(src, { minimize: true }).code;
935+
936+
it("keeps An+B selector arguments verbatim (no sign stripping)", () => {
937+
expect(min("a:nth-child(2n+1){b:c}")).toBe("a:nth-child(2n+1){b:c}");
938+
expect(min("a:nth-last-child(-n+3){b:c}")).toBe(
939+
"a:nth-last-child(-n+3){b:c}"
940+
);
941+
expect(min("a:nth-of-type(2n-1){b:c}")).toBe("a:nth-of-type(2n-1){b:c}");
942+
expect(min("a:nth-child(+3){b:c}")).toBe("a:nth-child(+3){b:c}");
943+
expect(min("a:nth-child(even){b:c}")).toBe("a:nth-child(even){b:c}");
944+
});
945+
946+
it("still normalizes numbers in declaration values", () => {
947+
expect(min("a{margin:+1.50px}")).toBe("a{margin:1.5px}");
948+
expect(min("a{margin:0.50px 1.0px 0}")).toBe("a{margin:.5px 1px 0}");
949+
});
950+
951+
it("keeps unicode-range values verbatim", () => {
952+
expect(min("@font-face{unicode-range:U+0025-00FF}")).toBe(
953+
"@font-face{unicode-range:U+0025-00FF}"
954+
);
955+
expect(min("@font-face{unicode-range:u+4??}")).toBe(
956+
"@font-face{unicode-range:u+4??}"
957+
);
958+
expect(min("@font-face{unicode-range:U+26}")).toBe(
959+
"@font-face{unicode-range:U+26}"
960+
);
961+
expect(min("@font-face{unicode-range:U+0-7F,U+80-FF}")).toBe(
962+
"@font-face{unicode-range:U+0-7F,U+80-FF}"
963+
);
964+
});
965+
966+
it("does not turn an invalid mixed-channel rgb() into a valid color", () => {
967+
expect(min("a{color:rgb(50%,100,30)}")).toBe("a{color:rgb(50%,100,30)}");
968+
expect(min("a{color:rgb(50%,100%,30)}")).toBe("a{color:rgb(50%,100%,30)}");
969+
});
970+
971+
it("still minifies all-number and all-percentage rgb()", () => {
972+
expect(min("a{color:rgb(255,0,0)}")).toBe("a{color:red}");
973+
expect(min("a{color:rgb(100%,0%,0%)}")).toBe("a{color:red}");
974+
});
975+
976+
it("keeps a hash inside a non-color function verbatim (id reference)", () => {
977+
expect(min("a{background:-moz-element(#Abc)}")).toBe(
978+
"a{background:-moz-element(#Abc)}"
979+
);
980+
});
981+
982+
it("still minifies top-level and gradient hashes as colors", () => {
983+
expect(min("a{color:#ABCDEF}")).toBe("a{color:#abcdef}");
984+
expect(min("a{b:linear-gradient(#AABBCC,#FF0000)}")).toBe(
985+
"a{b:linear-gradient(#abc,red)}"
986+
);
987+
});
988+
989+
it("does not leak the value context into the next parse after a visitor throw", () => {
990+
const processor = new SourceProcessor().use({
991+
[NodeType.Ident]: (
992+
/** @type {import("../lib/css/syntax").CssPath} */ path
993+
) => {
994+
if (path.inValue()) throw new Error("boom");
995+
}
996+
});
997+
expect(() => processor.process("a{color:red}")).toThrow("boom");
998+
// A leaked in-value flag would treat the selector hash as a color here.
999+
expect(min("#Face{color:red}")).toBe("#Face{color:red}");
1000+
});
1001+
});
1002+
9281003
describe("CssSyntax — nesting and error recovery", () => {
9291004
/**
9301005
* @param {string} src css source

0 commit comments

Comments
 (0)