fix(studio): the preview opens only the project's compositions (#8725)

* fix(studio): the preview opens only the project's compositions

The sub-composition preview built a page from any project file, and Studio's link opened any file in the tree as the active composition. Both now accept only what the project listing reports as a composition: an .html or .htm file outside dot and vendor folders whose source carries data-composition-id. A link naming anything else opens the root composition. A captured site's saved page no longer carries the composition marker, so it is never listed as one.

* test(cli): a directly opened sub-composition page carries the composition marker
This commit is contained in:
Miguel Ángel
2026-11-25 05:40:44 +00:00
committed by GitHub
parent fb8e7eba92
commit df0297366e
19 changed files with 235 additions and 54 deletions
@@ -1,4 +1,12 @@
import { mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import {
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
@@ -72,7 +80,10 @@ describe("runPostExtraction", () => {
},
);
async function runWithFonts(read: () => unknown): Promise<void> {
async function runWithFonts(
read: () => unknown,
bodyHtml?: string,
): Promise<{ outputDir: string }> {
const root = mkdtempSync(join(tmpdir(), "hyperframes-post-extraction-"));
onTestFinished(() => rmSync(root, { recursive: true, force: true }));
const outputDir = join(root, "capture");
@@ -80,6 +91,7 @@ describe("runPostExtraction", () => {
mkdirSync(join(outputDir, dir), { recursive: true });
}
const state = createPartialCaptureState({ url: "https://example.com", outputDir });
if (bodyHtml !== undefined) state.extracted.bodyHtml = bodyHtml;
fonts.read = read;
await runPostExtraction({
state,
@@ -102,8 +114,23 @@ describe("runPostExtraction", () => {
fontDrops: noDrops(),
canWrite: () => true,
});
return { outputDir };
}
// fails without the fix: a captured site that carries the composition marker was saved with it, so Studio listed
// extracted/page.html as a composition and ran its scripts on its own origin
it("saves the captured page without the composition marker", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
const { outputDir } = await runWithFonts(
() => ({ files: [], families: [], unidentified: [] }),
`<div data-composition-id="x"><script>fetch("/api/projects")</script></div><i DATA-COMPOSITION-ID = 'y'></i>`,
);
const saved = readFileSync(join(outputDir, "extracted", "page.html"), "utf-8");
expect(saved).toContain(`<script>fetch("/api/projects")</script>`);
expect(saved).not.toMatch(/data-composition-id/i);
});
const printed = (spy: { mock: { calls: unknown[][] } }): string =>
spy.mock.calls.map((call) => call.map(String).join(" ")).join("\n");
@@ -87,6 +87,9 @@ export interface PostExtractionResult {
animationCatalog: CaptureResult["animationCatalog"];
}
const withoutCompositionMarker = (capturedHtml: string): string =>
capturedHtml.replace(/data-composition-id/gi, "data-captured-composition-id");
export async function runPostExtraction(input: PostExtractionInput): Promise<PostExtractionResult> {
let {
state,
@@ -289,7 +292,9 @@ export async function runPostExtraction(input: PostExtractionInput): Promise<Pos
// Persist a self-contained page recreation under extracted/, with images already inlined.
try {
const pageHtml = `<!doctype html>\n<html ${extracted.htmlAttrs || ""}>\n<head>\n${extracted.headHtml}\n</head>\n<body>\n${extracted.bodyHtml}\n</body>\n</html>\n`;
const pageHtml = withoutCompositionMarker(
`<!doctype html>\n<html ${extracted.htmlAttrs || ""}>\n<head>\n${extracted.headHtml}\n</head>\n<body>\n${extracted.bodyHtml}\n</body>\n</html>\n`,
);
state.pageHtml = pageHtml;
if (canWrite())
writeCaptureFileSync(join(outputDir, "extracted", "page.html"), pageHtml, "utf-8");
@@ -125,7 +125,10 @@ describe("a project page opened by direct navigation", () => {
it("is answered sandboxed by this server", async () => {
const project = path.join(root, "project");
fs.writeFileSync(path.join(project, "index.html"), '<div data-composition-id="main"></div>');
fs.writeFileSync(path.join(project, "page.html"), "<script>document.title = 1</script>");
fs.writeFileSync(
path.join(project, "page.html"),
'<div data-composition-id="page"></div><script>document.title = 1</script>',
);
const id = encodeURIComponent(path.basename(project));
for (const file of ["page.html", "comp/page.html"]) {
const response = await server.app.request(`/api/projects/${id}/preview/${file}`, {
@@ -7,6 +7,9 @@ import { isInHiddenOrVendorDir, mkdirOwnedWithinProject, walkDir } from "./safeP
export const isCompositionSource = (html: string): boolean => /data-composition-id\s*=/.test(html);
export const isCompositionPath = (relPath: string): boolean =>
/\.html?$/i.test(relPath) && !isInHiddenOrVendorDir(relPath);
const STAMP_RECORD = join(".hyperframes", "hf-ids-stamped.json");
const contentHash = (text: string): string => createHash("sha1").update(text).digest("base64url");
@@ -58,7 +58,8 @@ describe("buildSubCompositionHtml", () => {
'<!doctype html><html><head><meta name="outside-head"></head><body></body></html>',
});
const dir = makeTempProject({
"scenes/scene.html": '<template><div id="scene"></div></template>',
"scenes/scene.html":
'<template><div id="scene" data-composition-id="scene"></div></template>',
});
symlinkSync(join(outside, "index.html"), join(dir, "index.html"));
const html = buildSubCompositionHtml(dir, "scenes/scene.html", "/runtime.js");
@@ -570,7 +571,7 @@ describe("buildSubCompositionHtml", () => {
<link rel="stylesheet" href="_shared.css" />
<style>.stage { background-image: url("frame-01.png"); }</style>
</head>
<body><div class="stage"><img src="frame-01.png" alt="" /></div></body>
<body><div class="stage" data-composition-id="frame-01"><img src="frame-01.png" alt="" /></div></body>
</html>`,
});
@@ -23,6 +23,7 @@ import {
import { TIMELINE_REGISTRY_SCRIPT } from "./authoredCode.js";
import { htmlHasGsapCore, insertGsapCoreBeforeHeadPlugin } from "./gsapCoreScript.js";
import { withRootPathsRelative } from "./rootPaths.js";
import { isCompositionPath, isCompositionSource } from "./hfIdPersist.js";
/**
* Rewrite relative asset paths in a parsed DOM tree. Shared across all
@@ -323,6 +324,7 @@ export function buildSubCompositionHtml(
rawOverride?: string,
gsapBaseUrl?: string,
): string | null {
if (!isCompositionPath(compPath)) return null;
const compFile = resolveWithinProject(projectDir, compPath);
if (!compFile || !existsSync(compFile)) return null;
@@ -330,6 +332,7 @@ export function buildSubCompositionHtml(
// directly, so the build uses ids minted from the raw file, which is never
// written by serving.
const rawComp = rawOverride ?? readFileSync(compFile, "utf-8");
if (!isCompositionSource(rawComp)) return null;
let compHeadContent = "";
let rewrittenContent: string;
@@ -0,0 +1,77 @@
// @vitest-environment node
import { afterAll, describe, expect, it } from "vitest";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createStudioApi } from "../createStudioApi";
import type { StudioApiAdapter } from "../types";
const SCRIPT = `<script>fetch("/api/projects")</script>`;
const projectDir = mkdtempSync(join(tmpdir(), "hf-preview-compositions-only-"));
for (const dir of ["scenes", "extracted", ".hyperframes"]) mkdirSync(join(projectDir, dir));
writeFileSync(join(projectDir, "index.html"), '<div data-composition-id="main"></div>');
writeFileSync(join(projectDir, "scenes", "intro.html"), '<div data-composition-id="intro"></div>');
writeFileSync(join(projectDir, "scenes", "outro.htm"), '<div data-composition-id="outro"></div>');
writeFileSync(join(projectDir, "extracted", "page.html"), `<html><body>${SCRIPT}</body></html>`);
writeFileSync(join(projectDir, "extracted", "visible-text.txt"), SCRIPT);
writeFileSync(join(projectDir, "data.json"), JSON.stringify({ html: SCRIPT }));
writeFileSync(join(projectDir, "subs.vtt"), `WEBVTT\n\n00:00.000 --> 00:01.000\n${SCRIPT}`);
writeFileSync(join(projectDir, "clip.mp4"), `<div data-composition-id="x">${SCRIPT}</div>`);
writeFileSync(
join(projectDir, ".hyperframes", "preset.html"),
`<div data-composition-id="p">${SCRIPT}</div>`,
);
afterAll(() => rmSync(projectDir, { recursive: true, force: true }));
const adapter: StudioApiAdapter = {
listProjects: () => [],
resolveProject: async (id: string) => ({ id, dir: projectDir }),
bundle: async () => null,
lint: async () => ({ findings: [] }),
runtimeUrl: "/api/runtime.js",
rendersDir: () => join(projectDir, "renders"),
startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "/tmp/out.mp4" }),
};
const api = createStudioApi(adapter);
const comp = (path: string, site?: string) =>
api.request(`http://localhost/projects/demo/preview/comp/${path}`, {
headers: site === undefined ? {} : { "sec-fetch-site": site },
});
// fails without the fix: the comp route built a page from any project file, so its scripts ran on Studio's origin
describe("the sub-composition preview", () => {
const notCompositions = [
"extracted/page.html",
"extracted/visible-text.txt",
"data.json",
"subs.vtt",
"clip.mp4",
".hyperframes/preset.html",
];
const sites = [undefined, "same-origin", "none", "cross-site"];
it.each(notCompositions)("answers no page for %s, however the request is made", async (path) => {
for (const site of sites) {
const res = await comp(path, site);
expect(res.status).toBe(404);
expect(res.headers.get("content-type") ?? "").not.toContain("text/html");
expect(await res.text()).not.toContain("fetch(");
}
});
it.each(["scenes/intro.html", "scenes/outro.htm"])("still builds %s", async (path) => {
const res = await comp(path, "same-origin");
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toContain("text/html");
});
it("answers only for what the project listing reports as compositions", async () => {
const listing = await (await api.request("http://localhost/projects/demo")).json();
expect([...listing.compositions].sort()).toEqual([
"index.html",
"scenes/intro.html",
"scenes/outro.htm",
]);
});
});
@@ -160,16 +160,12 @@ describe("an opaque preview frame's loads under its token", () => {
["video", "music.mp3"],
["video", "logo.png"],
["audio", "clip.mp4"],
["audio", "comp/music.mp3"],
["font", "data.json"],
["font", "scene.js"],
["script", "data.json"],
["script", "fonts/Brand.woff2"],
["script", "scene.html"],
["script", "comp/scene.html"],
// The sub-composition route answers any project file with an HTML page.
["script", "comp/scene.js"],
["font", "comp/fonts/Brand.woff2"],
["toString", "scene.js"],
["constructor", "fonts/Brand.woff2"],
])("refuses a %s load of %s", async (dest, path) => {
@@ -178,6 +174,17 @@ describe("an opaque preview frame's loads under its token", () => {
expectNotGranted(res);
});
// The sub-composition route answers only for compositions, so these never reach a page or a grant.
it.each([
["audio", "comp/music.mp3"],
["script", "comp/scene.js"],
["font", "comp/fonts/Brand.woff2"],
])("refuses a %s load of %s with no page", async (dest, path) => {
const res = await load(path, { origin: "null", "sec-fetch-dest": dest });
expect(res.status).toBe(404);
expectNotGranted(res);
});
it("refuses a load that names no Sec-Fetch-Dest", async () => {
expectNotGranted(await load("fonts/Brand.woff2", { origin: "null" }));
});
@@ -11,14 +11,17 @@ writeFileSync(
join(projectDir, "index.html"),
'<div data-composition-id="main" data-width="320" data-height="180"></div>',
);
writeFileSync(join(projectDir, "page.html"), "<script>document.title = 'ran'</script>");
writeFileSync(
join(projectDir, "page.html"),
`<div data-composition-id="page"></div><script>document.title = 'ran'</script>`,
);
writeFileSync(
join(projectDir, "icon.svg"),
'<svg xmlns="http://www.w3.org/2000/svg"><script>void 0</script></svg>',
);
writeFileSync(
join(projectDir, "clip.html"),
'<video id="local" src="clip.mp4"></video><video id="remote" src="https://cdn.example/a.mp4"></video>',
'<div data-composition-id="clip"><video id="local" src="clip.mp4"></video><video id="remote" src="https://cdn.example/a.mp4"></video></div>',
);
afterAll(() => rmSync(projectDir, { recursive: true, force: true }));
@@ -36,11 +36,15 @@ describe("a project file asked for as a service worker's script", () => {
for (const headers of workerFetches) expect((await get(path, headers)).status).toBe(403);
});
it.each(paths)("still loads at %s as a page script, module or dedicated worker", async (path) => {
for (const dest of ["script", "worker", "empty"]) {
const res = await get(path, { "sec-fetch-dest": dest });
expect(res.status).toBe(200);
expect(await res.text()).toContain("onfetch");
}
});
// Only the asset route: the sub-composition route builds pages from compositions, and answers nothing for a script.
it.each(paths.slice(0, 1))(
"still loads at %s as a page script, module or dedicated worker",
async (path) => {
for (const dest of ["script", "worker", "empty"]) {
const res = await get(path, { "sec-fetch-dest": dest });
expect(res.status).toBe(200);
expect(await res.text()).toContain("onfetch");
}
},
);
});
@@ -227,7 +227,10 @@ describe("registerPreviewRoutes", () => {
it("encodes the project name in <base>, so a '#' or '\"' in it keeps assets in its own folder", async () => {
const projectDir = createProjectDir();
writeFileSync(join(projectDir, "scene.html"), "<template><section></section></template>");
writeFileSync(
join(projectDir, "scene.html"),
'<template><section data-composition-id="scene"></section></template>',
);
const app = new Hono();
registerPreviewRoutes(app, createAdapter(projectDir));
const baseOf = async (path: string) =>
@@ -495,7 +498,7 @@ describe("registerPreviewRoutes", () => {
it("serves a later scene's image lazy, and captures every image eager under a capture-mode mark", async () => {
const projectDir = createProjectDir();
const later =
'<!DOCTYPE html><html><head></head><body><div data-start="5"><img src="b.png"></div></body></html>';
'<!DOCTYPE html><html><head></head><body><div data-composition-id="scene" data-start="5"><img src="b.png"></div></body></html>';
writeFileSync(join(projectDir, "index.html"), later);
writeFileSync(join(projectDir, "scene.html"), later);
const app = new Hono();
@@ -1374,7 +1377,7 @@ describe("hf-id surfacing in preview route", () => {
);
writeFileSync(
files[1]!,
`<div class="clip" data-start="0" data-end="3"><img src="logo.png"></div>`,
`<div class="clip" data-composition-id="scene" data-start="0" data-end="3"><img src="logo.png"></div>`,
);
const snapshot = () => files.map((f) => [readFileSync(f, "utf-8"), statSync(f).mtimeMs]);
const before = snapshot();
@@ -1393,7 +1396,7 @@ describe("hf-id surfacing in preview route", () => {
const compPath = join(projectDir, "scene.html");
writeFileSync(
compPath,
`<div class="clip" data-start="0" data-end="3"><img src="assets/logo.png"></div>`,
`<div class="clip" data-composition-id="scene" data-start="0" data-end="3"><img src="assets/logo.png"></div>`,
);
const app = new Hono();
const adapter = createAdapter(projectDir);
@@ -1476,8 +1479,14 @@ describe("hf-id surfacing in preview route", () => {
it("returns ByteString-safe stable and distinct ETags for percent-encoded CJK sub-comp paths", async () => {
const projectDir = createProjectDir();
mkdirSync(join(projectDir, "compositions"));
writeFileSync(join(projectDir, "compositions/測試.html"), "<div>First</div>");
writeFileSync(join(projectDir, "compositions/別頁.html"), "<div>Second</div>");
writeFileSync(
join(projectDir, "compositions/測試.html"),
'<div data-composition-id="first">First</div>',
);
writeFileSync(
join(projectDir, "compositions/別頁.html"),
'<div data-composition-id="second">Second</div>',
);
const app = new Hono();
registerPreviewRoutes(
app,
@@ -1505,7 +1514,7 @@ describe("hf-id surfacing in preview route", () => {
it("sub-comp served ids equal the source's ids even when relative asset paths are rewritten", async () => {
// Guards setTiming element_not_found: minting after the route rewrites src gives ids the source lacks.
const projectDir = createProjectDir();
const raw = `<div class="clip" data-start="0" data-end="3"><img src="assets/logo.png"></div>`;
const raw = `<div class="clip" data-composition-id="scene" data-start="0" data-end="3"><img src="assets/logo.png"></div>`;
writeFileSync(join(projectDir, "scene.html"), raw);
const app = new Hono();
registerPreviewRoutes(app, createAdapter(projectDir));
@@ -1688,7 +1697,7 @@ describe("preview ?variables= injection", () => {
const projectDir = createProjectDir();
writeFileSync(
join(projectDir, "scene.html"),
"<!doctype html><html><head></head><body><div class='clip' data-start='0' data-duration='2'>Scene</div></body></html>",
"<!doctype html><html><head></head><body><div class='clip' data-composition-id='scene' data-start='0' data-duration='2'>Scene</div></body></html>",
);
const app = new Hono();
registerPreviewRoutes(app, createAdapter(projectDir));
@@ -1710,7 +1719,7 @@ describe("sub-composition preview attribute integrity", () => {
]);
writeFileSync(
join(projectDir, "card.html"),
`<!doctype html><html data-composition-variables='${decls}'><head></head><body><div class="clip" data-start="0" data-duration="2">x</div></body></html>`,
`<!doctype html><html data-composition-variables='${decls}'><head></head><body><div class="clip" data-composition-id="scene" data-start="0" data-duration="2">x</div></body></html>`,
);
const app = new Hono();
registerPreviewRoutes(app, createAdapter(projectDir));
@@ -3354,7 +3363,7 @@ describe("GSAP mirror configuration", () => {
async (mode) => {
const projectDir = createProjectDir();
const authored = "https://authored.example/gsap@3.14.2/dist/gsap.min.js";
const source = `<html><head><meta name="${metaName}" content="https://authored.example/npm"><script src="${authored}"></script></head><body><script>gsap.to("#card", { motionPath: {} });</script></body></html>`;
const source = `<html><head><meta name="${metaName}" content="https://authored.example/npm"><script src="${authored}"></script></head><body><div data-composition-id="main"></div><script>gsap.to("#card", { motionPath: {} });</script></body></html>`;
writeFileSync(join(projectDir, "index.html"), source);
writeFileSync(join(projectDir, "scene.html"), source);
const app = appForMirror(projectDir, mirror, {
@@ -3398,7 +3407,10 @@ describe("GSAP mirror configuration", () => {
],
}),
);
writeFileSync(join(projectDir, "scene.html"), "<template><section>Scene</section></template>");
writeFileSync(
join(projectDir, "scene.html"),
'<template><section data-composition-id="scene">Scene</section></template>',
);
const app = appForMirror(projectDir, mirror);
const root = parseHTML(await (await app.request(previewUrl)).text()).document;
const urls = [...root.querySelectorAll("script[src]")].map((script) =>
@@ -3420,7 +3432,7 @@ describe("GSAP mirror configuration", () => {
"revalidates %s when the mirror setting changes",
async (suffix) => {
const projectDir = createProjectDir();
const source = `<html><head><script src="vendor/gsap.min.js"></script></head><body><script>gsap.to("#card", { motionPath: {} });</script></body></html>`;
const source = `<html><head><script src="vendor/gsap.min.js"></script></head><body><div data-composition-id="main"></div><script>gsap.to("#card", { motionPath: {} });</script></body></html>`;
writeFileSync(join(projectDir, "index.html"), source);
writeFileSync(join(projectDir, "scene.html"), source);
const url = previewUrl + suffix;
@@ -3443,7 +3455,7 @@ describe("GSAP mirror configuration", () => {
const plugin = "https://authored.example/MotionPathPlugin.min.js";
writeFileSync(
join(projectDir, "index.html"),
`<html><head><script src="${plugin}"></script></head><body><script>gsap.to("#card", { motionPath: {} });</script></body></html>`,
`<html><head><script src="${plugin}"></script></head><body><div data-composition-id="main"></div><script>gsap.to("#card", { motionPath: {} });</script></body></html>`,
);
const configured = await (await appForMirror(projectDir, mirror).request(previewUrl)).text();
expect(
@@ -3471,7 +3483,10 @@ describe("GSAP mirror configuration", () => {
it("invalidates root, subcomposition, and persistent preview caches when the mirror changes", async () => {
const projectDir = createProjectDir();
writeFileSync(join(projectDir, "scene.html"), "<template><section>Scene</section></template>");
writeFileSync(
join(projectDir, "scene.html"),
'<template><section data-composition-id="scene">Scene</section></template>',
);
const bundle = vi.fn(
async () =>
'<html><head></head><body><div data-hf-scene="a">Cached preview</div></body></html>',
@@ -3580,7 +3595,10 @@ describe("bundled GSAP local root", () => {
],
}),
);
writeFileSync(join(projectDir, "scene.html"), "<template><section>Scene</section></template>");
writeFileSync(
join(projectDir, "scene.html"),
'<template><section data-composition-id="scene">Scene</section></template>',
);
}
it("loads every GSAP dependency Studio adds from the host's bundled copy", async () => {
@@ -3604,7 +3622,7 @@ describe("bundled GSAP local root", () => {
writeFileSync(
join(projectDir, "index.html"),
`<html><head><script src="vendor/gsap.min.js"></script></head><body><script>gsap.to("#card", { motionPath: {} });</script></body></html>`,
`<html><head><script src="vendor/gsap.min.js"></script></head><body><div data-composition-id="main"></div><script>gsap.to("#card", { motionPath: {} });</script></body></html>`,
);
const withPath = await (await app.request(previewUrl)).text();
expect(
@@ -3620,7 +3638,7 @@ describe("bundled GSAP local root", () => {
const projectDir = createProjectDir();
writeFileSync(
join(projectDir, "index.html"),
`<html><head><script src="vendor/gsap@3.14.2/dist/gsap.min.js"></script></head><body><script>gsap.to("#card", { motionPath: {} });</script></body></html>`,
`<html><head><script src="vendor/gsap@3.14.2/dist/gsap.min.js"></script></head><body><div data-composition-id="main"></div><script>gsap.to("#card", { motionPath: {} });</script></body></html>`,
);
const html = await (await appForHost(projectDir).request(previewUrl)).text();
expect(
@@ -68,6 +68,7 @@ import { getMimeType } from "../helpers/mime.js";
import { serveWhileOpen } from "../helpers/servedFiles.js";
import { openRangeEnd } from "../helpers/mediaRange.js";
import { hasBaseElement } from "../helpers/subComposition.js";
import { isCompositionPath } from "../helpers/hfIdPersist.js";
import {
runOffThread,
ROOT_PREVIEW_DEADLINE_MS,
@@ -886,6 +887,7 @@ export function registerPreviewRoutes(
return c.text("not found", 404);
}
const compPath = projectRelativePath(project.dir, compFile);
if (!isCompositionPath(compPath)) return c.text("not found", 404);
// "v2" salts the etag for the hf-id-pinning change below: a client holding
// a pre-pin cached response (preview-only ids, unstamped disk file) must
@@ -32,7 +32,10 @@ function projectWithComposition(): { dir: string; cleanup: () => void } {
const dir = mkdtempSync(join(tmpdir(), "hf-projectid-"));
writeFileSync(join(dir, "index.html"), "<html><body>COMPOSITION</body></html>");
mkdirSync(join(dir, "scenes"), { recursive: true });
writeFileSync(join(dir, "scenes", "scene-1.html"), "<html><body>SCENE ONE</body></html>");
writeFileSync(
join(dir, "scenes", "scene-1.html"),
'<html><body><div data-composition-id="scene-1">SCENE ONE</div></body></html>',
);
return { dir, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
}
@@ -2,12 +2,12 @@ import { readFile } from "node:fs/promises";
import { join } from "node:path";
import type { Hono } from "hono";
import type { StudioApiAdapter } from "../types.js";
import { isInHiddenOrVendorDir, isPrivateProjectPath, walkDir } from "../helpers/safePath.js";
import { isCompositionSource } from "../helpers/hfIdPersist.js";
import { isPrivateProjectPath, walkDir } from "../helpers/safePath.js";
import { isCompositionPath, isCompositionSource } from "../helpers/hfIdPersist.js";
import { resolveProjectSignature } from "../helpers/projectSignature.js";
async function filterCompositionFiles(projectDir: string, files: string[]): Promise<string[]> {
const htmlFiles = files.filter((f) => f.endsWith(".html") && !isInHiddenOrVendorDir(f));
const htmlFiles = files.filter(isCompositionPath);
const checks = await Promise.all(
htmlFiles.map(async (f) => {
try {
+1 -1
View File
@@ -123,7 +123,7 @@ export function StudioApp({ readOnlyPreview = false, readOnlyPreviewReason }: St
useActiveComposition({
projectId,
initialUrlStateRef,
fileTree: fileManager.fileTree,
compositions: fileManager.compositions,
fileTreeLoaded: fileManager.fileTreeLoaded,
masterCompPath,
setEditingFile: fileManager.setEditingFile,
@@ -10,7 +10,7 @@ import type { AppToast, EditingFile } from "../utils/studioHelpers";
export function useActiveComposition({
projectId,
initialUrlStateRef,
fileTree,
compositions,
fileTreeLoaded,
masterCompPath,
setEditingFile,
@@ -18,7 +18,7 @@ export function useActiveComposition({
}: {
projectId: string | null;
initialUrlStateRef: MutableRefObject<StudioUrlState>;
fileTree: string[];
compositions: string[];
fileTreeLoaded: boolean;
masterCompPath: string | null;
setEditingFile: (file: EditingFile) => void;
@@ -44,7 +44,7 @@ export function useActiveComposition({
useHydrateActiveCompPathFromUrl({
hydrated: activeCompPathHydrated,
fileTreeLoaded,
fileTree,
compositions,
initialUrlStateRef,
setActiveCompPath,
setHydrated: setActiveCompPathHydrated,
@@ -4,21 +4,21 @@ import { normalizeStudioCompositionPath, type StudioUrlState } from "../utils/st
/**
* One-time hydration of `activeCompPath` from the initial URL state, once the
* file tree has loaded (a path that isn't in the tree yet can't be
* validated). Runs exactly once — `hydrated` flips true whether or not the
* file tree has loaded (a path that isn't in the server's compositions yet can't
* be validated). Runs exactly once — `hydrated` flips true whether or not the
* URL named a valid path, so a later file-tree change never re-fires it.
*/
export function useHydrateActiveCompPathFromUrl({
hydrated,
fileTreeLoaded,
fileTree,
compositions,
initialUrlStateRef,
setActiveCompPath,
setHydrated,
}: {
hydrated: boolean;
fileTreeLoaded: boolean;
fileTree: string[];
compositions: string[];
initialUrlStateRef: MutableRefObject<StudioUrlState>;
setActiveCompPath: (updater: (current: string | null) => string | null) => void;
setHydrated: (value: boolean) => void;
@@ -28,9 +28,9 @@ export function useHydrateActiveCompPathFromUrl({
if (!fileTreeLoaded) return;
const nextCompPath = normalizeStudioCompositionPath(
initialUrlStateRef.current.activeCompPath,
fileTree,
compositions,
);
setActiveCompPath((current) => (current === nextCompPath ? current : nextCompPath));
setHydrated(true);
}, [hydrated, fileTree, fileTreeLoaded, initialUrlStateRef, setActiveCompPath, setHydrated]);
}, [hydrated, compositions, fileTreeLoaded, initialUrlStateRef, setActiveCompPath, setHydrated]);
}
@@ -170,7 +170,7 @@ describe("full stack: useFileTree -> useActiveComposition (masterCompPath stalen
const initialUrlStateRef = useRef(readStudioUrlStateFromWindow());
const projectIdRef = useRef(projectId);
projectIdRef.current = projectId;
const { fileTree, fileTreeLoaded, compositions } = useFileTree({ projectId, projectIdRef });
const { fileTreeLoaded, compositions } = useFileTree({ projectId, projectIdRef });
const masterCompPath = useMemo(
() => resolveMasterCompositionPath(compositions),
[compositions],
@@ -178,7 +178,7 @@ describe("full stack: useFileTree -> useActiveComposition (masterCompPath stalen
const { activeCompPath } = useActiveComposition({
projectId,
initialUrlStateRef,
fileTree,
compositions,
fileTreeLoaded,
masterCompPath,
setEditingFile: vi.fn(),
@@ -231,4 +231,29 @@ describe("full stack: useFileTree -> useActiveComposition (masterCompPath stalen
fetchSpy.mockRestore();
});
// fails without the fix: a link from any site picked which project file the same-origin player frame loads
it.each([
["extracted/page.html", "index.html"],
["scenes/intro.html", "scenes/intro.html"],
])("opens the URL's comp %s as %s", async (comp, opened) => {
PROJECT_DATA["project-d"] = {
files: ["index.html", "extracted/page.html", "scenes/intro.html"],
compositions: ["index.html", "scenes/intro.html"],
};
window.location.hash = `#project/project-d?comp=${encodeURIComponent(comp)}`;
const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(mockFetch as typeof fetch);
const host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
await act(async () => {
root?.render(<FullStackHarness projectId="project-d" />);
await Promise.resolve();
await Promise.resolve();
});
expect((host.firstElementChild as HTMLElement).dataset.activeCompPath).toBe(opened);
fetchSpy.mockRestore();
});
});
+2 -2
View File
@@ -66,10 +66,10 @@ export function normalizeStudioUrlPanelTab(tab: RightPanelTab | null): RightPane
export function normalizeStudioCompositionPath(
activeCompPath: string | null,
fileTree: string[],
compositions: string[],
): string | null {
if (!activeCompPath || activeCompPath === "index.html") return null;
return fileTree.includes(activeCompPath) ? activeCompPath : null;
return compositions.includes(activeCompPath) ? activeCompPath : null;
}
function parseBoolean(value: string | null): boolean | null {