import { afterEach, describe, expect, it } from "vitest"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { parseHTML } from "linkedom"; import { checkSubCompositionUsability, findPageCompositionRoot, resolveSubCompositionContent, type ParsableDocumentLike, } from "@hyperframes/parsers/sub-composition-validity"; import { createMemoryAdapter, openComposition } from "./index"; import { createFsAdapter } from "./adapters/fs"; const tempDirs: string[] = []; afterEach(() => { for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); const parse = (html: string) => parseHTML(html).document as unknown as ParsableDocumentLike; const LEAF_HTML = `
`; interface PlacementScenario { name: string; targetPath: string; files: Record; mustKeepTemplates?: string[]; } async function openWithMemoryProject(files: Record, targetPath: string) { const persist = createMemoryAdapter(); for (const [p, html] of Object.entries(files)) await persist.write(p, html); return openComposition(files[targetPath]!, { persist, persistPath: targetPath }); } async function assertSinglePermittedDelete( scenario: PlacementScenario, id: string, beforeRootId: string | null, ): Promise { const comp = await openWithMemoryProject(scenario.files, scenario.targetPath); if (!comp.can({ type: "removeElement", target: id }).ok) { comp.dispose(); return; } comp.removeElement(id); const afterHtml = comp.serialize(); comp.dispose(); expect(checkSubCompositionUsability(afterHtml, parse), `${scenario.name} #${id}`).toEqual({ ok: true, }); const afterDoc = parseHTML(afterHtml).document; if (beforeRootId) { expect(findPageCompositionRoot(afterDoc)?.id ?? null, `${scenario.name} root`).toBe( beforeRootId, ); } for (const tplId of scenario.mustKeepTemplates ?? []) { expect(afterDoc.getElementById(tplId), `${scenario.name} ${tplId}`).not.toBeNull(); } } async function assertScenarioPermittedDeletes(scenario: PlacementScenario): Promise { const targetHtml = scenario.files[scenario.targetPath]!; const beforeRootId = findPageCompositionRoot(parseHTML(targetHtml).document)?.id ?? null; const probe = await openWithMemoryProject(scenario.files, scenario.targetPath); const ids = probe.getElements().map((el) => el.id); probe.dispose(); for (const id of ids) await assertSinglePermittedDelete(scenario, id, beforeRootId); } describe("openComposition cross-file delete guard", () => { // fails without the fix: public SDK can/removeElement/flush dropped a scene referenced by another file. it("refuses deleting a locally mounted scene template through FsAdapter in 2-file and 3-file nested projects", async () => { const dir = mkdtempSync(join(tmpdir(), "hf-sdk-cross-file-")); tempDirs.push(dir); mkdirSync(join(dir, "compositions"), { recursive: true }); writeFileSync( join(dir, "index.html"), `
`, ); writeFileSync( join(dir, "compositions", "middle.html"), `
`, ); writeFileSync(join(dir, "compositions", "leaf.html"), LEAF_HTML); const persist = createFsAdapter({ root: dir }); const comp = await openComposition(LEAF_HTML, { persist, persistPath: "compositions/leaf.html", }); const nested = comp.getElements().find((el) => el.attributes.id === "nested"); expect(nested).toBeDefined(); expect(comp.can({ type: "removeElement", target: nested!.id }).ok).toBe(false); comp.removeElement(nested!.id); await comp.flush(); const saved = readFileSync(join(dir, "compositions", "leaf.html"), "utf-8"); expect(saved).toContain('id="child-template"'); expect(resolveSubCompositionContent(saved, parse(saved)).contentHtml).toContain( 'data-composition-id="child"', ); comp.dispose(); }); // fails without the fix: an unrelated file carrying an empty element with the same id blocked a valid delete. it("allows deleting a locally mounted wrapper when only an unrelated file shares the composition id", async () => { const persist = createMemoryAdapter(); await persist.write( "unrelated.html", `
`, ); await persist.write("compositions/leaf.html", LEAF_HTML); const comp = await openComposition(LEAF_HTML, { persist, persistPath: "compositions/leaf.html", }); const nested = comp.getElements().find((el) => el.attributes.id === "nested"); expect(nested).toBeDefined(); expect(comp.can({ type: "removeElement", target: nested!.id }).ok).toBe(true); comp.removeElement(nested!.id); await comp.flush(); const saved = (await persist.read("compositions/leaf.html")) ?? ""; expect(saved).not.toContain('id="nested"'); expect(saved).toContain('data-composition-id="leaf"'); comp.dispose(); }); // fails without the fix: omitting persistPath skipped the graph guard even though flush writes composition.html. it("protects the default composition.html output path when persistPath is omitted", async () => { const persist = createMemoryAdapter(); await persist.write( "index.html", `
`, ); await persist.write("composition.html", LEAF_HTML); const comp = await openComposition(LEAF_HTML, { persist }); const nested = comp.getElements().find((el) => el.attributes.id === "nested"); expect(nested).toBeDefined(); expect(comp.can({ type: "removeElement", target: nested!.id }).ok).toBe(false); comp.removeElement(nested!.id); await comp.flush(); expect((await persist.read("composition.html")) ?? "").toContain('id="child-template"'); comp.dispose(); }); const INDEX_REFERRING_LEAF = `
`; const idOf = (comp: Awaited>, htmlId: string) => comp.getElements().find((el) => el.attributes.id === htmlId)!.id; /** The memory adapter `inner` behind one whose listing `listFiles` answers. */ const listingBy = ( inner: ReturnType, listFiles: () => Promise, ) => ({ read: (path: string) => inner.read(path), write: (path: string, html: string) => inner.write(path, html), flush: () => inner.flush(), listVersions: (path: string) => inner.listVersions(path), loadFrom: (path: string, key: string) => inner.loadFrom(path, key), on: inner.on.bind(inner), listFiles, }); // fails without the fix: a save refused for a referenced root's delete also undid a newer, unrelated delete. it("keeps an unrelated delete made after a referenced root's delete", async () => { const leaf = LEAF_HTML.replace( '
', '
Side
', ); const persist = createMemoryAdapter(); await persist.write("compositions/leaf.html", leaf); const comp = await openComposition(leaf, { persist, persistPath: "compositions/leaf.html" }); await persist.write("index.html", INDEX_REFERRING_LEAF); comp.removeElement(idOf(comp, "nested")); comp.removeElement(idOf(comp, "side")); await comp.flush(); expect(comp.serialize()).not.toContain('id="side"'); expect((await persist.read("compositions/leaf.html")) ?? "").not.toContain('id="side"'); comp.dispose(); }); // fails without the fix: a listing that failed while saving put the saved file back over a newer edit and its undo. it("keeps a newer edit and its undo when the project listing fails while it saves", async () => { const inner = createMemoryAdapter(); await inner.write("compositions/leaf.html", LEAF_HTML); let failing = false; const persist = listingBy(inner, async () => { if (failing) throw new Error("listing failed"); return inner.listFiles!(); }); const comp = await openComposition(LEAF_HTML, { persist, persistPath: "compositions/leaf.html", }); failing = true; comp.removeElement(idOf(comp, "clip")); comp.undo(); comp.setText(idOf(comp, "clip"), "Newer"); await comp.flush(); expect(comp.serialize()).toContain("Newer"); expect((await inner.read("compositions/leaf.html")) ?? "").toContain("Newer"); expect(comp.canUndo()).toBe(true); comp.dispose(); }); // Property check through the outermost SDK door: every can()=ok deletion keeps page root + project refs usable. it("preserves page root and referenced templates for every SDK-permitted deletion across placement table", async () => { const scenarios: Array<{ name: string; targetPath: string; files: Record; mustKeepTemplates?: string[]; }> = [ { name: "plain document root", targetPath: "index.html", files: { "index.html": `
Hi
`, }, }, { name: "template carrying its own composition id", targetPath: "compositions/scene.html", files: { "compositions/scene.html": ``, }, mustKeepTemplates: ["scene-template"], }, { name: "two-file direct reference to locally mounted template", targetPath: "compositions/a.html", files: { "index.html": `
`, "compositions/a.html": LEAF_HTML, }, mustKeepTemplates: ["child-template"], }, { name: "three-file nested project-root reference", targetPath: "compositions/leaf.html", files: { "index.html": `
`, "compositions/middle.html": `
`, "compositions/leaf.html": LEAF_HTML, }, mustKeepTemplates: ["child-template"], }, { name: "shared bundle inline mount across two sub-compositions", targetPath: "compositions/a.html", files: { "index.html": `
`, "compositions/b.html": `
`, "compositions/a.html": `
`, }, mustKeepTemplates: ["a-template", "child-template"], }, ]; for (const scenario of scenarios) await assertScenarioPermittedDeletes(scenario); }); });