fablecut 1.15.0 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/comp.js CHANGED
@@ -76,11 +76,15 @@
76
76
  if (parentId === childId) return true;
77
77
  return usedComps(doc, childId).has(parentId);
78
78
  }
79
- /** Where comp `id` is used: [{in: compId | null (main), clip}] */
79
+ /** Where comp `id` is used: [{in: compId | null (a timeline), clip, sequence?}] — the open
80
+ * timeline, other comps, and the sequences that aren't open (see sequences.js). */
80
81
  function usages(doc, id) {
81
82
  const out = [];
82
83
  for (const c of doc.clips || []) if (c.kind === "comp" && c.compId === id) out.push({ in: null, clip: c });
83
84
  for (const comp of doc.comps || []) for (const c of comp.clips || []) if (c.kind === "comp" && c.compId === id) out.push({ in: comp.id, clip: c });
85
+ const seqs = Array.isArray(doc.sequences) ? doc.sequences : [];
86
+ const act = seqs.some((s) => s.id === doc.sequence) ? doc.sequence : seqs[0] && seqs[0].id;
87
+ for (const s of seqs) if (s && s.id !== act) for (const c of s.clips || []) if (c.kind === "comp" && c.compId === id) out.push({ in: null, sequence: s.id, clip: c });
84
88
  return out;
85
89
  }
86
90
 
@@ -253,8 +253,10 @@ const DRY_RUN_TIMEOUT_MS = 15_000;
253
253
  function dryRunProfile(profile, { fps = 30, hasAudio = true } = {}) {
254
254
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fablecut-dry-"));
255
255
  const out = path.join(dir, `probe${profile.extension}`);
256
+ // 256×144: hardware encoders refuse tiny frames (NVENC's minimum is about
257
+ // 145×49), and a profile that can't pass the dry run can never export.
256
258
  const args = ["-y", "-hide_banner", "-f", "lavfi",
257
- "-i", `color=c=black:s=64x64:r=${fps}:d=0.1`];
259
+ "-i", `color=c=black:s=256x144:r=${fps}:d=0.1`];
258
260
  if (hasAudio) args.push("-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo");
259
261
  args.push("-t", "0.1", ...withInputColor(profile, "bt709"), out);
260
262
  return new Promise((resolve) => {
@@ -283,8 +285,12 @@ function dryRunProfile(profile, { fps = 30, hasAudio = true } = {}) {
283
285
  proc.stderr.on("data", (d) => { stderr = (stderr + d).slice(-4000); });
284
286
  proc.on("close", (code) => {
285
287
  if (code === 0) { finish({ ok: true }); return; }
286
- const lines = stderr.trim().split("\n").filter(Boolean);
287
- finish({ ok: false, error: lines.slice(-3).join(" · ") || `ffmpeg exited ${code}` });
288
+ // ffmpeg ends with generic lines ("Conversion failed!"); lead with the ones naming the cause
289
+ const lines = stderr.trim().split("\n").map((l) => l.trim()).filter(Boolean);
290
+ const cause = lines.filter((l) => /error|invalid|unknown|not found|unrecognized|failed|minimum|unsupported|no such/i.test(l)
291
+ && !/^Conversion failed/i.test(l));
292
+ const picked = cause.length ? cause.slice(0, 2).concat(lines.slice(-1)) : lines.slice(-3);
293
+ finish({ ok: false, error: [...new Set(picked)].join(" · ") || `ffmpeg exited ${code}` });
288
294
  });
289
295
  });
290
296
  }
@@ -63,6 +63,32 @@
63
63
  "-c:a", "pcm_s16le",
64
64
  "-shortest"
65
65
  ]
66
+ },
67
+ "nvenc-h264": {
68
+ "label": "NVIDIA GPU · H.264",
69
+ "description": "Encodes on an NVIDIA GPU (NVENC): frees the CPU for rendering. Needs an NVIDIA card and an ffmpeg built with NVENC.",
70
+ "jpegQuality": 0.95,
71
+ "extension": ".mp4",
72
+ "color": { "matrix": "bt709", "primaries": "bt709", "trc": "bt709", "range": "tv" },
73
+ "args": [
74
+ "-c:v", "h264_nvenc", "-preset", "p5", "-tune", "hq", "-rc", "vbr", "-cq", "19", "-b:v", "0",
75
+ "-pix_fmt", "yuv420p",
76
+ "-c:a", "aac", "-b:a", "192k",
77
+ "-movflags", "+faststart", "-shortest"
78
+ ]
79
+ },
80
+ "nvenc-hevc": {
81
+ "label": "NVIDIA GPU · HEVC",
82
+ "description": "HEVC on an NVIDIA GPU (NVENC): smaller files than H.264 at similar quality. Needs an NVIDIA card and an ffmpeg built with NVENC.",
83
+ "jpegQuality": 0.95,
84
+ "extension": ".mp4",
85
+ "color": { "matrix": "bt709", "primaries": "bt709", "trc": "bt709", "range": "tv" },
86
+ "args": [
87
+ "-c:v", "hevc_nvenc", "-preset", "p5", "-tune", "hq", "-rc", "vbr", "-cq", "21", "-b:v", "0",
88
+ "-pix_fmt", "yuv420p", "-tag:v", "hvc1",
89
+ "-c:a", "aac", "-b:a", "192k",
90
+ "-movflags", "+faststart", "-shortest"
91
+ ]
66
92
  }
67
93
  }
68
94
  }
package/history.js ADDED
@@ -0,0 +1,341 @@
1
+ /* ═══════════════════════════════════════════════════════════════════════════
2
+ Versions: a project's history, kept beside it, never destructive.
3
+
4
+ projects/<id>/history/v0007.json the document as it was
5
+ projects/<id>/history/v0007.meta.json {v, name, note, kind, created,
6
+ revision, clips, duration, final}
7
+
8
+ One pair of files per version, created with an exclusive open, so the
9
+ editor server and an MCP server can both save versions without a shared
10
+ index to race on. Kinds: manual (the user or an agent), auto (every few
11
+ minutes while the project changes), agent (before an agent rewrites or
12
+ starts editing it), restore (what was there before a restore).
13
+
14
+ Restoring a version first saves the current document as a version, then
15
+ writes the old one back with a new revision: nothing is ever lost.
16
+ ═══════════════════════════════════════════════════════════════════════════ */
17
+ "use strict";
18
+ const crypto = require("crypto");
19
+ const fs = require("fs");
20
+ const path = require("path");
21
+ const SeqLib = require("./sequences");
22
+
23
+ const KINDS = ["manual", "auto", "agent", "restore"];
24
+ const MAX_NAME = 120, MAX_NOTE = 2000;
25
+ const pad = (n) => String(n).padStart(4, "0");
26
+ const readJSON = (file) => JSON.parse(fs.readFileSync(file, "utf8").replace(/^/, ""));
27
+ function writeJSON(file, obj) {
28
+ const tmp = `${file}.${crypto.randomUUID()}.tmp`;
29
+ fs.writeFileSync(tmp, JSON.stringify(obj, null, 2));
30
+ fs.renameSync(tmp, file);
31
+ }
32
+ const timelineEnd = (doc) => (Array.isArray(doc.clips) ? doc.clips : [])
33
+ .reduce((m, c) => Math.max(m, (+c.start || 0) + (+c.duration || 0)), 0);
34
+ const fmtDur = (s) => { const t = Math.round(s); return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`; };
35
+
36
+ /* What changed from document a (older) to b (newer), for people and agents.
37
+ With several sequences, each one's timeline is compared with the same
38
+ sequence in the other document, whichever was open in either. */
39
+ const TIMELINE_SETTINGS = ["width", "height", "fps", "background", "inPoint", "outPoint"];
40
+ const TIMELINE_LISTS = ["tracks", "markers", "master", "buses", "delivery", "outputs", "exportFrame"];
41
+ function timelineDiff(a, b) {
42
+ const byId = (arr) => new Map((Array.isArray(arr) ? arr : []).filter((x) => x && x.id).map((x) => [x.id, x]));
43
+ const label = (c) => `${c.name ? `"${c.name}"` : c.kind || "clip"} (${c.id})`;
44
+ const ca = byId(a.clips), cb = byId(b.clips);
45
+ const added = [...cb.values()].filter((c) => !ca.has(c.id));
46
+ const removed = [...ca.values()].filter((c) => !cb.has(c.id));
47
+ const changed = [];
48
+ for (const [id, cn] of cb) {
49
+ const co = ca.get(id);
50
+ if (!co || JSON.stringify(co) === JSON.stringify(cn)) continue;
51
+ const what = [];
52
+ if (co.track !== cn.track) what.push(`track ${co.track}→${cn.track}`);
53
+ if (co.start !== cn.start || co.duration !== cn.duration || co.in !== cn.in) what.push("timing");
54
+ if (JSON.stringify(co.props || {}) !== JSON.stringify(cn.props || {})) {
55
+ const keys = new Set([...Object.keys(co.props || {}), ...Object.keys(cn.props || {})]);
56
+ const ks = [...keys].filter((k) => JSON.stringify((co.props || {})[k]) !== JSON.stringify((cn.props || {})[k]));
57
+ what.push(ks.length > 4 ? `${ks.length} props` : ks.join(", "));
58
+ }
59
+ if (JSON.stringify(co.keyframes || {}) !== JSON.stringify(cn.keyframes || {})) what.push("keyframes");
60
+ if (JSON.stringify(co.fx || []) !== JSON.stringify(cn.fx || [])) what.push("effects");
61
+ if (JSON.stringify([co.transitionIn, co.transitionOut]) !== JSON.stringify([cn.transitionIn, cn.transitionOut])) what.push("transitions");
62
+ if (co.mediaId !== cn.mediaId) what.push("source");
63
+ if (!what.length) what.push("other fields");
64
+ changed.push({ id, name: cn.name || null, kind: cn.kind, what });
65
+ }
66
+ const settings = [];
67
+ for (const k of TIMELINE_SETTINGS)
68
+ if ((a[k] ?? null) !== (b[k] ?? null)) settings.push(`${k} ${JSON.stringify(a[k] ?? null)}→${JSON.stringify(b[k] ?? null)}`);
69
+ for (const k of TIMELINE_LISTS)
70
+ if (JSON.stringify(a[k] ?? null) !== JSON.stringify(b[k] ?? null)) settings.push(k);
71
+ const lenA = timelineEnd(a), lenB = timelineEnd(b);
72
+ const lines = [];
73
+ if (added.length) lines.push(`${added.length} clip(s) added: ${added.slice(0, 8).map(label).join(", ")}${added.length > 8 ? ", …" : ""}`);
74
+ if (removed.length) lines.push(`${removed.length} clip(s) removed: ${removed.slice(0, 8).map(label).join(", ")}${removed.length > 8 ? ", …" : ""}`);
75
+ if (changed.length) lines.push(`${changed.length} clip(s) changed: ${changed.slice(0, 8).map((c) => `${label(c)} ${c.what.join("/")}`).join("; ")}${changed.length > 8 ? "; …" : ""}`);
76
+ if (Math.abs(lenA - lenB) > 0.005) lines.push(`length ${fmtDur(lenA)} → ${fmtDur(lenB)}`);
77
+ return { added, removed, changed, settings, lines };
78
+ }
79
+ function diffDocs(a, b) {
80
+ const brief = (c) => ({ id: c.id, name: c.name || null, kind: c.kind });
81
+ const byId = (arr) => new Map((Array.isArray(arr) ? arr : []).filter((x) => x && x.id).map((x) => [x.id, x]));
82
+ const ma = byId(a.media), mb = byId(b.media);
83
+ const mediaAdded = [...mb.values()].filter((m) => !ma.has(m.id)), mediaRemoved = [...ma.values()].filter((m) => !mb.has(m.id));
84
+ // the project's own settings; the canvas, IN / OUT, tracks, mix and delivery belong to a sequence
85
+ const renamed = (a.name ?? null) !== (b.name ?? null) ? [`name ${JSON.stringify(a.name ?? null)}→${JSON.stringify(b.name ?? null)}`] : [];
86
+ const shared = ["comps", "collections", "folders"].filter((k) => JSON.stringify(a[k] ?? null) !== JSON.stringify(b[k] ?? null));
87
+ const project = [...renamed, ...shared];
88
+ const several = SeqLib.entries(a).length > 1 || SeqLib.entries(b).length > 1;
89
+ const lines = [];
90
+ let main, settings;
91
+ const sequences = [];
92
+ if (!several) {
93
+ main = timelineDiff(a, b);
94
+ settings = [...renamed, ...main.settings, ...shared];
95
+ lines.push(...main.lines.filter((l) => !l.startsWith("length ")));
96
+ if (mediaAdded.length || mediaRemoved.length) lines.push(mediaLine(mediaAdded, mediaRemoved));
97
+ lines.push(...main.lines.filter((l) => l.startsWith("length ")));
98
+ if (settings.length) lines.push(`project: ${settings.join(", ")}`);
99
+ } else {
100
+ // each sequence against itself; the clip lists returned are the newer document's open sequence
101
+ const view = (doc, id) => SeqLib.open(JSON.parse(JSON.stringify(doc)), id);
102
+ const ea = new Map(SeqLib.entries(a).map((x) => [x.id, x])), eb = new Map(SeqLib.entries(b).map((x) => [x.id, x]));
103
+ const openB = SeqLib.activeId(b);
104
+ settings = project.slice();
105
+ for (const [id, s] of eb) {
106
+ if (!ea.has(id)) { lines.push(`sequence "${s.name}" added`); sequences.push({ id, name: s.name, added: true }); continue; }
107
+ const d = timelineDiff(view(a, id), view(b, id));
108
+ const nameOld = ea.get(id).name;
109
+ if (nameOld !== s.name) d.lines.unshift(`renamed from "${nameOld}"`);
110
+ if (d.settings.length) d.lines.push(`settings: ${d.settings.join(", ")}`);
111
+ if (id === openB) { main = d; settings.push(...d.settings); }
112
+ if (d.lines.length) { lines.push(...d.lines.map((l) => `"${s.name}": ${l}`)); sequences.push({ id, name: s.name, lines: d.lines }); }
113
+ }
114
+ for (const [id, s] of ea) if (!eb.has(id)) { lines.push(`sequence "${s.name}" removed`); sequences.push({ id, name: s.name, removed: true }); }
115
+ if (SeqLib.activeId(a) !== openB && ea.has(openB)) lines.push(`open sequence "${ea.get(SeqLib.activeId(a))?.name || SeqLib.activeId(a)}" → "${eb.get(openB).name}"`);
116
+ if (!main) main = timelineDiff({ clips: [] }, view(b, openB));
117
+ if (mediaAdded.length || mediaRemoved.length) lines.push(mediaLine(mediaAdded, mediaRemoved));
118
+ if (project.length) lines.push(`project: ${project.join(", ")}`);
119
+ }
120
+ return {
121
+ same: !lines.length, lines,
122
+ added: main.added.map(brief), removed: main.removed.map(brief),
123
+ changed: main.changed, mediaAdded: mediaAdded.map((m) => m.id), mediaRemoved: mediaRemoved.map((m) => m.id), settings,
124
+ ...(several ? { sequences } : {}),
125
+ };
126
+ }
127
+ const mediaLine = (added, removed) => `media ${added.length ? "+" + added.length : ""}${added.length && removed.length ? " " : ""}${removed.length ? "−" + removed.length : ""}`;
128
+
129
+ function createHistory({ projects, autoMinutes = 10, keepAuto = 30 }) {
130
+ const dir = (pid) => path.join(projects.DIR, pid, "history");
131
+ const docPath = (pid, v) => path.join(dir(pid), `v${pad(v)}.json`);
132
+ const metaPath = (pid, v) => path.join(dir(pid), `v${pad(v)}.meta.json`);
133
+ const resolve = (pid) => {
134
+ const id = pid || projects.activeId();
135
+ projects.mustExist(id);
136
+ return id;
137
+ };
138
+
139
+ function entries(pid) {
140
+ let files = [];
141
+ try { files = fs.readdirSync(dir(pid)).filter((f) => /^v\d+\.meta\.json$/.test(f)); } catch { }
142
+ const out = [];
143
+ for (const f of files) { try { out.push(readJSON(path.join(dir(pid), f))); } catch { } }
144
+ return out.sort((x, y) => y.v - x.v); // newest first
145
+ }
146
+ const entry = (pid, v) => {
147
+ const n = Number(String(v).replace(/^v/i, ""));
148
+ const e = Number.isInteger(n) && entries(pid).find((x) => x.v === n);
149
+ if (!e) throw new Error(`no version ${JSON.stringify(v)} of this project (versions lists them)`);
150
+ return e;
151
+ };
152
+
153
+ /* Save the project as it is now. */
154
+ function save(pid, { name, note, kind = "manual", final = false, doc } = {}) {
155
+ pid = resolve(pid);
156
+ if (!KINDS.includes(kind)) throw new Error(`kind must be one of ${KINDS.join(", ")}`);
157
+ const cur = doc || projects.readDoc(pid);
158
+ fs.mkdirSync(dir(pid), { recursive: true });
159
+ const have = entries(pid);
160
+ let v = (have[0]?.v || 0) + 1;
161
+ // an exclusive create claims the number; another process may have taken it
162
+ for (;; v++) {
163
+ try { fs.writeFileSync(docPath(pid, v), JSON.stringify(cur, null, 2), { flag: "wx" }); break; }
164
+ catch (e) { if (e.code !== "EEXIST") throw e; }
165
+ }
166
+ const meta = {
167
+ v, name: String(name || "").trim().slice(0, MAX_NAME) || defaultName(kind, v),
168
+ note: String(note || "").slice(0, MAX_NOTE), kind, created: new Date().toISOString(),
169
+ revision: cur.revision || 0, clips: (cur.clips || []).length, duration: +timelineEnd(cur).toFixed(2), final: false,
170
+ };
171
+ writeJSON(metaPath(pid, v), meta);
172
+ if (final) markFinal(pid, v, true);
173
+ if (kind === "auto") prune(pid);
174
+ return { project: pid, version: final ? entry(pid, v) : meta };
175
+ }
176
+ const defaultName = (kind, v) => ({ manual: `Version ${String(v).padStart(2, "0")}`, auto: "Auto-save", agent: "Before agent edits", restore: "Before restore" })[kind];
177
+
178
+ function prune(pid) {
179
+ const autos = entries(pid).filter((e) => e.kind === "auto" && !e.final);
180
+ for (const e of autos.slice(keepAuto)) remove(pid, e.v, { force: true });
181
+ }
182
+
183
+ function list(pid) {
184
+ pid = resolve(pid);
185
+ return { project: pid, versions: entries(pid) };
186
+ }
187
+ function get(pid, v) {
188
+ pid = resolve(pid);
189
+ return readJSON(docPath(pid, entry(pid, v).v));
190
+ }
191
+
192
+ /* Write a version back. What was there is saved first, so a restore can be undone by restoring that. */
193
+ function restore(pid, v) {
194
+ pid = resolve(pid);
195
+ const e = entry(pid, v);
196
+ const old = readJSON(docPath(pid, e.v));
197
+ const before = save(pid, { kind: "restore", name: `Before restoring v${e.v}` }).version;
198
+ const cur = projects.readDoc(pid);
199
+ // writeDoc lifts the open project's revision past this one, so tabs and agents see the change
200
+ projects.writeDoc(pid, { ...old, revision: Math.max(cur.revision || 0, old.revision || 0) });
201
+ return { project: pid, restored: e, saved: before };
202
+ }
203
+
204
+ /* What changed between two versions, or from a version to now (b default "current"). */
205
+ function diff(pid, a, b = "current") {
206
+ pid = resolve(pid);
207
+ const load = (x) => (x === "current" || x == null ? projects.readDoc(pid) : get(pid, x));
208
+ return { project: pid, from: a, to: b, ...diffDocs(load(a), load(b)) };
209
+ }
210
+
211
+ function markFinal(pid, v, on = true) {
212
+ const e = entry(pid, v);
213
+ if (on) for (const o of entries(pid)) if (o.final && o.v !== e.v) writeJSON(metaPath(pid, o.v), { ...o, final: false });
214
+ writeJSON(metaPath(pid, e.v), { ...e, final: !!on });
215
+ return entry(pid, e.v);
216
+ }
217
+ function update(pid, v, { name, note, final } = {}) {
218
+ pid = resolve(pid);
219
+ let e = entry(pid, v);
220
+ if (name != null || note != null) {
221
+ e = { ...e };
222
+ if (name != null) { const n = String(name).trim().slice(0, MAX_NAME); if (!n) throw new Error("name can't be empty"); e.name = n; }
223
+ if (note != null) e.note = String(note).slice(0, MAX_NOTE);
224
+ writeJSON(metaPath(pid, e.v), e);
225
+ }
226
+ if (final != null) e = markFinal(pid, e.v, !!final);
227
+ return { project: pid, version: e };
228
+ }
229
+ function remove(pid, v, { force = false } = {}) {
230
+ pid = resolve(pid);
231
+ const e = entry(pid, v);
232
+ if (e.final && !force) throw new Error(`v${e.v} is marked final — unmark it first`);
233
+ for (const f of [docPath(pid, e.v), metaPath(pid, e.v)]) { try { fs.unlinkSync(f); } catch { } }
234
+ return { project: pid, deleted: e.v };
235
+ }
236
+
237
+ /* Auto-save the open project when it changed and the last version is old enough. */
238
+ function maybeAuto(now = Date.now()) {
239
+ let cur;
240
+ try { cur = projects.readRoot(); } catch { return null; }
241
+ let pid = projects.peekActive();
242
+ if (!pid) {
243
+ if (!(cur.clips || []).length) return null; // nothing worth keeping yet
244
+ pid = projects.activeId(); // versions need the project's folder
245
+ }
246
+ const last = entries(pid)[0];
247
+ if (last && (last.revision === (cur.revision || 0) || now - new Date(last.created).getTime() < autoMinutes * 60000)) return null;
248
+ if (!last && !(cur.clips || []).length) return null; // nothing worth keeping yet
249
+ return save(pid, { kind: "auto", doc: cur }).version;
250
+ }
251
+
252
+ /* Before an agent changes the project: one version per session start / rewrite, not one per edit. */
253
+ function beforeAgent(name) {
254
+ const pid = projects.activeId();
255
+ const cur = projects.readDoc(pid);
256
+ const last = entries(pid)[0];
257
+ if (last && last.revision === (cur.revision || 0)) return null; // already saved as it is
258
+ return save(pid, { kind: "agent", name, doc: cur }).version;
259
+ }
260
+
261
+ /* A whole project with its versions, as one JSON file. */
262
+ function backup(pid) {
263
+ pid = resolve(pid);
264
+ const meta = projects.list({ archived: "all" }).projects.find((p) => p.id === pid) || {};
265
+ return {
266
+ fablecut: "backup", format: 1, created: new Date().toISOString(),
267
+ name: meta.name, notes: meta.notes || "", tags: meta.tags || [],
268
+ project: projects.readDoc(pid),
269
+ versions: entries(pid).reverse().map((e) => ({ ...e, project: readJSON(docPath(pid, e.v)) })),
270
+ };
271
+ }
272
+ function importBackup(b, { name, open = false } = {}) {
273
+ if (!b || b.fablecut !== "backup" || !b.project) throw new Error("not a FableCut backup");
274
+ const out = projects.importDoc(b.project, { name: name || b.name, open: false });
275
+ projects.update(out.id, { notes: b.notes || "", tags: b.tags || [] });
276
+ fs.mkdirSync(dir(out.id), { recursive: true });
277
+ // each version is checked like a project, and its details are worked out again from it
278
+ const isDoc = (d) => d && typeof d === "object" && !Array.isArray(d) && Array.isArray(d.clips) && Array.isArray(d.media);
279
+ const good = (Array.isArray(b.versions) ? b.versions : []).filter((e) => e && Number.isInteger(e.v) && e.v > 0 && isDoc(e.project));
280
+ const finalV = good.filter((e) => e.final === true).map((e) => e.v).pop(); // one final cut: the newest one marked
281
+ let n = 0;
282
+ for (const e of good) {
283
+ const created = typeof e.created === "string" && !isNaN(Date.parse(e.created)) ? e.created : new Date().toISOString();
284
+ writeJSON(docPath(out.id, e.v), e.project);
285
+ writeJSON(metaPath(out.id, e.v), {
286
+ v: e.v, name: String(e.name || "").trim().slice(0, MAX_NAME) || `Version ${String(e.v).padStart(2, "0")}`,
287
+ note: String(e.note || "").slice(0, MAX_NOTE), kind: KINDS.includes(e.kind) ? e.kind : "manual", created,
288
+ revision: e.project.revision || 0, clips: e.project.clips.length, duration: +timelineEnd(e.project).toFixed(2), final: e.v === finalV,
289
+ });
290
+ n++;
291
+ }
292
+ const res = open ? projects.open(out.id) : { id: out.id, project: projects.list({ archived: "all" }).projects.find((p) => p.id === out.id) };
293
+ return { ...res, versions: n };
294
+ }
295
+
296
+ /* project.json can't be read at startup: keep the broken file, put back the newest good copy. */
297
+ function recover(projectFile) {
298
+ const pid = projects.peekActive();
299
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
300
+ const aside = projectFile.replace(/\.json$/, `.corrupt-${stamp}.json`);
301
+ fs.renameSync(projectFile, aside);
302
+ const cands = [];
303
+ if (pid) {
304
+ for (const e of entries(pid)) {
305
+ let t = new Date(e.created).getTime();
306
+ if (!Number.isFinite(t)) { try { t = fs.statSync(docPath(pid, e.v)).mtimeMs; } catch { t = 0; } } // a meta file without a usable date
307
+ cands.push({ t, file: docPath(pid, e.v), from: `version v${e.v}` });
308
+ }
309
+ const parked = path.join(projects.DIR, pid, "project.json");
310
+ try { cands.push({ t: fs.statSync(parked).mtimeMs, file: parked, from: "its last saved copy" }); } catch { }
311
+ }
312
+ cands.sort((x, y) => y.t - x.t);
313
+ for (const c of cands) {
314
+ try {
315
+ const doc = readJSON(c.file);
316
+ // only a document the editor can open: the next candidate otherwise
317
+ if (!doc || typeof doc !== "object" || Array.isArray(doc) || !Array.isArray(doc.clips) || !Array.isArray(doc.media)) continue;
318
+ writeJSON(projectFile, { ...doc, revision: (doc.revision || 0) + 1 });
319
+ return { recovered: true, from: c.from, aside };
320
+ } catch { }
321
+ }
322
+ return { recovered: false, aside };
323
+ }
324
+
325
+ function act(a = {}) {
326
+ const pid = a.project || null;
327
+ switch (a.action || "list") {
328
+ case "list": return list(pid);
329
+ case "save": return save(pid, { name: a.name, note: a.note, final: !!a.final });
330
+ case "restore": return restore(pid, a.version);
331
+ case "diff": return diff(pid, a.version, a.to || "current");
332
+ case "update": return update(pid, a.version, a);
333
+ case "delete": return remove(pid, a.version);
334
+ default: throw new Error(`unknown action ${JSON.stringify(a.action)} (list|save|restore|diff|update|delete)`);
335
+ }
336
+ }
337
+
338
+ return { list, get, save, restore, diff, update, remove, maybeAuto, beforeAgent, backup, importBackup, recover, act };
339
+ }
340
+
341
+ module.exports = { createHistory, diffDocs, KINDS };
package/index.html CHANGED
@@ -15,6 +15,7 @@
15
15
  <!-- ══════════ TOP BAR ══════════ -->
16
16
  <header class="topbar">
17
17
  <div class="logo"><span class="logo-mark">▶</span> Fable<b>Cut</b></div>
18
+ <button type="button" class="btn tiny hidden" id="btnProjectsDash" title="Projects (Ctrl/Cmd+O): open, create, duplicate, archive">Projects</button>
18
19
  <div class="topbar-center" id="projectName">Untitled Project</div>
19
20
  <div class="topbar-right">
20
21
  <span class="btn-group ws-switch" id="wsSwitch" role="tablist" title="Workspace">
@@ -209,6 +210,7 @@
209
210
  <!-- ══════════ TIMELINE ══════════ -->
210
211
  <section class="panel timeline-panel" id="timelinePanel">
211
212
  <div class="timeline-toolbar">
213
+ <button type="button" class="btn tiny seq-btn" id="btnSequences" aria-haspopup="menu" title="Sequences"><svg class="ico" viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="1.5" d="M1.75 3.25h12.5M1.75 8h8.5M1.75 12.75h10.5"/></svg> <span class="seq-name">Main</span><span class="seq-count"></span> ▾</button>
212
214
  <span class="comp-crumb hidden" id="compCrumb" aria-label="Open composition"></span>
213
215
  <button class="btn tiny hidden" id="btnTrimIO" title="Trim clips to IN/OUT (⇧T)"><svg class="ico" viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="1.85" stroke-linecap="square" d="M1.25 4.5H12M4.5 1.25V12M4.5 12H14.75M12 4.5V14.75"/></svg> Trim</button>
214
216
  <button class="btn tiny toggle hidden" id="btnWorkAreaPlay" title="Limit playback to IN/OUT (Home/End jump to markers; playhead outside = override)"><svg class="ico" viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="1.85" stroke-linecap="square" stroke-linejoin="miter" d="M1.5 2.5V13.5M14.5 2.5V13.5M4.25 8H11.75M9.35 5.6L12 8L9.35 10.4"/></svg> Limit</button>
@@ -268,6 +270,32 @@
268
270
  </div>
269
271
  </div>
270
272
 
273
+ <!-- ══════════ PROJECTS ══════════ -->
274
+ <div class="overlay hidden" id="projectsOverlay">
275
+ <div class="dialog projects-dialog" id="projectsDialog" role="dialog" aria-modal="true" aria-labelledby="projectsTitle" tabindex="-1">
276
+ <div class="pj-head">
277
+ <h2 id="projectsTitle">Projects</h2>
278
+ <span class="btn-group pj-views" role="tablist">
279
+ <button type="button" class="btn tiny on" data-pj-view="active">All projects</button>
280
+ <button type="button" class="btn tiny" data-pj-view="archived">Archived</button>
281
+ </span>
282
+ <input type="search" id="pjSearch" class="pj-search" placeholder="Search name, notes, #tag" aria-label="Search projects" spellcheck="false" autocomplete="off">
283
+ <select id="pjSort" class="pj-sort" aria-label="Sort by" title="Sort by">
284
+ <option value="opened">Last opened</option><option value="modified">Last modified</option>
285
+ <option value="created">Created</option><option value="name">Name</option>
286
+ </select>
287
+ <label class="btn tiny" for="pjImportFile" title="Add a project file (.json): an old backup, or one from another machine">Import…</label>
288
+ <input type="file" id="pjImportFile" class="sr-only" accept=".json,application/json">
289
+ <button type="button" class="btn tiny accent" id="pjNewBtn">+ New project</button>
290
+ <button type="button" class="btn ghost pj-close" id="pjClose" aria-label="Close" title="Close (Esc)">✕</button>
291
+ </div>
292
+ <div class="pj-body">
293
+ <div class="pj-grid" id="pjGrid"></div>
294
+ <aside class="pj-side" id="pjSide"></aside>
295
+ </div>
296
+ </div>
297
+ </div>
298
+
271
299
  <!-- ══════════ EXPORT SETUP ══════════ -->
272
300
  <div class="overlay hidden" id="exportSetup">
273
301
  <div class="dialog export-dialog" role="dialog" aria-modal="true" aria-labelledby="exportSetupTitle">
@@ -581,6 +609,19 @@
581
609
  <tr><td><b>Templates</b> tab</td><td>Drag a lower third, logo animation or social layout onto the timeline (or click +) · fill in its fields in the Inspector's <b>Template</b> section · right-click a comp → <b>Save as template</b></td></tr>
582
610
  </table>
583
611
  </section>
612
+ <section class="keys-sec">
613
+ <h3>Projects <span>top bar → Projects</span></h3>
614
+ <table class="keys">
615
+ <tr><td><kbd>Ctrl/Cmd</kbd>+<kbd>O</kbd></td><td>Open the Projects dashboard (or click the project name)</td></tr>
616
+ <tr><td><kbd>Ctrl/Cmd</kbd>+<kbd>S</kbd></td><td>Save a version of the open project (every edit is saved anyway; a version is a point to come back to)</td></tr>
617
+ <tr><td>Project → <b>Versions…</b></td><td>Compare a version with now · <b>Restore…</b> (click twice; what is there is saved as a version first) · mark the final cut</td></tr>
618
+ <tr><td>Timeline toolbar → <b>sequence menu</b></td><td>Open another sequence of this project · <b>New sequence…</b> (any canvas, empty or a copy) · <b>Duplicate</b> · <b>Rename…</b> · <b>Delete…</b> (click twice; kept as a version first)</td></tr>
619
+ <tr><td>Project card</td><td>Click to see its details, notes and tags · double-click to open it</td></tr>
620
+ <tr><td><kbd>Enter</kbd> on a card</td><td>Open that project</td></tr>
621
+ <tr><td><kbd>Esc</kbd></td><td>Back out of <b>New project</b>, then close the dashboard</td></tr>
622
+ <tr><td><b>Delete…</b> (Archived)</td><td>Click twice — only archived projects can be deleted</td></tr>
623
+ </table>
624
+ </section>
584
625
  <section class="keys-sec">
585
626
  <h3>Color workspace</h3>
586
627
  <table class="keys">
@@ -630,9 +671,11 @@
630
671
  <script src="color.js"></script>
631
672
  <script src="edit-ops.js"></script>
632
673
  <script src="comp.js"></script>
674
+ <script src="sequences.js"></script>
633
675
  <script src="templates.js"></script>
634
676
  <script src="media-lib.js"></script>
635
677
  <script src="delivery.js"></script>
678
+ <script src="mp4-demux.js"></script>
636
679
  <script src="app.js"></script>
637
680
  </body>
638
681
  </html>