OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.
TypeScript
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { calculateProjectDuration, ProjectSerializer, type Project } from "@openreel/core";
import { useProjectStore } from "../stores/project-store";
/**
* Saved-project compatibility: project files written by the w4, w5, w6 and w8 trees (generated by
* checking those refs out in a throw-away worktree and saving through their own serializer, see
* fixtures/compat/README.md) must keep loading, keep describing the same timeline and survive a
* re-save without losing or changing anything they had.
*/
const FIXTURES = join(__dirname, "fixtures", "compat");
const WAVES = ["w4", "w5", "w6", "w8"] as const;
const serializer = new ProjectSerializer({} as never);
const read = (wave: string): string => readFileSync(join(FIXTURES, `${wave}.openreel.json`), "utf8");
type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
/** Every path in `original` that is missing or different in `resaved` (extra keys in `resaved` are allowed). */
function lost(original: Json, resaved: Json, path = "$"): string[] {
if (original === null || typeof original !== "object") return Object.is(original, resaved) ? [] : [`${path}: ${JSON.stringify(original)} -> ${JSON.stringify(resaved)}`];
if (resaved === null || typeof resaved !== "object") return [`${path}: object -> ${JSON.stringify(resaved)}`];
if (Array.isArray(original)) {
if (!Array.isArray(resaved) || resaved.length !== original.length) return [`${path}: array length ${original.length} -> ${Array.isArray(resaved) ? resaved.length : "non-array"}`];
return original.flatMap((value, index) => lost(value, resaved[index], `${path}[${index}]`));
}
const record = resaved as { [key: string]: Json };
return Object.entries(original).flatMap(([key, value]) => (key in record ? lost(value, record[key], `${path}.${key}`) : [`${path}.${key}: removed`]));
}
/** Keys present after the re-save that the fixture did not have. */
function added(original: Json, resaved: Json, path = "$"): string[] {
if (original === null || resaved === null || typeof original !== "object" || typeof resaved !== "object") return [];
if (Array.isArray(original) || Array.isArray(resaved)) {
return Array.isArray(original) && Array.isArray(resaved) ? original.flatMap((value, index) => added(value, resaved[index], `${path}[${index}]`)) : [];
}
const before = original as { [key: string]: Json };
return Object.entries(resaved as { [key: string]: Json }).flatMap(([key, value]) => (key in before ? added(before[key], value, `${path}.${key}`) : [`${path}.${key}`]));
}
const clipCount = (project: Project): number => project.timeline.tracks.reduce((sum, track) => sum + track.clips.length, 0);
describe.each(WAVES)("project saved by the %s tree", (wave) => {
const json = read(wave);
const file = JSON.parse(json) as { version: string; project: Json };
it("validates and imports with its timeline, media, text and markers intact", () => {
const validation = serializer.validateProjectJson(json);
expect(validation.valid, JSON.stringify(validation)).toBe(true);
const project = serializer.importFromJson(json);
expect(project.name).toBe(`Compat ${wave}`);
expect(project.settings).toMatchObject({ width: 1280, height: 720, frameRate: 30 });
expect(project.mediaLibrary.items.map((item) => item.id)).toEqual(["media-scenes", "media-tone"]);
expect(project.textClips?.filter((clip) => !clip.metadata?.graphicInstanceId).map((clip) => clip.text)).toEqual(["Compat title"]);
// Since wave 7 nesting moves the markers that fall inside the nested span into the nest.
const markers = wave === "w8" ? project.sequences!.flatMap((sequence) => sequence.timeline.markers) : project.timeline.markers;
expect(markers.map((marker) => marker.label)).toEqual(["Marker A"]);
const main = project.timeline.tracks.find((track) => track.name === "Main")!;
const music = project.timeline.tracks.find((track) => track.name === "Music")!;
expect(music.clips.map((clip) => [clip.startTime, clip.duration])).toEqual([[0, 4]]);
if (wave === "w6" || wave === "w8") {
// The first two clips were nested: the parent holds the nest clip plus the third scene.
expect(main.clips.map((clip) => [clip.startTime, clip.duration]).sort((a, b) => a[0] - b[0])).toEqual([[0, 4], [4, 2]]);
expect(project.sequences?.length).toBeGreaterThanOrEqual(2);
} else {
expect(main.clips.map((clip) => [clip.startTime, clip.duration]).sort((a, b) => a[0] - b[0])).toEqual([[0, 2], [2, 2], [4, 2]]);
expect(main.transitions).toHaveLength(1);
}
expect(calculateProjectDuration(project)).toBeCloseTo(6, 3);
});
it("re-saves without losing or changing anything the file had, and the second re-save is identical", () => {
const resaved = serializer.exportToJson(serializer.importFromJson(json));
const resavedFile = JSON.parse(resaved) as { version: string; project: Json };
expect(resavedFile.version).toBe(file.version);
// The one tolerated "loss": a rack pan of exactly 0 is the default and the normalizer omits it.
expect(lost(file.project, resavedFile.project).filter((path) => !/\.audioRack\.pan: removed$/.test(path))).toEqual([]);
// Files from before multi-sequence gain the single implicit main sequence and nothing else
// structural; media items that have no blob are flagged as placeholders on load.
const extras = added(file.project, resavedFile.project).filter(
(path) => !/\.items\[\d+\]\.isPlaceholder$/.test(path) && path !== "$.generatedShaders" &&
// The rack normalizer fills a slot's missing parameters with their defaults.
!/\.audioRack\.effects\[\d+\]\.params\./.test(path),
);
// w6 files gain nothing, except the derived nest projection now records each nest's own
// design space (compoundClips[].settings, optional since wave 7; same values as the sequence).
if (wave === "w6" || wave === "w8") expect(extras.filter((path) => !/^\$\.compoundClips\[\d+\]\.settings$/.test(path))).toEqual([]);
else expect(extras.every((path) => /^\$\.(sequences|activeSequenceId|openSequenceIds)/.test(path)), extras.join(", ")).toBe(true);
// Stable from here on: another load + save changes nothing.
// (compared structurally: the normalizers may emit keys in a different order the first time).
expect(JSON.parse(serializer.exportToJson(serializer.importFromJson(resaved)))).toEqual(resavedFile);
});
it("opens in the project store and exposes the same clips and active sequence", async () => {
const project = serializer.importFromJson(json);
useProjectStore.getState().loadProject(project);
const loaded = useProjectStore.getState().project;
expect(clipCount(loaded)).toBe(clipCount(project));
expect(loaded.timeline.duration).toBeCloseTo(6, 3);
for (const track of loaded.timeline.tracks) for (const clip of track.clips) expect(clip.trackId).toBe(track.id);
if (wave === "w6" || wave === "w8") expect(loaded.activeSequenceId).toBe(project.activeSequenceId);
// And an edit on the loaded project is one ordinary undo step.
const history = useProjectStore.getState().actionHistory;
const before = history.getUndoStackSize();
const firstClip = loaded.timeline.tracks.find((track) => track.name === "Music")!.clips[0];
await useProjectStore.getState().moveClip(firstClip.id, 1, firstClip.trackId);
expect(history.getUndoStackSize()).toBe(before + 1);
await useProjectStore.getState().undo();
expect(useProjectStore.getState().getClip(firstClip.id)?.startTime).toBe(0);
});
});
describe("Essential Graphics (w8)", () => {
const json = read("w8");
it("the fixture holds one graphic instance with ordinary member clips", () => {
const project = serializer.importFromJson(json);
expect(project.graphicInstances).toHaveLength(1);
const instance = project.graphicInstances![0];
expect(instance).toMatchObject({ startTime: 1, duration: 4 });
expect(instance.values).toMatchObject({ name: "Compat Name", accent: "#22aa66" });
const members = [...(project.textClips ?? []), ...(project.shapeClips ?? [])].filter((clip) => clip.metadata?.graphicInstanceId === instance.id);
expect(members.length).toBeGreaterThan(2);
expect(members.every((clip) => clip.startTime === 1 && clip.duration === 4)).toBe(true);
});
it("opens in the store; a control change is one undo step and undo restores the exact members", async () => {
useProjectStore.getState().loadProject(serializer.importFromJson(json));
const history = useProjectStore.getState().actionHistory;
const instance = useProjectStore.getState().project.graphicInstances![0];
const serial = () => {
const p = useProjectStore.getState().getFullProject();
return JSON.stringify([p.graphicInstances, p.textClips, p.shapeClips, p.svgClips]);
};
const before = serial();
const depth = history.getUndoStackSize();
const { setGraphicValue } = await import("../services/graphic-commands");
const result = await setGraphicValue(instance.id, "name", "Changed");
expect(result.ok).toBe(true);
expect(history.getUndoStackSize()).toBe(depth + 1);
expect(serial()).not.toBe(before);
await useProjectStore.getState().undo();
expect(serial()).toBe(before);
});
it("older waves (w4-w6) load with no graphic instances and nothing added", () => {
for (const wave of ["w4", "w5", "w6"] as const) {
const project = serializer.importFromJson(read(wave));
expect(project.graphicInstances).toBeUndefined();
expect(serializer.exportToJson(project)).not.toContain("graphicInstances");
}
});
});
describe("range markers (comment, duration, kind)", () => {
it("survive export and import, and markers saved before they existed stay exactly as they were", () => {
const old = serializer.importFromJson(read("w5"));
const [oldMarker] = old.timeline.markers;
expect(Object.keys(oldMarker).sort()).toEqual(["color", "id", "label", "time"]);
const range = { id: "range-1", time: 2, label: "Scene", color: "#ef4444", duration: 1.5, comment: "Check audio", kind: "chapter" as const };
const withRange: Project = { ...old, timeline: { ...old.timeline, markers: [...old.timeline.markers, range] } };
const json = serializer.exportToJson(withRange);
expect(serializer.validateProjectJson(json).valid).toBe(true);
const back = serializer.importFromJson(json);
expect(back.timeline.markers).toEqual([oldMarker, range]);
expect(serializer.importFromJson(serializer.exportToJson(back)).timeline.markers).toEqual([oldMarker, range]);
});
});