Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(cli): add timeline editing verbs (#4221)
Miguel Ángelf92d017b999d
diff --git a/docs/developers/cli.mdx b/docs/developers/cli.mdxindex 79c694d01f..0943795da8 100644--- a/docs/developers/cli.mdx+++ b/docs/developers/cli.mdx@@ -39,6 +39,8 @@ remains authoritative: run `npx hyperframes <command> --help`.| Inspect keyframe behavior | `npx hyperframes keyframes` || Compare two or more versions | `npx hyperframes compare v1/ v2/` |+`hyperframes timeline` also accepts agent editing verbs. Use `move`, `trim`, `split`, or `delete` with a row ref; add `--plan` to inspect the before/after rows and diff without writing, or `--json` for a machine-readable receipt. Time values accept seconds, relative offsets, frames, and anchors such as `after:#intro`.+## Rendering and automationThe CLI also renders in batches and from variables, writes image sequences anddiff --git a/packages/cli/src/commands/timeline.ts b/packages/cli/src/commands/timeline.tsindex f025a08496..6ec6448e01 100644--- a/packages/cli/src/commands/timeline.ts+++ b/packages/cli/src/commands/timeline.ts@@ -1,26 +1,630 @@+import {+ applyFileMutations,+ fileContentVersion,+ patchElementInHtml,+ removeElementFromHtml,+ splitElementInHtml,+} from "@hyperframes/studio-server";+import type { AppliedFileMutation } from "@hyperframes/studio-server";+import { fpsToNumber, parseFpsWithDefault } from "@hyperframes/core";+import { readCompositionFps } from "../utils/compositionFps.js";+import { readFileSync } from "node:fs";+import { join } from "node:path";import { defineCommand } from "citty";import type { Example } from "./_examples.js";-import { describeProject } from "../timeline/describeProject.js";+import {+ describeProject,+ type ProjectTimeline,+ type TimelineRow,+} from "../timeline/describeProject.js";import { formatTimeline } from "../timeline/formatTimeline.js";+import { resolveRef } from "../timeline/resolveRef.js";+import { parseTimeExpression } from "../timeline/timeExpr.js";import { ensureDOMParser } from "../utils/dom.js";+import { setCommandExitCode } from "../utils/commandResult.js";import { resolveProject } from "../utils/project.js";import { withMeta } from "../utils/updateCheck.js";export const examples: Example[] = [["Show every track and clip of the project in the current directory", "hyperframes timeline"],- ["Same, as JSON for an agent", "hyperframes timeline ./my-video --json"],+ ["Move a clip without writing", "hyperframes timeline move '#hero' +2 --plan"],+ ["Delete a clip and return a receipt", "hyperframes timeline delete '#hero' --json"],];+type MutationVerb = "move" | "trim" | "split" | "delete";++type MutationDecision =+ | { ok: true; after: string; nextStart: number; nextDuration: number }+ | { ok: false; reason: string; fix: string };++interface MutationContext {+ ref: string;+ row: TimelineRow;+ before: string;+ resolved: Extract<ReturnType<typeof resolveRef>, { ok: true }>;+ parseTime: (expression: string) => ReturnType<typeof parseTimeExpression>;+ duration: number;+}++type ParsedMutationTime =+ | { ok: true; seconds: number }+ | { ok: false; reason: string; fix: string };++const allRows = (timeline: ProjectTimeline): TimelineRow[] =>+ timeline.tracks.flatMap((track) => track.rows);++function refusal(reason: string, fix: string, json: boolean): void {+ setCommandExitCode(2);+ const payload = { ok: false, reason, fix };+ console.error(json ? JSON.stringify(payload, null, 2) : `${reason}; ${fix}.`);+}++function fpsFor(indexPath: string): number {+ const parsed = parseFpsWithDefault(+ readCompositionFps(readFileSync(indexPath, "utf-8")) ?? undefined,+ );+ return fpsToNumber(parsed.ok ? parsed.value : { num: 30, den: 1 });+}++function declaredFps(source: string): number | null {+ const raw = readCompositionFps(source);+ if (raw === null) return null;+ const parsed = parseFpsWithDefault(raw);+ return parsed.ok ? fpsToNumber(parsed.value) : null;+}++function splitBaseId(row: TimelineRow): string {+ return row.ref.startsWith("hf:") ? row.ref.slice(3) : row.id;+}++function nextFreeSplitId(source: string, base: string): string {+ const document = new DOMParser().parseFromString(source, "text/html");+ const existing = new Set(Array.from(document.querySelectorAll("[id]"), (element) => element.id));+ const match = /^(.*)-(\d+)$/.exec(base);+ const prefix = match && existing.has(match[1]!) ? match[1]! : base;+ let suffix = 2;+ while (existing.has(`${prefix}-${suffix}`)) suffix += 1;+ return `${prefix}-${suffix}`;+}++function parseMutationTime(+ context: MutationContext,+ expression: string,+ fix: string,+): ParsedMutationTime {+ const value = context.parseTime(expression);+ if (!value.ok) return { ok: false, reason: value.reason, fix };+ if (value.seconds < 0 || value.seconds > context.duration) {+ return {+ ok: false,+ reason: `time ${value.seconds} is outside the composition duration`,+ fix: "pass a time between 0 and the composition duration",+ };+ }+ return { ok: true, seconds: value.seconds };+}++function diff(before: string, after: string): string {+ if (before === after) return "";+ const beforeLines = before.split("\n");+ const afterLines = after.split("\n");+ let prefix = 0;+ while (+ prefix < beforeLines.length &&+ prefix < afterLines.length &&+ beforeLines[prefix] === afterLines[prefix]+ ) {+ prefix += 1;+ }+ let suffix = 0;+ while (+ suffix < beforeLines.length - prefix &&+ suffix < afterLines.length - prefix &&+ beforeLines[beforeLines.length - suffix - 1] === afterLines[afterLines.length - suffix - 1]+ ) {+ suffix += 1;+ }+ const changedBefore = beforeLines.slice(prefix, beforeLines.length - suffix);+ const changedAfter = afterLines.slice(prefix, afterLines.length - suffix);+ const lines = [+ "--- before",+ "+++ after",+ ...changedBefore.map((line) => `-${line}`),+ ...changedAfter.map((line) => `+${line}`),+ ];+ const output = lines.join("\n");+ return output.length <= 8_000 ? output : `${output.slice(0, 7_997)}...`;+}++function overlap(+ row: TimelineRow,+ timeline: ProjectTimeline,+ start: number,+ end: number,+): TimelineRow | undefined {+ return allRows(timeline).find(+ (candidate) =>+ candidate !== row &&+ candidate.file === row.file &&+ candidate.trackIndex === row.trackIndex &&+ Math.max(start, candidate.start) < Math.min(end, candidate.end),+ );+}++function moveMutation(context: MutationContext, args: Record<string, unknown>): MutationDecision {+ const expression = typeof args.time === "string" ? args.time : "";+ const time = parseMutationTime(context, expression, "pass a valid time expression");+ if (!time.ok) return time;+ const end = time.seconds + context.row.duration;+ if (end > context.duration) {+ return {+ ok: false,+ reason: `move would end at ${end}, beyond composition duration ${context.duration}`,+ fix: `choose a start at or before the latest valid start ${context.duration - context.row.duration}`,+ };+ }+ const patched = patchElementInHtml(context.before, context.resolved.target, [+ { type: "html-attribute", property: "data-start", value: String(time.seconds) },+ ]);+ if (!patched.matched) {+ return { ok: false, reason: `${context.ref} was not found`, fix: "choose an existing clip" };+ }+ return {+ ok: true,+ after: patched.html,+ nextStart: time.seconds,+ nextDuration: context.row.duration,+ };+}++function splitMutation(context: MutationContext, args: Record<string, unknown>): MutationDecision {+ const expression = typeof args.time === "string" ? args.time : "";+ const time = parseMutationTime(context, expression, "pass a valid time expression");+ if (!time.ok) return time;+ const split = splitElementInHtml(+ context.before,+ context.resolved.target,+ time.seconds,+ nextFreeSplitId(context.before, splitBaseId(context.row)),+ {+ start: context.row.start,+ duration: context.row.duration,+ track: context.row.trackIndex,+ },+ );+ if (!split.matched || !split.newId) {+ return {+ ok: false,+ reason: `${context.ref} cannot be split at ${time.seconds}`,+ fix: "choose a time inside the clip",+ };+ }+ return {+ ok: true,+ after: split.html,+ nextStart: context.row.start,+ nextDuration: context.row.duration,+ };+}++function trimMutation(context: MutationContext, args: Record<string, unknown>): MutationDecision {+ const bounds = trimBounds(context, args);+ if (!bounds.ok) return bounds;+ const patched = patchElementInHtml(context.before, context.resolved.target, [+ { type: "html-attribute", property: "data-start", value: String(bounds.nextStart) },+ { type: "html-attribute", property: "data-duration", value: String(bounds.nextDuration) },+ ]);+ if (!patched.matched) {+ return { ok: false, reason: `${context.ref} was not found`, fix: "choose an existing clip" };+ }+ return {+ ok: true,+ after: patched.html,+ nextStart: bounds.nextStart,+ nextDuration: bounds.nextDuration,+ };+}++function trimBounds(+ context: MutationContext,+ args: Record<string, unknown>,+): MutationDecision | { ok: true; nextStart: number; nextDuration: number } {+ const input = trimInput(args);+ if (!input.ok) return input;+ const start = trimStart(context, input.start);+ if (!start.ok) return start;+ return finishTrim(+ context,+ start.seconds,+ trimEnd(context, input.end),+ trimDuration(context, input.duration),+ );+}++function trimInput(args: Record<string, unknown>) {+ const input = {+ start: typeof args.start === "string" ? args.start : undefined,+ end: typeof args.end === "string" ? args.end : undefined,+ duration: typeof args.duration === "string" ? args.duration : undefined,+ };+ if (input.start || input.end || input.duration) return { ok: true as const, ...input };+ return {+ ok: false as const,+ reason: "trim requires --start, --end, or --duration",+ fix: "pass one trim option",+ };+}++function finishTrim(+ context: MutationContext,+ nextStart: number,+ end: ReturnType<typeof trimEnd>,+ duration: ReturnType<typeof trimDuration>,+): MutationDecision | { ok: true; nextStart: number; nextDuration: number } {+ if (end && !end.ok) return end;+ if (duration && !duration.ok) return duration;+ const nextDuration = duration?.seconds ?? (end ? end.seconds - nextStart : context.row.duration);+ if (nextDuration <= 0) {+ return {+ ok: false,+ reason: "trim duration must be positive",+ fix: "choose a later end or positive duration",+ };+ }+ return { ok: true, nextStart, nextDuration };+}++function trimStart(context: MutationContext, expression: string | undefined) {+ if (!expression) return { ok: true as const, seconds: context.row.start };+ return parseMutationTime(context, expression, "pass a valid time expression");+}++function trimEnd(context: MutationContext, expression: string | undefined) {+ if (!expression) return undefined;+ return parseMutationTime(context, expression, "pass a valid time expression");+}++function trimDuration(context: MutationContext, expression: string | undefined) {+ if (!expression) return undefined;+ return parseMutationTime(context, expression, "pass a valid duration");+}++function deleteMutation(context: MutationContext): MutationDecision {+ return {+ ok: true,+ after: removeElementFromHtml(context.before, context.resolved.target),+ nextStart: context.row.start,+ nextDuration: context.row.duration,+ };+}++function decideMutation(+ verb: MutationVerb,+ context: MutationContext,+ args: Record<string, unknown>,+): MutationDecision {+ switch (verb) {+ case "move":+ return moveMutation(context, args);+ case "trim":+ return trimMutation(context, args);+ case "split":+ return splitMutation(context, args);+ case "delete":+ return deleteMutation(context);+ }+}++async function runMutation(verb: MutationVerb, args: Record<string, unknown>): Promise<void> {+ const setup = await prepareMutation(args);+ if (!setup.ok) return refusal(setup.reason, setup.fix, setup.json);+ const decision = decideMutation(verb, setup.context, args);+ if (!decision.ok) return refusal(decision.reason, decision.fix, setup.json);+ await finishMutation(setup, verb, decision);+}++interface MutationSetup {+ ok: true;+ project: ReturnType<typeof resolveProject>;+ ref: string;+ json: boolean;+ plan: boolean;+ overwrite: boolean;+ timeline: ProjectTimeline;+ indexSource: string;+ row: TimelineRow;+ resolved: Extract<ReturnType<typeof resolveRef>, { ok: true }>;+ filePath: string;+ before: string;+ expectedVersion: string;+ context: MutationContext;+}++type MutationSetupResult =+ | MutationSetup+ | { ok: false; reason: string; fix: string; json: boolean };++async function prepareMutation(args: Record<string, unknown>): Promise<MutationSetupResult> {+ const project = resolveProject(typeof args.dir === "string" ? args.dir : undefined);+ const ref = typeof args.ref === "string" ? args.ref : "";+ const json = args.json === true;+ const plan = args.plan === true;+ const overwrite = args.overwrite === true;+ const snap = args.snap === true;+ ensureDOMParser();+ const indexSource = readFileSync(project.indexPath, "utf-8");+ const initialTimeline = await describeProject(+ project.indexPath,+ undefined,+ new Map([["index.html", indexSource]]),+ );+ const projectFps = declaredFps(indexSource);+ if (snap && projectFps === null) {+ return {+ ok: false,+ reason: "project fps is unknown",+ fix: "set data-fps on the project, then rerun with --snap",+ json,+ };+ }+ const initialResolved = resolveRef(initialTimeline, ref);+ if (!initialResolved.ok)+ return { ok: false, reason: initialResolved.reason, fix: initialResolved.fix, json };+ const initialRow = initialResolved.row;+ const filePath = join(project.dir, initialRow.file);+ const before = readFileSync(filePath, "utf-8");+ const expectedVersion = fileContentVersion(before);+ const sources = new Map([+ ["index.html", indexSource],+ [initialRow.file, before],+ ]);+ const timeline = await describeProject(project.indexPath, undefined, sources);+ const resolved = resolveRef(timeline, ref);+ if (!resolved.ok) return { ok: false, reason: resolved.reason, fix: resolved.fix, json };+ const row = resolved.row;+ const anchor = (anchorRef: string) => {+ const found = resolveRef(timeline, anchorRef);+ return found.ok ? found.row : undefined;+ };+ const parseTime = (expression: string) => {+ const parsed = parseTimeExpression(expression, {+ row,+ duration: timeline.duration,+ fps: fpsFor(project.indexPath),+ resolveAnchor: anchor,+ });+ if (!parsed.ok || !snap) return parsed;+ return { ok: true as const, seconds: Math.round(parsed.seconds * projectFps!) / projectFps! };+ };+ return {+ ok: true,+ project,+ ref,+ json,+ plan,+ overwrite,+ timeline,+ indexSource,+ row,+ resolved,+ filePath,+ before,+ expectedVersion,+ context: {+ ref,+ row,+ before,+ resolved,+ parseTime,+ // Nested rows use the visible host clip duration as their composition bound.+ duration:+ row.nested && row.hostRow ? rowAt(timeline, row.hostRow).duration : timeline.duration,+ },+ };+}++async function finishMutation(+ setup: MutationSetup,+ verb: MutationVerb,+ decision: Extract<MutationDecision, { ok: true }>,+): Promise<void> {+ const { after, nextStart, nextDuration } = decision;+ const { ref, row, timeline, json, overwrite, project, before } = setup;+ const refusalMessage = mutationRefusal(verb, after, before, ref);+ if (refusalMessage) return refusal(refusalMessage.reason, refusalMessage.fix, json);+ const conflict = mutationConflict(verb, overwrite, row, timeline, nextStart, nextDuration);+ if (conflict) return refusal(conflict.reason, conflict.fix, json);+ const describeSource = (source: string): Promise<ProjectTimeline> =>+ describeProject(+ project.indexPath,+ undefined,+ new Map([+ ["index.html", setup.indexSource],+ [row.file, source],+ ]),+ );+ const describedBefore = await describeSource(before);+ const result = mutationResult(row, describedBefore, setup.plan);+ if (setup.plan) return printPlan(result, json, timeline, describeSource, after, before);+ return applyAndPrint({+ setup,+ verb,+ json,+ row,+ nextStart,+ nextDuration,+ after,+ before,+ result,+ describeSource,+ });+}++async function applyAndPrint(args: {+ setup: MutationSetup;+ verb: MutationVerb;+ json: boolean;+ row: TimelineRow;+ nextStart: number;+ nextDuration: number;+ after: string;+ before: string;+ result: ReturnType<typeof mutationResult>;+ describeSource: (source: string) => Promise<ProjectTimeline>;+}): Promise<void> {+ const receipt = applyMutation(args.setup, args.after);+ if (receipt && "error" in receipt)+ return refusal(receipt.error, "re-run hyperframes timeline", args.json);+ if (!receipt && args.after !== args.before) {+ return refusal("mutation produced no receipt", "re-run hyperframes timeline", args.json);+ }+ args.result.after = rowsForFile(await args.describeSource(args.after), args.row.file);+ args.result.receipt = receipt+ ? {+ file: receipt.sourceFile,+ version: receipt.version,+ writeToken: receipt.writeToken,+ changed: receipt.changed,+ backupPath: receipt.backupPath,+ }+ : null;+ if (args.json) {+ console.log(JSON.stringify(withMeta(args.result), null, 2));+ return;+ }+ console.log(+ `${args.verb} ${args.row.ref}: ${args.row.start}-${args.row.end}s -> ${args.nextStart}-${args.nextStart + args.nextDuration}s\nreceipt: ${receipt?.version ?? "unchanged"}`,+ );+}++function rowsForFile(timeline: ProjectTimeline, file: string): TimelineRow[] {+ return allRows(timeline).filter((candidate) => candidate.file === file);+}++function rowAt(+ timeline: ProjectTimeline,+ pointer: { kind: TimelineRow["trackKind"]; index: number },+): TimelineRow {+ const track = timeline.tracks.find((candidate) => candidate.kind === pointer.kind);+ if (!track) throw new Error(`missing track ${pointer.kind}`);+ const row = track.rows[pointer.index];+ if (!row) throw new Error(`missing row ${pointer.kind}/${pointer.index}`);+ return row;+}++function mutationResult(row: TimelineRow, before: ProjectTimeline, planned: boolean) {+ return {+ ok: true,+ receipt: null as unknown,+ file: row.file,+ before: rowsForFile(before, row.file),+ after: [] as TimelineRow[],+ warnings: row.warnings,+ planned,+ };+}++async function printPlan(+ result: ReturnType<typeof mutationResult>,+ json: boolean,+ timeline: ProjectTimeline,+ describeSource: (source: string) => Promise<ProjectTimeline>,+ after: string,+ before: string,+): Promise<void> {+ const plannedTimeline = await describeSource(after);+ result.after = rowsForFile(plannedTimeline, result.file);+ if (json) console.log(JSON.stringify(withMeta(result), null, 2));+ else+ console.log(+ `${formatTimeline(timeline)}\n\nplanned:\n${formatTimeline(plannedTimeline)}\n\ndiff:\n${diff(before, after)}`,+ );+}++function applyMutation(+ setup: MutationSetup,+ after: string,+): AppliedFileMutation | { error: string } | undefined {+ try {+ return applyFileMutations(setup.project.dir, [+ {+ sourceFile: setup.row.file,+ absPath: setup.filePath,+ before: setup.before,+ after,+ expectedVersion: setup.expectedVersion,+ },+ ])[0];+ } catch (error) {+ if (error instanceof Error && error.message === "file changed since the timeline was read") {+ return { error: error.message };+ }+ throw error;+ }+}++function mutationRefusal(+ verb: MutationVerb,+ after: string,+ before: string,+ ref: string,+): { reason: string; fix: string } | null {+ if (verb !== "delete" || after !== before) return null;+ return { reason: `${ref} was not found`, fix: "choose an existing clip" };+}++function mutationConflict(+ verb: MutationVerb,+ overwrite: boolean,+ row: TimelineRow,+ timeline: ProjectTimeline,+ nextStart: number,+ nextDuration: number,+): { reason: string; fix: string } | null {+ if ((verb !== "move" && verb !== "trim") || overwrite) return null;+ const conflict = overlap(row, timeline, nextStart, nextStart + nextDuration);+ if (!conflict) return null;+ return {+ reason: `${row.ref} would overlap ${conflict.ref} at ${nextStart}-${nextStart + nextDuration}`,+ fix: "pass --overwrite or move the named neighbour",+ };+}++function mutationCommand(verb: MutationVerb) {+ return defineCommand({+ meta: { name: verb, description: `${verb} a timeline clip` },+ args: {+ ref: { type: "positional", required: true },+ time: { type: "positional", required: verb === "move" || verb === "split" },+ dir: { type: "string" },+ start: { type: "string" },+ end: { type: "string" },+ duration: { type: "string" },+ plan: { type: "boolean", default: false },+ json: { type: "boolean", default: false },+ overwrite: { type: "boolean", default: false },+ snap: { type: "boolean", default: false },+ },+ async run({ args }) {+ await runMutation(verb, args);+ },+ });+}+export default defineCommand({- meta: {- name: "timeline",- description: "Print the project's tracks and clips (start, duration, source, volume, rate)",- },+ meta: { name: "timeline", description: "Print and edit the project's tracks and clips" },args: {dir: { type: "positional", description: "Project directory", required: false },json: { type: "boolean", description: "Output as JSON", default: false },},+ subCommands: {+ move: () => mutationCommand("move"),+ trim: () => mutationCommand("trim"),+ split: () => mutationCommand("split"),+ delete: () => mutationCommand("delete"),+ },async run({ args }) {+ if (args._?.[0]) return;const project = resolveProject(args.dir);ensureDOMParser();const timeline = await describeProject(project.indexPath);diff --git a/packages/cli/src/timeline/describeProject.ts b/packages/cli/src/timeline/describeProject.tsindex 1adb58d454..988138f027 100644--- a/packages/cli/src/timeline/describeProject.ts+++ b/packages/cli/src/timeline/describeProject.ts@@ -34,6 +34,8 @@ import {export type DurationSource = MediaDurationSource | "inner";export interface TimelineRow extends ClipFact {+ ref: string;+ warnings: string[];trackKind: TrackKind;/** False when the source does not author a duration (media length is only known at render). */durationAuthored: boolean;@@ -67,6 +69,8 @@ export interface RowPointer {/** A row before flattening: children are still row objects and refs are not assigned. */type ClipDraft = Omit<TimelineRow, "index" | "nested" | "host" | "hostRow" | "children"> & {+ elementId: string | null;+ hfId: string | null;children: ClipDraft[];};@@ -132,6 +136,7 @@ interface DocScope {/** Bounds concurrent ffprobe spawns for the whole run. Shared reference, not new per document. */withProbeSlot: <T>(fn: () => Promise<T>) => Promise<T>;measure: MeasureMedia;+ sourceOverrides: ReadonlyMap<string, string>;}/** Source length in seconds of a media file. ffprobe in production; tests pass a recorded fake. */@@ -253,29 +258,43 @@ function mainTimelineStart(scope: DocScope, el: Element, start: number): number});}-async function describeRow(scope: DocScope, node: DomNode, depth: number): Promise<ClipDraft> {+interface RowTiming {+ start: number;+ authored: number | null;+ absStart: number;+ children: ClipDraft[];+ duration: DurationResolution;+}++async function resolveRowTiming(scope: DocScope, node: DomNode, depth: number): Promise<RowTiming> {const { el } = node;- const { doc, startCache } = scope;- const start = resolveReferencedStart(doc, el, startCache, new Set());- const authored = resolveReferencedDuration(doc, el, startCache, new Set());+ const start = resolveReferencedStart(scope.doc, el, scope.startCache, new Set());+ const authored = resolveReferencedDuration(scope.doc, el, scope.startCache, new Set());const host = el.getAttribute("data-composition-src");const absStart = mainTimelineStart(scope, el, start);const children = host && depth === 0 ? await readSubComposition(host, scope, absStart) : [];const kind = el.tagName.toLowerCase();- const { duration, durationSource, pendingReason } = MEDIA_TAG.test(kind)+ const duration = MEDIA_TAG.test(kind)? await resolveMediaRowDuration(scope, el, kind as MediaTag, authored): resolveContainerDuration(authored, children);+ return { start, authored, absStart, children, duration };+}++function describeRowFields(scope: DocScope, node: DomNode, timing: RowTiming): ClipDraft {+ const { el } = node;+ const kind = el.tagName.toLowerCase();+ const host = el.getAttribute("data-composition-src");const rate = parseNumeric(el.getAttribute("data-playback-rate"));return {id: el.id || el.getAttribute("data-composition-id") || kind,label: null,kind,trackKind: trackKindOf(node).kind,- start,- duration,- end: start + duration,- absStart: roundMs(absStart),- absEnd: roundMs(absStart + duration),+ start: timing.start,+ duration: timing.duration.duration,+ end: timing.start + timing.duration.duration,+ absStart: roundMs(timing.absStart),+ absEnd: roundMs(timing.absStart + timing.duration.duration),file: scope.file,trackIndex: parseNumeric(el.getAttribute("data-track-index")) ?? 0,src: el.getAttribute("src") ?? host,@@ -285,13 +304,21 @@ async function describeRow(scope: DocScope, node: DomNode, depth: number): PromiplaybackRate: rate === 1 ? null : rate,audioGroup: el.getAttribute(HF_AUDIO_GROUP_ATTR),role: null,- durationAuthored: authored !== null,- durationSource,- pendingReason,- children,+ durationAuthored: timing.authored !== null,+ durationSource: timing.duration.durationSource,+ pendingReason: timing.duration.pendingReason,+ children: timing.children,+ ref: "",+ warnings: [],+ elementId: el.id || null,+ hfId: el.getAttribute("data-hf-id"),};}+async function describeRow(scope: DocScope, node: DomNode, depth: number): Promise<ClipDraft> {+ return describeRowFields(scope, node, await resolveRowTiming(scope, node, depth));+}+async function readSubComposition(src: string,parent: DocScope,@@ -300,7 +327,9 @@ async function readSubComposition(const authored = resolve(parent.dir, src);const file = realFileInside(parent.projectDir, authored);if (!file) return [];- const doc = new DOMParser().parseFromString(readFileSync(file, "utf-8"), "text/html");+ const relativeFile = relative(parent.projectDir, authored).split(sep).join("/");+ const source = parent.sourceOverrides.get(relativeFile) ?? readFileSync(file, "utf-8");+ const doc = new DOMParser().parseFromString(source, "text/html");const template = doc.querySelector("template");const root = (template?.content ?? doc).querySelector("[data-composition-id]");if (!root) return [];@@ -313,6 +342,7 @@ async function readSubComposition(file: relative(parent.projectDir, authored).split(sep).join("/"),withProbeSlot: parent.withProbeSlot,measure: parent.measure,+ sourceOverrides: parent.sourceOverrides,};const rows = await Promise.all(topLevelElements(toNode(root)).map((node) => describeRow(scope, node, 1)),@@ -348,16 +378,41 @@ function flatten(top: ClipDraft[]): TimelineTrack[] {byKind.flatMap((t) => t.entries.map((e, index) => [e.clip, { kind: t.kind, index }] as const)),);const at = (clip: ClipDraft) => pointers.get(clip)!;+ const fileIds = new Map<string, Map<string, number>>();+ for (const { entries } of byKind) {+ for (const { clip } of entries) {+ if (!clip.elementId) continue;+ const ids = fileIds.get(clip.file) ?? new Map<string, number>();+ ids.set(clip.elementId, (ids.get(clip.elementId) ?? 0) + 1);+ fileIds.set(clip.file, ids);+ }+ }return byKind.map(({ kind, entries: kindEntries }) => ({kind,- rows: kindEntries.map(({ clip, host }, index) => ({- ...clip,- index,- nested: host !== null,- host: host && host.id,- hostRow: host && at(host),- children: clip.children.map(at),- })),+ rows: kindEntries.map(({ clip, host }, index) => {+ const uniqueId = clip.elementId && fileIds.get(clip.file)?.get(clip.elementId) === 1;+ const ref = uniqueId+ ? `#${clip.elementId}`+ : clip.hfId+ ? `hf:${clip.hfId}`+ : `${kind}/${index}`;+ const warnings =+ uniqueId || clip.hfId+ ? []+ : [+ 'row has no stable name; add id="<name>" to the element in this file, then retry with #<name>',+ ];+ return {+ ...clip,+ index,+ ref,+ warnings,+ nested: host !== null,+ host: host && host.id,+ hostRow: host && at(host),+ children: clip.children.map(at),+ };+ }),}));}@@ -365,10 +420,13 @@ function flatten(top: ClipDraft[]): TimelineTrack[] {export async function describeProject(indexPath: string,measure: MeasureMedia = measureWithFfprobe,+ sourceOverrides: ReadonlyMap<string, string> = new Map(),): Promise<ProjectTimeline> {- const doc = new DOMParser().parseFromString(readFileSync(indexPath, "utf-8"), "text/html");+ const projectDir = dirname(indexPath);+ const source = sourceOverrides.get(basename(indexPath)) ?? readFileSync(indexPath, "utf-8");+ const doc = new DOMParser().parseFromString(source, "text/html");const root = doc.querySelector("[data-composition-id]") ?? doc.body;- const dir = dirname(indexPath);+ const dir = projectDir;const scope: DocScope = {doc,dir,@@ -378,6 +436,7 @@ export async function describeProject(file: basename(indexPath),withProbeSlot: createProbeGate(PROBE_CONCURRENCY),measure,+ sourceOverrides,};const rows = (await Promise.all(topLevelElements(toNode(root)).map((node) => describeRow(scope, node, 0)))diff --git a/packages/cli/src/timeline/formatTimeline.ts b/packages/cli/src/timeline/formatTimeline.tsindex 1444f76e5a..c412feb6fd 100644--- a/packages/cli/src/timeline/formatTimeline.ts+++ b/packages/cli/src/timeline/formatTimeline.ts@@ -53,7 +53,7 @@ function line(row: TimelineRow, total: number): string {const times = row.host? `${span(row.absStart, row.absEnd)} (local ${span(row.start, row.end)}) nested in ${row.host} ${row.file}`: span(row.start, row.end);- return ` |${bar(row, total)}| ${row.id} ${times} ${details(row)}`.trimEnd();+ return ` |${bar(row, total)}| ${row.ref} ${row.id} ${times} ${details(row)}`.trimEnd();}function header({ kind, rows }: TimelineTrack): string {diff --git a/packages/cli/src/timeline/resolveRef.ts b/packages/cli/src/timeline/resolveRef.tsnew file mode 100644index 0000000000..f8e5a802b2--- /dev/null+++ b/packages/cli/src/timeline/resolveRef.ts@@ -0,0 +1,46 @@+import type { SourceMutationTarget } from "@hyperframes/studio-server";+import type { ProjectTimeline, TimelineRow } from "./describeProject.js";++export type RefResolution =+ | { ok: true; row: TimelineRow; target: SourceMutationTarget }+ | { ok: false; reason: string; fix: string };++function targetFor(row: TimelineRow): SourceMutationTarget | null {+ if (row.ref.startsWith("#")) return { id: row.ref.slice(1) };+ if (row.ref.startsWith("hf:")) return { hfId: row.ref.slice(3) };+ return row.id && row.id !== row.kind ? { id: row.id } : null;+}++export function resolveRef(timeline: ProjectTimeline, ref: string): RefResolution {+ const rows = timeline.tracks.flatMap((track) => track.rows);+ const matches = ref.startsWith("#")+ ? rows.filter((row) => row.ref === ref || row.id === ref.slice(1))+ : ref.startsWith("hf:")+ ? rows.filter((row) => row.ref === ref)+ : (() => {+ const match = /^(video|graphics|captions|audio)\/(\d+)$/.exec(ref);+ if (!match) return [];+ const row = timeline.tracks+ .find((track) => track.kind === match[1])+ ?.rows.find((candidate) => candidate.index === Number(match[2]));+ return row ? [row] : [];+ })();+ if (matches.length !== 1) {+ return {+ ok: false,+ reason:+ matches.length === 0 ? `${ref} was not found` : `${ref} matches ${matches.length} rows`,+ fix: 'add id="<name>" to the element in its source file, then retry with #<name>',+ };+ }+ const row = matches[0]!;+ const target = targetFor(row);+ if (!target) {+ return {+ ok: false,+ reason: `${ref} has no stable element id in ${row.file}`,+ fix: `add id="<name>" to the element in ${row.file}, then retry with #<name>`,+ };+ }+ return { ok: true, row, target };+}diff --git a/packages/cli/src/timeline/timeExpr.test.ts b/packages/cli/src/timeline/timeExpr.test.tsnew file mode 100644index 0000000000..99c51e634e--- /dev/null+++ b/packages/cli/src/timeline/timeExpr.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from "vitest";+import { parseTimeExpression } from "./timeExpr.js";+import type { TimelineRow } from "./describeProject.js";++const row: TimelineRow = {+ ref: "#clip",+ warnings: [],+ id: "clip",+ label: null,+ kind: "video",+ trackKind: "video",+ start: 4,+ duration: 2,+ end: 6,+ absStart: 4,+ absEnd: 6,+ file: "index.html",+ index: 0,+ nested: false,+ host: null,+ hostRow: null,+ children: [],+ trackIndex: 0,+ src: null,+ sourceFile: null,+ volume: null,+ lanes: [],+ playbackRate: null,+ audioGroup: null,+ role: null,+ durationAuthored: true,+ durationSource: "authored",+ pendingReason: null,+ laneError: null,+};++describe("parseTimeExpression", () => {+ it.each([+ ["12.5", 12.5],+ ["+2", 6],+ ["-0.5", 3.5],+ ["30f", 1],+ ["after:#other", 9],+ ["before:#other", 7],+ ["start-of:#other", 7],+ ["end-of:#other", 9],+ ["end", 20],+ ])("parses %s", (expression, seconds) => {+ const result = parseTimeExpression(expression, {+ row,+ duration: 20,+ fps: 30,+ resolveAnchor: (ref) => (ref === "#other" ? { ...row, start: 7, end: 9 } : undefined),+ });+ expect(result).toEqual({ ok: true, seconds });+ });+});diff --git a/packages/cli/src/timeline/timeExpr.ts b/packages/cli/src/timeline/timeExpr.tsnew file mode 100644index 0000000000..e0233c83a4--- /dev/null+++ b/packages/cli/src/timeline/timeExpr.ts@@ -0,0 +1,37 @@+import type { TimelineRow } from "./describeProject.js";++export interface TimeExpressionContext {+ row: TimelineRow;+ duration: number;+ fps: number;+ resolveAnchor: (ref: string) => TimelineRow | undefined;+}++export type TimeExpression = { ok: true; seconds: number } | { ok: false; reason: string };++export function parseTimeExpression(+ expression: string,+ context: TimeExpressionContext,+): TimeExpression {+ const raw = expression.trim();+ if (raw === "end") return { ok: true, seconds: context.duration };+ const frames = /^(-?\d+(?:\.\d+)?)f$/.exec(raw);+ if (frames) return { ok: true, seconds: Number(frames[1]) / context.fps };+ const absolute = /^\d+(?:\.\d+)?$/.test(raw);+ const relative = /^[+-]\d+(?:\.\d+)?$/.test(raw);+ if (absolute) return { ok: true, seconds: Number(raw) };+ if (relative) return { ok: true, seconds: context.row.start + Number(raw) };+ const anchor = /^(after|before|start-of|end-of):(.+)$/.exec(raw);+ if (!anchor) return { ok: false, reason: `invalid time expression: ${expression}` };+ const row = context.resolveAnchor(anchor[2]!);+ if (!row) return { ok: false, reason: `anchor ref not found: ${anchor[2]}` };+ switch (anchor[1]) {+ case "after":+ case "end-of":+ return { ok: true, seconds: row.end };+ case "before":+ case "start-of":+ return { ok: true, seconds: row.start };+ }+ return { ok: false, reason: `invalid time anchor: ${anchor[1]}` };+}diff --git a/packages/cli/src/timeline/timeline.e2e.test.ts b/packages/cli/src/timeline/timeline.e2e.test.tsnew file mode 100644index 0000000000..e64ca7e071--- /dev/null+++ b/packages/cli/src/timeline/timeline.e2e.test.ts@@ -0,0 +1,216 @@+import { spawnSync } from "node:child_process";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";++const cliEntry = resolve(fileURLToPath(import.meta.url), "..", "..", "cli.ts");++function project(): string {+ const dir = mkdtempSync(join(tmpdir(), "hf-timeline-cli-"));+ writeFileSync(+ join(dir, "index.html"),+ `<div data-composition-id="main" data-duration="12"><div id="clip" data-hf-id="clip" data-start="1" data-duration="2" data-track-index="0"></div><div id="neighbour" data-hf-id="neighbour" data-start="5" data-duration="2" data-track-index="0"></div></div>`,+ );+ return dir;+}++function run(dir: string, ...args: string[]) {+ return spawnSync(+ "bun",+ ["run", cliEntry, "timeline", args[0]!, "--dir", dir, "--json", ...args.slice(1)],+ {+ cwd: dir,+ encoding: "utf8",+ timeout: 30_000,+ env: { ...process.env, HYPERFRAMES_SKIP_UPDATE_CHECK: "1" },+ },+ );+}++describe("timeline edit command", () => {+ it.each([+ ["move", ["#clip", "+1"], 'data-start="2"'],+ ["trim", ["#clip", "--duration", "1"], 'data-duration="1"'],+ ["split", ["#clip", "2"], 'id="clip-2"'],+ ["delete", ["#clip"], 'id="clip"'],+ ])("executes %s against a temp project", (verb, args, marker) => {+ const dir = project();+ try {+ const result = run(dir, verb, ...args);+ expect(result.status, result.stderr).toBe(0);+ const output = JSON.parse(result.stdout) as {+ before: Array<{ ref: string }>;+ after: Array<{ ref: string; start: number; duration: number }>;+ };+ expect(output).toMatchObject({+ ok: true,+ receipt: expect.any(Object),+ });+ expect(output.before.some((row) => row.ref === "#clip")).toBe(true);+ const clipAfter = output.after.find((row) => row.ref === "#clip");+ if (verb === "move") expect(clipAfter).toMatchObject({ start: 2 });+ if (verb === "trim") expect(clipAfter).toMatchObject({ duration: 1 });+ if (verb === "split") expect(output.after).toHaveLength(3);+ if (verb === "delete") expect(clipAfter).toBeUndefined();+ const html = readFileSync(join(dir, "index.html"), "utf8");+ if (verb === "delete") expect(html).not.toContain('id="clip"');+ else expect(html).toContain(marker);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("names an id-less hf ref split from its stable id", () => {+ const dir = project();+ try {+ const indexPath = join(dir, "index.html");+ writeFileSync(indexPath, readFileSync(indexPath, "utf8").replace('id="clip"', ""));+ const result = run(dir, "split", "hf:clip", "2");+ expect(result.status, result.stderr).toBe(0);+ expect(readFileSync(indexPath, "utf8")).toContain('id="clip-2"');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("uses the next free numeric split suffix on repeat", () => {+ const dir = project();+ try {+ const first = run(dir, "split", "#clip", "1.5");+ expect(first.status, first.stderr).toBe(0);+ const second = run(dir, "split", "#clip-2", "2.5");+ expect(second.status, second.stderr).toBe(0);+ const html = readFileSync(join(dir, "index.html"), "utf8");+ expect(html).toContain('id="clip-2"');+ expect(html).toContain('id="clip-3"');+ expect(html).not.toContain('id="clip-2-2"');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("refuses overlap", () => {+ const dir = project();+ try {+ const result = run(dir, "move", "#clip", "4");+ expect(result.status).toBe(2);+ expect(result.stderr).toContain("--overwrite");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("refuses an ambiguous reference", () => {+ const dir = project();+ try {+ writeFileSync(+ join(dir, "index.html"),+ `<div data-composition-id="main"><div id="dup" data-start="1" data-duration="2" data-track-index="0"></div><div id="dup" data-start="5" data-duration="2" data-track-index="0"></div></div>`,+ );+ const result = run(dir, "delete", "#dup");+ expect(result.status).toBe(2);+ expect(result.stderr).toContain("matches 2 rows");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("refuses snap when the project fps is unknown", () => {+ const dir = project();+ try {+ const result = run(dir, "move", "#clip", "1.03", "--snap");+ expect(result.status).toBe(2);+ expect(result.stderr).toContain("set data-fps");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("refuses a move whose clip would end beyond the composition", () => {+ const dir = mkdtempSync(join(tmpdir(), "hf-timeline-move-bound-"));+ try {+ const indexPath = join(dir, "index.html");+ writeFileSync(+ indexPath,+ `<div data-composition-id="main" data-duration="53"><div id="clip" data-start="1" data-duration="10" data-track-index="0"></div></div>`,+ );+ const result = run(dir, "move", "#clip", "50");+ expect(result.status).toBe(2);+ expect(result.stderr).toContain("end at 60");+ expect(result.stderr).toContain("latest valid start 43");+ expect(readFileSync(indexPath, "utf8")).toContain('data-start="1"');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("snaps a known project fps to one frame", () => {+ const dir = project();+ try {+ const indexPath = join(dir, "index.html");+ writeFileSync(+ indexPath,+ readFileSync(indexPath, "utf8").replace(+ 'data-composition-id="main"',+ 'data-composition-id="main" data-fps="10"',+ ),+ );+ const result = run(dir, "move", "#clip", "1.06", "--snap");+ expect(result.status, result.stderr).toBe(0);+ const output = JSON.parse(result.stdout) as {+ after: Array<{ ref: string; start: number }>;+ };+ expect(output.after.find((row) => row.ref === "#clip")).toMatchObject({+ start: 1.1,+ });+ expect(readFileSync(join(dir, "index.html"), "utf8")).toContain('data-start="1.1"');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("uses the nested composition duration for time bounds", () => {+ const dir = mkdtempSync(join(tmpdir(), "hf-timeline-nested-"));+ try {+ writeFileSync(+ join(dir, "index.html"),+ `<div data-composition-id="main" data-duration="60"><div id="host" data-composition-src="sub.html" data-start="10" data-duration="3" data-track-index="0"></div></div>`,+ );+ writeFileSync(+ join(dir, "sub.html"),+ `<div data-composition-id="sub" data-duration="3"><div id="inner" data-start="0" data-duration="1" data-track-index="0"></div></div>`,+ );+ const result = run(dir, "move", "#inner", "45");+ expect(result.status).toBe(2);+ expect(result.stderr).toContain("composition duration");+ expect(readFileSync(join(dir, "sub.html"), "utf8")).toContain('data-start="0"');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("keeps --plan JSON aligned with applied JSON and does not write", () => {+ const plannedDir = project();+ const appliedDir = project();+ try {+ const before = readFileSync(join(plannedDir, "index.html"), "utf8");+ const planned = run(plannedDir, "move", "#clip", "+1", "--plan");+ expect(planned.status, planned.stderr).toBe(0);+ const planJson = JSON.parse(planned.stdout) as Record<string, unknown>;+ expect(planJson.planned).toBe(true);+ expect(readFileSync(join(plannedDir, "index.html"), "utf8")).toBe(before);++ const applied = run(appliedDir, "move", "#clip", "+1");+ expect(applied.status, applied.stderr).toBe(0);+ const appliedJson = JSON.parse(applied.stdout) as Record<string, unknown>;+ expect(appliedJson.planned).toBe(false);+ expect(Object.keys(planJson).sort()).toEqual(Object.keys(appliedJson).sort());+ expect(appliedJson.receipt).toMatchObject({ file: "index.html", changed: true });+ } finally {+ rmSync(plannedDir, { recursive: true, force: true });+ rmSync(appliedDir, { recursive: true, force: true });+ }+ });+});diff --git a/packages/studio-server/src/helpers/applyFileMutations.test.ts b/packages/studio-server/src/helpers/applyFileMutations.test.tsnew file mode 100644index 0000000000..07ac259f77--- /dev/null+++ b/packages/studio-server/src/helpers/applyFileMutations.test.ts@@ -0,0 +1,80 @@+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { tmpdir } from "node:os";+import { describe, expect, it } from "vitest";+import { applyFileMutations } from "./applyFileMutations.js";+import { fileContentVersion, identifyFileWrite, resetFileWriteReceipts } from "./fileVersion.js";++function expectStaleMutation(after: string): void {+ const projectDir = mkdtempSync(join(tmpdir(), "hf-mutation-version-"));+ const path = join(projectDir, "index.html");+ try {+ writeFileSync(path, "before", "utf8");+ const expectedVersion = fileContentVersion(readFileSync(path, "utf8"));+ writeFileSync(path, "external", "utf8");+ expect(() =>+ applyFileMutations(projectDir, [+ { sourceFile: "index.html", absPath: path, before: "before", after, expectedVersion },+ ]),+ ).toThrow("file changed since the timeline was read");+ expect(readFileSync(path, "utf8")).toBe("external");+ } finally {+ rmSync(projectDir, { recursive: true, force: true });+ }+}++describe("applyFileMutations", () => {+ it("refuses a file whose version changed since the caller read it", () => {+ expectStaleMutation("after");+ });++ it("refuses a stale no-op instead of silently accepting it", () => {+ expectStaleMutation("before");+ });++ it("clears receipts for writes rolled back after a partial batch", () => {+ resetFileWriteReceipts();+ const projectDir = mkdtempSync(join(tmpdir(), "hf-mutation-rollback-"));+ const first = join(projectDir, "first.html");+ const second = join(projectDir, "second.html");+ try {+ writeFileSync(first, "first-before", "utf8");+ writeFileSync(second, "second-before", "utf8");+ let writes = 0;+ expect(() =>+ applyFileMutations(+ projectDir,+ [+ {+ sourceFile: "first.html",+ absPath: first,+ before: "first-before",+ after: "first-after",+ },+ {+ sourceFile: "second.html",+ absPath: second,+ before: "second-before",+ after: "second-after",+ },+ ],+ undefined,+ (path, content, encoding) => {+ writes += 1;+ if (writes === 2) {+ writeFileSync(path, "second-partial", encoding);+ throw new Error("second write failed");+ }+ writeFileSync(path, content, encoding);+ },+ ),+ ).toThrow("second write failed");+ expect(readFileSync(first, "utf8")).toBe("first-before");+ expect(readFileSync(second, "utf8")).toBe("second-before");+ expect(identifyFileWrite(first, fileContentVersion("first-after"))).toBeNull();+ } finally {+ resetFileWriteReceipts();+ rmSync(projectDir, { recursive: true, force: true });+ }+ });+});diff --git a/packages/studio-server/src/helpers/applyFileMutations.ts b/packages/studio-server/src/helpers/applyFileMutations.tsnew file mode 100644index 0000000000..d1988d5453--- /dev/null+++ b/packages/studio-server/src/helpers/applyFileMutations.ts@@ -0,0 +1,113 @@+import { readFileSync, writeFileSync } from "node:fs";+import { backupPathForResponse, snapshotBeforeWrite } from "./backupJournal.js";+import {+ clearFileWriteReceipt,+ createWriteToken,+ fileContentVersion,+ recordFileWriteReceipt,+} from "./fileVersion.js";++export interface FileMutationInput {+ sourceFile: string;+ absPath: string;+ before?: string;+ after: string;+ expectedVersion?: string;+}++export interface AppliedFileMutation {+ sourceFile: string;+ changed: boolean;+ before: string;+ after: string;+ backupPath: string | null;+ version: string;+ writeToken: string | null;+}++/** Applies prepared HTML mutations with the same journal and receipt semantics as Studio. */+export function applyFileMutations(+ projectDir: string,+ mutations: readonly FileMutationInput[],+ requestToken?: string,+ writeFile: (path: string, content: string, encoding: "utf-8") => void = writeFileSync,+): AppliedFileMutation[] {+ const prepared = mutations.map((mutation) => ({+ ...mutation,+ before: mutation.before ?? readFileSync(mutation.absPath, "utf-8"),+ }));+ const results: AppliedFileMutation[] = [];+ const attempted: Array<PreparedMutation & { version: string; writeToken: string }> = [];+ try {+ for (const mutation of prepared) {+ results.push(applyOneMutation(projectDir, mutation, requestToken, writeFile, attempted));+ }+ return results;+ } catch (error) {+ const rollbackErrors: unknown[] = [];+ for (const mutation of attempted.reverse()) {+ try {+ writeFile(mutation.absPath, mutation.before, "utf-8");+ clearFileWriteReceipt(mutation.absPath, mutation.version, mutation.writeToken);+ } catch (rollbackError) {+ rollbackErrors.push(rollbackError);+ }+ }+ if (rollbackErrors.length > 0) {+ throw new AggregateError(+ [error, ...rollbackErrors],+ "File mutation failed and rollback did not complete",+ );+ }+ throw error;+ }+}++type PreparedMutation = FileMutationInput & { before: string };++function applyOneMutation(+ projectDir: string,+ mutation: PreparedMutation,+ requestToken: string | undefined,+ writeFile: (path: string, content: string, encoding: "utf-8") => void,+ attempted: Array<PreparedMutation & { version: string; writeToken: string }>,+): AppliedFileMutation {+ const current = readFileSync(mutation.absPath, "utf-8");+ assertExpectedVersion(mutation.expectedVersion, current);+ if (mutation.after === mutation.before) {+ return {+ ...mutation,+ before: current,+ changed: false,+ backupPath: null,+ version: fileContentVersion(mutation.before),+ writeToken: null,+ };+ }+ const backup = snapshotBeforeWrite(projectDir, mutation.absPath);+ if (backup.error) throw new Error(`backup failed: ${backup.error}`);+ const before = current;+ const version = fileContentVersion(mutation.after);+ const writeToken = createWriteToken(requestToken);+ attempted.push({ ...mutation, before, version, writeToken });+ writeFile(mutation.absPath, mutation.after, "utf-8");+ recordFileWriteReceipt(mutation.absPath, {+ path: mutation.sourceFile,+ version,+ writeToken,+ });+ return {+ ...mutation,+ before,+ changed: true,+ backupPath: backupPathForResponse(projectDir, backup.backupPath),+ version,+ writeToken,+ };+}++function assertExpectedVersion(expectedVersion: string | undefined, current: string): void {+ if (expectedVersion !== undefined && fileContentVersion(current) !== expectedVersion) {+ throw new Error("file changed since the timeline was read");+ }+}diff --git a/packages/studio-server/src/helpers/fileVersion.ts b/packages/studio-server/src/helpers/fileVersion.tsindex 6c99dc2041..037babde4d 100644--- a/packages/studio-server/src/helpers/fileVersion.ts+++ b/packages/studio-server/src/helpers/fileVersion.ts@@ -32,6 +32,14 @@ export function recordFileWriteReceipt(absPath: string, receipt: FileWriteReceipreceipts.set(absPath, current);}+export function clearFileWriteReceipt(absPath: string, version: string, writeToken: string): void {+ const current = (receipts.get(absPath) ?? []).filter(+ (entry) => entry.version !== version || entry.writeToken !== writeToken,+ );+ if (current.length > 0) receipts.set(absPath, current);+ else receipts.delete(absPath);+}+/*** Attach one API write's identity to the watcher echo for its exact bytes.*diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.tsindex 395d2d8a8b..665e4f96a3 100644--- a/packages/studio-server/src/index.ts+++ b/packages/studio-server/src/index.ts@@ -11,6 +11,18 @@ export type {StudioSelectionTextField,} from "./types.js";export { isSafePath, walkDir } from "./helpers/safePath.js";+export {+ patchElementInHtml,+ splitElementInHtml,+ removeElementFromHtml,+ type PatchOperation,+ type SourceMutationTarget,+} from "./helpers/sourceMutation.js";+export {+ applyFileMutations,+ type AppliedFileMutation,+ type FileMutationInput,+} from "./helpers/applyFileMutations.js";export type { PreviewApiAdapter } from "./helpers/mediaProxyPreview.js";export { getMimeType, MIME_TYPES } from "./helpers/mime.js";export {diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.tsindex 139d78ca7d..7fb8494832 100644--- a/packages/studio-server/src/routes/files.ts+++ b/packages/studio-server/src/routes/files.ts@@ -31,6 +31,7 @@ import {fileContentVersion,recordFileWriteReceipt,} from "../helpers/fileVersion.js";+import { applyFileMutations } from "../helpers/applyFileMutations.js";import {findUnsafeDomPatchValues,findUnsafeMutationValues,@@ -309,6 +310,7 @@ export function commitElementPatchBatches(projectDir: string,batches: ElementPatchBatchRequest[],writeFile: (path: string, content: string, encoding: "utf-8") => void = writeFileSync,+ requestToken?: string,):| { error: "duplicate" | "forbidden" | "not-found"; sourceFile: string }| { durable: boolean; files: ElementPatchBatchFileResult[] } {@@ -357,52 +359,25 @@ export function commitElementPatchBatches(};}- const files: ElementPatchBatchFileResult[] = [];- const attemptedWrites: typeof prepared = [];- try {- for (const file of prepared) {- if (file.after === file.before) {- files.push({- sourceFile: file.sourceFile,- changed: false,- matched: file.matched,- before: file.before,- after: file.before,- });- continue;- }- const backup = snapshotBeforeWrite(projectDir, file.absPath);- if (backup.error) {- throw new Error(`Failed to create backup for ${file.sourceFile}: ${backup.error}`);- }- attemptedWrites.push(file);- writeFile(file.absPath, file.after, "utf-8");- files.push({- sourceFile: file.sourceFile,- changed: true,- matched: file.matched,- before: file.before,- after: file.after,- backupPath: backupPathForResponse(projectDir, backup.backupPath),- });- }- } catch (error) {- const rollbackErrors: unknown[] = [];- for (const file of attemptedWrites.reverse()) {- try {- writeFile(file.absPath, file.before, "utf-8");- } catch (rollbackError) {- rollbackErrors.push(rollbackError);- }- }- if (rollbackErrors.length > 0) {- throw new AggregateError(- [error, ...rollbackErrors],- "Element patch batch failed and rollback did not complete",- );- }- throw error;- }+ const applied = applyFileMutations(+ projectDir,+ prepared.map(({ sourceFile, absPath, before, after }) => ({+ sourceFile,+ absPath,+ before,+ after,+ })),+ requestToken,+ writeFile,+ );+ const files: ElementPatchBatchFileResult[] = applied.map((file, index) => ({+ sourceFile: file.sourceFile,+ changed: file.changed,+ matched: prepared[index]?.matched ?? [],+ before: file.before,+ after: file.after,+ backupPath: file.backupPath ?? undefined,+ }));return { durable: true, files };}@@ -411,16 +386,12 @@ function commitElementPatchBatchesWithReceipts(projectDir: string,batches: ElementPatchBatchRequest[],): ReturnType<typeof commitElementPatchBatches> {- const result = commitElementPatchBatches(projectDir, batches);- if ("error" in result || !result.durable) return result;-- for (const file of result.files) {- if (!file.changed) continue;- const absPath = resolveWithinProject(projectDir, file.sourceFile);- if (!absPath) throw new Error(`Committed element patch escaped project: ${file.sourceFile}`);- recordMutationReceipt(c, file.sourceFile, absPath, file.after);- }- return result;+ return commitElementPatchBatches(+ projectDir,+ batches,+ writeFileSync,+ c.req.header("X-Hyperframes-Write-Token"),+ );}/**