@morshoto/framekit 0.1.6 → 0.1.10

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 (33) hide show
  1. package/bin/framekit.mjs +2 -1
  2. package/dist-package/adapters/final-cut/typescript/src/assets.js +157 -35
  3. package/dist-package/adapters/final-cut/typescript/src/background-export.js +384 -0
  4. package/dist-package/adapters/final-cut/typescript/src/canonical.js +189 -32
  5. package/dist-package/adapters/final-cut/typescript/src/connection.js +3 -3
  6. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +33 -7
  7. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +615 -49
  8. package/dist-package/adapters/final-cut/typescript/src/index.js +4 -0
  9. package/dist-package/adapters/final-cut/typescript/src/library-inspection.js +390 -0
  10. package/dist-package/adapters/final-cut/typescript/src/live.js +6 -3
  11. package/dist-package/adapters/final-cut/typescript/src/media.js +151 -0
  12. package/dist-package/adapters/final-cut/typescript/src/native-session.js +412 -0
  13. package/dist-package/adapters/final-cut/typescript/src/native.js +1192 -364
  14. package/dist-package/adapters/final-cut/typescript/src/publisher.js +225 -32
  15. package/dist-package/adapters/final-cut/typescript/src/session.js +145 -17
  16. package/dist-package/apps/mcp-server/src/main.js +26 -7
  17. package/dist-package/apps/mcp-server/src/routing.js +227 -39
  18. package/dist-package/apps/mcp-server/src/server.js +532 -97
  19. package/dist-package/apps/mcp-server/src/version.js +109 -1
  20. package/dist-package/packages/runtime/src/application/media-analysis-service.js +1 -3
  21. package/dist-package/packages/runtime/src/application/project-service.js +46 -7
  22. package/dist-package/packages/runtime/src/capabilities.js +55 -7
  23. package/dist-package/packages/runtime/src/context/project-catalog.js +159 -0
  24. package/dist-package/packages/runtime/src/domain/capabilities.js +33 -0
  25. package/dist-package/packages/runtime/src/domain/context.js +14 -1
  26. package/dist-package/packages/runtime/src/domain/index.js +1 -0
  27. package/dist-package/packages/runtime/src/domain/timeline-target.js +217 -0
  28. package/dist-package/packages/runtime/src/editing/edit-service.js +15 -1
  29. package/dist-package/packages/runtime/src/editing/intent.js +178 -2
  30. package/dist-package/packages/runtime/src/index.js +1 -0
  31. package/dist-package/packages/runtime/src/runtime.js +2 -2
  32. package/dist-package/packages/testkit/src/in-memory-editor.js +5 -4
  33. package/package.json +7 -2
@@ -1,9 +1,9 @@
1
- import { createHash } from "node:crypto";
2
- import { readFile, writeFile } from "node:fs/promises";
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { readFile, rename, unlink, writeFile } from "node:fs/promises";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { dirname, isAbsolute, resolve } from "node:path";
5
5
  import { XMLBuilder, XMLParser } from "fast-xml-parser";
6
- import { withCapabilityFamilies } from "../../../../packages/runtime/src/index.js";
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
8
  const TIMELINE_KINDS = new Set([
9
9
  ...CLIP_KINDS,
@@ -50,6 +50,14 @@ export class FcpxmlDocumentAdapter {
50
50
  return hash(await readFile(this.filePath, "utf8"));
51
51
  }
52
52
  async getCapabilities() {
53
+ let hasStableEffects = false;
54
+ try {
55
+ await this.ensureLoaded();
56
+ hasStableEffects = effectResources(this.xml ?? []).some((resource) => stableEffectIdentity(resource) !== undefined);
57
+ }
58
+ catch {
59
+ // Capability inspection remains useful before an artifact is created.
60
+ }
53
61
  return withCapabilityFamilies({
54
62
  editor: {
55
63
  projectRead: true,
@@ -59,21 +67,53 @@ export class FcpxmlDocumentAdapter {
59
67
  readAfterWrite: true,
60
68
  incrementalChanges: false,
61
69
  rollback: true,
62
- assetDiscovery: false,
63
70
  liveStateRead: false,
64
71
  playheadWrite: false,
65
72
  frameCapture: false,
66
73
  projectCatalogRead: true,
67
74
  projectSelection: true,
68
75
  compositeTransactions: true,
76
+ assetDiscovery: hasStableEffects,
77
+ mediaImport: false,
78
+ mediaPlacement: true,
69
79
  pictureInPicture: true,
80
+ titlePlacement: hasStableEffects,
81
+ clipMove: true,
82
+ clipReplace: true,
83
+ clipRemoval: true,
84
+ transitionPlacement: hasStableEffects,
85
+ audioAttachment: true,
86
+ audioMixing: true,
87
+ masking: false,
88
+ personCutout: false,
70
89
  semanticOperations: { "add-marker": true, "set-gain": true, "timeline.picture-in-picture.add": true },
71
90
  },
72
91
  analyzers: emptyAnalyzerCapabilities(),
73
92
  }, { backend: "fcpxml-document" });
74
93
  }
75
94
  async listAssets() {
76
- return [];
95
+ await this.ensureLoaded();
96
+ return effectResources(this.xml ?? [])
97
+ .map((resource) => {
98
+ const identity = stableEffectIdentity(resource);
99
+ const localId = String(attribute(resource, "id") ?? "");
100
+ if (!identity || !localId)
101
+ return undefined;
102
+ return {
103
+ id: `fcpxml:effect:${identity}`,
104
+ kind: "effect",
105
+ name: String(attribute(resource, "name") ?? identity),
106
+ vendor: "Final Cut Pro",
107
+ metadata: {
108
+ identity,
109
+ localId,
110
+ provider: "fcpxml-document",
111
+ source: "fcpxml-resources",
112
+ discovery: { backend: "fcpxml-document", guarantee: "canonical-read" },
113
+ },
114
+ };
115
+ })
116
+ .filter((asset) => asset !== undefined);
77
117
  }
78
118
  async read() {
79
119
  return this.readProject();
@@ -97,16 +137,17 @@ export class FcpxmlDocumentAdapter {
97
137
  .filter(({ kind }) => CLIP_KINDS.has(kind))
98
138
  .map((entry) => this.clipFromXml(entry, timelineId));
99
139
  const frameDuration = sequenceFrameDuration(sequence, this.xml ?? []);
100
- const durationValue = attribute(sequence, "duration")
101
- ?? formatSeconds(Math.max(0, ...storyElements.map((element) => element.start + element.duration)));
140
+ const durationTime = attribute(sequence, "duration") === undefined
141
+ ? timelineDuration(elements)
142
+ : parseRational(attribute(sequence, "duration"));
102
143
  return {
103
144
  projectId,
104
145
  projectName,
105
146
  timeline: {
106
147
  id: timelineId,
107
148
  name: sequenceName,
108
- duration: parseSeconds(durationValue),
109
- durationTime: parseRational(durationValue),
149
+ duration: rationalSeconds(durationTime),
150
+ durationTime,
110
151
  ...(frameDuration ? { frameDuration } : {}),
111
152
  clips,
112
153
  storyElements,
@@ -146,18 +187,29 @@ export class FcpxmlDocumentAdapter {
146
187
  if (!project.sequences.some((sequence) => sequence.id === sequenceId)) {
147
188
  throw new Error(`SEQUENCE_NOT_FOUND: ${sequenceId}`);
148
189
  }
149
- return { ...catalog, activeProjectId: project.id, activeSequenceId: sequenceId };
190
+ return createProjectSelectionResult({ ...catalog, activeProjectId: project.id, activeSequenceId: sequenceId }, selection, this.revision());
150
191
  }
151
192
  async apply(operation, expectedRevision) {
152
193
  await this.ensureLoaded();
153
194
  if (!sameRevision(expectedRevision, this.revision())) {
154
195
  throw new Error("STALE_CONTEXT: FCPXML document changed before write");
155
196
  }
197
+ const originalXml = structuredClone(this.xml);
198
+ const originalSequence = this.sequence;
199
+ const originalSignature = this.fileSignature;
156
200
  this.history.set(expectedRevision.id, structuredClone(this.xml));
157
- this.applyOperation(operation);
158
- this.sequence += 1;
159
- await this.persist();
160
- return this.revision();
201
+ try {
202
+ this.applyOperation(operation);
203
+ this.sequence += 1;
204
+ await this.persist();
205
+ return this.revision();
206
+ }
207
+ catch (error) {
208
+ this.xml = originalXml;
209
+ this.sequence = originalSequence;
210
+ this.fileSignature = originalSignature;
211
+ throw error;
212
+ }
161
213
  }
162
214
  async previewTransaction(operations, expectedRevision) {
163
215
  await this.ensureLoaded();
@@ -169,10 +221,7 @@ export class FcpxmlDocumentAdapter {
169
221
  const originalSignature = this.fileSignature;
170
222
  try {
171
223
  for (const operation of operations) {
172
- if (operation.type === "media.import"
173
- || operation.type.startsWith("timeline.") && operation.type !== "timeline.picture-in-picture.add") {
174
- throw new Error(`CAPABILITY_UNAVAILABLE: FCPXML preview does not support ${operation.type}`);
175
- }
224
+ this.assertArtifactOperationSupported(operation, "preview");
176
225
  this.applyOperation(operation);
177
226
  }
178
227
  const preview = await this.readProject();
@@ -195,10 +244,7 @@ export class FcpxmlDocumentAdapter {
195
244
  this.history.set(expectedRevision.id, structuredClone(this.xml));
196
245
  try {
197
246
  for (const operation of operations) {
198
- if (operation.type === "media.import"
199
- || operation.type.startsWith("timeline.") && operation.type !== "timeline.picture-in-picture.add") {
200
- throw new Error(`CAPABILITY_UNAVAILABLE: FCPXML transaction does not support ${operation.type}`);
201
- }
247
+ this.assertArtifactOperationSupported(operation, "transaction");
202
248
  this.applyOperation(operation);
203
249
  }
204
250
  this.sequence += 1;
@@ -211,11 +257,37 @@ export class FcpxmlDocumentAdapter {
211
257
  throw error;
212
258
  }
213
259
  }
260
+ assertArtifactOperationSupported(operation, phase) {
261
+ const supported = new Set([
262
+ "rename-clip",
263
+ "trim-clip",
264
+ "set-gain",
265
+ "ripple-delete",
266
+ "add-marker",
267
+ "timeline.media.add",
268
+ "timeline.picture-in-picture.add",
269
+ "timeline.audio.fades",
270
+ "timeline.title.add",
271
+ "timeline.media.move",
272
+ "timeline.media.replace",
273
+ "timeline.media.remove",
274
+ "timeline.transition.add",
275
+ "timeline.audio.attach",
276
+ "timeline.audio.mix",
277
+ ]);
278
+ if (!supported.has(operation.type)) {
279
+ throw new Error(`CAPABILITY_UNAVAILABLE: FCPXML ${phase} does not support ${operation.type}`);
280
+ }
281
+ }
214
282
  applyOperation(operation) {
215
283
  const project = this.projectNode();
216
284
  const sequenceNode = findElement(project, "sequence");
217
- const sequence = sequenceNode ?? {};
218
- const spine = findElement(sequence, "spine") ?? {};
285
+ if (!sequenceNode)
286
+ throw new Error("FCPXML_SCHEMA_UNSUPPORTED: project sequence is required");
287
+ const spine = findElement(sequenceNode, "spine");
288
+ if (!spine)
289
+ throw new Error("FCPXML_SCHEMA_UNSUPPORTED: sequence spine is required");
290
+ const sequence = sequenceNode;
219
291
  const timelineId = stableTimelineId(project, sequenceNode);
220
292
  if (operation.type === "timeline.picture-in-picture.add") {
221
293
  this.applyPictureInPicture(spine, timelineId, operation);
@@ -224,35 +296,40 @@ export class FcpxmlDocumentAdapter {
224
296
  }
225
297
  switch (operation.type) {
226
298
  case "rename-clip": {
227
- const node = this.findClipNode(spine, operation.clipId, timelineId);
228
- if (!node)
299
+ const entry = this.findClipEntry(spine, operation.clipId, timelineId);
300
+ if (!entry)
229
301
  throw new Error(`CLIP_NOT_FOUND: ${operation.clipId}`);
230
302
  if (operation.name.trim().length === 0)
231
303
  throw new Error("INVALID_OPERATION: clip name cannot be empty");
232
- setAttribute(node, "name", operation.name);
304
+ setAttribute(entry.node, "name", operation.name);
233
305
  break;
234
306
  }
235
307
  case "trim-clip": {
236
- const node = this.findClipNode(spine, operation.clipId, timelineId);
237
- if (!node)
308
+ const entry = this.findClipEntry(spine, operation.clipId, timelineId);
309
+ if (!entry)
238
310
  throw new Error(`CLIP_NOT_FOUND: ${operation.clipId}`);
239
311
  if ((!Number.isFinite(operation.duration) || operation.duration <= 0) && !operation.durationTime) {
240
312
  throw new Error("INVALID_OPERATION: clip duration must be positive");
241
313
  }
242
- setAttribute(node, "duration", operation.durationTime ? formatRational(operation.durationTime) : formatSeconds(operation.duration));
314
+ const duration = operation.durationTime ? rationalSeconds(operation.durationTime) : operation.duration;
315
+ this.assertSourceRange(entry.node, duration);
316
+ setAttribute(entry.node, "duration", operation.durationTime ? formatRational(operation.durationTime) : formatSeconds(duration));
243
317
  break;
244
318
  }
245
319
  case "set-gain": {
246
- const node = this.findClipNode(spine, operation.clipId, timelineId);
247
- if (!node)
320
+ const entry = this.findClipEntry(spine, operation.clipId, timelineId);
321
+ if (!entry)
248
322
  throw new Error(`CLIP_NOT_FOUND: ${operation.clipId}`);
249
323
  if (!Number.isFinite(operation.gainDb))
250
324
  throw new Error("INVALID_OPERATION: gain must be finite");
251
- this.setAdjustVolume(node, operation.gainDb);
325
+ this.setAdjustVolume(entry.node, operation.gainDb);
252
326
  break;
253
327
  }
254
328
  case "ripple-delete":
255
- throw new Error("CAPABILITY_UNAVAILABLE: FCPXML ripple-delete requires story-element source-range transforms");
329
+ if (operation.timelineId !== timelineId)
330
+ throw new Error(`TIMELINE_NOT_FOUND: ${operation.timelineId}`);
331
+ this.applyRippleDelete(spine, operation.range.start, operation.range.end);
332
+ break;
256
333
  case "add-marker": {
257
334
  if (operation.timelineId !== timelineId) {
258
335
  throw new Error(`TIMELINE_NOT_FOUND: ${operation.timelineId}`);
@@ -267,9 +344,345 @@ export class FcpxmlDocumentAdapter {
267
344
  });
268
345
  break;
269
346
  }
347
+ case "timeline.media.add":
348
+ this.applyMediaAdd(spine, timelineId, operation);
349
+ break;
350
+ case "timeline.audio.fades":
351
+ this.applyAudioFades(spine, timelineId, operation);
352
+ break;
353
+ case "timeline.title.add":
354
+ this.applyTitleAdd(spine, timelineId, operation);
355
+ break;
356
+ case "timeline.media.move":
357
+ this.applyMediaMove(spine, timelineId, operation);
358
+ break;
359
+ case "timeline.media.replace":
360
+ this.applyMediaReplace(spine, timelineId, operation);
361
+ break;
362
+ case "timeline.media.remove":
363
+ this.applyMediaRemove(spine, timelineId, operation);
364
+ break;
365
+ case "timeline.transition.add":
366
+ this.applyTransitionAdd(spine, timelineId, operation);
367
+ break;
368
+ case "timeline.audio.attach":
369
+ this.applyAudioAttach(spine, timelineId, operation);
370
+ break;
371
+ case "timeline.audio.mix":
372
+ this.applyAudioMix(spine, timelineId, operation);
373
+ break;
270
374
  }
271
375
  this.updateSequenceDuration(sequence, spine);
272
376
  }
377
+ findClipEntry(spine, clipId, timelineId) {
378
+ return timelineEntries(spine)
379
+ .filter(({ kind }) => CLIP_KINDS.has(kind))
380
+ .find(({ kind, node, path }) => this.instanceId(node, kind, path, timelineId) === clipId);
381
+ }
382
+ mediaResource(mediaId) {
383
+ const media = this.mediaFromResources().find((candidate) => candidate.mediaId === mediaId);
384
+ if (!media)
385
+ throw new Error(`MEDIA_NOT_FOUND: ${mediaId}`);
386
+ return media;
387
+ }
388
+ effectResource(assetId, operation) {
389
+ const resource = effectResources(this.xml ?? []).find((candidate) => {
390
+ const localId = String(attribute(candidate, "id") ?? "");
391
+ const identity = stableEffectIdentity(candidate);
392
+ return assetId === localId || assetId === identity || assetId === `fcpxml:effect:${identity}`;
393
+ });
394
+ if (!resource)
395
+ throw new Error(`${operation === "title" ? "TITLE" : "TRANSITION"}_ASSET_NOT_FOUND: ${assetId}`);
396
+ if (!stableEffectIdentity(resource)) {
397
+ throw new Error(`FCPXML_EFFECT_IDENTITY_UNAVAILABLE: ${assetId}`);
398
+ }
399
+ return resource;
400
+ }
401
+ applyMediaAdd(spine, timelineId, operation) {
402
+ const media = this.mediaResource(operation.mediaId);
403
+ if (timelineEntries(spine).some(({ kind, node, path }) => this.instanceId(node, kind, path, timelineId) === operation.occurrenceId)) {
404
+ throw new Error(`OCCURRENCE_ALREADY_EXISTS: ${operation.occurrenceId}`);
405
+ }
406
+ if (!Number.isFinite(operation.start) || !Number.isFinite(operation.duration)
407
+ || operation.start < 0 || operation.duration <= 0) {
408
+ throw new Error("INVALID_OPERATION: media placement timing");
409
+ }
410
+ if (!mediaKindCompatible(operation.role, media.mediaKind)) {
411
+ throw new Error(`MEDIA_KIND_MISMATCH: ${operation.mediaId}`);
412
+ }
413
+ if (media.duration !== undefined && operation.duration > media.duration) {
414
+ throw new Error("INVALID_OPERATION: media placement duration must fit the source");
415
+ }
416
+ const lane = operation.targetLane ?? (operation.role === "video" ? "primary" : undefined);
417
+ if (operation.role === "video" && lane !== "primary") {
418
+ throw new Error("INVALID_OPERATION: video must target the primary storyline");
419
+ }
420
+ if (operation.role !== "video" && (typeof lane !== "number" || lane === 0)) {
421
+ throw new Error("INVALID_OPERATION: audio requires an explicit non-primary lane");
422
+ }
423
+ const kind = operation.role === "video" ? "asset-clip" : "audio";
424
+ const node = elementNode(kind, {
425
+ id: operation.occurrenceId,
426
+ ref: operation.mediaId,
427
+ offset: formatSeconds(operation.start),
428
+ start: "0s",
429
+ duration: formatSeconds(operation.duration),
430
+ ...(lane === "primary" ? {} : { lane: String(lane) }),
431
+ ...(operation.role === "video" ? {} : { role: operation.role }),
432
+ });
433
+ appendChild(spine, kind, node);
434
+ }
435
+ applyAudioFades(spine, timelineId, operation) {
436
+ const entry = this.findClipEntry(spine, operation.clipId, timelineId);
437
+ if (!entry)
438
+ throw new Error(`CLIP_NOT_FOUND: ${operation.clipId}`);
439
+ if (!Number.isFinite(operation.fadeIn) || !Number.isFinite(operation.fadeOut)
440
+ || operation.fadeIn < 0 || operation.fadeOut < 0
441
+ || operation.fadeIn + operation.fadeOut > rationalSeconds(entry.durationTime)) {
442
+ throw new Error("INVALID_OPERATION: audio fades must be non-negative and fit within the clip duration");
443
+ }
444
+ this.setAudioFades(entry.node, operation.fadeIn, operation.fadeOut);
445
+ }
446
+ applyTitleAdd(spine, timelineId, operation) {
447
+ const effect = this.effectResource(operation.assetId, "title");
448
+ this.assertNewOccurrence(spine, timelineId, operation.occurrenceId);
449
+ if (!operation.text.trim() || !Number.isFinite(operation.start) || !Number.isFinite(operation.duration)
450
+ || operation.start < 0 || operation.duration <= 0 || !Number.isInteger(operation.targetLane) || operation.targetLane === 0) {
451
+ throw new Error("INVALID_OPERATION: title text, timing, and non-primary lane are required");
452
+ }
453
+ const node = elementNode("title", {
454
+ id: operation.occurrenceId,
455
+ ref: String(attribute(effect, "id")),
456
+ name: String(attribute(effect, "name") ?? operation.assetId),
457
+ offset: formatSeconds(operation.start),
458
+ duration: formatSeconds(operation.duration),
459
+ lane: String(operation.targetLane),
460
+ });
461
+ appendTextChild(node, "text", operation.text);
462
+ appendChild(spine, "title", node);
463
+ }
464
+ applyMediaMove(spine, timelineId, operation) {
465
+ const entry = this.findClipEntry(spine, operation.occurrenceId, timelineId);
466
+ if (!entry)
467
+ throw new Error(`CLIP_NOT_FOUND: ${operation.occurrenceId}`);
468
+ if (!Number.isFinite(operation.start) || operation.start < 0) {
469
+ throw new Error("INVALID_OPERATION: media move start must be non-negative");
470
+ }
471
+ const existingLane = attribute(entry.node, "lane");
472
+ const lane = operation.targetLane ?? (existingLane === undefined ? "primary" : Number(existingLane));
473
+ if (lane === "primary" && entry.parent !== spine) {
474
+ throw new Error("CAPABILITY_UNAVAILABLE: moving nested FCPXML media to the primary storyline");
475
+ }
476
+ if (lane !== "primary" && (!Number.isInteger(lane) || lane === 0)) {
477
+ throw new Error("INVALID_OPERATION: media move requires a valid lane");
478
+ }
479
+ const parentStart = rationalSeconds(entry.parentStartTime);
480
+ if (operation.start < parentStart) {
481
+ throw new Error("INVALID_OPERATION: media move cannot precede its FCPXML parent");
482
+ }
483
+ setAttribute(entry.node, "offset", formatSeconds(operation.start - parentStart));
484
+ if (lane === "primary")
485
+ removeAttribute(entry.node, "lane");
486
+ else
487
+ setAttribute(entry.node, "lane", String(lane));
488
+ }
489
+ applyMediaReplace(spine, timelineId, operation) {
490
+ const entry = this.findClipEntry(spine, operation.occurrenceId, timelineId);
491
+ if (!entry)
492
+ throw new Error(`CLIP_NOT_FOUND: ${operation.occurrenceId}`);
493
+ const media = this.mediaResource(operation.mediaId);
494
+ const currentMediaId = attribute(entry.node, "ref");
495
+ const currentMedia = currentMediaId === undefined
496
+ ? undefined
497
+ : this.mediaFromResources().find((candidate) => candidate.mediaId === String(currentMediaId));
498
+ const currentKind = entry.kind === "audio" ? "audio" : currentMedia?.mediaKind;
499
+ if ((currentKind !== undefined && media.mediaKind !== undefined && currentKind !== media.mediaKind)
500
+ || entry.kind === "audio" && media.mediaKind === "video") {
501
+ throw new Error(`MEDIA_KIND_MISMATCH: ${operation.mediaId}`);
502
+ }
503
+ const duration = operation.duration ?? rationalSeconds(entry.durationTime);
504
+ if (!Number.isFinite(duration) || duration <= 0 || media.duration !== undefined
505
+ && sourceStart(entry.node) + duration > media.duration) {
506
+ throw new Error("INVALID_OPERATION: replacement duration must fit the source");
507
+ }
508
+ setAttribute(entry.node, "ref", operation.mediaId);
509
+ setAttribute(entry.node, "duration", formatSeconds(duration));
510
+ setAttribute(entry.node, "name", media.source.split("/").pop() || media.mediaId);
511
+ }
512
+ applyMediaRemove(spine, timelineId, operation) {
513
+ const entry = this.findClipEntry(spine, operation.occurrenceId, timelineId);
514
+ if (!entry)
515
+ throw new Error(`CLIP_NOT_FOUND: ${operation.occurrenceId}`);
516
+ removeChild(entry.parent, entry.node);
517
+ }
518
+ applyTransitionAdd(spine, timelineId, operation) {
519
+ const effect = this.effectResource(operation.assetId, "transition");
520
+ this.assertNewOccurrence(spine, timelineId, operation.transitionId);
521
+ const before = this.findClipEntry(spine, operation.beforeClipId, timelineId);
522
+ const after = this.findClipEntry(spine, operation.afterClipId, timelineId);
523
+ if (!before || !after || before.parent !== spine || after.parent !== spine) {
524
+ throw new Error("EDIT_POINT_NOT_FOUND: transition clips are required on the primary storyline");
525
+ }
526
+ const beforeIndex = childIndex(spine, before.node);
527
+ const afterIndex = childIndex(spine, after.node);
528
+ if (beforeIndex < 0 || afterIndex !== beforeIndex + 1) {
529
+ throw new Error("EDIT_POINT_INVALID: transition clips must be adjacent");
530
+ }
531
+ const beforeEnd = rationalSeconds(before.startTime) + rationalSeconds(before.durationTime);
532
+ if (Math.abs(beforeEnd - rationalSeconds(after.startTime)) > 1e-6) {
533
+ throw new Error("EDIT_POINT_INVALID: transition clips must meet on one lane");
534
+ }
535
+ if (!Number.isFinite(operation.duration) || operation.duration <= 0
536
+ || operation.duration > Math.min(rationalSeconds(before.durationTime), rationalSeconds(after.durationTime))) {
537
+ throw new Error("INVALID_OPERATION: transition duration must fit both clips");
538
+ }
539
+ const node = elementNode("transition", {
540
+ id: operation.transitionId,
541
+ name: String(attribute(effect, "name") ?? operation.assetId),
542
+ offset: formatSeconds(rationalSeconds(after.startTime) - operation.duration / 2),
543
+ duration: formatSeconds(operation.duration),
544
+ "framekit-before-clip": operation.beforeClipId,
545
+ "framekit-after-clip": operation.afterClipId,
546
+ });
547
+ appendChild(node, "filter-video", elementNode("filter-video", {
548
+ ref: String(attribute(effect, "id")),
549
+ name: String(attribute(effect, "name") ?? operation.assetId),
550
+ }));
551
+ insertChildAt(spine, "transition", node, afterIndex);
552
+ }
553
+ applyAudioAttach(spine, timelineId, operation) {
554
+ const target = this.findClipEntry(spine, operation.targetClipId, timelineId);
555
+ if (!target)
556
+ throw new Error(`CLIP_NOT_FOUND: ${operation.targetClipId}`);
557
+ const media = this.mediaResource(operation.mediaId);
558
+ if (media.mediaKind !== "audio")
559
+ throw new Error(`AUDIO_MEDIA_REQUIRED: ${operation.mediaId}`);
560
+ this.assertNewOccurrence(spine, timelineId, operation.occurrenceId);
561
+ const startOffset = operation.startOffset ?? 0;
562
+ const duration = operation.duration ?? media.duration;
563
+ if (!Number.isFinite(startOffset) || startOffset < 0 || duration === undefined
564
+ || !Number.isFinite(duration) || duration <= 0 || media.duration !== undefined && duration > media.duration
565
+ || startOffset + duration > rationalSeconds(target.durationTime)) {
566
+ throw new Error("INVALID_OPERATION: attached audio must fit within the target clip");
567
+ }
568
+ const node = elementNode("audio", {
569
+ id: operation.occurrenceId,
570
+ ref: operation.mediaId,
571
+ offset: formatSeconds(startOffset),
572
+ start: "0s",
573
+ duration: formatSeconds(duration),
574
+ lane: "-1",
575
+ role: "audio",
576
+ "framekit-attached-to": operation.targetClipId,
577
+ });
578
+ appendChild(target.node, "audio", node);
579
+ }
580
+ applyAudioMix(spine, timelineId, operation) {
581
+ const entry = this.findClipEntry(spine, operation.clipId, timelineId);
582
+ if (!entry)
583
+ throw new Error(`CLIP_NOT_FOUND: ${operation.clipId}`);
584
+ const mediaId = attribute(entry.node, "ref");
585
+ const media = mediaId === undefined ? undefined : this.mediaFromResources().find((candidate) => candidate.mediaId === String(mediaId));
586
+ if (entry.kind !== "audio" && media?.mediaKind !== "audio") {
587
+ throw new Error("INVALID_OPERATION: audio mix requires an audio clip");
588
+ }
589
+ if (operation.gainDb === undefined && operation.fadeIn === undefined && operation.fadeOut === undefined) {
590
+ throw new Error("INVALID_OPERATION: audio mix requires a gain or fade change");
591
+ }
592
+ if (operation.gainDb !== undefined) {
593
+ if (!Number.isFinite(operation.gainDb))
594
+ throw new Error("INVALID_OPERATION: gain must be finite");
595
+ this.setAdjustVolume(entry.node, operation.gainDb);
596
+ }
597
+ if (operation.fadeIn !== undefined || operation.fadeOut !== undefined) {
598
+ const existing = audioFadeProperties(entry.node);
599
+ const fadeIn = operation.fadeIn ?? existing.fadeIn ?? 0;
600
+ const fadeOut = operation.fadeOut ?? existing.fadeOut ?? 0;
601
+ if (!Number.isFinite(fadeIn) || !Number.isFinite(fadeOut) || fadeIn < 0 || fadeOut < 0
602
+ || fadeIn + fadeOut > rationalSeconds(entry.durationTime)) {
603
+ throw new Error("INVALID_OPERATION: audio mix values must fit the clip");
604
+ }
605
+ this.setAudioFades(entry.node, fadeIn, fadeOut);
606
+ }
607
+ }
608
+ setAudioFades(node, fadeIn, fadeOut) {
609
+ const volume = firstChild(node, "adjust-volume") ?? elementNode("adjust-volume", {});
610
+ if (!firstChild(node, "adjust-volume"))
611
+ appendChild(node, "adjust-volume", volume);
612
+ const param = firstChild(volume, "param") ?? elementNode("param", { name: "amount" });
613
+ if (!firstChild(volume, "param"))
614
+ appendChild(volume, "param", param);
615
+ removeChildren(param, "fadeIn");
616
+ removeChildren(param, "fadeOut");
617
+ appendChild(param, "fadeIn", elementNode("fadeIn", { duration: formatSeconds(fadeIn) }));
618
+ appendChild(param, "fadeOut", elementNode("fadeOut", { duration: formatSeconds(fadeOut) }));
619
+ }
620
+ assertNewOccurrence(spine, timelineId, occurrenceId) {
621
+ if (timelineEntries(spine).some(({ kind, node, path }) => this.instanceId(node, kind, path, timelineId) === occurrenceId)) {
622
+ throw new Error(`OCCURRENCE_ALREADY_EXISTS: ${occurrenceId}`);
623
+ }
624
+ }
625
+ assertSourceRange(node, duration) {
626
+ const mediaId = attribute(node, "ref");
627
+ if (mediaId === undefined)
628
+ return;
629
+ const media = this.mediaFromResources().find((candidate) => candidate.mediaId === String(mediaId));
630
+ if (media?.duration !== undefined && sourceStart(node) + duration > media.duration) {
631
+ throw new Error("INVALID_OPERATION: clip duration must fit the source");
632
+ }
633
+ }
634
+ applyRippleDelete(spine, start, end) {
635
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || end <= start) {
636
+ throw new Error("INVALID_OPERATION: ripple-delete range must be finite and increasing");
637
+ }
638
+ const direct = storyEntries(spine)
639
+ .map(({ kind, node }) => timelineEntries(spine).find((entry) => entry.node === node && entry.kind === kind))
640
+ .filter((entry) => entry !== undefined);
641
+ const delta = end - start;
642
+ for (const entry of direct) {
643
+ const entryStart = rationalSeconds(entry.startTime);
644
+ const entryEnd = entryStart + rationalSeconds(entry.durationTime);
645
+ if (entryEnd <= start || entryStart >= end)
646
+ continue;
647
+ if (entry.kind === "transition") {
648
+ throw new Error("CAPABILITY_UNAVAILABLE: FCPXML ripple-delete cannot transform transitions safely");
649
+ }
650
+ if (storyEntries(entry.node).length > 0) {
651
+ throw new Error("CAPABILITY_UNAVAILABLE: FCPXML ripple-delete cannot split anchored story elements safely");
652
+ }
653
+ if (entryStart < start && entryEnd > end) {
654
+ throw new Error("CAPABILITY_UNAVAILABLE: FCPXML ripple-delete requires a source-preserving clip split");
655
+ }
656
+ }
657
+ for (const entry of direct) {
658
+ const entryStart = rationalSeconds(entry.startTime);
659
+ const entryEnd = entryStart + rationalSeconds(entry.durationTime);
660
+ if (entryEnd <= start)
661
+ continue;
662
+ if (entryStart >= end) {
663
+ setAttribute(entry.node, "offset", formatSeconds(entryStart - delta));
664
+ continue;
665
+ }
666
+ if (entryStart < start && entryEnd <= end) {
667
+ const duration = start - entryStart;
668
+ if (duration <= 0)
669
+ removeChild(entry.parent, entry.node);
670
+ else
671
+ setAttribute(entry.node, "duration", formatSeconds(duration));
672
+ continue;
673
+ }
674
+ if (entryStart >= start && entryEnd > end) {
675
+ const duration = entryEnd - end;
676
+ const sourceAdvance = end - entryStart;
677
+ setAttribute(entry.node, "offset", formatSeconds(start));
678
+ setAttribute(entry.node, "duration", formatSeconds(duration));
679
+ if (CLIP_KINDS.has(entry.kind))
680
+ setAttribute(entry.node, "start", formatSeconds(sourceStart(entry.node) + sourceAdvance));
681
+ continue;
682
+ }
683
+ removeChild(entry.parent, entry.node);
684
+ }
685
+ }
273
686
  applyPictureInPicture(spine, timelineId, operation) {
274
687
  const media = this.mediaFromResources().find((candidate) => candidate.mediaId === operation.mediaId);
275
688
  if (!media)
@@ -357,8 +770,15 @@ export class FcpxmlDocumentAdapter {
357
770
  }
358
771
  async persist() {
359
772
  const content = this.builder.build(this.xml);
360
- await writeFile(this.filePath, content, "utf8");
361
- this.fileSignature = hash(content);
773
+ const temporaryPath = `${this.filePath}.framekit-${randomUUID()}.tmp`;
774
+ try {
775
+ await writeFile(temporaryPath, content, "utf8");
776
+ await rename(temporaryPath, this.filePath);
777
+ this.fileSignature = hash(content);
778
+ }
779
+ finally {
780
+ await unlink(temporaryPath).catch(() => undefined);
781
+ }
362
782
  }
363
783
  projectNode() {
364
784
  return findElement(this.xml ?? [], "project") ?? {};
@@ -366,6 +786,11 @@ export class FcpxmlDocumentAdapter {
366
786
  storyElementFromXml(entry, timelineId) {
367
787
  const { node, kind, path, startTime, durationTime } = entry;
368
788
  const visual = pictureInPictureProperties(node);
789
+ const referencedEffect = kind === "title"
790
+ ? attribute(node, "ref")
791
+ : kind === "transition" ? attribute(firstChild(node, "filter-video") ?? {}, "ref") : undefined;
792
+ const assetId = referencedEffect === undefined ? undefined : this.effectAssetId(String(referencedEffect));
793
+ const text = kind === "title" ? textChildValue(node, "text") : undefined;
369
794
  return {
370
795
  id: this.instanceId(node, kind, path, timelineId),
371
796
  kind,
@@ -374,8 +799,18 @@ export class FcpxmlDocumentAdapter {
374
799
  startTime,
375
800
  durationTime,
376
801
  ...(attribute(node, "lane") !== undefined ? { lane: Number(attribute(node, "lane")) } : {}),
377
- ...(attribute(node, "ref") !== undefined ? { mediaId: String(attribute(node, "ref")) } : {}),
802
+ ...(CLIP_KINDS.has(kind) && attribute(node, "ref") !== undefined
803
+ ? { mediaId: String(attribute(node, "ref")) }
804
+ : {}),
378
805
  ...(attribute(node, "framekit-attached-to") !== undefined ? { attachedTo: String(attribute(node, "framekit-attached-to")) } : {}),
806
+ ...(assetId ? { assetId } : {}),
807
+ ...(text !== undefined ? { text } : {}),
808
+ ...(attribute(node, "framekit-before-clip") !== undefined
809
+ ? { beforeClipId: String(attribute(node, "framekit-before-clip")) }
810
+ : {}),
811
+ ...(attribute(node, "framekit-after-clip") !== undefined
812
+ ? { afterClipId: String(attribute(node, "framekit-after-clip")) }
813
+ : {}),
379
814
  ...visual,
380
815
  };
381
816
  }
@@ -383,6 +818,8 @@ export class FcpxmlDocumentAdapter {
383
818
  const { node, kind, path, startTime, durationTime } = entry;
384
819
  const gain = firstChild(node, "adjust-volume");
385
820
  const visual = pictureInPictureProperties(node);
821
+ const fades = audioFadeProperties(node);
822
+ const role = kind === "audio" ? audioRoleFromXml(node) : undefined;
386
823
  const sourceStartValue = attribute(node, "start");
387
824
  const sourceStartTime = sourceStartValue === undefined ? undefined : parseRational(sourceStartValue);
388
825
  const sourceStart = sourceStartTime === undefined ? undefined : rationalSeconds(sourceStartTime);
@@ -396,10 +833,13 @@ export class FcpxmlDocumentAdapter {
396
833
  duration: rationalSeconds(durationTime),
397
834
  ...(sourceStart !== undefined ? { sourceStart, sourceStartTime } : {}),
398
835
  track: Number(attribute(node, "lane") ?? 0),
836
+ ...(role !== undefined ? { role } : {}),
399
837
  ...(attribute(node, "framekit-attached-to") !== undefined ? { attachedTo: String(attribute(node, "framekit-attached-to")) } : {}),
400
838
  startTime,
401
839
  durationTime,
402
840
  ...(gain ? { gainDb: parseDb(attribute(gain, "amount") ?? "0dB") } : {}),
841
+ ...(fades.fadeIn !== undefined ? { fadeIn: fades.fadeIn } : {}),
842
+ ...(fades.fadeOut !== undefined ? { fadeOut: fades.fadeOut } : {}),
403
843
  ...visual,
404
844
  };
405
845
  }
@@ -408,10 +848,12 @@ export class FcpxmlDocumentAdapter {
408
848
  return String(explicit ?? `${timelineId}:spine:${path}:${kind}`);
409
849
  }
410
850
  findClipNode(spine, clipId, timelineId) {
411
- return timelineEntries(spine)
412
- .filter(({ kind }) => CLIP_KINDS.has(kind))
413
- .find(({ kind, node, path }) => this.instanceId(node, kind, path, timelineId) === clipId)
414
- ?.node;
851
+ return this.findClipEntry(spine, clipId, timelineId)?.node;
852
+ }
853
+ effectAssetId(ref) {
854
+ const effect = effectResources(this.xml ?? []).find((candidate) => attribute(candidate, "id") === ref);
855
+ const identity = effect === undefined ? undefined : stableEffectIdentity(effect);
856
+ return identity === undefined ? undefined : `fcpxml:effect:${identity}`;
415
857
  }
416
858
  setAdjustVolume(node, gainDb) {
417
859
  const existing = firstChild(node, "adjust-volume");
@@ -450,15 +892,12 @@ export class FcpxmlDocumentAdapter {
450
892
  });
451
893
  }
452
894
  updateSequenceDuration(sequence, spine) {
453
- const duration = Math.max(0, ...timelineEntries(spine)
454
- .filter(({ kind }) => kind !== "marker" && kind !== "caption")
455
- .map(({ startTime, durationTime }) => rationalSeconds(startTime) + rationalSeconds(durationTime)));
456
- setAttribute(sequence, "duration", formatSeconds(duration));
895
+ setAttribute(sequence, "duration", formatRational(timelineDuration(timelineEntries(spine))));
457
896
  }
458
897
  mediaFromResources() {
459
898
  const resources = findElement(this.xml ?? [], "resources");
460
899
  return storyEntries(resources ?? {})
461
- .filter(({ kind }) => kind === "asset" || kind === "media" || kind === "effect")
900
+ .filter(({ kind }) => kind === "asset" || kind === "media")
462
901
  .map(({ node }) => {
463
902
  const durationValue = attribute(node, "duration");
464
903
  const mediaKind = mediaKindFromResource(node);
@@ -496,6 +935,98 @@ function storyEntries(node) {
496
935
  .map((child) => ({ kind: Object.keys(child).find((key) => key !== ":@") ?? kind, node: child }))
497
936
  : []);
498
937
  }
938
+ function effectResources(document) {
939
+ const resources = findElement(document, "resources");
940
+ return storyEntries(resources ?? {})
941
+ .filter(({ kind }) => kind === "effect")
942
+ .map(({ node }) => node);
943
+ }
944
+ function stableEffectIdentity(node) {
945
+ const uid = attribute(node, "uid");
946
+ return uid === undefined || String(uid).trim().length === 0 ? undefined : String(uid);
947
+ }
948
+ function elementNode(kind, values) {
949
+ return {
950
+ [kind]: [],
951
+ ":@": Object.fromEntries(Object.entries(values).map(([name, value]) => [`@_${name}`, value])),
952
+ };
953
+ }
954
+ function appendTextChild(node, kind, value) {
955
+ const elementKey = Object.keys(node).find((key) => key !== ":@");
956
+ const child = { [kind]: [{ "#text": value }] };
957
+ if (elementKey) {
958
+ node[elementKey] = [...(Array.isArray(node[elementKey]) ? node[elementKey] : []), child];
959
+ }
960
+ else {
961
+ node[kind] = [child];
962
+ }
963
+ }
964
+ function childIndex(parent, child) {
965
+ for (const value of Object.values(parent)) {
966
+ if (!Array.isArray(value))
967
+ continue;
968
+ const index = value.indexOf(child);
969
+ if (index >= 0)
970
+ return index;
971
+ }
972
+ return -1;
973
+ }
974
+ function removeChild(parent, child) {
975
+ for (const [key, value] of Object.entries(parent)) {
976
+ if (key === ":@" || !Array.isArray(value))
977
+ continue;
978
+ const index = value.indexOf(child);
979
+ if (index >= 0) {
980
+ value.splice(index, 1);
981
+ return;
982
+ }
983
+ }
984
+ }
985
+ function removeChildren(parent, kind) {
986
+ for (const [key, value] of Object.entries(parent)) {
987
+ if (key === ":@" || !Array.isArray(value))
988
+ continue;
989
+ parent[key] = value.filter((child) => Object.keys(child).find((name) => name !== ":@") !== kind);
990
+ }
991
+ }
992
+ function sourceStart(node) {
993
+ const value = attribute(node, "start");
994
+ return value === undefined ? 0 : parseSeconds(value);
995
+ }
996
+ function audioFadeProperties(node) {
997
+ const volume = firstChild(node, "adjust-volume");
998
+ const param = volume === undefined ? undefined : firstChild(volume, "param");
999
+ const fadeIn = param === undefined ? undefined : firstChild(param, "fadeIn");
1000
+ const fadeOut = param === undefined ? undefined : firstChild(param, "fadeOut");
1001
+ return {
1002
+ ...(fadeIn ? { fadeIn: parseSeconds(attribute(fadeIn, "duration") ?? "0s") } : {}),
1003
+ ...(fadeOut ? { fadeOut: parseSeconds(attribute(fadeOut, "duration") ?? "0s") } : {}),
1004
+ };
1005
+ }
1006
+ function audioRoleFromXml(node) {
1007
+ const role = attribute(node, "role");
1008
+ if (role === undefined || role === "audio")
1009
+ return "audio";
1010
+ if (role === "music")
1011
+ return "music";
1012
+ throw new Error(`FCPXML_UNSUPPORTED_AUDIO_ROLE: ${role}`);
1013
+ }
1014
+ function textChildValue(node, kind) {
1015
+ const text = firstChild(node, kind);
1016
+ if (!text)
1017
+ return undefined;
1018
+ const value = Array.isArray(text[kind]) ? text[kind][0]?.["#text"] : undefined;
1019
+ if (Array.isArray(value) && value.length > 0)
1020
+ return String(value[0]);
1021
+ if (typeof value === "string" || typeof value === "number")
1022
+ return String(value);
1023
+ return undefined;
1024
+ }
1025
+ function mediaKindCompatible(role, mediaKind) {
1026
+ if (mediaKind === undefined)
1027
+ return true;
1028
+ return role === "video" ? mediaKind === "video" : mediaKind === "audio";
1029
+ }
499
1030
  function timelineEntries(spine) {
500
1031
  const entries = [];
501
1032
  const visit = (node, parentStart, parentPath) => {
@@ -507,7 +1038,7 @@ function timelineEntries(spine) {
507
1038
  const durationTime = parseRational(attribute(child, "duration") ?? "0s");
508
1039
  const startTime = addRational(parentStart, localStart);
509
1040
  if (TIMELINE_KINDS.has(kind)) {
510
- entries.push({ kind, node: child, path, startTime, durationTime });
1041
+ entries.push({ kind, node: child, path, startTime, durationTime, parent: node, parentStartTime: parentStart });
511
1042
  }
512
1043
  visit(child, startTime, path);
513
1044
  });
@@ -515,6 +1046,15 @@ function timelineEntries(spine) {
515
1046
  visit(spine, { value: "0", timescale: "1" }, "");
516
1047
  return entries;
517
1048
  }
1049
+ function timelineDuration(entries) {
1050
+ return entries
1051
+ .filter(({ kind }) => kind !== "marker" && kind !== "caption")
1052
+ .map(({ startTime, durationTime }) => addRational(startTime, durationTime))
1053
+ .reduce((maximum, endTime) => compareRational(endTime, maximum) > 0 ? endTime : maximum, {
1054
+ value: "0",
1055
+ timescale: "1",
1056
+ });
1057
+ }
518
1058
  function findElement(nodes, kind) {
519
1059
  const containers = Array.isArray(nodes) ? nodes : [nodes];
520
1060
  for (const container of containers) {
@@ -561,6 +1101,27 @@ function sequenceFrameDuration(sequence, document) {
561
1101
  function setAttribute(node, name, value) {
562
1102
  node[":@"] = { ...attributes(node), [`@_${name}`]: value };
563
1103
  }
1104
+ function removeAttribute(node, name) {
1105
+ const next = { ...attributes(node) };
1106
+ delete next[`@_${name}`];
1107
+ if (Object.keys(next).length === 0)
1108
+ delete node[":@"];
1109
+ else
1110
+ node[":@"] = next;
1111
+ }
1112
+ function insertChildAt(parent, kind, child, index) {
1113
+ const elementKey = Object.keys(parent).find((key) => key !== ":@");
1114
+ const wrapper = Object.prototype.hasOwnProperty.call(child, kind)
1115
+ ? child
1116
+ : { [kind]: [], ...child };
1117
+ if (!elementKey) {
1118
+ parent[kind] = [wrapper];
1119
+ return;
1120
+ }
1121
+ const children = Array.isArray(parent[elementKey]) ? parent[elementKey] : [];
1122
+ children.splice(index, 0, wrapper);
1123
+ parent[elementKey] = children;
1124
+ }
564
1125
  function parseSeconds(value) {
565
1126
  return rationalSeconds(parseRational(value));
566
1127
  }
@@ -604,6 +1165,11 @@ function addRational(left, right) {
604
1165
  denominator: BigInt(left.timescale) * BigInt(right.timescale),
605
1166
  });
606
1167
  }
1168
+ function compareRational(left, right) {
1169
+ const difference = BigInt(left.value) * BigInt(right.timescale)
1170
+ - BigInt(right.value) * BigInt(left.timescale);
1171
+ return difference < 0n ? -1 : difference > 0n ? 1 : 0;
1172
+ }
607
1173
  function greatestCommonDivisor(left, right) {
608
1174
  let a = left < 0n ? -left : left;
609
1175
  let b = right < 0n ? -right : right;
@@ -629,10 +1195,10 @@ function formatSeconds(value) {
629
1195
  function decimalToRational(value) {
630
1196
  const text = value.toFixed(6).replace(/0+$/, "").replace(/\.$/, "");
631
1197
  if (!text.includes("."))
632
- return { value: text, timescale: "1" };
1198
+ return rationalTime({ numerator: BigInt(text), denominator: 1n });
633
1199
  const decimals = text.split(".")[1].length;
634
1200
  const scale = 10 ** decimals;
635
- return { value: String(Math.round(value * scale)), timescale: String(scale) };
1201
+ return rationalTime({ numerator: BigInt(Math.round(value * scale)), denominator: BigInt(scale) });
636
1202
  }
637
1203
  function formatDb(value) {
638
1204
  return `${value}dB`;