Skip to content

Commit ccb722d

Browse files
fix: minify a style="" body as a rule's contents in every CSS minimizer (#748)
* fix: minify a `style=""` body as a rule's contents in every CSS minimizer webpack hands an HTML `style=""` to the renderer as `css` with `as: "block-contents"`. Only cssnano read a bare declaration list; csso and clean-css answered with nothing, erasing the attribute, lightningcss and swc failed to parse it, and esbuild rejected `as` as an unknown option. Each now drops `as` from its options and minifies the body inside a rule, reading the contents back out (webpack/webpack#22288). Claude-Session: https://claude.ai/code/session_01Vszf1WJhCqatsMQ2xZLF9x * fix: read a rule's contents past a quoted brace, and keep the caller's options `ruleBody` now skips braces inside strings and comments instead of declining the rule, `esbuildMinifyCss` no longer deletes `as` from the options object it is handed, and `swcMinifyCss` drops a map the options asked for when the body was wrapped. Claude-Session: https://claude.ai/code/session_01Vszf1WJhCqatsMQ2xZLF9x * test: run the CSS minimizer block-contents cases only where they install cssnano@8 reaches for `Array.prototype.difference`, so the Node < 22 and Windows rows skip them through `RUN_CSS_TESTS`, like `css-minify-option`. Claude-Session: https://claude.ai/code/session_01Vszf1WJhCqatsMQ2xZLF9x * test: cover an escaped brace and a string or comment left open in `ruleBody` The comment check loses its `closed + 2 > end` half, which an answer ending in `}` can never reach. Claude-Session: https://claude.ai/code/session_01Vszf1WJhCqatsMQ2xZLF9x * test: run the csso and clean-css block-contents cases on every row Both are plain JavaScript supporting Node 10, so only cssnano and the native minimizers stay behind `RUN_CSS_TESTS`. The page cases assert their output instead of snapshotting it: a snapshot in a skipped block is reported obsolete, which fails a `--ci` row. Claude-Session: https://claude.ai/code/session_01Vszf1WJhCqatsMQ2xZLF9x * fix: read a rule's contents past a block a custom property's value holds `ruleBody` now tracks brace depth instead of declining any unquoted brace, so `--x:{a:b}` in a `style=""` is minified; a second rule or a block left open still declines. Claude-Session: https://claude.ai/code/session_01Vszf1WJhCqatsMQ2xZLF9x
1 parent 55cadc3 commit ccb722d

4 files changed

Lines changed: 409 additions & 30 deletions

File tree

‎.changeset/css-block-contents.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"minimizer-webpack-plugin": patch
3+
---
4+
5+
Minify a `style=""` body as a rule's contents with every CSS minimizer, rather than dropping or rejecting it.

‎src/utils.js‎

Lines changed: 184 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ const path = require("path");
2222
const CLASSIC_SCRIPT = "script";
2323
const MODULE_SCRIPT = "module";
2424
const EVENT_HANDLER = "event-handler";
25+
const BLOCK_CONTENTS = "block-contents";
2526

2627
/**
2728
* The function a body handed out as an event handler belongs to. Named past any
@@ -61,6 +62,68 @@ function functionBody(answered) {
6162
: undefined;
6263
}
6364

65+
/**
66+
* The rule a body handed out as a block's contents belongs to, since no
67+
* stylesheet production reads a bare declaration list. The newline ends a bad
68+
* string the body may close with.
69+
* @param {string} body the block's contents
70+
* @returns {string} the stylesheet it is the contents of
71+
*/
72+
function asRule(body) {
73+
return `a{${body}\n}`;
74+
}
75+
76+
/**
77+
* The block's contents inside the rule a minimizer answered with: empty where
78+
* it dropped the rule as holding nothing, `undefined` for any other answer.
79+
* @param {string | undefined} answered what the minimizer answered
80+
* @returns {string | undefined} the contents, or undefined
81+
*/
82+
function ruleBody(answered) {
83+
if (typeof answered !== "string") return undefined;
84+
85+
const written = answered.trim();
86+
87+
if (written === "") return "";
88+
89+
const opened = /^a\s*\{/.exec(written);
90+
91+
if (!opened || !written.endsWith("}")) return undefined;
92+
93+
const end = written.length - 1;
94+
95+
let depth = 0;
96+
97+
// A brace a string or a comment holds is text rather than a block's edge, and
98+
// one left open would reach past the brace closing the rule.
99+
for (let i = opened[0].length; i < end; i++) {
100+
const char = written[i];
101+
102+
if (char === "{") {
103+
depth++;
104+
} else if (char === "}") {
105+
// Below zero is this rule closing before the answer ends.
106+
if (--depth < 0) return undefined;
107+
} else if (char === "\\") {
108+
i++;
109+
} else if (char === '"' || char === "'") {
110+
for (i++; i < end && written[i] !== char; i++) {
111+
if (written[i] === "\\") i++;
112+
}
113+
114+
if (i >= end) return undefined;
115+
} else if (char === "/" && written[i + 1] === "*") {
116+
const closed = written.indexOf("*/", i + 2);
117+
118+
if (closed === -1) return undefined;
119+
120+
i = closed + 1;
121+
}
122+
}
123+
124+
return depth === 0 ? written.slice(opened[0].length, end).trim() : undefined;
125+
}
126+
64127
/**
65128
* The version a package reports. Read by walking up from its resolved entry
66129
* point rather than by requiring `<name>/package.json`, which a package whose
@@ -1682,14 +1745,30 @@ async function cssoMinify(input, sourceMap, minimizerOptions) {
16821745
return { errors: [/** @type {Error} */ (err)] };
16831746
}
16841747

1748+
// Self-require rather than the bindings above: a minify function reaches a
1749+
// worker as its source, where this module's own scope is gone.
1750+
const { BLOCK_CONTENTS, asRule, ruleBody } =
1751+
// eslint-disable-next-line import/no-self-import
1752+
require("./utils.js");
1753+
1754+
const { as, ...cssoOptions } = minimizerOptions || {};
1755+
const contents = as === BLOCK_CONTENTS;
16851756
const [[filename, source]] = Object.entries(input);
16861757
const code = Buffer.isBuffer(source) ? source.toString() : source;
1687-
const result = csso.minify(code, {
1758+
const result = csso.minify(contents ? asRule(code) : code, {
16881759
filename,
16891760
sourceMap: Boolean(sourceMap),
1690-
...minimizerOptions,
1761+
...cssoOptions,
16911762
});
16921763

1764+
if (contents) {
1765+
const body = ruleBody(result.css);
1766+
1767+
// A wrap moves every position, so the map describes a stylesheet that is
1768+
// not what comes back.
1769+
return { code: body === undefined ? code : body };
1770+
}
1771+
16931772
return {
16941773
code: result.css,
16951774
map: result.map
@@ -1740,13 +1819,33 @@ async function cleanCssMinify(input, sourceMap, minimizerOptions) {
17401819
return { errors: [/** @type {Error} */ (err)] };
17411820
}
17421821

1822+
// Self-require rather than the bindings above: a minify function reaches a
1823+
// worker as its source, where this module's own scope is gone.
1824+
const { BLOCK_CONTENTS, asRule, ruleBody } =
1825+
// eslint-disable-next-line import/no-self-import
1826+
require("./utils.js");
1827+
1828+
const { as, ...cleanCssOptions } = minimizerOptions || {};
1829+
const contents = as === BLOCK_CONTENTS;
17431830
const [[name, source]] = Object.entries(input);
17441831
const code = Buffer.isBuffer(source) ? source.toString() : source;
17451832
const result = await new CleanCSS({
17461833
sourceMap: Boolean(sourceMap),
1747-
...minimizerOptions,
1834+
...cleanCssOptions,
17481835
returnPromise: true,
1749-
}).minify({ [name]: { styles: code } });
1836+
}).minify({ [name]: { styles: contents ? asRule(code) : code } });
1837+
1838+
if (contents) {
1839+
const body = ruleBody(result.styles);
1840+
1841+
// A wrap moves every position, so the map describes a stylesheet that is
1842+
// not what comes back.
1843+
return {
1844+
code: body === undefined ? code : body,
1845+
warnings: result.warnings,
1846+
};
1847+
}
1848+
17501849
const generatedSourceMap = result.sourceMap
17511850
? /** @type {RawSourceMap} */ (
17521851
/** @type {{ toJSON(): RawSourceMap }} */ (
@@ -1809,25 +1908,26 @@ cleanCssMinify.filter = (name) => CSS_FILE_RE.test(name);
18091908
*/
18101909
async function esbuildMinifyCss(input, sourceMap, minimizerOptions) {
18111910
/**
1812-
* @param {import("esbuild").TransformOptions & { ecma?: string | number, module?: boolean }=} esbuildOptions esbuild options
1911+
* @param {import("esbuild").TransformOptions & { ecma?: string | number, module?: boolean, as?: string }=} esbuildOptions esbuild options
18131912
* @returns {import("esbuild").TransformOptions} built esbuild options
18141913
*/
1815-
const buildEsbuildOptions = (esbuildOptions = {}) => {
1914+
const buildEsbuildOptions = ({
18161915
// `module` and `ecma` are JavaScript-only concepts; the dispatcher
1817-
// injects them for every minimizer, but esbuild's CSS transform
1818-
// rejects unknown options.
1819-
delete esbuildOptions.ecma;
1820-
delete esbuildOptions.module;
1821-
1916+
// injects them for every minimizer, and `as` is the body's rather than
1917+
// esbuild's, but esbuild's CSS transform rejects unknown options.
1918+
ecma,
1919+
module,
1920+
as,
1921+
...esbuildOptions
1922+
} = {}) =>
18221923
// Need deep copy objects to avoid https://github.com/terser/terser/issues/366
1823-
return {
1924+
({
18241925
loader: "css",
18251926
minify: true,
18261927
legalComments: "inline",
18271928
...esbuildOptions,
18281929
sourcemap: false,
1829-
};
1830-
};
1930+
});
18311931

18321932
let esbuild;
18331933

@@ -1837,11 +1937,22 @@ async function esbuildMinifyCss(input, sourceMap, minimizerOptions) {
18371937
return { errors: [/** @type {Error} */ (err)] };
18381938
}
18391939

1940+
// Self-require rather than the bindings above: a minify function reaches a
1941+
// worker as its source, where this module's own scope is gone.
1942+
const { BLOCK_CONTENTS, asRule, ruleBody } =
1943+
// eslint-disable-next-line import/no-self-import
1944+
require("./utils.js");
1945+
1946+
const contents =
1947+
typeof minimizerOptions !== "undefined" &&
1948+
minimizerOptions.as === BLOCK_CONTENTS;
1949+
18401950
// Copy `esbuild` options
18411951
const esbuildOptions = buildEsbuildOptions(minimizerOptions);
18421952

1843-
// Let `esbuild` generate a SourceMap
1844-
if (sourceMap) {
1953+
// Let `esbuild` generate a SourceMap; a wrap moves every position, so the
1954+
// map would describe a stylesheet that is not what comes back.
1955+
if (sourceMap && !contents) {
18451956
esbuildOptions.sourcemap = true;
18461957
esbuildOptions.sourcesContent = false;
18471958
}
@@ -1851,10 +1962,14 @@ async function esbuildMinifyCss(input, sourceMap, minimizerOptions) {
18511962

18521963
esbuildOptions.sourcefile = filename;
18531964

1854-
const result = await esbuild.transform(code, esbuildOptions);
1965+
const result = await esbuild.transform(
1966+
contents ? asRule(code) : code,
1967+
esbuildOptions,
1968+
);
1969+
const body = contents ? ruleBody(result.code) : undefined;
18551970

18561971
return {
1857-
code: result.code,
1972+
code: contents ? (body === undefined ? code : body) : result.code,
18581973
map: result.map ? JSON.parse(result.map) : undefined,
18591974
warnings:
18601975
result.warnings.length > 0
@@ -1935,33 +2050,49 @@ async function lightningCssMinify(input, sourceMap, minimizerOptions) {
19352050
return { errors: [/** @type {Error} */ (err)] };
19362051
}
19372052

2053+
// Self-require rather than the bindings above: a minify function reaches a
2054+
// worker as its source, where this module's own scope is gone.
2055+
const { BLOCK_CONTENTS, asRule, ruleBody } =
2056+
// eslint-disable-next-line import/no-self-import
2057+
require("./utils.js");
2058+
2059+
const contents =
2060+
typeof minimizerOptions !== "undefined" &&
2061+
minimizerOptions.as === BLOCK_CONTENTS;
19382062
const [[filename, source]] = Object.entries(input);
19392063
const code = Buffer.isBuffer(source) ? source.toString() : source;
19402064
/**
1941-
* @param {Partial<import("lightningcss").TransformOptions<import("lightningcss").CustomAtRules>>=} lightningCssOptions lightning css options
2065+
* @param {Partial<import("lightningcss").TransformOptions<import("lightningcss").CustomAtRules>> & { as?: string }=} lightningCssOptions lightning css options
19422066
* @returns {import("lightningcss").TransformOptions<import("lightningcss").CustomAtRules>} built lightning css options
19432067
*/
1944-
const buildLightningCssOptions = (lightningCssOptions = {}) =>
2068+
const buildLightningCssOptions = ({ as, ...lightningCssOptions } = {}) =>
19452069
// Need deep copy objects to avoid https://github.com/terser/terser/issues/366
19462070
({
19472071
minify: true,
19482072
...lightningCssOptions,
19492073
sourceMap: false,
19502074
filename,
1951-
code: new Uint8Array(Buffer.from(code)),
2075+
code: new Uint8Array(Buffer.from(contents ? asRule(code) : code)),
19522076
});
19532077

19542078
// Copy `lightningCss` options
19552079
const lightningCssOptions = buildLightningCssOptions(minimizerOptions);
19562080

19572081
// Let `lightningcss` generate a SourceMap. The dispatcher in
1958-
// `minify.js` chains the previous step's map onto this one.
1959-
if (sourceMap) {
2082+
// `minify.js` chains the previous step's map onto this one. A wrap moves
2083+
// every position, so the map would describe what does not come back.
2084+
if (sourceMap && !contents) {
19602085
lightningCssOptions.sourceMap = true;
19612086
}
19622087

19632088
const result = lightningCss.transform(lightningCssOptions);
19642089

2090+
if (contents) {
2091+
const body = ruleBody(result.code.toString());
2092+
2093+
return { code: body === undefined ? code : body };
2094+
}
2095+
19652096
return {
19662097
code: result.code.toString(),
19672098
map: result.map ? JSON.parse(result.map.toString()) : undefined,
@@ -2027,28 +2158,49 @@ async function swcMinifyCss(input, sourceMap, minimizerOptions) {
20272158
return { errors: [/** @type {Error} */ (err)] };
20282159
}
20292160

2161+
// Self-require rather than the bindings above: a minify function reaches a
2162+
// worker as its source, where this module's own scope is gone.
2163+
const { BLOCK_CONTENTS, asRule, ruleBody } =
2164+
// eslint-disable-next-line import/no-self-import
2165+
require("./utils.js");
2166+
2167+
const contents =
2168+
typeof minimizerOptions !== "undefined" &&
2169+
minimizerOptions.as === BLOCK_CONTENTS;
20302170
const [[filename, source]] = Object.entries(input);
20312171
const code = Buffer.isBuffer(source) ? source.toString() : source;
20322172
/**
2033-
* @param {Partial<import("@swc/css").MinifyOptions>=} swcOptions swc options
2173+
* @param {Partial<import("@swc/css").MinifyOptions> & { as?: string }=} swcOptions swc options
20342174
* @returns {import("@swc/css").MinifyOptions} built swc options
20352175
*/
2036-
const buildSwcOptions = (swcOptions = {}) =>
2176+
const buildSwcOptions = ({ as, ...swcOptions } = {}) =>
20372177
// Need deep copy objects to avoid https://github.com/terser/terser/issues/366
20382178
({ ...swcOptions, filename });
20392179

20402180
// Copy `swc` options
20412181
const swcOptions = buildSwcOptions(minimizerOptions);
20422182

2043-
// Let `swc` generate a SourceMap
2044-
if (sourceMap) {
2183+
// Let `swc` generate a SourceMap; a wrap moves every position, so the map
2184+
// would describe a stylesheet that is not what comes back, whatever the
2185+
// options asked for.
2186+
if (contents) {
2187+
swcOptions.sourceMap = false;
2188+
} else if (sourceMap) {
20452189
swcOptions.sourceMap = true;
20462190
}
20472191

2048-
const result = await swc.minify(Buffer.from(code), swcOptions);
2192+
const result = await swc.minify(
2193+
Buffer.from(contents ? asRule(code) : code),
2194+
swcOptions,
2195+
);
2196+
const body = contents ? ruleBody(result.code.toString()) : undefined;
20492197

20502198
return {
2051-
code: result.code.toString(),
2199+
code: contents
2200+
? body === undefined
2201+
? code
2202+
: body
2203+
: result.code.toString(),
20522204
map: result.map ? JSON.parse(result.map.toString()) : undefined,
20532205
errors: result.errors
20542206
? result.errors.map(swcCssDiagnosticToError)
@@ -3796,10 +3948,12 @@ compress.supportsWorker = () => false;
37963948
compress.supportsWorkerThreads = () => false;
37973949

37983950
module.exports = {
3951+
BLOCK_CONTENTS,
37993952
CLASSIC_SCRIPT,
38003953
EVENT_HANDLER,
38013954
MODULE_SCRIPT,
38023955
asFunction,
3956+
asRule,
38033957
cleanCssMinify,
38043958
compress,
38053959
cssnanoMinify,
@@ -3825,6 +3979,7 @@ module.exports = {
38253979
packageVersion,
38263980
readPreset,
38273981
replaceExtension,
3982+
ruleBody,
38283983
sharpGenerate,
38293984
sharpMinify,
38303985
svgoMinify,

0 commit comments

Comments
 (0)