Skip to content

Commit fc9dc8c

Browse files
authored
feat(html): minify the document an <iframe srcdoc> holds (#21767)
* feat(html): minify the document an <iframe srcdoc> holds Adds `optimization.minimize.html.minifySrcdoc`, off by default. The body is a whole document of its own, so like a conditional comment's it cannot be minified where it is found: the values are recorded, minified, and put back into the source, which is then minified as usual. A nested iframe recurses. * fix(html): scope the srcdoc minifier and quote what it writes back An `<iframe>` in foreign content is an SVG or MathML element sharing the name, so its `srcdoc` is not this attribute and its value is left alone. A value written without quotes gains them: a document holds spaces and `>`, either of which would end a bare value and swallow the attribute after it. * fix(html): minify a conditional comment inside a srcdoc too The nested body went through a bare processor, so a downlevel-hidden conditional comment in there kept its unminified markup when both options were on. Both nested languages now go through one whole-document function, which the srcdoc pass recurses into. * fix(html): put a conditional comment's body back by offset Rewriting it with `replace` found the body's first occurrence, which is inside the condition when the condition reads the same — `<!--[if IE ]> IE` had its condition minified and its body left alone. The offsets are recorded instead of the text. * fix(html): put a conditional comment back where it was parsed Splicing it into the output rewrote every identical string there, so the same markup written inside a script was minified as if it were the comment. The body now goes back into the source by offset, the way a srcdoc's does, which drops the recording pass with it.
1 parent 6890ffc commit fc9dc8c

13 files changed

Lines changed: 292 additions & 46 deletions

File tree

‎.changeset/048-html-remove-redundant-attributes.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
"webpack": minor
33
---
44

5-
Minify HTML further: leave out the implied `<html>` tag and any optional end tag nothing prints behind, print an empty attribute value bare, write an attribute value in the fewest bytes that parse back the same, drop an empty attribute and a run of nested empty elements, fold an enumerated value to lower case, and add the `optimization.minimize.html` options `collapseWhitespace`, `mergeStyles`, `minifyConditionalComments`, `preserveComments`, `removeEmptyAttributes`, `removeEmptyElements`, `removeImpliedTags`, `removeRedundantAttributes`, `sortAttributes` and `sortTokenLists`.
5+
Minify HTML further: leave out the implied `<html>` tag and any optional end tag nothing prints behind, print an empty attribute value bare, write an attribute value in the fewest bytes that parse back the same, drop an empty attribute and a run of nested empty elements, fold an enumerated value to lower case, and add the `optimization.minimize.html` options `collapseWhitespace`, `mergeStyles`, `minifyConditionalComments`, `minifySrcdoc` (minify the document an `<iframe srcdoc>` holds), `preserveComments`, `removeEmptyAttributes`, `removeEmptyElements`, `removeImpliedTags`, `removeRedundantAttributes`, `sortAttributes` and `sortTokenLists`.

‎declarations/WebpackOptions.d.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2445,6 +2445,11 @@ export interface OptimizationMinimizeHtml {
24452445
* @since 5.110.0
24462446
*/
24472447
minifyConditionalComments?: boolean;
2448+
/**
2449+
* Minify the document held in an `<iframe srcdoc>` attribute. Off by default: the body is a whole document of its own (its base URL is `about:srcdoc`), so minifying it is safe, but the attribute is readable from script and a consumer comparing `iframe.srcdoc` byte for byte would see it change.
2450+
* @since 5.110.0
2451+
*/
2452+
minifySrcdoc?: boolean;
24482453
/**
24492454
* Patterns naming comments to keep, on top of the ones minifying always keeps (downlevel conditional comments, server-side includes and template directives). A string is read as a regular expression source and matched against the comment's text.
24502455
* @since 5.110.0

‎lib/html/htmlMinify.js‎

Lines changed: 90 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
* re-resolves in the worker — via the installed package, or the dev self-link.
2424
* @param {{ [file: string]: string }} input a single `{ filename: code }` entry
2525
* @param {(RawSourceMap | undefined)=} sourceMap input source map (unused: safe serialize keeps positions token-coarse, so no map is produced yet)
26-
* @param {HtmlPrintOptions & { minifyConditionalComments?: boolean }=} minimizerOptions minimizer options — `environment`, `convertLengthUnits` and `rewriteCustomProperties` reach the CSS minifier this runs over inline CSS; the rest is `optimization.minimize.html`
26+
* @param {HtmlPrintOptions & { minifyConditionalComments?: boolean, minifySrcdoc?: boolean }=} minimizerOptions minimizer options — `environment`, `convertLengthUnits` and `rewriteCustomProperties` reach the CSS minifier this runs over inline CSS; the rest is `optimization.minimize.html`
2727
* @returns {{ code: string }} the minified HTML
2828
*/
2929
const htmlMinify = (input, sourceMap, minimizerOptions = {}) => {
@@ -40,7 +40,13 @@ const htmlMinify = (input, sourceMap, minimizerOptions = {}) => {
4040
// parses but change the attribute string a script reads back, so a consumer
4141
// that compares those bytes wants a way to turn each off. Room to widen them
4242
// too: any boolean value rather than only the canonical spellings.
43-
const { SourceProcessor, NodeType } = webpack.html.syntax;
43+
const {
44+
SourceProcessor,
45+
NodeType,
46+
NS_HTML,
47+
decodeEntities,
48+
escapeAttribute
49+
} = webpack.html.syntax;
4450
const [[, code]] = Object.entries(input);
4551
// The nested CSS minifier gets the abilities and options a `.css` asset
4652
// gets, or the inline copy of a declaration would disagree with it.
@@ -55,6 +61,7 @@ const htmlMinify = (input, sourceMap, minimizerOptions = {}) => {
5561
preserveComments,
5662
removeRedundantAttributes,
5763
minifyConditionalComments,
64+
minifySrcdoc,
5865
sortAttributes,
5966
sortTokenLists,
6067
removeImpliedTags
@@ -76,49 +83,88 @@ const htmlMinify = (input, sourceMap, minimizerOptions = {}) => {
7683
sortTokenLists,
7784
removeImpliedTags
7885
};
79-
// A downlevel-hidden conditional comment holds markup, and it cannot be
80-
// minified where it is found: the visitor that finds it runs inside the
81-
// document's own parse, and the walk state is module-scoped, so `grammar`
82-
// refuses to start a second one. The bodies are therefore recorded as the
83-
// document prints — a visitor rides the walk that prints, so this costs no
84-
// extra parse — and each is minified afterwards and spliced in by exact
85-
// source text, never by a pattern over the output, which would find a
86-
// `<!--[if` written inside a script.
87-
/** @type {Map<string, string>} */
88-
const conditionals = new Map();
89-
// One processor for both passes. It stops recording once the document is
90-
// printed, so a body carrying something that looks like another conditional
91-
// comment cannot write into the map being read below.
92-
let recording = true;
93-
const processor = new SourceProcessor();
94-
if (minifyConditionalComments) {
95-
processor.use({
96-
[NodeType.Comment]: (path) => {
97-
if (!recording) return;
98-
const source = path.source();
99-
const opened = source.indexOf("]>");
100-
const closes = source.lastIndexOf("<![endif]");
101-
if (!/^<!--\[if\s/i.test(source) || opened === -1 || closes <= opened) {
102-
return;
103-
}
104-
conditionals.set(source, source.slice(opened + 2, closes));
86+
// Recursion goes through this local name, never the module's own: the plugin
87+
// ships this function to its workers as source, where that binding is absent.
88+
/**
89+
* @param {string} text a whole document
90+
* @returns {string} the same document, minified
91+
*/
92+
const minifyDocument = (text) => {
93+
// Put back into the source, not the output: the printer respells an
94+
// attribute value, so the recorded text is not what the output holds.
95+
let source = text;
96+
// Spelt as an attribute with a value: one written bare carries no document.
97+
if (minifySrcdoc && /srcdoc\s*=/i.test(source)) {
98+
/** @type {{ start: number, end: number, value: string }[]} */
99+
const found = [];
100+
new SourceProcessor()
101+
.use({
102+
[NodeType.Element]: (path) => {
103+
// An `<iframe>` in foreign content is an SVG or MathML element that
104+
// happens to share the name, and its `srcdoc` is not this attribute.
105+
if (path.tagName() !== "iframe" || path.namespace() !== NS_HTML) {
106+
return;
107+
}
108+
for (const attribute of path.attributes()) {
109+
if (attribute.name !== "srcdoc" || attribute.value === "") {
110+
continue;
111+
}
112+
found.push({
113+
start: attribute.valueStart,
114+
end: attribute.valueEnd,
115+
value: attribute.value
116+
});
117+
}
118+
}
119+
})
120+
.process(source, {});
121+
// Back to front, so an earlier splice does not move a later range.
122+
for (let i = found.length - 1; i >= 0; i--) {
123+
const { start, end, value } = found[i];
124+
const inner = minifyDocument(decodeEntities(value, true));
125+
// A document is not something an unquoted value can hold — a space or a
126+
// `>` in it would end the attribute — so one written bare gets quotes.
127+
const delimiter = source.charCodeAt(start - 1);
128+
const quoted = delimiter === 34 || delimiter === 39;
129+
const written = escapeAttribute(inner, quoted ? delimiter : 34, true);
130+
source = `${source.slice(0, start)}${quoted ? written : `"${written}"`}${source.slice(end)}`;
131+
}
132+
}
133+
// Same shape as the srcdoc pass above, and for the same reason: the body is
134+
// markup this parse cannot start a second one over.
135+
if (minifyConditionalComments && /<!--\[if\s/i.test(source)) {
136+
/** @type {[number, number][]} */
137+
const found = [];
138+
new SourceProcessor()
139+
.use({
140+
[NodeType.Comment]: (path) => {
141+
const comment = path.source();
142+
const opened = comment.indexOf("]>");
143+
const closes = comment.lastIndexOf("<![endif]");
144+
if (
145+
!/^<!--\[if\s/i.test(comment) ||
146+
opened === -1 ||
147+
closes <= opened
148+
) {
149+
return;
150+
}
151+
found.push([path.start() + opened + 2, path.start() + closes]);
152+
}
153+
})
154+
.process(source, {});
155+
// Back to front, so an earlier splice does not move a later range.
156+
for (let i = found.length - 1; i >= 0; i--) {
157+
const [start, end] = found[i];
158+
const body = source.slice(start, end);
159+
source = `${source.slice(0, start)}${minifyDocument(body)}${source.slice(end)}`;
105160
}
106-
});
107-
}
108-
// `process` parses once, and with `mode: "minify"` its walk also prints the
109-
// safely minified serialization — no second parse. No `source` is named, so no
110-
// map is built: the HTML serialize is token-coarse and only the code is used.
111-
const { code: out } = processor.process(code, printOptions);
112-
recording = false;
113-
if (conditionals.size === 0) return { code: out };
114-
let spliced = out;
115-
for (const [source, body] of conditionals) {
116-
if (!spliced.includes(source)) continue;
117-
const { code: minified } = processor.process(body, printOptions);
118-
if (minified === body) continue;
119-
spliced = spliced.split(source).join(source.replace(body, minified));
120-
}
121-
return { code: spliced };
161+
}
162+
// `process` parses once, and with `mode: "minify"` its walk also prints the
163+
// safely minified serialization — no second parse. No `source` is named, so no
164+
// map is built: the HTML serialize is token-coarse and only the code is used.
165+
return new SourceProcessor().process(source, printOptions).code;
166+
};
167+
return { code: minifyDocument(code) };
122168
};
123169

124170
// Worker-safe (see the body's in-worker `require`), so it may run in the shared

‎schemas/WebpackOptions.check.js‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎schemas/WebpackOptions.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3793,6 +3793,11 @@
37933793
"type": "boolean",
37943794
"added": "5.110.0"
37953795
},
3796+
"minifySrcdoc": {
3797+
"description": "Minify the document held in an `<iframe srcdoc>` attribute. Off by default: the body is a whole document of its own (its base URL is `about:srcdoc`), so minifying it is safe, but the attribute is readable from script and a consumer comparing `iframe.srcdoc` byte for byte would see it change.",
3798+
"type": "boolean",
3799+
"added": "5.110.0"
3800+
},
37963801
"preserveComments": {
37973802
"description": "Patterns naming comments to keep, on top of the ones minifying always keeps (downlevel conditional comments, server-side includes and template directives). A string is read as a regular expression source and matched against the comment's text.",
37983803
"type": "array",

‎test/__snapshots__/Cli.basictest.js.snap‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11194,6 +11194,19 @@ Object {
1119411194
"multiple": false,
1119511195
"simpleType": "boolean",
1119611196
},
11197+
"optimization-minimize-html-minify-srcdoc": Object {
11198+
"configs": Array [
11199+
Object {
11200+
"description": "Minify the document held in an \`<iframe srcdoc>\` attribute. Off by default: the body is a whole document of its own (its base URL is \`about:srcdoc\`), so minifying it is safe, but the attribute is readable from script and a consumer comparing \`iframe.srcdoc\` byte for byte would see it change.",
11201+
"multiple": false,
11202+
"path": "optimization.minimize.html.minifySrcdoc",
11203+
"type": "boolean",
11204+
},
11205+
],
11206+
"description": "Minify the document held in an \`<iframe srcdoc>\` attribute. Off by default: the body is a whole document of its own (its base URL is \`about:srcdoc\`), so minifying it is safe, but the attribute is readable from script and a consumer comparing \`iframe.srcdoc\` byte for byte would see it change.",
11207+
"multiple": false,
11208+
"simpleType": "boolean",
11209+
},
1119711210
"optimization-minimize-html-preserve-comments": Object {
1119811211
"configs": Array [
1119911212
Object {
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2+
3+
exports[`ConfigCacheTestCases html minimize-srcdoc minimize-srcdoc should compile 1`] = `
4+
"<!doctype html><head><title>Srcdoc</title></head><body>
5+
<iframe id=basic srcdoc=\\"<p class=a>hi\\"></iframe>
6+
<iframe id=single srcdoc='<b>bold</b>'></iframe>
7+
<iframe id=nested srcdoc='<iframe srcdoc=\\"<i>deep</i>\\"></iframe>'></iframe>
8+
<iframe id=style srcdoc=\\"<style>.a{color:red}</style><p class=a>styled\\"></iframe>
9+
<iframe id=doctype srcdoc=\\"<!doctype html><body><p>whole</body></html>\\"></iframe>
10+
<iframe id=entities srcdoc=\\"<p>a & b &amp;lt; c\\"></iframe>
11+
<iframe id=quote-in-body srcdoc=\\"<p title=q>quoted\\"></iframe>
12+
<iframe id=upper srcdoc=\\"<em>up</em>\\"></iframe>
13+
<iframe id=conditional srcdoc=\\"<!--[if IE]><p class=ie>downlevel<![endif]-->\\"></iframe>
14+
<iframe id=bare srcdoc=\\"<p>bare\\" title=after></iframe>
15+
<!--[if IE ]>IE <![endif]-->
16+
<script type=application/json>{\\"cc\\":\\"<!--[if IE]><p >script</p><![endif]-->\\"}</script>
17+
<!--[if IE]><p>script<![endif]-->
18+
<iframe id=empty srcdoc></iframe>
19+
<iframe id=none src=child.html></iframe>
20+
<div id=not-an-iframe srcdoc=\\"<!-- kept --><p >div</p>\\"></div>
21+
<svg><iframe id=foreign srcdoc=\\"<!-- kept --><p >svg</p>\\"></iframe></svg>
22+
<p>the word srcdoc in text is not an attribute</p>
23+
24+
25+
</body></html>"
26+
`;
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2+
3+
exports[`ConfigTestCases html minimize-srcdoc minimize-srcdoc should compile 1`] = `
4+
"<!doctype html><head><title>Srcdoc</title></head><body>
5+
<iframe id=basic srcdoc=\\"<p class=a>hi\\"></iframe>
6+
<iframe id=single srcdoc='<b>bold</b>'></iframe>
7+
<iframe id=nested srcdoc='<iframe srcdoc=\\"<i>deep</i>\\"></iframe>'></iframe>
8+
<iframe id=style srcdoc=\\"<style>.a{color:red}</style><p class=a>styled\\"></iframe>
9+
<iframe id=doctype srcdoc=\\"<!doctype html><body><p>whole</body></html>\\"></iframe>
10+
<iframe id=entities srcdoc=\\"<p>a & b &amp;lt; c\\"></iframe>
11+
<iframe id=quote-in-body srcdoc=\\"<p title=q>quoted\\"></iframe>
12+
<iframe id=upper srcdoc=\\"<em>up</em>\\"></iframe>
13+
<iframe id=conditional srcdoc=\\"<!--[if IE]><p class=ie>downlevel<![endif]-->\\"></iframe>
14+
<iframe id=bare srcdoc=\\"<p>bare\\" title=after></iframe>
15+
<!--[if IE ]>IE <![endif]-->
16+
<script type=application/json>{\\"cc\\":\\"<!--[if IE]><p >script</p><![endif]-->\\"}</script>
17+
<!--[if IE]><p>script<![endif]-->
18+
<iframe id=empty srcdoc></iframe>
19+
<iframe id=none src=child.html></iframe>
20+
<div id=not-an-iframe srcdoc=\\"<!-- kept --><p >div</p>\\"></div>
21+
<svg><iframe id=foreign srcdoc=\\"<!-- kept --><p >svg</p>\\"></iframe></svg>
22+
<p>the word srcdoc in text is not an attribute</p>
23+
24+
25+
</body></html>"
26+
`;
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import "./page.html";
2+
3+
it("should minify the document held in an <iframe srcdoc>", () => {
4+
// The emitted page is the assertion — see the snapshot in test.config.js.
5+
expect(true).toBe(true);
6+
});
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<title>Srcdoc</title>
5+
</head>
6+
<body>
7+
<iframe id="basic" srcdoc="&lt;!-- dropped --&gt;&lt;p class=&quot;a&quot;&gt;hi&lt;/p&gt;"></iframe>
8+
<iframe id="single" srcdoc='&lt;!-- dropped --&gt;&lt;b &gt;bold&lt;/b&gt;'></iframe>
9+
<iframe id="nested" srcdoc="&lt;!-- dropped --&gt;&lt;iframe srcdoc=&quot;&amp;lt;!-- dropped --&amp;gt;&amp;lt;i &amp;gt;deep&amp;lt;/i&amp;gt;&quot;&gt;&lt;/iframe&gt;"></iframe>
10+
<iframe id="style" srcdoc="&lt;style&gt; .a { color : #ff0000 } &lt;/style&gt;&lt;p class=a&gt;styled&lt;/p&gt;"></iframe>
11+
<iframe id="doctype" srcdoc="&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;body&gt;&lt;p &gt;whole&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;"></iframe>
12+
<iframe id="entities" srcdoc="&lt;p&gt;a &amp;amp; b &amp;lt; c&lt;/p&gt;"></iframe>
13+
<iframe id="quote-in-body" srcdoc="&lt;p title=&quot;q&quot; &gt;quoted&lt;/p&gt;"></iframe>
14+
<iframe id="upper" SRCDOC="&lt;!-- dropped --&gt;&lt;em &gt;up&lt;/em&gt;"></iframe>
15+
<iframe id="conditional" srcdoc="&lt;!--[if IE]&gt;&lt;p class=&quot;ie&quot;&gt;downlevel&lt;/p&gt;&lt;![endif]--&gt;"></iframe>
16+
<iframe id="bare" srcdoc=&lt;!--dropped--&gt;&lt;p&gt;bare&lt;/p&gt; title="after"></iframe>
17+
<!--[if IE ]> IE <![endif]-->
18+
<script type="application/json">{"cc":"<!--[if IE]><p >script</p><![endif]-->"}</script>
19+
<!--[if IE]><p >script</p><![endif]-->
20+
<iframe id="empty" srcdoc=""></iframe>
21+
<iframe id="none" src="child.html"></iframe>
22+
<div id="not-an-iframe" srcdoc="&lt;!-- kept --&gt;&lt;p &gt;div&lt;/p&gt;"></div>
23+
<svg><iframe id="foreign" srcdoc="&lt;!-- kept --&gt;&lt;p &gt;svg&lt;/p&gt;"></iframe></svg>
24+
<p>the word srcdoc in text is not an attribute</p>
25+
</body>
26+
</html>

0 commit comments

Comments
 (0)