@morshoto/framekit 0.1.17 → 0.1.18

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 (26) hide show
  1. package/README.md +10 -4
  2. package/dist-package/adapters/final-cut/typescript/src/canonical.js +19 -7
  3. package/dist-package/adapters/final-cut/typescript/src/connection.js +5 -3
  4. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +128 -29
  5. package/dist-package/adapters/final-cut/typescript/src/index.js +1 -0
  6. package/dist-package/adapters/final-cut/typescript/src/library-inspection.js +60 -1
  7. package/dist-package/adapters/final-cut/typescript/src/live.js +2 -2
  8. package/dist-package/adapters/final-cut/typescript/src/publish-readback.js +213 -0
  9. package/dist-package/adapters/final-cut/typescript/src/publisher.js +762 -238
  10. package/dist-package/adapters/final-cut/typescript/src/session.js +6 -1
  11. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +200 -48
  12. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +17 -7
  13. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +2 -2
  14. package/dist-package/apps/cli/src/main.js +34 -19
  15. package/dist-package/apps/mcp-server/src/build-alignment.js +59 -0
  16. package/dist-package/apps/mcp-server/src/build-identity.js +30 -0
  17. package/dist-package/apps/mcp-server/src/build-identity.json +5 -0
  18. package/dist-package/apps/mcp-server/src/headless-project-snapshot.js +101 -0
  19. package/dist-package/apps/mcp-server/src/headless-projects.js +255 -16
  20. package/dist-package/apps/mcp-server/src/main.js +27 -3
  21. package/dist-package/apps/mcp-server/src/server.js +270 -49
  22. package/dist-package/apps/mcp-server/src/version.js +21 -2
  23. package/dist-package/packages/runtime/src/application/media-analysis-service.js +15 -5
  24. package/dist-package/packages/runtime/src/runtime.js +6 -0
  25. package/dist-package/packages/runtime/src/timeline/editing-session.js +7 -2
  26. package/package.json +9 -9
package/README.md CHANGED
@@ -66,10 +66,16 @@ Open `/plugins` in Codex, find **Framekit**, and select **Install**. Start a new
66
66
  Codex session to load the Framekit MCP tools. No repository checkout or manual
67
67
  `codex mcp add` is required.
68
68
 
69
- The plugin runs the published package in headless mode. It connects only to an
70
- existing Workflow Extension bridge and does not launch, activate, focus, or
71
- edit Final Cut through macOS UI automation. See the
72
- [first-run setup and capability boundaries](./docs/final-cut/installation.md).
69
+ The plugin runs the published package in headless mode. For live Final Cut
70
+ capabilities, it connects only to an existing Workflow Extension bridge and
71
+ does not launch, activate, focus, or edit Final Cut through macOS UI automation.
72
+ Framekit-owned video projects can register local media, analyze it, create an
73
+ approved rough-cut plan, and render a verified MP4 plus editable FCPXML without
74
+ a connected Final Cut session. Optional native publishing is experimental and
75
+ is not guaranteed in v0.1.18: a document-open dispatch does not prove that
76
+ Final Cut completed an import or created a native project. See the
77
+ [Codex video production runbook](./docs/tests/codex-video-production-e2e.md)
78
+ and [first-run setup and capability boundaries](./docs/final-cut/installation.md).
73
79
 
74
80
  For local native development, use the checkout's CLI wrapper from the repository
75
81
  root:
@@ -87,12 +87,17 @@ export class FinalCutCanonicalSnapshotSource {
87
87
  exportTimeoutMs;
88
88
  pollIntervalMs;
89
89
  target;
90
+ readbackTarget;
90
91
  stageOnDesktop;
91
92
  constructor(options = {}) {
92
93
  this.executor = options.executor ?? executeCanonicalAppleScript;
93
94
  this.exportTimeoutMs = Math.max(1_000, options.exportTimeoutMs ?? 30_000);
94
95
  this.pollIntervalMs = Math.max(10, options.pollIntervalMs ?? 100);
95
96
  this.target = options.target;
97
+ this.readbackTarget = options.readbackTarget;
98
+ if (this.target && this.readbackTarget) {
99
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_INVALID: FCPXML UID and catalog readback bindings cannot be combined");
100
+ }
96
101
  this.stageOnDesktop = !options.executor;
97
102
  }
98
103
  async readSnapshot() {
@@ -108,7 +113,7 @@ export class FinalCutCanonicalSnapshotSource {
108
113
  for (let attempt = 1; attempt <= 2; attempt += 1) {
109
114
  const result = parseFinalCutCanonicalExportResult(await this.executor(buildFinalCutCanonicalExportScript(exportPath)));
110
115
  if (result.status === "export-requested") {
111
- return await readCanonicalExport(exportPath, this.exportTimeoutMs, this.pollIntervalMs, this.target);
116
+ return await readCanonicalExport(exportPath, this.exportTimeoutMs, this.pollIntervalMs, this.target, this.readbackTarget);
112
117
  }
113
118
  const error = new FinalCutCanonicalExportError(result);
114
119
  if (!error.retryable || error.cleanup !== "complete" || attempt === 2)
@@ -133,10 +138,7 @@ export class FinalCutCanonicalSnapshotSource {
133
138
  export function buildFinalCutCanonicalExportScript(exportPath) {
134
139
  const exportDirectory = dirname(exportPath);
135
140
  const exportName = basename(exportPath);
136
- const defaultDesktop = join(homedir(), "Desktop");
137
- const chooseExportDirectory = exportDirectory === defaultDesktop
138
- ? ""
139
- : ` keystroke "g" using {command down, shift down}
141
+ const chooseExportDirectory = ` keystroke "g" using {command down, shift down}
140
142
  delay 1
141
143
  try
142
144
  set pathField to text field 1 of sheet 1 of window "Export XML"
@@ -1520,7 +1522,7 @@ async function executeCanonicalAppleScript(script) {
1520
1522
  throw new Error(`FINAL_CUT_CANONICAL_AUTOMATION_FAILED: ${detail}`);
1521
1523
  }
1522
1524
  }
1523
- async function readCanonicalExport(path, timeoutMs, pollIntervalMs, target) {
1525
+ async function readCanonicalExport(path, timeoutMs, pollIntervalMs, target, readbackTarget) {
1524
1526
  const deadline = Date.now() + timeoutMs;
1525
1527
  let previousSignature;
1526
1528
  let lastReadError;
@@ -1542,7 +1544,17 @@ async function readCanonicalExport(path, timeoutMs, pollIntervalMs, target) {
1542
1544
  }
1543
1545
  if (readablePath && signature && signature === previousSignature) {
1544
1546
  try {
1545
- return await new FcpxmlDocumentAdapter(readablePath, target).readProject();
1547
+ const snapshot = await new FcpxmlDocumentAdapter(readablePath, target, {
1548
+ allowMissingImmutableIdsForReadback: Boolean(readbackTarget),
1549
+ }).readProject();
1550
+ if (readbackTarget) {
1551
+ if (snapshot.projectName !== readbackTarget.projectName || snapshot.timeline.name !== readbackTarget.sequenceName) {
1552
+ throw new Error("TARGET_MISMATCH: canonical export project and sequence names differ from the catalog-bound created target");
1553
+ }
1554
+ snapshot.projectId = readbackTarget.projectId;
1555
+ snapshot.timeline.id = readbackTarget.sequenceId;
1556
+ }
1557
+ return snapshot;
1546
1558
  }
1547
1559
  catch (error) {
1548
1560
  lastReadError = error;
@@ -36,6 +36,7 @@ export class FinalCutConnectionManager {
36
36
  activateExtension;
37
37
  restartFinalCut;
38
38
  restartAfterInstall;
39
+ installBeforeProbe;
39
40
  probe;
40
41
  sleep;
41
42
  status;
@@ -66,6 +67,7 @@ export class FinalCutConnectionManager {
66
67
  this.registerExtension = options.registerExtension ?? (() => defaultRegisterExtension(this.extensionInstallPath));
67
68
  this.activateExtension = options.activateExtension ?? ((activationOptions) => defaultActivateFinalCut(activationOptions));
68
69
  this.restartAfterInstall = options.restartAfterInstall ?? false;
70
+ this.installBeforeProbe = options.installBeforeProbe ?? false;
69
71
  this.restartFinalCut = options.restartFinalCut ?? (() => defaultRestartFinalCut(this.detectFinalCut, this.launchFinalCut, this.sleep));
70
72
  this.probe = options.probe ?? defaultProbe(this.socketPath);
71
73
  this.sleep = options.sleep ?? ((milliseconds) => new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds)));
@@ -105,12 +107,12 @@ export class FinalCutConnectionManager {
105
107
  this.update({ state: "detecting", lastError: undefined });
106
108
  const existing = await this.tryProbe();
107
109
  this.update({ extensionInstalled: await pathExists(this.extensionInstallPath) });
108
- if (existing.result)
110
+ if (existing.result && !this.installBeforeProbe)
109
111
  return this.ready(existing.result);
110
- if (this.canonicalProviderRequired) {
112
+ if (this.canonicalProviderRequired && !existing.result) {
111
113
  return this.fail("FINAL_CUT_CANONICAL_PROVIDER_UNAVAILABLE", `Canonical live provider is unavailable at ${this.socketPath}; metadata-only fallback is disabled`, "needs-user-action");
112
114
  }
113
- if (this.headless) {
115
+ if (this.headless && !existing.result) {
114
116
  this.update({ state: "waiting-for-socket" });
115
117
  const waiting = await this.waitForHeadlessBridge(existing.error);
116
118
  if (waiting.result)
@@ -5,6 +5,17 @@ import { dirname, isAbsolute, resolve } from "node:path";
5
5
  import { XMLBuilder, XMLParser } from "fast-xml-parser";
6
6
  import { createProjectSelectionResult, withCapabilityFamilies } from "../../../../packages/runtime/src/index.js";
7
7
  const CLIP_KINDS = new Set(["asset-clip", "clip", "ref-clip", "sync-clip", "mc-clip", "audio", "video"]);
8
+ const MARKER_HOST_KINDS = new Set([...CLIP_KINDS, "gap", "title", "live-drawing"]);
9
+ const MARKER_FOLLOWING_CHILD_KINDS = new Set([
10
+ "audio-channel-source",
11
+ "audio-role-source",
12
+ "sync-source",
13
+ "filter-video",
14
+ "filter-video-mask",
15
+ "filter-audio",
16
+ "metadata",
17
+ "reserved",
18
+ ]);
8
19
  const TIMELINE_KINDS = new Set([
9
20
  ...CLIP_KINDS,
10
21
  "gap",
@@ -38,9 +49,11 @@ export class FcpxmlDocumentAdapter {
38
49
  sequence = 0;
39
50
  fileSignature;
40
51
  history = new Map();
41
- constructor(filePath, target) {
52
+ allowMissingImmutableIdsForReadback;
53
+ constructor(filePath, target, options = {}) {
42
54
  this.filePath = filePath;
43
55
  this.target = target;
56
+ this.allowMissingImmutableIdsForReadback = options.allowMissingImmutableIdsForReadback ?? false;
44
57
  }
45
58
  async getIdentity() {
46
59
  return { name: "Final Cut Pro", version: "FCPXML", backend: "fcpxml-document" };
@@ -284,17 +297,27 @@ export class FcpxmlDocumentAdapter {
284
297
  }
285
298
  }
286
299
  identity(project, sequence) {
287
- const projectUid = immutableUid(project, "PROJECT");
300
+ const projectUid = optionalImmutableUid(project);
301
+ if (!projectUid && !this.allowMissingImmutableIdsForReadback)
302
+ immutableUid(project, "PROJECT");
288
303
  if (this.target && projectUid !== this.target.projectUid) {
289
304
  throw new Error(`TARGET_MISMATCH: exported project UID ${projectUid} does not match live project UID ${this.target.projectUid}`);
290
305
  }
291
- const exportedSequenceUid = sequence ? attribute(sequence, "uid") : undefined;
306
+ const exportedSequenceUid = sequence ? optionalImmutableUid(sequence) : undefined;
307
+ if (!exportedSequenceUid && !projectUid && !this.target?.sequenceId && !this.allowMissingImmutableIdsForReadback) {
308
+ immutableUid(sequence, "SEQUENCE");
309
+ }
292
310
  if (this.target && exportedSequenceUid !== undefined && String(exportedSequenceUid) !== this.target.sequenceId) {
293
311
  throw new Error(`TARGET_MISMATCH: exported sequence UID ${String(exportedSequenceUid)} does not match live sequence UID ${this.target.sequenceId}`);
294
312
  }
295
313
  return {
296
- projectId: this.target?.projectId ?? `fcpxml:project:${projectUid}`,
297
- sequenceId: this.target?.sequenceId ?? stableSequenceId(sequence),
314
+ projectId: this.target?.projectId ?? (projectUid
315
+ ? `fcpxml:project:${projectUid}`
316
+ : `fcpxml:readback-project:${hash(`${this.filePath}\0${attribute(project, "name") ?? "Final Cut Project"}`)}`),
317
+ sequenceId: this.target?.sequenceId ?? (exportedSequenceUid
318
+ ? `fcpxml:sequence:${exportedSequenceUid}`
319
+ : projectUid ? `fcpxml:sequence:${projectUid}`
320
+ : `fcpxml:readback-sequence:${hash(`${this.filePath}\0${attribute(sequence ?? {}, "name") ?? "Final Cut Sequence"}`)}`),
298
321
  };
299
322
  }
300
323
  applyOperation(operation) {
@@ -349,17 +372,7 @@ export class FcpxmlDocumentAdapter {
349
372
  this.applyRippleDelete(spine, operation.range.start, operation.range.end);
350
373
  break;
351
374
  case "add-marker": {
352
- if (operation.timelineId !== timelineId) {
353
- throw new Error(`TIMELINE_NOT_FOUND: ${operation.timelineId}`);
354
- }
355
- appendChild(spine, "marker", {
356
- ":@": {
357
- "@_id": operation.marker.id,
358
- "@_start": formatSeconds(operation.marker.start),
359
- "@_duration": formatSeconds(operation.marker.duration),
360
- "@_value": operation.marker.name,
361
- },
362
- });
375
+ this.applyMarker(spine, timelineId, operation);
363
376
  break;
364
377
  }
365
378
  case "timeline.media.add":
@@ -392,6 +405,40 @@ export class FcpxmlDocumentAdapter {
392
405
  }
393
406
  this.updateSequenceDuration(sequence, spine);
394
407
  }
408
+ applyMarker(spine, timelineId, operation) {
409
+ if (operation.timelineId !== timelineId) {
410
+ throw new Error(`TIMELINE_NOT_FOUND: ${operation.timelineId}`);
411
+ }
412
+ const markerStart = parseRational(formatSeconds(operation.marker.start));
413
+ const markerDuration = parseRational(formatSeconds(operation.marker.duration));
414
+ const markerEnd = addRational(markerStart, markerDuration);
415
+ const host = timelineEntries(spine).find((entry) => {
416
+ if (!MARKER_HOST_KINDS.has(entry.kind))
417
+ return false;
418
+ const hostEnd = addRational(entry.startTime, entry.durationTime);
419
+ return compareRational(markerStart, entry.startTime) >= 0
420
+ && compareRational(markerEnd, hostEnd) <= 0;
421
+ });
422
+ if (!host) {
423
+ throw new Error("FCPXML_MARKER_TARGET_UNAVAILABLE: marker must fit inside an existing story element");
424
+ }
425
+ const sourceStart = parseRational(attribute(host.node, "start") ?? "0s");
426
+ const localStart = addRational(sourceStart, subtractRational(markerStart, host.startTime));
427
+ const marker = elementNode("marker", {
428
+ start: formatRational(localStart),
429
+ duration: formatRational(markerDuration),
430
+ value: operation.marker.name,
431
+ note: `com.framekit.id:${operation.marker.id}`,
432
+ });
433
+ const firstFollowingChild = storyEntries(host.node)
434
+ .find(({ kind }) => MARKER_FOLLOWING_CHILD_KINDS.has(kind));
435
+ if (firstFollowingChild) {
436
+ insertChildBefore(host.node, firstFollowingChild.node, "marker", marker);
437
+ }
438
+ else {
439
+ appendChild(host.node, "marker", marker);
440
+ }
441
+ }
395
442
  findClipEntry(spine, clipId, timelineId) {
396
443
  return timelineEntries(spine)
397
444
  .filter(({ kind }) => CLIP_KINDS.has(kind))
@@ -866,7 +913,10 @@ export class FcpxmlDocumentAdapter {
866
913
  };
867
914
  }
868
915
  instanceId(node, kind, path, timelineId) {
869
- const explicit = attribute(node, "id") ?? attribute(node, "uid");
916
+ const metadata = firstChild(node, "metadata");
917
+ const framekitId = metadata === undefined ? undefined : storyEntries(metadata)
918
+ .find(({ kind: childKind, node: child }) => childKind === "md" && attribute(child, "key") === "com.framekit.id")?.node;
919
+ const explicit = attribute(node, "id") ?? attribute(node, "uid") ?? (framekitId && attribute(framekitId, "value"));
870
920
  return String(explicit ?? `${timelineId}:spine:${path}:${kind}`);
871
921
  }
872
922
  findClipNode(spine, clipId, timelineId) {
@@ -890,7 +940,7 @@ export class FcpxmlDocumentAdapter {
890
940
  .filter(({ kind }) => kind === "marker")
891
941
  .map(({ node, startTime, durationTime }, index) => {
892
942
  return {
893
- id: String(attribute(node, "id") ?? `marker-${index + 1}`),
943
+ id: String(attribute(node, "id") ?? framekitNoteId(attribute(node, "note")) ?? `marker-${index + 1}`),
894
944
  start: rationalSeconds(startTime),
895
945
  duration: rationalSeconds(durationTime),
896
946
  startTime,
@@ -904,12 +954,12 @@ export class FcpxmlDocumentAdapter {
904
954
  .filter(({ kind }) => kind === "caption")
905
955
  .map(({ node, startTime, durationTime }, index) => {
906
956
  return {
907
- id: String(attribute(node, "id") ?? `caption-${index + 1}`),
957
+ id: String(attribute(node, "id") ?? framekitNoteId(textChildValue(node, "note")) ?? `caption-${index + 1}`),
908
958
  start: rationalSeconds(startTime),
909
959
  duration: rationalSeconds(durationTime),
910
960
  startTime,
911
961
  durationTime,
912
- text: String(attribute(node, "text") ?? attribute(node, "name") ?? ""),
962
+ text: String(textChildValue(node, "text") ?? attribute(node, "text") ?? attribute(node, "name") ?? ""),
913
963
  };
914
964
  });
915
965
  }
@@ -1038,12 +1088,35 @@ function textChildValue(node, kind) {
1038
1088
  const text = firstChild(node, kind);
1039
1089
  if (!text)
1040
1090
  return undefined;
1041
- const value = Array.isArray(text[kind]) ? text[kind][0]?.["#text"] : undefined;
1042
- if (Array.isArray(value) && value.length > 0)
1043
- return String(value[0]);
1044
- if (typeof value === "string" || typeof value === "number")
1045
- return String(value);
1046
- return undefined;
1091
+ const value = xmlTextContent(text);
1092
+ return value.length > 0 ? value : undefined;
1093
+ }
1094
+ function xmlTextContent(node) {
1095
+ return Object.entries(node)
1096
+ .filter(([kind]) => kind !== ":@")
1097
+ .map(([kind, value]) => {
1098
+ if (kind === "#text") {
1099
+ const text = (Array.isArray(value) ? value : [value])
1100
+ .filter((part) => typeof part === "string" || typeof part === "number")
1101
+ .map(String)
1102
+ .filter((part) => part.trim().length > 0)
1103
+ .join("");
1104
+ return text;
1105
+ }
1106
+ if (!Array.isArray(value))
1107
+ return "";
1108
+ return value
1109
+ .filter((child) => typeof child === "object" && child !== null)
1110
+ .map(xmlTextContent)
1111
+ .join("");
1112
+ })
1113
+ .join("");
1114
+ }
1115
+ function framekitNoteId(value) {
1116
+ const prefix = "com.framekit.id:";
1117
+ return typeof value === "string" && value.startsWith(prefix) && value.length > prefix.length
1118
+ ? value.slice(prefix.length)
1119
+ : undefined;
1047
1120
  }
1048
1121
  function mediaKindCompatible(role, mediaKind) {
1049
1122
  if (mediaKind === undefined)
@@ -1058,8 +1131,13 @@ function timelineEntries(spine) {
1058
1131
  const localOffset = parseRational(attribute(child, "offset")
1059
1132
  ?? ((kind === "marker" || kind === "caption") ? attribute(child, "start") : undefined)
1060
1133
  ?? "0s");
1061
- const localStart = parentKind === "asset-clip"
1062
- && (kind === "title" || kind === "asset-clip" && attribute(child, "audioRole") === "music")
1134
+ const markerInHost = kind === "marker"
1135
+ && parentKind !== undefined
1136
+ && MARKER_HOST_KINDS.has(parentKind);
1137
+ const assetClipRelativeChild = parentKind === "asset-clip"
1138
+ && (kind === "title" || kind === "caption" || kind === "asset-clip" && attribute(child, "audioRole") === "music");
1139
+ const sourceRelativeChild = markerInHost || assetClipRelativeChild;
1140
+ const localStart = sourceRelativeChild
1063
1141
  ? subtractRational(localOffset, parseRational(attribute(node, "start") ?? "0s"))
1064
1142
  : localOffset;
1065
1143
  const durationTime = parseRational(attribute(child, "duration") ?? "0s");
@@ -1110,6 +1188,23 @@ function appendChild(node, kind, child) {
1110
1188
  node[kind] = [...(Array.isArray(node[kind]) ? node[kind] : []), wrapper];
1111
1189
  }
1112
1190
  }
1191
+ function insertChildBefore(parent, before, kind, child) {
1192
+ const elementKey = Object.keys(parent).find((key) => key !== ":@");
1193
+ if (!elementKey || !Array.isArray(parent[elementKey])) {
1194
+ appendChild(parent, kind, child);
1195
+ return;
1196
+ }
1197
+ const children = parent[elementKey];
1198
+ const index = children.indexOf(before);
1199
+ if (index < 0) {
1200
+ appendChild(parent, kind, child);
1201
+ return;
1202
+ }
1203
+ const wrapper = Object.prototype.hasOwnProperty.call(child, kind)
1204
+ ? child
1205
+ : { [kind]: [], ...child };
1206
+ children.splice(index, 0, wrapper);
1207
+ }
1113
1208
  function attributes(node) {
1114
1209
  return (node[":@"] ?? {});
1115
1210
  }
@@ -1241,7 +1336,7 @@ function mediaKindFromResource(node) {
1241
1336
  const hasAudio = attribute(node, "hasAudio");
1242
1337
  if (hasVideo === "1" || hasVideo === "true")
1243
1338
  return "video";
1244
- if ((hasVideo === "0" || hasVideo === "false") && (hasAudio === "1" || hasAudio === "true"))
1339
+ if (hasAudio === "1" || hasAudio === "true")
1245
1340
  return "audio";
1246
1341
  return undefined;
1247
1342
  }
@@ -1342,6 +1437,10 @@ function immutableUid(node, kind) {
1342
1437
  }
1343
1438
  return String(uid);
1344
1439
  }
1440
+ function optionalImmutableUid(node) {
1441
+ const uid = node ? attribute(node, "uid") : undefined;
1442
+ return uid === undefined || String(uid).trim().length === 0 ? undefined : String(uid);
1443
+ }
1345
1444
  function stableTimelineId(project, sequence) {
1346
1445
  stableProjectId(project);
1347
1446
  return stableSequenceId(sequence);
@@ -11,6 +11,7 @@ export * from "./media.js";
11
11
  export * from "./native.js";
12
12
  export * from "./disposable-native.js";
13
13
  export * from "./publisher.js";
14
+ export * from "./publish-readback.js";
14
15
  export * from "./export.js";
15
16
  export * from "./background-export.js";
16
17
  export * from "./background-materialization.js";
@@ -1,5 +1,8 @@
1
1
  import { execFile as execFileCallback } from "node:child_process";
2
+ import { realpathSync } from "node:fs";
3
+ import { resolve } from "node:path";
2
4
  import { promisify } from "node:util";
5
+ import { fileURLToPath } from "node:url";
3
6
  import { validateProjectCatalog } from "../../../../packages/runtime/src/index.js";
4
7
  export const FINAL_CUT_LIBRARY_INSPECTION_BACKEND = "final-cut-background-library";
5
8
  export const FINAL_CUT_LIBRARY_INSPECTION_TIMEOUT_MS = 30_000;
@@ -62,6 +65,43 @@ export class FinalCutLibraryInspectionProvider {
62
65
  }
63
66
  return catalog;
64
67
  }
68
+ /** Bind a newly imported project to the exact library location requested by its FCPXML. */
69
+ async resolveProjectBinding(libraryPath, identity) {
70
+ const result = await this.inspect();
71
+ if (result.status === "unavailable" || result.status === "error") {
72
+ throw new Error(`${result.error.code}: ${result.error.message}`);
73
+ }
74
+ const expectedPath = normalizeLibraryPath(libraryPath);
75
+ const libraries = result.catalog.libraries.filter((library) => library.path
76
+ && normalizeLibraryPath(library.path) === expectedPath);
77
+ if (libraries.length === 0) {
78
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_PENDING: library has not appeared at ${expectedPath}`);
79
+ }
80
+ if (libraries.length !== 1) {
81
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_MISMATCH: multiple Final Cut libraries report path ${expectedPath}`);
82
+ }
83
+ const library = libraries[0];
84
+ const matches = library.events.flatMap((event) => event.projects.flatMap((project) => {
85
+ if (project.name !== identity.projectName)
86
+ return [];
87
+ const sequences = project.sequences.filter((sequence) => sequence.name === identity.sequenceName);
88
+ return sequences.map((sequence) => ({ event, project, sequence }));
89
+ }));
90
+ if (matches.length === 0) {
91
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_PENDING: project ${identity.projectName} / sequence ${identity.sequenceName} has not appeared in ${expectedPath}`);
92
+ }
93
+ if (matches.length !== 1) {
94
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_MISMATCH: expected one project and sequence in ${expectedPath}, found ${matches.length}`);
95
+ }
96
+ const match = matches[0];
97
+ return {
98
+ projectId: match.project.id,
99
+ sequenceId: match.sequence.id,
100
+ libraryId: library.id,
101
+ eventId: match.event.id,
102
+ libraryPath: expectedPath,
103
+ };
104
+ }
65
105
  }
66
106
  /** Build the JXA program used for direct, read-only Final Cut Apple Events. */
67
107
  export function buildFinalCutLibraryInspectionScript(applicationIdentifier = "com.apple.FinalCut") {
@@ -136,6 +176,7 @@ function libraryValue(library) {
136
176
  return {
137
177
  id: textValue(library, "id"),
138
178
  name: textValue(library, "name"),
179
+ path: textValue(library, "file"),
139
180
  events: events === null ? null : events.map(eventValue)
140
181
  };
141
182
  }
@@ -251,7 +292,8 @@ function parseLibrary(value, path, issues) {
251
292
  const events = parseChildren(record.events, `${path}.events`, "event", parseEvent, issues);
252
293
  if (!id || !name)
253
294
  return undefined;
254
- return { id, name, events };
295
+ const libraryPath = optionalText(record.path);
296
+ return { id, name, ...(libraryPath ? { path: libraryPath } : {}), events };
255
297
  }
256
298
  function parseEvent(value, path, issues) {
257
299
  const record = asRecord(value);
@@ -358,6 +400,23 @@ function normalizeInteger(value) {
358
400
  return String(value);
359
401
  return undefined;
360
402
  }
403
+ function optionalText(value) {
404
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
405
+ }
406
+ function normalizeLibraryPath(path) {
407
+ try {
408
+ const resolved = resolve(path.startsWith("file:") ? fileURLToPath(path) : path);
409
+ try {
410
+ return realpathSync(resolved);
411
+ }
412
+ catch {
413
+ return resolved;
414
+ }
415
+ }
416
+ catch {
417
+ return resolve(path);
418
+ }
419
+ }
361
420
  function parseTopLevelError(value, fallback) {
362
421
  const record = asRecord(value);
363
422
  const message = typeof record?.message === "string" && record.message.trim() ? record.message : fallback;
@@ -172,7 +172,7 @@ export class FinalCutLiveAdapter {
172
172
  const response = await this.request({
173
173
  method: "deliver-fcpxml",
174
174
  artifactPath: request.artifactPath,
175
- ...(request.targetLibraryUid ? { targetLibraryUid: request.targetLibraryUid } : {}),
175
+ ...(request.targetLibraryLocation ? { targetLibraryLocation: request.targetLibraryLocation } : {}),
176
176
  activates: request.activates,
177
177
  });
178
178
  if (!response.delivery)
@@ -239,7 +239,7 @@ function validateFcpxmlDelivery(delivery, request) {
239
239
  if (delivery.status !== "dispatched" && (!delivery.error?.code?.trim() || !delivery.error.message.trim())) {
240
240
  throw new Error("FINAL_CUT_LIVE_PROTOCOL: blocked FCPXML delivery response is missing an error");
241
241
  }
242
- if (request.targetLibraryUid && delivery.target.requestedLibraryUid !== request.targetLibraryUid) {
242
+ if (request.targetLibraryLocation && delivery.target.requestedLibraryLocation !== request.targetLibraryLocation) {
243
243
  throw new Error("FINAL_CUT_LIVE_PROTOCOL: FCPXML delivery target does not match the request");
244
244
  }
245
245
  }