Skip to content

Commit 772feca

Browse files
fix(javascript): spell an escaped directive safe for an inline script
- A directive printed as spelled skipped the escaping `inline_script` gives every other string, so `"x\x20</script>"` could end the script element it sits in; it now gets the same `<\/script`, `\x3c!--` and `--\x3e`, each reading as what it replaces. - The JavaScript sweep asks only for the expectations a narrowed run can reach: a fixture or preset left out no longer reads as stale. - Say the parser's relations parse under a build's options, and drop the `EXPECTED_ANY` the test option objects did not need. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011CuRTB8fAv8PE7di49qDL4
1 parent b5a5d8d commit 772feca

5 files changed

Lines changed: 53 additions & 9 deletions

File tree

‎lib/javascript/syntax-printer.js‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39416,6 +39416,23 @@ const installEstreePrint = (modules) => {
3941639416
else output.print_template_string_chars(text);
3941739417
};
3941839418

39419+
/**
39420+
* A string's spelling made safe in an inline `<script>`, as `encode_string`
39421+
* makes a value: each escape added reads as what it replaces.
39422+
* @param {string} spelling the text between a string's quotes
39423+
* @returns {string} the same string, spelled so no `</script` or `<!--` shows
39424+
*/
39425+
const inlineScriptSpelling = (spelling) =>
39426+
spelling
39427+
.replace(/<\u002F(script)([>/\t\n\f\r ])/gi, "<\\/$1$2")
39428+
// An escaped `\<` gives its backslash up to the `\x3c` taking its place.
39429+
.replace(
39430+
/(\\*)\u003C!--/g,
39431+
(_match, slashes) =>
39432+
`${slashes.length % 2 === 1 ? slashes.slice(1) : slashes}\\x3c!--`
39433+
)
39434+
.replace(/--\u003E/g, "--\\x3e");
39435+
3941939436
/** @type {EstreeGenerators} */
3942039437
const codegen = {
3942139438
Program: (node, output) => {
@@ -39430,7 +39447,10 @@ const installEstreePrint = (modules) => {
3943039447
// its value instead could spell another directive, or none.
3943139448
if (node.directive !== value) {
3943239449
const quote = expression.quote || '"';
39433-
output.print(`${quote}${node.directive}${quote}`);
39450+
const spelled = output.option("inline_script")
39451+
? inlineScriptSpelling(node.directive)
39452+
: node.directive;
39453+
output.print(`${quote}${spelled}${quote}`);
3943439454
} else {
3943539455
output.print_string(value, expression.quote);
3943639456
}

‎test/unitCases/syntax-printer.unittest.js‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6291,7 +6291,6 @@ describe("syntax-printer", () => {
62916291

62926292
it("should minify synchronously as it does asynchronously", async () => {
62936293
const { minify, modules } = await load();
6294-
/** @type {EXPECTED_ANY} */
62956294
const options = { module: true, sourceMap: true };
62966295
const code = "export const a = 1 + 2; console.log(a);";
62976296
const sync = modules.minifySync(code, { ...options });
@@ -6301,7 +6300,6 @@ describe("syntax-printer", () => {
63016300
});
63026301

63036302
describe("printing its own output again", () => {
6304-
/** @type {EXPECTED_ANY} */
63056303
const formatOnly = { compress: false, mangle: false, module: true };
63066304

63076305
/**
@@ -6332,6 +6330,22 @@ describe("syntax-printer", () => {
63326330
).toBe(reference.code);
63336331
});
63346332

6333+
it("should spell a directive's `</script` and `<!--` safe for an inline script, keeping its value", async () => {
6334+
for (const [code, expected] of [
6335+
['"x\\x20</script>"; f();', '"x\\x20<\\/script>";f();'],
6336+
['"x\\<!--\\x20"; f();', '"x\\x3c!--\\x20";f();'],
6337+
['"x\\\\<!--\\x20"; f();', '"x\\\\\\x3c!--\\x20";f();'],
6338+
['"a\\x20-->"; f();', '"a\\x20--\\x3e";f();']
6339+
]) {
6340+
const [printed, again] = await twice(code);
6341+
expect(printed).toBe(`${expected}`);
6342+
expect(again).toBe(printed);
6343+
expect(vm.runInNewContext(printed.slice(0, printed.indexOf(";")))).toBe(
6344+
vm.runInNewContext(code.slice(0, code.indexOf(";")))
6345+
);
6346+
}
6347+
});
6348+
63356349
it("should keep the line break after a banner before a dropped `;`, as terser prints it", async () => {
63366350
const { minify } = await load();
63376351
const code = "/*! license\n */\n;(function () { f(); })();";

‎tooling/COMPARE_TOOLS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,6 @@
1616
4. Parser, `slices`: the bytes between a node's offsets, parsed alone, give the node back. **A slice is parsed in a context keeping its meaning, never at top level** (`yield x` is an identifier outside a generator; a lone `<td>x</td>` is dropped and its text foster-parented): CSS wraps a declaration in a rule and a value in a declaration; JS tries a ladder of function and class-method contexts under the source's own `ecmaVersion` (`function*(){}` can't open a statement; an ES6-pinned case can't parse `async function*`); HTML runs the fragment parsing algorithm on the enclosing tag, as browsers do for `innerHTML`. A node no context parses is counted, not reported. Left out (§13.2 again): an element the parser inserted or cloned (no tag to slice), and one whose end is still its start tag's (its range doesn't hold its children). **Two limits keep it to seconds**: one shape is one question (a bundle's millionth `Identifier[0,3)` is skipped — CSS went 30s → 4.6s), and each source may spend at most four times its bytes on reparsing, leaves first; both skip counts are reported, as unread coverage. The JS sweep also reads `fixtures/acorn-corpus.json` under each case's options, reaching productions no fixture writes; sources the parser refuses are counted, not reported (those cases assert the refusal).
1717
5. Parser, `purity`: rereading the same bytes in one process gives the same answer. **Every source is read once before any is read again**, so every other source sits between a source's two readings — catching a cache keyed on the last input. **The digest holds what the parse derived, not only offsets** (`parseHtml` interns tag and attribute names as slices of the document first spelling them and drops those on the next parse, so a stale name keeps correct offsets): HTML tag/attribute names and values, CSS derived names, and every primitive on a JS node, read off the node's own keys so new productions are covered; CSS and HTML also digest the printed bytes. Refusals are digested too, except running out of stack (its position depends on the surrounding call depth). A disagreeing source is read a third time back to back, telling leaked state from a non-repeatable parse.
1818
6. Parser, `acorn` (JS): every fixture's tree equals acorn's under a build's options, every key positions included — the comparator `test262-parser.spectest.js`, `js-fuzz.spectest.js` and the parser's unit tests import from `compare-js-tools.js`. acorn's own corpus is left out (`WebpackParser.unittest.js` replays its trees), and a source acorn refuses is left to the test262 suites.
19-
- Relations 3–6 are the parser's and run under no option set. A parser that also prints is held to both halves. These catch what a comparison can't: being a few bytes off one's own best isn't being worse than another tool.
19+
- Relations 3–6 are the parser's and skip the printer's option sets; each source is parsed under the options a build reads it with. A parser that also prints is held to both halves. These catch what a comparison can't: being a few bytes off one's own best isn't being worse than another tool.
2020
- A divergence the printer owes nothing for goes in the script's `EXPECTED` table with its reason, never suppressed by a passing gate; an entry that stops matching is itself a finding, so a fix retires it.
2121
- The HTML sweep adds a third option set, `embedded` (the aggressive one + `builtinEmbeddedRenderer`) — what a build runs, so inline `<style>` and `style=""` reach the CSS minifier and both printers are checked as one. It caught a recovered CSS string keeping the quote its source opened with, which `.css` suites can't reach (a css module ends declarations with a newline, making an open string a bad-string).

‎tooling/compare-js-tools.js‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1488,6 +1488,7 @@ const EXPECTED = [
14881488
relation: "idempotence",
14891489
contains: "var ",
14901490
source: "ECharts",
1491+
presets: ["default", "2 passes"],
14911492
why: "terser breaks the line after a kept comment where the next token began one, and a comment holding a break is read back as one"
14921493
}
14931494
];
@@ -1558,13 +1559,21 @@ const invariants = async (write) => {
15581559
_missingFixtures = built.missing.filter((label) => wantedFixture(label));
15591560
const corpus = built.corpus.filter(([label]) => wantedFixture(label));
15601561
const presets = PRESETS.filter(([name]) => wantedPreset(name));
1561-
// Filtered like the corpus is: an expectation for a relation this run was
1562-
// never going to reach matched nothing because nothing asked it to, which is
1563-
// not the divergence having gone away.
1562+
// Filtered like the corpus is: an expectation for a relation, fixture or
1563+
// preset this run was never going to reach matched nothing because nothing
1564+
// asked it to, which is not the divergence having gone away.
15641565
const groups = findingGroups(
15651566
EXPECTED.filter(
15661567
(entry) =>
15671568
wantedRelation(entry.relation) &&
1569+
(entry.source === undefined ||
1570+
corpus.some(([label]) =>
1571+
label.includes(/** @type {string} */ (entry.source))
1572+
)) &&
1573+
(entry.presets === undefined ||
1574+
presets.some(([name]) =>
1575+
/** @type {string[]} */ (entry.presets).includes(name)
1576+
)) &&
15681577
(!entry.relation.startsWith("respelling ") ||
15691578
wantedSpelling(entry.relation.slice("respelling ".length)))
15701579
)

‎tooling/compare-tools-harness.js‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1016,8 +1016,9 @@ const purityRelation = (sources) => {
10161016
/**
10171017
* A finding the printer owes nothing for, with the reason it is owed nothing.
10181018
* `relation` and `contains` together name it; `source` narrows it to one
1019-
* fixture where the same repro is a defect elsewhere.
1020-
* @typedef {{ relation: string, contains: string, source?: string, why: string }} Expected
1019+
* fixture where the same repro is a defect elsewhere, and `presets` to the
1020+
* option sets it shows under, so a run narrowed past them does not ask for it.
1021+
* @typedef {{ relation: string, contains: string, source?: string, presets?: string[], why: string }} Expected
10211022
*/
10221023

10231024
/**

0 commit comments

Comments
 (0)