Skip to content

Commit 78aaae3

Browse files
test: hold EMBEDDED_LANGUAGES to the sites that offer it (#21936)
* test: hold EMBEDDED_LANGUAGES to the sites that offer it Both lists say a caller reads them to know which languages it handles, so each entry needs a live offer site behind it and nothing may arrive that the list does not name. Neither direction was checked: a language added with no site, or a site removed, showed up only as an unexplained snapshot diff somewhere else. One document and one stylesheet reach every site, and each test asserts the offered set against the exported list, then that the renderer's answer is what the serialization carries — being offered a body is only half of minifying it. * test: shorten the new comments to the test-file convention * test: bundle every embedded body a host can nest The offer sites were covered one level deep and in plain text. Three gaps, each now a real build: - A `data:` payload reached through base64 is decoded, minified and encoded back as base64. Only a declined `image/png;base64` was covered before. - A nested body nests bodies of its own: SVG through the CSS in an inline `<style>` and again through a `style` attribute, and CSS through the document an `<iframe srcdoc>` holds. - An `asset/inline` module is minified for every language a minimizer claims, not only CSS and SVG. * test: shorten the copied comment to the test-file convention * test: fold the embedded config cases back into one * test: cover the embedded surface in one case Every shape a host and a nested body can take, in one build each: - A document webpack parses as an entry, one it parses as a module, and one it only emits — each with an inline `<style>`, a `style` attribute, a `<script>`, a JSON `<script>`, an `<svg>` subtree and an `<iframe srcdoc>` carrying its own `<style>`, and each `<style>` carrying a `data:` SVG two levels down. Only the emitted-only document keeps its `<script>` inline, so it alone reaches a JavaScript minimizer there. - A stylesheet's `url()` payload in every language a media type names, plain and base64, plus an `image/png` naming none. - Every `exportType`: the one that emits a stylesheet, the one that exports its text, and the two that inject it — those last on a target whose runtime works without a document. - An `asset/source` and an `asset/inline` module of every language. * test: type the shared minimizer helper as an array * test: offer every embedded language in both configs The second config carried only terser and the css minifier, so the sheet its `style` / `css-style-sheet` export types embed kept its nested html, json and svg payloads unminified. Share one minimizer list, and assert the export contract rather than `typeof`, which accepts null. * test: one snapshot per embedded relationship Each host/language pair gets its own test rather than a handful of cases carrying hand-written substring expectations: the emitted fragment is isolated and snapshotted whole, so a regression next to the construct shows up instead of passing unread. * test: do not let a tag isolation depend on casing Match every html construct case-insensitively, and anchor the script one on the script it means rather than on any script element. * test: observe each css export type in its own build Reading the injected stylesheet off a globalThis registry made the test depend on state shared with every other case in the worker: the harness clears it before these deferred bodies run, so the assertion saw whatever case ran next. Build `style` for the web and read this case's document; leave `css-style-sheet` where no document exists, so its text is the one webpack wrote rather than one a parser reassembled. * test: name the css export type each stylesheet is built with `link` was covered only by omitting the rule, so nothing said which export type that case exercised or would notice if the default moved. * test: reach every language through a base64 data url Only svg and css were carried base64, so the decode, minify and re-encode path went untested for the three languages most likely to differ in it. * feat(html): minify an iframe srcdoc through the embedded path `minifySrcdoc` gated a pre-pass of its own, but not the offer: with a `renderEmbeddedSource` set — which is how webpack wires html, css and js minification together — the document was minified whatever the option said, so its default-off promise was never kept. The srcdoc is now one more embedded body, minified by webpack's own minifier when no caller answers for it, and the option is gone. Two printer changes keep the output where the pre-pass had it: the offer is made for a value written bare as well as a quoted one, and an attribute the renderer answered for is written with whichever delimiter needs fewer escapes, the source's breaking the tie. BREAKING CHANGE: `optimization.minimize.html.minifySrcdoc` is removed; an `<iframe srcdoc>` is minified whenever html minification is on. * feat(html): minify a JSON script through the embedded path A JSON `<script>` is an embedded body like any other: it is offered to whatever renderer a caller set, and minified by webpack's own minifier when nothing answers. `minifyJson` sat in front of that as a transform switch of its own, so turning it off also took the body away from a caller that had asked for it. `minifyStyles` stays: a `style=""` is not among the languages offered — how the attribute is written is read back off the minified text — so the switch still names something the embedded path does not reach. BREAKING CHANGE: `optimization.minimize.html.minifyJson` is removed; a JSON `<script>` is minified whenever html minification is on. * feat(html): minify inline css through the embedded path An inline `<style>` and a `style=""` are both offered as css — the attribute as the `block-contents` production it is — so `minifyStyles` sat in front of the same path `minifyJson` did, and turning it off took the body away from a caller that had asked for css. This corrects the reasoning in the previous commit, which kept the switch on the grounds that a `style=""` is not offered. It is: what `getEmbeddedTypes` leaves out is a separate language entry for it, not the offer, and a renderer is handed every one the document holds. BREAKING CHANGE: `optimization.minimize.html.minifyStyles` is removed; an inline `<style>` and a `style=""` are minified whenever html minification is on. * test: one document through every embedded site, with a renderer and without The two arms answer different questions. With a renderer, every site is offered exactly once — an inline `<style>`, a JSON `<script>`, a `<script>`, a `style=""` as the block-contents production it is, an `<svg>` subtree and one per `<iframe srcdoc>` — and each answer lands where it was asked for. Without one, the document records what webpack minifies on its own, which is also where it stops: a `<script>` of JavaScript, an `<svg>` subtree and every `data:` payload the inline `<style>` carries are left as written. A config case cannot drive the second arm: webpack's own pipeline always supplies a renderer once html, css and js minification share a minimizer. * test: one stylesheet through every embedded site, with a renderer and without The css host's counterpart to the html one. Each language is reached twice — written out and base64 — so the two arms also say that base64 is a spelling of the url rather than of the body: the same source is handed over both times, and an answer is re-encoded to match the url it came from. A media type naming no language and a url that is not a payload reach no renderer at all. Without a renderer the stylesheet around the bodies is minified and the bodies are not, webpack having nothing of its own to fall back to here. * test: cover the delimiter an answered srcdoc is written with Codecov read one line of the tie-break uncovered once every flag had uploaded, and the branch data named five more paths in the same helper: an answer holding only a quote of one kind, the source delimiter kept where the answer needs neither, a bare value quoted from its answer alone, and the deferring path declining. The last two need different callers to reach: htmlMinify hands every renderer to the deferring path, so the synchronous branch is only reachable through the print API. Declining there restores the raw value as the source spelled it, references and delimiter included, rather than the decoded document the renderer was shown -- which is what the test now states. * chore: bump the embedded-path changeset to patch HTML and CSS minification are experimental, so taking three options off `optimization.minimize.html` breaks no stable surface. The entry was also a count behind: it dropped three options, not two. * fix(html): take a style attribute's answer whatever quoting it needs A deferred `style=""` answer was declined whenever it disagreed with the built-in about whether the value could be written unquoted, so the built-in's text stood and the answer was dropped without a word. Only a foreign element's surviving `/>` reads that, to decide whether a space must precede it -- an html element's tag just ends. Hold the answer to the built-in's shape only where something reads it. The default build showed this as an inconsistency between two sites for the same language: a `data:` payload inside an inline `<style>` was minified while the identical one inside a `style=""` was left raw, because minifying it let the value go unquoted.
1 parent f5ef3cd commit 78aaae3

44 files changed

Lines changed: 1362 additions & 319 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Minify an embedded body through the embedded path, dropping three html options.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Take a minified `style` attribute's answer whatever quoting it needs.

‎declarations/WebpackOptions.d.ts‎

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2549,21 +2549,6 @@ export interface OptimizationMinimizeHtml {
25492549
* @since 5.110.0
25502550
*/
25512551
minifyConditionalComments?: boolean;
2552-
/**
2553-
* Strip the whitespace between the tokens of a `<script>` whose type is a JSON MIME type. Every literal is copied byte for byte, so no number is rounded and no escape rewritten. On by default.
2554-
* @since 5.110.0
2555-
*/
2556-
minifyJson?: boolean;
2557-
/**
2558-
* 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.
2559-
* @since 5.110.0
2560-
*/
2561-
minifySrcdoc?: boolean;
2562-
/**
2563-
* Run the CSS minimizer over an inline `<style>` element and every `style=""` attribute, with the options `optimization.minimize.css` names. On by default.
2564-
* @since 5.110.0
2565-
*/
2566-
minifyStyles?: boolean;
25672552
/**
25682553
* Write an attribute value with whichever delimiters cost least — bare where the grammar allows it, else under the quote that needs fewer character references. On by default: the DOM reads the same value either way.
25692554
* @since 5.110.0

‎lib/html/htmlMinify.js‎

Lines changed: 51 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
* re-resolves in the worker — via the installed package, or the dev self-link.
3535
* @param {{ [file: string]: string }} input a single `{ filename: code }` entry
3636
* @param {(RawSourceMap | undefined)=} sourceMap input source map (unused: safe serialize keeps positions token-coarse, so no map is produced yet)
37-
* @param {Omit<HtmlPrintOptions, "renderEmbeddedSource" | "deferEmbeddedSource"> & { css?: { convertLengthUnits?: boolean, rewriteCustomProperties?: boolean, unusedSymbols?: string[], pseudoClasses?: { [name: string]: string } }, minifyConditionalComments?: boolean, minifySrcdoc?: boolean, renderEmbeddedSource?: AsyncEmbeddedSourceRenderer }=} minimizerOptions minimizer options — `environment` and `css` (`optimization.minimize.css`, whole) reach the CSS minifier this runs over inline CSS; the rest is `optimization.minimize.html`. The two stand apart rather than merged: both languages name a `quotes` and a `comments`, and one flat object would hand each the other's answer. `renderEmbeddedSource` minifies source this document embeds and may be asynchronous — one parse serves both it and the output — and `minifySrcdoc` takes an `<iframe srcdoc>` back off it, since it minifies one already
37+
* @param {Omit<HtmlPrintOptions, "renderEmbeddedSource" | "deferEmbeddedSource"> & { css?: { convertLengthUnits?: boolean, rewriteCustomProperties?: boolean, unusedSymbols?: string[], pseudoClasses?: { [name: string]: string } }, minifyConditionalComments?: boolean, renderEmbeddedSource?: AsyncEmbeddedSourceRenderer }=} minimizerOptions minimizer options — `environment` and `css` (`optimization.minimize.css`, whole) reach the CSS minifier this runs over inline CSS; the rest is `optimization.minimize.html`. The two stand apart rather than merged: both languages name a `quotes` and a `comments`, and one flat object would hand each the other's answer. `renderEmbeddedSource` minifies source this document embeds and may be asynchronous — one parse serves both it and the output. What it declines this minifies itself, for the languages webpack ships a minifier for
3838
* @returns {Promise<{ code: string, warnings?: (Error | string)[], errors?: (Error | string)[] }>} the minified HTML, and what a renderer reported over what it embeds
3939
*/
4040
const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
@@ -52,9 +52,6 @@ const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
5252
embeddedText,
5353
SourceProcessor,
5454
NodeType,
55-
NS_HTML,
56-
decodeEntities,
57-
escapeAttribute,
5855
pickTransforms
5956
} = webpack.html.syntax;
6057
const [[, code]] = Object.entries(input);
@@ -69,16 +66,11 @@ const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
6966
removeEmptyElements,
7067
removeRedundantAttributes,
7168
minifyConditionalComments,
72-
minifySrcdoc,
7369
sortAttributes,
7470
sortTokenLists,
7571
removeImpliedTags,
7672
renderEmbeddedSource
7773
} = minimizerOptions;
78-
// A `<iframe srcdoc>` the pre-pass below owns is not offered, or the same
79-
// document would be minified twice — once each, and the pre-pass keeps the
80-
// delimiter and reaches a value written bare, which the printer cannot.
81-
const ownsSrcdoc = Boolean(minifySrcdoc);
8274
// One list for the whole run: a nested document reaches this same collector,
8375
// so what a renderer reports inside an `<iframe srcdoc>` is reported once at
8476
// the top rather than lost at the level that heard it.
@@ -108,13 +100,24 @@ const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
108100
// Handed each body the print offers, with what it reported kept: how the
109101
// element or attribute around one is written is decided from the answer, and
110102
// a body declined or thrown on is spelled as an untapped run spells it.
111-
const renderer =
112-
renderEmbeddedSource === undefined
113-
? undefined
114-
: (/** @type {string} */ _source, /** @type {EXPECTED_ANY} */ hole) =>
115-
askEmbeddedRenderer(renderEmbeddedSource, hole, reported).then(
116-
embeddedText
117-
);
103+
// A caller's renderer is asked first; whatever it declines this minifies
104+
// itself, for the languages webpack ships a minifier for.
105+
const renderer = async (
106+
/** @type {string} */ source,
107+
/** @type {EXPECTED_ANY} */ hole
108+
) => {
109+
if (renderEmbeddedSource !== undefined) {
110+
const answered = embeddedText(
111+
await askEmbeddedRenderer(renderEmbeddedSource, hole, reported)
112+
);
113+
114+
if (typeof answered === "string") return answered;
115+
}
116+
117+
// A nested document is a document, so it is minified the same way. The
118+
// built-in CSS and JSON minifiers already reach every other body.
119+
return hole.type === "html" ? minifyDocument(source) : undefined;
120+
};
118121
/**
119122
* @param {string} text a whole document
120123
* @returns {Promise<string>} the same document, printed
@@ -123,9 +126,6 @@ const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
123126
(
124127
await new SourceProcessor().processAsync(text, {
125128
...printOptions,
126-
// The pre-pass below minifies the document an `<iframe srcdoc>` holds,
127-
// so one is not offered here as well.
128-
deferSrcdoc: !ownsSrcdoc,
129129
renderEmbeddedSource: renderer
130130
})
131131
).code;
@@ -142,94 +142,49 @@ const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
142142
// Put back into the source, not the output: the printer respells an
143143
// attribute value, so the recorded text is not what the output holds.
144144
let source = text;
145-
// Both are markup this parse cannot start a second one over, so both are
146-
// located in one walk and spliced afterwards. Their ranges never nest: a
147-
// `srcdoc` is an attribute value and a conditional comment's body is a
148-
// comment, neither of which this parse reads as markup.
149-
const wantsSrcdoc = Boolean(minifySrcdoc) && /srcdoc\s*=/i.test(source);
145+
// A conditional comment's body is markup this parse cannot start a second
146+
// one over, so each is located in a walk and spliced afterwards.
150147
const wantsConditional =
151148
Boolean(minifyConditionalComments) && /<!--\[if\s/i.test(source);
152149

153-
if (wantsSrcdoc || wantsConditional) {
154-
/** @type {{ start: number, end: number, srcdoc: boolean, value: string }[]} */
150+
if (wantsConditional) {
151+
/** @type {{ start: number, end: number, value: string }[]} */
155152
const found = [];
156153
/** @type {{ [type: number]: (path: EXPECTED_ANY) => void }} */
157154
const visitors = {};
158155

159-
if (wantsSrcdoc) {
160-
visitors[NodeType.Element] = (path) => {
161-
// An `<iframe>` in foreign content is an SVG or MathML element that
162-
// happens to share the name, and its `srcdoc` is not this attribute.
163-
if (path.tagName() !== "iframe" || path.namespace() !== NS_HTML) {
164-
return;
165-
}
166-
167-
for (const attribute of path.attributes()) {
168-
if (attribute.name !== "srcdoc" || attribute.value === "") continue;
169-
170-
found.push({
171-
start: attribute.valueStart,
172-
end: attribute.valueEnd,
173-
srcdoc: true,
174-
value: attribute.value
175-
});
176-
}
177-
};
178-
}
179-
180-
if (wantsConditional) {
181-
visitors[NodeType.Comment] = (path) => {
182-
const comment = path.source();
183-
const opened = comment.indexOf("]>");
184-
const closes = comment.lastIndexOf("<![endif]");
185-
186-
if (
187-
!/^<!--\[if\s/i.test(comment) ||
188-
opened === -1 ||
189-
closes <= opened
190-
) {
191-
return;
192-
}
156+
visitors[NodeType.Comment] = (path) => {
157+
const comment = path.source();
158+
const opened = comment.indexOf("]>");
159+
const closes = comment.lastIndexOf("<![endif]");
160+
161+
if (
162+
!/^<!--\[if\s/i.test(comment) ||
163+
opened === -1 ||
164+
closes <= opened
165+
) {
166+
return;
167+
}
193168

194-
const start = path.start() + opened + 2;
195-
const end = path.start() + closes;
169+
const start = path.start() + opened + 2;
170+
const end = path.start() + closes;
196171

197-
found.push({
198-
start,
199-
end,
200-
srcdoc: false,
201-
value: comment.slice(opened + 2, closes)
202-
});
203-
};
204-
}
172+
found.push({
173+
start,
174+
end,
175+
value: comment.slice(opened + 2, closes)
176+
});
177+
};
205178

206179
new SourceProcessor().use(visitors).process(source, {});
207-
// An element's attributes are visited where the element is, so the two
208-
// kinds do not arrive interleaved by position on their own.
209-
found.sort((a, b) => a.start - b.start);
210180

211181
// Back to front, so an earlier splice does not move a later range.
212182
for (let i = found.length - 1; i >= 0; i--) {
213-
const { start, end, srcdoc, value } = found[i];
183+
const { start, end, value } = found[i];
214184
// Sequential: a later splice must not move an earlier range.
185+
const inner = await minifyDocument(value);
215186

216-
const inner = await minifyDocument(
217-
srcdoc ? decodeEntities(value, true) : value
218-
);
219-
let written = inner;
220-
221-
if (srcdoc) {
222-
// A document is not something an unquoted value can hold — a space
223-
// or a `>` in it would end the attribute — so one written bare gets
224-
// quotes.
225-
const delimiter = source.charCodeAt(start - 1);
226-
const quoted = delimiter === 34 || delimiter === 39;
227-
const escaped = escapeAttribute(inner, quoted ? delimiter : 34, true);
228-
229-
written = quoted ? escaped : `"${escaped}"`;
230-
}
231-
232-
source = `${source.slice(0, start)}${written}${source.slice(end)}`;
187+
source = `${source.slice(0, start)}${inner}${source.slice(end)}`;
233188
}
234189
}
235190
// `process` parses once, and with `mode: "minify"` its walk also prints the
@@ -258,23 +213,19 @@ htmlMinify.getTypes = () => ["html"];
258213
/**
259214
* The languages this can offer a caller through `renderEmbeddedSource` — an
260215
* inline `<style>`, a `<script>`, an `<svg>` subtree and the document an
261-
* `<iframe srcdoc>` holds, less the one `minifySrcdoc` keeps to itself. A
262-
* `style=""` is not among them: how the attribute is written is decided by
263-
* reading the minified text back, so it stays with the built-in CSS minifier,
264-
* which is webpack's own `cssMinify`.
265-
* @param {{ minifySrcdoc?: boolean }=} minimizerOptions the options this will run with
216+
* `<iframe srcdoc>` holds. A `style=""` is not among them: how the attribute is
217+
* written is decided by reading the minified text back, so it stays with the
218+
* built-in CSS minifier, which is webpack's own `cssMinify`.
266219
* @returns {string[]} the languages
267220
*/
268-
htmlMinify.getEmbeddedTypes = (minimizerOptions = {}) => {
221+
htmlMinify.getEmbeddedTypes = () => {
269222
/** @type {string[]} */
270223
const languages =
271224
/** @type {typeof import("../index")} */
272225
// eslint-disable-next-line import/no-extraneous-dependencies -- webpack self-require, as the body does
273226
require(/** @type {string} */ ("webpack")).html.syntax.EMBEDDED_LANGUAGES;
274227

275-
return minimizerOptions.minifySrcdoc
276-
? languages.filter((language) => language !== "html")
277-
: languages;
228+
return languages;
278229
};
279230

280231
// When several minify functions share one `minimizer-webpack-plugin` instance,

0 commit comments

Comments
 (0)