Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/060-xml-minify-well-formed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"webpack": patch
---

Keep minified XML well-formed: close a cut-off CDATA, escape a bare `&`.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ jobs:
run: yarn test:invariants:css --require-corpus

# One language's finding must not hide another's: each names a repro of
# its own and all three are read in the same sitting. `!cancelled()`
# its own and all four are read in the same sitting. `!cancelled()`
# rather than `always()`, so a cancelled run stops here instead of
# sweeping again.
- name: HTML printer invariants
Expand Down
6 changes: 6 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ Spell names out in full (`attributeCount`, not `attrCnt`), beyond the abbreviati

Path-shape regexps and their helpers live in `lib/util/identifier.js`: **import from there — never re-declare a local copy**, even a one-liner like `/\\/g`. Export one that is defined but not exported; define one locally only when nothing fits ([details](docs/code-style.md#path-regexps-and-helpers-live-in-one-file)).

### No private exports

> [!REQUIRED]

**Never add a `_`-prefixed export** (`module.exports._foo`) to any file in the project to share an internal helper with another file: every export is reachable, so other developers come to depend on it and it can't change freely. Keep the helper in the one file that uses it, or move the logic so one file owns it; a helper useful in its own right is exported under a public name with full JSDoc instead, as the HTML and CSS `escape*` / `decode*` helpers are. **The only exception is testing**: a private export a test needs to reach code no public entry point can.

### Don't enumerate module or source types

> [!REQUIRED]
Expand Down
21 changes: 20 additions & 1 deletion lib/html/syntax-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -6392,6 +6392,11 @@ const isXmlChar = (code) =>
const XML_REFERENCE_REGEXP =
/&(?:#(?:x([\da-fA-F]+)|(\d+))|([^\s&;#<>"'=/%]+));/g;
const XML_CHARACTER_REFERENCE_REGEXP = /&#(?:x([\da-fA-F]+)|(\d+));/g;
// An `&` opening no well-formed reference (§4.1, a `Name` per §2.3), which a
// strict parser refuses. One class per part, surrogates read per code unit, so
// a long name never backtracks; the decoder kept it as text, so it is escaped.
const XML_BARE_AMPERSAND_REGEXP =
/&(?!(?:#(?:x[\da-fA-F]+|\d+)|[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u2070-\u218F\u2C00-\u2FEF\u3001-\uDB7F\uF900-\uFDCF\uFDF0-\uFFFD\u200C-\u200D][-.0-9:A-Z_a-z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uDFFF\uF900-\uFDCF\uFDF0-\uFFFD\u200C-\u200D]*);)/;
// WHY: §3.3.3 normalizes each literal whitespace character of an attribute value
// to a space after §2.11 has folded CRLF, so a CRLF is one space; replacement
// text of an entity is already folded, so there each character counts alone.
Expand Down Expand Up @@ -6523,6 +6528,19 @@ const escapeXmlText = (data) =>
.replace(/>/g, "&gt;")
.replace(/\r/g, "&#13;");

/**
* Whether XML text or an attribute value, as written in its source, may be
* written back unchanged: no `<` and every `&` opening a reference (§4.1).
* @example
* isXmlWellFormedText("a &amp; b"); // true
* isXmlWellFormedText("&undeclared;"); // true: a reference, declared or not
* isXmlWellFormedText("a & b"); // false: a strict parser refuses the bare `&`
* @param {string} raw the text or attribute value as written
* @returns {boolean} true when it is well-formed as written
*/
const isXmlWellFormedText = (raw) =>
!raw.includes("<") && !XML_BARE_AMPERSAND_REGEXP.test(raw);

/**
* Escape an attribute value for XML (§3.1): `&`, `<` and the delimiter, plus the
* whitespace §3.3.3 would otherwise normalize to a space.
Expand Down Expand Up @@ -13377,7 +13395,7 @@ const _xmlOpenTag = (path, minify) => {
_attrValues[i] === null &&
valueStart > 0 &&
raw.length < value.length &&
!raw.includes("<")
isXmlWellFormedText(raw)
) {
const written = _htmlSource.charAt(valueStart - 1);
if (written === '"' || written === "'") {
Expand Down Expand Up @@ -15783,6 +15801,7 @@ module.exports.grammar = grammar;
module.exports.isAllAsciiWhitespace = isAllAsciiWhitespace;
module.exports.isAsciiAlphanumeric = isAsciiAlphanumeric;
module.exports.isAsciiWhitespace = isAsciiWhitespace;
module.exports.isXmlWellFormedText = isXmlWellFormedText;
module.exports.metaTag = metaTag;
module.exports.parseCssUrls = parseCssUrls;
module.exports.parseHtml = parseHtml;
Expand Down
27 changes: 14 additions & 13 deletions lib/html/syntax-printer.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ const {
escapeXmlText,
isAllAsciiWhitespace,
isAsciiAlphanumeric,
isXmlWellFormedText,
startsWithAsciiWhitespace,
stripAsciiWhitespace
} = require("./syntax-parser");
Expand Down Expand Up @@ -316,19 +317,17 @@ const _printXml = (path, writer, minify) => {
case NodeType.Text: {
const raw = path.source();
const data = _dataOf(path.node);
if (minify && _isXmlStylesheet(path)) {
return data.trim() === ""
? raw
: _S._deferEmbeddedSource === undefined
? _xmlCharacterData(_renderEmbedded(data, CSS_TYPE))
: _deferEmbedded(data, CSS_TYPE, (rendered) =>
_xmlCharacterData(
typeof rendered === "string" ? rendered : data
)
);
const stylesheet = minify && _isXmlStylesheet(path);
if (stylesheet && data.trim() !== "") {
return _S._deferEmbeddedSource === undefined
? _xmlCharacterData(_renderEmbedded(data, CSS_TYPE))
: _deferEmbedded(data, CSS_TYPE, (rendered) =>
_xmlCharacterData(typeof rendered === "string" ? rendered : data)
);
}
// A CDATA section the input ran out in would hold the end tags after it.
if (!minify) {
// A blank stylesheet is kept as written, as the renderer is never asked.
if (!minify || stylesheet) {
return raw.includes("<![CDATA[") && !raw.endsWith("]]>")
? escapeXmlText(data)
: raw;
Expand All @@ -342,8 +341,10 @@ const _printXml = (path, writer, minify) => {
escaped = `<![CDATA[${data}]]>`;
}
// The source's own spelling when shorter: a declared entity reference, or
// a `>` it left bare. A `<` in it is a CDATA section, never kept as is.
return raw.length < escaped.length && !raw.includes("<") ? raw : escaped;
// a `>` it left bare. A `<` is a CDATA section, a bare `&` no reference.
return raw.length < escaped.length && isXmlWellFormedText(raw)
? raw
: escaped;
}
case NodeType.Comment: {
const source = path.source();
Expand Down
37 changes: 36 additions & 1 deletion test/unitCases/tooling/compare-css.unittest.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,42 @@
"use strict";

const CACHE_NAME = "css-tool-comparison";

const installed = jest.fn(() => Promise.resolve(CACHE_NAME));

// A real install would `npm ci` the corpus into a contributor's cache, and every
// packed stylesheet and built fixture is taken as there, so `--setup` fetches
// and builds nothing: what is under test is that it installs and stops.
jest.mock("../../../tooling/compare-tools-harness", () => ({
...jest.requireActual("../../../tooling/compare-tools-harness"),
exists: () => Promise.resolve(true),
installPackages: installed
}));

const { SourceProcessor } = require("../../../lib/css/syntax");
const { COLD_BRANCHES } = require("../../../tooling/compare-css-tools");
const {
COLD_BRANCHES,
runMode
} = require("../../../tooling/compare-css-tools");

// Read before anything clears the mock: an unguarded script installs while
// being required, and a `beforeEach` would erase exactly that evidence.
const callsWhileRequiring = installed.mock.calls.length;

describe("the CSS tool comparison", () => {
it("should start nothing when the script is required rather than run", () => {
expect(callsWhileRequiring).toBe(0);
});

it("should install the corpus and stop on `--setup`", async () => {
installed.mockClear();

await runMode("--setup");

expect(installed).toHaveBeenCalledTimes(1);
expect(installed).toHaveBeenCalledWith(CACHE_NAME);
});
});

// What each rewrite the fixture is there for writes. Every one was counted at
// zero over every stylesheet on disk before the fixture was written, so an edit
Expand Down
111 changes: 110 additions & 1 deletion test/unitCases/tooling/compare-harness.unittest.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const { Readable } = require("stream");
const { pathToFileURL } = require("url");
const {
compress,
cutsAt,
exists,
filterFrom,
findingGroups,
Expand All @@ -26,7 +27,9 @@ const {
profileShares,
run,
sweepExitCode,
sweepMode
sweepMode,
wantedExpectations,
wantedRespelling
} = require("../../../tooling/compare-tools-harness");

/** @type {string} */
Expand Down Expand Up @@ -833,6 +836,112 @@ describe("compare-tools-harness", () => {
expect(text).toContain("idempotence — bytes");
expect(text).toContain("stale — 1 expectation(s) matched nothing");
});

it("lets an entry naming several fixtures cover a group reaching them", () => {
const groups = findingGroups([
{
relation: "idempotence",
contains: "a ->",
source: ["one", "two"],
why: "those fixtures write it"
}
]);
groups.add(finding("idempotence", " a -> b"), "default", "one.html");
groups.add(finding("idempotence", " a -> b"), "default", "two.html");
expect(written(groups).count).toBe(0);
groups.add(finding("idempotence", " a -> b"), "default", "three.html");
expect(written(groups).count).toBe(2);
});
});

describe("cutsAt", () => {
it("cuts inside the first construct past the midpoint, else the first", () => {
const source = "<a>1</a><b>2</b><c>3</c>";
expect(cutsAt(source, [["in a start tag", /<[a-z]/g]])).toEqual([
["in a start tag", "<a>1</a><b>2</b><c"]
]);
expect(cutsAt(source, [["in a comment", /<!--./g]])).toEqual([]);
expect(cutsAt("<a>1</a>xyz", [["in a tag", /<[a-z]/g]])).toEqual([
["in a tag", "<a"]
]);
});

it("leaves out a cut that would keep the whole source", () => {
expect(cutsAt("ab<a", [["in a start tag", /<[a-z]/g]])).toEqual([]);
});
});

describe("narrowing a sweep", () => {
afterEach(() => {
delete process.env.RELATION;
delete process.env.SPELLING;
});

it("asks every respelling when nothing narrows the run", () => {
expect(wantedRespelling("quote-double")).toBe(true);
});

it("asks a respelling `RELATION` names alone or as `respelling`", () => {
process.env.RELATION = "respelling quote-double";
expect(wantedRespelling("quote-double")).toBe(true);
expect(wantedRespelling("quote-single")).toBe(false);
process.env.RELATION = "respelling";
expect(wantedRespelling("quote-single")).toBe(true);
process.env.RELATION = "spans";
expect(wantedRespelling("quote-single")).toBe(false);
});

it("asks only the respelling `SPELLING` names", () => {
process.env.SPELLING = "unquote";
expect(wantedRespelling("unquote")).toBe(true);
expect(wantedRespelling("quote-double")).toBe(false);
});

/** @type {import("../../../tooling/compare-tools-harness").Expected[]} */
const EXPECTED = [
{ relation: "idempotence", contains: "a", why: "…" },
{ relation: "respelling quote-double", contains: "b", why: "…" },
{ relation: "idempotence", contains: "c", source: "one", why: "…" },
{ relation: "idempotence", contains: "d", presets: ["legacy"], why: "…" },
{
relation: "idempotence",
contains: "e",
source: ["three", "one"],
why: "…"
}
];

/**
* @param {string[]} labels the fixtures the run reads
* @param {string[]} presets the option sets it prints under
* @returns {string[]} what each kept entry contains
*/
const kept = (labels, presets) =>
wantedExpectations(EXPECTED, labels, presets).map(
(entry) => entry.contains
);

it("keeps every entry a full run reaches", () => {
expect(kept(["one.html"], ["default", "legacy"])).toEqual([
"a",
"b",
"c",
"d",
"e"
]);
});

it("drops an entry for a fixture or preset the run does not read", () => {
expect(kept(["two.html"], ["default"])).toEqual(["a", "b"]);
});

it("drops an entry for a relation or respelling the run does not ask", () => {
process.env.SPELLING = "unquote";
expect(kept(["one.html"], ["legacy"])).toEqual(["a", "c", "d", "e"]);
delete process.env.SPELLING;
process.env.RELATION = "respelling quote-double";
expect(kept(["one.html"], ["legacy"])).toEqual(["b"]);
});
});
});

Expand Down
33 changes: 32 additions & 1 deletion test/unitCases/tooling/compare-html.unittest.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,46 @@
"use strict";

const CACHE_NAME = "html-tool-comparison";

const installed = jest.fn(() => Promise.resolve(CACHE_NAME));

// A real install would `npm ci` the corpus into a contributor's cache, and
// nothing here reads it: the built documents are the ones under test.
jest.mock("../../../tooling/compare-tools-harness", () => ({
...jest.requireActual("../../../tooling/compare-tools-harness"),
installPackages: installed
}));

const fs = require("fs");
const path = require("path");
const { SourceProcessor } = require("../../../lib/html/syntax");
const {
COLD_CONSTRUCTS,
EMBEDDED_LEGACY_OPTIONS,
EMBEDDED_OPTIONS
EMBEDDED_OPTIONS,
runMode
} = require("../../../tooling/compare-html-tools");
const { collectFiles } = require("../../../tooling/compare-tools-harness");

// Read before anything clears the mock: an unguarded script installs while
// being required, and a `beforeEach` would erase exactly that evidence.
const callsWhileRequiring = installed.mock.calls.length;

describe("the HTML tool comparison", () => {
it("should start nothing when the script is required rather than run", () => {
expect(callsWhileRequiring).toBe(0);
});

it("should install the corpus and stop on `--setup`", async () => {
installed.mockClear();

await expect(runMode("--setup")).resolves.toBe(CACHE_NAME);

expect(installed).toHaveBeenCalledTimes(1);
expect(installed).toHaveBeenCalledWith(CACHE_NAME);
});
});

const ROOT = path.join(__dirname, "..", "..", "..");

// cspell:ignore popovertarget popovertargetaction contenteditable exportparts
Expand Down
Loading
Loading