@morshoto/framekit 0.1.13 → 0.1.16

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.
Files changed (30) hide show
  1. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +28 -0
  2. package/dist-package/adapters/final-cut/typescript/src/canonical.js +144 -35
  3. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +36 -7
  4. package/dist-package/adapters/final-cut/typescript/src/index.js +2 -0
  5. package/dist-package/adapters/final-cut/typescript/src/live.js +56 -1
  6. package/dist-package/adapters/final-cut/typescript/src/native.js +311 -20
  7. package/dist-package/adapters/final-cut/typescript/src/pasteboard-snapshot.js +312 -0
  8. package/dist-package/adapters/final-cut/typescript/src/publisher.js +68 -8
  9. package/dist-package/adapters/final-cut/typescript/src/sqlite-wal-observation.js +263 -0
  10. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +75 -3
  11. package/dist-package/adapters/headless/typescript/src/ffmpeg-media-probe.js +62 -0
  12. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +443 -0
  13. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +181 -0
  14. package/dist-package/adapters/headless/typescript/src/index.js +3 -0
  15. package/dist-package/apps/mcp-server/src/headless-projects.js +139 -0
  16. package/dist-package/apps/mcp-server/src/headless-sessions.js +3 -0
  17. package/dist-package/apps/mcp-server/src/main.js +22 -1
  18. package/dist-package/apps/mcp-server/src/materialization-jobs.js +233 -4
  19. package/dist-package/apps/mcp-server/src/readback-policy.js +26 -0
  20. package/dist-package/apps/mcp-server/src/routing.js +134 -5
  21. package/dist-package/apps/mcp-server/src/server.js +214 -31
  22. package/dist-package/packages/runtime/src/application/local-media.js +157 -0
  23. package/dist-package/packages/runtime/src/application/project-store.js +234 -0
  24. package/dist-package/packages/runtime/src/application/project-transactions.js +227 -0
  25. package/dist-package/packages/runtime/src/index.js +6 -0
  26. package/dist-package/packages/runtime/src/render/render-and-verify.js +126 -0
  27. package/dist-package/packages/runtime/src/render/render-contract.js +143 -0
  28. package/dist-package/packages/runtime/src/timeline/editing-session.js +277 -9
  29. package/dist-package/packages/runtime/src/timeline/fast-observation.js +141 -0
  30. package/package.json +2 -1
@@ -0,0 +1,157 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createReadStream } from "node:fs";
3
+ import { lstat } from "node:fs/promises";
4
+ import { basename, resolve } from "node:path";
5
+ export class LocalMediaError extends Error {
6
+ code;
7
+ details;
8
+ constructor(code, message, details) {
9
+ super(`${code}: ${message}`);
10
+ this.name = "LocalMediaError";
11
+ this.code = code;
12
+ this.details = details;
13
+ }
14
+ }
15
+ export class LocalMediaRegistrar {
16
+ store;
17
+ metadataProbe;
18
+ clock;
19
+ constructor(store, metadataProbe, options = {}) {
20
+ this.store = store;
21
+ this.metadataProbe = metadataProbe;
22
+ this.clock = options.clock ?? (() => new Date().toISOString());
23
+ }
24
+ async register(sourcePath, expectedRevision) {
25
+ const source = await inspectLocalFile(sourcePath);
26
+ const digest = await digestFile(source.path);
27
+ await assertStableSource(source, digest);
28
+ const project = await this.store.load();
29
+ if (expectedRevision && !sameRevision(project.timeline.revision, expectedRevision)) {
30
+ throw new LocalMediaError("MEDIA_CHANGED", "project revision changed before media registration", {
31
+ expectedRevision,
32
+ actualRevision: project.timeline.revision,
33
+ });
34
+ }
35
+ const existing = project.timeline.resources.find((resource) => resource.source === source.path);
36
+ if (existing) {
37
+ if (existing.sourceDigest !== digest) {
38
+ throw new LocalMediaError("MEDIA_CHANGED", `registered source changed: ${source.path}`, {
39
+ id: existing.id,
40
+ source: source.path,
41
+ expectedDigest: existing.sourceDigest,
42
+ actualDigest: digest,
43
+ });
44
+ }
45
+ await assertStableSource(source, digest);
46
+ return { status: "already-registered", project, resource: structuredClone(existing) };
47
+ }
48
+ const metadata = await this.metadataProbe.probe(source.path);
49
+ await assertStableSource(source, digest);
50
+ const resource = {
51
+ id: stableMediaId(source.path, digest),
52
+ name: basename(source.path),
53
+ mediaKind: metadata.streams.some((stream) => stream.kind === "video") ? "video" : "audio",
54
+ source: source.path,
55
+ sourceKind: "local-file",
56
+ sourceDigest: digest,
57
+ metadata: structuredClone(metadata),
58
+ };
59
+ const next = structuredClone(project);
60
+ next.timeline.resources.push(resource);
61
+ const timestamp = this.clock();
62
+ next.timeline.revision = nextRevision(project.timeline.revision, timestamp);
63
+ next.metadata.updatedAt = timestamp;
64
+ const saved = await this.store.save(next, project.timeline.revision);
65
+ return { status: "registered", project: saved, resource: structuredClone(resource) };
66
+ }
67
+ async inspect(project) {
68
+ const loadedProject = project ?? await this.store.load();
69
+ const results = [];
70
+ for (const resource of loadedProject.timeline.resources) {
71
+ if (resource.sourceKind !== "local-file" || !resource.source || !resource.sourceDigest)
72
+ continue;
73
+ try {
74
+ const source = await inspectLocalFile(resource.source);
75
+ const actualDigest = await digestFile(source.path);
76
+ await assertStableSource(source, actualDigest);
77
+ results.push(actualDigest === resource.sourceDigest
78
+ ? { id: resource.id, source: source.path, status: "available", expectedDigest: resource.sourceDigest, actualDigest }
79
+ : { id: resource.id, source: source.path, status: "changed", expectedDigest: resource.sourceDigest, actualDigest });
80
+ }
81
+ catch (error) {
82
+ if (error instanceof LocalMediaError && error.code === "MEDIA_MISSING") {
83
+ results.push({ id: resource.id, source: resource.source, status: "missing", expectedDigest: resource.sourceDigest });
84
+ continue;
85
+ }
86
+ throw error;
87
+ }
88
+ }
89
+ return results;
90
+ }
91
+ async reopen() {
92
+ const project = await this.store.load();
93
+ const statuses = await this.inspect(project);
94
+ const invalid = statuses.find((status) => status.status !== "available");
95
+ if (invalid?.status === "missing") {
96
+ throw new LocalMediaError("MEDIA_MISSING", `registered source is missing: ${invalid.source}`, { media: statuses });
97
+ }
98
+ if (invalid?.status === "changed") {
99
+ throw new LocalMediaError("MEDIA_CHANGED", `registered source changed: ${invalid.source}`, { media: statuses });
100
+ }
101
+ return project;
102
+ }
103
+ }
104
+ async function inspectLocalFile(sourcePath) {
105
+ const path = resolve(sourcePath);
106
+ let details;
107
+ try {
108
+ details = await lstat(path);
109
+ }
110
+ catch (error) {
111
+ if (error.code === "ENOENT") {
112
+ throw new LocalMediaError("MEDIA_MISSING", `local source does not exist: ${path}`, { source: path });
113
+ }
114
+ throw error;
115
+ }
116
+ if (!details.isFile() || details.isSymbolicLink()) {
117
+ throw new LocalMediaError("MEDIA_AMBIGUOUS", `local source is not a regular file: ${path}`, { source: path });
118
+ }
119
+ return { path, device: details.dev, inode: details.ino, size: details.size, mtimeMs: details.mtimeMs, ctimeMs: details.ctimeMs };
120
+ }
121
+ async function assertStableSource(identity, expectedDigest) {
122
+ const current = await inspectLocalFile(identity.path);
123
+ if (current.device !== identity.device
124
+ || current.inode !== identity.inode
125
+ || current.size !== identity.size
126
+ || current.mtimeMs !== identity.mtimeMs
127
+ || current.ctimeMs !== identity.ctimeMs
128
+ || await digestFile(current.path) !== expectedDigest) {
129
+ throw new LocalMediaError("MEDIA_CHANGED", `local source changed during registration: ${identity.path}`, {
130
+ source: identity.path,
131
+ expectedDigest,
132
+ });
133
+ }
134
+ }
135
+ async function digestFile(path) {
136
+ const digest = createHash("sha256");
137
+ await new Promise((resolvePromise, reject) => {
138
+ const stream = createReadStream(path);
139
+ stream.on("data", (chunk) => digest.update(chunk));
140
+ stream.once("error", reject);
141
+ stream.once("end", resolvePromise);
142
+ });
143
+ return digest.digest("hex");
144
+ }
145
+ function stableMediaId(path, digest) {
146
+ return `local-media:${createHash("sha256").update(`${path}\0${digest}`).digest("hex")}`;
147
+ }
148
+ function sameRevision(left, right) {
149
+ return left.id === right.id && left.sequence === right.sequence;
150
+ }
151
+ function nextRevision(previous, timestamp) {
152
+ return {
153
+ id: `revision-${createHash("sha256").update(`${previous.id}\0${previous.sequence + 1}\0${timestamp}`).digest("hex")}`,
154
+ sequence: previous.sequence + 1,
155
+ timestamp,
156
+ };
157
+ }
@@ -0,0 +1,234 @@
1
+ import { mkdir as nodeMkdir, readFile as nodeReadFile, rename as nodeRename, unlink as nodeUnlink, writeFile as nodeWriteFile } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { validateTimelineIr } from "../timeline/editing-session.js";
5
+ export const FRAMEKIT_PROJECT_SCHEMA_VERSION = 1;
6
+ export class ProjectPersistenceError extends Error {
7
+ code;
8
+ details;
9
+ constructor(code, message, details, options) {
10
+ super(`${code}: ${message}`, options);
11
+ this.name = "ProjectPersistenceError";
12
+ this.code = code;
13
+ this.details = details;
14
+ }
15
+ }
16
+ const fileSystem = {
17
+ mkdir: async (path, options) => { await nodeMkdir(path, options); },
18
+ readFile: async (path, encoding) => nodeReadFile(path, encoding),
19
+ writeFile: async (path, data, options) => { await nodeWriteFile(path, data, options); },
20
+ rename: async (from, to) => { await nodeRename(from, to); },
21
+ unlink: async (path) => { await nodeUnlink(path); },
22
+ };
23
+ export class FramekitProjectStore {
24
+ path;
25
+ fs;
26
+ constructor(path, fs = fileSystem) {
27
+ this.path = path;
28
+ this.fs = fs;
29
+ }
30
+ async create(project) {
31
+ return this.withProjectLock(async () => {
32
+ try {
33
+ await this.fs.readFile(this.path, "utf8");
34
+ throw new ProjectPersistenceError("PROJECT_ALREADY_EXISTS", `project file already exists: ${this.path}`);
35
+ }
36
+ catch (error) {
37
+ if (error instanceof ProjectPersistenceError)
38
+ throw error;
39
+ if (!isMissingFile(error))
40
+ throw error;
41
+ }
42
+ return this.saveUnlocked(project);
43
+ });
44
+ }
45
+ async load() {
46
+ let raw;
47
+ try {
48
+ raw = await this.fs.readFile(this.path, "utf8");
49
+ }
50
+ catch (error) {
51
+ if (isMissingFile(error)) {
52
+ throw new ProjectPersistenceError("PROJECT_NOT_FOUND", `project file does not exist: ${this.path}`, { path: this.path }, { cause: error });
53
+ }
54
+ throw new ProjectPersistenceError("PROJECT_CORRUPT", `project file could not be read: ${this.path}`, { path: this.path }, { cause: error });
55
+ }
56
+ try {
57
+ return decodeFramekitProject(raw);
58
+ }
59
+ catch (error) {
60
+ if (error instanceof ProjectPersistenceError)
61
+ throw error;
62
+ throw new ProjectPersistenceError("PROJECT_CORRUPT", `project file is invalid: ${this.path}`, { path: this.path }, { cause: error });
63
+ }
64
+ }
65
+ async save(project, expectedRevision) {
66
+ return this.withProjectLock(() => this.saveUnlocked(project, expectedRevision));
67
+ }
68
+ async saveUnlocked(project, expectedRevision) {
69
+ try {
70
+ validateFramekitProject(project);
71
+ }
72
+ catch (error) {
73
+ throw new ProjectPersistenceError("PROJECT_INVALID", "project does not satisfy the canonical schema", undefined, { cause: error });
74
+ }
75
+ if (expectedRevision) {
76
+ const current = await this.load();
77
+ if (!sameRevision(current.timeline.revision, expectedRevision)) {
78
+ throw new ProjectPersistenceError("PROJECT_STALE_REVISION", "expected project revision does not match the persisted project", { expectedRevision, actualRevision: current.timeline.revision });
79
+ }
80
+ }
81
+ const temporary = `${this.path}.${randomUUID()}.tmp`;
82
+ try {
83
+ await this.fs.mkdir(dirname(this.path), { recursive: true });
84
+ await this.fs.writeFile(temporary, `${encodeFramekitProject(project)}\n`, { encoding: "utf8", flag: "wx" });
85
+ await this.fs.rename(temporary, this.path);
86
+ return structuredClone(project);
87
+ }
88
+ catch (error) {
89
+ throw new ProjectPersistenceError("PROJECT_SAVE_FAILED", `atomic project write failed: ${this.path}`, { path: this.path }, { cause: error });
90
+ }
91
+ finally {
92
+ await this.removeTemporaryFile(temporary);
93
+ }
94
+ }
95
+ async withProjectLock(operation) {
96
+ await this.fs.mkdir(dirname(this.path), { recursive: true });
97
+ const lockPath = `${this.path}.lock`;
98
+ const deadline = Date.now() + 2_000;
99
+ while (true) {
100
+ try {
101
+ await this.fs.writeFile(lockPath, `${process.pid}\n`, { encoding: "utf8", flag: "wx" });
102
+ break;
103
+ }
104
+ catch (error) {
105
+ if (!isAlreadyExists(error)) {
106
+ throw new ProjectPersistenceError("PROJECT_SAVE_FAILED", `could not acquire project lock: ${this.path}`, { path: this.path }, { cause: error });
107
+ }
108
+ if (await this.removeStaleLock(lockPath))
109
+ continue;
110
+ if (Date.now() >= deadline) {
111
+ throw new ProjectPersistenceError("PROJECT_SAVE_FAILED", `could not acquire project lock: ${this.path}`, { path: this.path }, { cause: error });
112
+ }
113
+ await new Promise((resolve) => setTimeout(resolve, 5));
114
+ }
115
+ }
116
+ try {
117
+ return await operation();
118
+ }
119
+ finally {
120
+ await this.removeTemporaryFile(lockPath);
121
+ }
122
+ }
123
+ async removeStaleLock(lockPath) {
124
+ let owner;
125
+ try {
126
+ owner = await this.fs.readFile(lockPath, "utf8");
127
+ }
128
+ catch (error) {
129
+ return isMissingFile(error);
130
+ }
131
+ const pid = Number.parseInt(owner.trim(), 10);
132
+ if (!Number.isInteger(pid) || pid <= 0 || isProcessDead(pid)) {
133
+ try {
134
+ await this.fs.unlink(lockPath);
135
+ return true;
136
+ }
137
+ catch (error) {
138
+ return isMissingFile(error);
139
+ }
140
+ }
141
+ return false;
142
+ }
143
+ async removeTemporaryFile(path) {
144
+ try {
145
+ await this.fs.unlink(path);
146
+ }
147
+ catch (error) {
148
+ if (!isMissingFile(error))
149
+ throw error;
150
+ }
151
+ }
152
+ }
153
+ export function encodeFramekitProject(project) {
154
+ validateFramekitProject(project);
155
+ return stableJson(project);
156
+ }
157
+ export function decodeFramekitProject(input) {
158
+ let value;
159
+ try {
160
+ value = typeof input === "string" ? JSON.parse(input) : input;
161
+ }
162
+ catch (error) {
163
+ throw new ProjectPersistenceError("PROJECT_CORRUPT", "project JSON is malformed", undefined, { cause: error });
164
+ }
165
+ const record = asRecord(value);
166
+ if (!record)
167
+ throw new ProjectPersistenceError("PROJECT_CORRUPT", "project document must be an object");
168
+ if (record.schemaVersion !== FRAMEKIT_PROJECT_SCHEMA_VERSION) {
169
+ const code = typeof record.schemaVersion === "number" && record.schemaVersion > FRAMEKIT_PROJECT_SCHEMA_VERSION
170
+ ? "PROJECT_SCHEMA_UNSUPPORTED"
171
+ : "PROJECT_CORRUPT";
172
+ throw new ProjectPersistenceError(code, `unsupported project schema version: ${String(record.schemaVersion)}`, {
173
+ receivedSchemaVersion: record.schemaVersion,
174
+ supportedSchemaVersion: FRAMEKIT_PROJECT_SCHEMA_VERSION,
175
+ });
176
+ }
177
+ try {
178
+ validateFramekitProject(record);
179
+ }
180
+ catch (error) {
181
+ throw new ProjectPersistenceError("PROJECT_CORRUPT", "project document does not satisfy the canonical schema", undefined, { cause: error });
182
+ }
183
+ return structuredClone(record);
184
+ }
185
+ export function validateFramekitProject(project) {
186
+ if (!project || typeof project !== "object" || project.schemaVersion !== FRAMEKIT_PROJECT_SCHEMA_VERSION) {
187
+ throw new Error("PROJECT_INVALID: schemaVersion must be 1");
188
+ }
189
+ if (!project.metadata || typeof project.metadata !== "object")
190
+ throw new Error("PROJECT_INVALID: metadata is required");
191
+ requireText(project.metadata.createdAt, "metadata.createdAt");
192
+ requireText(project.metadata.updatedAt, "metadata.updatedAt");
193
+ validateTimelineIr(project.timeline);
194
+ }
195
+ function stableJson(value) {
196
+ if (value === undefined)
197
+ return "null";
198
+ if (value === null || typeof value !== "object")
199
+ return JSON.stringify(value);
200
+ if (Array.isArray(value))
201
+ return `[${value.map(stableJson).join(",")}]`;
202
+ const entries = Object.entries(value)
203
+ .filter(([, child]) => child !== undefined)
204
+ .sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
205
+ return `{${entries.map(([key, child]) => `${JSON.stringify(key)}:${stableJson(child)}`).join(",")}}`;
206
+ }
207
+ function asRecord(value) {
208
+ return value !== null && typeof value === "object" && !Array.isArray(value)
209
+ ? value
210
+ : undefined;
211
+ }
212
+ function requireText(value, field) {
213
+ if (typeof value !== "string" || !value.trim())
214
+ throw new Error(`PROJECT_INVALID: ${field} must be non-empty`);
215
+ }
216
+ function sameRevision(left, right) {
217
+ return left.id === right.id && left.sequence === right.sequence;
218
+ }
219
+ function isMissingFile(error) {
220
+ return typeof error === "object" && error !== null && error.code === "ENOENT";
221
+ }
222
+ function isAlreadyExists(error) {
223
+ return typeof error === "object" && error !== null && error.code === "EEXIST";
224
+ }
225
+ function isProcessDead(pid) {
226
+ try {
227
+ process.kill(pid, 0);
228
+ return false;
229
+ }
230
+ catch (error) {
231
+ const code = error.code;
232
+ return code !== "EPERM";
233
+ }
234
+ }
@@ -0,0 +1,227 @@
1
+ import { EditingSession, timelineIrDigest, } from "../timeline/editing-session.js";
2
+ import { ProjectPersistenceError, } from "./project-store.js";
3
+ export const PROJECT_EDIT_COMMAND_SCHEMA_VERSION = 1;
4
+ export class ProjectTransactionError extends Error {
5
+ code;
6
+ details;
7
+ constructor(code, message, details, options) {
8
+ super(`${code}: ${message}`, options);
9
+ this.name = "ProjectTransactionError";
10
+ this.code = code;
11
+ this.details = details;
12
+ }
13
+ }
14
+ export class ProjectTransactionService {
15
+ store;
16
+ clock;
17
+ constructor(store, options = {}) {
18
+ this.store = store;
19
+ this.clock = options.clock ?? (() => new Date().toISOString());
20
+ }
21
+ async preview(command) {
22
+ const project = await this.loadAndGuard(command);
23
+ try {
24
+ const session = EditingSession.create({ base: project.timeline, clock: this.clock });
25
+ const preview = session.preview(command.operations, command.expectedRevision);
26
+ return buildPreview(command, project, preview);
27
+ }
28
+ catch (error) {
29
+ throw this.invalid(error);
30
+ }
31
+ }
32
+ async execute(command) {
33
+ const project = await this.loadAndGuard(command);
34
+ let applied;
35
+ try {
36
+ const session = EditingSession.create({ base: project.timeline, clock: this.clock });
37
+ applied = session.apply(command.operations, command.expectedRevision);
38
+ }
39
+ catch (error) {
40
+ throw this.invalid(error);
41
+ }
42
+ if (applied.after.revision.sequence !== project.timeline.revision.sequence + 1) {
43
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", "successful edit did not advance the project revision exactly once", {
44
+ beforeRevision: project.timeline.revision,
45
+ afterRevision: applied.after.revision,
46
+ });
47
+ }
48
+ const next = structuredClone(project);
49
+ next.timeline = applied.after;
50
+ next.metadata.updatedAt = this.clock();
51
+ try {
52
+ const saved = await this.store.save(next, project.timeline.revision);
53
+ return {
54
+ ...buildPreview(command, project, applied),
55
+ after: saved,
56
+ committed: true,
57
+ };
58
+ }
59
+ catch (error) {
60
+ if (error instanceof ProjectPersistenceError && error.code === "PROJECT_STALE_REVISION") {
61
+ throw new ProjectTransactionError("PROJECT_EDIT_STALE_REVISION", "project became stale before the edit could commit", error.details, { cause: error });
62
+ }
63
+ throw error;
64
+ }
65
+ }
66
+ async loadAndGuard(command) {
67
+ validateCommand(command);
68
+ const project = await this.store.load();
69
+ if (project.timeline.project.id !== command.target.projectId || project.timeline.sequence.id !== command.target.sequenceId) {
70
+ throw new ProjectTransactionError("PROJECT_EDIT_TARGET_MISMATCH", "command target does not match the persisted project", {
71
+ expectedTarget: command.target,
72
+ actualTarget: { projectId: project.timeline.project.id, sequenceId: project.timeline.sequence.id },
73
+ });
74
+ }
75
+ if (!sameRevision(project.timeline.revision, command.expectedRevision)) {
76
+ throw new ProjectTransactionError("PROJECT_EDIT_STALE_REVISION", "expected project revision does not match the persisted project", {
77
+ expectedRevision: command.expectedRevision,
78
+ actualRevision: project.timeline.revision,
79
+ });
80
+ }
81
+ return project;
82
+ }
83
+ invalid(error) {
84
+ if (error instanceof ProjectTransactionError)
85
+ return error;
86
+ if (error instanceof Error && error.message.startsWith("TIMELINE_IR_UNSUPPORTED:")) {
87
+ return new ProjectTransactionError("PROJECT_EDIT_UNSUPPORTED", error.message.slice("TIMELINE_IR_UNSUPPORTED:".length).trim(), undefined, { cause: error });
88
+ }
89
+ return new ProjectTransactionError("PROJECT_EDIT_INVALID", error instanceof Error ? error.message : String(error), undefined, {
90
+ cause: error instanceof Error ? error : undefined,
91
+ });
92
+ }
93
+ }
94
+ function buildPreview(command, project, result) {
95
+ const before = structuredClone(project);
96
+ const after = structuredClone(project);
97
+ before.timeline = result.before;
98
+ after.timeline = result.after;
99
+ const diff = {
100
+ beforeDigest: timelineIrDigest(result.before),
101
+ afterDigest: timelineIrDigest(result.after),
102
+ operations: structuredClone(command.operations),
103
+ changedOccurrenceIds: [...result.changedOccurrenceIds],
104
+ changedMarkerIds: [...result.changedMarkerIds],
105
+ changedTitleIds: [...result.changedTitleIds],
106
+ changedTransitionIds: [...result.changedTransitionIds],
107
+ };
108
+ return {
109
+ command: structuredClone(command),
110
+ before,
111
+ after,
112
+ diff,
113
+ changedOccurrenceIds: [...result.changedOccurrenceIds],
114
+ changedMarkerIds: [...result.changedMarkerIds],
115
+ changedTitleIds: [...result.changedTitleIds],
116
+ changedTransitionIds: [...result.changedTransitionIds],
117
+ };
118
+ }
119
+ function validateCommand(command) {
120
+ if (!command || typeof command !== "object" || command.schemaVersion !== PROJECT_EDIT_COMMAND_SCHEMA_VERSION) {
121
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", "command schemaVersion must be 1");
122
+ }
123
+ if (!command.target || typeof command.target !== "object" || !text(command.target.projectId) || !text(command.target.sequenceId)) {
124
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", "command target requires projectId and sequenceId");
125
+ }
126
+ if (!command.expectedRevision || typeof command.expectedRevision !== "object"
127
+ || !text(command.expectedRevision.id)
128
+ || !Number.isSafeInteger(command.expectedRevision.sequence)
129
+ || command.expectedRevision.sequence < 0
130
+ || !text(command.expectedRevision.timestamp)) {
131
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", "command expectedRevision is invalid");
132
+ }
133
+ if (!Array.isArray(command.operations)) {
134
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", "command operations must be an array");
135
+ }
136
+ for (const operation of command.operations)
137
+ validateOperation(operation);
138
+ }
139
+ function validateOperation(operation) {
140
+ if (!operation || typeof operation !== "object" || !text(operation.type)) {
141
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", "every operation must include a supported type");
142
+ }
143
+ const candidate = operation;
144
+ switch (candidate.type) {
145
+ case "insert-occurrence":
146
+ if (!candidate.occurrence || typeof candidate.occurrence !== "object") {
147
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", "operation.occurrence is required");
148
+ }
149
+ if (candidate.placement !== undefined && candidate.placement !== "append" && candidate.placement !== "insert") {
150
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", "operation.placement must be append or insert");
151
+ }
152
+ return;
153
+ case "rename-occurrence":
154
+ requireOperationText(candidate, "occurrenceId");
155
+ requireOperationText(candidate, "name");
156
+ return;
157
+ case "trim-occurrence":
158
+ requireOperationText(candidate, "occurrenceId");
159
+ requireRationalShape(candidate.durationTime, "durationTime");
160
+ return;
161
+ case "move-occurrence":
162
+ requireOperationText(candidate, "occurrenceId");
163
+ requireRationalShape(candidate.startTime, "startTime");
164
+ if (candidate.track !== undefined && (!Number.isInteger(candidate.track) || candidate.track < 0)) {
165
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", "operation.track must be a non-negative integer");
166
+ }
167
+ return;
168
+ case "split-occurrence":
169
+ requireOperationText(candidate, "occurrenceId");
170
+ requireRationalShape(candidate.splitOffsetTime, "splitOffsetTime");
171
+ requireOperationText(candidate, "newOccurrenceId");
172
+ return;
173
+ case "set-gain":
174
+ requireOperationText(candidate, "occurrenceId");
175
+ if (typeof candidate.gainDb !== "number" || !Number.isFinite(candidate.gainDb)) {
176
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", "operation.gainDb must be finite");
177
+ }
178
+ return;
179
+ case "set-transform":
180
+ requireOperationText(candidate, "occurrenceId");
181
+ if (!candidate.transform || typeof candidate.transform !== "object") {
182
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", "operation.transform is required");
183
+ }
184
+ return;
185
+ case "remove-occurrence":
186
+ requireOperationText(candidate, "occurrenceId");
187
+ return;
188
+ case "add-marker":
189
+ if (!candidate.marker || typeof candidate.marker !== "object") {
190
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", "operation.marker is required");
191
+ }
192
+ return;
193
+ case "add-title":
194
+ if (!candidate.title || typeof candidate.title !== "object") {
195
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", "operation.title is required");
196
+ }
197
+ return;
198
+ case "remove-title":
199
+ requireOperationText(candidate, "titleId");
200
+ return;
201
+ case "add-transition":
202
+ if (!candidate.transition || typeof candidate.transition !== "object") {
203
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", "operation.transition is required");
204
+ }
205
+ return;
206
+ case "remove-transition":
207
+ requireOperationText(candidate, "transitionId");
208
+ return;
209
+ default:
210
+ throw new ProjectTransactionError("PROJECT_EDIT_UNSUPPORTED", `unsupported operation type: ${String(candidate.type)}`);
211
+ }
212
+ }
213
+ function requireOperationText(operation, field) {
214
+ if (!text(operation[field]))
215
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", `operation.${field} must be non-empty`);
216
+ }
217
+ function requireRationalShape(value, field) {
218
+ if (!value || typeof value !== "object" || !text(value.value) || !text(value.timescale)) {
219
+ throw new ProjectTransactionError("PROJECT_EDIT_INVALID", `operation.${field} must be a rational time`);
220
+ }
221
+ }
222
+ function text(value) {
223
+ return typeof value === "string" && value.trim().length > 0;
224
+ }
225
+ function sameRevision(left, right) {
226
+ return left.id === right.id && left.sequence === right.sequence;
227
+ }
@@ -7,7 +7,13 @@ export * from "./editing/duration-policy.js";
7
7
  export * from "./capabilities.js";
8
8
  export * from "./timeline/snapshot-digest.js";
9
9
  export * from "./timeline/editing-session.js";
10
+ export * from "./render/render-contract.js";
11
+ export * from "./render/render-and-verify.js";
10
12
  export * from "./timeline/drift-reconciliation.js";
13
+ export * from "./timeline/fast-observation.js";
14
+ export * from "./application/project-store.js";
15
+ export * from "./application/local-media.js";
16
+ export * from "./application/project-transactions.js";
11
17
  export * from "./context/project-catalog.js";
12
18
  export * from "./speech/filler-removal.js";
13
19
  export * from "./audio/dialogue-normalization.js";