Skip to content

Commit 0d51eb0

Browse files
perf(core): a heavy project's first preview page builds without repeated style and path scans (#5893)
* perf(core): a project with many composition variables builds without a style scan per variable * perf(core): a build checks each project path once, however often a scene is mounted * perf(core): collecting a page's characters for fonts no longer copies the page into arrays
1 parent 5641a91 commit 0d51eb0

4 files changed

Lines changed: 122 additions & 5 deletions

File tree

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// @vitest-environment node
2+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+
import { tmpdir } from "node:os";
4+
import { join } from "node:path";
5+
import { afterAll, expect, it, vi } from "vitest";
6+
import { bundleToSingleHtml } from "./htmlBundler";
7+
8+
const checked = vi.hoisted(() => [] as string[]);
9+
10+
vi.mock("../safePath.js", async (importOriginal) => {
11+
const actual = await importOriginal<typeof import("../safePath.js")>();
12+
return {
13+
...actual,
14+
isSafePath: (base: string, resolved: string) => {
15+
checked.push(resolved);
16+
return actual.isSafePath(base, resolved);
17+
},
18+
};
19+
});
20+
21+
const dir = mkdtempSync(join(tmpdir(), "hf-bundle-entry-paths-"));
22+
afterAll(() => rmSync(dir, { recursive: true, force: true }));
23+
24+
it("checks each project path once per build, however many times a sub-composition is mounted", async () => {
25+
mkdirSync(join(dir, "compositions"), { recursive: true });
26+
mkdirSync(join(dir, "assets"), { recursive: true });
27+
writeFileSync(join(dir, "assets", "logo.png"), "png");
28+
writeFileSync(join(dir, "compositions", "texture.png"), "png");
29+
writeFileSync(
30+
join(dir, "compositions", "card.html"),
31+
`<!doctype html><html><head><style>
32+
.card { background: url(../assets/logo.png); }
33+
.card .bg { background: url(texture.png); }
34+
</style></head><body>
35+
<div data-composition-id="card" data-width="320" data-height="180" data-start="0" data-duration="2">
36+
<div class="bg"></div>
37+
</div></body></html>`,
38+
);
39+
const mount = (start: number) =>
40+
`<div data-composition-id="card" data-composition-src="compositions/card.html" data-start="${start}"` +
41+
` data-duration="2"></div>`;
42+
writeFileSync(
43+
join(dir, "index.html"),
44+
`<!doctype html><html><body>
45+
<div data-composition-id="main" data-width="320" data-height="180" data-start="0" data-duration="6">
46+
${[0, 2, 4].map(mount).join("\n")}
47+
</div>
48+
<script>window.__timelines = {};</script>
49+
</body></html>`,
50+
);
51+
52+
const bundled = await bundleToSingleHtml(dir, { inlineAssets: false });
53+
54+
expect(bundled).toContain("url(compositions/texture.png)");
55+
expect(bundled).toContain("url(assets/logo.png)");
56+
const repeated = checked.filter((path, at) => checked.indexOf(path) !== at);
57+
expect(repeated).toEqual([]);
58+
});

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3646,3 +3646,34 @@ describe("stampHfIds", () => {
36463646
expect(logo(html)).not.toContain("data-hf-id");
36473647
});
36483648
});
3649+
3650+
describe("emitRootCompositionVariableStyles — authored definitions", () => {
3651+
function emitted(authoredCss: string): string {
3652+
const { document } = parseHTML(
3653+
`<!doctype html><html><head><style>${authoredCss}</style></head>` +
3654+
`<body><div data-composition-id="card"></div></body></html>`,
3655+
);
3656+
emitRootCompositionVariableStyles(document, {
3657+
card: { accent: "blue", "accent-dark": "navy" },
3658+
});
3659+
return document.querySelector("style[data-hf-composition-variables]")?.textContent ?? "";
3660+
}
3661+
3662+
it("leaves a variable the stylesheet defines, whatever space sits before its colon", () => {
3663+
for (const authored of [
3664+
":root{--accent:red}",
3665+
":root { --accent : red }",
3666+
":root {\n --accent\n : red }",
3667+
]) {
3668+
const css = emitted(authored);
3669+
expect(css).not.toContain("--accent:");
3670+
expect(css).toContain("--accent-dark: navy");
3671+
}
3672+
});
3673+
3674+
it("still emits a variable whose name only begins a longer authored one, or is only read", () => {
3675+
const css = emitted(":root { --accent-dark: black; } .badge { color: var(--accent); }");
3676+
expect(css).toContain("--accent: blue");
3677+
expect(css).not.toContain("--accent-dark");
3678+
});
3679+
});

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

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1063,9 +1063,16 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
10631063
const entryHtml = readFileSync(indexPath, "utf-8");
10641064
const mountedShell = readMountedSceneShell(projectDir, entryFile, entryHtml);
10651065
const sourceDir = mountedShell ? projectDir : dirname(indexPath);
1066+
// Every mount of a sub-composition asks again for each of its url()s; isSafePath realpaths the whole chain.
1067+
const entryPaths = new Map<string, string | null>();
10661068
const resolveEntryPath = (relativePath: string): string | null => {
1067-
const resolved = resolve(sourceDir, relativePath);
1068-
return isSafePath(projectDir, resolved) ? resolved : null;
1069+
let entry = entryPaths.get(relativePath);
1070+
if (entry === undefined) {
1071+
const resolved = resolve(sourceDir, relativePath);
1072+
entry = isSafePath(projectDir, resolved) ? resolved : null;
1073+
entryPaths.set(relativePath, entry);
1074+
}
1075+
return entry;
10691076
};
10701077

10711078
const resolveEntryUrl = (url: string): string | null => resolveEntryPath(decodedUrlPath(url));
@@ -1538,7 +1545,23 @@ function authoredDefinesPredicate(document: Document): (id: string) => boolean {
15381545
const authoredCss = [...document.querySelectorAll("style:not([data-hf-composition-variables])")]
15391546
.map((s) => s.textContent || "")
15401547
.join("\n");
1541-
return (id) => new RegExp(`${cssVariableName(id)}\\s*:`).test(authoredCss);
1548+
const defined = namesBeforeAColon(authoredCss);
1549+
return (id) => defined.has(cssVariableName(id));
1550+
}
1551+
1552+
/** Every `--name` written right before a `:`, including the tail of a longer word (`.a--b:hover`), in one pass. */
1553+
function namesBeforeAColon(css: string): Set<string> {
1554+
const names = new Set<string>();
1555+
const word = /[\w-]+/g;
1556+
const colonNext = /\s*:/y;
1557+
for (let match = word.exec(css); match; match = word.exec(css)) {
1558+
colonNext.lastIndex = word.lastIndex;
1559+
if (!colonNext.test(css)) continue;
1560+
const text = match[0];
1561+
for (let at = text.indexOf("--"); at !== -1; at = text.indexOf("--", at + 1))
1562+
names.add(text.slice(at));
1563+
}
1564+
return names;
15421565
}
15431566

15441567
/**

‎packages/core/src/fonts/deterministicFonts.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1886,8 +1886,13 @@ function extractGoogleFontsText(html: string): string | undefined {
18861886
// Intentional over-approximation: raw html includes base64, scripts, and
18871887
// class names, but they collapse in the Set and the budget gate catches bloat.
18881888
const uniqueCharacters = new Set<string>();
1889-
for (const character of new Set([...Array.from(html), ...Array.from(decodedBodyText)])) {
1890-
addCaseClosure(uniqueCharacters, character, locales);
1889+
const seen = new Set<string>();
1890+
for (const text of [html, decodedBodyText]) {
1891+
for (const character of text) {
1892+
if (seen.has(character)) continue;
1893+
seen.add(character);
1894+
addCaseClosure(uniqueCharacters, character, locales);
1895+
}
18911896
}
18921897

18931898
if (hasTextTransformKeyword(html, FULL_WIDTH_KEYWORD_RE)) addFullwidthVariants(uniqueCharacters);

0 commit comments

Comments
 (0)