Skip to content

Commit 4e7fcf7

Browse files
fix(core): resolve sub-composition sibling asset paths everywhere (#2994)
Extends the studio-preview fix to the render path and the asset-discovery utilities, which share the same resolver and had the same defect. `rewriteAssetPath` takes an optional `assetExists` probe. A plain relative ref authored in a sub-composition (`_shared.css`, `clip.mp4`) is re-pointed at the composition's own directory when that sibling exists on disk; project-root refs with no sibling (the registry's `assets/logo.png` convention) stay as authored. Callers that can see the filesystem supply the probe, so the module stays free of node:fs. Also fixes a second defect in the inliner: `<head>` <link> hrefs and external script srcs are hoisted into the root document but never went through the rewrite at all, so even the documented `../` form escaped the project and 404'd at render time. Wired into the preview bundler, the producer compiler, the studio preview builder, the HEVC preview lint, the project lint's asset scans, publish proxy baking, and media-treatment source resolution.
1 parent 91d1474 commit 4e7fcf7

13 files changed

Lines changed: 299 additions & 80 deletions

File tree

‎packages/cli/src/commands/media-treatment.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { existsSync, readFileSync, writeFileSync } from "node:fs";
2-
import { relative, resolve } from "node:path";
2+
import { join, relative, resolve } from "node:path";
33
import {
44
HF_COLOR_GRADING_ATTR,
55
getHfColorGradingCapabilities,
@@ -502,7 +502,7 @@ export function resolveMediaTreatmentSource(
502502
if (!cleanSource) throw new Error("Selected media has no analyzable local src");
503503
const projectRelative = cleanSource.startsWith("/")
504504
? cleanSource
505-
: rewriteAssetPath(compositionFile, cleanSource);
505+
: rewriteAssetPath(compositionFile, cleanSource, (path) => existsSync(join(projectDir, path)));
506506
const asset = resolveExistingLocalAsset(projectDir, projectRelative);
507507
if (!asset) throw new Error(`Media file not found: ${source}`);
508508
return asset.resolved;

‎packages/cli/src/utils/publishProxyBake.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
* structured manifest rather than silently shipping an unplayable asset.
2626
*/
2727

28+
import { existsSync } from "node:fs";
2829
import { readFile } from "node:fs/promises";
2930
import { basename, dirname, resolve } from "node:path";
3031
import { parseHTML } from "linkedom";
@@ -147,7 +148,9 @@ export async function bakeMediaProxies(
147148
// (rewriteAssetPath to root-relative, then decodeUrlPathVariants via
148149
// resolveLocalAssetCandidates) so percent-encoded and root-absolute
149150
// srcs match the map keys the scan produced.
150-
const rootRelativeSrc = rewriteAssetPath(entryPath, cleaned);
151+
const rootRelativeSrc = rewriteAssetPath(entryPath, cleaned, (path) =>
152+
existsSync(resolve(absProjectDir, path)),
153+
);
151154
for (const candidate of resolveLocalAssetCandidates(absProjectDir, rootRelativeSrc)) {
152155
const archivePath = proxyByAbsolutePath.get(candidate);
153156
if (archivePath) return archivePath;

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -898,6 +898,13 @@ export async function bundleToSingleHtml(
898898
parseHtml: parseHTMLContent,
899899
hostIdentityMap: hostIdentityByElement,
900900
rewriteInlineStyles: true,
901+
// A sub-composition's SIBLING assets (`_shared.css` next to it) must be
902+
// re-pointed at its own directory when its content moves to the root
903+
// document; project-root refs with no such sibling stay as authored.
904+
assetExists: (path: string) => {
905+
const resolved = resolveEntryPath(path);
906+
return resolved !== null && existsSync(resolved);
907+
},
901908
flattenInnerRoot: prepareFlattenedInnerRoot,
902909
readVariableDefaults: readDeclaredDefaults,
903910
parseHostVariables: parseHostVariableValues,

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

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,3 +553,71 @@ describe("inlineSubCompositions – recursive host discovery", () => {
553553
]);
554554
});
555555
});
556+
557+
describe("inlineSubCompositions – sub-composition asset paths", () => {
558+
// Every asset ref a sub-composition in a subdirectory carries has to be
559+
// re-pointed when its content moves into the project-root document. Hoisted
560+
// <head> <link>/<script src> used to bypass the rewrite entirely (so even the
561+
// documented `../` form escaped the project), and sibling refs (`_shared.css`)
562+
// silently 404'd. Both render the frame unstyled.
563+
const SUB_COMP = `<!doctype html>
564+
<html><head>
565+
<link rel="stylesheet" href="_shared.css">
566+
<link rel="stylesheet" href="../shared/theme.css">
567+
<script src="helper.js"></script>
568+
<style>.badge { background-image: url("frame.png"); }</style>
569+
</head><body>
570+
<div data-composition-id="frame" data-width="1920" data-height="1080">
571+
<img src="frame.png" alt="">
572+
<div style="background-image: url('frame.png')"></div>
573+
</div>
574+
</body></html>`;
575+
576+
const PROJECT_FILES = [
577+
"design/styleframes/_shared.css",
578+
"design/styleframes/frame.png",
579+
"design/styleframes/helper.js",
580+
"design/shared/theme.css",
581+
];
582+
583+
function inlineFrame() {
584+
const { document } = parseHTML(`<!DOCTYPE html>
585+
<html><body>
586+
<div data-composition-id="main">
587+
<div data-composition-id="frame" data-composition-src="design/styleframes/frame-01.html"
588+
data-start="0" data-duration="4" data-track-index="0"></div>
589+
</div>
590+
</body></html>`);
591+
const host = document.querySelector("[data-composition-src]")!;
592+
const result = inlineSubCompositions(document, [host], {
593+
resolveHtml: () => SUB_COMP,
594+
parseHtml: (html) => parseHTML(html).document,
595+
rewriteInlineStyles: true,
596+
assetExists: (path: string) => PROJECT_FILES.includes(path),
597+
});
598+
return { document, result };
599+
}
600+
601+
it("rewrites hoisted <link> hrefs against the sub-composition dir", () => {
602+
const { result } = inlineFrame();
603+
const hrefs = result.externalLinks.map((l) => l.href);
604+
expect(hrefs).toContain("design/styleframes/_shared.css");
605+
expect(hrefs).toContain("design/shared/theme.css");
606+
expect(hrefs).not.toContain("_shared.css");
607+
expect(hrefs).not.toContain("../shared/theme.css");
608+
});
609+
610+
it("rewrites hoisted external script srcs", () => {
611+
const { result } = inlineFrame();
612+
expect(result.externalScriptSrcs).toContain("design/styleframes/helper.js");
613+
});
614+
615+
it("rewrites sibling refs in markup, hoisted CSS, and inline styles", () => {
616+
const { document, result } = inlineFrame();
617+
expect(document.querySelector("img")?.getAttribute("src")).toBe("design/styleframes/frame.png");
618+
expect(result.styles.join("\n")).toContain("design/styleframes/frame.png");
619+
expect(document.querySelector("[style]")?.getAttribute("style")).toContain(
620+
"design/styleframes/frame.png",
621+
);
622+
});
623+
});

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

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,11 @@
99
*/
1010

1111
import {
12+
rewriteAssetPath,
1213
rewriteAssetPaths,
1314
rewriteCssAssetUrls,
1415
rewriteInlineStyleAssetUrls,
16+
type AssetExists,
1517
} from "./rewriteSubCompPaths";
1618
import { queryByAttr } from "../utils/cssSelector";
1719
import {
@@ -101,6 +103,15 @@ export interface InlineSubCompositionsOptions {
101103
*/
102104
scriptErrorLabel?: string;
103105

106+
/**
107+
* Probe for "does this project-root-relative path exist?". Supplied by
108+
* callers that can see the filesystem so a sub-composition's SIBLING asset
109+
* refs (`<link href="_shared.css">` next to the composition) resolve against
110+
* its own directory instead of 404ing at the project root. Omit it and plain
111+
* relative paths pass through unchanged. See `AssetExists`.
112+
*/
113+
assetExists?: AssetExists;
114+
104115
/**
105116
* Log a warning when a composition file cannot be resolved. `reason` is a
106117
* short, human-readable explanation (e.g. "the file is empty (0 bytes or
@@ -169,6 +180,7 @@ export function inlineSubCompositions(
169180
buildScopeSelector = defaultBuildScopeSelector,
170181
scriptErrorLabel = "[HyperFrames] composition script error:",
171182
onMissingComposition,
183+
assetExists,
172184
} = options;
173185

174186
const styles: string[] = [];
@@ -264,11 +276,17 @@ export function inlineSubCompositions(
264276
}
265277
}
266278

279+
// `<head>` <link>/<script src> are hoisted into the ROOT document, so they
280+
// need the same directory rewrite the body's [src]/[href] pass applies —
281+
// without it even the documented `../` form escapes the project and 404s.
282+
const resolveSubAssetPath = (raw: string | null): string =>
283+
rewriteAssetPath(src, (raw || "").trim(), assetExists);
284+
267285
// Scope one sub-composition <style> body. scopeRootSelectors keeps the
268286
// sub-comp's html/body/:root rules from clobbering the host document (they
269287
// are remapped to the composition box); see compositionScoping.
270288
const scopeSubStyle = (raw: string): string => {
271-
const css = rewriteCssAssetUrls(raw, src);
289+
const css = rewriteCssAssetUrls(raw, src, assetExists);
272290
return scopeCompId
273291
? scopeCssToComposition(css, scopeCompId, runtimeScope || undefined, authoredRootId, {
274292
compoundAuthoredRoot: compoundAuthoredRoot === true,
@@ -286,7 +304,7 @@ export function inlineSubCompositions(
286304
styles.push(scopeSubStyle(s.textContent || ""));
287305
}
288306
for (const s of [...compDoc.head.querySelectorAll("script")]) {
289-
const externalSrc = (s.getAttribute("src") || "").trim();
307+
const externalSrc = resolveSubAssetPath(s.getAttribute("src"));
290308
if (externalSrc) {
291309
if (!externalScriptSrcs.includes(externalSrc)) {
292310
externalScriptSrcs.push(externalSrc);
@@ -297,7 +315,7 @@ export function inlineSubCompositions(
297315
for (const link of [
298316
...compDoc.head.querySelectorAll('link[rel="stylesheet"], link[rel="preconnect"]'),
299317
]) {
300-
const href = (link.getAttribute("href") || "").trim();
318+
const href = resolveSubAssetPath(link.getAttribute("href"));
301319
if (href && !seenLinkHrefs.has(href)) {
302320
seenLinkHrefs.add(href);
303321
const rel = (link.getAttribute("rel") || "").trim();
@@ -317,7 +335,7 @@ export function inlineSubCompositions(
317335

318336
// Extract scripts from content
319337
for (const s of [...contentDoc.querySelectorAll("script")]) {
320-
const externalSrc = (s.getAttribute("src") || "").trim();
338+
const externalSrc = resolveSubAssetPath(s.getAttribute("src"));
321339
if (externalSrc) {
322340
if (!externalScriptSrcs.includes(externalSrc)) {
323341
externalScriptSrcs.push(externalSrc);
@@ -352,6 +370,7 @@ export function inlineSubCompositions(
352370
(el: Element, attr: string, val: string) => {
353371
el.setAttribute(attr, val);
354372
},
373+
assetExists,
355374
);
356375

357376
if (rewriteInlineStyles) {
@@ -365,6 +384,7 @@ export function inlineSubCompositions(
365384
(el: Element, val: string) => {
366385
el.setAttribute("style", val);
367386
},
387+
assetExists,
368388
);
369389
}
370390

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@ export {
44
rewriteAssetPaths,
55
rewriteInlineStyleAssetUrls,
66
rewriteCssAssetUrls,
7+
type AssetExists,
78
} from "@hyperframes/parsers/asset-paths";
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs";
2+
import { tmpdir } from "node:os";
3+
import { join } from "node:path";
4+
import { describe, expect, it } from "vitest";
5+
import { collectLocalVideoCandidates } from "./hevcPreviewLint.js";
6+
7+
function makeProject(files: string[]): string {
8+
const dir = mkdtempSync(join(tmpdir(), "hf-hevc-lint-"));
9+
for (const rel of files) {
10+
const full = join(dir, rel);
11+
mkdirSync(join(full, ".."), { recursive: true });
12+
writeFileSync(full, "video-bytes", "utf-8");
13+
}
14+
return dir;
15+
}
16+
17+
// A sub-composition referencing a SIBLING video (`clip.mp4` next to it) resolves
18+
// against its own directory, exactly as the preview and render paths now do.
19+
// Resolving it against the project root instead either finds nothing (the file
20+
// is silently skipped, so a real HEVC source is never reported) or finds a
21+
// same-named file at the root and probes the WRONG one.
22+
describe("collectLocalVideoCandidates", () => {
23+
it("resolves a sibling video against the sub-composition dir", () => {
24+
const dir = makeProject(["design/styleframes/clip.mp4"]);
25+
26+
const candidates = collectLocalVideoCandidates(dir, [
27+
{ html: `<video src="clip.mp4"></video>`, compSrcPath: "design/styleframes/frame-01.html" },
28+
]);
29+
30+
expect([...candidates.keys()]).toEqual([join(dir, "design/styleframes/clip.mp4")]);
31+
});
32+
33+
it("prefers the sibling over a same-named file at the project root", () => {
34+
const dir = makeProject(["clip.mp4", "design/styleframes/clip.mp4"]);
35+
36+
const candidates = collectLocalVideoCandidates(dir, [
37+
{ html: `<video src="clip.mp4"></video>`, compSrcPath: "design/styleframes/frame-01.html" },
38+
]);
39+
40+
expect([...candidates.keys()]).toEqual([join(dir, "design/styleframes/clip.mp4")]);
41+
});
42+
43+
it("still resolves project-root refs that have no sibling", () => {
44+
const dir = makeProject(["assets/clip.mp4"]);
45+
46+
const candidates = collectLocalVideoCandidates(dir, [
47+
{ html: `<video src="assets/clip.mp4"></video>`, compSrcPath: "blocks/hero.html" },
48+
]);
49+
50+
expect([...candidates.keys()]).toEqual([join(dir, "assets/clip.mp4")]);
51+
});
52+
});

‎packages/lint/src/hevcPreviewLint.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import { execFile } from "node:child_process";
2+
import { existsSync } from "node:fs";
3+
import { join } from "node:path";
24
import { rewriteAssetPath } from "@hyperframes/parsers/asset-paths";
35
import { findFfBinary } from "@hyperframes/parsers/ff-binaries";
46
import {
@@ -92,7 +94,9 @@ export function collectLocalVideoCandidates(
9294
const src = cleanAssetUrl(rawSrc);
9395
if (!src) continue;
9496
if (isRemoteOrInlineUrl(src)) continue;
95-
const rootRelative = compSrcPath ? rewriteAssetPath(compSrcPath, src) : src;
97+
const rootRelative = compSrcPath
98+
? rewriteAssetPath(compSrcPath, src, (path) => existsSync(join(projectDir, path)))
99+
: src;
96100
const resolvedAsset = resolveExistingLocalAsset(projectDir, rootRelative);
97101
if (!resolvedAsset) continue;
98102
if (!candidates.has(resolvedAsset.resolved)) candidates.set(resolvedAsset.resolved, src);

‎packages/lint/src/project.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,10 @@ function resolveCssAssetCandidates(
133133
return resolveLocalAssetCandidates(projectDir, join(dirname(cssRootRelativePath), url));
134134
}
135135
if (htmlCompSrcPath) {
136-
return resolveLocalAssetCandidates(projectDir, rewriteAssetPath(htmlCompSrcPath, url));
136+
return resolveLocalAssetCandidates(
137+
projectDir,
138+
rewriteAssetPath(htmlCompSrcPath, url, (path) => existsSync(join(projectDir, path))),
139+
);
137140
}
138141
return resolveLocalAssetCandidates(projectDir, url);
139142
}
@@ -284,7 +287,9 @@ function lintAudioSrcNotFound(
284287
const src = match[1]!;
285288
if (/^(https?:|data:|blob:)/i.test(src)) continue;
286289
if (isUnresolvedAssetPlaceholder(src)) continue;
287-
const rootRelative = compSrcPath ? rewriteAssetPath(compSrcPath, src) : src;
290+
const rootRelative = compSrcPath
291+
? rewriteAssetPath(compSrcPath, src, (path) => existsSync(join(projectDir, path)))
292+
: src;
288293
if (!resolveLocalAssetCandidates(projectDir, rootRelative).some(existsSync)) {
289294
missingSrcs.push(src);
290295
}
@@ -330,7 +335,9 @@ function lintMissingLocalAsset(
330335
const src = cleanAssetUrl(rawSrc);
331336
if (!src) continue;
332337
if (isRemoteOrInlineUrl(src)) continue;
333-
const rootRelative = compSrcPath ? rewriteAssetPath(compSrcPath, src) : src;
338+
const rootRelative = compSrcPath
339+
? rewriteAssetPath(compSrcPath, src, (path) => existsSync(join(projectDir, path)))
340+
: src;
334341
const resolvedAsset = resolveExistingLocalAsset(projectDir, rootRelative);
335342
if (resolvedAsset) continue;
336343

‎packages/parsers/src/rewriteSubCompPaths.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,46 @@ describe("rewriteAssetPath", () => {
5555

5656
expect(elements[0]?.style).toBe(`background-image: url("cover.png")`);
5757
});
58+
59+
// A sub-composition referencing a SIBLING file (`_shared.css`, no `../`) means
60+
// a file in its own directory, but the inlined/preview document resolves it
61+
// against the project root — so it 404s. `assetExists` lets a caller that can
62+
// see the filesystem opt into browser semantics, while paths with no such
63+
// sibling (the registry's project-root `assets/logo.png` convention) stay put.
64+
describe("with an assetExists probe", () => {
65+
const exists = (p: string) =>
66+
[
67+
"design/styleframes/_shared.css",
68+
"design/styleframes/frame.png",
69+
"assets/logo.png",
70+
].includes(p);
71+
72+
it("resolves a sibling file against the sub-composition dir", () => {
73+
expect(rewriteAssetPath("design/styleframes/frame-01.html", "_shared.css", exists)).toBe(
74+
"design/styleframes/_shared.css",
75+
);
76+
});
77+
78+
it("keeps a query string and hash on the rewritten path", () => {
79+
expect(rewriteAssetPath("design/styleframes/frame-01.html", "frame.png?v=2", exists)).toBe(
80+
"design/styleframes/frame.png?v=2",
81+
);
82+
});
83+
84+
it("leaves project-root-relative paths alone when no sibling exists", () => {
85+
expect(rewriteAssetPath("blocks/hero.html", "assets/logo.png", exists)).toBe(
86+
"assets/logo.png",
87+
);
88+
});
89+
90+
it("still resolves `../` without consulting the probe", () => {
91+
expect(rewriteAssetPath("compositions/scene.html", "../icon.svg", exists)).toBe("icon.svg");
92+
});
93+
94+
it("is a no-op without the probe (unchanged default)", () => {
95+
expect(rewriteAssetPath("design/styleframes/frame-01.html", "_shared.css")).toBe(
96+
"_shared.css",
97+
);
98+
});
99+
});
58100
});

0 commit comments

Comments
 (0)