Skip to content

Commit e78da30

Browse files
authored
fix(core): bound inert region scans in timing compiler (#3717)
* fix(core): bound inert region scans in timing compiler * fix(core): use literal search for comment terminators * fix(core): recognize end-bang HTML comment boundaries
1 parent fe2cc92 commit e78da30

2 files changed

Lines changed: 105 additions & 7 deletions

File tree

‎packages/core/src/compiler/timingCompiler.test.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { readFileSync } from "node:fs";
22
import { dirname, join } from "node:path";
3+
import { JSDOM } from "jsdom";
34
import { describe, it, expect } from "vitest";
45
import {
56
compileTimingAttrs,
@@ -18,6 +19,82 @@ it("source contains no raw NUL bytes", () => {
1819
expect(src.includes("\x00")).toBe(false);
1920
});
2021

22+
describe("inert region scanning", () => {
23+
const media = '<video id="v" data-start="1" data-duration="2">';
24+
25+
it.each([
26+
`<!-- ${media} <!-- nested -->`,
27+
`<ScRiPt type="text/javascript">${media}</sCrIpT \n>`,
28+
`<STYLE>${media}</STYLE\u00a0>`,
29+
`<script-data>${media}</script>`,
30+
`<style:${media}</style>`,
31+
`<!-- <script>${media} -->`,
32+
`<script><!-- ${media}</script>`,
33+
`<style><script>${media}</style>`,
34+
])("preserves the existing complete-region boundaries in %j", (region) => {
35+
const result = compileTimingAttrs(region + media);
36+
expect(result).toEqual({ html: region + compileTimingAttrs(media).html, unresolved: [] });
37+
expect(extractResolvedMedia(region + media)).toEqual(extractResolvedMedia(media));
38+
});
39+
40+
it.each(["<!--", "<script>", "<style>", "<scripture>", "<stylesheet>"])(
41+
"keeps media outside a complete inert region after %j visible",
42+
(prefix) => {
43+
expect(compileTimingAttrs(prefix + media).html).toBe(prefix + compileTimingAttrs(media).html);
44+
expect(extractResolvedMedia(prefix + media)).toEqual(extractResolvedMedia(media));
45+
},
46+
);
47+
48+
it.each(["-->", "--!>"])("recognizes %j as the first comment end like the browser", (end) => {
49+
const hidden = '<video id="hidden" data-duration="1">';
50+
const visible = '<video id="visible" data-start="1" data-duration="2">';
51+
const comment = `<!-- ${hidden} ${end}`;
52+
// The trailing delimiter must not extend the comment over visible media.
53+
const html = comment + visible + " -->";
54+
const dom = new JSDOM(html);
55+
expect([...dom.window.document.querySelectorAll("video")].map((el) => el.id)).toEqual([
56+
"visible",
57+
]);
58+
dom.window.close();
59+
expect(compileTimingAttrs(html)).toEqual({
60+
html: comment + compileTimingAttrs(visible).html + " -->",
61+
unresolved: [],
62+
});
63+
expect(extractResolvedMedia(html).map((el) => el.id)).toEqual(["visible"]);
64+
});
65+
66+
it("closes an end-bang comment without a later standard delimiter", () => {
67+
const comment = '<!-- <video id="hidden" data-duration="1"> --!>';
68+
expect(compileTimingAttrs(comment + media)).toEqual({
69+
html: comment + compileTimingAttrs(media).html,
70+
unresolved: [],
71+
});
72+
expect(extractResolvedMedia(comment + media)).toEqual(extractResolvedMedia(media));
73+
});
74+
75+
it.each(["<!--", "<script", "<style"])(
76+
"handles many unclosed %j prefixes while masking other region kinds",
77+
(prefix) => {
78+
const unclosed = prefix.repeat(100_000);
79+
const hidden = prefix === "<!--" ? `<style>${media}</style>` : `<!--${media}-->`;
80+
expect(compileTimingAttrs(unclosed + hidden + media)).toEqual({
81+
html: unclosed + hidden + compileTimingAttrs(media).html,
82+
unresolved: [],
83+
});
84+
expect(extractResolvedMedia(unclosed + hidden + media)).toEqual(extractResolvedMedia(media));
85+
},
86+
);
87+
88+
it("uses the first closing delimiter and resumes scanning after it", () => {
89+
const hidden = `<script>${media}</script>`;
90+
const html = hidden + media + `</script><!--${media}--><style>${media}</style>`;
91+
expect(compileTimingAttrs(html).html).toBe(
92+
hidden + compileTimingAttrs(media).html + `</script><!--${media}--><style>${media}</style>`,
93+
);
94+
expect(extractResolvedMedia(html)).toEqual(extractResolvedMedia(media));
95+
});
96+
});
97+
2198
describe("compileTimingAttrs", () => {
2299
it.each(["", " ", "0s", "0abc", "0px", "-1s", "Infinity", "NaN"])(
23100
"does not partially parse invalid literal data-duration=%j",

‎packages/core/src/compiler/timingCompiler.ts‎

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -113,18 +113,39 @@ function setAttr(tag: string, attr: string, value: string): string {
113113
// `<video>`/`<audio>` gets rewritten as if it were a real element (issue #1938).
114114
// Mask those inert regions with placeholders (no `<`, so the tag regexes skip
115115
// them) before scanning, then restore them verbatim.
116-
const INERT_REGION_RE =
117-
/<!--[\s\S]*?-->|<script\b[\s\S]*?<\/script\s*>|<style\b[\s\S]*?<\/style\s*>/gi;
118-
119116
// The NUL delimiters must stay as \u0000 escapes: raw 0x00 bytes make this file
120117
// binary to git and are corrupted by Bun's transpiler when bundled (issue #2139).
121118
function maskInertRegions(html: string): { masked: string; restore: (s: string) => string } {
122119
const stash: string[] = [];
123-
const masked = html.replace(INERT_REGION_RE, (region) => {
120+
const parts: string[] = [];
121+
const opening = /<!--|<script\b|<style\b/gi;
122+
const closings = new Map([
123+
["<!--", /--!?>/g],
124+
["<script", /<\/script\s*>/gi],
125+
["<style", /<\/style\s*>/gi],
126+
]);
127+
let cursor = 0;
128+
let match: RegExpExecArray | null;
129+
while ((match = opening.exec(html)) !== null) {
130+
const kind = match[0].toLowerCase();
131+
const closing = closings.get(kind);
132+
if (!closing) continue;
133+
closing.lastIndex = opening.lastIndex;
134+
const end = closing.exec(html) ? closing.lastIndex : -1;
135+
if (end < 0) {
136+
// No later opener of this kind can close either. Search each unmatched
137+
// suffix only once, while still allowing other kinds of inert regions.
138+
closings.delete(kind);
139+
continue;
140+
}
124141
const token = `\u0000HFMASK${stash.length}\u0000`;
125-
stash.push(region);
126-
return token;
127-
});
142+
parts.push(html.slice(cursor, match.index), token);
143+
stash.push(html.slice(match.index, end));
144+
cursor = end;
145+
opening.lastIndex = cursor;
146+
}
147+
parts.push(html.slice(cursor));
148+
const masked = parts.join("");
128149
const restore = (s: string): string =>
129150
// oxlint-disable-next-line no-control-regex -- NUL cannot appear in HTML, which is what makes it a safe mask delimiter
130151
s.replace(/\u0000HFMASK(\d+)\u0000/g, (_, i) => stash[Number(i)] ?? "");

0 commit comments

Comments
 (0)