Files
hyperframes/packages/parsers/src/rewriteSubCompPaths.ts
T
Michael Wang ded5e3eec2 perf: CSS url, @import, @font-face, style and comment scans run in linear time (#7809)
* perf(parsers): find CSS url() references in linear time

A new css-url-scans entry finds what each CSS url( regex in the compile path
and the runtime finds, match for match and group for group, with forward
scans. The regexes restart from every unclosed url(, @import or background:
and read to the end of the text each time, so their time grows with the
square or cube of the input. The scans read each character a bounded number
of times.

rewriteCssAssetUrls uses the scan in place of CSS_URL_RE, which stays
exported for existing callers. A fuzz test checks 20,000 generated pages
against the regexes, and timed tests cover 1 MB of each unclosed form.

The parsers packed-size budget rises to cover the new entry.

* perf(core): bundler, SVG id namespacing and runtime find CSS urls in linear time

The bundler's url() inlining, CSS-file rebasing and @import inlining and
hoisting, the SVG url(#id) rewrite, the runtime's sub-composition url()
rewrite and the scene swap's url and @import list now use the
@hyperframes/parsers css-url-scans entry. Each returns the same matches as
the regex it replaces, in time linear in the CSS length.

* perf(producer): compile finds CSS urls, imports and backgrounds in linear time

Asset collection, head-style @import coalescing, the ancestor
background-image check, remote background and font-face url localization and
local font embedding now use the @hyperframes/parsers css-url-scans entry,
which returns the same matches as the regexes it replaces. A timed test
covers remote background discovery on 200 KB of unclosed background urls.

* perf(parsers): scan style blocks, font-face blocks, comments and mask urls in linear time

css-url-scans gains forward scans for `<style>` blocks, `@font-face { }`
blocks, `/* */` comments, the quoted-or-bare `url()` form and the
`mask-image: … url()` declaration. Each returns the same matches and groups
as the regex in its doc comment. The fuzz test now checks all fifteen scans
on 20,000 generated pages, and the timed tests cover 1 MB of each unclosed
form.

* perf(core): strip and restore stylesheet comments in linear time

Bundling a stylesheet finds its comments with the parsers comment scan and
puts them back in one pass over the placeholders. A comment comes back
verbatim, including text such as `$'` that a string replacement pattern
would expand.

* perf(producer): find style and font-face blocks in linear time

Remote font discovery and local font embedding read `<style>` blocks and
`@font-face` rules with the parsers scans, which return the same blocks as
the regexes they replace.

* perf(lint): read stylesheet and mask-image urls in linear time

The missing stylesheet asset and texture mask rules find `url()` values with
the parsers scans, including the mask-image fallback for a stylesheet that
does not parse.

* perf(cli): rewrite published CSS urls in linear time

Publishing rewrites stylesheet `url()` references with the parsers scan in
place of CSS_URL_RE, with the same matches.

* chore: size budgets cover the CSS scans in parsers and inspector

verify:packed-manifests measures parsers at 894,913 unpacked bytes and
inspector at 3,764,456, both just over 1% above their budgets once the
linear CSS scans are bundled. The budgets rise to 900,000 and 3,790,000.

* perf(parsers): scan stylesheet links and CSS rules in linear time

css-url-scans gains forward scans for `<link … rel="stylesheet" …>` tags and
`selector { declarations }` rules that return the same matches and groups as
the regexes in their doc comments. Both join the 20,000-page fuzz test and
the 1 MB timed tests.

* perf(core): restore stylesheet imports and list scene font faces in linear time

Bundling a stylesheet puts its comment and @import placeholders back in one
pass, so an imported sheet comes back verbatim and is not searched again.
fontFaceBlocks lists @font-face rules with the parsers scan. A fuzz test
checks the one-pass restore against the sequential one on 20,000 sheets.

* perf(producer): find stylesheet links, CSS rules and font-face blocks in linear time

Font stylesheet inlining and project font discovery find stylesheet links,
and the ancestor background check finds CSS rules, with the parsers scans.
extractFontFaceBlocks matches every brace in one pass instead of counting
depth again from each @font-face; a fuzz test checks it against the depth
count on 20,000 sheets.

* test(core): time the CSS placeholder restore directly

The bundle test with 6,000 imports was timed mostly on 6,000 file reads,
which took 2.7 s on the Windows runner. The restore is now timed on its own
over 20,000 placeholders, and a short bundle test still checks that every
import of a sheet is inlined.
2026-11-15 08:22:52 +00:00

164 lines
6.2 KiB
TypeScript

/**
* Rewrite relative asset paths in sub-composition content so they resolve
* correctly after the content is inlined into the root document.
*
* A sub-composition at "compositions/scene.html" referencing "../icon.svg"
* means the project root — but after inlining into root index.html, the
* "../" escapes the project directory and causes 404s. This function
* resolves each relative path against the sub-composition's directory,
* then normalizes it to be relative to the project root.
*
* Used by both the core bundler (preview) and the producer compiler (render)
* to ensure consistent behavior.
*/
// URL paths in HTML output are POSIX regardless of host OS — use the `posix`
// submodule so Windows builds don't emit backslash-separated paths (or worse,
// drive-letter-prefixed artifacts from `resolve("/", ...)`).
import { posix } from "path";
import { cssUrlMatches, replaceMatches } from "./cssUrlScans.js";
import { rewriteSrcsetUrls } from "./srcset.js";
const { join, resolve, dirname } = posix;
import {
PATH_ATTRS,
isNonRelativeUrl,
splitUrlSuffix,
decodeWellFormedEscapes,
encodeUrlPath,
} from "./assetPaths.js";
const isAbsoluteOrSpecial = isNonRelativeUrl;
/**
* Returns true only for paths that traverse up with `../`.
* Plain relative paths like `assets/foo.svg` are ambiguous: two conventions are
* in the wild, and only the filesystem can tell them apart — see `AssetExists`.
*/
function needsRewrite(val: string): boolean {
return val.startsWith("../") || val === "..";
}
/**
* Probe for "does this project-root-relative path exist?", supplied by callers
* that can see the filesystem (the studio preview builder, the bundler, the
* producer). Keeps this module free of `node:fs` so it stays browser-safe.
*
* It disambiguates the two conventions for a plain relative path authored in a
* sub-composition that lives in a subdirectory:
*
* 1. A SIBLING file — `<link href="_shared.css">` next to the composition.
* This is what a browser resolves when the file is opened directly, and
* what an author means. Once the content moves into the project-root
* document it must become `design/styleframes/_shared.css` or it 404s.
* 2. A PROJECT-ROOT asset — registry blocks are installed into a
* subdirectory but reference `assets/logo.png` at the root. Already
* correct in the root document; rewriting would break it.
*
* A sibling that exists on disk means (1); anything else is left as authored.
* Without a probe the behavior is unchanged — plain relative paths pass through.
*/
export type AssetExists = (projectRelativePath: string) => boolean;
/**
* Rewrite a single relative path from a sub-composition's context to the
* project root context.
*
* @param compSrcPath - The `data-composition-src` value (e.g. "compositions/scene.html")
* @param relativePath - The asset path to rewrite (e.g. "../icon.svg")
* @param assetExists - Optional filesystem probe; see `AssetExists`.
* @returns The rewritten path relative to project root (e.g. "icon.svg"), or
* the original path if no rewriting is needed.
*/
export function rewriteAssetPath(
compSrcPath: string,
relativePath: string,
assetExists?: AssetExists,
): string {
if (isAbsoluteOrSpecial(relativePath)) return relativePath;
const compDir = dirname(compSrcPath);
if (!compDir || compDir === ".") return relativePath;
const { basePath, suffix } = splitUrlSuffix(relativePath);
const slashed = basePath.replace(/\\/g, "/");
if (!slashed || slashed.startsWith("/")) return relativePath;
const filePath = decodeWellFormedEscapes(slashed);
const sibling = resolve("/", join(compDir, filePath)).slice(1);
if (!needsRewrite(filePath) && (!assetExists || !assetExists(sibling))) return relativePath;
return encodeUrlPath(sibling) + suffix;
}
/**
* Rewrite all relative `src` and `href` attributes on elements within a
* DOM tree, adjusting paths from the sub-composition's directory context
* to the project root.
*
* @param elements - Iterable of DOM elements to scan (e.g. from querySelectorAll)
* @param compSrcPath - The `data-composition-src` value
* @param getAttr - Function to read an attribute from an element
* @param setAttr - Function to set an attribute on an element
*/
export function rewriteAssetPaths<T>(
elements: Iterable<T>,
compSrcPath: string,
getAttr: (el: T, attr: string) => string | null | undefined,
setAttr: (el: T, attr: string, value: string) => void,
assetExists?: AssetExists,
): void {
for (const el of elements) {
for (const attr of PATH_ATTRS) {
const val = (getAttr(el, attr) || "").trim();
const rewritten = rewriteAssetPath(compSrcPath, val, assetExists);
if (rewritten !== val) {
setAttr(el, attr, rewritten);
}
}
const srcset = getAttr(el, "srcset");
if (!srcset) continue;
const rewritten = rewriteSrcsetUrls(srcset, (url) =>
rewriteAssetPath(compSrcPath, url, assetExists),
);
if (rewritten !== srcset) setAttr(el, "srcset", rewritten);
}
}
/**
* Rewrite CSS url(...) references inside inline style attributes.
*/
export function rewriteInlineStyleAssetUrls<T>(
elements: Iterable<T>,
compSrcPath: string,
getStyle: (el: T) => string | null | undefined,
setStyle: (el: T, value: string) => void,
assetExists?: AssetExists,
): void {
const compDir = dirname(compSrcPath);
if (!compDir || compDir === ".") return;
for (const el of elements) {
const style = getStyle(el);
if (!style) continue;
const rewritten = rewriteCssAssetUrls(style, compSrcPath, assetExists);
if (rewritten !== style) {
setStyle(el, rewritten);
}
}
}
/**
* Rewrite CSS url(...) references in a sub-composition's inline styles so
* ../foo.woff2 remains valid after the CSS is hoisted into the root document.
*/
export function rewriteCssAssetUrls(
cssText: string,
compSrcPath: string,
assetExists?: AssetExists,
): string {
if (!cssText) return cssText;
return replaceMatches(cssText, cssUrlMatches(cssText), (full, quote, rawUrl) => {
const urlValue = (rawUrl || "").trim();
const rewritten = rewriteAssetPath(compSrcPath, urlValue, assetExists);
if (rewritten === urlValue) return full;
return `url(${quote || ""}${rewritten}${quote || ""})`;
});
}