@morshoto/framekit 0.1.12 → 0.1.14

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.
@@ -1,6 +1,6 @@
1
1
  import { execFile as execFileCallback } from "node:child_process";
2
2
  import { mkdtemp, rm, stat } from "node:fs/promises";
3
- import { basename, join } from "node:path";
3
+ import { basename, dirname, join } from "node:path";
4
4
  import { tmpdir } from "node:os";
5
5
  import { promisify } from "node:util";
6
6
  import { canonicalSnapshotDigest, canonicalTimelineMode, assertTimelineTargetReadAfterWrite, createTimelineTarget, resolveTimelineTarget, reconcileProjectCatalog, validateProjectCatalog, withCapabilityFamilies, CapabilityUnavailableError, } from "../../../../packages/runtime/src/index.js";
@@ -8,6 +8,63 @@ import { recoverCanonicalNativeMutation } from "./canonical-recovery.js";
8
8
  import { verifyCanonicalReadback } from "./canonical-verification.js";
9
9
  import { FcpxmlDocumentAdapter } from "./fcpxml.js";
10
10
  const execFile = promisify(execFileCallback);
11
+ /** Structured failure returned when headed Export XML recovery can be retried. */
12
+ export class FinalCutCanonicalExportError extends Error {
13
+ code;
14
+ retryable;
15
+ cleanup;
16
+ constructor(result) {
17
+ super(`${result.code}: ${result.message}`);
18
+ this.name = "FinalCutCanonicalExportError";
19
+ this.code = result.code;
20
+ this.retryable = result.status === "retryable";
21
+ this.cleanup = result.cleanup;
22
+ }
23
+ toJSON() {
24
+ return {
25
+ code: this.code,
26
+ message: this.message,
27
+ retryable: this.retryable,
28
+ cleanup: this.cleanup,
29
+ };
30
+ }
31
+ }
32
+ /** Parse the JSON envelope returned by the headed canonical export workflow. */
33
+ export function parseFinalCutCanonicalExportResult(input) {
34
+ if (input === "canonical-export-requested")
35
+ return { status: "export-requested" };
36
+ let payload;
37
+ try {
38
+ payload = typeof input === "string" ? JSON.parse(input) : input;
39
+ }
40
+ catch (error) {
41
+ throw new Error(`FINAL_CUT_CANONICAL_EXPORT_RESULT_INVALID: response was not valid JSON (${String(error)})`);
42
+ }
43
+ if (!payload || typeof payload !== "object") {
44
+ throw new Error("FINAL_CUT_CANONICAL_EXPORT_RESULT_INVALID: response must be an object");
45
+ }
46
+ const result = payload;
47
+ if (result.status === "export-requested")
48
+ return { status: "export-requested" };
49
+ if (result.status !== "retryable" && result.status !== "failed") {
50
+ throw new Error("FINAL_CUT_CANONICAL_EXPORT_RESULT_INVALID: response status is unsupported");
51
+ }
52
+ if (typeof result.code !== "string" || !result.code.trim()) {
53
+ throw new Error("FINAL_CUT_CANONICAL_EXPORT_RESULT_INVALID: response code is required");
54
+ }
55
+ if (typeof result.message !== "string" || !result.message.trim()) {
56
+ throw new Error("FINAL_CUT_CANONICAL_EXPORT_RESULT_INVALID: response message is required");
57
+ }
58
+ if (result.cleanup !== "complete" && result.cleanup !== "incomplete") {
59
+ throw new Error("FINAL_CUT_CANONICAL_EXPORT_RESULT_INVALID: response cleanup status is unsupported");
60
+ }
61
+ return {
62
+ status: result.status,
63
+ code: result.code,
64
+ message: result.message,
65
+ cleanup: result.cleanup,
66
+ };
67
+ }
11
68
  /** Report the complete guarantees required before claiming canonical live support. */
12
69
  export function assessCanonicalLiveReadiness(capabilities) {
13
70
  const mode = canonicalTimelineMode(capabilities);
@@ -28,21 +85,32 @@ export class FinalCutCanonicalSnapshotSource {
28
85
  executor;
29
86
  exportTimeoutMs;
30
87
  pollIntervalMs;
88
+ target;
31
89
  constructor(options = {}) {
32
90
  this.executor = options.executor ?? executeCanonicalAppleScript;
33
91
  this.exportTimeoutMs = Math.max(1_000, options.exportTimeoutMs ?? 30_000);
34
92
  this.pollIntervalMs = Math.max(10, options.pollIntervalMs ?? 100);
93
+ this.target = options.target;
35
94
  }
36
95
  async readSnapshot() {
37
96
  const directory = await mkdtemp(join(tmpdir(), "framekit-finalcut-canonical-"));
38
97
  const exportPath = join(directory, "active.fcpxml");
39
98
  try {
40
- await this.executor(buildFinalCutCanonicalExportScript(exportPath));
41
- return await readCanonicalExport(exportPath, this.exportTimeoutMs, this.pollIntervalMs);
99
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
100
+ const result = parseFinalCutCanonicalExportResult(await this.executor(buildFinalCutCanonicalExportScript(exportPath)));
101
+ if (result.status === "export-requested") {
102
+ return await readCanonicalExport(exportPath, this.exportTimeoutMs, this.pollIntervalMs, this.target);
103
+ }
104
+ const error = new FinalCutCanonicalExportError(result);
105
+ if (!error.retryable || error.cleanup !== "complete" || attempt === 2)
106
+ throw error;
107
+ await new Promise((resolve) => setTimeout(resolve, 100));
108
+ }
109
+ throw new Error("FINAL_CUT_CANONICAL_EXPORT_FAILED: retry attempts exhausted");
42
110
  }
43
111
  catch (error) {
44
112
  const detail = error instanceof Error ? error.message : String(error);
45
- if (detail.includes("FINAL_CUT_CANONICAL_"))
113
+ if (detail.includes("FINAL_CUT_CANONICAL_") || detail.includes("TARGET_MISMATCH"))
46
114
  throw error;
47
115
  throw new Error(`FINAL_CUT_CANONICAL_EXPORT_FAILED: ${detail}`);
48
116
  }
@@ -52,6 +120,8 @@ export class FinalCutCanonicalSnapshotSource {
52
120
  }
53
121
  }
54
122
  export function buildFinalCutCanonicalExportScript(exportPath) {
123
+ const exportDirectory = dirname(exportPath);
124
+ const exportName = basename(exportPath);
55
125
  return `
56
126
  using terms from application "System Events"
57
127
 
@@ -84,86 +154,320 @@ on findWindow(finalCut, expectedNames, timeoutSeconds, timeoutMessage)
84
154
  end repeat
85
155
  end findWindow
86
156
 
87
- on findDescendantByRole(container, expectedRole, timeoutSeconds, timeoutMessage)
157
+ on roleIsExpected(candidateRole, expectedRoles)
158
+ repeat with expectedRole in expectedRoles
159
+ if candidateRole is (expectedRole as text) then return true
160
+ end repeat
161
+ return false
162
+ end roleIsExpected
163
+
164
+ on accessibilityMatchesExpectedName(candidate, expectedNames)
165
+ repeat with attributeName in {"AXDescription", "AXTitle", "AXIdentifier"}
166
+ try
167
+ set candidateLabel to value of attribute (attributeName as text) of candidate as text
168
+ repeat with expectedName in expectedNames
169
+ if candidateLabel is (expectedName as text) then return true
170
+ end repeat
171
+ end try
172
+ end repeat
173
+ try
174
+ set candidateLabel to name of candidate as text
175
+ repeat with expectedName in expectedNames
176
+ if candidateLabel is (expectedName as text) then return true
177
+ end repeat
178
+ on error
179
+ return false
180
+ end try
181
+ return false
182
+ end accessibilityMatchesExpectedName
183
+
184
+ on findAccessibilityDescendant(container, expectedRoles, depth)
185
+ if depth > 12 then return missing value
186
+ try
187
+ if my roleIsExpected(role of container as text, expectedRoles) then return container
188
+ end try
189
+ try
190
+ repeat with childRef in (UI elements of container)
191
+ set candidate to contents of childRef
192
+ set found to my findAccessibilityDescendant(candidate, expectedRoles, depth + 1)
193
+ if found is not missing value then return found
194
+ end repeat
195
+ end try
196
+ return missing value
197
+ end findAccessibilityDescendant
198
+
199
+ on accessibilityContainsPathMarker(candidate)
200
+ repeat with attributeName in {"AXDescription", "AXTitle", "AXIdentifier"}
201
+ try
202
+ set candidateLabel to value of attribute (attributeName as text) of candidate as text
203
+ if candidateLabel contains "Go to the folder" or candidateLabel contains "path" or candidateLabel contains "Path" or candidateLabel contains "location" or candidateLabel contains "Location" then return true
204
+ end try
205
+ end repeat
206
+ try
207
+ set candidateLabel to name of candidate as text
208
+ if candidateLabel contains "Go to the folder" or candidateLabel contains "path" or candidateLabel contains "Path" or candidateLabel contains "location" or candidateLabel contains "Location" then return true
209
+ end try
210
+ return false
211
+ end accessibilityContainsPathMarker
212
+
213
+ on matchesCanonicalPathField(candidate)
214
+ try
215
+ if not my roleIsExpected(role of candidate as text, {"AXTextField", "AXTextArea", "AXComboBox"}) then return false
216
+ end try
217
+ try
218
+ set candidateIdentifier to value of attribute "AXIdentifier" of candidate as text
219
+ if candidateIdentifier is "path" or candidateIdentifier is "location" then return true
220
+ end try
221
+ return my accessibilityContainsPathMarker(candidate)
222
+ end matchesCanonicalPathField
223
+
224
+ on findFocusedCanonicalPathField(container, focusedCandidate, depth, insidePathContainer)
225
+ if depth > 12 then return missing value
226
+ set candidateInsidePathContainer to insidePathContainer
227
+ try
228
+ set candidateRole to role of container as text
229
+ if candidateRole is "AXSheet" or candidateRole is "AXDialog" then set candidateInsidePathContainer to true
230
+ if my accessibilityContainsPathMarker(container) then set candidateInsidePathContainer to true
231
+ if my roleIsExpected(candidateRole, {"AXTextField", "AXTextArea", "AXComboBox"}) and candidateInsidePathContainer then
232
+ if container is focusedCandidate then return container
233
+ end if
234
+ end try
235
+ try
236
+ repeat with childRef in (UI elements of container)
237
+ set candidate to contents of childRef
238
+ set found to my findFocusedCanonicalPathField(candidate, focusedCandidate, depth + 1, candidateInsidePathContainer)
239
+ if found is not missing value then return found
240
+ end repeat
241
+ end try
242
+ return missing value
243
+ end findFocusedCanonicalPathField
244
+
245
+ on findCanonicalPathField(container, depth)
246
+ if depth > 12 then return missing value
247
+ try
248
+ if my matchesCanonicalPathField(container) then return container
249
+ end try
250
+ try
251
+ repeat with childRef in (UI elements of container)
252
+ set candidate to contents of childRef
253
+ set found to my findCanonicalPathField(candidate, depth + 1)
254
+ if found is not missing value then return found
255
+ end repeat
256
+ end try
257
+ return missing value
258
+ end findCanonicalPathField
259
+
260
+ on findSavePathField(saveWindow, timeoutSeconds, timeoutMessage)
88
261
  set deadline to (current date) + timeoutSeconds
89
262
  repeat
263
+ set focusedCandidate to missing value
90
264
  try
91
- repeat with candidate in (entire contents of container)
92
- try
93
- if role of candidate is expectedRole then return candidate
94
- end try
95
- end repeat
265
+ set focusedCandidate to value of attribute "AXFocusedUIElement"
266
+ end try
267
+ try
268
+ if my matchesCanonicalPathField(focusedCandidate) then return focusedCandidate
96
269
  end try
270
+ set candidate to my findFocusedCanonicalPathField(saveWindow, focusedCandidate, 0, false)
271
+ if candidate is not missing value then return candidate
272
+ set candidate to my findCanonicalPathField(saveWindow, 0)
273
+ if candidate is not missing value then return candidate
97
274
  if (current date) > deadline then error timeoutMessage
98
275
  delay 0.1
99
276
  end repeat
100
- end findDescendantByRole
277
+ end findSavePathField
101
278
 
102
- on pressDescendantButtonIfPresent(container, expectedNames)
279
+ on matchesCanonicalSaveNameField(candidate)
103
280
  try
104
- set candidates to entire contents of container
281
+ if not my roleIsExpected(role of candidate as text, {"AXTextField", "AXTextArea", "AXComboBox"}) then return false
282
+ end try
283
+ repeat with attributeName in {"AXIdentifier", "AXDescription", "AXTitle"}
284
+ try
285
+ set candidateLabel to value of attribute (attributeName as text) of candidate as text
286
+ if candidateLabel is "saveAsNameTextField" or candidateLabel is "Save As:" or candidateLabel is "Save As" then return true
287
+ end try
288
+ end repeat
289
+ return false
290
+ end matchesCanonicalSaveNameField
291
+
292
+ on findCanonicalSaveNameFieldDescendant(container, depth)
293
+ if depth > 12 then return missing value
294
+ try
295
+ if my matchesCanonicalSaveNameField(container) then return container
296
+ end try
297
+ try
298
+ repeat with childRef in (UI elements of container)
299
+ set candidate to contents of childRef
300
+ set found to my findCanonicalSaveNameFieldDescendant(candidate, depth + 1)
301
+ if found is not missing value then return found
302
+ end repeat
303
+ end try
304
+ return missing value
305
+ end findCanonicalSaveNameFieldDescendant
306
+
307
+ on findCanonicalSaveNameField(saveWindow, timeoutSeconds, timeoutMessage)
308
+ set deadline to (current date) + timeoutSeconds
309
+ repeat
310
+ set candidate to my findCanonicalSaveNameFieldDescendant(saveWindow, 0)
311
+ if candidate is not missing value then return candidate
312
+ if (current date) > deadline then error timeoutMessage
313
+ delay 0.1
314
+ end repeat
315
+ end findCanonicalSaveNameField
316
+
317
+ on findAccessibilityButton(container, expectedNames, depth)
318
+ if depth > 12 then return missing value
319
+ try
320
+ if (role of container as text) is "AXButton" then
321
+ if my accessibilityMatchesExpectedName(container, expectedNames) then return container
322
+ end if
323
+ end try
324
+ try
325
+ repeat with childRef in (UI elements of container)
326
+ set candidate to contents of childRef
327
+ set found to my findAccessibilityButton(candidate, expectedNames, depth + 1)
328
+ if found is not missing value then return found
329
+ end repeat
330
+ end try
331
+ return missing value
332
+ end findAccessibilityButton
333
+
334
+ on pressAccessibilityButtonIfPresent(container, expectedNames)
335
+ set candidate to my findAccessibilityButton(container, expectedNames, 0)
336
+ if candidate is missing value then return false
337
+ try
338
+ perform action "AXPress" of candidate
339
+ return true
340
+ on error
341
+ try
342
+ click candidate
343
+ return true
344
+ on error
345
+ return false
346
+ end try
347
+ end try
348
+ end pressAccessibilityButtonIfPresent
349
+
350
+ on cancelCanonicalWindowIfOpen(finalCut, windowName)
351
+ repeat 20 times
352
+ try
353
+ if not (exists window windowName of finalCut) then return true
354
+ set targetWindow to window windowName of finalCut
355
+ if not my pressAccessibilityButtonIfPresent(targetWindow, {"Cancel", "Close"}) then key code 53
356
+ end try
357
+ delay 0.1
358
+ end repeat
359
+ try
360
+ return not (exists window windowName of finalCut)
105
361
  on error
106
362
  return false
107
363
  end try
108
- repeat with candidate in candidates
364
+ end cancelCanonicalWindowIfOpen
365
+
366
+ on cleanupCanonicalExport(finalCut)
367
+ repeat 5 times
368
+ set foundWindow to false
369
+ repeat with candidateName in {"Save", "Export XML", "XML"}
370
+ try
371
+ set candidateNameText to candidateName as text
372
+ if exists window candidateNameText of finalCut then
373
+ set foundWindow to true
374
+ my cancelCanonicalWindowIfOpen(finalCut, candidateNameText)
375
+ end if
376
+ end try
377
+ end repeat
378
+ if not foundWindow then exit repeat
379
+ end repeat
380
+ repeat with candidateName in {"Save", "Export XML", "XML"}
109
381
  try
110
- if role of candidate is "AXButton" then
111
- set candidateName to name of candidate as text
112
- repeat with expectedName in expectedNames
113
- if candidateName is (expectedName as text) and enabled of candidate then
114
- perform action "AXPress" of candidate
115
- return true
116
- end if
117
- end repeat
118
- end if
382
+ if exists window (candidateName as text) of finalCut then return false
119
383
  end try
120
384
  end repeat
121
- return false
122
- end pressDescendantButtonIfPresent
385
+ return true
386
+ end cleanupCanonicalExport
387
+
388
+ on canonicalExportCode(errorMessage)
389
+ if errorMessage contains "not authorized" or errorMessage contains "-1743" or errorMessage contains "-25211" then return "FINAL_CUT_CANONICAL_PERMISSION_REQUIRED"
390
+ set knownCodes to {"FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE", "FINAL_CUT_CANONICAL_EXPORT_WINDOW_UNAVAILABLE", "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE", "FINAL_CUT_CANONICAL_SAVE_PATH_UNAVAILABLE", "FINAL_CUT_CANONICAL_SAVE_NAME_UNAVAILABLE", "FINAL_CUT_CANONICAL_SAVE_BUTTON_UNAVAILABLE"}
391
+ repeat with candidateCode in knownCodes
392
+ set candidateCodeText to candidateCode as text
393
+ if errorMessage contains candidateCodeText then return candidateCodeText
394
+ end repeat
395
+ return "FINAL_CUT_CANONICAL_EXPORT_RECOVERY_REQUIRED"
396
+ end canonicalExportCode
397
+
398
+ on canonicalExportResponse(statusValue, codeValue, messageValue, cleanupValue)
399
+ return "{" & quote & "status" & quote & ":" & quote & statusValue & quote & "," & quote & "code" & quote & ":" & quote & codeValue & quote & "," & quote & "message" & quote & ":" & quote & messageValue & quote & "," & quote & "cleanup" & quote & ":" & quote & cleanupValue & quote & "}"
400
+ end canonicalExportResponse
123
401
 
124
402
  end using terms from
125
403
 
126
404
  tell application "System Events"
127
405
  tell process "Final Cut Pro"
128
- set frontmost to true
129
- delay 0.1
130
- if not frontmost then error "FINAL_CUT_CANONICAL_NOT_FRONTMOST: Final Cut Pro must be frontmost"
131
406
  set finalCut to it
132
- set fileMenu to menu "File" of menu bar 1
133
- set exportCommand to missing value
134
407
  try
135
- set exportCommand to my findMenuItem(fileMenu, {"Export XML…", "Export XML..."}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: File > Export XML was not exposed")
136
- on error
137
- set exportMenuItem to my findMenuItem(fileMenu, {"Export"}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: File > Export was not exposed")
138
- perform action "AXPress" of exportMenuItem
139
- set exportMenu to missing value
140
- repeat 100 times
141
- try
142
- if exists menu "Export" of exportMenuItem then
143
- set exportMenu to menu "Export" of exportMenuItem
144
- exit repeat
145
- end if
146
- end try
147
- delay 0.1
148
- end repeat
149
- if exportMenu is missing value then error "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: Export submenu was not exposed"
150
- set exportCommand to my findMenuItem(exportMenu, {"XML…", "XML..."}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: Export XML command was not exposed")
408
+ set frontmost to true
409
+ delay 0.1
410
+ if not frontmost then error "FINAL_CUT_CANONICAL_NOT_FRONTMOST: Final Cut Pro must be frontmost"
411
+ set fileMenu to menu "File" of menu bar 1
412
+ set exportCommand to missing value
413
+ try
414
+ set exportCommand to my findMenuItem(fileMenu, {"Export XML…", "Export XML..."}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: File > Export XML was not exposed")
415
+ on error
416
+ set exportMenuItem to my findMenuItem(fileMenu, {"Export"}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: File > Export was not exposed")
417
+ perform action "AXPress" of exportMenuItem
418
+ set exportMenu to missing value
419
+ repeat 100 times
420
+ try
421
+ if exists menu "Export" of exportMenuItem then
422
+ set exportMenu to menu "Export" of exportMenuItem
423
+ exit repeat
424
+ end if
425
+ end try
426
+ delay 0.1
427
+ end repeat
428
+ if exportMenu is missing value then error "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: Export submenu was not exposed"
429
+ set exportCommand to my findMenuItem(exportMenu, {"XML…", "XML..."}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: Export XML command was not exposed")
430
+ end try
431
+ perform action "AXPress" of exportCommand
432
+ set exportWindow to my findWindow(finalCut, {"Export XML", "XML"}, 15, "FINAL_CUT_CANONICAL_EXPORT_WINDOW_UNAVAILABLE: Export XML window did not appear")
433
+ my pressAccessibilityButtonIfPresent(exportWindow, {"Next…", "Next...", "Export"})
434
+ delay 0.2
435
+ set saveWindow to my findWindow(finalCut, {"Save", "Export XML"}, 15, "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: XML save window did not appear")
436
+ keystroke "g" using {command down, shift down}
437
+ set pathField to my findSavePathField(saveWindow, 5, "FINAL_CUT_CANONICAL_SAVE_PATH_UNAVAILABLE: save path field did not appear")
438
+ set value of pathField to ${appleScriptString(exportDirectory)}
439
+ delay 0.2
440
+ key code 36
441
+ delay 0.2
442
+ set saveWindow to my findWindow(finalCut, {"Save", "Export XML"}, 15, "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: XML save window did not appear")
443
+ set nameField to my findCanonicalSaveNameField(saveWindow, 5, "FINAL_CUT_CANONICAL_SAVE_NAME_UNAVAILABLE: save filename field did not appear")
444
+ set value of nameField to ${appleScriptString(exportName)}
445
+ if not my pressAccessibilityButtonIfPresent(saveWindow, {"Save"}) then error "FINAL_CUT_CANONICAL_SAVE_BUTTON_UNAVAILABLE: Save button was not exposed"
446
+ repeat 10 times
447
+ set savePanelOpen to false
448
+ repeat with saveWindowName in {"Save", "Export XML"}
449
+ try
450
+ if exists window (saveWindowName as text) of finalCut then
451
+ set savePanelOpen to true
452
+ set saveWindow to window (saveWindowName as text) of finalCut
453
+ exit repeat
454
+ end if
455
+ end try
456
+ end repeat
457
+ if not savePanelOpen then exit repeat
458
+ if not my pressAccessibilityButtonIfPresent(saveWindow, {"Save"}) then key code 36
459
+ delay 0.2
460
+ end repeat
461
+ my pressAccessibilityButtonIfPresent(saveWindow, {"Replace"})
462
+ return my canonicalExportResponse("export-requested", "", "", "complete")
463
+ on error errorMessage number errorNumber
464
+ set cleanupComplete to my cleanupCanonicalExport(finalCut)
465
+ set codeValue to my canonicalExportCode(errorMessage as text)
466
+ if cleanupComplete and codeValue is not "FINAL_CUT_CANONICAL_PERMISSION_REQUIRED" then
467
+ return my canonicalExportResponse("retryable", codeValue, "Final Cut Export XML did not complete; generated dialogs were closed and retry is safe", "complete")
468
+ end if
469
+ return my canonicalExportResponse("failed", codeValue, "Final Cut Export XML recovery could not complete safely", "incomplete")
151
470
  end try
152
- perform action "AXPress" of exportCommand
153
- set exportWindow to my findWindow(finalCut, {"Export XML", "XML"}, 15, "FINAL_CUT_CANONICAL_EXPORT_WINDOW_UNAVAILABLE: Export XML window did not appear")
154
- my pressDescendantButtonIfPresent(exportWindow, {"Next…", "Next...", "Export"})
155
- delay 0.2
156
- set saveWindow to my findWindow(finalCut, {"Save", "Export XML"}, 15, "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: XML save window did not appear")
157
- keystroke "g" using {command down, shift down}
158
- set pathSheet to my findDescendantByRole(saveWindow, "AXSheet", 5, "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: save path sheet did not appear")
159
- set pathField to my findDescendantByRole(pathSheet, "AXTextField", 5, "FINAL_CUT_CANONICAL_SAVE_PATH_UNAVAILABLE: save path field did not appear")
160
- set value of pathField to ${appleScriptString(exportPath)}
161
- key code 36
162
- delay 0.2
163
- my pressDescendantButtonIfPresent(saveWindow, {"Save"})
164
- delay 0.2
165
- my pressDescendantButtonIfPresent(saveWindow, {"Replace"})
166
- return "canonical-export-requested"
167
471
  end tell
168
472
  end tell`;
169
473
  }
@@ -311,6 +615,31 @@ export class FinalCutCanonicalNativeProvider {
311
615
  const readiness = assessCanonicalLiveReadiness(capabilities);
312
616
  if (readiness.ready)
313
617
  return capabilities;
618
+ const canonicalReadReady = capabilities.editor.projectRead
619
+ && capabilities.editor.timelineSnapshotRead
620
+ && capabilities.editor.projectCatalogRead;
621
+ if (canonicalReadReady) {
622
+ return withCapabilityFamilies({
623
+ ...capabilities,
624
+ editor: {
625
+ ...capabilities.editor,
626
+ timelineWrite: false,
627
+ readAfterWrite: false,
628
+ rollback: false,
629
+ compositeTransactions: false,
630
+ semanticOperations: {},
631
+ },
632
+ }, {
633
+ canonicalDocument: {
634
+ read: true,
635
+ write: false,
636
+ artifactWrite: false,
637
+ },
638
+ editing: {
639
+ compositeTransactions: false,
640
+ },
641
+ });
642
+ }
314
643
  return withCapabilityFamilies({
315
644
  ...capabilities,
316
645
  editor: {
@@ -1082,27 +1411,34 @@ async function executeCanonicalAppleScript(script) {
1082
1411
  throw new Error(`FINAL_CUT_CANONICAL_AUTOMATION_FAILED: ${detail}`);
1083
1412
  }
1084
1413
  }
1085
- async function readCanonicalExport(path, timeoutMs, pollIntervalMs) {
1414
+ async function readCanonicalExport(path, timeoutMs, pollIntervalMs, target) {
1086
1415
  const deadline = Date.now() + timeoutMs;
1087
1416
  let previousSignature;
1088
1417
  let lastReadError;
1089
1418
  while (Date.now() <= deadline) {
1419
+ let readablePath;
1090
1420
  let signature;
1091
- try {
1092
- const details = await stat(path);
1093
- if (details.isFile() && details.size > 0) {
1094
- signature = `${details.size}:${details.mtimeMs}`;
1421
+ for (const candidatePath of [path, join(`${path}.fcpxmld`, "Info.fcpxml")]) {
1422
+ try {
1423
+ const details = await stat(candidatePath);
1424
+ if (details.isFile() && details.size > 0) {
1425
+ readablePath = candidatePath;
1426
+ signature = `${candidatePath}:${details.size}:${details.mtimeMs}`;
1427
+ break;
1428
+ }
1429
+ }
1430
+ catch {
1431
+ // The Save dialog or Final Cut directory package may still be open.
1095
1432
  }
1096
1433
  }
1097
- catch {
1098
- // The Save dialog may still be open.
1099
- }
1100
- if (signature && signature === previousSignature) {
1434
+ if (readablePath && signature && signature === previousSignature) {
1101
1435
  try {
1102
- return await new FcpxmlDocumentAdapter(path).readProject();
1436
+ return await new FcpxmlDocumentAdapter(readablePath, target).readProject();
1103
1437
  }
1104
1438
  catch (error) {
1105
1439
  lastReadError = error;
1440
+ if (error instanceof Error && error.message.includes("TARGET_MISMATCH"))
1441
+ throw error;
1106
1442
  }
1107
1443
  }
1108
1444
  previousSignature = signature;
@@ -21,6 +21,7 @@ const TIMELINE_KINDS = new Set([
21
21
  */
22
22
  export class FcpxmlDocumentAdapter {
23
23
  filePath;
24
+ target;
24
25
  parser = new XMLParser({
25
26
  preserveOrder: true,
26
27
  ignoreAttributes: false,
@@ -37,8 +38,9 @@ export class FcpxmlDocumentAdapter {
37
38
  sequence = 0;
38
39
  fileSignature;
39
40
  history = new Map();
40
- constructor(filePath) {
41
+ constructor(filePath, target) {
41
42
  this.filePath = filePath;
43
+ this.target = target;
42
44
  }
43
45
  async getIdentity() {
44
46
  return { name: "Final Cut Pro", version: "FCPXML", backend: "fcpxml-document" };
@@ -125,9 +127,10 @@ export class FcpxmlDocumentAdapter {
125
127
  const sequence = sequenceNode ?? {};
126
128
  const spine = findElement(sequence, "spine") ?? {};
127
129
  const projectName = String(attribute(project, "name") ?? "Final Cut Project");
128
- const projectId = stableProjectId(project);
130
+ const identity = this.identity(project, sequenceNode);
131
+ const projectId = identity.projectId;
129
132
  const sequenceName = String(attribute(sequenceNode ?? {}, "name") ?? projectName);
130
- const timelineId = stableTimelineId(project, sequenceNode);
133
+ const timelineId = identity.sequenceId;
131
134
  const elements = timelineEntries(spine);
132
135
  const storyElements = elements
133
136
  .map((entry) => ({ kind: entry.kind, element: this.storyElementFromXml(entry, timelineId) }))
@@ -162,10 +165,11 @@ export class FcpxmlDocumentAdapter {
162
165
  await this.ensureLoaded();
163
166
  const project = this.projectNode();
164
167
  const projectName = String(attribute(project, "name") ?? "Final Cut Project");
165
- const projectId = stableProjectId(project);
166
168
  const sequence = findElement(project, "sequence");
169
+ const identity = this.identity(project, sequence);
170
+ const projectId = identity.projectId;
167
171
  const sequenceName = String(attribute(sequence ?? {}, "name") ?? projectName);
168
- const sequenceId = stableSequenceId(sequence);
172
+ const sequenceId = identity.sequenceId;
169
173
  return {
170
174
  projects: [{
171
175
  id: projectId,
@@ -279,6 +283,20 @@ export class FcpxmlDocumentAdapter {
279
283
  throw new Error(`CAPABILITY_UNAVAILABLE: FCPXML ${phase} does not support ${operation.type}`);
280
284
  }
281
285
  }
286
+ identity(project, sequence) {
287
+ const projectUid = immutableUid(project, "PROJECT");
288
+ if (this.target && projectUid !== this.target.projectUid) {
289
+ throw new Error(`TARGET_MISMATCH: exported project UID ${projectUid} does not match live project UID ${this.target.projectUid}`);
290
+ }
291
+ const exportedSequenceUid = sequence ? attribute(sequence, "uid") : undefined;
292
+ if (this.target && exportedSequenceUid !== undefined && String(exportedSequenceUid) !== this.target.sequenceId) {
293
+ throw new Error(`TARGET_MISMATCH: exported sequence UID ${String(exportedSequenceUid)} does not match live sequence UID ${this.target.sequenceId}`);
294
+ }
295
+ return {
296
+ projectId: this.target?.projectId ?? `fcpxml:project:${projectUid}`,
297
+ sequenceId: this.target?.sequenceId ?? stableSequenceId(sequence),
298
+ };
299
+ }
282
300
  applyOperation(operation) {
283
301
  const project = this.projectNode();
284
302
  const sequenceNode = findElement(project, "sequence");
@@ -288,7 +306,7 @@ export class FcpxmlDocumentAdapter {
288
306
  if (!spine)
289
307
  throw new Error("FCPXML_SCHEMA_UNSUPPORTED: sequence spine is required");
290
308
  const sequence = sequenceNode;
291
- const timelineId = stableTimelineId(project, sequenceNode);
309
+ const timelineId = this.identity(project, sequenceNode).sequenceId;
292
310
  if (operation.type === "timeline.picture-in-picture.add") {
293
311
  this.applyPictureInPicture(spine, timelineId, operation);
294
312
  this.updateSequenceDuration(sequence, spine);
@@ -901,9 +919,10 @@ export class FcpxmlDocumentAdapter {
901
919
  .map(({ node }) => {
902
920
  const durationValue = attribute(node, "duration");
903
921
  const mediaKind = mediaKindFromResource(node);
922
+ const originalMedia = storyEntries(node).find(({ kind, node: representation }) => kind === "media-rep" && attribute(representation, "kind") === "original-media")?.node;
904
923
  return {
905
924
  mediaId: String(attribute(node, "id") ?? ""),
906
- source: resolveMediaSource(String(attribute(node, "src") ?? attribute(node, "name") ?? attribute(node, "id") ?? ""), this.filePath),
925
+ source: resolveMediaSource(String(attribute(node, "src") ?? (originalMedia && attribute(originalMedia, "src")) ?? attribute(node, "name") ?? attribute(node, "id") ?? ""), this.filePath),
907
926
  ...(mediaKind ? { mediaKind } : {}),
908
927
  ...(durationValue !== undefined ? { duration: parseSeconds(durationValue) } : {}),
909
928
  };
@@ -174,6 +174,8 @@ function isTimeoutFailure(error) {
174
174
  const candidate = error;
175
175
  if (candidate.code === "ETIMEDOUT")
176
176
  return true;
177
+ if (candidate.killed === true && candidate.signal === "SIGTERM")
178
+ return true;
177
179
  if (typeof candidate.message === "string" && /timed out/i.test(candidate.message))
178
180
  return true;
179
181
  }