mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-19 11:26:02 +00:00
fix(core): keep SVG id renaming linear in the page size and within the render size limit (#8147)
* test(core): SVG id renaming shares its table, looks up only named ids, caps and charges what it adds * fix(core): SVG id renaming shares one table, caps id prefixes and charges the bytes it adds * test(core): a long namespace is hashed once per mount * fix(core): sanitize and hash each mount's namespace once, before minting its ids * test(core): page goldens carry the regenerated selector alias bundle
This commit is contained in:
@@ -90,7 +90,7 @@ export interface CanaryInput {
|
||||
* to a UTF-8 encoding here first, which is not free in the browser bundle
|
||||
* (`TextEncoder` is fine; `Buffer` is not).
|
||||
*/
|
||||
function fnv1a32(input: string): number {
|
||||
export function fnv1a32(input: string): number {
|
||||
let hash = 0x811c9dc5;
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
hash ^= input.charCodeAt(i);
|
||||
|
||||
@@ -285,7 +285,7 @@ window.__timelines.main = gsap.timeline({ paused: true });</script><script type=
|
||||
let u = ne(e, a.end);
|
||||
return u ? { name: n.name, rawName: n.rawName, namespace: n.namespace, operator: o, value: a.value, flag: u.flag } : null;
|
||||
}
|
||||
function E(e, n) {
|
||||
function x(e, n) {
|
||||
return e.replace(W, (t) => t.startsWith("[") ? n(t) : t);
|
||||
}
|
||||
var re = "data-hf-svg-reference-aliases";
|
||||
@@ -295,14 +295,14 @@ window.__timelines.main = gsap.timeline({ paused: true });</script><script type=
|
||||
if (!r) return s;
|
||||
let { name: l, rawName: g, namespace: m, operator: b, value: D, flag: w } = r;
|
||||
if (m.kind === "named" != (i !== void 0)) return s;
|
||||
let x = w?.toLowerCase() === "i" ? u : (S) => S, L = u(l), P = t.filter((S) => {
|
||||
let E = w?.toLowerCase() === "i" ? u : (S) => S, L = u(l), P = t.filter((S) => {
|
||||
let V = m.kind === "none" ? S.name : S.localName, U = m.kind === "named" ? i.get(m.prefix) : null;
|
||||
return (m.kind === "any" || S.namespaceURI === U) && u(V) === L;
|
||||
}), v = /* @__PURE__ */ new Set([s]);
|
||||
for (let S of P) a(x(S.before), x(D), b) && v.add(`[${g}="${N(S.after)}"${w ? ` ${w}` : ""}]`);
|
||||
for (let S of P) a(E(S.before), E(D), b) && v.add(`[${g}="${N(S.after)}"${w ? ` ${w}` : ""}]`);
|
||||
return v.size === 1 ? s : `:is(${[...v].join(", ")})`;
|
||||
};
|
||||
if (i) return E(e, d);
|
||||
if (i) return x(e, d);
|
||||
let p = new Map(n.map(({ id: s, replacement: r }) => [s, r])), f = /* @__PURE__ */ new Map();
|
||||
for (let s of t) {
|
||||
if (s.name !== "id" || s.before === s.after || p.has(s.before)) continue;
|
||||
@@ -311,7 +311,7 @@ window.__timelines.main = gsap.timeline({ paused: true });</script><script type=
|
||||
}
|
||||
for (let [s, r] of f) p.set(s, `:is(${[...r].join(", ")})`);
|
||||
let c = q(e, [...p.keys()], (s) => p.get(s));
|
||||
return E(c, d);
|
||||
return x(c, d);
|
||||
}
|
||||
function se(e, n, t = true) {
|
||||
let i = [], a = (t ? [...e.querySelectorAll(`[${n}]`)] : []).map((d) => d.getAttribute(n)), u = e.getAttribute?.(n);
|
||||
@@ -836,7 +836,7 @@ window.__timelines.main = gsap.timeline({ paused: true });</script><script type=
|
||||
let u = ne(e, a.end);
|
||||
return u ? { name: n.name, rawName: n.rawName, namespace: n.namespace, operator: o, value: a.value, flag: u.flag } : null;
|
||||
}
|
||||
function E(e, n) {
|
||||
function x(e, n) {
|
||||
return e.replace(W, (t) => t.startsWith("[") ? n(t) : t);
|
||||
}
|
||||
var re = "data-hf-svg-reference-aliases";
|
||||
@@ -846,14 +846,14 @@ window.__timelines.main = gsap.timeline({ paused: true });</script><script type=
|
||||
if (!r) return s;
|
||||
let { name: l, rawName: g, namespace: m, operator: b, value: D, flag: w } = r;
|
||||
if (m.kind === "named" != (i !== void 0)) return s;
|
||||
let x = w?.toLowerCase() === "i" ? u : (S) => S, L = u(l), P = t.filter((S) => {
|
||||
let E = w?.toLowerCase() === "i" ? u : (S) => S, L = u(l), P = t.filter((S) => {
|
||||
let V = m.kind === "none" ? S.name : S.localName, U = m.kind === "named" ? i.get(m.prefix) : null;
|
||||
return (m.kind === "any" || S.namespaceURI === U) && u(V) === L;
|
||||
}), v = /* @__PURE__ */ new Set([s]);
|
||||
for (let S of P) a(x(S.before), x(D), b) && v.add(`[${g}="${N(S.after)}"${w ? ` ${w}` : ""}]`);
|
||||
for (let S of P) a(E(S.before), E(D), b) && v.add(`[${g}="${N(S.after)}"${w ? ` ${w}` : ""}]`);
|
||||
return v.size === 1 ? s : `:is(${[...v].join(", ")})`;
|
||||
};
|
||||
if (i) return E(e, d);
|
||||
if (i) return x(e, d);
|
||||
let p = new Map(n.map(({ id: s, replacement: r }) => [s, r])), f = /* @__PURE__ */ new Map();
|
||||
for (let s of t) {
|
||||
if (s.name !== "id" || s.before === s.after || p.has(s.before)) continue;
|
||||
@@ -862,7 +862,7 @@ window.__timelines.main = gsap.timeline({ paused: true });</script><script type=
|
||||
}
|
||||
for (let [s, r] of f) p.set(s, `:is(${[...r].join(", ")})`);
|
||||
let c = q(e, [...p.keys()], (s) => p.get(s));
|
||||
return E(c, d);
|
||||
return x(c, d);
|
||||
}
|
||||
function se(e, n, t = true) {
|
||||
let i = [], a = (t ? [...e.querySelectorAll(`[${n}]`)] : []).map((d) => d.getAttribute(n)), u = e.getAttribute?.(n);
|
||||
@@ -1387,7 +1387,7 @@ window.__timelines.main = gsap.timeline({ paused: true });</script><script type=
|
||||
let u = ne(e, a.end);
|
||||
return u ? { name: n.name, rawName: n.rawName, namespace: n.namespace, operator: o, value: a.value, flag: u.flag } : null;
|
||||
}
|
||||
function E(e, n) {
|
||||
function x(e, n) {
|
||||
return e.replace(W, (t) => t.startsWith("[") ? n(t) : t);
|
||||
}
|
||||
var re = "data-hf-svg-reference-aliases";
|
||||
@@ -1397,14 +1397,14 @@ window.__timelines.main = gsap.timeline({ paused: true });</script><script type=
|
||||
if (!r) return s;
|
||||
let { name: l, rawName: g, namespace: m, operator: b, value: D, flag: w } = r;
|
||||
if (m.kind === "named" != (i !== void 0)) return s;
|
||||
let x = w?.toLowerCase() === "i" ? u : (S) => S, L = u(l), P = t.filter((S) => {
|
||||
let E = w?.toLowerCase() === "i" ? u : (S) => S, L = u(l), P = t.filter((S) => {
|
||||
let V = m.kind === "none" ? S.name : S.localName, U = m.kind === "named" ? i.get(m.prefix) : null;
|
||||
return (m.kind === "any" || S.namespaceURI === U) && u(V) === L;
|
||||
}), v = /* @__PURE__ */ new Set([s]);
|
||||
for (let S of P) a(x(S.before), x(D), b) && v.add(`[${g}="${N(S.after)}"${w ? ` ${w}` : ""}]`);
|
||||
for (let S of P) a(E(S.before), E(D), b) && v.add(`[${g}="${N(S.after)}"${w ? ` ${w}` : ""}]`);
|
||||
return v.size === 1 ? s : `:is(${[...v].join(", ")})`;
|
||||
};
|
||||
if (i) return E(e, d);
|
||||
if (i) return x(e, d);
|
||||
let p = new Map(n.map(({ id: s, replacement: r }) => [s, r])), f = /* @__PURE__ */ new Map();
|
||||
for (let s of t) {
|
||||
if (s.name !== "id" || s.before === s.after || p.has(s.before)) continue;
|
||||
@@ -1413,7 +1413,7 @@ window.__timelines.main = gsap.timeline({ paused: true });</script><script type=
|
||||
}
|
||||
for (let [s, r] of f) p.set(s, `:is(${[...r].join(", ")})`);
|
||||
let c = q(e, [...p.keys()], (s) => p.get(s));
|
||||
return E(c, d);
|
||||
return x(c, d);
|
||||
}
|
||||
function se(e, n, t = true) {
|
||||
let i = [], a = (t ? [...e.querySelectorAll(`[${n}]`)] : []).map((d) => d.getAttribute(n)), u = e.getAttribute?.(n);
|
||||
|
||||
@@ -312,7 +312,7 @@ window.__timelines.main = gsap.timeline({ paused: true });
|
||||
let u = ne(e, a.end);
|
||||
return u ? { name: n.name, rawName: n.rawName, namespace: n.namespace, operator: o, value: a.value, flag: u.flag } : null;
|
||||
}
|
||||
function E(e, n) {
|
||||
function x(e, n) {
|
||||
return e.replace(W, (t) => t.startsWith("[") ? n(t) : t);
|
||||
}
|
||||
var re = "data-hf-svg-reference-aliases";
|
||||
@@ -322,14 +322,14 @@ window.__timelines.main = gsap.timeline({ paused: true });
|
||||
if (!r) return s;
|
||||
let { name: l, rawName: g, namespace: m, operator: b, value: D, flag: w } = r;
|
||||
if (m.kind === "named" != (i !== void 0)) return s;
|
||||
let x = w?.toLowerCase() === "i" ? u : (S) => S, L = u(l), P = t.filter((S) => {
|
||||
let E = w?.toLowerCase() === "i" ? u : (S) => S, L = u(l), P = t.filter((S) => {
|
||||
let V = m.kind === "none" ? S.name : S.localName, U = m.kind === "named" ? i.get(m.prefix) : null;
|
||||
return (m.kind === "any" || S.namespaceURI === U) && u(V) === L;
|
||||
}), v = /* @__PURE__ */ new Set([s]);
|
||||
for (let S of P) a(x(S.before), x(D), b) && v.add(`[${g}="${N(S.after)}"${w ? ` ${w}` : ""}]`);
|
||||
for (let S of P) a(E(S.before), E(D), b) && v.add(`[${g}="${N(S.after)}"${w ? ` ${w}` : ""}]`);
|
||||
return v.size === 1 ? s : `:is(${[...v].join(", ")})`;
|
||||
};
|
||||
if (i) return E(e, d);
|
||||
if (i) return x(e, d);
|
||||
let p = new Map(n.map(({ id: s, replacement: r }) => [s, r])), f = /* @__PURE__ */ new Map();
|
||||
for (let s of t) {
|
||||
if (s.name !== "id" || s.before === s.after || p.has(s.before)) continue;
|
||||
@@ -338,7 +338,7 @@ window.__timelines.main = gsap.timeline({ paused: true });
|
||||
}
|
||||
for (let [s, r] of f) p.set(s, `:is(${[...r].join(", ")})`);
|
||||
let c = q(e, [...p.keys()], (s) => p.get(s));
|
||||
return E(c, d);
|
||||
return x(c, d);
|
||||
}
|
||||
function se(e, n, t = true) {
|
||||
let i = [], a = (t ? [...e.querySelectorAll(`[${n}]`)] : []).map((d) => d.getAttribute(n)), u = e.getAttribute?.(n);
|
||||
@@ -864,7 +864,7 @@ window.__timelines.main = gsap.timeline({ paused: true });
|
||||
let u = ne(e, a.end);
|
||||
return u ? { name: n.name, rawName: n.rawName, namespace: n.namespace, operator: o, value: a.value, flag: u.flag } : null;
|
||||
}
|
||||
function E(e, n) {
|
||||
function x(e, n) {
|
||||
return e.replace(W, (t) => t.startsWith("[") ? n(t) : t);
|
||||
}
|
||||
var re = "data-hf-svg-reference-aliases";
|
||||
@@ -874,14 +874,14 @@ window.__timelines.main = gsap.timeline({ paused: true });
|
||||
if (!r) return s;
|
||||
let { name: l, rawName: g, namespace: m, operator: b, value: D, flag: w } = r;
|
||||
if (m.kind === "named" != (i !== void 0)) return s;
|
||||
let x = w?.toLowerCase() === "i" ? u : (S) => S, L = u(l), P = t.filter((S) => {
|
||||
let E = w?.toLowerCase() === "i" ? u : (S) => S, L = u(l), P = t.filter((S) => {
|
||||
let V = m.kind === "none" ? S.name : S.localName, U = m.kind === "named" ? i.get(m.prefix) : null;
|
||||
return (m.kind === "any" || S.namespaceURI === U) && u(V) === L;
|
||||
}), v = /* @__PURE__ */ new Set([s]);
|
||||
for (let S of P) a(x(S.before), x(D), b) && v.add(`[${g}="${N(S.after)}"${w ? ` ${w}` : ""}]`);
|
||||
for (let S of P) a(E(S.before), E(D), b) && v.add(`[${g}="${N(S.after)}"${w ? ` ${w}` : ""}]`);
|
||||
return v.size === 1 ? s : `:is(${[...v].join(", ")})`;
|
||||
};
|
||||
if (i) return E(e, d);
|
||||
if (i) return x(e, d);
|
||||
let p = new Map(n.map(({ id: s, replacement: r }) => [s, r])), f = /* @__PURE__ */ new Map();
|
||||
for (let s of t) {
|
||||
if (s.name !== "id" || s.before === s.after || p.has(s.before)) continue;
|
||||
@@ -890,7 +890,7 @@ window.__timelines.main = gsap.timeline({ paused: true });
|
||||
}
|
||||
for (let [s, r] of f) p.set(s, `:is(${[...r].join(", ")})`);
|
||||
let c = q(e, [...p.keys()], (s) => p.get(s));
|
||||
return E(c, d);
|
||||
return x(c, d);
|
||||
}
|
||||
function se(e, n, t = true) {
|
||||
let i = [], a = (t ? [...e.querySelectorAll(`[${n}]`)] : []).map((d) => d.getAttribute(n)), u = e.getAttribute?.(n);
|
||||
@@ -1416,7 +1416,7 @@ window.__timelines.main = gsap.timeline({ paused: true });
|
||||
let u = ne(e, a.end);
|
||||
return u ? { name: n.name, rawName: n.rawName, namespace: n.namespace, operator: o, value: a.value, flag: u.flag } : null;
|
||||
}
|
||||
function E(e, n) {
|
||||
function x(e, n) {
|
||||
return e.replace(W, (t) => t.startsWith("[") ? n(t) : t);
|
||||
}
|
||||
var re = "data-hf-svg-reference-aliases";
|
||||
@@ -1426,14 +1426,14 @@ window.__timelines.main = gsap.timeline({ paused: true });
|
||||
if (!r) return s;
|
||||
let { name: l, rawName: g, namespace: m, operator: b, value: D, flag: w } = r;
|
||||
if (m.kind === "named" != (i !== void 0)) return s;
|
||||
let x = w?.toLowerCase() === "i" ? u : (S) => S, L = u(l), P = t.filter((S) => {
|
||||
let E = w?.toLowerCase() === "i" ? u : (S) => S, L = u(l), P = t.filter((S) => {
|
||||
let V = m.kind === "none" ? S.name : S.localName, U = m.kind === "named" ? i.get(m.prefix) : null;
|
||||
return (m.kind === "any" || S.namespaceURI === U) && u(V) === L;
|
||||
}), v = /* @__PURE__ */ new Set([s]);
|
||||
for (let S of P) a(x(S.before), x(D), b) && v.add(`[${g}="${N(S.after)}"${w ? ` ${w}` : ""}]`);
|
||||
for (let S of P) a(E(S.before), E(D), b) && v.add(`[${g}="${N(S.after)}"${w ? ` ${w}` : ""}]`);
|
||||
return v.size === 1 ? s : `:is(${[...v].join(", ")})`;
|
||||
};
|
||||
if (i) return E(e, d);
|
||||
if (i) return x(e, d);
|
||||
let p = new Map(n.map(({ id: s, replacement: r }) => [s, r])), f = /* @__PURE__ */ new Map();
|
||||
for (let s of t) {
|
||||
if (s.name !== "id" || s.before === s.after || p.has(s.before)) continue;
|
||||
@@ -1442,7 +1442,7 @@ window.__timelines.main = gsap.timeline({ paused: true });
|
||||
}
|
||||
for (let [s, r] of f) p.set(s, `:is(${[...r].join(", ")})`);
|
||||
let c = q(e, [...p.keys()], (s) => p.get(s));
|
||||
return E(c, d);
|
||||
return x(c, d);
|
||||
}
|
||||
function se(e, n, t = true) {
|
||||
let i = [], a = (t ? [...e.querySelectorAll(`[${n}]`)] : []).map((d) => d.getAttribute(n)), u = e.getAttribute?.(n);
|
||||
|
||||
@@ -1257,3 +1257,25 @@ describe("SVG namespacing compatibility on current compiler", () => {
|
||||
dom.window.close();
|
||||
});
|
||||
});
|
||||
|
||||
// fails without the fix: renaming a mount's colliding SVG ids charged nothing to the render's budget.
|
||||
it("charges the bytes SVG id renaming adds to the mount that grew", () => {
|
||||
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 data-composition-id="b" data-composition-src="art.html" data-start="0" data-duration="2"></div>
|
||||
</div></body></html>`);
|
||||
const hosts = [...document.querySelectorAll("[data-composition-src]")];
|
||||
const charged: Array<[string, number]> = [];
|
||||
|
||||
inlineSubCompositions(document, hosts, {
|
||||
resolveHtml: () =>
|
||||
`<template><div data-composition-id="art"><svg><clipPath id="clip"><rect/></clipPath></svg><div clip-path="url(#clip)"></div></div></template>`,
|
||||
parseHtml: (html) => parseHTML(html).document,
|
||||
chargeEmitted: (src, bytes) => charged.push([src, bytes]),
|
||||
});
|
||||
|
||||
expect(document.querySelectorAll('[id="clip"]')).toHaveLength(1);
|
||||
expect(charged.filter(([src, bytes]) => src === "art.html" && bytes > 0).length).toBeGreaterThan(
|
||||
0,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -419,7 +419,7 @@ export function inlineSubCompositions(
|
||||
const moduleScripts: string[] = [];
|
||||
const externalLinks: ExternalLink[] = [];
|
||||
const variablesByComp: Record<string, Record<string, unknown>> = {};
|
||||
const svgIdScopes: Array<SvgIdScope & { styleStart: number; styleEnd: number }> = [];
|
||||
const svgIdScopes: Array<SvgIdScope & { src: string; styleStart: number; styleEnd: number }> = [];
|
||||
// A file mounted many times reads the same; only its scope, ids and variables differ per mount.
|
||||
// Each file is parsed once and only read; a mount edits its own copy.
|
||||
const parsed = new Map<string, Document>();
|
||||
@@ -790,6 +790,7 @@ export function inlineSubCompositions(
|
||||
// scoping and script scoping already key on. Nested hosts are excluded
|
||||
// because each of them is recorded as its own scope when dequeued.
|
||||
svgIdScopes.push({
|
||||
src,
|
||||
root: hostEl,
|
||||
namespace: runtimeCompId || scopeCompId,
|
||||
exclude: nested.hosts.map((nestedHost) => nestedHost.host),
|
||||
@@ -808,26 +809,35 @@ export function inlineSubCompositions(
|
||||
// getElementById/media-id fixes.
|
||||
const hostRoots = svgIdScopes.map(({ root }) => root);
|
||||
const clips = sceneClipRoots(document, hostRoots);
|
||||
const svgIdMaps = namespaceCollidingSvgIds(document, [
|
||||
...svgIdScopes.map(({ root, namespace, exclude, styleStart, styleEnd }) => ({
|
||||
root,
|
||||
namespace,
|
||||
exclude,
|
||||
cssTexts: styles.slice(styleStart, styleEnd).map((style) => style.css),
|
||||
})),
|
||||
{
|
||||
root: document.documentElement,
|
||||
namespace: "",
|
||||
referenceTarget: "document",
|
||||
exclude: [...hostRoots, ...clips],
|
||||
cssTexts: rootStyles.map((style) => style.textContent ?? ""),
|
||||
},
|
||||
...clips.map((root, index) => ({
|
||||
root,
|
||||
namespace: `clip-${index}`,
|
||||
exclude: hostRoots.filter((host) => root.contains(host)),
|
||||
})),
|
||||
]);
|
||||
const svgIdMaps = namespaceCollidingSvgIds(
|
||||
document,
|
||||
[
|
||||
...svgIdScopes.map(({ root, namespace, exclude, styleStart, styleEnd }) => ({
|
||||
root,
|
||||
namespace,
|
||||
exclude,
|
||||
cssTexts: styles.slice(styleStart, styleEnd).map((style) => style.css),
|
||||
})),
|
||||
{
|
||||
root: document.documentElement,
|
||||
namespace: "",
|
||||
referenceTarget: "document",
|
||||
exclude: [...hostRoots, ...clips],
|
||||
cssTexts: rootStyles.map((style) => style.textContent ?? ""),
|
||||
},
|
||||
...clips.map((root, index) => ({
|
||||
root,
|
||||
namespace: `clip-${index}`,
|
||||
exclude: hostRoots.filter((host) => root.contains(host)),
|
||||
})),
|
||||
],
|
||||
undefined,
|
||||
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);
|
||||
};
|
||||
svgIdMaps.slice(0, svgIdScopes.length).forEach((idMap, index) => {
|
||||
const { styleStart, styleEnd } = svgIdScopes[index]!;
|
||||
const references = readSvgReferenceAliases(
|
||||
@@ -835,7 +845,9 @@ export function inlineSubCompositions(
|
||||
SVG_REFERENCE_ALIASES_ATTR,
|
||||
);
|
||||
for (let i = styleStart; i < styleEnd; i += 1) {
|
||||
styles[i]!.css = rewriteSvgIdReferencesInCss(styles[i]!.css, idMap, references);
|
||||
const rewritten = rewriteSvgIdReferencesInCss(styles[i]!.css, idMap, references);
|
||||
chargeGrowth(svgIdScopes[index]!.src, styles[i]!.css, rewritten);
|
||||
styles[i]!.css = rewritten;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -844,11 +856,14 @@ export function inlineSubCompositions(
|
||||
SVG_REFERENCE_ALIASES_ATTR,
|
||||
);
|
||||
for (const style of rootStyles) {
|
||||
style.textContent = rewriteSvgIdReferencesInCss(
|
||||
style.textContent ?? "",
|
||||
const css = style.textContent ?? "";
|
||||
const rewritten = rewriteSvgIdReferencesInCss(
|
||||
css,
|
||||
svgIdMaps[svgIdScopes.length]!,
|
||||
rootReferences,
|
||||
);
|
||||
chargeGrowth("the page", css, rewritten);
|
||||
style.textContent = rewritten;
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -203,6 +203,21 @@ function markUnguardedOffsets(selector: string): boolean[] {
|
||||
* full replacement text (including its own leading `#`, if any) to splice
|
||||
* in.
|
||||
*/
|
||||
/** The `#id` values a selector names, read as `replaceSelectorIdTokens` reads them. */
|
||||
export function selectorIdTokens(selector: string): string[] {
|
||||
const ids: string[] = [];
|
||||
if (!selector.includes("#")) return ids;
|
||||
const unguarded = markUnguardedOffsets(selector);
|
||||
for (let index = 0; index < selector.length; index += 1) {
|
||||
if (!unguarded[index] || selector[index] !== "#") continue;
|
||||
const token = decodeCssIdentifierAt(selector, index + 1);
|
||||
if (!token) continue;
|
||||
ids.push(token.value);
|
||||
index = token.end - 1;
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
export function replaceSelectorIdTokens(
|
||||
selector: string,
|
||||
candidateIds: readonly string[],
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { parseHTML } from "linkedom";
|
||||
|
||||
const hashCalls = vi.hoisted(() => [] as string[]);
|
||||
vi.mock("../canary", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../canary")>();
|
||||
return {
|
||||
...actual,
|
||||
fnv1a32: (input: string) => {
|
||||
hashCalls.push(input);
|
||||
return actual.fnv1a32(input);
|
||||
},
|
||||
};
|
||||
});
|
||||
import {
|
||||
SVG_AUTHORED_ID_ATTR,
|
||||
namespaceCollidingSvgIds,
|
||||
@@ -429,3 +441,127 @@ it("finalizes initially referenced keepers while allowing first-use references a
|
||||
]);
|
||||
expect(roots[1]!.querySelector("g")!.getAttribute("clip-path")).toBe("url(#b--clip)");
|
||||
});
|
||||
|
||||
function scopedDocument(specs: ScopeSpec[], after = "") {
|
||||
const { document } = parseHTML(
|
||||
`<!DOCTYPE html><html><body>${specs.map((spec) => `<div class="scope">${spec.html}</div>`).join("")}${after}</body></html>`,
|
||||
);
|
||||
const roots = [...document.querySelectorAll("div.scope")];
|
||||
const scopes = specs.map((spec, index) => ({ root: roots[index]!, namespace: spec.namespace }));
|
||||
return {
|
||||
document: document as unknown as Parameters<typeof namespaceCollidingSvgIds>[0],
|
||||
scopes,
|
||||
};
|
||||
}
|
||||
|
||||
function countMapSets<T>(run: () => T): { result: T; sets: number } {
|
||||
const set = vi.spyOn(Map.prototype, "set");
|
||||
try {
|
||||
const result = run();
|
||||
return { result, sets: set.mock.calls.length };
|
||||
} finally {
|
||||
set.mockRestore();
|
||||
}
|
||||
}
|
||||
|
||||
// fails without the fix: each scope copied the whole document rename table, scopes x ids entries.
|
||||
it("shares one document rename table across scopes instead of copying it per scope", () => {
|
||||
const ids = Array.from({ length: 200 }, (_, index) => `c${index}`);
|
||||
const defs = ids.map((id) => `<clipPath id="${id}"/><rect clip-path="url(#${id})"/>`).join("");
|
||||
const { document, scopes } = scopedDocument(
|
||||
[
|
||||
{ namespace: "first", html: `<svg>${defs}</svg>` },
|
||||
...ids.map((_, index) => ({ namespace: `m${index}`, html: "<i></i>" })),
|
||||
],
|
||||
`<svg>${ids.map((id) => `<clipPath id="${id}"/>`).join("")}</svg>`,
|
||||
);
|
||||
|
||||
const { result: idMaps, sets } = countMapSets(() => namespaceCollidingSvgIds(document, scopes));
|
||||
|
||||
expect(idMaps[200]!.get("c7")).toBe("first--c7");
|
||||
expect(idMaps[200]!.size).toBe(200);
|
||||
expect(sets).toBeLessThan(10_000);
|
||||
});
|
||||
|
||||
// fails without the fix: every selector rebuilt a table of every renamed id.
|
||||
it("looks up only the ids a stylesheet names", () => {
|
||||
const idMap = new Map(Array.from({ length: 2000 }, (_, index) => [`c${index}`, `m--c${index}`]));
|
||||
const css = Array.from(
|
||||
{ length: 300 },
|
||||
(_, index) => `.r${index} #c${index} { fill: url(#c${index}); }`,
|
||||
).join("\n");
|
||||
|
||||
const { result, sets } = countMapSets(() => rewriteSvgIdReferencesInCss(css, idMap));
|
||||
|
||||
expect(result).toContain(".r5 :is(#c5, #m--c5) { fill: url(#m--c5); }");
|
||||
expect(sets).toBeLessThan(20_000);
|
||||
});
|
||||
|
||||
// fails without the fix: the whole namespace, however long, prefixed every renamed id.
|
||||
it("caps a long namespace's prefix, each mount's renamed ids still distinct", () => {
|
||||
const long = (end: string) => `${"x".repeat(5000)}${end}`;
|
||||
const { idMaps } = namespace([
|
||||
{ namespace: "a", html: CLIPPED },
|
||||
{ namespace: long("1"), html: CLIPPED },
|
||||
{ namespace: long("2"), html: CLIPPED },
|
||||
]);
|
||||
|
||||
const one = idMaps[1]!.get("clip")!;
|
||||
const two = idMaps[2]!.get("clip")!;
|
||||
expect(one.length).toBeLessThan(64);
|
||||
expect(two.length).toBeLessThan(64);
|
||||
expect(two).not.toBe(one);
|
||||
});
|
||||
|
||||
const attributeBytes = (document: { querySelectorAll(selector: string): Iterable<Element> }) =>
|
||||
[...document.querySelectorAll("*")].reduce(
|
||||
(sum, el) =>
|
||||
sum + [...el.attributes].reduce((n, attr) => n + attr.name.length + attr.value.length + 4, 0),
|
||||
0,
|
||||
);
|
||||
|
||||
// fails without the fix: the pass wrote renamed ids and their records without charging them.
|
||||
it("charges every attribute byte it adds", () => {
|
||||
const { document, scopes } = scopedDocument([
|
||||
{ namespace: "a", html: CLIPPED },
|
||||
{ namespace: "b", html: CLIPPED },
|
||||
{ namespace: "c", html: CLIPPED },
|
||||
]);
|
||||
const before = attributeBytes(document);
|
||||
const charged: number[] = [];
|
||||
|
||||
namespaceCollidingSvgIds(document, scopes, undefined, (_scope, bytes) => charged.push(bytes));
|
||||
|
||||
const total = charged.reduce((sum, bytes) => sum + bytes, 0);
|
||||
expect(total).toBeGreaterThan(0);
|
||||
expect(total).toBe(attributeBytes(document) - before);
|
||||
});
|
||||
|
||||
it("stops at the first charge the budget refuses", () => {
|
||||
const { document, scopes } = scopedDocument([
|
||||
{ namespace: "a", html: CLIPPED },
|
||||
{ namespace: "b", html: CLIPPED },
|
||||
]);
|
||||
|
||||
expect(() =>
|
||||
namespaceCollidingSvgIds(document, scopes, undefined, () => {
|
||||
throw new Error("too large");
|
||||
}),
|
||||
).toThrow("too large");
|
||||
});
|
||||
|
||||
// fails without the fix: every renamed id re-sanitized and re-hashed its mount's whole namespace.
|
||||
it("hashes a long namespace once per mount, not once per renamed id", () => {
|
||||
const ids = Array.from({ length: 200 }, (_, index) => `c${index}`);
|
||||
const defs = ids.map((id) => `<clipPath id="${id}"/><rect clip-path="url(#${id})"/>`).join("");
|
||||
const { document, scopes } = scopedDocument([
|
||||
{ namespace: "a", html: `<svg>${defs}</svg>` },
|
||||
{ namespace: "x".repeat(5000), html: `<svg>${defs}</svg>` },
|
||||
]);
|
||||
hashCalls.length = 0;
|
||||
|
||||
const idMaps = namespaceCollidingSvgIds(document, scopes);
|
||||
|
||||
expect(idMaps[1]!.size).toBe(200);
|
||||
expect(hashCalls.length).toBe(1);
|
||||
});
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
|
||||
import { replaceMatches, urlHashRefMatches } from "@hyperframes/parsers/css-url-scans";
|
||||
import postcss from "postcss";
|
||||
import { escapeCssIdentifier } from "./selectorIdTokens";
|
||||
import { fnv1a32 } from "../canary";
|
||||
import { escapeCssIdentifier, selectorIdTokens } from "./selectorIdTokens";
|
||||
import {
|
||||
SVG_REFERENCE_ALIASES_ATTR,
|
||||
readSvgReferenceAliases,
|
||||
@@ -33,8 +34,13 @@ function isHrefAttrName(name: string): boolean {
|
||||
return name === "href" || name.endsWith(":href");
|
||||
}
|
||||
|
||||
const MAX_NAMESPACE_PREFIX = 48;
|
||||
|
||||
/** A namespace this long keeps its head and a hash of the whole, so a renamed id's length never depends on it. */
|
||||
function sanitizeNamespaceSegment(value: string): string {
|
||||
return value.replace(/[^a-zA-Z0-9_-]/g, "-");
|
||||
const segment = value.replace(/[^a-zA-Z0-9_-]/g, "-");
|
||||
if (segment.length <= MAX_NAMESPACE_PREFIX) return segment;
|
||||
return `${segment.slice(0, 32)}-${fnv1a32(value).toString(16).padStart(8, "0")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -44,7 +50,7 @@ function sanitizeNamespaceSegment(value: string): string {
|
||||
* URL, not a CSS identifier, so it carries no escapes; the replacement keeps the quoting and
|
||||
* swaps only the id, which stays a valid fragment because the prefix is `[A-Za-z0-9_-]`.
|
||||
*/
|
||||
function rewriteUrlHashRefs(value: string, idMap: ReadonlyMap<string, string>): string {
|
||||
function rewriteUrlHashRefs(value: string, idMap: SvgIdMap): string {
|
||||
if (!value || !value.toLowerCase().includes("url(")) return value;
|
||||
return replaceMatches(value, urlHashRefMatches(value), (full, pre, quote, id, post) => {
|
||||
const mapped = idMap.get(id);
|
||||
@@ -57,11 +63,7 @@ type ReferenceDecision =
|
||||
| { kind: "retain"; alias: SvgReferenceAlias }
|
||||
| { kind: "managed"; before: string; after: string };
|
||||
|
||||
function nativeReferenceValue(
|
||||
name: string,
|
||||
value: string,
|
||||
idMap: ReadonlyMap<string, string>,
|
||||
): string | null {
|
||||
function nativeReferenceValue(name: string, value: string, idMap: SvgIdMap): string | null {
|
||||
if (isHrefAttrName(name) && value.startsWith("#")) {
|
||||
const mapped = idMap.get(value.slice(1));
|
||||
return mapped ? `#${mapped}` : value;
|
||||
@@ -73,7 +75,7 @@ function nativeReferenceValue(
|
||||
function decideReferenceWrite(
|
||||
attr: Attr,
|
||||
previous: SvgReferenceAlias | undefined,
|
||||
idMap: ReadonlyMap<string, string>,
|
||||
idMap: SvgIdMap,
|
||||
): ReferenceDecision {
|
||||
if (attr.name === SVG_REFERENCE_ALIASES_ATTR || attr.name === ID_ATTR) return { kind: "skip" };
|
||||
const before = previous && attr.value === previous.after ? previous.before : attr.value;
|
||||
@@ -100,7 +102,7 @@ function referenceAlias(
|
||||
}
|
||||
|
||||
/** Apply managed reference writes while retaining provenance for later assembly phases. */
|
||||
function rewriteElementIdReferences(el: Element, idMap: ReadonlyMap<string, string>): void {
|
||||
function rewriteElementIdReferences(el: Element, idMap: SvgIdMap): void {
|
||||
const prior = new Map(
|
||||
readSvgReferenceAliases(el, SVG_REFERENCE_ALIASES_ATTR, false).map((alias) => [
|
||||
alias.name,
|
||||
@@ -306,8 +308,8 @@ function buildIdCensus(document: SvgIdQueryable): IdCensus {
|
||||
}
|
||||
|
||||
/** A namespaced id that is not already taken anywhere in the document. */
|
||||
function mintNamespacedId(namespace: string, originalId: string, usedIds: Set<string>): string {
|
||||
const base = `${sanitizeNamespaceSegment(namespace)}--${originalId}`;
|
||||
function mintNamespacedId(prefix: string, originalId: string, usedIds: Set<string>): string {
|
||||
const base = `${prefix}--${originalId}`;
|
||||
let candidate = base;
|
||||
for (let n = 2; usedIds.has(candidate); n += 1) candidate = `${base}-${n}`;
|
||||
usedIds.add(candidate);
|
||||
@@ -337,10 +339,12 @@ function planRenames(
|
||||
scopeIndexByRenamable: ReadonlyMap<Element, number>,
|
||||
): Map<string, string>[] {
|
||||
const idMaps = scopes.map(() => new Map<string, string>());
|
||||
const prefixes: Array<string | undefined> = [];
|
||||
for (const [id, elements] of census.elementsById) {
|
||||
if (elements.length < 2) continue;
|
||||
for (const index of collisionScopes(id, elements, scopeIndexByRenamable)) {
|
||||
idMaps[index]!.set(id, mintNamespacedId(scopes[index]!.namespace, id, census.usedIds));
|
||||
prefixes[index] ??= sanitizeNamespaceSegment(scopes[index]!.namespace);
|
||||
idMaps[index]!.set(id, mintNamespacedId(prefixes[index]!, id, census.usedIds));
|
||||
}
|
||||
}
|
||||
return idMaps;
|
||||
@@ -379,10 +383,49 @@ function localReferenceBindings(elements: readonly Element[]) {
|
||||
return { ids, renamed };
|
||||
}
|
||||
|
||||
/** What reads a scope's renames: a plain `Map`, or a `ScopedIdMap`. */
|
||||
export type SvgIdMap = Pick<ReadonlyMap<string, string>, "get" | "has" | "size">;
|
||||
|
||||
/** One scope's renames read through to the document's shared table, never copied per scope. */
|
||||
class ScopedIdMap implements SvgIdMap {
|
||||
constructor(
|
||||
private readonly own: ReadonlyMap<string, string>,
|
||||
private readonly shared: ReadonlyMap<string, string>,
|
||||
private readonly hidden: ReadonlySet<string | null>,
|
||||
) {}
|
||||
|
||||
get(id: string): string | undefined {
|
||||
return this.own.get(id) ?? (this.hidden.has(id) ? undefined : this.shared.get(id));
|
||||
}
|
||||
|
||||
has(id: string): boolean {
|
||||
return this.get(id) !== undefined;
|
||||
}
|
||||
|
||||
get size(): number {
|
||||
let size = this.own.size + this.shared.size;
|
||||
for (const id of this.own.keys()) if (this.shared.has(id)) size -= 1;
|
||||
for (const id of this.hidden)
|
||||
if (id !== null && !this.own.has(id) && this.shared.has(id)) size -= 1;
|
||||
return size;
|
||||
}
|
||||
}
|
||||
|
||||
const attributeBytes = (el: Element): number =>
|
||||
Array.from(el.attributes ?? [], (attr) => attr.name.length + attr.value.length + 4).reduce(
|
||||
(sum, bytes) => sum + bytes,
|
||||
0,
|
||||
);
|
||||
|
||||
/** Rename the planned elements in one scope and rewrite every reference in
|
||||
* that scope's attributes to match. */
|
||||
function applyRenames(resolved: ResolvedScope, idMap: ReadonlyMap<string, string>): void {
|
||||
* that scope's attributes to match. `charge` gets each element's added bytes. */
|
||||
function applyRenames(
|
||||
resolved: ResolvedScope,
|
||||
idMap: SvgIdMap,
|
||||
charge?: (bytes: number) => void,
|
||||
): void {
|
||||
for (const el of resolved.elements) {
|
||||
const before = charge ? attributeBytes(el) : 0;
|
||||
const currentId = el.getAttribute(ID_ATTR);
|
||||
if (currentId && resolved.renamable.has(el) && idMap.has(currentId)) {
|
||||
if (!el.hasAttribute(SVG_AUTHORED_ID_ATTR)) el.setAttribute(SVG_AUTHORED_ID_ATTR, currentId);
|
||||
@@ -399,6 +442,7 @@ function applyRenames(resolved: ResolvedScope, idMap: ReadonlyMap<string, string
|
||||
el.setAttribute(ID_ATTR, after);
|
||||
}
|
||||
rewriteElementIdReferences(el, idMap);
|
||||
if (charge) charge(attributeBytes(el) - before);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -437,7 +481,8 @@ export function namespaceCollidingSvgIds(
|
||||
document: SvgIdQueryable,
|
||||
scopes: readonly SvgIdScope[],
|
||||
finalizedIds?: Set<Element>,
|
||||
): Map<string, string>[] {
|
||||
charge?: (scopeIndex: number, bytes: number) => void,
|
||||
): SvgIdMap[] {
|
||||
if (scopes.length === 0) return [];
|
||||
|
||||
const census = buildIdCensus(document);
|
||||
@@ -460,11 +505,14 @@ export function namespaceCollidingSvgIds(
|
||||
const local = localReferenceBindings(
|
||||
scopes[index]!.referenceTarget === "document" ? [] : scope.elements,
|
||||
);
|
||||
const inherited = [...documentTargets].filter(([id]) => !local.ids.has(id));
|
||||
return new Map([...inherited, ...local.renamed, ...idMaps[index]!]);
|
||||
return new ScopedIdMap(
|
||||
new Map([...local.renamed, ...idMaps[index]!]),
|
||||
documentTargets,
|
||||
local.ids,
|
||||
);
|
||||
});
|
||||
referenceMaps.forEach((idMap, index) => {
|
||||
applyRenames(resolved[index]!, idMap);
|
||||
applyRenames(resolved[index]!, idMap, charge && ((bytes) => charge(index, bytes)));
|
||||
});
|
||||
for (const el of newlyEligible) finalizedIds?.add(el);
|
||||
return referenceMaps;
|
||||
@@ -485,7 +533,7 @@ export function namespaceCollidingSvgIds(
|
||||
*/
|
||||
export function rewriteSvgIdReferencesInCss(
|
||||
css: string,
|
||||
idMap: ReadonlyMap<string, string>,
|
||||
idMap: SvgIdMap,
|
||||
references: readonly SvgReferenceAlias[] = [],
|
||||
): string {
|
||||
if (!css || (idMap.size === 0 && references.length === 0)) return css;
|
||||
@@ -503,15 +551,17 @@ export function rewriteSvgIdReferencesInCss(
|
||||
const recordedIds = new Set(
|
||||
references.filter((alias) => alias.name === ID_ATTR).map((alias) => alias.before),
|
||||
);
|
||||
const ids = [...idMap]
|
||||
.filter(([id]) => !recordedIds.has(id))
|
||||
.map(([id, renamed]) => ({
|
||||
id,
|
||||
replacement: `:is(#${escapeCssIdentifier(id)}, #${escapeCssIdentifier(renamed)})`,
|
||||
}));
|
||||
const idsNamedBy = (selector: string) =>
|
||||
selectorIdTokens(selector).flatMap((id) => {
|
||||
const renamed = recordedIds.has(id) ? undefined : idMap.get(id);
|
||||
if (!renamed) return [];
|
||||
return [
|
||||
{ id, replacement: `:is(#${escapeCssIdentifier(id)}, #${escapeCssIdentifier(renamed)})` },
|
||||
];
|
||||
});
|
||||
root.walkRules((rule) => {
|
||||
const rewritten = rule.selectors.map((selector) =>
|
||||
rewriteSvgSelectors(selector, ids, references),
|
||||
rewriteSvgSelectors(selector, idsNamedBy(selector), references),
|
||||
);
|
||||
if (rewritten.some((selector, index) => selector !== rule.selectors[index])) {
|
||||
rule.selectors = rewritten;
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user