mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
fix(core): keep SVG selector alias growth within the compile budget (#8238)
* test(core): pin that selector alias growth is charged while it is built * fix(core): keep SVG selector alias growth within the compile budget * fix(core): charge renamed-id selector growth too, and settle to the sheet's real growth * chore(core): regenerate the selector alias installer and page goldens * test(core): build the alias growth fixture from compiler-written aliases * test(core): trip the alias budget only in the selector rewrite * test(core): rewrite an escaped id with exactly its growth left * fix(core): charge a renamed id against the token it replaces * chore(core): regenerate the selector alias installer and page goldens
This commit is contained in:
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1281,6 +1281,53 @@ it("charges the bytes SVG id renaming adds to the mount that grew", () => {
|
||||
);
|
||||
});
|
||||
|
||||
// fails without the fix: a mount's alias alternatives were all built before any of their bytes were charged.
|
||||
it("charges a mount's selector aliases while they are built, and each byte once", () => {
|
||||
const leaves = 300;
|
||||
const leaf = `<template><div data-composition-id="leaf"><svg><g id="a"></g><use href="#a"/></svg></div></template>`;
|
||||
const art = (rules: number) =>
|
||||
`<template><div data-composition-id="art"><style>${Array.from(
|
||||
{ length: rules },
|
||||
(_, i) => `[href="#a"] .r${i} { fill: red; }`,
|
||||
).join(
|
||||
"\n",
|
||||
)}</style>${'<div data-composition-id="leaf" data-composition-src="leaf.html" data-start="0" data-duration="2"></div>'.repeat(leaves)}</div></template>`;
|
||||
const inline = (rules: number, chargeEmitted: (src: string, bytes: number) => void) => {
|
||||
const { document } = parseHTML(`<!DOCTYPE html><html><body><div data-composition-id="main">
|
||||
<div data-composition-id="a" data-composition-src="art.html" data-start="0" data-duration="2"></div>
|
||||
</div></body></html>`);
|
||||
return inlineSubCompositions(
|
||||
document,
|
||||
[...document.querySelectorAll("[data-composition-src]")],
|
||||
{
|
||||
resolveHtml: (src) => (src === "art.html" ? art(rules) : leaf),
|
||||
parseHtml: (html) => parseHTML(html).document,
|
||||
chargeEmitted,
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
let renaming = 0;
|
||||
inline(0, (_src, bytes) => (renaming += bytes));
|
||||
let charged = 0;
|
||||
const limit = renaming + 16 * 1024;
|
||||
expect(() =>
|
||||
inline(50, (_src, bytes) => {
|
||||
charged += bytes;
|
||||
if (charged > limit) throw new Error("over budget");
|
||||
}),
|
||||
).toThrow("over budget");
|
||||
expect(charged).toBeLessThan(limit + 200);
|
||||
|
||||
const perSrc = new Map<string, number>();
|
||||
const { styles } = inline(1, (src, bytes) => perSrc.set(src, (perSrc.get(src) ?? 0) + bytes));
|
||||
const authored = art(1).match(/<style>([^<]*)<\/style>/)![1]!;
|
||||
const growth = styles[0]!.css.length - authored.length;
|
||||
expect(growth).toBeGreaterThan(5_000);
|
||||
expect(perSrc.get("art.html")).toBeGreaterThanOrEqual(growth);
|
||||
expect(perSrc.get("art.html")).toBeLessThan(growth + 1000);
|
||||
});
|
||||
|
||||
// fails without the fix: nested templates were walked per copy, linkedom copied each, and SVG ones rescanned.
|
||||
describe("dropAuthoredSvgReferenceAliases", () => {
|
||||
const planted = `data-hf-svg-reference-aliases="[]"`;
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
SVG_REFERENCE_ALIASES_ATTR,
|
||||
dropAuthoredSvgReferenceAliases,
|
||||
readSvgReferenceAliases,
|
||||
type SvgReferenceAlias,
|
||||
} from "./svgSelectorAliases";
|
||||
import { readExternalScriptAttributes, type ExternalScriptAttributes } from "./externalScripts";
|
||||
import { parseImportMap, type ImportMap } from "./importMaps";
|
||||
@@ -41,6 +42,7 @@ import {
|
||||
namespaceCollidingSvgIds,
|
||||
sceneClipRoots,
|
||||
rewriteSvgIdReferencesInCss,
|
||||
type SvgIdMap,
|
||||
type SvgIdScope,
|
||||
} from "./svgIdNamespacing";
|
||||
import {
|
||||
@@ -849,9 +851,18 @@ export function inlineSubCompositions(
|
||||
chargeEmitted &&
|
||||
((index, bytes) => chargeEmitted(svgIdScopes[index]?.src ?? "the page", bytes)),
|
||||
);
|
||||
const chargeGrowth = (src: string, before: string, after: string) => {
|
||||
if (after.length > before.length) chargeEmitted?.(src, after.length - before.length);
|
||||
};
|
||||
const rewriteCss = (
|
||||
src: string,
|
||||
css: string,
|
||||
idMap: SvgIdMap,
|
||||
references: readonly SvgReferenceAlias[],
|
||||
) =>
|
||||
rewriteSvgIdReferencesInCss(
|
||||
css,
|
||||
idMap,
|
||||
references,
|
||||
chargeEmitted && ((bytes) => chargeEmitted(src, bytes)),
|
||||
);
|
||||
svgIdMaps.slice(0, svgIdScopes.length).forEach((idMap, index) => {
|
||||
const { styleStart, styleEnd } = svgIdScopes[index]!;
|
||||
const references = readSvgReferenceAliases(
|
||||
@@ -859,9 +870,7 @@ export function inlineSubCompositions(
|
||||
SVG_REFERENCE_ALIASES_ATTR,
|
||||
);
|
||||
for (let i = styleStart; i < styleEnd; i += 1) {
|
||||
const rewritten = rewriteSvgIdReferencesInCss(styles[i]!.css, idMap, references);
|
||||
chargeGrowth(svgIdScopes[index]!.src, styles[i]!.css, rewritten);
|
||||
styles[i]!.css = rewritten;
|
||||
styles[i]!.css = rewriteCss(svgIdScopes[index]!.src, styles[i]!.css, idMap, references);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -871,13 +880,7 @@ export function inlineSubCompositions(
|
||||
);
|
||||
for (const style of rootStyles) {
|
||||
const css = style.textContent ?? "";
|
||||
const rewritten = rewriteSvgIdReferencesInCss(
|
||||
css,
|
||||
svgIdMaps[svgIdScopes.length]!,
|
||||
rootReferences,
|
||||
);
|
||||
chargeGrowth("the page", css, rewritten);
|
||||
style.textContent = rewritten;
|
||||
style.textContent = rewriteCss("the page", css, svgIdMaps[svgIdScopes.length]!, rootReferences);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -221,7 +221,7 @@ export function selectorIdTokens(selector: string): string[] {
|
||||
export function replaceSelectorIdTokens(
|
||||
selector: string,
|
||||
candidateIds: readonly string[],
|
||||
resolveReplacement: (matchedId: string) => string,
|
||||
resolveReplacement: (matchedId: string, matchedToken: string) => string,
|
||||
): string {
|
||||
if (candidateIds.length === 0 || !selector.includes("#")) return selector;
|
||||
const candidates = new Set(candidateIds);
|
||||
@@ -235,7 +235,7 @@ export function replaceSelectorIdTokens(
|
||||
? decodeCssIdentifierAt(selector, index + 1)
|
||||
: null;
|
||||
if (token && candidates.has(token.value)) {
|
||||
result += resolveReplacement(token.value);
|
||||
result += resolveReplacement(token.value, selector.slice(index, token.end));
|
||||
index = token.end;
|
||||
} else {
|
||||
result += selector[index];
|
||||
|
||||
@@ -621,3 +621,98 @@ it("hashes a long namespace once per mount, not once per renamed id", () => {
|
||||
expect(idMaps[1]!.size).toBe(200);
|
||||
expect(hashCalls.length).toBe(1);
|
||||
});
|
||||
|
||||
// fails without the fix: the rewrite built every alternative, and its growth was charged only once the sheet existed.
|
||||
describe("rewriteSvgIdReferencesInCss charges its growth while it builds", () => {
|
||||
const limit = 64 * 1024;
|
||||
const references = Array.from({ length: 2000 }, (_, i) => ({
|
||||
name: "href",
|
||||
localName: "href",
|
||||
namespaceURI: null,
|
||||
before: "#a",
|
||||
after: `#m-${i}-${"x".repeat(100)}`,
|
||||
}));
|
||||
|
||||
it.each([
|
||||
`[href="#a"]`,
|
||||
`[href^="#"]`,
|
||||
`[href$="a"]`,
|
||||
`[href*="a"]`,
|
||||
`[href~="#a"]`,
|
||||
`[href|="#a"]`,
|
||||
`[href="#A" i]`,
|
||||
])("stops within one alternative of the budget for %s", (predicate) => {
|
||||
const css = Array.from({ length: 50 }, (_, i) => `${predicate} .r${i} { fill: red; }`).join(
|
||||
"\n",
|
||||
);
|
||||
let charged = 0;
|
||||
const charge = (bytes: number) => {
|
||||
charged += bytes;
|
||||
if (charged > limit) throw new Error("over budget");
|
||||
};
|
||||
|
||||
expect(() => rewriteSvgIdReferencesInCss(css, new Map(), references, charge)).toThrow(
|
||||
"over budget",
|
||||
);
|
||||
expect(charged).toBeLessThan(limit + 200);
|
||||
});
|
||||
|
||||
it("stops within one id rename of the budget", () => {
|
||||
const css = Array.from({ length: 2000 }, (_, i) => `#clip .r${i} { fill: red; }`).join("\n");
|
||||
const idMap = new Map([["clip", `clip-${"x".repeat(200)}`]]);
|
||||
let charged = 0;
|
||||
const charge = (bytes: number) => {
|
||||
charged += bytes;
|
||||
if (charged > limit) throw new Error("over budget");
|
||||
};
|
||||
expect(() => rewriteSvgIdReferencesInCss(css, idMap, [], charge)).toThrow("over budget");
|
||||
expect(charged).toBeLessThan(limit + 500);
|
||||
});
|
||||
|
||||
// fails without the fix: the id's decoded length was charged against, not the escaped token it replaced.
|
||||
const renamedClip = [
|
||||
{
|
||||
name: "id",
|
||||
localName: "id",
|
||||
namespaceURI: null,
|
||||
before: "clip",
|
||||
after: "m--clip-namespaced",
|
||||
},
|
||||
];
|
||||
it.each([
|
||||
[`#\\63 lip { fill: red; }`, new Map([["clip", "m--clip-namespaced"]]), []],
|
||||
[`#cl\\69 p .a { fill: red; }`, new Map([["clip", "m--clip-namespaced"]]), []],
|
||||
[`#\\63 lip { fill: red; }`, new Map(), renamedClip],
|
||||
])("rewrites %j with exactly its growth left (%#)", (css, idMap, aliases) => {
|
||||
const growth = rewriteSvgIdReferencesInCss(css, idMap, aliases).length - css.length;
|
||||
let left = growth;
|
||||
const rewritten = rewriteSvgIdReferencesInCss(css, idMap, aliases, (bytes) => {
|
||||
left -= bytes;
|
||||
if (left < 0) throw new Error("over budget");
|
||||
});
|
||||
expect(growth).toBeGreaterThan(0);
|
||||
expect(rewritten).toContain("m--clip-namespaced");
|
||||
expect(left).toBe(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[`.x,[href="#a"],\n\n .b { fill: red; }`, new Map()],
|
||||
[`.x,#clip,\n\n .b { fill: red; }`, new Map([["clip", "m--clip"]])],
|
||||
[`[href="#a"] #clip { fill: url(#clip); }`, new Map([["clip", "m--clip"]])],
|
||||
])("charges exactly the growth of %j", (css, idMap) => {
|
||||
let charged = 0;
|
||||
const rewritten = rewriteSvgIdReferencesInCss(css, idMap, references.slice(0, 2), (bytes) => {
|
||||
charged += bytes;
|
||||
});
|
||||
expect(rewritten).not.toBe(css);
|
||||
expect(charged).toBe(Math.max(0, rewritten.length - css.length));
|
||||
});
|
||||
|
||||
it("charges nothing for a sheet it leaves as it is", () => {
|
||||
const charge = vi.fn();
|
||||
expect(
|
||||
rewriteSvgIdReferencesInCss(`[href="#b"] { fill: red; }`, new Map(), references, charge),
|
||||
).toBe(`[href="#b"] { fill: red; }`);
|
||||
expect(charge).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -535,6 +535,7 @@ export function rewriteSvgIdReferencesInCss(
|
||||
css: string,
|
||||
idMap: SvgIdMap,
|
||||
references: readonly SvgReferenceAlias[] = [],
|
||||
charge?: (bytes: number) => void,
|
||||
): string {
|
||||
if (!css || (idMap.size === 0 && references.length === 0)) return css;
|
||||
if (!css.includes("#") && !css.includes("[") && !css.toLowerCase().includes("url(")) return css;
|
||||
@@ -548,6 +549,13 @@ export function rewriteSvgIdReferencesInCss(
|
||||
return css;
|
||||
}
|
||||
let mutated = false;
|
||||
let charged = 0;
|
||||
const chargeSelector =
|
||||
charge &&
|
||||
((bytes: number) => {
|
||||
charged += bytes;
|
||||
charge(bytes);
|
||||
});
|
||||
const recordedIds = recordedSvgIds(references);
|
||||
const idsNamedBy = (selector: string) =>
|
||||
selectorIdTokens(selector).flatMap((id) => {
|
||||
@@ -559,7 +567,7 @@ export function rewriteSvgIdReferencesInCss(
|
||||
});
|
||||
root.walkRules((rule) => {
|
||||
const rewritten = rule.selectors.map((selector) =>
|
||||
rewriteSvgSelectors(selector, idsNamedBy(selector), references),
|
||||
rewriteSvgSelectors(selector, idsNamedBy(selector), references, undefined, chargeSelector),
|
||||
);
|
||||
if (rewritten.some((selector, index) => selector !== rule.selectors[index])) {
|
||||
rule.selectors = rewritten;
|
||||
@@ -582,5 +590,9 @@ export function rewriteSvgIdReferencesInCss(
|
||||
}
|
||||
});
|
||||
|
||||
return mutated ? root.toResult({ map: false }).css : css;
|
||||
const rewritten = mutated ? root.toResult({ map: false }).css : css;
|
||||
// Selector growth was charged as it was built; settle to the sheet's real growth.
|
||||
const settle = Math.max(0, rewritten.length - css.length) - charged;
|
||||
if (charge && settle !== 0) charge(settle);
|
||||
return rewritten;
|
||||
}
|
||||
|
||||
@@ -134,6 +134,7 @@ export function rewriteSvgSelectors(
|
||||
ids: readonly IdSelectorAlias[],
|
||||
references: readonly SvgReferenceAlias[],
|
||||
namespaces?: Namespaces,
|
||||
charge?: (bytes: number) => void,
|
||||
): string {
|
||||
const index = aliasIndex(references);
|
||||
const rewriteAttribute = (predicate: string): string => {
|
||||
@@ -144,9 +145,10 @@ export function rewriteSvgSelectors(
|
||||
const { rawName, flag } = parsed;
|
||||
const alternatives = new Set([predicate]);
|
||||
for (const alias of aliasesFor(index, parsed, namespaces)) {
|
||||
alternatives.add(
|
||||
`[${rawName}="${tokens.escapeCssAttributeValue(alias.after)}"${flag ? ` ${flag}` : ""}]`,
|
||||
);
|
||||
const alternative = `[${rawName}="${tokens.escapeCssAttributeValue(alias.after)}"${flag ? ` ${flag}` : ""}]`;
|
||||
if (alternatives.has(alternative)) continue;
|
||||
charge?.(alternative.length + (alternatives.size === 1 ? ":is(, )".length : ", ".length));
|
||||
alternatives.add(alternative);
|
||||
}
|
||||
return alternatives.size === 1 ? predicate : `:is(${[...alternatives].join(", ")})`;
|
||||
};
|
||||
@@ -155,11 +157,11 @@ export function rewriteSvgSelectors(
|
||||
const namedIds = tokens
|
||||
.selectorIdTokens(selector)
|
||||
.filter((id) => replacements.has(id) || index.renamedIdAlternatives.has(id));
|
||||
const rewrittenIds = tokens.replaceSelectorIdTokens(
|
||||
selector,
|
||||
namedIds,
|
||||
(id) => replacements.get(id) ?? index.renamedIdAlternatives.get(id)!,
|
||||
);
|
||||
const rewrittenIds = tokens.replaceSelectorIdTokens(selector, namedIds, (id, token) => {
|
||||
const replacement = replacements.get(id) ?? index.renamedIdAlternatives.get(id)!;
|
||||
charge?.(replacement.length - token.length);
|
||||
return replacement;
|
||||
});
|
||||
return tokens.replaceSelectorAttributeTokens(rewrittenIds, rewriteAttribute);
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user