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/CLAUDE.md +239 -6
- package/README.md +3 -0
- package/app.js +1105 -36
- package/comp.js +5 -1
- package/encode-profiles.js +9 -3
- package/encoding-profiles.json +26 -0
- package/history.js +341 -0
- package/index.html +43 -0
- package/mcp-server.js +139 -4
- package/media-lib.js +14 -3
- package/mp4-demux.js +256 -0
- package/package.json +1 -1
- package/project-ops.js +76 -8
- package/projects.js +324 -0
- package/sequences.js +216 -0
- package/server.js +116 -1
- package/style.css +256 -0
package/project-ops.js
CHANGED
|
@@ -29,10 +29,10 @@
|
|
|
29
29
|
const api = factory(dep("./audio-fx", "FableCutFx"), dep("./edit-ops", "FableCutEdit"), dep("./color", "FableCutColor"),
|
|
30
30
|
dep("./mask", "FableCutMask"), dep("./tracker", "FableCutTracker"), dep("./motion", "FableCutMotion"),
|
|
31
31
|
dep("./comp", "FableCutComp"), dep("./templates", "FableCutTemplates"), dep("./media-lib", "FableCutMedia"),
|
|
32
|
-
dep("./delivery", "FableCutDelivery"));
|
|
32
|
+
dep("./delivery", "FableCutDelivery"), dep("./sequences", "FableCutSeq"));
|
|
33
33
|
if (node) module.exports = api;
|
|
34
34
|
else root.FableCutProjectOps = api;
|
|
35
|
-
})(typeof self !== "undefined" ? self : this, function (FX, EditOps, Color, Mask, Tracker, Motion, CompLib, Templates, MediaLib, Delivery) {
|
|
35
|
+
})(typeof self !== "undefined" ? self : this, function (FX, EditOps, Color, Mask, Tracker, Motion, CompLib, Templates, MediaLib, Delivery, SeqLib) {
|
|
36
36
|
"use strict";
|
|
37
37
|
|
|
38
38
|
const DEFAULT_TRACKS = EditOps.DEFAULT_TRACKS;
|
|
@@ -253,6 +253,7 @@
|
|
|
253
253
|
// props.shapes (shape layers) and clip.parent: validated like setShape / setParent
|
|
254
254
|
const NO_MEDIA = ["text", "adjust", "shape", "null", "comp"];
|
|
255
255
|
let inCompId = null; // set while an inComp op runs its ops inside a comp
|
|
256
|
+
let inSeqId = null; // set while an inSequence op runs its ops on a sequence that isn't open
|
|
256
257
|
// a comp clip names a comp that exists, and placing it here makes no loop
|
|
257
258
|
const checkCompClip = (c, label) => {
|
|
258
259
|
if (c.kind !== "comp") { if (c.compId != null) throw new Error(`${label}: compId is for kind:"comp" clips`); return; }
|
|
@@ -478,6 +479,7 @@
|
|
|
478
479
|
};
|
|
479
480
|
fit(proj.clips);
|
|
480
481
|
for (const comp of proj.comps || []) fit(comp.clips);
|
|
482
|
+
for (const seq of SeqLib.others(proj)) fit(seq.clips);
|
|
481
483
|
if (trimmed) note += ` (${trimmed} clip edge${trimmed === 1 ? "" : "s"} trimmed to the new file's ${m.duration}s)`;
|
|
482
484
|
}
|
|
483
485
|
notes.push(note);
|
|
@@ -490,6 +492,10 @@
|
|
|
490
492
|
const inner = (comp.clips || []).find((c) => c.mediaId === op.id);
|
|
491
493
|
if (inner) throw new Error(`removeMedia: media ${op.id} is used by clip ${inner.id} in comp ${comp.id}`);
|
|
492
494
|
}
|
|
495
|
+
for (const seq of SeqLib.others(proj)) {
|
|
496
|
+
const inner = (seq.clips || []).find((c) => c.mediaId === op.id);
|
|
497
|
+
if (inner) throw new Error(`removeMedia: media ${op.id} is used by clip ${inner.id} in sequence ${seq.id}`);
|
|
498
|
+
}
|
|
493
499
|
const n = proj.media.length;
|
|
494
500
|
proj.media = proj.media.filter((x) => x.id !== op.id);
|
|
495
501
|
if (proj.media.length === n) throw new Error("removeMedia: no media " + op.id);
|
|
@@ -791,7 +797,7 @@
|
|
|
791
797
|
const comp = CompLib.getComp(proj, op.id);
|
|
792
798
|
if (!comp) throw new Error("removeComp: no comp " + op.id);
|
|
793
799
|
const used = CompLib.usages(proj, comp.id);
|
|
794
|
-
if (used.length) throw new Error(`removeComp: ${comp.id} is used by ${used.map((u) => u.clip.id + (u.in ? ` (in ${u.in})` : "")).join(", ")} — remove those clips first`);
|
|
800
|
+
if (used.length) throw new Error(`removeComp: ${comp.id} is used by ${used.map((u) => u.clip.id + (u.in ? ` (in ${u.in})` : u.sequence ? ` (in sequence ${u.sequence})` : "")).join(", ")} — remove those clips first`);
|
|
795
801
|
proj.comps = proj.comps.filter((c) => c.id !== comp.id);
|
|
796
802
|
notes.push(`-comp ${comp.id}`);
|
|
797
803
|
break;
|
|
@@ -1027,8 +1033,63 @@
|
|
|
1027
1033
|
notes.push("-" + op.id);
|
|
1028
1034
|
break;
|
|
1029
1035
|
}
|
|
1036
|
+
case "addSequence": case "openSequence": case "updateSequence": case "removeSequence": case "inSequence": {
|
|
1037
|
+
// sequences: several timelines in one project; the open one is the top level (see sequences.js)
|
|
1038
|
+
const name = op.op;
|
|
1039
|
+
if (inSeqId && name !== "updateSequence") throw new Error(`${name} can't run inside inSequence — run it on its own`);
|
|
1040
|
+
if (name === "addSequence") {
|
|
1041
|
+
// {op:"addSequence", name?, id?, from?: "empty" | "open" | <id>, width?, height?, fps?, open?} (or those in sequence:{…})
|
|
1042
|
+
const src = op.sequence && typeof op.sequence === "object" ? op.sequence : {};
|
|
1043
|
+
const { op: _op, sequence: _s, open: _o, ...flat } = op;
|
|
1044
|
+
// a typo (widht, form) must not quietly make the wrong sequence
|
|
1045
|
+
for (const k of Object.keys({ ...flat, ...src })) if (!["id", "name", "from", "width", "height", "fps"].includes(k))
|
|
1046
|
+
throw new Error(`addSequence: '${k}' isn't a sequence setting (id, name, from, width, height, fps, open)`);
|
|
1047
|
+
let s;
|
|
1048
|
+
try { s = SeqLib.add(proj, { ...flat, ...src }); } catch (err) { throw new Error(err.message); }
|
|
1049
|
+
notes.push(`+sequence ${s.id} "${s.name}" ${s.width}x${s.height}@${s.fps}${s.clips.length ? ` (${s.clips.length} clips)` : ""}`);
|
|
1050
|
+
if (op.open) { SeqLib.open(proj, s.id); notes.push(`opened ${s.id}`); }
|
|
1051
|
+
break;
|
|
1052
|
+
}
|
|
1053
|
+
const seq = SeqLib.find(proj, op.id || op.sequence);
|
|
1054
|
+
if (!seq) throw new Error(`${name}: no sequence ${op.id || op.sequence} (${SeqLib.entries(proj).map((x) => x.id).join(", ")})`);
|
|
1055
|
+
if (name === "openSequence") {
|
|
1056
|
+
SeqLib.open(proj, seq.id);
|
|
1057
|
+
notes.push(`opened ${seq.id} "${seq.name}"`);
|
|
1058
|
+
} else if (name === "updateSequence") {
|
|
1059
|
+
const set = op.set || {};
|
|
1060
|
+
for (const k of Object.keys(set)) if (!["name", "index"].includes(k))
|
|
1061
|
+
throw new Error(`updateSequence: ${k} can't be set here (name, index) — set the canvas, frame rate and the rest with setProject, inside {op:"inSequence"} for one that isn't open`);
|
|
1062
|
+
try {
|
|
1063
|
+
if (set.name != null) SeqLib.rename(proj, seq.id, set.name);
|
|
1064
|
+
if (set.index != null) SeqLib.move(proj, seq.id, set.index);
|
|
1065
|
+
} catch (err) { throw new Error(`updateSequence: ${err.message}`); }
|
|
1066
|
+
notes.push(`~sequence ${seq.id}`);
|
|
1067
|
+
} else if (name === "removeSequence") {
|
|
1068
|
+
const wasOpen = SeqLib.activeId(proj) === seq.id;
|
|
1069
|
+
// a sequence holding the user's locked work goes only when they asked (force:true)
|
|
1070
|
+
const body = wasOpen ? proj : seq;
|
|
1071
|
+
const lockedLanes = new Set(Array.isArray(body.lockedTracks) ? body.lockedTracks : []);
|
|
1072
|
+
const hit = (body.clips || []).find((c) => c.locked === true || lockedLanes.has(c.track));
|
|
1073
|
+
refuseLocked("removeSequence", hit ? `sequence ${seq.id} holds locked clip ${hit.id}` : lockedLanes.size ? `sequence ${seq.id} has locked tracks (${[...lockedLanes].join(", ")})` : null, op);
|
|
1074
|
+
try { SeqLib.remove(proj, seq.id); } catch (err) { throw new Error(`removeSequence: ${err.message}`); }
|
|
1075
|
+
notes.push(`-sequence ${seq.id}` + (wasOpen ? ` (opened ${SeqLib.activeId(proj)})` : ""));
|
|
1076
|
+
} else {
|
|
1077
|
+
// {op:"inSequence", sequence, ops:[…]} — run ops on a sequence without opening it
|
|
1078
|
+
if (!Array.isArray(op.ops)) throw new Error("inSequence needs ops:[…]");
|
|
1079
|
+
if (inCompId) throw new Error("inSequence can't run inside inComp");
|
|
1080
|
+
const back = SeqLib.activeId(proj);
|
|
1081
|
+
SeqLib.open(proj, seq.id);
|
|
1082
|
+
inSeqId = seq.id;
|
|
1083
|
+
const n0 = notes.length;
|
|
1084
|
+
try { applyOps(op.ops); }
|
|
1085
|
+
finally { inSeqId = null; SeqLib.open(proj, back); }
|
|
1086
|
+
const inner = notes.splice(n0);
|
|
1087
|
+
notes.push(`${seq.id}{${inner.join(" ")}}`);
|
|
1088
|
+
}
|
|
1089
|
+
break;
|
|
1090
|
+
}
|
|
1030
1091
|
case "setProject": {
|
|
1031
|
-
const allowed =
|
|
1092
|
+
const allowed =["name", "width", "height", "fps", "background", "markers", "disabledTracks", "lockedTracks", "untargetedTracks", "exportFrame", "encodeProfile", "delivery", "outputs", "master", "inPoint", "outPoint"];
|
|
1032
1093
|
for (const [k, v] of Object.entries(op.set || {})) {
|
|
1033
1094
|
if (!allowed.includes(k)) throw new Error(`setProject: '${k}' not settable (allowed: ${allowed.join(", ")})`);
|
|
1034
1095
|
if ((k === "inPoint" || k === "outPoint") && v != null && (typeof v !== "number" || !Number.isFinite(v) || v < 0))
|
|
@@ -1083,7 +1144,8 @@
|
|
|
1083
1144
|
default:
|
|
1084
1145
|
throw new Error("Unknown op: " + op.op + " (addClip|updateClip|removeClip|addMedia|updateMedia|removeMedia|relinkMedia|replaceMedia|setCollection|removeCollection|setProject|setTrack|setBus|removeBus|setFx|setFxKeys|setGrade|setGradeLayer|setMask|removeMask|setMaskKeys|setMatte|removeTrack|setShape|removeShape|setParent|setMotionPath|setTextPath|" +
|
|
1085
1146
|
"split|rippleDelete|closeGap|lift|extract|rippleTrim|roll|slip|slide|insert|overwrite|crossfade|" +
|
|
1086
|
-
"addComp|updateComp|removeComp|precompose|inComp|applyPreset|addTemplate|setTemplate|savePreset|saveTemplate
|
|
1147
|
+
"addComp|updateComp|removeComp|precompose|inComp|applyPreset|addTemplate|setTemplate|savePreset|saveTemplate|" +
|
|
1148
|
+
"addSequence|openSequence|updateSequence|removeSequence|inSequence)");
|
|
1087
1149
|
}
|
|
1088
1150
|
} };
|
|
1089
1151
|
applyOps(ops);
|
|
@@ -1140,6 +1202,8 @@
|
|
|
1140
1202
|
(doc.untargetedTracks?.length ? ` untargetedTracks:[${doc.untargetedTracks.join(",")}]` : "") +
|
|
1141
1203
|
(doc.disabledTracks?.length ? ` disabledTracks:[${doc.disabledTracks.join(",")}]` : ""),
|
|
1142
1204
|
...mixLine(doc),
|
|
1205
|
+
...(SeqLib.entries(doc).length > 1 ? [`SEQUENCES (${SeqLib.entries(doc).length}) — this view is the open one; edit another with {op:"inSequence", sequence, ops:[…]} or open it with openSequence:`,
|
|
1206
|
+
...SeqLib.list(doc).map((r) => " " + SeqLib.describe(r))] : []),
|
|
1143
1207
|
`MEDIA (${doc.media.length}):`,
|
|
1144
1208
|
...(() => {
|
|
1145
1209
|
const uses = MediaLib.usageCounts(doc);
|
|
@@ -1209,9 +1273,12 @@
|
|
|
1209
1273
|
seen.add(comp.id);
|
|
1210
1274
|
}
|
|
1211
1275
|
}
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1276
|
+
if (doc.sequences != null || doc.sequence != null) {
|
|
1277
|
+
try { SeqLib.normalize(doc); } catch (err) { throw new Error(err.message); }
|
|
1278
|
+
}
|
|
1279
|
+
// the same checks for clips on the timeline, inside comps and in the sequences that aren't open
|
|
1280
|
+
const checkClip = (c, where, seq) => {
|
|
1281
|
+
const at = where ? `comp ${where}: ` : seq ? `sequence ${seq}: ` : "";
|
|
1215
1282
|
if (!c.id || !c.track || typeof c.start !== "number" || typeof c.duration !== "number")
|
|
1216
1283
|
throw new Error(`${at}clip ${c.id || "?"} needs id, track, numeric start and duration`);
|
|
1217
1284
|
if (!["text", "adjust", "shape", "null", "comp"].includes(c.kind) && !doc.media.some((m) => m.id === c.mediaId))
|
|
@@ -1227,6 +1294,7 @@
|
|
|
1227
1294
|
};
|
|
1228
1295
|
for (const c of doc.clips) checkClip(c, null);
|
|
1229
1296
|
for (const comp of doc.comps || []) for (const c of comp.clips) checkClip(c, comp.id);
|
|
1297
|
+
for (const seq of SeqLib.others(doc)) for (const c of seq.clips || []) checkClip(c, null, seq.id);
|
|
1230
1298
|
}
|
|
1231
1299
|
|
|
1232
1300
|
const TEXT_ONLY_NOTE = [
|
package/projects.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
/* ═══════════════════════════════════════════════════════════════════════════
|
|
2
|
+
Projects: several projects in one data folder.
|
|
3
|
+
|
|
4
|
+
./project.json stays THE open project — the editor, the MCP server, agents
|
|
5
|
+
and scripts all keep reading and writing that one file. Every project also
|
|
6
|
+
has its own folder:
|
|
7
|
+
|
|
8
|
+
projects/index.json {active: "<id>"}
|
|
9
|
+
projects/<id>/meta.json {id, created, opened, archived, notes, tags}
|
|
10
|
+
projects/<id>/project.json the document (stale while that project is open:
|
|
11
|
+
the live copy is ./project.json)
|
|
12
|
+
projects/<id>/thumb.jpg the editor's last picture of it
|
|
13
|
+
library/project-templates/<id>.json saved templates {name, created, project}
|
|
14
|
+
|
|
15
|
+
Opening another project parks ./project.json in the open project's folder,
|
|
16
|
+
then copies the chosen one over it with a revision above both, so a save
|
|
17
|
+
from an editor tab or agent that read the old project is refused (409 /
|
|
18
|
+
CONFLICT) instead of landing on the new one. media/, exports/ and analysis/
|
|
19
|
+
are shared, so a duplicate or a template copies no footage.
|
|
20
|
+
═══════════════════════════════════════════════════════════════════════════ */
|
|
21
|
+
"use strict";
|
|
22
|
+
const crypto = require("crypto");
|
|
23
|
+
const fs = require("fs");
|
|
24
|
+
const path = require("path");
|
|
25
|
+
|
|
26
|
+
/* Canvas presets offered next to the user's saved templates. */
|
|
27
|
+
const BUILTIN_TEMPLATES = [
|
|
28
|
+
{ id: "landscape-1080", name: "Landscape 16:9 · 1080p", width: 1920, height: 1080, fps: 30 },
|
|
29
|
+
{ id: "vertical-1080", name: "Vertical 9:16 · Reels, Shorts, TikTok", width: 1080, height: 1920, fps: 30 },
|
|
30
|
+
{ id: "square-1080", name: "Square 1:1", width: 1080, height: 1080, fps: 30 },
|
|
31
|
+
{ id: "portrait-1350", name: "Portrait 4:5 · feed post", width: 1080, height: 1350, fps: 30 },
|
|
32
|
+
{ id: "uhd-4k", name: "4K UHD 16:9", width: 3840, height: 2160, fps: 30 },
|
|
33
|
+
{ id: "landscape-720", name: "Landscape 16:9 · 720p", width: 1280, height: 720, fps: 30 },
|
|
34
|
+
];
|
|
35
|
+
const FPS_CHOICES = [23.976, 24, 25, 29.97, 30, 50, 59.94, 60];
|
|
36
|
+
const MAX_NOTES = 4000, MAX_TAGS = 12, MAX_NAME = 120;
|
|
37
|
+
|
|
38
|
+
const readJSON = (file) => JSON.parse(fs.readFileSync(file, "utf8").replace(/^/, ""));
|
|
39
|
+
function writeJSON(file, obj) {
|
|
40
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
41
|
+
// unique tmp: the editor and the MCP server may write at once
|
|
42
|
+
const tmp = `${file}.${crypto.randomUUID()}.tmp`;
|
|
43
|
+
fs.writeFileSync(tmp, JSON.stringify(obj, null, 2));
|
|
44
|
+
fs.renameSync(tmp, file);
|
|
45
|
+
}
|
|
46
|
+
const newId = () => "p_" + crypto.randomBytes(5).toString("hex");
|
|
47
|
+
const validId = (id) => typeof id === "string" && /^p_[a-z0-9]{4,24}$/.test(id);
|
|
48
|
+
const slug = (s) => String(s || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
|
|
49
|
+
const cleanName = (s) => String(s ?? "").replace(/[\u0000-\u001f]/g, " ").trim().slice(0, MAX_NAME);
|
|
50
|
+
function cleanTags(v) {
|
|
51
|
+
const list = Array.isArray(v) ? v : String(v ?? "").split(",");
|
|
52
|
+
const out = [];
|
|
53
|
+
for (const t of list) {
|
|
54
|
+
const s = String(t ?? "").trim().replace(/^#+/, "").trim().slice(0, 32);
|
|
55
|
+
if (s && !out.some((x) => x.toLowerCase() === s.toLowerCase())) out.push(s);
|
|
56
|
+
}
|
|
57
|
+
return out.slice(0, MAX_TAGS);
|
|
58
|
+
}
|
|
59
|
+
const timelineEnd = (doc) => (Array.isArray(doc.clips) ? doc.clips : [])
|
|
60
|
+
.reduce((m, c) => Math.max(m, (+c.start || 0) + (+c.duration || 0)), 0);
|
|
61
|
+
const blankProject = (name, t) => ({
|
|
62
|
+
name, width: t.width, height: t.height, fps: t.fps, revision: 0, media: [], clips: [],
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
function createProjects({ dataDir, projectFile, libraryDir }) {
|
|
66
|
+
const DIR = path.join(dataDir, "projects");
|
|
67
|
+
const INDEX = path.join(DIR, "index.json");
|
|
68
|
+
const TEMPLATES = path.join(libraryDir, "project-templates");
|
|
69
|
+
const folder = (id) => path.join(DIR, id);
|
|
70
|
+
const metaFile = (id) => path.join(folder(id), "meta.json");
|
|
71
|
+
const docFile = (id) => path.join(folder(id), "project.json");
|
|
72
|
+
const thumbFile = (id) => path.join(folder(id), "thumb.jpg");
|
|
73
|
+
|
|
74
|
+
const readRoot = () => {
|
|
75
|
+
try { return readJSON(projectFile); }
|
|
76
|
+
catch (e) { throw new Error(`project.json can't be read (${e.message}) — fix or replace it before switching projects`); }
|
|
77
|
+
};
|
|
78
|
+
const readMeta = (id) => { try { return readJSON(metaFile(id)); } catch { return null; } };
|
|
79
|
+
const writeMeta = (id, meta) => writeJSON(metaFile(id), meta);
|
|
80
|
+
const exists = (id) => validId(id) && fs.existsSync(metaFile(id));
|
|
81
|
+
|
|
82
|
+
/* The open project's id. The first call gives the existing ./project.json
|
|
83
|
+
a folder of its own, so a data folder from before projects just works. */
|
|
84
|
+
function activeId() {
|
|
85
|
+
let id = null;
|
|
86
|
+
try { id = readJSON(INDEX).active; } catch { }
|
|
87
|
+
if (exists(id)) return id;
|
|
88
|
+
id = newId();
|
|
89
|
+
let created = new Date().toISOString();
|
|
90
|
+
try { created = fs.statSync(projectFile).mtime.toISOString(); } catch { }
|
|
91
|
+
writeMeta(id, { id, created, opened: new Date().toISOString(), archived: false, notes: "", tags: [] });
|
|
92
|
+
writeJSON(INDEX, { active: id });
|
|
93
|
+
return id;
|
|
94
|
+
}
|
|
95
|
+
/* The open project's id without creating anything (null before the first dashboard use). */
|
|
96
|
+
function peekActive() {
|
|
97
|
+
try { const id = readJSON(INDEX).active; return exists(id) ? id : null; } catch { return null; }
|
|
98
|
+
}
|
|
99
|
+
const mustExist = (id) => {
|
|
100
|
+
if (!exists(id)) throw new Error(`no project ${JSON.stringify(id)} (fablecut_projects {action:"list"} lists them)`);
|
|
101
|
+
};
|
|
102
|
+
/* The document of a project: ./project.json for the open one. */
|
|
103
|
+
const readDoc = (id) => (id === activeId() ? readRoot() : readJSON(docFile(id)));
|
|
104
|
+
const writeDoc = (id, doc) => {
|
|
105
|
+
if (id !== activeId()) { writeJSON(docFile(id), doc); return; }
|
|
106
|
+
// the open project: bump the revision like any other save, so tabs reload
|
|
107
|
+
const cur = readRoot();
|
|
108
|
+
writeJSON(projectFile, { ...doc, revision: Math.max(cur.revision || 0, doc.revision || 0) + 1 });
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
function summary(id, active) {
|
|
112
|
+
const meta = readMeta(id) || { id };
|
|
113
|
+
let doc = null, modified = null;
|
|
114
|
+
const file = id === active ? projectFile : docFile(id);
|
|
115
|
+
try { doc = readJSON(file); modified = fs.statSync(file).mtime.toISOString(); } catch { }
|
|
116
|
+
let thumb = null;
|
|
117
|
+
try { thumb = Math.round(fs.statSync(thumbFile(id)).mtimeMs); } catch { }
|
|
118
|
+
return {
|
|
119
|
+
id, name: doc?.name || "Untitled Project", active: id === active,
|
|
120
|
+
archived: !!meta.archived, notes: meta.notes || "", tags: meta.tags || [],
|
|
121
|
+
created: meta.created || null, opened: meta.opened || null, modified,
|
|
122
|
+
width: doc?.width ?? null, height: doc?.height ?? null, fps: doc?.fps ?? null,
|
|
123
|
+
duration: doc ? +timelineEnd(doc).toFixed(2) : null,
|
|
124
|
+
clips: doc?.clips?.length ?? 0, media: doc?.media?.length ?? 0,
|
|
125
|
+
thumb, unreadable: !doc,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function list({ archived = "exclude" } = {}) {
|
|
130
|
+
const active = activeId();
|
|
131
|
+
let ids = [];
|
|
132
|
+
try { ids = fs.readdirSync(DIR, { withFileTypes: true }).filter((e) => e.isDirectory() && exists(e.name)).map((e) => e.name); } catch { }
|
|
133
|
+
let projects = ids.map((id) => summary(id, active));
|
|
134
|
+
if (archived === "exclude") projects = projects.filter((p) => !p.archived || p.active);
|
|
135
|
+
else if (archived === "only") projects = projects.filter((p) => p.archived);
|
|
136
|
+
projects.sort((a, b) => String(b.opened || b.modified || "").localeCompare(String(a.opened || a.modified || "")));
|
|
137
|
+
return { active, projects };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/* Park the open project in its folder, then put `id` in ./project.json. */
|
|
141
|
+
function open(id) {
|
|
142
|
+
mustExist(id);
|
|
143
|
+
const cur = activeId();
|
|
144
|
+
if (id === cur) return { id, already: true, project: summary(id, cur) };
|
|
145
|
+
const root = readRoot();
|
|
146
|
+
let next;
|
|
147
|
+
try { next = readJSON(docFile(id)); }
|
|
148
|
+
catch (e) { throw new Error(`project ${id} can't be read (${e.message})`); }
|
|
149
|
+
writeJSON(docFile(cur), root);
|
|
150
|
+
next.revision = Math.max(root.revision || 0, next.revision || 0) + 1;
|
|
151
|
+
try {
|
|
152
|
+
writeJSON(projectFile, next);
|
|
153
|
+
writeJSON(INDEX, { active: id });
|
|
154
|
+
} catch (e) {
|
|
155
|
+
// ./project.json and index.json must agree: put the open project back
|
|
156
|
+
try { writeJSON(projectFile, { ...root, revision: next.revision + 1 }); } catch { }
|
|
157
|
+
throw new Error(`switching to ${id} failed (${e.message}) — ${cur} is still open`);
|
|
158
|
+
}
|
|
159
|
+
const meta = readMeta(id) || { id };
|
|
160
|
+
writeMeta(id, { ...meta, opened: new Date().toISOString(), archived: false });
|
|
161
|
+
return { id, from: cur, project: summary(id, id) };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function add(doc, { name, notes, tags, template } = {}) {
|
|
165
|
+
const id = newId();
|
|
166
|
+
const now = new Date().toISOString();
|
|
167
|
+
const out = { ...doc, name: cleanName(name) || doc.name || "Untitled Project", revision: 0 };
|
|
168
|
+
writeJSON(docFile(id), out);
|
|
169
|
+
const meta = { id, created: now, opened: null, archived: false, notes: String(notes || "").slice(0, MAX_NOTES), tags: cleanTags(tags) };
|
|
170
|
+
if (template) meta.template = template;
|
|
171
|
+
writeMeta(id, meta);
|
|
172
|
+
return id;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function findTemplate(tid) {
|
|
176
|
+
const b = BUILTIN_TEMPLATES.find((t) => t.id === tid);
|
|
177
|
+
if (b) return { builtin: true, ...b };
|
|
178
|
+
const s = templates().find((t) => t.id === tid);
|
|
179
|
+
if (!s) throw new Error(`no project template ${JSON.stringify(tid)} (built-in: ${BUILTIN_TEMPLATES.map((t) => t.id).join(", ")}${templates().some((t) => !t.builtin) ? "; saved: " + templates().filter((t) => !t.builtin).map((t) => t.id).join(", ") : ""})`);
|
|
180
|
+
return s;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/* A new project from a template (default: 1080p landscape), optionally opened. */
|
|
184
|
+
function create({ name, template = "landscape-1080", fps, width, height, notes, tags, open: andOpen = true } = {}) {
|
|
185
|
+
const t = findTemplate(template);
|
|
186
|
+
let doc;
|
|
187
|
+
if (t.builtin) doc = blankProject("", t);
|
|
188
|
+
else doc = structuredClone(readJSON(path.join(TEMPLATES, t.id + ".json")).project);
|
|
189
|
+
if (fps != null) {
|
|
190
|
+
if (!(Number(fps) > 0 && Number(fps) <= 120)) throw new Error("fps must be a frame rate between 1 and 120");
|
|
191
|
+
doc.fps = Number(fps);
|
|
192
|
+
}
|
|
193
|
+
for (const [k, v] of [["width", width], ["height", height]]) {
|
|
194
|
+
if (v == null) continue;
|
|
195
|
+
if (!Number.isInteger(v) || v < 16 || v > 8192 || v % 2) throw new Error(`${k} must be an even number of pixels, 16…8192`);
|
|
196
|
+
doc[k] = v;
|
|
197
|
+
}
|
|
198
|
+
const id = add(doc, { name: cleanName(name) || "Untitled Project", notes, tags, template: t.id });
|
|
199
|
+
return andOpen ? open(id) : { id, project: summary(id, activeId()) };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function duplicate(id, { name, open: andOpen = false } = {}) {
|
|
203
|
+
mustExist(id);
|
|
204
|
+
const src = readDoc(id);
|
|
205
|
+
const meta = readMeta(id) || {};
|
|
206
|
+
const nid = add(structuredClone(src), { name: cleanName(name) || `${src.name || "Untitled Project"} copy`, notes: meta.notes, tags: meta.tags });
|
|
207
|
+
try { fs.copyFileSync(thumbFile(id), thumbFile(nid)); } catch { }
|
|
208
|
+
return andOpen ? open(nid) : { id: nid, project: summary(nid, activeId()) };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/* Rename / notes / tags. */
|
|
212
|
+
function update(id, { name, notes, tags } = {}) {
|
|
213
|
+
mustExist(id);
|
|
214
|
+
if (name != null) {
|
|
215
|
+
const n = cleanName(name);
|
|
216
|
+
if (!n) throw new Error("name can't be empty");
|
|
217
|
+
const doc = readDoc(id);
|
|
218
|
+
if (doc.name !== n) writeDoc(id, { ...doc, name: n });
|
|
219
|
+
}
|
|
220
|
+
if (notes != null || tags != null) {
|
|
221
|
+
const meta = readMeta(id) || { id };
|
|
222
|
+
if (notes != null) meta.notes = String(notes).slice(0, MAX_NOTES);
|
|
223
|
+
if (tags != null) meta.tags = cleanTags(tags);
|
|
224
|
+
writeMeta(id, meta);
|
|
225
|
+
}
|
|
226
|
+
return { id, project: summary(id, activeId()) };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function archive(id, on = true) {
|
|
230
|
+
mustExist(id);
|
|
231
|
+
if (on && id === activeId()) throw new Error("the open project can't be archived — open another project first");
|
|
232
|
+
writeMeta(id, { ...(readMeta(id) || { id }), archived: !!on });
|
|
233
|
+
return { id, project: summary(id, activeId()) };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/* Deleting is for archived projects only, so it always takes two steps. */
|
|
237
|
+
function remove(id) {
|
|
238
|
+
mustExist(id);
|
|
239
|
+
if (id === activeId()) throw new Error("the open project can't be deleted");
|
|
240
|
+
if (!readMeta(id)?.archived) throw new Error("archive the project first — only archived projects can be deleted");
|
|
241
|
+
fs.rmSync(folder(id), { recursive: true, force: true });
|
|
242
|
+
return { id, deleted: true };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/* A project file from elsewhere (an old backup, another machine). */
|
|
246
|
+
function importDoc(doc, { name, open: andOpen = false } = {}) {
|
|
247
|
+
if (!doc || typeof doc !== "object" || !Array.isArray(doc.clips) || !Array.isArray(doc.media))
|
|
248
|
+
throw new Error("not a FableCut project (it needs clips and media arrays)");
|
|
249
|
+
const id = add(structuredClone(doc), { name: cleanName(name) || doc.name });
|
|
250
|
+
return andOpen ? open(id) : { id, project: summary(id, activeId()) };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function templates() {
|
|
254
|
+
const out = BUILTIN_TEMPLATES.map((t) => ({ ...t, builtin: true, clips: 0 }));
|
|
255
|
+
let files = [];
|
|
256
|
+
try { files = fs.readdirSync(TEMPLATES).filter((f) => f.toLowerCase().endsWith(".json")).sort(); } catch { }
|
|
257
|
+
for (const f of files) {
|
|
258
|
+
try {
|
|
259
|
+
const t = readJSON(path.join(TEMPLATES, f));
|
|
260
|
+
const p = t.project || {};
|
|
261
|
+
out.push({ id: f.slice(0, -5), name: t.name || f.slice(0, -5), builtin: false, created: t.created || null,
|
|
262
|
+
width: p.width, height: p.height, fps: p.fps, clips: (p.clips || []).length, duration: +timelineEnd(p).toFixed(2) });
|
|
263
|
+
} catch { }
|
|
264
|
+
}
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/* Save a project — its canvas, tracks, clips and media references — as a template. */
|
|
269
|
+
function saveTemplate(id, { name } = {}) {
|
|
270
|
+
mustExist(id);
|
|
271
|
+
const doc = structuredClone(readDoc(id));
|
|
272
|
+
const label = cleanName(name) || doc.name || "Template";
|
|
273
|
+
const tid = slug(label);
|
|
274
|
+
if (!tid) throw new Error("name the template (letters or digits)");
|
|
275
|
+
if (BUILTIN_TEMPLATES.some((t) => t.id === tid)) throw new Error(`"${label}" is a built-in template — pick another name`);
|
|
276
|
+
delete doc.revision;
|
|
277
|
+
writeJSON(path.join(TEMPLATES, tid + ".json"), { name: label, created: new Date().toISOString(), project: doc });
|
|
278
|
+
return { template: templates().find((t) => t.id === tid) };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function deleteTemplate(tid) {
|
|
282
|
+
if (BUILTIN_TEMPLATES.some((t) => t.id === tid)) throw new Error("built-in templates can't be deleted");
|
|
283
|
+
const file = path.join(TEMPLATES, slug(tid) + ".json");
|
|
284
|
+
if (!slug(tid) || !fs.existsSync(file)) throw new Error(`no saved template ${JSON.stringify(tid)}`);
|
|
285
|
+
fs.unlinkSync(file);
|
|
286
|
+
return { template: tid, deleted: true };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function setThumb(id, buf) {
|
|
290
|
+
mustExist(id);
|
|
291
|
+
if (!Buffer.isBuffer(buf) || buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) throw new Error("thumbnail must be a JPEG");
|
|
292
|
+
if (buf.length > 1024 * 1024) throw new Error("thumbnail too large (1 MB max)");
|
|
293
|
+
const tmp = `${thumbFile(id)}.${crypto.randomUUID()}.tmp`;
|
|
294
|
+
fs.writeFileSync(tmp, buf);
|
|
295
|
+
fs.renameSync(tmp, thumbFile(id));
|
|
296
|
+
return { id, ok: true };
|
|
297
|
+
}
|
|
298
|
+
const thumbPath = (id) => (exists(id) && fs.existsSync(thumbFile(id)) ? thumbFile(id) : null);
|
|
299
|
+
|
|
300
|
+
/* One entry point for the REST API and the MCP tool. */
|
|
301
|
+
function act(a = {}) {
|
|
302
|
+
switch (a.action) {
|
|
303
|
+
case "list": return { ...list({ archived: a.archived }), templates: templates() };
|
|
304
|
+
case "open": return open(a.id);
|
|
305
|
+
case "new": return create(a);
|
|
306
|
+
case "duplicate": return duplicate(a.id, a);
|
|
307
|
+
case "update": case "rename": return update(a.id, a);
|
|
308
|
+
case "archive": return archive(a.id, true);
|
|
309
|
+
case "unarchive": return archive(a.id, false);
|
|
310
|
+
case "delete": return remove(a.id);
|
|
311
|
+
case "import": return importDoc(a.project, a);
|
|
312
|
+
case "templates": return { templates: templates() };
|
|
313
|
+
case "save_template": return saveTemplate(a.id, a);
|
|
314
|
+
case "delete_template": return deleteTemplate(a.template);
|
|
315
|
+
default:
|
|
316
|
+
throw new Error(`unknown action ${JSON.stringify(a.action)} (list|open|new|duplicate|update|archive|unarchive|delete|import|templates|save_template|delete_template)`);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
return { DIR, INDEX, TEMPLATES, activeId, peekActive, mustExist, readRoot, readDoc, writeDoc, list, open, create, duplicate, update, archive, remove, importDoc,
|
|
321
|
+
templates, saveTemplate, deleteTemplate, setThumb, thumbPath, act };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
module.exports = { createProjects, BUILTIN_TEMPLATES, FPS_CHOICES };
|